Uploadify stuck at 100% but still does the upload - zend-framework

I seem to have a problem with uploadify. It always get stuck at 100% on the first file, no matter what the file is. I am using Zend on my Wamp and it works fine there but as soon as I upload it on my linux server it gets stuck. The file is uploaded and renamed but it never fires the onComplete event and stays at 100% on the first file.
Here is my javascript:
$('#fileInput').uploadify({
'uploader' : 'http://test.thevenuelist.co.uk/js/uploadify/uploadify.swf',
'script' : 'http://test.thevenuelist.co.uk/ajax/uploadify',
'cancelImg' : 'http://test.thevenuelist.co.uk/js/uploadify/cancel.png',
'folder' : '/userdata/images/',
'auto' : true,
'multi' : true,
'fileDesc' : 'Image Files (*.jpg;*.jpeg;*.gif;*.png)',
'fileExt' : '*.jpg;*.jpeg;*.gif;*.png',
'buttonText' : 'Upload Images',
'removeCompleted' : true,
'onComplete' : function (event, queueID, fileObj, response, data) {
var answer = eval('(' + response + ')');
if(answer.result == "success")
{
$("#hdnImages").val($("#hdnImages").val() + answer.fileName + ",");
var toAdd = "<li><img src='/images/delete.png' id='removeItem' rel='"+answer.fileName+"' style='cursor:pointer;' title='Remove' alt='Remove'/> Image "+answer.realName+" uploaded</li>";
$("#completedItemsList").append(toAdd);
}
},
'onError': function (event, queueID ,fileObj, errorObj) {
alert(errorObj.info);
}
});
And here is my Zend code behind:
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT']. '/' . $_REQUEST['folder'] . '/';
$fileNameArray = explode('.',$_FILES['Filedata']['name']);
$hash = substr(md5(microtime()),0,5);
$finalFileName = $fileNameArray[0].$hash.'.'.$fileNameArray[1];
$targetFile = str_replace('//','/',$targetPath) . $finalFileName;
if(move_uploaded_file($tempFile,$targetFile))
{
$data = array("result"=>"success","fileName"=>$finalFileName,"realName"=>$_FILES['Filedata']['name']);
}
else
{
$data = array("result"=>"failed");
}
echo Zend_Json::encode($data);
Any help would be greatly appreciated. I have spent way too much time trying to figure it out. I need my onComplete event to work so I can finish my forms.

I found with uploadify I had to return either a 1 or a 0 for success or failure to get it to work.

Related

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

How to prevent SQL injection in PhalconPHP when using sql in model?

