cruge / models / data / CrugeStoredUser.php

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
<?php
/**
 * CrugeStoredUser
 *
 *  Modelo que realiza la persistencia de components.CrugeUser
 *
 * @property integer $iduser
 * @property string $username
 * @property string $email
 * @property string $password
 * @property string $authkey
 * @property integer $state
 * @property integer $totalsessioncounter
 * @property integer $currentsessioncounter
 * @property string $regdate    fecha de registro
 * @property string $actdate    fecha de activacion
 * @property string $logondate    ultimo login exitoso
 * @author: Christian Salazar H. <christiansalazarh@gmail.com> @bluyell
 * @license protected/modules/cruge/LICENSE
 */
class CrugeStoredUser extends CActiveRecord implements ICrugeStoredUser
{
    public $_fields = array();
    public $deleteConfirmation; // required on 'delete'
    public $newPassword; // declararlo 'safe'

    // terminos y condiciones, caso registration,
    public $terminosYCondiciones;
    public $verifyCode;

    // establecer a true si se quiere saltar la validacion de captcha.
    // ver acerca de: cruge\components\CrugeUserManager.php::createBlankUser
    public $bypassCaptcha;

	public function getCustomFieldValue($fieldname, $defValue=""){
		$field = $this->getCustomField($fieldname);
		if($field != null)
			return $field->getFieldValue();
		return $defValue;
	}

	public function getCustomField($fieldname){
		foreach($this->getFields() as $obj)
			if($fieldname == $obj->fieldname)
				return $obj;
		return null;
	}

	public function getUserDescription(){
		$fieldNames = CrugeUtil::config()->userDescriptionFieldsArray;
		$tmp = "";
		if(in_array("username",$fieldNames))
			$tmp .= ",".$this->username;
		if(in_array("email",$fieldNames))
			$tmp .= ",".$this->email;
		if($fieldNames != null)
		foreach($fieldNames as $fname)
			if(($fname != "username") && ($fname != "email"))
			$tmp .= ",".$this->getCustomFieldValue($fname,"nohay_".$fname);
		if($tmp == "")
			$tmp = $this->getUsername();
		return ltrim($tmp,", ");
	}

    /* es un loadModel de uso multiple. $modo puede ser: 'iduser','username' o 'email' para
        indicar por cual campo se quiere cargar el modelo.
        @returns ICrugeStoredUser
    */
    public static function loadModel($id, $modo = 'iduser')
    {
        return self::model()->findByAttributes(array($modo => $id));
    }

    /* entrega un array con los nombres de los atributos clave para orden, de primero el userid */
    public static function getSortFieldNames()
    {
        return array('iduser', 'username', 'email', 'state', 'logondate');
    }

    public function getStateName()
    {
        return Yii::app()->user->um->getStateName($this->state);
    }

    /*
        recibe un array de instancias de ICrugeField previamente cargada de valores
    */
    public function setFields($arFields)
    {
        $this->_fields = $arFields;
    }

    public function getFields()
    {
        if ($this->_fields == null) {
            return array();
        }
        return $this->_fields;
    }

    public function setAttributes($values, $safeOnly = true)
    {

        if (count($this->getFields()) > 0) {
            $test = __CLASS__ . ".setAttributes:\n";
            foreach ($values as $k => $v) {
                $test .= "[{$k}={$v}]\n";
            }
            $test .= "\nparse field values:\n";
            foreach ($values as $fieldName => $value) {
                $test .= "{$fieldName}...";

                $boolFound = false;
                foreach ($this->getFields() as $f) {
                    if ($f->fieldname == $fieldName) {
                        $test .= " found. setfieldvalue:[{$value}]\n";
                        $f->setFieldValue($value);
                        $boolFound = true;
                        break;
                    }
                }
                if ($boolFound == false) {
                    $test .= " [not found]\n";
                }
            }
            Yii::log($test, "info");
        }

        parent::setAttributes($values);
    }

