示例#1
0
 /**
  * doCallback 
  * 		you must process a calilback response comming from host auth provider.
  *
  *	you pass remote data to your local system using:
  *		$this->setData($anydata);
  *		$this->setLastError('error message');
  *
  * @access public
  * @return bool boolean result true if login is correct.
  */
 public function doCallback()
 {
     if (isset($_REQUEST['error'])) {
         if ($_REQUEST['error'] == 'access_denied') {
             $this->setLastError($_REQUEST['error_description']);
             return false;
         }
     }
     $s = new CHttpSession();
     $s->open();
     if (isset($s['state'])) {
         if ($s['state'] === $_REQUEST['state']) {
             $ac = $this->_getAccessToken($_REQUEST['code']);
             $this->setData($this->_requestUser($ac));
             $s->close();
             return true;
         } else {
             $this->setLastError('CRSF validation failed.');
             $s->close();
             return false;
         }
     } else {
         $this->setLastError('invalid state argument.');
         $s->close();
         return false;
     }
 }
示例#2
0
 public function setDevice($type = null)
 {
     $device = new CHttpSession();
     $device->open();
     $device['device-type'] = $type ? $type : $this->classic;
     $device->close();
 }
 /**
  * @param $id
  * @param $criteria
  * @return CActiveRecord
  * @throws CHttpException
  */
 public function loadModel($id, $criteria = false)
 {
     if (!$id) {
         throw new CHttpException(404, 'Property not found');
     }
     $criteria = $criteria ?: new CDbCriteria();
     $previewSession = new CHttpSession();
     $previewSession->open();
     $previewString = isset($previewSession['preview']) && $previewSession['preview'] ? $previewSession['preview'] : null;
     $previewString = isset($_GET['preview']) && $_GET['preview'] ? $_GET['preview'] : $previewString;
     if (Yii::app()->user->isGuest) {
         $criteria->scopes = ['notUnderTheRadar'];
         if ($previewString) {
             $criteria->compare('emailLinkString', $previewString);
         } else {
             $criteria->scopes = ['publicAvailable', 'notUnderTheRadar'];
         }
     }
     $model = Deal::model()->findByPk($id, $criteria);
     if (!$model) {
         throw new CHttpException(404, 'Property not found');
     } else {
         $previewSession['preview'] = $previewString;
         $previewSession->close();
     }
     return $model;
 }
 public function runAction($action, $data)
 {
     $this->id = $data;
     $s = new CHttpSession();
     $s->open();
     $storedData = $s[$this->id];
     $s->close();
     $this->model = $storedData['model'];
     if ($action == 'listitems') {
         $parent_id = null;
         if (isset($_GET['id'])) {
             $parent_id = $_GET['id'];
         }
         return $this->model->eyuiformeditordb_listitems($_GET['item_type'], $parent_id);
     }
     if ($action == 'newitem') {
         $parent_id = null;
         if (isset($_GET['id'])) {
             $parent_id = $_GET['id'];
         }
         return $this->model->eyuiformeditordb_newitem($_GET['item_type'], self::t("New Item"), $parent_id);
     }
     if ($action == 'deleteitem') {
         if ($this->model->eyuiformeditordb_deleteitem($_GET['id'])) {
             return "OK";
         }
     }
     if ($action == 'updateitem') {
         $obj = CJSON::decode(trim(file_get_contents('php://input')));
         if ($this->model->eyuiformeditordb_updateitem($obj) == true) {
             return "OK";
         }
     }
 }
