TYPO3 - Create User programmatically - php

Is it possible to create or delete a User programmatically (without SQL) in a typo3 extension?

To CRUD frontend users (fe_users) there already is a Repository and a Model available which you might use in your own Extbase extension. Below...
typo3/sysext/extbase/Classes/Domain
you can find the Model and Repository classes.

some code examples:
function createUser() {
// TypoScript Template mit userid anlegen
// Neue Seite anlegen
$tmpId = 'NEWuser478d8d';
$data['be_users'][$tmpId] = array(
'username' => $this->email,
'password' => $this->password,
'admin' => 0,
'pid' => 0,
'usergroup' => $this->usergroup,
'lang' => 'de',
'email' => $this->email,
'db_mountpoints' => '',
'realName' => $this->realName,
'file_mountpoints' => '',
'fileoper_perms' => (int)$this->conf['fileoper_perms'],
'options' => '2', // mount from group: filemount, aber nicht dbmount
'db_mountpoints' => $this->dbMountPage,
'file_mountpoints' => $this->conf['file_mountpoints'],
'workspace_perms' => 0,
'workspace_id' => 0,
'workspace_preview' => 0
);
$this->debug($data, 'beuser');
$this->tce->start($data,array());
$this->tce->process_datamap();
$this->userid = $this->tce->substNEWwithIDs[$tmpId];
// t3lib_div::debug('Neue Userid:'.$this->userid);
return true;
}
afair you need an be-user which is active, so create one:
/**
* Creates a Be-User
*
* #return void
*/
function setBeUser() {
global $BE_USER;
unset($BE_USER);
$BE_USER = t3lib_div::makeInstance('t3lib_beUserAuth');
$BE_USER->OS = TYPO3_OS;
$BE_USER->setBeUserByUid($this->conf['setBeUserByUid']);
$BE_USER->fetchGroupData();
$BE_USER->backendSetUC();
$GLOBALS['BE_USER'] = $BE_USER;
$GLOBALS['LANG'] = t3lib_div::makeInstance('language');
$GLOBALS['LANG']->init($BE_USER->uc['lang']);
return $BE_USER;
}
init tce:
$this->tce = t3lib_div::makeInstance('t3lib_TCEmain');
$this->tce->BE_USER = $this->setBeUser();
$this->tce->stripslashes_values = 0;
$this->createUser();

Related

Drupal 8 Custom Module - From dynamic data (API) to store at Fields (Content type) Drupal DB

