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\Addon;
18 use Friendica\Core\Config;
19 use Friendica\Core\L10n;
21 function js_upload_install() {
22 Addon::registerHook('photo_upload_form', 'addon/js_upload/js_upload.php', 'js_upload_form');
23 Addon::registerHook('photo_post_init', 'addon/js_upload/js_upload.php', 'js_upload_post_init');
24 Addon::registerHook('photo_post_file', 'addon/js_upload/js_upload.php', 'js_upload_post_file');
25 Addon::registerHook('photo_post_end', 'addon/js_upload/js_upload.php', 'js_upload_post_end');
29 function js_upload_uninstall() {
30 Addon::unregisterHook('photo_upload_form', 'addon/js_upload/js_upload.php', 'js_upload_form');
31 Addon::unregisterHook('photo_post_init', 'addon/js_upload/js_upload.php', 'js_upload_post_init');
32 Addon::unregisterHook('photo_post_file', 'addon/js_upload/js_upload.php', 'js_upload_post_file');
33 Addon::unregisterHook('photo_post_end', 'addon/js_upload/js_upload.php', 'js_upload_post_end');
37 function js_upload_form(&$a,&$b) {
39 $b['default_upload'] = false;
41 $b['addon_text'] .= '<link href="' . $a->get_baseurl() . '/addon/js_upload/file-uploader/client/fileuploader.css" rel="stylesheet" type="text/css">';
42 $b['addon_text'] .= '<script src="' . $a->get_baseurl() . '/addon/js_upload/file-uploader/client/fileuploader.js" type="text/javascript"></script>';
44 $upload_msg = L10n::t('Upload a file');
45 $drop_msg = L10n::t('Drop files here to upload');
46 $cancel = L10n::t('Cancel');
47 $failed = L10n::t('Failed');
49 $maximagesize = intval(get_config('system','maximagesize'));
51 $b['addon_text'] .= <<< EOT
53 <div id="file-uploader-demo1">
55 <p>Please enable JavaScript to use file uploader.</p>
56 <!-- or put a simple form for upload here -->
60 <script type="text/javascript">
62 function getSelected(opt) {
63 var selected = new Array();
65 for (var intLoop = 0; intLoop < opt.length; intLoop++) {
66 if ((opt[intLoop].selected) ||
67 (opt[intLoop].checked)) {
68 index = selected.length;
69 //selected[index] = new Object;
70 selected[index] = opt[intLoop].value;
71 //selected[index] = intLoop;
76 function createUploader() {
77 uploader = new qq.FileUploader({
78 element: document.getElementById('file-uploader-demo1'),
79 action: '{$b['post_url']}',
81 template: '<div class="qq-uploader">' +
82 '<div class="qq-upload-drop-area"><span>$drop_msg</span></div>' +
83 '<div class="qq-upload-button">$upload_msg</div>' +
84 '<ul class="qq-upload-list"></ul>' +
87 // template for one item in file list
88 fileTemplate: '<li>' +
89 '<span class="qq-upload-file"></span>' +
90 '<span class="qq-upload-spinner"></span>' +
91 '<span class="qq-upload-size"></span>' +
92 '<a class="qq-upload-cancel" href="#">$cancel</a>' +
93 '<span class="qq-upload-failed-text">$failed</span>' +
97 sizeLimit: $maximagesize,
98 onSubmit: function(id,filename) {
99 if (typeof acl!="undefined"){
100 uploader.setParams( {
101 newalbum : document.getElementById('photos-upload-newalbum').value,
102 album : document.getElementById('photos-upload-album-select').value,
103 not_visible : document.getElementById('photos-upload-noshare').checked,
104 group_allow : acl.allow_gid.join(','),
105 contact_allow : acl.allow_cid.join(','),
106 group_deny : acl.deny_gid.join(','),
107 contact_deny : acl.deny_cid.join(',')
110 uploader.setParams( {
111 newalbum : document.getElementById('photos-upload-newalbum').value,
112 album : document.getElementById('photos-upload-album-select').value,
113 not_visible : document.getElementById('photos-upload-noshare').checked,
114 group_allow : getSelected(document.getElementById('group_allow')).join(','),
115 contact_allow : getSelected(document.getElementById('contact_allow')).join(','),
116 group_deny : getSelected(document.getElementById('group_deny')).join(','),
117 contact_deny : getSelected(document.getElementById('contact_deny')).join(',')
125 // in your app create uploader as soon as the DOM is ready
126 // don't wait for the window to load
127 window.onload = createUploader;
137 function js_upload_post_init(&$a,&$b) {
139 // list of valid extensions, ex. array("jpeg", "xml", "bmp")
141 $allowedExtensions = array("jpeg","gif","png","jpg");
143 // max file size in bytes
145 $sizeLimit = get_config('system','maximagesize'); //6 * 1024 * 1024;
147 $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
149 $result = $uploader->handleUpload();
152 // to pass data through iframe you will need to encode all html tags
153 $a->data['upload_jsonresponse'] = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
155 if(isset($result['error'])) {
156 logger('mod/photos.php: photos_post(): error uploading photo: ' . $result['error'] , 'LOGGER_DEBUG');
157 echo json_encode($result);
161 $a->data['upload_result'] = $result;
165 function js_upload_post_file(&$a,&$b) {
167 $result = $a->data['upload_result'];
169 $b['src'] = $result['path'];
170 $b['filename'] = $result['filename'];
171 $b['filesize'] = filesize($b['src']);
176 function js_upload_post_end(&$a,&$b) {
178 logger('upload_post_end');
179 if(x($a->data,'upload_jsonresponse')) {
180 echo $a->data['upload_jsonresponse'];
188 * Handle file uploads via XMLHttpRequest
190 class qqUploadedFileXhr {
192 private $pathnm = '';
195 * Save the file in the temp dir.
196 * @return boolean TRUE on success
199 $input = fopen("php://input", "r");
201 $upload_dir = get_config('system','tempdir');
203 $upload_dir = sys_get_temp_dir();
205 $this->pathnm = tempnam($upload_dir,'frn');
207 $temp = fopen($this->pathnm,"w");
208 $realSize = stream_copy_to_stream($input, $temp);
213 if ($realSize != $this->getSize()){
220 return $this->pathnm;
224 return $_GET['qqfile'];
228 if (isset($_SERVER["CONTENT_LENGTH"])){
229 return (int)$_SERVER["CONTENT_LENGTH"];
231 throw new Exception('Getting content length is not supported.');
237 * Handle file uploads via regular form post (uses the $_FILES array)
240 class qqUploadedFileForm {
244 * Save the file to the specified path
245 * @return boolean TRUE on success
254 return $_FILES['qqfile']['tmp_name'];
258 return $_FILES['qqfile']['name'];
261 return $_FILES['qqfile']['size'];
265 class qqFileUploader {
266 private $allowedExtensions = array();
267 private $sizeLimit = 10485760;
270 function __construct(array $allowedExtensions = array(), $sizeLimit = 10485760){
271 $allowedExtensions = array_map("strtolower", $allowedExtensions);
273 $this->allowedExtensions = $allowedExtensions;
274 $this->sizeLimit = $sizeLimit;
276 if (isset($_GET['qqfile'])) {
277 $this->file = new qqUploadedFileXhr();
278 } elseif (isset($_FILES['qqfile'])) {
279 $this->file = new qqUploadedFileForm();
287 private function toBytes($str){
289 $last = strtolower($str[strlen($str)-1]);
291 case 'g': $val *= 1024;
292 case 'm': $val *= 1024;
293 case 'k': $val *= 1024;
299 * Returns array('success'=>true) or array('error'=>'error message')
301 function handleUpload(){
304 return ['error' => L10n::t('No files were uploaded.')];
307 $size = $this->file->getSize();
310 return ['error' => L10n::t('Uploaded file is empty')];
313 // if ($size > $this->sizeLimit) {
315 // return array('error' => L10n::t('Uploaded file is too large'));
319 $maximagesize = get_config('system','maximagesize');
321 if(($maximagesize) && ($size > $maximagesize)) {
322 return ['error' => L10n::t('Image exceeds size limit of ') . $maximagesize ];
326 $pathinfo = pathinfo($this->file->getName());
327 $filename = $pathinfo['filename'];
329 $ext = $pathinfo['extension'];
331 if($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)){
332 $these = implode(', ', $this->allowedExtensions);
333 return ['error' => L10n::t('File has an invalid extension, it should be one of ') . $these . '.'];
336 if ($this->file->save()){
339 'path' => $this->file->getPath(),
340 'filename' => $filename . '.' . $ext
344 'error'=> L10n::t('Upload was cancelled, or server error encountered'),
345 'path' => $this->file->getPath(),
346 'filename' => $filename . '.' . $ext