]> git.mxchange.org Git - friendica.git/blob - js/ajaxupload.js
add remove_user hook (it looks like dreamhost changed all my file permissions, this...
[friendica.git] / js / ajaxupload.js
1 /**
2  * AJAX Upload ( http://valums.com/ajax-upload/ ) 
3  * Copyright (c) Andris Valums
4  * Licensed under the MIT license ( http://valums.com/mit-license/ )
5  * Thanks to Gary Haran, David Mark, Corey Burns and others for contributions. 
6  */
7
8 (function () {
9     /* global window */
10     /* jslint browser: true, devel: true, undef: true, nomen: true, bitwise: true, regexp: true, newcap: true, immed: true */
11     
12     /**
13      * Wrapper for FireBug's console.log
14      */
15     function log(){
16         if (typeof(console) != 'undefined' && typeof(console.log) == 'function'){            
17             Array.prototype.unshift.call(arguments, '[Ajax Upload]');
18             console.log( Array.prototype.join.call(arguments, ' '));
19         }
20     } 
21
22     /**
23      * Attaches event to a dom element.
24      * @param {Element} el
25      * @param type event name
26      * @param fn callback This refers to the passed element
27      */
28     function addEvent(el, type, fn){
29         if (el.addEventListener) {
30             el.addEventListener(type, fn, false);
31         } else if (el.attachEvent) {
32             el.attachEvent('on' + type, function(){
33                 fn.call(el);
34                 });
35             } else {
36             throw new Error('not supported or DOM not loaded');
37         }
38     }   
39     
40     /**
41      * Attaches resize event to a window, limiting
42      * number of event fired. Fires only when encounteres
43      * delay of 100 after series of events.
44      * 
45      * Some browsers fire event multiple times when resizing
46      * http://www.quirksmode.org/dom/events/resize.html
47      * 
48      * @param fn callback This refers to the passed element
49      */
50     function addResizeEvent(fn){
51         var timeout;
52                
53             addEvent(window, 'resize', function(){
54             if (timeout){
55                 clearTimeout(timeout);
56             }
57             timeout = setTimeout(fn, 100);                        
58         });
59     }    
60     
61     // Needs more testing, will be rewriten for next version        
62     // getOffset function copied from jQuery lib (http://jquery.com/)
63     if (document.documentElement.getBoundingClientRect){
64         // Get Offset using getBoundingClientRect
65         // http://ejohn.org/blog/getboundingclientrect-is-awesome/
66         var getOffset = function(el){
67             var box = el.getBoundingClientRect();
68             var doc = el.ownerDocument;
69             var body = doc.body;
70             var docElem = doc.documentElement; // for ie 
71             var clientTop = docElem.clientTop || body.clientTop || 0;
72             var clientLeft = docElem.clientLeft || body.clientLeft || 0;
73              
74             // In Internet Explorer 7 getBoundingClientRect property is treated as physical,
75             // while others are logical. Make all logical, like in IE8. 
76             var zoom = 1;            
77             if (body.getBoundingClientRect) {
78                 var bound = body.getBoundingClientRect();
79                 zoom = (bound.right - bound.left) / body.clientWidth;
80             }
81             
82             if (zoom > 1) {
83                 clientTop = 0;
84                 clientLeft = 0;
85             }
86             
87             var top = box.top / zoom + (window.pageYOffset || docElem && docElem.scrollTop / zoom || body.scrollTop / zoom) - clientTop, left = box.left / zoom + (window.pageXOffset || docElem && docElem.scrollLeft / zoom || body.scrollLeft / zoom) - clientLeft;
88             
89             return {
90                 top: top,
91                 left: left
92             };
93         };        
94     } else {
95         // Get offset adding all offsets 
96         var getOffset = function(el){
97             var top = 0, left = 0;
98             do {
99                 top += el.offsetTop || 0;
100                 left += el.offsetLeft || 0;
101                 el = el.offsetParent;
102             } while (el);
103             
104             return {
105                 left: left,
106                 top: top
107             };
108         };
109     }
110     
111     /**
112      * Returns left, top, right and bottom properties describing the border-box,
113      * in pixels, with the top-left relative to the body
114      * @param {Element} el
115      * @return {Object} Contains left, top, right,bottom
116      */
117     function getBox(el){
118         var left, right, top, bottom;
119         var offset = getOffset(el);
120         left = offset.left;
121         top = offset.top;
122         
123         right = left + el.offsetWidth;
124         bottom = top + el.offsetHeight;
125         
126         return {
127             left: left,
128             right: right,
129             top: top,
130             bottom: bottom
131         };
132     }
133     
134     /**
135      * Helper that takes object literal
136      * and add all properties to element.style
137      * @param {Element} el
138      * @param {Object} styles
139      */
140     function addStyles(el, styles){
141         for (var name in styles) {
142             if (styles.hasOwnProperty(name)) {
143                 el.style[name] = styles[name];
144             }
145         }
146     }
147         
148     /**
149      * Function places an absolutely positioned
150      * element on top of the specified element
151      * copying position and dimentions.
152      * @param {Element} from
153      * @param {Element} to
154      */    
155     function copyLayout(from, to){
156             var box = getBox(from);
157         
158         addStyles(to, {
159                 position: 'absolute',                    
160                 left : box.left + 'px',
161                 top : box.top + 'px',
162                 width : from.offsetWidth + 'px',
163                 height : from.offsetHeight + 'px'
164             });        
165         to.title = from.title;
166
167     }
168
169     /**
170     * Creates and returns element from html chunk
171     * Uses innerHTML to create an element
172     */
173     var toElement = (function(){
174         var div = document.createElement('div');
175         return function(html){
176             div.innerHTML = html;
177             var el = div.firstChild;
178             return div.removeChild(el);
179         };
180     })();
181             
182     /**
183      * Function generates unique id
184      * @return unique id 
185      */
186     var getUID = (function(){
187         var id = 0;
188         return function(){
189             return 'ValumsAjaxUpload' + id++;
190         };
191     })();        
192  
193     /**
194      * Get file name from path
195      * @param {String} file path to file
196      * @return filename
197      */  
198     function fileFromPath(file){
199         return file.replace(/.*(\/|\\)/, "");
200     }
201     
202     /**
203      * Get file extension lowercase
204      * @param {String} file name
205      * @return file extenstion
206      */    
207     function getExt(file){
208         return (-1 !== file.indexOf('.')) ? file.replace(/.*[.]/, '') : '';
209     }
210
211     function hasClass(el, name){        
212         var re = new RegExp('\\b' + name + '\\b');        
213         return re.test(el.className);
214     }    
215     function addClass(el, name){
216         if ( ! hasClass(el, name)){   
217             el.className += ' ' + name;
218         }
219     }    
220     function removeClass(el, name){
221         var re = new RegExp('\\b' + name + '\\b');                
222         el.className = el.className.replace(re, '');        
223     }
224     
225     function removeNode(el){
226         el.parentNode.removeChild(el);
227     }
228
229     /**
230      * Easy styling and uploading
231      * @constructor
232      * @param button An element you want convert to 
233      * upload button. Tested dimentions up to 500x500px
234      * @param {Object} options See defaults below.
235      */
236     window.AjaxUpload = function(button, options){
237         this._settings = {
238             // Location of the server-side upload script
239             action: 'upload.php',
240             // File upload name
241             name: 'userfile',
242             // Additional data to send
243             data: {},
244             // Submit file as soon as it's selected
245             autoSubmit: true,
246             // The type of data that you're expecting back from the server.
247             // html and xml are detected automatically.
248             // Only useful when you are using json data as a response.
249             // Set to "json" in that case. 
250             responseType: false,
251             // Class applied to button when mouse is hovered
252             hoverClass: 'hover',
253             // Class applied to button when button is focused
254             focusClass: 'focus',
255             // Class applied to button when AU is disabled
256             disabledClass: 'disabled',            
257             // When user selects a file, useful with autoSubmit disabled
258             // You can return false to cancel upload                    
259             onChange: function(file, extension){
260             },
261             // Callback to fire before file is uploaded
262             // You can return false to cancel upload
263             onSubmit: function(file, extension){
264             },
265             // Fired when file upload is completed
266             // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
267             onComplete: function(file, response){
268             }
269         };
270                         
271         // Merge the users options with our defaults
272         for (var i in options) {
273             if (options.hasOwnProperty(i)){
274                 this._settings[i] = options[i];
275             }
276         }
277                 
278         // button isn't necessary a dom element
279         if (button.jquery){
280             // jQuery object was passed
281             button = button[0];
282         } else if (typeof button == "string") {
283             if (/^#.*/.test(button)){
284                 // If jQuery user passes #elementId don't break it                                      
285                 button = button.slice(1);                
286             }
287             
288             button = document.getElementById(button);
289         }
290         
291         if ( ! button || button.nodeType !== 1){
292             throw new Error("Please make sure that you're passing a valid element"); 
293         }
294                 
295         if ( button.nodeName.toUpperCase() == 'A'){
296             // disable link                       
297             addEvent(button, 'click', function(e){
298                 if (e && e.preventDefault){
299                     e.preventDefault();
300                 } else if (window.event){
301                     window.event.returnValue = false;
302                 }
303             });
304         }
305                     
306         // DOM element
307         this._button = button;        
308         // DOM element                 
309         this._input = null;
310         // If disabled clicking on button won't do anything
311         this._disabled = false;
312         
313         // if the button was disabled before refresh if will remain
314         // disabled in FireFox, let's fix it
315         this.enable();        
316         
317         this._rerouteClicks();
318     };
319     
320     // assigning methods to our class
321     AjaxUpload.prototype = {
322         setData: function(data){
323             this._settings.data = data;
324         },
325         disable: function(){            
326             addClass(this._button, this._settings.disabledClass);
327             this._disabled = true;
328             
329             var nodeName = this._button.nodeName.toUpperCase();            
330             if (nodeName == 'INPUT' || nodeName == 'BUTTON'){
331                 this._button.setAttribute('disabled', 'disabled');
332             }            
333             
334             // hide input
335             if (this._input){
336                 // We use visibility instead of display to fix problem with Safari 4
337                 // The problem is that the value of input doesn't change if it 
338                 // has display none when user selects a file           
339                 this._input.parentNode.style.visibility = 'hidden';
340             }
341         },
342         enable: function(){
343             removeClass(this._button, this._settings.disabledClass);
344             this._button.removeAttribute('disabled');
345             this._disabled = false;
346             
347         },
348         /**
349          * Creates invisible file input 
350          * that will hover above the button
351          * <div><input type='file' /></div>
352          */
353         _createInput: function(){ 
354             var self = this;
355                         
356             var input = document.createElement("input");
357             input.setAttribute('type', 'file');
358             input.setAttribute('name', this._settings.name);
359
360             addStyles(input, {
361                 'position' : 'absolute',
362                 // in Opera only 'browse' button
363                 // is clickable and it is located at
364                 // the right side of the input
365                 'right' : 0,
366                 'margin' : 0,
367                 'padding' : 0,
368                 'fontSize' : '480px',
369                 // in Firefox if font-family is set to
370                 // 'inherit' the input doesn't work
371                 'fontFamily' : 'sans-serif',
372                 'cursor' : 'pointer'
373             });            
374
375             var div = document.createElement("div");                        
376             addStyles(div, {
377                 'display' : 'block',
378                 'position' : 'absolute',
379                 'overflow' : 'hidden',
380                 'margin' : 0,
381                 'padding' : 0,                
382                 'opacity' : 0,
383                 // Make sure browse button is in the right side
384                 // in Internet Explorer
385                 'direction' : 'ltr',
386                 //Max zIndex supported by Opera 9.0-9.2
387                 'zIndex': 2147483583,
388                                 'cursor' : 'pointer'
389
390             });
391             
392             // Make sure that element opacity exists.
393             // Otherwise use IE filter            
394             if ( div.style.opacity !== "0") {
395                 if (typeof(div.filters) == 'undefined'){
396                     throw new Error('Opacity not supported by the browser');
397                 }
398                 div.style.filter = "alpha(opacity=0)";
399             }            
400             
401             addEvent(input, 'change', function(){
402                  
403                 if ( ! input || input.value === ''){                
404                     return;                
405                 }
406                             
407                 // Get filename from input, required                
408                 // as some browsers have path instead of it          
409                 var file = fileFromPath(input.value);
410                                 
411                 if (false === self._settings.onChange.call(self, file, getExt(file))){
412                     self._clearInput();                
413                     return;
414                 }
415                 
416                 // Submit form when value is changed
417                 if (self._settings.autoSubmit) {
418                     self.submit();
419                 }
420             });            
421
422             addEvent(input, 'mouseover', function(){
423                 addClass(self._button, self._settings.hoverClass);
424             });
425             
426             addEvent(input, 'mouseout', function(){
427                 removeClass(self._button, self._settings.hoverClass);
428                 removeClass(self._button, self._settings.focusClass);
429                 
430                 // We use visibility instead of display to fix problem with Safari 4
431                 // The problem is that the value of input doesn't change if it 
432                 // has display none when user selects a file           
433                 input.parentNode.style.visibility = 'hidden';
434
435             });   
436                         
437             addEvent(input, 'focus', function(){
438                 addClass(self._button, self._settings.focusClass);
439             });
440             
441             addEvent(input, 'blur', function(){
442                 removeClass(self._button, self._settings.focusClass);
443             });
444             
445                 div.appendChild(input);
446             document.body.appendChild(div);
447               
448             this._input = input;
449         },
450         _clearInput : function(){
451             if (!this._input){
452                 return;
453             }            
454                              
455             // this._input.value = ''; Doesn't work in IE6                               
456             removeNode(this._input.parentNode);
457             this._input = null;                                                                   
458             this._createInput();
459             
460             removeClass(this._button, this._settings.hoverClass);
461             removeClass(this._button, this._settings.focusClass);
462         },
463         /**
464          * Function makes sure that when user clicks upload button,
465          * the this._input is clicked instead
466          */
467         _rerouteClicks: function(){
468             var self = this;
469             
470             // IE will later display 'access denied' error
471             // if you use using self._input.click()
472             // other browsers just ignore click()
473
474             addEvent(self._button, 'mouseover', function(){
475                 if (self._disabled){
476                     return;
477                 }
478                                 
479                 if ( ! self._input){
480                         self._createInput();
481                 }
482                 
483                 var div = self._input.parentNode;                            
484                 copyLayout(self._button, div);
485                 div.style.visibility = 'visible';
486                                 
487             });
488             
489             
490             // commented because we now hide input on mouseleave
491             /**
492              * When the window is resized the elements 
493              * can be misaligned if button position depends
494              * on window size
495              */
496             //addResizeEvent(function(){
497             //    if (self._input){
498             //        copyLayout(self._button, self._input.parentNode);
499             //    }
500             //});            
501                                          
502         },
503         /**
504          * Creates iframe with unique name
505          * @return {Element} iframe
506          */
507         _createIframe: function(){
508             // We can't use getTime, because it sometimes return
509             // same value in safari :(
510             var id = getUID();            
511              
512             // We can't use following code as the name attribute
513             // won't be properly registered in IE6, and new window
514             // on form submit will open
515             // var iframe = document.createElement('iframe');
516             // iframe.setAttribute('name', id);                        
517  
518             var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
519             // src="javascript:false; was added
520             // because it possibly removes ie6 prompt 
521             // "This page contains both secure and nonsecure items"
522             // Anyway, it doesn't do any harm.            
523             iframe.setAttribute('id', id);
524             
525             iframe.style.display = 'none';
526             document.body.appendChild(iframe);
527             
528             return iframe;
529         },
530         /**
531          * Creates form, that will be submitted to iframe
532          * @param {Element} iframe Where to submit
533          * @return {Element} form
534          */
535         _createForm: function(iframe){
536             var settings = this._settings;
537                         
538             // We can't use the following code in IE6
539             // var form = document.createElement('form');
540             // form.setAttribute('method', 'post');
541             // form.setAttribute('enctype', 'multipart/form-data');
542             // Because in this case file won't be attached to request                    
543             var form = toElement('<form method="post" enctype="multipart/form-data"></form>');
544                         
545             form.setAttribute('action', settings.action);
546             form.setAttribute('target', iframe.name);                                   
547             form.style.display = 'none';
548             document.body.appendChild(form);
549             
550             // Create hidden input element for each data key
551             for (var prop in settings.data) {
552                 if (settings.data.hasOwnProperty(prop)){
553                     var el = document.createElement("input");
554                     el.setAttribute('type', 'hidden');
555                     el.setAttribute('name', prop);
556                     el.setAttribute('value', settings.data[prop]);
557                     form.appendChild(el);
558                 }
559             }
560             return form;
561         },
562         /**
563          * Gets response from iframe and fires onComplete event when ready
564          * @param iframe
565          * @param file Filename to use in onComplete callback 
566          */
567         _getResponse : function(iframe, file){            
568             // getting response
569             var toDeleteFlag = false, self = this, settings = this._settings;   
570                
571             addEvent(iframe, 'load', function(){                
572                 
573                 if (// For Safari 
574                     iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" ||
575                     // For FF, IE
576                     iframe.src == "javascript:'<html></html>';"){                                                                        
577                         // First time around, do not delete.
578                         // We reload to blank page, so that reloading main page
579                         // does not re-submit the post.
580                         
581                         if (toDeleteFlag) {
582                             // Fix busy state in FF3
583                             setTimeout(function(){
584                                 removeNode(iframe);
585                             }, 0);
586                         }
587                                                 
588                         return;
589                 }
590                 
591                 var doc = iframe.contentDocument ? iframe.contentDocument : window.frames[iframe.id].document;
592                 
593                 // fixing Opera 9.26,10.00
594                 if (doc.readyState && doc.readyState != 'complete') {
595                    // Opera fires load event multiple times
596                    // Even when the DOM is not ready yet
597                    // this fix should not affect other browsers
598                    return;
599                 }
600                 
601                 // fixing Opera 9.64
602                 if (doc.body && doc.body.innerHTML == "false") {
603                     // In Opera 9.64 event was fired second time
604                     // when body.innerHTML changed from false 
605                     // to server response approx. after 1 sec
606                     return;
607                 }
608                 
609                 var response;
610                 
611                 if (doc.XMLDocument) {
612                     // response is a xml document Internet Explorer property
613                     response = doc.XMLDocument;
614                 } else if (doc.body){
615                     // response is html document or plain text
616                     response = doc.body.innerHTML;
617                     
618                     if (settings.responseType && settings.responseType.toLowerCase() == 'json') {
619                         // If the document was sent as 'application/javascript' or
620                         // 'text/javascript', then the browser wraps the text in a <pre>
621                         // tag and performs html encoding on the contents.  In this case,
622                         // we need to pull the original text content from the text node's
623                         // nodeValue property to retrieve the unmangled content.
624                         // Note that IE6 only understands text/html
625                         if (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE') {
626                             doc.normalize();
627                             response = doc.body.firstChild.firstChild.nodeValue;
628                         }
629                         
630                         if (response) {
631                             response = eval("(" + response + ")");
632                         } else {
633                             response = {};
634                         }
635                     }
636                 } else {
637                     // response is a xml document
638                     response = doc;
639                 }
640                 
641                 settings.onComplete.call(self, file, response);
642                 
643                 // Reload blank page, so that reloading main page
644                 // does not re-submit the post. Also, remember to
645                 // delete the frame
646                 toDeleteFlag = true;
647                 
648                 // Fix IE mixed content issue
649                 iframe.src = "javascript:'<html></html>';";
650             });            
651         },        
652         /**
653          * Upload file contained in this._input
654          */
655         submit: function(){                        
656             var self = this, settings = this._settings;
657             
658             if ( ! this._input || this._input.value === ''){                
659                 return;                
660             }
661                                     
662             var file = fileFromPath(this._input.value);
663             
664             // user returned false to cancel upload
665             if (false === settings.onSubmit.call(this, file, getExt(file))){
666                 this._clearInput();                
667                 return;
668             }
669             
670             // sending request    
671             var iframe = this._createIframe();
672             var form = this._createForm(iframe);
673             
674             // assuming following structure
675             // div -> input type='file'
676             removeNode(this._input.parentNode);            
677             removeClass(self._button, self._settings.hoverClass);
678             removeClass(self._button, self._settings.focusClass);
679                         
680             form.appendChild(this._input);
681                         
682             form.submit();
683
684             // request set, clean up                
685             removeNode(form); form = null;                          
686             removeNode(this._input); this._input = null;            
687             
688             // Get response from iframe and fire onComplete event when ready
689             this._getResponse(iframe, file);            
690
691             // get ready for next request            
692             this._createInput();
693         }
694     };
695 })();