/**
  * Now we have the requests answered, add the DatabasePatcher as it needs the db object
  *
  * @return boolean
  */
 public function checkRegistryRequestsAnswers()
 {
     $this->escort = \GemsEscort::getInstance();
     //Load the dbaModel
     $model = new \Gems_Model_DbaModel($this->db, $this->escort->getDatabasePaths());
     if ($this->project->databaseFileEncoding) {
         $model->setFileEncoding($this->project->databaseFileEncoding);
     }
     $this->dbaModel = $model;
     return true;
 }
Example #2
0
 public static function init(\MUtil_Html_Creator $creator = null)
 {
     if (null === $creator) {
         $creator = \MUtil_Html::getCreator();
     }
     // \MUtil_Html::$verbose = true;
     // Set the image directories
     \MUtil_Html_ImgElement::addImageDir('gems/images');
     \MUtil_Html_ImgElement::addImageDir('gems/icons');
     $escort = \GemsEscort::getInstance();
     if (isset($escort->project->imagedir)) {
         \MUtil_Html_ImgElement::addImageDir($escort->project->imagedir);
     }
     // Gems specific element functions
     $creator->addElementFunction('actionDisabled', array(__CLASS__, 'actionDisabled'), 'actionLink', array(__CLASS__, 'actionLink'), 'buttonDiv', array(__CLASS__, 'buttonDiv'), 'pagePanel', array(__CLASS__, 'pagePanel'), 'pInfo', array(__CLASS__, 'pInfo'), 'smallData', array(__CLASS__, 'smallData'));
     // \Gems_Util::callProjectClass('Html', 'init', $creator);
     // Allow in-project overruling
     $projectFile = APPLICATION_PATH . '/classes/' . GEMS_PROJECT_NAME_UC . '/Html.php';
     if (file_exists($projectFile)) {
         include_once $projectFile;
         call_user_func(array(GEMS_PROJECT_NAME_UC . '_Html', 'init'), $creator);
     }
     // */
     return $creator;
 }
 public function formCKEditor($name = null, $value = null, $attribs = null, $options = null)
 {
     // Remove from attribs what we need to have in options
     foreach ($attribs as $key => $val) {
         $method = 'set' . ucfirst($key);
         if (method_exists($this, $method)) {
             $this->{$method}($val);
             unset($attribs[$key]);
         }
     }
     $baseUrl = \GemsEscort::getInstance()->basepath->getBasePath() . '/';
     $this->view->headScript()->appendFile($baseUrl . $this->_basedir . '/' . 'ckeditor.js');
     $this->view->headScript()->prependScript("\r\n            CKEditorConfig = " . \Zend_Json::encode($this->config) . ";\r\n            ");
     //\MUtil_Echo::track($baseUrl);
     //\MUtil_Echo::track('test');
     //
     //$markup = sprintf($this->_format, $id, $name, $value);
     $output = $this->formTextarea($name, $value, $attribs);
     // Get regular textarea output
     $output = sprintf('<div class="ckeditor">%s</div>', $output);
     // Wrap in a div
     $id = $name;
     $this->view->inlineScript()->appendScript("\r\n            if (typeof CKEditorConfig === 'undefined') {\r\n                CKEditorConfig = {};\r\n            }\r\n            CKEDITOR.replace( '{$id}', CKEditorConfig );\r\n        ");
     return $output;
 }
 /**
  * Called after the check that all required registry values
  * have been set correctly has run.
  *
  * @return void
  */
 public function afterRegistry()
 {
     $this->codeVersion = $this->loader->getVersions()->getBuild();
     foreach ($this->escort->getLoaderDirs() as $prefix => $dir) {
         $this->projectDirs[$prefix . '_'] = $prefix;
     }
 }
 /**
  * Now we have the requests answered, add the DatabasePatcher as it needs the db object
  *
  * @return boolean
  */
 public function checkRegistryRequestsAnswers()
 {
     $escort = \GemsEscort::getInstance();
     //As an upgrade almost always includes executing db patches, make a DatabasePatcher object available
     $this->patcher = new \Gems_Util_DatabasePatcher($this->db, 'patches.sql', $escort->getDatabasePaths());
     return parent::checkRegistryRequestsAnswers();
 }
 /**
  * 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;
 }
 /**
  * Action that switches the maintenance lock on or off.
  */
 public function maintenanceAction()
 {
     // Switch lock
     $this->util->getMaintenanceLock()->reverse();
     // Dump the existing maintenance mode messages.
     $this->escort->getMessenger()->clearCurrentMessages();
     $this->escort->getMessenger()->clearMessages();
     \MUtil_Echo::out();
     // Redirect
     $request = $this->getRequest();
     $this->_reroute(array($request->getActionKey() => 'index'));
 }
 /**
  * Initialize the view
  *
  * Make sure the needed javascript is loaded
  *
  * @param \Zend_View $view
  */
 protected function _initView($view)
 {
     $baseUrl = \GemsEscort::getInstance()->basepath->getBasePath();
     // Make sure we can use jQuery
     \MUtil_JQuery::enableView($view);
     // Now add the scrollTo plugin so we can scroll to today
     $view->headScript()->appendFile($baseUrl . '/gems/js/jquery.scrollTo.min.js');
     /*
      * And add some initialization:
      *  - Hide all tokens initially (accessability, when no javascript they should be visible)
      *  - If there is a day labeled today, scroll to it (prevents errors when not visible)
      */
     $view->headScript()->appendFile($baseUrl . '/gems/js/trafficlight.js');
 }
 /**
  * Constructor
  *
  * @param  \Zend_Application|\Zend_Application_Bootstrap_Bootstrapper $application
  * @return void
  */
 public function __construct($application)
 {
     parent::__construct($application);
     self::$_instanceOfSelf = $this;
     // DIRECTORIES USED BY LOADER
     $dirs = $this->getOption('loaderDirs');
     if ($dirs) {
         $newDirs = array();
         foreach ($dirs as $key => $path) {
             if (defined($key)) {
                 $newDirs[constant($key)] = $path;
             } else {
                 $newDirs[$key] = $path;
             }
         }
         $dirs = $newDirs;
     } else {
         global $GEMS_DIRS;
         // Use $GEMS_DIRS if defined
         if (isset($GEMS_DIRS)) {
             $dirs = array();
             foreach ($GEMS_DIRS as $prefix => $dir) {
                 $dirs[$prefix] = $dir . '/' . strtr($prefix, '_', '/');
             }
         } else {
             // Default setting
             $dirs = array(GEMS_PROJECT_NAME_UC => APPLICATION_PATH . '/classes/' . GEMS_PROJECT_NAME_UC, 'Gems' => GEMS_LIBRARY_DIR . '/classes/Gems');
         }
     }
     // \MUtil_Echo::track($dirs);
     $this->_loaderDirs = array_reverse($dirs);
     foreach ($this->_loaderDirs as $prefix => $path) {
         if ($prefix) {
             \MUtil_Model::addNameSpace($prefix);
         }
     }
     // PROJECT LOADER
     $this->_projectLoader = new \MUtil_Loader_PluginLoader($this->_loaderDirs);
     // FIRE BUG
     $firebug = $application->getOption('firebug');
     $this->_startFirebird = $firebug['log'];
     // START SESSIE
     $sessionOptions['name'] = GEMS_PROJECT_NAME_UC . '_' . md5(APPLICATION_PATH) . '_SESSID';
     $sessionOptions['cookie_path'] = strtr(dirname($_SERVER['SCRIPT_NAME']), '\\', '/');
     $sessionOptions['cookie_httponly'] = true;
     $sessionOptions['cookie_secure'] = APPLICATION_ENV == 'production' || APPLICATION_ENV === 'acceptance';
     \Zend_Session::start($sessionOptions);
 }
 /**
  * Action that switches the maintenance lock on or off.
  */
 public function maintenanceAction()
 {
     // Switch lock
     if ($this->util->getMonitor()->reverseMaintenanceMonitor()) {
         $this->accesslog->logChange($this->getRequest(), $this->_('Maintenance mode set ON'));
     } else {
         $this->accesslog->logChange($this->getRequest(), $this->_('Maintenance mode set OFF'));
         // Dump the existing maintenance mode messages.
         $this->escort->getMessenger()->clearCurrentMessages();
         $this->escort->getMessenger()->clearMessages();
         \MUtil_Echo::out();
     }
     // Redirect
     $request = $this->getRequest();
     $this->_reroute(array($request->getActionKey() => 'index'));
 }
 public function render($content)
 {
     $element = $this->getElement();
     $view = $element->getView();
     $baseUrl = \GemsEscort::getInstance()->basepath->getBasePath() . '/';
     $view->headScript()->appendFile($baseUrl . $this->_basedir . '/' . 'ckeditor.js');
     //\MUtil_Echo::track($baseUrl);
     //\MUtil_Echo::track('test');
     $element = $this->getElement();
     $name = htmlentities($element->getFullyQualifiedName());
     $label = htmlentities($element->getLabel());
     $id = htmlentities($element->getId());
     $value = htmlentities($element->getValue());
     $markup = sprintf($this->_format, $id, $name, $value);
     $view = $element->getView();
     $view->inlineScript()->appendScript("\r\n\t\t\tif (typeof CKEditorConfig === 'undefined') {\r\n\t\t\t\tCKEditorConfig = {};\r\n\t\t\t}\r\n\t\t\tCKEDITOR.replace( '{$id}', CKEditorConfig );\r\n\t\t");
     return $markup;
 }
 public function colorPicker($id, $value = '', array $params = array(), array $attribs = array())
 {
     $attribs = $this->_prepareAttributes($id, $value, $attribs);
     if (strlen($value) >= 6) {
         $params['color'] = $value;
     }
     $params['showInput'] = true;
     $params['preferredFormat'] = "hex";
     if (count($params) > 0) {
         $params = \ZendX_JQuery::encodeJson($params);
     } else {
         $params = "{}";
     }
     $js = sprintf('%s("#%s").spectrum(%s);', \ZendX_JQuery_View_Helper_JQuery::getJQueryHandler(), $attribs['id'], $params);
     $this->jquery->addOnLoad($js);
     $baseUrl = \GemsEscort::getInstance()->basepath->getBasePath();
     $this->view->headScript()->appendFile($baseUrl . '/gems/spectrum/spectrum.js');
     $this->view->headLink()->appendStylesheet($baseUrl . '/gems/spectrum/spectrum.css');
     //$z = new \Zend_View_Helper_HeadStyle()->append($baseUrl)
     return $this->view->formText($id, $value, $attribs);
 }
 /**
  *
  * @param \Zend_Db_Adapter_Abstract $db
  * @param array $directories directory => name | \Zend_Db_Adaptor_Abstract | array(['path' =>], 'name' =>, 'db' =>,)
  */
 public function __construct(\Zend_Db_Adapter_Abstract $db, array $directories)
 {
     parent::__construct('DbaModel');
     $this->defaultDb = $db;
     $this->directories = $directories;
     //Grab translate object from the Escort
     $this->translate = \GemsEscort::getInstance()->translate;
     $this->set('group', 'maxlength', 40, 'type', \MUtil_Model::TYPE_STRING);
     $this->set('name', 'key', true, 'maxlength', 40, 'type', \MUtil_Model::TYPE_STRING);
     $this->set('type', 'maxlength', 40, 'type', \MUtil_Model::TYPE_STRING);
     $this->set('order', 'decimals', 0, 'default', self::DEFAULT_ORDER, 'maxlength', 6, 'type', \MUtil_Model::TYPE_NUMERIC);
     $this->set('defined', 'type', \MUtil_Model::TYPE_NUMERIC);
     $this->set('exists', 'type', \MUtil_Model::TYPE_NUMERIC);
     $this->set('state', 'type', \MUtil_Model::TYPE_NUMERIC);
     $this->set('path', 'maxlength', 255, 'type', \MUtil_Model::TYPE_STRING);
     $this->set('fullPath', 'maxlength', 255, 'type', \MUtil_Model::TYPE_STRING);
     $this->set('fileName', 'maxlength', 100, 'type', \MUtil_Model::TYPE_STRING);
     $this->set('script', 'type', \MUtil_Model::TYPE_STRING);
     $this->set('lastChanged', 'type', \MUtil_Model::TYPE_DATETIME);
     $this->set('location', 'maxlength', 12, 'type', \MUtil_Model::TYPE_STRING);
     $this->set('state', 'multiOptions', array(\Gems_Model_DbaModel::STATE_CREATED => $this->_('created'), \Gems_Model_DbaModel::STATE_DEFINED => $this->_('not created'), \Gems_Model_DbaModel::STATE_UNKNOWN => $this->_('unknown')));
 }
 /**
  * Renders the entire report (including layout)
  *
  * @param array|string[] $respondentId
  * @param boolean $group Group same surveys or not
  * @param string $format html|pdf, the output format to use
  */
 public function render($respondents, $group = true, $format = 'html')
 {
     $this->_group = $group;
     $this->html->snippet($this->_reportHeader);
     $respondentCount = count($respondents);
     $respondentIdx = 0;
     foreach ($respondents as $respondentId) {
         $respondentIdx++;
         $this->_exportRespondent($respondentId);
         if ($respondentIdx < $respondentCount) {
             // Add some whitespace between patients
             $this->html->div('', array('style' => 'height: 100px'));
         }
     }
     $this->html->snippet($this->_reportFooter, 'respondents', $respondents);
     $this->menu->setVisible(false);
     if ($this->escort instanceof \Gems_Project_Layout_MultiLayoutInterface) {
         $this->escort->layoutSwitch();
     }
     $this->escort->postDispatch(\Zend_Controller_Front::getInstance()->getRequest());
     \Zend_Controller_Action_HelperBroker::getExistingHelper('layout')->disableLayout();
     \Zend_Controller_Action_HelperBroker::getExistingHelper('viewRenderer')->setNoRender(true);
     $this->view->layout()->content = $this->html->render($this->view);
     $content = $this->view->layout->render();
     if ($format == 'pdf') {
         if (is_array($respondentId) && isset($respondentId['gr2o_id_organization'])) {
             $respondentId = $respondentId['gr2o_patient_nr'];
         }
         $filename = 'respondent-export-' . strtolower($respondentId) . '.pdf';
         $content = $this->_pdf->convertFromHtml($content);
         $this->_pdf->echoPdfContent($content, $filename, true);
     } else {
         echo $content;
     }
     $this->menu->setVisible(true);
 }
 /**
  * Set this organization as teh one currently active
  *
  * @return \Gems_User_Organization (continutation pattern)
  */
 public function setAsCurrentOrganization()
 {
     $organizationId = $this->getId();
     if ($organizationId && !\Gems_Cookies::setOrganization($organizationId, $this->basepath->getBasePath())) {
         throw new \Exception('Cookies must be enabled for this site.');
     }
     $escort = \GemsEscort::getInstance();
     if ($escort instanceof \Gems_Project_Layout_MultiLayoutInterface) {
         $escort->layoutSwitch($this->getStyle());
     }
     return $this;
 }
 /**
  *
  * @return \Gems_Menu
  */
 protected function getMenu()
 {
     if (!$this->menu) {
         $escort = \GemsEscort::getInstance();
         $this->setMenu($escort->menu);
     }
     return $this->menu;
 }
 public function __construct()
 {
     $this->_model = \GemsEscort::getInstance()->getLoader()->getModels()->createRespondentModel();
 }
 /**
  * Sets the user up as a new staff user
  *
  * @param \Gems_User_User $user
  * @param string $password
  */
 protected function makeNewStaffUser(\Gems_User_User $user, $password)
 {
     $staff_id = $user->getUserId();
     $sql = 'SELECT gul_id_user FROM gems__user_logins WHERE gul_can_login = 1 AND gul_login = ? AND gul_id_organization = ?';
     try {
         $user_id = $this->db->fetchOne($sql, array($user->getLoginName(), $user->getBaseOrganizationId()));
         $currentTimestamp = new \MUtil_Db_Expr_CurrentTimestamp();
         // Move to USER_STAFF
         $values['gup_id_user'] = $user_id;
         $values['gup_password'] = $this->hashNewPassword($password);
         $values['gup_reset_key'] = null;
         $values['gup_reset_requested'] = null;
         $values['gup_reset_required'] = 0;
         $values['gup_changed'] = $currentTimestamp;
         $values['gup_changed_by'] = $staff_id;
         $values['gup_created'] = $currentTimestamp;
         $values['gup_created_by'] = $staff_id;
         $this->db->insert('gems__user_passwords', $values);
         // Update user class
         $values = array();
         $values['gul_user_class'] = \Gems_User_UserLoader::USER_STAFF;
         $values['gul_changed'] = $currentTimestamp;
         $values['gul_changed_by'] = $staff_id;
         $this->db->update('gems__user_logins', $values, $this->db->quoteInto('gul_id_user = ?', $user_id));
         // Remove old password
         $values = array();
         $values['gsf_password'] = null;
         $values['gsf_changed'] = $currentTimestamp;
         $values['gsf_changed_by'] = $user_id;
         $this->db->update('gems__staff', $values, $this->db->quoteInto('gsf_id_user = ?', $staff_id));
         $user->refresh(\Gems_User_UserLoader::USER_STAFF);
     } catch (\Zend_Db_Exception $e) {
         \GemsEscort::getInstance()->logger->log($e->getMessage(), \Zend_Log::ERR);
         // Fall through as this does not work if the database upgrade did not run
         // \MUtil_Echo::r($e);
     }
 }
 /**
  * Default login page
  */
 public function loginAction()
 {
     $request = $this->getRequest();
     $form = $this->createLoginForm();
     // Retrieve these before the session is reset
     $staticSession = \GemsEscort::getInstance()->getStaticSession();
     $previousRequestParameters = $staticSession->previousRequestParameters;
     $previousRequestMode = $staticSession->previousRequestMode;
     if ($form->wasSubmitted()) {
         if ($form->isValid($request->getPost(), false)) {
             $user = $form->getUser();
             $user->setAsCurrentUser();
             if ($messages = $user->reportPasswordWeakness($request->getParam($form->passwordFieldName))) {
                 $user->setPasswordResetRequired(true);
                 $this->addMessage($this->_('Your password must be changed.'));
                 foreach ($messages as &$message) {
                     $message = ucfirst($message) . '.';
                 }
                 $this->addMessage($messages);
             }
             /**
              * Fix current locale in cookies
              */
             \Gems_Cookies::setLocale($user->getLocale(), $this->basepath->getBasePath());
             /**
              * Ready
              */
             $this->addMessage(sprintf($this->_('Login successful, welcome %s.'), $user->getFullName()), 'success');
             /**
              * Log the login
              */
             $this->accesslog->logChange($request);
             if ($previousRequestParameters) {
                 $this->_reroute(array('controller' => $previousRequestParameters['controller'], 'action' => $previousRequestParameters['action']), false);
             } else {
                 // This reroutes to the first available menu page after login.
                 //
                 // Do not user $user->gotoStartPage() as the menu is still set
                 // for no login.
                 $this->_reroute(array('controller' => null, 'action' => null), true);
             }
             return;
         } else {
             $errors = \MUtil_Ra::flatten($form->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', $request->getParam($form->usernameFieldName), $request->getParam($form->organizationFieldName), $logErrors);
             $this->accesslog->logChange($request, $msg);
         }
         // */
     } else {
         if ($request->isPost()) {
             $form->populate($request->getPost());
         }
     }
     $this->displayLoginForm($form);
 }
Example #20
0
 public function saveAnswer($file, $remove = true)
 {
     if (!file_exists($file)) {
         throw new \Gems_Exception_Coding(sprintf($this->translate->_('File not found: %s'), $file));
     }
     //We read the xml file
     $xml = simplexml_load_file($file);
     if ($xml === false) {
         throw new \Gems_Exception_Coding(sprintf($this->translate->_('Could not read form definition for form %s'), $file));
     }
     $formId = (string) $xml->attributes()->id;
     if ($formId != $this->getFormID()) {
         //Can not save to this object as it is a different form!
         throw new \Gems_Exception_Coding(sprintf($this->translate->_('Response is for a different formId: %s <-> %s'), $formId, $this->getFormID()));
     }
     $model = $this->getModel();
     $answers = $this->flattenAnswers($xml);
     //Now we should parse the response, extract the options given for a (multi)select
     $output = array();
     foreach ($this->instance as $name => $element) {
         $bindName = $this->_getBindName($name);
         if (array_key_exists($bindName, $this->bind)) {
             $bindInfo = $this->bind[$bindName];
         } else {
             $bindInfo['type'] = 'string';
         }
         if (array_key_exists($bindName, $this->body) && array_key_exists('repeat', $this->body[$bindName])) {
             // CHECK NESTED
             // We found a field that should go into the nested record
             // Now process all answers
             $group = $this->body[$bindName]['repeat'];
             foreach ($answers[$group] as $idx => $element) {
                 if (!array_key_exists($group, $output)) {
                     $output[$group] = array();
                 }
                 if (!array_key_exists($idx, $output[$group])) {
                     $output[$group][$idx] = array();
                 }
                 $output[$group][$idx] = $output[$group][$idx] + $this->_processAnswer($name, $element, $bindInfo['type']);
             }
         } else {
             $output = $output + $this->_processAnswer($name, $answers, $bindInfo['type']);
         }
     }
     $output['orf_id'] = null;
     $answers = $model->save($output);
     if ($model->getChanged() && $remove) {
         $log = \Gems_Log::getLogger();
         $log->log($file . '-->' . substr($file, 0, -4) . '.bak', \Zend_Log::ERR);
         rename($file, substr($file, 0, -4) . '.bak');
     }
     // @@TODO: make hook for respondentID lookup too
     if (isset($answers['token'])) {
         // We receveid a form linked to a token, signal the 'inSource' for this token.
         $loader = GemsEscort::getInstance()->getLoader();
         $token = $loader->getTracker()->getToken($answers['token']);
         $token->getUrl($loader->getCurrentUser()->getLocale(), $loader->getCurrentUser()->getUserId());
     }
     return $answers;
 }
 /**
  * Construct a fieldmap object to add LS source code knowledge and interpretation to the database data about a survey.
  *
  * @param int $sourceSurveyId            Survey ID
  * @param string $language               (ISO) Language
  * @param \Zend_Db_Adapter_Abstract $lsDb The Lime Survey database connection
  * @param \Zend_Translate $translate      A translate object
  * @param type $tablePrefix              The prefix to use for all LS tables (in this installation)
  */
 public function __construct($sourceSurveyId, $language, \Zend_Db_Adapter_Abstract $lsDb, \Zend_Translate $translate, $tablePrefix)
 {
     $this->sourceSurveyId = $sourceSurveyId;
     $this->language = $language;
     $this->lsDb = $lsDb;
     $this->translate = $translate;
     $this->tablePrefix = $tablePrefix;
     $this->cache = \GemsEscort::getInstance()->cache;
     //Load the cache from escort
 }
 public function scanresponsesAction()
 {
     $model = $this->getModel();
     //Perform a scan of the form directory, to update the database of forms
     $eDir = dir($this->responseDir);
     $formCnt = 0;
     $addCnt = 0;
     $files = array();
     $rescan = $this->getRequest()->getParam('rescan', false);
     while (false !== ($filename = $eDir->read())) {
         $ext = substr($filename, -4);
         if ($ext == '.xml' || $ext == '.bak' && $rescan) {
             if ($rescan) {
                 $oldname = $filename;
                 $filename = substr($oldname, 0, -4) . '.xml';
                 rename($this->responseDir . $oldname, $this->responseDir . $filename);
             }
             $files[] = $filename;
             $formCnt++;
         }
     }
     foreach ($files as $filename) {
         $result = $this->processReceivedForm($this->responseDir . $filename);
         if ($result !== false) {
             $addCnt++;
         }
     }
     $cache = \GemsEscort::getInstance()->cache;
     $cache->clean();
     $this->html[] = sprintf('Checked %s responses and added %s responses', $formCnt, $addCnt);
 }
Example #23
0
 public function __construct($charset = null)
 {
     parent::__construct($charset);
     $this->escort = \GemsEscort::getInstance();
     $this->project = $this->escort->project;
 }
Example #24
0
 /**
  * Function that automatically fills changed, changed_by, created and created_by fields with a certain prefix.
  *
  * @param \MUtil_Model_DatabaseModelAbstract $model
  * @param string $prefix Three letter code
  * @param int $userid Gems user id
  */
 public static function setChangeFieldsByPrefix(\MUtil_Model_DatabaseModelAbstract $model, $prefix, $userid = null)
 {
     $changed_field = $prefix . '_changed';
     $changed_by_field = $prefix . '_changed_by';
     $created_field = $prefix . '_created';
     $created_by_field = $prefix . '_created_by';
     foreach (array($changed_field, $changed_by_field, $created_field, $created_by_field) as $field) {
         $model->set($field, 'elementClass', 'none');
     }
     $model->setOnSave($changed_field, new \MUtil_Db_Expr_CurrentTimestamp());
     $model->setSaveOnChange($changed_field);
     $model->setOnSave($created_field, new \MUtil_Db_Expr_CurrentTimestamp());
     $model->setSaveWhenNew($created_field);
     if (!$userid) {
         $userid = \GemsEscort::getInstance()->currentUser->getUserId();
         if (!$userid) {
             $userid = 1;
         }
     }
     if ($userid) {
         $model->setOnSave($changed_by_field, $userid);
         $model->setSaveOnChange($changed_by_field);
         $model->setOnSave($created_by_field, $userid);
         $model->setSaveWhenNew($created_by_field);
     }
 }
 protected function _scanForms()
 {
     $messages = array();
     $formCnt = 0;
     $addCnt = 0;
     $eDir = $this->_checkDir($this->formDir);
     if ($eDir !== false) {
         $model = $this->loader->getModels()->getOpenRosaFormModel();
         while (false !== ($filename = $eDir->read())) {
             if (substr($filename, -4) == '.xml') {
                 $formCnt++;
                 $form = new \OpenRosa_Tracker_Source_OpenRosa_Form($this->formDir . $filename);
                 $filter['gof_form_id'] = $form->getFormID();
                 $filter['gof_form_version'] = $form->getFormVersion();
                 $forms = $model->load($filter);
                 if (!$forms) {
                     $newValues = array();
                     $newValues['gof_id'] = null;
                     $newValues['gof_form_id'] = $form->getFormID();
                     $newValues['gof_form_version'] = $form->getFormVersion();
                     $newValues['gof_form_title'] = $form->getTitle();
                     $newValues['gof_form_xml'] = $filename;
                     $newValues = $model->save($newValues);
                     if (\Gems_Tracker::$verbose) {
                         \MUtil_Echo::r($newValues, 'added form');
                     }
                     $addCnt++;
                 }
             }
         }
     }
     $cache = GemsEscort::getInstance()->cache;
     $cache->clean();
     $messages[] = sprintf('Checked %s forms and added %s forms', $formCnt, $addCnt);
 }
 /**
  * Self constructor
  */
 public function __construct()
 {
     // gems__respondents MUST be first table for INSERTS!!
     parent::__construct('respondents', 'gems__respondents', 'grs');
     $this->addTable('gems__respondent2org', array('grs_id_user' => 'gr2o_id_user'), 'gr2o');
     $this->addTable('gems__reception_codes', array('gr2o_reception_code' => 'grc_id_reception_code'));
     $this->setKeys($this->_getKeysFor('gems__respondent2org'));
     $this->setOnSave('gr2o_opened', new \MUtil_Db_Expr_CurrentTimestamp());
     $this->setSaveOnChange('gr2o_opened');
     $this->setOnSave('gr2o_opened_by', \GemsEscort::getInstance()->session->user_id);
     $this->setSaveOnChange('gr2o_opened_by');
     $this->addColumn(new \Zend_Db_Expr("CASE WHEN grc_success = 1 THEN '' ELSE 'deleted' END"), 'row_class');
     $this->addColumn(new \Zend_Db_Expr("CASE WHEN grc_success = 1 THEN 0 ELSE 1 END"), 'resp_deleted');
     if (!$this->has('grs_ssn')) {
         $this->hashSsn = self::SSN_HIDE;
     }
     if (self::SSN_HASH === $this->hashSsn) {
         $this->setSaveWhen('grs_ssn', array($this, 'whenSSN'));
         $this->setOnLoad('grs_ssn', array($this, 'hideSSN'));
         $this->setOnSave('grs_ssn', array($this, 'saveSSN'));
     }
 }
    /**
     * Initialize the view
     *
     * Make sure the needed javascript is loaded
     *
     * @param \Zend_View $view
     */
    protected function _initView($view)
    {
        $baseUrl = \GemsEscort::getInstance()->basepath->getBasePath();
        // Make sure we can use jQuery
        \MUtil_JQuery::enableView($view);
        // Now add the scrollTo plugin so we can scroll to today
        $view->headScript()->appendFile($baseUrl . '/gems/js/jquery.scrollTo.min.js');
        /*
         * And add some initialization:
         *  - Hide all tokens initially (accessability, when no javascript they should be visible)
         *  - If there is a day labeled today, scroll to it (prevents errors when not visible)
         */
        $view->headScript()->appendScript('

    // Click track
    $(".traject .panel-heading").click(function(){
        $(this).next().toggle();
        if($(this).next().is(":visible")) {
            $(this).find("h3 span").removeClass("fa-chevron-right").addClass("fa-chevron-down");
            // Close all days
            $(this).next().find(".actor").each(function(){if ( $(this).find(".zpitems").is(":visible") ) { $(this).find("h5").click(); }});
            // Scroll to today
            $(this).next().find(".object.today").each(function(){
                // Open current day
                $(this).children(".actor").each(function(){if ( $(this).find(".zplegenda").is(":visible") ) { $(this).find("h5").click(); }});
                // Scroll to today
                $(this).parent().parent().scrollTo($(this),0, { offset: $(this).outerWidth(true)-$(this).parent().parent().innerWidth()} );    /* today is rightmost block */
            });
        } else {
            $(this).find("h3 span").addClass("fa-chevron-right").removeClass("fa-chevron-down");
        }
    });

    // Click day
    $(".object h4").click(function(){
        if ( $(this).parent().find(".actor h5 span").first().hasClass("fa-minus-square") ) {
            // First is open, now close first and all others
            $(this).parent().find(".actor h5 span").each(function(){
                if ( $(this).hasClass("fa-minus-square")) {
                    $(this).parent().click();
                }
            });
        } else {
            // First is closed, now open first and all others
            $(this).parent().find(".actor h5 span").each(function(){
                if ( $(this).hasClass("fa-plus-square")) {
                    $(this).parent().click();
                }
            });
        }
    });

    // Click actor
    $(".actor h5").click(function(){
        if ( $(this).find("span").first().hasClass("fa-plus-square") ) {
            $(this).find("span").removeClass("fa-plus-square").addClass("fa-minus-square");
            $(this).parent().find(".zplegenda").toggle(false);
            $(this).parent().find(".zpitems").toggle(true);
        } else {
            $(this).find("span").addClass("fa-plus-square").removeClass("fa-minus-square");
            $(this).parent().find(".zplegenda").toggle(true);
            $(this).parent().find(".zpitems").toggle(false);
        }
    });

    // Click legend
    $(".actor .zplegenda").click(function(){
        // delegate to actor
        $(this).parent().find("h5").click();
    });

    // Initially hide all zpitems so only zplegende remains visible
    $(".object .actor").children(".zpitems").toggle(false);

    // First close all tracks
    $(".traject .panel-heading").click();
    // and open the first one
    $(".traject .panel-heading").first().click();

    // Inline answers + printing dialog
    $(".zpitem.success a[target=\'inline\']").click(function(e){
        e.preventDefault();
        // Now open a new div, not #menu and bring it to the front
        // Add a close button to it, maybe the available tooltip can help here
        $("div#modalpopup").html("<div class=\'loading\'></div>"); // Make sure we show no old information
        $("div#modalpopup").load($(this).attr(\'href\'));
        $("div#modalpopup").dialog({
            modal: true,
            width: 500,
            position:{ my: "left top", at: "left top", of: "#main" },
            buttons: [
                {
                text: "Print",
                "class": "btn-primary",
                click: function() {
                        if ($(".modal").is(":visible")) {
                            var oldId = $(event.target).closest(".modal").attr("id");
                            var modalId = "modelprint";
                            $(event.target).closest(".modal").attr("id", modalId);
                            $("body").css("visibility", "hidden");
                            $("body #container").css("display", "none");
                            $("div#modalpopup").css("visibility", "visible");
                            $("#" + modalId).removeClass("modal");
                            window.print();
                            $("body").css("visibility", "visible");
                            $("body #container").css("display", "block");
                            $("#" + modalId).addClass("modal");
                            $(event.target).closest(".modal").attr("id", oldId);
                        } else {
                            window.print();
                        }
                    }
                }
                ]
        });
    });');
        // find the menu items only once for more efficiency
        $this->_trackAnswer = $this->findMenuItem('track', 'answer');
        $this->_surveyAnswer = $this->findMenuItem('survey', 'answer');
        $this->_takeSurvey = $this->findMenuItem('ask', 'take');
    }
 /**
  * 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
  */
 protected function addBrowseTableColumns(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model)
 {
     // \MUtil_Model::$verbose = true;
     //
     // Initiate data retrieval for stuff needed by links
     $bridge->gr2o_patient_nr;
     $bridge->gr2o_id_organization;
     $bridge->gr2t_id_respondent_track;
     $HTML = \MUtil_Html::create();
     $roundDescription[] = $HTML->if($bridge->gto_round_description, $HTML->small(' [', $bridge->gto_round_description, ']'));
     $roundDescription[] = $HTML->small(' [', $bridge->createSortLink('gto_round_description'), ']');
     $roundIcon[] = \MUtil_Lazy::iif($bridge->gro_icon_file, \MUtil_Html::create('img', array('src' => $bridge->gro_icon_file, 'class' => 'icon')));
     if ($menuItem = $this->findMenuItem('track', 'show-track')) {
         $href = $menuItem->toHRefAttribute($this->request, $bridge);
         $track1 = $HTML->if($bridge->gtr_track_name, $HTML->a($href, $bridge->gtr_track_name));
     } else {
         $track1 = $bridge->gtr_track_name;
     }
     $track[] = array($track1, $HTML->if($bridge->gr2t_track_info, $HTML->small(' [', $bridge->gr2t_track_info, ']')));
     $track[] = array($bridge->createSortLink('gtr_track_name'), $HTML->small(' [', $bridge->createSortLink('gr2t_track_info'), ']'));
     $bridge->addMultiSort($track);
     $bridge->addMultiSort('gsu_survey_name', $roundDescription, $roundIcon);
     $bridge->addSortable('ggp_name');
     $bridge->addSortable('calc_used_date', null, $HTML->if($bridge->is_completed, 'disabled date', 'enabled date'));
     $bridge->addSortable('gto_changed');
     $bridge->addSortable('assigned_by', $this->_('Assigned by'));
     $project = \GemsEscort::getInstance()->project;
     // If we are allowed to see the result of the survey, show them
     $user = $this->loader->getCurrentUser();
     if ($user->hasPrivilege('pr.respondent.result')) {
         $bridge->addSortable('gto_result', $this->_('Score'), 'date');
     }
     $bridge->useRowHref = false;
     $actionLinks[] = $this->createMenuLink($bridge, 'track', 'answer');
     $actionLinks[] = array($bridge->ggp_staff_members->if($this->createMenuLink($bridge, 'ask', 'take'), $bridge->calc_id_token->strtoupper()), 'class' => $bridge->ggp_staff_members->if(null, $bridge->calc_id_token->if('token')));
     // calc_id_token is empty when the survey has been completed
     // Remove nulls
     $actionLinks = array_filter($actionLinks);
     if ($actionLinks) {
         $bridge->addItemLink($actionLinks);
     }
     $this->addTokenLinks($bridge);
 }