Zend1 form upload document file - forms

I've got an "addForm" and a "editForm". After I have added a document file in the addForm, it will be saved in my db. If I want to edit this form, I have to upload this document again. The old document will be deleted. I would like to make a function to check whether the document is already uploaded or not, so I do not have to upload it every time I want to edit an item. I just do not know where to start. A little help will be great.
my add/editform:
$pdf = new Zend_Form_Element_File('document');
$pdf->setLabel('Nieuwe PDF')
->addValidator('extension', true, array('docx',
'docx','pdf','txt'))
->addValidator('Count', false, 1)
->addValidator('Size', false, 10240000)
->setDestination( PUBLIC_PATH . '/../data/invoicespdf/')
->setRequired(false);

Try using this in the controller...modify it to fit your needs :
if ($request->isPost()) {
if ($form->isValid($request->getPost())) {
if ('administrator' == $user->role) {
$oldFileName = $form->getElement('oldfilename')->getValue(); //the hidden field
$data = $form->getValues();
$model->populate($data);
if (file_exists('uploads/cv/' . $oldFileName)) {
$form->getElement('cv')->setIgnore(true); //this is my Form File Element - the file exists, I don't need to store the filename
} else { // if you want you can unlink $oldFileName
$upload = new Zend_File_Transfer_Adapter_Http();
$info = $upload->getFileInfo('cv');
$upload->setDestination("uploads/cv/");
if (file_exists('uploads/cv/' . $info['cv']['name'])) {
$newFileName = time() . rand(0, 100000) . "-" . $info['cv']['name']; // I need to avoid overwriting file
} else {
$newFileName = $info['cv']['name'];
$upload->addFilter('Rename', $newFileName);
}
try {
$upload->receive();
} catch (Zend_File_Transfer_Exception $e) {
$e->getMessage();
}
}
$model->save();
return $this->_helper->redirector('list');
} else {
//some error message
$this->_helper->redirector('list');
}
} else { //form not valid
$this->view->form = $form;
}
} else {
$model->find($id);
$data = array();
$data = $model->toArray();
$data['oldfilename'] = $model->get_cv(); //the filename stored in db
$form->getElement('cv')->setRequired(false);
$form->populate($data);
$this->view->form = $form;
}

Related

output records in the form of html table from moodle database , custom block development

Please check this code for the custom block to be placed in the dashboard. We want to display an HTML table for the records. But it does not add up to the custom block, rather it appears on the top page.
enter image description here
class block_scorecard extends block_base {
function init() {
$this->title = get_string('pluginname', 'block_scorecard');
}
function get_content() {
global $DB;
if ($this->content !== NULL) {
return $this->content;
}
$content = '';
$courses = $DB->get_records('scorm_scoes_track', ['element' => 'cmi.core.total_time']);
$table=new html_table();
$table->head=array('No of attempts','Time modified','status');
foreach ($courses as $course) {
$attempt=$course->attempt;
$timemodified=userdate($course->timemodified, get_string('strftimerecentfull'));
$status=$course->value;
$table->data[]=array($attempt, $timemodified, $status);
}
echo html_writer::table($table);
$this->content = new stdClass;
$this->content->text = $content;
}}
echo html_writer::table($table);
Should be
$content .= html_writer::table($table);

Moodle File Manager - Crucial part