示例#5
0
 public function actionRegistration($datakey = '')
 {
     $this->layout = CrugeUtil::config()->registrationLayout;
     $model = Yii::app()->user->um->createBlankUser();
     $model->bypassCaptcha = false;
     $model->terminosYCondiciones = false;
     if (Yii::app()->user->um->getDefaultSystem()->getn('registerusingterms') == 0) {
         $model->terminosYCondiciones = true;
     }
     // para que cargue los campos del usuario
     Yii::app()->user->um->loadUserFields($model);
     // 'datakey' es el nombre de una variable de sesion
     // establecida por alguna parte que invoque a actionRegistration
     // y que se le pasa a este action para de ahi se lean datos.
     //
     // el dato esperado alli es un array indexado ('attribuye'=>'value')
     // tales valores deberan usarse para inicializar el formulario
     // del usuario como se indica aqui:
     //
     // ejemplo de array en sesion:
     //	array('username'=>'csalazar','email'=>'*****@*****.**'
     //	,'nombre'=>'christian', 'apellido'=>'salazar')
     //
     // siendo: "nombre" y "apellido" los nombre de campos personalizados
     //	que inmediantamente tras registro seran inicializados.
     //
     if ($datakey != null) {
         // leo la data de la varibale de sesion
         $s = new CHttpSession();
         $s->open();
         $values = $s[$datakey];
         $s->close();
         // asumo que es un array, asi que aqui vamos
         //
         $model->username = $values['username'];
         $model->email = $values['email'];
         // ahora, procesa los campos personalizados,
         // rellenando aquellos mapeados contra los campos existentes:
         foreach ($model->getFields() as $f) {
             if (isset($values[$f->fieldname])) {
                 $f->setFieldValue($values[$f->fieldname]);
             }
         }
     }
     if (isset($_POST[CrugeUtil::config()->postNameMappings['CrugeStoredUser']])) {
         $model->attributes = $_POST[CrugeUtil::config()->postNameMappings['CrugeStoredUser']];
         if ($model->validate()) {
             $newPwd = trim($model->newPassword);
             Yii::app()->user->um->changePassword($model, $newPwd);
             Yii::app()->user->um->generateAuthenticationKey($model);
             if (Yii::app()->user->um->save($model, 'insert')) {
                 $this->onNewUser($model, $newPwd);
                 $this->redirect(array('welcome'));
             }
         }
     }
     $this->render("registration", array('model' => $model));
 }