I've created a custom module in Drupal 8 that grab some data from an API, and puts them in the Drupal DB creating a new table.
I want to add this data as the contents of a specific content type.
How can I do that?
here is my code :
<?php
/**
* Implements hook_cron().
*/
function ods_cron() {
$message = 'Cron run: ' . date('Y-m-d H:i:s');
$ods = \Drupal::service('ods.ods');
$conf = \Drupal::service('ods.ods_configuration_request');
if ($conf->isDevelopment()) {
// Development
$response_bond = beforeSendRequest($conf->devUrlExternalBond(), 'GET');
$response_mf = beforeSendRequest($conf->devUrlExternalMutualFund(), 'GET');
} else {
// Production
$parameters_bond = [
'headers' => $conf->headers(),
'authorization' => $conf->basicAuthorization(),
'data_post' => $conf->bodyBond(),
];
$parameters_mf = [
'headers' => $conf->headers(),
'authorization' => $conf->basicAuthorization(),
'data_post' => $conf->bodyMutualFund(),
];
$response_bond = beforeSendRequest($conf->urlExternalBond(), 'POST', $parameters_bond);
$response_mf = beforeSendRequest($conf->urlExternalMutualFund(), 'POST', $parameters_mf);
}
$raw_result_bond = json_decode($response_bond);
$raw_result_mf = json_decode($response_mf);
// Development
if ($conf->isDevelopment()) {
$raw_result_bond = json_decode($raw_result_bond[0]->field_bonds);
$raw_result_mf = json_decode($raw_result_mf[0]->field_api);
}
$BondsProductList = $raw_result_bond->BondsProductInqRs->BondsProductList;
$MFProductInqList = $raw_result_mf->MFProductInqRs->MFProductInqList;
// Bond data store to internal
if ($BondsProductList !== null) {
$bond_datas = [];
foreach ($BondsProductList as $row => $content) {
$bond_datas[] = [
'AskPrice' => number_format($content->AskPrice, 1, '.', ','),
'BidPrice' => number_format($content->BidPrice, 1, '.', ','),
'BuySettle' => number_format($content->BuySettle, 1, '.', ','),
'CouponFreqCode' => $content->CouponFreqCode,
'CouponFreqID' => number_format($content->CouponFreqID),
'CouponRate' => number_format($content->CouponRate, 2, '.', ','),
'IDCurrency' => $content->IDCurrency,
'LastCoupon' => $content->LastCoupon,
'MaturityDate' => $content->MaturityDate,
'MinimumBuyUnit' => number_format($content->MinimumBuyUnit),
'MultipleOfUnit' => number_format($content->MultipleOfUnit),
'NextCoupon' => $content->NextCoupon,
'Penerbit' => $content->Penerbit,
'ProductCode' => $content->ProductCode,
'ProductName' => $content->ProductName,
'ProductAlias' => $content->ProductAlias,
'RiskProfile' => $content->RiskProfile,
'SellSettle' => $content->SellSettle
];
}
$insert_data = $ods->setData(
'bond',
[
'AskPrice', 'BidPrice', 'BuySettle', 'CouponFreqCode', 'CouponFreqID', 'CouponRate', 'IDCurrency',
'LastCoupon', 'MaturityDate', 'MinimumBuyUnit', 'MultipleOfUnit', 'NextCoupon', 'Penerbit',
'ProductCode', 'ProductName', 'ProductAlias', 'RiskProfile', 'SellSettle'
],
$bond_datas
);
if ($insert_data) {
// make response as JSON File and store the file
$ods->makeJsonFile($bond_datas, 'feeds/bonds', 'bond.json');
}
}
// Mutual Fund data store to internal
if ($MFProductInqList !== null) {
$mf_datas = [];
foreach ($MFProductInqList as $row => $content) {
$mf_datas[] = [
'ProductCode' => $content->ProductCode,
'ProductName' => $content->ProductName,
'ProductCategory' => $content->ProductCategory,
'ProductType' => $content->ProductType,
'Currency' => $content->Currency,
'Performance1' => $content->field_1_tahun_mf,
'Performance2' => $content->Performance2,
'Performance3' => $content->Performance3,
'Performance4' => $content->Performance4,
'Performance5' => $content->Performance5,
'UrlProspektus' => $content->UrlProspektus,
'UrlFactSheet' => $content->UrlFactSheet,
'UrlProductFeatureDocument' => $content->UrlProductFeatureDocument,
'RiskProfile' => $content->RiskProfile,
'FundHouseName' => $content->FundHouseName,
'NAVDate' => $content->NAVDate,
'NAVValue' => $content->NAVValue
];
}
$insert_data_mf = $ods->setData(
'mutual_fund',
[
'ProductCode', 'ProductName', 'ProductCategory', 'ProductType', 'Currency', 'Performance1', 'Performance2', 'Performance3',
'Performance4', 'Performance5', 'UrlProspektus', 'UrlFactSheet', 'UrlProductFeatureDocument', 'RiskProfile', 'FundHouseName',
'NAVDate', 'NAVValue'
],
$mf_datas
);
if ($insert_data_mf) {
// make response as JSON File and store the file
$ods->makeJsonFile($mf_datas, 'feeds/mf', 'mutual_fund.json');
}
}
// console log
\Drupal::logger('ods')->notice($message);
}
So can I store the data to pristine drupal 8 table?
First, you need to create the content type in the Drupal 8 backend going to Structure > Content type.
Second you can add a node programmatically like this
use Drupal\node\Entity\Node;
$node = Node::create(array(
'type' => 'your_content_type',
'title' => 'your title',
'langcode' => 'en',
'uid' => '1',
'status' => 1,
'body'=> 'your body',
));
$node->save();