Let's say I am building a search that finds all the teacher and got an input where the user can put in the search term. I tried reading the phalcon documentation but I only see things like binding parameters. I read the other thread about needing prepare statements do I need that in Phalcon as well?
And my function in the model would be something like this:
public function findTeachers($q, $userId, $isUser, $page, $limit, $sort)
{
$sql = 'SELECT id FROM tags WHERE name LIKE "%' . $q . '%"';
$result = new Resultset(null, $this,
$this->getReadConnection()->query($sql, array()));
$tagResult = $result->toArray();
$tagList = array();
foreach ($tagResult as $key => $value) {
$tagList[] = $value['id'];
....
}
}
My question is for the Phalcon framework is there any settings or formats I should code for this line $sql = 'SELECT id FROM tags WHERE name LIKE "%' . $q . '%"';
And also any general recommendation for preventing SQL Injection in PhalconPHP controllers and index would be appreciated.
For reference:
My controller:
public function searchAction()
{
$this->view->disable();
$q = $this->request->get("q");
$sort = $this->request->get("sort");
$searchUserModel = new SearchUsers();
$loginUser = $this->component->user->getSessionUser();
if (!$loginUser) {
$loginUser = new stdClass;
$loginUser->id = '';
}
$page = $this->request->get("page");
$limit = 2;
if (!$page){
$page = 1;
}
$list = $searchUserModel->findTeachers($q, $loginUser->id, ($loginUser->id)?true:false, $page, $limit, $sort);
if ($list){
$list['status'] = true;
}
echo json_encode($list);
}
My Ajax:
function(cb){
$.ajax({
url: '/search/search?q=' + mapObject.q + '&sort=<?php echo $sort;?>' + '&page=' + mapObject.page,
data:{},
success: function(res) {
//console.log(res);
var result = JSON.parse(res);
if (!result.status){
return cb(null, result.list);
}else{
return cb(null, []);
}
},
error: function(xhr, ajaxOptions, thrownError) {
cb(null, []);
}
});
with q being the user's search term.
You should bind the query parameter to avoid an SQL injection. From what I can remember Phalcon can be a bit funny with putting the '%' wildcard in the conditions value so I put them in the bind.
This would be better than just filtering the query.
$tags = Tags::find([
'conditions' => 'name LIKE :name:',
'bind' => [
'name' => "%" . $q . "%"
]
])
Phalcon\Filter is helpful when interacting with the database.
In your controller you can say, remove everything except letters and numbers from $q.
$q = $this->request->get("q");
$q = $this->filter->sanitize($q, 'alphanum');
The shortest way for requests:
$q = $this->request->get('q', 'alphanum');

How to finish batch and redirect then

I'm working on a Drupal 7 project. I'm using a batch, implenting some operations, and showing a progress bar. in my "formulaire_finished", wich is executed at the end, as last operation of the batch, I want to download a file, and then redirect to another page, because the process is over.
However, The readfile() function use a drupal_exit(), and so my redirection isn't done.
Here is my code:
function formulaire_finished($success, $results, $operations) {
if ($success) {
$path = $results['infos']['path'];
download_file($path);
// Redirection
drupal_goto($_SESSION['my_page'], array('query' => array('details' => '1')));
} else {
// An error occurred.
// $operations contains the operations that remained unprocessed.
$error_operation = reset($operations);
drupal_set_message(t('An error occurred while processing #operation with arguments : #args', array('#operation' => $error_operation[0], '#args' => print_r($error_operation[0], TRUE), )));
}
}
download function:
function download_file($path) {
$dir = $path;
$filename = basename($dir);
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
drupal_add_http_header('Pragma', 'public');
drupal_add_http_header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
} else {
drupal_add_http_header('Pragma', 'no-cache');
}
drupal_add_http_header('Expires', '0');
drupal_add_http_header('Content-Type', 'application/vnd.ms-excel');
drupal_add_http_header('Content-Disposition', 'attachment; filename=' . basename($dir) . ';');
drupal_add_http_header('Content-Transfer-Encoding', 'binary');
drupal_add_http_header('Content-Length', filesize($dir));
readfile($dir);
unlink($dir);
drupal_exit();
}
All ideas are welcome.
In the below function , can you try to return true always from the below function.
function download_file($path) {
$dir = $path;
$filename = basename($dir);
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
drupal_add_http_header('Pragma', 'public');
drupal_add_http_header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
} else {
drupal_add_http_header('Pragma', 'no-cache');
}
drupal_add_http_header('Expires', '0');
drupal_add_http_header('Content-Type', 'application/vnd.ms-excel');
drupal_add_http_header('Content-Disposition', 'attachment; filename=' . basename($dir) . ';');
drupal_add_http_header('Content-Transfer-Encoding', 'binary');
drupal_add_http_header('Content-Length', filesize($dir));
readfile($dir);
unlink($dir);
//drupal_exit();
// Can you use simple return here
return true;
}
I don't think you should output the file for download during the finish callback of a batch operation. You should save the file to drupal's file system and save a reference to the file. You can then download it after the batch finishes.

Moodle development error in new plugin module with file manager

Please if you can help me in my problem, I'm developing a new module in Moodle (v. 2.4) (mod_problem), as part of my master thesis.
In the mod_form I included a file manager element as follows:
//** file
//-------------------------------------------------------
$mform->addElement('header', 'content', get_string('problemfile', 'problem'));
$mform->addElement('filemanager', 'problemfile', get_string('files'), null, array('subdirs'=>1, 'accepted_types'=>'*'));
//-------------------------------------------------------
In the preprocessing method I added this:
function data_preprocessing(&$default_values) {
if ($this->current->instance) {
// editing existing instance - copy existing files into draft area
$draftitemid = file_get_submitted_draft_itemid('problemfile');
file_prepare_draft_area($draftitemid, $this->context->id, 'mod_problem', 'content', 0, array('subdirs'=>1, 'accepted_types'=>'*'));
$default_values['problemfile'] = $draftitemid;
}
}
Then in the lib.php file of my module I added the following:
$draftitemid = $problem->problemfile;
$problem->id = $DB->insert_record('problem', $problem);
$cmid = $problem->coursemodule;
$context = context_module::instance($cmid);
if (!empty($problem->problemfile)) {
$draftitemid = $problem->problemfile;
file_save_draft_area_files($draftitemid, $context->id, 'mod_problem', 'content', 0, array('subdirs'=>1, 'accepted_types'=>'*'));
}
I also created the (mod_problem_pluginfile()) function that include:
$fs = get_file_storage();
$filename = array_pop($args);
$filepath = $args ? '/'.implode('/', $args).'/' : '/';
if (!$file = $fs->get_file($context->id, 'mod_problem', 'content', 0, $filepath, $filename) or $file->is_directory()) {
send_file_not_found();
}
send_stored_file($file, 0, 0, true, array('preview' => $preview));
Then when I want to print the file list for students in view.php:
require_once($CFG->libdir.'/filelib.php');
require_once($CFG->dirroot.'/repository/lib.php');
$fs = get_file_storage();
$files = $fs->get_area_files($context->id, 'mod_problem', 'content', 0);
//try 2
foreach ($files as $file) {
$filename = $file->get_filename();
$url = moodle_url::make_pluginfile_url($file->get_contextid(), $file->get_component(),
$file->get_filearea(),$file->get_itemid(), $file->get_filepath(), $filename, false);
$out[] = html_writer::link($url, $filename);
}
$br = html_writer::empty_tag('br');
echo implode($br, $out);
when I view the module I got the list of files with the links but when I click in the link it gives me this error: Sorry, the requested file could not be found. It stop in the mod_problem_pluginfile() function when I read the files it is not found
This is the error I got:
//---------------------------------
Debug info:
Error code: filenotfound
Stack trace:
line 476 of \lib\setuplib.php: moodle_exception thrown
line 1977 of \lib\filelib.php: call to print_error()
line 412 of \mod\problem\lib.php: call to send_file_not_found()
line 4314 of \lib\filelib.php: call to mod_problem_pluginfile()
line 38 of \pluginfile.php: call to file_pluginfile()
//------------------------------------------
I'm not sure why it's not reading the files, even though they are stored.
Please any help with this is very appreciated as I'm running out of time in fixing such problem.
Seems you didn't post the full mod_problem_pluginfile() function.
if (!$file = $fs->get_file($context->id, 'mod_problem', 'content', 0, $filepath, $filename) or $file->is_directory()) {
send_file_not_found();
}
It could be your $context->id, make sure it's the same you as you called file_save_draft_area_files()