示例#6
0
 /**
  * remoteLoginInterface
  *    es una interfaz para iniciar sesion o registrar a un usuario de forma
  *  automatizada.
  *
  * $fieldmap: que campos de Cruge estan relacionados
  * con cuales campos que nos ha enviado facebook o google.
  * por ejemplo: array('email'=>'contact/email'),
  *
  * $values se espera que sea un array indexado, cuyo
  * indice sea un campo de facebook o google:
  * por ejemplo:  array('contact/email'=>'*****@*****.**'),
  *
  * $modality:  la modalidad de registro de un usuario, puede ser una de:
  *
  *     'auto'        : registra al usuario de inmediato y le inicia la sesion
  *    'manual'    : lo envia a la pantalla de registro con datos precargados.
  *    'none'        : si el usuario no esta registrado no procede.
  *
  * @param array $fieldmap
  * @param array $values
  * @param string $modality 'auto', 'manual' , 'none'
  * @param string $errorResult (out) error result string
  * @param string $role_name usar 'default' para usar rol definido en variables de sistema.
  * @param boolean $bool_send_email true para que envie correos de notificacion
  * @access public
  * @return false o una URL (array o string) para ir a ella.
  */
 public function remoteLoginInterface($fieldmap, $_values, $modality, &$errorResult, $debug = false, $role_name = 'default', $bool_send_email = true)
 {
     $values = '';
     if (is_string($_values)) {
         $values = CJSON::decode($_values);
     } else {
         $values = $_values;
     }
     // para depurar:
     //
     // die(CJSON::encode(array('fieldmap'=>$fieldmap,'values'=>$values)));
     //
     // se genera un array con datos que cruge entienda a partir
     // de los valores y fieldmap entregados:
     //
     // cada par del array contendrá a la salida:
     //	array('username'=>'csalazar', 'email'=>'*****@*****.**'
     //		, 'nombre'=>'christian','apellido'=>'salazar')
     $mapped_values = array();
     foreach ($fieldmap as $localfield => $remotefield) {
         $mapped_values[$localfield] = '';
         if (isset($values[$remotefield])) {
             $mapped_values[$localfield] = $values[$remotefield];
         }
     }
     // para depurar:
     //
     if ($debug == true) {
         echo CJSON::encode(array('fieldmap' => $fieldmap, 'values' => $values));
         die("<hr/>" . CJSON::encode($mapped_values));
     }
     $email = '';
     if (isset($mapped_values['email'])) {
         $email = $mapped_values['email'];
     }
     if (empty($email)) {
         // hay algun problema con los valores entregados
         $errorResult = 'El email no esta presente en los datos entregados';
         return false;
     }
     // primero pedirle a cruge que inicie sesion
     // con el 'email' detectado. (si el caso es google, solo vendra email,
     // si el caso es facebook vendra username e email, por eso usamos
     // email como base).
     $crugeUser = $this->loginUser($email);
     // PASO 4. Quiza el usuario no exista y haya que registrarlo, por
     // tanto aplicariamos una logica de negocio propia de tu aplicacion.
     // si el usuario ya estaba registrado loginUser retornara ese usuario.
     $logged_on = false;
     if ($crugeUser == null) {
         // usuario no registrado en Cruge, segun tu decision, podemos
         // aplicar ciertas modalidades:
         //	'auto', 'manual' o 'none'
         if ($modality == 'auto') {
             // automaticamente registra al usuario y le inicia sesion
             //
             $crugeUser = $this->createNewUser($mapped_values, $role_name, $bool_send_email);
             if ($crugeUser == null) {
                 $errorResult = 'No se pudo crear el usuario';
                 return false;
             }
             $crugeUser = $this->loginUser($mapped_values['email']);
             if ($crugeUser != null) {
                 $logged_on = true;
             } else {
                 $errorResult = 'No se pudo iniciar sesion.';
                 return false;
             }
         } elseif ($modality == 'manual') {
             // le pone algunos campos prefijados obtenidos de facebook
             // o google, pero el usuario debe continuar su proceso
             // de registro manualmente
             // el actionRegistration de cruge ofrece una ventaja:
             // se le puede dar un nombre de variable de sesion en la cual
             // se almacenan datos para que inicialize el usuario antes
             // de presentar el form de registro.
             $s = new CHttpSession();
             $s->open();
             $s['_crugeregistration_'] = $mapped_values;
             $s->close();
             // nos vamos al action de registro de Cruge pasandole
             // como argumento esta variable de sesion:
             $errorResult = 'registration';
             return array('/cruge/ui/registration', 'datakey' => '_crugeregistration_');
         } elseif ($modality == 'none') {
             // no esta permitido el registro por facebook o google:
             $errorResult = 'Debe registrarse manualmente.';
             return false;
         }
     } else {
         $logged_on = true;
     }
     if ($logged_on == true) {
         // el usuario ya estaba registrado en Cruge
         // lo llevamos a la pagina de usuario bienvenido de cruge
         //
         // returnUrl fue establecido automaticamente por:
         //		cruge.models.filters.CrugeDefaultSession::onLogin
         //	al valor de tu configuracion:  'afterLoginUrl'
         return Yii::app()->user->returnUrl;
     } else {
         $errorResult = 'No se pudo iniciar sesion con su cuenta.';
         return false;
     }
 }
示例#7
0
    		<div id="logo"><a href="http://yii/index.php/site/index" title="home">
    		<img src="<?php 
Yii::app()->request->baseUrl;
?>
/images/logo.png"  alt="logo" />
    		<?php 
echo CHtml::encode(Yii::app()->name);
?>
</a></div>
    	
    	</div><!-- header -->
        <?php 