Laravel inserts two user records at register, how to prevent this?

I am creating an application where I have to insert a user at registration with custom fields. As found online, i customised the create method in the Laravel RegisterController. However, now the application inserts two user records whenever I register a new user. Can someone help me with this please?
Here is the code of my create method in the RegisterController
protected function create(array $data)
{
/********************************************************************************
* CALCULATE ALL THE NEEDED DATA FOR THE USER
********************************************************************************/
// Delete the uncompleted registration
UncompletedRegistration::deleteByEmail($data['email']);
// Set the right values based on the filled values
$compercentagecreative = 0.0;
$compercentagenotcreative = 0.0;
$creativepercent = 0.0;
switch ($data['headjob']) {
case 1:
$compercentagecreative = config('constants.percentageRates.comPercentageCreative.headjob');
$compercentagenotcreative = config('constants.percentageRates.comPercentageNotCreative.headjob');
$creativepercent = config('constants.percentageRates.creativePercent.headjob');
break;
case 2:
$compercentagecreative = config('constants.percentageRates.comPercentageCreative.notheadjob');
$compercentagenotcreative = config('constants.percentageRates.comPercentageNotCreative.notheadjob');
$creativepercent = config('constants.percentageRates.creativePercent.notheadjob');
break;
default:
$compercentagecreative = config('constants.percentageRates.comPercentageCreative.headjob');
$compercentagenotcreative = config('constants.percentageRates.comPercentageNotCreative.headjob');
$creativepercent = config('constants.percentageRates.creativePercent.headjob');
break;
}
// Format the VAT number
$data['vatnumber'] = Helper::formatVatNumber($data['vatnumber']);
$isVatValid = false;
try {
// Check if vat is valid
$response = Helper::checkVat($data['vatnumber']);
$responseArray = json_decode($response);
$isVatValid = $responseArray->valid;
} catch (\Exception $exception) {
$isVatValid = false;
}
// Generate an activation key
$activationKey = md5(uniqid('CS', true));
/********************************************************************************
* CREATE THE USER IN THE DATABASE
********************************************************************************/
// Create the user and insert in the database
return User::create([
'usertype' => config('constants.userTypes.USER'),
'registeredon' => strtotime(date("Y-m-d H:i:s")),
'activationkey' => $activationKey,
'language' => 'nl',
'email' => Helper::truncate($data['email']),
'fullname' => Helper::truncate($data['lastname'] . ' ' . $data['firstname']),
'firstname' => Helper::truncate($data['firstname']),
'lastname' => Helper::truncate($data['lastname']),
'password' => Hash::make($data['password']),
'lastloginon' => strtotime('now'),
'lastloginip' => $_SERVER['REMOTE_ADDR'],
'activatedon' => strtotime(date('Y-m-d H:i:s', strtotime('1970-01-01 00:00:00'))),
'deleted' => false,
'companyname' => Helper::truncate($data['companyname']),
'street' => Helper::truncate($data['street']),
'number' => Helper::truncate($data['number']),
'city' => Helper::truncate($data['city']),
'zipcode' => Helper::truncate($data['zipcode']),
'vatnumber' => Helper::truncate($data['vatnumber']),
'validvat' => $isVatValid,
'website' => Helper::truncate($data['website']),
'phonenumber' => Helper::truncate($data['phonenumber']),
'bankname' => Helper::truncate($data['bank']),
'iban' => Helper::truncate($data['iban']),
'bicswift' => Helper::truncate($data['bicswift']),
'paymentremindermode' => $data['paymentremindermode'],
'invoicecreationremindermode' => 2,
'nettosavedmailmode' => 1,
'zombiemailsent' => 0,
'zombiemail180sent' => 0,
'nettosavedperinvoicmailemode' => 1,
'logo' => NULL,
'emailaccepted' => false,
'contractaccepted' => false,
'compercentagecreative' => $compercentagecreative,
'compercentagenotcreative' => $compercentagenotcreative,
'contractdate' => date("Y-m-d H:i:s"),
'creativepercent' => $creativepercent,
'activity' => $data['activity'],
'headjob' => $data['headjob'],
'template' => config('constants.templates.ORIGINAL'),
'freebtw' => isset($data['freebtw']) ? ($data['freebtw'] == "on" ? true : false) : false,
'refid' => Input::get('invite_id'),
'api_key' => Helper::generateRandomString(40),
'allowed_quotation' => true,
'send_bcc' => false
]);
}

