add semester

This commit is contained in:
François 2024-12-08 19:05:07 +01:00
parent 874dd95a25
commit 56572b5b76
8 changed files with 1728 additions and 13 deletions

View File

@ -11,7 +11,7 @@
a.php?time=month&key=password + POST file => upload a.php?time=month&key=password + POST file => upload
a.php?s=mel@domain.org => form a.php?s=mel@domain.org => form
a.php?s=mel@domain.org&t=password + [action] => manage account a.php?s=mel@domain.org&t=password + [action] => manage account
action: a=login a=logout a=r[on|off] a=p[minute|hour|day|week|month|quarter] action: a=login a=logout a=r[on|off] a=p[minute|hour|day|week|month|quarter|semester]
*/ */
use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\PHPMailer;
@ -90,7 +90,7 @@ define ('M_WELCOME', "<p>Informations concernant le compte : <b>___SENDER___</b>
define ('M_INCONSISTENT_DATES', define ('M_INCONSISTENT_DATES',
" (dates incoh&eacute;antes avec ___FILENAME___ : ___DIRTIME___ != ___FILETIME___)"); " (dates incoh&eacute;antes avec ___FILENAME___ : ___DIRTIME___ != ___FILETIME___)");
define ('A_ACTION', 'a'); // action : T_LOGIN, T_LOGOUT, A_MODE(none|footer|attachment|both), A_RECORD+(on|off), A_PERIOD(minute|hour|day|week|month|quarter), A_LANG(fr|en|br) define ('A_ACTION', 'a'); // action : T_LOGIN, T_LOGOUT, A_MODE(none|footer|attachment|both), A_RECORD+(on|off), A_PERIOD(minute|hour|day|week|month|quarter|semester), A_LANG(fr|en|br)
define ('A_GET', 'g'); // get archive define ('A_GET', 'g'); // get archive
define ('A_HASH', 'h'); // file to update or delete define ('A_HASH', 'h'); // file to update or delete
define ('A_OPEN_TOKEN', 'o'); // ask token define ('A_OPEN_TOKEN', 'o'); // ask token
@ -129,13 +129,14 @@ define ('T_ARCHIVE_MIME', "text/kaz_email_archive");
$modeText = ['none' => "sans", 'footer' => "pied de page", 'attachment' => "pi&egrave;ce jointe", 'both' => "les deux"]; $modeText = ['none' => "sans", 'footer' => "pied de page", 'attachment' => "pi&egrave;ce jointe", 'both' => "les deux"];
$trackText = ['on' => "oui", 'off' => "non"]; $trackText = ['on' => "oui", 'off' => "non"];
$periodText = ['minute' => "minute", 'hour' => "heure", 'day' => "jour", 'week' => "semaine", 'month' => "mois"]; $periodText = ['minute' => "minute", 'hour' => "heure", 'day' => "jour", 'week' => "semaine", 'month' => "mois", 'quarter' => "trimestre", "semester" => "semestre"];
// XXX , 'quarter' => "trimestre"]; $periodButton = ['hour' => ["&#128336;", ">1 heure"], // 1F550
$periodButton = ['hour' => ["&#128341;", ">1 heure"], 'day' => ["&#128337;", ">1 jour"], // 1F551
'day' => ["&#128348;", ">1 jour"], 'week' => ["&#128338;", "> 1 semaine"], // 1F552
'week' => ["&#128349;", "> 1 semaine"], 'month' => ["&#128339;", "> 1 mois"], // 1F553
'month' => ["&#128350;", "> 1 mois"]]; 'quarter' => ["&#128340;", "> 1 trimestre"], // 1F554
// XXX 'quarter' => ["&#128351;", "> 1 trimestre"]]; 'semester' => ["&#128341;", "> 1 semestre"] // 1F555
];
$langText = ['fr' => "Francais", 'br' => "Breton", 'en' => "english"]; $langText = ['fr' => "Francais", 'br' => "Breton", 'en' => "english"];
$doLogout = ''; $doLogout = '';
$message = ''; $message = '';
@ -308,6 +309,9 @@ function period2seconds ($periodName) {
case 'quarter': case 'quarter':
return JIRAFEAU_QUARTER; return JIRAFEAU_QUARTER;
break; break;
case 'semester':
return JIRAFEAU_SEMESTER;
break;
case 'year': case 'year':
return JIRAFEAU_YEAR; return JIRAFEAU_YEAR;
break; break;

View File

@ -0,0 +1,201 @@
<?php
/*
* Jirafeau, your web file repository
* Copyright (C) 2008 Julien "axolotl" BERNARD <axolotl@magieeternelle.org>
* Copyright (C) 2015 Jerome Jutteau <jerome@jutteau.fr>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* Default configuration
*
* To overwrite these settings copy the file,
* rename it to »config.local.php« and adapt the parameters.
**/
/* URL of installation, with traling slash (eg. »https://exmaple.com/jirafeau/«)
*/
$cfg['web_root'] = '';
/* Path to data directory, with trailing slash (eg. »/var/www/data/var_314159265358979323846264«
*/
$cfg['var_root'] = '';
/* Language - choice between 'auto' or any language located in the /lib/locales/ folder.
* The mode »auto« will cause the script to detect the user's browser information
* and offer a matching language, and use »en« if it is not available.
* Forcing to a specific lang lightly reduce lang computation.
*/
$cfg['lang'] = 'auto';
/* Select a theme - see media folder for available themes
*/
$cfg['style'] = 'courgette';
/* Name the organisation running this installation, eg. 'ACME'
*/
$cfg['organisation'] = 'ACME';
/* Provide a contact person for this installation, eg. 'John Doe <doe@example.com>'
*/
$cfg['contactperson'] = '';
/* Give the installation a title, eg. 'Datahub' or 'John Doe Filehost'
*/
$cfg['title'] = '';
/* Propose a preview link if file type is previewable
*/
$cfg['preview'] = true;
/* Enable the encryption feature
* By enabling it, file-level deduplication won't work anymore. See FAQ.
*/
$cfg['enable_crypt'] = false;
/* Length of link reference
*/
$cfg['link_name_length'] = 8;
/* Upload password(s).
* An empty array will disable the password authentification.
* $cfg['upload_password'] = array(); // No password
* $cfg['upload_password'] = array('psw1'); // One password
* $cfg['upload_password'] = array('psw1', 'psw2'); // Two passwords
*/
$cfg['upload_password'] = array();
/* List of IP allowed to upload a file.
* If the list is empty, then there is no upload restriction based on IP.
* Elements of the list can be a single IP (e.g. "123.45.67.89") or
* an IP range (e.g. "123.45.0.0/16").
* Note that CIDR notation is available for IPv4 only for the moment.
*/
$cfg['upload_ip'] = array();
/* List of IP allowed to upload a file without password.
* Elements of the list can be a single IP (e.g. "123.45.67.89") or
* an IP range (e.g. "123.45.0.0/16").
* Note that CIDR notation is available for IPv4 only for the moment.
*/
$cfg['upload_ip_nopassword'] = array();
/* Password for the admin interface.
* An empty password will disable the password authentification.
* The password is a sha256 hash of the original version.
*/
$cfg['admin_password'] = '';
/* If set, let the user be authenticated as administrator.
* The user provided here is the user authenticated by HTTP authentication.
* Note that Jirafeau does not manage the HTTP login part, it just checks
* that the provided user is logged in.
* If »admin_password« parameter is set, then the »admin_password« is ignored.
*/
$cfg['admin_http_auth_user'] = '';
/* Allow user to select different options for file expiration time.
* Possible values in array:
* 'minute': file is available for one minute
* 'hour': file available for one hour
* 'day': file available for one day
* 'week': file available for one week
* 'month': file is available for one month
* 'quarter': file is available for three months
* 'semester': file is available for six months
* 'year': file available for one year
* 'none': unlimited availability
*/
$cfg['availabilities'] = array(
'minute' => true,
'hour' => true,
'day' => true,
'week' => true,
'month' => true,
'quarter' => false,
'semester' => false,
'year' => false,
'none' => false
);
/* Set a default value for the expiration time.
* The value has to equal one of the enabled options in »availabilities«, e.g. »month«.
*/
$cfg['availability_default'] = 'month';
/* Give the uploading user the option to have the file
* deleted after the first download.
*/
$cfg['one_time_download'] = true;
/* Set maximal upload size expressed in MB.
* »0« means unlimited upload size.
*/
$cfg['maximal_upload_size'] = 0;
/* Proxy IP
* If the installation is behind some reverse proxies, it is possible to set
* the allowed proxy IP.
* $cfg['proxy_ip'] = array('12.34.56.78');
* Jirafeau will then get a visitor's IP from HTTP_X_FORWARDED_FOR
* instead of REMOTE_ADDR.
*/
$cfg['proxy_ip'] = array();
/* File hash
* In order to make file deduplication work, files can be hashed through different methods.
* By default, files are hashed through md5 but other methods are available.
*
* Possible values are 'md5', 'md5_outside' and 'random'.
*
* With 'md5' option, the whole file is hashed through md5. This is the default.
* With 'md5_outside', hash is computed using:
* - md5 of the first part of the file,
* - md5 of the last part of the file and
* - file's size.
* This method offer file deduplication at minimal cost but can be dangerous as files with the same partial hash can be mistaken.
* With 'random' option, file hash is set to a random value and file deduplication cannot work anymore but it is fast and safe.
*/
$cfg['file_hash'] = 'md5';
/* Work around that LiteSpeed truncates large files when downloading.
* Only for use with the LiteSpeed web server!
* An internal redirect is made using X-LiteSpeed-Location instead
* of streaming the file from PHP.
* Limitations:
* - The Jirafeau files folder has to be placed under the document root and should be
* protected from unauthorized access using rewrite rules.
* See https://www.litespeedtech.com/support/wiki/doku.php/litespeed_wiki:config:internal-redirect#protection_from_direct_access
* - Incompatible with server side encryption.
* - Incompatible with one time download.
*/
$cfg['litespeed_workaround'] = false;
/* Store uploader's IP along with 'link' file.
* Depending of your legislation, you may have to adjust this parameter.
*/
$cfg['store_uploader_ip'] = true;
/* Required flag to test if the installation is already installed
* or needs to start the installation script
*/
$cfg['installation_done'] = false;
/* Enable this debug flag to allow eventual PHP error reporting.
* This is disabled by default permission misconfiguration might generate warnings or errors.
* Those warnings can break Jirafeau and also show path to var- folder in debug messages.
* var- folder should kept secret and accessing it may lead to data leak if unprotected.
*/
$cfg['debug'] = false;

119
src/Jirafeau/en.json Normal file
View File

@ -0,0 +1,119 @@
{
"SIZE_DATA": "Data size",
"INCOMPATIBLE_OPTIONS_W": "The following configuration options are incompatible:",
"NO_BROWSER_SUPPORT": "Your browser may not support HTML5, so the maximum file size is ",
"PLURAL_ENDING": "s",
"JI_WEB_RE": "Jirafeau, your web file repository",
"SEL_FILE": "Select a file",
"SEND": "Send",
"UP": "Uploading …",
"ONE_TIME_DL": "One-time download",
"PSW": "Password",
"TIME_LIM": "Time limit",
"MAX_FILE_SIZE": "Maximum file size",
"POWERED_BY": "powered by the copyleft, libre software project Jirafeau",
"MADE_WITH": "Made with",
"JI_PROJECT": "Jirafeau Project",
"1_MIN": "One minute",
"1_H": "One hour",
"1_D": "One day",
"1_W": "One week",
"1_M": "One month",
"1_Q": "One quarter",
"1_S": "One semester",
"1_Y": "One year",
"NONE": "None",
"UP_PSW": "Upload password",
"2_BIG": "The file is too big",
"FILE_LIM": "File size limited to",
"FILE_DIR_W": "The file directory is not writable.",
"LINK_DIR_W": "The link directory is not writable.",
"ASYNC_DIR_W": "The async directory is not writable.",
"INSTALL_SCRIPT_HERE": "Installer script still present",
"ERR_OCC": "An error occurred.",
"FILE_UP": "File uploaded.",
"DL_PAGE": "Download page",
"VALID_UNTIL": "This file is valid until the following date",
"VIEW_LINK": "View link",
"DIRECT_DL": "Direct download link",
"DELETE_LINK": "Delete link",
"DL": "Download",
"PREVIEW": "Preview",
"FILE_404": "Sorry, the requested file is not found",
"FILE_NOT_AVAIL": "File not available.",
"CONFIRM_DEL": "Confirm deletion",
"GONNA_DEL": "You are about to delete",
"DELETE": "Delete",
"FILE_DELETED": "File has been deleted.",
"FILE_EXPIRED": "The time limit of this file has expired.",
"PSW_PROTEC": "Password protection",
"GIMME_PSW": "Supply password for this file",
"ACCESS_KO": "Access denied",
"NOW_DOWNLOADING": "You are about to download",
"USING_SERVICE": "By using our services, you accept our",
"TOS": "Terms of Service",
"AUTO_DESTRUCT": "Warning, this file will self-destruct after being read",
"INTERNAL_ERROR_DEL": "Internal error during file creation.",
"CONF_AUTOGEN_COMMENT": "This file was generated by the installation process. You can edit it. Please see config.original.php to understand the configuration items.",
"CANNOT_CREATE_DIR": "The following directory could not be created",
"MANUAL_CREATE": "You should create this directory manually.",
"DIR_NOT_W": "The following directory is not writable",
"GIMME_W": "You should give the write permission to the web server on this directory.",
"HERE_SOLUTION": "Here is a solution",
"CONF_SOLUTION": "The local configuration file could not be created. Create a <code>lib/config.local.php</code> file and grant write permission to the web server (preferred solution), or grant write permission to the web server in the <code>lib</code> directory.",
"CONF_SOLUTION_2": "The local configuration is not writable by the web server. Grant write permission to the web server in the '<code>lib/config.local.php</code>' file.",
"JI_INSTALL": "Installation of Jirafeau",
"STEP": "step",
"OUT_OF": "out of",
"ADMIN_PSW": "Admin password",
"FINALIZATION": "Finalisation",
"SETTING_UP": "Jirafeau is setting up the website according to the configuration you provided.",
"PREV_STEP": "Previous step",
"RETRY_STEP": "Retry this step",
"JI_FONCTIONAL": "Jirafeau is now fully operational",
"INFO": "Information",
"BASE_ADDR_INFO": "The base address of Jirafeau is the first part of the URL, until (and including) the last slash. For example: \"http://www.example.com/\". Do not forget the trailing slash!",
"BASE_ADDR": "Base address",
"DATA_DIR_EXPLAINATION": "The data directory is where your files and information about your files will be stored. You should put it outside your website, or at least restrict the access to this directory. Do not forget the trailing slash!",
"DATA_DIR": "Data directory",
"NEXT_STEP": "Next step",
"ADMIN_INTERFACE_INFO": "Jirafeau has an admin interface (through admin.php). You can set a password to access the interface or leave it empty to disable the interface.",
"NO_ADMIN": "Sorry, the admin interface is not enabled.",
"NO_ADMIN_AUTH": "Sorry, you have not logged onto the admin interface.",
"LOGIN": "Login",
"BAD_PSW": "Wrong password.",
"ADMIN_INTERFACE": "Admin interface",
"CLEAN_EXPIRED": "Clean expired files",
"CLEAN_INCOMPLETE": "Clean old unfinished transfers",
"CLEAN": "Clean",
"SEARCH_NAME": "Search for files by name",
"SEARCH": "Search",
"LS_FILES": "List all files",
"LIST": "List",
"ACTIONS": "Actions",
"SEARH_BY_HASH": "Search for files by file hash",
"SEARCH_LINK": "Search a specific link",
"CLEANED_FILES_CNT": "Number of cleaned files",
"LOGOUT": "Log out",
"NOW_LOGOUT": "You are now logged out",
"LINK_DELETED": "Link deleted",
"FILENAME": "Filename",
"FILE": "file",
"LINK": "link",
"TYPE": "Type",
"SIZE": "Size",
"EXPIRE": "Expire",
"ONETIME": "One-time",
"UPLOAD_DATE": "Upload date",
"ORIGIN": "Origin",
"ACTION": "Action",
"DEL_LINK": "Del link",
"DEL_FILE_LINKS": "Del file and links",
"DELETED_LINKS": "Deleted links",
"YEAR": "year",
"DAY": "day",
"MINUTE": "minute",
"HOUR": "hour",
"SECOND": "second",
"LESS_1_SEC": "less than a second"
}

View File

@ -0,0 +1,791 @@
<?php
/*
* Jirafeau, your web file repository
* Copyright (C) 2015 Jerome Jutteau <jerome@jutteau.fr>
* Copyright (C) 2015 Nicola Spanti (RyDroid) <dev@nicola-spanti.info>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
header('Content-Type: text/javascript');
define('JIRAFEAU_ROOT', dirname(__FILE__) . '/../');
require(JIRAFEAU_ROOT . 'lib/settings.php');
require(JIRAFEAU_ROOT . 'lib/functions.php');
require(JIRAFEAU_ROOT . 'lib/lang.php');
?>
// @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-v3-or-Later
var web_root = "<?php echo $cfg['web_root']; ?>";
var lang_array = <?php echo json_lang_generator(null); ?>;
var lang_array_fallback = <?php echo json_lang_generator("en"); ?>;
function translate (expr) {
if (lang_array.hasOwnProperty(expr)) {
var e = lang_array[expr];
if (!isEmpty(e))
return e;
}
if (lang_array_fallback.hasOwnProperty(expr)) {
var e = lang_array_fallback[expr];
if (!isEmpty(e))
return e;
}
return "FIXME: " + expr;
}
function isEmpty(str) {
return (!str || 0 === str.length);
}
// Extend date object with format method
Date.prototype.format = function(format) {
format = format || 'YYYY-MM-DD hh:mm';
var zeropad = function(number, length) {
number = number.toString();
length = length || 2;
while(number.length < length)
number = '0' + number;
return number;
},
formats = {
YYYY: this.getFullYear(),
MM: zeropad(this.getMonth() + 1),
DD: zeropad(this.getDate()),
hh: zeropad(this.getHours()),
mm: zeropad(this.getMinutes()),
O: (function() {
localDate = new Date;
sign = (localDate.getTimezoneOffset() > 0) ? '-' : '+';
offset = Math.abs(localDate.getTimezoneOffset());
hours = zeropad(Math.floor(offset / 60));
minutes = zeropad(offset % 60);
return sign + hours + ":" + minutes;
})()
},
pattern = '(' + Object.keys(formats).join(')|(') + ')';
return format.replace(new RegExp(pattern, 'g'), function(match) {
return formats[match];
});
};
function dateFromUtcString(datestring) {
// matches »YYYY-MM-DD hh:mm«
var m = datestring.match(/(\d+)-(\d+)-(\d+)\s+(\d+):(\d+)/);
return new Date(Date.UTC(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], 0));
}
function dateFromUtcTimestamp(datetimestamp) {
return new Date(parseInt(datetimestamp) * 1000)
}
function dateToUtcString(datelocal) {
return new Date(
datelocal.getUTCFullYear(),
datelocal.getUTCMonth(),
datelocal.getUTCDate(),
datelocal.getUTCHours(),
datelocal.getUTCMinutes(),
datelocal.getUTCSeconds()
).format();
}
function dateToUtcTimestamp(datelocal) {
return (Date.UTC(
datelocal.getUTCFullYear(),
datelocal.getUTCMonth(),
datelocal.getUTCDate(),
datelocal.getUTCHours(),
datelocal.getUTCMinutes(),
datelocal.getUTCSeconds()
) / 1000);
}
function convertAllDatetimeFields() {
datefields = document.getElementsByClassName('datetime')
for(var i=0; i<datefields.length; i++) {
dateUTC = datefields[i].getAttribute('data-datetime');
datefields[i].setAttribute('title', dateUTC + ' (GMT)');
datefields[i].innerHTML = dateFromUtcString(dateUTC).format('YYYY-MM-DD hh:mm (GMT O)');
}
}
function show_link (reference, delete_code, crypt_key, date)
{
// Upload finished
document.getElementById('uploading').style.display = 'none';
document.getElementById('upload').style.display = 'none';
document.getElementById('upload_finished').style.display = '';
document.title = "100% - <?php echo empty($cfg['title']) ? 'Jirafeau' : $cfg['title']; ?>";
// Download page
var download_link_href = 'f.php?h=' + reference;
if (crypt_key.length > 0)
{
download_link_href += '&k=' + crypt_key;
}
if (!!document.getElementById('upload_finished_download_page'))
{
document.getElementById('upload_link').href = download_link_href;
document.getElementById('upload_link_text').innerHTML = web_root + download_link_href;
}
// Email link
var filename = document.getElementById('file_select').files[0].name;
var b = encodeURIComponent("<?php echo t("DL"); ?> \"" + filename + "\":") + "%0D" + "%0A";
b += encodeURIComponent(web_root + download_link_href) + "%0D" + "%0A";
if (false == isEmpty(date))
{
b += "%0D" + "%0A" + encodeURIComponent("<?php echo t("VALID_UNTIL"); ?>: " + date.format('YYYY-MM-DD hh:mm (GMT O)')) + "%0D" + "%0A";
document.getElementById('upload_link_email').href = "mailto:?body=" + b + "&subject=" + encodeURIComponent(filename);
}
// Delete link
var delete_link_href = 'f.php?h=' + reference + '&d=' + delete_code;
document.getElementById('delete_link').href = delete_link_href;
document.getElementById('delete_link_text').innerHTML = web_root + delete_link_href;
// Validity date
if (isEmpty(date))
{
document.getElementById('date').style.display = 'none';
}
else {
document.getElementById('date').innerHTML = '<span class="datetime" title="'
+ dateToUtcString(date) + ' (GMT)">'
+ date.format('YYYY-MM-DD hh:mm (GMT O)')
+ '</span>';
document.getElementById('date').style.display = '';
}
// Preview link (if allowed)
if (!!document.getElementById('preview_link'))
{
document.getElementById('upload_finished_preview').style.display = 'none';
var preview_link_href = 'f.php?h=' + reference + '&p=1';
if (crypt_key.length > 0)
{
preview_link_href += '&k=' + crypt_key;
}
// Test if content can be previewed
type = document.getElementById('file_select').files[0].type;
if (type.indexOf("image") > -1 ||
type.indexOf("audio") > -1 ||
type.indexOf("text") > -1 ||
type.indexOf("video") > -1)
{
document.getElementById('preview_link').href = preview_link_href;
document.getElementById('preview_link_text').innerHTML = web_root + preview_link_href;
document.getElementById('upload_finished_preview').style.display = '';
}
}
// Direct download link
var direct_download_link_href = 'f.php?h=' + reference + '&d=1';
if (crypt_key.length > 0)
{
direct_download_link_href += '&k=' + crypt_key;
}
document.getElementById('direct_link').href = direct_download_link_href;
document.getElementById('direct_link_text').innerHTML = web_root + direct_download_link_href;
// Hide preview and direct download link if password is set
if (document.getElementById('input_key').value.length > 0)
{
if (!!document.getElementById('preview_link'))
document.getElementById('upload_finished_preview').style.display = 'none';
document.getElementById('upload_direct_download').style.display = 'none';
}
}
function show_upload_progression (percentage, speed, time_left)
{
document.getElementById('uploaded_percentage').innerHTML = percentage;
document.getElementById('uploaded_speed').innerHTML = speed;
document.getElementById('uploaded_time').innerHTML = time_left;
document.title = percentage + " - <?php echo empty($cfg['title']) ? 'Jirafeau' : $cfg['title']; ?>";
}
function hide_upload_progression ()
{
document.getElementById('uploaded_percentage').style.display = 'none';
document.getElementById('uploaded_speed').style.display = 'none';
document.getElementById('uploaded_time').style.display = 'none';
document.title = "<?php echo empty($cfg['title']) ? 'Jirafeau' : $cfg['title']; ?>";
}
function upload_progress (e)
{
if (e == undefined || e == null || !e.lengthComputable)
return;
// Init time estimation if needed
if (upload_time_estimation_total_size == 0)
upload_time_estimation_total_size = e.total;
// Compute percentage
var p = Math.round (e.loaded * 100 / e.total);
var p_str = ' ';
if (p != 100)
p_str = p.toString() + '%';
// Update estimation speed
upload_time_estimation_add(e.loaded);
// Get speed string
var speed_str = upload_time_estimation_speed_string();
speed_str = upload_speed_refresh_limiter(speed_str);
// Get time string
var time_str = chrono_update(upload_time_estimation_time());
show_upload_progression (p_str, speed_str, time_str);
}
function control_selected_file_size(max_size, error_str)
{
f_size = document.getElementById('file_select').files[0].size;
if (max_size > 0 && f_size > max_size * 1024 * 1024)
{
pop_failure(error_str);
document.getElementById('send').style.display = 'none';
}
else
{
// add class to restyle upload form in next step
document.getElementById('upload').setAttribute('class', 'file-selected');
// display options
document.getElementById('options').style.display = 'block';
document.getElementById('send').style.display = 'block';
document.getElementById('error_pop').style.display = 'none';
document.getElementById('send').focus();
}
}
function XHRErrorHandler(e)
{
var text = "${e.type}: ${e.loaded} bytes transferred"
console.log(text)
}
function pop_failure (e)
{
var text = "<p>An error occured";
if (typeof e !== 'undefined')
text += ": " + e;
text += "</p>";
document.getElementById('error_pop').innerHTML = e;
document.getElementById('uploading').style.display = 'none';
document.getElementById('error_pop').style.display = '';
document.getElementById('upload').style.display = '';
document.getElementById('send').style.display = '';
}
function add_time_string_to_date(d, time)
{
if(typeof(d) != 'object' || !(d instanceof Date))
{
return false;
}
if (time == 'minute')
{
d.setSeconds (d.getSeconds() + 60);
return true;
}
if (time == 'hour')
{
d.setSeconds (d.getSeconds() + 3600);
return true;
}
if (time == 'day')
{
d.setSeconds (d.getSeconds() + 86400);
return true;
}
if (time == 'week')
{
d.setSeconds (d.getSeconds() + 604800);
return true;
}
if (time == 'month')
{
d.setSeconds (d.getSeconds() + 2592000);
return true;
}
if (time == 'quarter')
{
d.setSeconds (d.getSeconds() + 7776000);
return true;
}
if (time == 'semester')
{
d.setSeconds (d.getSeconds() + 110678400);
return true;
}
if (time == 'year')
{
d.setSeconds (d.getSeconds() + 31536000);
return true;
}
return false;
}
function classic_upload (file, time, password, one_time, upload_password)
{
// Delay time estimation init as we can't have file size
upload_time_estimation_init(0);
var req = new XMLHttpRequest ();
req.upload.addEventListener ("progress", upload_progress, false);
req.addEventListener ("error", XHRErrorHandler, false);
req.addEventListener ("abort", XHRErrorHandler, false);
req.onreadystatechange = function ()
{
if (req.readyState == 4 && req.status == 200)
{
var res = req.responseText;
// if response starts with "Error" then show a failure
if (/^Error/.test(res))
{
pop_failure (res);
return;
}
res = res.split ("\n");
var expiryDate = '';
if (time != 'none')
{
// convert time (local time + selected expiry date)
var localDatetime = new Date();
if(!add_time_string_to_date(localDatetime, time))
{
pop_failure ('Error: Date can not be parsed');
return;
}
expiryDate = localDatetime;
}
show_link (res[0], res[1], res[2], expiryDate);
}
else
{
pop_failure ("<?php echo t("ERR_OCC"); ?>");
}
}
req.open ("POST", 'script.php' , true);
var form = new FormData();
form.append ("file", file);
if (time)
form.append ("time", time);
if (password)
form.append ("key", password);
if (one_time)
form.append ("one_time_download", '1');
if (upload_password.length > 0)
form.append ("upload_password", upload_password);
req.send (form);
}
function check_html5_file_api ()
{
return window.File && window.FileReader && window.FileList && window.Blob;
}
var async_global_transfered = 0;
var async_global_file;
var async_global_ref = '';
var async_global_max_size = 0;
var async_global_time;
var async_global_transfering = 0;
var async_global_last_code;
function async_upload_start (max_size, file, time, password, one_time, upload_password)
{
async_global_transfered = 0;
async_global_file = file;
async_global_max_size = max_size;
async_global_time = time;
var req = new XMLHttpRequest ();
req.addEventListener ("error", XHRErrorHandler, false);
req.addEventListener ("abort", XHRErrorHandler, false);
req.onreadystatechange = function ()
{
if (req.readyState == 4 && req.status == 200)
{
var res = req.responseText;
if (/^Error/.test(res))
{
pop_failure (res);
return;
}
res = res.split ("\n");
async_global_ref = res[0];
var code = res[1];
async_upload_push (code);
}
}
req.open ("POST", 'script.php?init_async' , true);
var form = new FormData();
form.append ("filename", async_global_file.name);
form.append ("type", async_global_file.type);
if (time)
form.append ("time", time);
if (password)
form.append ("key", password);
if (one_time)
form.append ("one_time_download", '1');
if (upload_password.length > 0)
form.append ("upload_password", upload_password);
// Start time estimation
upload_time_estimation_init(async_global_file.size);
req.send (form);
}
function async_upload_progress (e)
{
if (e == undefined || e == null || !e.lengthComputable && async_global_file.size != 0)
return;
// Compute percentage
var p = Math.round ((e.loaded + async_global_transfered) * 100 / (async_global_file.size));
var p_str = ' ';
if (p != 100)
p_str = p.toString() + '%';
// Update estimation speed
upload_time_estimation_add(e.loaded + async_global_transfered);
// Get speed string
var speed_str = upload_time_estimation_speed_string();
speed_str = upload_speed_refresh_limiter(speed_str);
// Get time string
var time_str = chrono_update(upload_time_estimation_time());
show_upload_progression (p_str, speed_str, time_str);
}
function async_upload_push (code)
{
async_global_last_code = code;
if (async_global_transfered == async_global_file.size)
{
hide_upload_progression ();
async_upload_end (code);
return;
}
var req = new XMLHttpRequest ();
req.upload.addEventListener ("progress", async_upload_progress, false);
req.addEventListener ("error", XHRErrorHandler, false);
req.addEventListener ("abort", XHRErrorHandler, false);
req.onreadystatechange = function ()
{
if (req.readyState == 4)
{
if (req.status == 200)
{
var res = req.responseText;
// This error may be triggered when Jirafeau does not receive any file in POST.
// This may be due to bad php configuration where post_max_size is too low
// comparing to upload_max_filesize. Let's retry with lower file size.
if (res === "Error 23")
{
async_global_max_size = Math.max(1, async_global_max_size - 500);
async_upload_push (async_global_last_code);
return;
}
else if (/^Error/.test(res))
{
pop_failure (res);
return;
}
res = res.split ("\n");
var code = res[0]
async_global_transfered = async_global_transfering;
async_upload_push (code);
return;
}
else
{
if (req.status == 413) // Request Entity Too Large
{
// lower async_global_max_size and retry
async_global_max_size = Math.max(1, parseInt (async_global_max_size * 0.8));
}
async_upload_push (async_global_last_code);
return;
}
}
}
req.open ("POST", 'script.php?push_async' , true);
var start = async_global_transfered;
var end = start + async_global_max_size;
if (end >= async_global_file.size)
end = async_global_file.size;
var blob = async_global_file.slice (start, end);
async_global_transfering = end;
var form = new FormData();
form.append ("ref", async_global_ref);
form.append ("data", blob);
form.append ("code", code);
req.send (form);
}
function async_upload_end (code)
{
var req = new XMLHttpRequest ();
req.addEventListener ("error", XHRErrorHandler, false);
req.addEventListener ("abort", XHRErrorHandler, false);
req.onreadystatechange = function ()
{
if (req.readyState == 4 && req.status == 200)
{
var res = req.responseText;
if (/^Error/.test(res))
{
pop_failure (res);
return;
}
res = res.split ("\n");
var expiryDate = '';
if (async_global_time != 'none')
{
// convert time (local time + selected expiry date)
var localDatetime = new Date();
if(!add_time_string_to_date(localDatetime, async_global_time)) {
pop_failure ('Error: Date can not be parsed');
return;
}
expiryDate = localDatetime;
}
show_link (res[0], res[1], res[2], expiryDate);
}
}
req.open ("POST", 'script.php?end_async' , true);
var form = new FormData();
form.append ("ref", async_global_ref);
form.append ("code", code);
req.send (form);
}
function upload (max_size)
{
var one_time_checkbox = document.getElementById('one_time_download');
var one_time = one_time_checkbox !== null ? one_time_checkbox.checked : false;
if (check_html5_file_api ())
{
async_upload_start (
max_size,
document.getElementById('file_select').files[0],
document.getElementById('select_time').value,
document.getElementById('input_key').value,
one_time,
document.getElementById('upload_password').value
);
}
else
{
classic_upload (
document.getElementById('file_select').files[0],
document.getElementById('select_time').value,
document.getElementById('input_key').value,
one_time,
document.getElementById('upload_password').value
);
}
}
var upload_time_estimation_total_size = 42;
var upload_time_estimation_transfered_size = 42;
var upload_time_estimation_transfered_date = 42;
var upload_time_estimation_moving_average_speed = 42;
function upload_time_estimation_init(total_size)
{
upload_time_estimation_total_size = total_size;
upload_time_estimation_transfered_size = 0;
upload_time_estimation_moving_average_speed = 0;
var d = new Date();
upload_time_estimation_transfered_date = d.getTime();
}
function upload_time_estimation_add(total_transfered_size)
{
// Let's compute the current speed
var d = new Date();
var speed = upload_time_estimation_moving_average_speed;
if (d.getTime() - upload_time_estimation_transfered_date != 0)
speed = (total_transfered_size - upload_time_estimation_transfered_size)
/ (d.getTime() - upload_time_estimation_transfered_date);
// Let's compute moving average speed on 30 values
var m = (upload_time_estimation_moving_average_speed * 29 + speed) / 30;
// Update global values
upload_time_estimation_transfered_size = total_transfered_size;
upload_time_estimation_transfered_date = d.getTime();
upload_time_estimation_moving_average_speed = m;
}
function upload_time_estimation_speed_string()
{
// speed ms -> s
var s = upload_time_estimation_moving_average_speed * 1000;
var res = 0;
var scale = '';
if (s <= 1000)
{
res = s.toString();
scale = "B/s";
}
else if (s < 1000000)
{
res = Math.floor(s/100) / 10;
scale = "KB/s";
}
else
{
res = Math.floor(s/100000) / 10;
scale = "MB/s";
}
if (res == 0)
return '';
return res.toString() + ' ' + scale;
}
function milliseconds_to_time_string (milliseconds)
{
function numberEnding (number) {
return (number > 1) ? translate ('PLURAL_ENDING') : '';
}
var temp = Math.floor(milliseconds / 1000);
var years = Math.floor(temp / 31536000);
if (years) {
return years + ' ' + translate ('YEAR') + numberEnding(years);
}
var days = Math.floor((temp %= 31536000) / 86400);
if (days) {
return days + ' ' + translate ('DAY') + numberEnding(days);
}
var hours = Math.floor((temp %= 86400) / 3600);
if (hours) {
return hours + ' ' + translate ('HOUR') + numberEnding(hours);
}
var minutes = Math.floor((temp %= 3600) / 60);
if (minutes) {
return minutes + ' ' + translate ('MINUTE') + numberEnding(minutes);
}
var seconds = temp % 60;
if (seconds) {
return seconds + ' ' + translate ('SECOND') + numberEnding(seconds);
}
return translate ('LESS_1_SEC');
}
function upload_time_estimation_time()
{
// Estimate remaining time
if (upload_time_estimation_moving_average_speed == 0)
return 0;
return (upload_time_estimation_total_size - upload_time_estimation_transfered_size)
/ upload_time_estimation_moving_average_speed;
}
var chrono_last_update = 0;
var chrono_time_ms = 0;
var chrono_time_ms_last_update = 0;
function chrono_update(time_ms)
{
var d = new Date();
var chrono = 0;
// Don't update too often
if (d.getTime() - chrono_last_update < 3000 &&
chrono_time_ms_last_update > 0)
chrono = chrono_time_ms;
else
{
chrono_last_update = d.getTime();
chrono_time_ms = time_ms;
chrono = time_ms;
chrono_time_ms_last_update = d.getTime();
}
// Adjust chrono for smooth estimation
chrono = chrono - (d.getTime() - chrono_time_ms_last_update);
// Let's update chronometer
var time_str = '';
if (chrono > 0)
time_str = milliseconds_to_time_string (chrono);
return time_str;
}
var upload_speed_refresh_limiter_last_update = 0;
var upload_speed_refresh_limiter_last_value = '';
function upload_speed_refresh_limiter(speed_str)
{
var d = new Date();
if (d.getTime() - upload_speed_refresh_limiter_last_update > 1500)
{
upload_speed_refresh_limiter_last_value = speed_str;
upload_speed_refresh_limiter_last_update = d.getTime();
}
return upload_speed_refresh_limiter_last_value;
}
// document.ready()
document.addEventListener('DOMContentLoaded', function(event) {
// Search for all datetime fields and convert the time to local timezone
convertAllDatetimeFields();
});
// Add copy event listeners
function copyLinkToClipboard(link_id) {
var focus = document.activeElement;
var e = document.getElementById(link_id);
var tmp = document.createElement("textarea");
document.body.appendChild(tmp);
tmp.textContent = e.href;
tmp.focus();
tmp.setSelectionRange(0, tmp.value.length);
document.execCommand("copy");
document.body.removeChild(tmp);
focus.focus();
}
function addCopyListener(button_id, link_id) {
if(document.getElementById(button_id)){
document.getElementById(button_id)
.addEventListener("click", function() {
copyLinkToClipboard(link_id);});
}
}
// @license-end

519
src/Jirafeau/script.php Normal file
View File

@ -0,0 +1,519 @@
<?php
/*
* Jirafeau, your web file repository
* Copyright (C) 2015 Jerome Jutteau <jerome@jutteau.fr>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/* This file offer a kind of API for jirafeau. */
define('JIRAFEAU_ROOT', dirname(__FILE__) . '/');
require(JIRAFEAU_ROOT . 'lib/settings.php');
require(JIRAFEAU_ROOT . 'lib/functions.php');
require(JIRAFEAU_ROOT . 'lib/lang.php');
global $script_langages;
$script_langages = array('bash' => 'Bash');
/* Operations may take a long time.
* Be sure PHP's safe mode is off.
*/
@set_time_limit(0);
if ($_SERVER['REQUEST_METHOD'] == "GET" && count($_GET) == 0) {
require(JIRAFEAU_ROOT . 'lib/template/header.php');
check_errors($cfg);
if (has_error()) {
show_errors();
require(JIRAFEAU_ROOT . 'lib/template/footer.php');
exit;
} ?>
<div class="info">
<h2>Scripting interface</h2>
<p>This interface permits to script your uploads and downloads.</p>
<p>See <a href="https://gitlab.com/mojo42/Jirafeau/blob/master/script.php">source code</a> of this interface to get available calls :)</p>
<p>You may download a preconfigured <a href="script.php?lang=bash">Bash Script</a> to easily send to and get files from the API via command line.</p>
</div>
<br />
<?php
require(JIRAFEAU_ROOT . 'lib/template/footer.php');
exit;
}
/* Lets use interface now. */
header('Content-Type: text/plain; charset=utf-8');
check_errors($cfg);
if (has_error()) {
echo 'Error 1';
exit;
}
/* Upload file */
if (isset($_FILES['file']) && is_writable(VAR_FILES)
&& is_writable(VAR_LINKS)) {
if (isset($_POST['upload_password'])) {
if (!jirafeau_challenge_upload($cfg, get_ip_address($cfg), $_POST['upload_password'])) {
echo 'Error 3: Invalid password';
exit;
}
} else {
if (!jirafeau_challenge_upload($cfg, get_ip_address($cfg), null)) {
echo 'Error 2: No password nor allowed IP';
exit;
}
}
$key = '';
if (isset($_POST['key'])) {
$key = $_POST['key'];
}
$time = time();
if (!isset($_POST['time']) || !$cfg['availabilities'][$_POST['time']]) {
echo 'Error 4: The parameter time is invalid.';
exit;
} else {
switch ($_POST['time']) {
case 'minute':
$time += JIRAFEAU_MINUTE;
break;
case 'hour':
$time += JIRAFEAU_HOUR;
break;
case 'day':
$time += JIRAFEAU_DAY;
break;
case 'week':
$time += JIRAFEAU_WEEK;
break;
case 'month':
$time += JIRAFEAU_MONTH;
break;
case 'quarter':
$time += JIRAFEAU_QUARTER;
break;
case 'semester':
$time += JIRAFEAU_SEMESTER;
break;
case 'year':
$time += JIRAFEAU_YEAR;
break;
default:
$time = JIRAFEAU_INFINITY;
break;
}
}
// Check file size
if ($cfg['maximal_upload_size'] > 0 &&
$_FILES['file']['size'] > $cfg['maximal_upload_size'] * 1024 * 1024) {
echo 'Error 5: Your file exceeds the maximum authorized file size.';
exit;
}
// Check if one time download is enabled
if (!$cfg['one_time_download'] && isset($_POST['one_time_download'])) {
echo 'Error 26: One time download is disabled.';
exit;
}
if ($cfg['store_uploader_ip']) {
$ip = get_ip_address($cfg);
} else {
$ip = "";
}
$res = jirafeau_upload(
$_FILES['file'],
isset($_POST['one_time_download']),
$key,
$time,
$ip,
$cfg['enable_crypt'],
$cfg['link_name_length'],
$cfg['file_hash']
);
if (empty($res) || $res['error']['has_error']) {
echo 'Error 6 ' . $res['error']['why'];
exit;
}
/* Print direct link. */
echo $res['link'];
/* Print delete link. */
echo NL;
echo $res['delete_link'];
/* Print decrypt key. */
echo NL;
echo urlencode($res['crypt_key']);
} elseif (isset($_GET['h'])) {
$link_name = $_GET['h'];
$key = '';
if (isset($_POST['key'])) {
$key = $_POST['key'];
}
$d = '';
if (isset($_GET['d'])) {
$d = $_GET['d'];
}
if (!preg_match('/[0-9a-zA-Z_-]+$/', $link_name)) {
echo 'Error 7';
exit;
}
$link = jirafeau_get_link($link_name);
if (count($link) == 0) {
echo 'Error 8';
exit;
}
if (strlen($d) > 0 && $d == $link['link_code']) {
jirafeau_delete_link($link_name);
echo "Ok";
exit;
}
if ($link['time'] != JIRAFEAU_INFINITY && time() > $link['time']) {
jirafeau_delete_link($link_name);
echo 'Error 9';
exit;
}
if (strlen($link['key']) > 0 && md5($key) != $link['key']) {
sleep(2);
echo 'Error 10';
exit;
}
$p = s2p($link['hash']);
if (!file_exists(VAR_FILES . $p . $link['hash'])) {
echo 'Error 11';
exit;
}
/* Read file. */
header('Content-Length: ' . $link['file_size']);
header('Content-Type: ' . $link['mime_type']);
header('Content-Disposition: attachment; filename="' .
$link['file_name'] . '"');
$r = fopen(VAR_FILES . $p . $link['hash'], 'r');
while (!feof($r)) {
print fread($r, 1024);
}
fclose($r);
if ($link['onetime'] == 'O') {
jirafeau_delete_link($link_name);
}
exit;
} elseif (isset($_GET['get_capacity'])) {
echo jirafeau_get_max_upload_size_bytes();
} elseif (isset($_GET['get_maximal_upload_size'])) {
echo $cfg['maximal_upload_size'];
} elseif (isset($_GET['get_version'])) {
echo JIRAFEAU_VERSION;
} elseif (isset($_GET['lang'])) {
$l=$_GET['lang'];
if ($l == "bash") {
?>
#!/bin/bash
# This script has been auto-generated by Jirafeau but you can still edit options below.
# Config begin
proxy='' # Or set JIRAFEAU_PROXY.
url='<?php echo $cfg['web_root']; ?>' # Or set JIRAFEAU_URL.
time='<?php echo $cfg['availability_default']; ?>' # Or set JIRAFEAU_TIME.
one_time='' # Or set JIRAFEAU_ONE_TIME.
curl='' # Or set JIRAFEAU_CURL_PATH.
upload_password='' # Or set JIRAFEAU_UPLOAD_PASSWD
# Config end
if [ -n "$JIRAFEAU_PROXY" ]; then
proxy="$JIRAFEAU_PROXY"
fi
if [ -n "$JIRAFEAU_URL" ]; then
url="$JIRAFEAU_URL"
fi
if [ -z "$url" ]; then
echo "Please set url in script parameters or export JIRAFEAU_URL"
fi
if [ -n "$JIRAFEAU_TIME" ]; then
time="$JIRAFEAU_TIME"
fi
if [ -n "$JIRAFEAU_ONE_TIME" ]; then
one_time='1'
fi
if [ -n "$UPLOAD_PASSWD" ]; then
upload_password="$JIRAFEAU_UPLOAD_PASSWORD"
fi
if [ -z "$curl" ]; then
curl="$JIRAFEAU_CURL_PATH"
fi
if [ -z "$curl" ] && [ -e "/usr/bin/curl" ]; then
curl="/usr/bin/curl"
fi
if [ -z "$curl" ] && [ -e "/bin/curl.exe" ]; then
curl="/bin/curl.exe"
fi
if [ -z "$curl" ]; then
echo "Please set your curl binary path (by editing this script or export JIRAFEAU_CURL_PATH global variable)."
exit
fi
if [ -z "$2" ]; then
echo "Jirafeau Bash Script <?php echo JIRAFEAU_VERSION; ?>"
echo "--------------------------"
echo "Usage:"
echo " $0 OPTIONS"
echo
echo "Options:"
echo " $0 send FILE [PASSWORD]"
echo " $0 get URL [PASSWORD]"
echo " $0 delete URL"
echo
echo "Global variables to export:"
echo " JIRAFEAU_PROXY: Domain and port of proxy server, eg. »proxysever.example.com:3128«"
echo " JIRAFEAU_URL : URI to Jirafeau installation with trailing slash, eg. »https://example.com/jirafeau/«"
echo " JIRAFEAU_TIME : expiration time, eg. »minute«, »hour«, »day«, »week«, »month«, »quarter«, »semester«, »year« or »none«"
echo " JIRAFEAU_ONE_TIME : self-destroy after first download, eg. »1« to enable or »« (empty) to disable"
echo " JIRAFEAU_CURL : alternative path to curl binary"
echo " JIRAFEAU_UPLOAD_PASSWD : upload password"
exit 0
fi
if [ -n "$proxy" ]; then
proxy="-x $proxy"
fi
options=''
if [ -n "$one_time" ]; then
options="$options -F one_time_download=1"
fi
if [ -n "$upload_password" ]; then
options="$options -F upload_password=$upload_password"
fi
password=''
if [ -n "$3" ]; then
password="$3"
options="$options -F key=$password"
fi
apipage='script.php'
downloadpage='f.php'
if [ "$1" == "send" ]; then
if [ ! -f "$2" ]; then
echo "File \"$2\" does not exists."
exit
fi
# Ret result
res=$($curl -X POST --http1.0 $proxy $options \
-F "time=$time" \
-F "file=@$2" \
$url$apipage)
if [[ "$res" == Error* ]]; then
echo "Error while uploading."
echo $res
exit
fi
# Not using head or tail to minimise command dependencies
code=$(cnt=0; echo "$res" | while read l; do
if [[ "$cnt" == "0" ]]; then
echo "$l"
fi
cnt=$(( cnt + 1 ))
done)
del_code=$(cnt=0; echo "$res" | while read l; do
if [[ "$cnt" == "1" ]]; then
echo "$l"
fi
cnt=$(( cnt + 1 ))
done)
key_code=$(cnt=0; echo "$res" | while read l; do
if [[ "$cnt" == "2" ]]; then
echo "$l"
fi
cnt=$(( cnt + 1 ))
done)
echo
echo "Download page:"
if [[ $key_code ]]; then
echo " ${url}${downloadpage}?h=$code&k=$key_code"
else
echo " ${url}${downloadpage}?h=$code"
fi
echo "Direct download:"
if [[ $key_code ]]; then
echo " ${url}${downloadpage}?h=$code&k=$key_code&d=1"
else
echo " ${url}${downloadpage}?h=$code&d=1"
fi
echo "Delete link:"
echo " ${url}${downloadpage}?h=$code&d=$del_code"
echo
echo "Download via API:"
if [[ $key_code ]]; then
echo " ${0} get ${url}${apipage}?h=$code&k=$key_code [PASSWORD}"
else
echo " ${0} get ${url}${apipage}?h=$code [PASSWORD}"
fi
echo "Delete via API:"
echo " ${0} delete ${url}${downloadpage}?h=$code&d=$del_code"
elif [ "$1" == "get" ]; then
if [ -z "$password" ]; then
$curl $proxy -OJ "$2"
else
$curl $proxy -OJ -X POST -F key=$password "$2"
fi
elif [ "$1" == "delete" ]; then
$curl $proxy "$2"
fi
<?php
} else {
echo 'Error 12';
exit;
}
}
/* Initialize an asynchronous upload. */
elseif (isset($_GET['init_async'])) {
if (isset($_POST['upload_password'])) {
if (!jirafeau_challenge_upload($cfg, get_ip_address($cfg), $_POST['upload_password'])) {
echo 'Error 20: Invalid password';
exit;
}
} else {
if (!jirafeau_challenge_upload($cfg, get_ip_address($cfg), null)) {
echo 'Error 19: No password nor allowed IP';
exit;
}
}
if (!isset($_POST['filename'])) {
echo 'Error 21';
exit;
}
$type = '';
if (isset($_POST['type'])) {
$type = $_POST['type'];
}
$key = '';
if (isset($_POST['key'])) {
$key = $_POST['key'];
}
// Check if one time download is enabled
if (!$cfg['one_time_download'] && isset($_POST['one_time_download'])) {
echo 'Error 26: One time download is disabled.';
exit;
}
$time = time();
if (!isset($_POST['time']) || !$cfg['availabilities'][$_POST['time']]) {
echo 'Error 22';
exit;
} else {
switch ($_POST['time']) {
case 'minute':
$time += JIRAFEAU_MINUTE;
break;
case 'hour':
$time += JIRAFEAU_HOUR;
break;
case 'day':
$time += JIRAFEAU_DAY;
break;
case 'week':
$time += JIRAFEAU_WEEK;
break;
case 'month':
$time += JIRAFEAU_MONTH;
break;
case 'quarter':
$time += JIRAFEAU_QUARTER;
break;
case 'semester':
$time += JIRAFEAU_SEMESTER;
break;
case 'year':
$time += JIRAFEAU_YEAR;
break;
default:
$time = JIRAFEAU_INFINITY;
break;
}
}
if ($cfg['store_uploader_ip']) {
$ip = get_ip_address($cfg);
} else {
$ip = "";
}
echo jirafeau_async_init(
$_POST['filename'],
$type,
isset($_POST['one_time_download']),
$key,
$time,
$ip
);
}
/* Continue an asynchronous upload. */
elseif (isset($_GET['push_async'])) {
if ((!isset($_POST['ref']))
|| (!isset($_FILES['data']))
|| (!isset($_POST['code']))) {
echo 'Error 23';
} else {
echo jirafeau_async_push(
$_POST['ref'],
$_FILES['data'],
$_POST['code'],
$cfg['maximal_upload_size']
);
}
}
/* Finalize an asynchronous upload. */
elseif (isset($_GET['end_async'])) {
if (!isset($_POST['ref'])
|| !isset($_POST['code'])) {
echo 'Error 24';
} else {
echo jirafeau_async_end($_POST['ref'], $_POST['code'], $cfg['enable_crypt'], $cfg['link_name_length'], $cfg['file_hash']);
}
} else {
echo 'Error 25';
}
exit;
?>

