3 * Jirafeau, your web file repository
4 * Copyright (C) 2015 Jerome Jutteau <j.jutteau@gmail.com>
5 * Copyright (C) 2015 Nicola Spanti (RyDroid) <dev@nicola-spanti.info>
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 header('Content-Type: text/javascript');
23 define('JIRAFEAU_ROOT', dirname(__FILE__
) . '/../');
25 require(JIRAFEAU_ROOT
. 'lib/settings.php');
26 require(JIRAFEAU_ROOT
. 'lib/functions.php');
27 require(JIRAFEAU_ROOT
. 'lib/lang.php');
30 function translate (expr
)
32 var lang_array
= <?php
echo json_lang_generator() ?
>;
33 if (lang_array
.hasOwnProperty(expr
))
34 return lang_array
[expr
];
38 function isEmpty(str
) {
39 return (!str ||
0 === str
.length
);
42 // Extend date object with format method
43 Date
.prototype
.format
= function(format
) {
44 format
= format ||
'YYYY-MM-DD hh:mm';
46 var zeropad
= function(number
, length
) {
47 number
= number
.toString();
49 while(number
.length
< length
)
50 number
= '0' + number
;
54 YYYY
: this
.getFullYear(),
55 MM
: zeropad(this
.getMonth() +
1),
56 DD
: zeropad(this
.getDate()),
57 hh
: zeropad(this
.getHours()),
58 mm
: zeropad(this
.getMinutes()),
61 sign
= (localDate
.getTimezoneOffset() > 0) ?
'-' : '+';
62 offset
= Math
.abs(localDate
.getTimezoneOffset());
63 hours
= zeropad(Math
.floor(offset
/ 60));
64 minutes
= zeropad(offset %
60);
65 return sign + hours +
":" + minutes
;
68 pattern
= '(' +
Object.keys(formats
).join(')|(') +
')';
70 return format
.replace(new RegExp(pattern
, 'g'), function(match
) {
71 return formats
[match
];
75 function dateFromUtcString(datestring
) {
76 // matches »YYYY-MM-DD hh:mm«
77 var m
= datestring
.match(/(\d+
)-(\d+
)-(\d+
)\s+
(\d+
):(\d+
)/);
78 return new Date(Date
.UTC(+m
[1], +m
[2] - 1, +m
[3], +m
[4], +m
[5], 0));
81 function dateFromUtcTimestamp(datetimestamp
) {
82 return new Date(parseInt(datetimestamp
) * 1000)
85 function dateToUtcString(datelocal
) {
87 datelocal
.getUTCFullYear(),
88 datelocal
.getUTCMonth(),
89 datelocal
.getUTCDate(),
90 datelocal
.getUTCHours(),
91 datelocal
.getUTCMinutes(),
92 datelocal
.getUTCSeconds()
96 function dateToUtcTimestamp(datelocal
) {
98 datelocal
.getUTCFullYear(),
99 datelocal
.getUTCMonth(),
100 datelocal
.getUTCDate(),
101 datelocal
.getUTCHours(),
102 datelocal
.getUTCMinutes(),
103 datelocal
.getUTCSeconds()
107 function convertAllDatetimeFields() {
108 datefields
= document
.getElementsByClassName('datetime')
109 for(var i
=0; i
<datefields
.length
; i++
) {
110 dateUTC
= datefields
[i
].getAttribute('data-datetime');
111 datefields
[i
].setAttribute('title', dateUTC +
' (GMT)');
112 datefields
[i
].innerHTML
= dateFromUtcString(dateUTC
).format('YYYY-MM-DD hh:mm (GMT O)');
116 function show_link (reference
, delete_code
, crypt_key
, date
)
119 document
.getElementById('uploading').style
.display
= 'none';
120 document
.getElementById('upload').style
.display
= 'none';
121 document
.getElementById('upload_finished').style
.display
= '';
122 document
.title
= "<?php echo empty($cfg['title']) ? 'Jirafeau' : $cfg['title']; ?> - 100%";
125 var download_link_href
= 'f.php?h=' + reference
;
126 if (crypt_key
.length
> 0)
128 download_link_href +
= '&k=' + crypt_key
;
130 if (!!document
.getElementById('upload_finished_download_page'))
132 document
.getElementById('upload_link').href
= download_link_href
;
136 var filename
= document
.getElementById('file_select').files
[0].name
;
137 var b
= encodeURIComponent("Download file \"" + filename +
"\":") +
"%0D";
138 b +
= encodeURIComponent("<?php echo $cfg['web_root']; ?>" + download_link_href
) +
"%0D";
139 if (false == isEmpty(date
))
141 b +
= "%0D" +
encodeURIComponent("This file will be available until " + date
.format('YYYY-MM-DD hh:mm (GMT O)')) +
"%0D";
142 document
.getElementById('upload_link_email').href
= "mailto:?body=" + b +
"&subject=" +
encodeURIComponent(filename
);
146 var delete_link_href
= 'f.php?h=' + reference +
'&d=' + delete_code
;
147 document
.getElementById('delete_link').href
= delete_link_href
;
152 document
.getElementById('date').style
.display
= 'none';
155 document
.getElementById('date').innerHTML
= '<span class="datetime" title="'
156 +
dateToUtcString(date
) +
' (GMT)">'
157 + date
.format('YYYY-MM-DD hh:mm (GMT O)')
159 document
.getElementById('date').style
.display
= '';
162 // Preview link (if allowed)
163 if (!!document
.getElementById('preview_link'))
165 document
.getElementById('upload_finished_preview').style
.display
= 'none';
166 var preview_link_href
= 'f.php?h=' + reference +
'&p=1';
167 if (crypt_key
.length
> 0)
169 preview_link_href +
= '&k=' + crypt_key
;
172 // Test if content can be previewed
173 type
= document
.getElementById('file_select').files
[0].type
;
174 if (type
.indexOf("image") > -1 ||
175 type
.indexOf("audio") > -1 ||
176 type
.indexOf("text") > -1 ||
177 type
.indexOf("video") > -1)
179 document
.getElementById('preview_link').href
= preview_link_href
;
180 document
.getElementById('upload_finished_preview').style
.display
= '';
184 // Direct download link
185 var direct_download_link_href
= 'f.php?h=' + reference +
'&d=1';
186 if (crypt_key
.length
> 0)
188 direct_download_link_href +
= '&k=' + crypt_key
;
190 document
.getElementById('direct_link').href
= direct_download_link_href
;
192 // Hide preview and direct download link if password is set
193 if (document
.getElementById('input_key').value
.length
> 0)
195 if (!!document
.getElementById('preview_link'))
196 document
.getElementById('upload_finished_preview').style
.display
= 'none';
197 document
.getElementById('upload_direct_download').style
.display
= 'none';
201 function show_upload_progression (percentage
, speed
, time_left
)
203 document
.getElementById('uploaded_percentage').innerHTML
= percentage
;
204 document
.getElementById('uploaded_speed').innerHTML
= speed
;
205 document
.getElementById('uploaded_time').innerHTML
= time_left
;
206 document
.title
= "<?php echo empty($cfg['title']) ? 'Jirafeau' : $cfg['title']; ?> - " + percentage
;
209 function hide_upload_progression ()
211 document
.getElementById('uploaded_percentage').style
.display
= 'none';
212 document
.getElementById('uploaded_speed').style
.display
= 'none';
213 document
.getElementById('uploaded_time').style
.display
= 'none';
214 document
.title
= "<?php echo empty($cfg['title']) ? 'Jirafeau' : $cfg['title']; ?>";
217 function upload_progress (e
)
219 if (e
== undefined || e
== null ||
!e
.lengthComputable
)
222 // Init time estimation if needed
223 if (upload_time_estimation_total_size
== 0)
224 upload_time_estimation_total_size
= e
.total
;
226 // Compute percentage
227 var p
= Math
.round (e
.loaded
* 100 / e
.total
);
230 p_str
= p
.toString() +
'%';
231 // Update estimation speed
232 upload_time_estimation_add(e
.loaded
);
234 var speed_str
= upload_time_estimation_speed_string();
235 speed_str
= upload_speed_refresh_limiter(speed_str
);
237 var time_str
= chrono_update(upload_time_estimation_time());
239 show_upload_progression (p_str
, speed_str
, time_str
);
242 function control_selected_file_size(max_size
, error_str
)
244 f_size
= document
.getElementById('file_select').files
[0].size
;
245 if (max_size
> 0 && f_size
> max_size
* 1024 * 1024)
247 pop_failure(error_str
);
248 document
.getElementById('send').style
.display
= 'none';
252 // add class to restyle upload form in next step
253 document
.getElementById('upload').setAttribute('class', 'file-selected');
255 document
.getElementById('options').style
.display
= 'block';
256 document
.getElementById('send').style
.display
= 'block';
257 document
.getElementById('error_pop').style
.display
= 'none';
258 document
.getElementById('send').focus();
262 function pop_failure (e
)
264 var text
= "An error occured";
265 if (typeof e
!== 'undefined')
267 text
= "<p>" + text +
"</p>";
268 document
.getElementById('error_pop').innerHTML
= e
;
270 document
.getElementById('uploading').style
.display
= 'none';
271 document
.getElementById('error_pop').style
.display
= '';
272 document
.getElementById('upload').style
.display
= '';
273 document
.getElementById('send').style
.display
= '';
276 function add_time_string_to_date(d
, time
)
278 if(typeof(d
) != 'object' ||
!(d
instanceof Date
))
283 if (time
== 'minute')
285 d
.setSeconds (d
.getSeconds() +
60);
290 d
.setSeconds (d
.getSeconds() +
3600);
295 d
.setSeconds (d
.getSeconds() +
86400);
300 d
.setSeconds (d
.getSeconds() +
604800);
305 d
.setSeconds (d
.getSeconds() +
2419200);
308 if (time
== 'quarter')
310 d
.setSeconds (d
.getSeconds() +
7257600);
315 d
.setSeconds (d
.getSeconds() +
29030400);
321 function classic_upload (file
, time
, password
, one_time
, upload_password
)
323 // Delay time estimation init as we can't have file size
324 upload_time_estimation_init(0);
326 var req
= new XMLHttpRequest ();
327 req
.upload
.addEventListener ("progress", upload_progress
, false);
328 req
.addEventListener ("error", pop_failure
, false);
329 req
.addEventListener ("abort", pop_failure
, false);
330 req
.onreadystatechange
= function ()
332 if (req
.readyState
== 4 && req
.status
== 200)
334 var res
= req
.responseText
;
336 // if response starts with "Error" then show a failure
337 if (/^Error
/.test(res
))
343 res
= res
.split ("\n");
347 // convert time (local time + selected expiry date)
348 var localDatetime
= new Date();
349 if(!add_time_string_to_date(localDatetime
, time
))
351 pop_failure ('Error: Date can not be parsed');
354 expiryDate
= localDatetime
;
357 show_link (res
[0], res
[1], res
[2], expiryDate
);
360 req
.open ("POST", 'script.php' , true);
362 var form
= new FormData();
363 form
.append ("file", file
);
365 form
.append ("time", time
);
367 form
.append ("key", password
);
369 form
.append ("one_time_download", '1');
370 if (upload_password
.length
> 0)
371 form
.append ("upload_password", upload_password
);
376 function check_html5_file_api ()
378 return window
.File
&& window
.FileReader
&& window
.FileList
&& window
.Blob
;
381 var async_global_transfered
= 0;
382 var async_global_file
;
383 var async_global_ref
= '';
384 var async_global_max_size
= 0;
385 var async_global_time
;
386 var async_global_transfering
= 0;
388 function async_upload_start (max_size
, file
, time
, password
, one_time
, upload_password
)
390 async_global_transfered
= 0;
391 async_global_file
= file
;
392 async_global_max_size
= max_size
;
393 async_global_time
= time
;
395 var req
= new XMLHttpRequest ();
396 req
.addEventListener ("error", pop_failure
, false);
397 req
.addEventListener ("abort", pop_failure
, false);
398 req
.onreadystatechange
= function ()
400 if (req
.readyState
== 4 && req
.status
== 200)
402 var res
= req
.responseText
;
404 if (/^Error
/.test(res
))
410 res
= res
.split ("\n");
411 async_global_ref
= res
[0];
413 async_upload_push (code
);
416 req
.open ("POST", 'script.php?init_async' , true);
418 var form
= new FormData();
419 form
.append ("filename", async_global_file
.name
);
420 form
.append ("type", async_global_file
.type
);
422 form
.append ("time", time
);
424 form
.append ("key", password
);
426 form
.append ("one_time_download", '1');
427 if (upload_password
.length
> 0)
428 form
.append ("upload_password", upload_password
);
430 // Start time estimation
431 upload_time_estimation_init(async_global_file
.size
);
436 function async_upload_progress (e
)
438 if (e
== undefined || e
== null ||
!e
.lengthComputable
&& async_global_file
.size
!= 0)
441 // Compute percentage
442 var p
= Math
.round ((e
.loaded + async_global_transfered
) * 100 / (async_global_file
.size
));
445 p_str
= p
.toString() +
'%';
446 // Update estimation speed
447 upload_time_estimation_add(e
.loaded + async_global_transfered
);
449 var speed_str
= upload_time_estimation_speed_string();
450 speed_str
= upload_speed_refresh_limiter(speed_str
);
452 var time_str
= chrono_update(upload_time_estimation_time());
454 show_upload_progression (p_str
, speed_str
, time_str
);
457 function async_upload_push (code
)
459 if (async_global_transfered
== async_global_file
.size
)
461 hide_upload_progression ();
462 async_upload_end (code
);
465 var req
= new XMLHttpRequest ();
466 req
.upload
.addEventListener ("progress", async_upload_progress
, false);
467 req
.addEventListener ("error", pop_failure
, false);
468 req
.addEventListener ("abort", pop_failure
, false);
469 req
.onreadystatechange
= function ()
471 if (req
.readyState
== 4 && req
.status
== 200)
473 var res
= req
.responseText
;
475 if (/^Error
/.test(res
))
481 res
= res
.split ("\n");
483 async_global_transfered
= async_global_transfering
;
484 async_upload_push (code
);
487 req
.open ("POST", 'script.php?push_async' , true);
489 var chunk_size
= parseInt (async_global_max_size
* 0.50);
490 var start
= async_global_transfered
;
491 var end
= start + chunk_size
;
492 if (end
>= async_global_file
.size
)
493 end
= async_global_file
.size
;
494 var blob
= async_global_file
.slice (start
, end
);
495 async_global_transfering
= end
;
497 var form
= new FormData();
498 form
.append ("ref", async_global_ref
);
499 form
.append ("data", blob
);
500 form
.append ("code", code
);
504 function async_upload_end (code
)
506 var req
= new XMLHttpRequest ();
507 req
.addEventListener ("error", pop_failure
, false);
508 req
.addEventListener ("abort", pop_failure
, false);
509 req
.onreadystatechange
= function ()
511 if (req
.readyState
== 4 && req
.status
== 200)
513 var res
= req
.responseText
;
515 if (/^Error
/.test(res
))
521 res
= res
.split ("\n");
523 if (async_global_time
!= 'none')
525 // convert time (local time + selected expiry date)
526 var localDatetime
= new Date();
527 if(!add_time_string_to_date(localDatetime
, async_global_time
)) {
528 pop_failure ('Error: Date can not be parsed');
531 expiryDate
= localDatetime
;
534 show_link (res
[0], res
[1], res
[2], expiryDate
);
537 req
.open ("POST", 'script.php?end_async' , true);
539 var form
= new FormData();
540 form
.append ("ref", async_global_ref
);
541 form
.append ("code", code
);
545 function upload (max_size
)
547 if (check_html5_file_api ()
548 && document
.getElementById('file_select').files
[0].size
>= max_size
)
552 document
.getElementById('file_select').files
[0],
553 document
.getElementById('select_time').value
,
554 document
.getElementById('input_key').value
,
555 document
.getElementById('one_time_download').checked
,
556 document
.getElementById('upload_password').value
562 document
.getElementById('file_select').files
[0],
563 document
.getElementById('select_time').value
,
564 document
.getElementById('input_key').value
,
565 document
.getElementById('one_time_download').checked
,
566 document
.getElementById('upload_password').value
571 var upload_time_estimation_total_size
= 42;
572 var upload_time_estimation_transfered_size
= 42;
573 var upload_time_estimation_transfered_date
= 42;
574 var upload_time_estimation_moving_average_speed
= 42;
576 function upload_time_estimation_init(total_size
)
578 upload_time_estimation_total_size
= total_size
;
579 upload_time_estimation_transfered_size
= 0;
580 upload_time_estimation_moving_average_speed
= 0;
582 upload_time_estimation_transfered_date
= d
.getTime();
585 function upload_time_estimation_add(total_transfered_size
)
587 // Let's compute the current speed
589 var speed
= upload_time_estimation_moving_average_speed
;
590 if (d
.getTime() - upload_time_estimation_transfered_date
!= 0)
591 speed
= (total_transfered_size
- upload_time_estimation_transfered_size
)
592 / (d
.getTime() - upload_time_estimation_transfered_date
);
593 // Let's compute moving average speed on 30 values
594 var m
= (upload_time_estimation_moving_average_speed
* 29 + speed
) / 30;
595 // Update global values
596 upload_time_estimation_transfered_size
= total_transfered_size
;
597 upload_time_estimation_transfered_date
= d
.getTime();
598 upload_time_estimation_moving_average_speed
= m
;
601 function upload_time_estimation_speed_string()
604 var s
= upload_time_estimation_moving_average_speed
* 1000;
612 else if (s
< 1000000)
614 res
= Math
.floor(s
/100) / 10;
619 res
= Math
.floor(s
/100000) / 10;
624 return res
.toString() +
' ' + scale
;
627 function milliseconds_to_time_string (milliseconds
)
629 function numberEnding (number
) {
630 var currentLanguage
= '<?php echo $cfg['lang
']; ?>';
632 if(currentLanguage
== 'de') {
633 return (number
> 1) ?
'n' : '';
636 return (number
> 1) ?
's' : '';
640 var temp
= Math
.floor(milliseconds
/ 1000);
641 var years
= Math
.floor(temp
/ 31536000);
643 return years +
' ' +
translate ('year') +
numberEnding(years
);
645 var days
= Math
.floor((temp %
= 31536000) / 86400);
647 return days +
' ' +
translate ('day') +
numberEnding(days
);
649 var hours
= Math
.floor((temp %
= 86400) / 3600);
651 return hours +
' ' +
translate ('hour') +
numberEnding(hours
);
653 var minutes
= Math
.floor((temp %
= 3600) / 60);
655 return minutes +
' ' +
translate ('minute') +
numberEnding(minutes
);
657 var seconds
= temp %
60;
659 return seconds +
' ' +
translate ('second') +
numberEnding(seconds
);
661 return translate ('less than a second');
664 function upload_time_estimation_time()
666 // Estimate remaining time
667 if (upload_time_estimation_moving_average_speed
== 0)
669 return (upload_time_estimation_total_size
- upload_time_estimation_transfered_size
)
670 / upload_time_estimation_moving_average_speed
;
673 var chrono_last_update
= 0;
674 var chrono_time_ms
= 0;
675 var chrono_time_ms_last_update
= 0;
676 function chrono_update(time_ms
)
680 // Don't update too often
681 if (d
.getTime() - chrono_last_update
< 3000 &&
682 chrono_time_ms_last_update
> 0)
683 chrono
= chrono_time_ms
;
686 chrono_last_update
= d
.getTime();
687 chrono_time_ms
= time_ms
;
689 chrono_time_ms_last_update
= d
.getTime();
692 // Adjust chrono for smooth estimation
693 chrono
= chrono
- (d
.getTime() - chrono_time_ms_last_update
);
695 // Let's update chronometer
698 time_str
= milliseconds_to_time_string (chrono
);
702 var upload_speed_refresh_limiter_last_update
= 0;
703 var upload_speed_refresh_limiter_last_value
= '';
704 function upload_speed_refresh_limiter(speed_str
)
707 if (d
.getTime() - upload_speed_refresh_limiter_last_update
> 1500)
709 upload_speed_refresh_limiter_last_value
= speed_str
;
710 upload_speed_refresh_limiter_last_update
= d
.getTime();
712 return upload_speed_refresh_limiter_last_value
;
716 document
.addEventListener('DOMContentLoaded', function(event
) {
717 // Search for all datetime fields and convert the time to local timezone
718 convertAllDatetimeFields();
721 // Add copy event listeners
722 function copyLinkToClipboard(link_id
) {
723 var focus
= document
.activeElement
;
724 var e
= document
.getElementById(link_id
);
726 var tmp
= document
.createElement("textarea");
727 document
.body
.appendChild(tmp
);
728 tmp
.textContent
= e
.href
;
730 tmp
.setSelectionRange(0, tmp
.value
.length
);
731 document
.execCommand("copy");
732 document
.body
.removeChild(tmp
);
737 function addCopyListener(button_id
, link_id
) {
738 document
.getElementById(button_id
)
739 .addEventListener("click", function() {
740 copyLinkToClipboard(link_id
);});