yii2 file upload not working - file-upload

I have followed the following guide https://github.com/yiisoft/yii2/blob/master/docs/guide/input-file-upload.md but no file is being uploaded. below is my configuration
_form
This is in a for loop so i can get an array of different records.
<?= $form->field(new UploadForm , "[$count]file")->fileInput()->label(false) ?>
view
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>...
controller
if(isset(Yii::$app->request->post()['Factsheets'])){
for($i=0 ; $i < count(Yii::$app->request->post()['Factsheets']); $i++) {
//Yii::error(print_r(Yii::$app->request->post()['Factsheets'][$i],true));
if(!empty(Yii::$app->request->post()['UploadForm'][$i]['file'])){
$file = new UploadForm();
$file->file = UploadedFile::getInstance(Yii::$app->request->post()['UploadForm'][$i], 'file');
if ($file->file && $file->validate()) {
$file->file->saveAs('uploads/' . $file->file->baseName . '.' . $file->file->extension);
}
}
}
}
post log
[Factsheets] => Array
(
[0] => Array
(
[type] => image
[factsheet_id] => 1185
[path] => ../public/filespool/2/289/Pelotas_Reprocessing.jpg
)
[1] => Array
(
[type] => tech_paper
[factsheet_id] => 1433
[path] => ?basin=pelotas
)
[2] => Array
(
[type] => factsheet
[factsheet_id] => 1844
[path] => ../public/filespool/2/289/Pelotas_Reprocessing.pdf
)
)
[UploadForm] => Array
(
[0] => Array
(
[file] =>
)
[1] => Array
(
[file] =>
)
[2] => Array
(
[file] =>
)
)
I have noticed the following in the post log now. how do i construct it?
$_FILES = [
'UploadForm' => [
'name' => [
0 => [
'file' => 'Destin_Dome.jpg'
]
1 => [
'file' => ''
]
2 => [
'file' => 'Pelotas_Reprocessing.pdf'
]
]
'type' => [
0 => [
'file' => 'image/jpeg'
]
1 => [
'file' => ''
]
2 => [
'file' => ''
]
]
'tmp_name' => [
0 => [
'file' => '/tmp/phpoPgbJ9'
]
1 => [
'file' => ''
]
2 => [
'file' => ''
]
]
'error' => [
0 => [
'file' => 0
]
1 => [
'file' => 4
]
2 => [
'file' => 1
]
]
'size' => [
0 => [
'file' => 1129373
]
1 => [
'file' => 0
]
2 => [
'file' => 0
]
]
]
]
It seems like it is failing validation however i was able to make a copy like:
if(!empty($_FILES['UploadForm']['tmp_name']['file'])){
copy($_FILES['UploadForm']['tmp_name']['file'],"/tmp/".$_FILES['UploadForm']['name']['file']);
}
fileUpload model
public $file;
public $image;
public $factsheet;
/**
* #return array the validation rules.
*/
public function rules()
{
return [
[['file'], 'file','maxFiles' => 10],
[['image'], 'file','extensions' => 'gif, jpg'],
[['factsheet'], 'file','checkExtensionByMimeType' => false,'extensions' => 'pdf'],
];
}

I may be wrong but I think the problem is in your controller: your model rules are for multiple file upload and your form field too, but in the controller you set $model->file as a single UploadedFile instance. That is why your validation does not work. I can't give your advice (to change controller or model rule) because I do not clearly understand what are you doing here. It looks like you are creating multiple models from a single file upload field...

Related

Laravel 5.8 LDAP Authentication not working - LdapRecord Package