79
src/Jirafeau/settings.php Normal file
View File

@ -0,0 +1,79 @@
<?php
/*
* Jirafeau, your web file repository
* Copyright (C) 2008 Julien "axolotl" BERNARD <axolotl@magieeternelle.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
global $cfg;
// Read config files
require(JIRAFEAU_ROOT . 'lib/config.original.php');
if (file_exists(JIRAFEAU_ROOT . 'lib/config.local.php')) {
// read local copy and merge with original values
$cfgOriginal = $cfg;
require(JIRAFEAU_ROOT . 'lib/config.local.php');
$cfg = array_merge($cfgOriginal, $cfg);
unset($cfgOriginal);
}
// Setup debug mode
if ($cfg['debug'] === true) {
@error_reporting(E_ALL);
} else {
@error_reporting(0);
}
// Set constants
/* Jirafeau package */
define('JIRAFEAU_PACKAGE', 'Jirafeau');
define('JIRAFEAU_VERSION', '4.3.0');
/* Directories. */
define('VAR_FILES', $cfg['var_root'] . 'files/');
define('VAR_LINKS', $cfg['var_root'] . 'links/');
define('VAR_ASYNC', $cfg['var_root'] . 'async/');
// helping variable to build absolute link to
// root of the domain without handling the URL scheme
$absPrefix = parse_url($cfg['web_root'], PHP_URL_PATH);
if (true === empty($absPrefix)) {
// fallback if installation isnt done yet: relative links to same level on the current page
$absPrefix = './';
}
define('JIRAFEAU_ABSPREFIX', $absPrefix);
/* Useful constants. */
if (!defined('NL')) {
define('NL', "\n");
}
if (!defined('QUOTE')) {
define('QUOTE', "'");
}
define('JIRAFEAU_INFINITY', -1);
define('JIRAFEAU_MINUTE', 60); // 60
define('JIRAFEAU_HOUR', 3600); // JIRAFEAU_MINUTE * 60
define('JIRAFEAU_DAY', 86400); // JIRAFEAU_HOUR * 24
define('JIRAFEAU_WEEK', 604800); // JIRAFEAU_DAY * 7
define('JIRAFEAU_MONTH', 2592000); // JIRAFEAU_DAY * 30
define('JIRAFEAU_QUARTER', 7776000); // JIRAFEAU_DAY * 90
define('JIRAFEAU_SEMESTER', 110678400); // JIRAFEAU_DAY * 183
define('JIRAFEAU_YEAR', 31536000); // JIRAFEAU_DAY * 365
// set UTC as default timezone for all date/time functions
date_default_timezone_set('UTC');

