sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function execute($exportType = null, $command = null, $params = null)
{
$params = array_slice(func_get_args(), 2);
$export = $this->loader->getExport()->getExport($exportType);
$export->setBatch($this->_batch);
if ($messages = call_user_func_array(array($export, $command), $params)) {
foreach ($messages as $message) {
$this->_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
@param string $exportType Name of export class
@param string $command Command to call in export class
@param array $filter The filter to use
@param string $language The language used / to use for the export
@param array $data The formdata | entailment |
public static function initialize($target, $parameters)
{
if (is_array($parameters)) {
foreach ($parameters as $key => $value) {
$method = 'set'.ucfirst(static::camelCase($key));
if (method_exists($target, $method)) {
$target->$method($value);
}
}
}
} | Initialize an object with a given array of parameters
Parameters are automatically converted to camelCase. Any parameters which do
not match a setter on the target object are ignored.
@param mixed $target The object to set parameters on
@param array $parameters An array of parameters to set | entailment |
public static function getMailerClassName($className)
{
if (class_exists($className)) {
return $className;
}
// replace underscores with namespace marker, PSR-0 style
$fullyQualified = '\\Omnimail\\' . str_replace('_', '\\', $className);
if (!class_exists($fullyQualified)) {
$fullyQualified = $fullyQualified . '\\Mailer';
if (!class_exists($fullyQualified)) {
throw new \Exception("Class '${className}' not found");
}
}
return $fullyQualified;
} | Resolve a short Mailer name to a full namespaced Mailer class.
@param string $className
@return string
@throws \Exception | entailment |
protected function _initView($view) {
$baseUrl = \GemsEscort::getInstance()->basepath->getBasePath();
// Make sure we can use jQuery
\MUtil_JQuery::enableView($view);
// Now add the scrollTo plugin so we can scroll to today
$view->headScript()->appendFile($baseUrl . '/gems/js/jquery.scrollTo.min.js');
/*
* And add some initialization:
* - Hide all tokens initially (accessability, when no javascript they should be visible)
* - If there is a day labeled today, scroll to it (prevents errors when not visible)
*/
$view->headScript()->appendFile($baseUrl . '/gems/js/trafficlight.js');
} | Initialize the view
Make sure the needed javascript is loaded
@param \Zend_View $view | entailment |
public function createMenuLink($parameterSource, $controller, $action = 'index', $label = null, $menuItem = null) {
if (!is_null($menuItem) || $menuItem = $this->findMenuItem($controller, $action)) {
$item = $menuItem->toActionLinkLower($this->request, $parameterSource, $label);
if (is_object($item)) {
$item->setAttrib('class', '');
}
return $item;
}
} | Copied, optimised to we use the optional $menuItem we stored in _initView instead
of doing the lookup again and again
@param type $parameterSource
@param type $controller
@param type $action
@param type $label
@param type $menuItem
@return \MUtil_Html_AElement | entailment |
public function getHtmlOutput(\Zend_View_Abstract $view)
{
$html = $this->getHtmlSequence();
$org = $this->token->getOrganization();
$tracker = $this->loader->getTracker();
$html->h3($this->_('Token'));
if ($this->token->hasRelation()) {
$p = $html->pInfo(sprintf($this->_('Welcome %s,'), $this->token->getRelation()->getName()));
$html->pInfo(sprintf($this->_('We kindly ask you to answer a survey about %s.'), $this->token->getRespondent()->getName()));
} else {
$p = $html->pInfo(sprintf($this->_('Welcome %s,'), $this->token->getRespondentName()));
}
$p->br();
$p->br();
if ($this->wasAnswered) {
$html->pInfo(sprintf($this->_('Thank you for answering the "%s" survey.'), $this->token->getSurveyName()));
// $html->pInfo($this->_('Please click the button below to answer the next survey.'));
} else {
if ($welcome = $org->getWelcome()) {
$html->pInfo()->raw(\MUtil_Markup::render($this->_($welcome), 'Bbcode', 'Html'));
}
// $html->pInfo(sprintf($this->_('Please click the button below to answer the survey for token %s.'), strtoupper($this->token->getTokenId())));
}
// Only valid or answerd in the last
$where = "(gto_completion_time IS NULL AND gto_valid_from <= CURRENT_TIMESTAMP AND (gto_valid_until IS NULL OR gto_valid_until >= CURRENT_TIMESTAMP))";
// Do we always look back
if ($this->lookbackInHours) {
$where .= $this->db->quoteInto("OR DATE_ADD(gto_completion_time, INTERVAL ? HOUR) >= CURRENT_TIMESTAMP", $this->lookbackInHours, \Zend_Db::INT_TYPE);
}
// We always look back from the entered token
if ($this->token->isCompleted()) {
$filterTime = $this->token->getCompletionTime();
$filterTime->subHour(1);
$where .= $this->db->quoteInto(" OR gto_completion_time >= ?", $filterTime->toString('yyyy-MM-dd HH:mm:ss'));
}
// Get the tokens
$tokens = $this->token->getAllUnansweredTokens($where);
if ($tokens) {
$currentToken = $this->token->isCompleted() ? false : $this->token->getTokenId();
$lastRound = false;
$lastTrack = false;
$open = 0;
$pStart = $html->pInfo();
foreach ($tokens as $row) {
if ($row['gtr_track_name'] !== $lastTrack) {
$lastTrack = $row['gtr_track_name'];
$div = $html->div();
$div->class = 'askTrack';
$div->append($this->_('Track'));
$div->append(' ');
$div->strong($row['gtr_track_name']);
if ($row['gr2t_track_info']) {
$div->small(sprintf($this->_(' (%s)'), $row['gr2t_track_info']));
}
}
if ($row['gto_round_description'] && ($row['gto_round_description'] !== $lastRound)) {
$lastRound = $row['gto_round_description'];
$div = $html->div();
$div->class = 'askRound';
$div->strong(sprintf($this->_('Round: %s'), $row['gto_round_description']));
$div->br();
}
$token = $tracker->getToken($row);
$div = $html->div();
$div->class = 'askSurvey';
if ($token->isCompleted()) {
$div->actionDisabled($token->getSurveyName());
$div->append(' ');
$div->append($this->formatCompletion($token->getCompletionTime()));
} else {
$open++;
$a = $div->actionLink($this->getTokenHref($token), $token->getSurveyName());
$div->append(' ');
$div->append($this->formatDuration($token->getSurvey()->getDuration()));
$div->append($this->formatUntil($token->getValidUntil()));
/*
if (false === $currentToken) {
$currentToken = $token->getTokenId();
}
if ($token->getTokenId() == $currentToken) {
$a->appendAttrib('class', 'currentRow');
} // */
}
}
if ($open) {
$pStart->append($this->plural('Please answer the open survey.', 'Please answer the open surveys.', $open));
} else {
$html->pInfo($this->_('Thank you for answering all open surveys.'));
}
} else {
$html->pInfo($this->_('There are no surveys to show for this token.'));
}
if ($sig = $org->getSignature()) {
$p = $html->pInfo();
$p->br();
$p->raw(\MUtil_Markup::render($this->_($sig), 'Bbcode', 'Html'));
}
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 |
protected function loadFormData()
{
parent::loadFormData();
if ($this->createData && ($this->request->isPost() && (! isset($this->formData[$this->saveButtonId])))) {
if ((! $this->_saveButton) || (! $this->_saveButton->isChecked())) {
if (isset($this->formData['grs_ssn']) && $this->formData['grs_ssn']) {
$filter = array(
'grs_ssn' => $this->formData['grs_ssn'],
'gr2o_id_organization' => true, // Make sure all organizations are checked in RespModel
);
if ($this->formData['gr2o_id_organization']) {
$orgId = $this->formData['gr2o_id_organization'];
} else {
$orgId = $this->model->get('gr2o_id_organization', 'default');
}
$order = array(
$this->db->quoteInto(
"CASE WHEN gr2o_id_organization = ? THEN 1 ELSE 2 END",
$orgId
) => SORT_ASC
);
$data = $this->model->loadFirst($filter, $order);
// Fallback for when just a respondent row was saved but no resp2org exists
if (! $data) {
$data = $this->db->fetchRow(
"SELECT * FROM gems__respondents WHERE grs_ssn = ?",
$this->formData['grs_ssn']
);
if ($data) {
$data['gr2o_id_organization'] = false;
}
}
if ($data) {
// \MUtil_Echo::track($this->formData);
// \MUtil_Echo::track($data);
// Do not use this value
unset($data['grs_ssn']);
if ($data['gr2o_id_organization'] == $orgId) {
// gr2o_patient_nr
// gr2o_id_organization
$this->addMessage($this->_('Known respondent.'));
//*
foreach ($data as $name => $value) {
if ((substr($name, 0, 4) == 'grs_') || (substr($name, 0, 5) == 'gr2o_')) {
if (array_key_exists($name, $this->formData)) {
$this->formData[$name] = $value;
}
$cname = $this->model->getKeyCopyName($name);
if (array_key_exists($cname, $this->formData)) {
$this->formData[$cname] = $value;
}
}
} // */
} else {
if ($data['gr2o_id_organization']) {
$org = $this->loader->getOrganization($data['gr2o_id_organization']);
$this->addMessage(sprintf(
$this->_('Respondent data retrieved from %s.'),
$org->getName()
));
} else {
$this->addMessage($this->_('Respondent data found.'));
}
foreach ($data as $name => $value) {
if ((substr($name, 0, 4) == 'grs_') && array_key_exists($name, $this->formData)) {
$this->formData[$name] = $value;
}
$this->formData['gr2o_id_user'] = $data['grs_id_user'];
}
}
}
}
}
}
} | Hook that loads the form data from $_POST or the model
Or from whatever other source you specify here. | entailment |
public function calcultateName($value, $isNew = false, $name = null, array $context = array())
{
$options = $this->util->getDbLookup()->getOrganizations();
$output = [];
foreach (['gaf_filter_text1', 'gaf_filter_text2', 'gaf_filter_text3', 'gaf_filter_text4'] as $field) {
if (isset($context[$field], $options[$context[$field]])) {
$output[] = $options[$context[$field]];
}
}
switch (count($output)) {
case 0:
return $this->_('No organization');
case 1:
return reset($output);
default:
return sprintf($this->_('One of: %s'), implode($this->_(', '), $output));
}
} | 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 string | entailment |
public function getTextSettings()
{
$options = $this->util->getTranslated()->getEmptyDropdownArray() +
$this->util->getDbLookup()->getOrganizations();
foreach (['gaf_filter_text1', 'gaf_filter_text2', 'gaf_filter_text3', 'gaf_filter_text4'] as $i => $field) {
$output[$field] = [
'label' => $this->_('Organization') . ' ' . ($i + 1),
'multiOptions' => $options,
'required' => false,
];
}
return $output;
} | Get the settings for the gaf_filter_textN fields
Fields not in this array are not shown in any way
@return array gaf_filter_textN => array(modelFieldName => fieldValue) | entailment |
protected function getAutoSearchElements(array $data)
{
$elements = parent::getAutoSearchElements($data);
if ($elements) {
$br = \MUtil_Html::create('br');
$elements[] = $this->_createSelectElement('gtr_track_class', $this->model, $this->_('(all track engines)'));
$elements[] = $br;
$optionsA = $this->util->getTranslated()->getYesNo();
$elementA = $this->_createSelectElement('gtr_active', $optionsA, $this->_('(both)'));
$elementA->setLabel($this->model->get('gtr_active', 'label'));
$elements[] = $elementA;
$user = $this->loader->getCurrentUser();
$optionsO = $user->getRespondentOrganizations();
$elementO = $this->_createSelectElement('org', $optionsO, $this->_('(all organizations)'));
$elements[] = $elementO;
}
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 getSelect()
{
if (null === $this->_select) {
$db = $this->getAdapter();
/**
* Build select object
*/
$select = new \Zend_Db_Select($db);
$select->from('gems__surveys', array('gsu_export_code'))
->where('gsu_export_code = ?')
->where('gsu_id_survey NOT IN (?)', implode(', ', $this->_tested))
->limit(1);
// \MUtil_Echo::track($select->__toString());
$this->_select = $select;
}
return $this->_select;
} | Gets the select object to be used by the validator.
If no select object was supplied to the constructor,
then it will auto-generate one from the given table,
schema, field, and adapter options.
@return Zend_Db_Select The Select object which will be used | entailment |
public function isValid($value, $context = array())
{
$this->_setValue($value);
foreach ($context as $field => $val) {
if (\MUtil_String::startsWith($field, 'survey__')) {
$sid = intval(substr($field, 8));
if (($sid !== $this->_surveyId) && ($value == $val)) {
$this->_error(self::ERROR_RECORD_FOUND);
return false;
}
$this->_tested[] = $sid;
}
}
$result = $this->_query($value);
if ($result) {
$this->_error(self::ERROR_RECORD_FOUND);
return false;
}
return true;
} | 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 array $context
@return boolean
@throws \Zend_Validate_Exception If validation of $value is impossible | entailment |
protected function getAutoSearchElements(array $data)
{
$elements = parent::getAutoSearchElements($data);
$orgs = $this->currentUser->getRespondentOrganizations();
if (count($orgs) > 1) {
$elements[] = $this->_createSelectElement('gap_id_organization', $orgs, $this->_('(all organizations)'));
}
$locations = $this->loader->getAgenda()->getLocations();
if (count($locations) > 1) {
$elements[] = $this->_createSelectElement('gap_id_location', $locations, $this->_('(all locations)'));
}
$elements[] = null;
$this->_addPeriodSelectors($elements, 'gap_admission_time');
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 setAfterSaveRoute()
{
parent::setAfterSaveRoute();
if ($this->afterSaveRouteUrl) {
$this->afterSaveRouteUrl[\MUtil_Model::REQUEST_ID] = $this->formData['gtf_id_track'];
$this->afterSaveRouteUrl[\Gems_Model::FIELD_ID] = $this->formData['gtf_id_field'];
$this->afterSaveRouteUrl['sub'] = $this->formData['sub'];
}
return $this;
} | Set what to do when the form is 'finished'.
@return \MUtil_Snippets_ModelFormSnippetAbstract (continuation pattern) | entailment |
protected static function get_extractor_classes()
{
// Check cache
if (self::$sorted_extractor_classes) {
return self::$sorted_extractor_classes;
}
// Generate the sorted list of extractors on demand.
$classes = ClassInfo::subclassesFor(__CLASS__);
array_shift($classes);
$classPriorities = [];
foreach ($classes as $class) {
$classPriorities[$class] = Config::inst()->get($class, 'priority');
}
arsort($classPriorities);
// Save classes
$sortedClasses = array_keys($classPriorities);
return self::$sorted_extractor_classes = $sortedClasses;
} | Gets the list of prioritised extractor classes
@return array | entailment |
public static function for_file($file)
{
if (!$file || (is_string($file) && !file_exists($file))) {
return null;
}
// Ensure we have a File instance to work with
if (is_string($file)) {
/** @var File $fileObject */
$fileObject = File::create();
$fileObject->setFromLocalFile($file);
$file = $fileObject;
}
$extension = $file->getExtension();
$mime = $file->getMimeType();
foreach (self::get_extractor_classes() as $className) {
$extractor = self::get_extractor($className);
// Skip unavailable extractors
if (!$extractor->isAvailable()) {
continue;
}
// Check extension
if ($extension && $extractor->supportsExtension($extension)) {
return $extractor;
}
// Check mime
if ($mime && $extractor->supportsMime($mime)) {
return $extractor;
}
}
} | Given a File object, decide which extractor instance to use to handle it
@param File|string $file
@return FileTextExtractor|null | entailment |
protected static function getPathFromFile(File $file)
{
$path = tempnam(TEMP_PATH, 'pdftextextractor_');
if (false === $path) {
throw new Exception(static::class . '->getPathFromFile() could not allocate temporary file name');
}
// Append extension to temp file if one is set
if ($file->getExtension()) {
$path .= '.' . $file->getExtension();
}
// Remove any existing temp files with this name
if (file_exists($path)) {
unlink($path);
}
$bytesWritten = file_put_contents($path, $file->getStream());
if (false === $bytesWritten) {
throw new Exception(static::class . '->getPathFromFile() failed to write temporary file');
}
return $path;
} | Some text extractors (like pdftotext) may require a physical file to read from, so write the current
file contents to a temp file and return its path
@param File $file
@return string
@throws Exception | entailment |
public function getRelation($respondentId, $relationId)
{
$filter = array(
'grr_id_respondent' => $respondentId, // Just a safeguard to make sure we get only relations for this patient
'grr_id' => $relationId
);
$data = $this->loadFirst($filter);
if (!$data) {
$data = array();
}
$relationObject = $this->loader->getInstance('Model_RespondentRelationInstance', $this, $data);
return $relationObject;
} | Return an object for a row of this model
@param int $respondentId
@param int $relationId
@return \Gems_Model_RespondentRelationInstance | entailment |
public function getRelationsFor($respondentId, $patientNr = null, $organizationId = null, $onlyActive = true)
{
static $relationsCache = array();
if (is_null($respondentId)) {
$respondentId = $this->loader->getUtil()->getDbLookup()->getRespondentId($patientNr, $organizationId);
}
if (!array_key_exists($respondentId, $relationsCache)) {
$relations = array();
$filter = array('grr_id_respondent'=>$respondentId);
if ($onlyActive) {
$filter['grr_active'] = 1;
}
$rawRelations = $this->load($filter);
foreach ($rawRelations as $relation)
{
$relations[$relation['grr_id']] = join(' ', array($relation['grr_type'], $relation['grr_first_name'], $relation['grr_last_name']));
}
$relationsCache[$respondentId] = $relations;
}
return $relationsCache[$respondentId];
} | Get the relations for a given respondentId or patientNr + organizationId combination
@param type $respondentId
@param type $patientNr
@param type $organizationId
@return array | entailment |
public static function getLogger()
{
if (!self::$_logger) {
if ($zfdebug = Zend_Controller_Front::getInstance()->getPlugin('ZFDebug_Controller_Plugin_Debug')) {
self::$_logger = $zfdebug->getPlugin('Log')->getLog();
} else {
return false;
}
}
return self::$_logger;
} | Get the ZFDebug logger
@return Zend_Log | entailment |
public static function errorHandler($level, $message, $file, $line)
{
if (! ($level & error_reporting()))
return false;
switch ($level) {
case E_NOTICE:
case E_USER_NOTICE:
$method = 'notice';
$type = 'Notice';
break;
case E_WARNING:
case E_USER_WARNING:
$method = 'warn';
$type = 'Warning';
break;
case E_ERROR:
case E_USER_ERROR:
$method = 'crit';
$type = 'Fatal Error';
break;
default:
$method = 'err';
$type = 'Unknown, ' . $level;
break;
}
self::$errors[] = array(
'type' => $type ,
'message' => $message ,
'file' => $file ,
'line' => $line,
'trace' => debug_backtrace()
);
$message = sprintf(
"%s in %s on line %d",
$message,
str_replace($_SERVER['DOCUMENT_ROOT'], '', $file),
$line
);
// if (ini_get('log_errors'))
// error_log(sprintf("%s: %s", $type, $message));
if (($logger = self::getLogger())) {
$logger->$method($message);
}
return false;
} | Debug Bar php error handler
@param string $level
@param string $message
@param string $file
@param string $line
@return bool | entailment |
public function dispatchLoopShutdown()
{
$response = Zend_Controller_Front::getInstance()->getResponse();
foreach ($response->getException() as $e) {
$exception = get_class($e) . ': ' . $e->getMessage()
. ' thrown in ' . str_replace($_SERVER['DOCUMENT_ROOT'], '', $e->getFile())
. ' on line ' . $e->getLine();
$exception .= '<ol>';
foreach ($e->getTrace() as $t) {
$func = $t['function'] . '()';
if (isset($t['class']))
$func = $t['class'] . $t['type'] . $func;
if (! isset($t['file']))
$t['file'] = 'unknown';
if (! isset($t['line']))
$t['line'] = 'n/a';
$exception .= '<li>' . $func . ' in '
. str_replace($_SERVER['DOCUMENT_ROOT'], '', $t['file'])
. ' on line ' . $t['line'] . '</li>';
}
$exception .= '</ol>';
if ($logger = self::getLogger())
$logger->crit($exception);
}
} | Defined by Zend_Controller_Plugin_Abstract
@param Zend_Controller_Request_Abstract
@return void | entailment |
public function loadExtra($name)
{
$useCurrent = ZenValidator::config()->use_current;
$parsleyFolder = 'parsley';
if($useCurrent) {
$parsleyFolder = 'parsley_current';
}
Requirements::javascript(ZENVALIDATOR_PATH . '/javascript/'.$parsleyFolder.'/extra/validator/' . $name . '.js');
$lang = i18n::get_lang_from_locale(i18n::get_locale());
Requirements::javascript(ZENVALIDATOR_PATH . '/javascript/'.$parsleyFolder.'/i18n/' . $lang . '.extra.js');
} | Load extra validator
@param string $name | entailment |
public function applyParsley()
{
if (!$this->field) {
throw new Exception("A constrained Field does not exist on the FieldSet, check you have the right field name for your ZenValidatorConstraint.");
}
$this->parsleyApplied = true;
if ($this->customMessage) {
$this->field->setAttribute(sprintf('data-parsley-%s-message', $this->getConstraintName()), $this->customMessage);
}
// CheckboxSetField might not have a unique name, so set parsley-multiple attribute
if (get_class($this->field) === 'CheckboxSetField') {
$this->field->setAttribute('data-parsley-multiple', $this->field->getName());
}
} | Sets the html attributes required for frontend validation
Subclasses should call parent::applyParsley
@return void | entailment |
public function removeParsley()
{
$this->parsleyApplied = false;
if ($this->field && $this->customMessage) {
$this->field->setAttribute(sprintf('data-parsley-%s-message', $this->getConstraintName()), '');
}
if (get_class($this->field) === 'CheckboxSetField') {
$this->field->setAttribute('data-parsley-multiple', '');
}
} | Removes the html attributes required for frontend validation
Subclasses should call parent::removeParsley
@return void | entailment |
public function validate($value)
{
// The value which comes in is a files array so we can look through this
// to and then get the files to test aspects of them.
if (isset($value['Files'])) {
foreach($value['Files'] as $fileID) {
$file = File::get()->byId($fileID);
// Now have the file double-check it is an image and if so then
// get some information about the image using PHPs getimagesize()
if ($file->ClassName == 'Image') {
$info = getimagesize(BASE_PATH . "/" . $file->Filename);
if ($info && is_array($info)) {
$width = $info[0];
$height = $info[1];
switch ($this->type) {
case self::WIDTH:
return $width == $this->val1;
break;
case self::HEIGHT:
return $height == $this->val1;
break;
case self::WIDTH_HEIGHT:
return (($width == $this->val1) && ($height == $this->val2));
break;
case self::RATIO:
$baseWidth = floor($width / $this->val1);
$baseHeight = floor($height / $this->val2);
return $baseWidth == $baseHeight;
break;
case self::MIN_WIDTH:
return $width >= $this->val1;
break;
case self::MIN_HEIGHT:
return $height >= $this->val1;
break;
case self::MIN_WIDTH_HEIGHT:
return (($width >= $this->val1) && ($height >= $this->val2));
break;
case self::MAX_WIDTH:
return $width <= $this->val1;
break;
case self::MAX_HEIGHT:
return $height <= $this->val1;
break;
case self::MAX_WIDTH_HEIGHT:
return (($width <= $this->val1) && ($height <= $this->val2));
break;
default:
throw new Exception('Invalid type : ' . $this->type);
}
}
}
}
} else {
// Return true so if no file selected then not shown validation message
// when the field is optional. If required dev should add to required fields as well.
return true;
}
} | Validate function called for validator.
@param Mixed $value the value of the field being validated.
@return boolean | entailment |
public function getDefaultMessage()
{
switch ($this->type) {
case self::WIDTH:
return sprintf(
_t(
'ZenValidator.DIMWIDTH',
'Image width must be %s pixels'
),
$this->val1
);
break;
case self::HEIGHT:
return sprintf(
_t(
'ZenValidator.DIMHEIGHT',
'Image height must be %s pixels'
),
$this->val1
);
break;
case self::WIDTH_HEIGHT:
return sprintf(
_t(
'ZenValidator.DIMWIDTHHEIGHT',
'Image width must be %s pixels and Image height must be %s pixels'
),
$this->val1,
$this->val2
);
break;
case self::RATIO:
return sprintf(
_t(
'ZenValidator.DIMRATIO',
'Image aspect ratio (shape) must be %s:%s'
),
$this->val1,
$this->val2
);
break;
case self::MIN_WIDTH:
return sprintf(
_t(
'ZenValidator.DIMMINWIDTH',
'Image width must be greater than or equal to %s pixels'
),
$this->val1
);
break;
case self::MIN_HEIGHT:
return sprintf(
_t(
'ZenValidator.DIMMINHEIGHT',
'Image height must be greater than or equal to %s pixels'
),
$this->val1
);
break;
case self::MIN_WIDTH_HEIGHT:
return sprintf(
_t(
'ZenValidator.DIMMINWIDTHHEIGHT',
'Image width must be greater than or equal to %s pixels and Image height must be greater than or equal to %s pixels'
),
$this->val1,
$this->val2
);
break;
case self::MAX_WIDTH:
return sprintf(
_t(
'ZenValidator.DIMMAXWIDTH',
'Image width must be less than or equal to %s pixels'
),
$this->val1
);
break;
case self::MAX_HEIGHT:
return sprintf(
_t(
'ZenValidator.DIMMAXHEIGHT',
'Image height must be less than or equal to %s pixels'
),
$this->val1
);
break;
case self::MAX_WIDTH_HEIGHT:
return sprintf(
_t(
'ZenValidator.DIMMAXWIDTHHEIGHT',
'Image width must be less than or equal to %s pixels and Image height must be less than or equal to %s pixels'
),
$this->val1,
$this->val2
);
break;
}
} | Gets the default message for the validator
@return string the validation message | entailment |
protected function addBrowseTableColumns(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model)
{
$tData = $this->util->getTokenData();
$bridge->gr2t_id_respondent_track; // Data needed for edit button
$bridge->gr2o_id_organization; // Data needed for edit button
// Get the buttons
$respMenu = $this->menu->findAllowedController('respondent', 'show');
if ($respMenu) {
$respondentButton = $respMenu->toActionLink($this->request, $bridge, $this->_('Show respondent'));
$respondentButton->appendAttrib('class', 'rightFloat');
} else {
$respondentButton = null;
}
$trackMenu = $this->menu->findAllowedController('respondent', 'show-track');
if ($trackMenu) {
$trackButton = $trackMenu->toActionLink($this->request, $bridge, $this->_('Show track'));
$trackButton->appendAttrib('class', 'rightFloat');
} else {
$trackButton = null;
}
// Row with dates and patient data
$bridge->tr(array('onlyWhenChanged' => true, 'class' => 'even'));
$bridge->addSortable('gr2o_patient_nr');
$bridge->addSortable('respondent_name')->colspan = 2;
if ($this->multiTracks) {
$bridge->addSortable('grs_birthday');
$bridge->addMultiSort('grs_city', array($respondentButton));
$model->set('gr2t_track_info', 'tableDisplay', 'smallData');
// Row with track info
$bridge->tr(array('onlyWhenChanged' => true, 'class' => 'even'));
$td = $bridge->addMultiSort('gtr_track_name', 'gr2t_track_info');
$td->class = 'indentLeft';
$td->colspan = 4;
$td->renderWithoutContent = false; // Do not display this cell and thus this row if there is not content
$td = $bridge->addMultiSort('progress', array($trackButton));
$td->renderWithoutContent = false; // Do not display this cell and thus this row if there is not content
} else {
$bridge->addSortable('grs_birthday');
$bridge->addMultiSort('progress', array($respondentButton));
}
$bridge->tr(array('class' => array('odd', $bridge->row_class), 'title' => $bridge->gto_comment));
$col = $bridge->addColumn(
$this->createInfoPlusCol($bridge),
' '); // Space needed because TableElement does not look at rowspans
$col->rowspan = 2;
$bridge->addSortable('gto_valid_from');
$bridge->addSortable('gto_valid_until');
$model->set('gto_round_description', 'tableDisplay', 'smallData');
$bridge->addMultiSort('gsu_survey_name', 'gto_round_description')->colspan = 2;
$bridge->tr(array('class' => array('odd', $bridge->row_class), 'title' => $bridge->gto_comment));
// $bridge->addColumn();
$bridge->addSortable('gto_mail_sent_date');
$bridge->addSortable('gto_completion_time');
$bridge->addSortable('gto_id_token');
$bridge->addMultiSort('ggp_name', [$this->createActionButtons($bridge)]);
} | Adds columns from the model to the bridge that creates the browse table.
Overrule this function to add different columns to the browse table, without
having to recode the core table building code.
@param \MUtil_Model_Bridge_TableBridge $bridge
@param \MUtil_Model_ModelAbstract $model
@return void | entailment |
protected function addColumns(\MUtil_Html_TableElement $table)
{
$table->addColumn(
array(\MUtil_Html::raw($this->repeater->key), 'class' => $this->repeater->class),
$this->_('Question code')
);
$table->addColumn(
array(\MUtil_Html::raw($this->repeater->question), 'class' => $this->repeater->class),
$this->_('Question')
);
$table->addColumn(
$this->repeater->answers->call($this, 'showAnswers', $this->repeater->answers),
$this->_('Answer options')
);
// $table->addColumn($this->repeater->type, 'Type');
} | Add the columns ot the table
This is a default implementation, overrule at will
@param \MUtil_Html_TableElement $table | entailment |
public function getHtmlOutput(\Zend_View_Abstract $view)
{
$div = \MUtil_Html::create('div');
if ($this->surveyId && $this->data) {
$div->h3(sprintf($this->_('Questions in survey %s'), $this->survey->getName()));
$div->append(parent::getHtmlOutput($view));
} else {
$this->addMessage($this->_('Survey not found'));
if ($this->surveyId) {
$div->pInfo(sprintf($this->_('Survey %s does not exist.'), $this->surveyId));
} else {
$div->pInfo($this->_('Survey not specified.'));
}
}
$item = $this->menu->getCurrentParent();
if ($item) {
$div->append($item->toActionLink($this->_('Cancel'), $this->request));
}
return $div;
} | Create the snippets content
This is a stub function either override getHtmlOutput() or override render()
@param \Zend_View_Abstract $view Just in case it is needed here
@return \MUtil_Html_HtmlInterface Something that can be rendered | entailment |
public function hasHtmlOutput()
{
// Apply translations
if (! $this->showAnswersTranslated) {
// Here, not in e.g. __construct as these vars may be set during initiation
$this->showAnswersNone = $this->_($this->showAnswersNone);
$this->showAnswersRemoved = $this->_($this->showAnswersRemoved);
$this->showAnswersSeparator = $this->_($this->showAnswersSeparator);
$this->showAnswersTranslated = true;
}
// Overrule any setting of these values from source
$this->data = null;
$this->repeater = null;
if (! $this->surveyId) {
if (($this->token instanceof \Gems_Tracker_Token) && $this->token->exists) {
$this->surveyId = $this->token->getSurveyId();
} elseif ($this->trackData && (! $this->trackId)) {
// Look up key values from trackData
if (isset($this->trackData['gsu_id_survey'])) {
$this->surveyId = $this->trackData['gsu_id_survey'];
} elseif (isset($this->trackData['gro_id_survey'])) {
$this->surveyId = $this->trackData['gro_id_survey'];
} elseif (! $this->trackId) {
if (isset($this->trackData['gtr_id_track'])) {
$this->trackId = $this->trackData['gtr_id_track'];
} elseif (isset($this->trackData['gro_id_track'])) {
$this->trackId = $this->trackData['gro_id_track'];
}
}
}
if ((! $this->trackId) && $this->trackEngine) {
$this->trackId = $this->trackEngine->getTrackId();
}
if ($this->trackId && (! $this->surveyId)) {
// Use the track ID to get the id of the first active survey
$this->surveyId = $this->db->fetchOne('SELECT gro_id_survey FROM gems__rounds WHERE gro_active = 1 AND gro_id_track = ? ORDER BY gro_id_order', $this->trackId);
}
}
// \MUtil_Echo::track($this->surveyId, $this->trackId);
// Get the survey
if ($this->surveyId && (! $this->survey instanceof \Gems_Tracker_Survey)) {
$this->survey = $this->loader->getTracker()->getSurvey($this->surveyId);
}
// Load the data
if (($this->survey instanceof \Gems_Tracker_Survey) && $this->survey->exists) {
$this->data = \MUtil_Ra::addKey($this->survey->getQuestionInformation($this->locale->getLanguage()), 'key');
//\MUtil_Echo::track($this->data);
}
return parent::hasHtmlOutput();
} | The place to check if the data set in the snippet is valid
to generate the snippet.
When invalid data should result in an error, you can throw it
here but you can also perform the check in the
checkRegistryRequestsAnswers() function from the
{@see \MUtil_Registry_TargetInterface}.
@return boolean | entailment |
protected function addClass($addClass) {
$targetClass = $this->getAttrib('class');
if(!empty($targetClass) && (strpos($targetClass, $addClass) === false)) {
$targetClass .= " {$addClass}";
} else {
$targetClass = $addClass;
}
$this->setAttrib('class', $targetClass);
return $this;
} | Add a class to an existing class, taking care of spacing
@param string $targetClass The existing class
@param string $addClass the Class or classes to add, seperated by spaces | entailment |
public function loadDefaultDecorators()
{
if ($this->loadDefaultDecoratorsIsDisabled()) {
return $this;
}
$htmlTagOptions = array(
'tag' => 'div',
'id' => array('callback' => array(get_class($this), 'resolveElementId')),
);
$labelOptions = array();
if (\MUtil_Bootstrap::enabled()) {
$htmlTagOptions['class'] = 'element-container';
}
$decorators = $this->getDecorators();
if (empty($decorators)) {
$this->addDecorator('ViewHelper')
->addDecorator('Errors')
->addDecorator('Description', array('tag' => 'p', 'class' => 'help-block'))
->addDecorator('HtmlTag', $htmlTagOptions)
->addDecorator('Label')
->addDecorator('BootstrapRow');
}
return $this;
} | Load default decorators
@return \Zend_Form_Element | entailment |
public function setBasePath($basePath) {
$basePath = (string) $basePath;
if (file_exists($basePath . '/ckeditor.js')) {
$this->basePath = $basePath;
} else {
throw new \Zend_Exception(sprintf('CKEditor.php not found at %s', $basePath));
}
return $this;
} | Set the path to the public files of the CKEditor
@param string $basePath
@return CKEditor_Form_CKEditor | entailment |
public function setCKConfig($key, $value = null) {
if (is_array($key)) {
if (false === $value) {
// Overwrite existing config
$this->config = $key;
} else {
// Add to existing config
foreach ($key as $idx => $value)
{
$this->config[$idx] = $value;
}
}
} else {
// Set individual item, add to existing config
$this->config[$key] = $value;
}
} | Set the configuration for the CKEditor
ARRAY
Use array as first parameter to set all items at once. This will
overwrite the existing config. Use false as second parameter to ADD
to the existing config
STRING
or use a string to set items one by one, the second parameter is
the value
@param string|array $key
@param mixed $value | entailment |
public function setView(\Zend_View_Interface $view = null) {
if (null !== $view) {
if (false === $view->getPluginLoader('helper')->getPaths('CKEditor_View_Helper')) {
$view->addHelperPath('CKEditor/View/Helper', 'CKEditor_View_Helper');
}
}
if (!file_exists($this->basePath . '/ckeditor.js')) {
throw new \Zend_Exception('Use setBasePath() to set the full path to the file ckeditor.php in the public folder of ckedit.');
}
return parent::setView($view);
} | Set the view object
Ensures that the view object has the CKEditor view helper path set.
@param \Zend_View_Interface $view
@return CKEditor_Form_CKEditor | entailment |
protected function addFormElements(\Zend_Form $form)
{
$element = $form->createElement('textarea', 'script');
$element->setDescription($this->_('Separate multiple commands with semicolons (;).'));
$element->setLabel('SQL:');
$element->setRequired(true);
$form->addElement($element);
$this->saveLabel = $this->_('Run');
$this->addCsrf();
$this->addSaveButton();
} | 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 loadForm()
{
if (! $this->_form) {
$options = array();
if (\MUtil_Bootstrap::enabled()) {
//$options['class'] = 'form-horizontal';
$options['role'] = 'form';
}
$this->_form = $this->createForm($options);
$this->addFormElements($this->_form);
}
} | Makes sure there is a form. | entailment |
public function getHtmlOutput(\Zend_View_Abstract $view)
{
$output = parent::getHtmlOutput($view);
if ($this->result) {
$output->h3($this->_('Result sets'));
$output[] = $this->getResultTable($this->result);
}
return $output;
} | 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 getResultTable($results)
{
$resultSet = 1;
$resultTable = \MUtil_Html::create()->array();
foreach ($results as $result) {
if (is_string($result)) {
$this->addMessage($result);
} else {
$resultRow = $resultTable->echo($result, sprintf($this->_('Result set %s.'), $resultSet++));
$resultRow->class = 'browser';
}
}
return $resultTable;
} | Return an array attribute with the current resultset
@return \MUtil_Html_ArrayAttribute | entailment |
protected function saveData()
{
$resultSet = 0;
if($this->request->isPost()) {
$this->_form->populate($this->request->getPost());
}
if ($this->_saveButton->isChecked() && $this->_form->isValid($this->request->getPost())) {
$data = $this->_form->getValues();
$data['name'] = '';
$data['type'] = $this->_('raw');
$model = $this->getModel();
$this->result = $model->runScript($data, true);
}
} | Hook containing the actual save code.
@return int The number of "row level" items changed | entailment |
public static function pagePanel($paginator = null, $request = null, $translator = null, $args = null)
{
$types = array(
'paginator' => 'Zend_Paginator',
'request' => 'Zend_Controller_Request_Abstract',
'translator' => 'Zend_Translate',
'view' => 'Zend_View',
);
$args = \MUtil_Ra::args(func_get_args(), $types, null, \MUtil_Ra::STRICT);
$panel_args = array();
foreach (array('baseUrl', 'paginator', 'request', 'scrollingStyle', 'view', 'itemCount') as $var) {
if (isset($args[$var])) {
$panel_args[$var] = $args[$var];
unset($args[$var]);
}
}
if (isset($args['translator'])) {
$translator = $args['translator'];
unset($args['translator']);
} else {
$translator = \Zend_Registry::get('Zend_Translate');
}
if (isset($args['class'])) {
if ($args['class'] instanceof \MUtil_Html_AttributeInterface) {
$args['class']->add('browselink');
} else {
$args['class'] = new \MUtil_Html_ClassArrayAttribute('browselink', $args['class']);;
}
} else {
$args['class'] = new \MUtil_Html_ClassArrayAttribute('browselink');
}
// \MUtil_Echo::track($args);
// \MUtil_Echo::track($panel_args['baseUrl']);
if (\MUtil_Bootstrap::enabled()) {
$pager = new \MUtil_Bootstrap_Html_PagePanel($panel_args);
} else {
$pager = new \MUtil_Html_PagePanel($panel_args);
}
$pager[] = $pager->pageLinks(
array($translator->_('<< First'), 'class' => new \MUtil_Html_ClassArrayAttribute('browselink', 'keyHome')),
array($translator->_('< Previous'), 'class' => new \MUtil_Html_ClassArrayAttribute('browselink', 'keyPgUp')),
array($translator->_('Next >'), 'class' => new \MUtil_Html_ClassArrayAttribute('browselink', 'keyPgDn')),
array($translator->_('Last >>'), 'class' => new \MUtil_Html_ClassArrayAttribute('browselink', 'keyEnd')),
$translator->_(' | '), $args);
$pager->div(
$pager->uptoOffDynamic(
$translator->_('to'),
$translator->_('of'),
array('-', 'class' => new \MUtil_Html_ClassArrayAttribute('browselink btn btn-xs', 'keyCtrlUp')),
array('+', 'class' => new \MUtil_Html_ClassArrayAttribute('browselink btn btn-xs', 'keyCtrlDown')),
null,
' ',
$args),
array('class' => 'pagination-index rightFloat pull-right'));
return $pager;
} | Create a page panel
@param mixed $paginator \MUtil_Ra::args() arguements
@param mixed $request
@param mixed $translator
@param mixed $args
@return \MUtil_Html_PagePanel | entailment |
public function execute($lineNr = null, $fieldData = null)
{
$batch = $this->getBatch();
$import = $batch->getVariable('import');
if (! (isset($import['trackId']) && $import['trackId'])) {
// Do nothing
return;
}
$tracker = $this->loader->getTracker();
$trackEngine = $tracker->getTrackEngine($import['trackId']);
$fieldModel = $trackEngine->getFieldsMaintenanceModel(true, 'create');
$fieldData['gtf_id_track'] = $import['trackId'];
$fieldData = $fieldModel->save($fieldData);
// Store the field reference
$import['fieldCodes']['{f' . $fieldData['gtf_id_order'] . '}'] = FieldsDefinition::makeKey(
$fieldData['sub'],
$fieldData['gtf_id_field']
);
if (isset($fieldData['gtf_calculate_using']) && $fieldData['gtf_calculate_using']) {
$batch->addTask(
'Tracker\\Import\\UpdateFieldCalculationTask',
$lineNr,
$fieldData['gtf_id_field'],
$fieldModel->getModelNameForRow($fieldData),
$fieldData['gtf_calculate_using']
);
}
} | Should handle execution of the task, taking as much (optional) parameters as needed
The parameters should be optional and failing to provide them should be handled by
the task
@param array $trackData Nested array of trackdata | entailment |
public function _processRowAfterLoad(array $row, $new = false, $isPost = false, &$transformColumns = array())
{
if ($this->_addLoadDependency) {
// Display of data field
if (! (isset($row['gtf_field_type']) && $row['gtf_field_type'])) {
$row['gtf_field_type'] = $this->getFieldType($row);
}
// assert: $row['gtf_field_type'] is now always filled.
if (! isset($row[$this->_modelField])) {
$row[$this->_modelField] = $this->getModelNameForRow($row);
}
// Now add the type specific dependency (if any)
$class = $this->getTypeDependencyClass($row['gtf_field_type']);
if ($class) {
$dependency = $this->tracker->createTrackClass($class, $row['gtf_id_track']);
$this->addDependency($dependency, null, null, 'row');
}
}
return parent::_processRowAfterLoad($row, $new, $isPost, $transformColumns);
} | Process on load functions and dependencies
@see addDependency()
@see setOnLoad()
@param array $row The row values to load
@param boolean $new True when it is a new item not saved in the model
@param boolean $isPost True when passing on post data
@param array $transformColumns
@return array The possibly adapted array of values | entailment |
protected function addAppointmentsToModel()
{
$model = new \MUtil_Model_TableModel('gems__track_appointments');
\Gems_Model::setChangeFieldsByPrefix($model, 'gtap');
$map = $model->getItemsOrdered();
$map = array_combine($map, str_replace('gtap_', 'gtf_', $map));
$map['gtap_id_app_field'] = 'gtf_id_field';
$this->addUnionModel($model, $map, self::APPOINTMENTS_NAME);
$model->addColumn(new \Zend_Db_Expr("'appointment'"), 'gtf_field_type');
$model->addColumn(new \Zend_Db_Expr("NULL"), 'gtf_field_values');
$model->addColumn(new \Zend_Db_Expr("NULL"), 'gtf_field_default');
$model->addColumn(new \Zend_Db_Expr("NULL"), 'gtf_calculate_using');
} | Add appointment model to union model | entailment |
public function applyBrowseSettings($detailed = false)
{
$this->resetOrder();
$yesNo = $this->util->getTranslated()->getYesNo();
$types = $this->getFieldTypes();
$this->set('gtf_id_track'); // Set order
$this->set('gtf_field_name', 'label', $this->_('Name'));
$this->set('gtf_id_order', 'label', $this->_('Order'),
'description', $this->_('The display and processing order of the fields.')
);
$this->set('gtf_field_type', 'label', $this->_('Type'),
'multiOptions', $types,
'default', 'text'
);
if ($detailed) {
$this->set('gtf_field_values'); // Set order
$this->set('gtf_field_default'); // Set order
$this->set('gtf_field_description'); // Set order
}
$this->set('gtf_field_code', 'label', $this->_('Field code'),
'description', $this->_('Optional code name to link the field to program code.')
);
$this->set('htmlUse',
'elementClass', 'Exhibitor', 'nohidden', true,
'value', \MUtil_Html::create('h3', $this->_('Field use'))
);
$this->set('gtf_to_track_info', 'label', $this->_('In description'),
'description', $this->_('Add this field to the track description'),
'multiOptions', $yesNo
);
$this->set('gtf_track_info_label', // No label, set order
'description', $this->_('Add the name of this field to the track description'),
'multiOptions', $yesNo,
'required', false
);
$this->set('gtf_required', 'label', $this->_('Required'),
'multiOptions', $yesNo,
'required', false
);
$this->set('gtf_readonly', 'label', $this->_('Readonly'),
'description', $this->_('Check this box if this field is always set by code instead of the user.'),
'multiOptions', $yesNo,
'required', false
);
$this->set('htmlCalc',
'elementClass', 'None', 'nohidden', true,
'value', \MUtil_Html::create('h3', $this->_('Field calculation'))
);
$this->set('gtf_calculate_using',
'description', $this->_('Automatically calculate this field using other fields')
);
if ($detailed) {
// Appointment caculcation field
$this->set('gtf_filter_id'); // Set order
$this->set('gtf_min_diff_length'); // Set order
$this->set('gtf_min_diff_unit'); // Set order
$this->set('gtf_max_diff_exists', 'multiOptions', $yesNo); // Set order
$this->set('gtf_max_diff_length'); // Set order
$this->set('gtf_max_diff_unit'); // Set order
$this->set('gtf_after_next'); // Set order
$this->set('gtf_uniqueness'); // Set order
} else {
$this->set('calculation', 'label', $this->_('Calculate using'),
'description', $this->_('Automatically calculate this field using other fields'),
'noSort', true
);
$this->setOnLoad('calculation', array($this, 'loadCalculationSources'));
}
$this->set('gtf_create_track', 'label', $this->_('Create track'),
'description', $this->_('Create a track if the respondent does not have a track where this field is empty.'),
'multiOptions', $yesNo
);
$this->set('gtf_create_wait_days'); // Set order
return $this;
} | Set those settings needed for the browse display
@param boolean $detailed For detailed settings
@return \Gems\Tracker\Model\FieldMaintenanceModel (continuation pattern) | entailment |
public function applyDetailSettings()
{
$this->applyBrowseSettings(true);
$this->_addLoadDependency = true;
$this->set('gtf_id_track', 'label', $this->_('Track'),
'multiOptions', $this->util->getTrackData()->getAllTracks()
);
$this->set('gtf_field_description', 'label', $this->_('Description'),
'description', $this->_('Optional extra description to show the user.')
);
$this->set('gtf_track_info_label', 'label', $this->_('Add name to description'));
$this->set('htmlUse', 'label', ' ');
// But do always transform gtf_calculate_using on load and save
// as otherwise we might not be sure what to do
$contact = new \MUtil_Model_Type_ConcatenatedRow(self::FIELD_SEP, '; ', false);
$contact->apply($this, 'gtf_calculate_using');
// Clean up data always show in browse view, but not always in detail views
$this->set('gtf_create_track', 'label', null);
$switches = array(
0 => array(
'gtf_track_info_label' => array('elementClass' => 'Hidden', 'label' => null),
),
);
$this->addDependency(array('ValueSwitchDependency', $switches), 'gtf_to_track_info');
} | Set those settings needed for the detailed display
@return \Gems\Tracker\Model\FieldMaintenanceModel (continuation pattern) | entailment |
public function applyEditSettings()
{
$this->applyDetailSettings();
$this->set('gtf_id_field', 'elementClass', 'Hidden');
$this->set('gtf_id_track', 'elementClass', 'Exhibitor');
$this->set('gtf_field_type', 'elementClass', 'Exhibitor');
$this->set('gtf_field_name', 'elementClass', 'Text',
'size', '30',
'minlength', 2,
'required', true,
'validator', $this->createUniqueValidator(array('gtf_field_name', 'gtf_id_track'))
);
$this->set('gtf_id_order', 'elementClass', 'Text',
'validators[int]', 'Int',
'validators[gt]', new \Zend_Validate_GreaterThan(0),
'validators[unique]', $this->createUniqueValidator(array('gtf_id_order', 'gtf_id_track'))
);
$this->set('gtf_field_code', 'elementClass', 'Text', 'minlength', 4);
$this->set('gtf_field_description', 'elementClass', 'Text', 'size', 30);
$this->set('gtf_field_values', 'elementClass', 'Hidden');
$this->set('gtf_field_default', 'elementClass', 'Hidden');
$this->set('gtf_to_track_info', 'elementClass', 'CheckBox',
'onclick', 'this.form.submit();'
);
$this->set('gtf_track_info_label', 'elementClass', 'CheckBox',
'required', false);
$this->set('gtf_required', 'elementClass', 'CheckBox');
$this->set('gtf_readonly', 'elementClass', 'CheckBox');
$this->set('gtf_filter_id', 'elementClass', 'Hidden');
$this->set('gtf_min_diff_length', 'elementClass', 'Hidden');
$this->set('gtf_min_diff_unit', 'elementClass', 'Hidden');
$this->set('gtf_max_diff_length', 'elementClass', 'Hidden');
$this->set('gtf_max_diff_unit', 'elementClass', 'Hidden');
$this->set('gtf_after_next', 'elementClass', 'None'); // Deprecatedin 1.7.1
$this->set('gtf_uniqueness', 'elementClass', 'Hidden');
$this->set('gtf_create_track', 'elementClass', 'Hidden');
$this->set('gtf_create_wait_days', 'elementClass', 'Hidden');
$class = 'Model\\Dependency\\FieldTypeChangeableDependency';
$dependency = $this->tracker->createTrackClass($class, $this->_modelField);
$this->addDependency($dependency);
} | Set those values needed for editing
@return \Gems\Tracker\Model\FieldMaintenanceModel (continuation pattern) | entailment |
public function delete($filter = true)
{
$rows = $this->load($filter);
foreach ($rows as $row) {
$name = $this->getModelNameForRow($row);
$field = $row['gtf_id_field'];
if (self::FIELDS_NAME === $name) {
$this->db->delete(
'gems__respondent2track2field',
$this->db->quoteInto('gr2t2f_id_field = ?', $field)
);
} elseif (self::APPOINTMENTS_NAME === $name) {
$this->db->delete(
'gems__respondent2track2appointment',
$this->db->quoteInto('gr2t2a_id_app_field = ?', $field)
);
}
}
return parent::delete($filter);
} | 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 |
protected function getFieldType(array &$row)
{
if (isset($row[$this->_modelField]) && ($row[$this->_modelField] === self::APPOINTMENTS_NAME)) {
return 'appointment';
}
if (isset($row['gtf_id_field']) && $row['gtf_id_field']) {
$row[\Gems_Model::FIELD_ID] = $row['gtf_id_field'];
}
if (isset($row[\Gems_Model::FIELD_ID])) {
return $this->db->fetchOne(
"SELECT gtf_field_type FROM gems__track_fields WHERE gtf_id_field = ?",
$row[\Gems_Model::FIELD_ID]
);
}
if (! $this->has('gtf_field_type', 'default')) {
$this->set('gtf_field_type', 'default', 'text');
}
return $this->get('gtf_field_type', 'default');
} | Get the type from the row in case it was not set
@param array $row Loaded row
@return string Data type for the row | entailment |
public function getFieldTypes()
{
$output = array(
'activity' => $this->_('Activity'),
'appointment' => $this->_('Appointment'),
'boolean' => $this->_('Boolean'),
'caretaker' => $this->_('Caretaker'),
'consent' => $this->_('Consent'),
'date' => $this->_('Date'),
'text' => $this->_('Free text'),
'textarea' => $this->_('Long free text'),
'location' => $this->_('Location'),
'datetime' => $this->_('Moment in time'),
'procedure' => $this->_('Procedure'),
'relation' => $this->_('Relation'),
'select' => $this->_('Select one'),
'multiselect' => $this->_('Select multiple'),
'track' => $this->_('Track'),
);
asort($output);
return $output;
} | The list of field types
@return array of storage name => label | entailment |
public function getModelNameForRow(array $row)
{
if (isset($row['gtf_field_type']) && ('appointment' === $row['gtf_field_type'])) {
return self::APPOINTMENTS_NAME;
}
if ((! isset($row['gtf_field_type'])) && isset($row[$this->_modelField]) && $row[$this->_modelField]) {
return $row[$this->_modelField];
}
return self::FIELDS_NAME;
} | Get the name of the union model that should be used for this row.
@param array $row
@return string | entailment |
public function getTypeDependencyClass($fieldType)
{
if (isset($this->dependencies[$fieldType]) && $this->dependencies[$fieldType]) {
return 'Model\\Dependency\\' . $this->dependencies[$fieldType];
}
} | Get the dependency class name (if any)
@param string $fieldType
@return string Classname including Model\Dependency\ part | entailment |
protected function loadCalculationSources($value, $isNew = false, $name = null, array $context = array(), $isPost = false)
{
if ($isPost) {
return $value;
}
if (isset($context['gtf_filter_id']) && $context['gtf_filter_id']) {
$filters = $this->loader->getAgenda()->getFilterList();
if (isset($filters[$context['gtf_filter_id']])) {
return $filters[$context['gtf_filter_id']];
} else {
return sprintf($this->_("Non-existing filter %s"), $context['gtf_filter_id']);
}
}
if (isset($context['gtf_calculate_using']) && $context['gtf_calculate_using']) {
$count = substr_count($context['gtf_calculate_using'], '|') + 1;
return sprintf($this->plural('%d field', '%d fields', $count), $count);
}
return $value;
} | A ModelAbstract->setOnLoad() function that concatenates the
value if it is an array.
@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
@param boolean $isPost True when passing on post data
@return string Desciption | entailment |
public function loadFirst($filter = true, $sort = true, $loadDependencies = true)
{
// Needed as the default order otherwise triggers the type dependency
$oldDep = $this->_addLoadDependency;
$this->_addLoadDependency = $loadDependencies;
$output = parent::loadFirst($filter, $sort);
$this->_addLoadDependency = $oldDep;
return $output;
} | Returns an array containing the first requested item.
@param mixed $filter True to use the stored filter, array to specify a different filteloa
@param mixed $sort True to use the stored sort, array to specify a different sort
@param boolean $loadDependencies When true the row dependencies are loaded
@return array An array or false | entailment |
protected function addModelSettings(array &$settings)
{
$empty = [];
$multi = explode(parent::FIELD_SEP, $this->_fieldDefinition['gtf_field_values']);
if (empty($this->_fieldDefinition['gtf_field_values']) || empty($multi)) {
$multi = $this->util->getTranslated()->getYesNo();
}
if ($this->_fieldDefinition['gtf_required'] !== 1) {
$empty = $this->util->getTranslated()->getEmptyDropdownArray();
}
$settings['elementClass'] = 'Radio';
$settings['separator'] = ' ';
$settings['multiOptions'] = $empty + array_combine($this->keyValues, array_slice($multi, 0, 2));
if ($this->_fieldDefinition['gtf_field_default'] !== null) {
$settings['default'] = (int)$this->_fieldDefinition['gtf_field_default'];
}
} | Add the model settings like the elementClass for this field.
elementClass is overwritten when this field is read only, unless you override it again in getDataModelSettings()
@param array $settings The settings set so far | entailment |
public function afterRegistry()
{
parent::afterRegistry();
if ($this->showForRespondents && is_bool($this->showForRespondents)) {
$this->showForRespondents = $this->_('Respondents');
}
if ($this->showForStaff && is_bool($this->showForStaff)) {
$this->showForStaff = $this->_('Staff');
}
if ($this->showForTracks && is_bool($this->showForTracks)) {
$this->showForTracks = $this->_('Tracks');
}
if ($this->showTitle && is_bool($this->showTitle)) {
$this->showTitle = $this->_('Add');
}
} | Called after the check that all required registry values
have been set correctly has run.
@return void | entailment |
public function getHtmlOutput(\Zend_View_Abstract $view)
{
$pageRef = array(\MUtil_Model::REQUEST_ID => $this->request->getParam(\MUtil_Model::REQUEST_ID));
$output = false;
$addToLists = \MUtil_Html::create()->div(array('class' => 'tooldock'));
if ($this->showTitle) {
$addToLists->strong($this->showTitle);
}
if ($this->showForTracks) {
$dropdown = $this->_getTracks('tracks', $pageRef, $this->showForTracks);
if ($dropdown) {
$addToLists[] = $dropdown;
$output = true;
}
}
if ($this->showForRespondents || $this->showForStaff) {
$div = \MUtil_Html::create()->div(array('class' => 'toolbox btn-group'));
$div->button($this->_('Surveys for'), array('class' => 'toolanchor btn', 'type' => 'button'));
if ($this->showForRespondents) {
$dropdown = $this->_getTracks('respondents', $pageRef, $this->showForRespondents);
if ($dropdown) {
$div[] = $dropdown;
$output = true;
}
}
if ($this->showForStaff) {
$dropdown = $this->_getTracks('staff', $pageRef, $this->showForStaff);
if ($dropdown) {
$div[] = $dropdown;
$output = true;
}
}
$addToLists[] = $div;
}
if ($output) {
return $addToLists;
}
} | Allow manual assignment of surveys/tracks to a patient
If project uses the \Gems_Project_Tracks_MultiTracksInterface, show a track drowpdown
If project uses the \Gems_Project_Tracks_StandAloneSurveysInterface, show a survey
drowpdown for both staff and patient
@param \Zend_View_Abstract $view Just in case it is needed here
@return \MUtil_Html_HtmlInterface Something that can be rendered | entailment |
public function createModel($detailed, $action)
{
$engine = $this->getTrackEngine();
$model = $engine->getFieldsMaintenanceModel($detailed, $action);
return $model;
} | Creates a model for getModel(). Called only for each new $action.
The parameters allow you to easily adapt the model to the current action. The $detailed
parameter was added, because the most common use of action is a split between detailed
and summarized actions.
@param boolean $detailed True when the current action is not in $summarizedActions.
@param string $action The current action.
@return \Gems_Model_TrackModel | entailment |
public function getDeleteQuestion()
{
$field = $this->_getParam('fid');
if (FieldMaintenanceModel::APPOINTMENTS_NAME === $this->_getParam('sub')) {
$used = $this->db->fetchOne(
"SELECT COUNT(*)
FROM gems__respondent2track2appointment
WHERE gr2t2a_id_app_field = ? AND gr2t2a_id_appointment IS NOT NULL",
$field
);
} else {
$used = $this->db->fetchOne(
"SELECT COUNT(*)
FROM gems__respondent2track2field
WHERE gr2t2f_id_field = ? AND gr2t2f_value IS NOT NULL",
$field
);
}
if (! $used) {
return $this->_('Do you want to delete this field?');
}
$this->addMessage(sprintf($this->plural(
'This field will be deleted from %s assigned track.',
'This field will be deleted from %s assigned tracks.',
$used), $used));
return sprintf($this->plural(
'Do you want to delete this field and the value stored for the field?',
'Do you want to delete this field and the %s values stored for the field?',
$used), $used);
} | Helper function to get the question for the delete action.
@return $string | entailment |
public function getCreateTitle()
{
return sprintf(
$this->_('New field for %s track...') ,
$this->util->getTrackData()->getTrackTitle($this->_getIdParam())
);
} | Helper function to get the title for the create action.
@return $string | entailment |
public function getIndexTitle()
{
return sprintf($this->_('Fields %s'), $this->util->getTrackData()->getTrackTitle($this->_getIdParam()));
} | Helper function to get the title for the index action.
@return $string | entailment |
public function execute($sourceId = null, $userId = null)
{
$batch = $this->getBatch();
$source = $this->loader->getTracker()->getSource($sourceId);
if (is_null($userId)) {
$userId = $this->loader->getCurrentUser()->getUserId();
}
$surveyCount = $batch->addToCounter('sourceSyncSources');
$batch->setMessage('sourceSyncSources', sprintf(
$this->plural('Check %s source', 'Check %s sources', $surveyCount),
$surveyCount
));
$source->synchronizeSurveyBatch($batch, $userId);
} | Should handle execution of the task, taking as much (optional) parameters as needed
The parameters should be optional and failing to provide them should be handled by
the task | entailment |
public function execute($trackId = null, $exportOrganizations = false)
{
$batch = $this->getBatch();
$data = $this->db->fetchRow("SELECT * FROM gems__tracks WHERE gtr_id_track = ?", $trackId);
$orgs = $exportOrganizations ? $data['gtr_organizations'] : false;
unset($data['gtr_id_track'], $data['gtr_track_type'], $data['gtr_active'], $data['gtr_survey_rounds'], $data['gtr_organizations'],
$data['gtr_changed'],
$data['gtr_changed_by'], $data['gtr_created'], $data['gtr_created_by']);
// Main track data
$this->exportTypeHeader('track');
$this->exportFieldHeaders($data);
$this->exportFieldData($data);
if ($orgs) {
// Organizations
$this->exportTypeHeader('organizations');
$this->exportFieldHeaders(array('gor_id_organization' => null, 'gor_name' => null));
foreach (explode('|', $orgs) as $orgId) {
if ($orgId) {
$org = $this->loader->getOrganization($orgId);
if ($org) {
$this->exportFieldData(array($orgId, $org->getName()));
}
}
}
$batch->addMessage($this->_('Trackdata exported with organizations.'));
} else {
$batch->addMessage($this->_('Trackdata exported without organizations.'));
}
$this->exportFlush();
} | Should handle execution of the task, taking as much (optional) parameters as needed
The parameters should be optional and failing to provide them should be handled by
the task | entailment |
protected function addBrowseTableColumns(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model)
{
// Make sure these fields are loaded
$model->get('gro_valid_after_field');
$model->get('gro_valid_after_id');
$model->get('gro_valid_after_length');
$model->get('gro_valid_after_source');
$model->get('gro_valid_after_unit');
$model->get('gro_valid_for_field');
$model->get('gro_valid_for_id');
$model->get('gro_valid_for_length');
$model->get('gro_valid_for_source');
$model->get('gro_valid_for_unit');
// We want to markt the row for inactive surveys so it visually stands out
$model->get('gsu_active');
$bridge->tr()->appendAttrib('class', \MUtil_Lazy::iif(
$bridge->gsu_active,
'',
'inactive'
));
// Add link to survey-edit
$menuItems = $this->findMenuItems('survey-maintenance', 'edit');
if ($menuItems) {
$menuItem = reset($menuItems);
if ($menuItem instanceof \Gems_Menu_SubMenuItem) {
$href = $menuItem->toHRefAttribute(['id' => $bridge->getLazy('gro_id_survey')]);
if ($href) {
$aElem = new \MUtil_Html_AElement($href);
$aElem->setOnEmpty('');
$model->set('gro_id_survey', 'itemDisplay', $aElem);
}
}
}
parent::addBrowseTableColumns($bridge, $model);
} | Adds columns from the model to the bridge that creates the browse table.
Overrule this function to add different columns to the browse table, without
having to recode the core table building code.
@param \MUtil_Model_Bridge_TableBridge $bridge
@param \MUtil_Model_ModelAbstract $model
@return void | entailment |
public function afterRegistry()
{
parent::afterRegistry();
$model = $this->getModel();
$br = \MUtil_Html::create('br');
$sp = \MUtil_Html::raw(' ');
$this->columns[10] = array('gro_id_order');
$this->columns[20] = array('gro_id_survey');
$this->columns[30] = array('gro_round_description');
$this->columns[40] = array('gro_icon_file');
$this->columns[45] = array('ggp_name');
$fromHeader = array(
'', // No content
array($this->_('Valid from'), $br) // Force break in the header
);
$untilHeader = array('', array($this->_('Valid until'), $br));
$this->columns[50] = array($fromHeader,'gro_valid_after_field', $sp, 'gro_valid_after_source', $sp, 'gro_valid_after_id');
$this->columns[60] = array($untilHeader, 'gro_valid_for_field', $sp, 'gro_valid_for_source', $sp, 'gro_valid_for_id');
$this->columns[70] = array('gro_active');
if ($label = $model->get('gro_changed_event', 'label')) {
$this->columns[80] = array('gro_changed_event');
}
if ($label = $model->get('gro_changed_event', 'label')) {
$this->columns[90] = array('gro_display_event');
}
$this->columns[100] = array('gro_code');
$this->columns[110] = array('condition_display');
// Organizations can possibly be replaced with a condition
$this->columns[120] = array('organizations');
} | Called after the check that all required registry values
have been set correctly has run.
@return void | entailment |
protected function createModel()
{
if (! $this->model instanceof RoundModel) {
$this->model = $this->trackEngine->getRoundModel(false, 'index');
}
// Now add the joins so we can sort on the real name
// $this->model->addTable('gems__surveys', array('gro_id_survey' => 'gsu_id_survey'));
// $this->model->set('gsu_survey_name', $this->model->get('gro_id_survey'));
return $this->model;
} | Creates the model
@return \MUtil_Model_ModelAbstract | entailment |
protected function addShowTableRows(\MUtil_Model_Bridge_VerticalTableBridge $bridge, \MUtil_Model_ModelAbstract $model)
{
if ($this->addOnclickEdit) {
$menuItem = $this->getEditMenuItem();
if ($menuItem) {
// Add click to edit
$bridge->tbody()->onclick = array('location.href=\'', $menuItem->toHRefAttribute($this->request), '\';');
}
}
parent::addShowTableRows($bridge, $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 | entailment |
public function getHtmlOutput(\Zend_View_Abstract $view)
{
if ($table = parent::getHtmlOutput($view)) {
if ($title = $this->getTitle()) {
$htmlDiv = \MUtil_Html::div(array('renderWithoutContent' => false));
$htmlDiv->h3($title);
$this->applyHtmlAttributes($table);
$htmlDiv[] = $table;
return $htmlDiv;
} else {
return $table;
}
}
} | Create the snippets content
This is a stub function either override getHtmlOutput() or override render()
@param \Zend_View_Abstract $view Just in case it is needed here
@return \MUtil_Html_HtmlInterface Something that can be rendered | entailment |
protected function setShowTableFooter(\MUtil_Model_Bridge_VerticalTableBridge $bridge, \MUtil_Model_ModelAbstract $model)
{
if ($this->displayMenu) {
if (! $this->menuList) {
$this->menuList = $this->menu->getCurrentMenuList($this->request, $this->_('Cancel'));
}
if ($this->menuList instanceof \Gems_Menu_MenuList) {
$this->menuList->addParameterSources($bridge);
}
$bridge->tfrow($this->menuList, array('class' => 'centerAlign'));
}
} | Set the footer of the browse table.
Overrule this function to set the header differently, without
having to recode the core table building code.
@param \MUtil_Model_Bridge_VerticalTableBridge $bridge
@param \MUtil_Model_ModelAbstract $model
@return void | entailment |
public function getFormElements(&$form, &$data)
{
$element = $form->createElement('multiCheckbox', 'format');
$element->setLabel($this->_('CSV options'))
->setMultiOptions(array(
'addHeader' => $this->_('Add headers with column names'),
'formatVariable' => $this->_('Export labels instead of field names'),
'formatAnswer' => $this->_('Format answers')
))
->setBelongsTo($this->getName())
->setSeparator(' ');
$elements['format'] = $element;
$element = $form->createElement('select', 'delimiter');
$element->setLabel($this->_('Delimiter'))
->setMultiOptions(array(',' => ',', ';' => ';'))
->setBelongsTo($this->getName());
$elements['delimiter'] = $element;
return $elements;
} | form elements for extra options for this particular export option
@param \MUtil_Form $form Current form to add the form elements
@param array $data current options set in the form
@return array Form elements | entailment |
protected function addHeader($filename)
{
$file = fopen($filename, 'w');
$bom = pack("CCC", 0xef, 0xbb, 0xbf);
fwrite($file, $bom);
$name = $this->getName();
if (isset($this->data[$name], $this->data[$name]['format'], $this->data[$name]['format'][0]) && in_array('addHeader', $this->data[$name]['format'])) {
$labeledCols = $this->getLabeledColumns();
$labels = array();
if (in_array('formatVariable', $this->data[$name]['format'])) {
foreach($labeledCols as $columnName) {
$labels[] = $this->model->get($columnName, 'label');
}
} else {
$labels = $labeledCols;
}
if (isset($this->data[$name]) && isset($this->data[$name]['delimiter'])) {
$this->delimiter = $this->data[$name]['delimiter'];
}
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 addRows($data, $modelId, $tempFilename, $filter)
{
$name = $this->getName();
if (isset($data[$name]) && isset($data[$name]['delimiter'])) {
$this->delimiter = $data[$name]['delimiter'];
}
if (!(isset($data[$name], $data[$name]['format'], $data[$name]['format'][0]) && in_array('formatAnswer', $data[$name]['format']))) {
$this->modelFilterAttributes = array('formatFunction', 'dateFormat', 'storageFormat', 'itemDisplay');
}
parent::addRows($data, $modelId, $tempFilename, $filter);
} | Add model rows to file. Can be batched
@param array $data Data submitted by export form
@param array $modelId Model Id when multiple models are passed
@param string $tempFilename The temporary filename while the file is being written
@param array $filter Filter (limit) to use | entailment |
public function addRow($row, $file)
{
$exportRow = $this->filterRow($row);
$labeledCols = $this->getLabeledColumns();
$exportRow = array_replace(array_flip($labeledCols), $exportRow);
fputcsv($file, $exportRow, $this->delimiter, '"');
} | Add a separate row to a file
@param array $row a row in the model
@param file $file The already opened file | entailment |
public function formatString($input)
{
if (is_array($input)) {
$input = join(', ', $input);
}
$output = strip_tags($input);
$output = str_replace(array("\r", "\n"), array(' ', ' '), $output);
$output = $this->filterCsvInjection($output);
return $output;
} | Formatting of strings for CSV export.
@param type $input
@return string | entailment |
public function filterAnswers(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model, array $currentNames)
{
$repeater = $model->loadRepeatable();
$table = $bridge->getTable();
$table->setRepeater($repeater);
// Filter unless option 'fullanswers' is true, can be set as get or post var.
$requestFullAnswers = \Zend_Controller_Front::getInstance()->getRequest()->getParam('fullanswers', false);
if (! $repeater->__start()) {
return $currentNames;
}
$keys = array();
if ($requestFullAnswers !== false) {
// No filtering
return $model->getItemsOrdered();
} else {
foreach ($model->getItemNames() as $name) {
$start = substr(strtolower($name),0,$this->IncludeLength);
if (in_array($start, $this->IncludeStarts)) {
$keys[$name] = $name;
}
}
}
$answers = $this->token->getRawAnswers();
// Prevent errors when no answers present
if (!empty($answers)) {
$results = array_intersect($currentNames, array_keys($keys), array_keys($answers));
} else {
$results = array_intersect($currentNames, array_keys($keys));
}
$results = $this->restoreHeaderPositions($model, $results);
if ($results) {
return $results;
}
return $this->getHeaders($model, $currentNames);
} | This function is called in addBrowseTableColumns() to filter the names displayed
by AnswerModelSnippetGeneric.
@see \Gems_Tracker_Snippets_AnswerModelSnippetGeneric
@param \MUtil_Model_Bridge_TableBridge $bridge
@param \MUtil_Model_ModelAbstract $model
@param array $currentNames The current names in use (allows chaining)
@return array Of the names of labels that should be shown | entailment |
public function getAnswerDisplaySnippets(\Gems_Tracker_Token $token)
{
$snippets = parent::getAnswerDisplaySnippets($token);
array_unshift($snippets, 'Survey_Display_FullAnswerToggleSnippet');
return $snippets;
} | Function that returns the snippets to use for this display.
@param \Gems_Tracker_Token $token The token to get the snippets for
@return array of Snippet names or nothing | entailment |
protected function createForm($options = null)
{
$form = parent::createForm($options);
$form->activateJQuery();
return $form;
} | Creates the form itself
@param array $options
@return \Gems_Form | entailment |
protected function getAutoSearchElements(array $data)
{
// Search text
$elements = parent::getAutoSearchElements($data);
$this->_addPeriodSelectors($elements, array('grco_created' => $this->_('Date sent')));
$br = \MUtil_Html::create()->br();
$elements[] = null;
$dbLookup = $this->util->getDbLookup();
$elements[] = $this->_createSelectElement(
'gto_id_track',
$this->getRespondentTrackNames(),
$this->_('(select a track)')
);
$elements[] = $this->_createSelectElement('gto_id_survey',
$this->getRespondentSurveyNames(),
$this->_('(select a survey)'));
$elements[] = $this->_createSelectElement('status',
$this->util->getTokenData()->getEveryStatus(),
$this->_('(select a status)'));
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 createModel($detailed, $action)
{
$fields = array();
// Export all
if ('export' === $action) {
$detailed = true;
}
$organizations = $this->util->getDbLookup()->getOrganizations();
$fields[] = 'gtr_track_name';
$sql = "CASE WHEN gtr_organizations LIKE '%%|%s|%%' THEN 1 ELSE 0 END";
foreach ($organizations as $orgId => $orgName) {
$fields['O'.$orgId] = new \Zend_Db_Expr(sprintf($sql, $orgId));
}
$fields['total'] = new \Zend_Db_Expr("(LENGTH(gtr_organizations) - LENGTH(REPLACE(gtr_organizations, '|', ''))-1)");
$fields[] = 'gtr_id_track';
$select = $this->db->select();
$select->from('gems__tracks', $fields);
$model = new \MUtil_Model_SelectModel($select, 'track-verview');
$model->setKeys(array('gtr_id_track'));
$model->resetOrder();
$model->set('gtr_track_name', 'label', $this->_('Track name'));
$model->set('total', 'label', $this->_('Total'));
$model->setOnTextFilter('total', array($this, 'noTextFilter'));
foreach ($organizations as $orgId => $orgName) {
$model->set('O' . $orgId, 'label', $orgName,
'tdClass', 'rightAlign',
'thClass', 'rightAlign');
$model->setOnTextFilter('O' . $orgId, array($this, 'noTextFilter'));
if ($action !== 'export') {
$model->set('O'. $orgId, 'formatFunction', array($this, 'formatCheckmark'));
}
}
// \MUtil_Model::$verbose = true;
return $model;
} | Creates a model for getModel(). Called only for each new $action.
The parameters allow you to easily adapt the model to the current action. The $detailed
parameter was added, because the most common use of action is a split between detailed
and summarized actions.
@param boolean $detailed True when the current action is not in $summarizedActions.
@param string $action The current action.
@return \MUtil_Model_ModelAbstract | entailment |
public function execute($lineNr = null, $organizationData = null)
{
$batch = $this->getBatch();
$import = $batch->getVariable('import');
if (isset($organizationData['gor_id_organization']) && $organizationData['gor_id_organization']) {
$oldId = $organizationData['gor_id_organization'];
} else {
$oldId = false;
$batch->addToCounter('import_errors');
$batch->addMessage(sprintf(
$this->_('No gor_id_organization not specified for organization at line %d.'),
$lineNr
));
}
if (isset($organizationData['gor_name']) && $organizationData['gor_name']) {
if ($oldId) {
$orgId = $this->db->fetchOne(
"SELECT gor_id_organization FROM gems__organizations WHERE gor_name = ?",
$organizationData['gor_name']
);
if ($orgId) {
$import['organizationIds'][$oldId] = $orgId;
$import['formDefaults']['gtr_organizations'][] = $orgId;
} else {
$import['organizationIds'][$oldId] = false;
}
}
} else {
$orgId = false;
$batch->addToCounter('import_errors');
$batch->addMessage(sprintf(
$this->_('No gor_name not specified for organization at line %d.'),
$lineNr
));
}
} | Should handle execution of the task, taking as much (optional) parameters as needed
The parameters should be optional and failing to provide them should be handled by
the task | entailment |
public function addContentString($wikiContent)
{
$isMainContent = isset($this->attribute[$this->separatorCount]) &&
$this->attribute[$this->separatorCount] == '$$';
$this->wikiContentArr[$this->separatorCount] .= $wikiContent;
if ($isMainContent) {
$parsedContent = $this->convertWords($wikiContent);
$this->generator->addContent($parsedContent);
} else {
$this->contents[$this->separatorCount] .= $wikiContent;
}
} | Called by the inline parser, when it found a new content.
@param string $wikiContent The original content in wiki syntax | entailment |
public function addContentGenerator($wikiContent, Generator\InlineGeneratorInterface $childGenerator)
{
$isMainContent = isset($this->attribute[$this->separatorCount]) &&
$this->attribute[$this->separatorCount] == '$$';
$this->wikiContentArr[$this->separatorCount] .= $wikiContent;
if ($isMainContent) {
$this->generator->addContent($childGenerator);
} else {
$this->contents[$this->separatorCount] .= $wikiContent;
}
} | Called by the inline parser, when it found a new content.
@param string $wikiContent The original content in wiki syntax
@param Generator\InlineGeneratorInterface $childGenerator The content already parsed (by an other Tag object), when this tag contains other tags. | entailment |
public function addSeparator($token)
{
$this->wikiContent .= $this->wikiContentArr[$this->separatorCount];
++$this->separatorCount;
if ($this->separatorCount > count($this->separators)) {
$this->currentSeparator = end($this->separators);
} else {
$this->currentSeparator = $this->separators[$this->separatorCount - 1];
}
$this->wikiContent .= $this->currentSeparator;
$this->contents[$this->separatorCount] = '';
$this->wikiContentArr[$this->separatorCount] = '';
} | Called by the inline parser, when it found a separator.
@param string $token The token found as a separator | entailment |
public function getWikiContent()
{
return $this->beginTag.$this->wikiContent.$this->wikiContentArr[$this->separatorCount].$this->endTag;
} | Returns the wiki content of the tag.
@return string The content. | entailment |
public function getContent()
{
$cntattr = count($this->attribute);
$count = ($this->separatorCount >= $cntattr) ? ($cntattr - 1) : $this->separatorCount;
for ($i = 0; $i <= $count; ++$i) {
if ($this->attribute[$i] != '$$') {
$this->generator->setAttribute($this->attribute[$i], $this->wikiContentArr[$i]);
}
}
return $this->generator;
} | Return generators that will generate final content.
@return \WikiRenderer\Generator\InlineGeneratorInterface | entailment |
public function isOtherTagAllowed()
{
if (isset($this->attribute[$this->separatorCount])) {
return ($this->attribute[$this->separatorCount] == '$$');
} else {
return false;
}
} | indicates if the tag can contains other tags.
@return bool true if the tag can contain other tags | entailment |
public function getBogusContent()
{
$generator = $this->documentGenerator->getInlineGenerator('textline');
$generator->addRawContent($this->beginTag);
$m = count($this->contents) - 1;
$s = count($this->separators);
foreach ($this->contents as $k => $v) {
if ($this->attribute[$k] == '$$') {
foreach ($this->generator->getChildGenerators() as $child) {
$generator->addContent($child);
}
} else {
$generator->addRawContent($v);
}
if ($k < $m) {
if ($k < $s) {
$generator->addRawContent($this->separators[$k]);
} else {
$generator->addRawContent(end($this->separators));
}
}
}
return $generator;
} | Returns the generated content of the tag.
@return string the content | entailment |
protected function getAutoSearchElements(array $data)
{
$elements = parent::getAutoSearchElements($data);
if ($elements) {
$optionsG = $this->util->getDbLookup()->getGroups();
$elementG = $this->_createSelectElement('gsf_id_primary_group', $optionsG, $this->_('(all functions)'));
$elements[] = $elementG;
$user = $this->loader->getCurrentUser();
$optionsO = $user->getAllowedOrganizations();
if (count($optionsO) > 1) {
$elementO = $this->_createSelectElement('gsf_id_organization', $optionsO, $this->_('(all organizations)'));
$elements[] = $elementO;
}
$optionsA = $this->model->get('gsf_active', 'multiOptions');
$elementA = $this->_createSelectElement('gsf_active', $optionsA, $this->_('(both)'));
$elementA->setLabel($this->model->get('gsf_active', 'label'));
$elements[] = $elementA;
$optionsT = $this->model->get('has_2factor', 'multiOptions');;
$elementT = $this->_createSelectElement('has_2factor', $optionsT, $this->_('(all)'));
$elementT->setLabel($this->model->get('has_2factor', 'label'));
$elements[] = $elementT;
}
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 applyBrowseSettings()
{
$formatDate = $this->util->getTranslated()->formatDate;
$this->resetOrder();
$this->setKeys(array(
\Gems_Model::RESPONDENT_TRACK => 'gr2t_id_respondent_track',
\MUtil_Model::REQUEST_ID1 => 'gr2o_patient_nr',
\MUtil_Model::REQUEST_ID2 => 'gr2o_id_organization',
));
$this->set('gtr_track_name', 'label', $this->_('Track'));
$this->set('gr2t_track_info', 'label', $this->_('Description'),
'description', $this->_('Enter the particulars concerning the assignment to this respondent.'));
$this->set('assigned_by', 'label', $this->_('Assigned by'));
$this->set('gr2t_start_date', 'label', $this->_('Start'),
'dateFormat', 'dd-MM-yyyy',
'formatFunction', $formatDate,
'default', new \Zend_Date());
$this->set('gr2t_end_date', 'label', $this->_('Ending on'),
'dateFormat', 'dd-MM-yyyy',
'formatFunction', $formatDate);
$this->set('gr2t_reception_code');
$this->set('gr2t_comment', 'label', $this->_('Comment'));
$this->addColumn('CONCAT(gr2t_completed, \'' . $this->_(' of ') . '\', gr2t_count)', 'progress');
$this->set('progress', 'label', $this->_('Progress'));
return $this;
} | Set those settings needed for the browse display
@return \Gems_Model_RespondentTrackModel | entailment |
public function applyDetailSettings(\Gems_Tracker_Engine_TrackEngineInterface $trackEngine, $edit = false)
{
$this->resetOrder();
$translated = $this->util->getTranslated();
$formatDate = $this->util->getTranslated()->formatDate;
$this->set('gr2o_patient_nr', 'label', $this->_('Respondent number'));
$this->set('respondent_name', 'label', $this->_('Respondent name'));
$this->set('gtr_track_name', 'label', $this->_('Track'));
$this->set('gr2t_mailable',
'label', $this->_('May be mailed'),
'elementClass', 'radio',
'separator', ' ',
'multiOptions', array(
'1' => $this->_('Yes'),
'0' => $this->_('No'),
)
);
$this->set('assigned_by', 'label', $this->_('Assigned by'));
$this->set('gr2t_start_date', 'label', $this->_('Start'),
'dateFormat', 'dd-MM-yyyy',
'formatFunction', $formatDate);
// Integrate fields
$trackEngine->addFieldsToModel($this, $edit);
$this->set('gr2t_end_date_manual', 'label', $this->_('Set ending on'),
'description', $this->_('Manually set dates are fixed an will never be (re)calculated.'),
'elementClass', 'Radio',
'multiOptions', $translated->getDateCalculationOptions(),
'separator', ' '
);
$this->set('gr2t_end_date', 'label', $this->_('Ending on'),
'dateFormat', 'dd-MM-yyyy',
'formatFunction', $formatDate);
$this->set('gr2t_track_info', 'label', $this->_('Description'));
$this->set('gr2t_comment', 'label', $this->_('Comment'));
$this->set('grc_description', 'label', $this->_('Reception code'),
'elementClass', 'Exhibitor');
$this->refreshGroupSettings();
return $this;
} | Set those settings needed for the detailed display
@param \Gems_Tracker_Engine_TrackEngineInterface $trackEngine
@param boolean $edit When true the fields are added in edit mode
@return \Gems_Model_RespondentTrackModel | entailment |
public function applyEditSettings(\Gems_Tracker_Engine_TrackEngineInterface $trackEngine)
{
$this->applyDetailSettings($trackEngine, true);
$this->addEditTracking();
$this->set('gr2o_patient_nr', 'elementClass', 'Exhibitor');
$this->set('respondent_name', 'elementClass', 'Exhibitor');
$this->set('gtr_track_name', 'elementClass', 'Exhibitor');
// Fields set in details
$this->set('gr2t_track_info', 'elementClass', 'None');
$this->set('assigned_by', 'elementClass', 'None');
$this->set('gr2t_reception_code', 'elementClass', 'None');
$this->set('gr2t_start_date', 'elementClass', 'Date',
'default', new \Zend_Date(),
'required', true,
'size', 30
);
$this->set('gr2t_end_date', 'elementClass', 'Date',
'default', null,
'size', 30
);
$this->set('gr2t_comment', 'elementClass', 'Textarea',
'cols', 80,
'rows', 5
);
return $this;
} | Set those values needed for editing
@param \Gems_Tracker_Engine_TrackEngineInterface $trackEngine
@return \Gems_Model_RespondentTrackModel | entailment |
public function applyParameters(array $parameters, $includeNumericFilters = false)
{
if ($parameters) {
// Altkey
if (isset($parameters[\Gems_Model::RESPONDENT_TRACK])) {
$id = $parameters[\Gems_Model::RESPONDENT_TRACK];
unset($parameters[\Gems_Model::RESPONDENT_TRACK]);
$parameters['gr2t_id_respondent_track'] = $id;
}
if (isset($parameters[\Gems_Model::TRACK_ID])) {
$id = $parameters[\Gems_Model::TRACK_ID];
unset($parameters[\Gems_Model::TRACK_ID]);
$parameters['gtr_id_track'] = $id;
}
return parent::applyParameters($parameters, $includeNumericFilters);
}
return array();
} | Stores the fields that can be used for sorting or filtering in the
sort / filter objects attached to this model.
@param array $parameters
@param boolean $includeNumericFilters When true numeric filter keys (0, 1, 2...) are added to the filter as well
@return array The $parameters minus the sort & textsearch keys | entailment |
public function loadNew($count = null, array $filter = null)
{
$values = array();
// Get the defaults
foreach ($this->getItemNames() as $name) {
$value = $this->get($name, 'default');
// Load 'Value' if set
if (null === $value) {
$value = $this->get($name, 'value');
}
$values[$name] = $value;
}
// Create the extra values for the result
if ($filter) {
$db = $this->getAdapter();
if (isset($filter['gr2o_patient_nr'], $filter['gr2o_id_organization'])) {
$sql = "SELECT *,
CONCAT(
COALESCE(CONCAT(grs_last_name, ', '), '-, '),
COALESCE(CONCAT(grs_first_name, ' '), ''),
COALESCE(grs_surname_prefix, '')) AS respondent_name
FROM gems__respondents INNER JOIN gems__respondent2org ON grs_id_user = gr2o_id_user
WHERE gr2o_patient_nr = ? AND gr2o_id_organization = ?";
$values = $db->fetchRow($sql, array($filter['gr2o_patient_nr'], $filter['gr2o_id_organization'])) + $values;
$values['gr2t_id_user'] = $values['gr2o_id_user'];
$values['gr2t_id_organization'] = $values['gr2o_id_organization'];
}
if (isset($filter['gtr_id_track'])) {
$sql = 'SELECT * FROM gems__tracks WHERE gtr_id_track = ?';
$values = $db->fetchRow($sql, $filter['gtr_id_track']) + $values;
$values['gr2t_id_track'] = $values['gtr_id_track'];
$values['gr2t_count'] = $values['gtr_survey_rounds'];
}
}
// \MUtil_Echo::track($filter, $values);
$rows = $this->processAfterLoad(array($values), true);
$row = reset($rows);
// Return only a single row when no count is specified
if (null === $count) {
return $row;
} else {
return array_fill(0, $count, $row);
}
} | Creates new items - in memory only. Extended to load information from linked table using $filter().
When $filter contains the keys gr2o_patient_nr and gr2o_id_organization the corresponding respondent
information is loaded into the new item.
When $filter contains the key gtr_id_track the corresponding track information is loaded.
The $filter values are also propagated to the corresponding key values in the new item.
@param int $count When null a single new item is return, otherwise a nested array with $count new items
@param array $filter Allowed key values: gr2o_patient_nr, gr2o_id_organization and gtr_id_track
@return array Nested when $count is not null, otherwise just a simple array | entailment |
public function save(array $newValues, array $filter = null)
{
$keys = $this->getKeys();
// This is the only key to save on, no matter
// the keys used to initiate the model.
$this->setKeys($this->_getKeysFor('gems__respondent2track'));
// Change the end date until the end of the day
if (isset($newValues['gr2t_end_date']) && $newValues['gr2t_end_date']) {
$displayFormat = $this->get('gr2t_end_date', 'dateFormat');
if ( ! $displayFormat) {
$displayFormat = \MUtil_Model_Bridge_FormBridge::getFixedOption('date', 'dateFormat');
}
// Of course do not do so when we got a time format
if (! \MUtil_Date_Format::getTimeFormat($displayFormat)) {
$newValues['gr2t_end_date'] = new \MUtil_Date($newValues['gr2t_end_date'], $displayFormat);
$newValues['gr2t_end_date']->setTimeToDayEnd();
}
}
$newValues = parent::save($newValues, $filter);
$this->setKeys($keys);
return $newValues;
} | Save a single model item.
@param array $newValues The values to store for a single model item.
@param array $filter If the filter contains old key values these are used
to decide on update versus insert.
@return array The values as they are after saving (they may change). | entailment |
public function getPanel()
{
$panel = '';
$linebreak = $this->getLinebreak();
# Support for APC
if (function_exists('apc_sma_info') && ini_get('apc.enabled')) {
$mem = apc_sma_info();
$memSize = $mem['num_seg'] * $mem['seg_size'];
$memAvail = $mem['avail_mem'];
$memUsed = $memSize - $memAvail;
$cache = apc_cache_info();
if ($cache['mem_size'] > 0) {
$panel .= '<h4>APC '.phpversion('apc').' Enabled</h4>';
$panel .= round($memAvail/1024/1024, 1) . 'M available, '
. round($memUsed/1024/1024, 1) . 'M used' . $linebreak
. $cache['num_entries'].' Files cached ('
. round($cache['mem_size']/1024/1024, 1) . 'M)' . $linebreak
. $cache['num_hits'] . ' Hits ('
. round($cache['num_hits'] * 100 / ($cache['num_hits'] + $cache['num_misses']), 1) . '%)'
;//. $linebreak
//. $cache['expunges'] . ' Expunges (cache full count)';
}
}
if (function_exists('opcache_get_configuration')) {
$opconfig = opcache_get_configuration();
if ($opconfig['directives']['opcache.enable']) {
$opstatus = opcache_get_status();
$cache = $opstatus['opcache_statistics'];
$panel .= '<h4>'.$opconfig['version']['opcache_product_name'].' '.$opconfig['version']['version'].' Enabled</h4>';
$panel .= round($opstatus['memory_usage']['used_memory']/1024/1024, 1) . 'M used, '
. round($opstatus['memory_usage']['free_memory']/1024/1024, 1) . 'M free ('
. round($opstatus['memory_usage']['current_wasted_percentage'], 1) .'% wasted)' . $linebreak
. $cache['num_cached_scripts'].' Files cached' . $linebreak
. $cache['hits'] . ' Hits ('
. round($cache['opcache_hit_rate'], 1) . '%)';
}
}
foreach ($this->_cacheBackends as $name => $backend) {
$fillingPercentage = $backend->getFillingPercentage();
$ids = $backend->getIds();
# Print full class name, backends might be custom
$panel .= '<h4>Cache '.$name.' ('.get_class($backend).')</h4>';
$panel .= count($ids).' Entr'.(count($ids)>1?'ies':'y').''.$linebreak
. 'Filling Percentage: '.$backend->getFillingPercentage().'%'.$linebreak;
$cacheSize = 0;
foreach ($ids as $id) {
# Calculate valid cache size
$memPre = memory_get_usage();
if ($cached = $backend->load($id)) {
$memPost = memory_get_usage();
$cacheSize += $memPost - $memPre;
unset($cached);
}
}
$panel .= 'Valid Cache Size: ' . round($cacheSize/1024, 1) . 'K';
}
return $panel;
} | Gets content panel for the Debugbar
@return string | entailment |
protected function _addRelation($select)
{
// now add a left join with the round table so we have all tokens, also the ones without rounds
if (!is_null($this->_gemsData['gto_id_relation'])) {
$select->forWhere('gto_id_relation = ?', $this->_gemsData['gto_id_relation']);
} else {
$select->forWhere('gto_id_relation IS NULL');
}
} | Add relation to the select statement
@param Gems_Tracker_Token_TokenSelect $select | entailment |
protected function _ensureRespondentData()
{
if (! isset($this->_gemsData['grs_id_user'], $this->_gemsData['gr2o_id_user'], $this->_gemsData['gco_code'])) {
$sql = "SELECT *
FROM gems__respondents INNER JOIN
gems__respondent2org ON grs_id_user = gr2o_id_user INNER JOIN
gems__consents ON gr2o_consent = gco_description
WHERE gr2o_id_user = ? AND gr2o_id_organization = ? LIMIT 1";
$respId = $this->_gemsData['gto_id_respondent'];
$orgId = $this->_gemsData['gto_id_organization'];
// \MUtil_Echo::track($this->_gemsData);
if ($row = $this->db->fetchRow($sql, array($respId, $orgId))) {
$this->_gemsData = $this->_gemsData + $row;
} else {
$token = $this->_tokenId;
throw new \Gems_Exception("Respondent data missing for token $token.");
}
}
} | Makes sure the respondent data is part of the $this->_gemsData | entailment |
protected function _getResultFieldLength()
{
if (null !== $this->resultFieldLength) {
return $this->resultFieldLength;
}
if (null !== self::$staticResultFieldLength) {
$this->resultFieldLength = self::$staticResultFieldLength;
return $this->resultFieldLength;
}
$model = new \MUtil_Model_TableModel('gems__tokens');
self::$staticResultFieldLength = $model->get('gto_result', 'maxlength');
$this->resultFieldLength = self::$staticResultFieldLength;
return $this->resultFieldLength;
} | The maximum length of the result field
@return int | entailment |
protected function _updateToken(array $values, $userId)
{
if ($this->tracker->filterChangesOnly($this->_gemsData, $values)) {
if (\Gems_Tracker::$verbose) {
$echo = '';
foreach ($values as $key => $val) {
$echo .= $key . ': ' . $this->_gemsData[$key] . ' => ' . $val . "\n";
}
\MUtil_Echo::r($echo, 'Updated values for ' . $this->_tokenId);
}
if (! isset($values['gto_changed'])) {
$values['gto_changed'] = new \MUtil_Db_Expr_CurrentTimestamp();
}
if (! isset($values['gto_changed_by'])) {
$values['gto_changed_by'] = $userId;
}
// Update values in this object
$this->_gemsData = $values + (array) $this->_gemsData;
// return 1;
return $this->db->update('gems__tokens', $values, array('gto_id_token = ?' => $this->_tokenId));
} else {
return 0;
}
} | Update the token, both in the database and in memory.
@param array $values The values that this token should be set to
@param int $userId The current user
@return int 1 if data changed, 0 otherwise | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.