Exemple #1
0
 /**
  * Change the status of a block.
  *
  * Invert the status of a given block id (collapsed/uncollapsed).
  *
  * @return void
  */
 public function changestatus()
 {
     $bid = FormUtil::getPassedValue('bid');
     $uid = UserUtil::getVar('uid');
     $dbtable = DBUtil::getTables();
     $column = $dbtable['userblocks_column'];
     $where = "WHERE {$column['bid']}='" . DataUtil::formatForStore($bid) . "' AND {$column['uid']}='" . DataUtil::formatForStore($uid) . "'";
     $active = DBUtil::selectField('userblocks', 'active', $where);
     $obj = array();
     $obj['active'] = $active ? 0 : 1;
     $where = "WHERE {$column['uid']}='" . DataUtil::formatForStore($uid) . "' AND {$column['bid']}='" . DataUtil::formatForStore($bid) . "'";
     $res = DBUtil::updateObject($obj, 'userblocks', $where);
     if (!$res) {
         return LogUtil::registerError($this->__('Error! An SQL error occurred.'));
     }
     // now lets get back to where we came from
     $this->redirect(System::serverGetVar('HTTP_REFERER'));
 }
Exemple #2
0
 public function setTreballCataleg($idCat) {
     // Verificació de seguretat
     if (!SecurityUtil::checkPermission('Cataleg::', '::', ACCESS_ADMIN)) {
         return LogUtil::registerPermissionError();
     }
     $id = (isset($idCat)) ? $idCat : null;
     if ($id) {
         // Variable de mòdul
           $where = "WHERE catId=$id";
           $estatIni = DBUtil::selectField('cataleg','estat',$where);
           if ($estatIni == Cataleg_Constant::TANCAT) {
               $obj = array ('estat' => Cataleg_Constant::LES_MEVES);
               DBUtil::updateObject ($obj, 'cataleg', $where);
           }
         return ModUtil::setVar("Cataleg", "treball", $id);
     } else {
         return false;
     }
 }
Exemple #3
0
 /**
  * Increments or decremnts a sequence number (column position) in a table for a given ID.
  *
  * If exists, it swaps the sequence of the field above or down.
  *
  * @param array  $obj       The object we wish to increment or decrement.
  * @param string $tablename The tablename key for the PNTables structure.
  * @param string $direction Whether we want to increment or decrement the position of the object. Possible values are 'up' (default) and 'down'.
  * @param string $field     The name of the field we wish to resequence.
  * @param string $idcolumn  The column which contains the unique ID.
  * @param string $field2    An additional field to consider in the where-clause.
  * @param string $value2    An additional value to consider in the where-clause.
  *
  * @return true/false on success/failure
  */
 public static function moveField($obj, $tablename, $direction = 'up', $field = 'position', $idcolumn = 'id', $field2 = '', $value2 = '')
 {
     if (!is_array($obj)) {
         throw new \Exception(__f('%1$s: %2$s is not an array.', array('ObjectUtil::moveField', 'object')));
     }
     if (!isset($obj[$idcolumn])) {
         throw new \Exception(__f('Unable to determine a valid ID in object [%1$s, %2$s]', array($idcolumn, 'ObjectUtil::moveField')));
     }
     $dbtables = DBUtil::getTables();
     $table = $dbtables[$tablename];
     $column = $dbtables["{$tablename}_column"];
     if (!$column[$field]) {
         throw new \Exception(__f('%1$s: there is no [%2$s] field in the [%3$s] table.', array('ObjectUtil::moveField', $field, $tablename)));
     }
     // Get info on current position of field
     $where = "{$column[$idcolumn]}='" . DataUtil::formatForStore($obj[$idcolumn]) . "'";
     $seq = DBUtil::selectField($tablename, $field, $where);
     // Get info on displaced field
     $direction = strtolower($direction);
     $where2 = '';
     if ($field2 && $value2) {
         $where2 = " AND {$column[$field2]}='" . DataUtil::formatForStore($value2) . "'";
     }
     if ($direction == 'up') {
         $sql = "SELECT {$column[$idcolumn]}, {$column[$field]}\n                    FROM {$table}\n                    WHERE {$column[$field]} < '" . DataUtil::formatForStore($seq) . "' {$where2}\n                    ORDER BY {$column[$field]} DESC LIMIT 0,1";
     } elseif ($direction == 'down') {
         $sql = "SELECT {$column[$idcolumn]}, {$column[$field]}\n                    FROM {$table}\n                    WHERE {$column[$field]} > '" . DataUtil::formatForStore($seq) . "' {$where2}\n                    ORDER BY {$column[$field]} ASC LIMIT 0,1";
     } else {
         throw new \Exception(__f('%1$s: invalid direction [%2$s] supplied.', array('ObjectUtil::moveField', $direction)));
     }
     $res = DBUtil::executeSQL($sql);
     if ($res->EOF) {
         // No field directly above or below that one
         return false;
     }
     list($altid, $altseq) = $res->fields;
     // Swap sequence numbers
     $sql = "UPDATE {$table} SET {$column[$field]}='" . DataUtil::formatForStore($seq) . "' WHERE {$column[$idcolumn]}='" . DataUtil::formatForStore($altid) . "'";
     $upd1 = DBUtil::executeSQL($sql);
     $sql = "UPDATE {$table} SET {$column[$field]}='" . DataUtil::formatForStore($altseq) . "' WHERE {$column[$idcolumn]}='" . DataUtil::formatForStore($obj[$idcolumn]) . "'";
     $upd2 = DBUtil::executeSQL($sql);
     DBUtil::flushCache($tablename);
     return true;
 }