View File

@ -184,7 +184,7 @@ MODE=$(curl "${JIRAFEAU_LOCAL}/a.php?m=${MAIL_SOURCE}" 2>/dev/null )
TRACK=$(curl "${JIRAFEAU_LOCAL}/a.php?r=${MAIL_SOURCE}" 2>/dev/null ) TRACK=$(curl "${JIRAFEAU_LOCAL}/a.php?r=${MAIL_SOURCE}" 2>/dev/null )
[[ "${TRACK}" =~ ^(|0|1|false|true|FALSE|TRUE|on|off)$ ]] || TRACK="${DEFAULT_TRACK}" [[ "${TRACK}" =~ ^(|0|1|false|true|FALSE|TRUE|on|off)$ ]] || TRACK="${DEFAULT_TRACK}"
PERIOD=$(curl "${JIRAFEAU_LOCAL}/a.php?p=${MAIL_SOURCE}" 2>/dev/null ) PERIOD=$(curl "${JIRAFEAU_LOCAL}/a.php?p=${MAIL_SOURCE}" 2>/dev/null )
[[ "${PERIOD}" =~ ^(minute|hour|day|week|month|quarter)$ ]] || PERIOD="${DEFAULT_PERIOD}" [[ "${PERIOD}" =~ ^(minute|hour|day|week|month|quarter|semester)$ ]] || PERIOD="${DEFAULT_PERIOD}"
LOG_FIC "${NL}" \ LOG_FIC "${NL}" \
" MAIL_SOURCE : ${YELLOW}${MAIL_SOURCE}${NC}${NL}" \ " MAIL_SOURCE : ${YELLOW}${MAIL_SOURCE}${NC}${NL}" \

