4 * Description: JavaScript photo/image uploader. Uses Valum 'qq' Uploader.
6 * Author: Chris Case <http://friendika.openmindspace.org/profile/chris_case>
11 * JavaScript Photo/Image Uploader
13 * Uses Valum 'qq' Uploader.
14 * Module Author: Chris Case
17 use Friendica\Core\Config;
18 use Friendica\Core\Hook;
19 use Friendica\Core\L10n;
20 use Friendica\Core\Logger;
22 function js_upload_install() {
23 Hook::register('photo_upload_form', 'addon/js_upload/js_upload.php', 'js_upload_form');
24 Hook::register('photo_post_init', 'addon/js_upload/js_upload.php', 'js_upload_post_init');
25 Hook::register('photo_post_file', 'addon/js_upload/js_upload.php', 'js_upload_post_file');
26 Hook::register('photo_post_end', 'addon/js_upload/js_upload.php', 'js_upload_post_end');
30 function js_upload_uninstall() {
31 Hook::unregister('photo_upload_form', 'addon/js_upload/js_upload.php', 'js_upload_form');
32 Hook::unregister('photo_post_init', 'addon/js_upload/js_upload.php', 'js_upload_post_init');
33 Hook::unregister('photo_post_file', 'addon/js_upload/js_upload.php', 'js_upload_post_file');
34 Hook::unregister('photo_post_end', 'addon/js_upload/js_upload.php', 'js_upload_post_end');
38 function js_upload_form(&$a,&$b) {
40 $b['default_upload'] = false;
42 $b['addon_text'] .= '<link href="' . $a->getBaseURL() . '/addon/js_upload/file-uploader/client/fileuploader.css" rel="stylesheet" type="text/css">';
43 $b['addon_text'] .= '<script src="' . $a->getBaseURL() . '/addon/js_upload/file-uploader/client/fileuploader.js" type="text/javascript"></script>';
45 $upload_msg = L10n::t('Select files for upload');
46 $drop_msg = L10n::t('Drop files here to upload');
47 $cancel = L10n::t('Cancel');
48 $failed = L10n::t('Failed');
50 $maximagesize = intval(Config::get('system','maximagesize'));
52 $b['addon_text'] .= <<< EOT
54 <div id="file-uploader-demo1">
56 <p>Please enable JavaScript to use file uploader.</p>
57 <!-- or put a simple form for upload here -->
61 <script type="text/javascript">
63 function getSelected(opt) {
64 var selected = new Array();
66 for (var intLoop = 0; intLoop < opt.length; intLoop++) {
67 if ((opt[intLoop].selected) ||
68 (opt[intLoop].checked)) {
69 index = selected.length;
70 //selected[index] = new Object;
71 selected[index] = opt[intLoop].value;
72 //selected[index] = intLoop;
77 function createUploader() {
78 uploader = new qq.FileUploader({
79 element: document.getElementById('file-uploader-demo1'),
80 action: '{$b['post_url']}',
82 template: '<div class="qq-uploader">' +
83 '<div class="qq-upload-drop-area"><span>$drop_msg</span></div>' +
84 '<div class="qq-upload-button">$upload_msg</div>' +
85 '<ul class="qq-upload-list"></ul>' +
88 // template for one item in file list
89 fileTemplate: '<li>' +
90 '<span class="qq-upload-file"></span>' +
91 '<span class="qq-upload-spinner"></span>' +
92 '<span class="qq-upload-size"></span>' +
93 '<a class="qq-upload-cancel" href="#">$cancel</a>' +
94 '<span class="qq-upload-failed-text">$failed</span>' +
98 sizeLimit: $maximagesize,
99 onSubmit: function(id,filename) {
100 var newalbumElm = document.getElementById('photos-upload-newalbum');
101 var albumElm = document.getElementById('photos-upload-album-select');
103 var newalbum = newalbumElm ? newalbumElm.value : "";
104 var album = albumElm ? albumElm.value : "";
106 if (typeof acl != "undefined"){
107 uploader.setParams( {
110 not_visible : document.getElementById('photos-upload-noshare').checked,
111 group_allow : acl.allow_gid.join(','),
112 contact_allow : acl.allow_cid.join(','),
113 group_deny : acl.deny_gid.join(','),
114 contact_deny : acl.deny_cid.join(',')
117 uploader.setParams( {
120 not_visible : document.getElementById('photos-upload-noshare').checked,
121 group_allow : getSelected(document.getElementById('group_allow')).join(','),
122 contact_allow : getSelected(document.getElementById('contact_allow')).join(','),
123 group_deny : getSelected(document.getElementById('group_deny')).join(','),
124 contact_deny : getSelected(document.getElementById('contact_deny')).join(',')
132 // in your app create uploader as soon as the DOM is ready
133 // don't wait for the window to load
134 window.onload = createUploader;
144 function js_upload_post_init(&$a,&$b) {
146 // list of valid extensions, ex. array("jpeg", "xml", "bmp")
148 $allowedExtensions = ["jpeg","gif","png","jpg"];
150 // max file size in bytes
152 $sizeLimit = Config::get('system','maximagesize'); //6 * 1024 * 1024;
154 $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
156 $result = $uploader->handleUpload();
159 // to pass data through iframe you will need to encode all html tags
160 $a->data['upload_jsonresponse'] = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
162 if(isset($result['error'])) {
163 Logger::log('mod/photos.php: photos_post(): error uploading photo: ' . $result['error'] , Logger::DEBUG);
164 echo json_encode($result);
168 $a->data['upload_result'] = $result;
172 function js_upload_post_file(&$a,&$b) {
174 $result = $a->data['upload_result'];
176 $b['src'] = $result['path'];
177 $b['filename'] = $result['filename'];
178 $b['filesize'] = filesize($b['src']);
183 function js_upload_post_end(&$a,&$b) {
185 Logger::log('upload_post_end');
186 if(!empty($a->data['upload_jsonresponse'])) {
187 echo $a->data['upload_jsonresponse'];
195 * Handle file uploads via XMLHttpRequest
197 class qqUploadedFileXhr {
199 private $pathnm = '';
202 * Save the file in the temp dir.
203 * @return boolean TRUE on success
206 $input = fopen("php://input", "r");
208 $upload_dir = Config::get('system','tempdir');
210 $upload_dir = sys_get_temp_dir();
212 $this->pathnm = tempnam($upload_dir,'frn');
214 $temp = fopen($this->pathnm,"w");
215 $realSize = stream_copy_to_stream($input, $temp);
220 if ($realSize != $this->getSize()){
227 return $this->pathnm;
231 return $_GET['qqfile'];
235 if (isset($_SERVER["CONTENT_LENGTH"])){
236 return (int)$_SERVER["CONTENT_LENGTH"];
238 throw new Exception('Getting content length is not supported.');
244 * Handle file uploads via regular form post (uses the $_FILES array)
247 class qqUploadedFileForm {
251 * Save the file to the specified path
252 * @return boolean TRUE on success
261 return $_FILES['qqfile']['tmp_name'];
265 return $_FILES['qqfile']['name'];
268 return $_FILES['qqfile']['size'];
272 class qqFileUploader {
273 private $allowedExtensions = [];
274 private $sizeLimit = 10485760;
277 function __construct(array $allowedExtensions = [], $sizeLimit = 10485760){
278 $allowedExtensions = array_map("strtolower", $allowedExtensions);
280 $this->allowedExtensions = $allowedExtensions;
281 $this->sizeLimit = $sizeLimit;
283 if (isset($_GET['qqfile'])) {
284 $this->file = new qqUploadedFileXhr();
285 } elseif (isset($_FILES['qqfile'])) {
286 $this->file = new qqUploadedFileForm();
294 private function toBytes($str){
296 $last = strtolower($str[strlen($str)-1]);
298 case 'g': $val *= 1024;
299 case 'm': $val *= 1024;
300 case 'k': $val *= 1024;
306 * Returns array('success'=>true) or array('error'=>'error message')
308 function handleUpload(){
311 return ['error' => L10n::t('No files were uploaded.')];
314 $size = $this->file->getSize();
317 return ['error' => L10n::t('Uploaded file is empty')];
320 // if ($size > $this->sizeLimit) {
322 // return array('error' => L10n::t('Uploaded file is too large'));
326 $maximagesize = Config::get('system','maximagesize');
328 if(($maximagesize) && ($size > $maximagesize)) {
329 return ['error' => L10n::t('Image exceeds size limit of ') . $maximagesize ];
333 $pathinfo = pathinfo($this->file->getName());
334 $filename = $pathinfo['filename'];
336 $ext = $pathinfo['extension'];
338 if($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)){
339 $these = implode(', ', $this->allowedExtensions);
340 return ['error' => L10n::t('File has an invalid extension, it should be one of ') . $these . '.'];
343 if ($this->file->save()){
346 'path' => $this->file->getPath(),
347 'filename' => $filename . '.' . $ext
351 'error'=> L10n::t('Upload was cancelled, or server error encountered'),
352 'path' => $this->file->getPath(),
353 'filename' => $filename . '.' . $ext