Exemple #4
0
    /**
     * Import users from CSV file. 
     * @author Josep Ferràndiz Farré (jferran6@xtec.cat)
     * **CSV File header** Allowed fields: uname,new_uname,email,password,forcechgpass,activated,firstname,lastname1,lastname2,birthdate,gender,code,in,out
     * Fields "in" and "out" contains group IDs where the user will be added or removed, separated by "|" char
     * Deletions will be made before insertions.
     * 
     */
    public function import(){
        $this->throwForbiddenUnless(SecurityUtil::checkPermission('IWusers::', '::', ACCESS_ADMIN));
        // Sincronize tables users & IWUsers 
        ModUtil::apiFunc($this->name, 'admin', 'sincronize');
        $view = Zikula_View::getInstance($this->name);
        
        if ($this->request->isPost()) {
            $this->checkCsrfToken();
            $importFile = $this->request->files->get('importFile', null);
            $delimiter  = $this->request->request->get('delimiter', ';');
            // 1. Validate file: header & structure
            if (is_null($importFile)) {
                LogUtil::registerError($this->__('File error. Probably exceeds max. file size.'));
            } else {
                // Header fields table equivalents
                $headerTrans =array('uname'       => 'uname', 
                                    'new_uname'   => 'new_uname', 
                                    'email'       => 'email',
                                    'code'        => 'code',
                                    'password'    => 'password',
                                    'forcechgpass'=> 'forcechgpass',
                                    'activated'   => 'activated',
                                    'firstname'   => 'nom',
                                    'lastname1'   => 'cognom1',
                                    'lastname2'   => 'cognom2',
                                    'description' => 'description',
                                    'birthdate'   => 'naixement',
                                    'gender'      => 'sex',
                                    'in'          => 'in',
                                    'out'         => 'out'
                    );

                $import = new CsvImporter($importFile['tmp_name'],true, $headerTrans, $delimiter);  
                $header  = $import->getHeader();
                $oHeader = $import->getOriHeader();
                
                $check  = ModUtil::apiFunc($this->name, 'admin', 'checkCsvHeader', $header);
                // Check CSV file header
                if (!$check['correcte']) {
                    // CSV header incorrect
                    LogUtil::registerError($check['msg']);
                } else {
                    // Get CSV file content
                    $data = $import->get();
                    // Initialize 
                    $update = array();
                    $insert = array();
                    $optimizeGroups = ((in_array('in', $header)) || (in_array('out', $header)));
                    $forcechgpass   = in_array('forcechgpass', $header);
                    $iErrors = array();
                    // Check file info
                    foreach ($data as &$line) {
                        $uid = UserUtil::getIdFromName($line['uname']);
                        if ($optimizeGroups) {
                            $res = ModUtil::apiFunc($this->name, 'admin', 'optimizeGroups', array('uid' => $uid, 'data'=> $line));
                            $line['in'] = $res['in'];
                            $line['out'] = $res['out'];                            
                        }                            
                        if ($uid){       
                            $line['uid'] = $uid;
                            // Update
                            if (isset($line['activated'])){
                                if ($line['activated']!=""){
                                    $line['activated'] = $line['activated'] == '0' ? 0 : 1;                                    
                                } else {
                                    // Mantain actual value
                                    $line['activated'] = DBUtil::selectField('users', 'activated', 'uid='.$uid);
                                }                                
                            }
                            $update[] = $line;                                
                        } else {
                            // Insert new user
                            if ($line['uname'] !=""){
                                if (!isset($line['activated']) || (isset($line['activated']) && $line['activated']!='0')) $line['activated'] = 1;
                                $insert[] = $line;
                            } else {
                                // Error. No username 
                                $line['error'] = $this->__('No username.');
                                $iErrors[] = $line;
                            }
                        }                            
                    }
                    // Process file information
                    $allChanges = ModUtil::apiFunc($this->name, 'admin', 'applyCsvValues', array('update' => $update, 'insert' =>$insert));               
                    unset($update); $update = array();
                    unset($insert); $insert = array();
                    foreach ($allChanges as $user){                       
                        switch ($user['action']){
                            case 'm':
                                $update[] = $user;
                                break;
                            default:
                                $insert[] = $user;
                        }
                        if (isset($user['error'])){ 
                            // There are errors
                            $iErrors[] = $user;
                        }
                    }
                    $view->assign('insert', $insert);
                    $view->assign('update', $update);
                    $view->assign('iErrors', $iErrors);
                    $view->assign('header', $oHeader);
                    $view->assign('hc', count($oHeader));
                    return $view->fetch('IWusers_admin_importResults.tpl');        

                } // File header is correct
            } // exist import file                
        } // Is POST
         
        // Get zikula groups name and gid
        $g = UserUtil::getGroups('','name');
        foreach ($g as $key => $value) {
            $groupInfo[] = array_slice($value,0,2);
        }
                
        $view->assign('post_max_size', ini_get('post_max_size'));
        $view->assign('groupInfo', $groupInfo);
        
        return $view->fetch('IWusers_admin_import.tpl');        
    }