View File

@ -48,6 +48,8 @@ CYAN='\e[0;36m'
NC='\e[0m' # No Color NC='\e[0m' # No Color
NL=' NL='
' '
PERIODE="month"
######################################## ########################################
LOG () { LOG () {
echo -e "$1" 1>&2 echo -e "$1" 1>&2
@ -139,7 +141,7 @@ cat "${TMP_DIR}/url-to-refresh.txt" | grep "${JIRAFEAU_URL}" | while read REMOTE
REMOTE_REF=$(echo "${REMOTE_LINK}" | sed -e 's/.*h=\([^&]*\).*/\1/' -e 's/.*http.*//') REMOTE_REF=$(echo "${REMOTE_LINK}" | sed -e 's/.*h=\([^&]*\).*/\1/' -e 's/.*http.*//')
[ -z "${REMOTE_REF}" ] && continue [ -z "${REMOTE_REF}" ] && continue
LOG " - ${BLUE}update ${REMOTE_REF}${NC}" LOG " - ${BLUE}update ${REMOTE_REF}${NC}"
curlJirafeauUpdate "month" "${REMOTE_REF}" curlJirafeauUpdate "${PERIODE}" "${REMOTE_REF}"
echo "old: ${REMOTE_REF} ${REMOTE_KEY}" >> "${TMP_DIR}/archive-content.txt" echo "old: ${REMOTE_REF} ${REMOTE_KEY}" >> "${TMP_DIR}/archive-content.txt"
done done
@ -168,7 +170,7 @@ cat "${TMP_DIR}/PJ-name.txt" | {
LOG " - ${BLUE}find ${ATTACH_NAME} / (${ATTACH_CONTENT_TYPE}) / ${ATTACH_MEDIA} ${NC}" LOG " - ${BLUE}find ${ATTACH_NAME} / (${ATTACH_CONTENT_TYPE}) / ${ATTACH_MEDIA} ${NC}"
PASSWORD=$(apg -n 1 -m 12 -M cln) PASSWORD=$(apg -n 1 -m 12 -M cln)
PASSWORD_MD5=$(echo -n ${PASSWORD} | ${MD5_CMD} | cut -d \ -f 1) PASSWORD_MD5=$(echo -n ${PASSWORD} | ${MD5_CMD} | cut -d \ -f 1)
curlJirafeauSend "month" "${ATTACH_MEDIA}" "${ATTACH_CONTENT_TYPE}" "${ATTACH_NAME}" "${PASSWORD}" > "${TMP_DIR}/one.txt" curlJirafeauSend "${PERIODE}" "${ATTACH_MEDIA}" "${ATTACH_CONTENT_TYPE}" "${ATTACH_NAME}" "${PASSWORD}" > "${TMP_DIR}/one.txt"
cat "${TMP_DIR}/one.txt" | { cat "${TMP_DIR}/one.txt" | {
read JIR_TOKEN read JIR_TOKEN
@ -192,7 +194,7 @@ cat "${TMP_DIR}/PJ-name.txt" | {
if [ "${NB_ATTACH}" -gt 1 ]; then if [ "${NB_ATTACH}" -gt 1 ]; then
PASSWORD=$(apg -n 1 -m 12 -M cln) PASSWORD=$(apg -n 1 -m 12 -M cln)
PASSWORD_MD5=$(echo -n ${PASSWORD} | ${MD5_CMD} | cut -d \ -f 1) PASSWORD_MD5=$(echo -n ${PASSWORD} | ${MD5_CMD} | cut -d \ -f 1)
curlJirafeauSend "month" "${TMP_DIR}/archive-content.txt" "text/kaz_email_archive" "archive_content" "${PASSWORD}" > "${TMP_DIR}/one.txt" || exit 1 curlJirafeauSend "${PERIODE}" "${TMP_DIR}/archive-content.txt" "text/kaz_email_archive" "archive_content" "${PASSWORD}" > "${TMP_DIR}/one.txt" || exit 1
cat "${TMP_DIR}/one.txt" | { cat "${TMP_DIR}/one.txt" | {
read JIR_TOKEN read JIR_TOKEN
read JIR_CODE read JIR_CODE