$session = new CHttpSession();
$session->open();
$user = $session['data'];
$session->close();
// user of system
$userCart = false;
$userInsp = false;
$admin = false;
switch ($user) {
    case 'client':
        $userCart = true;
        break;
    case 'inspector':
        $userInsp = true;
        break;
    case 'admin':
        $admin = true;
        break;
    default:
示例#8
0
 /**
  * hash_call: Function to perform the API call to PayPal using API signature
  * @methodName is name of API  method.
  * @nvpStr is nvp string.
  * returns an associtive array containing the response from the server.
  */
 public function hash_call($methodName, $nvpStr)
 {
     $session = new CHttpSession();
     //declaring of global variables
     //global $API_Endpoint,$version,$API_UserName,$API_Password,$API_Signature,$nvp_Header, $subject, $AUTH_token,$AUTH_signature,$AUTH_timestamp;
     // form header string
     $nvpheader = $this->nvpHeader();
     //setting the curl parameters.
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $this->API_ENDPOINT);
     curl_setopt($ch, CURLOPT_VERBOSE, 1);
     //turning off the server and peer verification(TrustManager Concept).
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_POST, 1);
     //in case of permission APIs send headers as HTTPheders
     if (!empty($this->AUTH_TOKEN) && !empty($this->AUTH_SIGNATURE) && !empty($this->AUTH_TIMESTAMP)) {
         $headers_array[] = "X-PP-AUTHORIZATION: " . $nvpheader;
         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers_array);
         curl_setopt($ch, CURLOPT_HEADER, false);
     } else {
         $nvpStr = $nvpheader . $nvpStr;
     }
     //if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled.
     //Set proxy name to PROXY_HOST and port number to PROXY_PORT in constants.php
     if ($this->USE_PROXY) {
         curl_setopt($ch, CURLOPT_PROXY, PROXY_HOST . ":" . PROXY_PORT);
     }
     //check if version is included in $nvpStr else include the version.
     if (strlen(str_replace('VERSION=', '', strtoupper($nvpStr))) == strlen($nvpStr)) {
         $nvpStr = "&VERSION=" . urlencode($this->VERSION) . $nvpStr;
     }
     $nvpreq = "METHOD=" . urlencode($methodName) . $nvpStr;
     //setting the nvpreq as POST FIELD to curl
     curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
     //getting response from server
     $response = curl_exec($ch);
     //convrting NVPResponse to an Associative Array
     $nvpResArray = $this->deformatNVP($response);
     $nvpReqArray = $this->deformatNVP($nvpreq);
     $session->open();
     $session['nvpReqArray'] = $nvpReqArray;
     $session->close();
     if (curl_errno($ch)) {
         // moving to display page to display curl errors
         $session->open();
         $session['curl_error_no'] = curl_errno($ch);
         $session['curl_error_msg'] = curl_error($ch);
         //$location = "APIError.php";
         $session->close();
         // $this->redirect(array('/paypal/APIError','msg'=>'Error in curl'));
         // header("Location: $location");
     } else {
         //closing the curl
         curl_close($ch);
     }
     return $nvpResArray;
 }
示例#9
0
 protected function sendVerify($operation, $data)
 {
     $session = new CHttpSession();
     $session->open();
     if ($operation == "email") {
         $val = StringUtil::random(8);
     } elseif ($operation == "mobile") {
         $val = StringUtil::random(5, 1);
     }
     $verifyVal = md5($val);
     $verifyName = $operation;
     $session[$verifyName] = $verifyVal;
     $session["verifyData"] = $data;
     $res = $this->makeVerify($operation, $data, $val);
     $session->close();
     return $res;
 }