I'm trying to implements an LDAP authentication in an application for my company. I'm using Laravel 5.8 and the LdapRecord package
I have succeed to connect the application with the LDAP server test see Successfully connected and my to authenticate with openldap to online server its also Successfully. but when i want to do the authentication with active directory to my app it not working , Why who can help me?
Here is my code :
The .env
LDAP_LOGGING=true
LDAP_CONNECTION=default
LDAP_HOST=server
LDAP_PORT=389
LDAP_BASE_DN="dc=mydomain,dc=local"
LDAP_TIMEOUT=5
LDAP_SSL=false
LDAP_TLS=false
The ldap.php
return [
'default' => env('LDAP_CONNECTION', 'default'),
'connections' => [
'default' => [
'hosts' => [env('LDAP_HOST', 'server')],
'username' => env('LDAP_USERNAME', ''),
'password' => env('LDAP_PASSWORD', ''),
'port' => env('LDAP_PORT', 389),
'base_dn' => env('LDAP_BASE_DN', 'dc=mydomain,dc=local'),
'timeout' => env('LDAP_TIMEOUT', 5),
'use_ssl' => env('LDAP_SSL', false),
'use_tls' => env('LDAP_TLS', false),
],
],
'logging' => env('LDAP_LOGGING', true),
'cache' => [
'enabled' => env('LDAP_CACHE', false),
'driver' => env('CACHE_DRIVER', 'file'),
],
];
The auth.php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'ldap',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
'providers' => [
'users' => [
'driver' => 'eloquent' ,
'model' => App \ User :: class,
],
'ldap' => [
'driver' => 'ldap',
'model' => LdapRecord\Models\ActiveDirectory\User::class,
// 'model' => LdapRecord\Models\OpenLDAP\User::class,
'database' => [
'model' => App\User::class,
'sync_passwords' => false,
'sync_attributes' => [
'name' => 'cn',
'email' => 'mail',
],
],
]
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
'password_timeout' => 10800,
];
The user.php model
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use LdapRecord\Laravel\Auth\LdapAuthenticatable;
use LdapRecord\Laravel\Auth\AuthenticatesWithLdap;
class User extends Authenticatable implements LdapAuthenticatable
{
use Notifiable, AuthenticatesWithLdap, HasLdapUser ;
protected $fillable = [
'name',
'email',
'password',
];
protected $hidden = [
'password', 'remember_token' ,
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
The LoginController
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
protected function credentials(Request $request)
{
return [
'uid' => $request->get('username'),
'password' => $request->get('password'),
];
}
public function username()
{
return 'username';
}
}
Is there anyone who has already used this package and can help me on my code ? thank you in advance :)

Yii2- ArrayHelper change index of array

I have an array as follows:
[
0 => [
'name' => 'CARD'
'id' => '0'
]
1 => [
'name' => 'MOBILE'
'id' => '1'
]
2 => [
'name' => 'GIFT'
'id' => '2'
]
]
I want to change the key id to type in all the array. Is there a way to do this in Yii2 using ArrayHelper?
You can use getColumn() for this:
$result = ArrayHelper::getColumn($array, function ($data) {
return [
'name' => $data['name'],
'type' => $data['id'],
];
});
But it will not really differ from array_map() or simple foreach.
There is not an array helper for this but you could do this with a php foreach
foreach ($myArray as $key => $value) {
$myArray[$key]['type'] = $value['id'];
unset($myArray[$key]['id']);
}

Joining With SQL Function In CakePHP 3

Hi there I want to change this query into cakePHP 3.0 format but the code is not working could you guys can help me to solve this problem?
Normal SQL:
SELECT COUNT(user_tag_review.id) AS user_numbers, SUM(user_rating.rating_value) AS rating_value FROM user_tag_review INNER JOIN user_rating ON user_tag_review.id = user_rating.review_id WHERE user_tag_review.recruiter_id = 2 AND user_rating.rating_id = 1
CakePHP code that I have used:
$review_table = TableRegistry::get('UserTagReview');
$query = $review_table->find();
$query->select(["user_numbers" => $query->func()->count("UserTagReview.id")])
->hydrate(false)
->join(["table" => "user_rating",
"alias" => "r",
"type" => "INNER",
"condition" => ['r.review_id = UserTagReview.id']
])
->select(["rating_value" => $query->func()->sum("r.rating_value")])
->where(["UserTagReview.recruiter_id" => $recruiter_id, "UserTagReview.rating_id = " . 1]);
$result = $query->all()->toArray();
I think simpler way to migrate that SQL to Cake is fields options in finder:
$table = TableRegistry::get('UserTagReview');
$result = $table
->find('all' , [
'fields' => [
'user_numbers' => 'COUNT(UserTagReview.id)',
'rating_value' => 'SUM(user_rating.rating_value)'
],
'join' => [
[
'table' => 'user_rating',
'alias' => 'user_rating',
'type' => 'INNER',
'conditions' => [
'UserTagReview.id = user_rating.review_id'
]
]
],
'conditions' => [
'UserTagReview.recruiter_id' => 2,
'user_rating.rating_id' => 1
]
])
->hydrate(FALSE)
->toArray();
Maybe this code is not 100% correct, but focus on fields array - if we use this as associative array, we can evaluate any sql:
'fields' => [
'alias' => 'COUNT(IF(1,1,0))'
]

install.php is not being run during installation