Image capture/upload with Phonegap (cordova) for iPhone not working

I have been trying to set up an app through PhoneGap (Cordova) to take images and upload them to our server. I have gone through so many of the responses on here and tried the code in them. I can get the camera up and taking a photo, I can access the phone gallery even. But I can not get it to send the image to the server. I've tried sending the image, and even sending the base64 image stream. I can't get it to the server.
Here is the javascript on the client side:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
}
function ImageUpload() {
this.useExistingPhoto = function(e) {
this.capture(Camera.PictureSourceType.SAVEDPHOTOALBUM);
}
this.takePhoto = function(e) {
this.capture(Camera.PictureSourceType.CAMERA);
}
this.capture = function(sourceType) {
navigator.camera.getPicture(this.onCaptureSuccess, this.onCaptureFaile, {
destinationType: Camera.DestinationType.FILE_URI,
soureType: sourceType,
correctOrientation: true
});
}
this.onCaptureSuccess = function(imageURI) {
var fail, ft, options, params, win;
success = function(response) {
alert("Your photo has been uploaded!");
};
fail = function(error) {
alert("An error has occurred: Code = " + error.code + "\nMessage = "+error.message);
};
options = new FailUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "text/plain";
params = {
val1: "some value",
val2: "some other value"
};
options.params = params;
ft= new FileTransfer();
ft.upload(imageURI, 'http://style.appdev01.com/app/client-profile.php', success, faile, options);
}
this.OnCaptureFail = function(message) {
alert("Failed because: "+message);
}
};
var imageuploader = new ImageUpload();
Two buttons call imageuploader.takePhoto and .useExistingPhoto on click.
On the server side I have this php:
if(isset($_FILES['file'])) {
$target_path = "/home/style/public_html/images/client_images/app_image.jpg";
move_uploaded_file($_FILES['file']['tmp_name'], $target_path);
$insert = "INSERT INTO
`fut`
SET
`request` = '".serialize($_POST)."',
`file` = '".serialize($_FILES)."'";
$mysql->query($insert);
}
This is just to store the POST and FILE arrays to the db to make sure they came through and create the image.
But again, nothing is getting to the server. Any help would be GREATLY appreciated. I've tried so many versions of this code from so many questions here and all over the web.
define ('SITE_ROOT', realpath(dirname(__FILE__))); /* echo SITE_ROOT; to dir
move_uploaded_file($_FILES["file"]["tmp_name"],SITE_ROOT."/uploads/".$_FILES["file"]["name"]); // will move file, make sure uplaods has write permission!
That works for me on Android Simulator, not on Tablet, but let me know if you have it working, busy on the same thing.
$myarray = array( $_REQUEST);
foreach ($myarray as $key => $value) {
echo "<p>".$key."</p>";
echo "<p>".$value."</p>";
echo "<hr />";
}
That you can use to check POST / GET!
Try this is my code. It has worked for me.
Encode your URL by encodeURI method
fileKey with "file" as in your server side script $_FILES['file']
uploadFile: function(refNo){
var uri = fileUpload.fileUri;
var file = uri.substr(uri.lastIndexOf('/') + 1);
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = file;
options.mimeType="image/jpeg";
alert("name === "+uri);
options.chunkedMode = false;
var ft = new FileTransfer();
Common.ajaxLoading('show');
ft.upload(uri,encodeURI("http://172.16.1.147:80/upload/home.php") , fileUpload.uploadSuccess, fileUpload.uploadFail, options, true);
},