示例#10
0
 public static function getForm3()
 {
     $session = new CHttpSession();
     $session->open();
     if (isset($_SESSION['job_apply_form3'])) {
         $arr = CJSON::decode($_SESSION['job_apply_form3']);
     } else {
         $arr = array();
     }
     $session->close();
     return $arr;
 }
 /**
  * Method called whenever an EYui widget is invoked from an action int order to start a query.
  * invoked via jquery-ajax, by: eyuisearch.js
  * @see
  *	EYuiActionRunnable
  *	EYuiAction
  * @returns an array or any object. it will be converted in EYuiAction to a JSON representation.
  */
 public function runAction($action, $data)
 {
     $this->id = $_GET['formid'];
     // recovery session information saved before when widget was built
     $s = new CHttpSession();
     $s->open();
     $data = $s['eyuiform_' . $this->id];
     //array('model'=>$this->model,'pages'=>$this->pages);
     $s->close();
     $this->model = $data['model'];
     $this->pages = $data['pages'];
     if ($action == 'submit') {
         // get the post. it will be an array formed in js component as:
         // { id: input.id , val: input.value }
         $rawPost = trim(file_get_contents('php://input'));
         $post = CJSON::decode($rawPost);
         Yii::log(__METHOD__ . ".submit:\n" . $rawPost, "info");
         // validates each provided field in post
         $errorFields = array();
         foreach ($post as $fieldentry) {
             if (($field = $this->findFieldByName(trim($fieldentry['id']))) != null) {
                 // query the model for current field value
                 $field->setValue($this->model->eyuiform_getFieldValue($this->id, $field->id, $field->getName()));
                 // the new field value readed from post
                 $result = $this->validateField($field, $fieldentry['val']);
                 // array entry definition for each error passed to jquery:
                 if ($result['result'] == false) {
                     $errorFields[] = array('fieldname' => $field->getName(), 'message' => $result['message'], 'help' => $result['help'], 'id' => $field->id, 'label' => $field->label, 'page' => $field->getPage()->label, 'group' => $field->getGroup()->label);
                 }
             } else {
                 throw new Exception("the field provided in your form is not recognized by EYuiForm config.");
             }
         }
         if (count($errorFields) > 0) {
             return array('result' => false, 'message' => '', 'errors' => $errorFields);
         }
         // all fields pass validation, now massive saving for each field:
         // notify begintrans
         $transaction_handler = $this->model->eyuiform_transaction('begin');
         foreach ($post as $fieldentry) {
             Yii::log(__METHOD__ . "\nsaving field:\n" . $fieldentry['id'], "info");
             if (($field = $this->findFieldByName(trim($fieldentry['id']))) != null) {
                 $field->setValue(trim($fieldentry['val']));
                 if (!$this->model->eyuiform_saveFieldValue($this->id, $field->id, $field->getName(), $field->getValue())) {
                     // abort saving
                     Yii::log(__METHOD__ . "\nsaving field ABORT.\n", "info");
                     $this->model->eyuiform_transaction('rollback', $transaction_handler);
                     return array('result' => false, 'message' => 'Error saving field', 'fieldname' => $field->getName());
                     break;
                 }
             }
         }
         Yii::log(__METHOD__ . "\nsaving field end.\n", "info");
         // notify commit
         $this->model->eyuiform_transaction('commit', $transaction_handler);
         return array('result' => true, 'message' => 'FORM SUBMITTED');
     } else {
         if ($action == 'fieldchange') {
             // a specific field has a change and need to be validated in model
             //
             $post = CJSON::decode(trim(file_get_contents('php://input')));
             if (($field = $this->findFieldByName(trim($post['id']))) != null) {
                 // query the model for current field value
                 $field->setValue($this->model->eyuiform_getFieldValue($this->id, $field->id, $field->getName()));
                 // the new field value readed from post
                 return $this->validateField($field, trim($post['val']));
             } else {
                 throw new Exception("the field provided in your form is not recognized by EYuiForm config.");
             }
         }
     }
 }
 public function actionLogout()
 {
     Yii::app()->user->logout();
     Yii::app()->session->clear();
     Yii::app()->session->destroy();
     //        session_destroy();
     $session = new CHttpSession();
     $session->close();
     $this->redirect(Yii::app()->getBaseUrl(true) . "/site/login");
 }