    public function validate($attributes = null, $clearErrors = true)
    {
		// si el metodo de autenticacion es solo email, y, username es blanco
		// se genera uno automaticamente:
		if($this->scenario == 'insert'){
		$declared_authmodes = CrugeUtil::config()->availableAuthModes;
		if(count($declared_authmodes == 1)){
			if(($declared_authmodes[0] == 'email') && ($this->username=='')){
				$um = new CrugeUserManager();
				$this->username = $um->generateNewUserName($this->email);
			}else
			if(($declared_authmodes[0] == 'username') && ($this->email=='')){
				$this->email = $this->username.'@noemail.local';
			}
		}}

        // realiza la validacion normal sobre los atributos de este modelo
        $validateResult = parent::validate();

        // ahora realiza la validacion sobre aquellos campos personalizados
        // y copia todos los errores al objeto mayor ($this)
        //
        foreach ($this->getFields() as $f) {
            if ($f->validateField() == false) {
                $this->addErrors($f->getErrors());
                $validateResult = false;
            }
        }

        return $validateResult;
    }

    public function save($runValidation = true, $attributes = null)
    {
        Yii::log(__METHOD__, "info");
        if ($this->hasErrors()) {
            Yii::log(__METHOD__ . " return false, has errors.", "info");
            return false;
        }

        // importante aqui:
        // primero debe guardar el usuario (this) y luego los campos
        // si se hiciera al reves y el escenario fuese 'insert' entonces al crear el CrugeFieldValue // se generaria un error porque el user->iduser no existiria aun.
        //
        $ok = parent::save();
        $this->saveFields();

        Yii::log(__METHOD__ . " returns: [" . $ok . "]", "info");
        return $ok;
    }

    public function saveFields()
    {
        foreach ($this->getFields() as $f) {
            // buscar el objeto ICrugeFieldValue, darle valores y guardarlo
            $crugeFieldValueInst = Yii::app()->user->um->loadICrugeFieldValue($this, $f);
            $boolOk = false;
            if ($crugeFieldValueInst != null) {
                $crugeFieldValueInst->value = $f->getFieldValue();
                $boolOk = $crugeFieldValueInst->save();
            }
            Yii::log(
                "\n" . __METHOD__ . " \nfieldname='" . $f->fieldname . "'\nfieldvalue='" . $f->getFieldValue()
                    . "'\n boolOk=[" . $boolOk . "]\ncrugeFieldValueInst=[" . ($crugeFieldValueInst == null ? 'null' : 'not null') . "]\n\n",
                "info"
            );
        }
    }

    /**
    @retuns string nombre de usuario (para login).
     */
    public function getUserName()
    {
        return $this->username;
    }

    public function getEmail()
    {
        return $this->email;
    }

    public function tableName()
    {
        return CrugeUtil::getTableName('user');
    }

    public function getPrimaryKey()
    {
        return $this->iduser;
    }

    public static function listModels($param = array())
    {
        return self::model()->findAllByAttributes($param);
    }

    public function getUpdateUrl()
    {
        return 'index.php?r=test' . $this->getPrimaryKey();
    }


