/**
  * 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 !== 'excel');
     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;
 }
 /**
  * Called after the check that all required registry values
  * have been set correctly has run.
  *
  * @return void
  */
 public function afterRegistry()
 {
     parent::afterRegistry();
     $this->addColumn($this->util->getTokenData()->getStatusExpression(), 'status');
     if (!$this->request instanceof \Zend_Controller_Request_Abstract) {
         $this->request = \Zend_Controller_Front::getInstance()->getRequest();
     }
 }
 /**
  * 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)
 {
     $model = new \Gems_Model_JoinModel('log_maint', 'gems__log_setup', 'gls', true);
     $model->set('gls_name', 'label', $this->_('Action'), 'elementClass', 'create' == $action ? 'Text' : 'Exhibitor', 'validators[unique]', $model->createUniqueValidator('gls_name'));
     $model->set('gls_when_no_user', 'label', $this->_('Log when no user'), 'description', $this->_('Always log this action, even when no one is logged in.'), 'elementClass', 'CheckBox', 'multiOptions', $this->util->getTranslated()->getYesNo());
     $model->set('gls_on_action', 'label', $this->_('Log view'), 'description', $this->_('Always log when viewed / opened.'), 'elementClass', 'CheckBox', 'multiOptions', $this->util->getTranslated()->getYesNo());
     $model->set('gls_on_post', 'label', $this->_('Log change tries'), 'description', $this->_('Log when trying to change the data.'), 'elementClass', 'CheckBox', 'multiOptions', $this->util->getTranslated()->getYesNo());
     $model->set('gls_on_change', 'label', $this->_('Log data change'), 'description', $this->_('Log when data changes.'), 'elementClass', 'CheckBox', 'multiOptions', $this->util->getTranslated()->getYesNo());
     return $model;
 }
 public function __construct($name = null, $startTable = null, $fieldPrefix = null, $saveable = null)
 {
     parent::__construct('respondent_relation', 'gems__respondent_relations', 'grr');
     $this->addTable('gems__respondent2org', array('gr2o_id_user' => 'grr_id_respondent'), null, false);
     $keys = $this->_getKeysFor('gems__respondent2org');
     $keys['rid'] = 'grr_id';
     $this->setKeys($keys);
     // Do not really delete but make inactive so we can always display old relations
     $this->setDeleteValues('grr_active', 0);
 }
 public function __construct(\Gems_Tracker_Survey $survey, \Gems_Tracker_Source_SourceInterface $source)
 {
     parent::__construct($survey->getName(), 'gems__tokens', 'gto');
     $this->addTable('gems__reception_codes', array('gto_reception_code' => 'grc_id_reception_code'));
     $this->addColumn('CASE WHEN grc_success = 1 AND gto_valid_from <= CURRENT_TIMESTAMP AND gto_completion_time IS NULL AND (gto_valid_until IS NULL OR gto_valid_until >= CURRENT_TIMESTAMP) THEN 1 ELSE 0 END', 'can_be_taken');
     $this->addColumn("CASE WHEN grc_success = 1 THEN '' ELSE 'deleted' END", 'row_class');
     $this->source = $source;
     $this->survey = $survey;
     $this->addAnswersToModel();
 }
 /**
  * Get a select statement using a filter and sort
  *
  * Modified to add the information schema, only possible like this since
  * the table has no primary key and can not be added using normal joins
  *
  * @param array $filter
  * @param array $sort
  * @return \Zend_Db_Table_Select
  */
 public function _createSelect(array $filter, array $sort)
 {
     $select = parent::_createSelect($filter, $sort);
     $config = $select->getAdapter()->getConfig();
     if (isset($config['dbname'])) {
         $constraint = $select->getAdapter()->quoteInto(' AND TABLE_SCHEMA=?', $config['dbname']);
     } else {
         $constraint = '';
     }
     $select->joinLeft('INFORMATION_SCHEMA.TABLES', "table_name  = convert(concat_ws('_','gems__orf_', REPLACE(gof_form_id,'.','_'),gof_form_version) USING utf8)" . $constraint, array('TABLE_ROWS'));
     return $select;
 }
 public function __construct(\Gems_Tracker_Survey $survey, \Gems_Tracker_Source_SourceInterface $source)
 {
     parent::__construct($survey->getName(), 'gems__tokens', 'gto');
     $this->addTable('gems__reception_codes', array('gto_reception_code' => 'grc_id_reception_code'));
     // Add relations
     $this->addLeftTable('gems__track_fields', array('gto_id_relationfield' => 'gtf_id_field', 'gtf_field_type = "relation"'));
     // Add relation fields
     $this->addLeftTable('gems__respondent_relations', array('gto_id_relation' => 'grr_id', 'gto_id_respondent' => 'grr_id_respondent'));
     // Add relation
     $this->set('grr_name', 'column_expression', new Zend_Db_Expr('CONCAT_WS(" ", gems__respondent_relations.grr_first_name, gems__respondent_relations.grr_last_name)'));
     $this->addColumn('CASE WHEN grc_success = 1 AND gto_valid_from <= CURRENT_TIMESTAMP AND gto_completion_time IS NULL AND (gto_valid_until IS NULL OR gto_valid_until >= CURRENT_TIMESTAMP) THEN 1 ELSE 0 END', 'can_be_taken');
     $this->addColumn("CASE WHEN grc_success = 1 THEN '' ELSE 'deleted' END", 'row_class');
     $this->source = $source;
     $this->survey = $survey;
     $this->addAnswersToModel();
 }
    protected function createModel($detailed, $action)
    {
        $model = new \Gems_Model_JoinModel('chartconfig', 'gems__chart_config', 'gcc');
        $empty = $this->loader->getUtil()->getTranslated()->getEmptyDropdownArray();
        $model->set('gcc_tid', 'label', $this->_('Track'), 'multiOptions', $empty + $this->db->fetchPairs('SELECT gtr_id_track, gtr_track_name FROM gems__tracks ORDER BY gtr_track_name;'), 'onchange', 'this.form.submit();');
        $model->set('gcc_rid', 'label', $this->_('Round'));
        $model->set('gcc_sid', 'label', $this->_('Survey'), 'multiOptions', $empty + $this->db->fetchPairs('SELECT gsu_id_survey, gsu_survey_name FROM gems__surveys ORDER BY gsu_survey_name;'));
        $model->set('gcc_code', 'label', $this->_('Survey code'));
        $model->set('gcc_description', 'label', $this->_('Description'));
        $roundStatement = 'SELECT gro_id_round, concat_ws(" ", gro_id_order, gro_survey_name, gro_round_description) FROM gems__rounds ORDER BY gro_id_order;';
        if ($detailed) {
            if ($this->getRequest()->isPost()) {
                $data = $this->getRequest()->getParams();
                if (array_key_exists('gcc_tid', $data) && !empty($data['gcc_tid'])) {
                    $trackId = (int) $data['gcc_tid'];
                    $roundStatement = 'SELECT gro_id_round, concat_ws(" ", gro_id_order, gro_survey_name, gro_round_description) FROM gems__rounds WHERE gro_id_track = ' . $trackId . ' ORDER BY gro_id_order;';
                }
            }
            $default = '[
  {
    "question_code":[
      "SCORE1",
      "SCORE2"
    ],
    "question_text":"DSM scores",
    "grid":false,
    "min":25,
    "max":100,
    "rulers":[
      {
        "value":60,
        "class":"negative",
        "label":"lower"
      },
      {
        "value":69,
        "class":"positive",
        "label":"upper"
      }
    ]
  }
]';
            $model->set('gcc_config', 'label', $this->_('Config'), 'elementClass', 'textArea', 'default', $default);
            if ($action == 'show') {
                $model->set('gcc_config', 'formatFunction', array($this, 'formatjsonpre'));
            }
            $model->setOnLoad('gcc_config', array($this, 'formatjson'));
        }
        $model->set('gcc_rid', 'multiOptions', $empty + $this->db->fetchPairs($roundStatement));
        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)
 {
     $yesNo = $this->util->getTranslated()->getYesNo();
     $model = new \Gems_Model_JoinModel('surveys', 'gems__surveys');
     $model->addTable('gems__groups', array('gsu_id_primary_group' => 'ggp_id_group'));
     $model->addColumn("(SELECT COUNT(DISTINCT gro_id_track)\r\n                    FROM gems__tracks INNER JOIN gems__rounds ON gtr_id_track = gro_id_track\r\n                    WHERE gro_id_survey = gsu_id_survey)", 'track_count');
     $model->resetOrder();
     $model->set('gsu_survey_name', 'label', $this->_('Survey'));
     if ($detailed) {
         $model->set('gsu_survey_description', 'label', $this->_('Description'), 'formatFunction', array(__CLASS__, 'formatDescription'));
         $model->set('gsu_active', 'label', sprintf($this->_('Active in %s'), $this->project->getName()), 'elementClass', 'Checkbox', 'multiOptions', $yesNo);
     }
     $model->set('ggp_name', 'label', $this->_('By'));
     $model->set('track_count', 'label', $this->_('Usage'), 'description', $this->_('How many track definitions use this survey?'));
     $model->set('gsu_insertable', 'label', $this->_('Insertable'), 'description', $this->_('Can this survey be manually inserted into a track?'), 'multiOptions', $yesNo);
     if ($detailed) {
         $model->set('gsu_duration', 'label', $this->_('Duration description'), 'description', $this->_('Text to inform the respondent, e.g. "20 seconds" or "1 minute".'));
     }
     return $model;
 }
 /**
  * Stores the fields that can be used for sorting or filtering in the
  * sort / filter objects attached to this model.
  *
  * @param array $parameters
  * @param boolean $includeNumericFilters When true numeric filter keys (0, 1, 2...) are added to the filter as well
  * @return array The $parameters minus the sort & textsearch keys
  */
 public function applyParameters(array $parameters, $includeNumericFilters = false)
 {
     if ($parameters) {
         // Allow use when passed only an ID value
         if (isset($parameters[\MUtil_Model::REQUEST_ID]) && !isset($parameters[\MUtil_Model::REQUEST_ID1], $parameters[\MUtil_Model::REQUEST_ID2])) {
             $id = $parameters[\MUtil_Model::REQUEST_ID];
             $keys = $this->getKeys();
             $field = array_shift($keys);
             $parameters[$field] = $id;
             if ($field2 = array_shift($keys)) {
                 $parameters[$field2] = $this->getCurrentOrganization();
                 \MUtil_Echo::r('Still using old HiddenModel parameters.', 'DEPRECIATION WARNING');
                 \MUtil_Echo::r($parameters);
             }
             unset($parameters[\MUtil_Model::REQUEST_ID]);
         }
         if (isset($parameters[\MUtil_Model::REQUEST_ID2]) && !array_key_exists($parameters[\MUtil_Model::REQUEST_ID2], $this->currentUser->getAllowedOrganizations())) {
             $this->initTranslateable();
             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()));
         }
         return parent::applyParameters($parameters, $includeNumericFilters);
     }
     return array();
 }
 /**
  * Save a single model item.
  *
  * Makes sure the password is saved too using the userclass
  *
  * @param array $newValues The values to store for a single model item.
  * @param array $filter If the filter contains old key values these are used
  * to decide on update versus insert.
  * @param array $saveTables Optional array containing the table names to save,
  * otherwise the tables set to save at model level will be saved.
  * @return array The values as they are after saving (they may change).
  */
 public function save(array $newValues, array $filter = null, array $saveTables = null)
 {
     //First perform a save
     $savedValues = parent::save($newValues, $filter, $saveTables);
     //Now check if we need to save config values
     if (isset($newValues['gor_user_class']) && !empty($newValues['gor_user_class'])) {
         $definition = $this->loader->getUserLoader()->getUserDefinition($newValues['gor_user_class']);
         if ($definition instanceof \Gems_User_UserDefinitionConfigurableInterface && $definition->hasConfig()) {
             $savedValues = $definition->saveConfig($savedValues, $newValues);
             if ($definition->getConfigChanged() > 0 && $this->getChanged() < 1) {
                 $this->setChanged(1);
             }
         }
     }
     return $savedValues;
 }
 /**
  * Called after the check that all required registry values
  * have been set correctly has run.
  *
  * This function is no needed if the classes are setup correctly
  *
  * @return void
  */
 public function afterRegistry()
 {
     parent::afterRegistry();
     $this->addColumn(new \Zend_Db_Expr(sprintf("CASE WHEN gla_by IS NULL THEN '%s'\n                    ELSE CONCAT(\n                        COALESCE(gsf_last_name, '-'),\n                        ', ',\n                        COALESCE(CONCAT(gsf_first_name, ' '), ''),\n                        COALESCE(gsf_surname_prefix, '')\n                        )\n                    END", $this->_('(no user)'))), 'staff_name');
     $this->addColumn(new \Zend_Db_Expr(sprintf("CASE WHEN grs_id_user IS NULL THEN '%s'\n                    ELSE CONCAT(\n                        COALESCE(grs_last_name, '-'),\n                        ', ',\n                        COALESCE(CONCAT(grs_first_name, ' '), ''),\n                        COALESCE(grs_surname_prefix, '')\n                        )\n                    END", $this->_('(no respondent)'))), 'respondent_name');
 }
 /**
  * Construct a round model
  */
 public function __construct(\Zend_Db_Adapter_Abstract $db)
 {
     parent::__construct('rounds', 'gems__rounds', 'gro', true);
     $this->db = $db;
 }
 /**
  *
  * @param string $name
  */
 public function __construct($name = 'app-filter')
 {
     parent::__construct($name, 'gems__appointment_filters', 'gaf');
 }
 /**
  * Save a single model item.
  *
  * @param array $newValues The values to store for a single model item.
  * @param array $filter If the filter contains old key values these are used
  * to decide on update versus insert.
  * @return array The values as they are after saving (they may change).
  */
 public function save(array $newValues, array $filter = null)
 {
     // When appointment id is not set, then check for existing instances of
     // this appointment using the source information
     if (!isset($newValues['gap_id_appointment']) && isset($newValues['gap_id_in_source'], $newValues['gap_id_organization'], $newValues['gap_source'])) {
         $sql = "SELECT gap_id_appointment\n                FROM gems__appointments\n                WHERE gap_id_in_source = ? AND gap_id_organization = ? AND gap_source = ?";
         $id = $this->db->fetchOne($sql, array($newValues['gap_id_in_source'], $newValues['gap_id_organization'], $newValues['gap_source']));
         if ($id) {
             $newValues['gap_id_appointment'] = $id;
         }
     }
     $oldChanged = $this->getChanged();
     $returnValues = parent::save($newValues, $filter);
     if ($this->getChanged() && $this->getChanged() !== $oldChanged) {
         if ($this->isAutoTrackUpdate()) {
             $appointment = $this->loader->getAgenda()->getAppointment($returnValues);
             $this->_changedTokenCount += $appointment->updateTracks();
         }
     }
     // \MUtil_Echo::track($this->_changedTokenCount);
     return $returnValues;
 }
 /**
  * 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;
 }
 /**
  * Create the mail template model
  */
 public function __construct()
 {
     parent::__construct('commtemplate', 'gems__comm_templates', 'gct');
 }
 /**
  * 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;
 }
 /**
  * Save a single model item.
  *
  * Makes sure the password is saved too using the userclass
  *
  * @param array $newValues The values to store for a single model item.
  * @param array $filter If the filter contains old key values these are used
  * to decide on update versus insert.
  * @param array $saveTables Optional array containing the table names to save,
  * otherwise the tables set to save at model level will be saved.
  * @return array The values as they are after saving (they may change).
  */
 public function save(array $newValues, array $filter = null, array $saveTables = null)
 {
     //First perform a save
     $savedValues = parent::save($newValues, $filter, $saveTables);
     //Now check if we need to set the password
     if (isset($newValues['fld_password']) && !empty($newValues['fld_password'])) {
         if ($this->getChanged() < 1) {
             $this->setChanged(1);
         }
         //Now load the userclass and save the password use the $savedValues as for a new
         //user we might not have the id in the $newValues
         $user = $this->loader->getUserLoader()->getUserByStaffId($savedValues['gsf_id_user']);
         if ($user->canSetPassword()) {
             $user->setPassword($newValues['fld_password']);
         }
     }
     return $savedValues;
 }
 /**
  * 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();
     $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_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 ('edit' == $action) {
         //                $element = new \Gems_JQuery_Form_Element_ToggleCheckboxes('toggleOrg', array('selector'=>'input[name^=gtr_organizations]'));
         //                $element->setLabel($this->_('Toggle'));
         //                $model->set('toggleOrg', 'elementClass', $element);
         //            }
         $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)));
         $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');
         $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;
 }
 /**
  * Link the model to the user_passwords table.
  *
  * @param \Gems_Model_JoinModel $model
  * @deprecated since version 1.5.4
  */
 public static function addUserPassword(\Gems_Model_JoinModel $model)
 {
     $model->addLeftTable('gems__user_passwords', array('gul_id_user' => 'gup_id_user'), 'gup');
 }
 /**
  * Create a database model for retrieving the respondent tracks
  *
  * @return \Gems_Model_JoinModel A NEW JoinModel, not a continuation pattern return
  */
 public function getRespondentTracksModel()
 {
     $model = new \Gems_Model_JoinModel('surveys', 'gems__respondent2track');
     $model->addTable('gems__tracks', array('gr2t_id_track' => 'gtr_id_track'));
     $model->addTable('gems__respondent2org', array('gr2t_id_user' => 'gr2o_id_user'));
     return $model;
 }