public function actioncargamasiva() { $model = new Cargamasiva(); $construir_archivo = array(); $todosErrores = array(); if (isset($_POST['Cargamasiva'])) { $model->attributes = $_POST['Cargamasiva']; $construir_archivo = array(); if ($model->validate()) { $model->archivo = CUploadedFile::getInstance($model, 'archivo'); $model->archivo->saveAs(Yii::app()->basePath . '/../assets/archivo.' . $model->archivo->extensionName); $fila = -1; $usuario_procesados = 0; $usuario_noprocesados = 0; $file = file(Yii::app()->basePath . '/../assets/archivo.' . $model->archivo->extensionName); $lineas = count($file); $lineas--; //$si = true; if (($gestor = fopen(Yii::app()->basePath . '/../assets/archivo.' . $model->archivo->extensionName, "r")) !== FALSE) { while (($datos = fgetcsv($gestor, 1000, ";")) !== FALSE) { $numero = count($datos); if ($numero != 0) { if ($fila != -1) { $transaction = Yii::app()->db->beginTransaction(); try { $ente = new EntesOrganos(); $usuario = new Usuarios('cargamasiva'); $ente->codigo_onapre = utf8_encode(trim($datos[0])) != '' ? utf8_encode(trim($datos[0])) : ''; $ente->nombre = utf8_encode(trim($datos[1])); $ente->tipo = "O"; $ente->creado_por = "snc"; $ente->rif = utf8_encode(trim($datos[2])); if ($ente->save()) { $usuario->usuario = strtolower(utf8_encode(trim($datos[5]))); $usuario->correo = strtolower(utf8_encode(trim($datos[5]))); $usuario->nombre = strtoupper(utf8_encode(trim($datos[3]))); $usuario->cedula = utf8_encode(trim($datos[4])); $usuario->cargo = utf8_encode(trim($datos[6])) != '' ? strtoupper(utf8_encode(trim($datos[6]))) : ''; $usuario->contrasena = md5(rand(0, 100)); $usuario->creado_el = date("Y-m-d"); $usuario->llave_activacion = md5(rand(0, 100)); $usuario->actualizado_el = date("Y-m-d"); $usuario->rol = 'organo'; $usuario->ente_organo_id = $ente->ente_organo_id; if ($usuario->save()) { $transaction->commit(); $usuario_procesados++; //$this->enviarCorreoRecuperacion($usuario->usuario, '1234567'); Yii::app()->user->setFlash('success', "{$usuario_procesados} usuario(s) procesado(s) del archivo con número de lineas {$lineas} !"); } else { /*print_r(Chtml::errorSummary($usuario)); Yii::app()->end();*/ throw new Exception(Chtml::errorSummary($usuario), 1); //$transaction->rollBack(); //Yii::app()->user->setFlash('error', "Ocurrio un error al momento de crear el usuario!"); } } else { //print_r(Chtml::errorSummary($ente)); // Yii::app()->end(); throw new Exception(Chtml::errorSummary($ente), 1); //$transaction->rollBack(); //Yii::app()->user->setFlash('error', "Ocurrio un error al momento de crear el organo!"); } } catch (Exception $e) { $transaction->rollBack(); $usuario_noprocesados++; $construir_archivo[$fila] = $file[$fila + 1]; $todosErrores[$fila] = $e->getMessage(); $si = false; //Yii::app()->user->setFlash('error', $e->getMessage()); Yii::app()->user->setFlash('error', "{$usuario_noprocesados} usuario(s) NO procesado(s) del archivo con número de lineas {$lineas}"); } } } $fila++; } fclose($gestor); } //$this->redirect(array('planificacion/descargar','id'=>$model->id, 'title'=>$model->title)); //$this->redirect(array('planificacion/errores')); //print_r($construir_archivo); //$this->redirect('planificacion/descargar'); //$file = 'assets/archivo.csv'; //echo $file; //return Yii::app()->getRequest()->sendFile('archivo.csv',@file_get_contents($file),'application/vnd.ms-excel'); } } $this->render('cargamasiva', array('model' => $model, 'errores' => $construir_archivo, 'todosErrores' => $todosErrores)); }
<?php if (Yii::app()->user->hasFlash('error')) { ?> <div class="alert alert-danger alert-dismissable"> <i class="fa fa-ban"></i> <button class="close" aria-hidden="true" data-dismiss="alert" type="button">×</button> <b><?php echo Yii::app()->user->getFlash('error'); ?> </b> <?php echo Chtml::errorSummary($model); ?> </div> <?php } elseif (Yii::app()->user->hasFlash('success')) { ?> <div class="alert alert-success alert-dismissable"> <i class="fa fa-check"></i> <button class="close" aria-hidden="true" data-dismiss="alert" type="button">×</button> <b><?php echo Yii::app()->user->getFlash('success'); ?> </b> </div> <?php }
/** * import from csv */ function import($iSurveyId) { $iSurveyId = (int) $iSurveyId; if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'import')) { Yii::app()->session['flashmessage'] = gT("You do not have sufficient rights to access this page."); $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}")); } // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}'); if (!$bTokenExists) { self::_newtokentable($iSurveyId); } App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'tokensimport.js'); $aEncodings = aEncodingsArray(); if (Yii::app()->request->isPostRequest) { $sUploadCharset = Yii::app()->request->getPost('csvcharset'); if (!array_key_exists($sUploadCharset, $aEncodings)) { $sUploadCharset = 'auto'; } $bFilterDuplicateToken = Yii::app()->request->getPost('filterduplicatetoken'); $bFilterBlankEmail = Yii::app()->request->getPost('filterblankemail'); $bAllowInvalidEmail = Yii::app()->request->getPost('allowinvalidemail'); $aAttrFieldNames = getAttributeFieldNames($iSurveyId); $aDuplicateList = array(); $aInvalidEmailList = array(); $aInvalidFormatList = array(); $aModelErrorList = array(); $aFirstLine = array(); $oFile = CUploadedFile::getInstanceByName("the_file"); $sPath = Yii::app()->getConfig('tempdir'); $sFileName = $sPath . '/' . randomChars(20); //$sFileTmpName=$oFile->getTempName(); /* More way to validate CSV ? $aCsvMimetypes = array( 'text/csv', 'text/plain', 'application/csv', 'text/comma-separated-values', 'application/excel', 'application/vnd.ms-excel', 'application/vnd.msexcel', 'text/anytext', 'application/octet-stream', 'application/txt', ); */ if (strtolower($oFile->getExtensionName()) != 'csv') { Yii::app()->setFlashMessage(gT("Only CSV files are allowed."), 'error'); } elseif (!@$oFile->saveAs($sFileName)) { Yii::app()->setFlashMessage(sprintf(gT("Upload file not found. Check your permissions and path (%s) for the upload directory"), $sPath), 'error'); } else { $iRecordImported = 0; $iRecordCount = 0; $iRecordOk = 0; $iInvalidEmailCount = 0; // Count invalid email imported // This allows to read file with MAC line endings too @ini_set('auto_detect_line_endings', true); // open it and trim the ednings $aTokenListArray = file($sFileName); $sBaseLanguage = Survey::model()->findByPk($iSurveyId)->language; if (!Yii::app()->request->getPost('filterduplicatefields') || Yii::app()->request->getPost('filterduplicatefields') && count(Yii::app()->request->getPost('filterduplicatefields')) == 0) { $aFilterDuplicateFields = array('firstname', 'lastname', 'email'); } else { $aFilterDuplicateFields = Yii::app()->request->getPost('filterduplicatefields'); } $sSeparator = Yii::app()->request->getPost('separator'); foreach ($aTokenListArray as $buffer) { $buffer = @mb_convert_encoding($buffer, "UTF-8", $sUploadCharset); if ($iRecordCount == 0) { // Parse first line (header) from CSV $buffer = removeBOM($buffer); // We alow all field except tid because this one is really not needed. $aAllowedFieldNames = Token::model($iSurveyId)->tableSchema->getColumnNames(); if (($kTid = array_search('tid', $aAllowedFieldNames)) !== false) { unset($aAllowedFieldNames[$kTid]); } // Some header don't have same column name $aReplacedFields = array('invited' => 'sent', 'reminded' => 'remindersent'); switch ($sSeparator) { case 'comma': $sSeparator = ','; break; case 'semicolon': $sSeparator = ';'; break; default: $comma = substr_count($buffer, ','); $semicolon = substr_count($buffer, ';'); if ($semicolon > $comma) { $sSeparator = ';'; } else { $sSeparator = ','; } } $aFirstLine = str_getcsv($buffer, $sSeparator, '"'); $aFirstLine = array_map('trim', $aFirstLine); $aIgnoredColumns = array(); // Now check the first line for invalid fields foreach ($aFirstLine as $index => $sFieldname) { $aFirstLine[$index] = preg_replace("/(.*) <[^,]*>\$/", "\$1", $sFieldname); $sFieldname = $aFirstLine[$index]; if (!in_array($sFieldname, $aAllowedFieldNames)) { $aIgnoredColumns[] = $sFieldname; } if (array_key_exists($sFieldname, $aReplacedFields)) { $aFirstLine[$index] = $aReplacedFields[$sFieldname]; } } } else { $line = str_getcsv($buffer, $sSeparator, '"'); if (count($aFirstLine) != count($line)) { $aInvalidFormatList[] = sprintf(gt("Line %s"), $iRecordCount); $iRecordCount++; continue; } $aWriteArray = array_combine($aFirstLine, $line); //kick out ignored columns foreach ($aIgnoredColumns as $column) { unset($aWriteArray[$column]); } $bDuplicateFound = false; $bInvalidEmail = false; $aWriteArray['email'] = isset($aWriteArray['email']) ? trim($aWriteArray['email']) : ""; $aWriteArray['firstname'] = isset($aWriteArray['firstname']) ? $aWriteArray['firstname'] : ""; $aWriteArray['lastname'] = isset($aWriteArray['lastname']) ? $aWriteArray['lastname'] : ""; $aWriteArray['language'] = isset($aWriteArray['language']) ? $aWriteArray['language'] : $sBaseLanguage; if ($bFilterDuplicateToken) { $aParams = array(); $oCriteria = new CDbCriteria(); $oCriteria->condition = ""; foreach ($aFilterDuplicateFields as $field) { if (isset($aWriteArray[$field])) { $oCriteria->addCondition("{$field} = :{$field}"); $aParams[":{$field}"] = $aWriteArray[$field]; } } if (!empty($aParams)) { $oCriteria->params = $aParams; } $dupresult = TokenDynamic::model($iSurveyId)->count($oCriteria); if ($dupresult > 0) { $bDuplicateFound = true; $aDuplicateList[] = sprintf(gt("Line %s : %s %s (%s)"), $iRecordCount, $aWriteArray['firstname'], $aWriteArray['lastname'], $aWriteArray['email']); } } //treat blank emails if (!$bDuplicateFound && $bFilterBlankEmail && $aWriteArray['email'] == '') { $bInvalidEmail = true; $aInvalidEmailList[] = sprintf(gt("Line %s : %s %s"), $iRecordCount, CHtml::encode($aWriteArray['firstname']), CHtml::encode($aWriteArray['lastname'])); } if (!$bDuplicateFound && $aWriteArray['email'] != '') { $aEmailAddresses = explode(';', $aWriteArray['email']); foreach ($aEmailAddresses as $sEmailaddress) { if (!validateEmailAddress($sEmailaddress)) { if ($bAllowInvalidEmail) { $iInvalidEmailCount++; if (empty($aWriteArray['emailstatus']) || strtoupper($aWriteArray['emailstatus'] == "OK")) { $aWriteArray['emailstatus'] = "invalid"; } } else { $bInvalidEmail = true; $aInvalidEmailList[] = sprintf(gt("Line %s : %s %s (%s)"), $iRecordCount, CHtml::encode($aWriteArray['firstname']), CHtml::encode($aWriteArray['lastname']), CHtml::encode($aWriteArray['email'])); } } } } if (!$bDuplicateFound && !$bInvalidEmail && isset($aWriteArray['token'])) { $aWriteArray['token'] = sanitize_token($aWriteArray['token']); // We allways search for duplicate token (it's in model. Allow to reset or update token ? if (Token::model($iSurveyId)->count("token=:token", array(":token" => $aWriteArray['token']))) { $bDuplicateFound = true; $aDuplicateList[] = sprintf(gt("Line %s : %s %s (%s) - token : %s"), $iRecordCount, CHtml::encode($aWriteArray['firstname']), CHtml::encode($aWriteArray['lastname']), CHtml::encode($aWriteArray['email']), CHtml::encode($aWriteArray['token'])); } } if (!$bDuplicateFound && !$bInvalidEmail) { // unset all empty value foreach ($aWriteArray as $key => $value) { if ($aWriteArray[$key] == "") { unset($aWriteArray[$key]); } if (substr($value, 0, 1) == '"' && substr($value, -1) == '"') { // Fix CSV quote $value = substr($value, 1, -1); } } // Some default value : to be moved to Token model rules in future release ? // But think we have to accept invalid email etc ... then use specific scenario $oToken = Token::create($iSurveyId); if ($bAllowInvalidEmail) { $oToken->scenario = 'allowinvalidemail'; } foreach ($aWriteArray as $key => $value) { $oToken->{$key} = $value; } if (!$oToken->save()) { tracevar($oToken->getErrors()); $aModelErrorList[] = sprintf(gt("Line %s : %s"), $iRecordCount, Chtml::errorSummary($oToken)); } else { $iRecordImported++; } } $iRecordOk++; } $iRecordCount++; } $iRecordCount = $iRecordCount - 1; unlink($sFileName); $aData['aTokenListArray'] = $aTokenListArray; // Big array in memory, just for success ? $aData['iRecordImported'] = $iRecordImported; $aData['iRecordOk'] = $iRecordOk; $aData['iRecordCount'] = $iRecordCount; $aData['aFirstLine'] = $aFirstLine; // Seem not needed $aData['aDuplicateList'] = $aDuplicateList; $aData['aInvalidFormatList'] = $aInvalidFormatList; $aData['aInvalidEmailList'] = $aInvalidEmailList; $aData['aModelErrorList'] = $aModelErrorList; $aData['iInvalidEmailCount'] = $iInvalidEmailCount; $aData['thissurvey'] = getSurveyInfo($iSurveyId); $aData['iSurveyId'] = $aData['surveyid'] = $iSurveyId; $this->_renderWrappedTemplate('token', array('tokenbar', 'csvpost'), $aData); Yii::app()->end(); } } // If there are error with file : show the form $aData['aEncodings'] = $aEncodings; $aData['iSurveyId'] = $iSurveyId; $aData['thissurvey'] = getSurveyInfo($iSurveyId); $aData['surveyid'] = $iSurveyId; $aTokenTableFields = getTokenFieldsAndNames($iSurveyId); unset($aTokenTableFields['sent']); unset($aTokenTableFields['remindersent']); unset($aTokenTableFields['remindercount']); unset($aTokenTableFields['usesleft']); foreach ($aTokenTableFields as $sKey => $sValue) { if ($sValue['description'] != $sKey) { $sValue['description'] .= ' - ' . $sKey; } $aNewTokenTableFields[$sKey] = $sValue['description']; } $aData['aTokenTableFields'] = $aNewTokenTableFields; $this->_renderWrappedTemplate('token', array('tokenbar', 'csvupload'), $aData); }
public function actionChangePass() { $user = new User(); if (isset($_POST['User'])) { $user = $this->loadModel(Yii::app()->user->name); $user->old_password = $_POST['User']['old_password']; $user->new_password = $_POST['User']['new_password']; $user->new_password_repeat = $_POST['User']['new_password_repeat']; $user->scenario = 'change_password'; $user->current_password = $user->password; if ($user->validate()) { $user->password = $user->new_password; if ($user->save()) { echo CJSON::encode(array('result' => 'success', 'message' => 'You password has been changed.')); } else { print_r($user->getErrors()); } } else { echo CJSON::encode(array('result' => 'failed', 'old' => CHtml::error($user, 'old_password'), 'new' => CHtml::error($user, 'new_password'), 'confirm' => CHtml::error($user, 'new_password_repeat'), 'all' => Chtml::errorSummary($user))); } } }
public function actionChangeInfo() { $model = new Member(); if (isset($_POST['Member'])) { $model = Member::model()->findByAttributes(array('email' => Yii::app()->user->name)); if ($_POST['Member']['name'] != "") { $model->name = $_POST['Member']['name']; } if ($_POST['Member']['company_name'] != "") { $model->company_name = $_POST['Member']['company_name']; } if ($_POST['Member']['phone'] != "") { $model->phone = $_POST['Member']['phone']; } if ($_POST['Member']['address'] != "") { $model->address = $_POST['Member']['address']; } $model->scenario = 'change_info'; if ($model->save()) { if ($model->type_account == "1") { $tipe = "Standar Account"; } elseif ($member->type_account = "2") { $tipe = "Premium Account"; } else { $tipe = "wow"; } $result = $tipe . "<br><br>\t" . $model->email . "<br>" . $model->name . "<br>" . $model->company_name . "<br><br>" . $model->phone . "<br>" . $model->address; echo CJSON::encode(array('result' => 'success', 'html' => $result, 'message' => 'Your information has been changed.')); } else { echo CJSON::encode(array('result' => 'failed', 'name' => CHtml::error($model, 'name'), 'company' => CHtml::error($model, 'company_name'), 'phone' => CHtml::error($model, 'phone'), 'address' => CHtml::error($model, 'address'), 'all' => Chtml::errorSummary($model))); } } }