Exemple #5
0
 public function processRecoveryPassword()
 {
     // get variables
     $username = $this->INPUT['zuname'];
     $password1 = $this->INPUT['zpass1'];
     $password2 = $this->INPUT['zpass2'];
     // check that username is not empty
     if (empty($username)) {
         $this->setError(__('Username cannot be empty'));
         return false;
     }
     // check that password is not empty
     if (empty($password1)) {
         $this->setError(__('Password cannot be empty'));
         return false;
     }
     // check that passwords match
     if ($password1 != $password2) {
         $this->setError(__('Passwords do not match'));
         return false;
     }
     // check that username is not the anonymous one
     $anonymous = ModUtil::getVar('Users', 'anonymous');
     if ($username == $anonymous || $username == strtolower($anonymous)) {
         $this->setError(__('You cannot change the password for the anonymous user. Please provide the username of a valid user'));
         return false;
     }
     $table = DBUtil::getTables();
     $userstable = $table['users'];
     $userscolumn = $table['users_column'];
     // check that username exists
     $uid = DBUtil::selectField('users', 'uid', $userscolumn['uname'] . "='" . $username . "'");
     if (!$uid) {
         $this->setError(__('The username you supplied is not valid'));
         return false;
     }
     // hash the password and check if it is valid
     $password = UserUtil::getHashedPassword($password1);
     if (!$password) {
         $this->setError(__('The password you supplied is not valid'));
         return false;
     }
     // update the password
     // create the object
     $obj = array('uid' => $uid, 'pass' => $password);
     // perform update
     if (!DBUtil::updateObject($obj, 'users', '', 'uid')) {
         $this->setError(__('Error resetting the password'));
         return false;
     }
     // Set a status message.
     $this->setStatus(__('The password was successfully reset'));
     // Recovery successful.
     return true;
 }
