blueimp jquery upload SyntaxError: Unexpected token < - cakephp

I'm using blueimp to upload images in cakephp 2.x. Images are upload but issue is after uploading images.I got error "SyntaxError: Unexpected token <" and json data in html format. I tried to figured it out myself and find a solution given on SO. I tried to resolve my issue by following answer given in solution but could not. (sorry for bad English)
my controller code
App::import('Vendor', 'UploadHandler', array('file' => 'file.upload/UploadHandler.php'));
$this->layout = 'upload';
$options = array(
// 'upload_dir' => WWW_ROOT . DS . 'img',
'accept_file_types' => '/\.(gif|jpe?g|png)$/i',
);
$upload_handler = new UploadHandler($options);
}
I changed url In main.js(blueimp js file)
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: 'index'
});
json data displayed on index page.
{"files":[{"name":"1186225_383357368459160_1371777554_n.jpg","size":58938,"url":"http:\/\/localhost\/ec\/cakephp\/app\/webroot\/files\/1186225_383357368459160_1371777554_n.jpg","thumbnailUrl":"http:\/\/localhost\/ec\/cakephp\/app\/webroot\/files\/thumbnail\/1186225_383357368459160_1371777554_n.jpg","deleteUrl":"http:\/\/localhost\/ec\/cakephp\/app\/webroot\/?file=1186225_383357368459160_1371777554_n.jpg","deleteType":"DELETE"},{"name":"e0775308650b201469fc68765dc4ff7a.jpg","size":150919,"url":"http:\/\/localhost\/ec\/cakephp\/app\/webroot\/files\/e0775308650b201469fc68765dc4ff7a.jpg","thumbnailUrl":"http:\/\/localhost\/ec\/cakephp\/app\/webroot\/files\/thumbnail\/e0775308650b201469fc68765dc4ff7a.jpg","deleteUrl":"http:\/\/localhost\/ec\/cakephp\/app\/webroot\/?file=e0775308650b201469fc68765dc4ff7a.jpg","deleteType":"DELETE"}]}

i had the same problem.
it was the validate variable
wrong
public $validate;
correct
public $validate = array();

Related

Laravel Http::fake response with file

I am trying to mock/test an Http request in a feature test to mock the whatsapp APIs, using Http::fake() in the setUp as follow:
Http::fake([
'https://www.test-whatsapp.com/upload/image' => Http::response(UploadedFile::fake()->image('TestWhatsapp.jpg')->get()),
'https://www.test-whatsapp.com/*' => Http::response(),
]);
I'd like to mock that when my app calls https://www.test-whatsapp.com/upload/image i get the file content but it seems that it never get sent. This is my actual test:
public function test_ask_attachment_image()
{
$this->receivedMessage(['type' => 'TEXT', 'text' => 'ask-attachment']);
$this->receivedMessage(['type' => 'IMAGE', 'caption' => 'some text', 'url' => '"https://www.test-whatsapp.com/upload/image']);
Http::assertSent(function (Request $request){
Log::debug($request->url(), [$request->body()]);
return true;
});
}
But the log gives an empty body.
I tried to print_r the whole response but still no sign of the file.
In the end I tried with an existing file using file_get_content but i got the same result.
I have logged the faked file and it get the content right.
How can i fake an endpoint to return me a file content? Thank you for any suggestions!
Edit
After debugging more i found out that the problem is not when i'm trying to create an image but a generic file using the method UploadedFile::fake()->create('TestWhatsapp.mp4', 1000). I get the size and the mimetype right but the file is still empty.

CSRF issues when integrating TinyMCE image upload with CakePHP 3.8

