/**
  * 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
  */
 public function createModel($detailed, $action)
 {
     //
     $model = new \Gems_Model_JoinModel('resptrack', 'gems__respondent2track');
     $model->addTable('gems__respondent2org', array('gr2t_id_user' => 'gr2o_id_user', 'gr2t_id_organization' => 'gr2o_id_organization'));
     $model->addTable('gems__tracks', array('gr2t_id_track' => 'gtr_id_track'));
     $model->addTable('gems__reception_codes', array('gr2t_reception_code' => 'grc_id_reception_code'));
     $model->addFilter(array('grc_success' => 1));
     $model->resetOrder();
     $model->set('gr2o_patient_nr', 'label', $this->_('Respondent nr'));
     $model->set('gr2t_start_date', 'label', $this->_('Start date'), 'dateFormat', 'dd-MM-yyyy');
     $model->set('gr2t_end_date', 'label', $this->_('End date'), 'dateFormat', 'dd-MM-yyyy');
     $filter = $this->getSearchFilter($action !== 'export');
     if (!(isset($filter['gr2t_id_organization']) && $filter['gr2t_id_organization'])) {
         $model->addFilter(array('gr2t_id_organization' => $this->currentUser->getRespondentOrgFilter()));
     }
     if (!(isset($filter['gr2t_id_track']) && $filter['gr2t_id_track'])) {
         $model->setFilter(array('1=0'));
         $this->autofilterParameters['onEmpty'] = $this->_('No track selected...');
         return $model;
     }
     // Add the period filter - if any
     if ($where = \Gems_Snippets_AutosearchFormSnippet::getPeriodFilter($filter, $this->db)) {
         $model->addFilter(array($where));
     }
     $trackId = $filter['gr2t_id_track'];
     $engine = $this->loader->getTracker()->getTrackEngine($trackId);
     $engine->addFieldsToModel($model, false);
     return $model;
 }
 /**
  * Hook that loads the form data from $_POST or the model
  *
  * Or from whatever other source you specify here.
  */
 protected function loadFormData()
 {
     if (!$this->formData) {
         parent::loadFormData();
         $model = $this->getModel();
         $roles = $model->get('ggp_role', 'multiOptions');
         $userRoles = $this->currentUser->getAllowedRoles();
         // \MUtil_Echo::track($userRoles, $roles);
         // Make sure we get the roles as they are labeled
         foreach ($roles as $role => $label) {
             if (!isset($userRoles[$role])) {
                 unset($roles[$role]);
             }
         }
         if ($this->formData['ggp_role'] && !isset($roles[$this->formData['ggp_role']])) {
             if ($this->createData) {
                 $this->formData['ggp_role'] = reset($roles);
             } else {
                 $this->addMessage($this->_('You do not have sufficient privilege to edit this group.'));
                 $this->afterSaveRouteUrl = array($this->request->getActionKey() => 'show');
                 $this->resetRoute = false;
                 return;
             }
         }
         $model->set('ggp_role', 'multiOptions', $roles);
         $this->menu->getParameterSource()->offsetSet('ggp_role', $this->formData['ggp_role']);
     }
 }
 /**
  * Switch the active organization
  */
 public function changeUiAction()
 {
     $request = $this->getRequest();
     $orgId = urldecode($request->getParam('org'));
     $oldOrg = $this->currentUser->getCurrentOrganizationId();
     $origUrl = base64_decode($request->getParam('current_uri'));
     $allowedOrganizations = $this->currentUser->getAllowedOrganizations();
     if (isset($allowedOrganizations[$orgId])) {
         $this->currentUser->setCurrentOrganization($orgId);
         if ($origUrl) {
             // Check for organisation id in url, but not when a patient id is stated
             if (strpos($origUrl, '/' . \MUtil_Model::REQUEST_ID1 . '/') === false) {
                 foreach ($this->currentUser->possibleOrgIds as $key) {
                     $finds[] = '/' . $key . '/' . $oldOrg;
                     $replaces[] = '/' . $key . '/' . $orgId;
                 }
                 $correctUrl = str_replace($finds, $replaces, $origUrl);
             } else {
                 $correctUrl = $origUrl;
             }
             // \MUtil_Echo::track($origUrl, $correctUrl);
             $this->getResponse()->setRedirect($correctUrl);
         } else {
             $this->currentUser->gotoStartPage($this->menu, $request);
         }
         return;
     }
     throw new \Gems_Exception($this->_('Inaccessible or unknown organization'), 403, null, sprintf($this->_('Access to this page is not allowed for current role: %s.'), $this->currentUser->getRole()));
 }
 /**
  * Returns true if and only if $value meets the validation requirements
  *
  * If $value fails validation, then this method returns false, and
  * getMessages() will return an array of messages that explain why the
  * validation failed.
  *
  * @param  mixed $value
  * @param  mixed $content
  * @return boolean
  * @throws \Zend_Validate_Exception If validation of $value is impossible
  */
 public function isValid($value, $context = array())
 {
     $this->_report = $this->_user->reportPasswordWeakness($value);
     foreach ($this->_report as &$report) {
         $report = ucfirst($report) . '.';
     }
     // \MUtil_Echo::track($value, $this->_report);
     return !(bool) $this->_report;
 }
 /**
  * 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
  */
 public function createModel($detailed, $action)
 {
     $model = new \Gems_Model_JoinModel('resptrack', 'gems__respondent2track');
     $model->addTable('gems__respondent2org', array('gr2t_id_user' => 'gr2o_id_user', 'gr2t_id_organization' => 'gr2o_id_organization'));
     $model->addTable('gems__tracks', array('gr2t_id_track' => 'gtr_id_track'));
     $model->addTable('gems__reception_codes', array('gr2t_reception_code' => 'grc_id_reception_code'));
     $model->addFilter(array('grc_success' => 1));
     $model->resetOrder();
     $model->set('gr2o_patient_nr', 'label', $this->_('Respondent nr'));
     $model->set('gr2t_start_date', 'label', $this->_('Start date'), 'dateFormat', 'dd-MM-yyyy');
     $model->set('gr2t_end_date', 'label', $this->_('End date'), 'dateFormat', 'dd-MM-yyyy');
     $filter = $this->getSearchFilter($action !== 'export');
     if (!(isset($filter['gr2t_id_organization']) && $filter['gr2t_id_organization'])) {
         $model->addFilter(array('gr2t_id_organization' => $this->currentUser->getRespondentOrgFilter()));
     }
     if (!(isset($filter['gr2t_id_track']) && $filter['gr2t_id_track'])) {
         $model->setFilter(array('1=0'));
         $this->autofilterParameters['onEmpty'] = $this->_('No track selected...');
         return $model;
     }
     // Add the period filter - if any
     if ($where = \Gems_Snippets_AutosearchFormSnippet::getPeriodFilter($filter, $this->db)) {
         $model->addFilter(array($where));
     }
     $select = $this->db->select();
     $select->from('gems__rounds', array('gro_id_round', 'gro_id_order', 'gro_round_description', 'gro_icon_file'))->joinInner('gems__surveys', 'gro_id_survey = gsu_id_survey', array('gsu_survey_name'))->where('gro_id_track = ?', $filter['gr2t_id_track'])->order('gro_id_order');
     if (isset($filter['gsu_id_primary_group']) && $filter['gsu_id_primary_group']) {
         $select->where('gsu_id_primary_group = ?', $filter['gsu_id_primary_group']);
     }
     $data = $this->db->fetchAll($select);
     if (!$data) {
         return $model;
     }
     $status = $this->util->getTokenData()->getStatusExpression();
     $select = $this->db->select();
     $select->from('gems__tokens', array('gto_id_respondent_track', 'gto_id_round', 'gto_id_token', 'status' => $status))->joinInner('gems__reception_codes', 'gto_reception_code = grc_id_reception_code', array())->where('gto_id_track = ?', $filter['gr2t_id_track'])->order('grc_success')->order('gto_id_respondent_track')->order('gto_round_order');
     // \MUtil_Echo::track($this->db->fetchAll($select));
     $newModel = new \MUtil_Model_SelectModel($select, 'tok');
     $newModel->setKeys(array('gto_id_respondent_track'));
     $transformer = new \MUtil_Model_Transform_CrossTabTransformer();
     $transformer->addCrosstabField('gto_id_round', 'status', 'stat_')->addCrosstabField('gto_id_round', 'gto_id_token', 'tok_');
     foreach ($data as $row) {
         $name = 'stat_' . $row['gro_id_round'];
         $transformer->set($name, 'label', \MUtil_Lazy::call('substr', $row['gsu_survey_name'], 0, 2), 'description', sprintf("%s\n[%s]", $row['gsu_survey_name'], $row['gro_round_description']), 'noSort', true, 'round', $row['gro_round_description'], 'roundIcon', $row['gro_icon_file']);
         $transformer->set('tok_' . $row['gro_id_round']);
     }
     $newModel->addTransformer($transformer);
     // \MUtil_Echo::track($data);
     $joinTrans = new \MUtil_Model_Transform_JoinTransformer();
     $joinTrans->addModel($newModel, array('gr2t_id_respondent_track' => 'gto_id_respondent_track'));
     $model->resetOrder();
     $model->set('gr2o_patient_nr');
     $model->set('gr2t_start_date');
     $model->addTransformer($joinTrans);
     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
  */
 protected function createModel($detailed, $action)
 {
     // Make sure the user is loaded
     $user = $this->getSelectedUser();
     if ($user) {
         if (!($this->currentUser->hasPrivilege('pr.staff.see.all') || $this->currentUser->isAllowedOrganization($user->getBaseOrganizationId()))) {
             throw new \Gems_Exception($this->_('No access to page'), 403, null, sprintf($this->_('You have no right to access users from the organization %s.'), $user->getBaseOrganization()->getName()));
         }
     }
     return parent::createModel($detailed, $action);
 }
 /**
  * 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
  */
 public function execute()
 {
     $batch = $this->getBatch();
     $import = $batch->getVariable('import');
     if (!(isset($import['trackId']) && $import['trackId'])) {
         // Do nothing
         return;
     }
     $tracker = $this->loader->getTracker();
     $trackEngine = $tracker->getTrackEngine($import['trackId']);
     $trackEngine->updateRoundCount($this->currentUser->getUserLoginId());
 }
 public function getHtmlOutput(\Zend_View_Abstract $view)
 {
     $html = $this->getHtmlSequence();
     $html->h1($this->_('Respondent report'));
     $table = $html->table(array('class' => 'browser'));
     $table->th($this->_('Report information'), array('colspan' => 2));
     $table->tr()->th($this->_('Generated by'))->td($this->currentUser->getFullName());
     $table->tr()->th($this->_('Generated on'))->td(new \Zend_Date());
     $table->tr()->th($this->_('Organization'))->td($this->currentOrganization->getName());
     $html->br();
     return $html;
 }
 /**
  * Process the respondent and return true when data has changed.
  *
  * The event has to handle the actual storage of the changes.
  *
  * @param \Gems_Tracker_Respondent $respondent
  * @param int $userId The current user
  * @return boolean True when something changed
  */
 public function processChangedRespondent(\Gems_Tracker_Respondent $respondent)
 {
     $changes = 0;
     $tracker = $this->loader->getTracker();
     $respTracks = $tracker->getRespondentTracks($respondent->getId(), $respondent->getOrganizationId());
     $userId = $this->currentUser->getUserId();
     foreach ($respTracks as $respondentTrack) {
         if ($respondentTrack instanceof \Gems_Tracker_RespondentTrack) {
             $changes += $respondentTrack->checkTrackTokens($userId);
         }
     }
     // \MUtil_Echo::track('Hi there! ' . $changes);
     return (bool) $changes;
 }
 /**
  * Returns a text element for autosearch. Can be overruled.
  *
  * The form / html elements to search on. Elements can be grouped by inserting null's between them.
  * That creates a distinct group of elements
  *
  * @param array $data The $form field values (can be usefull, but no need to set them)
  * @return array Of \Zend_Form_Element's or static tekst to add to the html or null for group breaks.
  */
 protected function getAutoSearchElements(array $data)
 {
     $elements = parent::getAutoSearchElements($data);
     $orgs = $this->currentUser->getRespondentOrganizations();
     if (count($orgs) > 1) {
         $elements[] = $this->_createSelectElement('gap_id_organization', $orgs, $this->_('(all organizations)'));
     }
     $locations = $this->loader->getAgenda()->getLocations();
     if (count($locations) > 1) {
         $elements[] = $this->_createSelectElement('gap_id_location', $locations, $this->_('(all locations)'));
     }
     $elements[] = null;
     $this->_addPeriodSelectors($elements, 'gap_admission_time');
     return $elements;
 }
 /**
  * Check the tokens for all surveys
  */
 public function checkAllAction()
 {
     $batch = $this->loader->getTracker()->recalculateTokens('surveyCheckAll', $this->currentUser->getUserId());
     $title = $this->_('Checking for all surveys for answers .');
     $this->_helper->BatchRunner($batch, $title, $this->accesslog);
     $this->addSnippet('Survey\\CheckAnswersInformation', 'itemDescription', $this->_('This task checks all tokens for all surveys for answers.'));
 }
 /**
  * Add a staff browse edit page to the menu,
  *
  * @param string $label
  * @param array $other
  * @return \Gems_Menu_SubMenuItem
  */
 public function addStaffPage($label, array $other = array())
 {
     if ($this->user->hasPrivilege('pr.staff.edit.all')) {
         $filter = array_keys($this->escort->getUtil()->getDbLookup()->getOrganizations());
     } else {
         $filter = array_keys($this->user->getAllowedOrganizations());
     }
     $page = $this->addPage($label, 'pr.staff', 'staff', 'index', $other);
     $page->addAutofilterAction();
     $createPage = $page->addCreateAction();
     $showPage = $page->addShowAction();
     $pages[] = $showPage->addEditAction();
     $pages[] = $showPage->addAction($this->_('Reset password'), 'pr.staff.edit', 'reset')->setModelParameters(1)->addParameterFilter('gsf_active', 1);
     $showPage->addAction($this->_('Send Mail'), 'pr.staff.edit', 'mail')->setModelParameters(1)->addParameterFilter('can_mail', 1, 'gsf_active', 1, 'gsf_id_organization', $filter);
     $pages = $pages + $showPage->addDeReactivateAction('gsf_active', 1, 0);
     // LOG CONTROLLER
     $logPage = $showPage->addPage($this->_('Activity overview'), 'pr.staff-log', 'staff-log', 'index')->setModelParameters(1)->addParameterFilter('gsf_id_organization', $filter);
     $logPage->addAutofilterAction();
     $logPage->addShowAction()->setModelParameters(1)->addNamedParameters('log', 'gla_id');
     $page->addExportAction();
     $page->addImportAction();
     if (!$this->user->hasPrivilege('pr.staff.edit.all')) {
         foreach ($pages as $sub_page) {
             $sub_page->addParameterFilter('gsf_id_organization', $filter, 'accessible_role', 1);
         }
     }
     return $page;
 }
Exemplo n.º 13
0
 /**
  * Perform automatic job mail
  */
 public function commJob()
 {
     $batch = $this->loader->getTaskRunnerBatch('cron');
     $batch->minimalStepDurationMs = 3000;
     // 3 seconds max before sending feedback
     $batch->autoStart = true;
     if (!$batch->isLoaded()) {
         // Check for unprocessed tokens
         $tracker = $this->loader->getTracker();
         $tracker->processCompletedTokens(null, $this->currentUser->getUserId());
         $batch->addTask('Mail\\AddAllMailJobsTask');
     }
     $title = $this->_('Executing cron jobs');
     $this->_helper->BatchRunner($batch, $title, $this->accesslog);
     $this->html->br();
 }
 /**
  * Overrule this function for any activities you want to take place
  * after the form has successfully been validated, but before any
  * buttons are processed.
  *
  * @param int $step The current step
  */
 protected function afterFormValidationFor($step)
 {
     if (3 == $step) {
         $import = $this->loadImportData();
         $model = $this->getModel();
         $saves = array();
         foreach ($model->getCol('exportCode') as $name => $exportCode) {
             if (isset($this->formData[$name]) && $this->formData[$name]) {
                 $saves[] = array('gsu_id_survey' => $this->formData[$name], 'gsu_export_code' => $exportCode);
                 $import['surveyCodes'][$exportCode] = $this->formData[$name];
             }
         }
         if ($saves) {
             $sModel = new \MUtil_Model_TableModel('gems__surveys');
             \Gems_Model::setChangeFieldsByPrefix($sModel, 'gus', $this->currentUser->getUserId());
             $sModel->saveAll($saves);
             $count = $sModel->getChanged();
             if ($count == 0) {
                 $this->addMessage($this->_('No export code changed'));
             } else {
                 $this->cache->clean(\Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG, array('surveys'));
                 $this->addMessage(sprintf($this->plural('%d export code changed', '%d export codes changed', $count), $count));
             }
         }
     }
 }
 /**
  * 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
  */
 public function hasHtmlOutput()
 {
     $model = $this->getModel();
     $data = $model->loadFirst();
     $roles = $this->currentUser->getAllowedRoles();
     //\MUtil_Echo::track($data);
     // Perform access check here, before anything has happened!!!
     if (isset($data['ggp_role']) && !isset($roles[$data['ggp_role']])) {
         $this->addMessage($this->_('You do not have sufficient privilege to edit this group.'));
         $this->afterSaveRouteUrl = array($this->request->getActionKey() => 'show');
         $this->resetRoute = false;
         return false;
     }
     $this->menu->getParameterSource()->offsetSet('ggp_role', $data['ggp_role']);
     return parent::hasHtmlOutput();
 }
 /**
  * Hook containing the actual save code.
  *
  * Call's afterSave() for user interaction.
  *
  * @see afterSave()
  */
 protected function saveData()
 {
     $model = $this->getModel();
     $userId = $this->currentUser->getUserId();
     $tokenData = array();
     $copyFields = array('gto_id_round', 'gto_valid_from', 'gto_valid_from_manual', 'gto_valid_until', 'gto_valid_until_manual', 'gto_comment', 'gto_id_relationfield');
     foreach ($copyFields as $name) {
         if (array_key_exists($name, $this->formData)) {
             if ($model->hasOnSave($name)) {
                 $tokenData[$name] = $model->getOnSave($this->formData[$name], $this->createData, $name, $this->formData);
             } elseif ('' === $this->formData[$name]) {
                 $tokenData[$name] = null;
             } else {
                 $tokenData[$name] = $this->formData[$name];
             }
         } else {
             $tokenData[$name] = null;
         }
     }
     $rounds = $model->get('gto_round_order', 'multiOptions');
     $tokenData['gto_id_round'] = '0';
     $tokenData['gto_round_order'] = $this->formData['gto_round_order'];
     $tokenData['gto_round_description'] = $rounds[$this->formData['gto_round_order']];
     $surveyId = $this->formData['gto_id_survey'];
     $this->token = $this->respondentTrack->addSurveyToTrack($surveyId, $tokenData, $userId);
     $changed = 1;
     // Communicate with the user
     $this->afterSave($changed);
 }
 /**
  * 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
  */
 protected function createModel($detailed, $action)
 {
     $dbLookup = $this->util->getDbLookup();
     $dbTracks = $this->util->getTrackData();
     $translated = $this->util->getTranslated();
     $empty = $translated->getEmptyDropdownArray();
     $unselected = array('' => '');
     $model = new \MUtil_Model_TableModel('gems__comm_jobs');
     \Gems_Model::setChangeFieldsByPrefix($model, 'gcj');
     $model->set('gcj_id_message', 'label', $this->_('Template'), 'multiOptions', $unselected + $dbLookup->getCommTemplates('token'));
     $model->set('gcj_id_user_as', 'label', $this->_('By staff member'), 'multiOptions', $unselected + $dbLookup->getActiveStaff(), 'default', $this->currentUser->getUserId(), 'description', $this->_('Used for logging and possibly from address.'));
     $model->set('gcj_active', 'label', $this->_('Active'), 'multiOptions', $translated->getYesNo(), 'elementClass', 'Checkbox', 'required', true, 'description', $this->_('Job is only run when active.'));
     $fromMethods = $unselected + $this->getBulkMailFromOptions();
     $model->set('gcj_from_method', 'label', $this->_('From address used'), 'multiOptions', $fromMethods);
     if ($detailed) {
         $model->set('gcj_from_fixed', 'label', $this->_('From other'), 'description', sprintf($this->_("Only when '%s' is '%s'."), $model->get('gcj_from_method', 'label'), end($fromMethods)));
     }
     $model->set('gcj_process_method', 'label', $this->_('Processing Method'), 'default', 'O', 'multiOptions', $translated->getBulkMailProcessOptions());
     $model->set('gcj_filter_mode', 'label', $this->_('Filter for'), 'multiOptions', $unselected + $this->getBulkMailFilterOptions());
     // If you really want to see this information in the overview, uncomment for the shorter labels
     // $model->set('gcj_filter_days_between', 'label', $this->_('Interval'), 'validators[]', 'Digits');
     // $model->set('gcj_filter_max_reminders','label', $this->_('Max'), 'validators[]', 'Digits');
     $model->set('gcj_id_track', 'label', $this->_('Track'), 'multiOptions', $empty + $dbTracks->getAllTracks());
     $defaultRounds = $empty + $this->db->fetchPairs('SELECT gro_round_description, gro_round_description FROM gems__rounds WHERE gro_round_description IS NOT NULL AND gro_round_description != "" GROUP BY gro_round_description');
     $model->set('gcj_round_description', 'label', $this->_('Round'), 'multiOptions', $defaultRounds, 'variableSelect', array('source' => 'gcj_id_track', 'baseQuery' => $this->roundDescriptionQuery, 'ajax' => array('controller' => 'comm-job', 'action' => 'roundselect'), 'firstValue' => $empty, 'defaultValues' => $defaultRounds));
     $model->set('gcj_id_survey', 'label', $this->_('Survey'), 'multiOptions', $empty + $dbTracks->getAllSurveys());
     if ($detailed) {
         $model->set('gcj_filter_days_between', 'label', $this->_('Days between reminders'), 'description', $this->_('1 day means the reminder is send the next day'), 'validators[]', 'Digits');
         $model->set('gcj_filter_max_reminders', 'label', $this->_('Maximum reminders'), 'description', $this->_('1 means only one reminder will be send'), 'validators[]', 'Digits');
         $model->set('gcj_id_organization', 'label', $this->_('Organization'), 'multiOptions', $empty + $dbLookup->getOrganizations());
     }
     return $model;
 }
Exemplo n.º 18
0
 /**
  * Go directly to url
  */
 public function toSurveyAction()
 {
     if (!$this->_initToken()) {
         // Default option
         $this->_forward('index');
         return;
     }
     $language = $this->locale->getLanguage();
     try {
         $url = $this->token->getUrl($language, $this->currentUser->getUserId() ? $this->currentUser->getUserId() : $this->token->getRespondentId());
         /************************
          * Optional user logout *
          ************************/
         if ($this->currentUser->isLogoutOnSurvey()) {
             $this->currentUser->unsetAsCurrentUser();
         }
         // Redirect at once
         header('Location: ' . $url);
         exit;
     } catch (\Gems_Tracker_Source_SurveyNotFoundException $e) {
         $this->addMessage(sprintf($this->_('The survey for token %s is no longer active.'), strtoupper($this->tokenId)));
         // Default option
         $this->_forward('index');
     }
 }
 /**
  * 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
  */
 public function createModel($detailed, $action)
 {
     $filter = $this->getSearchFilter($action !== 'export');
     // Return empty model when no track sel;ected
     if (!(isset($filter['gtf_id_track']) && $filter['gtf_id_track'])) {
         $model = new \Gems_Model_JoinModel('trackfields', 'gems__track_fields');
         $model->set('gtf_field_name', 'label', $this->_('Name'));
         $model->setFilter(array('1=0'));
         $this->autofilterParameters['onEmpty'] = $this->_('No track selected...');
         return $model;
     }
     $this->trackId = $filter['gtf_id_track'];
     $tracker = $this->loader->getTracker();
     $this->engine = $tracker->getTrackEngine($this->trackId);
     $orgs = $this->currentUser->getRespondentOrgFilter();
     $this->orgWhere = " AND gr2t_id_organization IN (" . implode(", ", $orgs) . ")";
     $sql = "SELECT COUNT(*)\n            FROM gems__respondent2track INNER JOIN gems__reception_codes ON gr2t_reception_code = grc_id_reception_code\n            WHERE gr2t_id_track = ? AND grc_success = 1" . $this->orgWhere;
     $this->trackCount = $this->db->fetchOne($sql, $this->trackId);
     $model = $this->engine->getFieldsMaintenanceModel();
     //$model->setFilter($filter);
     // $model->addColumn(new \Zend_Db_Expr($trackCount), 'trackcount');
     // $model->addColumn(new \Zend_Db_Expr("(SELECT COUNT())"), 'fillcount');
     $model->set('trackcount', 'label', $this->_('Tracks'));
     $model->setOnLoad('trackcount', $this->trackCount);
     $model->set('fillcount', 'label', $this->_('Filled'));
     $model->setOnLoad('fillcount', array($this, 'fillCount'));
     $model->set('emptycount', 'label', $this->_('Empty'));
     $model->setOnLoad('emptycount', array($this, 'emptyCount'));
     $model->set('valuecount', 'label', $this->_('Unique values'));
     $model->setOnLoad('valuecount', array($this, 'valueCount'));
     return $model;
 }
 public function showAction()
 {
     $orgId = $this->_getParam(\MUtil_Model::REQUEST_ID2);
     $patientNr = $this->_getParam(\MUtil_Model::REQUEST_ID1);
     $respId = $this->util->getDbLookup()->getRespondentId($patientNr, $orgId);
     $userId = $this->currentUser->getUserId();
     // Updated gr20_opened
     $this->openedRespondent($patientNr, $orgId, $respId);
     // Check for completed tokens
     $this->loader->getTracker()->processCompletedTokens($respId, $userId, $orgId);
     $model = $this->getModel();
     $model->applyRequest($this->getRequest(), true);
     $data = $model->loadFirst();
     if (!isset($data['grs_id_user'])) {
         $this->addMessage(sprintf($this->_('Unknown %s requested'), $this->getTopic()));
         $this->_reroute(array('action' => 'index'));
         return;
     }
     $params['model'] = $model;
     $params['baseUrl'] = array(\MUtil_Model::REQUEST_ID1 => $this->_getParam(\MUtil_Model::REQUEST_ID1), \MUtil_Model::REQUEST_ID2 => $this->_getParam(\MUtil_Model::REQUEST_ID2));
     $params['buttons'] = $this->createMenuLinks();
     $params['onclick'] = $this->findAllowedMenuItem('edit');
     if ($params['onclick']) {
         $params['onclick'] = $params['onclick']->toHRefAttribute($this->getRequest());
     }
     $params['respondentData'] = $data;
     $this->addSnippets($this->showSnippets, $params);
 }
 /**
  * If the current user is the system user, present a message and don't allow to edit
  *
  * @return boolean
  */
 public function hasHtmlOutput()
 {
     if ($this->currentUser->getUserId() == \Gems_User_UserLoader::SYSTEM_USER_ID) {
         $this->addMessage($this->getNotAllowedMessage());
         return false;
     }
     return parent::hasHtmlOutput();
 }
 /**
  * The place to check if the data set in the snippet is valid
  * to generate the snippet.
  *
  * When invalid data should result in an error, you can throw it
  * here but you can also perform the check in the
  * checkRegistryRequestsAnswers() function from the
  * {@see \MUtil_Registry_TargetInterface}.
  *
  * @return boolean
  */
 public function hasHtmlOutput()
 {
     if (!($this->user->hasAllowedRole() && $this->user->canSetPassword())) {
         $this->addMessage($this->getNotAllowedMessage());
         return false;
     }
     return parent::hasHtmlOutput();
 }
Exemplo n.º 23
0
 /**
  * Get the filter to use with the model for searching including model sorts, etc..
  *
  * @param boolean $useRequest Use the request as source (when false, the session is used)
  * @return array or false
  */
 public function getSearchFilter($useRequest = true)
 {
     $filter = parent::getSearchFilter($useRequest);
     if (!(isset($filter['gsf_id_organization']) && $filter['gsf_id_organization'])) {
         $filter['gsf_id_organization'] = array_keys($this->currentUser->getAllowedOrganizations());
     }
     return $filter;
 }
 /**
  * Overrule this function for any activities you want to take place
  * after the form has successfully been validated, but before any
  * buttons are processed.
  *
  * @param int $step The current step
  */
 protected function afterFormValidationFor($step)
 {
     parent::afterFormValidationFor($step);
     if ($this->trackEngine) {
         if (4 == $step) {
             $import = $this->loadImportData();
             $model = $this->getModel();
             $saves = array();
             $import['deactivateRounds'] = array();
             foreach ($model->getCol('roundId') as $name => $roundId) {
                 $round = $this->trackEngine->getRound($roundId);
                 if (isset($this->formData[$name]) && $this->formData[$name] && $round instanceof Round) {
                     switch ($this->formData[$name]) {
                         case self::ROUND_DEACTIVATE:
                             $import['deactivateRounds'][$roundId] = $round->getFullDescription();
                             break;
                         case self::ROUND_LEAVE:
                             if (isset($import['roundOrderToLine'][$round->getRoundOrder()])) {
                                 $lineNr = $import['roundOrderToLine'][$round->getRoundOrder()];
                                 unset($import['rounds'][$lineNr]);
                             }
                             $import['roundOrders'][$round->getRoundOrder()] = $roundId;
                             break;
                         default:
                             if (isset($import['roundOrderToLine'][$this->formData[$name]])) {
                                 $lineNr = $import['roundOrderToLine'][$this->formData[$name]];
                                 $import['rounds'][$lineNr]['gro_id_round'] = $roundId;
                             }
                             $import['roundOrders'][$this->formData[$name]] = $roundId;
                             break;
                     }
                 }
             }
         }
     } elseif (3 == $step) {
         $import = $this->loadImportData();
         $model = $this->getModel();
         $saves = array();
         foreach ($model->getCol('exportCode') as $name => $exportCode) {
             if (isset($this->formData[$name]) && $this->formData[$name]) {
                 $saves[] = array('gsu_id_survey' => $this->formData[$name], 'gsu_export_code' => $exportCode);
                 $import['surveyCodes'][$exportCode] = $this->formData[$name];
             }
         }
         if ($saves) {
             $sModel = new \MUtil_Model_TableModel('gems__surveys');
             \Gems_Model::setChangeFieldsByPrefix($sModel, 'gus', $this->currentUser->getUserId());
             $sModel->saveAll($saves);
             $count = $sModel->getChanged();
             if ($count == 0) {
                 $this->addMessage($this->_('No export code changed'));
             } else {
                 $this->cache->clean(\Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG, array('surveys'));
                 $this->addMessage(sprintf($this->plural('%d export code changed', '%d export codes changed', $count), $count));
             }
         }
     }
 }
 /**
  * The file name to use for final storage, minus the extension
  *
  * @param string $controller Name of controller (or other id)
  * @return string
  */
 public function getLongtermFileName($controller)
 {
     $date = new \MUtil_Date();
     $name[] = $controller;
     $name[] = $date->toString('YYYY-MM-ddTHH-mm-ss');
     $name[] = preg_replace('/[^a-zA-Z0-9_]/', '', $this->currentUser->getLoginName());
     $name[] = $this->getOrganizationCode();
     return implode('.', array_filter($name));
 }
 /**
  * Synchronize survey status for the surveys in all sources
  */
 public function synchronizeAllAction()
 {
     $batch = $this->loader->getTracker()->synchronizeSources(null, $this->currentUser->getUserId());
     $batch->minimalStepDurationMs = 3000;
     $title = $this->_('Synchronize all sources.');
     $this->_helper->batchRunner($batch, $title, $this->accesslog);
     $this->html->actionLink(array('action' => 'index'), $this->_('Cancel'), array('class' => 'btn-danger'));
     $this->addSynchronizationInformation();
 }
 /**
  * Action for checking all assigned rounds for a single track using a batch
  */
 public function recalcFieldsAction()
 {
     $id = $this->_getIdParam();
     $track = $this->getTrackEngine();
     $where = $this->db->quoteInto('gr2t_id_track = ?', $id);
     $batch = $this->loader->getTracker()->recalcTrackFields('trackRecalcFields' . $id, $this->currentUser->getUserId(), $where);
     $title = sprintf($this->_("Recalculating fields for track '%s'."), $track->getTrackName(), $this->accesslog);
     $this->_helper->BatchRunner($batch, $title, $this->accesslog);
     $this->addRecalcInformation();
 }
 /**
  * The password should not contain the name of the user or the login name.
  *
  * @param mixed $parameter
  * @param string $password
  */
 protected function notTheName($parameter, $password)
 {
     $on = $parameter != 0;
     if ($on) {
         $lpwd = strtolower($password);
         if (false !== strpos($lpwd, strtolower($this->user->getLoginName())) || null === $password) {
             $this->_addError($this->translate->_('should not contain your login name'));
         }
     }
 }
 /**
  * Action for checking all assigned rounds for a single track using a batch
  */
 public function checkTrackAction()
 {
     $id = $this->_getIdParam();
     $track = $this->getTrackEngine();
     $where = $this->db->quoteInto('gr2t_id_track = ?', $id);
     $batch = $this->loader->getTracker()->checkTrackRounds('trackCheckRounds' . $id, $this->currentUser->getUserId(), $where);
     $title = sprintf($this->_("Checking round assignments for track '%s'."), $track->getTrackName());
     $this->_helper->BatchRunner($batch, $title, $this->accesslog);
     $this->addSnippet('Track\\CheckRoundsInformation');
 }
 /**
  * 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
  */
 protected function createModel($detailed, $action)
 {
     // Export all
     if ('excel' === $action) {
         $detailed = true;
     }
     if ($detailed) {
         $year = $this->_('Year');
         $month = $this->_('Month');
         $fields[$year] = new \Zend_Db_Expr("YEAR(gr2o_created)");
         $fields[$month] = new \Zend_Db_Expr("MONTH(gr2o_created)");
     }
     $consents = $this->util->getDbLookup()->getUserConsents();
     $deleteds = array('' => '') + $this->util->getReceptionCodeLibrary()->getRespondentDeletionCodes();
     $sql = "SUM(CASE WHEN grc_success = 1 AND gr2o_consent = '%s' THEN 1 ELSE 0 END)";
     foreach ($consents as $consent => $translated) {
         $fields[$translated] = new \Zend_Db_Expr(sprintf($sql, $consent));
     }
     $fields[$this->_('Total OK')] = new \Zend_Db_Expr("SUM(CASE WHEN grc_success = 1 THEN 1 ELSE 0 END)");
     $sql = "SUM(CASE WHEN gr2o_reception_code = '%s' THEN 1 ELSE 0 END)";
     foreach ($deleteds as $code => $translated) {
         $fields[$translated] = new \Zend_Db_Expr(sprintf($sql, $code));
     }
     $fields[$this->_('Dropped')] = new \Zend_Db_Expr("SUM(CASE WHEN grc_success = 0 THEN 1 ELSE 0 END)");
     $fields[$this->_('Total')] = new \Zend_Db_Expr("COUNT(*)");
     $select = $this->db->select();
     $select->from('gems__respondent2org', $fields)->joinInner('gems__reception_codes', 'gr2o_reception_code = grc_id_reception_code', array())->joinInner('gems__organizations', 'gr2o_id_organization = gor_id_organization', array('gor_name', 'gor_id_organization'));
     $select->group(array('gor_name', 'gor_id_organization'));
     if ($detailed) {
         $select->group(array($fields[$year], $fields[$month]));
     }
     $model = new \MUtil_Model_SelectModel($select, 'consent-plan');
     $model->setKeys(array('gor_id_organization'));
     $model->resetOrder();
     $model->set('gor_name', 'label', $this->_('Organization'));
     foreach ($fields as $field => $expr) {
         $model->set($field, 'label', $field, 'tdClass', 'rightAlign', 'thClass', 'rightAlign');
     }
     foreach ($deleteds as $code => $translated) {
         $model->set($translated, 'tdClass', 'rightAlign smallTime', 'thClass', 'rightAlign smallTime');
     }
     foreach (array($this->_('Total OK'), $this->_('Dropped'), $this->_('Total')) as $name) {
         $model->set($name, 'itemDisplay', \MUtil_Html::create('strong'), 'tableHeaderDisplay', \MUtil_Html::create('em'), 'tdClass', 'rightAlign selectedColumn', 'thClass', 'rightAlign selectedColumn');
     }
     if ($detailed) {
         $model->set($month, 'formatFunction', $this->util->getLocalized()->getMonthName);
     }
     // Only show organisations the user is allowed to see
     $allowed = $this->currentUser->getAllowedOrganizations();
     $model->setFilter(array('gr2o_id_organization' => array_keys($allowed)));
     // \MUtil_Model::$verbose = true;
     return $model;
 }