Exemple #6
0
 public function nom_marc($args) {
     // Security check
     if (!SecurityUtil::checkPermission('IWbookings::', "::", ACCESS_ADMIN)) {
         throw new Zikula_Exception_Forbidden();
     }
     
     // Checks if module IWtimeframes is installed. 
     if (ModUtil::apiFunc('IWbookings', 'admin','check_module','IWtimeframes')) {
         $mdid = FormUtil::getPassedValue('mdid', isset($args['mdid']) ? $args['mdid'] : null, 'POST');
         $name = DBUtil::selectField('IWtimeframes_definition', 'nom_marc', 'mdid =' . $mdid);
  
         if (empty($name)) { // EL marc horari referenciat no existeix              
             // Actualitzar la informació relativa dels espais 
             ModUtil::apiFunc('IWbookings', 'admin','reset_timeframe',$mdid); 
         }
         return $name;
     }         
 }
Exemple #7
0
    /**
     *  Comprova si un usuari pot realitzar una acció amb una activitat
     *
     * > El resultat dependrà de l'estat i editabilitat del catàleg, de l'estat de\n
     * > l'activitat (en els casos d'edició d'activitat existent) i de si l'usuari \n
     * > pertany al grup propietari de l'activitat
     * 
     * @param array $args Array amb els paràmetres de la funció
     *
     * ### Paràmetres de l'array $args:
     * * string **accio** Nom de la funció de la qual se'n vol verificar l'accessibilitat
     * * integer **id** Id de l'element per verificar (catId, actId o uniId)
     * 
     * @return aboolean **true** Si es pot executar la funció demanada o **false** en cas contrari
     */
    public function haveAccess($args) {
        //Verificar permisos
        $this->throwForbiddenUnless(SecurityUtil::checkPermission('Cataleg::', '::', ACCESS_READ));

        $accio = isset($args['accio']) ? $args['accio'] : null;
        $id = isset($args['id']) ? $args['id'] : null;

        $result = false; // retorn per defecte
        if (SecurityUtil::checkPermission('Cataleg::', '::', ACCESS_ADMIN))
            $result = true; // Gestors accés total
        else {
            if (!is_null($id) && is_numeric($id)) {
                switch ($accio) {
                    // funcions d'edició d'activitats
                    case "edit": // Mostrar el formulari d'edició d'activitats. Espera actId
                        $catId = ModUtil::apiFunc($this->name, 'user', 'getParent', array('id' => 'actId', 'value' => $id));
                        //Obtenir editabilitat i estat del catàleg
                        $catDisp = DBUtil::selectObject('cataleg', 'catId=' . $catId, array('estat', 'editable'));
                        // Una activitat és editable si catàleg no està TANCAT i editable = 1
                        $catEditable = $catDisp['editable'] && ($catDisp['estat'] >= Cataleg_Constant::LES_MEVES);
                        // Obtenim estat de l'activitat
                        $estat = DBUtil::selectField('cataleg_activitats', 'estat', 'actId=' . $id);
                        // Un usuari només pot editar activitats d'una unitat a la qual pertanyi
                        $isMine = ModUtil::apiFunc($this->name, 'user', 'isMine', $id);
                        $result = ($estat != Cataleg_Constant::ENVIADA && $estat != Cataleg_Constant::ANULLADA && $catEditable && $isMine);
                        break;
                    case "addnew": // Mostrar el formulari de creació d'activitats si cataleg editable i no tancat
                        // Espera catId
                        $catDisp = DBUtil::selectObject('cataleg', 'catId=' . $id, array('estat', 'editable'));
                        $result = ( $catDisp['estat'] > Cataleg_Constant::TANCAT ) && $catDisp['editable'];
                        break;
                    case "save": // Desar canvis en una activitat exitent. Espera actId
                        $catId = ModUtil::apiFunc($this->name, 'user', 'getParent', array('id' => 'actId', 'value' => $id));
                        $catDisp = DBUtil::selectObject('cataleg', 'catId=' . $catId, array('estat', 'editable'));
                        $isMine = ModUtil::apiFunc($this->name, 'user', 'isMine', $id);

                        $result = $isMine && ($catDisp['estat'] > Cataleg_Constant::TANCAT ) && $catDisp['editable'] && ($estat == Cataleg_Constant::ESBORRANY);
                        break;
                    case "new": // Crear una activitat nova (no hi ha actId). Espera uniId
                        // Obtenir catàleg a partir uniId 
                        $catId = ModUtil::apiFunc($this->name, 'user', 'getParent', array('id' => 'uniId', 'value' => $id));
                        // Disponibilitat del catàleg
                        $catDisp = DBUtil::selectObject('cataleg', 'catId=' . $catId, array('estat', 'editable'));
                        // Verificar que usuari és membre de uniId 
                        $isMember = ModUtil::apiFunc($this->name, 'user', 'isMember', $id);
                        $result = $isMember && ( $catDisp['estat'] > Cataleg_Constant::TANCAT ) && $catDisp['editable'];
                        break;
                    case "delete": // Esborrar una activitat. Espera actId
                        $catId = ModUtil::apiFunc($this->name, 'user', 'getParent', array('id' => 'actId', 'value' => $id));
                        $catDisp = DBUtil::selectObject('cataleg', 'catId=' . $catId, array('estat', 'editable'));
                        $isMine = ModUtil::apiFunc($this->name, 'user', 'isMine', $id);
                        // Estat de l'activitat ESBORRANY
                        $estat = DBUtil::selectField('cataleg_activitats', 'estat', 'actId=' . $id);
                        $result = $isMine && ($catDisp['estat'] > Cataleg_Constant::TANCAT ) && $catDisp['editable'] && ($estat == Cataleg_Constant::ESBORRANY);
                        break;

                    // Opcions de lectura
                    case "cataleg": // Mostra les línies prioritàries i enllaços a orientacions i activitats.                            
                    case "display": // orientacions de línia prioritària. Espera catId
                        $catEstat = DBUtil::selectField('cataleg', 'estat', 'catId=' . $id);
                        // Els editors accedeixen al catàleg si l'estat és ORIENTACIONS o més
                        if (SecurityUtil::checkPermission('Cataleg::', '::', ACCESS_ADD)) // És editor
                            $result = ($catEstat >= Cataleg_Constant::ORIENTACIONS);
                        else
                            $result = ($catEstat == Cataleg_Constant::OBERT);
                        break;

                    case "show": // Detall d'una fitxa d'activitat
                        $catId = ModUtil::apiFunc($this->name, 'user', 'getParent', array('id' => 'actId', 'value' => $id));
                        $catEstat = DBUtil::selectField('cataleg', 'estat', 'catId=' . $catId);
                        // Els editors accedeixen al catàleg si l'estat és ACTIVITATS o més
                        if (SecurityUtil::checkPermission('Cataleg::', '::', ACCESS_ADD)) {// És editor
                            if (ModUtil::apiFunc($this->name, 'user', 'isMine', $id)) {
                                $result = ($catEstat >= Cataleg_Constant::LES_MEVES);
                            } else {
                                $result = ($catEstat >= Cataleg_Constant::ACTIVITATS);
                            }
                        } else {
                            $result = ($catEstat == Cataleg_Constant::OBERT);
                        }
                        break;
                    case "activitats": // Llistat d'activitats per prioritat
                        $catEstat = DBUtil::selectField('cataleg', 'estat', 'catId=' . $id);
                        // Els editors accedeixen al catàleg si l'estat és ACTIVITATS o més
                        if (SecurityUtil::checkPermission('Cataleg::', '::', ACCESS_ADD)) // És editor
                            $result = ($catEstat >= Cataleg_Constant::ACTIVITATS);
                        else
                            $result = ($catEstat == Cataleg_Constant::OBERT);
                        break;
                    case "view": // Accés a "Les meves activitats"
                        $catEstat = DBUtil::selectField('cataleg', 'estat', 'catId=' . $id);
                        // Els editors accedeixen al catàleg si l'estat és ACTIVITATS o més
                        if (SecurityUtil::checkPermission('Cataleg::', '::', ACCESS_ADD)) // És editor
                            $result = ($catEstat >= Cataleg_Constant::LES_MEVES);
                        break;
                }
            }
        }
        return $result;
    }