I'm using CakePHP 3.8 to create a CMS for a website. I need a simple WYSIWYG editor with image upload. I'd previously used CKEditor, but was having problems getting the image upload working, so thought I'd try TinyMCE instead.
So, I downloaded TinyMCE 5 (with all standard plugins), linked it in in the head section of my page, and created a form with a TinyMCE textarea like this:
<fieldset>
<legend>New Page</legend>
<?php
echo $this->Flash->render();
echo $this->Form->create($newpage);
echo $this->Form->control('title');
echo $this->Form->control('content',
array('label' => 'Page Content',
'type' => 'textarea',
'id' => 'editor_area'));
echo $this->Form->button('Save');
echo $this->Form->end();
?>
</fieldset>
<script>
tinymce.init({
selector:'#editor_area',
height: 500,
menubar: false,
images_upload_url: '<?php echo IMG_UPLOAD_URL ?>',
toolbar: [
'undo redo | cut copy paste | styleselect | bold italic underline removeformat | alignleft aligncenter alignright | charmap | bullist numlist | link image'
],
plugins: ['advlist lists link autolink image charmap imagetools code']
});
</script>
This works fine, text area appears with the editor etc. The upload url in images_upload_url points to the following UploadsController.php (I've left out the details for brevity; can add them in if needed):
<?php
namespace App\Controller\Admin;
use App\Controller\AppController;
class UploadsController extends AppController
{
public function uploadImage() {
$result = array();
$result['success'] = 'success';
// Process file upload
return $this->response->withType('application/json')
->withStringBody(json_encode($result));
}
}
When I upload an image, I get the following error in the console:
Failed to load resource: the server responded with a status of 403 (Forbidden)
The output from CakePHP shows the error:
Error: CSRF token mismatch.
The debugger shows that the POST includes the following:
Cookie: CAKEPHP=dvsktjv7vp8la5nv7dv19634d1; csrfToken=53e5718e13a1e963d51f9c93c48471a478b35c02b565d6f0699cd2a335775c2b17986cfc2cc587ff7343a6573e3eb2e498a9cb962397599c023417d1dfa9506c; ckCsrfToken=7l2PEC0g06819qQcLwdX5ul7E7jNRa3r61jENt2x
I'm not sure where to go from here.
(Or if there's a more straightforward way to include a free/inexpensive WYSIWYG editor with a decent image/file uploader, I'm open to suggestions! It's a website for a school, so budget is very small and can't be a monthly cost.)
The cookie data is only one part of the CSRF protection mechanism, the client needs to send the CSRF token in either the request data or the X-CSRF-Token header too.
I'm not overly familiar with TinyMCE image uploads, but looking at the docs, you'll probably need a custom upload handler, where you can add additional data, the CSRF token that is.
Taking the example from the TinyMCE docs, the handler could look something like this, where the CSRF token is appended to the form data:
images_upload_handler: function (blobInfo, success, failure) {
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', <?= json_encode(IMG_UPLOAD_URL) ?>);
xhr.onload = function() {
var json;
if (xhr.status != 200) {
failure('HTTP Error: ' + xhr.status);
return;
}
json = JSON.parse(xhr.responseText);
if (!json || typeof json.location != 'string') {
failure('Invalid JSON: ' + xhr.responseText);
return;
}
success(json.location);
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
// append CSRF token in the form data
formData.append('_csrfToken', <?= json_encode($this->request->getParam('_csrfToken')) ?>);
xhr.send(formData);
}
Also according to the docs the response JSON must contain a property named location that contains the web path to the uploaded file, that might be in the code that you've left out, mentioning it just in case.
See also
TinyMCE Docs > Introduction & getting started > Uploading images and files
TinyMCE Docs > Configuration reference > Image & file upload options > images_upload_handler
Cookbook > Security > Cross Site Request Forgery (CSRF) Middleware

How to use Auth component of Cakephp 3 in Event

I'm using CakePHP 3.2 and proffer plugin for image uploading.
I want to rewrite the default path of proffer plugin to upload image and change image name before save.
As per the documentation of proffer from github. I have created an event in /src/Event
Now I want to rename the file like
$this->Auth->user('id').'-'.$row('id').date('dmyhis').ext
this is what I have done
$newFilename = $this->Auth->user('id').'-'.$event->subject()->get('id') . '_' . Inflector::slug($event->subject()->get('name')) . date('ymdhis') . $ext;
But this is giving error that Auth can not be used here. Is there any way to use Auth Component outside controller ?
You can access the logged in user id by loading the session.
use Cake\Network\Session;
$session = new Session();
$userData = $session->read('Auth.User.id');
Use this as a reference: Reading & Writing Session Data
With cake 3.x and after, you should using this:
$this->request->session()->read('Auth');
When debug it
debug( $this->request->session()->read('Auth') );
[
'id' => (int) 2,
'username' => 'admin',
'nice_name' => 'Tommy Do',
'first_name' => 'Huy',
'last_name' => 'Đỗ',
...//and more info in UserTable
]
And access to each element.
$this->request->session()->read('Auth.nice_name');
Print:
Tommy Do
Hope it will help you :D

title_for_layout while viewing pdf with cakeResponse

i'm viewing pdf files from database using this function:
public function pdfPreview($taskId){
$file = $this->StoredFile->find('first', array(
'conditions' => array(
'StoredFile.id' => $taskId
),
'contain' => false
));
$this->response->body($file['StoredFile']['data']);
$this->response->type('pdf');
//$this->response->header('Content-Disposition', 'inline');
//Return response object to prevent controller from trying to render a view
return $this->response;
}
Is there any way to set title for layout with CakeResponse while not rendering layout, because i'm trying to set filename as title, but i didn't found solution?
Usually the $title_for_layout view var is passed to the html and put between <title> tags.
However, as I understand, you are outputting a PDF using raw data from de database. This is then interpreted by the browser to render a PDF view. The browser thinks it is displaying a file, so when you set the filename in the Content-Disposition header it will display this in its title. Like they do on https://stackoverflow.com/a/2016016/1535656

CakePHP and jQuery Autocomplete

I am working with CakePHP. What I need in my application is autosuggestion. I used following code to achieve my goal:
jQuery("#name").autocomplete( '<?php echo HTTP_PATH.'songs/sss'; ?>', {
multiple: true,
mustMatch: true,
matchContains: true,
autoFill: false,
});
Sending my request to the SongsController' sss function... My controller function is:
public function sss(){
$this->layout = '';
$condition = '';
$condition = array('Poet.status'=>'3');
$poet_name = $this->Poet->find('list', array('conditions' => $condition));
return $poet_name;
}
First issue is that I am returning my result in array. How would I separate my result again in a suggestion list.
Second thing is that when I tried to check the response using the Firebug panel, I noticed that CakePHP is expecting a view at this point. I don't want any sort of view as I am not updating anything...
You'll want to check out serializing you data as JSON: http://book.cakephp.org/2.0/en/views/json-and-xml-views.html#using-data-views-with-the-serialize-key. By setting a _serialize variable in the view you are telling Cake what data is important when it gets a request for a data view.
You will also need to add Router::parseExtensions('json'); and a .json to the end of your URI in the jQuery call so that Cake knows to respond with a JSON data view and use the data in the _serialize key you set like I mentioned above. There more info on file extensions here: http://book.cakephp.org/2.0/en/development/routing.html#file-extensions
Here's how I would write the method:
public function sss(){
$this->layout = '';
$condition = array('Poet.status'=>'3');
$poets = $this->Poet->find('list', array('conditions' => $condition));
$this->set(compact('poets'));
$this->set('_serialize', $poets);
}

Resources