My install.php is not being run during installation.I checked everywhere.To be sure,I ran the code in install.php elsewhere and it worked well. But during installation only the install.php is being skipped somehow.My module name is Hotelreservation, hence the code in install.php is as below. Why is there no error display during installation ?
<?php
class Hotelreservation_Installer extends Engine_Package_Installer_Module
{
public function onInstall()
{
$this->_hotelroomsBrowsePage();
parent::onInstall();
}
protected function _hotelroomsBrowsePage()
{
$db = $this->getDb();
// profile page
$page_id = $db->select()
->from('engine4_core_pages', 'page_id')
->where('name = ?', 'hotelreservation_index_browse')
->limit(1)
->query()
->fetchColumn();
if (!$page_id) {
// Insert page
$db->insert('engine4_core_pages', array(
'name' => 'hotelreservation_index_browse',
'displayname' => 'HotelRooms Browse Page',
'title' => 'Browse Rooms',
'description' => 'this page displays rooms',
'custom' => 0,
));
$page_id = $db->lastInsertId();
// Insert main
$db->insert('engine4_core_content', array(
'type' => 'container',
'name' => 'main',
'page_id' => $page_id,
));
$main_id = $db->lastInsertId();
// Insert middle
$db->insert('engine4_core_content', array(
'type' => 'container',
'name' => 'middle',
'page_id' => $page_id,
'parent_content_id' => $main_id,
'order' => 2,
));
$middle_id = $db->lastInsertId();
// Insert hotelreservation.browse-menu
$db->insert('engine4_core_content', array(
'type' => 'widget',
'name' => 'hotelreservation.browse-menu',
'page_id' => $page_id,
'parent_content_id' => $middle_id,
'order' => 1,
));
// Insert core content
$db->insert('engine4_core_content', array(
'type' => 'widget',
'name' => 'core.content',
'page_id' => $page_id,
'parent_content_id' => $middle_id,
'order' => 2,
));
// Insert left
$db->insert('engine4_core_content', array(
'type' => 'container',
'name' => 'left',
'page_id' => $page_id,
'parent_content_id' => $main_id,
'order' => 3,
));
$left_id = $db->lastInsertId();
}
return $this;
}
}// end class
Did you add info to mainfest file like this in packages array
'callback' => array(
'path' => 'Your path to php file',
'class' => 'Hotelreservation_Installer',
),
I agree with Arif. Check the file manifest.php inside of //settings:
(info of module Album)
'callback' => array(
'path' => 'application/modules/Album/settings/install.php',
'class' => 'Album_Installer',
),
I had this same issue and got it to work.
It turns out that the installer looks in application/packages/module-yourmodule-x.x.x.json first. around line 35 you'll find:
"callback": {
"path": null,
"class": "Engine_Package_Installer_Module",
"priority": 100
},
change that to:
"callback": {
"path": "application/modules/Yourmodule/settings/install.php",
"class": "Yourmodule_Installer",
"priority": 100
},
now, when you run the installer, your install.php will be called.

Zend Framework 2 + Doctrine 2 and Authentication Service

It was successfully working before I changed the authentication service name from 'orm_default' to 'admin', and it is necessary since I have more modules which uses more authentication services.
The problem is I'm getting the following error:
Fatal error: Uncaught exception 'Zend\ServiceManager\Exception\ServiceNotFoundException' with message 'Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for doctrine.authenticationservice.admin'
My module.config.php
'doctrine' => array
(
'driver' => array
(
__NAMESPACE__ . '_driver' => array
(
'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
'cache' => 'array',
'paths' => array(__DIR__ . '/../src/' . __NAMESPACE__ . '/Entity')
),
'orm_default' => array
(
'drivers' => array
(
__NAMESPACE__ . '\Entity' => __NAMESPACE__ . '_driver'
),
)
),
'authentication' => array
(
'admin' => array
(
'object_manager' => 'Doctrine\ORM\EntityManager',
'identity_class' => __NAMESPACE__ . '\Entity\User',
'identity_property' => 'email',
'credential_property' => 'password',
'credentialCallable' => __NAMESPACE__ . '\Model\User::hashPassword'
),
),
),
My Module.php
public function getServiceConfig()
{
return array
(
'factories' => array
(
'Admin\Auth' => function($sm)
{
return $sm->get('doctrine.authenticationservice.admin');
},
'Admin\Form\Auth\Login' => function($sm)
{
return new Form\Auth\Login();
},
),
);
}
It was confirmed as a bug: https://github.com/doctrine/DoctrineORMModule/issues/291
According to a comment in a doctrine module source file it plans to be fixed in 1.0. In this meantime you can it in your any module.config.php file of your application like this:
'authentication' =>
[
'application' =>
[
'object_manager' => 'Doctrine\ORM\EntityManager',
'identity_class' => 'Application\Entity\Customer',
'identity_property' => 'email',
'credential_property' => 'password',
'credentialCallable' => 'Application\Entity\Customer::hashPassword'
],
],
'authenticationadapter' =>
[
'application' => true,
],
'authenticationstorage' =>
[
'application' => true,
],
'authenticationservice' =>
[
'application' => true,
]
I had exactly same problem when i was working on my project. After working my *ss out for two nights, i solved the problem by simply re-installing the doctrine-orm-module after reading https://github.com/doctrine/DoctrineORMModule, "Registered Service names" section. This simply means doctrine orm module wasn't properly installed, or wasn't installed.