authentication to MQ via mqseries library php

I need some help with php mqseries library.
I have some troubles connecting to Queue-manager. It does connect without authentication, but when I'm trying to use MQCSP, I get
2035 error.
I've contacted the developers, one of them told me that he no longer works on it, others don't respond.
It looks like on IBM it doesn't work.
Here is my connection code:
$cfg = array();
$cfg['ESB_ADDRESS'] = '10.4.116.110(1416)';
$cfg['ESB_CHANNEL'] = 'SITEEXT.SVRCONN';
$cfg['ESB_QUEUE_MANAGER'] = 'IIB.ADP.MI1';
$cfg['ESB_QUEUE_NAME'] = 'SITEEXT_TO_ESB';
$cfg['ESB_TOPIC_STRING'] = '';
$cfg['USERID'] = 'svcgo-site';
$cfg['PASSWORD'] = 'site91';
$cfg['QMgrName'] = 'IIB.ADP.MI1';
$cfg['DiscInterval'] = '10';
/*
$cfg['ESB_ADDRESS'] = '10.4.111.139(1414)';
$cfg['ESB_CHANNEL'] = 'SITEEXT.SVRCONN';
$cfg['ESB_QUEUE_MANAGER'] = 'QM01';
$cfg['ESB_QUEUE_NAME'] = 'TEST_QUEUE1';
//$cfg['ESB_QUEUE_NAME'] = 'SITEEXT_TO_ESB';
$cfg['ESB_TOPIC_STRING'] = '';
$cfg['USERID'] = 'svcgo-site';
$cfg['PASSWORD'] = 'site91';
//$cfg['QMgrName'] = 'QM01';
$cfg['DiscInterval'] = '10';
*/
$connectionOptions = array(
'StrucId' => MQSERIES_MQCNO_STRUC_ID,
'Version' => MQSERIES_MQCNO_CURRENT_VERSION,
'Options' => MQSERIES_MQCNO_STANDARD_BINDING,
//MQSERIES_USE_MQCSP_AUTHENTICATION,
'MQCD' => array(
//'Version' => MQSERIES_MQCD_VERSION_11,
'ChannelName' => $cfg['ESB_CHANNEL'],
'TransportType' => MQSERIES_MQXPT_TCP,
'ConnectionName' => $cfg['ESB_ADDRESS']
),
MQSERIES_USE_MQCSP_AUTHENTICATION => true,
MQSERIES_MQCSP_AUTHENTICATION => true,
USER_AUTHENTICATION_MQCSP => true,
USE_MQCSP_AUTHENTICATION => true,
MQSERIES_USER_AUTHENTICATION_MQCSP => true,
useMQCSPAuthentication => true,
'MQCSP' => array(
'Version' => MQSERIES_MQCSP_CURRENT_VERSION,
'StrucId' => MQSERIES_MQCSP_STRUC_ID,
'AuthenticationType' => MQSERIES_MQCSP_AUTH_USER_ID_AND_PWD,
'CSPUserIdPtr' => $cfg['USERID'],
'CSPUserIdLength' => strlen($cfg['USERID']),
'CSPPasswordLength' => strlen($cfg['PASSWORD']),
'CSPPasswordPtr' => $cfg['PASSWORD']
),
/*
'ClientConnPtr' => array(
//'Version' => MQSERIES_MQCD_VERSION_11,
'ChannelName' => $cfg['ESB_CHANNEL'],
'TransportType' => MQSERIES_MQXPT_TCP,
'ConnectionName' => $cfg['ESB_ADDRESS']
)
*/
);
mqseries_connx($cfg['ESB_QUEUE_MANAGER'], $connectionOptions, $connection, $completionCode, $reason);
if ($completionCode !== MQSERIES_MQCC_OK) {
die("Connx CompCode : {$completionCode} Reason : {$reason} Text : " . mqseries_strerror($reason));
}
else{echo "Good<br>";}
Php v.5.3.17
IBM MQ 9
Mqseries client library v 0.15.0
That PHP package does not have the code in it to handle the MQCSP structure and add it to the CNO. Looks like you would need to modify the _mqseries_set_mqcno_from_array function and how it is called.

