sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function hasHtmlOutput()
{
$sql = "SELECT COALESCE(gto_round_description, '') AS label,
SUM(
CASE
WHEN gto_completion_time IS NOT NULL
THEN 1
ELSE 0
END
) AS completed,
SUM(
CASE
WHEN gto_completion_time IS NULL AND
gto_valid_from < CURRENT_TIMESTAMP AND
(gto_valid_until > CURRENT_TIMESTAMP OR gto_valid_until IS NULL)
THEN 1
ELSE 0
END
) AS waiting,
COUNT(*) AS any
FROM gems__tokens INNER JOIN
gems__surveys ON gto_id_survey = gsu_id_survey INNER JOIN
gems__rounds ON gto_id_round = gro_id_round INNER JOIN
gems__respondent2track ON gto_id_respondent_track = gr2t_id_respondent_track INNER JOIN
gems__reception_codes AS rcto ON gto_reception_code = rcto.grc_id_reception_code INNER JOIN
gems__reception_codes AS rctr ON gr2t_reception_code = rctr.grc_id_reception_code
WHERE gto_id_respondent = ? AND
gro_active = 1 AND
gsu_active = 1 AND
rcto.grc_success = 1 AND
rctr.grc_success = 1
GROUP BY COALESCE(gto_round_description, '')
ORDER BY MIN(COALESCE(gto_round_order, 100000)), gto_round_description";
// \MUtil_Echo::track($this->respondentId);
$tabLabels = $this->db->fetchAll($sql, $this->respondentId);
if ($tabLabels) {
$default = null;
$filters = array();
$noOpen = true;
$tabs = array();
foreach ($tabLabels as $row) {
$name = '_' . \MUtil_Form::normalizeName($row['label']);
$label = $row['label'] ? $row['label'] : $this->_('empty');
if ($row['waiting']) {
$label = sprintf($this->_('%s (%d open)'), $label, $row['waiting']);
} else {
$label = $label;
}
if (! $row['label']) {
$label = \MUtil_Html::create('em', $label);
}
$filters[$name] = $row['label'];
$tabs[$name] = $label;
if (in_array($row['label'], $this->neverDefaults)) {
// Skip default setting
continue;
}
if ($noOpen && ($row['completed'] > 0)) {
$default = $name;
}
if ($row['waiting'] > 0) {
$default = $name;
$noOpen = false;
}
}
if (null === $default) {
reset($filters);
$default = key($filters);
}
// Set the model
$reqFilter = $this->request->getParam($this->getParameterKey());
if (! isset($filters[$reqFilter])) {
$reqFilter = $default;
}
if ('' === $filters[$reqFilter]) {
$this->model->setMeta('tab_filter', array("(gto_round_description IS NULL OR gto_round_description = '')"));
} else {
$this->model->setMeta('tab_filter', array('gto_round_description' => $filters[$reqFilter]));
}
// \MUtil_Echo::track($tabs, $reqFilter, $default, $tabLabels);
$this->defaultTab = $default;
$this->_tabs = $tabs;
}
return $this->_tabs && parent::hasHtmlOutput();
} | The place to check if the data set in the snippet is valid
to generate the snippet.
When invalid data should result in an error, you can throw it
here but you can also perform the check in the
checkRegistryRequestsAnswers() function from the
{@see \MUtil_Registry_TargetInterface}.
@return boolean | entailment |
public function getSubmitButton()
{
$element = $this->getElement($this->_submitFieldName);
if (! $element) {
// Submit knop
$options = array('class' => 'button');
$element = $this->createElement('submit', $this->_submitFieldName, $options);
$element->setLabel($this->getSubmitButtonLabel());
$this->addElement($element);
}
return $element;
} | Returns/sets a submit button.
@return \Zend_Form_Element_Submit | entailment |
protected function getCommands($filename, $type)
{
$commands = $this->config->get('availableCommands');
if (!$type || !isset($commands[$type])) {
return array();
}
$command = array();
foreach ((array)$this->config->get('enabledCommands') as $commandType) {
if (isset($commands[$type][$commandType])) {
$command[] = sprintf(
$commands[$type][$commandType],
rtrim($this->config->get('binDirectory'), '/'),
escapeshellarg($filename),
$this->config->get('optimisingQuality')
);
}
}
return $command;
} | Gets all enabled commands for the file and type of image
@param $filename
@param $type
@return array | entailment |
public function execute($row = null)
{
if ($row) {
if ((! isset($row['grs_id_user'])) &&
isset($row['grs_ssn']) &&
$this->targetModel instanceof \Gems_Model_RespondentModel &&
$this->targetModel->hashSsn !== \Gems_Model_RespondentModel::SSN_HIDE) {
if (\Gems_Model_RespondentModel::SSN_HASH === $this->targetModel->hashSsn) {
$search = $this->targetModel->saveSSN($row['grs_ssn']);
} else {
$search = $row['grs_ssn'];
}
$sql = 'SELECT grs_id_user FROM gems__respondents WHERE grs_ssn = ?';
$id = $this->db->fetchOne($sql, $search);
// Check for change in patient ID
if ($id) {
if (isset($row['gr2o_id_organization']) &&
$this->targetModel instanceof \MUtil_Model_DatabaseModelAbstract) {
$sql = 'SELECT gr2o_patient_nr
FROM gems__respondent2org
WHERE gr2o_id_user = ? AND gr2o_id_organization = ?';
$patientId = $this->db->fetchOne($sql, array($id, $row['gr2o_id_organization']));
if ($patientId) {
// Change the patient number
$copyId = $this->targetModel->getKeyCopyName('gr2o_patient_nr');
$row[$copyId] = $patientId;
}
}
$row['grs_id_user'] = $id;
$row['gr2o_id_user'] = $id;
}
}
parent::execute($row);
}
} | 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 $row Row to save | entailment |
public function execute($patchLevel = null)
{
//Update the patchlevel only when we have executed at least one patch
$batch = $this->getBatch();
if ($batch->getCounter('executed')) {
$this->db->query(
'INSERT IGNORE INTO gems__patch_levels (gpl_level, gpl_created) VALUES (?, CURRENT_TIMESTAMP)',
$patchLevel
);
}
} | 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 int $patchLevel Only execute patches for this patchlevel | entailment |
public function getPresetTargetData()
{
$targetData = parent::getPresetTargetData();
if ($this->token) {
$targetData['track'] = $this->token->getTrackName();
$targetData['round'] = $this->token->getRoundDescription();
$targetData['survey'] = $this->token->getSurvey()->getName();
$targetData['last_contact'] = $this->token->getMailSentDate();
}
return $targetData;
} | Get specific data set in the mailer
@return Array | entailment |
protected function logRespondentCommunication()
{
$currentUserId = $this->loader->getCurrentUser()->getUserId();
$changeDate = new \MUtil_Db_Expr_CurrentTimestamp();
$logData['grco_id_to'] = $this->respondent->getId();
if (! is_int($this->by)) {
$this->by = $currentUserId;
}
$logData['grco_id_by'] = $this->by;
$logData['grco_organization'] = $this->organizationId;
$logData['grco_id_token'] = $this->token->getTokenId();
$logData['grco_method'] = 'email';
$logData['grco_topic'] = substr($this->applyFields($this->subject), 0, 120);
$to = array();
foreach($this->to as $name=> $address) {
$to[] = $name . '<'.$address.'>';
}
$logData['grco_address'] = substr(join(',', $to), 0, 120);
$logData['grco_sender'] = substr($this->from, 0, 120);
$logData['grco_id_message'] = $this->templateId ? $this->templateId : null;
$logData['grco_changed'] = $changeDate;
$logData['grco_changed_by'] = $this->by;
$logData['grco_created'] = $changeDate;
$logData['grco_created_by'] = $this->by;
$this->db->insert('gems__log_respondent_communications', $logData);
} | Log the communication for the respondent. | entailment |
public function tokenMailFields()
{
if ($this->token) {
$locale = $this->respondent->getLanguage();
$survey = $this->token->getSurvey();
// Count todo
$tSelect = $this->loader->getTracker()->getTokenSelect(array(
'all' => 'COUNT(*)',
'track' => $this->db->quoteInto(
'SUM(CASE WHEN gto_id_respondent_track = ? THEN 1 ELSE 0 END)',
$this->token->getRespondentTrackId())
));
$tSelect->andSurveys(array())
->forRespondent($this->token->getRespondentId(), $this->organizationId)
->forGroupId($survey->getGroupId())
->onlyValid();
$todo = $tSelect->fetchRow();
// Set the basic fields
$result['round'] = $this->token->getRoundDescription();
$organizationLoginUrl = $this->organization->getLoginUrl();
$result['site_ask_url'] = $organizationLoginUrl . '/ask/';
// Url's
$url = $organizationLoginUrl . '/ask/forward/' . \MUtil_Model::REQUEST_ID . '/';
$url .= $this->token->getTokenId();
$urlInput = $result['site_ask_url'] . 'index/' . \MUtil_Model::REQUEST_ID . '/' . $this->token->getTokenId();
$result['survey'] = $survey->getName();
$result['todo_all'] = sprintf($this->translate->plural('%d survey', '%d surveys', $todo['all'], $locale), $todo['all']);
$result['todo_all_count'] = $todo['all'];
$result['todo_track'] = sprintf($this->translate->plural('%d survey', '%d surveys', $todo['track'], $locale), $todo['track']);
$result['todo_track_count'] = $todo['track'];
$result['token'] = strtoupper($this->token->getTokenId());
$result['token_from'] = \MUtil_Date::format($this->token->getValidFrom(), \Zend_Date::DATE_LONG, 'yyyy-MM-dd', $locale);
$result['token_link'] = '[url=' . $url . ']' . $survey->getName() . '[/url]';
$result['token_until'] = \MUtil_Date::format($this->token->getValidUntil(), \Zend_Date::DATE_LONG, 'yyyy-MM-dd', $locale);
$result['token_url'] = $url;
$result['token_url_input'] = $urlInput;
$result['track'] = $this->token->getTrackName();
// Add the code fields
$codes = $this->token->getRespondentTrack()->getCodeFields();
foreach ($codes as $code => $data) {
$key = 'track.' . $code;
if (is_array($data)) {
$data = implode(' ', $data);
}
$result[$key] = $data;
}
if ($this->token->hasRelation()) {
$allFields = $this->getMailFields(false);
// Set about to patient name
$result['relation_about'] = $allFields['name'];
$result['relation_about_first_name'] = $allFields['first_name'];
$result['relation_about_full_name'] = $allFields['full_name'];
$result['relation_about_greeting'] = $allFields['greeting'];
$result['relation_about_last_name'] = $allFields['last_name'];
$result['relation_field_name'] = $this->token->getRelationFieldName();
if ($relation = $this->token->getRelation()) {
// Now update all respondent fields to be of the relation
$result['name'] = $relation->getName();
$result['first_name'] = $relation->getFirstName();
$result['last_name'] = $relation->getLastName();
$result['full_name'] = $relation->getHello($locale);
$result['greeting'] = $relation->getGreeting($locale);
$result['to'] = $relation->getEmail();
} else {
$result['name'] = $this->translate->getAdapter()->_('Undefined relation');
$result['first_name'] = '';
$result['last_name'] = '';
$result['full_name'] = '';
$result['greeting'] = '';
$result['to'] = '';
}
} else {
$result['relation_about'] = $this->translate->getAdapter()->_('yourself', $this->token->getRespondentLanguage());
$result['relation_about_first_name'] = '';
$result['relation_about_full_name'] = '';
$result['relation_about_greeting'] = '';
$result['relation_about_last_name'] = '';
$result['relation_field_name'] = '';
}
} else {
$result['round'] = '';
$result['site_ask_url'] = '';
$result['survey'] = '';
$result['todo_all'] = '';
$result['todo_all_count'] = '';
$result['todo_track'] = '';
$result['todo_track_count'] = '';
$result['token'] = '';
$result['token_from'] = '';
$result['token_link'] = '';
$result['token_until'] = '';
$result['token_url'] = '';
$result['token_url_input'] = '';
$result['track'] = '';
$result['relation_about'] = $this->translate->getAdapter()->_('yourself');
$result['relation_about_first_name'] = '';
$result['relation_about_full_name'] = '';
$result['relation_about_greeting'] = '';
$result['relation_about_last_name'] = '';
$result['relation_field_name'] = '';
}
return $result;
} | Returns an array of {field_names} => values for this token for
use in an e-mail tamplate.
@param array $tokenData
@return array | entailment |
public function updateToken($tokenId=false)
{
if (!$tokenId) {
$tokenId = $this->token->getTokenId();
}
$tokenData['gto_mail_sent_num'] = new \Zend_Db_Expr('gto_mail_sent_num + 1');
$tokenData['gto_mail_sent_date'] = \MUtil_Date::format(new \Zend_Date(), 'yyyy-MM-dd');
$this->db->update('gems__tokens', $tokenData, $this->db->quoteInto('gto_id_token = ?', $tokenId));
} | Update the token data when a Mail has been sent.
@param integer $tokenId TokenId to update. If none is supplied, use the current token | entailment |
public function barcodeAction()
{
$code = $this->getRequest()->getParam('code', 'empty');
\Zend_Layout::getMvcInstance()->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$barcodeOptions = array('text' => $code);
$rendererOptions = array();
$barcode = \Zend_Barcode::render('code128', 'image', $barcodeOptions, $rendererOptions);
$barcode->render();
} | This can be used to generate barcodes, use the action
/openrosa/barcode/code/<tokenid>
example:
/openrosa/barocde/code/22pq-grkq
The image will be a png | entailment |
public function downloadAction()
{
$filename = $this->getRequest()->getParam('form');
$filename = basename($filename); //Strip paths
$file = $this->formDir . $filename;
if (!empty($filename) && file_exists($file)) {
$this->getHelper('layout')->disableLayout();
$this->getResponse()->setHeader('Content-Type', 'application/xml; charset=utf-8');
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
} else {
$this->getResponse()->setHttpResponseCode(404);
$this->html->div("form $filename not found");
}
} | This action should serve the right form to the downloading application
it should also handle expiration / availability of forms | entailment |
public function formlistAction()
{
//first create the baseurl of the form http(s)://projecturl/openrosa/download/form/
$helper = new \Zend_View_Helper_ServerUrl();
$baseUrl = $helper->serverUrl() . \Zend_Controller_Front::getInstance()->getBaseUrl() . '/openrosa/download/form/';
//As we don't have forms defined yet, we pass in an array, but ofcourse this should be dynamic
//and come from a helper method
$model = $this->getModel();
$rawForms = $model->load(array('gof_form_active'=>1));
foreach($rawForms as $form) {
$forms[] = array(
'formID' => $form['gof_form_id'],
'name' => $form['gof_form_title'],
'version' => $form['gof_form_version'],
'hash' => md5($form['gof_form_id'].$form['gof_form_version']),
'downloadUrl' => $baseUrl . $form['gof_form_xml']
);
}
//Now make it a rosaresponse
$this->makeRosaResponse();
$xml = $this->getXml('xforms xmlns="http://openrosa.org/xforms/xformsList"');
foreach ($forms as $form) {
$xform = $xml->addChild('xform');
foreach ($form as $key => $value) {
$xform->addChild($key, $value);
}
}
echo $xml->asXML();
} | Accessible via formList as defined in the menu and standard for openRosa clients | entailment |
private function processReceivedForm($answerXmlFile)
{
//Log what we received
$log = \Gems_Log::getLogger();
//$log->log(print_r($xmlFile, true), \Zend_Log::ERR);
$xml = simplexml_load_file($answerXmlFile);
$formId = $xml->attributes()->id;
$formVersion = $xml->attributes()->version;
//Lookup what form belongs to this formId and then save
$model = $this->getModel();
$filter = array(
//'gof_form_active' => 1,
'gof_form_id' => $formId,
'gof_form_version' => $formVersion,
);
if ($formData = $model->loadFirst($filter)) {
$this->openrosaFormID = $formData['gof_id'];
// Safeguard for when the form definition no longer exists
try {
$form = new OpenRosa_Tracker_Source_OpenRosa_Form($this->formDir . $formData['gof_form_xml']);
$answers = $form->saveAnswer($answerXmlFile);
return $answers['orf_id'];
} catch (\Exception $exc) {
return false;
}
} else {
return false;
}
} | Handles receiving and storing the data from a form, files are stored on actual upload process
this only handles storing form data and can be used for resubmission too.
@param type $xmlFile
@return string ResultID or false on failure | entailment |
public function preDispatch()
{
parent::preDispatch();
$action = strtolower($this->getRequest()->getActionName());
if (in_array($action, $this->authActions)) {
$auth = \Zend_Auth::getInstance();
$this->auth = $auth;
if (!$auth->hasIdentity()) {
$config = array(
'accept_schemes' => 'basic',
'realm' => GEMS_PROJECT_NAME,
'nonce_timeout' => 3600,
);
$adapter = new \Zend_Auth_Adapter_Http($config);
$basicResolver = new \Zend_Auth_Adapter_Http_Resolver_File();
//This is a basic resolver, use username:realm:password
//@@TODO: move to a better db stored authentication system
$basicResolver->setFile(GEMS_ROOT_DIR . '/var/settings/pwd.txt');
$adapter->setBasicResolver($basicResolver);
$request = $this->getRequest();
$response = $this->getResponse();
assert($request instanceof \Zend_Controller_Request_Http);
assert($response instanceof \Zend_Controller_Response_Http);
$adapter->setRequest($request);
$adapter->setResponse($response);
$result = $auth->authenticate($adapter);
if (!$result->isValid()) {
$adapter->getResponse()->sendResponse();
print 'Unauthorized';
exit;
}
}
}
} | Implements HTTP Basic auth | entailment |
public function submissionAction()
{
$this->makeRosaResponse();
if ($this->getRequest()->isHead()) {
$this->getResponse()->setHttpResponseCode(204);
} elseif ($this->getRequest()->isPost()) {
//Post
// We get $_FILES variable holding the formresults as xml and all possible
// attachments like photo's and video's
$upload = new \Zend_File_Transfer_Adapter_Http();
// We should really add some validators here see http://framework.zend.com/manual/en/zend.file.transfer.validators.html
// Returns all known internal file information
$files = $upload->getFileInfo();
foreach ($files as $file => $info) {
// file uploaded ?
if (!$upload->isUploaded($file)) {
print "Why haven't you uploaded the file ?";
continue;
}
// validators are ok ?
if (!$upload->isValid($file)) {
print "Sorry but $file is not what we wanted";
continue;
}
}
//Dit moet een filter worden (rename filter) http://framework.zend.com/manual/en/zend.file.transfer.filters.html
$upload->setDestination($this->responseDir);
//Hier moeten we denk ik eerst de xml_submission_file uitlezen, en daar
//iets mee doen
if ($upload->receive('xml_submission_file')) {
$xmlFile = $upload->getFileInfo('xml_submission_file');
$answerXmlFile = $xmlFile['xml_submission_file']['tmp_name'];
$resultId = $this->processReceivedForm($answerXmlFile);
if ($resultId === false) {
//form not accepted!
foreach ($xml->children() as $child) {
$log->log($child->getName() . ' -> ' . $child, \Zend_Log::ERR);
}
} else {
//$log->log(print_r($files, true), \Zend_Log::ERR);
//$log->log($deviceId, \Zend_Log::ERR);
\MUtil_File::ensureDir($this->responseDir . 'forms/' . (int) $this->openrosaFormID . '/');
$upload->setDestination($this->responseDir . 'forms/' . (int) $this->openrosaFormID . '/');
foreach ($upload->getFileInfo() as $file => $info) {
if ($info['received'] != 1) {
//Rename to responseid_filename
//@@TODO: move to form subdir, for better separation
$upload->addFilter('Rename', $resultId . '_' . $info['name'], $file);
}
}
//Now receive the other files
if (!$upload->receive()) {
$messages = $upload->getMessages();
echo implode("\n", $messages);
}
$this->getResponse()->setHttpResponseCode(201); //Form received ok
}
}
}
} | Accepts the form
Takes two roundtrips:
- first we get a HEAD request that should be answerd with
responsecode 204
- then we get a post that only submits $_FILES (so actual $_POST will be empty)
this will be an xml file for the actuel response and optionally images and/or video
proper responses are
201 received and stored
202 received ok, not stored | entailment |
protected function afterLoad()
{
if ($this->_data &&
$this->db instanceof \Zend_Db_Adapter_Abstract) {
$this->_fieldList2 = $this->loadFieldList($this->_data['gaf_filter_text1'], $this->_data['gaf_filter_text2']);
$this->_fieldList4 = $this->loadFieldList($this->_data['gaf_filter_text3'], $this->_data['gaf_filter_text4']);
}
} | Override this function when you need to perform any actions when the data is loaded.
Test for the availability of variables as these objects can be loaded data first after
deserialization or registry variables first after normal instantiation.
That is why this function called both at the end of afterRegistry() and after exchangeArray(),
but NOT after unserialize().
After this the object should be ready for serialization | entailment |
public function getAppointmentFieldValue(\Gems_Agenda_Appointment $appointment, $field)
{
switch ($field) {
case 'gap_id_organization':
return $appointment->getOrganizationId();
case 'gap_source':
return $appointment->getSource();
case 'gap_id_attended_by':
return $appointment->getAttendedById();
case 'gap_id_referred_by':
return $appointment->getReferredById();
case 'gap_id_activity':
return $appointment->getActivityId();
case 'gap_id_procedure':
return $appointment->getProcedureId();
case 'gap_id_location':
return $appointment->getLocationId();
case 'gap_subject':
return $appointment->getSubject();
}
} | Get the field value from an appointment object
@param \Gems_Agenda_Appointment $appointment
@param string $field
@return mixed | entailment |
public function getSqlAppointmentsWhere()
{
if ($this->_data['gaf_filter_text1'] && $this->_data['gaf_filter_text2']) {
$wheres[] = $this->getSqlWhereSingle($this->_data['gaf_filter_text1'], $this->_data['gaf_filter_text2'], $this->_fieldList2);
}
if ($this->_data['gaf_filter_text3'] && $this->_data['gaf_filter_text4']) {
$wheres[] = $this->getSqlWhereSingle($this->_data['gaf_filter_text3'], $this->_data['gaf_filter_text4'], $this->_fieldList4);
}
foreach ($wheres as $key => $where) {
if ($where == parent::NO_MATCH_SQL) {
return parent::NO_MATCH_SQL;
} elseif ($where == parent::MATCH_ALL_SQL) {
unset($wheres[$key]);
}
}
if ($wheres) {
return '(' . join(' AND ', $wheres) . ')';
} else {
return parent::MATCH_ALL_SQL;
}
} | Generate a where statement to filter the appointment model
@return string | entailment |
public function matchAppointment(\Gems_Agenda_Appointment $appointment)
{
$result1 = $this->matchSingle(
$this->_data['gaf_filter_text1'],
$this->_data['gaf_filter_text2'],
$this->_fieldList2,
$appointment);
$result2 = $this->matchSingle(
$this->_data['gaf_filter_text3'],
$this->_data['gaf_filter_text4'],
$this->_fieldList4,
$appointment);
return $result1 && $result2;
} | Check a filter for a match
@param \Gems\Agenda\Gems_Agenda_Appointment $appointment
@return boolean | entailment |
protected function matchSingle($field, $searchTxt, $fieldList, $appointment)
{
$result = true;
if ($field && $searchTxt) {
$value = $this->getAppointmentFieldValue($appointment, $field);
if (isset($this->_lookupTables[$field])) {
if ($fieldList && $fieldList !== true) {
if (! isset($fieldList)) {
$result = false;
}
} else {
$result = false;
}
} else {
$regex = '/' . str_replace(array('%', '_'), array('.*', '.{1,1}'), $searchTxt) . '/i';
if (! (boolean) preg_match($regex, $value)) {
$result = false;
}
}
}
return $result;
} | Check a filter for a match
@param $field
@param $searchTxt
@param $fieldList
@param \Gems\Agenda\Gems_Agenda_Appointment $appointment
@return boolean | entailment |
public function execute($formData = null)
{
$batch = $this->getBatch();
$import = $batch->getVariable('import');
$tracker = $this->loader->getTracker();
$model = $tracker->getTrackModel();
$model->applyFormatting(true, true);
$trackData = $import['trackData'];
$trackData['gtr_track_name'] = $formData['gtr_track_name'];
$trackData['gtr_organizations'] = $formData['gtr_organizations'];
// \MUtil_Echo::track($trackData);
if ($trackData['gtr_date_start'] && (! $trackData['gtr_date_start'] instanceof \Zend_Date)) {
$trackData['gtr_date_start'] = new \MUtil_Date($trackData['gtr_date_start'], 'yyyy-MM-dd');
}
$output = $model->save($trackData);
$import['trackId'] = $output['gtr_id_track'];
$import['trackData']['gtr_id_track'] = $output['gtr_id_track'];
$batch->addMessage(sprintf($this->_('Created track with id %d'), $output['gtr_id_track']));
} | 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 |
function DecodeVendorSpecificContent($vendor_specific_raw_value)
{
$result = array();
$offset_in_raw = 0;
$vendor_id = (ord(substr($vendor_specific_raw_value, 0, 1))*256*256*256)+(ord(substr($vendor_specific_raw_value, 1, 1))*256*256)+(ord(substr($vendor_specific_raw_value, 2, 1))*256)+ord(substr($vendor_specific_raw_value, 3, 1));
$offset_in_raw += 4;
while ($offset_in_raw < strlen($vendor_specific_raw_value))
{
$vendor_type = (ord(substr($vendor_specific_raw_value, 0+$offset_in_raw, 1)));
$vendor_length = (ord(substr($vendor_specific_raw_value, 1+$offset_in_raw, 1)));
$attribute_specific = substr($vendor_specific_raw_value, 2+$offset_in_raw, $vendor_length);
$result[] = array($vendor_id, $vendor_type, $attribute_specific);
$offset_in_raw += ($vendor_length);
}
return $result;
} | *******************************************************************
Array returned: array(array(Vendor-Id1, Vendor type1, Attribute-Specific1), ..., array(Vendor-IdN, Vendor typeN, Attribute-SpecificN)
******************************************************************* | entailment |
function AccessRequest($username = '', $password = '', $udp_timeout = 0, $state = NULL)
{
$this->ClearDataReceived();
$this->ClearLastError();
$this->SetPacketCodeToSend(1); // Access-Request
if (0 < strlen($username))
{
$this->SetUsername($username);
}
if (0 < strlen($password))
{
$this->SetPassword($password);
}
if ($state!==NULL)
{
$this->SetAttribute(24, $state);
}
else
{
$this->SetAttribute(6, 1); // 1=Login
}
if (intval($udp_timeout) > 0)
{
$this->SetUdpTimeout($udp_timeout);
}
$attributes_content = '';
for ($attributes_loop = 0; $attributes_loop < count($this->_attributes_to_send); $attributes_loop++)
{
$attributes_content .= $this->_attributes_to_send[$attributes_loop];
}
$packet_length = 4; // Radius packet code + Identifier + Length high + Length low
$packet_length += strlen($this->_request_authenticator); // Request-Authenticator
$packet_length += strlen($attributes_content); // Attributes
$packet_data = chr($this->_radius_packet_to_send);
$packet_data .= chr($this->GetNextIdentifier());
$packet_data .= chr(intval($packet_length/256));
$packet_data .= chr(intval($packet_length%256));
$packet_data .= $this->_request_authenticator;
$packet_data .= $attributes_content;
$_socket_to_server = socket_create(AF_INET, SOCK_DGRAM, 17); // UDP packet = 17
if ($_socket_to_server === FALSE)
{
$this->_last_error_code = socket_last_error();
$this->_last_error_message = socket_strerror($this->_last_error_code);
}
elseif (FALSE === socket_connect($_socket_to_server, $this->_ip_radius_server, $this->_authentication_port))
{
$this->_last_error_code = socket_last_error();
$this->_last_error_message = socket_strerror($this->_last_error_code);
}
elseif (FALSE === socket_write($_socket_to_server, $packet_data, $packet_length))
{
$this->_last_error_code = socket_last_error();
$this->_last_error_message = socket_strerror($this->_last_error_code);
}
else
{
$this->DebugInfo('<b>Packet type '.$this->_radius_packet_to_send.' ('.$this->GetRadiusPacketInfo($this->_radius_packet_to_send).')'.' sent</b>');
if ($this->_debug_mode)
{
$readable_attributes = '';
foreach($this->_attributes_to_send as $one_attribute_to_send)
{
$attribute_info = $this->GetAttributesInfo(ord(substr($one_attribute_to_send,0,1)));
$this->DebugInfo('Attribute '.ord(substr($one_attribute_to_send,0,1)).' ('.$attribute_info[0].'), length '.(ord(substr($one_attribute_to_send,1,1))-2).', format '.$attribute_info[1].', value <em>'.$this->DecodeAttribute(substr($one_attribute_to_send,2), ord(substr($one_attribute_to_send,0,1))).'</em>');
}
}
$read_socket_array = array($_socket_to_server);
$write_socket_array = NULL;
$except_socket_array = NULL;
$received_packet = chr(0);
if (!(FALSE === socket_select($read_socket_array, $write_socket_array, $except_socket_array, $this->_udp_timeout)))
{
if (in_array($_socket_to_server, $read_socket_array))
{
if (FALSE === ($received_packet = @socket_read($_socket_to_server, 1024))) // @ used, than no error is displayed if the connection is closed by the remote host
{
$received_packet = chr(0);
$this->_last_error_code = socket_last_error();
$this->_last_error_message = socket_strerror($this->_last_error_code);
}
else
{
socket_close($_socket_to_server);
}
}
}
else
{
socket_close($_socket_to_server);
}
}
$this->_radius_packet_received = intval(ord(substr($received_packet, 0, 1)));
$this->DebugInfo('<b>Packet type '.$this->_radius_packet_received.' ('.$this->GetRadiusPacketInfo($this->_radius_packet_received).')'.' received</b>');
if ($this->_radius_packet_received > 0)
{
$this->_identifier_received = intval(ord(substr($received_packet, 1, 1)));
$packet_length = (intval(ord(substr($received_packet, 2, 1))) * 256) + (intval(ord(substr($received_packet, 3, 1))));
$this->_response_authenticator = substr($received_packet, 4, 16);
$attributes_content = substr($received_packet, 20, ($packet_length - 4 - 16));
while (strlen($attributes_content) > 2)
{
$attribute_type = intval(ord(substr($attributes_content,0,1)));
$attribute_length = intval(ord(substr($attributes_content,1,1)));
$attribute_raw_value = substr($attributes_content,2,$attribute_length-2);
$attributes_content = substr($attributes_content, $attribute_length);
$attribute_value = $this->DecodeAttribute($attribute_raw_value, $attribute_type);
$attribute_info = $this->GetAttributesInfo($attribute_type);
if (26 == $attribute_type)
{
$vendor_array = $this->DecodeVendorSpecificContent($attribute_value);
foreach($vendor_array as $vendor_one)
{
$this->DebugInfo('Attribute '.$attribute_type.' ('.$attribute_info[0].'), length '.($attribute_length-2).', format '.$attribute_info[1].', Vendor-Id: '.$vendor_one[0].", Vendor-type: ".$vendor_one[1].", Attribute-specific: ".$vendor_one[2]);
}
}
else
{
$this->DebugInfo('Attribute '.$attribute_type.' ('.$attribute_info[0].'), length '.($attribute_length-2).', format '.$attribute_info[1].', value <em>'.$attribute_value.'</em>');
}
$this->_attributes_received[] = array($attribute_type, $attribute_value);
}
}
return (2 == ($this->_radius_packet_received));
} | /*
Function : AccessRequest
Return TRUE if Access-Request is accepted, FALSE otherwise | entailment |
public function execute($lineNr = null, $conditionData = null)
{
$batch = $this->getBatch();
$import = $batch->getVariable('import');
$conditionId = $conditionData['gcon_id'];
if (! (isset($import['trackId']) && $import['trackId'])) {
// Do nothing
return;
}
$conditions = $this->loader->getConditions();
$model = $this->loader->getModels()->getConditionModel()->applyEditSettings(true);
// Try to find by classname and options
$filter = [
'gcon_class' => $conditionData['gcon_class'],
'gcon_condition_text1' => $conditionData['gcon_condition_text1'],
'gcon_condition_text2' => $conditionData['gcon_condition_text2'],
'gcon_condition_text3' => $conditionData['gcon_condition_text3'],
'gcon_condition_text4' => $conditionData['gcon_condition_text4']
];
$found = $model->loadFirst($filter);
if (!$found) {
// Insert
$conditionData['gcon_id'] = null;
} else {
$conditionData['gcon_id'] = $found['gcon_id'];
}
$conditionSaved = $model->save($conditionData);
$import['importConditions'][$conditionId] = $conditionSaved['gcon_id'];
} | Should handle execution of the task, taking as much (optional) parameters as needed
The parameters should be optional and failing to provide them should be handled by
the task | entailment |
public function getHtmlOutput(\Zend_View_Abstract $view)
{
$html = $this->getHtmlSequence();
if ($this->trackName) {
$html->h3(sprintf($this->_('Surveys in %s track'), $this->trackName));
}
$trackRepeater = $this->getRepeater($this->trackId);
$table = $html->div(array('class' => 'table-container'))->table($trackRepeater, array('class' => 'browser table'));
if ($link = $this->findMenuItem('project-tracks', 'questions')) {
$table->tr()->onclick = array('location.href=\'', $link->toHRefAttribute($trackRepeater), '\';');
$table->addColumn($link->toActionLinkLower($trackRepeater));
}
$surveyName[] = $trackRepeater->gsu_survey_name;
$surveyName[] = \MUtil_Lazy::iif($trackRepeater->gro_icon_file, \MUtil_Html::create('img', array('src' => $trackRepeater->gro_icon_file, 'class' => 'icon')));
$table->addColumn($surveyName, $this->_('Survey'));
$table->addColumn($trackRepeater->gro_round_description, $this->_('Details'));
$table->addColumn($trackRepeater->ggp_name, $this->_('By'));
$table->addColumn($trackRepeater->gsu_survey_description->call(array(__CLASS__, 'oneLine')),
$this->_('Description'));
return $html;
} | Create the snippets content
This is a stub function either override getHtmlOutput() or override render()
@param \Zend_View_Abstract $view Just in case it is needed here
@return \MUtil_Html_HtmlInterface Something that can be rendered | entailment |
public function hasHtmlOutput()
{
if (! $this->trackId) {
if (isset($this->trackData['gtr_id_track'])) {
$this->trackId = $this->trackData['gtr_id_track'];
} elseif ($this->trackEngine instanceof \Gems_Tracker_Engine_TrackEngineInterface) {
$this->trackId = $this->trackEngine->getTrackId();
}
}
if (! $this->trackName) {
if (isset($this->trackData['gtr_track_name'])) {
$this->trackName = $this->trackData['gtr_track_name'];
} elseif ($this->trackEngine instanceof \Gems_Tracker_Engine_TrackEngineInterface) {
$this->trackName = $this->trackEngine->getTrackName();
}
}
return (boolean) $this->trackName && 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 createForm($options = null)
{
// Make sure the reset parameter is removed
$url = [
$this->basepath->getBasePathIfExists(),
'/',
$this->request->getControllerName(),
'/',
$this->request->getActionName(),
];
$this->loginForm->setAction(implode('', $url));
return $this->loginForm;
} | Creates an empty form. Allows overruling in sub-classes.
@param mixed $options
@return \Zend_Form | entailment |
protected function processForm()
{
// Check job monitors as long as the login form is being processed
$this->util->getMonitor()->checkMonitors();
// Start the real work
$this->loadForm();
$orgId = null;
if ($this->request->isPost()) {
$orgId = $this->loginForm->getActiveOrganizationId();
if ($orgId && ($this->currentUser->getCurrentOrganizationId() != $orgId)) {
$this->currentUser->setCurrentOrganization($orgId);
}
}
if ($this->loginForm->wasSubmitted()) {
$user = $this->loginForm->getUser();
if ($this->loginForm->isValid($this->request->getPost(), false)) {
$user->switchLocale();
$this->loginStatusTracker
->setPasswordText($this->loginForm->getPasswordText())
->setUser($user);
return false;
}
$errors = \MUtil_Ra::flatten($this->loginForm->getMessages());
// \MUtil_Echo::track($errors);
// Also log the error to the log table when the project has logging enabled
$logErrors = join(' - ', $errors);
$msg = sprintf(
'Failed login for : %s (%s) - %s',
$user->getLoginName(),
$user->getCurrentOrganizationId(),
$logErrors
);
$this->accesslog->logChange($this->request, $msg);
}
return true;
} | Step by step form processing
Returns false when $this->afterSaveRouteUrl is set during the
processing, which happens by default when the data is saved.
@return boolean True when the form should be displayed | entailment |
public function cleanupAction()
{
$params = $this->_processParameters($this->showParameters);
$params['contentTitle'] = $this->_('Clean up existing appointments?');
$params['filterOn'] = 'gap_id_procedure';
$params['filterWhen'] = 'gap_filter';
$snippets = array(
'Generic\\ContentTitleSnippet',
'Agenda\\AppointmentCleanupSnippet',
'Agenda_CalendarTableSnippet',
);
$this->addSnippets($snippets, $params);
} | Cleanup appointments | entailment |
protected function createModel($detailed, $action)
{
$translated = $this->util->getTranslated();
$model = new \MUtil_Model_TableModel('gems__agenda_procedures');
\Gems_Model::setChangeFieldsByPrefix($model, 'gapr');
$model->setDeleteValues('gapr_active', 0);
$model->set('gapr_name', 'label', $this->_('Procedure'),
'description', $this->_('A procedure describes an appointments effects on a respondent:
e.g. an excercise, an explanantion, a massage, mindfullness, a (specific) operation, etc...'),
'required', true
);
$model->setIfExists('gapr_id_organization', 'label', $this->_('Organization'),
'description', $this->_('Optional, an import match with an organization has priority over those without.'),
'multiOptions', $translated->getEmptyDropdownArray() + $this->util->getDbLookup()->getOrganizations()
);
$model->setIfExists('gapr_name_for_resp', 'label', $this->_('Respondent explanation'),
'description', $this->_('Alternative description to use with respondents.')
);
$model->setIfExists('gapr_match_to', 'label', $this->_('Import matches'),
'description', $this->_("Split multiple import matches using '|'.")
);
$model->setIfExists('gapr_code', 'label', $this->_('Procedure code'),
'size', 10,
'description', $this->_('Optional code name to link the procedure to program code.'));
$model->setIfExists('gapr_active', 'label', $this->_('Active'),
'description', $this->_('Inactive means assignable only through automatich processes.'),
'elementClass', 'Checkbox',
'multiOptions', $translated->getYesNo()
);
$model->setIfExists('gapr_filter', 'label', $this->_('Filter'),
'description', $this->_('When checked appointments with these procedures are not imported.'),
'elementClass', 'Checkbox',
'multiOptions', $translated->getYesNo()
);
$model->addColumn("CASE WHEN gapr_active = 1 THEN '' ELSE 'deleted' END", 'row_class');
return $model;
} | Creates a model for getModel(). Called only for each new $action.
The parameters allow you to easily adapt the model to the current action. The $detailed
parameter was added, because the most common use of action is a split between detailed
and summarized actions.
@param boolean $detailed True when the current action is not in $summarizedActions.
@param string $action The current action.
@return \MUtil_Model_ModelAbstract | entailment |
protected function applySurveyListValidAfter(\MUtil_Model_ModelAbstract $model, array &$itemData)
{
$this->_ensureRounds();
$previous = $this->getPreviousRoundId($itemData['gro_id_round'], $itemData['gro_id_order']);
if ($previous) {
$itemData['gro_valid_after_id'] = $previous;
$rounds[$previous] = $this->getRound($previous)->getFullDescription();
} else {
$itemData['gro_valid_after_id'] = null;
$rounds = $this->util->getTranslated()->getEmptyDropdownArray();
}
$model->set('gro_valid_after_id', 'multiOptions', $rounds, 'elementClass', 'Exhibitor');
return false;
} | Set the surveys to be listed as valid after choices for this item and the way they are displayed (if at all)
@param \MUtil_Model_ModelAbstract $model The round model
@param array $itemData The current items data
@param boolean True if the update changed values (usually by changed selection lists). | entailment |
protected function applySurveyListValidFor(\MUtil_Model_ModelAbstract $model, array &$itemData)
{
if (! (isset($itemData['gro_id_round']) && $itemData['gro_id_round'])) {
$itemData['gro_id_round'] = '';
}
// Fixed value
$itemData['gro_valid_for_id'] = $itemData['gro_id_round'];
// The options array
$rounds[$itemData['gro_id_round']] = $this->_('This round');
$model->set('gro_valid_for_id', 'multiOptions', $rounds, 'elementClass', 'Exhibitor');
return false;
} | Set the surveys to be listed as valid for choices for this item and the way they are displayed (if at all)
@param \MUtil_Model_ModelAbstract $model The round model
@param array $itemData The current items data
@param boolean True if the update changed values (usually by changed selection lists). | entailment |
public function getConversionTargets(array $options)
{
$results = array();
foreach ($options as $className => $label) {
switch ($className) {
case 'AnyStepEngine':
case 'NextStepEngine':
$results[$className] = $label;
break;
}
}
return $results;
} | Returns a list of classnames this track engine can be converted into.
Should always contain at least the class itself.
@see convertTo()
@param array $options The track engine class options available in as a "track engine class names" => "descriptions" array
@return array Filter or adaptation of $options | entailment |
protected function getValidUntilDate($fieldSource, $fieldName, $prevRoundId, \Gems_Tracker_Token $token, \Gems_Tracker_RespondentTrack $respTrack, $validFrom)
{
$date = null;
switch ($fieldSource) {
case parent::NO_TABLE:
break;
case parent::TOKEN_TABLE:
// Always uses the current token
if ($fieldName == 'gto_valid_from') {
// May be changed but is not yet stored
$date = $validFrom;
} else {
// No previous here, date is always from this tokens date
$date = $token->getDateTime($fieldName);
}
break;
case parent::ANSWER_TABLE:
if ($prev = $token->getPreviousSuccessToken()) {
$date = $prev->getAnswerDateTime($fieldName);
}
break;
case parent::APPOINTMENT_TABLE:
case parent::RESPONDENT_TRACK_TABLE:
$date = $respTrack->getDate($fieldName);
break;
}
return $date;
} | Returns the date to use to calculate the ValidUntil if any
@param string $fieldSource Source for field from round
@param string $fieldName Name from round
@param int $prevRoundId Id from round
@param \Gems_Tracker_Token $token
@param \Gems_Tracker_RespondentTrack $respTrack
@param \MUtil_Date $validFrom The calculated new valid from value or null
@return \MUtil_Date date time or null | entailment |
public function toPHP()
{
$value1 = '$fields->dataFieldByName(\'' . $this->master . '\')->dataValue()';
$value2 = $this->value;
if ($operator = $this->phpOperator()) {
return $value1 . " {$operator} \"$value2\"";
}
switch ($this->operator) {
case 'contains':
return 'strpos(' . $value1 . '' . ", \"$value2\") !== false";
case 'Checked':
return "$value1 == \"1\"";
case 'Empty':
return $value1 . '==""';
case 'hasCheckedOption':
return 'strpos(' . $value1 . '' . ", \"$value2\") !== false";
case 'hasCheckedAtLeast':
return 'substr_count('.$value1.',",") >= ' . $value2;
case 'hasCheckedLessThan':
return 'substr_count('.$value1.',",") <= ' . $value2;
default:
throw new Exception("ValidationLogicCriteria: php operator \"$this->operator\" not configured.");
}
} | Returns a string of php code to be evaluated
@return string | entailment |
protected function addBrowseTableColumns(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model)
{
$br = \MUtil_Html::create('br');
if (! $this->columns) {
$this->columns = array(
10 => array('gsf_login', $br, 'gsf_id_primary_group'),
20 => array('name', $br, 'gsf_email'),
30 => array('gsf_id_organization', $br, 'gsf_gender'),
40 => array('gsf_active', $br, 'has_2factor'),
);
}
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 |
protected function createModel()
{
if ($this->model instanceof \Gems_Model_StaffModel) {
$model = $this->model;
} else {
$model = $this->loader->getModels()->getStaffModel();
$model->applyBrowseSettings();
}
return $model;
} | Creates the model
@return \MUtil_Model_ModelAbstract | entailment |
protected function getEditMenuItems()
{
$resets = $this->findMenuItems($this->menuActionController, 'reset');
foreach ($resets as $resetPw) {
if ($resetPw instanceof \Gems_Menu_SubMenuItem) {
$resetPw->set('label', $this->_('password'));
}
}
return array_merge(
parent::getEditMenuItems(),
$resets,
$this->findMenuItems($this->menuActionController, 'mail')
);
} | Returns an edit menu item, if access is allowed by privileges
@return \Gems_Menu_SubMenuItem | entailment |
protected function createModel()
{
if (! $this->model instanceof \Gems_Tracker_Model_TrackModel) {
$this->model = $this->loader->getTracker()->getTrackModel();
}
return $this->model;
} | Creates the model
@return \MUtil_Model_ModelAbstract | entailment |
protected function setShowTableFooter(\MUtil_Model_Bridge_VerticalTableBridge $bridge, \MUtil_Model_ModelAbstract $model)
{
if ($model instanceof \Gems_Tracker_Model_TrackModel) {
$this->useCount = $model->getStartCount($this->trackId);
if ($this->useCount) {
$this->addMessage(sprintf($this->plural(
'This track has been started %s time.', 'This track has been started %s times.',
$this->useCount
), $this->useCount));
$this->addMessage($this->_('This track cannot be deleted, only deactivated.'));
$this->deleteQuestion = $this->_('Do you want to deactivate this track?');
$this->displayTitle = $this->_('Deactivate track');
}
}
parent::setShowTableFooter($bridge, $model);
} | 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 toggleCheckboxes($id, $value = null, array $params = array())
{
$js = sprintf('%1$s("#%2$s").click(function(){
var checkboxes = %1$s("%3$s");
checkboxes.prop("checked", !checkboxes.prop("checked"));
});',
\ZendX_JQuery_View_Helper_JQuery::getJQueryHandler(),
$id,
$params['selector']
);
unset($params['selector']);
$this->jquery->addOnLoad($js);
//Now do something to add the jquery stuff
return $this->view->formButton($id, $value, $params);
} | put your code here | entailment |
public function setView(\Zend_View_Interface $view = null)
{
$element = parent::setView($view);
if (null !== $view) {
if (false === $view->getPluginLoader('helper')->getPaths('Gems_JQuery_View_Helper')) {
$view->addHelperPath('Gems/JQuery/View/Helper', 'Gems_JQuery_View_Helper');
}
}
return $element;
} | Set the view object
Ensures that the view object has the \Gems_jQuery view helper path set.
@param \Zend_View_Interface $view
@return \Gems_JQuery_Form_Element_ToggleCheckboxes | entailment |
protected function createModel($detailed, $action)
{
// Load organizationId and respondentId
$this->loadParams();
$model = $this->loader->getModels()->createAppointmentModel();
if ($detailed) {
if (('edit' === $action) || ('create' === $action)) {
$model->applyEditSettings($this->organizationId);
if ($action == 'create') {
// Set default date to tomoorow.
$now = new \MUtil_Date();
$now->addDay(1);
$loid = $this->db->fetchOne(
"SELECT gap_id_location
FROM gems__appointments
WHERE gap_id_user = ? AND gap_id_organization = ?
ORDER BY gap_admission_time DESC",
array($this->respondentId, $this->organizationId)
);
if ($loid !== false) {
$model->set('gap_id_location', 'default', $loid);
}
$model->set('gap_id_user', 'default', $this->respondentId);
$model->set('gap_manual_edit', 'default', 1);
$model->set('gap_admission_time', 'default', $now);
} else {
// When there is something saved, then set manual edit to 1
$model->setSaveOnChange('gap_manual_edit');
$model->setOnSave( 'gap_manual_edit', 1);
}
} else {
$model->applyDetailSettings();
}
} else {
$model->applyBrowseSettings();
$model->addFilter(array(
'gap_id_user' => $this->respondentId,
'gap_id_organization' => $this->organizationId,
));
}
return $model;
} | Creates a model for getModel(). Called only for each new $action.
The parameters allow you to easily adapt the model to the current action. The $detailed
parameter was added, because the most common use of action is a split between detailed
and summarized actions.
@param boolean $detailed True when the current action is not in $summarizedActions.
@param string $action The current action.
@return \MUtil_Model_ModelAbstract | entailment |
public function getContentTitle()
{
$patientId = $this->_getParam(\MUtil_Model::REQUEST_ID1);
if ($patientId) {
if ($this->currentUser->areAllFieldsMaskedWhole('grs_first_name', 'grs_surname_prefix', 'grs_last_name')) {
return sprintf($this->_('Appointments for respondent number %s'), $patientId);
}
$respondent = $this->loader->getRespondent(
$patientId,
$this->getRequest()->getParam(\MUtil_Model::REQUEST_ID2)
);
return sprintf($this->_('Appointments for respondent number %s: %s'), $patientId, $respondent->getName());
}
return $this->getIndexTitle();
} | Helper function to get the informed title for the index action.
@return $string | entailment |
public function getRespondent()
{
if (! $this->_respondent) {
$id = $this->_getParam(\Gems_Model::APPOINTMENT_ID);
if ($id && ! ($this->_getParam(\MUtil_Model::REQUEST_ID1) || $this->_getParam(\MUtil_Model::REQUEST_ID2))) {
$appointment = $this->loader->getAgenda()->getAppointment($id);
$this->_respondent = $appointment->getRespondent();
if (! $this->_respondent->exists) {
throw new \Gems_Exception($this->_('Unknown respondent.'));
}
$this->_respondent->applyToMenuSource($this->menu->getParameterSource());
} else {
$this->_respondent = parent::getRespondent();
}
}
return $this->_respondent;
} | Get the respondent object
@return \Gems_Tracker_Respondent | entailment |
protected function loadParams()
{
$patientNr = $this->_getParam(\MUtil_Model::REQUEST_ID1);
$this->appointmentId = $this->_getParam(\Gems_Model::APPOINTMENT_ID);
if ($this->appointmentId) {
$select = $this->db->select();
$select->from('gems__appointments', array('gap_id_user', 'gap_id_organization'))
->joinInner(
'gems__respondent2org',
'gap_id_user = gr2o_id_user AND gap_id_organization = gr2o_id_organization',
array('gr2o_patient_nr')
)
->where('gap_id_appointment = ?', $this->appointmentId);
$data = $this->db->fetchRow($select);
if ($data) {
$this->organizationId = $data['gap_id_organization'];
$this->respondentId = $data['gap_id_user'];
$patientNr = $data['gr2o_patient_nr'];
}
} else {
$this->organizationId = $this->_getParam(\MUtil_Model::REQUEST_ID2);
if ($patientNr && $this->organizationId) {
$this->respondentId = $this->util->getDbLookup()->getRespondentId(
$patientNr,
$this->organizationId
);
}
}
if (! $this->respondentId) {
throw new \Gems_Exception($this->_('Requested agenda data not available!'));
} else {
$orgs = $this->currentUser->getAllowedOrganizations();
if (! isset($orgs[$this->organizationId])) {
$org = $this->loader->getOrganization($this->organizationId);
if ($org->exists()) {
throw new \Gems_Exception(
sprintf($this->_('You have no access to %s appointments!'), $org->getName())
);
} else {
throw new \Gems_Exception($this->_('Organization does not exist.'));
}
}
}
$source = $this->menu->getParameterSource();
if ($this->appointmentId) {
$source->setAppointmentId($this->appointmentId);
}
if ($patientNr && $this->organizationId) {
$source->setPatient($patientNr, $this->organizationId);
}
} | Loads and checks the request parameters
@throws \Gems_Exception | entailment |
public function applyBrowseSettings()
{
$this->loadFilterDependencies(false);
$yesNo = $this->util->getTranslated()->getYesNo();
$this->set('gaf_class', 'label', $this->_('Filter type'),
'description', $this->_('Determines what is filtered how.'),
'multiOptions', $this->filterOptions
);
$this->addColumn('COALESCE(gaf_manual_name, gaf_calc_name)', 'gaf_name');
$this->set('gaf_name', 'label', $this->_('Name'));
$this->set('gaf_id_order', 'label', $this->_('Order'),
'description', $this->_('Execution order of the filters, lower numbers are executed first.')
);
$this->set('gaf_active', 'label', $this->_('Active'),
'multiOptions', $yesNo
);
$this->addColumn(new \Zend_Db_Expr(
"(SELECT COUNT(*) FROM gems__track_appointments WHERE gaf_id = gtap_filter_id)"
), 'usetrack');
$this->set('usetrack', 'label', $this->_('Use in track fields'),
'description', $this->_('The number of uses of this filter in track fields.'),
'elementClass', 'Exhibitor'
);
$this->addColumn(new \Zend_Db_Expr(
"(SELECT COUNT(*)
FROM gems__appointment_filters AS other
WHERE gaf_class IN ('AndAppointmentFilter', 'OrAppointmentFilter') AND
(
gems__appointment_filters.gaf_id = other.gaf_filter_text1 OR
gems__appointment_filters.gaf_id = other.gaf_filter_text2 OR
gems__appointment_filters.gaf_id = other.gaf_filter_text3 OR
gems__appointment_filters.gaf_id = other.gaf_filter_text4
)
)"
), 'usefilter');
$this->set('usefilter', 'label', $this->_('Use in filters'),
'description', $this->_('The number of uses of this filter in other filters.'),
'elementClass', 'Exhibitor'
);
return $this;
} | Set those settings needed for the browse display
@return \Gems_Agenda_AppointmentFilterModelAbstract | entailment |
public function applyDetailSettings()
{
$this->loadFilterDependencies(true);
$yesNo = $this->util->getTranslated()->getYesNo();
$this->resetOrder();
$this->set('gaf_class', 'label', $this->_('Filter type'),
'description', $this->_('Determines what is filtered how.'),
'multiOptions', $this->filterOptions
);
$this->set('gaf_manual_name', 'label', $this->_('Manual name'),
'description', $this->_('A name for this filter. The calculated name is used otherwise.'));
$this->set('gaf_calc_name', 'label', $this->_('Calculated name'));
$this->set('gaf_id_order', 'label', $this->_('Order'),
'description', $this->_('Execution order of the filters, lower numbers are executed first.')
);
// Set the order
$this->set('gaf_filter_text1');
$this->set('gaf_filter_text2');
$this->set('gaf_filter_text3');
$this->set('gaf_filter_text4');
$this->set('gaf_active', 'label', $this->_('Active'),
'multiOptions', $yesNo
);
$this->addColumn(new \Zend_Db_Expr(sprintf(
"(SELECT COALESCE(GROUP_CONCAT(gtr_track_name, '%s', gtap_field_name
ORDER BY gtr_track_name, gtap_id_order SEPARATOR '%s'), '%s')
FROM gems__track_appointments INNER JOIN gems__tracks ON gtap_id_track = gtr_id_track
WHERE gaf_id = gtap_filter_id)",
$this->_(': '),
$this->_('; '),
$this->_('Not used in tracks')
)), 'usetrack');
$this->set('usetrack', 'label', $this->_('Use in track fields'),
'description', $this->_('The use of this filter in track fields.'),
'elementClass', 'Exhibitor'
);
$this->addColumn(new \Zend_Db_Expr(sprintf(
"(SELECT COALESCE(GROUP_CONCAT(gaf_calc_name ORDER BY gaf_id_order SEPARATOR '%s'), '%s')
FROM gems__appointment_filters AS other
WHERE gaf_class IN ('AndAppointmentFilter', 'OrAppointmentFilter') AND
(
gems__appointment_filters.gaf_id = other.gaf_filter_text1 OR
gems__appointment_filters.gaf_id = other.gaf_filter_text2 OR
gems__appointment_filters.gaf_id = other.gaf_filter_text3 OR
gems__appointment_filters.gaf_id = other.gaf_filter_text4
)
)",
$this->_('; '),
$this->_('Not used in filters')
)), 'usefilter');
$this->set('usefilter', 'label', $this->_('Use in filters'),
'description', $this->_('The use of this filter in other filters.'),
'elementClass', 'Exhibitor'
);
return $this;
} | Set those settings needed for the detailed display
@return \Gems_Agenda_AppointmentFilterModelAbstract | entailment |
public function applyEditSettings($create = false)
{
$this->applyDetailSettings();
reset($this->filterOptions);
$default = key($this->filterOptions);
$this->set('gaf_class', 'default', $default, 'onchange', 'this.form.submit();');
// gaf_id is not needed for some validators
$this->set('gaf_id', 'elementClass', 'Hidden');
$this->set('gaf_calc_name', 'elementClass', 'Exhibitor');
$this->setOnSave('gaf_calc_name', array($this, 'calcultateName'));
$this->set('gaf_active', 'elementClass', 'Checkbox');
if ($create) {
$default = $this->db->fetchOne("SELECT MAX(gaf_id_order) FROM gems__appointment_filters");
$this->set('gaf_id_order', 'default', intval($default) + 10);
}
return $this;
} | Set those values needed for editing
@return \Gems_Agenda_AppointmentFilterModelAbstract | entailment |
protected function loadFilterDependencies($activateDependencies = true)
{
if (! $this->filterOptions) {
$maxLength = $this->get('gaf_calc_name', 'maxlength');
$this->filterOptions = array();
foreach ($this->filterDependencies as $dependencyClass) {
$dependency = $this->agenda->newFilterObject($dependencyClass);
if ($dependency instanceof FilterModelDependencyAbstract) {
$this->filterOptions[$dependency->getFilterClass()] = $dependency->getFilterName();
if ($activateDependencies) {
$dependency->setMaximumCalcLength($maxLength);
$this->addDependency($dependency);
}
}
}
asort($this->filterOptions);
}
return $this->filterOptions;
} | Load filter dependencies into model and populate the filterOptions
@return array filterClassName => Label | entailment |
public function afterRegistry()
{
parent::afterRegistry();
$this->model = $this->loader->getModels()->getRespondentModel(true);
if ($this->addLoginCheck) {
$this->model->addLoginCheck();
}
// Load the data
$this->refresh();
} | Called after the check that all required registry values
have been set correctly has run.
@return void | entailment |
public function applyToMenuSource(\Gems_Menu_ParameterSource $source)
{
$source->setPatient($this->getPatientNumber(), $this->getOrganizationId());
$source->offsetSet('resp_deleted', ($this->getReceptionCode()->isSuccess() ? 0 : 1));
return $this;
} | Set menu parameters from this token
@param \Gems_Menu_ParameterSource $source
@return \Gems_Tracker_RespondentTrack (continuation pattern) | entailment |
public function getAge($date = null, $months = false)
{
$birthDate = $this->getBirthDay();
if (is_null($date)) {
$date = new \MUtil_Date();
}
if (!($birthDate instanceof \MUtil_Date) || !($date instanceof \MUtil_Date)) {
return null;
}
// Now calculate age
if ($months) {
$age = $date->diffMonths($birthDate);
$unit = 'dd';
} else {
$age = $date->diffYears($birthDate);
$unit = 'MMdd';
}
if ($date->get($unit) < $birthDate->get($unit)) {
$age--;
}
return $age;
} | Returns current age or at a given date when supplied
@param \MUtil_Date|null $date
@return int | entailment |
public function getFullName()
{
$genderGreetings = $this->util->getTranslated()->getGenderHello($this->getLanguage());
$greeting = isset($genderGreetings[$this->getGender()]) ? $genderGreetings[$this->getGender()] : '';
return $greeting . ' ' . $this->getName();
} | Get the formal name of respondent
@return string | entailment |
public function getGreeting()
{
$genderGreetings = $this->util->getTranslated()->getGenderGreeting($this->getLanguage());
$gender = $this->getGender();
if (isset($genderGreetings[$gender])) {
$greeting = $genderGreetings[$this->getGender()] . ' ';
} else {
$greeting = '';
}
return $greeting . ' ' . $this->getLastName();
} | Get the propper greeting of respondent
@return string | entailment |
public function getGreetingNL()
{
$genderGreetings = $this->util->getTranslated()->getGenderGreeting($this->getLanguage());
$greeting = $genderGreetings[$this->_gemsData['grs_gender']];
return $greeting . ' ' . ucfirst($this->getLastName());
} | Get the propper greeting of respondent
@return string | entailment |
public function getLanguage() {
if (!isset($this->respondentLanguage)) {
$this->respondentLanguage = $this->_gemsData['grs_iso_lang'];
}
return $this->respondentLanguage;
} | Get the respondents prefered language
@return string | entailment |
public function getLastName()
{
$lastname = '';
if (!empty($this->_gemsData['grs_surname_prefix'])) {
$lastname .= $this->_gemsData['grs_surname_prefix'] . ' ';
}
$lastname .= $this->_gemsData['grs_last_name'];
return $lastname;
} | Get Last name of respondent
@return string | entailment |
public function getPhonenumber()
{
for ($i = 1; $i <= $this->maxPhoneNumber; $i++) {
if (isset($this->_gemsData['grs_phone_' . $i]) && ! empty($this->_gemsData['grs_phone_' . $i])) {
return $this->_gemsData['grs_phone_' . $i];
}
}
return null;
} | Get the first entered phonenumber of the respondent.
@return string | entailment |
public function hasActiveTracks()
{
$select = $this->db->select()
->from('gems__respondent2track', ['gr2t_id_respondent_track'])
->joinInner('gems__reception_codes', 'gr2t_reception_code = grc_id_reception_code', [])
->where('grc_success = 1')
->where('gr2t_id_user = ?', $this->respondentId)
->where('gr2t_id_organization = ?', $this->organizationId)
->limit(1);
return (boolean) $this->db->fetchOne($select);
} | Has the respondent active tracks
@return boolean | entailment |
public function hasAnyTracks()
{
$select = $this->db->select()
->from('gems__respondent2track', ['gr2t_id_respondent_track'])
->where('gr2t_id_user = ?', $this->respondentId)
->where('gr2t_id_organization = ?', $this->organizationId)
->limit(1);
return (boolean) $this->db->fetchOne($select);
} | Has the respondent active tracks
@return boolean | entailment |
public function refresh()
{
$default = true;
$filter = array();
if ($this->patientId) {
$filter['gr2o_patient_nr'] = $this->patientId;
$default = false;
} elseif ($this->respondentId) {
$filter['gr2o_id_user'] = $this->respondentId;
$default = false;
}
if (! $filter) {
// Otherwise we load the first patient in the current organization
$filter[] = '1=0';
}
if ($this->organizationId) {
$filter['gr2o_id_organization'] = $this->organizationId;
}
$this->_gemsData = $this->model->loadFirst($filter);
if ($this->_gemsData) {
$this->exists = true;
$this->patientId = $this->_gemsData['gr2o_patient_nr'];
$this->organizationId = $this->_gemsData['gr2o_id_organization'];
$this->respondentId = $this->_gemsData['gr2o_id_user'];
} else {
$this->_gemsData = $this->model->loadNew();
$this->exists = false;
}
if ($this->currentUser instanceof \Gems_User_User) {
$this->_gemsData = $this->currentUser->applyGroupMask($this->_gemsData);
}
} | Refresh the data | entailment |
public function restoreTracks(\Gems_Util_ReceptionCode $oldCode, \Gems_Util_ReceptionCode $newCode) {
$count = 0;
if (!$oldCode->isSuccess() && $newCode->isSuccess()) {
$respTracks = $this->loader->getTracker()->getRespondentTracks(
$this->getId(),
$this->getOrganizationId()
);
foreach ($respTracks as $respTrack) {
if ($respTrack instanceof \Gems_Tracker_RespondentTrack) {
if ($oldCode->getCode() === $respTrack->getReceptionCode()->getCode()) {
$respTrack->setReceptionCode($newCode, null, $this->currentUser->getUserId());
$respTrack->restoreTokens($oldCode, $newCode);
$count++;
} else {
// If the code was not assigned to the track, still try to restore tokens
$tmpCount = $respTrack->restoreTokens($oldCode, $newCode);
$count = $count + min($tmpCount, 1);
}
}
}
}
return $count;
} | Restores tracks for a respondent, when the reception code matches the given $oldCode
Used when restoring a respondent, and the restore tracks box is checked. This will
also restore all tokens in the tracks that have the same codes.
@param \Gems_Util_ReceptionCode $oldCode The old reception code
@param \Gems_Util_ReceptionCode $newCode the new reception code
@return int The number of restored tracks | entailment |
public function setReceptionCode($newCode)
{
return $this->model->setReceptionCode(
$this->getPatientNumber(),
$this->getOrganizationId(),
$newCode,
$this->getId(),
$this->getReceptionCode()
);
} | Set the reception code for a respondent and cascade non-success codes to the
tracks / surveys.
@param string $newCode String or \Gems_Util_ReceptionCode
@return \Gems_Util_ReceptionCode The new code reception code object for further processing | entailment |
protected function createModel($detailed, $action)
{
$filter = $this->getSearchFilter();
if (isset($filter['gto_id_survey']) && is_numeric($filter['gto_id_survey'])) {
// Surveys have been selected
$exportModelSource = $this->getExportModelSource();
$model = $exportModelSource->getModel($filter, $filter);
$noExportColumns = $model->getColNames('noExport');
foreach($noExportColumns as $colName) {
$model->remove($colName, 'label');
}
} else {
$model = parent::createModel($detailed, $action);
$model->set('gto_id_survey', 'label', $this->_('Please select a survey to start the export'));
}
return $model;
} | Creates a model for getModel(). Called only for each new $action.
The parameters allow you to easily adapt the model to the current action. The $detailed
parameter was added, because the most common use of action is a split between detailed
and summarized actions.
@param boolean $detailed True when the current action is not in $summarizedActions.
@param string $action The current action.
@return \MUtil_Model_ModelAbstract | entailment |
protected function setAfterDeleteRoute()
{
parent::setAfterDeleteRoute();
if (is_array($this->afterSaveRouteUrl)) {
$this->afterSaveRouteUrl[\MUtil_Model::REQUEST_ID] = $this->trackId;
$this->afterSaveRouteUrl[\Gems_Model::ROUND_ID] = null;
$this->afterSaveRouteUrl[$this->confirmParameter] = null;
}
} | Set what to do when the form is 'finished'.
@return \MUtil_Snippets_ModelYesNoDeleteSnippetAbstract | entailment |
protected function setShowTableFooter(\MUtil_Model_Bridge_VerticalTableBridge $bridge, \MUtil_Model_ModelAbstract $model)
{
if ($model instanceof RoundModel) {
$this->useCount = $model->getStartCount($this->roundId);
if ($this->useCount) {
$this->addMessage(sprintf($this->plural(
'This round has been completed %s time.', 'This round has been completed %s times.',
$this->useCount
), $this->useCount));
$this->addMessage($this->_('This round cannot be deleted, only deactivated.'));
$this->deleteQuestion = $this->_('Do you want to deactivate this round?');
$this->displayTitle = $this->_('Deactivate round');
}
}
parent::setShowTableFooter($bridge, $model);
} | 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 getContent($file)
{
$content = $file instanceof File ? $file->getString() : file_get_contents($file);
// Yes, yes, regex'ing HTML is evil.
// Since we don't care about well-formedness or markup here, it does the job.
$content = preg_replace(
[
// Remove invisible content
'@<head[^>]*?>.*?</head>@siu',
'@<style[^>]*?>.*?</style>@siu',
'@<script[^>]*?.*?</script>@siu',
'@<object[^>]*?.*?</object>@siu',
'@<embed[^>]*?.*?</embed>@siu',
'@<applet[^>]*?.*?</applet>@siu',
'@<noframes[^>]*?.*?</noframes>@siu',
'@<noscript[^>]*?.*?</noscript>@siu',
'@<noembed[^>]*?.*?</noembed>@siu',
// Add line breaks before and after blocks
'@</?((address)|(blockquote)|(center)|(del))@iu',
'@</?((div)|(h[1-9])|(ins)|(isindex)|(p)|(pre))@iu',
'@</?((dir)|(dl)|(dt)|(dd)|(li)|(menu)|(ol)|(ul))@iu',
'@</?((table)|(th)|(td)|(caption))@iu',
'@</?((form)|(button)|(fieldset)|(legend)|(input))@iu',
'@</?((label)|(select)|(optgroup)|(option)|(textarea))@iu',
'@</?((frameset)|(frame)|(iframe))@iu',
],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', "$0", "$0", "$0", "$0", "$0", "$0", "$0", "$0"],
$content
);
return strip_tags($content);
} | Extracts content from regex, by using strip_tags()
combined with regular expressions to remove non-content tags like <style> or <script>,
as well as adding line breaks after block tags.
@param File $file
@return string | entailment |
public function setOptions(array $options = array())
{
if (isset($options['image_path'])) {
$this->_options['image_path'] = $options['image_path'];
}
if (isset($options['plugins'])) {
$this->_options['plugins'] = $options['plugins'];
}
return $this;
} | Sets options of the Debug Bar
@param array $options
@return ZFDebug_Controller_Plugin_Debug | entailment |
public function unregisterPlugin($plugin)
{
if (false !== strpos($plugin, '_')) {
foreach ($this->_plugins as $key => $_plugin) {
if ($plugin == get_class($_plugin)) {
unset($this->_plugins[$key]);
}
}
} else {
$plugin = strtolower($plugin);
if (isset($this->_plugins[$plugin])) {
unset($this->_plugins[$plugin]);
}
}
return $this;
} | Unregister a plugin in the Debug Bar
@param string $plugin
@return ZFDebug_Controller_Plugin_Debug | entailment |
public function getPlugin($identifier)
{
$identifier = strtolower($identifier);
if (isset($this->_plugins[$identifier])) {
return $this->_plugins[$identifier];
}
return false;
} | Get a registered plugin in the Debug Bar
@param string $identifier
@return ZFDebug_Controller_Plugin_Debug_Plugin_Interface | entailment |
public function dispatchLoopShutdown()
{
if ($this->getRequest()->isXmlHttpRequest()) {
return;
}
$contentType = $this->getRequest()->getHeader('Content-Type');
if ((false !== $contentType) && (false === strpos($contentType, 'html')) && ($contentType !== '')) {
return;
}
$disable = Zend_Controller_Front::getInstance()->getRequest()->getParam('ZFDEBUG_DISABLE');
if (isset($disable)) {
return;
}
$html = '';
$html .= "<div id='ZFDebug_info'>\n";
$html .= "\t<span class='ZFDebug_span' style='padding-right:0px;' onclick='ZFDebugPanel(ZFDebugCurrent);'>
<img style='vertical-align:middle;' src='".$this->_icon('close')."'>
</span>\n";
/**
* Creating panel content for all registered plugins
*/
foreach ($this->_plugins as $plugin) {
$tab = $plugin->getTab();
if ($tab == '') {
continue;
}
if (null !== $this->_options['image_path'] &&
file_exists($this->_options['image_path'] .'/'. $plugin->getIdentifier() .'.png')) {
$pluginIcon = $this->_options['image_path'] .'/'. $plugin->getIdentifier() .'.png';
} else {
$pluginIcon = $plugin->getIconData();
}
/* @var $plugin ZFDebug_Controller_Plugin_Debug_Plugin_Interface */
$showPanel = ($plugin->getPanel() == '') ? 'log' : $plugin->getIdentifier();
$html .= "\t".'<span id="ZFDebugInfo_'.$plugin->getIdentifier()
. '" class="ZFDebug_span clickable" onclick="ZFDebugPanel(\'ZFDebug_'
. $showPanel . '\');">' . "\n";
if ($pluginIcon) {
$html .= "\t\t".'<img src="' . $pluginIcon . '" style="vertical-align:middle" alt="'
. $plugin->getIdentifier() . '" title="'
. $plugin->getIdentifier() . '"> ' . "\n";
}
$html .= $tab . "</span>\n";
}
$html .= '<span id="ZFDebugInfo_Request" class="ZFDebug_span">'
. "\n"
. round(memory_get_peak_usage()/1024) . 'K in '
. round((microtime(true)-$_SERVER['REQUEST_TIME'])*1000) . 'ms'
. '</span>' . "\n";
$html .= "</div>\n";
$html .= '<div id="ZFDebugResize"></div>';
/**
* Creating menu tab for all registered plugins
*/
$this->getPlugin('log')->mark('Shutdown', true);
foreach ($this->_plugins as $plugin) {
$panel = $plugin->getPanel();
if ($panel == '') {
continue;
}
/* @var $plugin ZFDebug_Controller_Plugin_Debug_Plugin_Interface */
$html .= "\n" . '<div id="ZFDebug_' . $plugin->getIdentifier()
. '" class="ZFDebug_panel" name="ZFDebug_panel">' . "\n" . $panel . "\n</div>\n";
}
$this->_output($html);
} | Defined by Zend_Controller_Plugin_Abstract | entailment |
protected function _loadPlugins()
{
foreach ($this->_options['plugins'] as $plugin => $options) {
if (is_numeric($plugin)) {
# Plugin passed as array value instead of key
$plugin = $options;
$options = array();
}
// Register an instance
if (is_object($plugin) && in_array('ZFDebug_Controller_Plugin_Debug_Plugin_Interface', class_implements($plugin))) {
$this->registerPlugin($plugin);
continue;
}
if (!is_string($plugin)) {
throw new Exception("Invalid plugin name", 1);
}
$plugin = ucfirst($plugin);
// Register a classname
if (in_array($plugin, ZFDebug_Controller_Plugin_Debug::$standardPlugins)) {
// standard plugin
$pluginClass = 'ZFDebug_Controller_Plugin_Debug_Plugin_' . $plugin;
} else {
// we use a custom plugin
if (!preg_match('~^[\w]+$~D', $plugin)) {
throw new Zend_Exception("ZFDebug: Invalid plugin name [$plugin]");
}
$pluginClass = $plugin;
}
require_once str_replace('_', DIRECTORY_SEPARATOR, $pluginClass) . '.php';
$object = new $pluginClass($options);
$this->registerPlugin($object);
}
} | Load plugins set in config option
@return void; | entailment |
protected function _getVersionPanel()
{
$panel = "<h4>ZFDebug $this->_version – Zend Framework "
. Zend_Version::VERSION . " on PHP " . phpversion() . "</h4>\n"
. "<p>©2008-2013 <a href='http://jokke.dk'>Joakim Nygård</a>" . $this->getLinebreak()
. "with contributions by <a href='http://www.bangal.de'>Andreas Pankratz</a> and others</p>"
. "<p>The project is hosted at <a href='https://github.com/jokkedk/ZFDebug'>https://github.com/jokkedk/ZFDebug</a>"
. " and released under the BSD License" . $this->getLinebreak()
. "Includes images from the <a href='http://www.famfamfam.com/lab/icons/silk/'>Silk Icon set</a> by Mark James</p>"
. "<p>Disable ZFDebug temporarily by sending ZFDEBUG_DISABLE as a GET/POST parameter</p>";
// $panel .= '<h4>Zend Framework '.Zend_Version::VERSION.' / PHP '.phpversion().' with extensions:</h4>';
// $extensions = get_loaded_extensions();
// natcasesort($extensions);
// $panel .= implode('<br>', $extensions);
return $panel;
} | Returns version panel
@return string | entailment |
protected function _icon($kind)
{
switch ($kind) {
case 'database':
if (null === $this->_options['image_path'])
return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAEYSURBVBgZBcHPio5hGAfg6/2+R980k6wmJgsJ5U/ZOAqbSc2GnXOwUg7BESgLUeIQ1GSjLFnMwsKGGg1qxJRmPM97/1zXFAAAAEADdlfZzr26miup2svnelq7d2aYgt3rebl585wN6+K3I1/9fJe7O/uIePP2SypJkiRJ0vMhr55FLCA3zgIAOK9uQ4MS361ZOSX+OrTvkgINSjS/HIvhjxNNFGgQsbSmabohKDNoUGLohsls6BaiQIMSs2FYmnXdUsygQYmumy3Nhi6igwalDEOJEjPKP7CA2aFNK8Bkyy3fdNCg7r9/fW3jgpVJbDmy5+PB2IYp4MXFelQ7izPrhkPHB+P5/PjhD5gCgCenx+VR/dODEwD+A3T7nqbxwf1HAAAAAElFTkSuQmCC';
return $this->_options['image_path'] . '/database.png';
break;
case 'exception':
if (null === $this->_options['image_path'])
return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAJPSURBVDjLpZPLS5RhFMYfv9QJlelTQZwRb2OKlKuINuHGLlBEBEOLxAu46oL0F0QQFdWizUCrWnjBaDHgThCMoiKkhUONTqmjmDp2GZ0UnWbmfc/ztrC+GbM2dXbv4ZzfeQ7vefKMMfifyP89IbevNNCYdkN2kawkCZKfSPZTOGTf6Y/m1uflKlC3LvsNTWArr9BT2LAf+W73dn5jHclIBFZyfYWU3or7T4K7AJmbl/yG7EtX1BQXNTVCYgtgbAEAYHlqYHlrsTEVQWr63RZFuqsfDAcdQPrGRR/JF5nKGm9xUxMyr0YBAEXXHgIANq/3ADQobD2J9fAkNiMTMSFb9z8ambMAQER3JC1XttkYGGZXoyZEGyTHRuBuPgBTUu7VSnUAgAUAWutOV2MjZGkehgYUA6O5A0AlkAyRnotiX3MLlFKduYCqAtuGXpyH0XQmOj+TIURt51OzURTYZdBKV2UBSsOIcRp/TVTT4ewK6idECAihtUKOArWcjq/B8tQ6UkUR31+OYXP4sTOdisivrkMyHodWejlXwcC38Fvs8dY5xaIId89VlJy7ACpCNCFCuOp8+BJ6A631gANQSg1mVmOxxGQYRW2nHMha4B5WA3chsv22T5/B13AIicWZmNZ6cMchTXUe81Okzz54pLi0uQWp+TmkZqMwxsBV74Or3od4OISPr0e3SHa3PX0f3HXKofNH/UIG9pZ5PeUth+CyS2EMkEqs4fPEOBJLsyske48/+xD8oxcAYPzs4QaS7RR2kbLTTOTQieczfzfTv8QPldGvTGoF6/8AAAAASUVORK5CYII=';
return $this->_options['image_path'] . '/exception.png';
break;
case 'error':
if (null === $this->_options['image_path'])
return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAIsSURBVDjLpVNLSJQBEP7+h6uu62vLVAJDW1KQTMrINQ1vPQzq1GOpa9EppGOHLh0kCEKL7JBEhVCHihAsESyJiE4FWShGRmauu7KYiv6Pma+DGoFrBQ7MzGFmPr5vmDFIYj1mr1WYfrHPovA9VVOqbC7e/1rS9ZlrAVDYHig5WB0oPtBI0TNrUiC5yhP9jeF4X8NPcWfopoY48XT39PjjXeF0vWkZqOjd7LJYrmGasHPCCJbHwhS9/F8M4s8baid764Xi0Ilfp5voorpJfn2wwx/r3l77TwZUvR+qajXVn8PnvocYfXYH6k2ioOaCpaIdf11ivDcayyiMVudsOYqFb60gARJYHG9DbqQFmSVNjaO3K2NpAeK90ZCqtgcrjkP9aUCXp0moetDFEeRXnYCKXhm+uTW0CkBFu4JlxzZkFlbASz4CQGQVBFeEwZm8geyiMuRVntzsL3oXV+YMkvjRsydC1U+lhwZsWXgHb+oWVAEzIwvzyVlk5igsi7DymmHlHsFQR50rjl+981Jy1Fw6Gu0ObTtnU+cgs28AKgDiy+Awpj5OACBAhZ/qh2HOo6i+NeA73jUAML4/qWux8mt6NjW1w599CS9xb0mSEqQBEDAtwqALUmBaG5FV3oYPnTHMjAwetlWksyByaukxQg2wQ9FlccaK/OXA3/uAEUDp3rNIDQ1ctSk6kHh1/jRFoaL4M4snEMeD73gQx4M4PsT1IZ5AfYH68tZY7zv/ApRMY9mnuVMvAAAAAElFTkSuQmCC';
return $this->_options['image_path'] . '/error.png';
break;
case 'close':
return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAYAAAAfSC3RAAABHElEQVQoFZ2SMUsDQRCFN6eRIIIS0MZW0gUs72orayvh/C3HNfkXV/kftEhz3V0pigghrc0VQdsYiO/b3MAaYgh58HZ2387czt6+jvuLvpaX4oV41m59KTbipzhrNdexieKVOBBPAy2cfmsxEaeIBwwCRdfiMYt/0JNOJ3NxFmmgPU7qii7P8yExRKCRQy41jsR7qITRUqiq6sk05mjsmaY45I43Ii14KPEhjuPbuq6fEWyeJMnjKsOPDYV34lEgOitG4wNrRchz7rgXDlXFO21tVR24tVOp2e/n8I4L8VzslWXZRFE0SdN0rLVHURSvaFmWvbUSRvgw55gB/Fu2CZvCj8QXcWrOwYM44kTEIZvASe+it5ydaIk7m/wXTbV0eSnRtrUAAAAASUVORK5CYII=';
break;
default:
if (null === $this->_options['image_path'])
return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHhSURBVDjLpZI9SJVxFMZ/r2YFflw/kcQsiJt5b1ije0tDtbQ3GtFQYwVNFbQ1ujRFa1MUJKQ4VhYqd7K4gopK3UIly+57nnMaXjHjqotnOfDnnOd/nt85SURwkDi02+ODqbsldxUlD0mvHw09ubSXQF1t8512nGJ/Uz/5lnxi0tB+E9QI3D//+EfVqhtppGxUNzCzmf0Ekojg4fS9cBeSoyzHQNuZxNyYXp5ZM5Mk1ZkZT688b6thIBenG/N4OB5B4InciYBCVyGnEBHO+/LH3SFKQuF4OEs/51ndXMXC8Ajqknrcg1O5PGa2h4CJUqVES0OO7sYevv2qoFBmJ/4gF4boaOrg6rPLYWaYiVfDo0my8w5uj12PQleB0vcp5I6HsHAUoqUhR29zH+5B4IxNTvDmxljy3x2YCYUwZVlbzXJh9UKeQY6t2m0Lt94Oh5loPdqK3EkjzZi4MM/Y9Db3MTv/mYWVxaqkw9IOATNR7B5ABHPrZQrtg9sb8XDKa1+QOwsri4zeHD9SAzE1wxBTXz9xtvMc5ZU5lirLSKIz18nJnhOZjb22YKkhd4odg5icpcoyL669TAAujlyIvmPHSWXY1ti1AmZ8mJ3ElP1ips1/YM3H300g+W+51nc95YPEX8fEbdA2ReVYAAAAAElFTkSuQmCC';
return $this->_options['image_path'] . '/unknown.png';
break;
}
} | Returns path to the specific icon
@return string | entailment |
protected function _headerOutput()
{
$collapsed = isset($_COOKIE['ZFDebugCollapsed']) ? $_COOKIE['ZFDebugCollapsed'] : '';
if ($collapsed) {
$boxheight = isset($_COOKIE['ZFDebugHeight']) ? $_COOKIE['ZFDebugHeight'] : '240';
} else {
$boxheight = '32';
}
return ('
<style type="text/css" media="screen">
html,body {height:100%}
#ZFDebug, #ZFDebug div, #ZFDebug span, #ZFDebug h1, #ZFDebug h2, #ZFDebug h3, #ZFDebug h4, #ZFDebug h5, #ZFDebug h6, #ZFDebug p, #ZFDebug blockquote, #ZFDebug pre, #ZFDebug a, #ZFDebug code, #ZFDebug em, #ZFDebug img, #ZFDebug strong, #ZFDebug dl, #ZFDebug dt, #ZFDebug dd, #ZFDebug ol, #ZFDebug ul, #ZFDebug li, #ZFDebug table, #ZFDebug tbody, #ZFDebug tfoot, #ZFDebug thead, #ZFDebug tr, #ZFDebug th, #ZFDebug td {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-size: 100%;
vertical-align: baseline;
background: transparent;
}
#ZFDebug_offset {height:'.$boxheight.'px}
#ZFDebug {height:'.$boxheight.'px; width:100%; background:#262626;
font: 12px/1.4em Lucida Grande, Lucida Sans Unicode, sans-serif;
position:fixed; bottom:0px; left:0px; color:#FFF; background:#000000;
z-index:2718281828459045;}
#ZFDebug p {margin:1em 0}
#ZFDebug a {color:#FFFFFF}
#ZFDebug tr {color:#FFFFFF;}
#ZFDebug td {vertical-align:top; padding-bottom:1em}
#ZFDebug ol {margin:1em 0 0 0; padding:0; list-style-position: inside;}
#ZFDebug li {margin:0;}
#ZFDebug .clickable {cursor:pointer}
#ZFDebug #ZFDebug_info {display:block; height:32px;
background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAyCAMAAABSxbpPAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACFQTFRFFhYWIyMjGhoaHBwcJSUlExMTFBQUHx8fISEhGBgYJiYmWIZXxwAAAC5JREFUeNrsxskNACAMwLBAucr+A/OLWAEJv0wXQ1xSVBFiiiWKaGLr96EeAQYA2KMRY8RL/qEAAAAASUVORK5CYII=) }
#ZFDebug #ZFDebugResize {cursor:row-resize; height:1px; border-top:1px solid #1a1a1a;border-bottom:1px solid #333333; }
#ZFDebug .ZFDebug_span {padding:0 15px; line-height:32px; display:block; float:left}
#ZFDebug .ZFDebug_panel {padding:0px 15px 15px 15px;
font: 11px/1.4em Menlo, Monaco, Lucida Console, monospace;
text-align:left; height:'.($boxheight-50).'px; overflow:auto; display:none; }
#ZFDebug h4 {font:bold 12px/1.4em Menlo, Monaco, Lucida Console, monospace; margin:1em 0; color: yellow;}
#ZFDebug .ZFDebug_active {background:#1a1a1a;}
#ZFDebug .ZFDebug_panel .pre {margin:0 0 0 22px}
#ZFDebug_exception { border:1px solid #CD0A0A;display: block; }
</style>
<script type="text/javascript">
var ZFDebugLoad = window.onload;
window.onload = function(){
if (ZFDebugLoad) {
ZFDebugLoad();
}
if ("'.$collapsed.'" != "") {
ZFDebugPanel("' . $collapsed . '");
}
window.zfdebugHeight = "'.(isset($_COOKIE['ZFDebugHeight']) ? $_COOKIE['ZFDebugHeight'] : '240').'";
document.onmousemove = function(e) {
var event = e || window.event;
window.zfdebugMouse = Math.max(40, Math.min(window.innerHeight, -1*(event.clientY-window.innerHeight-32)));
}
var ZFDebugResizeTimer = null;
document.getElementById("ZFDebugResize").onmousedown=function(e){
ZFDebugResize();
ZFDebugResizeTimer = setInterval("ZFDebugResize()",50);
return false;
}
document.onmouseup=function(e){
clearTimeout(ZFDebugResizeTimer);
}
};
function ZFDebugResize()
{
window.zfdebugHeight = window.zfdebugMouse;
document.cookie = "ZFDebugHeight="+window.zfdebugHeight+";expires=;path=/";
document.getElementById("ZFDebug").style.height = window.zfdebugHeight+"px";
document.getElementById("ZFDebug_offset").style.height = window.zfdebugHeight+"px";
var panels = document.getElementById("ZFDebug").children;
for (var i=0; i < document.getElementById("ZFDebug").childElementCount; i++) {
if (panels[i].className.indexOf("ZFDebug_panel") == -1)
continue;
panels[i].style.height = window.zfdebugHeight-50+"px";
}
}
var ZFDebugCurrent = null;
function ZFDebugPanel(name) {
if (ZFDebugCurrent == name) {
document.getElementById("ZFDebug").style.height = "32px";
document.getElementById("ZFDebug_offset").style.height = "32px";
ZFDebugCurrent = null;
document.cookie = "ZFDebugCollapsed=;expires=;path=/";
} else {
document.getElementById("ZFDebug").style.height = window.zfdebugHeight+"px";
document.getElementById("ZFDebug_offset").style.height = window.zfdebugHeight+"px";
ZFDebugCurrent = name;
document.cookie = "ZFDebugCollapsed="+name+";expires=;path=/";
}
var panels = document.getElementById("ZFDebug").children;
for (var i=0; i < document.getElementById("ZFDebug").childElementCount; i++) {
if (panels[i].className.indexOf("ZFDebug_panel") == -1)
continue;
if (ZFDebugCurrent && panels[i].id == name) {
document.getElementById("ZFDebugInfo_"+name.substring(8)).className += " ZFDebug_active";
panels[i].style.display = "block";
panels[i].style.height = (window.zfdebugHeight-50)+"px";
} else {
var element = document.getElementById("ZFDebugInfo_"+panels[i].id.substring(8));
element.className = element.className.replace("ZFDebug_active", "");
panels[i].style.display = "none";
}
}
}
</script>
');
} | Returns html header for the Debug Bar
@return string | entailment |
protected function _output($html)
{
$html = "<div id='ZFDebug_offset'></div>\n<div id='ZFDebug'>\n$html\n</div>\n</body>";
$response = $this->getResponse();
// $response->setBody(preg_replace('/(<\/head>)/i', $this->_headerOutput() . '$1', $response->getBody()));
$response->setBody(str_ireplace('</body>', $this->_headerOutput() . $html, $response->getBody()));
} | Appends Debug Bar html output to the original page
@param string $html
@return void | entailment |
public function answerImportAction()
{
$controller = 'answers';
$importLoader = $this->loader->getImportLoader();
$params['defaultImportTranslator'] = $importLoader->getDefaultTranslator($controller);
$params['formatBoxClass'] = 'browser table';
$params['importer'] = $importLoader->getImporter($controller);
$params['importLoader'] = $importLoader;
$params['tempDirectory'] = $importLoader->getTempDirectory();
$params['importTranslators'] = $importLoader->getTranslators($controller);
$this->addSnippets('Survey_AnswerImportSnippet', $params);
} | Import answers to a survey | entailment |
public function calculateDuration($value, $isNew = false, $name = null, array $context = array(), $isPost = false)
{
$surveyId = isset($context['gsu_id_survey']) ? $context['gsu_id_survey'] : false;
if (! $surveyId) {
return $this->_('incalculable');
}
$fields['cnt'] = 'COUNT(DISTINCT gto_id_token)';
$fields['avg'] = 'AVG(CASE WHEN gto_duration_in_sec > 0 THEN gto_duration_in_sec ELSE NULL END)';
$fields['std'] = 'STDDEV_POP(CASE WHEN gto_duration_in_sec > 0 THEN gto_duration_in_sec ELSE NULL END)';
$select = $this->loader->getTracker()->getTokenSelect($fields);
$select->forSurveyId($surveyId)
->onlyCompleted();
$row = $select->fetchRow();
if ($row) {
$trs = $this->util->getTranslated();
$seq = new \MUtil_Html_Sequence();
$seq->setGlue(\MUtil_Html::create('br', $this->view));
$seq->sprintf($this->_('Answered surveys: %d.'), $row['cnt']);
$seq->sprintf(
$this->_('Average answer time: %s.'),
$row['cnt'] ? $trs->formatTimeUnknown($row['avg']) : $this->_('n/a')
);
$seq->sprintf(
$this->_('Standard deviation: %s.'),
$row['cnt'] ? $trs->formatTimeUnknown($row['std']) : $this->_('n/a')
);
if ($row['cnt']) {
// Picked solution from http://stackoverflow.com/questions/1291152/simple-way-to-calculate-median-with-mysql
$sql = "SELECT t1.gto_duration_in_sec as median_val
FROM (SELECT @rownum:=@rownum+1 as `row_number`, gto_duration_in_sec
FROM gems__tokens, (SELECT @rownum:=0) r
WHERE gto_id_survey = ? AND gto_completion_time IS NOT NULL
ORDER BY gto_duration_in_sec
) AS t1,
(SELECT count(*) as total_rows
FROM gems__tokens
WHERE gto_id_survey = ? AND gto_completion_time IS NOT NULL
) as t2
WHERE t1.row_number = floor(total_rows / 2) + 1";
$med = $this->db->fetchOne($sql, array($surveyId, $surveyId));
if ($med) {
$seq->sprintf($this->_('Median value: %s.'), $trs->formatTimeUnknown($med));
}
// \MUtil_Echo::track($row, $med, $sql, $select->getSelect()->__toString());
} else {
$seq->append(sprintf($this->_('Median value: %s.'), $this->_('n/a')));
}
return $seq;
}
} | A ModelAbstract->setOnLoad() function that takes care of transforming a
dateformat read from the database to a \Zend_Date format
If empty or \Zend_Db_Expression (after save) it will return just the value
currently there are no checks for a valid date format.
@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 \MUtil_Date|\Zend_Db_Expr|string | entailment |
public function calculateTrackCount($value, $isNew = false, $name = null, array $context = array(), $isPost = false)
{
$surveyId = isset($context['gsu_id_survey']) ? $context['gsu_id_survey'] : false;
if (! $surveyId) {
return 0;
}
$select = new \Zend_Db_Select($this->db);
$select->from('gems__rounds', array('useCnt' => 'COUNT(*)', 'trackCnt' => 'COUNT(DISTINCT gro_id_track)'));
$select->joinLeft('gems__tracks', 'gtr_id_track = gro_id_track', array())
->where('gro_id_survey = ?', $surveyId);
$counts = $select->query()->fetchObject();
if ($counts && ($counts->useCnt || $counts->trackCnt)) {
return sprintf($this->_('%d times in %d track(s).'), $counts->useCnt, $counts->trackCnt);
} else {
return $this->_('Not in any track.');
}
} | A ModelAbstract->setOnLoad() function that takes care of transforming a
dateformat read from the database to a \Zend_Date format
If empty or \Zend_Db_Expression (after save) it will return just the value
currently there are no checks for a valid date format.
@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 \MUtil_Date|\Zend_Db_Expr|string | entailment |
public function calculateTrackUsage($value, $isNew = false, $name = null, array $context = array(), $isPost = false)
{
$surveyId = isset($context['gsu_id_survey']) ? $context['gsu_id_survey'] : false;
if (! $surveyId) {
return 0;
}
$select = new \Zend_Db_Select($this->db);
$select->from('gems__tracks', array('gtr_track_name'));
$select->joinLeft('gems__rounds', 'gro_id_track = gtr_id_track', array('useCnt' => 'COUNT(*)'))
->where('gro_id_survey = ?', $surveyId)
->group('gtr_track_name');
$usage = $this->db->fetchPairs($select);
if ($usage) {
$seq = new \MUtil_Html_Sequence();
$seq->setGlue(\MUtil_Html::create('br'));
foreach ($usage as $track => $count) {
$seq[] = sprintf($this->plural(
'%d time in %s track.',
'%d times in %s track.',
$count), $count, $track);
}
return $seq;
} else {
return $this->_('Not in any track.');
}
} | A ModelAbstract->setOnLoad() function that takes care of transforming a
dateformat read from the database to a \Zend_Date format
If empty or \Zend_Db_Expression (after save) it will return just the value
currently there are no checks for a valid date format.
@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 \MUtil_Date|\Zend_Db_Expr|string | entailment |
public function checkAction()
{
$surveyId = $this->getSurveyId();
$where = $this->db->quoteInto('gto_id_survey = ?', $surveyId);
$batch = $this->loader->getTracker()->recalculateTokens('surveyCheck' . $surveyId, $this->currentUser->getUserId(), $where);
$title = sprintf($this->_('Checking for the %s survey for answers .'),
$this->db->fetchOne("SELECT gsu_survey_name FROM gems__surveys WHERE gsu_id_survey = ?", $surveyId));
$this->_helper->BatchRunner($batch, $title, $this->accesslog);
$this->addSnippet('Survey\\CheckAnswersInformation',
'itemDescription', $this->_('This task checks all tokens using this survey for answers.')
);
} | Check the tokens for a single survey | entailment |
protected function createModel($detailed, $action)
{
$dbLookup = $this->util->getDbLookup();
$survey = null;
$translated = $this->util->getTranslated();
$yesNo = $translated->getYesNo();
if ($detailed) {
$surveyId = $this->_getIdParam();
if ($surveyId) {
$survey = $this->loader->getTracker()->getSurvey($surveyId);
}
}
$model = new \Gems_Model_JoinModel('surveys', 'gems__surveys', 'gus');
$model->addTable('gems__sources', array('gsu_id_source' => 'gso_id_source'));
$model->setCreate(false);
$model->addColumn(
"CASE WHEN gsu_survey_pdf IS NULL OR CHAR_LENGTH(gsu_survey_pdf) = 0 THEN 0 ELSE 1 END",
'gsu_has_pdf'
);
$model->addColumn(
sprintf(
"CASE WHEN (gsu_status IS NULL OR gsu_status = '') THEN '%s' ELSE gsu_status END",
$this->_('OK')
),
'gsu_status_show',
'gsu_status'
);
$model->addColumn(
"CASE WHEN gsu_surveyor_active THEN '' ELSE 'deleted' END",
'row_class'
);
$model->resetOrder();
$model->set('gsu_survey_name', 'label', $this->_('Name'),
'elementClass', 'Exhibitor'
);
$model->set('gsu_survey_description', 'label', $this->_('Description'),
'elementClass', 'Exhibitor',
'formatFunction', array(__CLASS__, 'formatDescription')
);
$model->set('gso_source_name', 'label', $this->_('Source'),
'elementClass', 'Exhibitor');
$model->set('gsu_surveyor_active', 'label', $this->_('Active in source'),
'elementClass', 'Exhibitor',
'multiOptions', $yesNo
);
$model->set('gsu_surveyor_id', 'label', $this->_('Source survey id'),
'elementClass', 'Exhibitor'
);
$model->set('gsu_status_show', 'label', $this->_('Status in source'),
'elementClass', 'Exhibitor');
$model->set('gsu_active', 'label', sprintf($this->_('Active in %s'), $this->project->getName()),
'elementClass', 'Checkbox',
'multiOptions', $yesNo
);
$model->set('gsu_id_primary_group', 'label', $this->_('Group'),
'description', $this->_('If empty, survey will never show up!'),
'multiOptions', $dbLookup->getGroups()
);
if ($detailed) {
$model->addDependency('CanEditDependency', 'gsu_surveyor_active', array('gsu_active'));
$model->set('gsu_active',
'validators[group]', new \MUtil_Validate_Require(
$model->get('gsu_active', 'label'),
'gsu_id_primary_group',
$model->get('gsu_id_primary_group', 'label')
));
}
$model->set('gsu_insertable', 'label', $this->_('Insertable'),
'description', $this->_('Can this survey be manually inserted into a track?'),
'elementClass', 'Checkbox',
'multiOptions', $yesNo,
'onclick', 'this.form.submit()'
);
if ($detailed) {
$model->set('gsu_valid_for_length', 'label', $this->_('Add to inserted end date'),
'description', $this->_('Add to the start date to calculate the end date when inserting.'),
'filter', 'Int'
);
$model->set('gsu_valid_for_unit', 'label', $this->_('Inserted end date unit'),
'description', $this->_('The unit used to calculate the end date when inserting the survey.'),
'multiOptions', $translated->getPeriodUnits()
);
$model->set('gsu_insert_organizations', 'label', $this->_('Insert organizations'),
'description', $this->_('The organizations where the survey may be inserted.'),
'elementClass', 'MultiCheckbox',
'multiOptions', $dbLookup->getOrganizations(),
'required', true
);
$ct = new \MUtil_Model_Type_ConcatenatedRow('|', $this->_(', '));
$ct->apply($model, 'gsu_insert_organizations');
if (($action == 'create') || ($action == 'edit')) {
$model->set('toggleOrg',
'elementClass', 'ToggleCheckboxes',
'selectorName', 'gsu_insert_organizations'
);
}
$switches = array(
0 => array(
'gsu_valid_for_length' => array('elementClass' => 'Hidden', 'label' => null),
'gsu_valid_for_unit' => array('elementClass' => 'Hidden', 'label' => null),
'gsu_insert_organizations' => array('elementClass' => 'Hidden', 'label' => null),
'toggleOrg' => array('elementClass' => 'Hidden', 'label' => null),
),
);
$model->addDependency(array('ValueSwitchDependency', $switches), 'gsu_insertable');
}
if ($detailed) {
$model->set('track_usage', 'label', $this->_('Usage'),
'elementClass', 'Exhibitor',
'noSort', true,
'no_text_search', true
);
$model->setOnLoad('track_usage', array($this, 'calculateTrackUsage'));
$model->set('calc_duration', 'label', $this->_('Duration calculated'),
'elementClass', 'Html',
'noSort', true,
'no_text_search', true
);
$model->setOnLoad('calc_duration', array($this, 'calculateDuration'));
$model->set('gsu_duration', 'label', $this->_('Duration description'),
'description', $this->_('Text to inform the respondent, e.g. "20 seconds" or "1 minute".')
);
if ($survey instanceof \Gems_Tracker_Survey) {
$surveyFields = $this->util->getTranslated()->getEmptyDropdownArray() +
$survey->getQuestionList($this->locale->getLanguage());
$model->set('gsu_result_field', 'label', $this->_('Result field'),
'multiOptions', $surveyFields
);
// $model->set('gsu_agenda_result', 'label', $this->_('Agenda field'));
}
} else {
$model->set('track_count', 'label', ' ',
'elementClass', 'Exhibitor',
'noSort', true,
'no_text_search', true
);
$model->setOnLoad('track_count', array($this, 'calculateTrackCount'));
}
$model->set('gsu_code', 'label', $this->_('Survey code'),
'description', $this->_('Optional code name to link the survey to program code.'),
'size', 10);
$model->set('gsu_export_code', 'label', $this->_('Survey export code'),
'description', $this->_('A unique code indentifying this survey during track import'),
'size', 20);
if ($detailed) {
$events = $this->loader->getEvents();
$beforeOptions = $events->listSurveyBeforeAnsweringEvents();
if (count($beforeOptions) > 1) {
$model->set('gsu_beforeanswering_event', 'label', $this->_('Before answering'),
'multiOptions', $beforeOptions,
'elementClass', 'Select'
);
}
$completedOptions = $events->listSurveyCompletionEvents();
if (count($completedOptions) > 1) {
$model->set('gsu_completed_event', 'label', $this->_('After completion'),
'multiOptions', $completedOptions,
'elementClass', 'Select'
);
}
$displayOptions = $events->listSurveyDisplayEvents();
if (count($displayOptions) > 1) {
$model->set('gsu_display_event', 'label', $this->_('Answer display'),
'multiOptions', $displayOptions,
'elementClass', 'Select'
);
}
if (('show' !== $action) || $survey->hasPdf()) {
// Only the action changes from the current page
// and the right to see the pdf is the same as
// the right to see this page.
$pdfLink = \MUtil_Html::create(
'a',
array($this->getRequest()->getActionKey() => 'pdf'),
array(
'class' => 'pdf',
'target' => '_blank',
'type' => 'application/pdf',
'onclick' => 'event.cancelBubble = true;',
)
);
$model->set('gsu_survey_pdf', 'label', 'Pdf',
'accept', 'application/pdf',
'destination', $this->loader->getPdf()->getUploadDir('survey_pdfs'),
'elementClass', 'File',
'extension', 'pdf',
'filename', $surveyId,
'required', false,
'itemDisplay', $pdfLink,
'validators[pdf]', new \MUtil_Validate_Pdf()
);
}
}
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 getBrowseColumns()
{
$br = \MUtil_Html::create('br');
$output[10] = array('gsu_survey_name', $br, 'gsu_survey_description');
$output[20] = array('gsu_surveyor_active', \MUtil_Html::raw($this->_(' [')), 'gso_source_name',
\MUtil_Html::raw($this->_(']')), $br, 'gsu_status_show', $br, 'gsu_insertable');
$output[30] = array('gsu_active', \MUtil_Html::raw(' '), 'track_count', $br, 'gsu_id_primary_group');
$output[40] = array('gsu_surveyor_id', $br, 'gsu_code', $br, 'gsu_export_code');
return $output;
} | Set column usage to use for the browser.
Must be an array of arrays containing the input for TableBridge->setMultisort()
@return array or false | entailment |
public function getSurveyId()
{
$id = $this->_getIdParam();
$survey = $this->loader->getTracker()->getSurvey($id);
$this->menu->getParameterSource()->offsetSet('gsu_active', $survey->isActive() ? 1 : 0);
return $id;
} | Return the survey id (and set a menu var)
@return int | entailment |
public function pdfAction()
{
// Make sure nothing else is output
$this->initRawOutput();
// Output the PDF
$this->loader->getPdf()->echoPdfBySurveyId($this->_getParam(\MUtil_Model::REQUEST_ID));
} | Open pdf linked to survey | entailment |
public function getHtmlOutput(\Zend_View_Abstract $view)
{
$snippets = array();
$data = $this->getModel()->load();
// Find the first token with answers
foreach($data as $tokenData) {
$token = $this->loader->getTracker()->getToken($tokenData)->refresh();
$tokenAnswers = $token->getRawAnswers();
if (!empty($tokenAnswers)) {
break;
}
}
// Some spacing with previous elements
$snippets[] = \MUtil_Html::create()->p(\MUtil_Html::raw(' '), array('style'=>'clear:both;'));
$config = $this->getConfig($token);
// Fallback to all score elements in one chart when no config found
if (! is_array($config)) {
$config = array();
foreach ($tokenAnswers as $key => $value)
{
if (substr(strtolower($key),0,5) == 'score') {
$config[0]['question_code'][] = $key;
}
}
}
// Set the default options
$defaultOptions = array(
'data'=>$data,
'showHeaders' => false,
'showButtons' => false
);
// Add all configured charts
foreach ($config as $chartOptions) {
$chartOptions = $chartOptions + $defaultOptions;
$snippets[] = $this->loader->getSnippetLoader($this)->getSnippet('Survey_Display_BarChartSnippet', $chartOptions);
}
// Clear the floats
$snippets[] = \MUtil_Html::create()->p(array('class'=>'chartfooter'));
return $snippets;
} | Copied from parent, but insert chart instead of table after commented out part
@param \Zend_View_Abstract $view
@return type | entailment |
public function getConfig($token)
{
try {
$trackId = $token->getTrackId();
$roundId = $token->getRoundId();
$db = \Zend_Db_Table::getDefaultAdapter();
$select = $db->select()->from('gems__chart_config')
->where('gcc_tid = ?', $trackId)
->where('gcc_rid = ?', $roundId);
if ($result = $select->query()->fetch()) {
$config = \Zend_Json::decode($result['gcc_config']);
return $config;
}
$surveyId = $token->getSurveyId();
$select = $db->select()->from('gems__chart_config')
->where('gcc_sid = ?', $surveyId);
if ($result = $select->query()->fetch()) {
$config = \Zend_Json::decode($result['gcc_config']);
return $config;
}
$surveyCode = $token->getSurvey()->getCode();
$select = $db->select()->from('gems__chart_config')
->where('gcc_code = ?', $surveyCode);
$config = $select->query()->fetch();
if ($config !== false) {
$config = \Zend_Json::decode($config['gcc_config']);
}
return $config;
} catch (\Exception $exc) {
// Just ignore...
}
// If all fails, we might be missing the config table
return false;
} | Get config options for this token
Order of reading is track/round, survey, survey code
@param \Gems_Tracker_Token $token | entailment |
public function getHtmlOutput(\Zend_View_Abstract $view)
{
$html = $this->getHtmlSequence();
$html->h2($this->_('Thank you for subscribing!'));
return $html;
} | Create the snippets content
This is a stub function either override getHtmlOutput() or override render()
@param \Zend_View_Abstract $view Just in case it is needed here
@return \MUtil_Html_HtmlInterface Something that can be rendered | entailment |
public function getHtmlOutput(\Zend_View_Abstract $view)
{
if ($this->roundId) {
$htmlDiv = \MUtil_Html::div();
if ($this->showTitle) {
$htmlDiv->h3(sprintf($this->_('%s round'), $this->trackEngine->getName()));
}
$table = parent::getHtmlOutput($view);
$this->applyHtmlAttributes($table);
// Make sure deactivated rounds are show as deleted
foreach ($table->tbody() as $tr) {
$skip = true;
foreach ($tr as $td) {
if ($skip) {
$skip = false;
} else {
$td->appendAttrib('class', $table->getRepeater()->row_class);
}
}
}
if ($this->showMenu) {
$table->tfrow($this->getMenuList(), array('class' => 'centerAlign'));
}
$htmlDiv[] = $table;
return $htmlDiv;
} else {
$this->addMessage($this->_('No round specified.'));
}
} | Create the snippets content
This is a stub function either override getHtmlOutput() or override render()
@param \Zend_View_Abstract $view Just in case it is needed here
@return \MUtil_Html_HtmlInterface Something that can be rendered | entailment |
protected function getMenuList()
{
$links = $this->menu->getMenuList();
$links->addParameterSources($this->request, $this->menu->getParameterSource());
$source = new \Gems_Menu_ParameterSource(array(
'gro_id_track' => $this->trackId,
'gro_id_round' => $this->trackEngine->getPreviousRoundId($this->roundId),
));
$links->append($this->menu->getCurrent()->toActionLink(true, \MUtil_Html::raw($this->_('< Previous')), $source));
$links->addCurrentParent($this->_('Cancel'));
$links->addCurrentChildren();
$links->addCurrentSiblings();
$source->offsetSet('gro_id_round', $this->trackEngine->getNextRoundId($this->roundId));
$links->append($this->menu->getCurrent()->toActionLink(true, \MUtil_Html::raw($this->_('Next >')), $source));
return $links;
} | overrule to add your own buttons.
@return \Gems_Menu_MenuList | entailment |
protected function addModelSettings(array &$settings)
{
$empty = $this->util->getTranslated()->getEmptyDropdownArray();
$settings['elementClass'] = 'Select';
$settings['multiOptions'] = $empty + $this->getLookup();
} | 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 calculateFieldInfo($currentValue, array $fieldData)
{
if (! $currentValue) {
return $currentValue;
}
$lookup = $this->getLookup();
if (isset($lookup[$currentValue])) {
return $lookup[$currentValue];
}
return null;
} | Calculation the field info display for this type
@param array $currentValue The current value
@param array $fieldData The other values loaded so far
@return mixed the new value | entailment |
public function calculateFieldValue($currentValue, array $fieldData, array $trackData)
{
$calcUsing = $this->getCalculationFields($fieldData);
if ($calcUsing) {
$agenda = $this->getAgenda();
// Get the used fields with values
foreach (array_filter($calcUsing) as $value) {
$appointment = $agenda->getAppointment($value);
if ($appointment->exists) {
return $this->getId($appointment);
}
}
}
return $currentValue;
} | Calculate the field value using the current values
@param array $currentValue The current value
@param array $fieldData The other known field values
@param array $trackData The currently available track data (track id may be empty)
@return mixed the new value | entailment |
protected function getAgenda()
{
if (!$this->agenda) {
$this->agenda = $this->loader->getAgenda();
}
return $this->agenda;
} | Retreive the agenda if not injected
@return \Gems_Agenda | entailment |
public function getDataModelDependyChanges(array $context, $new)
{
if ($this->isReadOnly()) {
return null;
}
$empty = $this->util->getTranslated()->getEmptyDropdownArray();
$output['multiOptions'] = $empty + $this->getLookup($context['gr2t_id_organization']);
return $output;
} | Returns the changes to the model for this field that must be made in an array consisting of
<code>
array(setting1 => $value1, setting2 => $value2, ...),
</code>
By using [] array notation in the setting array key you can append to existing
values.
Use the setting 'value' to change a value in the original data.
When a 'model' setting is set, the workings cascade.
@param array $context The current data this object is dependent on
@param boolean $new True when the item is a new record not yet saved
@return array (setting => value) | entailment |
public function createModel($detailed, $action)
{
$model = new \MUtil_Model_FolderModel(
GEMS_ROOT_DIR . '/var/logs',
null,
$this->recursive
);
if ($this->recursive) {
$model->set('relpath', 'label', $this->_('File (local)'),
'maxlength', 255,
'size', 40,
'validators', array('File_Path', 'File_IsRelativePath')
);
$model->set('filename', 'elementClass', 'Exhibitor');
}
if ($detailed || (! $this->recursive)) {
$model->set('filename', 'label', $this->_('Filename'), 'size', 30, 'maxlength', 255);
}
if ($detailed) {
$model->set('path', 'label', $this->_('Path'), 'elementClass', 'Exhibitor');
$model->set('fullpath', 'label', $this->_('Full name'), 'elementClass', 'Exhibitor');
$model->set('extension', 'label', $this->_('Type'), 'elementClass', 'Exhibitor');
$model->set('content', 'label', $this->_('Content'),
'formatFunction', array(\MUtil_Html::create(), 'pre'),
'elementClass', 'TextArea');
}
$model->set('size', 'label', $this->_('Size'),
'formatFunction', array('MUtil_File', 'getByteSized'),
'elementClass', 'Exhibitor');
$model->set('changed', 'label', $this->_('Changed on'),
'dateFormat', $this->util->getTranslated()->dateTimeFormatString,
'elementClass', 'Exhibitor');
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 deleteAction()
{
$model = $this->getModel();
$model->applyRequest($this->getRequest());
$model->delete();
$this->_reroute(array($this->getRequest()->getActionKey() => 'index', MUTil_Model::REQUEST_ID => null));
} | Confirm has been moved to javascript | entailment |
public function downloadAction()
{
$model = $this->getModel();
$model->applyRequest($this->getRequest());
$fileData = $model->loadFirst();
header('Content-Type: application/x-download');
header('Content-Length: '.$fileData['size']);
header('Content-Disposition: inline; filename="'.$fileData['filename'].'"');
header('Pragma: public');
echo $fileData['content'];
exit();
} | Action for downloading the file | entailment |
public function changePasswordAction()
{
if ($this->changePasswordSnippets) {
$params = $this->_processParameters($this->changePasswordParameters);
$this->addSnippets($this->changePasswordSnippets, $params);
}
} | Allow a user to change his / her password. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.