I am trying to show the file uploaded from File Manager mform element. I could store the file to mdl_files. To get the file saved is a bit hard to program. I tried implementing few options from Moodle Forums, but was stuck here. I really hope that someone can provide a solution for Moodle File manager (a crucial part). Could anyone guide me where I went wrong and suggest me to get the fileurl.
<?php
require('config.php');
require_once($CFG->libdir.'/formslib.php');
class active_form extends moodleform {
function definition() {
$mform = $this->_form;
$fileoptions = $this->_customdata['fileoptions'];
$mform->addElement('filemanager', 'video', get_string('video', 'moodle'), null,
$fileoptions);
$this->add_action_buttons();
}
function validation($data, $files) {
$errors = parent::validation($data, $files);
return $errors;
}
}
// Function for local_statistics plugin.
function local_statistics_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload,
array $options=array()) {
global $DB;
if ($context->contextlevel != CONTEXT_SYSTEM) {
return false;
}
$itemid = (int)array_shift($args);
if ($itemid != 0) {
return false;
}
$fs = get_file_storage();
$filename = array_pop($args);
if (empty($args)) {
$filepath = '/';
} else {
$filepath = '/'.implode('/', $args).'/';
}
$file = $fs->get_file($context->id, 'local_statistics', $filearea, $itemid, $filepath,$filename);
if (!$file) {
return false;
}
// finally send the file
send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
}
// Form Settings
$fileoptions = array('maxbytes' => 0, 'maxfiles' => 1, 'subdirs' => 0, 'context' =>
context_system::instance());
$data = new stdClass();
$data = file_prepare_standard_filemanager($data, 'video', $fileoptions, context_system::instance(),
'local_statistics', 'video', 0);
$mform = new active_form(null, array('fileoptions' => $fileoptions));
// Form Submission
if ($data = $mform->get_data()) {
$data = file_postupdate_standard_filemanager($data, 'video', $fileoptions,
context_system::instance(), 'local_statistics', 'video', 0);
$fs = get_file_storage();
$files = $fs->get_area_files($context->id, 'local_statistics', 'video', '0', 'sortorder', false);
foreach ($files as $file) {
$fileurl = moodle_url::make_pluginfile_url($file->get_contextid(), $file->get_component(),
$file->get_filearea(), $file->get_itemid(), $file->get_filepath(),
$file->get_filename());
echo $fileurl;
}
}
?>
I've had a quick look through your code and it all looks reasonable, but you've not included the code of the local_statistics_pluginfile() function in local/statistics/lib.php - without that function, Moodle is unable to authenticate any requests from the browser to serve files, so all files will return a 'file not found' message.
Have a look at the documentation for details of what the x_pluginfile function should look like (or look for examples in any of the core plugins in Moodle): https://docs.moodle.org/dev/File_API#Serving_files_to_users

column missing in exchangearray