Typo 3: Create user on FE login

The situation:
I build an authentication service that uses Basic Authentication to check if the user exists on an external database and fetches some data. The users in question only exist on the external database.
The problem:
Typo3 needs to have an user entry in the fe_user table to login the user.
So whenever this entry does not exist, the user cannot login.
What I want to do:
Create the user in the authentication service to avoid using a sql dump from the external database and ensure that synchronisation is possible.
The relevant code:
public function authUser(array $user) {
$a_user = $this->login['uname'];
$a_pwd = $this->login['uident_text'];
$url = 'https://soliday.fluchtpunkt.at/api/queryMediaItems';
$data = json_decode('{"language":"de-at"}');
$basicAuth = base64_encode("$a_user:$a_pwd");
// use key 'http' even if you send the request to https://...
$options = array (
'http' => array (
'header' => array(
"Content-Type: application/json",
"Accept: application/json",
"Authorization: Basic {$basicAuth}"
),
'method' => 'POST',
'content' => '{"language":"de-at"}'
)
);
$context = stream_context_create ( $options );
$result = file_get_contents ($url, false, $context);
$response = gzdecode($result);
$checkUser = $this->fetchUserRecord ( $this->login ['uname'] );
if (!is_array($checkUser)&& $result!== FALSE) {
$this->createUser();
}
// failure
if ($result === FALSE) {
return static::STATUS_AUTHENTICATION_FAILURE_BREAK;
}
$this->processData($response);
// success
return static::STATUS_AUTHENTICATION_SUCCESS_BREAK;
}
public function createUser() {
$username = $this->login ['uname'];
$password = $this->login ['uident_text'];
$record = $GLOBALS ['TYPO3_DB']->exec_SELECTgetSingleRow ( '*', 'fe_users', "username = '" . $username . "' AND disable = 0 AND deleted = 0" );
if (! $record) {
// user has no DB record (yet), create one using defaults registered in extension config
// password is not important, username is set to the user's input
$record = array (
'username' => $username,
'password' => $password,
'name' => '',
'email' => '',
'disable' => '0',
'deleted' => '0',
'pid' => $this->config ['storagePid'],
'usergroup' => $this->config ['addUsersToGroups'],
'tstamp' => time ()
);
if (t3lib_extMgm::isLoaded ( 'extbase' )) {
$record ['tx_extbase_type'] = $this->config ['recordType'];
}
$GLOBALS ['TYPO3_DB']->exec_INSERTquery ( 'fe_users', $record );
$uid = $GLOBALS ['TYPO3_DB']->sql_insert_id ();
$record = $GLOBALS ['TYPO3_DB']->exec_SELECTgetSingleRow ( '*', 'fe_users', 'uid = ' . intval ( $uid ) );
}
$_SESSION [$this->sessionKey] ['user'] ['fe'] = $record;
}
the ext_localconf.php file:
<?php
if (!defined('TYPO3_MODE')) {
die ('Access denied.');
}
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addService(
$_EXTKEY,
'auth' /* sv type */,
'AuthService' /* sv key */,
array(
'title' => 'GET Authentication service',
'description' => 'Authenticates users with GET request.',
'subtype' => 'getUserFE, authUserFE',
'available' => true,
'priority' => 90,
'quality' => 90,
'os' => '',
'exec' => '',
'className' => Plaspack\professionalZoneLogin\Service\AuthService::class,
)
);
You should extend AuthenticationService with your own code, way of doing that is described here https://docs.typo3.org/typo3cms/CoreApiReference/ApiOverview/Xclasses/Index.html
Not sure if it's related, but t3lib_extMgm should be \TYPO3\CMS\Core\Utility\ExtensionManagementUtility unless you're using TYPO3 6.
You can also see if you get any SQL errors by calling $GLOBALS['TYPO3_DB']->sql_error().

