Codeigniter Custom data validation - php

I will try to upload an Excel file and verify its contents.
So I tried the code as below.
if ($this->upload->do_upload("filename"))
{
...
// I Think it is idiot code . . but . . anyway . . :_(
$_POST = array(
"name" => $cell[0],
"phone" => $cell[1],
"birth" => $cell[2],
...
);
$config = array(
array("field"=>"name", "label"=>"Name", "rule"=> "required"),
...
);
$this->form_validation->set_rules($config);
$this->form_validation->set_error_delimiters('', '');
if ($this->form_validation->run() === false)
{
throw new Exception($this->form_validation->error_string());
}
...
}
How to validate custom data using form_validation?

You can pass your data like that:
$data = array(
'username' => 'johndoe',
'password' => 'mypassword',
'passconf' => 'mypassword'
);
$this->form_validation->set_data($data);

Related

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().

how to integrate Assently api for e-signature transaction in PHP

In my wp project, I am using Assently for e-signature implementation. Though I have an account and created a pdf form file to be filled by the user I just am not able to proceed a bit. I am finding documentation not clear.
Also, I am not clear about what needs to be done so that the user will be shown form to process the transaction.
So, any help/suggestions to proceed forward is appreciated.
I have tried the following based on assently-laravel. But it's asking me to login. What is an error here?
Code:
define('ASSENTLY_DEBUG', true);
define('ASSENTLY_KEY', 'key');
define('ASSENTLY_SECRET', 'secret-generated');
include_once('assently/Assently.php');
$assently = new Assently();
$assently->authenticate(ASSENTLY_KEY, ASSENTLY_SECRET);
$url = 'https://test.assently.com/api/v2/createcasefromtemplate';
$default = array(
'Id' => '5a0e0869-' . rand(1111, 9999) . '-4b79-' . rand(1111, 9999) . '-466ea5cca5ce'
);
$data = array(
'auth' => $assently->auth(),
'templateId' => '0e004e2b-b192-4ce2-8f47-d7a4576d7df6',
'newCaseId' => '5a0e0869-' . rand(1111, 9999) . '-4b79-' . rand(1111, 9999) . '-466ea5cca5ce',
'agentUsername' => ''
);
$data = array(
'json' => $data
);
$options = array(
'http' => array(
'header' => "Content-type: application/json; charset=utf-8\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo '<pre>';
print_r($result);
die;
create this class inside assently folder
use Assently\AssentlyCase;
use Exception;
class CustomAssentlyCase extends AssentlyCase
{
public function createFromTemplate($data)
{
$default = [
'newCaseId' => '5a0e0869-'.rand(1111, 9999).'-4b79-'.rand(1111, 9999).'-466ea5cca5ce'
];
$json = array_merge($default, $data);
try{
$response = $this->client->post($this->url('createcasefromtemplate'), [
'auth' => $this->assently->auth(),
'json' => $json
]);
}catch(Exception $e){
print_r($e->getMessage());
}
return $response;
}
}
Use
define('ASSENTLY_DEBUG', true);
define('ASSENTLY_KEY', 'key');
define('ASSENTLY_SECRET', 'secret-generated');
include_once('assently/Assently.php');
include_once('assently/CustomAssentlyCase.php');
$assently = new Assently();
$assently->authenticate(ASSENTLY_KEY, ASSENTLY_SECRET);
$data = array(
'templateId' => '0e004e2b-b192-4ce2-8f47-d7a4576d7df6',
'newCaseId' => '5a0e0869-'.rand(1111, 9999).'-4b79-'.rand(1111, 9999).'-466ea5cca5ce',
'agentUsername' => 'agentUsername' // PUT your agent username here it is required
);
$customAssentlyCase = new CustomAssentlyCase($assently);
$result = $customAssentlyCase->createFromTemplate($data);
print_r($result);
Try this, though not tested but should work. Good luck.

POST request in PHP is returning PHP code when file extension is used

I am sending post requests in PHP to get a boolean value from my API (so it should return wither true or false)
This is the code I am using in the file for my API. The file is called users.php
if ($_POST['type'] == "authenticateMinecraft"){
$p = new dibdibs\post(
array(
'url' => 'https://authserver.mojang.com/authenticate',
'data' => array(
'agent' => array(
'name' => 'Minecraft',
'version' => 1
),
'username' => $_POST['username'],
'password' => $_POST['password'],
'clientToken' => "33225A179D9A4E1BDA73C012C1C3CBAB8BD00326883BDBEB6FA682482E40F68D"
)
)
);
$res = $p->json();
if (isset($res["selectedProfile"])){
echo("true");
}
else{
echo("false");
}
}
This is the code I am using to reference it (I am using a class which I have put on Pastebin to actually send the request).
$params = array(
'data' => array(
'type' => 'authenticateMinecraft',
'username' => $mcuname,
'password' => $mcpasswd
),
'url' => "api/users.php"
);
$c = new dibdibs\post($params);
$r = $c->http();
var_dump($r);
Whenever I use the .php fule extension when defining url, the whole PHP code of the API page is returned, but when I remove the extension, only true or false is returned. Why is this and is it a problem that I should be aware of and I should fox?

Gravity Forms - gform_after_submission not working

gform_after_submission is getting called in my page, but the $entry and $form objects are null. Is there any reason why that would be happening? Based on the output of the logs, I know the code runs, but can't figure out why the $entry argument is null.
add_action('gform_after_submission_2', 'post_to_third_party', 10, 2);
function post_to_third_party($entry, $form) {
error_log("Posting comments form");
$post_url = 'https://api.club-os.com/prospects?clubLocationId=686';
$body = array(
'first_name' => $entry['7.3'],
'last_name' => $entry['7.6'],
'email' => $entry['6'],
'mobilePhone' => $entry['8']
);
error_log('Before Post to' . $post_url);
$args = array(
'headers' => array('Authorization' => 'Basic ' . base64_encode( 'username' . ':' . 'password' )),
'body' => $body,
'sslverify' => false
);
foreach ($body as $key => $value) {
error_log($value . " in " . $key . ", ");
}
$request = new WP_Http();
$response = $request->post($post_url, $args);
}
Figured it out.
'first_name' => $entry['7.3'],
'last_name' => $entry['7.6'],
The 7.3 and 7.6 were incorrect indexes to the $entry object. I just used '7' and the split function to get it to work correctly.

zf2 how to upload files, more than 1 file

I refer to http://samsonasik.wordpress.com/2012/08/31/zend-framework-2-creating-upload-form-file-validation/ and follow this, I can upload 1 file successfully by using rename filter in ZF2.
However when I use this way to upload 2 files, it goes wrong. I paste my code as following:
$this->add(array(
'name' => 'bigpicture',
'attributes' => array(
'type' => 'file'
),
'options' => array(
'label' => 'Big Pic'
)
));
$this->add(array(
'name' => 'smallpicture',
'attributes' => array(
'type' => 'file'
),
'options' => array(
'label' => 'Small Pic'
)
));
<div class="row"><?php echo $this->formRow($form->get('smallpicture')) ?></div>
<div class="row"><?php echo $this->formRow($form->get('bigpicture')) ?></div>
$data = array_merge(
$request->getPost()->toArray(),
$request->getFiles()->toArray()
);
$form->setData($data);
if ($form->isValid()) {
$product->exchangeArray($form->getData());
$picid = $this->getProductTable()->saveProduct($product);
$pathstr = $this->md5path($picid);
$this->folder('public/images/product/'.$pathstr);
//move_uploaded_file($data['smallpicture']['tmp_name'], 'public/images/product/'.$pathstr.'/'.$picid.'_small.jpg');
//move_uploaded_file($data['bigpicture']['tmp_name'], 'public/images/product/'.$pathstr.'/'.$picid.'_big.jpg');
$fileadaptersmall = new \Zend\File\Transfer\Adapter\Http();
$fileadaptersmall->addFilter('File\Rename',array(
'source' => $data['smallpicture']['tmp_name'],
'target' => 'public/images/product/'.$pathstr.'/'.$picid.'_small.jpg',
'overwrite' => true
));
$fileadaptersmall->receive();
$fileadapterbig = new \Zend\File\Transfer\Adapter\Http();
$fileadapterbig->addFilter('File\Rename',array(
'source' => $data['bigpicture']['tmp_name'],
'target' => 'public/images/product/'.$pathstr.'/'.$picid.'_big.jpg',
'overwrite' => true
));
$fileadapterbig->receive();
}
the above are form,view,action.
using this way, only the small picture uploaed successfully. the big picture goes wrong.
a warning flashed like the following:
Warning:move_uploaded_file(C:\WINDOWS\TMP\small.jpg):failed to open stream:Invalid argument in
E:\myproject\vendor\zendframework\zendframework\library\zend\file\transfer\adapter\http.php
on line 173
Warning:move_uploaded_file():Unable to move 'C:\WINDOWS\TMP\php76.tmp'
to 'C:\WINDOWS\TEMP\big.jpg' in
E:\myproject\vendor\zendframework\zendframework\library\zend\file\transfer\adapter\http.php
on line 173
Who can tell me how to upload more than 1 file in this way. you know, the rename filter way similar to above. thanks.
I ran into the same problem with a site i did. The solution was to do the renaming in the controller itself by getting all the images and then stepping through them.
if ($file->isUploaded()) {
$pInfo = pathinfo($file->getFileName());
$time = uniqid();
$newName = $pName . '-' . $type . '-' . $time . '.' . $pInfo['extension'];
$file->addFilter('Rename', array('target' => $newName));
$file->receive();
}
Hope this helps point you in the right direction.
I encountered the same problem and i managed to make it work using the below code;
$folder = 'YOUR DIR';
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setDestination($folder);
foreach ($adapter->getFileInfo() as $info) {
$originalFileName = $info['name'];
if ($adapter->receive($originalFileName)) {
$newFilePath = $folder . '/' . $newFileName;
$adapter->addFilter('Rename', array('target' => $newFilePath,
'overwrite' => true));
}
}

Categories