Esempio n. 1
0
    public function configure(XenForo_ControllerAdmin_Abstract $controller, array &$config)
    {
        if ($config) {
            $errors = $this->validateConfiguration($config);
            if ($errors) {
                return $controller->responseError($errors);
            }
            if (isset($config['attachmentPath']) || isset($config['avatarPath'])) {
                // already configured
                return true;
            }
            $this->_bootstrap($config);
            $settings = $this->_sourceDb->fetchPairs('
				SELECT varname, value
				FROM ' . $this->_prefix . 'setting
				WHERE varname IN (\'attachpath\', \'attachfile\', \'avatarpath\', \'usefileavatar\')
			');
            if ($settings['attachfile'] && $settings['attachpath'] || $settings['usefileavatar'] && $settings['avatarpath']) {
                return $controller->responseView('XenForo_ViewAdmin_Import_vBulletin_Config', 'import_vbulletin_config', array('config' => $config, 'attachmentPath' => $settings['attachfile'] ? $settings['attachpath'] : '', 'avatarPath' => $settings['usefileavatar'] ? $settings['avatarpath'] : '', 'retainKeys' => $config['retain_keys']));
            }
            return true;
        } else {
            $configPath = getcwd() . '/includes/config.php';
            if (file_exists($configPath) && is_readable($configPath)) {
                $config = array();
                include $configPath;
                $viewParams = array('input' => $config);
            } else {
                $viewParams = array('input' => array('MasterServer' => array('servername' => 'localhost', 'port' => 3306, 'username' => '', 'password' => ''), 'Database' => array('dbname' => '', 'tableprefix' => ''), 'Mysqli' => array('charset' => '')));
            }
            return $controller->responseView('XenForo_ViewAdmin_Import_vBulletin_Config', 'import_vbulletin_config', $viewParams);
        }
    }
    public function configure(XenForo_ControllerAdmin_Abstract $controller, array &$config)
    {
        if ($config) {
            $errors = $this->validateConfiguration($config);
            if ($errors) {
                return $controller->responseError($errors);
            }
            if (isset($config['albumPicPath'])) {
                return true;
            }
            $this->_bootstrap($config);
            $settings = $this->_sourceDb->fetchPairs('
				SELECT varname, value
				FROM ' . $this->_prefix . 'setting
				WHERE varname IN (\'attachfile\', \'attachpath\')
			');
            if (intval($settings['attachfile']) !== self::ATTACH_AS_DB) {
                return $controller->responseView('XenGallery_ViewAdmin_Import_Config', 'xengallery_import_config_vbulletin', array('config' => $config, 'productName' => str_replace('XFMG: Import From ', '', self::getName()), 'albumPicPath' => $settings['attachpath'], 'attachType' => $settings['attachfile'], 'retainKeys' => $config['retain_keys']));
            }
            return true;
        } else {
            $configPath = getcwd() . '/includes/config.php';
            if (file_exists($configPath) && is_readable($configPath)) {
                $config = array();
                include $configPath;
                $viewParams = array('input' => $config);
            } else {
                $viewParams = array('input' => array('MasterServer' => array('servername' => 'localhost', 'port' => 3306, 'username' => '', 'password' => ''), 'Database' => array('dbname' => '', 'tableprefix' => ''), 'Mysqli' => array('charset' => '')), 'productName' => str_replace('XFMG: Import From ', '', self::getName()));
            }
            return $controller->responseView('XenForo_ViewAdmin_Import_vBulletin_Config', 'xengallery_import_config_vbulletin', $viewParams);
        }
    }
Esempio n. 3
0
 /**
  * @param string $username
  * @return array
  */
 public function fetchAttrs($username)
 {
     $sql = "SELECT `key`, `value` FROM {$this->_prefix}attributes WHERE username = ?";
     $attrs = $this->_db->fetchPairs($sql, $username);
     if (empty($attrs)) {
         return null;
     }
     return $attrs;
 }
 /**
  * Override this function when you need to perform any actions when the data is loaded.
  *
  * Test for the availability of variables as these objects can be loaded data first after
  * deserialization or registry variables first after normal instantiation.
  *
  * That is why this function called both at the end of afterRegistry() and after exchangeArray(),
  * but NOT after unserialize().
  *
  * After this the object should be ready for serialization
  */
 protected function afterLoad()
 {
     if ($this->_data && $this->db instanceof \Zend_Db_Adapter_Abstract && !$this->_locations) {
         if ($this->_data['gaf_filter_text1']) {
             $sqlActivites = "SELECT glo_id_location, glo_id_location\n                    FROM gems__locations\n                    WHERE glo_active = 1 AND glo_name LIKE '%s'\n                    ORDER BY glo_id_location";
             $this->_locations = $this->db->fetchPairs(sprintf($sqlActivites, addslashes($this->_data['gaf_filter_text1'])));
         } else {
             $this->_locations = true;
         }
     }
 }
 /**
  * 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()
 {
     $role = \Gems_Roles::getInstance();
     $parents = $this->db->fetchPairs("SELECT grl_id_role, grl_parents FROM gems__roles");
     // \MUtil_Echo::track($parents);
     if ($parents) {
         foreach ($parents as $id => $priv) {
             $values['grl_parents'] = implode(',', $role->translateToRoleIds($priv));
             $this->db->update('gems__roles', $values, $this->db->quoteInto('grl_id_role = ?', $id));
         }
     }
 }
    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;
    }
 /**
  * Called after the check that all required registry values
  * have been set correctly has run.
  *
  * @return void
  */
 public function afterRegistry()
 {
     parent::afterRegistry();
     $this->orgTranslations = $this->db->fetchPairs('
         SELECT gor_provider_id, gor_id_organization
             FROM gems__organizations
             WHERE gor_provider_id IS NOT NULL
             ORDER BY gor_provider_id');
     $this->orgTranslations = $this->orgTranslations + $this->db->fetchPairs('
         SELECT gor_code, gor_id_organization
             FROM gems__organizations
             WHERE gor_code IS NOT NULL
             ORDER BY gor_id_organization');
 }
 /**
  * Returns the data for a user object. It may be empty if the user is unknown.
  *
  * @param string $login_name
  * @param int $organization
  * @return array Of data to fill the user with.
  */
 public function getUserData($login_name, $organization)
 {
     $orgs = null;
     try {
         $orgs = $this->db->fetchPairs("SELECT gor_id_organization, gor_name FROM gems__organizations WHERE gor_active = 1 ORDER BY gor_name");
         natsort($orgs);
     } catch (\Zend_Db_Exception $zde) {
     }
     if (!$orgs) {
         // Table might not exist or be empty, so do something failsafe
         $orgs = array($organization => 'create db first');
     }
     return array('user_id' => \Gems_User_UserLoader::SYSTEM_USER_ID, 'user_login' => $login_name, 'user_name' => $login_name, 'user_group' => 800, 'user_role' => $this->project->getConsoleRole(), 'user_style' => 'gems', 'user_base_org_id' => $organization, 'user_allowed_ip_ranges' => null, 'user_blockable' => false, '__allowedOrgs' => $orgs);
 }
 /**
  * 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($tableName = '', $idField = '', $passwordField = '', $methodField = '')
 {
     $passwords = $this->db->fetchPairs("SELECT {$idField}, {$passwordField} FROM {$tableName} WHERE {$passwordField} IS NOT NULL AND {$methodField} IS NULL");
     if ($passwords) {
         $values[$methodField] = 'default';
         foreach ($passwords as $key => $password) {
             $values[$passwordField] = $this->project->encrypt($password, $values[$methodField]);
             $this->db->update($tableName, $values, "{$idField} = '{$key}'");
         }
         $this->getBatch()->addMessage(sprintf($this->_('%d passwords encrypted for table %s.'), count($passwords), $tableName));
     } else {
         $this->getBatch()->addMessage(sprintf($this->_('No passwords found in table %s.'), $tableName));
     }
 }
 /**
  * Ajax return function for round selection
  */
 public function roundselectAction()
 {
     \Zend_Layout::resetMvcInstance();
     $trackId = $this->getRequest()->getParam('sourceValue');
     $rounds = $this->db->fetchPairs($this->roundDescriptionQuery, $trackId);
     echo json_encode($rounds);
 }
 /**
  * Load the data when the cache is empty.
  *
  * @param mixed $id
  * @return array The array of data values
  */
 protected function loadData($id)
 {
     if (\Gems_User_UserLoader::SYSTEM_NO_ORG === $id) {
         $data = false;
     } else {
         try {
             $sql = "SELECT * FROM gems__organizations WHERE gor_id_organization = ? LIMIT 1";
             $data = $this->db->fetchRow($sql, intval($id));
         } catch (\Exception $e) {
             $data = false;
         }
     }
     if ($data) {
         try {
             $dbOrgId = $this->db->quote($id, \Zend_Db::INT_TYPE);
             $sql = "SELECT gor_id_organization, gor_name\n                    FROM gems__organizations\n                    WHERE gor_active = 1 AND\n                        (\n                          gor_id_organization = {$dbOrgId} OR\n                          gor_accessible_by LIKE '%:{$dbOrgId}:%'\n                        )\n                    ORDER BY gor_name";
             $data['can_access'] = $this->db->fetchPairs($sql);
             natsort($data['can_access']);
         } catch (\Exception $e) {
             $data['can_access'] = array();
         }
         // \MUtil_Echo::track($sql, $data['can_access']);
         if (array_key_exists('gor_url_base', $data) && ($baseUrls = explode(' ', $data['gor_url_base']))) {
             $data['base_url'] = reset($baseUrls);
         }
     } else {
         $data = $this->_noOrganization;
         $data['gor_id_organization'] = $id;
     }
     return $data;
 }
Esempio n. 12
0
 /**
  * @param type $aParams
  */
 public function show($aParams = null)
 {
     $aParams = $this->actionController->getRequest()->getParams();
     $aDefaultOptions = array('' => 'Not selected');
     $aControlsValues = array();
     foreach ($this->_aParams['controls'] as $sKey => $aValue) {
         $aControlsValues[$sKey] = array();
         if (isset($aValue['values']) && !is_array($aValue['values'])) {
             switch ($aValue['values']) {
                 case 'issue':
                     $aQuery = $this->_oDbAdapter->select()->from($aValue['values'], array('id', 'title'))->where('application = ?', $aParams['aid']);
                     $aControlsValues[$sKey] = $this->_oDbAdapter->fetchPairs($aQuery);
                     break;
                 default:
                     break;
             }
         }
         if (!isset($this->_aParams['controls'][$sKey]['values']) || !is_array($aValue['values'])) {
             is_array($aControlsValues[$sKey]) ? $aControlsValues[$sKey] = $aDefaultOptions + $aControlsValues[$sKey] : $aDefaultOptions;
         } else {
             $aControlsValues[$sKey] = $this->_aParams['controls'][$sKey]['values'];
         }
     }
     $this->actionController->view->{$this->getName()} = array('controlsValues' => $aControlsValues);
     parent::show();
 }
 /**
  * Function used to fill the tab bar
  *
  * @return array tabId => label
  */
 protected function getTabs()
 {
     $user = $this->loader->getCurrentUser();
     $sql = "SELECT gr2o_id_organization, gr2o_patient_nr FROM gems__respondent2org WHERE gr2o_id_user = ?";
     $this->defaultTab = $user->getCurrentOrganizationId();
     $this->currentTab = $this->request->getParam(\MUtil_Model::REQUEST_ID2);
     $allowedOrgs = $user->getRespondentOrganizations();
     $existingOrgs = $this->db->fetchPairs($sql, $this->respondent->getId());
     $tabs = array();
     foreach ($allowedOrgs as $orgId => $name) {
         if (isset($existingOrgs[$orgId])) {
             $tabs[$orgId] = $name;
             $this->hrefs[$orgId] = array(\MUtil_Model::REQUEST_ID1 => $existingOrgs[$orgId], \MUtil_Model::REQUEST_ID2 => $orgId, 'RouteReset' => true);
         }
     }
     return $tabs;
 }
Esempio n. 14
0
    protected function _getUserGroupPermsForUserGroup($userGroupId)
    {
        return $this->_sourceDb->fetchPairs('
			SELECT permission, add_deny
			FROM ' . $this->_prefix . 'permissions
			WHERE id_group = ?
		', $userGroupId);
    }
Esempio n. 15
0
 /**
  * Возвращает плоский список разделов, привязанных к определенному модулю
  *  
  * @param int $moduleid Id модуля
  * @return array
  */
 public function getCategoriesListByModule($moduleid = null)
 {
     $select = $this->_db->select()->from('pw_categories', array('categoryid', 'categoryname'))->order('cleft');
     if (!is_null($moduleid)) {
         $select->where('moduleid=?', $moduleid);
     }
     return $this->_db->fetchPairs($select);
 }
 /**
  * Returns the token deletion reception code list.
  *
  * @return array a value => label array.
  */
 public function getUnansweredTokenDeletionCodes()
 {
     $select = $this->_getDeletionCodeSelect();
     $select->where('grc_for_surveys = ?', self::APPLY_DO)->where('grc_redo_survey = ?', self::REDO_NONE);
     $pairs = $this->_translateAndSort($this->db->fetchPairs($select));
     asort($pairs);
     return;
 }
Esempio n. 17
0
 /**
  * Test the Adapter's fetchPairs() method.
  */
 public function testAdapterFetchPairs()
 {
     $table = $this->getIdentifier(self::TABLE_NAME);
     $title = 'News Item 1';
     $result = $this->_db->fetchPairs('SELECT id, title FROM ' . $this->_db->quoteIdentifier($table) . ' WHERE date_created > ? ORDER BY id', array('2006-01-01'));
     $this->assertEquals(2, count($result));
     // count rows
     $this->assertEquals($title, $result[1]);
 }
Esempio n. 18
0
    /**
     * Caches the app_cache and module_cache from IPB
     */
    protected function _cacheAppsAndModules()
    {
        $caches = $this->_sourceDb->fetchPairs('
			SELECT cs_key, cs_value
			FROM ' . $this->_prefix . 'cache_store
			WHERE cs_key IN(\'app_cache\', \'module_cache\')
		');
        $this->_appCache = unserialize($caches['app_cache']);
        $this->_moduleCache = unserialize($caches['module_cache']);
    }
 /**
  * Returns the changes to the model for this field that must be made in an array consisting of
  *
  * <code>
  *  array(setting1 => $value1, setting2 => $value2, ...),
  * </code>
  *
  * By using [] array notation in the setting array key you can append to existing
  * values.
  *
  * Use the setting 'value' to change a value in the original data.
  *
  * When a 'model' setting is set, the workings cascade.
  *
  * @param array $context The current data this object is dependent on
  * @param boolean $new True when the item is a new record not yet saved
  * @return array (setting => value)
  */
 public function getDataModelDependyChanges(array $context, $new)
 {
     if ($this->isReadOnly()) {
         return null;
     }
     $sql = $this->_sql . "WHERE grr_id_respondent = ? ORDER BY grr_type";
     $empty = $this->util->getTranslated()->getEmptyDropdownArray();
     $output['multiOptions'] = $empty + $this->db->fetchPairs($sql, $context['gr2t_id_user']);
     return $output;
 }
 /**
  * Show the changes in the database
  */
 public function showChangesAction()
 {
     $patchLevels = $this->db->fetchPairs('SELECT DISTINCT gpa_level, gpa_level FROM gems__patches ORDER BY gpa_level DESC');
     $searchData['gpa_level'] = reset($patchLevels);
     if ($this->request instanceof \Zend_Controller_Request_Abstract) {
         $searchData = $this->request->getParams() + $searchData;
     }
     $snippet = $this->addSnippet('Database\\StructuralChanges', 'patchLevels', $patchLevels, 'searchData', $searchData);
     if (1 == $this->request->getParam('download')) {
         $snippet->outputText($this->view, $this->_helper);
     }
 }
Esempio n. 21
0
 /**
  * Set those settings needed for the browse display
  *
  * @return \Gems\Model\LogModel
  */
 public function applyBrowseSettings($detailed = false)
 {
     $this->resetOrder();
     //Not only active, we want to be able to read the log for inactive organizations too
     $orgs = $this->db->fetchPairs('SELECT gor_id_organization, gor_name FROM gems__organizations');
     $this->set('gla_created', 'label', $this->_('Date'));
     $this->set('gls_name', 'label', $this->_('Action'));
     $this->set('gla_organization', 'label', $this->_('Organization'), 'multiOptions', $orgs);
     $this->set('staff_name', 'label', $this->_('Staff'));
     $this->set('gla_role', 'label', $this->_('Role'));
     $this->set('respondent_name', 'label', $this->_('Respondent'));
     $jdType = new JsonData();
     $this->set('gla_message', 'label', $this->_('Message'));
     $jdType->apply($this, 'gla_message', $detailed);
     if ($detailed) {
         $this->set('gla_data', 'label', $this->_('Data'));
         $jdType->apply($this, 'gla_data', $detailed);
         $this->set('gla_method', 'label', $this->_('Method'));
         $this->set('gla_remote_ip', 'label', $this->_('IP address'));
     }
 }
 /**
  * Get the calculate from options
  *
  * @param int $trackId
  * @return array
  */
 protected function getOptions($trackId = null)
 {
     if (null === $trackId) {
         $trackId = $this->_trackId;
     }
     $appFields = $this->db->fetchPairs("\n            SELECT gtap_id_app_field, gtap_field_name\n                FROM gems__track_appointments\n                WHERE gtap_id_track = ?\n                ORDER BY gtap_id_order", $trackId);
     $options = array();
     if ($appFields) {
         foreach ($appFields as $id => $label) {
             $key = FieldsDefinition::makeKey(FieldMaintenanceModel::APPOINTMENTS_NAME, $id);
             $options[$key] = $label;
         }
     }
     return $options;
 }
 /**
  * Override this function when you need to perform any actions when the data is loaded.
  *
  * Test for the availability of variables as these objects can be loaded data first after
  * deserialization or registry variables first after normal instantiation.
  *
  * That is why this function called both at the end of afterRegistry() and after exchangeArray(),
  * but NOT after unserialize().
  *
  * After this the object should be ready for serialization
  */
 protected function afterLoad()
 {
     if ($this->_data && $this->db instanceof \Zend_Db_Adapter_Abstract && !($this->_activities || $this->_procedures)) {
         if ($this->_data['gaf_filter_text1']) {
             $sqlActivites = "SELECT gaa_id_activity, gaa_id_activity\n                    FROM gems__agenda_activities\n                    WHERE gaa_active = 1 AND gaa_name LIKE '%s'\n                    ORDER BY gaa_id_activity";
             $this->_activities = $this->db->fetchPairs(sprintf($sqlActivites, addslashes($this->_data['gaf_filter_text1'])));
         } else {
             $this->_activities = true;
         }
         if ($this->_data['gaf_filter_text2'] || $this->_data['gaf_filter_text2']) {
             $sqlProcedures = "SELECT gapr_id_procedure, gapr_id_procedure\n                    FROM gems__agenda_procedures\n                    WHERE gapr_active = 1 ";
             if ($this->_data['gaf_filter_text2']) {
                 $sqlProcedures .= sprintf(" AND gapr_name LIKE '%s' ", addslashes($this->_data['gaf_filter_text2']));
             }
             if ($this->_data['gaf_filter_text3']) {
                 $sqlProcedures .= sprintf(" AND gapr_name NOT LIKE '%s' ", addslashes($this->_data['gaf_filter_text3']));
             }
             $sqlProcedures .= "ORDER BY gapr_id_procedure";
             $this->_procedures = $this->db->fetchPairs($sqlProcedures);
         } else {
             $this->_procedures = true;
         }
     }
 }
 /**
  * Return a list of organizations that are considered top-organizations, in this
  * case organizations that are not accessible by others as they are considered
  * the children of the top organizations. Feel free to modify to suit your
  * needs.
  *
  * @return array
  */
 public function getTopOrganisations()
 {
     try {
         $organizations = $this->db->fetchPairs('SELECT gor_id_organization, gor_name FROM gems__organizations WHERE gor_active=1 AND gor_has_login=1 AND (gor_accessible_by IS NULL OR gor_accessible_by = "::") ORDER BY gor_name');
     } catch (\Exception $e) {
         try {
             // 1.4 fallback
             $organizations = $this->db->fetchPairs('SELECT gor_id_organization, gor_name FROM gems__organizations WHERE gor_active=1 AND gor_accessible_by IS NULL ORDER BY gor_name');
         } catch (\Exception $e) {
             $organizations = array();
         }
     }
     natsort($organizations);
     return $organizations;
 }
 public function getAvailableMailTemplates($list = false, $target = false)
 {
     $select = $this->loader->getModels()->getCommTemplateModel()->getSelect();
     if ($target) {
         if (is_array($target)) {
             $select->where('gct_target IN (?)', $target);
         } else {
             $select->where('gct_target = ?', $target);
         }
     }
     $templates = $this->db->fetchPairs($select);
     if (!$list) {
         $templates = array('' => '') + $templates;
     }
     return $templates;
 }
 /**
  * Creates a \Zend_Form_Element_Select
  *
  * If $options is a string it is assumed to contain an SQL statement.
  *
  * @param string        $class   Name of the class to use
  * @param string        $name    Name of the select element
  * @param string|array  $options Can be a SQL select string or key/value array of options
  * @param string        $empty   Text to display for the empty selector
  * @return \Zend_Form_Element_Multi
  */
 private function _createMultiElement($class, $name, $options, $empty)
 {
     if ($options instanceof \MUtil_Model_ModelAbstract) {
         $options = $options->get($name, 'multiOptions');
     } elseif (is_string($options)) {
         $options = $this->db->fetchPairs($options);
         natsort($options);
     }
     if ($options || null !== $empty) {
         if (null !== $empty) {
             $options = array('' => $empty) + $options;
         }
         $element = $this->form->createElement($class, $name, array('multiOptions' => $options));
         return $element;
     }
 }
 /**
  * Utility function for loading a query from cache
  *
  * @param string $cacheId The class is prepended to this id
  * @param mixed $sql string or \Zend_Db_Select
  * @param callable $function The function called with each row to form the result
  * @param array $binds sql paramters
  * @param mixed $tags string or array of strings
  * @param string Optional function to sort on, only known functions will do
  * @return array
  */
 protected function _getSelectPairsProcessedCached($cacheId, $sql, $function, $binds = array(), $tags = array(), $sort = null)
 {
     $cacheId = get_class($this) . '_' . $cacheId;
     $result = false;
     //$this->cache->load($cacheId);
     if ($result) {
         return $result;
     }
     $result = $this->db->fetchPairs($sql, (array) $binds);
     if ($result) {
         foreach ($result as $id => &$value) {
             $value = call_user_func($function, $value);
         }
         if ($sort) {
             $this->_sortResult($result, $sort);
         }
     }
     $this->cache->save($result, $cacheId, (array) $tags);
     return $result;
 }
 /**
  * A ModelAbstract->setOnLoad() function that takes care of transforming a
  * dateformat read from the database to a \Zend_Date format
  *
  * If empty or \Zend_Db_Expression (after save) it will return just the value
  * currently there are no checks for a valid date format.
  *
  * @see \MUtil_Model_ModelAbstract
  *
  * @param mixed $value The value being saved
  * @param boolean $isNew True when a new item is being saved
  * @param string $name The name of the current field
  * @param array $context Optional, the other values being saved
  * @param boolean $isPost True when passing on post data
  * @return \MUtil_Date|\Zend_Db_Expr|string
  */
 public function calculateTrackUsage($value, $isNew = false, $name = null, array $context = array(), $isPost = false)
 {
     $surveyId = isset($context['gsu_id_survey']) ? $context['gsu_id_survey'] : false;
     if (!$surveyId) {
         return 0;
     }
     $select = new \Zend_Db_Select($this->db);
     $select->from('gems__tracks', array('gtr_track_name'));
     $select->joinLeft('gems__rounds', 'gro_id_track = gtr_id_track', array('useCnt' => 'COUNT(*)'))->where('gro_id_survey = ?', $surveyId)->group('gtr_track_name');
     $usage = $this->db->fetchPairs($select);
     if ($usage) {
         $seq = new \MUtil_Html_Sequence();
         $seq->setGlue(\MUtil_Html::create('br'));
         foreach ($usage as $track => $count) {
             $seq[] = sprintf($this->plural('%d time in %s track.', '%d times in %s track.', $count), $count, $track);
         }
         return $seq;
     } else {
         return $this->_('Not in any track.');
     }
 }
Esempio n. 29
0
 /**
  * Returns the changes that must be made in an array consisting of
  *
  * <code>
  * array(
  *  field1 => array(setting1 => $value1, setting2 => $value2, ...),
  *  field2 => array(setting3 => $value3, setting4 => $value4, ...),
  * </code>
  *
  * By using [] array notation in the setting name you can append to existing
  * values.
  *
  * Use the setting 'value' to change a value in the original data.
  *
  * When a 'model' setting is set, the workings cascade.
  *
  * @param array $context The current data this object is dependent on
  * @param boolean $new True when the item is a new record not yet saved
  * @return array name => array(setting => value)
  */
 public function getChanges(array $context, $new)
 {
     $select = clone $this->_select;
     foreach ($this->_filter as $fieldName => $contextName) {
         if ($contextName instanceof \Zend_Db_Expr) {
             $select->where($fieldName . ' = ?', $contextName);
         } elseif (null === $context[$contextName]) {
             $select->where($fieldName . ' IS NULL');
         } else {
             $select->where($fieldName . ' = ?', $context[$contextName]);
         }
     }
     $options = $this->db->fetchPairs($select);
     // \MUtil_Echo::track($this->getEffecteds());
     $results = array();
     foreach ($this->getEffecteds() as $name => $settings) {
         foreach ($settings as $setting) {
             $results[$name][$setting] = $options;
         }
     }
     return $results;
 }
 /**
  * Returns the current organization according to the current site url.
  *
  * @static array $url An array of url => orgId values
  * @return int An organization id or null
  */
 public function getOrganizationIdByUrl()
 {
     static $urls;
     if (!is_array($urls)) {
         if ($this->cache) {
             $cacheId = GEMS_PROJECT_NAME . '__' . strtr(get_class($this), '\\/', '__') . '__organizations_url';
             $urls = $this->cache->load($cacheId);
         } else {
             $cacheId = false;
         }
         // When we don't use cache or cache reports 'false' for a miss or expiration
         // then try to reload the data
         if ($cacheId === false || $urls === false) {
             $urls = array();
             try {
                 $data = $this->db->fetchPairs("SELECT gor_id_organization, gor_url_base FROM gems__organizations WHERE gor_active=1 AND gor_url_base IS NOT NULL");
             } catch (\Zend_Db_Exception $zde) {
                 // Table might not be filled
                 $data = array();
             }
             foreach ($data as $orgId => $urlsBase) {
                 foreach (explode(' ', $urlsBase) as $url) {
                     if ($url) {
                         $urls[$url] = $orgId;
                     }
                 }
             }
             if ($cacheId) {
                 $this->cache->save($urls, $cacheId, array('organization', 'organizations'));
             }
         }
         // \MUtil_Echo::track($urls);
     }
     $current = $this->util->getCurrentURI();
     if (isset($urls[$current])) {
         return $urls[$current];
     }
 }