I'm missing a column in my exchangeArray. It is the column with the filename, here a snippet of my controller add action:
if ($form->isValid()) {
$data = $form->getData();
// Upload path
$location = "public/files/";
// A bit validation of uploaded file
$allowedExtension = array('xls', 'xlsx');
$extension = explode('.', $data['DCL_Path']['name']);
$extension = end($extension);
$import['DCL_Path']=$data['DCL_Path']['name'];
//$fileName = time() . '.' . $extension;
$fileName = $data['DCL_Path']['name'];
// Check if everything is OK!
//echo $fileName;
if (0 === $data['DCL_Path']['error'] && in_array($extension, $allowedExtension)) {
move_uploaded_file($data['DCL_Path']['tmp_name'], $location . $fileName);
} else {
echo 'Something went wrong!';
}
//$namen = explode(",", $import ); //Konvertierung des Strings in ein Array
//echo "<pre>"; var_dump($namen); echo "</pre>"; //Formartierte Ausgabe des Arrays
$this->table->saveImport($import);
Everything will be saved, but DCL_path is missing.
Here my exchangearray also:
public function exchangeArray(array $data)
{
$this->DCLID= !empty($data['DCLID']) ? $data['DCLID'] : null;
$this->UnitID= !empty($data['UnitID']) ? $data['UnitID'] : null;
$this->DCL_Path= !empty($data['DCL_Path']) ? $data['DCL_Path'] : null;
$this->Importdate= !empty($data['Importdate']) ? $data['Importdate'] : null;
$this->Importuser= !empty($data['Importuser']) ? $data['Importuser'] : null;
$this->Importok= !empty($data['Importok']) ? $data['Importok'] : null;
$this->DCL_Type= !empty($data['DCL_Type']) ? $data['DCL_Type'] : null;
$this->Changed_per_User= !empty($data['Changed_per_User']) ? $data['Changed_per_User'] : null;
$this->Description_Changes= !empty($data['Description_Changes']) ? $data['Description_Changes'] : null;
}
I added this statement: $import['DCL_Path']=$data['DCL_Path']['name']; to force it, but it didn't help. So my question would be how to add data in datafields of my exchangeArray.
EDIT1: Here is the start off my addAction.
$import = new Import(); //Neue Instanz von Import
$form->setInputFilter($import->getInputFilter()); //Filter an Form binden
$form->setData($request->getPost()); //Daten abholen
//echo $form->isValid();
if (! $form->isValid()) {
return ['form' => $form]; //Wenn die Daten nicht valide sind
// return $this->redirect()->toRoute('import'); //Routing
// Zend_Debug::dump("nicht valide");
//echo "nicht valide";
}
else{ //aus Tableadapter
$import->exchangeArray($form->getData());
// echo "valide";
//echo $import["DCL_Path"];
// Merge data thus
$data = array_merge_recursive(
$this->getRequest()->getPost()->toArray(),
$this->getRequest()->getFiles()->toArray()
);
$form->setData($data);
I also find another solution which is working, I post it additional perhaps it might help somebody else. Of course I still would prefer the way via exchangeArray.
$this->table->saveImport($import); //Daten speichern
$letzter = $this->table->getlastImport($fileName);
echo ($letzter->DCLID);
$this->table->updateoneRow($letzter->DCLID, 'DCL_Path', $fileName);

How I can move contact from one list to another using PHP API

I am using PHP SDK for constant contact plugin. I want to move contact from one list to another. I have tried following code it will generate BAD response error.
$action = "Updating Contact";
$contact = $response->results[0];
foreach ($contact->lists as $key => $value) {
unset($contact->lists[$key]);
}
$cc->contactService->updateContact(WPYog_ACCESS_TOKEN, $contact,true);
$contact->addList((string)$_POST['list_id']);
$contact->first_name = 'Sudhir';
$contact->status = 'ACTIVE';
$contact->email_addresses[0]->status = 'ACTIVE';
$contact->last_name = 'Pandey';
try {
$cc->contactService->updateContact(WPYog_ACCESS_TOKEN, $contact,true);
}catch (CtctException $ex) {
var_dump($ex->getErrors());
}
I have found answer. First of all fetch the record by using this
$action = "Updating Contact";
$contact = $response->results[0];
// Now empty the list
$contact->lists = array();
$contact->addList((string)$_POST['list_id']);
$contact->first_name = 'Sudhir';
$contact->status = 'ACTIVE';
$contact->email_addresses[0]->status = 'ACTIVE';
$contact->last_name = 'Pandey';
try {
$cc->contactService->updateContact(WPYog_ACCESS_TOKEN, $contact,true);
}catch (CtctException $ex) {
var_dump($ex->getErrors());
}

Zend for picture uploads needing to resize images

So, I am using Zend to handle my image uploads. This script works well, but I was wondering if there is a way to resize the image that is being uploaded no matter what the current size is. I've seen 2 similar posts, but their code was entirely different, thus would be difficult to translate into mine from theirs. If possible, I would really like to not have to use extensions, but I will if I have to. Any ideas?
if (isset($_POST['upload'])) {
require_once('scripter/lib.php');
//try {
$destination = 'C:\----';
$uploader = new Zend_File_Transfer_Adapter_Http();
$uploader->setDestination($destination);
$filename = $uploader->getFileName(NULL, FALSE);
$uploader->addValidator('Size', FALSE, '10000kB');
$uploader->addValidator('ImageSize', FALSE, array('minheight' => 100, 'minwidth' => 100));
//$pic = $filename;
if (!$uploader->isValid() || $errors) {
$messages = $uploader->getMessages();
} else {
//$pic = $filename;
$no_spaces = str_replace(' ', '_', $filename, $renamed);
$uploader->addValidator('Extension', FALSE, 'gif, png, jpg');
$recognized = FALSE;
if ($uploader->isValid()) {
$recognized = TRUE;
} else {
$mime = $uploader->getMimeType();
$acceptable = array('jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif');
$key = array_search($mime, $acceptable);
if (!$key) {
$messages[] = 'Unrecognized image type';
} else {
$no_spaces = "$no_spaces.$key";
$recognized = TRUE;
$renamed = TRUE;
}
}
$uploader->clearValidators();
if ($recognized) {
$existing = scandir($destination);
if (in_array($no_spaces, $existing)) {
$dot = strrpos($no_spaces, '.');
$base = substr($no_spaces, 0, $dot);
$extension = substr($no_spaces, $dot);
$i = 1;
do {
$no_spaces = $base . '_' . $i++ . $extension;
} while (in_array($no_spaces, $existing));
$renamed = TRUE;
}
$uploader->addFilter('Rename', array('target' => $no_spaces));
$success = $uploader->receive();
if (!$success) {
$messages = $uploader->getMessages();
} else {
//$pic = $no_spaces;
$uploaded = "$filename uploaded successfully";
$pic = $filename;
if ($renamed) {
$pic = "imgs/upld/" . $no_spaces;
$uploaded .= " and renamed $no_spaces";
//$pic = $no_spaces;
//$pic = $uploader->getFileName(NULL, FALSE);
} else {$pic = "imgs/upld/" . $filename;;}
$messages[] = "$uploaded";
//$pic = $no_spaces;
}
Zend Framework does not ship with a component for handling images.
Good News! PHP has several components that are really good at dealing with all kinds of image issues.
GD (one of those great PHP extensions) is currently shipped as a core extension for PHP, perhaps you will find it useful.
Maybe this will help: http://phpcodeforbeginner.blogspot.com/2013/04/resize-image-or-crop-image-using-gd.html
(not really trying to be too snarky ;)