I want to upload zip file in symfony but failed to do so.
When i am uploading text ot pdf or excel file,image or single file then it is uploaded fine.
But when i tried to upload zip file it returns nothig and also there is no error log only blank page is appaear.
Im My form i have the following code.
class UploadSalaryForm extends BaseForm {
public function configure() {
// Note: Widget names were kept from old non-symfony version
$var = 'salary';
$this->setWidgets(array(
'EmpID' => new sfWidgetFormInputHidden(),
'seqNO' => new sfWidgetFormInputHidden(),
'MAX_FILE_SIZE' => new sfWidgetFormInputHidden(),
'ufile' => new sfWidgetFormInputFile(),
'txtAttDesc' => new sfWidgetFormInputText(),
'screen' => new sfWidgetFormInputHidden(),
'commentOnly' => new sfWidgetFormInputHidden(),
));
$this->setValidators(array(
'EmpID' => new sfValidatorNumber(array('required' => true, 'min'=> 0)),
'seqNO' => new sfValidatorNumber(array('required' => false, 'min'=> 0)),
'MAX_FILE_SIZE' => new sfValidatorNumber(array('required' => true)),
'ufile' => new sfValidatorFile(array('required' => false)),
//'ufile', new sfValidatorFileZip(array('required' => false)),
'txtAttDesc' => new sfValidatorString(array('required' => false)),
'screen' => new sfValidatorString(array('required' => true,'max_length' => 50)),
'commentOnly' => new sfValidatorString(array('required' => false)),
));
// set up your post validator method
$this->validatorSchema->setPostValidator(
new sfValidatorCallback(array(
'callback' => array($this, 'postValidate')
))
);
}
public function postValidate($validator, $values) {
// If seqNo given, ufile should not be given.
// If seqNo not given and commentsonly was clicked, ufile should be given
$attachId = $values['seqNO'];
$file = $values['ufile'];
$commentOnly = $this->getValue('commentOnly') == "1";
if (empty($attachId) && empty($file)) {
$message = sfContext::getInstance()->getI18N()->__('Upload file missing');
$error = new sfValidatorError($validator, $message);
throw new sfValidatorErrorSchema($validator, array('' => $error));
} else if (!empty($attachId) && $commentOnly && !empty($file)) {
$message = sfContext::getInstance()->getI18N()->__('Invalid input');
$error = new sfValidatorError($validator, $message);
throw new sfValidatorErrorSchema($validator, array('' => $error));
}
return $values;
}
/**
* Save employee contract
*/
public function save() {
$empNumber = $this->getValue('EmpID');
$attachId = $this->getValue('seqNO');
$empAttachment = false;
if (empty($attachId)) {
$q = Doctrine_Query::create()
->select('MAX(a.attach_id)')
->from('EmployeeAttachment a')
->where('a.emp_number = ?', $empNumber);
$result = $q->execute(array(), Doctrine::HYDRATE_ARRAY);
if (count($result) != 1) {
throw new PIMServiceException('MAX(a.attach_id) failed.');
}
$attachId = is_null($result[0]['MAX']) ? 1 : $result[0]['MAX'] + 1;
} else {
$q = Doctrine_Query::create()
->select('a.emp_number, a.attach_id')
->from('EmployeeAttachment a')
->where('a.emp_number = ?', $empNumber)
->andWhere('a.attach_id = ?', $attachId);
$result = $q->execute();
if ($result->count() == 1) {
$empAttachment = $result[0];
} else {
throw new PIMServiceException('Invalid attachment');
}
}
//
// New file upload
//
$newFile = false;
if ($empAttachment === false) {
$empAttachment = new EmployeeAttachment();
$empAttachment->emp_number = $empNumber;
$empAttachment->attach_id = $attachId;
$newFile = true;
}
$commentOnly = $this->getValue('commentOnly');
if ($newFile || ($commentOnly == '0')) {
$file = $this->getValue('ufile');
echo "file==".$file;
$tempName = $file->getTempName();
$empAttachment->size = $file->getSize();
$empAttachment->filename = $file->getOriginalName();
$empAttachment->attachment = file_get_contents($tempName);;
$empAttachment->file_type = $file->getType();
$empAttachment->screen = $this->getValue('screen');
$empAttachment->attached_by = $this->getOption('loggedInUser');
$empAttachment->attached_by_name = $this->getOption('loggedInUserName');
// emp_id and name
}
$empAttachment->description = $this->getValue('txtAttDesc');
$empAttachment->save();
}
}
But this code is only worked for single file not for zip file.
I want to upload and extract zip file.
Related
I have a problem, I am currently doing a search by date range of maximum 10 days and the issue is that if there are more than 10 messages or there is a total of 38 messages it takes 4 to 5 minutes to load the data, so I wanted to know if there is a way to bring it paginated directly when doing the query in Horde.
public function connect($username, $password, $hostname, $port, $ssl, $folder, $debug = 0, $cache = 0)
{
$opt = [
'username' => $username,
'password' => $password,
'hostspec' => $hostname,
'port' => $port,
'secure' => $ssl,
];
if ($debug) $opt['debug'] = Log::debug("message");
if ($cache) $opt['cache'] = array(
'backend' => new \Horde_Imap_Client_Cache_Backend_Cache(array(
'cacheob' => new Horde_Cache(new Horde_Cache_Storage_File(array(
'dir' => '/tmp/hordecache'
)))
))
);
static::$folder = 'INBOX';
try {
return static::$client = new \Horde_Imap_Client_Socket($opt);
} catch (\Horde_Imap_Client_Exception $e) {
// Any errors will cause an Exception.
dd('Error');
}
}
public function searchSince($date_string)
{
try {
$query = new Horde_Imap_Client_Search_Query();
$query->dateSearch(
new Horde_Imap_Client_DateTime($date_string), Horde_Imap_Client_Search_Query::DATE_SINCE
);
$results = static::$client->search(static::$folder,$query);
} catch (\Exception $th) {
dd('Since Mail');
}
if ($results) {
static::$var = $results['match']->ids;
return true;
}
return false;
}
//I get the header data of each message (subject, date, uid, from, client name)
public function next(){
if ($var = next(static::$var)) {
static::$id = $var;
$headers = HordeImap::fetchHeaders(static::$id);
static::$clientName = $headers->getHeader('From')->getAddressList(true)->first()->__get('personal');
static::$fromEmail = $headers->getHeader('From')->getAddressList(true)->first()->__get('bare_address');
static::$subject = $headers->getHeader('subject')->__get('value');
$emailDate = $headers->getHeader('Date')->__get('value');
$unixTimestamp = strtotime($emailDate);
static::$emailDate = date('Y-m-d H:i:s',$unixTimestamp);
return true;
}
return false;
}
Controller
$mailb = new HordeImap();
$mailb->connect($userMail->client,$userMail->secret_token,$userMail->server,$userMail->port,'ssl','INDEX',1);
$msgs = $mailb->searchSince(date('d F Y', strtotime(date("Y-m-d", time()) . " -10 days")));
static::$mailbox = [];
if($msgs) while($mailb->next()){
static::$mailbox[] = [
'uid' => $mailb::$id,
'from' => $mailb::$fromEmail,
'client'=> $mailb::$clientName,
'date' => $mailb::$emailDate,
'subject'=> $mailb::$subject,
];
}
// I page the array once I have obtained all the contents.
$page = null;
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
$items = static::$mailbox instanceof Collection ? static::$mailbox : Collection::make(static::$mailbox);
dd(new LengthAwarePaginator($items->forPage($page, 5), $items->count(), 5, null, []));
I have a question about Abstract Validators. I was trying to implement the solution of Mb Rostami found here.
This is the error I get:
Zend\Validator\ValidatorPluginManager::get was unable to fetch or create an instance for Application\Validators\File\Image
All I need to do I guess is to somehow inject the class into the model. What is Application\Validators\File\Image?
So how to fix this error? Most easy solution would be to add the validator class as an invocable to the module?
The input filter in model class:
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$inputFilter->add(array(
'name' => 'eid',
'required' => true,
'filters' => array(
array('name' => 'Int'),
)
));
$newFileName = sha1(time(), true);
$inputFilter->add(
array(
'name' => 'ImageValidator',
'required' => true,
'validators' => array(
array(
'name' => '\Application\Validators\File\Image',
'options' => array(
'minSize' => '64',
'maxSize' => '5120',
'newFileName' => $newFileName,
'uploadPath' => './data/'
),
),
)
)
);
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
Validator class:
<?php
namespace Application\Validators\File;
use Zend\Validator\File\Extension;
use Zend\File\Transfer\Adapter\Http;
use Zend\Validator\File\FilesSize;
use Zend\Filter\File\Rename;
use Zend\Validator\File\MimeType;
use Zend\Validator\AbstractValidator;
class Image extends AbstractValidator
{
const FILE_EXTENSION_ERROR = 'invalidFileExtention';
const FILE_NAME_ERROR = 'invalidFileName';
const FILE_INVALID = 'invalidFile';
const FALSE_EXTENSION = 'fileExtensionFalse';
const NOT_FOUND = 'fileExtensionNotFound';
const TOO_BIG = 'fileFilesSizeTooBig';
const TOO_SMALL = 'fileFilesSizeTooSmall';
const NOT_READABLE = 'fileFilesSizeNotReadable';
public $minSize = 64; //KB
public $maxSize = 1024; //KB
public $overwrite = true;
public $newFileName = null;
public $uploadPath = './data/';
public $extensions = array('jpg', 'png', 'gif', 'jpeg');
public $mimeTypes = array(
'image/gif',
'image/jpg',
'image/png',
);
protected $messageTemplates = array(
self::FILE_EXTENSION_ERROR => "File extension is not correct",
self::FILE_NAME_ERROR => "File name is not correct",
self::FILE_INVALID => "File is not valid",
self::FALSE_EXTENSION => "File has an incorrect extension",
self::NOT_FOUND => "File is not readable or does not exist",
self::TOO_BIG => "All files in sum should have a maximum size of '%max%' but '%size%' were detected",
self::TOO_SMALL => "All files in sum should have a minimum size of '%min%' but '%size%' were detected",
self::NOT_READABLE => "One or more files can not be read",
);
protected $fileAdapter;
protected $validators;
protected $filters;
public function __construct($options)
{
$this->fileAdapter = new Http();
parent::__construct($options);
}
public function isValid($fileInput)
{
$options = $this->getOptions();
$extensions = $this->extensions;
$minSize = $this->minSize;
$maxSize = $this->maxSize;
$newFileName = $this->newFileName;
$uploadPath = $this->uploadPath;
$overwrite = $this->overwrite;
if (array_key_exists('extensions', $options)) {
$extensions = $options['extensions'];
}
if (array_key_exists('minSize', $options)) {
$minSize = $options['minSize'];
}
if (array_key_exists('maxSize', $options)) {
$maxSize = $options['maxSize'];
}
if (array_key_exists('newFileName', $options)) {
$newFileName = $options['newFileName'];
}
if (array_key_exists('uploadPath', $options)) {
$uploadPath = $options['uploadPath'];
}
if (array_key_exists('overwrite', $options)) {
$overwrite = $options['overwrite'];
}
$fileName = $fileInput['name'];
$fileSizeOptions = null;
if ($minSize) {
$fileSizeOptions['min'] = $minSize * 1024;
}
if ($maxSize) {
$fileSizeOptions['max'] = $maxSize * 1024;
}
if ($fileSizeOptions) {
$this->validators[] = new FilesSize($fileSizeOptions);
}
$this->validators[] = new Extension(array('extension' => $extensions));
if (!preg_match('/^[a-z0-9-_]+[a-z0-9-_\.]+$/i', $fileName)) {
$this->error(self::FILE_NAME_ERROR);
return false;
}
$extension = pathinfo($fileName, PATHINFO_EXTENSION);
if (!in_array($extension, $extensions)) {
$this->error(self::FILE_EXTENSION_ERROR);
return false;
}
if ($newFileName) {
$destination = $newFileName . ".$extension";
if (!preg_match('/^[a-z0-9-_]+[a-z0-9-_\.]+$/i', $destination)) {
$this->error(self::FILE_NAME_ERROR);
return false;
}
} else {
$destination = $fileName;
}
$renameOptions['target'] = $uploadPath . $destination;
$renameOptions['overwrite'] = $overwrite;
$this->filters[] = new Rename($renameOptions);
$this->fileAdapter->setFilters($this->filters);
$this->fileAdapter->setValidators($this->validators);
if ($this->fileAdapter->isValid()) {
$this->fileAdapter->receive();
return true;
} else {
$messages = $this->fileAdapter->getMessages();
if ($messages) {
$this->setMessages($messages);
foreach ($messages as $key => $value) {
$this->error($key);
}
} else {
$this->error(self::FILE_INVALID);
}
return false;
}
}
}
The solution was simple, at least in my case. Like I mentioned above: check the folder structure. Zend Framework has it's own way of structuring project files, so the file path needs to match.
I am currently doing an internship and I tried to make an activity module to show playlist, from video given by a filemanager. I succeed to send the video to the database but when I want to edit my module, it doesn't show any videos in the filemanager.
I read the moodle documentation about file API and I decided to use the following code (Load existing files into draft area)
:
if (empty($entry->id)) {
$entry = new stdClass;
$entry->id = null;
}
$draftitemid = file_get_submitted_draft_itemid('attachments');
file_prepare_draft_area($draftitemid, $context->id, 'mod_glossary','attachment', $entry->id,array('subdirs' => 0, 'maxbytes' => $maxbytes, 'maxfiles' => 50));
$entry->attachments = $draftitemid;
$mform->set_data($entry);
So I put the following lines in my mod_form.php :
$filemanager_options = array();
$filemanager_options['accepted_types'] = '*';
$filemanager_options['maxbytes'] = 0;
$filemanager_options['maxfiles'] = -1;
$filemanager_options['mainfile'] = true;
$mform->addElement('filemanager', 'files', get_string('selectfiles'), null, $filemanager_options);
if (empty($entry->id)) {
$entry = new stdClass;
$entry->id = null;
}
$draftitemid = file_get_submitted_draft_itemid('mymanager');
file_prepare_draft_area($draftitemid, $this->context->id, 'mod_playlist', 'content', 0,
array('subdirs'=>true));
$entry->attachments = $draftitemid;
$mform->set_data($entry);
The problem is that the file manager is still empty, and the line "$mform->set_data($entry); " makes the page to crash(blank).
Here is a template for uploading files.
In local/myplugin/upload.php
require_once(dirname(dirname(dirname(__FILE__))) . '/config.php');
require_once(dirname(__FILE__) . '/upload_form.php');
require_login();
$context = context_system::instance();
require_capability('local/myplugin:upload', $context);
$pageurl = new moodle_url('/local/myplugin/upload.php');
$heading = get_string('myupload', 'local_myplugin');
$PAGE->set_context($context);
$PAGE->set_heading(format_string($heading));
$PAGE->set_title(format_string($heading));
$PAGE->set_url('/local/myplugin/upload.php');
echo $OUTPUT->header();
echo $OUTPUT->heading($heading);
$fileoptions = array(
'maxbytes' => 0,
'maxfiles' => '1',
'subdirs' => 0,
'context' => context_system::instance()
);
$data = new stdClass();
$data = file_prepare_standard_filemanager($data, 'myfiles',
$fileoptions, context_system::instance(), 'local_myplugin', 'myfiles', 0); // 0 is the item id.
$mform = new upload_form(
null,
array(
'fileoptions' => $fileoptions,
)
);
if ($formdata = $mform->get_data()) {
// Save the file.
$data = file_postupdate_standard_filemanager($data, 'myfiles',
$fileoptions, context_system::instance(), 'local_myplugin', 'myfiles', 0);
} else {
// Display the form.
$mform->set_data($data);
$mform->display();
}
echo $OUTPUT->footer();
Then in local/myplugin/upload_form.php
defined('MOODLE_INTERNAL') || die;
require_once($CFG->libdir . '/formslib.php');
class upload_form extends moodleform {
public function definition() {
$mform =& $this->_form;
$fileoptions = $this->_customdata['fileoptions'];
$mform->addElement('filemanager', 'myfiles_filemanager',
get_string('myfiles', 'local_myplugin'), null, $fileoptions);
$this->add_action_buttons(false, get_string('save', 'local_myplugin'));
}
}
You will also need this in /local/myplugin/lib.php
function local_myplugin_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options = array()) {
if ($context->contextlevel != CONTEXT_SYSTEM) {
send_file_not_found();
}
$fs = get_file_storage();
$file = $fs->get_file($context->id, 'local_myplugin', $filearea, $args[0], '/', $args[1]);
send_stored_file($file);
}
Updating my collection record field with 'MongoBinData', exception is triggered:
"document fragment is too large: 21216456, max: 16777216"
I find some web discussion about 'allowDiskUse:true' for aggregate, but nothing ubout 'update'.
Here a part of code in PHP:
try {
$criteria = array( '_id' => $intReleaseId);
$fileData = file_get_contents( $_FILES[ $fileKey]["tmp_name"]);
$mongoBinData = new MongoBinData( $fileData, MongoBinData::GENERIC)
$docItem['data'] = $mongoBinData;
$docItem['fileType'] = $strFileType;
$docItem['fileSize'] = $intFileSize;
$docItem['fileExtension'] = $strFileExtension;
$docItem['fileName'] = $strFileName;
$options = array( "upsert" => true,
'safe' => true, 'fsync' => true,
'allowDiskUse' => true ); // this option doesn't change anything
$reportJson = self::GetCollection('releases')->update( $criteria, $docItem, $options);
...
MongoDb release is db version v3.0.6
Some idea ?
Self resolved.
Use gridFS is immediate and simple.
$_mongo = new MongoClient();
$_db = $_mongo->selectDB($_mDbName);
$_gridFS = $_db->getGridFS();
/* */
function saveFileData($intReleaseId, $binData) {
$criteria = array( '_id' => $intReleaseId);
// if exist or not, remove previous value
try {
$_gridFS->remove( $criteria);
}
catch(Exception $e) {}
// store new file content
$storeByteCompleted = false;
try {
$reportId = $_gridFS->storeBytes(
$binData,
array("_id" => $intReleaseId));
if ($reportId == $intReleaseId) {
$storeByteCompleted = true;
}
catch(Exception $e) {}
return $storeByteCompleted;
}
function loadFileData($intReleaseId) {
$gridfsFile = null;
$binData = null;
try {
$gridfsFile = $_gridFS->get($intReleaseId);
}
catch(Exception $e) {}
if ($gridfsFile != null) {
$binData = $gridfsFile->getBytes()
}
return $binData;
}
That's all.
I am trying to insert uploaded filenames to a table with the date they were uploaded, but I am running into some errors with trying to get the values of the filename with $_FILES
Here is my code:
public function uploadAction()
{
if (!$user = $this->identity()) {
return $this->redirect()->toUrl('/login/log');
}
$user = $this->identity();
$layout = $this->layout();
$layout->setVariable('user1', $user->username);
$form = new FileUploadForm();
$request = $this->getRequest();
if ($request->isPost()) {
$file = new File();
$form->setInputFilter($file->getInputFilter());
$captions = $request->getPost()->toArray();
$get_file = $this->params()->fromFiles('file');
$data = array_merge_recursive($this->getRequest()->getPost()->toArray(), $this->getRequest()->getFiles()->toArray());
$form->setData($data);
if ($form->isValid()) {
$size = new Size(array('min' => '10kB', 'max' => FileHandler::FILESIZE . 'MB'));
$extension = new Extension(array('jpg', 'jpeg', 'png'), true);
$adapter = new Http();
$adapter->setValidators(array($size, $extension), $get_file['name']);
if (!$adapter->isValid()) {
return $this->redirect()->toUrl('/admin/upload-failure');
} else {
$dir_check = !is_dir(FileHandler::UPLOAD_PATH . $user->username)
?
mkdir(FileHandler::UPLOAD_PATH . $user->username) ? FileHandler::UPLOAD_PATH . $user->username : null
: FileHandler::UPLOAD_PATH . $user->username;
$adapter->setDestination($dir_check);
if ($adapter->receive($get_file['name'])) {
$this->getFileUploadFactory()->insertUploadDate($_FILES);
$file->exchangeArray($form->getData());
return $this->redirect()->toUrl('/admin/upload-success');
} else {
return $this->redirect()->toUrl('/admin/upload-failure');
}
}
}
}
public function insertUploadDate(array $file)
{
try {
$insert = new Insert('uploads');
foreach ($file as $key => $value) {
$insert->columns(array('filename', 'upload_date'))
->values(array('filename' => $value, 'upload_date' => date('Y-m-d')));
$adapter = $this->table_gateway->getAdapter();
$adapter->query(
$this->sql->getSqlStringForSqlObject($insert),
$adapter::QUERY_MODE_EXECUTE
);
}
return true;
} catch (\PDOException $e) {
// save the exception message to the error file
$writer = new Stream(self::ERROR_PATH);
$logger = new Logger();
$logger->addWriter($writer);
$logger->info($e->getMessage() . "\r\r");
return false;
}
}
and then in the controller I am calling it like this:
$this->getFileUploadFactory()->insertUploadDate($_FILES);
Like I said, it's not inserting the correct names of the files I uploaded (using html5 multiple upload option)
Thanks!