示例#13
0
 /**
  * POST Method
  * @param string $print_response
  */
 public function post($print_response = true)
 {
     $session = new CHttpSession();
     $session->open();
     $NX_object = $session['_nx_object'];
     if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE') {
         return $this->delete($print_response);
     }
     $upload = isset($_FILES[$this->options['param_name']]) ? $_FILES[$this->options['param_name']] : null;
     // Parse the Content-Disposition header, if available:
     $file_name = isset($_SERVER['HTTP_CONTENT_DISPOSITION']) ? rawurldecode(preg_replace('/(^[^"]+")|("$)/', '', $_SERVER['HTTP_CONTENT_DISPOSITION'])) : null;
     $file_type = isset($_SERVER['HTTP_CONTENT_DESCRIPTION']) ? $_SERVER['HTTP_CONTENT_DESCRIPTION'] : null;
     // Parse the Content-Range header, which has the following form:
     // Content-Range: bytes 0-524287/2000000
     $content_range = isset($_SERVER['HTTP_CONTENT_RANGE']) ? split('[^0-9]+', $_SERVER['HTTP_CONTENT_RANGE']) : null;
     $size = $content_range ? $content_range[3] : null;
     $info = array();
     if ($upload && is_array($upload['tmp_name'])) {
         // param_name is an array identifier like "files[]",
         // $_FILES is a multi-dimensional array:
         foreach ($upload['tmp_name'] as $index => $value) {
             $info[] = $this->handle_file_upload($upload['tmp_name'][$index], $file_name ? $file_name : $upload['name'][$index], $size ? $size : $upload['size'][$index], $file_type ? $file_type : $upload['type'][$index], $upload['error'][$index], $index, $content_range);
         }
         foreach ($info as $myFile) {
             if (!isset($myFile->error)) {
                 $documentToSave = $session['_nx_document'];
                 $documentToSave->ID_DOCUMENT = $myFile->tipoDocumento;
                 $documentToSave->NAME = $myFile->name;
                 $documentToSave->DESCRIPTION = $myFile->nombre;
                 $documentToSave->setOwnerId($myFile->propietario);
                 $documentToSave->PATH = $this->getFileContextPath($myFile->url);
                 $documentToSave->SIZE = $myFile->size;
                 $documentToSave->TYPE = $myFile->type;
                 $documentToSave->THUMBNAIL = $this->getFileContextPath($myFile->thumbnail_url);
                 $documentToSave->DELURL = $this->getFileContextPathDel($myFile->delete_url);
                 $documentToSave->DELTYPE = $myFile->delete_type;
                 $documentToSave->STATUS = 1;
                 $documentToSave->save();
                 $myFile->delete_type = $documentToSave->DELURL;
             }
         }
     } else {
         // param_name is a single object identifier like "file",
         // $_FILES is a one-dimensional array:
         $info[] = $this->handle_file_upload(isset($upload['tmp_name']) ? $upload['tmp_name'] : null, $file_name ? $file_name : (isset($upload['name']) ? $upload['name'] : null), $size ? $size : (isset($upload['size']) ? $upload['size'] : $_SERVER['CONTENT_LENGTH']), $file_type ? $file_type : (isset($upload['type']) ? $upload['type'] : $_SERVER['CONTENT_TYPE']), isset($upload['error']) ? $upload['error'] : null, null, $content_range);
         foreach ($info as $myFile) {
             if (isset($myFile->error)) {
                 $documentToSave = $session['_nx_document'];
                 $documentToSave->ID_DOCUMENT = $myFile->tipoDocumento;
                 $documentToSave->NAME = $myFile->name;
                 $documentToSave->setOwnerId($myFile->propietario);
                 $documentToSave->PATH = $myFile->url;
                 $documentToSave->SIZE = $myFile->size;
                 $documentToSave->TYPE = $myFile->type;
                 $documentToSave->THUMBNAIL = $myFile->thumbnail_url;
                 $documentToSave->DELURL = $myFile->delete_url;
                 $documentToSave->DELTYPE = $myFile->delete_type;
                 $documentToSave->STATUS = 1;
                 $documentToSave->DESCRIPTION = $myFile->nombre;
                 $documentToSave->save();
             }
         }
     }
     $session->close();
     return $this->generate_response($info, $print_response);
 }