Prestashop error "invalid security token"

im creating a new module for prestashop 1.5.6 and im having some problems with it.
The module has to send sms to the costumers and it has to be an option of the back-Office menu.
I have created the module with the install and uninstall functions and added the tabs to the back-office menu, but im a newbie in prestashop so i don´t know how to make the AdminMyModuleController.php and when i try to click the tab of the module it says "INVALID SECURITY TOKEN", i don´t know how resolve this issue because i don´t know much of security.
If someone can add me on facebook or whatever to help me would be amazing.
Here is the code of the mymodule.php:
private function _createTab()
{
// Tab Raiz
$data = array(
'id_tab' => '',
'id_parent' => 0,
'class_name' => 'Empty',
'module' => 'mymodule',
'position' => 14, 'active' => 1
);
/* Insert the data to the tab table*/
$res = Db::getInstance()->insert('tab', $data);
//Get last insert id from db which will be the new tab id
$id_tabP = Db::getInstance()->Insert_ID();
//Define tab multi language data
$data_lang = array(
'id_tab' => $id_tabP,
'id_lang' => Configuration::get('PS_LANG_DEFAULT'),
'name' => 'SMS a clientes'
);
// Now insert the tab lang data
$res &= Db::getInstance()->insert('tab_lang', $data_lang);
// Tab Configuracion
$data = array(
'id_tab' => '',
'id_parent' => $id_tabP,
'class_name' => 'AdminMymodule',
'module' => 'mymodule',
'position' => 1, 'active' => 1
);
$res = Db::getInstance()->insert('tab', $data);
$id_tab = Db::getInstance()->Insert_ID();
$data_lang = array(
'id_tab' => $id_tab,
'id_lang' => Configuration::get('PS_LANG_DEFAULT'),
'name' => 'Configuracion'
);
$res &= Db::getInstance()->insert('tab_lang', $data_lang);
// Tab Enviar Sms
$data = array(
'id_tab' => '',
'id_parent' => $id_tabP,
'class_name' => 'AdminEnviar',
'module' => 'mymodule',
'position' => 1, 'active' => 1
);
$res = Db::getInstance()->insert('tab', $data);
$id_tab = Db::getInstance()->Insert_ID();
$data_lang = array(
'id_tab' => $id_tab,
'id_lang' => Configuration::get('PS_LANG_DEFAULT'),
'name' => 'Enviar SMS'
);
$res &= Db::getInstance()->insert('tab_lang', $data_lang);
return true;
}
Thanks
As Lliw said, you must use InstallModuleTab function.
private function installModuleTab($tabClass, $tabName, $idTabParent)
{
$pass = true;
$tab = new Tab();
$tab->name = $tabName;
$tab->class_name = $tabClass;
$tab->module = $this->name; // defined in __construct() function
$tab->id_parent = $idTabParent;
$pass = $tab->save();
return($pass);
}
You can put all in your Install function. For example for your first tab:
public function install()
{
if(!parent::install()
|| !$this->installModuleTab('Empty', array(1 => 'SMS a clientes'), $idTabParent = 0))
return false;
return true;
}
You can set languages with the following array:
array(1 => 'SMS a clientes', 2 => 'Language 2', 3 => 'Language 3')
Then you must create the AdminMyModuleController.php file
It's the wrong way to create a module tab. You should use this function in your install() :
$this->installModuleTab('AdminMyModule', array(1 => 'Attribute description'), $idTabParent = 9);
Then create an AdminMyModuleController.php in your module folder/controllers/admin/AdminMyModuleController.php
But you will need to set some function to see something displayed, i'll make a tutorial for that but until i do it, you can look in another admincontroller from the prestashop core and do the same.

Categories