5 * JavaScript Photo/Image Uploader
7 * Uses Valum 'qq' Uploader.
8 * Module Author: Chris Case
10 * Prior to enabling, ensure that you have a directory 'uploads'
11 * which is writable by the web server.
16 function js_upload_install() {
17 register_hook('photo_upload_form', 'addon/js_upload/js_upload.php', 'js_upload_form');
18 register_hook('photo_post_init', 'addon/js_upload/js_upload.php', 'js_upload_post_init');
19 register_hook('photo_post_file', 'addon/js_upload/js_upload.php', 'js_upload_post_file');
20 register_hook('photo_post_end', 'addon/js_upload/js_upload.php', 'js_upload_post_end');
24 function js_upload_uninstall() {
25 unregister_hook('photo_upload_form', 'addon/js_upload/js_upload.php', 'js_upload_form');
26 unregister_hook('photo_post_init', 'addon/js_upload/js_upload.php', 'js_upload_post_init');
27 unregister_hook('photo_post_file', 'addon/js_upload/js_upload.php', 'js_upload_post_file');
28 unregister_hook('photo_post_end', 'addon/js_upload/js_upload.php', 'js_upload_post_end');
32 function js_upload_form(&$a,&$b) {
34 $b['default_upload'] = false;
36 $b['addon_text'] .= '<link href="' . $a->get_baseurl() . '/addon/js_upload/file-uploader/client/fileuploader.css" rel="stylesheet" type="text/css">';
37 $b['addon_text'] .= '<script src="' . $a->get_baseurl() . '/addon/js_upload/file-uploader/client/fileuploader.js" type="text/javascript"></script>';
39 $upload_msg = t('Upload a file');
40 $drop_msg = t('Drop files here to upload');
41 $cancel = t('Cancel');
42 $failed = t('Failed');
44 $b['addon_text'] .= <<< EOT
46 <div id="file-uploader-demo1">
48 <p>Please enable JavaScript to use file uploader.</p>
49 <!-- or put a simple form for upload here -->
53 <script type="text/javascript">
55 function getSelected(opt) {
56 var selected = new Array();
58 for (var intLoop = 0; intLoop < opt.length; intLoop++) {
59 if ((opt[intLoop].selected) ||
60 (opt[intLoop].checked)) {
61 index = selected.length;
62 //selected[index] = new Object;
63 selected[index] = opt[intLoop].value;
64 //selected[index] = intLoop;
69 function createUploader() {
70 uploader = new qq.FileUploader({
71 element: document.getElementById('file-uploader-demo1'),
72 action: '{$b['post_url']}',
74 template: '<div class="qq-uploader">' +
75 '<div class="qq-upload-drop-area"><span>$drop_msg</span></div>' +
76 '<div class="qq-upload-button">$upload_msg</div>' +
77 '<ul class="qq-upload-list"></ul>' +
80 // template for one item in file list
81 fileTemplate: '<li>' +
82 '<span class="qq-upload-file"></span>' +
83 '<span class="qq-upload-spinner"></span>' +
84 '<span class="qq-upload-size"></span>' +
85 '<a class="qq-upload-cancel" href="#">$cancel</a>' +
86 '<span class="qq-upload-failed-text">$failed</span>' +
90 onSubmit: function(id,filename) {
93 newalbum : document.getElementById('photos-upload-newalbum').value,
94 album : document.getElementById('photos-upload-album-select').value,
95 group_allow : getSelected(document.getElementById('group_allow')).join(','),
96 contact_allow : getSelected(document.getElementById('contact_allow')).join(','),
97 group_deny : getSelected(document.getElementById('group_deny')).join(','),
98 contact_deny : getSelected(document.getElementById('contact_deny')).join(',')
105 // in your app create uploader as soon as the DOM is ready
106 // don't wait for the window to load
107 window.onload = createUploader;
117 function js_upload_post_init(&$a,&$b) {
119 // list of valid extensions, ex. array("jpeg", "xml", "bmp")
121 $allowedExtensions = array("jpeg","gif","png","jpg");
123 // max file size in bytes
125 $sizeLimit = 6 * 1024 * 1024;
127 $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
129 $result = $uploader->handleUpload();
132 // to pass data through iframe you will need to encode all html tags
133 $a->data['upload_jsonresponse'] = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
135 if(isset($result['error'])) {
136 logger('mod/photos.php: photos_post(): error uploading photo: ' . $result['error'] , 'LOGGER_DEBUG');
140 $a->data['upload_result'] = $result;
144 function js_upload_post_file(&$a,&$b) {
146 $result = $a->data['upload_result'];
148 $b['src'] = $result['path'];
149 $b['filename'] = $result['filename'];
150 $b['filesize'] = filesize($b['src']);
155 function js_upload_post_end(&$a,&$b) {
157 logger('upload_post_end');
158 if(x($a->data,'upload_jsonresponse')) {
159 echo $a->data['upload_jsonresponse'];
167 * Handle file uploads via XMLHttpRequest
169 class qqUploadedFileXhr {
171 private $pathnm = '';
174 * Save the file in the temp dir.
175 * @return boolean TRUE on success
178 $input = fopen("php://input", "r");
179 $this->pathnm = tempnam(sys_get_temp_dir(),'frn');
180 $temp = fopen($this->pathnm,"w");
181 $realSize = stream_copy_to_stream($input, $temp);
186 if ($realSize != $this->getSize()){
193 return $this->pathnm;
197 return $_GET['qqfile'];
201 if (isset($_SERVER["CONTENT_LENGTH"])){
202 return (int)$_SERVER["CONTENT_LENGTH"];
204 throw new Exception('Getting content length is not supported.');
210 * Handle file uploads via regular form post (uses the $_FILES array)
213 class qqUploadedFileForm {
217 * Save the file to the specified path
218 * @return boolean TRUE on success
227 return $_FILES['qqfile']['tmp_name'];
231 return $_FILES['qqfile']['name'];
234 return $_FILES['qqfile']['size'];
238 class qqFileUploader {
239 private $allowedExtensions = array();
240 private $sizeLimit = 10485760;
243 function __construct(array $allowedExtensions = array(), $sizeLimit = 10485760){
244 $allowedExtensions = array_map("strtolower", $allowedExtensions);
246 $this->allowedExtensions = $allowedExtensions;
247 $this->sizeLimit = $sizeLimit;
249 $this->checkServerSettings();
251 if (isset($_GET['qqfile'])) {
252 $this->file = new qqUploadedFileXhr();
253 } elseif (isset($_FILES['qqfile'])) {
254 $this->file = new qqUploadedFileForm();
261 private function checkServerSettings(){
262 $postSize = $this->toBytes(ini_get('post_max_size'));
263 $uploadSize = $this->toBytes(ini_get('upload_max_filesize'));
264 logger('mod/photos.php: qqFileUploader(): upload_max_filesize=' . $uploadSize , 'LOGGER_DEBUG');
265 if ($postSize < $this->sizeLimit || $uploadSize < $this->sizeLimit){
266 $size = max(1, $this->sizeLimit / 1024 / 1024) . 'M';
267 die("{'error':'increase post_max_size and upload_max_filesize to $size'}");
271 private function toBytes($str){
273 $last = strtolower($str[strlen($str)-1]);
275 case 'g': $val *= 1024;
276 case 'm': $val *= 1024;
277 case 'k': $val *= 1024;
283 * Returns array('success'=>true) or array('error'=>'error message')
285 function handleUpload(){
288 return array('error' => t('No files were uploaded.'));
291 $size = $this->file->getSize();
294 return array('error' => t('Uploaded file is empty'));
297 if ($size > $this->sizeLimit) {
299 return array('error' => t('Uploaded file is too large'));
303 $maximagesize = get_config('system','maximagesize');
305 if(($maximagesize) && ($size > $maximagesize)) {
306 return array('error' => t('Image exceeds size limit of ') . $maximagesize );
310 $pathinfo = pathinfo($this->file->getName());
311 $filename = $pathinfo['filename'];
313 $ext = $pathinfo['extension'];
315 if($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)){
316 $these = implode(', ', $this->allowedExtensions);
317 return array('error' => t('File has an invalid extension, it should be one of ') . $these . '.');
320 if ($this->file->save()){
323 'path' => $this->file->getPath(),
324 'filename' => $filename . '.' . $ext
328 'error'=> t('Upload was cancelled, or server error encountered'),
329 'path' => $this->file->getPath(),
330 'filename' => $filename . '.' . $ext