Exemple #8
0
    /**
     * Add a user to a group item.
     *
     * @param int $args['gid'] the ID of the item.
     * @param int $args['uid'] the ID of the user.
     *
     * @return bool true if successful, false otherwise.
     */
    public function adduser($args)
    {
        $this->throwForbiddenUnless(SecurityUtil::checkPermission('IWusers::', '::', ACCESS_ADD));
        // Argument check
        if ((!isset($args['gid'])) || (!isset($args['uid']))) {
            return LogUtil::registerArgsError();
        }

        $where = 'gid='.$args['gid'];
        $item = DBUtil::selectField('groups', 'gid', $where);
       
        if ($item == false) {
            return LogUtil::registerError($this->__('Sorry! No such item found.'));
        }
        
        // Add item
        $object = array('gid' => $args['gid'],
                'uid' => $args['uid']);
        $result = DBUtil::insertObject($object, 'group_membership');

        // Check for an error with the database code
        if (!$result) {
            return LogUtil::registerError($this->__('Error! Could not create the new item.'));
        }

        // Let other modules know that we have updated a group.
        $adduserEvent = new Zikula_Event('group.adduser', $object);
        $this->eventManager->notify($adduserEvent);

        // Let the calling process know that we have finished successfully
        return true;
    }
Exemple #9
0
 /**
  * Creació i/o Edició d'un usuari del catàleg
  *
  * ### Paràmetres rebuts per POST:
  * -Corresponents als diferents camps de la taula *users*-
  * * integer **uid** [opcional definit-edició/no_definit-creació]
  * * string **uname**
  * 
  * -Corresponents als diferents camps de la taula *iw_users*-
  * * string **iw_nom**
  * * string **iw_cognom1**
  * * string **iw_cognom2**
  * 
  * -Per gestionar les grups relacionats amb el catàleg-
  * * array **groups**
  * 
  * -Per gestionar la contrasenya de l'usuari-
  * * string **password**
  * * string **rpassword**
  * * string **changeme**
  *
  * @return void Retorna a la funció *usergest* després de desar les dades
  */
 public function addeditUser() {
     //Comprovacions de seguretat. Només els gestors poden crear i editar usuaris
     if (!SecurityUtil::checkPermission('Cataleg::', '::', ACCESS_ADMIN)) {
         return LogUtil::registerPermissionError();
     }
     // Primer desem les modificacions de les dades d'usuari a users i a IWusers i reassignem els grups de l'usuari
     $user['zk']['uid'] = FormUtil::getPassedValue('uid', null, 'POST');
     //Comprovem si es passa una uid (per editar) o no (i s'ha de crear un nou usuari)
     if (!empty($user['zk']['uid'])) {
         //Comprovem que aquest usuari eixisteixi i es pugui editar (és a dir, que sigui del grup d'usuaris del catàleg)
         $grupCat = ModUtil::apiFunc('Cataleg', 'admin', 'getgrupsZikula');
         $catUsersList = UserUtil::getUsersForGroup($grupCat['Sirius']);
         if (!in_array($user['zk']['uid'], $catUsersList)) {
             LogUtil::registerError($this->__('No existeix cap usuari del catàleg amb l\'identificador indicat.'));
             return system::redirect(ModUtil::url('Cataleg', 'admin', 'usersgest'));
         }
         $user['iw']['uid'] = $user['zk']['uid'];
         $user['iw']['suid'] = $user['zk']['uid'];
         $r = 'edit';
     }
     $user['zk']['uname'] = FormUtil::getPassedValue('uname', null, 'POST');
     //Comprovem que no existeix cap usuari amb aquest uname
     if (!empty($user['zk']['uid'])) {
         $where = "uname = '" . $user['zk']['uname'] . "' AND uid != " . $user['zk']['uid'];
     } else {
         $where = "uname = '" . $user['zk']['uname'] . "'";
     }
     $uname = UserUtil::getUsers($where);
     if ($uname) {
         LogUtil::registerError($this->__('El nom d\'usuari triat ja existeix.'));
         return system::redirect(ModUtil::url('Cataleg', 'admin', 'usersgest'));
     }
     $user['zk']['email'] = FormUtil::getPassedValue('email', null, 'POST');
     $user['iw']['nom'] = FormUtil::getPassedValue('iw_nom', null, 'POST');
     $user['iw']['cognom1'] = FormUtil::getPassedValue('iw_cognom1', null, 'POST');
     $user['iw']['cognom2'] = FormUtil::getPassedValue('iw_cognom2', null, 'POST');
     $user['gr'] = FormUtil::getPassedValue('groups', null, 'POST');
     
     $prev_pass = FormUtil::getPassedValue('prev_pass', 0, 'POST');
     $setpass = FormUtil::getPassedValue('setpass', 0, 'POST');
     if ($setpass == 1) {
         $password = FormUtil::getPassedValue('password', null, 'POST');
         $changeme = FormUtil::getPassedValue('changeme', 0, 'POST');
     } else {
         $password = null;
     }
     $setcode = FormUtil::getPassedValue('setcode', 0, 'POST');
     if ($setcode == 1) $iwcode = FormUtil::getPassedValue('iwcode_s', null, 'POST');
     if ($setcode == 2) $iwcode = FormUtil::getPassedValue('iwcode_m', null, 'POST');
     if ($iwcode) {
         $user['iw']['code'] = $iwcode;
     } elseif ($r == 'edit'){
         $iwcode = DBUtil::selectField('IWusers', 'code', 'iw_uid='.$user['zk']['uid']);
     }
     if ($iwcode) {
         $gtafInfo = ModUtil::apiFunc('Cataleg','admin','getGtafEntity',$iwcode);
         $grupCat = ModUtil::apiFunc('Cataleg', 'admin', 'getgrupsZikula');
         if (isset($grupCat[$gtafInfo['entity']['tipus']])) $user['gr'][] = $grupCat[$gtafInfo['entity']['tipus']];
     }
     $insertUserId = ModUtil::apifunc('Cataleg', 'admin', 'saveUser', $user);
     if ($insertUserId) {
         if ($r == 'edit') {
             LogUtil::registerStatus($this->__('L\'usuari s\'ha editat correctament.'));
         } else {
             LogUtil::registerStatus($this->__('L\'usuari s\'ha creat correctament.'));
         }
     } else {
         LogUtil::registerError($this->__('No s\'ha pogut desar l\'usuari.'));
         return system::redirect(ModUtil::url('Cataleg', 'admin', 'usersgest'));
     }
     //Si es tria 'buidar' la contrasenya, aquesta opció mana sobre el canvi i forçar el canvi
     if ($setpass == 2) {
         $reg = array('pass' => '');
         if (DBUtil::updateObject($reg,'users','uid ='. $insertUserId)) {
             UserUtil::setVar('', $passreminder, $insertUserId);
             LogUtil::registerStatus($this->__('L\'usuari haurà de validar-se per LDAP'));
         }
     }
     // Segon pas: desem el possible canvi de contrasenya
     if ($password) {
         $rpassword = FormUtil::getPassedValue('rpassword', null, 'POST');
         $passreminder = $this->__('Constasenya establerta des de l\'administració.');
         $passwordErrors = ModUtil::apiFunc('Users', 'registration', 'getPasswordErrors', array(
                     'uname' => $user['zk']['uname'],
                     'pass' => $password,
                     'passagain' => $rpassword,
                     'passreminder' => $passreminder
         ));
         if (empty($passwordErrors)) {
             if (UserUtil::setPassword($password, $insertUserId)) {
                 UserUtil::setVar('passreminder', $passreminder, $insertUserId);
                 LogUtil::registerStatus($this->__('S\'ha desat la contrasenya.'));
             }
         } else {
             LogUtil::registerError($this->__('No s\'ha desat la contrasenya.'));
             LogUtil::registerError($passwordErrors['pass']);
         }
     }
     // Tercer pas: establim la variable que controla el forçar el canvi de contrasenya
     if ($setpass == 1 && ($prev_pass || $password)) {
         UserUtil::setVar('_Users_mustChangePassword', $changeme, $insertUserId);
         if ($changeme == 1)
             LogUtil::registerStatus($this->__('L\'usuari haurà de canviar la contrasenya en la propera validació.'));
     }
     return system::redirect(ModUtil::url('Cataleg', 'admin', 'usersgest'));
 }