    /**
     * Returns the static model of the specified AR class.
     * @return CrugeStoredUser the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }


    /**  hay un escenario llamado 'internal', que es puesto por CrugeUserManager::save()
     *   para poder guardar atributos especificos sin ser afectado por las reglas para formularios
     *
     *
     *
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        return array(
            array(
                'username',
                'match',
                'pattern' => '/^[a-zA-Z0-9\_\-\.]{3,45}$/'
            ,
                'message' => CrugeTranslator::t('logon', 'Invalid username')
            ),
            array('username,email', 'required'),
            array('newPassword', 'safe', 'on' => 'update'),
            array('newPassword', 'required', 'on' => 'insert, manualcreate'),
            array('newPassword', 'length', 'min' => 6, 'max' => 20),
            array(
                'newPassword',
                'match'
            ,
                'pattern' => '/^[a-zA-Z0-9@#$%]{6,20}$/'
            ,
                'message' => CrugeTranslator::t(
                    'logon',
                    'Password may contain numbers or symbols ({symbols}) and between {min} and {max} characters',
                    array('{symbols}' => '@#$%', '{min}' => 6, '{max}' => 20)
                )
            ),
            array('username, password', 'length', 'max' => 64),
            array('state', 'numerical', 'integerOnly' => true),
            array('authkey', 'length', 'max' => 100),
            array('email', 'email'),
            array('email', 'length', 'max' => 100),
            array('username,email', 'validate_unique'),
            array('deleteConfirmation', 'required', 'on' => 'delete'),
            array(
                'deleteConfirmation',
                'compare',
                'compareValue' => '1'
            ,
                'on' => 'delete',
                'message' => CrugeTranslator::t('logon', 'Please, confirm checking the checkbox')
            ),
            array(
                'terminosYCondiciones',
                'required'
            ,
                'requiredValue' => '1'
            ,
                'on' => 'insert'
            ,
                'message' => CrugeTranslator::t('logon', 'Please, check if you understand and accept the terms of use'),
            ),
            array(
                'verifyCode',
                $this->_getCaptchaRule(),
                'on' => 'insert',
                'message' => CrugeTranslator::t('logon', 'Security code is mandatory'),
            ),
            array(
                'verifyCode',
                'captcha',
                'on' => 'insert',
                'allowEmpty' => true,
                'message' => CrugeTranslator::t('logon', 'Security code is invalid'),
            ),
            array('iduser, username, email, state, logondate', 'safe', 'on' => 'search'),

        );
    }

    /**
    al establecer $_crugeStoredUser->bypassCaptcha = true;
    entonces el captcha no sera tomado en cuenta.

    esta funcion es util cuando se quiere crear un nuevo usuario de cruge por la via del API.
     */
    private function _getCaptchaRule()
    {
        if (Yii::app()->user->um->getDefaultSystem()->getn('registerusingcaptcha') == 1) {
            // el administrador decidio pedir captcha para registrar los usuarios,
            // 	pero quiza el flag bypassCaptcha este activo.
            if ($this->bypassCaptcha == true) {
                // captcha es requerido, pero sera no sera tomado en cuenta.
                $this->verifyCode = null;
                return 'safe';
            } else {
                return 'required';
            } // captcha es requerido
        } else {
            // el administrador ha deshabilitado el uso de captcha.
            $this->verifyCode = null;
            return 'safe';
        }
    }


    public function validate_unique($att, $params)
    {
        $model = self::model()->findByAttributes(array($att => $this[$att]));
        if ($model != null) {
            $duptext = CrugeTranslator::t('logon', '\'{attribute}\' already in use', array('attribute' => $att));
            if ($this->scenario == 'insert') {
                $this->addError($att, $duptext);
                return;
            }
            if ($this->scenario == 'update') {
                if ($this->iduser != $model->iduser) {
                    $this->addError($att, $duptext);
                }
                return;
            }
        }
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'sessions' => array(self::HAS_MANY, 'crugesession', 'iduser'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'idusuario' => ucfirst(CrugeTranslator::t('usuario#')),
            'username' => ucfirst(CrugeTranslator::t('username')),
            'email' => ucfirst(CrugeTranslator::t('correo')),
            'password' => ucfirst(CrugeTranslator::t('clave')),
            'authkey' => ucfirst(CrugeTranslator::t('llave de autenticacion')),
            'state' => ucfirst(CrugeTranslator::t('estado de la cuenta')),
            'newPassword' => ucfirst(CrugeTranslator::t('clave')),
            'deleteConfirmation' => ucfirst(CrugeTranslator::t('confirmar eliminacion')),
            'regdate' => ucfirst(CrugeTranslator::t('registrado')),
            'actdate' => ucfirst(CrugeTranslator::t('activado')),
            'logondate' => ucfirst(CrugeTranslator::t('ultimo acceso')),
            'terminosYCondiciones' => ucfirst(CrugeTranslator::t('comprendo y acepto, por favor registrarme')),
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('iduser', $this->iduser);
        $criteria->compare('username', $this->username, true);
        $criteria->compare('email', $this->email, true);
        $criteria->compare('state', $this->state);
        $criteria->compare('logondate', $this->logondate);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
            'sort' => array(
                'defaultOrder' => array('iduser' => true),
            ),
        ));
    }
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.