First commit

This commit is contained in:
Nathan
2026-09-18 20:29:17 -06:00
commit 3b09abe571
2840 changed files with 467153 additions and 0 deletions
@@ -0,0 +1,410 @@
(function($, exports) {
"use strict";
/**
* Base LocalStorage cache
*
* @param options {object}
* - key (required) identifier of the collection
* - serverId (recommended) identifier of the Piwigo instance
* - serverKey (required) state of collection server-side
* - lifetime (optional) cache lifetime in seconds
* - loader (required) function called to fetch data, takes a callback as first argument
* which must be called with the loaded date
*/
var LocalStorageCache = function(options) {
this._init(options);
};
/*
* Constructor (deported for easy inheritance)
*/
LocalStorageCache.prototype._init = function(options) {
this.key = options.key + '_' + options.serverId;
this.serverKey = options.serverKey;
this.lifetime = options.lifetime ? options.lifetime*1000 : 3600*1000;
this.loader = options.loader;
this.storage = window.localStorage;
this.ready = !!this.storage;
};
/*
* Get the cache content
* @param callback {function} called with the data as first parameter
*/
LocalStorageCache.prototype.get = function(callback) {
var now = new Date().getTime(),
that = this;
if (this.ready && this.storage[this.key] != undefined) {
var cache = JSON.parse(this.storage[this.key]);
if (now - cache.timestamp <= this.lifetime && cache.key == this.serverKey) {
callback(cache.data);
return;
}
}
this.loader(function(data) {
that.set.call(that, data);
callback(data);
});
};
/*
* Manually set the cache content
* @param data {mixed}
*/
LocalStorageCache.prototype.set = function(data) {
try {
if (this.ready) {
this.storage[this.key] = JSON.stringify({
timestamp: new Date().getTime(),
key: this.serverKey,
data: data
});
}
} catch (e) {
console.log("Local storage error:");
console.log(e);
console.log("Use of direct result from Piwigo API.");
}
};
/*
* Manually clear the cache
*/
LocalStorageCache.prototype.clear = function() {
if (this.ready) {
this.storage.removeItem(this.key);
}
};
/**
* Abstract class containing common initialization code for selectize
*/
var AbstractSelectizer = function(){};
AbstractSelectizer.prototype = new LocalStorageCache({});
/*
* Load Selectize with cache content
* @param $target {jQuery} may have some data attributes (create, default, value)
* @param options {object}
* - value (optional) list of preselected items (ids, or objects with "id" attribute")
* - default (optional) default value which will be forced if the select is emptyed
* - create (optional) allow item user creation
* - filter (optional) function called for each select before applying the data
* takes two parameters: cache data, options
* must return new data
*/
AbstractSelectizer.prototype._selectize = function($target, globalOptions) {
$target.data('cache', this);
this.get(function(data) {
$target.each(function() {
var filtered, value, defaultValue,
options = $.extend({}, globalOptions);
// apply filter function
if (options.filter != undefined) {
filtered = options.filter.call(this, data, options);
}
else {
filtered = data;
}
this.selectize.settings.maxOptions = filtered.length + 100;
// active creation mode
if (this.hasAttribute('data-create')) {
options.create = true;
}
this.selectize.settings.create = !!options.create;
// load options
this.selectize.load(function(callback) {
if ($.isEmptyObject(this.options)) {
callback(filtered);
}
});
// load items
if ((value = $(this).data('value'))) {
options.value = value;
}
if (options.value != undefined) {
$.each(value, $.proxy(function(i, cat) {
if ($.isNumeric(cat))
this.selectize.addItem(cat);
else
this.selectize.addItem(cat.id);
}, this));
}
// set default
if ((defaultValue = $(this).data('default'))) {
options.default = defaultValue;
}
if (options.default == 'first') {
options.default = filtered[0] ? filtered[0].id : undefined;
}
if (options.default != undefined) {
// add default item
if (this.selectize.getValue() == '') {
this.selectize.addItem(options.default);
}
// if multiple: prevent item deletion
if (this.multiple) {
this.selectize.getItem(options.default).find('.remove').hide();
this.selectize.on('item_remove', function(id) {
if (id == options.default) {
this.addItem(id);
this.getItem(id).find('.remove').hide();
}
});
}
// if single: restore default on blur
else {
this.selectize.on('dropdown_close', function() {
if (this.getValue() == '') {
this.addItem(options.default);
}
});
}
}
});
});
};
// redefine Selectize templates without escape
AbstractSelectizer.getRender = function(field_label, lang) {
lang = lang || { 'Add': 'Add' };
return {
'option': function(data, escape) {
return '<div class="option">' + data[field_label] + '</div>';
},
'item': function(data, escape) {
return '<div class="item">' + data[field_label] + '</div>';
},
'option_create': function(data, escape) {
return '<div class="create">' + lang['Add'] + ' <strong>' + data.input + '</strong>&hellip;</div>';
}
};
};
/**
* Special LocalStorage for admin categories list
*
* @param options {object}
* - serverId (recommended) identifier of the Piwigo instance
* - serverKey (required) state of collection server-side
* - rootUrl (required) used for WS call
*/
var CategoriesCache = function(options) {
options.key = 'categoriesAdminList';
options.loader = function(callback) {
$.getJSON(options.rootUrl + 'ws.php?format=json&method=pwg.categories.getAdminList', function(data) {
var cats = data.result.categories.map(function(c, i) {
c.pos = i;
delete c['comment'];
delete c['uppercats'];
return c;
});
callback(cats);
});
};
this._init(options);
};
CategoriesCache.prototype = new AbstractSelectizer();
/*
* Init Selectize with cache content
* @see AbstractSelectizer._selectize
*/
CategoriesCache.prototype.selectize = function($target, options) {
options = options || {};
$target.selectize({
valueField: 'id',
labelField: 'fullname',
sortField: 'pos',
searchField: ['fullname'],
plugins: ['remove_button'],
render: AbstractSelectizer.getRender('fullname', options.lang)
});
this._selectize($target, options);
};
/**
* Special LocalStorage for admin tags list
*
* @param options {object}
* - serverId (recommended) identifier of the Piwigo instance
* - serverKey (required) state of collection server-side
* - rootUrl (required) used for WS call
*/
var TagsCache = function(options) {
options.key = 'tagsAdminList';
options.loader = function(callback) {
$.getJSON(options.rootUrl + 'ws.php?format=json&method=pwg.tags.getAdminList', function(data) {
var tags = data.result.tags.map(function(t) {
t.id = '~~' + t.id + '~~';
delete t['url_name'];
delete t['lastmodified'];
return t;
});
callback(tags);
});
};
this._init(options);
};
TagsCache.prototype = new AbstractSelectizer();
/*
* Init Selectize with cache content
* @see AbstractSelectizer._selectize
*/
TagsCache.prototype.selectize = function($target, options) {
options = options || {};
$target.selectize({
valueField: 'id',
labelField: 'name',
sortField: 'name',
searchField: ['name'],
plugins: ['remove_button'],
render: AbstractSelectizer.getRender('name', options.lang)
});
this._selectize($target, options);
};
/**
* Special LocalStorage for admin groups list
*
* @param options {object}
* - serverId (recommended) identifier of the Piwigo instance
* - serverKey (required) state of collection server-side
* - rootUrl (required) used for WS call
*/
var GroupsCache = function(options) {
options.key = 'groupsAdminList';
options.loader = function(callback) {
$.getJSON(options.rootUrl + 'ws.php?format=json&method=pwg.groups.getList&per_page=9999', function(data) {
var groups = data.result.groups.map(function(g) {
delete g['lastmodified'];
return g;
});
callback(groups);
});
};
this._init(options);
};
GroupsCache.prototype = new AbstractSelectizer();
/*
* Init Selectize with cache content
* @see AbstractSelectizer._selectize
*/
GroupsCache.prototype.selectize = function($target, options) {
options = options || {};
$target.selectize({
valueField: 'id',
labelField: 'name',
sortField: 'name',
searchField: ['name'],
plugins: ['remove_button'],
render: AbstractSelectizer.getRender('name', options.lang)
});
this._selectize($target, options);
};
/**
* Special LocalStorage for admin users list
*
* @param options {object}
* - serverId (recommended) identifier of the Piwigo instance
* - serverKey (required) state of collection server-side
* - rootUrl (required) used for WS call
*/
var UsersCache = function(options) {
options.key = 'usersAdminList';
options.loader = function(callback) {
var users = [];
// recursive loader
(function load(page){
jQuery.getJSON(options.rootUrl + 'ws.php?format=json&method=pwg.users.getList&display=username&per_page=9999&page='+ page, function(data) {
users = users.concat(data.result.users);
if (data.result.paging.count == data.result.paging.per_page) {
load(++page);
}
else {
callback(users);
}
});
}(0));
};
this._init(options);
};
UsersCache.prototype = new AbstractSelectizer();
/*
* Init Selectize with cache content
* @see AbstractSelectizer._selectize
*/
UsersCache.prototype.selectize = function($target, options) {
options = options || {};
$target.selectize({
valueField: 'id',
labelField: 'username',
sortField: 'username',
searchField: ['username'],
plugins: ['remove_button'],
render: AbstractSelectizer.getRender('username', options.lang)
});
this._selectize($target, options);
};
/**
* Expose classes in global scope
*/
exports.LocalStorageCache = LocalStorageCache;
exports.CategoriesCache = CategoriesCache;
exports.TagsCache = TagsCache;
exports.GroupsCache = GroupsCache;
exports.UsersCache = UsersCache;
}(jQuery, window));
@@ -0,0 +1,122 @@
jQuery.fn.pwgAddAlbum = function(options) {
options = options || {};
var $popup = jQuery('#addAlbumForm'),
$albumParent = $popup.find('[name="category_parent"]')
$button = jQuery(this),
$target = jQuery('[name="'+ $button.data('addAlbum') +'"]'),
cache = $target.data('cache');
console.log(cache);
if ($target[0] && !$target[0].selectize) {
jQuery.error('pwgAddAlbum: target must use selectize');
}
if (!cache) {
jQuery.error('pwgAddAlbum: missing categories cache');
}
function init() {
$popup.data('init', true);
cache.selectize($albumParent, {
'default': 0,
'filter': function(categories) {
categories.push({
id: 0,
fullname: '------------',
global_rank: 0
});
if (options.filter) {
categories = options.filter.call(this, categories);
}
return categories;
}
});
$popup.find('form').on('submit', function(e) {
e.preventDefault();
var parent_id = $albumParent.val(),
name = $popup.find('[name=category_name]').val();
if (!name) {
jQuery('#categoryNameError').css('visibility', 'visible');
return;
}
jQuery('#categoryNameError').css('visibility', 'hidden');
jQuery.ajax({
url: 'ws.php?format=json',
type: 'POST',
dataType: 'json',
data: {
method: 'pwg.categories.add',
parent: parent_id,
name: name
},
beforeSend: function() {
jQuery('#albumCreationLoading').css('display', 'inline-block');
jQuery('.albumCreationButton').hide();
},
success: function(data) {
jQuery('#albumCreationLoading').hide();
jQuery('.albumCreationButton').show();
$button.colorbox.close();
var newAlbum = {
id: data.result.id,
name: name,
fullname: name,
global_rank: '0',
dir: null,
nb_images: 0,
pos: 0
};
var parentSelectize = $albumParent[0].selectize;
if (parent_id != 0) {
var parent = parentSelectize.options[parent_id];
newAlbum.fullname = parent.fullname + ' / ' + newAlbum.fullname;
newAlbum.global_rank = parent.global_rank + '.1';
newAlbum.pos = parent.pos + 1;
}
var targetSelectize = $target[0].selectize;
targetSelectize.addOption(newAlbum);
targetSelectize.setValue(newAlbum.id);
parentSelectize.addOption(newAlbum);
if (options.afterSelect) {
options.afterSelect();
}
},
error: function(XMLHttpRequest, textStatus, errorThrows) {
jQuery('#albumCreationLoading').hide();
alert(errorThrows);
}
});
});
}
this.colorbox({
inline: true,
href: '#addAlbumForm',
width: 650, height: 'auto',
onComplete: function() {
if (!$popup.data('init')) {
init();
}
jQuery('#categoryNameError').css('visibility','hidden');
$popup.find('[name=category_name]').val('').focus();
$albumParent[0].selectize.setValue($target.val() || 0);
}
});
return this;
};
@@ -0,0 +1,736 @@
let activeAlbumSelector = null;
$(window).on('keypress', function(e) {
const haveAlbumSelector = $('#addLinkedAlbum').is(':visible');
if (haveAlbumSelector && e.key === "Enter") {
e.preventDefault();
}
});
/**
* Album selector instance
* @param {Array} selectedCategoriesIds - Array of IDs for elements already selected.
* @param {Function} selectAlbum - Function to handle the selection of an album.
* @param {Function} removeSelectedAlbum - Function to handle the removal of a selected album.
* @param {Boolean} showRootButton - Flag to indicate whether to show the "root" button.
* @param {Boolean} adminMode - Flag to indicate if the selector is in admin mode.
* @param {Number} limitParam - Maximum number of results to retrieve.
* @param {Number} currentAlbumId - ID of the currently selected album. (Only if you use ShowRootButton to keep one album always selected)
* @param {String} modalTitle - Custom title for the album selector modal.
* @param {String} modalSearchPlaceholder - Custom placeholder text for the search input in the modal.
*/
class AlbumSelector {
#in_admin_mode;
#methodPwg;
#limitParam;
#isAlbumCreationChecked;
#selectAlbum;
#removeSelectedAlbum;
#currentSelectedId;
#searchCat;
#cats;
#selected_categories;
#show_root_btn;
#put_to_root;
#current_cat;
#title;
#searchPlaceholder;
#loading_add;
/**
* Selector for AlbumSelector
*/
static selectors = {
addLinkedAlbum: $('#addLinkedAlbum'),
closeAlbumPopIn: $('#closeAlbumPopIn'),
searchInput: $('#search-input-ab'),
searchResult: $('#searchResult'),
limitReached: $('.limitReached'),
iconCancelInput: $('.search-cancel-linked-album'),
relatedCategoriesDom: $('.related-categories-container .breadcrumb-item .remove-item'),
iconSearchingSpin: $('.searching'),
albumSelector: $('#linkedAlbumSelector'),
albumCreate: $('#linkedAlbumCreate'),
albumCheckBox: $('#album-create-check'),
linkedAddAlbum: $('#linkedAddAlbum'),
linkedModalTitle: $('#linkedModalTitle'),
linkedAlbumSwitch: $('#linkedAlbumSwitch'),
linkedAlbumSubTitle: $('#linkedAlbumSubtitle'),
linkedAddNewAlbum: $('#linkedAddNewAlbum'),
linkedAlbumInput: $('#linkedAlbumInput'),
putToRoot: $('.put-to-root-container'),
linkedAlbumCancel: $('#linkedAlbumCancel'),
linkedAddAlbumErrors: $('#linkedAddAlbumErrors'),
addAlbumErrors: $('.AddAlbumErrors'),
putToRootBtn: $('#put-to-root'),
linkedAlbumPopInContainer: $('.linkedAlbumPopInContainer'),
};
constructor({
selectedCategoriesIds=[],
selectAlbum=() => {},
removeSelectedAlbum=() => {},
showRootButton=false,
adminMode=false,
limitParam=50,
currentAlbumId=0,
modalTitle='',
modalSearchPlaceholder='',
}) {
this.instanceId = `AlbumSelector-${Math.random().toString(36).substring(2, 9)}`;
this.#in_admin_mode = adminMode;
this.#methodPwg = adminMode ? 'pwg.categories.getAdminList' : 'pwg.categories.getList';
this.#limitParam = limitParam;
this.#selected_categories = adminMode ? [...selectedCategoriesIds] : selectedCategoriesIds.map(String);
this.#isAlbumCreationChecked = false;
this.#cats = {};
this.#searchCat = {};
this.#selectAlbum = (args) => selectAlbum.call(
null,
{
...args,
newSelectedAlbum: this.#newSelectedAlbum.bind(this),
addSelectedAlbum: this.#addSelectedAlbum.bind(this),
getSelectedAlbum: this.get_selected_albums.bind(this),
}
);
this.#removeSelectedAlbum = (args) => removeSelectedAlbum.call(
null,
{
...args,
getSelectedAlbum: this.get_selected_albums.bind(this),
}
);
this.#currentSelectedId = '';
this.#show_root_btn = showRootButton;
this.#put_to_root = false;
this.#current_cat = currentAlbumId;
this.#title = modalTitle === '' ? str_album_modal_title : modalTitle;
this.#searchPlaceholder = modalSearchPlaceholder === '' ?
str_album_modal_placeholder : modalSearchPlaceholder;
this.#loading_add = false;
this.#init();
}
#init() {
// console.log('init id:', activeAlbumSelector.instanceId);
if (this.#in_admin_mode && this.#show_root_btn) {
AlbumSelector.selectors.linkedAlbumPopInContainer.addClass('big');
}
if (!this.#show_root_btn) {
AlbumSelector.selectors.putToRoot.remove();
}
if (!this.#in_admin_mode) {
AlbumSelector.selectors.albumCreate.remove();
AlbumSelector.selectors.linkedAlbumSwitch.remove();
}
}
/*-----------
Public method
-----------*/
open() {
if (activeAlbumSelector && activeAlbumSelector !== this) {
activeAlbumSelector.close();
}
activeAlbumSelector = this;
this.#open_album_selector();
}
close() {
if (activeAlbumSelector === this) {
activeAlbumSelector = null;
}
this.#close_album_selector();
}
remove_selected_album(id) {
if (this.#selected_categories.includes(id)) {
const cat_to_remove_index = this.#selected_categories.indexOf(id);
if (cat_to_remove_index > -1) {
this.#selected_categories.splice(cat_to_remove_index, 1);
}
}
this.#removeSelectedAlbum({ id_album: id });
}
get_selected_albums() {
return [...this.#selected_categories];
}
select_album(id) {
this.#selected_categories.push(id.toString());
}
resetAll() {
this.#selected_categories = [];
if (this.#in_admin_mode) {
this.#hard_reset_album_selector();
} else {
this.#reset_album_selector();
}
}
hardUpdate(cats) {
this.#selected_categories = cats;
}
/*---------------------
in selectAlbum() method
---------------------*/
#newSelectedAlbum() {
this.#selected_categories = this.#show_root_btn && this.#put_to_root
? ['0']
: [this.#currentSelectedId];
}
#addSelectedAlbum() {
this.#selected_categories.push(this.#currentSelectedId);
}
/*----------
Event method
----------*/
#loadGeneralEvent() {
const instanceAb = `.${this.instanceId}`;
// event close album selector
AlbumSelector.selectors.closeAlbumPopIn.off(`click${instanceAb}`).on(`click${instanceAb}`, () => {
this.#close_album_selector();
});
// event escape album selector
$(document).off(`keyup${instanceAb}`).on(`keyup${instanceAb}`, (e) => {
if (e.key === "Escape" && AlbumSelector.selectors.addLinkedAlbum.is(":visible")) {
this.#close_album_selector();
}
if (e.key === 'Enter' && AlbumSelector.selectors.addLinkedAlbum.is(":visible")) {
if ($('#linkedAddNewAlbum').is(':visible')) {
AlbumSelector.selectors.linkedAddNewAlbum.trigger(`click${instanceAb}`);
}
}
});
// event empty search input
if (AlbumSelector.selectors.iconCancelInput.length) {
AlbumSelector.selectors.iconCancelInput.off(`click${instanceAb}`).on(`click${instanceAb}`, () => {
this.#reset_search_input(true);
});
}
// event perform search
AlbumSelector.selectors.searchInput.off(`keyup${instanceAb}`).on(`keyup${instanceAb}`, (e) => {
const searchValue = AlbumSelector.selectors.searchInput.val();
if (searchValue.length > 0) {
AlbumSelector.selectors.iconCancelInput.show();
} else {
AlbumSelector.selectors.iconCancelInput.hide();
}
this.#perform_albums_search(searchValue);
});
// event in admin mode
if (this.#in_admin_mode) {
AlbumSelector.selectors.albumCheckBox.off(`change${instanceAb}`).on(`change${instanceAb}`, (e) => {
this.#isAlbumCreationChecked = $(e.currentTarget).is(':checked');
this.#switch_album_creation();
});
}
// event put root btn
if (this.#show_root_btn) {
AlbumSelector.selectors.putToRootBtn.off(`click${instanceAb}`).on(`click${instanceAb}`, (e) => {
if (!this.#selected_categories.includes('0')) {
const curr = $(e.currentTarget);
curr.addClass('notClickable');
this.#put_to_root = true;
this.#selectAlbum({ album: {id: 0, root: str_root} });
this.#close_album_selector();
}
});
}
}
#loadPickAlbumEvent() {
const instanceAb = `.${this.instanceId}`;
if (this.#isAlbumCreationChecked) {
$('.prefill-results-item').off(`click${instanceAb}`).on(`click${instanceAb}`, (e) => {
const curr = $(e.currentTarget);
const cat_id = curr.attr('id');
const cat = this.#cats[cat_id];
this.#switch_album_view(cat);
});
} else {
$('.prefill-results-item.available').off(`click${instanceAb}`).on(`click${instanceAb}`, (e) => {
const curr = $(e.currentTarget);
const cat_id = curr.attr('id');
const cat = this.#cats[cat_id];
this.#currentSelectedId = cat.id;
this.#selectAlbum({ album: cat });
this.#close_album_selector();
});
}
}
#loadSubCatEvent() {
const instanceAb = `.${this.instanceId}`;
$('.display-subcat').off(`click${instanceAb}`).on(`click${instanceAb}`, (e) => {
const curr = e.currentTarget;
const cat_id = $(curr).prop('id');
const cat = this.#cats[cat_id];
if ($(curr).hasClass('open')) {
$(curr).removeClass('open');
$("#subcat-" + cat.id).fadeOut();
} else if ($("#subcat-" + cat.id).length) {
$(curr).addClass('open');
$("#subcat-" + cat.id).fadeIn();
} else {
$("#" + cat_id + ".display-subcat").removeClass('gallery-icon-up-open').addClass('gallery-icon-spin6 animate-spin');
$("#" + cat_id + ".search-result-item").after(`<div id="subcat-${cat_id}" class="search-result-subcat-item"></div>`);
this.#prefill_search_subcats(cat_id).then(() => {
$("#" + cat_id + ".display-subcat").removeClass('gallery-icon-spin6 animate-spin').addClass('gallery-icon-up-open');
$(curr).addClass('open');
$("#subcat-" + cat.id).fadeIn();
});
}
});
}
#loadFillResultEvent(tempSelect) {
const instanceAb = `.${this.instanceId}`;
AlbumSelector.selectors.searchResult.find('.search-result-item').off(`click${instanceAb}`).on(`click${instanceAb}`, (e) => {
const curr = $(e.currentTarget);
const cat_id = curr.attr('id');
const cat = this.#searchCat[cat_id];
const formated_cat_id = this.#in_admin_mode ? cat.id : String(cat.id);
if (!tempSelect.includes(formated_cat_id)) {
this.#currentSelectedId = cat.id;
this.#selectAlbum({ album: cat });
this.#close_album_selector();
}
});
}
/*--------------
General method
--------------*/
#setActive() {
if (activeAlbumSelector && activeAlbumSelector !== this) {
activeAlbumSelector.close();
}
activeAlbumSelector = this;
}
#open_album_selector() {
this.#setActive();
this.#loadGeneralEvent();
if (this.#in_admin_mode) {
this.#hard_reset_album_selector();
} else {
this.#reset_album_selector();
}
if (this.#show_root_btn && !this.#selected_categories.includes('0')) {
AlbumSelector.selectors.putToRootBtn.removeClass('notClickable');
} else {
AlbumSelector.selectors.putToRootBtn.addClass('notClickable');
}
AlbumSelector.selectors.linkedModalTitle.html(this.#title);
AlbumSelector.selectors.searchInput.attr('placeholder', this.#searchPlaceholder);
AlbumSelector.selectors.addLinkedAlbum.fadeIn();
}
#close_album_selector() {
this.#cats = {};
this.#searchCat = {};
this.#currentSelectedId = '';
this.#put_to_root = false;
this.#loading_add = false;
this.#destroyEvent();
AlbumSelector.selectors.addLinkedAlbum.fadeOut();
}
#reset_album_selector() {
this.#prefill_search();
this.#reset_search_input(false);
// AlbumSelector.selectors.searchInput.val('');
// // AlbumSelector.selectors.searchInput.trigger("input");
AlbumSelector.selectors.limitReached.html(str_no_search_in_progress);
AlbumSelector.selectors.albumSelector.show();
}
#hard_reset_album_selector() {
AlbumSelector.selectors.albumCreate.hide();
this.#hide_new_album_error();
this.#reset_album_selector();
AlbumSelector.selectors.linkedAlbumInput.val('');
if (AlbumSelector.selectors.albumCheckBox.is(':checked')) {
AlbumSelector.selectors.albumCheckBox.trigger('click');
}
AlbumSelector.selectors.searchResult.show();
AlbumSelector.selectors.linkedAlbumSwitch.show();
}
#reset_search_input(prefill) {
AlbumSelector.selectors.searchInput.val('');
AlbumSelector.selectors.limitReached.show().html(str_no_search_in_progress);
AlbumSelector.selectors.searchResult.empty();
if(prefill) {
this.#prefill_search();
}
}
#switch_album_creation() {
this.#reset_album_selector();
const instanceAb = `.${this.instanceId}`;
if (this.#isAlbumCreationChecked) {
if (AlbumSelector.selectors.putToRoot.length) {
AlbumSelector.selectors.putToRoot.hide();
}
AlbumSelector.selectors.linkedModalTitle.hide();
AlbumSelector.selectors.linkedModalTitle.html(str_create_and_select);
AlbumSelector.selectors.linkedAddAlbum.show();
AlbumSelector.selectors.linkedModalTitle.fadeIn();
AlbumSelector.selectors.linkedAddAlbum.off(`click${instanceAb}`).on(`click${instanceAb}`, () => {
this.#switch_album_view('root');
});
} else {
if (AlbumSelector.selectors.putToRoot.length) {
AlbumSelector.selectors.putToRoot.fadeIn();
}
AlbumSelector.selectors.linkedModalTitle.hide();
AlbumSelector.selectors.linkedModalTitle.html(this.#title);
AlbumSelector.selectors.linkedModalTitle.fadeIn();
AlbumSelector.selectors.linkedAddAlbum.hide();
AlbumSelector.selectors.linkedAddAlbum.off('click');
}
}
#switch_album_view(cat) {
const instanceAb = `.${this.instanceId}`;
AlbumSelector.selectors.albumSelector.hide();
AlbumSelector.selectors.searchResult.hide();
AlbumSelector.selectors.linkedAlbumSwitch.hide();
AlbumSelector.selectors.albumCreate.fadeIn();
AlbumSelector.selectors.linkedAlbumSubTitle.html(sprintf(str_add_subcat_of, cat === 'root' ? str_root_album_select : cat.name));
AlbumSelector.selectors.linkedAddNewAlbum.off(`click${instanceAb}`).on(`click${instanceAb}`, () => {
this.#add_new_album(cat === 'root' ? cat : cat.id);
});
AlbumSelector.selectors.linkedAlbumCancel.off(`click${instanceAb}`).on(`click${instanceAb}`, () => {
this.#close_album_selector();
});
AlbumSelector.selectors.linkedAlbumInput.off(`input${instanceAb}`).on(`input${instanceAb}`, () => {
this.#hide_new_album_error();
});
}
#hide_new_album_error() {
AlbumSelector.selectors.addAlbumErrors.css('visibility', 'hidden');
}
#show_new_album_error(text) {
AlbumSelector.selectors.linkedAddAlbumErrors.html(text);
AlbumSelector.selectors.addAlbumErrors.css('visibility', 'visible');
}
#select_new_album_and_close(cat) {
const tempThis = this;
this.#currentSelectedId = cat.id;
this.#selectAlbum({ album: cat });
this.#close_album_selector();
}
#destroyEvent() {
const instanceAb = `.${this.instanceId}`;
$(document).off(`keyup${instanceAb}`);
$(document).off(`click${instanceAb}`);
$(document).off(`change${instanceAb}`);
$(document).off(`input${instanceAb}`);
AlbumSelector.selectors.searchInput.off(`keyup${instanceAb}`);
AlbumSelector.selectors.searchResult.find('.search-result-item').off(`click${instanceAb}`);
$('.prefill-results-item').off(`click${instanceAb}`);
$('.prefill-results-item.available').off(`click${instanceAb}`);
}
/*--------------
Dom modification
--------------*/
#prefill_results(rank, cats, limit) {
const isCreationMode = this.#isAlbumCreationChecked;
const iconAlbum = this.#isAlbumCreationChecked ? 'icon-add-album' : 'gallery-icon-plus-circled';
const tempSelectedCat = this.#current_cat ? [...this.#selected_categories, this.#current_cat.toString()] : [...this.#selected_categories];
this.#cats = { ...this.#cats, ...Object.fromEntries(cats.map(c => [c.id, c])) };
let display_div = $('#subcat-' + rank);
if ('root' == rank) {
AlbumSelector.selectors.searchResult.empty();
display_div = AlbumSelector.selectors.searchResult;
} else {
display_div = $('#subcat-' + rank);
}
cats.forEach(cat => {
let subcat = '';
if (cat.nb_categories > 0) {
subcat = `<span id="${cat.id}" class="display-subcat gallery-icon-up-open"></span>`
}
const isNotInSelectedCat = !tempSelectedCat.includes(cat.id);
if (isCreationMode || isNotInSelectedCat ) {
display_div.append(
`<div class="search-result-item" id="${cat.id}">
${subcat}
<div class="prefill-results-item available" id="${cat.id}">
<span class="search-result-path"><span class="search-result-path-name">${cat.name}</span></span>
<span id=${cat.id}" class="${iconAlbum} item-add"></span>
</div>
</div>`
);
} else {
display_div.append(
`<div class="search-result-item already-in" id="${cat.id}" title="${str_album_selected}">
${subcat}
<div class="prefill-results-item" id="${cat.id}">
<span class="search-result-path"><span class="search-result-path-name">${cat.name}</span></span>
<span id="${cat.id}" class="gallery-icon-plus-circled item-add notClickable" title="${str_album_selected}"></span>
</div>
</div>`
);
}
if (rank !== 'root') {
const item = $("#" + rank + ".search-result-item");
const margin_left = parseInt(item.css('margin-left')) + 25;
$("#" + cat.id + ".search-result-item").css('margin-left', margin_left);
$("#" + cat.id + ".search-result-item .search-result-path").css('max-width', 400 - margin_left - 80);
}
});
this.#loadPickAlbumEvent();
this.#loadSubCatEvent();
// for debug
// console.log(limit);
if (limit.remaining_cats > 0) {
const text = sprintf(str_plus_albums_found, limit.limited_to, limit.total_cats);
display_div.append(
`<p class="and-more">${text}</p>`
);
}
}
#fill_results(cats) {
const iconAlbum = this.#isAlbumCreationChecked ? 'icon-add-album' : 'gallery-icon-plus-circled';
const tempSelectedCat = this.#current_cat ? [...this.#selected_categories, this.#current_cat.toString()] : [...this.#selected_categories];
this.#searchCat = Object.fromEntries(cats.map(c => [c.id, c]));
AlbumSelector.selectors.searchResult.empty();
cats.forEach(cat => {
const cat_name = this.#in_admin_mode ? cat.fullname : cat.name;
AlbumSelector.selectors.searchResult.append(
`<div class='search-result-item' id="${cat.id}">
<span class="search-result-path not-rtl">${this.#getEllipsisName(cat_name)}</span><span id="${cat.id}" class="${iconAlbum} item-add"></span>
</div>`
);
if (this.#isAlbumCreationChecked) {
const instanceAb = `.${this.instanceId}`;
$(".search-result-item#" + cat.id).off(`click${instanceAb}`).on(`click${instanceAb}`, () => {
this.#switch_album_view(cat);
});
return
}
if (tempSelectedCat.includes(cat.id)) {
$(".search-result-item #" + cat.id + ".item-add").addClass("notClickable").attr("title", str_album_selected);
$("#" + cat.id + ".search-result-item").addClass("notClickable").attr("title", str_album_selected);
}
});
!this.#isAlbumCreationChecked && this.#loadFillResultEvent(tempSelectedCat);
}
#getEllipsisName(str, lenght = 50) {
if (str.length <= lenght) return str;
return '...' + str.slice(-lenght).trim();
}
/*-----------
Ajax method
-----------*/
#prefill_search() {
$(".linkedAlbumPopInContainer .searching").show();
let api_params = {
cat_id: 0,
recursive: false,
fullname: true,
limit: this.#limitParam,
};
this.#in_admin_mode && (api_params.additional_output = 'full_name_with_admin_links');
$.ajax({
url: "ws.php?format=json&method=" + this.#methodPwg,
type: "POST",
dataType: "json",
data: api_params,
success: (data) => {
// for debug
// console.log(data);
$(".linkedAlbumPopInContainer .searching").hide();
const cats = data.result.categories;
const limit = data.result.limit;
this.#prefill_results("root", cats, limit);
},
error: function (e) {
$(".linkedAlbumPopInContainer .searching").hide();
console.log("error : ", e.message);
},
});
}
async #prefill_search_subcats(cat_id) {
let api_params = {
cat_id: cat_id,
recursive: false,
limit: this.#limitParam,
};
this.#in_admin_mode && (api_params.additional_output = 'full_name_with_admin_links');
$.ajax({
url: "ws.php?format=json&method=" + this.#methodPwg,
type: "POST",
dataType: "json",
data: api_params,
success: (data) => {
const cats = data.result.categories.filter((c) => c.id != cat_id);
const limit = data.result.limit;
this.#prefill_results(cat_id, cats, limit);
},
error: (e) => {
console.log('prefill search error :', e);
}
});
}
#perform_albums_search(searchText) {
if (searchText == '') {
this.#reset_search_input(true);
return;
}
let api_params = {
cat_id: 0,
recursive: true,
fullname: true,
search: searchText,
}
this.#in_admin_mode && (api_params.additional_output = 'full_name_with_admin_links');
AlbumSelector.selectors.iconSearchingSpin.show();
$.ajax({
url: "ws.php?format=json&method=" + this.#methodPwg,
type: "POST",
dataType: "json",
data: api_params,
success: (raw_data) => {
if ('ok' !== raw_data.stat) { return }
AlbumSelector.selectors.iconSearchingSpin.hide();
let categories = raw_data.result.categories;
this.#fill_results(categories);
if (raw_data.result.limit_reached) {
AlbumSelector.selectors.limitReached.html(str_result_limit.replace("%d", categories.length));
} else {
if (categories.length == 1) {
AlbumSelector.selectors.limitReached.html(str_album_found);
} else {
AlbumSelector.selectors.limitReached.html(str_albums_found.replace("%d", categories.length));
}
}
},
error: (e) => {
AlbumSelector.selectors.iconSearchingSpin.hide();
console.log(e.message);
}
});
}
#add_new_album(cat_id) {
if (this.#loading_add) return;
this.#loading_add = true;
const cat_name = AlbumSelector.selectors.linkedAlbumInput.val();
const cat_position = $("input[name=position]:checked").val();
const api_params = {
name: cat_name,
parent: cat_id === 'root' ? 0 : +cat_id,
position: cat_position,
}
if(!cat_name || '' === cat_name) {
this.#show_new_album_error(str_complete_name_field);
return
}
$.ajax({
url: 'ws.php?format=json&method=pwg.categories.add',
type: 'POST',
dataType: 'json',
data: api_params,
success: (data) => {
if (data.stat === 'ok') {
this.#get_album_by_id(data.result.id);
} else {
this.#show_new_album_error(str_an_error_has_occured);
}
},
error: () => {
this.#show_new_album_error(str_an_error_has_occured);
}
});
}
#get_album_by_id(cat_id) {
$.ajax({
url: 'ws.php?format=json&method=pwg.categories.getAdminList',
dataType: 'json',
data: {
cat_id,
additional_output: 'full_name_with_admin_links',
},
success: (data) => {
if(data.stat === 'ok') {
this.#select_new_album_and_close(data.result.categories[0]);
} else {
this.#show_new_album_error(str_an_error_has_occured);
}
},
error: () => {
this.#show_new_album_error(str_an_error_has_occured);
}
});
}
}
@@ -0,0 +1,920 @@
$(document).ready(() => {
const openUppercats = openCat == -1 ? [] : findAlbumById(data, openCat).uppercats.split(',');
const new_data = data.map((a) => {
const al = {...a, children: openUppercats.includes(a.id) ? a.children : []};
if (a.children) {
al.load_on_demand = openUppercats.includes(a.id) ? false : true;
al.haveChildren = a.children;
}
return al;
});
$("h1").append(`<span class='badge-number'>`+nb_albums+`</span>`);
$('.tree').tree({
data: new_data,
autoOpen : false,
dragAndDrop: true,
openFolderDelay: delay_autoOpen,
onCreateLi : createAlbumNode,
onCanSelectNode: function(node) {return false}
});
$('.tree').on( 'click', '.move-cat-toogler', function(e) {
var node_id = $(this).attr('data-id');
var node = $('.tree').tree('getNodeById', node_id);
if (node.load_on_demand && node.haveChildren) {
loadOnDemand(node);
}
if (node) {
open_nodes = $('.tree').tree('getState').open_nodes;
if (!open_nodes.includes(node_id)) {
$(this).html(toggler_open);
$('.tree').tree('openNode', node);
// reset event here:
$(".move-cat-add").off("click").on("click", function (e) {
e.preventDefault();
openAddAlbumPopIn($(this).data("aid"));
$(".AddAlbumSubmit").data("a-parent", $(this).data("aid"));
});
$(".move-cat-delete").off('click').on("click", function () {
triggerDeleteAlbum($(this).data("id"));
});
$(".move-cat-title-container").off("click").on("click", function () {
openRenameAlbumPopIn($(this).find(".move-cat-title").attr("title"));
$(".RenameAlbumSubmit").data("cat_id", $(this).attr('data-id'));
});
} else {
$(this).html(toggler_close);
$('.tree').tree('closeNode', node);
}
}
});
$('.tree').on(
'tree.open',
function(e) {
$('.move-cat-toogler[data-id='+e.node.id+']').html(toggler_open);
}
);
$('.tree').on(
'tree.close',
function(e) {
$('.move-cat-toogler[data-id='+e.node.id+']').html(toggler_close);
}
);
$('.tree').on(
'tree.move',
function(event) {
event.preventDefault();
if (event.move_info.moved_node.status != 'private') {
parentIsPrivate = false;
if (event.move_info.position == 'after') {
parentIsPrivate = (event.move_info.target_node.parent.status == 'private');
} else if (event.move_info.position == 'inside') {
parentIsPrivate = (event.move_info.target_node.status == 'private');
}
if (parentIsPrivate) {
$.confirm({
title: str_are_you_sure.replace(/%s/g, event.move_info.moved_node.name),
buttons: {
confirm: {
text: str_yes_change_parent,
btnClass: 'btn-red',
action: function () {
makePrivateHierarchy(event.move_info.moved_node);
applyMove(event);
},
},
cancel: {
text: str_no_change_parent
}
},
...jConfirm_confirm_options
})
} else {
applyMove(event);
}
} else {
applyMove(event);
}
}
);
$('.tree').on( 'click', '.move-cat-order', function(e) {
var node_id = $(this).attr('data-id');
var node = $('.tree').tree('getNodeById', node_id);
if (node) {
$('.cat-move-order-popin').fadeIn();
$('.cat-move-order-popin .album-name').html(getPathNode(node));
$('.cat-move-order-popin input[name=id]').val(node_id);
$('input[name=simpleAutoOrder]').attr('value', str_sub_album_order);
}
});
$('.order-root').on( 'click', function() {
$('.cat-move-order-popin').fadeIn();
$('.cat-move-order-popin .album-name').html(str_root);
$('.cat-move-order-popin input[name=id]').val(-1);
$('input[name=simpleAutoOrder]').attr('value', str_root_order);
});
$('.tree').on('mousedown mouseup', function mouseState(e) {
if (e.type == "mousedown") {
$(".tree").addClass("dragging")
} else if (e.type == "mouseup") {
$(".dragging").removeClass("dragging")
}
});
if (openCat != -1) {
nodeToGo = $('.tree').tree('getNodeById', openCat);
goToNode(nodeToGo, nodeToGo);
if (nodeToGo.children) {
$(".tree").tree("openNode", nodeToGo, false);
}
$([document.documentElement, document.body]).animate({
scrollTop: $("#cat-"+openCat).offset().top - ($(window).height() / 2) + ($("#cat-"+openCat).outerHeight() / 2)
}, 500);
}
// RenameAlbumPopIn
$(".RenameAlbumErrors").hide();
$(".move-cat-title-container").on("click", function () {
openRenameAlbumPopIn($(this).find(".move-cat-title").attr("title"));
$(".RenameAlbumSubmit").data("cat_id", $(this).attr('data-id'));
});
$(".CloseRenameAlbum").on("click", function () {
closeRenameAlbumPopIn();
});
$(".RenameAlbumCancel").on("click", function () {
closeRenameAlbumPopIn();
})
$(".RenameAlbumSubmit").on("click", function () {
catToEdit = $(this).data("cat_id");
jQuery.ajax({
url: "ws.php?format=json&method=pwg.categories.setInfo",
type: "POST",
data: {
category_id : catToEdit,
name : $(".RenameAlbumLabelUsername input").val(),
},
success: function (raw_data) {
data = jQuery.parseJSON(raw_data);
const node_id = $("#cat-"+catToEdit).find('.move-cat-toogler').attr('data-id');
const node = $('.tree').tree('getNodeById', node_id);
node.name = $(".RenameAlbumLabelUsername input").val();
$('.tree').tree('updateNode', node, $(".RenameAlbumLabelUsername input").val());
$(".move-cat-title-container").on("click", function () {
openRenameAlbumPopIn($(this).find(".move-cat-title").attr("title"));
$(".RenameAlbumSubmit").data("cat_id", $(this).attr('data-id'));
});
$(".move-cat-add").off("click").on("click", function (e) {
e.preventDefault();
openAddAlbumPopIn($(this).data("aid"));
$(".AddAlbumSubmit").data("a-parent", $(this).data("aid"));
});
closeRenameAlbumPopIn();
},
error: function(message) {
console.log(message);
}
});
})
// AddAlbumPopIn
$(".AddAlbumErrors").hide();
$(".DeleteAlbumErrors").hide();
$(".add-album-button").on("click", function () {
openAddAlbumPopIn(0);
$(".AddAlbumSubmit").data("a-parent", 0);
})
$(".move-cat-add").on("click", function (e) {
e.preventDefault();
openAddAlbumPopIn($(this).data("aid"));
$(".AddAlbumSubmit").data("a-parent", $(this).data("aid"));
})
$(".CloseAddAlbum").on("click", function () {
closeAddAlbumPopIn();
});
$(".AddAlbumCancel").on("click", function () {
closeAddAlbumPopIn();
});
$(".DeleteAlbumCancel").on("click", function () {
closeDeleteAlbumPopIn();
});
$(".AddAlbumSubmit").on("click", function () {
$(this).addClass("notClickable");
newAlbumName = $(".AddAlbumLabelUsername input").val();
newAlbumParent = $(".AddAlbumSubmit").data("a-parent");
newAlbumPosition = $("input[name=position]:checked").val();
jQuery.ajax({
url: "ws.php?format=json&method=pwg.categories.add",
type: "POST",
data: {
name : newAlbumName,
parent : newAlbumParent,
position : newAlbumPosition
},
success: function (raw_data) {
data = jQuery.parseJSON(raw_data);
var parent_node = $('.tree').tree('getNodeById', newAlbumParent);
if (parent_node && parent_node.load_on_demand && parent_node.haveChildren) {
loadOnDemand(parent_node);
}
if (parent_node) openNodeOnDemand(parent_node);
if (data.stat == "ok") {
if (newAlbumPosition == "last") {
$('.tree').tree(
'appendNode',
{
id: data.result.id,
isEmptyFolder: true,
name: newAlbumName
},
parent_node
);
} else {
$('.tree').tree(
'prependNode',
{
id: data.result.id,
isEmptyFolder: true,
name: newAlbumName
},
parent_node
);
}
if (parent_node) {
setSubcatsBadge(parent_node);
$("#cat-"+parent_node.id).on( 'click', '.move-cat-toogler', function(e) {
var node_id = parent_node.id;
var node = $('.tree').tree('getNodeById', node_id);
if (node) {
open_nodes = $('.tree').tree('getState').open_nodes;
if (!open_nodes.includes(node_id)) {
$(this).html(toggler_open);
$('.tree').tree('openNode', node);
} else {
$(this).html(toggler_close);
$('.tree').tree('closeNode', node);
}
}
});
}
$(".move-cat-add").off("click").on("click", function (e) {
e.preventDefault();
openAddAlbumPopIn($(this).data("aid"));
$(".AddAlbumSubmit").data("a-parent", $(this).data("aid"));
});
$(".move-cat-delete").on("click", function () {
triggerDeleteAlbum($(this).data("id"));
});
$(".move-cat-title-container").unbind("click").on("click", function () {
openRenameAlbumPopIn($(this).find(".move-cat-title").attr("title"));
$(".RenameAlbumSubmit").data("cat_id", $(this).attr('data-id'));
});
$('.tiptip').tipTip({
delay: 0,
fadeIn: 200,
fadeOut: 200,
edgeOffset: 3
});
updateTitleBadge(nb_albums+1)
goToNode($(".tree").tree('getNodeById', data.result.id), $(".tree").tree('getNodeById', data.result.id));
$('html,body').animate({
scrollTop: $("#cat-" + data.result.id).offset().top - screen.height / 2},
'slow');
closeAddAlbumPopIn();
$(".AddAlbumSubmit").removeClass("notClickable");
} else {
$(".AddAlbumErrors").text(str_album_name_empty).show();
$(".AddAlbumSubmit").removeClass("notClickable");
}
},
error: function(message) {
console.log(message);
}
});
})
// Delete Album
$(".move-cat-delete").on("click", function () {
triggerDeleteAlbum($(this).data("id"));
});
$('.user-list-checkbox').unbind("change").change(checkbox_change);
$('.user-list-checkbox').unbind("click").click(checkbox_click);
if (!light_album_manager) {
$('.tiptip').tipTip({
delay: 0,
fadeIn: 200,
fadeOut: 200,
edgeOffset: 3
});
}
});
function createAlbumNode(node, li) {
icon = "<span class='%icon%'></span>";
title = '<span data-id="'+node.id+'" class="move-cat-title-container ';
if (node.status == 'private' || node.parent.status == 'private') {
node.status = 'private';
title += 'icon-lock';
}
title += '">';
if (node.visible == 'false' || node.parent.visble == 'false') {
node.visble = 'false';
title += '<span class="tiptip icon-cone" title="'+ tiptip_locked_album +'" style="font-size: 16px"></span>';
}
title += '<p class="move-cat-title" title="'+node.name+'">%name%</p> <span class="icon-pencil"></span> </span>';
toggler_cont = "<div class='move-cat-toogler' data-id=%id%>%content%</div>";
toggler_close = "<span class='icon-left-open'></span>";
toggler_open = "<span class='icon-down-open'></span>";
actions =
'<div class="move-cat-action-cont">'
+"<div class='move-cat-action'>"
+'<a class="move-cat-add icon-add-album tiptip" title="'+ str_add_album +'" href="#" data-aid="'+node.id+'"></a>'
+'<a class="move-cat-edit icon-pencil tiptip" title="'+ str_edit_album +'" href="admin.php?page=album-'+node.id+'"></a>'
+'<a class="move-cat-upload icon-plus-circled tiptip" title="'+ str_add_photo +'" href="admin.php?page=photos_add&album='+node.id+'"></a>'
+'<a class="move-cat-see icon-eye tiptip" title="'+ str_visit_gallery +'" href="index.php?/category/'+node.id+'"></a>'
+'<a data-id="'+node.id+'" class="move-cat-order icon-sort-name-up tiptip" title="'+ str_sort_order +'"></a>'
+'<a data-id="'+node.id+'" class="move-cat-delete icon-trash tiptip" title="'+ str_delete_album +'" ></a>'
+"</div>"
+'</div>';
// action_order = '<a data-id="'+node.id+'" class="move-cat-order icon-sort-name-up tiptip" title="'+ str_sort_order +'"></a>';
cont = li.find('.jqtree-element');
cont.addClass('move-cat-container');
cont.attr('id', 'cat-'+node.id)
cont.html('');
cont.append(actions);
cont.find(".toggle-cat-option").on("click", function () {
$(".cat-option").hide();
$(this).find(".cat-option").toggle();
});
if (node.haveChildren || node.children.length != 0) {
open_nodes = $('.tree').tree('getState').open_nodes;
if (open_nodes.includes(node.id)) {
toggler = toggler_open;
} else {
toggler = toggler_close;
}
cont.append($(toggler_cont
.replace(/%content%/g, toggler)
.replace(/%id%/g, node.id)));
} else {
cont.find('.move-cat-order').addClass("notClickable");
cont.append($(toggler_cont
.replace(/%content%/g, toggler_close)
.replace(/%id%/g, node.id))).addClass("disabledToggle");
}
cont.append($(icon.replace(/%icon%/g, 'icon-grip-vertical-solid')));
cont.find('.icon-grip-vertical-solid').attr('title', str_albs_drag_drop);
if (node.haveChildren || node.children.length != 0) {
cont.append($(icon.replace(/%icon%/g, 'icon-sitemap')));
} else {
cont.append($(icon.replace(/%icon%/g, 'icon-folder-open')));
}
cont.append($(title.replace(/%name%/g, node.name)));
var colors = ["icon-red", "icon-blue", "icon-yellow", "icon-purple", "icon-green"];
var colorId = Number(node.id)%5;
cont.find("span.icon-folder-open, span.icon-sitemap").addClass(colors[colorId]).addClass("node-icon");
cont.find(".move-cat-title-container").after(
"<div class='badge-container'>"
+"<i class='icon-blue icon-sitemap nb-subcats'>"+node.nb_subcats+"</i>"
+"<i class='icon-purple icon-picture nb-images'>"+node.nb_images+"</i>"
+"<i class='icon-green icon-imagefolder-01 nb-sub-photos'>"+node.nb_sub_photos+"</i>"
+"<div class='badge-dropdown'>"
+"<span class='icon-blue icon-sitemap nb-subcats'>"+x_nb_subcats.replace('%d', node.nb_subcats)+"</span>"
+"<span class='icon-purple icon-picture nb-images'>"+x_nb_images.replace('%d', node.nb_images)+"</span>"
+"<span class='icon-green icon-imagefolder-01 nb-sub-photos'>"+x_nb_sub_photos.replace('%d', node.nb_sub_photos)+"</span>"
+"</div>"
+"</div>"
)
if (!(node.nb_subcats)) {
cont.find(".nb-subcats").hide();
}
if (!(node.nb_images != 0 && node.nb_images)) {
cont.find(".nb-images").hide();
}
if (!(node.nb_sub_photos)) {
cont.find(".nb-sub-photos").hide();
}
if (node.has_not_access) {
cont.find(".move-cat-see").addClass("notClickable");
}
}
/*----------------
Checkboxes
----------------*/
function checkbox_change() {
if ($(this).attr('data-selected') == '1') {
$(this).find("i").hide();
} else {
$(this).find("i").show();
}
}
function checkbox_click() {
if ($(this).attr('data-selected') == '1') {
$(this).attr('data-selected', '0');
$(this).find("i").hide();
} else {
$(this).attr('data-selected', '1');
$(this).find("i").show();
}
}
function isNumeric(num){
return !isNaN(num)
}
function openAddAlbumPopIn(parentAlbumId) {
if (parentAlbumId != 0) {
$("#AddAlbum .AddIconTitle span").html(add_sub_album_of.replace("%s", $(".tree").tree('getNodeById', parentAlbumId).name));
} else {
$("#AddAlbum .AddIconTitle span").html(add_album_root_title)
}
$("#AddAlbum").fadeIn();
const modalInput = $(".AddAlbumLabelUsername .user-property-input");
modalInput.val('');
modalInput.trigger('focus');
modalInput.off('keyup').on('keyup', function () {
if ($(this).val() !== '') {
$(".AddAlbumErrors").hide();
}
});
$("#AddAlbum").unbind('keyup');
$("#AddAlbum").on('keyup', function (e) {
// 13 is 'Enter'
if(e.keyCode === 13) {
$(".AddAlbumSubmit").trigger("click");
}
// 27 is 'Escape'
if(e.keyCode === 27) {
closeAddAlbumPopIn();
}
})
}
function closeAddAlbumPopIn() {
$("#AddAlbum").fadeOut(function() {
$(".AddAlbumErrors").hide();
});
}
function openRenameAlbumPopIn(replacedAlbumName) {
$("#RenameAlbum").fadeIn();
$(".RenameAlbumTitle span").html(rename_item.replace("%s", replacedAlbumName))
$(".RenameAlbumLabelUsername .user-property-input").val(replacedAlbumName);
$(".RenameAlbumLabelUsername .user-property-input").focus();
$(document).unbind("keypress").on('keypress',function(e) {
if(e.which == 13) {
$(".RenameAlbumSubmit").trigger("click");
}
});
}
function closeRenameAlbumPopIn() {
$("#RenameAlbum").fadeOut();
}
function triggerDeleteAlbum(cat_id) {
$.ajax({
url: "ws.php?format=json&method=pwg.categories.calculateOrphans",
type: "GET",
data: {
category_id: cat_id,
},
success: function (raw_data) {
let data = JSON.parse(raw_data).result[0]
if (data.nb_images_recursive == 0) {
$(".deleteAlbumOptions").hide();
} else {
$(".deleteAlbumOptions").show();
if (data.nb_images_associated_outside == 0) {
$("#IMAGES_ASSOCIATED_OUTSIDE").hide();
} else {
$("#IMAGES_ASSOCIATED_OUTSIDE .innerText").html("");
$("#IMAGES_ASSOCIATED_OUTSIDE .innerText").append(has_images_associated_outside.replace('%d', data.nb_images_recursive).replace('%d', data.nb_images_associated_outside));
}
if (data.nb_images_becoming_orphan == 0) {
$("#IMAGES_BECOMING_ORPHAN").hide();
} else {
$("#IMAGES_BECOMING_ORPHAN .innerText").html("");
$("#IMAGES_BECOMING_ORPHAN .innerText").append(has_images_becomming_orphans.replace('%d', data.nb_images_becoming_orphan));
}
}
},
error: function(message) {
console.log(message);
}
}).done(function () {
openDeleteAlbumPopIn(cat_id);
});
}
function openDeleteAlbumPopIn(cat_to_delete) {
$("#DeleteAlbum").fadeIn();
node = $(".tree").tree('getNodeById', cat_to_delete);
if (node.children.length == 0) {
$(".DeleteIconTitle span").html(delete_album_with_name.replace("%s", node.name));
} else {
nb_sub_cats = 0;
$(".DeleteIconTitle span").html(delete_album_with_subs.replace("%s", node.name).replace("%d", getAllSubAlbumsFromNode(node, nb_sub_cats)));
}
// Actually delete
$(".DeleteAlbumSubmit").unbind("click").on("click", function () {
$.ajax({
url: "ws.php?format=json&method=pwg.categories.delete",
type: "POST",
data: {
category_id: cat_to_delete,
photo_deletion_mode: $("input[name=photo_deletion_mode]:checked").val(),
pwg_token: pwg_token,
},
success: function (raw_data) {
parentOfDeletedNode = node.parent
$('.tree').tree('removeNode', node);
$(".move-cat-add").on("click", function (e) {
e.preventDefault();
openAddAlbumPopIn($(this).data("aid"));
$(".AddAlbumSubmit").data("a-parent", $(this).data("aid"));
});
$(".move-cat-delete").on("click", function () {
triggerDeleteAlbum($(this).data("id"));
});
$(".move-cat-title-container").unbind("click").on("click", function () {
openRenameAlbumPopIn($(this).find(".move-cat-title").attr("title"));
$(".RenameAlbumSubmit").data("cat_id", $(this).attr('data-id'));
});
$('.tiptip').tipTip({
delay: 0,
fadeIn: 200,
fadeOut: 200,
edgeOffset: 3
});
updateTitleBadge(nb_albums-1);
setSubcatsBadge(parentOfDeletedNode);
closeDeleteAlbumPopIn();
},
error: function(message) {
console.log(message);
}
});
})
}
function closeDeleteAlbumPopIn() {
$("#DeleteAlbum").fadeOut();
}
function getAllSubAlbumsFromNode(node, nb_sub_cats) {
nb_sub_cats = 0;
if (node.children != 0) {
node.children.forEach(child => {
nb_sub_cats++;
tmp = getAllSubAlbumsFromNode(child, nb_sub_cats);
nb_sub_cats += tmp;
});
} else {
return 0;
}
return nb_sub_cats;
}
function setSubcatsBadge(node) {
if (node.children.length != 0) {
$("#cat-"+node.id).find(".nb-subcats").text(node.children.length).show(100);
$("#cat-"+node.id).find(".badge-dropdown").find(".nb-subcats").text(x_nb_subcats.replace('%d', node.children.length));
} else {
$("#cat-"+node.id).find(".nb-subcats").hide(100)
}
}
function updateTitleBadge(new_nb_albums) {
nb_albums = new_nb_albums;
$(".badge-number").text(new_nb_albums);
}
function goToNode(node, firstNode) {
// console.log(firstNode.id, node.id);
if (node.parent) {
goToNode(node.parent, firstNode);
if(node != firstNode) {
$(".tree").tree('openNode', node);
// console.log("parent id : " + node.parent.id);
$("#cat-"+node.parent.id).show();
$("#cat-"+node.parent.id).addClass("imune");
}
} else {
$(".tree").tree('openNode', node);
$("#cat-"+firstNode.id).addClass("animateFocus");
showNodeChildrens(firstNode);
}
}
function showNodeChildrens(node) {
if (node.children) {
// console.log("childrens : " + node.children);
node.children.forEach(child => {
// console.log("children : " + child.id, child.name);
$("#cat-"+child.id).addClass("imune");
showNodeChildrens(child);
});
}
}
function closeTree(tree) {
// console.log(tree);
if (tree.tree('getState').open_nodes.length > 0) {
tree.tree('getState').open_nodes.forEach(nodeItem => {
var node = tree.tree('getNodeById', nodeItem);
tree.tree('closeNode', node);
});
}
}
function getId(parent) {
if (parent.getLevel() == 0) {
return 0;
} else {
return parent.id;
}
}
function getRank(node, ignoreId = null) {
if (node.getPreviousSibling() != null) {
if (node.id != ignoreId) {
return 1 + getRank(node.getPreviousSibling(), ignoreId);
} else {
return getRank(node.getPreviousSibling(), ignoreId);
}
} else {
if (node.id != ignoreId) {
return 1;
} else {
return 0;
}
}
}
function applyMove(event) {
waitingTimeout = setTimeout(() => {
$('.waiting-message').addClass('visible');
}, 500);
id = event.move_info.moved_node.id;
moveParent = null;
moveRank = null;
previous_parent = event.move_info.previous_parent;
target = event.move_info.target_node;
if (event.move_info.position == 'after') {
if (getId(previous_parent) != getId(target.parent)) {
moveParent = getId(target.parent);
}
moveRank = getRank(target, id) + 1;
} else if (event.move_info.position == 'inside') {
if (getId(previous_parent) != getId(target)) {
moveParent = getId(target);
const currentNode = $('.tree').tree('getNodeById', moveParent);
if (currentNode && currentNode.load_on_demand && currentNode.haveChildren) {
loadOnDemand(currentNode);
}
}
moveRank = 1;
} else if (event.move_info.position == 'before') {
if (getId(previous_parent) != getId(target.parent)) {
moveParent = getId(target.parent);
}
moveRank = 1;
}
moveNode(id, moveRank, moveParent).then(() => {
event.move_info.do_move();
clearTimeout(waitingTimeout);
$('.waiting-message').removeClass('visible');
setSubcatsBadge(previous_parent);
setSubcatsBadge($('.tree').tree('getNodeById', moveParent));
$(".move-cat-add").off("click").on("click", function (e) {
e.preventDefault();
openAddAlbumPopIn($(this).data("aid"));
$(".AddAlbumSubmit").data("a-parent", $(this).data("aid"));
});
$(".move-cat-delete").on("click", function () {
triggerDeleteAlbum($(this).data("id"));
});
$(".move-cat-title-container").on("click", function () {
openRenameAlbumPopIn($(this).find(".move-cat-title").attr("title"));
$(".RenameAlbumSubmit").data("cat_id", $(this).attr('data-id'));
});
$('.tiptip').tipTip({
delay: 0,
fadeIn: 200,
fadeOut: 200,
edgeOffset: 3
});
})
.catch(function (message) {
console.log('An error has occured : ' + message );
$(".move-cat-add").off("click").on("click", function (e) {
e.preventDefault();
openAddAlbumPopIn($(this).data("aid"));
$(".AddAlbumSubmit").data("a-parent", $(this).data("aid"));
});
$(".move-cat-delete").on("click", function () {
triggerDeleteAlbum($(this).data("id"));
});
$(".move-cat-title-container").on("click", function () {
openRenameAlbumPopIn($(this).find(".move-cat-title").attr("title"));
$(".RenameAlbumSubmit").data("cat_id", $(this).attr('data-id'));
});
$('.tiptip').tipTip({
delay: 0,
fadeIn: 200,
fadeOut: 200,
edgeOffset: 3
});
})
}
function moveNode(node, rank, parent) {
return new Promise ((res, rej) => {
if (parent != null) {
changeParent(node, parent, rank).then(() => res()).catch(() => rej())
} else if (rank != null) {
changeRank(node, rank).then(() => res()).catch(() => rej())
}
})
}
function changeParent(node, parent, rank) {
oldParent = node.parent
return new Promise((res, rej) => {
jQuery.ajax({
url: "ws.php?format=json&method=pwg.categories.move",
type: "POST",
data: {
category_id : node,
parent : parent,
pwg_token : pwg_token
},
before: function () {
oldParent = node.parent
},
success: function (raw_data) {
data = jQuery.parseJSON(raw_data);
if (data.stat === "ok") {
changeRank(node, rank)
const updated_cats = data.result.updated_cats;
if (updated_cats)
{
updated_cats.forEach((cat) => {
const node = $('.tree').tree('getNodeById', cat.cat_id);
node.nb_sub_photos = cat.nb_sub_photos;
$('.tree').tree('updateNode', node, node.name);
});
}
res();
} else {
rej(raw_data);
}
},
error: function(message) {
rej(message);
}
});
})
}
function changeRank(node, rank) {
return new Promise((res, rej) => {
jQuery.ajax({
url: "ws.php?format=json&method=pwg.categories.setRank",
type: "POST",
data: {
category_id : node,
rank : rank
},
success: function (raw_data) {
data = jQuery.parseJSON(raw_data);
if (data.stat === "ok") {
res();
} else {
rej(raw_data);
}
},
error: function(message) {
rej(message);
}
});
})
}
function makePrivateHierarchy(node) {
node.status = 'private';
node.children.forEach(node => {
makePrivateHierarchy(node);
});
}
function getPathNode(node) {
if (node.parent.getLevel() != 0) {
return getPathNode(node.parent) + ' / ' + node.name;
} else {
return node.name;
}
}
function findAlbumById(a, id) {
for (const album of a) {
if (album.id == id) { return album };
if (album.haveChildren && album.haveChildren.length > 0 || album.children && album.children.length > 0) {
const al = findAlbumById(album.haveChildren ?? album.children, id);
if (al) { return al };
}
}
return null;
}
function loadOnDemand(node) {
const children = node.haveChildren;
const formatedChild = children.map((a) => {
const al = {...a, children:[]};
if (a.children) {
al.load_on_demand = true;
al.haveChildren = a.children;
}
return al;
});
$('.tree').tree('loadData', formatedChild, node);
node.load_on_demand = false;
}
function openNodeOnDemand(node) {
open_nodes = $('.tree').tree('getState').open_nodes;
if (!open_nodes.includes(node)) {
$('.tree').tree('openNode', node);
$(".move-cat-add").off("click").on("click", function (e) {
e.preventDefault();
openAddAlbumPopIn($(this).data("aid"));
$(".AddAlbumSubmit").data("a-parent", $(this).data("aid"));
});
$(".move-cat-delete").off('click').on("click", function () {
triggerDeleteAlbum($(this).data("id"));
});
$(".move-cat-title-container").off("click").on("click", function () {
openRenameAlbumPopIn($(this).find(".move-cat-title").attr("title"));
$(".RenameAlbumSubmit").data("cat_id", $(this).attr('data-id'));
});
}
}
@@ -0,0 +1,141 @@
/* ********** Filters*/
function filter_enable(filter) {
/* show the filter*/
$("#"+filter).show();
/* check the checkbox to declare we use this filter */
$("input[type=checkbox][name="+filter+"_use]").prop("checked", true);
/* forbid to select this filter in the addFilter list */
$("#addFilter").find("a[data-value="+filter+"]").addClass("disabled", "disabled");
/* hide the no filter message */
$('.noFilter').hide();
$('.addFilter-button').removeClass('highlight');
}
function filter_disable(filter) {
/* hide the filter line */
$("#"+filter).hide();
/* uncheck the checkbox to declare we do not use this filter */
$("input[name="+filter+"_use]").prop("checked", false);
/* give the possibility to show it again */
$("#addFilter").find("a[data-value="+filter+"]").removeClass("disabled");
/* show the no filter message if no filter selected */
if ($('#filterList li:visible').length == 0) {
$('.noFilter').show();
$('.addFilter-button').addClass('highlight');
}
}
// Album Selector
function select_album_filter({ album, newSelectedAlbum, getSelectedAlbum }) {
$('#selectedAlbumNameFilter').html(album.name);
newSelectedAlbum();
hide_filters_error(str_select_album);
$('#filterCategoryValue').val(+getSelectedAlbum()[0]);
$('#selectAlbumFilter').hide();
$('#selectedAlbumFilterArea').fadeIn();
}
// Tags and Albums validation
function show_filters_error(message) {
errorFilters = message;
$('#errorFilter').html(`<p>${message}</p>`).fadeIn();
}
function hide_filters_error(message) {
if (message === errorFilters) {
$('#errorFilter').hide();
}
}
$(document).ready(function () {
const ab_filter = new AlbumSelector({
selectedCategoriesIds: selected_filter_cat_ids,
selectAlbum: select_album_filter,
adminMode: true,
});
$('#selectAlbumFilter, #selectedAlbumEditFilter').on('click', function() {
ab_filter.open();
});
$(".removeFilter").addClass("icon-cancel-circled");
$(".removeFilter").click(function () {
const filter = $(this).parent('li').attr("id");
filter_disable(filter);
return false;
});
$("#addFilter a").on('click', function () {
const filter = $(this).attr("data-value");
filter_enable(filter);
});
$("#removeFilters").click(function() {
$("#filterList li").each(function() {
const filter = $(this).attr("id");
filter_disable(filter);
});
return false;
});
$('[data-slider=widths]').pwgDoubleSlider(sliders.widths);
$('[data-slider=heights]').pwgDoubleSlider(sliders.heights);
$('[data-slider=ratios]').pwgDoubleSlider(sliders.ratios);
$('[data-slider=filesizes]').pwgDoubleSlider(sliders.filesizes);
$(document).mouseup(function (e) {
e.stopPropagation();
if (!$(event.target).hasClass('addFilter-button')) {
$('.addFilter-dropdown').slideUp();
}
});
// Filter JS Validation
$('.filterBlock select[data-selectize="tags"]').on('change', function() {
if ($(this).val()) {
hide_filters_error(str_select_tag);
}
})
$('#applyFilter').on('click', function(e) {
if ($('#filter_tags').is(':visible')) {
const tags = $('.filterBlock select[data-selectize="tags"]');
if (!tags.val()) {
e.preventDefault();
show_filters_error(str_select_tag);
$('#filter_tags .removeFilter').off('click.apply').on('click.apply', function() {
hide_filters_error(str_select_tag);
});
}
}
if ($('#filter_category').is(':visible')) {
const albums = ab_filter.get_selected_albums();
if (albums.length === 0) {
e.preventDefault();
show_filters_error(str_select_album);
$('#filter_category .removeFilter').off('click.apply').on('click.apply', function() {
hide_filters_error(str_select_album);
});
}
}
});
$('.help-popin-search').on('click', function() {
$('#modalQuickSearch').fadeIn();
});
$('#closeModalQuickSearch').on('click', function() {
$('#modalQuickSearch').fadeOut();
});
})
@@ -0,0 +1,525 @@
/* ********** Thumbs */
/* Shift-click: select all photos between the click and the shift+click */
jQuery(document).ready(function() {
var last_clicked=0,
last_clickedstatus=true;
jQuery.fn.enableShiftClick = function() {
var inputs = [],
count=0;
this.find('input[type=checkbox]').each(function() {
var pos=count;
inputs[count++]=this;
$(this).bind("shclick", function (dummy,event) {
if (event.shiftKey) {
var first = last_clicked;
var last = pos;
if (first > last) {
first=pos;
last=last_clicked;
}
for (var i=first; i<=last;i++) {
input = $(inputs[i]);
$(input).prop('checked', last_clickedstatus).trigger("change");
if (last_clickedstatus)
{
$(input).closest("li").addClass("thumbSelected");
}
else
{
$(input).closest("li").removeClass("thumbSelected");
}
}
}
else {
last_clicked = pos;
last_clickedstatus = this.checked;
}
return true;
});
$(this).click(function(event) { $(this).triggerHandler("shclick",event)});
});
}
$('ul.thumbnails').enableShiftClick();
const ab_action = new AlbumSelector({
adminMode: true,
selectAlbum: select_album_action,
removeSelectedAlbum: remove_album_action,
});
$('#associate_as').on('click', function () {
ab_action.open();
});
$('.selected-associate-action').on('click', (e) => {
if (e.target.classList.contains("remove-associate")) {
ab_action.remove_selected_album($(e.target).attr('id'));
}
});
});
/* ********** Album Selector */
function select_album_action({ album, addSelectedAlbum, getSelectedAlbum }) {
$('#associate_as p').html(str_add_alb_associate);
$(".selected-associate-action").append(
`<div class="selected-associate-item">
<span>${album.name}</span><span id="${album.id}" class="remove-associate icon-cancel-circled"></span>
<input type="hidden" id="associate_input_${album.id}" name="associate[]" value="${album.id}">
</div>`
);
addSelectedAlbum();
}
function remove_album_action({ id_album, getSelectedAlbum }) {
$('.selected-associate-item').find(`#${id_album}`).parent().remove();
const selected = getSelectedAlbum();
if (!selected.length) {
$('#associate_as p').html(str_select_alb_associate);
}
}
jQuery("a.preview-box").colorbox( {photo: true} );
jQuery('.thumbnails img').tipTip({
'delay' : 0,
'fadeIn' : 200,
'fadeOut' : 200
});
/* ********** Actions*/
jQuery('[data-datepicker]').pwgDatepicker({
showTimepicker: true,
cancelButton: lang.Cancel
});
jQuery('[data-add-album]').pwgAddAlbum();
$("input[name=remove_author]").click(function () {
if ($(this).is(':checked')) {
$("input[name=author]").hide();
}
else {
$("input[name=author]").show();
}
});
$("input[name=remove_title]").click(function () {
if ($(this).is(':checked')) {
$("input[name=title]").hide();
}
else {
$("input[name=title]").show();
}
});
$("input[name=remove_date_creation]").click(function () {
if ($(this).is(':checked')) {
$("#set_date_creation").hide();
}
else {
$("#set_date_creation").show();
}
});
var derivatives = {
elements: null,
done: 0,
total: 0,
finished: function() {
return derivatives.done == derivatives.total && derivatives.elements && derivatives.elements.length==0;
}
};
function progress_start() {
jQuery('#uploadingActions').show();
jQuery('#uploadingActions .progress-bar').width("0%");
}
function progress_end() {
jQuery('#uploadingActions').hide();
}
function progress(success) {
percent = parseInt(derivatives.done / derivatives.total * 100);
jQuery('#uploadingActions .progressbar').width(percent.toString()+'%');
if (success !== undefined) {
var type = success ? 'regenerateSuccess': 'regenerateError',
s = jQuery('[name="'+type+'"]').val();
jQuery('[name="'+type+'"]').val(++s);
}
if (derivatives.finished()) {
progress_end();
jQuery('#applyAction').click();
}
}
function getDerivativeUrls() {
var ids = derivatives.elements.splice(0, 500);
var params = {max_urls: 100000, ids: ids, types: []};
jQuery("#action_generate_derivatives input").each( function(i, t) {
if ($(t).is(":checked"))
params.types.push( t.value );
} );
jQuery('#applyActionBlock').hide();
jQuery('.permitActionListButton').hide();
jQuery('#confirmDel').hide();
jQuery('#regenerationMsg').show();
jQuery('#regenerationText').html(lang.generateMsg);
progress_start();
jQuery.ajax( {
type: "POST",
url: 'ws.php?format=json&method=pwg.getMissingDerivatives',
data: params,
dataType: "json",
success: function(data) {
if (!data.stat || data.stat != "ok") {
return;
}
derivatives.total += data.result.urls.length;
jQuery('#regenerationStatus .badge-number').html(derivatives.done.toString() + "/" + derivatives.total.toString());
progress();
for (var i=0; i < data.result.urls.length; i++) {
jQuery.manageAjax.add("queued", {
type: 'GET',
url: data.result.urls[i] + "&ajaxload=true",
dataType: 'json',
success: ( function(data) {
derivatives.done++;
jQuery('#regenerationStatus .badge-number').html(derivatives.done.toString() + "/" + derivatives.total.toString());
progress(true)
}),
error: ( function(data) {
derivatives.done++;
jQuery('#regenerationStatus .badge-number').html(derivatives.done.toString() + "/" + derivatives.total.toString());
progress(false)
})
});
}
if (derivatives.elements.length)
setTimeout( getDerivativeUrls, 25 * (derivatives.total-derivatives.done));
}
} );
}
function selectGenerateDerivAll() {
$("#action_generate_derivatives input[type=checkbox]").prop("checked", true).trigger("change");
}
function selectGenerateDerivNone() {
$("#action_generate_derivatives input[type=checkbox]").prop("checked", false).trigger("change");
}
function selectDelDerivAll() {
$('#action_delete_derivatives input[name="del_derivatives_type[]"]').prop("checked", true).trigger("change");
}
function selectDelDerivNone() {
$('#action_delete_derivatives input[name="del_derivatives_type[]"]').prop("checked", false).trigger("change");
}
// Trigger action click on pressing enter and if the value of applyAction is not equal to -1
$(window).on('keypress', function(e) {
const selected = $("select[name='selectAction']").val();
const haveTextarea = $(`#action_${selected} textarea`).length;
const haveAlbumSelector = $('#addLinkedAlbum').is(':visible');
if (e.key === "Enter" && selected != -1 && !haveTextarea && !haveAlbumSelector) {
e.preventDefault();
$('#applyAction').trigger('click');
}
});
/* sync metadatas or delete photos by blocks, with progress bar */
jQuery('#applyAction').click(function(e) {
if (typeof(elements) != "undefined") {
return true;
}
if (jQuery('[name="selectAction"]').val() == 'metadata') {
e.preventDefault();
e.stopPropagation();
jQuery('.bulkAction').hide();
jQuery('#regenerationText').html(lang.syncProgressMessage);
elements = Array();
if (jQuery('input[name=setSelected]').is(':checked')) {
elements = all_elements;
}
else {
jQuery('input[name="selection[]"]').filter(':checked').each(function() {
elements.push(jQuery(this).val());
});
}
var queuedManager = jQuery.manageAjax.create('queued', {
queue: true,
cacheResponse: false,
maxRequests: 1
});
progressBar_max = elements.length;
var todo = 0;
var syncBlockSize = Math.min(
Number((elements.length/2).toFixed()),
1000
);
var image_ids = Array();
jQuery('#applyActionBlock').hide();
jQuery('.permitActionListButton').hide();
jQuery('#confirmDel').hide();
jQuery('#regenerationMsg').show();
progress_bar_start();
for (i=0;i<elements.length;i++) {
image_ids.push(elements[i]);
if (i % syncBlockSize != syncBlockSize - 1 && i != elements.length - 1) {
continue;
}
(function(ids) {
var thisBatchSize = ids.length;
queuedManager.add({
url: "ws.php?format=json&method=pwg.images.syncMetadata",
type:"POST",
dataType: "json",
data: {
pwg_token: jQuery("input[name=pwg_token]").val(),
image_id: ids.join(',')
},
success: function(data) {
todo += thisBatchSize;
var isOk = data.stat && "ok" == data.stat;
if (isOk && data.result.nb_synchronized != thisBatchSize)
/*TODO: user feedback only data.nb_synchronized images out of thisBatchSize were sync*/;
/*TODO: user feedback if isError*/
jQuery('#regenerationStatus .badge-number').html(todo.toString() + "/" + progressBar_max.toString());
progress_bar(todo, progressBar_max, false);
},
error: function(data) {
todo += thisBatchSize;
/*TODO: user feedback*/
jQuery('#regenerationStatus .badge-number').html(todo.toString() + "/" + progressBar_max.toString());
progress_bar(todo, progressBar_max, false);
}
});
} )(image_ids);
image_ids = Array();
}
}
if (jQuery('[name="selectAction"]').val() == 'delete') {
if (!jQuery("#confirmDel input[name=confirm_deletion]").is(':checked')) {
jQuery("#confirmDel span.errors").css("visibility", "visible");
return false;
}
e.stopPropagation();
}
else {
return true;
}
jQuery('.bulkAction').hide();
var maxRequests=1;
var queuedManager = jQuery.manageAjax.create('queued', {
queue: true,
cacheResponse: false,
maxRequests: maxRequests
});
elements = Array();
if (jQuery('input[name=setSelected]').is(':checked')) {
elements = all_elements;
}
else {
jQuery('input[name="selection[]"]').filter(':checked').each(function() {
elements.push(jQuery(this).val());
});
}
progressBar_max = elements.length;
var todo = 0;
var deleteBlockSize = Math.min(
Number((elements.length/2).toFixed()),
1000
);
var image_ids = Array();
jQuery('#applyActionBlock').hide();
jQuery('.permitActionListButton').hide();
jQuery('#confirmDel').hide();
jQuery('#regenerationText').html(lang.deleteProgressMessage);
jQuery('#regenerationMsg').show();
progress_bar_start();
for (i=0;i<elements.length;i++) {
image_ids.push(elements[i]);
if (i % deleteBlockSize != deleteBlockSize - 1 && i != elements.length - 1) {
continue;
}
(function(ids) {
var thisBatchSize = ids.length;
queuedManager.add({
type: 'POST',
url: 'ws.php?format=json',
data: {
method: "pwg.images.delete",
pwg_token: jQuery("input[name=pwg_token]").val(),
image_id: ids.join(',')
},
dataType: 'json',
success: function(data) {
todo += thisBatchSize;
var isOk = data.stat && "ok" == data.stat;
if (isOk && data.result != thisBatchSize);
/*TODO: user feedback only data.result images out of thisBatchSize were deleted*/;
/*TODO: user feedback if isError*/
jQuery('#regenerationStatus .badge-number').html(todo.toString() + "/" + progressBar_max.toString());
progress_bar(todo, progressBar_max, false);
},
error: function(data) {
todo += thisBatchSize;
/*TODO: user feedback*/
jQuery('#regenerationStatus .badge-number').html(todo.toString() + "/" + progressBar_max.toString());
progress_bar(todo, progressBar_max, false);
}
});
} )(image_ids);
image_ids = Array();
}
/* tell PHP how many photos were deleted */
jQuery('form').append('<input type="hidden" name="nb_photos_deleted" value="'+elements.length+'">');
return false;
});
function progress_bar_start() {
jQuery('#uploadingActions').show();
jQuery('#uploadingActions .progress-bar').width("0%");
}
function progress_bar_end() {
jQuery('#uploadingActions').hide();
}
function progress_bar(val, max, success) {
percent = parseInt(val / max * 100);
jQuery('#uploadingActions .progressbar').width(percent.toString()+'%');
if (val == max)
jQuery('#applyAction').click();
}
jQuery("#confirmDel input[name=confirm_deletion]").change(function() {
jQuery("#confirmDel span.errors").css("visibility", "hidden");
});
jQuery('#sync_md5sum').click(function(e) {
jQuery(this).hide();
jQuery('#add_md5sum').show();
var addBlockSize = Math.min(
Number((jQuery('#md5sum_to_add').data('origin') / 2).toFixed()),
1000
);
add_md5sum_block(addBlockSize);
return false;
});
function add_md5sum_block(blockSize){
jQuery.ajax({
url: "ws.php?format=json&method=pwg.images.setMd5sum",
type:"POST",
dataType: "json",
data: {
pwg_token: jQuery("input[name=pwg_token]").val(),
block_size: blockSize
},
success:function(data) {
jQuery('#md5sum_to_add').html(data.result.nb_no_md5sum);
var percent_remaining = Number(
(data.result.nb_no_md5sum * 100 / jQuery('#md5sum_to_add').data('origin')).toFixed()
);
var percent_done = 100 - percent_remaining;
jQuery('#md5sum_added').html(percent_done);
if (data.result.nb_no_md5sum > 0) {
add_md5sum_block();
}
else {
// time to refresh the whole page
var redirect_to = 'admin.php?page=batch_manager';
redirect_to += '&action=sync_md5sum';
redirect_to += '&nb_md5sum_added='+jQuery('#md5sum_to_add').data('origin');
document.location = redirect_to;
}
},
error:function(XMLHttpRequest) {
jQuery('#add_md5sum').hide();
jQuery('#add_md5sum_error').show().html('error '+XMLHttpRequest.status+' : '+XMLHttpRequest.statusText);
}
});
}
jQuery('#delete_orphans').click(function(e) {
jQuery(this).hide();
jQuery('#orphans_deletion').show();
var deleteBlockSize = Math.min(
Number((jQuery('#orphans_to_delete').data('origin') / 2).toFixed()),
1000
);
delete_orphans_block(deleteBlockSize);
return false;
});
function delete_orphans_block(blockSize) {
jQuery.ajax({
url: "ws.php?format=json&method=pwg.images.deleteOrphans",
type:"POST",
dataType: "json",
data: {
pwg_token: jQuery("input[name=pwg_token]").val(),
block_size: blockSize
},
success:function(data) {
jQuery('#orphans_to_delete').html(data.result.nb_orphans);
var percent_remaining = Number(
(data.result.nb_orphans * 100 / jQuery('#orphans_to_delete').data('origin')).toFixed()
);
var percent_done = 100 - percent_remaining;
jQuery('#orphans_deleted').html(percent_done);
if (data.result.nb_orphans > 0) {
delete_orphans_block();
}
else {
// time to refresh the whole page
var redirect_to = 'admin.php?page=batch_manager';
redirect_to += '&action=delete_orphans';
redirect_to += '&nb_orphans_deleted='+jQuery('#orphans_to_delete').data('origin');
document.location = redirect_to;
}
},
error:function(XMLHttpRequest) {
jQuery('#orphans_deletion').hide();
jQuery('#orphans_deletion_error').show().html('error '+XMLHttpRequest.status+' : '+XMLHttpRequest.statusText);
}
});
}
@@ -0,0 +1,511 @@
$(document).ready(function() {
// Detect unsaved changes on any inputs
let user_interacted = false;
$('input, textarea, select').on('focus', function() {
user_interacted = true;
});
$('input, textarea').on('input', function() {
const pictureId = $(this).parents("fieldset").data("image_id");
if (user_interacted == true) {
showUnsavedLocalBadge(pictureId);
}
});
// Specific handler for datepicker inputs
$('input[data-datepicker]').on('change', function() {
const pictureId = $(this).parents("fieldset").data("image_id");
if (user_interacted == true) {
showUnsavedLocalBadge(pictureId);
}
});
$('select').on('change', function() {
const pictureId = $(this).parents("fieldset").data("image_id");
if (user_interacted == true) {
showUnsavedLocalBadge(pictureId);
}
});
$('.related-categories-container .remove-item, .datepickerDelete').on('click', function() {
user_interacted = true;
const pictureId = $(this).parents("fieldset").data("image_id");
showUnsavedLocalBadge(pictureId);
});
// METADATA SYNC
$('.action-sync-metadata').on('click', function(event) {
const pictureId = $(this).parents("fieldset").data("image_id");
$.confirm({
title: str_meta_warning,
draggable: false,
titleClass: "metadataSyncConfirm",
theme: "modern",
content: "",
animation: "zoom",
boxWidth: '30%',
useBootstrap: false,
type: 'red',
animateFromElement: false,
backgroundDismiss: true,
typeAnimated: false,
buttons: {
confirm: {
text: str_meta_yes,
btnClass: 'btn-red',
action: function() {
disableLocalButton(pictureId);
$.ajax({
type: 'POST',
url: 'ws.php?format=json',
data: {
method: "pwg.images.syncMetadata",
pwg_token: jQuery("input[name=pwg_token]").val(),
image_id: pictureId
},
dataType: 'json',
success: function(data) {
const isOk = data.stat && data.stat === "ok";
if (isOk) {
updateBlock(pictureId);
} else {
showErrorLocalBadge(pictureId);
enableLocalButton(pictureId);
}
},
error: function(data) {
console.error("Error occurred");
enableLocalButton(pictureId);
}
});
}
},
cancel: {
text: str_no
}
}
});
});
// DELETE
$('.action-delete-picture').on('click', function(event) {
const $fieldset = $(this).parents("fieldset");
const pictureId = $fieldset.data("image_id");
$.confirm({
title: str_are_you_sure,
draggable: false,
titleClass: "groupDeleteConfirm",
theme: "modern",
content: "",
animation: "zoom",
boxWidth: '30%',
useBootstrap: false,
type: 'red',
animateFromElement: false,
backgroundDismiss: true,
typeAnimated: false,
buttons: {
confirm: {
text: str_yes,
btnClass: 'btn-red',
action: function() {
let image_ids = [pictureId];
(function(ids) {
$.ajax({
type: 'POST',
url: 'ws.php?format=json',
data: {
method: "pwg.images.delete",
pwg_token: jQuery("input[name=pwg_token]").val(),
image_id: ids.join(',')
},
dataType: 'json',
success: function(data) {
const isOk = data.stat && data.stat === "ok";
if (isOk) {
$fieldset.remove();
$('.pagination-container').css({
'pointer-events': 'none',
'opacity': '0.5'
});
$('.button-reload').css('display', 'block');
$('div[data-image_id="' + pictureId + '"]').css('display', 'flex');
} else {
showErrorLocalBadge(pictureId);
}
},
error: function(data) {
console.error("Error occurred");
}
});
})(image_ids);
image_ids = [];
}
},
cancel: {
text: str_no
}
}
});
});
// VALIDATION
//Unit Save
$('.action-save-picture').on('click', async function(event) {
const $fieldset = $(this).parents("fieldset");
const pictureId = $fieldset.data("image_id");
await saveChanges(pictureId);
});
//Global Save
$('.action-save-global').on('click', function(event) {
saveAllChanges();
});
//Categories
const ab = new AlbumSelector({
selectedCategoriesIds: [],
selectAlbum: add_related_category,
adminMode: true,
modalTitle: str_title_ab,
});
$(".linked-albums.add-item").on("click", function() {
b_current_picture_id = $(this).parents("fieldset").data("image_id");
ab.hardUpdate(all_related_categories_ids[b_current_picture_id]);
ab.open();
});
$('.related-categories-container').on('click', (e) => {
if (e.target.classList.contains("remove-item")) {
const cat_id = $(e.target).attr('id');
const picture_id = $(e.target).parents("fieldset").data("image_id");
remove_selected_category(cat_id, picture_id);
check_related_categories(picture_id, all_related_categories_ids[picture_id]);
}
});
pluginFunctionMapInit(activePlugins);
})
function get_related_category(pictureId) {
return all_related_categories_ids.find((c) => c.id == pictureId).cat_ids ?? [];
}
function remove_selected_category(cat_id, picture_id) {
const cat_to_remove_index = all_related_categories_ids[picture_id].indexOf(cat_id);
if (cat_to_remove_index > -1) {
all_related_categories_ids[picture_id].splice(cat_to_remove_index, 1);
showUnsavedLocalBadge(picture_id);
}
$("#" + picture_id + " #" + cat_id).parent().remove();
}
function add_related_category({ album, getSelectedAlbum, addSelectedAlbum }) {
if (!getSelectedAlbum().includes(album.id)) {
$("#" + b_current_picture_id + " .related-categories-container").append(
`<div class="breadcrumb-item album-listed">
<span class="link-path">${album.full_name_with_admin_links}</span><span id="${album.id}" class="icon-cancel-circled remove-item"></span>
</div>`
);
showUnsavedLocalBadge(b_current_picture_id);
addSelectedAlbum();
all_related_categories_ids[b_current_picture_id].cat_ids = getSelectedAlbum();
}
check_related_categories(b_current_picture_id, getSelectedAlbum());
}
function check_related_categories(pictureId, selectedAlbum) {
$("#picture-" + pictureId + " .linked-albums-badge").html(selectedAlbum.length);
if (selectedAlbum.length == 0) {
$("#" + pictureId + " .linked-albums-badge").addClass("badge-red");
$("#" + pictureId + " .add-item").addClass("highlight");
$("#" + pictureId + " .orphan-photo").html(str_orphan).show();
} else {
$("#" + pictureId + " .linked-albums-badge.badge-red").removeClass("badge-red");
$("#" + pictureId + " .add-item.highlight").removeClass("highlight");
$("#" + pictureId + " .orphan-photo").hide();
}
}
function updateUnsavedGlobalBadge() {
const visibleLocalUnsavedCount = $(".local-unsaved-badge").filter(function() {
return $(this).css('display') === 'block';
}).length;
if (visibleLocalUnsavedCount > 0) {
$(".global-unsaved-badge").css('display', 'block');
$("#unsaved-count").text(visibleLocalUnsavedCount);
} else {
$(".global-unsaved-badge").css('display', 'none');
$("#unsaved-count").text('');
}
}
function showUnsavedLocalBadge(pictureId) {
hideSuccesLocalBadge(pictureId);
hideErrorLocalBadge(pictureId);
$("#picture-" + pictureId + " .local-unsaved-badge").css('display', 'block');
updateUnsavedGlobalBadge();
}
function hideUnsavedLocalBadge(pictureId) {
$("#picture-" + pictureId + " .local-unsaved-badge").css('display', 'none');
updateUnsavedGlobalBadge();
}
// $(window).on('beforeunload', function() {
// if (user_interacted) {
// return "You have unsaved changes, are you sure you want to leave this page?";
// }
// });
//Error badge
function showErrorLocalBadge(pictureId) {
$("#picture-" + pictureId + " .local-error-badge").css('display', 'block');
}
function hideErrorLocalBadge(pictureId) {
$("#picture-" + pictureId + " .local-error-badge").css('display', 'none');
}
//Succes badge
function updateSuccessGlobalBadge() {
const visibleLocalSuccesCount = $(".local-success-badge").filter(function() {
return $(this).css('display') === 'block';
}).length;
if (visibleLocalSuccesCount > 0) {
showSuccesGlobalBadge()
} else {
hideSuccesGlobalBadge()
}
}
function showSuccessLocalBadge(pictureId) {
const badge = $("#picture-" + pictureId + " .local-success-badge");
badge.css({
'display': 'block',
'opacity': 1
});
setTimeout(() => {
badge.fadeOut(1000, function() {
badge.css('display', 'none');
});
}, 3000);
}
function hideSuccesLocalBadge(pictureId) {
$("#picture-" + pictureId + " .local-success-badge").css('display', 'none');
}
function showSuccesGlobalBadge() {
const badge = $(".global-succes-badge");
badge.css({
'display': 'block',
'opacity': 1
});
setTimeout(() => {
badge.fadeOut(1000, function() {
badge.css('display', 'none');
});
}, 3000);
}
function hideSuccesGlobalBadge() {
$("global-succes-badge").css('display', 'none');
}
function showMetasyncSuccesBadge(pictureId) {
const badge = $("#picture-" + pictureId + " .metasync-success");
badge.css({
'display': 'block',
'opacity': 1
});
setTimeout(() => {
badge.fadeOut(1000, function() {
badge.css('display', 'none');
});
}, 3000);
}
function disableLocalButton(pictureId) {
$("#picture-" + pictureId + " .action-save-picture").addClass("disabled");
$("#picture-" + pictureId + " .action-save-picture i").removeClass("icon-floppy").addClass("icon-spin6 animate-spin");
disableGlobalButton();
}
function enableLocalButton(pictureId) {
$("#picture-" + pictureId + " .action-save-picture").removeClass("disabled");
$("#picture-" + pictureId + " .action-save-picture i").removeClass("icon-spin6 animate-spin").addClass("icon-floppy");
}
function disableGlobalButton() {
$(".action-save-global").addClass("disabled");
$(".action-save-global i").removeClass("icon-floppy").addClass("icon-spin6 animate-spin");
}
function enableGlobalButton() {
$(".action-save-global").removeClass("disabled");
$(".action-save-global i").removeClass("icon-spin6 animate-spin").addClass("icon-floppy");
}
async function saveChanges(pictureId) {
if ($("#picture-" + pictureId + " .local-unsaved-badge").css('display') === 'block') {
disableLocalButton(pictureId);
// Retrieve Infos
const name = $("#picture-" + pictureId + " #name").val();
const author = $("#picture-" + pictureId + " #author").val();
const date_creation = $("#picture-" + pictureId + " #date_creation").val();
const comment = $("#picture-" + pictureId + " #description").val();
const level = $("#picture-" + pictureId + " #level option:selected").val();
// Get Categories
const categories = all_related_categories_ids[pictureId];
let categoriesStr = categories.join(';');
// Get Tags
let tags = [];
$("#picture-" + pictureId + " #tags option").each(function () {
let tagId = $(this).val();
tags.push(tagId);
});
let tagsStr = tags.join(',');
let ajax_data = {
method: 'pwg.images.setInfo',
image_id: pictureId,
name: name,
author: author,
date_creation: date_creation,
comment: comment,
categories: categoriesStr,
// tag_ids: tagsStr,
tag_list: tags,
level: level,
single_value_mode: "replace",
multiple_value_mode: "replace",
pwg_token: jQuery("input[name=pwg_token]").val()
};
for (let key_index in pluginValues) {
let pluginValues_selector = pluginValues[key_index].selector;
let full_selector = $("#picture-" + pictureId + " " + pluginValues_selector);
let pluginValues_value = full_selector.val();
ajax_data[pluginValues[key_index].api_key] = pluginValues_value;
}
await $.ajax({
url: 'ws.php?format=json',
method: 'POST',
dataType: 'json',
data: ajax_data,
success: function(data) {
const isOk = data.stat && data.stat === 'ok';
if (isOk) {
enableLocalButton(pictureId);
enableGlobalButton();
hideUnsavedLocalBadge(pictureId);
showSuccessLocalBadge(pictureId);
updateSuccessGlobalBadge();
// Method 1 for extension's save (see Skeleton extension for more details)
pluginSaveLoop(activePlugins, pictureId);
}
else {
console.error("Error: " + data);
enableLocalButton(pictureId);
enableGlobalButton();
hideUnsavedLocalBadge(pictureId);
showErrorLocalBadge(pictureId);
updateSuccessGlobalBadge();
}
},
error: function(xhr, status, error) {
enableLocalButton(pictureId);
enableGlobalButton();
hideUnsavedLocalBadge(pictureId);
showErrorLocalBadge(pictureId);
updateSuccessGlobalBadge();
console.error('Error:', error);
}
});
}
}
async function saveAllChanges() {
const allField = $("fieldset").toArray();
for (let field of allField) {
const pictureId = $(field).data("image_id");
await saveChanges(pictureId);
}
}
//PLUGINS SAVE METHOD
const pluginFunctionMap = {};
function pluginFunctionMapInit(activePlugins) {
activePlugins.forEach(function(pluginId) {
const functionName = pluginId + '_batchManagerSave';
if (typeof window[functionName] === 'function') {
pluginFunctionMap[pluginId] = window[functionName];
}
});
}
function pluginSaveLoop(activePlugins, pictureId) {
if (activePlugins.length === 0) {
return;
}
activePlugins.forEach(function(pluginId) {
const saveFunction = pluginFunctionMap[pluginId];
if (typeof saveFunction === 'function') {
saveFunction(pictureId);
}
});
}
// UPDATE BLOCKS
function updateBlock(pictureId) {
$.ajax({
url: 'ws.php?format=json',
type: 'GET',
dataType: 'json',
data: {
method: 'pwg.images.getInfo',
image_id: pictureId
},
success: function(response) {
if (response.stat === 'ok') {
$("#picture-" + pictureId + " #name").val(response.result.name);
$("#picture-" + pictureId + " #author").val(response.result.author);
$("#picture-" + pictureId + " #date_creation").val(response.result.date_creation); //TODO
$("#picture-" + pictureId + " #description").val(response.result.comment);
$("#picture-" + pictureId + " #level").val(response.result.level);
$("#picture-" + pictureId + " #filename").text(response.result.file);
$("#picture-" + pictureId + " #filesize").text(response.result.filesize);
$("#picture-" + pictureId + " #dimensions").text(response.result.width + "x" + response.result.height);
// updateTags(response.result.tags, pictureId); //Yet to be implemented (TODO)
showMetasyncSuccesBadge(pictureId);
enableLocalButton(pictureId);
enableGlobalButton();
} else {
console.error("Error:", response.message);
showErrorLocalBadge(pictureId);
enableLocalButton(pictureId);
enableGlobalButton();
}
},
error: function(xhr, status, error) {
console.error("Error:", status, error);
showErrorLocalBadge(pictureId);
enableLocalButton(pictureId);
}
});
}
// TAGS UPDATE Yet to be implemented
// function updateTags(tagsData, pictureId) {
// const $tagsUpdate = $('#tags-'+pictureId).selectize({
// create: true,
// persist: false
// });
// const selectizeTags = $tagsUpdate[0].selectize;
// const transformedData = tagsData.map(function(item) {
// return {
// value: item.id,
// text: item.name
// };
// })
// console.log(transformedData);
// selectizeTags.clearOptions();
// selectizeTags.addOption(transformedData);
// selectizeTags.refreshOptions(true);
// };
@@ -0,0 +1,494 @@
function setDisplayCompact() {
removeIconDesc();
$(".albumActions").css("display", "flex");
removeHoverEffect($(".categoryBox"));
removeHoverEffect($(".categoryBox").children(".albumActions").children("a"));
$(".categoryBox").children(".albumActions").children("a").hover(function () {
$(this).css({
color : "#000000",
});
}, function () {
$(this).css({
color : "#848484",
});
});
$(".categoryBox").removeClass("line_cat").removeClass("tile_cat");
$(".addAlbum").removeClass("tile_add");
$(".categoryBox").css({
minWidth: "250px",
maxWidth: "350px",
flexDirection: "column",
maxHeight: "180px",
alignItems: "unset",
margin: "15px"
});
$(".albumInfos").css({
marginLeft: "0",
flexDirection: "column"
});
// $(".albumIcon").css({
// height: "80px"
// });
// $(".albumIcon span").css({
// fontSize: "19px",
// width: "27px",
// padding: "10px"
// });
$(".albumIcon").css({
height: "60px"
});
$(".albumIcon span").css({
fontSize: "14px",
width: "20px",
padding: "8px"
});
$(".albumInfos p").css({
margin: "0",
textAlign: "center",
whiteSpace: "normal"
});
$(".albumInfos p:last-child").css({
width: "auto"
});
$(".albumTop").css({
width: "auto",
justifyContent: "center",
flexDirection: "row",
alignItems: "baseline",
height: "65px"
});
$(".albumTitle").css("padding", "0 15px");
$(".addAlbum").css({
minWidth : "250px",
maxWidth: "350px",
flexDirection: "column",
maxHeight: "180px",
margin: "15px"
});
$(".addAlbum form label").css({
display: "none"
});
$(".addAlbumHead").css({
flexDirection: "column",
transform: "translateY(55px)",
alignItems: "center",
marginTop: "-10px",
transition: "0.4s ease",
marginBottom: "0px"
});
$(".addAlbum form").css("flex-direction", "column");
$(".addAlbum form").css({
flexDirection: "column",
marginTop: "0",
marginBottom: "0",
transitionDelay: "0s"
});
$(".addAlbum.input-mode form").css({
transitionDelay: "0.4s",
});
$(".addAlbum form input").css("margin", "0px 10px 0px 10px");
$(".addAlbum form button").css("margin", "10px auto 0 auto");
$(".addAlbum p").css("margin-bottom", "0px");
$(".addAlbumHead p").css("margin-left", "0");
$(".addAlbumHead span").css({
fontSize:"14px",
width: "20px",
height: "20px",
padding: "8px"
});
$(".albumActions").css({
flexDirection : "row",
marginTop: "auto",
width: "100%"
});
$(".albumActions a").css({
minWidth : "0px"
});
$(".albumActions a:first-child").css("margin-left", "35px");
$(".albumActions a:last-child").css("margin-right", "35px");
}
function setDisplayLine() {
/*********** Hover stuff ***********/
removeIconDesc();
$(".albumActions").css("display", "flex");
removeHoverEffect($(".categoryBox"));
$(".categoryBox").hover(function () {
$(this).css("background", "#ffd7ad");
$(this).children(".albumInfos").css({
color: "#515151"
});
$(this).children(".albumActions").children("a").css({
color: "#515151",
});
$(this).children(".albumTop").children(".albumIcon").children("span").addClass("albumIconLineHover");
}, function () {
$(this).css("background", "#fafafa");
$(this).children(".albumInfos").css({
color: "#a9a9a9"
});
$(this).children(".albumActions").children("a").css({
color: "#848484"
});
$(this).children(".albumTop").children(".albumIcon").children("span").removeClass("albumIconLineHover");
})
$(".categoryBox").children(".albumActions").children("a").hover(function () {
$(this).css({
color : "#000000",
});
}, function () {
$(this).css({
color : "#515151",
});
});
/************************************/
$(".categoryBox").addClass("line_cat").removeClass("tile_cat");
$(".addAlbum").removeClass("tile_add");
$(".categoryBox").css({
minWidth: "90%",
maxWidth: "100%",
flexDirection: "row",
maxHeight: "60px",
alignItems: "unset",
margin: "5px 15px"
});
$(".albumIcon").css({
height: "60px"
});
$(".albumIcon span").css({
fontSize: "14px",
width: "20px",
padding: "8px"
});
$(".addAlbumHead span").css({
fontSize:"14px",
width: "20px",
height: "20px",
padding: "8px"
});
$(".albumInfos").css({
marginLeft: "auto",
flexDirection: "row",
justifyContent: "space-around",
width: "auto"
});
$(".albumInfos p").css({
textAlign: "right",
margin: "0",
whiteSpace: "nowrap"
});
$(".albumInfos p:last-child").css({
width: "270px"
});
$(".albumTop").css({
width: "35%",
justifyContent: "flex-start",
flexDirection: "row",
alignItems : "baseline",
height: "75px"
});
$(".albumTitle").css("padding", "0 15px");
$(".addAlbum").css({
minWidth: "90%",
maxWidth: "100%",
flexDirection: "row",
maxHeight: "60px",
margin: "15px 15px 5px 15px"
});
$(".addAlbum form label").css({
display: "none"
});
$(".addAlbumHead").css({
flexDirection: "row",
transform: "translateY(0)",
alignItems: "center",
marginTop: "0",
transform: "translateX(200px)",
marginBottom: "0"
});
$(".addAlbum form").css({
flexDirection: "row",
marginTop: "0",
marginBottom: "0",
transitionDelay: "0s"
});
$(".addAlbum.input-mode form").css({
transitionDelay: "0s",
});
$(".addAlbum form").css("align-items", "center");
$(".addAlbum form input").css("margin", "0px 10px 0px 10px");
$(".addAlbum form button").css("margin", "0px 20px");
$(".addAlbum p").css("margin-bottom", "0px");
$(".addAlbumHead p").css("margin-left", "15px");
$(".albumActions").css({
flexDirection : "row",
margin: "auto 0px",
width: "300px",
});
$(".albumActions a").css({
minWidth : "30px"
});
$(".albumActions a:first-child").css("margin-left", "35px");
$(".albumActions a:last-child").css("margin-right", "35px");
}
function setDisplayTile() {
ShowIconDesc();
$(".albumActions").css("display", "flex");
removeHoverEffect($(".categoryBox"));
removeHoverEffect($(".categoryBox").children(".albumActions").children("a"));
$(".categoryBox").children(".albumActions").children("a").hover(function () {
$(this).css({
color : "#FFA646"
})
}, function () {
$(this).css({
color : "#848484"
})
});
AddHoverOnAlbumActions();
$(".addAlbum.input-mode form").css({
transitionDelay: "0s",
});
$(".categoryBox").removeClass("line_cat").addClass("tile_cat");
$(".addAlbum").addClass("tile_add");
$(".categoryBox").css({
minWidth: "220px",
maxWidth: "280px",
flexDirection: "column",
maxHeight: "320px",
alignItems: "center",
margin: "15px"
});
$(".albumActions").css({
flexDirection : "column",
margin:"auto",
alignItems: "flex-start",
width: "75%",
});
$(".albumInfos").css({
marginLeft: "0",
flexDirection: "column",
});
$(".albumInfos p:last-child").css({
width: "auto"
});
$(".albumInfos p").css({
margin: "0",
textAlign: "center",
whiteSpace: "normal"
});
$(".albumIcon").css({
height: "80px"
});
$(".albumIcon span").css({
fontSize: "19px",
width: "27px",
padding: "10px"
});
$(".albumTop").css({
width: "85%",
flexDirection: "column",
alignItems: "unset",
height: "110px",
});
$(".albumTitle").css("padding", "0");
$(".addAlbum").css({
minWidth: "220px",
maxWidth: "280px",
flexDirection: "column",
maxHeight: "320px",
margin: "15px"
});
$(".addAlbumHead").css({
flexDirection: "column",
transform: "translateY(75px)",
alignItems: "center",
marginTop: "10px",
transition: "0.4s ease",
marginBottom: "0"
});
$(".addAlbum form").css({
flexDirection: "column",
marginTop: "auto",
marginBottom: "20px",
transitionDelay: "0s"
});
$(".addAlbum form input").css("margin", "0px 10px 10px 10px");
$(".addAlbum form button").css("margin", "10px auto 0 auto");
$(".addAlbum p").css("margin-bottom", "20px");
$(".addAlbum form label").css({
display: "flex",
margin: "-25px 0 0 15px"
});
$(".addAlbumHead p").css("margin-left", "0");
$(".addAlbumHead span").css({
fontSize:"19px",
width: "27px",
height: "27px",
padding: "10px"
});
$(".albumInfos p").css("margin", "0");
$(".albumActions a").css({
minWidth : "0px"
});
$(".albumActions a:first-child").css("margin-left", "5px");
$(".albumActions a:last-child").css("margin-left", "5px");
}
function ShowIconDesc() {
$(".albumActions span.iconLegend").show();
}
function removeIconDesc() {
$(".albumActions span.iconLegend").hide();
}
function removeHoverEffect(e) {
e.unbind('mouseenter').unbind('mouseleave');
}
function AddHoverOnAlbumActions() {
$(".albumActions").css("display", "none");
$(".categoryBox").hover(function () {
$(this).children(".albumActions").css("display", "flex");
}, function () {
$(this).children(".albumActions").css("display", "none");
});
}
$(document).ready(function () {
if (!$.cookie("pwg_album_manager_view")) {
$.cookie("pwg_album_manager_view", "tile");
}
$(".addAlbum").on("click", function (e) {
if (e.target.className !== "cancelAddAlbum") {
$(".addAlbum").addClass('input-mode');
if ($.cookie("pwg_album_manager_view") !== "tile") {
$(".addAlbum p").hide(300);
}
};
});
$(".cancelAddAlbum").on("click", function () {
$('.addAlbum').removeClass('input-mode');
$(".addAlbum p").show(800);
});
if ($("#displayCompact").is(":checked")) {
setDisplayCompact();
};
if ($("#displayLine").is(":checked")) {
setDisplayLine();
};
if ($("#displayTile").is(":checked")) {
setDisplayTile();
};
$("#displayCompact").change(function () {
setDisplayCompact();
if ($(".addAlbum").hasClass("input-mode")) {
$(".addAlbum p").hide();
}
$.cookie("pwg_album_manager_view", "compact");
});
$("#displayLine").change(function () {
setDisplayLine();
if ($(".addAlbum").hasClass("input-mode")) {
$(".addAlbum p").hide();
}
$.cookie("pwg_album_manager_view", "line");
});
$("#displayTile").change(function () {
setDisplayTile();
if ($(".addAlbum").hasClass("input-mode")) {
$(".addAlbum p").show();
}
$.cookie("pwg_album_manager_view", "tile");
});
});
@@ -0,0 +1,511 @@
jQuery(document).ready(function() {
activateCommentDropdown();
checkAlbumLock();
const ab = new AlbumSelector({
selectedCategoriesIds: related_categories_ids,
selectAlbum: add_related_category,
showRootButton: true,
adminMode: true,
currentAlbumId: album_id,
modalTitle: str_modal_ab,
});
$(".unlock-album").on('click', function () {
jQuery.ajax({
url: "ws.php?format=json&method=pwg.categories.setInfo",
type:"POST",
dataType: "json",
data: {
category_id: album_id,
visible: 'true',
},
success:function(data) {
if (data.stat == "ok") {
is_visible = 'true';
if ($("#cat-locked").is(":checked")) {
$("input[id='cat-locked']").trigger('click');
}
checkAlbumLock();
setTimeout(
function() {
$('.info-message').hide()
},
5000
)
} else {
$('.info-error').show()
setTimeout(
function() {
$('.info-error').hide()
},
5000
)
}
},
error:function(XMLHttpRequest, textStatus, errorThrows) {
save_button_set_loading(false)
$('.info-error').show()
setTimeout(
function() {
$('.info-error').hide()
},
5000
)
console.log(errorThrows);
}
});
})
jQuery('.tiptip').tipTip({
'delay' : 0,
'fadeIn' : 200,
'fadeOut' : 200
});
$('#cat-properties-save').click(() => {
save_button_set_loading(true)
$('.info-error,.info-message').hide()
jQuery.ajax({
url: "ws.php?format=json&method=pwg.categories.setInfo",
type:"POST",
dataType: "json",
data: {
category_id: album_id,
name: $("#cat-name").val(),
comment: $("#cat-comment").val(),
visible: $("#cat-locked").is(":checked") ? 'false' : 'true',
commentable: $("#cat-commentable").is(":checked") ? "true":"false",
pwg_token: pwg_token,
},
success:function(data) {
if (data.stat == "ok") {
save_button_set_loading(false)
$('.info-message').show()
$('.cat-modification .cat-modify-info-subcontent').html(str_just_now)
$('.cat-modification .cat-modify-info-content').html(str_just_now)
is_visible = $("#cat-locked").is(":checked") ? 'false' : 'true';
checkAlbumLock();
setTimeout(
function() {
$('.info-message').hide()
},
5000
)
} else {
$('.info-error').show()
setTimeout(
function() {
$('.info-error').hide()
},
5000
)
}
},
error:function(XMLHttpRequest, textStatus, errorThrows) {
save_button_set_loading(false)
$('.info-error').show()
setTimeout(
function() {
$('.info-error').hide()
},
5000
)
console.log(errorThrows);
}
});
if (parent_album != default_parent_album) {
jQuery.ajax({
url: "ws.php?format=json&method=pwg.categories.move",
type:"POST",
dataType: "json",
data: {
category_id: album_id,
parent: parent_album,
pwg_token: pwg_token,
},
success: function (data) {
if (data.stat === "ok") {
$(".cat-modify-ariane").html(
data.result.new_ariane_string
)
default_parent_album = parent_album;
} else {
$('.info-error').show()
setTimeout(
function() {
$('.info-error').hide()
},
5000
)
}
},
error: function(e) {
console.log(e.message);
}
});
}
})
function save_button_set_loading(state = true) {
if (state) {
$('#cat-properties-save i').removeClass("icon-floppy")
$('#cat-properties-save i').addClass("icon-spin6")
$('#cat-properties-save i').addClass("animate-spin")
} else {
$('#cat-properties-save i').addClass("icon-floppy")
$('#cat-properties-save i').removeClass("icon-spin6")
$('#cat-properties-save i').removeClass("animate-spin")
}
$('#cat-properties-save').attr("disabled", state)
}
$(".deleteAlbum").on("click", function() {
$.confirm({
title: str_delete_album,
content : function () {
const self = this
return $.ajax({
url: "ws.php?format=json&method=pwg.categories.calculateOrphans",
type: "GET",
data: {
category_id: album_id,
},
success: function (raw_data) {
let data = JSON.parse(raw_data).result[0]
let message = "<p>" + str_delete_album_and_his_x_subalbums
.replace("%s", "<strong>"+album_name+"</strong>")
.replace("%d", "<strong>"+nb_sub_albums+"</strong>") + "</p>"
message += `<div class="cat-delete-modes">`;
message +=
`<div ${data.nb_images_recursive? "":"style='display:none'"}>
<input type="radio" name="deletion-mode" value="no_delete" id="no_delete" checked>
<label for="no_delete">${str_dont_delete_photos}</label>
</div>`;
if (data.nb_images_recursive) {
let t = 0
message += `<div>
<input type="radio" name="deletion-mode" value="force_delete" id="force_delete">
<label for="force_delete">${str_delete_all_photos.replaceAll("%d", _ => [data.nb_images_recursive, data.nb_images_associated_outside][t++])}</label>
</div>`;
}
if (data.nb_images_becoming_orphan)
message +=
`<div>
<input type="radio" name="deletion-mode" value="delete_orphans" id="delete_orphans">
<label for="delete_orphans">${str_delete_orphans.replace("%d", data.nb_images_becoming_orphan)}</label>
</div>`;
message += `</div>`;
self.setContent(message)
},
error: function(message) {
console.log(message);
self.setContent("An error has occured while calculating orphans")
}
});
},
buttons: {
deleteAlbum: {
text: str_delete_album,
btnClass: 'btn-red',
action: function () {
this.showLoading()
let deletionMode = $('input[name="deletion-mode"]:checked').val();
delete_album(deletionMode)
.then(()=>window.location.href = u_delete)
.catch((err)=> {
this.close()
console.log(err)
})
return false
},
},
cancel: {
text: str_cancel
}
},
...jConfirm_confirm_options
})
});
function delete_album(photo_deletion_mode) {
return new Promise((res, rej) => {
$.ajax({
url: "ws.php?format=json&method=pwg.categories.delete",
type: "POST",
data: {
category_id: album_id,
photo_deletion_mode: photo_deletion_mode,
pwg_token : pwg_token,
},
success: function (raw_data) {
res()
},
error: function(message) {
rej(message)
}
});
})
}
$('#refreshRepresentative').on('click', function(e) {
var method = 'pwg.categories.refreshRepresentative';
$('#refreshRepresentative i').removeClass("icon-ccw").addClass("icon-spin6").addClass("animate-spin")
jQuery.ajax({
url: "ws.php?format=json&method="+method,
type:"POST",
data: {
category_id: album_id
},
success:function(data) {
var data = jQuery.parseJSON(data);
if (data.stat == 'ok') {
jQuery("#deleteRepresentative").show();
jQuery(".cat-modify-representative")
.attr('style', `background-image:url('${data.result.src}')`)
.removeClass('icon-dice-solid')
}
else {
console.error(data);
}
$('#refreshRepresentative i').addClass("icon-ccw").removeClass("icon-spin6").removeClass("animate-spin")
},
error:function(XMLHttpRequest, textStatus, errorThrows) {
console.error(errorThrows);
$('#refreshRepresentative i').addClass("icon-ccw").removeClass("icon-spin6").removeClass("animate-spin")
}
});
e.preventDefault();
});
$('#deleteRepresentative').on('click', function(e) {
var method = 'pwg.categories.deleteRepresentative';
$('#deleteRepresentative i').removeClass("icon-cancel").addClass("icon-spin6").addClass("animate-spin")
jQuery.ajax({
url: "ws.php?format=json&method="+method,
type:"POST",
data: {
category_id: album_id
},
success:function(data) {
var data = jQuery.parseJSON(data);
if (data.stat == 'ok') {
jQuery("#deleteRepresentative").hide();
jQuery(".cat-modify-representative")
.attr('style', ``)
.addClass('icon-dice-solid')
}
else {
console.error(data);
}
$('#deleteRepresentative i').addClass("icon-cancel").removeClass("icon-spin6").removeClass("animate-spin")
},
error:function(XMLHttpRequest, textStatus, errorThrows) {
console.error(errorThrows);
$('#deleteRepresentative i').addClass("icon-cancel").removeClass("icon-spin6").removeClass("animate-spin")
}
});
e.preventDefault();
});
// Parent album popin
$("#cat-parent.icon-pencil").on("click", function (e) {
// Don't open the popin if you click on the album link
if (e.target.localName != 'a') {
ab.open();
}
});
$(".allow-comments").on("click", function () {
jQuery.ajax({
url: "ws.php?format=json&method=pwg.categories.setInfo",
type:"POST",
dataType: "json",
data: {
category_id: album_id,
commentable: true,
apply_commentable_to_subalbums: true,
},
beforeSend: function () {
save_button_set_loading(true);
},
success:function(data) {
if (data.stat == "ok") {
save_button_set_loading(false);
if (!$("#cat-commentable").is(":checked")) {
$("#cat-commentable").trigger("click");
}
temp_txt = $(".info-message").text();
$(".info-message").text(str_album_comment_allow);
$(".info-message").show();
setTimeout(
function() {
$('.info-message').hide()
$(".info-message").text(temp_txt);
},
5000
)
} else {
$('.info-error').show()
setTimeout(
function() {
$('.info-error').hide()
},
5000
)
}
},
error:function(e) {
console.log(e);
save_button_set_loading(false);
}
});
});
$(".disallow-comments").on("click", function () {
jQuery.ajax({
url: "ws.php?format=json&method=pwg.categories.setInfo",
type:"POST",
dataType: "json",
data: {
category_id: album_id,
commentable: false,
apply_commentable_to_subalbums: true,
},
beforeSend: function () {
save_button_set_loading(true);
},
success:function(data) {
if (data.stat == "ok") {
save_button_set_loading(false);
if ($("#cat-commentable").is(":checked")) {
$("#cat-commentable").trigger("click");
}
temp_txt = $(".info-message").text();
$(".info-message").text(str_album_comment_disallow);
$(".info-message").show();
setTimeout(
function() {
$('.info-message').hide()
$(".info-message").text(temp_txt);
},
5000
)
} else {
$('.info-error').show()
setTimeout(
function() {
$('.info-error').hide()
},
5000
)
}
},
error:function(e) {
console.log(e);
save_button_set_loading(false);
}
});
});
// Modal description
let form_unsaved = false;
const cat_modify = $('#cat-modify');
const desc_modal = $('#desc-modal');
const textareas = $('.sync-textarea');
$('#desc-zoom-square, #desc-modal-close').on('click', function() {
desc_modal.fadeToggle();
});
textareas.keyup(function() {
textareas.val($(this).val());
});
$(window).on('click', function(e) {
if(e.target == desc_modal[0]){
desc_modal.fadeToggle();
}
});
$(document).on('keyup', function (e) {
// 27 is 'Escape'
if(e.keyCode === 27 && desc_modal.is(':visible')) {
desc_modal.fadeToggle();
}
});
});
function checkAlbumLock() {
if (is_visible == 'true') {
$(".warnings").hide();
} else {
$(".warnings").css('display', 'flex');
}
}
// Parent album popin functions
function add_related_category({ album, newSelectedAlbum, getSelectedAlbum }) {
if (parent_album != album.id) {
$("#cat-parent").html(
album.full_name_with_admin_links ?? album.root
);
$(".search-result-item #" + album.id).addClass("notClickable");
$(".invisible-related-categories-select").append("<option selected value="+ album.id +"></option>");
newSelectedAlbum();
parent_album = getSelectedAlbum()[0];
}
}
function activateCommentDropdown() {
$(".toggle-comment-option").find(".comment-option").hide();
/* Display the option on the click on "..." */
$(".toggle-comment-option").on("click", function () {
$(this).find(".comment-option").toggle();
})
/* Hide img options and rename field on click on the screen */
$(document).mouseup(function (e) {
e.stopPropagation();
let option_is_clicked = false
$(".comment-option span").each(function () {
if (!($(this).has(e.target).length === 0)) {
option_is_clicked = true;
}
})
if (!option_is_clicked) {
$(".toggle-comment-option").find(".comment-option").hide();
}
});
}
@@ -0,0 +1,118 @@
const RESULT_LIMIT = 100;
const editLink = "admin.php?page=album-";
const colors = ["icon-red", "icon-blue", "icon-yellow", "icon-purple", "icon-green"];
$(function() {
$(".limit-album-reached").hide();
$('#cat_search_input').on('input', () => {
updateSearch();
});
})
// Update the page according to the search field
function updateSearch () {
let string = $('.search-input').val();
$('.search-album-result').html("");
$('.search-album-noresult').hide();
$(".limit-album-reached").hide();
if (string == '') {
// help button unnecessary so do not show
// $('.search-album-help').show();
$('.search-album-ghost').show();
$('.search-album-num-result').hide();
hideSearchContainer();
} else {
$('.search-album-ghost').hide();
$('.search-album-help').hide();
$('.search-album-num-result').show();
showSearchContainer();
let nbResult = 0;
nbResult = searchAlbumByName(data, string, nbResult);
if (nbResult != 1) {
if (nbResult >= RESULT_LIMIT) {
$('.search-album-num-result').html(str_result_limit.replace('%d', nbResult));
} else {
$('.search-album-num-result').html(str_albums_found.replace('%d', nbResult));
}
} else {
$('.search-album-num-result').html(str_album_found);
}
if (nbResult != 0) {
resultAppear($('.search-album-result .search-album-elem').first());
} else {
$('.search-album-noresult').show();
}
}
}
function searchAlbumByName(categories, search, nbResult, children, name='') {
for (const c of categories) {
if (nbResult >= RESULT_LIMIT) {
return nbResult;
}
let currentName = name + `<a href="${editLink + c.id}">${c.name}</a>` + ' / ';
if (c.name.toString().toLowerCase().includes(search.toLowerCase())) {
const haveChild = c.children && c.children.length ? true : false;
nbResult++;
addAlbumResult(c, nbResult, haveChild, currentName);
}
if (c.children && c.children.length) {
nbResult = searchAlbumByName(c.children, search, nbResult, true, currentName);
}
}
return nbResult;
}
// Add an album as a result in the page
function addAlbumResult (cat, nbResult, haveChildren, name) {
const id = +cat.id;
const template = $('.search-album-elem-template').html();
const newCatNode = $(template);
if (haveChildren) {
newCatNode.find('.search-album-icon').addClass('icon-sitemap');
} else {
newCatNode.find('.search-album-icon').addClass('icon-folder-open');
}
const colorId = id%5;
newCatNode.find('.search-album-icon').addClass(colors[colorId]);
newCatNode.find('.search-album-name').html(name.slice(0, -2));
const href = "admin.php?page=album-" + id;
newCatNode.find('.search-album-edit').attr('href', href);
$('.search-album-result').append(newCatNode);
if(nbResult >= RESULT_LIMIT) {
$(".limit-album-reached").show(1000);
$('.limit-album-reached').html(str_result_limit.replace('%d', nbResult));
}
}
// Make the results appear one after one [and limit results to 100]
function resultAppear(result) {
result.fadeIn();
if (result.next().length != 0) {
setTimeout(() => {resultAppear(result.next().first())}, 50);
}
}
function showSearchContainer() {
$('.tree').hide();
$('.album-search-result-container').show();
}
function hideSearchContainer() {
$('.album-search-result-container').hide();
$('.tree').fadeIn();
}
@@ -0,0 +1,618 @@
const commentsContainer = $('#comments');
const advancedFilters = $('#advancedFilters');
const switchMode = $('#toggleSelectionMode');
const commentContainer = $('#commentContainer');
const commentsAll = $('#commentsAll');
const commentsValidated = $('#commentsValidated');
const commentsPending = $('#commentsPending');
const commentsList = $('#commentsList');
const commentsNb = $('#commentsNb a');
const filterAuthor = $('#filter_author');
const filterDateStart = $('#filter_date_start');
const filterDateEnd = $('#filter_date_end');
const commentsSelectController = $('#commentsSelectController');
const tabFilters = $('#tabFilters');
const commentsSelectedArea = $('#commentsSelected');
const commentsSelectedOthers = $('#commentsSelectedOthers');
const modalViewComment = $('#modalViewComment');
const commentsPaginElipsis = '<span>...</span>';
const commentsPaginItems = '<a id="comments_page_%d" class="comments-paging" data-page="%d">%d</a>';
const commentsPaginItemsCurrent = '<a id="comments_page_%d" class="comments-paging comment-paging-current" data-page="%d">%d</a>';
const commentsOptionsFiltersAuthor = '<option value="" selected="">--</option>';
const commentsSelectedList = '<div class="comments-selected-item"><a class="icon-cancel comments-selected-remove" id="deletecomment_%d"></a> <p>#%d</p></div>';
let commentsState = {};
let commentsParams = {
status: 'all',
page: 0,
per_page: 5,
}
let updateAuthorId = true;
let searchTimeOut = null;
let selectionMode = false;
let commentsSelected = [];
$(function() {
$('#commentFilters').on('click', function() {
$(this).toggleClass('advanced-filter-open');
advancedFilters.toggle();
});
switchMode.on('change', function() {
$('#contentSelectMode').toggle();
$('#headerSelectMode, #contentSelectMode').toggleClass('selection-mode');
commentContainer.toggleClass('active');
if (!commentContainer.hasClass('active')) {
selectionMode = false;
$('.comment-select-checkbox').hide();
$('.comment-buttons').show();
commentsSelectController.removeClass('show');
tabFilters.show();
commentsUnselectAll();
} else {
selectionMode = true;
$('.comment-select-checkbox').show();
$('.comment-buttons').hide();
tabFilters.hide();
commentsSelectController.addClass('show');
}
});
$('#selectAll').on('click', function() {
commentsSelectAll();
});
$('#selectNone').on('click', function() {
commentsUnselectAll();
});
$('#selectInvert').on('click', function() {
commentsInvertSelect();
});
$('.tab-filters input').on('change', function() {
commentsParams.status = $(this).attr('data-status');
commentsParams.page = 0;
getComments(commentsParams);
});
commentsNb.on('click', function() {
const nb = $(this).text();
updateNbComments(nb);
commentsParams.page = 0;
getComments(commentsParams);
});
$('#closeModalViewComment').on('click', function() {
closeModalViewComment();
});
$('#commentSearchInput').on('input', function() {
clearTimeout(searchTimeOut);
searchTimeOut = setTimeout(() => {
const search = $(this).val();
delete commentsParams.author_id;
delete commentsParams.f_min_date;
delete commentsParams.f_max_date;
commentsParams.search = search;
getComments(commentsParams);
}, 300);
});
$('#commentsResetFilters').on('click', function() {
commentsClearFilters();
});
$(window).on('keydown', function(e) {
if (e.key === 'Escape') {
closeModalViewComment();
}
});
// get comments and set display
commentsParams.per_page = window.localStorage.getItem('adminCommentsNB') ?? 5
updateNbComments(commentsParams.per_page);
getComments(commentsParams);
});
function getComments(params) {
$.ajax({
url: 'ws.php?format=json&method=pwg.userComments.getList',
type: 'GET',
dataType: 'json',
data: params,
success: (data) => {
if (data.stat === 'ok') {
// for debug
// console.log(data.result);
commentsState = {...data.result};
commentsDisplaySummary(data.result.summary);
displayComments(data.result.comments);
commentsDiplayPagination(data.result.paging);
commentsDisplayFilters(data.result.filters);
delete commentsParams.search;
}
},
error: (e) => {
console.log(e);
$.alert({ title: str_an_error_has, content: "" , ...jConfirm_warning_options});
}
})
}
function commentsDisplaySummary(summary) {
commentsAll.text(summary.all_comments);
commentsValidated.text(summary.validated);
commentsPending.text(summary.pending);
}
function displayComments(comments) {
commentsList.empty();
comments.forEach((comment) => {
const clone = $('.comment-template').clone();
clone.removeClass('comment-template').addClass('comment');
clone.attr('id', comment.id);
clone.find('.comment-img').attr('src', comment.medium_url);
const raw_lenght = comment.raw_content.length;
const preview = raw_lenght > 50 ? comment.raw_content.substring(0, 50) + '...' : comment.raw_content;
clone.find('.comment-msg').text('"' + preview + '"');
clone.find('.comment-author-name').text(comment.author);
clone.find('.comment-datetime').text(comment.date);
clone.find('.comment-delete').data('idx', comment.id);
clone.find('.comment-validate').data('idx', comment.id);
clone.find('.comment-content').data('idx', comment.id);
clone.find('.comment-hash').text(`#${comment.id}`);
clone.find('.comment-select-checkbox').val(comment.id);
clone.find('.comment-link').attr('href', comment.admin_link);
const authorIcons = clone.find('.comment-author-icon');
switch (comment.author_status) {
case "guest":
authorIcons.addClass('icon-user-secret icon-yellow');
break;
case "webmaster":
authorIcons.addClass('icon-user icon-purple');
break;
case "admin":
authorIcons.addClass('icon-user icon-green');
break;
case "main_user":
authorIcons.addClass('icon-king icon-blue');
break;
default:
authorIcons.addClass('icon-user icon-yellow');
break;
}
if (comment.is_pending) {
clone.find('.comment-validate').show();
} else {
clone.find('.comment-container').addClass('comment-validated');
}
commentsList.append(clone);
});
$('.comment-delete').off('click').on('click', function(e) {
e.stopPropagation();
const id = $(this).data('idx');
deleteComment([id]);
});
$('.comment-validate').off('click').on('click', function(e) {
e.stopPropagation();
const id = $(this).data('idx');
validateComment([id]);
});
$('.comment-content').off('click').on('click', function() {
const id = $(this).data('idx');
if (selectionMode) {
const checkbox = $(this).find('.comment-select-checkbox');
if (checkbox.hasClass('icon-circle-empty')) {
checkbox.removeClass('icon-circle-empty').addClass('icon-ok-circled');
$(`#${id}`).addClass('comment-selected');
commentsSelected.push(id);
} else {
checkbox.removeClass('icon-ok-circled').addClass('icon-circle-empty');
$(`#${id}`).removeClass('comment-selected');
commentsSelected = commentsSelected.filter((idx) => idx != id);
}
commentsUpdateSelection();
return;
}
showModalViewComment(id);
});
}
function commentsDiplayPagination(paging) {
const container = $('.pagination-item-container');
container.empty();
if (paging.total_pages == 0) {
const pageNumbers = paging.total_pages + 1;
const page = commentsPaginItems.replace(/%d/g, pageNumbers);
$(page).addClass('actual').appendTo(container);
} else if (paging.total_pages <= 2) {
Array.from(Array(paging.total_pages + 1)).forEach((_, i) => {
const page = commentsPaginItems.replace(/%d/g, i + 1);
$(page).appendTo(container);
});
$(`#comments_page_${paging.page + 1}`).addClass('actual');
} else {
const pageOne = commentsPaginItems.replace(/%d/g, 1);
const pageLast = commentsPaginItems.replace(/%d/g, paging.total_pages + 1);
const pageCurrent = commentsPaginItemsCurrent.replace(/%d/g, paging.page + 1);
switch (paging.page) {
case 0:
container.append([
pageCurrent,
commentsPaginElipsis,
pageLast
]);
break;
case paging.total_pages:
container.append([
pageOne,
commentsPaginElipsis,
pageCurrent
]);
break;
default:
container.append([
pageOne,
commentsPaginElipsis,
pageCurrent,
commentsPaginElipsis,
pageLast
]);
break;
}
$('.pagination-arrow').removeClass('unavailable')
.off('click').on('click', function() {
let newPage = commentsParams.page;
if ($(this).hasClass('left')) {
newPage = newPage - 1;
} else {
newPage = newPage + 1;
}
if (newPage == -1 || newPage > commentsState.paging.total_pages) {
return;
}
commentsParams.page = newPage;
getComments(commentsParams);
});
}
$('.comments-paging').off('click').on('click', function() {
const newPage = $(this).attr('data-page') - 1;
commentsParams.page = newPage;
getComments(commentsParams);
});
}
function commentsDisplayFilters(filters) {
if (updateAuthorId) {
commentsDisplayAuthors(filters.nb_authors);
}
// reset here to let decide filterAuthor onChange
updateAuthorId = true;
const minDate = filters.started_at?.split(' ')[0] ?? '';
const maxDate = filters.ended_at?.split(' ')[0] ?? ''
filterDateStart.val(minDate).attr({ 'min': minDate, 'max': maxDate });
filterDateEnd.val(maxDate).attr({ 'max': maxDate, 'min': minDate });
filterDateStart.off('change').on('change', function() {
const min = $(this).val();
if (!min) {
delete commentsParams.f_min_date;
} else {
commentsParams.f_min_date = min;
}
filterDateEnd.attr({ 'min': min });
commentsParams.page = 0;
getComments(commentsParams);
});
filterDateEnd.off('change').on('change', function() {
const max = $(this).val();
if (!max) {
delete commentsParams.f_max_date;
} else {
commentsParams.f_max_date = max;
}
filterDateStart.attr({ 'max': max });
commentsParams.page = 0;
getComments(commentsParams);
});
}
function commentsDisplayAuthors(nb_authors) {
filterAuthor.empty();
filterAuthor.append(commentsOptionsFiltersAuthor);
nb_authors.forEach((a) => {
filterAuthor.append(`
<option value="${a.author_id}">${a.author} (${a.nb_authors})</option>
`);
});
filterAuthor.off('change').on('change', function() {
const authorId = $(this).val();
if (!authorId) {
delete commentsParams.author_id;
} else {
commentsParams.author_id = authorId;
}
commentsParams.page = 0;
updateAuthorId = false;
getComments(commentsParams);
});
}
function updateNbComments(nb) {
commentsNb.removeClass('selected-pagination');
$(`#pagination-per-page-${nb}`).addClass('selected-pagination');
commentsParams.per_page = nb;
window.localStorage.setItem('adminCommentsNB', nb);
}
function showModalViewComment(id) {
const comment = commentsState.comments.filter((c) => c.id == id)[0] ?? null;
if (!comment) return;
const item = $(`#${id}`);
modalViewComment.find('.comment-datetime').text(comment.date);
modalViewComment.find('.comment-author').remove();
modalViewComment.find('.comments-modal-infos').prepend(item.find('.comment-author').clone());
modalViewComment.find('.comments-modal-img').attr('src', comment.medium_url);
modalViewComment.find('.comments-modal-img-i').empty()
.append(`
<p class="comments-modal-filename">${comment.file}</p>
<p class="icon-calendar">${comment.image_date_available}</p>
`);
modalViewComment.find('.comments-modal-body').html(comment.content)
const validBtn = modalViewComment.find('.comments-modal-validate');
if (comment.is_pending) {
validBtn.show();
$('#commentsModalValidate').off('click').on('click', function() {
validateComment([id]);
closeModalViewComment();
});
} else {
validBtn.hide();
}
$('#commentsModalDelete').off('click').on('click', function() {
deleteComment([id]);
closeModalViewComment();
});
modalViewComment.fadeIn();
}
function closeModalViewComment() {
modalViewComment.fadeOut();
$('#commentsModalValidate').off('click');
$('#commentsModalDelete').off('click')
}
function validateComment(id) {
const idLenght = id.length ?? 1;
$.ajax({
url: 'ws.php?format=json&method=pwg.userComments.validate',
type: 'POST',
dataType: 'json',
data: {
comment_id: id,
pwg_token: pwg_token
},
success: function (res) {
if (res.stat === 'ok') {
$.alert({
...{
title: idLenght > 1 ? str_comments_validated : str_comment_validated,
content: "",
},
...jConfirm_alert_options
});
getComments(commentsParams);
return;
}
$.alert({
...{
title: str_an_error_has,
content: "",
},
...jConfirm_warning_options
});
},
error: function (e) {
console.log(e)
$.alert({
...{
title: str_an_error_has,
content: "",
},
...jConfirm_warning_options
});
}
});
}
function deleteComment(id) {
const idLenght = id.length ?? 1;
$.confirm({
title: idLenght > 1 ? str_deletes.replace("%d", idLenght) : str_delete.replace("%s", id),
draggable: false,
titleClass: "jconfirmDeleteConfirm",
theme: "modern",
content: "",
animation: "zoom",
boxWidth: '30%',
useBootstrap: false,
type: 'red',
animateFromElement: false,
backgroundDismiss: true,
typeAnimated: false,
buttons: {
confirm: {
text: str_yes_delete_confirmation,
btnClass: 'btn-red',
action: function () {
$.ajax({
url: 'ws.php?format=json&method=pwg.userComments.delete',
type: 'POST',
dataType: 'json',
data: {
comment_id: id,
pwg_token
},
success: function(res) {
if (res.stat === 'ok') {
getComments(commentsParams);
}
},
error: function(e) {
console.log(e)
}
})
}
},
cancel: {
text: str_no_delete_confirmation
}
}
});
}
function commentsUnselectAll() {
$('.comment').removeClass('comment-selected');
$('.comment-select-checkbox')
.removeClass('icon-ok-circled')
.addClass('icon-circle-empty');
commentsSelected = [];
commentsUpdateSelection();
}
function commentsSelectAll(){
$('.comment').addClass('comment-selected');
$('.comment-select-checkbox')
.removeClass('icon-circle-empty')
.addClass('icon-ok-circled');
commentsSelected = [];
$('.comment-selected').each((i, el) => {
const id = $(el).attr('id');
commentsSelected.push(id);
});
commentsUpdateSelection();
}
function commentsInvertSelect() {
$('.comment').toggleClass('comment-selected');
$('.comment-select-checkbox')
.toggleClass('icon-ok-circled')
.toggleClass('icon-circle-empty');
commentsSelected = [];
$('.comment-selected').each((i, el) => {
const id = $(el).attr('id');
commentsSelected.push(id);
});
commentsUpdateSelection();
}
function commentsUpdateSelection() {
if (commentsSelected.length === 0) {
$('#commentsSelection').hide();
$('#commentsNoSelection').show();
$('.comments-selected-remove').off('click');
$('#ValisateSelectionMode').off('click');
$('#DeleteSelectionMode').off('click');
return;
}
commentsSelectedArea.empty();
let count = 0;
commentsSelected.forEach((id) => {
if (count === 5) {
commentsSelectedOthers.text(str_and_others.replace(/%s/g, commentsSelected.length - 5));
return;
}
commentsSelectedOthers.text('');
const item = commentsSelectedList.replace(/%d/g, id);
commentsSelectedArea.append(item);
count++
});
$('.comments-selected-remove').off('click').on('click', function() {
const id = $(this).attr('id').split('_')[1];
if (!id) return;
$(`#${id} .comment-content`).trigger('click');
});
$('#ValisateSelectionMode').off('click').on('click', function() {
validateComment(commentsSelected);
commentsUnselectAll();
});
$('#DeleteSelectionMode').off('click').on('click', function() {
deleteComment(commentsSelected);
commentsUnselectAll();
});
$('#commentsNoSelection').hide();
$('#commentsSelection').show();
}
function commentsClearFilters() {
delete commentsParams.author_id;
delete commentsParams.image_id;
delete commentsParams.search;
delete commentsParams.f_min_date;
delete commentsParams.f_max_date;
getComments(commentsParams);
}
@@ -0,0 +1,335 @@
jQuery.fn.fontCheckbox = function() {
/* checkbox */
this.find('input[type=checkbox]').each(function() {
if (!jQuery(this).is(':checked')) {
jQuery(this).prev().toggleClass('icon-check icon-check-empty');
}
});
this.find('input[type=checkbox]').on('change', function() {
jQuery(this).prev().removeClass();
if (!jQuery(this).is(':checked')) {
jQuery(this).prev().addClass('icon-check-empty');
}
else {
jQuery(this).prev().addClass('icon-check');
}
});
/* radio */
this.find('input[type=radio]').each(function() {
if (!jQuery(this).is(':checked')) {
jQuery(this).prev().toggleClass('icon-dot-circled icon-circle-empty');
}
else {
jQuery(this).closest('label').addClass('selected');
}
});
this.find('input[type=radio]').on('change', function() {
jQuery('.font-checkbox input[type=radio][name="'+ jQuery(this).attr('name') +'"]').each(function() {
jQuery(this).prev().removeClass();
jQuery(this).closest('label').removeClass('selected');
if (!jQuery(this).is(':checked')) {
jQuery(this).prev().addClass('icon-circle-empty');
}
else {
jQuery(this).prev().addClass('icon-dot-circled');
jQuery(this).closest('label').addClass('selected');
}
})
});
};
// init fontChecbox everywhere
jQuery('.font-checkbox').fontCheckbox();
function array_delete(arr, item) {
var i = arr.indexOf(item);
if (i != -1) arr.splice(i, 1);
}
function str_repeat(i, m) {
for (var o = []; m > 0; o[--m] = i);
return o.join('');
}
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(elt /*, from*/)
{
var len = this.length;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
function sprintf() {
var i = 0, a, f = arguments[i++], o = [], m, p, c, x, s = '';
while (f) {
if (m = /^[^\x25]+/.exec(f)) {
o.push(m[0]);
}
else if (m = /^\x25{2}/.exec(f)) {
o.push('%');
}
else if (m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)) {
if (((a = arguments[m[1] || i++]) == null) || (a == undefined)) {
throw('Too few arguments.');
}
if (/[^s]/.test(m[7]) && (typeof(a) != 'number')) {
throw('Expecting number but found ' + typeof(a));
}
switch (m[7]) {
case 'b': a = a.toString(2); break;
case 'c': a = String.fromCharCode(a); break;
case 'd': a = parseInt(a); break;
case 'e': a = m[6] ? a.toExponential(m[6]) : a.toExponential(); break;
case 'f': a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a); break;
case 'o': a = a.toString(8); break;
case 's': a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a); break;
case 'u': a = Math.abs(a); break;
case 'x': a = a.toString(16); break;
case 'X': a = a.toString(16).toUpperCase(); break;
}
a = (/[def]/.test(m[7]) && m[2] && a >= 0 ? '+'+ a : a);
c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
x = m[5] - String(a).length - s.length;
p = m[5] ? str_repeat(c, x) : '';
o.push(s + (m[4] ? a + p : p + a));
}
else {
throw('Huh ?!');
}
f = f.substring(m[0].length);
}
return o.join('');
}
$('.search-cancel').on('click', function () {
$('.search-input').val('');
$('.search-input').trigger ("input");
})
$('.search-input').on('input', function() {
if ($('.search-input').val() == '') {
$('.search-cancel').hide();
} else {
$('.search-cancel').show();
}
})
// Class to implement a temporary state and reverse it
class TemporaryState {
constructor() {
//Arrays to reverse changes
this.attrChanges = []; //Attribute changes : {object(s), attribute, value}
this.classChanges = []; //Class changes : {object(s), state(add:true/remove:false), class}
this.htmlChanges = []; //Html changes : {object(s), html}
}
/**
* Change temporaly an attribute of an object
* @param {Jquery Object(s)} obj HTML Object(s)
* @param {String} attr Attribute
* @param {String} tempVal Temporary value of the attribute
*/
changeAttribute(obj, attr, tempVal) {
for (let i = 0; i < obj.length; i++) {
this.attrChanges.push({
object: $(obj[i]),
attribute: attr,
value: $(obj[i]).attr(attr)
})
}
obj.attr(attr, tempVal)
}
/**
* Add/remove a class temporarily
* @param {Jquery Object(s)} obj HTML Object
* @param {Boolean} st Add (true) or Remove (false) the class
* @param {String} loadclass Class Name
*/
changeClass(obj, st, tempclass) {
for (let i = 0; i < obj.length; i++) {
if (!($(obj[i]).hasClass(tempclass) && st)) {
this.classChanges.push({
object: $(obj[i]),
state: !st,
class: tempclass
})
if (st)
$(obj[i]).addClass(tempclass)
else
$(obj[i]).removeClass(tempclass)
}
}
}
/**
* Add temporarily a class to the object
* @param {Jquery Object(s)} obj
* @param {string} tempclass
*/
addClass(obj, tempclass) {
this.changeClass(obj, true, tempclass);
}
/**
* Remove temporarily a class to the object
* @param {Jquery Object(s)} obj
* @param {string} tempclass
*/
removeClass(obj, tempclass) {
this.changeClass(obj, false, tempclass);
}
/**
* Change temporaly the html of objects (remove event handlers on the actual content)
* @param {Jquery Object(s)} obj
* @param {string} temphtml
*/
changeHTML(obj, temphtml) {
for (let i = 0; i < obj.length; i++) {
this.htmlChanges.push({
object:$(obj[i]),
html:$(obj[i]).html()
})
}
obj.html(temphtml);
}
/**
* Reverse all the changes and clear the history
*/
reverse() {
this.attrChanges.forEach(function(change) {
if (change.value == undefined) {
change.object.removeAttr(change.attribute);
} else {
change.object.attr(change.attribute, change.value)
}
})
this.classChanges.forEach(function(change) {
if (change.state)
change.object.addClass(change.class)
else
change.object.removeClass(change.class)
})
this.htmlChanges.forEach(function(change) {
change.object.html(change.html);
})
this.attrChanges = [];
this.classChanges = [];
this.htmlChanges = [];
}
}
const jConfirm_alert_options = {
icon: 'icon-ok',
titleClass: "jconfirmAlert",
theme:"modern",
closeIcon: true,
draggable: false,
animation: "zoom",
boxWidth: '20%',
useBootstrap: false,
backgroundDismiss: true,
animateFromElement: false,
typeAnimated: false,
}
const jConfirm_confirm_options = {
draggable: false,
titleClass: "jconfirmDeleteConfirm",
theme: "modern",
animation: "zoom",
boxWidth: '40%',
useBootstrap: false,
type: 'red',
animateFromElement: false,
backgroundDismiss: true,
typeAnimated: false,
}
const jConfirm_warning_options = {
icon: "icon-attention",
draggable: false,
titleClass: "jconfirmWarning jconfirmAlert",
theme:"modern",
type: 'orange',
closeIcon: true,
draggable: false,
animation: "zoom",
boxWidth: '20%',
useBootstrap: false,
backgroundDismiss: true,
animateFromElement: false,
typeAnimated: false,
}
const jConfirm_confirm_with_content_options = {
draggable: false,
theme: "modern",
animation: "zoom",
boxWidth: '40%',
useBootstrap: false,
type: 'red',
animateFromElement: false,
backgroundDismiss: true,
typeAnimated: false,
}
jQuery.fn.pwg_jconfirm_follow_href = function({
alert_title = "TITLE",
alert_confirm = "CONFIRM",
alert_cancel = "CANCEL",
alert_content = ""
} = {}) {
let button_href = $(this).attr('href');
const options = alert_content === "" ? jConfirm_confirm_options : jConfirm_confirm_with_content_options
$(this).click(function() {
$.confirm({
content: alert_content,
title: alert_title,
buttons: {
confirm: {
text: alert_confirm,
btnClass: 'btn-red',
action: function () {
window.location.href = button_href;
}
},
cancel: {
text: alert_cancel
}
},
...options
});
return (false);
});
}
@@ -0,0 +1,184 @@
(function($) {
jQuery.timepicker.log = jQuery.noop; // that's ugly, but the timepicker is acting weird and throws parsing errors
// modify DatePicker internal methods to replace year select by a numeric input
var origGenerateMonthYearHeader = $.datepicker._generateMonthYearHeader,
origSelectMonthYear = $.datepicker._selectMonthYear;
$.datepicker._generateMonthYearHeader = function(inst, drawMonth, drawYear, minDate, maxDate,
secondary, monthNames, monthNamesShort) {
var html = origGenerateMonthYearHeader.call(this, inst, drawMonth, drawYear, minDate, maxDate,
secondary, monthNames, monthNamesShort);
var yearshtml = "<input type='number' class='ui-datepicker-year' data-handler='selectYear' data-event='change keyup' value='"+drawYear+"' style='width:4em;margin-left:2px;'>";
return html.replace(new RegExp('<select class=\'ui-datepicker-year\'.*</select>', 'gm'), yearshtml);
};
$.datepicker._selectMonthYear = debounce(function(id, select, period) {
if (period === 'M') {
origSelectMonthYear.call(this, id, select, period);
}
else {
var target = $(id),
inst = this._getInst(target[0]),
val = parseInt(select.value, 10);
if (isNaN(val)) {
inst['drawYear'] = '';
}
else {
inst['selectedYear'] = inst['drawYear'] = val;
this._notifyChange(inst);
this._adjustDate(target);
$('.ui-datepicker-year').focus();
}
}
}, 500);
// plugin definition
jQuery.fn.pwgDatepicker = function(settings) {
var options = jQuery.extend(true, {
showTimepicker: false,
cancelButton: false,
}, settings || {});
return this.each(function() {
var $this = jQuery(this),
originalValue = $this.val(),
originalDate,
$target = jQuery('[name="'+ $this.data('datepicker') +'"]'),
linked = !!$target.length,
$start, $end;
if (linked) {
originalValue = $target.val();
}
// custom setter
function set(date, init) {
if (date === '') date = null;
$this.datetimepicker('setDate', date);
if ($this.data('datepicker-start') && $start) {
$start.datetimepicker('option', 'maxDate', date);
}
else if ($this.data('datepicker-end') && $end) {
if (!init) { // on init, "end" is not initialized yet (assuming "start" is before "end" in the DOM)
$end.datetimepicker('option', 'minDate', date);
}
}
if (!date && linked) {
$target.val('');
}
}
// and custom cancel button
if (options.cancelButton) {
options.beforeShow = options.onChangeMonthYear = function() {
setTimeout(function() {
var buttonPane = $this.datepicker('widget')
.find('.ui-datepicker-buttonpane');
if (buttonPane.find('.pwg-datepicker-cancel').length == 0) {
$('<button type="button">'+ options.cancelButton +'</button>')
.on('click', function() {
set(originalDate, false);
$this.datepicker('hide').blur();
})
.addClass('pwg-datepicker-cancel ui-state-error ui-corner-all')
.appendTo(buttonPane);
}
}, 1);
};
}
// init picker
$this.datetimepicker(jQuery.extend({
dateFormat: linked ? 'DD d MM yy' : 'yy-mm-dd',
timeFormat: 'HH:mm',
separator: options.showTimepicker ? ' ' : '',
altField: linked ? $target : null,
altFormat: 'yy-mm-dd',
altTimeFormat: options.showTimepicker ? 'HH:mm:ss' : '',
autoSize: true,
changeMonth : true,
changeYear: true,
altFieldTimeOnly: false,
showSecond: false,
alwaysSetTime: false
}, options));
// attach range pickers
if ($this.data('datepicker-start')) {
$start = jQuery('[data-datepicker="'+ $this.data('datepicker-start') +'"]');
$this.datetimepicker('option', 'onClose', function(date) {
$start.datetimepicker('option', 'maxDate', date);
});
$this.datetimepicker('option', 'minDate', $start.datetimepicker('getDate'));
}
else if ($this.data('datepicker-end')) {
$end = jQuery('[data-datepicker="'+ $this.data('datepicker-end') +'"]');
$this.datetimepicker('option', 'onClose', function(date) {
$end.datetimepicker('option', 'minDate', date);
});
}
// attach unset button
if ($this.data('datepicker-unset')) {
jQuery('#'+ $this.data('datepicker-unset')).on('click', function(e) {
e.preventDefault();
set(null, false);
});
}
// set value from linked input
if (linked) {
var splitted = originalValue.split(' ');
if (splitted.length == 2 && options.showTimepicker) {
set(jQuery.datepicker.parseDateTime('yy-mm-dd', 'HH:mm:ss', originalValue), true);
}
else if (splitted[0].length == 10) {
set(jQuery.datepicker.parseDate('yy-mm-dd', splitted[0]), true);
}
else {
set(null, true);
}
}
originalDate = $this.datetimepicker('getDate');
// autoSize not handled by timepicker
if (options.showTimepicker) {
$this.attr('size', parseInt($this.attr('size'))+6);
}
});
};
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
}(jQuery));
@@ -0,0 +1,62 @@
(function($){
/**
* OPTIONS:
* values {mixed[]}
* selected {object} min and max
* text {string}
*/
$.fn.pwgDoubleSlider = function(options) {
var that = this;
function onChange(e, ui) {
that.find('[data-input=min]').val(options.values[ui.values[0]]);
that.find('[data-input=max]').val(options.values[ui.values[1]]);
that.find('.slider-info').html(sprintf(
options.text,
options.values[ui.values[0]],
options.values[ui.values[1]]
));
}
function findClosest(array, value) {
var closest = null, index = -1;
$.each(array, function(i, v){
if (closest == null || Math.abs(v - value) < Math.abs(closest - value)) {
closest = v;
index = i;
}
});
return index;
}
var values = [
options.values.indexOf(options.selected.min),
options.values.indexOf(options.selected.max)
];
if (values[0] == -1) {
values[0] = findClosest(options.values, options.selected.min);
}
if (values[1] == -1) {
values[1] = findClosest(options.values, options.selected.max);
}
var slider = this.find('.slider-slider').slider({
range: true,
min: 0,
max: options.values.length - 1,
values: values,
slide: onChange,
change: onChange
});
this.find('.slider-choice').on('click', function(){
slider.slider('values', 0, options.values.indexOf($(this).data('min')));
slider.slider('values', 1, options.values.indexOf($(this).data('max')));
});
return this;
};
}(jQuery));
@@ -0,0 +1,976 @@
const DELAY_FEEDBACK = 3000;
/*-------
Group Popin
-------*/
$(".group_details_popup_trigger").click(function () {
$(".Group_details-popup-container").show();
});
$(".CloseGroupPopup").click(function () {
$(".Group_details-popup-container").hide();
});
//Number On Badge
function updateBadge() {
$('.badge-number').html($('.GroupContainer').length - 2) //Less the add group div and the template
}
/*-------
Add User toggle and reduces height of user list when add user form is visible
-------*/
$("#form-btn").click(function () {
$("#cancel").show();
$("#addUserLabel").show();
$(".UserSearch").show();
$("#UserSubmit").show();
$("#form-btn").hide();
$(".groups .list_user").css("max-height", "100px");
});
$("#cancel").click(function () {
$("#cancel").hide();
$("#addUserLabel").hide();
$(".UserSearch").hide();
$("#UserSubmit").hide();
$("#form-btn").show();
$(".groups .list_user").css("max-height", "200px");
});
/*-------
Add Group toggle
-------*/
var isToggle = true;
$(".addGroupBlock").on("click", function() {
if (isToggle) {
deployAddGroupForm();
}
else {
hideAddGroupForm();
}
})
var deployAddGroupForm = function () {
$(".addGroupBlock").animate({
top: "20%",
padding: "0px"
}, 400, complete=function(){
$("#addGroupForm form").fadeIn();
$("#addGroupNameInput").focus();
});
isToggle = false;
}
var hideAddGroupForm = function () {
$("#addGroupForm form").fadeOut(function(){
$(".addGroupBlock").animate({
top: "50%",
padding: "100px 0"
}, 400)
});
isToggle = true;
}
/*-------
Add Group Submit
-------*/
jQuery(document).ready(function () {
$("#addGroupForm form").on("submit", function (e) {
e.preventDefault();
let name = $("#addGroupForm input[type=text]").val();
let loadState = new TemporaryState();
loadState.changeHTML($(".actionButtons button"), "<i class='icon-spin6 animate-spin'> </i>");
loadState.changeAttribute($(".actionButtons button"), "style", "pointer-events: none");
loadState.changeAttribute($(".actionButtons a"), "style", "pointer-events: none");
if (name.replace(/\s/g, '').length != 0) {
jQuery.ajax({
url: "ws.php?format=json&method=pwg.groups.add",
type: "POST",
data: {
'name': name,
'pwg_token': pwg_token,
},
success: function (raw_data) {
loadState.reverse();
data = jQuery.parseJSON(raw_data);
if (data.stat === "ok") {
$(".addGroupFormLabelAndInput input").val('');
group = data.result.groups[0];
groupBox = createGroup(group);
$("#addGroupForm").after(groupBox);
setupGroupBox(groupBox);
updateBadge();
} else {
$("#addGroupForm .groupError").html(str_name_not_empty);
$("#addGroupForm .groupError").fadeIn();
$("#addGroupForm .groupError").delay(DELAY_FEEDBACK).fadeOut();
}
},
error: function (err) {
console.log(err);
},
});
} else {
loadState.reverse();
$("#addGroupForm .groupError").html(str_name_not_empty);
$("#addGroupForm .groupError").fadeIn();
$("#addGroupForm .groupError").delay(DELAY_FEEDBACK).fadeOut();
}
});
});
var createGroup = function(group) {
//Setup the group
newgroup = $("#group-template").clone().attr("id", "group-" + group.id);
newgroup.attr("data-id", group.id);
newgroup.find("#group_name").html(group.name);
newgroup.find(".group_name-editable").val(group.name);
newgroup.find(".Group-checkbox label").attr("for", "Group-Checkbox-selection-" + group.id);
newgroup.find(".Group-checkbox input").attr("id", "Group-Checkbox-selection-" + group.id);
newgroup.find(".input-edit-group-name").attr("placeholder", group.name);
newgroup.find(".group_number_users").html(group.nb_users+" " + ((group.nb_users > 1)? str_members_default:str_member_default));
newgroup.find(".group_name-editable").html(group.name);
newgroup.find(".manage-permissions").attr("href", "admin.php?page=group_perm&group_id="+group.id)
hideAddGroupForm();
//Setup the icon color
var colors = ["icon-red", "icon-blue", "icon-yellow", "icon-purple", "icon-green"];
var colorId = Number(group.id)%5;
newgroup.find(".icon-users-1").addClass(colors[colorId]);
//Place group in first Place
newgroup.find(".groupMessage").html(str_group_created);
newgroup.find(".groupMessage").fadeIn();
newgroup.find(".groupMessage").delay(DELAY_FEEDBACK).fadeOut();
return newgroup;
}
/*-------
SETUP JS ON GROUP BOX
-------*/
jQuery(document).ready(function () {
$(".GroupContainer").each(function () {
if ($(this).attr("id") != "group-template")
setupGroupBox($(this));
});
});
var setupGroupBox = function (groupBox) {
var id = groupBox.data("id");
/* Change background color of group block if checked in selection mode */
groupBox.find(".Group-checkbox input[type='checkbox']").change(function () {
toogleSelection(id, groupBox.find(".Group-checkbox input[type='checkbox']").is(":checked"));
});
groupBox.find(".Group-checkbox input[type='checkbox']").attr("checked", false)
/* Display the option on the click on "..." */
groupBox.find(".group-dropdown-options").click(function GroupOptions() {
$(this).find("#GroupOptions").toggle();
});
/* Set the delete action */
groupBox.find("#GroupDelete").on("click", function () {
deleteGroup(id);
});
/* Set the rename action */
groupBox.find(".Group-name .icon-pencil, #GroupEdit").on("click", function () {
displayRenameForm(true, id);
setTimeout(() => {groupBox.find("#GroupOptions").hide()}, 10)
});
groupBox.find(".group-rename .validate").on("click", function () {
groupBox.find(".group-rename form").trigger("submit");
});
groupBox.find(".group-rename form").on("submit", function (e) {
e.preventDefault();
renameGroup(id, groupBox.find(".group_name-editable").val())
});
groupBox.find(".group-rename .icon-cancel").on('click', function() {
displayRenameForm(false, id)
groupBox.find(".group_name-editable").val(groupBox.find(".Group-name-container p").html());
})
/* Hide group options and rename field on click on the screen */
$(document).mouseup(function (e) {
e.stopPropagation();
let option_is_clicked = false
$("#GroupOptions div").each(function () {
if (!($(this).has(e.target).length === 0)) {
option_is_clicked = true;
}
})
if (!option_is_clicked) {
groupBox.find("#GroupOptions").hide();
}
});
/* Setup the default action */
if (groupBox.data("default") == 1) {
setupDefaultActions(id, true);
} else if (groupBox.data("default") == 0) {
setupDefaultActions(id, false);
}
groupBox.find(".manage-users").on("click", function(){openUserManager(id)});
groupBox.find("#GroupDuplicate").on("click", function(){duplicateAction(id)})
};
var toogleSelection = function(group_id, toggle) {
groupBox = $("#group-"+group_id);
if (toggle) {
groupBox.find(".Group-checkbox input").attr("checked", true);
groupBox.addClass("GroupBackgroudSelected");
groupBox.find(".icon-users-1").addClass("OrangeIcon");
groupBox.find(".group_number_users").addClass("OrangeFont");
//Display item selection on selection panel
item = $(
"<div data-id=" +
group_id +
">" +
"<a class='icon-cancel'></a>" +
"<p>" +
groupBox.find("#group_name").html() +
"</p> </div>"
);
item.appendTo(".DeleteGroupList");
item.find("a").on("click", function () {
groupBox.find(".Group-checkbox input").attr("checked", false);
toogleSelection(group_id);
});
updateSelectionPanel();
option = $('<option value="'+group_id+'">'+groupBox.find("#group_name").html()+'</option>')
option.appendTo("#MergeOptionsChoices");
} else {
groupBox.find(".Group-checkbox input").attr("checked", false);
groupBox.removeClass("GroupBackgroudSelected");
groupBox.find(".icon-users-1").removeClass("OrangeIcon");
groupBox.find(".group_number_users").removeClass("OrangeFont");
$(".DeleteGroupList div").each(function () {
if ($(this).data("id") == group_id) {
$(this).remove();
}
});
updateSelectionPanel();
$("#MergeOptionsChoices option").each(function () {
if ($(this).attr("value") == group_id) {
$(this).remove();
}
});
}
}
/* Group Ajax and Display Functions */
var deleteGroup = function (id) {
$.confirm({
title: str_delete.replace("%s",$("#group-"+id+" #group_name").html()),
draggable: false,
titleClass: "jconfirmDeleteConfirm",
theme: "modern",
content: "",
animation: "zoom",
boxWidth: '30%',
useBootstrap: false,
type: 'red',
animateFromElement: false,
backgroundDismiss: true,
typeAnimated: false,
buttons: {
confirm: {
text: str_yes_delete_confirmation,
btnClass: 'btn-red',
action: function () {
let groupName = $("#group-"+id+" .Group-name-container p").html()
$.alert({
...{title : str_group_deleted.replace("%s",groupName),
content: function() {
return jQuery.ajax({
url: "ws.php?format=json&method=pwg.groups.delete",
type: "POST",
data: "group_id=" + id + "&pwg_token=" + pwg_token,
success: function (raw_data) {
data = jQuery.parseJSON(raw_data);
if (data.stat === "ok") {
$("#group-" + id).remove();
$(".DeleteGroupList div[data-id="+id+"]").remove()
$("#MergeOptionsChoices option[value="+ id +"]").remove()
}
updateBadge();
},
error: function (err) {
console.log(err);
},
})
}},
...jConfirm_alert_options
});
}
},
cancel: {
text: str_no_delete_confirmation
}
}
});
};
var renameGroup = function(id, newName) {
let loadState = new TemporaryState();
loadState.changeHTML($("#group-" + id + " .group-rename .validate"), "<i class='animate-spin icon-spin6'></i>")
loadState.removeClass($("#group-" + id + " .group-rename .validate"), "icon-ok")
loadState.changeAttribute($("#group-" + id + " .group-rename span"), "style", "pointer-events: none");
if (newName.replace(/\s/g, '').length != 0) {
jQuery.ajax({
url: "ws.php?format=json&method=pwg.groups.setInfo",
type: "POST",
data: "group_id=" + id + "&pwg_token=" + pwg_token + "&name="+newName,
success: function (raw_data) {
data = jQuery.parseJSON(raw_data);
loadState.reverse();
if (data.stat === "ok") {
newName = data.result.groups[0].name;
//Display message
$("#group-" + id).find(".groupMessage").html(str_renaming_done);
$("#group-" + id).find(".groupMessage").fadeIn();
$("#group-" + id).find(".groupMessage").delay(DELAY_FEEDBACK).fadeOut();
$("#group-" + id).find("#group_name").html(newName);
//Hide editable field
displayRenameForm(false, id);
} else {
//Display error message
$("#group-" + id).find(".groupError").html(str_name_taken);
$("#group-" + id).find(".groupError").fadeIn();
$("#group-" + id).find(".groupError").delay(DELAY_FEEDBACK).fadeOut();
}
},
error: function (err) {
console.log(err);
},
});
} else {
loadState.reverse();
$("#group-" + id).find(".groupError").html(str_name_not_empty);
$("#group-" + id).find(".groupError").fadeIn();
$("#group-" + id).find(".groupError").delay(DELAY_FEEDBACK).fadeOut();
}
}
// Hide or display rename form
var displayRenameForm = function(doDisplay, grp_id) {
if (doDisplay) {
$("#group-" + grp_id).find(".group-rename").css("display", "flex");
$("#group-" + grp_id).find(".Group-name-container .icon-pencil").hide();
$("#group-" + grp_id).find(".Group-name-container p").css("opacity", 0)
} else {
$("#group-" + grp_id).find(".group-rename").hide();
$("#group-" + grp_id).find(".Group-name-container .icon-pencil").removeAttr("style");
$("#group-" + grp_id).find(".Group-name-container p").css("opacity", 1);
}
}
var setDefaultGroup = function (id, is_default) {
$("#group-" + id + " #GroupDefault").css("width", $("#group-" + id + " #GroupDefault").width())
$("#group-" + id + " #GroupDefault").html("<i class='icon-spin6 animate-spin'> </i>")
$("#group-" + id + " #GroupDefault").removeClass("icon-star");
$("#group-" + id + " #GroupDefault").attr("style", "pointer-events: none; text-align: center;")
$("#group-" + id).find(".is-default-token").addClass("icon-spin6").addClass("animate-spin").removeClass("icon-star")
jQuery.ajax({
url: "ws.php?format=json&method=pwg.groups.setInfo",
type: "POST",
data: "group_id=" + id + "&pwg_token=" + pwg_token + "&is_default="+is_default,
success: function (raw_data) {
data = jQuery.parseJSON(raw_data);
$("#group-"+id+" #GroupOptions").hide();
if (data.stat === "ok") {
if (is_default) {
setupDefaultActions(id,true)
} else {
setupDefaultActions(id,false)
}
}
},
error: function (err) {
console.log(err);
},
});
};
var setupDefaultActions = function(id, is_default) {
$("#group-" + id + " #GroupDefault").attr("style", "");
$("#group-" + id + " #GroupDefault").addClass("icon-star")
$("#group-" + id).find(".is-default-token").removeClass("icon-spin6").removeClass("animate-spin").addClass("icon-star")
if (is_default) {
$("#group-" + id).find("#GroupDefault").html(str_unset_default);
$("#group-" + id).find(".is-default-token").attr("title",str_unset_default)
$("#group-" + id).find("#GroupDefault").unbind("click");
$("#group-" + id).find(".is-default-token").removeClass("deactivate");
$("#group-" + id).find("#GroupDefault").on("click", function(){setDefaultGroup(id, false)})
$("#group-" + id).find(".is-default-token").on("click", function(){setDefaultGroup(id, false)})
} else {
$("#group-" + id).find("#GroupDefault").html(str_set_default);
$("#group-" + id).find(".is-default-token").attr("title",str_set_default)
$("#group-" + id).find(".is-default-token").addClass("deactivate");
$("#group-" + id).find("#GroupDefault").on("click", function(){setDefaultGroup(id, true)})
$("#group-" + id).find(".is-default-token").unbind("click");
}
}
var duplicateAction = function(id) {
let loadState = new TemporaryState();
loadState.changeHTML($("#group-" + id + " #GroupDuplicate"), "<i class='icon-spin6 animate-spin'> </i>")
loadState.removeClass($("#group-" + id + " #GroupDuplicate"), "icon-docs");
loadState.changeAttribute($("#group-" + id + " #GroupDuplicate"), "style", "pointer-events: none; text-align: center;")
copy_name = $("#group-" + id + " #group_name").html() + str_copy;
let name_exist = function(name) {
exist = false;
$(".Group-name-container p").each(function () {
if ($(this).html() === name)
exist = true
})
return exist;
}
let i = 1;
while (name_exist(copy_name))
{
copy_name = $("#group-" + id + " #group_name").html() + str_other_copy.replace("%s", i++)
}
jQuery.ajax({
url: "ws.php?format=json&method=pwg.groups.duplicate",
type: "POST",
data: "group_id=" + id + "&pwg_token=" + pwg_token + "&copy_name=" + copy_name,
success: function (raw_data) {
data = jQuery.parseJSON(raw_data);
loadState.reverse();
if (data.stat === "ok") {
$("#group-"+id+" #GroupOptions").hide();
group = data.result.groups[0];
let groupbox = createGroup(group)
groupbox.insertAfter($("#group-"+id));
setupGroupBox(groupbox);
updateBadge();
/* data.result.groups[0].is_default is a string */
if(data.result.groups[0].is_default == "true") {
setupDefaultActions(data.result.groups[0].id, true);
}
}
},
error: function (err) {
console.log(err);
},
});
}
/*-------
Selection mode toggle actions,
changes "..." in group block to checkbox,
disables group actions in selection mode
-------*/
$(function () {
$("#toggleSelectionMode").attr("checked", false)
$("#toggleSelectionMode").click(function () {
if ($(this).is(":checked")) {
$(".in-selection-mode").show();
$(".not-in-selection-mode").hide();
$(".GroupManagerButtons").removeClass("visible");
} else {
$(".in-selection-mode").hide();
$(".not-in-selection-mode").removeAttr("style");
$(".Group-checkbox input").attr("checked", false);
$(".Group-checkbox input[type='checkbox']").trigger("change");
}
});
});
/*-------
Update Selection Panel
-------*/
var state = "NoSelection";
var updateSelectionPanel = function (changedState = "") {
let numSelect = $(".DeleteGroupList div").length;
if (numSelect == 0) {
updateStatePanel("NoSelection")
} else if (changedState == "") {
if (numSelect == 1 && state != "ConfirmDeletion")
updateStatePanel("OneSelected")
if (numSelect > 1 && state == "OneSelected")
updateStatePanel("Selection");
} else {
if (changedState == "Selection" && numSelect == 1)
updateStatePanel("OneSelected")
else
updateStatePanel(changedState)
}
$(".number-Selected").html(numSelect + "");
};
/*Update the state of the panel in 5 states :
NoSelection, OneSelected, ConfirmDeletion, Selection, OptionMerge
*/
var updateStatePanel = function (newState = "Selection") {
state = newState;
switch (newState) {
case "OneSelected":
$("#DeleteSelectionMode").show();
$("#MergeSelectionMode").show();
buttonUnavailable($("#MergeSelectionMode"));
buttonAvailable($("#DeleteSelectionMode"), "updateSelectionPanel('ConfirmDeletion')");
$("#MergeOptionsBlock").hide();
$("#ConfirmGroupAction").hide();
break;
case "ConfirmDeletion":
$("#DeleteSelectionMode").hide();
$("#MergeSelectionMode").hide();
$("#MergeOptionsBlock").hide();
$("#ConfirmGroupAction").show();
break;
case "Selection":
$("#DeleteSelectionMode").show();
$("#MergeSelectionMode").show();
buttonAvailable($("#MergeSelectionMode"), "updateSelectionPanel('OptionMerge')");
buttonAvailable($("#DeleteSelectionMode"), "updateSelectionPanel('ConfirmDeletion')");
$("#MergeOptionsBlock").hide();
$("#ConfirmGroupAction").hide();
break;
case "OptionMerge":
$("#DeleteSelectionMode").hide();
$("#MergeSelectionMode").hide();
$("#MergeOptionsBlock").show();
$("#ConfirmGroupAction").hide();
break;
}
if (newState == "NoSelection") {
$("#DeleteSelectionMode").show();
$("#MergeSelectionMode").show();
buttonUnavailable($("#MergeSelectionMode"));
buttonUnavailable($("#DeleteSelectionMode"));
$(".SelectionModeGroup").hide();
$("#nothing-selected").show();
$("#MergeOptionsBlock").hide();
$("#ConfirmGroupAction").hide();
} else {
$(".SelectionModeGroup").show();
$("#nothing-selected").hide();
}
};
var buttonAvailable = function(button, onClick) {
button.removeClass("unavailable");
button.attr("OnClick", onClick);
}
var buttonUnavailable = function(button) {
button.addClass("unavailable");
button.removeAttr("OnClick");
}
/*-------
Merge function on button's pannel
-------*/
$('.ConfirmMergeButton').on("click", function() {
let loadState = new TemporaryState();
loadState.changeAttribute($('.ConfirmMergeButton'), "style", "pointer-events: none");
loadState.changeHTML($('.ConfirmMergeButton'), "<i class='icon-spin6 animate-spin'> </i>");
loadState.removeClass($('.ConfirmMergeButton'), "icon-ok");
merge_group = [];
str_merge_group = "";
name_merge = [];
name_dest = [];
dest_grp = $("#MergeOptionsChoices").val();
$(".DeleteGroupList div").each(function () {
if (dest_grp != $(this).attr("data-id"))
{
str_merge_group += "&merge_group_id[]="+$(this).attr("data-id");
merge_group.push($(this).attr("data-id"));
name_merge.push($(this).find("p").html())
} else {
name_dest = $(this).find("p").html();
}
})
jQuery.ajax({
url: "ws.php?format=json&method=pwg.groups.merge",
type: "POST",
data: "destination_group_id=" + dest_grp + str_merge_group + "&pwg_token=" + pwg_token,
success: function (raw_data) {
loadState.reverse();
data = jQuery.parseJSON(raw_data);
if (data.stat === "ok") {
updateSelectionPanel('Selection');
merge_group.forEach(function(id) {
($("#group-"+id).fadeOut(complete=function(){
$(this).remove();
}))
})
toogleSelection(dest_grp, false)
$(".DeleteGroupList").html("");
$("#MergeOptionsChoices").html("");
$.alert({
...{title: str_merged_into
.replace("%s1",name_merge.toString())
.replace("%s2",name_dest),
content: "",},
...jConfirm_alert_options
});
$("#group-"+dest_grp + " .group_number_users").html("<i class='icon-spin6 animate-spin'> </i>");
jQuery.ajax({
url: "ws.php?format=json&method=pwg.users.getList",
type: "POST",
data: "group_id=" + dest_grp,
success: function (raw_data) {
data = jQuery.parseJSON(raw_data);
let number = data.result.users.length;
$("#group-"+dest_grp + " .group_number_users").html(
number + " " + ((number > 1)? str_members_default:str_member_default)
);
updateBadge();
}
})
};
}
})
})
/*-------
Delete function on button's pannel
-------*/
$('.ConfirmDeleteButton').on("click", function() {
let names = [];
let ids = [];
$('.DeleteGroupList div').each(function () {
let id = $(this).data('id');
names.push($("#group-"+id+" #group_name").html());
ids.push(id);
});
let loadState = new TemporaryState;
loadState.changeAttribute($('.ConfirmDeleteButton'), "style", "pointer-events: none");
loadState.changeHTML($('.ConfirmDeleteButton'), "<i class='icon-spin6 animate-spin'> </i>");
loadState.removeClass($('.ConfirmDeleteButton'),"icon-ok");
str_id = ""
ids.forEach(function(id) {
str_id += "group_id[]=" + id + "&"
})
jQuery.ajax({
url: "ws.php?format=json&method=pwg.groups.delete",
type: "POST",
data: str_id + "pwg_token=" + pwg_token,
success: function (raw_data) {
data = jQuery.parseJSON(raw_data);
if (data.stat === "ok") {
$(".DeleteGroupList div").each(function() {
$(this).remove();
$("#group-" + $(this).attr("data-id")).remove();
$("#MergeOptionsChoices option[value="+ $(this).attr("data-id") +"]").remove()
})
loadState.reverse();
updateSelectionPanel("NoSelection");
$.alert({
...{title: str_groups_deleted.replace("%s",names.toString()),
content: "",
},
...jConfirm_alert_options
});
updateBadge();
}
},
error: function (err) {
console.log(err);
},
});
});
/*-------
Manage User Part
-------*/
// Initialize the research user bar
var selectize;
// Initialize the cache
var usersCache = {};
var usersInGroup = [];
// Max offset of the user container (322 = 6 lines)
var maxOffsetUserCont = 322;
var dissociateUserInfo = $("<div class='ValidationUserDissociated'>"
+ "<p class='icon-ok'></p>"
+ "</div>").appendTo(".group-name-block").hide();
var associateUserInfo = $("<div class='ValidationUserAssociated'>"
+ "<p class='icon-ok'></p>"
+ "</div>");
// Setup the user research bar
$(function() {
// initialize the Selectize control
$select = $('.AddUserBlock select').selectize({});
// fetch the instance
selectize = $select[0].selectize;
var idSearch = "";
$('.UserSearch input').on("focus", function() {
if (idSearch != $("#UserList").attr("data-group_id")) {
updateUserSearch();
}
});
// Update User search bar (remove group users in selection)
updateUserSearch = function () {
selectize.clear();
if (usersCache = {}) {
usersCache = new UsersCache({
serverKey: serverKey,
serverId: serverId,
rootUrl: rootUrl
});
}
JSON.parse(usersCache.storage[usersCache.key]).data.forEach(function(u){
selectize.addOption({value:u.id, text:u.username})
})
idSearch = $("#UserList").attr("data-group_id");
for (const [key, value] of Object.entries(selectize.options)) {
if (value.username === "guest") {
selectize.removeOption(value.id);
}
}
$('.UsernameBlock').each(function(){
selectize.removeOption($(this).data("id"));
})
}
});
// Display the user manager for a specific group
var openUserManager = function(grp_id) {
let loadState = new TemporaryState();
loadState.removeClass($("#group-" + grp_id + " #UserListTrigger"),'icon-user-1')
loadState.changeAttribute($("#group-" + grp_id + " #UserListTrigger"), "style", "pointer-events: none");
loadState.changeHTML($("#group-" + grp_id + " #UserListTrigger"), "<i class='icon-spin6 animate-spin'> </i>");
jQuery.ajax({
url: "ws.php?format=json&method=pwg.users.getList",
type: "POST",
data: "group_id=" + grp_id,
success: function (raw_data) {
loadState.reverse();
data = jQuery.parseJSON(raw_data);
if (data.stat === "ok") {
//Set the popin name
$(".group-name-block p").html(
$("#group-" + grp_id + " #group_name").html() + " / " + str_user_list
)
$(".UsersInGroupList").html("");
//Display the popin
$('#UserList').fadeIn();
//Fill with user blocks
usersInGroup = data.result.users;
// Sort in alphabetic order
usersInGroup.sort(function( a, b ) {
if ( a.username.toLowerCase() < b.username.toLowerCase() ){
return -1;
} else return 1
});
let i = 0;
while ($(".UsersInGroupList").outerHeight() <= maxOffsetUserCont && usersInGroup[i] != undefined){
getUserDisplay(usersInGroup[i].username, usersInGroup[i].id, grp_id).appendTo(".UsersInGroupList");
i++;
};
while ($(".UsersInGroupList").height() > maxOffsetUserCont) {
$(".UsernameBlock").last().remove();
}
updateMembernumber(usersInGroup.length, grp_id);
//Attribute the group id to the div
$("#UserList").attr("data-group_id", grp_id);
$(".LinkUserManager a").attr("href","admin.php?page=user_list&group="+grp_id)
}
},
error: function (err) {
console.log(err);
},
});
}
//Add a user block
var getUserDisplay = function(username, user_id, grp_id) {
let userBlock = $('<div class="UsernameBlock" data-id='+user_id+'>'+
'<span class="icon-user-1"></span>'+
'<p>'+username+'</p>'+
'<div class="Tooltip">'+
'<span class="icon-cancel"></span>'+
'<p class="TooltipText">'+str_user_dissociate+'</p>'+
'</div>'+
'</div>');
while ($(".UsersInGroupList")[0].offsetHeight > maxOffsetUserCont) {
$(".UsernameBlock").last().remove();
}
//Setup the delete action
userBlock.find(".icon-cancel").on("click", function () {
userBlock.find(".icon-cancel").addClass("icon-spin6")
userBlock.find(".icon-cancel").addClass("animate-spin")
userBlock.find(".icon-cancel").css("pointer-events", "none")
userBlock.find(".icon-cancel").removeClass("icon-cancel")
jQuery.ajax({
url: "ws.php?format=json&method=pwg.groups.deleteUser",
type: "POST",
data: "group_id=" + grp_id + "&user_id=" + user_id + "&pwg_token=" + pwg_token,
success: function (raw_data) {
data = jQuery.parseJSON(raw_data);
if (data.stat === "ok") {
let str = str_user_dissociated.replace("%s", username)
associateUserInfo.fadeOut();
dissociateUserInfo.find("p").html(str);
dissociateUserInfo.fadeIn()
$(".UsernameBlock").css("margin-right", "10px").css("border", "none");
userBlock.remove()
updateUserSearch();
while ($(".UsersInGroupList").height() > maxOffsetUserCont) {
$(".UsernameBlock").last().remove();
}
usersInGroup = usersInGroup.filter(u => u.id != user_id)
//Update member number
updateMembernumber(parseInt($(".UserNumberBadge").html()) -1, grp_id);
}
}
});
})
return userBlock;
}
//Update member number function
function updateMembernumber(number, grp_id) {
$(".GroupContainer[data-id="+grp_id+"] .group_number_users")
.html(number + " " + ((number > 1)? str_members_default:str_member_default));
$(".UserNumberBadge").html(number);
$(".AmountOfUsersShown strong:nth-child(2)").html(number)
$(".AmountOfUsersShown strong:nth-child(1)").html($(".UsernameBlock").length)
}
// Close pop-up on cross click
$(".CloseUserList").on("click", function() {$('#UserList').fadeOut();})
// Adding Group Action
$(".AddUserBlock button").on("click", function () {
let grp_id = $("#UserList").attr("data-group_id");
let usersString = ""
// Get selected ids
let id = selectize.getValue();
if (id != "") {
let loadState = new TemporaryState();
loadState.changeHTML($("#UserSubmit"),"<i class='icon-spin6 animate-spin'> </i>");
loadState.removeClass($("#UserSubmit"),"icon-user-add");
loadState.changeAttribute($("#UserSubmit"),"css","pointer-events:none")
jQuery.ajax({
url: "ws.php?format=json&method=pwg.groups.addUser",
type: "POST",
data: "group_id=" + grp_id+ "&user_id=" + id + "&pwg_token=" + pwg_token,
success: function (raw_data) {
loadState.reverse()
data = jQuery.parseJSON(raw_data);
if (data.stat === "ok") {
// Get the username
let username = "undefined";
JSON.parse(usersCache.storage[usersCache.key]).data.forEach(function(u) {
if (u.id == id) {
username = u.username;
}
})
let userBlock = getUserDisplay(username, id, grp_id).prependTo(".UsersInGroupList");
dissociateUserInfo.fadeOut()
$(".UsernameBlock:first").addClass('success_message');
$(".UsernameBlock").slice(1).css("margin-right", "10px").css("border", "none");
associateUserInfo.remove()
associateUserInfo.insertAfter(userBlock);
associateUserInfo.find("p").html(str_user_associated);
associateUserInfo.fadeIn()
updateUserSearch();
usersInGroup.push({username: username, id:id});
while ($(".UsersInGroupList").height() > maxOffsetUserCont) {
$(".UsernameBlock").last().remove();
}
//Update member number
updateMembernumber(parseInt($(".UserNumberBadge").html()) + 1, grp_id);
}
}
});
}
});
$(".input-user-name").on("input", function() {
searchString = $(this).val().toLowerCase();
grp_id = $(".UserListPopIn").data("group_id");
if (searchString != "") {
$(".UsersInGroupListContainer").css("min-height", $(".UsersInGroupListContainer").height())
usersInGroup.forEach(function(u) {
let isSearched = u.username.toLowerCase().includes(searchString)
if ($(".UsernameBlock[data-id="+u.id+"]").length != 0) {
if (!isSearched) {
$(".UsernameBlock[data-id="+u.id+"]").remove();
}
} else if (isSearched) {
getUserDisplay(u.username, u.id, grp_id)
.prependTo(".UsersInGroupList");
}
})
} else {
$(".UsersInGroupListContainer").css("min-height", "")
$(".UsersInGroupList").html("");
let i = 0;
while ($(".UsersInGroupList").outerHeight() <= maxOffsetUserCont && usersInGroup[i] != undefined){
getUserDisplay(usersInGroup[i].username, usersInGroup[i].id, grp_id)
.appendTo(".UsersInGroupList");
i++;
}
}
$(".AmountOfUsersShown strong:nth-child(1)").html($(".UsernameBlock").length)
while ($(".UsersInGroupList").height() > maxOffsetUserCont) {
$(".UsernameBlock").last().remove();
}
})
@@ -0,0 +1,684 @@
$(document).ready(() => {
activateLineOptions();
checkFilters();
if (current_param.ip != "") {
addIpFilter(current_param.ip);
}
if (current_param.image_id != "") {
addImageFilter(current_param.image_id);
}
if (current_param.user_id != "-1") {
addUserFilter(filter_user_name);
}
$(".elem-type-select").on("change", function (e) {
console.log($(".elem-type-select option:selected").attr("value"));
if ($(".elem-type-select option:selected").attr("value") == "visited") {
current_param.types = {
0: "none",
1: "picture"
}
} else if ($(".elem-type-select option:selected").attr("value") == "downloaded"){
current_param.types = {
0: "high",
1: "other"
}
} else {
current_param.types = {
0: "none",
1: "picture",
2: "high",
3: "other"
}
}
fillHistoryResult(current_param)
});
$('.date-start').on("change", function () {
if (current_param.start != $('.date-start input[name="start"]').attr("value")) {
current_param.start = $('.date-start input[name="start"]').attr("value");
current_param.pageNumber = 0;
fillHistoryResult(current_param);
}
});
$('.date-end').on("change", function () {
const newValue = $('.date-end input[name="end"]').attr("value");
if (current_param.end != newValue) {
current_param.end = $('.date-end input[name="end"]').attr("value");
current_param.pageNumber = 0;
// The datepicker first fills the end-date with '1899-12-31',
// which triggers an unnecessary ajax request
// when you come to the history search page from a photo.
if (newValue !== '1899-12-31') {
fillHistoryResult(current_param);
}
}
});
$("#start_unset").on("click", function () {
console.log("here" + current_param.start);
if (!current_param.start == "") {
current_param.pageNumber = 0;
current_param.start = "";
fillHistoryResult(current_param);
}
});
$("#end_unset").on("click", function () {
if (!current_param.start == today) {
current_param.end = today;
current_param.pageNumber = 0;
fillHistoryResult(current_param);
}
});
$('.pagination-arrow.rigth').on('click', () => {
current_param.pageNumber += 1;
fillHistoryResult(current_param);
});
$('.pagination-arrow.left').on('click', () => {
current_param.pageNumber -= 1;
fillHistoryResult(current_param);
});
$(".refresh-results").on("click", function () {
fillHistoryResult(current_param);
})
})
function activateLineOptions() {
$(".search-line").find(".img-option").hide();
/* Display the option on the click on "..." */
$(".search-line").find(".toggle-img-option").on("click", function () {
$(this).find(".img-option").toggle();
})
/* Hide img options and rename field on click on the screen */
$(document).mouseup(function (e) {
e.stopPropagation();
let option_is_clicked = false
$(".img-option span").each(function () {
if (!($(this).has(e.target).length === 0)) {
option_is_clicked = true;
}
})
if (!option_is_clicked) {
$(".search-line").find(".img-option").hide();
}
});
}
function fillSummaryResult(summary) {
$(".user-list").empty();
$(".summary-lines .summary-data").html(summary.NB_LINES);
$(".summary-weight .summary-data").html(unit_MB.replace("%s", summary.FILESIZE));
$(".summary-users .summary-data").html(summary.USERS);
$(".summary-guests .summary-data").html(summary.GUESTS);
if ((summary.GUESTS.split(" ")[0] != "0")) {
$(".summary-guests .summary-data").addClass("icon-plus-circled").on("click", function () {
if (current_param.user_id == "-1") {
current_param.user_id = guest_id;
addGuestFilter(str_guest);
fillHistoryResult(current_param);
}
}).hover(function () {
$(this).css({
cursor : "pointer"
})
});
$(".summary-guests").show();
} else {
$(".summary-guests").hide();
}
var id_of = [];
var user_dot_title = "";
// not sorted
summary.MEMBERS.forEach(keyval => {
for (const [key, value] of Object.entries(keyval)) {
id_of[key] = value;
user_dot_title += key + ", ";
}
});
user_dot_title = user_dot_title.slice(0, -2);
$(".user-dot").attr("title", user_dot_title).addClass("tiptip");
var tmp = 0;
$(".user-dot").hide();
//sorted
for (const [key, value] of Object.entries(summary.SORTED_MEMBERS)) {
if (tmp < 5) {
new_user_item = $("#-2").clone();
new_user_item.removeClass("hide");
new_user_item.find(".user-item-name").html(key);
new_user_item.data("user-id", id_of[key]);
new_user_item.on("click", function () {
if (current_param.user_id != id_of[key]) {
current_param.user_id = $(this).data("user-id");
addUserFilter(key)
fillHistoryResult(current_param);
}
})
$(".user-list").append(new_user_item);
tmp++;
} else {
$(".user-dot").show();
}
}
}
function showResults(doShow) {
console.log("EMPTY");
if (doShow) {
$(".search-summary").show();
$(".container").show();
} else {
$(".search-summary").hide();
$(".container").hide();
}
}
function fillHistoryResult(ajaxParam) {
// console.log(current_param);
// $(".tab .search-line").remove();
$.ajax({
url: API_METHOD,
method: "POST",
dataType: "JSON",
data: ajaxParam,
beforeSend: function () {
showResults(false);
$(".loading").removeClass("hide");
$(".noResults").hide();
$(".tab").empty();
},
success: function (raw_data) {
data = raw_data.result["lines"];
imageDisplay = raw_data.result["params"].display_thumbnail;
maxPage = raw_data.result["maxPage"];
summary = raw_data.result["summary"];
// console.log(raw_data);
//clear lines before refill
if (data.length > 0) {
var id = 0;
data.forEach(line => {
lineConstructor(line, id, imageDisplay)
id++
});
fillSummaryResult(summary);
showResults(true);
$(".noResults").hide();
} else {
showResults(false);
$(".noResults").show();
}
},
error: function (e) {
console.log(e);
}
}).done(() => {
activateLineOptions();
$(".loading").addClass("hide");
updatePagination(maxPage);
$('.tiptip').tipTip({
delay: 0,
fadeIn: 200,
fadeOut: 200,
edgeOffset: 3
});
})
}
function lineConstructor(line, id, imageDisplay) {
let newLine = $("#-1").clone();
let sections = [
"categories",
"tags",
"best_rated",
"memories-1-year-ago",
"list",
"search",
"most_visited",
"recent_pics",
"recent_cats",
"favorites"
]
let icons = [
"line-icon icon-folder-open icon-yellow",
"line-icon icon-tags icon-blue",
"line-icon icon-star icon-green",
"line-icon icon-clock icon-yellow",
"line-icon icon-dice-solid icon-purple",
"line-icon icon-search icon-purple",
"line-icon icon-fire icon-red",
"line-icon icon-clock icon-yellow",
"line-icon icon-clock icon-yellow",
"line-icon icon-heart icon-red"
];
newLine.removeClass("hide");
/* console log to help debug */
// console.log(line);
newLine.attr("id", id);
// console.log(id);
newLine.find(".date-day").html(line.DATE);
newLine.find(".date-hour").html(line.TIME);
newLine.find(".user-name").html(line.USERNAME + '<i class="add-filter icon-plus-circled"></i>');
newLine.find(".user-name").attr("id", line.USERID);
if (current_param.user_id == "-1") {
newLine.find(".user-name").on("click", function () {
current_param.user_id = $(this).attr('id') + "";
current_param.pageNumber = 0;
addUserFilter($(this).html());
fillHistoryResult(current_param);
})
}
newLine.find(".user-ip").html(line.IP + '<i class="add-filter icon-plus-circled"></i>');
newLine.find(".user-ip").data("ip", line.IP);
if (current_param.ip == "") {
newLine.find(".user-ip").on("click", function () {
current_param.ip = $(this).data("ip");
current_param.pageNumber = 0;
addIpFilter($(this).html());
fillHistoryResult(current_param);
})
}
newLine.find(".add-img-as-filter").data("img-id", line.IMAGEID);
if (current_param.image_id == "") {
newLine.find(".add-img-as-filter").on("click", function () {
current_param.image_id = $(this).data("img-id");
current_param.pageNumber = 0;
addImageFilter($(this).data("img-id"));
fillHistoryResult(current_param);
});
}
if (line.EDIT_IMAGE != "") {
newLine.find(".edit-img").attr("href", line.EDIT_IMAGE);
} else {
newLine.find(".edit-img")
.attr("href", "#")
.addClass("notClickable tiptip")
.attr('title', str_no_longer_exist_photo)
.on("click", (e) => {
e.preventDefault();
});
}
switch (line.SECTION) {
case "tags":
if (line.TAGS.length > 1 && line.TAGS.length <= 2 ) {
newLine.find(".type-name").html(line.TAGS[0] +", "+ line.TAGS[1] + ", ...");
newLine.find(".type-id").html("#" + line.TAGIDS[0] +", "+ line.TAGIDS[1] + ", ...");
} else if (line.TAGS.length > 2) {
newLine.find(".type-name").html(line.TAGS[0] +", "+ line.TAGS[1] +", "+ line.TAGS[2] + ", ...");
newLine.find(".type-id").html("#" + line.TAGIDS[0] +", "+ line.TAGIDS[1] +", "+ line.TAGIDS[2] + ", ...");
} else {
newLine.find(".type-name").html(line.TAGS[0]);
newLine.find(".type-id").html("#" + line.TAGIDS[0]);
}
let detail_str = "";
line.TAGS.forEach(tag => {
detail_str += tag + ", ";
});
detail_str = detail_str.slice(0, -2)
newLine.find(".detail-item-1").html(detail_str);
newLine.find(".detail-item-1").attr("title", detail_str).removeClass("hide").addClass('icon-tags');;
break;
case "most_visited":
newLine.find(".type-name").html(str_most_visited);
newLine.find(".detail-item-1").html(str_most_visited).addClass('icon-fire');
newLine.find(".type-id").hide();
break;
case "best_rated":
newLine.find(".type-name").html(str_best_rated);
newLine.find(".detail-item-1").html(str_best_rated).addClass("icon-star");
newLine.find(".type-id").hide();
break;
case "list":
newLine.find(".type-name").html(str_list);
newLine.find(".detail-item-1").html(str_list).addClass('icon-dice-solid');
newLine.find(".type-id").hide();
break;
case "search":
// for debug
// console.log('search n° : ', line.SEARCH_ID, ' ', line.SEARCH_DETAILS);
const search_details = line.SEARCH_DETAILS;
const search_icons = {
'allwords': 'gallery-icon-search',
'tags': 'gallery-icon-tag',
'date_posted': 'gallery-icon-calendar-plus',
'cat': 'gallery-icon-album',
'author': 'gallery-icon-user-edit',
'added_by': 'gallery-icon-user',
'filetypes': 'gallery-icon-file-image',
}
newLine.find(".type-name").html(line.SECTION);
newLine.find(".type-id").html("#" + line.SEARCH_ID);
if (!line.SEARCH_ID)
{
newLine.find(".type-id").hide();
}
if (!search_details)
{
newLine.find(".detail-item-1").hide();
break;
}
let active_search_details = {};
Object.keys(search_details).forEach(key => {
if (search_details[key] !== null) {
active_search_details[key] = search_details[key];
}
});
let count_item = 1;
let active_more = [];
const active_items = Object.keys(active_search_details);
if (active_items.length > 0)
{
if (active_search_details.allwords)
{
newLine.find(".detail-item-" + count_item).html(active_search_details.allwords.join(' ')).addClass(search_icons.allwords + ' tiptip');
newLine.find(".detail-item-" + count_item).attr('title', '<b>' + str_search_details['allwords'] + ' :</b> ' + active_search_details.allwords.join(' '));
count_item++;
active_more.push('allwords');
}
if (active_search_details.cat)
{
const array_cat = Object.values(active_search_details.cat);
const cat = array_cat.join(' + ');
let temp_div = $('<div>').html(cat);
let text = temp_div.text().trim();
newLine.find(".detail-item-" + count_item).html(cat).addClass(search_icons.cat + ' tiptip');
newLine.find(".detail-item-"+ count_item).attr('title','<b>' + str_search_details['cat'] + ' :</b> ' + text).removeClass("hide");
count_item++;
active_more.push('cat');
}
if (count_item <= 2 && active_search_details.tags)
{
const array_tags = Object.values(active_search_details.tags);
newLine.find(".detail-item-" + count_item).html(array_tags.join(' + ')).addClass(search_icons.tags + ' tiptip');
newLine.find(".detail-item-"+ count_item).attr('title', '<b>' + str_search_details['tags'] + ' :</b> ' + array_tags.join(' + ')).removeClass("hide");
count_item++;
active_more.push('tags');
}
if (count_item <= 2)
{
let badge_to_add = active_items.length == 1 ? 1 : count_item == 1 ? 2 : 1;
let badge_added = 0;
active_items.some(key => {
if (key !== 'allwords' && key !== 'cat' && key !== 'tags') {
let array_key;
if (Array.isArray(active_search_details[key]))
{
array_key = active_search_details[key];
}
else if (typeof active_search_details[key] === 'object')
{
array_key = Object.values(active_search_details[key]);
}
else
{
array_key = [active_search_details[key]];
}
newLine.find(".detail-item-" + count_item).html(array_key.join(' + ')).addClass(search_icons[key] + ' tiptip');
newLine.find(".detail-item-" + count_item).attr('title', '<b>' + str_search_details[key] + ' :</b> ' + array_key.join(' + ')).removeClass("hide");
count_item++;
badge_added++;
active_more.push(key);
if (badge_added === badge_to_add) {
return true;
}
}
return false;
});
}
}
else
{
newLine.find(".detail-item-1").hide();
}
if (active_items.length >= 3)
{
let count_more = 0;
let search_details_str = Object.entries(active_search_details)
.filter(([key]) => !active_more.includes(key))
.map(([key, value]) => {
let value_str;
if(Array.isArray(value)) {
value_str = value.join(' + ');
} else if (typeof value === 'object') {
value_str = Object.entries(value).map(([k, v]) => v).join(' + ');
} else {
value_str = value;
}
if (key == 'cat')
{
let temp_div = $('<div>').html(value_str);
let text = temp_div.text().trim();
value_str = text;
}
count_more++;
return `<b>${str_search_details[key]}</b> : ${value_str}`;
}).join(' <br />');
newLine.find(".detail-item-3").html(sprintf(str_and_more, count_more)).addClass('icon-info-circled-1 tiptip');
newLine.find(".detail-item-3").attr('title', search_details_str).removeClass('hide');
}
break;
case "favorites":
newLine.find(".type-name").html(str_favorites);
newLine.find(".detail-item-1").html(str_favorites).addClass('icon-heart');
newLine.find(".type-id").hide();
break;
case "recent_cats":
newLine.find(".type-name").html(str_recent_cats);
newLine.find(".detail-item-1").html(str_recent_cats).addClass('icon-clock');
newLine.find(".type-id").hide();
break;
case "recent_pics":
newLine.find(".type-name").html(str_recent_pics);
newLine.find(".detail-item-1").html(str_recent_pics).addClass('icon-clock');
newLine.find(".type-id").hide();
break;
case "categories":
newLine.find(".type-name").html(line.CATEGORY);
newLine.find(".detail-item-1").html(line.CATEGORY).addClass("icon-folder-open tiptip").attr("title", line.FULL_CATEGORY_PATH);
if (line.IMAGE == "") {
newLine.find(".type-id").hide();
}
break;
case "memories-1-year-ago":
newLine.find(".type-name").html(str_memories);
newLine.find(".detail-item-1").html(str_memories).addClass('icon-clock');
newLine.find(".type-id").hide();
break;
case "contact":
newLine.find(".type-icon i").addClass("line-icon icon-mail-1 icon-yellow");
newLine.find(".type-name").html(str_contact_form);
newLine.find(".detail-item-1").html(str_contact_form);
newLine.find(".type-id").hide();
break;
default:
newLine.find(".type-icon i").addClass("line-icon icon-help-puzzle icon-grey");
newLine.find(".type-name").html(line.SECTION);
newLine.find(".type-id").hide();
break;
}
if (line.IMAGE != "") {
newLine.find(".type-name").html(line.IMAGENAME);
newLine.find(".type-icon").html(line.IMAGE);
newLine.find(".type-id").html("#" + line.IMAGEID);
newLine.find(".type-icon").attr("href", line.EDIT_IMAGE).removeClass("no-img")
newLine.find(".type-icon img").attr("title", str_edit_img).addClass("tiptip")
newLine.find(".type-id").show();
} else {
newLine.find(".type-icon .icon-file-image").removeClass("icon-file-image");
newLine.find(".toggle-img-option").hide();
if (sections.indexOf(line.SECTION) != -1) {
var lineIconClass = icons[sections.indexOf(line.SECTION)];
newLine.find(".type-icon i").addClass(lineIconClass)
} else {
console.log("Unhandled section : " + line.SECTION);
}
}
newLine.find(".detail-item-1").removeClass("hide");
if (line.TYPE == "high") {
newLine.find(".detail-item-1").html(str_dwld).addClass("icon-blue").removeClass("detail-item-1").removeClass("hide");
newLine.find(".date-dwld-icon").addClass("icon-blue icon-floppy")
} else {
newLine.find(".date-dwld-icon").remove();
}
displayLine(newLine);
}
function displayLine(line) {
$(".tab").append(line);
}
function addUserFilter(username) {
var newFilter = $("#default-filter").clone();
newFilter.removeClass("hide");
newFilter.find(".filter-title").html(username);
newFilter.find(".filter-icon").addClass("icon-user");
newFilter.find(".remove-filter").on("click", function () {
$(this).parent().remove();
current_param.user_id = "-1";
current_param.pageNumber = 0;
fillHistoryResult(current_param);
checkFilters();
$(".summary-guests").show();
})
$(".summary-guests").hide();
$(".filter-container").append(newFilter);
checkFilters();
}
function addGuestFilter(username) {
var newFilter = $("#default-filter").clone();
newFilter.removeClass("hide");
newFilter.find(".filter-title").html(username);
newFilter.find(".filter-icon").addClass("icon-user-secret");
newFilter.find(".remove-filter").on("click", function () {
$(this).parent().remove();
current_param.user_id = "-1";
current_param.pageNumber = 0;
fillHistoryResult(current_param);
checkFilters();
})
$(".filter-container").append(newFilter);
checkFilters();
}
function addIpFilter(ip) {
var newFilter = $("#default-filter").clone();
newFilter.removeClass("hide");
newFilter.find(".filter-title").html(ip);
newFilter.find(".filter-icon").html("IP ").addClass("bold");
newFilter.find(".remove-filter").on("click", function () {
$(this).parent().remove();
current_param.ip = "";
current_param.pageNumber = 0;
fillHistoryResult(current_param);
checkFilters();
})
$(".filter-container").append(newFilter);
checkFilters();
}
function addImageFilter(img_id) {
var newFilter = $("#default-filter").clone();
newFilter.removeClass("hide");
newFilter.find(".filter-title").html("Image #" + img_id);
newFilter.find(".filter-icon").addClass("icon-picture");
newFilter.find(".remove-filter").on("click", function () {
$(this).parent().remove();
current_param.image_id = "";
current_param.pageNumber = 0;
fillHistoryResult(current_param);
checkFilters();
})
$(".filter-container").append(newFilter);
checkFilters();
}
function updateArrows(actualPage, maxPage) {
if (actualPage == 0) {
$('.pagination-arrow.left').addClass('unavailable');
} else {
$('.pagination-arrow.left').removeClass('unavailable');
}
if (actualPage == maxPage-1) {
$('.pagination-arrow.rigth').addClass('unavailable');
} else {
$('.pagination-arrow.rigth').removeClass('unavailable');
}
}
function updatePagination(maxPage) {
updateArrows(current_param.pageNumber, maxPage);
$(".pagination-item-container").empty();
$(".pagination-item-container").append(
"<a class='actual'>"+ (current_param.pageNumber+1) + "/" + maxPage +"</a>"
)
}
function checkFilters() {
if ($(".filter-container")[0].childElementCount - 1 > 0) { //Check if there are filters
$(".filter-tags label").show();
} else {
$(".filter-tags label").hide();
}
}
@@ -0,0 +1,135 @@
$(function() {
Object.entries(storage_details).forEach(([type, infos]) => {
// Determine if we use MB or GB and show it correctly
let size = infos.total.filesize;
let str_size_type_string = size > 1000000 ? str_gb : str_mb;
let size_nb = size > 1000000 ? (size / 1000000).toFixed(2) : (size / 1000).toFixed(0);
let str_size = str_size_type_string.replace("%s", size_nb);
// Display head of Tooltip
$('#storage-title-' + type).html('<b>'+translate_type[type]+'</b>');
$('#storage-size-' + type).html('<b>'+ str_size +'</b>');
$('#storage-files-' + type).html('<p>'+ (infos.total.nb_files ? translate_files.replace('%d', infos.total.nb_files) : "~") +'</p>');
// Display body of Tooltip
if (infos.details) {
$.each(infos.details, function(ext, data) {
// Determinate if we use MB or GB and show it correctly (duplicate code from total size for scaling code)
let detail_size = data.filesize;
let detail_str_size_type_string;
let detail_size_nb = 0;
if (detail_size > 1000000) {
detail_str_size_type_string = str_gb;
detail_size_nb = (detail_size / 1000000).toFixed(2);
} else {
detail_str_size_type_string = str_mb;
detail_size_nb = (detail_size / 1000).toFixed(0) < 1 ? (detail_size / 1000).toFixed(2) : (detail_size / 1000).toFixed(0);
}
let detail_str_size = detail_str_size_type_string.replace("%s", detail_size_nb);
$('#storage-detail-' + type).append(''+
'<span class="tooltip-details-cont">'+
'<span class="tooltip-details-ext"><b>'+ ext +'</b></span>'+
'<span class="tooltip-details-size"><b>'+ detail_str_size +'</b></span>'+
'<span class="tooltip-details-files">'+ translate_files.replace('%d', data.nb_files) +'</span>'+
'</span>'+
'');
let ext_bg_color = $('.storage-chart span[data-type="storage-'+type+'"]').css('background-color');
$('#storage-'+type+' .tooltip-details-ext b').css('color', ext_bg_color);
});
} else {
$('#storage-'+ type +' .separated').attr('style', 'display: none !important');
$('#storage-' + type +' .tooltip-header').css('margin', '0');
}
// Fixing storage chart tooltip bug in little screen
// Keep showing tooltip and his % when hovered
$('#storage-' + type).on('mouseenter', function() {
$(this).css('display', 'block');
$('.storage-chart span[data-type="storage-'+ type +'"] p').css('opacity', '0.4');
}).on('mouseleave', function() {
$(this).css('display', 'none');
$('.storage-chart span[data-type="storage-'+ type +'"] p').css('opacity', '0');
});
$('.storage-chart span[data-type="storage-'+ type +'"]').on('mouseover', function() {
$(this).find('p').css('opacity', '0.4');
}).on('mouseout', function() {
$(this).find('p').css('opacity', '0');
});
});
//Tooltip for the storage chart
resizeStorageTooltips();
//Tooltip for the activity chart
resizeActivityTooltips();
// Resize
$(window).on('resize', function(){
// resize storage tooltips
resizeStorageTooltips(true);
// resize activity tooltips
resizeActivityTooltips();
});
});
/*----------------
General function
----------------*/
function resizeStorageTooltips(resize=false) {
$('.storage-chart span').each(function () {
let tooltip = $('.storage-tooltips #'+$(this).data('type'));
let arrow = $('.storage-tooltips #'+$(this).data("type")+' .tooltip-arrow');
let left = $(this).position().left + $(this).width()/2 - tooltip.innerWidth()/2;
// Move tooltip if he create horizontal scrollbar
let storage_width = $('#chart-title-storage').innerWidth();
if(left + tooltip.innerWidth() > storage_width){
let diff = (left + tooltip.innerWidth()) - storage_width;
left = left - diff;
arrow.css('left', 'calc(50% + '+ diff +'px)');
}
tooltip.css('left', left+"px");
// Move tooltip if he create vertical scrollbar
let str_chart_pos = $('.storage-chart').offset().top;
let str_chart_height = $('.storage-chart').innerHeight();
let tooltip_height = $('.storage-tooltips #'+$(this).data("type")).innerHeight() + str_chart_height;
let windows_height = $(window).height();
if (resize) {
if (str_chart_pos + tooltip_height > windows_height) {
tooltip.css('bottom', 'calc(100% + '+ str_chart_height +'px)');
arrow.addClass('bottom');
} else {
tooltip.css('bottom', '');
arrow.removeClass('bottom');
}
} else {
if (str_chart_pos + tooltip_height > windows_height) {
tooltip.css('bottom', 'calc(100% + '+ str_chart_height +'px)');
arrow.addClass('bottom');
}
$(this).off('mouseenter').on('mouseenter', function() {
tooltip.show();
});
$(this).off('mouseleave').on('mouseleave', function() {
tooltip.hide();
});
}
});
}
function resizeActivityTooltips() {
$('.activity_tooltips').has('.tooltip').each(function() {
const max_width = $('#pwgMain').innerWidth() - 20;
const tooltip = $(this).find('.tooltip');
let left = $(this).position().left + ($(this).innerWidth() / 2) + (tooltip.innerWidth() / 2);
if (left > max_width) {
const arrow = $(this).find('.tooltip-arrow');
const diff = max_width - left;
tooltip.css('left', 'calc(50% + '+ diff +'px)');
arrow.css('left', 'calc(50% - '+ diff +'px)');
}
});
}
@@ -0,0 +1,62 @@
GeoIp = {
cache: {},
pending: {},
get: function(ip, callback){
if (!GeoIp.storageInit && window.localStorage) {
GeoIp.storageInit = true;
var cache = localStorage.getItem("freegeoip");
if (cache) {
cache = JSON.parse(cache);
for (var key in cache) {
var data = cache[key];
if ( (new Date()).getTime() - data.reqTime > 96 * 3600000)
delete cache[key];
}
GeoIp.cache = cache;
}
jQuery(window).on("unload", function() {
localStorage.setItem("freegeoip", JSON.stringify(GeoIp.cache) );
} );
}
if (GeoIp.cache.hasOwnProperty(ip))
callback(GeoIp.cache[ip]);
else if (GeoIp.pending[ip])
GeoIp.pending[ip].push(callback);
else {
GeoIp.pending[ip] = [callback];
jQuery.ajax( {
url: "http://freegeoip.net/json/" + ip,
dataType: "jsonp",
cache: true,
timeout: 5000,
success: function(data) {
data.reqTime = (new Date()).getTime();
var res=[];
if (data.city) res.push(data.city);
if (data.region_name) res.push(data.region_name);
if (data.country_name) res.push(data.country_name);
data.fullName = res.join(", ");
GeoIp.cache[ip] = data;
var callbacks = GeoIp.pending[ip];
delete GeoIp.pending[ip];
for (var i=0; i<callbacks.length; i++)
callbacks[i].call(null, data);
},
error: function() {
var data = {ip:ip, reqTime: (new Date()).getTime()};
GeoIp.cache[ip] = data;
var callbacks = GeoIp.pending[ip];
delete GeoIp.pending[ip];
for (var i=0; i<callbacks.length; i++)
callbacks[i].call(null, data);
}
});
}
}
}
@@ -0,0 +1,62 @@
function displayResponse(domElem, values, mDivs, mValues) {
for (let index = 0; index < domElem.length; index++) {
domElem[index].html(unit_MB.replace("%s",values[index]))
}
for (let index = 0; index < mDivs.length; index++) {
mDivName = mDivs[index].getAttribute("name");
mDivs[index].title = unit_MB.replace("%s", mValues[mDivName])
}
$(".cache-lastCalculated-value").html(no_time_elapsed);
}
$(document).ready(function () {
$(".refresh-cache-size").on("click", function () {
$(this).find(".refresh-icon").addClass("animate-spin");
return new Promise((res, rej) => {
jQuery.ajax({
url: "ws.php?format=json&method=pwg.getCacheSize",
type: "POST",
data: {
param : "test_param",
service : "test_service"
},
success: function (raw_data) {
data = jQuery.parseJSON(raw_data);
if (data.stat === "ok") {
res();
var domElemToRefresh = [$(".cache-size-value"), $(".multiple-pictures-sizes"), $(".multiple-compiledTemplate-sizes")];
var domElemValues = [data.result.infos[0].value, data.result.infos[1].value.all, data.result.infos[2].value];
for (let i = 0; i < domElemValues.length; i++) {
domElemValues[i] = (domElemValues[i]/1024/1024).toFixed(2);
}
var multipleSizes = $(".delete-check-container").children(".delete-size-check");
var multipleSizesValues = data.result.infos[1].value
for (const [key, value] of Object.entries(multipleSizesValues)) {
multipleSizesValues[key] = (multipleSizesValues[key]/1024/1024).toFixed(2);
}
displayResponse(domElemToRefresh , domElemValues, multipleSizes, multipleSizesValues);
$(".animate-spin").removeClass("animate-spin");
} else {
rej(data);
}
},
error: function(message) {
rej(message);
console.log(message);
}
});
})
})
})
@@ -0,0 +1,31 @@
$(document).ready(function () {
jQuery.ajax({
url: "ws.php?format=json&method=pwg.plugins.getList",
type: "GET",
dataType: "JSON",
success: function(data) {
plugins = data.result;
hasActivePlugins = false
nbActivatedPlugins = 0;
plugins.forEach(plugin => {
if (plugin.state == "active") {
hasActivePlugins = true
$("#pluginList ul").append("<li>" + plugin.name +"</li>");
$("#pluginList ul i").hide();
nbActivatedPlugins++;
}
});
if (!hasActivePlugins) {
$("#pluginList ul i").hide();
$("#pluginList ul").append("<p>" + no_active_plugin +"</p>");
}
$(".badge-number").append(nbActivatedPlugins);
},
error: function () {
$(".badge-number").append(0);
$("#pluginList ul").append("<p>" + error_occured +"</p>");
$("#pluginList ul i").hide();
}
});
})
@@ -0,0 +1,116 @@
const color_icons = ["icon-red", "icon-blue", "icon-yellow", "icon-purple", "icon-green"];
function line_constructor(line){
let new_line = $('#body_example').clone();
const line_details_example = $('#line_details_example').clone();
const initial_user = line.username.charAt(0).toUpperCase();
// id
new_line.attr('id', line.id);
// Display major information
if (line.major_infos) {
new_line.addClass('major-infos');
}
// Display object
new_line.find('.icon_object').addClass(line.object_icon);
new_line.find('.text_object').text(line.object).attr('title', line.object);
// Display action
new_line.find('.color_action').addClass(line.action_color);
new_line.find('.icon_action').addClass(line.action_icon);
new_line.find('.text_action').text(line.action).attr('title', line.action);
// Display Username
'System' == line.username
? new_line.find('.icon_user').addClass('icon-robot-head')
: new_line.find('.icon_user').addClass(color_icons[line.user_id % 5]).html(initial_user);
new_line.find('.text_username').text(line.username).attr('title', line.username);
// Display date & hour
new_line.find('.text_date').text(line.date).attr('title', line.date + ' ' + line.hour);
new_line.find('.text_hour').text(line.hour);
// Display Details
switch(line.detail.type){
case 'empty':
default:
// For empty CSS do it for us but he exist
break;
// Here is when we want to display only one element in details (and default)
case 'error':
case 'version':
case 'maintenance_action':
let new_line_detail = line_details_example.clone();
new_line_detail.removeAttr('id');
new_line_detail.find('.icon_details').addClass(line.detail.icon);
new_line_detail.find('.text_details').text(line.detail.text).attr('title', line.detail.text);
new_line.find('.tab-body-details').append(new_line_detail);
break;
// Here is when we want to display multiple elements one by one (Work if details can have one or multiple elements)
case 'db_fs_version':
case 'config_section':
Object.keys(line.detail)
.filter((key) => 'type' !== key)
.forEach((key) => {
let detail = line.detail[key];
let new_line_details = line_details_example.clone();
new_line_details.removeAttr('id');
new_line_details.find('.icon_details').addClass(detail.icon);
new_line_details.find('.text_details').text(detail.text).attr('title', detail.text);
new_line.find('.tab-body-details').append(new_line_details);
});
break;
// Here is when we need to specific the format for somes types
// from_to
case 'from_to':
let from = line_details_example.clone();
from.removeAttr('id');
from.find('.icon_details').addClass(line.detail[0].icon);
from.find('.text_details').text(line.detail[0].text).attr('title', line.detail[0].text);
new_line.find('.tab-body-details').append(from);
new_line.find('.tab-body-details').append('<span class="icon-right"> </span>');
let to = line_details_example.clone();
to.removeAttr('id');
to.find('.icon_details').addClass(line.detail[1].icon);
to.find('.text_details').text(line.detail[1].text).attr('title', line.detail[1].text);
new_line.find('.tab-body-details').append(to);
break;
}
$('#tab-body-content').append(new_line);
}
function get_system_activities(){
$.ajax({
url: window.location.href,
type: 'GET',
data: {
method: 'pwg.activity_sys.getList'
},
dataType: 'json',
success: (response) => {
const lines = response.data;
// help to debug
// console.log(lines);
$('.loading').hide();
lines.forEach((line) => line_constructor(line));
},
error: (e) => {
console.log(e);
}
});
}
$(document).ready(function() {
get_system_activities();
});
@@ -0,0 +1,573 @@
/*--------------
Variables
--------------*/
const btnFirstAlbum = $('#btnFirstAlbum');
const modalFirstAlbum = $('#addFirstAlbum');
const closeModalFirstAlbum = $('#closeFirstAlbum');
const inputFirstAlbum = $('#inputFirstAlbum');
const btnAddFirstAlbum = $('#btnAddFirstAlbum');
const firstAlbum = $('.addAlbumEmptyCenter');
const uploadForm = $('#uploadForm');
const addPhotosAS = $('#addPhotosAS');
const btnPhotosAS = $('#btnPhotosAS');
const selectedAlbum = $('#selectedAlbum');
const selectedAlbumName = $('#selectedAlbumName');
const selectedAlbumEdit = $('#selectedAlbumEdit');
const btnAddFiles = $('#addFiles');
const chooseAlbumFirst = $('#chooseAlbumFirst');
const uploaderPhotos = $('#uploader');
const formatsUpdated = [];
const formats = [];
/*--------------
On DOM load
--------------*/
$(function () {
// First album event
if (!nb_albums) {
btnFirstAlbum.on('click', function () {
open_new_album_modal();
});
closeModalFirstAlbum.on('click', function () {
close_new_album_modal();
});
btnAddFirstAlbum.on('click', function () {
add_first_album(ab.select_album.bind(ab));
});
inputFirstAlbum.on('keyup', function(e) {
if (e.key === 'Enter') {
btnAddFirstAlbum.trigger('click');
}
});
}
const ab = new AlbumSelector({
selectedCategoriesIds: related_categories_ids,
selectAlbum: add_related_category,
adminMode: true,
modalTitle: str_drop_album_ab,
});
// Open album selector event
btnPhotosAS.on('click', function () {
ab.open();
});
selectedAlbumEdit.on('click', function () {
ab.open();
});
// Upload logics
$(".dont-show-again").on("click", function () {
$.ajax({
url: "ws.php?format=json&method=pwg.users.preferences.set",
type: "POST",
dataType: "JSON",
data: {
param: 'promote-mobile-apps',
value: false,
},
success: function (res) {
jQuery(".promote-apps").hide();
}
})
});
$("#uploadWarningsSummary a.showInfo").on('click', function () {
$("#uploadWarningsSummary").hide();
$("#uploadWarnings").show();
return false;
});
$("#showPermissions").on('click', function () {
$(this).parent(".showFieldset").hide();
$("#permissions").show();
return false;
});
$("#uploadOptionsContent").hide();
$("#uploadOptions").on("click", function(){
$("#uploadOptionsContent").slideToggle();
$("#uploadOptions").toggleClass('options-open');
$(".moxie-shim-html5").css("display", "none");
})
$("#uploader").pluploadQueue({
// General settings
browse_button: 'addFiles',
container: 'uploadForm',
// runtimes : 'html5,flash,silverlight,html4',
runtimes: 'html5',
// url : '../upload.php',
url: 'ws.php?method=pwg.images.upload&format=json',
chunk_size,
filters: {
// Maximum file size
max_file_size,
// Specify what files to browse for
mime_types: [
{ title: "Image files", extensions: formatMode ? format_ext : file_ext }
]
},
// Rename files by clicking on their titles
rename: formatMode,
// Enable ability to drag'n'drop files onto the widget (currently only HTML5 supports that)
dragdrop: true,
preinit: {
Init: function (up, info) {
$('#uploader_container').removeAttr("title"); //remove the "using runtime" text
$('#startUpload').on('click', function (e) {
e.preventDefault();
up.start();
});
$('#cancelUpload').on('click', function (e) {
e.preventDefault();
up.stop();
up.trigger('UploadComplete', up.files);
});
}
},
init: {
// update custom button state on queue change
QueueChanged: function (up) {
$('#addFiles').addClass("addFilesButtonChanged");
$('#startUpload').prop('disabled', up.files.length == 0);
$("#addFiles").removeClass('buttonLike').addClass('buttonLike');
if (up.files.length > 0) {
$('.plupload_filelist_footer').show();
$('.plupload_filelist').css("overflow-y", "scroll");
}
if (up.files.length == 0) {
$('#addFiles').removeClass("addFilesButtonChanged");
$("#addFiles").removeClass('buttonLike').addClass('buttonLike');
$('.plupload_filelist_footer').hide();
$('.plupload_filelist').css("overflow-y", "hidden");
}
},
FilesAdded: async function (up, files) {
// Création de la liste avec plupload_id : image_name
fileNames = {};
exts = {};
files.forEach((file) => {
fileNames[file.id] = file.name;
exts[file.id] = file.name.substr(file.name.lastIndexOf('.') + 1);
});
if (formatMode) {
formats.forEach((forms) => {
$("#"+forms[0]+" > .plupload_file_name").append(`
<a target=\"_blank\" href=\"admin.php?page=photo-${forms[1].trim()}-properties\">
<span class=\"icon-eye\">
</span>
</a>`);
if(formatsUpdated.includes(forms[0])){
$("#"+forms[0]+" > .plupload_file_name").after(`
<a target=\"_blank\" href=\"admin.php?page=photo-${forms[1].trim()}-formats\">
<span class=\"icon-attention update-warning\">
${format_update_warning}
</span>
</a>
<a class="remove-format" id=\"remove_${forms[0]}\">
<span class = \"icon-cancel-circled\">
</span>
${format_remove}
</a>`);
$("#remove_"+forms[0]).on("click", function(){
up.removeFile(forms[0]);
});
}
});
// If no original image is specified
if (!haveFormatsOriginal) {
const images_search = await new Promise((res, rej) => {
//ajax qui renvois les id des images dans la gallerie.
$.ajax({
url: "ws.php?format=json&method=pwg.images.formats.searchImage",
type: "POST",
data: {
filename_list: JSON.stringify(fileNames),
},
success: function (result) {
let data = JSON.parse(result);
res(data.result)
}
})
})
const notFound = [];
const multiple = [];
files.forEach((f) => {
const search = images_search[f.id];
if (search.status == "found"){
f.format_of = search.image_id;
formats.push([f.id,f.format_of]);
$("#"+f.id+" > .plupload_file_name").append(`
<a target=\"_blank\" href=\"admin.php?page=photo-${f.format_of.trim()}-properties\">
<span class=\"icon-eye\">
</span>
</a>`);
if (search.format_exist)
{
$("#"+f.id+" > .plupload_file_name").after(`
<a target=\"_blank\" href=\"admin.php?page=photo-${f.format_of.trim()}-formats\">
<span class=\"icon-attention update-warning\">
${format_update_warning}
</span>
</a>
<a class="remove-format" id=\"remove_${f.id}\">
<span class = \"icon-cancel-circled\">
</span>
${format_remove}
</a>`);
formatsUpdated.push(f.id);
$("#remove_"+f.id).on("click", function(){
up.removeFile(f.id);
});
}
}
else {
if (search.status == "multiple")
multiple.push(f.name);
else
notFound.push(f.name);
up.removeFile(f.id);
}
})
files.filter(f => images_search[f.id].status === "found");
// If a file is not found or found more than one time
if (notFound.length || multiple.length) {
const [multStr, notFoundStr] = [multiple, notFound].map((tab) => {
//Get names
tab = tab.map(f => f.slice(0, f.indexOf('.')))
// Remove duplicates
tab = tab.filter((f, i) => i === tab.indexOf(f))
// Add "and X more" if necessary
if (tab.length > 5) {
tab[5] = str_and_X_others.replace('%d', tab.length - 5);
tab = tab.splice(0, 6);
}
return tab;
})
$.alert({
title: str_format_warning,
content: (notFound.length ? `<p>${str_format_warning_notFound.replace('%s', notFoundStr.join(', '))}</p>` : "")
+ (multiple.length ? `<p>${str_format_warning_multiple.replace('%s', multStr.join(', '))}</p>` : ""),
...jConfirm_warning_options
})
}
} else {
if (imageFormatsExtensions)
{
$forms_exts = JSON.parse(imageFormatsExtensions);
}
else
{
$forms_exts = [];
}
files.forEach((f) => {
f.format_of = originalImageId;
formats.push([f.id,f.format_of]);
$("#"+f.id+" > .plupload_file_name").append(`
<a target=\"_blank\" href=\"admin.php?page=photo-${f.format_of.trim()}-properties\">
<span class=\"icon-eye\">
</span>
</a>`);
if ($forms_exts.indexOf(exts[f.id]) != -1)
{
$("#"+f.id+" > .plupload_file_name").after(`
<a target=\"_blank\" href=\"admin.php?page=photo-${originalImageId.trim()}-formats\">
<span class=\"icon-attention update-warning\">
${format_update_warning}
</span>
</a>
<a class="remove-format" id=\"remove_${f.id}\">
<span class = \"icon-cancel-circled\">
</span>
${format_remove}
</a>`);
formatsUpdated.push(f.id);
$("#remove_"+f.id).on("click", function(){
up.removeFile(f.id);
});
}
})
}
}
},
FilesRemoved: function(up, file){
formats.forEach((forms) => {
$("#"+forms[0]+" > .plupload_file_name").append(`
<a target=\"_blank\" href=\"admin.php?page=photo-${forms[1].trim()}-properties\">
<span class=\"icon-eye\">
</span>
</a>`);
if(formatsUpdated.includes(forms[0])){
$("#"+forms[0]+" > .plupload_file_name").after(`
<a target=\"_blank\" href=\"admin.php?page=photo-${forms[1].trim()}-formats\">
<span class=\"icon-attention update-warning\">
${format_update_warning}
</span>
</a>
<a class="remove-format" id=\"remove_${forms[0]}\">
<span class = \"icon-cancel-circled\">
</span>
${format_remove}
</a>`);
$("#remove_"+forms[0]).on("click", function(){
up.removeFile(forms[0]);
});
}
});
},
UploadProgress: function (up, file) {
$('#uploadingActions .progressbar').width(up.total.percent + '%');
Piecon.setProgress(up.total.percent);
},
BeforeUpload: function (up, file) {
// hide buttons
$('#startUpload, .selectFilesButtonBlock').hide();
$('#uploadingActions').show();
$('.format-mode-group-manager').hide();
$('#selectedAlbumEdit').hide();
// if (!formatMode) {
// var categorySelectedId = $("select[name=category] option:selected").val();
// var categorySelectedPath = $("select[name=category]")[0].selectize.getItem(categorySelectedId).text();
// $('.selectedAlbum').show().find('span').html(categorySelectedPath);
// }
// warn user if she wants to leave page while upload is running
$(window).bind('beforeunload', function () {
return str_upload_in_progress;
});
// no more change on category/level
$("select[name=level]").attr("disabled", "disabled");
// You can override settings before the file is uploaded
var options = {
pwg_token: pwg_token
};
if (formatMode) {
options.format_of = file.format_of;
} else {
// options.category = $("select[name=category] option:selected").val();
options.category = ab.get_selected_albums()[0];
// options.level = $("select[name=level] option:selected").val();
options.name = file.name;
}
options.update_mode = $('#toggleUpdateMode').is(':checked');
up.setOption('multipart_params', options);
},
FileUploaded: function (up, file, info) {
// Called when file has finished uploading
//console.log('[FileUploaded] File:', file, "Info:", info);
// hide item line
$('#' + file.id).hide();
let data = JSON.parse(info.response);
$("#uploadedPhotos").parent("fieldset").show();
html = '<a href="admin.php?page=photo-' + data.result.image_id + '" style="position : relative" target="_blank">';
html += '<img src="' + data.result.square_src + '" class="thumbnail" title="' + data.result.name + '">';
if (formatMode) html += '<div class="format-ext-name" title="' + file.name + '"><span>' + file.name.slice(file.name.indexOf('.')) + '</span></div>';
html += '</a> ';
$("#uploadedPhotos").prepend(html);
// do not remove file, or it will reset the progress bar :-/
// up.removeFile(file);
uploadedPhotos.push(parseInt(data.result.image_id));
if(data.result.add_status=="add"){
addedPhotos.push(parseInt(data.result.image_id));
}
else{
updatedPhotos.push(parseInt(data.result.image_id));
}
if (!formatMode)
uploadCategory = data.result.category;
},
Error: function (up, error) {
// Called when file has finished uploading
//console.log('[Error] error: ', error);
var piwigoApiResponse = JSON.parse(error.response);
$(".errors ul").append('<li>' + piwigoApiResponse.message + '</li>');
$(".errors").show();
},
UploadComplete: function (up, files) {
// Called when all files are either uploaded or failed
//console.log('[UploadComplete]');
Piecon.reset();
if (!formatMode) {
$.ajax({
url: "ws.php?format=json&method=pwg.images.uploadCompleted",
type: "POST",
data: {
pwg_token: pwg_token,
image_id: uploadedPhotos.join(","),
category_id: uploadCategory.id,
}
});
}
$("#uploadForm, #permissions, .showFieldset").hide();
const infoTextAdd = formatMode ?
sprintf(formatsAdded_label, addedPhotos.length, [...new Set(addedPhotos)].length)
: sprintf(photosAdded_label, addedPhotos.length);
const infoTextUpdate = formatMode ?
sprintf(formatsUpdated_label, updatedPhotos.length, [...new Set(updatedPhotos)].length)
: sprintf(photosUpdated_label, updatedPhotos.length);
if (addedPhotos.length && updatedPhotos.length)
{
$(".infos").append( '<ul><li>' + infoTextAdd + ', ' + infoTextUpdate + '</li></ul>');
}
else
{
const infoText = addedPhotos.length ? infoTextAdd : infoTextUpdate;
$(".infos").append('<ul><li>' + infoText + '</li></ul>');
}
if (!formatMode) {
html = sprintf(
albumSummary_label,
'<a href="admin.php?page=album-' + uploadCategory.id + '">' + uploadCategory.label + '</a>',
parseInt(uploadCategory.nb_photos)
);
$(".infos ul").append('<li>' + html + '</li>');
}
$(".infos").show();
// TODO: use a new method pwg.caddie.empty +
// pwg.caddie.add(uploadedPhotos) instead of relying on huge GET parameter
// (and remove useless code from admin/photos_add_direct.php)
$(".batchLink").attr("href", "admin.php?page=photos_add&section=direct&batch=" + [...new Set(uploadedPhotos)].join(","));
$(".batchLink").html(sprintf(batch_Label, uploadedPhotos.length));
$(".afterUploadActions").show();
$('#uploadingActions').hide();
$('#selectedAlbumEdit').show();
// user can safely leave page without warning
$(window).unbind('beforeunload');
}
}
});
});
/*--------------
General functions
--------------*/
function add_related_category({ album, newSelectedAlbum }) {
let text = '';
$(album.full_name_with_admin_links).each(function (i, s) {
if ($(s).html()) { text += $(s).html() }
});
newSelectedAlbum();
selectedAlbumName.hide();
selectedAlbumName.html(text);
selectedAlbumName.fadeIn();
addPhotosAS.hide();
selectedAlbum.fadeIn();
enable_uploader();
}
function enable_uploader() {
btnAddFiles.removeAttr('disabled');
chooseAlbumFirst.hide();
uploaderPhotos.show();
}
/*-------------------
First album functions
-------------------*/
function open_new_album_modal() {
inputFirstAlbum.val('');
modalFirstAlbum.fadeIn();
inputFirstAlbum.trigger('focus');
}
function close_new_album_modal() {
modalFirstAlbum.fadeOut();
}
function hide_first_album(cat_name) {
modalFirstAlbum.hide();
firstAlbum.hide();
addPhotosAS.hide();
selectedAlbumName.html(cat_name);
selectedAlbum.show();
enable_uploader();
uploadForm.fadeIn();
}
function add_first_album(add_cat) {
const params = {
name: inputFirstAlbum.val().toString(),
pwg_token
}
$.ajax({
url: 'ws.php?format=json&method=pwg.categories.add',
method: 'POST',
dataType: 'json',
data: params,
success: function (res) {
if (res.stat === 'ok') {
add_cat(res.result.id);
hide_first_album(params.name);
} else {
console.error('An error has occurred');
}
},
error: function() {
console.error('An error has occurred');
}
});
}
@@ -0,0 +1,55 @@
function fitExtensions() {
$(".format-card-ext span").each((i, node) => {
let size = Math.min(180 * 1/node.innerHTML.length, 45)
node.setAttribute('style', `font-size:${size}px`)
})
}
fitExtensions()
$('.format-card').each((i, node) => {
let card = $(node)
let button = card.find(".format-delete")
button.click(() => {
$.confirm({
title: str_confirm_delete_format.replace("%s",card.find('.format-card-ext span').html()),
content: "",
buttons: {
confirm: {
text: str_confirm_msg,
btnClass: 'btn-red',
action: function () {
deleteFormat(card)
},
},
cancel: {
text: str_cancel_msg
}
},
...jConfirm_confirm_options
})
})
})
function deleteFormat(card) {
card.find('.format-delete i').attr("class", "icon-spin6 animate-spin")
$.ajax({
url: "ws.php?format=json&method=pwg.images.formats.delete",
type: "POST",
data: {
pwg_token : pwg_token,
format_id: card.data("id"),
},
success: function (raw_data) {
card.fadeOut("slow", () => {
card.remove();
if ($('.format-card').length == 0)
$('.no-formats').show()
})
},
error: function(message) {
console.log(message);
}
})
}
@@ -0,0 +1,77 @@
$(document).ready(function () {
const ab = new AlbumSelector({
selectedCategoriesIds: related_categories_ids,
selectAlbum: add_related_category,
removeSelectedAlbum: remove_related_category,
adminMode: true,
modalTitle: str_assoc_album_ab,
});
$(".linked-albums.add-item").on("click", function () {
ab.open();
});
$('.related-categories-container').on('click', (e) => {
if (e.target.classList.contains("remove-item")) {
ab.remove_selected_album($(e.target).attr('id'));
}
});
// Unsaved settings message before leave this page
let form_unsaved = false;
let user_interacted = false;
$('#pictureModify').find(':input').on('focus', function () {
user_interacted = true;
});
$('#pictureModify').find(':input').on('change', function () {
if (user_interacted) {
form_unsaved = true;
console.log($(this)[0].name, $(this));
}
});
$(window).on('beforeunload', function () {
if (form_unsaved) {
return 'Somes changes are not registered';
}
});
$('#pictureModify').on('submit', function () {
form_unsaved = false;
});
})
function remove_related_category({ id_album, getSelectedAlbum }) {
$(".invisible-related-categories-select option[value="+ id_album +"]").remove();
$(".invisible-related-categories-select").trigger('change');
$("#" + id_album).parent().remove();
check_related_categories(getSelectedAlbum());
}
function add_related_category({ album, addSelectedAlbum, getSelectedAlbum }) {
if (!getSelectedAlbum().includes(album.id)) {
$(".related-categories-container").append(
`<div class="breadcrumb-item">
<span class="link-path">${album.full_name_with_admin_links}</span><span id="${album.id}" class="icon-cancel-circled remove-item"></span>
</div>`
);
$(".search-result-item #" + album.id).addClass("notClickable");
$(".invisible-related-categories-select").append("<option selected value="+ album.id +"></option>").trigger('change');
addSelectedAlbum();
}
check_related_categories(getSelectedAlbum());
}
function check_related_categories(selected_cat) {
$(".linked-albums-badge").html(selected_cat.length);
if (selected_cat.length == 0) {
$(".linked-albums-badge").addClass("badge-red");
$(".add-item").addClass("highlight");
$(".orphan-photo").html(str_orphan).show();
} else {
$(".linked-albums-badge.badge-red").removeClass("badge-red");
$(".add-item.highlight").removeClass("highlight");
$(".orphan-photo").hide();
}
}
@@ -0,0 +1,747 @@
function setDisplayClassic() {
$(".pluginContainer").removeClass("line-form").removeClass("compact-form").addClass("classic-form");
$(".pluginDesc").show();
$(".pluginActions").show();
$(".pluginActionsSmallIcons").hide();
$(".pluginName").removeClass("pluginNameCompact");
// normalTitle();
}
function setDisplayCompact() {
$(".pluginContainer").removeClass("line-form").addClass("compact-form").removeClass("classic-form");
$(".pluginDesc").hide();
$(".pluginActions").hide();
$(".pluginActionsSmallIcons").show();
$(".pluginName").addClass("pluginNameCompact");
// reduceTitle()
}
function setDisplayLine() {
$(".pluginContainer").addClass("line-form").removeClass("compact-form").removeClass("classic-form");
$(".pluginDesc").show();
$(".pluginActions").show();
$(".pluginActionsSmallIcons").hide();
// normalTitle();
}
function reduceTitle() {
var x = document.getElementsByClassName("pluginName");
var length = 22;
for (const div of x) {
var text = div.innerHTML.trim()
if (text.length > length) {
var newText = text.substring(0, length);
newText = newText + "...";
div.innerHTML = newText;
div.title = text
}
}
}
function normalTitle() {
var x = document.getElementsByClassName("pluginName");
for (const div of x) {
div.innerHTML = div.dataset.title
}
}
function activatePlugin(id) {
$("#"+id+" .switch").attr("disabled", true);
$.ajax({
type: 'GET',
dataType: 'json',
url: 'ws.php',
data: { method: 'pwg.plugins.performAction',
action: 'activate',
plugin: id,
pwg_token: pwg_token,
format: 'json' },
success: function (data) {
if (data.stat == 'ok') {
let pluginName = id;
$("#" + id + " .pluginNotif").stop(false, true);
$("#" + id + " .AddPluginSuccess label span:first").html(plugin_added_str);
$("#" + id + " .AddPluginSuccess").css("display", "flex");
nb_plugin.active += 1;
nb_plugin.inactive -= 1;
actualizeFilter();
}
},
error: function (e) {
console.log(e.responseText);
$("#" + id + " .pluginNotif").stop(false, true);
$("#" + id + " .PluginActionError label span:first").html(plugin_action_error);
$("#" + id + " .PluginActionError").css("display", "flex");
$("#" + id + " .PluginActionError").delay(1500).fadeOut(2500);
}
}).done(function (data) {
$("#"+id+" .switch").attr("disabled", false);
$("#" + id + " .AddPluginSuccess").fadeOut(3000);
})
}
function disactivatePlugin(id) {
$("#"+id+" .switch").attr("disabled", true);
$.ajax({
type: 'GET',
dataType: 'json',
url: 'ws.php',
data: { method: 'pwg.plugins.performAction',
action: 'deactivate',
plugin: id,
pwg_token: pwg_token,
format: 'json' },
success: function (data) {
if (data.stat == 'ok') {
let pluginName = id;
$("#" + id + " .pluginNotif").stop(false, true);
$("#" + id + " .DeactivatePluginSuccess label span:first").html(plugin_deactivated_str);
$("#" + id + " .DeactivatePluginSuccess").css("display", "flex");
nb_plugin.inactive += 1;
nb_plugin.active -= 1;
actualizeFilter();
}
},
error: function (e) {
console.log(e);
$("#" + id + " .pluginNotif").stop(false, true);
$("#" + id + " .PluginActionError label span:first").html(plugin_action_error);
$("#" + id + " .PluginActionError").css("display", "flex");
$("#" + id + " .PluginActionError").delay(1500).fadeOut(2500);
}
}).done(function (data) {
$("#"+id+" .switch").attr("disabled", false);
$("#" + id + " .DeactivatePluginSuccess").fadeOut(3000);
})
}
function deletePlugin(id, name) {
$.alert({
title : deleted_plugin_msg.replace("%s",name),
content: function() {
return $.ajax({
type: 'GET',
dataType: 'json',
url: 'ws.php',
data: { method: 'pwg.plugins.performAction',
action: 'delete',
plugin: id,
pwg_token: pwg_token,
format: 'json' },
success: function (data) {
if (data.stat === "ok") {
$("#"+id).remove();
nb_plugin.inactive -=1;
nb_plugin.all -=1;
actualizeFilter();
}
},
error: function (e) {
console.log(e);
$("#" + id + " .pluginNotif").stop(false, true);
$("#" + id + " .PluginActionError label span:first").html(plugin_action_error);
$("#" + id + " .PluginActionError").css("display", "flex");
$("#" + id + " .PluginActionError").delay(1500).fadeOut(2500);
}
})
},
...jConfirm_alert_options
});
}
function restorePlugin(id) {
$.ajax({
type: 'GET',
dataType: 'json',
url: 'ws.php',
data: { method: 'pwg.plugins.performAction',
action: 'restore',
plugin: id,
pwg_token: pwg_token,
format: 'json' },
success: function (data) {
if (data.stat == 'ok') {
let pluginName = id;
$("#" + id + " .pluginNotif").stop(false, true);
$("#" + id + " .RestorePluginSuccess label span:first").html(plugin_restored_str);
$("#" + id + " .RestorePluginSuccess").css("display", "flex");
}
},
error: function (e) {
console.log(e);
$("#" + id + " .pluginNotif").stop(false, true);
$("#" + id + " .PluginActionError label span:first").html(plugin_action_error);
$("#" + id + " .PluginActionError").css("display", "flex");
$("#" + id + " .PluginActionError").delay(1500).fadeOut(2500);
}
}).done(function (data) {
$("#" + id + " .RestorePluginSuccess").fadeOut(3000);
})
}
function uninstallPlugin(id) {
$.ajax({
type: 'GET',
dataType: 'json',
url: 'ws.php',
data: { method: 'pwg.plugins.performAction',
action: 'uninstall',
plugin: id,
pwg_token: pwg_token,
format: 'json' },
success: function (data) {
$("#"+id).remove();
nb_plugin.other -=1;
nb_plugin.all -=1;
actualizeFilter();
},
error: function (e) {
$("#" + id + " .pluginNotif").stop(false, true);
$("#" + id + " .PluginActionError label span:first").html(plugin_action_error);
$("#" + id + " .PluginActionError").css("display", "flex");
$("#" + id + " .PluginActionError").delay(1500).fadeOut(2500);
console.log(e.message);
}
})
}
$(document).ready(function () {
actualizeFilter();
if ($("#displayClassic").is(":checked")) {
setDisplayClassic();
};
if ($("#displayCompact").is(":checked")) {
setDisplayCompact();
};
if ($("#displayLine").is(":checked")) {
setDisplayLine();
};
$("#displayClassic").change(function () {
setDisplayClassic();
set_view_selector('classic');
})
$("#displayCompact").change(function () {
setDisplayCompact();
set_view_selector('compact');
})
$("#displayLine").change(function () {
setDisplayLine();
set_view_selector('line');
})
/* Plugin Filters */
// Set filter on Active on load
if (nb_plugin.active > 0) {
$(".pluginMiniBox").each(function () {
if (!$(this).hasClass("plugin-active")) {
$(this).hide();
}
});
$("#seeActive").trigger("click");
} else {
$(".pluginMiniBox").show();
}
$("#seeAll").on("change", function () {
$(".pluginBox").show();
$('.search-input').trigger("input");
})
$("#seeActive").on("change", function () {
$(".pluginBox").show();
$(".pluginBox").each(function () {
if (!$(this).hasClass("plugin-active")) {
$(this).hide();
}
})
$('.search-input').trigger("input");
})
$("#seeInactive").on("change", function () {
$(".pluginBox").show();
$(".pluginBox").each(function () {
if (!$(this).hasClass("plugin-inactive")) {
$(this).hide();
}
})
$('.search-input').trigger("input");
})
$("#seeOther").on("change", function () {
$(".pluginBox").show();
$(".pluginBox").each(function () {
if (($(this).hasClass("plugin-active") || $(this).hasClass("plugin-inactive"))) {
$(this).hide();
}
})
$('.search-input').trigger("input");
})
/* Plugin Actions */
/**
* Activate / Deactivate
*/
if (isWebmaster != 0) {
$(".switch").change(function () {
$(".pluginMiniBox").addClass("usable");
if ($(this).find("#toggleSelectionMode").is(':checked')) {
activatePlugin($(this).parent().parent().attr("id"));
$(this).parent().parent().addClass("plugin-active").removeClass("plugin-inactive");
if ($(this).parent().parent().find(".pluginUnavailableAction").attr("href")) {
$(this).parent().parent().find(".pluginUnavailableAction").removeClass("pluginUnavailableAction").addClass("pluginActionLevel1");
}
} else {
disactivatePlugin($(this).parent().parent().attr("id"))
$(this).parent().parent().removeClass("plugin-active").addClass("plugin-inactive");
$(this).parent().parent().find(".pluginActionLevel1").removeClass("pluginActionLevel1").addClass("pluginUnavailableAction");
}
actualizeFilter();
})
} else {
$(".pluginMiniBox").addClass("notUsable");
$(".plugin-active").find(".slider").addClass("desactivate_disabled");
$(".plugin-inactive").find(".slider").addClass("activate_disabled");
$(".switch input").on("click", function (event) {
$(this).addClass("disabled");
event.preventDefault();
event.stopPropagation();
var id = $(this).parent().parent().parent().attr("id");
$("#" + id + " .pluginNotif").stop(false, true);
$("#" + id + " .PluginActionError label span:first").html(not_webmaster);
$("#" + id + " .PluginActionError").css("display", "flex");
$("#" + id + " .PluginActionError").delay(1500).fadeOut(2500);
setTimeout(function(){
$(".switch input").removeClass("disabled");
}, 400); //Same duration as the animation "desactivate_disabled" in css
});
}
/**
* Delete
*/
$(".pluginContent").find('.dropdown-option.delete-plugin-button').on('click', function () {
let plugin_name = $(this).closest(".pluginContent").find(".pluginName").html().trim();
let plugin_id = $(this).closest(".pluginContent").parent().attr("id");
$.confirm({
title: delete_plugin_msg.replace("%s",plugin_name),
buttons: {
confirm: {
text: confirm_msg,
btnClass: 'btn-red',
action: function () {
deletePlugin(plugin_id, plugin_name);
},
},
cancel: {
text: cancel_msg
}
},
...jConfirm_confirm_options
})
})
/**
* Restore
*/
$(".pluginContent").find('.dropdown-option.plugin-restore').on('click', function () {
let plugin_name = $(this).closest(".pluginContent").find(".pluginName").html().trim();
let plugin_id = $(this).closest(".pluginContent").parent().attr("id");
$.confirm({
title: restore_plugin_msg.replace('%s', plugin_name),
content: str_restore_def,
buttons: {
confirm: {
text: confirm_msg,
btnClass: 'btn-red',
action: function () {
restorePlugin(plugin_id);
},
},
cancel: {
text: cancel_msg
}
},
...jConfirm_confirm_options
})
})
/**
* Uninstall
*/
$(".pluginContent").find('.uninstall-plugin-button').on('click', function () {
let plugin_name = $(this).closest(".pluginContent").find(".pluginName").html().trim();
let plugin_id = $(this).closest(".pluginContent").parent().attr("id");
$.confirm({
title: uninstall_plugin_msg.replace('%s', plugin_name),
buttons: {
confirm: {
text: confirm_msg,
btnClass: 'btn-red',
action: function () {
uninstallPlugin(plugin_id);
},
},
cancel: {
text: cancel_msg
}
},
...jConfirm_confirm_options
})
})
})
function set_view_selector(view_type) {
$.ajax({
url: "ws.php?format=json&method=pwg.users.preferences.set",
type: "POST",
dataType: "JSON",
data: {
param: 'plugin-manager-view',
value: view_type,
}
})
}
// TPL part :
const queuedManager = jQuery.manageAjax.create("queued", {
queue: true,
maxRequests: 1,
});
const nb_plugins = jQuery("div.active").size();
const done = 0;
function showInactivePlugins () {
jQuery(".showInactivePlugins").fadeOut(
(complete = function () {
jQuery(".plugin-inactive").fadeIn();
})
);
};
function actualizeFilter() {
$("label[for='seeAll'] .filter-badge").html(nb_plugin.all);
$("label[for='seeActive'] .filter-badge").html(nb_plugin.active);
$("label[for='seeInactive'] .filter-badge").html(nb_plugin.inactive);
$("label[for='seeOther'] .filter-badge").html(nb_plugin.other);
$(".filterLabel").show();
$(".pluginMiniBox").each(function () {
if (nb_plugin.active == 0) {
$("label[for='seeActive']").hide();
if ($("#seeActive").is(":checked")) {
$("#seeAll").trigger("click");
}
}
if (nb_plugin.inactive == 0) {
$("label[for='seeInactive']").hide();
if ($("#seeInactive").is(":checked")) {
$("#seeAll").trigger("click");
}
}
if (nb_plugin.other == 0) {
$("label[for='seeOther']").hide();
if ($("#seeOther").is(":checked")) {
$("#seeAll").trigger("click");
}
}
});
}
function performPluginDeactivate(id) {
queuedManager.add({
type: "GET",
dataType: "json",
url: "ws.php",
data: {
method: "pwg.plugins.performAction",
action: "deactivate",
plugin: id,
pwg_token: pwg_token,
format: "json",
},
success: function (data) {
if (data["stat"] == "ok")
jQuery("#" + id)
.removeClass("active")
.addClass("inactive");
done++;
if (done == nb_plugins) location.reload();
},
});
}
/* group action */
jQuery(document).ready(function () {
$("label[for='seeActive'] .filter-badge").html(nb_plugin.active);
$("label[for='seeInactive'] .filter-badge").html(nb_plugin.inactive);
$("label[for='seeOther'] .filter-badge").html(nb_plugin.other);
$(".filterLabel").show();
$(".pluginBox").each(function () {
if (nb_plugin.active == 0) {
$("label[for='seeActive']").hide();
if ($("#seeActive").is(":checked")) {
$("#seeAll").trigger("click");
}
}
if (nb_plugin.inactive == 0) {
$("label[for='seeInactive']").hide();
if ($("#seeInactive").is(":checked")) {
$("#seeAll").trigger("click");
}
}
if (nb_plugin.other == 0) {
$("label[for='seeOther']").hide();
if ($("#seeOther").is(":checked")) {
$("#seeAll").trigger("click");
}
}
let myplugin = jQuery(this);
myplugin.find(".showOptions").click(function () {
myplugin.find(".PluginOptionsBlock").toggle();
});
});
jQuery("div.deactivate_all a").click(function () {
$.confirm({
title: deactivate_all_msg,
buttons: {
confirm: {
text: confirm_msg,
btnClass: "btn-red",
action: function () {
jQuery("div.active").each(function () {
performPluginDeactivate(jQuery(this).attr("id"));
});
},
},
cancel: {
text: cancel_msg,
},
},
...jConfirm_confirm_options,
});
});
/* incompatible plugins */
jQuery.ajax({
method: "GET",
url: "admin.php",
data: { page: "plugins_installed", incompatible_plugins: true },
dataType: "json",
success: function (data) {
for (i = 0; i < data.length; i++) {
if (show_details)
jQuery("#" + data[i] + " .pluginName").prepend(
'<a class="warning" title="' + incompatible_msg + '"></a>'
);
else
jQuery("#" + data[i] + " .pluginName").prepend(
'<span class="warning" title="' + incompatible_msg + '"></span>'
);
jQuery("#" + data[i]).addClass("incompatible");
jQuery("#" + data[i] + " .activate").each(function () {
$(this).pwg_jconfirm_follow_href({
alert_title: incompatible_msg + activate_msg,
alert_confirm: confirm_msg,
alert_cancel: cancel_msg,
});
});
}
jQuery(".warning").tipTip({
delay: 0,
fadeIn: 200,
fadeOut: 200,
maxWidth: "250px",
});
},
});
jQuery(".fullInfo").tipTip({
delay: 500,
fadeIn: 200,
fadeOut: 200,
maxWidth: "300px",
keepAlive: false,
});
/*Add the filter research*/
document.onkeydown = function (e) {
if (e.keyCode == 58) {
jQuery(".pluginFilter input.search-input").focus();
return false;
}
};
jQuery(".pluginFilter input").on("input", function () {
let text = jQuery(this).val().toLowerCase();
var searchNumber = 0;
var searchActive = 0;
var searchInactive = 0;
var searchOther = 0;
$(".pluginBox").each(function () {
if (text == "") {
jQuery(".nbPluginsSearch").hide();
if ($("#seeAll").is(":checked")) {
jQuery(this).show();
}
if (
$("#seeActive").is(":checked") &&
jQuery(this).hasClass("plugin-active")
) {
jQuery(this).show();
}
if (
$("#seeInactive").is(":checked") &&
jQuery(this).hasClass("plugin-inactive")
) {
jQuery(this).show();
}
if (
$("#seeOther").is(":checked") &&
(jQuery(this).hasClass("plugin-merged") ||
jQuery(this).hasClass("plugin-missing"))
) {
jQuery(this).show();
}
if ($(this).hasClass("plugin-active")) {
searchActive++;
}
if ($(this).hasClass("plugin-inactive")) {
searchInactive++;
}
if (
$(this).hasClass("plugin-merged") ||
$(this).hasClass("plugin-missing")
) {
searchOther++;
}
searchNumber++;
nb_plugin.all = searchNumber;
nb_plugin.active = searchActive;
nb_plugin.inactive = searchInactive;
nb_plugin.other = searchOther;
} else {
let name = jQuery(this).find(".pluginName").text().toLowerCase();
jQuery(".nbPluginsSearch").show();
let description = jQuery(this).find(".pluginDesc").text().toLowerCase();
if (name.search(text) != -1 || description.search(text) != -1) {
searchNumber++;
if ($("#seeAll").is(":checked")) {
jQuery(this).show();
}
if (
$("#seeActive").is(":checked") &&
jQuery(this).hasClass("plugin-active")
) {
jQuery(this).show();
}
if (
$("#seeInactive").is(":checked") &&
jQuery(this).hasClass("plugin-inactive")
) {
jQuery(this).show();
}
if (
$("#seeOther").is(":checked") &&
(jQuery(this).hasClass("plugin-merged") ||
jQuery(this).hasClass("plugin-missing"))
) {
jQuery(this).show();
}
if ($(this).hasClass("plugin-active")) {
searchActive++;
}
if ($(this).hasClass("plugin-inactive")) {
searchInactive++;
}
if (
$(this).hasClass("plugin-merged") ||
$(this).hasClass("plugin-missing")
) {
searchOther++;
}
nb_plugin.all = searchNumber;
nb_plugin.active = searchActive;
nb_plugin.inactive = searchInactive;
nb_plugin.other = searchOther;
} else {
jQuery(this).hide();
nb_plugin.all = searchNumber;
nb_plugin.active = searchActive;
nb_plugin.inactive = searchInactive;
nb_plugin.other = searchOther;
}
}
});
actualizeFilter();
if (searchNumber == 0) {
jQuery(".nbPluginsSearch").html(nothing_found);
} else if (searchNumber == 1) {
jQuery(".nbPluginsSearch").html(plugin_found.replace("%s", searchNumber));
} else {
jQuery(".nbPluginsSearch").html(
x_plugins_found.replace("%s", searchNumber)
);
}
});
/* Show Inactive plugins or button to show them*/
jQuery(".showInactivePlugins button").on("click", showInactivePlugins);
if (plugin_filter == "deactivated") {
jQuery(".filterLabel[for='seeInactive']").trigger("click");
}
});
$(document).mouseup(function (e) {
e.stopPropagation();
$(".pluginBox").each(function () {
if ($(this).find(".showOptions").has(e.target).length === 0) {
$(this).find(".PluginOptionsBlock").hide();
}
});
});
@@ -0,0 +1,317 @@
// <-- Define sort orders -->
var sortOrder = 'date';
var sortPlugins = (function (a, b) {
if (sortOrder == 'downloads' || sortOrder == 'revision' || sortOrder == 'date')
return parseInt($(a).data(sortOrder))
< parseInt($(b).data(sortOrder)) ? 1 : -1;
else
return $(a).data(sortOrder).toLowerCase()
> $(b).data(sortOrder).toLowerCase() ? 1 : -1;
});
$(function () {
// <-- Set the advanced filters -->
let betaTestPlugins = $('#showBetaTestPlugin')[0].hasAttribute('checked');
// object that remember filters states (initialized later)
let filters = {};
// toggle advanced filter's panel
$(".advanced-filter-btn").click(advanced_filter_button_click);
$(".advanced-filter span.icon-cancel").click(advanced_filter_hide);
function advanced_filter_button_click() {
if (!$(".advanced-filter").hasClass("advanced-filter-open")) {
advanced_filter_show();
} else {
advanced_filter_hide();
}
}
function advanced_filter_show() {
$(".advanced-filter-btn, .advanced-filter").addClass("advanced-filter-open");
}
function advanced_filter_hide() {
$(".advanced-filter-btn, .advanced-filter").removeClass("advanced-filter-open");
}
jQuery('select[name="selectOrder"]').change(function () {
sortOrder = this.value;
$('.pluginBox').sortElements(sortPlugins);
$.get("admin.php?plugins_new_order=" + sortOrder);
});
jQuery('#search').on("input", function () {
applyFilter('search', this.value.toUpperCase());
jQuery("#search").trigger("click");
});
$('.search-cancel').on('click', () => {
applyFilter('search', '');
})
$(".buttonInstall").each(function () {
let plugin_name = $(this).closest(".pluginBox").data('name');
$(this).pwg_jconfirm_follow_href({
alert_title: str_install_title.replace("%s", plugin_name),
alert_confirm: str_confirm_msg,
alert_cancel: str_cancel_msg
});
});
jQuery('.certification').tipTip({
'delay': 0,
'fadeIn': 200,
'fadeOut': 200
});
$('.pluginRating').each((i, node) => {
let ratingContainer = $(node);
let rating = ratingContainer.data('rating');
displayStars(ratingContainer.find('.rating-star-container'), rating);
})
// put default values in the select
let authorNames = [{ value: '', text: "-" }];
let tagsNames = [{ value: '', text: "-" }]
// read all plugin boxes to get author and tags
$('.pluginBox').each((i,el) => {
let author = $(el).data('author');
author.split(', ').forEach(name => {
if (!authorNames.find(el => el.value == name)) {
authorNames.push({ value: name, text: name})
}
});
let tags = $(el).data('tags');
tags.split(', ').forEach(tag => {
if (!tagsNames.find(el => el.value == tag)) {
tagsNames.push({ value: tag, text: tag })
}
});
})
// initialize the Selectize control
$select = $('#author-filter').selectize({
onChange: function (value) {
applyFilter('author', value);
},
plugins: ['remove_button'],
});
// fetch the instance
let selectizeAuthor = $select[0].selectize;
selectizeAuthor.addOption(authorNames);
// initialize the Selectize control
$select = $('#tag-filter').selectize({
onChange: function (value) {
applyFilter('tag', value);
},
plugins: ['remove_button'],
});
// fetch the instance
let selectizeTag = $select[0].selectize;
selectizeTag.addOption(tagsNames);
$('.notation-filter-slider').slider({
range: 'min',
value: 0,
min: 0,
max: 5,
step: 0.5,
slide: function(event, ui) {
updateRatingFilterLabel(ui.value);
applyFilter("rating", ui.value);
}
})
$('.revision-date-filter-slider').slider({
range: 'min',
value: 0,
min: 0,
max: 6,
slide: function (event, ui) {
let month;
[month, _] = value_to_month(ui.value);
updateRevisionFilterLabel(ui.value);
applyFilter("revision", month);
}
});
// All the slider values and it's corresponding month's number and label
function value_to_month(val) {
switch (val) {
case 6:
return [1, str_x_month.replace('%d', 1)];
break;
case 5:
return [3, str_x_months.replace('%d', 3)];
break;
case 4:
return [6, str_x_months.replace('%d', 6)];
break;
case 3:
return [12, str_x_year.replace('%d', 1)];
break;
case 2:
return [24, str_x_years.replace('%d', 2)];
break;
case 1:
return [60, str_x_years.replace('%d', 5)];
break;
default:
return [Number.MAX_SAFE_INTEGER, str_from_begining];
break;
}
}
// The certification filter dosen't include incompatible if the beta-test option is not checked
let minCertification = betaTestPlugins ? -1 : 0;
$('.certification-filter-slider').slider({
range: 'min',
value: minCertification,
min: minCertification,
max: 3,
slide: function (event, ui) {
updateCertificationFilterLabel(ui.value);
applyFilter("certification", ui.value);
}
});
// Diffrence between two dates, in months
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth();
months += d2.getMonth();
return months <= 0 ? 0 : months;
}
updateRatingFilterLabel(0);
updateCertificationFilterLabel(minCertification);
updateRevisionFilterLabel(0);
function displayStars(element, rating) {
element.find('span').addClass('icon-star-empty');
element.find('span i').attr('class','');
rating = Math.round(rating * 2);
if (rating % 2 == 1) {
$(element).find('span[data-star=' + ((rating - 1) / 2) + '] i').addClass('icon-star-half')
rating -= 1;
}
while (rating > 0) {
rating -= 2;
$(element).find('span[data-star=' + (rating / 2) + '] i').addClass('icon-star')
$(element).find('span[data-star=' + (rating / 2) + ']').removeClass('icon-star-empty')
}
}
// Updates labels when input change
function updateRatingFilterLabel(value) {
displayStars($('.advanced-filter-rating .rating-star-container'), value);
}
function updateCertificationFilterLabel(value) {
let certifNode = $('.advanced-filter-certification .certification');
certifNode.attr('data-certification', value);
certifNode.attr('title', strs_certification[String(value)]);
certifNode.tipTip({
'delay': 0,
'fadeIn': 200,
'fadeOut': 200
});
}
function updateRevisionFilterLabel(val) {
let label;
[_, label] = value_to_month(val);
$('.revision-date').html(label);
}
// <-- Apply advanced filters -->
// object that remember filters states
filters = {
"search": $('#search').val(),
"author": '',
"tag": '',
"rating": $('.notation-filter-slider').slider('value'),
"certification": $('.certification-filter-slider').slider('value'),
"revision": value_to_month($('.certification-filter-slider').slider('value'))[0],
}
selectizeAuthor.setValue('');
selectizeTag.setValue('');
function applyFilter(changed, value) {
filters[changed] = value;
sort((pluginBox) => {
let pluginRating = pluginBox.find('.pluginRating').data('rating') || 0;
let pluginCertification = pluginBox.find('.certification').data('certification');
let pluginAuthors = pluginBox.data('author').split(', ');
let pluginName = pluginBox.data('name').toUpperCase();
let pluginTags = pluginBox.data('tags').split(', ');
let pluginRevisionOld = monthDiff(new Date(pluginBox.data('revision')*1000), new Date()); // number of months between the last revision date and now
return (pluginRating >= filters.rating)
&& (pluginCertification >= filters.certification)
&& (filters.search === '' || pluginName.indexOf(filters.search) != -1)
&& (filters.author === '' || pluginAuthors.includes(filters.author))
&& (filters.tag === '' || pluginTags.includes(filters.tag))
&& pluginRevisionOld <= filters['revision'];
})
}
// Display or not plugin with a function handler
function sort(sortFunction) {
$('.pluginBox').each((i, el) => {
if (sortFunction($(el))) {
$(el).show();
} else {
$(el).hide();
}
})
}
function clearSort() {
$('.pluginBox').show();
}
// Crop the names of plugins if there are too long
$('.pluginName span').each((i,el) => {
let name = $(el)
if (name.html().length > 30) {
name.html(name.html().slice(0,30) + '...');
}
})
$('#showBetaTestPlugin').on('change', (e) => {
$('.beta-test-plugin-switch .slider').addClass('loading');
let queryParams = new URLSearchParams(window.location.search);
queryParams.set("beta-test", e.currentTarget.checked.toString());
history.replaceState(null, null, "?" + queryParams.toString());
window.location.reload(true);
})
});
@@ -0,0 +1,259 @@
/*-------
Data Get
-------*/
data = {};
data["hours"] = $("#data").data("hours");
data["days"] = $("#data").data("days");
data["months"] = $("#data").data("months");
data["years"] = $("#data").data("years");
data["compare-years"] = $("#data").data("compare-years");
data["month-stats"] = $("#data").data("month-stats");
data_unit = {
"hours":"day",
"days":"month",
"months": "year",
"years": "year"
}
compareMode = false;
/*-------
Creating graph
-------*/
var ctx = document.getElementById('stat-graph').getContext('2d');
//Create the gradient under the curve
function gradient(r, g, b) {
let gradient = ctx.createLinearGradient(0,400, 0,0);
gradient.addColorStop(0, 'rgba('+r+','+g+','+b+',0)');
gradient.addColorStop(1, 'rgba('+r+','+g+','+b+',1)');
return gradient;
}
//Setup the graph
Chart.defaults.global.elements.point.radius = 0.1;
Chart.defaults.global.elements.point.hitRadius = 10
Chart.defaults.global.defaultFontSize = 14;
Chart.defaults.global.defaultFontColor = '#888';
Chart.defaults.global.tooltips.intersect = false;
Chart.defaults.global.legend.onClick = null;
var statGraph = new Chart(ctx, {
type: 'line',
maintainAspectRatio: false,
});
//Line options
var displayOptions = {
backgroundColor: gradient(255, 119, 0),
borderColor: '#FFA646 ',
lineTension : 0.2
}
function changeData(dataType, options = displayOptions) {
if (!compareMode) {
statGraph.data = {
datasets: [{
label: str_number_page_visited,
data: getValues(data[dataType]),
...options
}]
}
statGraph.options = {
scales: {
xAxes: [{
type: 'time',
time: {
tooltipFormat: 'll'
},
gridLines: {
display: false
}
}],
yAxes: [{
ticks: {
min: 0
}
}]
},
legend: {
display:false
},
tooltips: {
mode: 'index'
},
hover :
{
intersect : false,
}
}
statGraph.options.scales.xAxes.forEach(axe => {
axe.time.tooltipFormat = str_tooltip_format[dataType];
axe.time.unit = data_unit[dataType];
axe.time.displayFormats = str_unit_format;
})
statGraph.update();
} else {
statGraph.options.legend.display = true;
statGraph.options.hover = {
intersect : true
}
statGraph.options.tooltips = {
mode : 'nearest'
}
if (dataType == "years") {
statGraph.data = {
datasets: getComparedYearDataset()
}
statGraph.options.scales = {
xAxes: [{
type: 'category',
labels: str_months,
gridLines: {
display: false
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: str_number_page_visited
},
tick: {
min: 0
}
}]
}
} else if (dataType == "months") {
days = [];
for (let i = 1; i<=31; i++) {
days.push(i);
}
statGraph.data = {
datasets: getMonthStatsDataset()
}
statGraph.options.scales = {
xAxes: [{
type: 'category',
labels : days,
gridLines: {
display: false
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: str_number_page_visited
}
}]
}
}
statGraph.update();
}
}
//Make Data readable by Chart.js
function getValues(data) {
values = [];
Object.keys(data).forEach(function(key) {
var newPoint = {
x:new Date(key),
y:data[key]
}
values.push(newPoint)
});
return values;
}
function getComparedYearDataset() {
colors = ["#ffa744", "#ff5252", "#896af3", "#2883c3", "#6ece5e"]
values = {};
dataset = [];
Object.keys(data["compare-years"]).forEach(function(key) {
date = new Date(key)
if (values[date.getFullYear()] == undefined) {
values[date.getFullYear()] = [];
}
values[date.getFullYear()][parseInt(date.getMonth())] = data["compare-years"][key];
});
Object.keys(values).forEach(function(key) {
dataset.push({
label : key,
data : values[key],
lineTension : 0.2,
borderColor : colors[parseInt(key) % colors.length],
backgroundColor: "rgba(0,0,0,0)"
})
});
return dataset;
}
function getMonthStatsDataset() {
colors = ["#ffa744", "#ff5252", "#896af3", "#2883c3", "#6ece5e"]
dataset = [];
colorIndice = 0;
let date;
data["month-stats"]["month"].forEach(values => {
let days_data = [];
Object.keys(values).forEach(function(key) {
date = new Date(key)
days_data[parseInt(date.getUTCDate()) - 1] = values[key];
});
dataset.push({
label : str_months[date.getMonth()]+" "+date.getFullYear(),
data : days_data,
lineTension : 0.2,
borderColor : colors[colorIndice % colors.length],
backgroundColor: "rgba(0,0,0,0)"
})
colorIndice++
});
averageTab = [];
for (let i = 0; i < 31; i++) {
averageTab[i] = data["month-stats"]["avg"];
}
dataset.push({
label : str_avg,
data : averageTab,
lineTension : 0.2,
borderColor : colors[4],
backgroundColor: "rgba(0,0,0,0)"
})
return dataset;
}
//Event listener
$(".stat-data-selector label").on("click", function(){
dataType = $(this).data("value");
changeData(dataType);
})
$(".stat-compare-mode input").on("change", function(){
compareMode = $(this)[0].checked;
if (compareMode) {
$("#hours-selector + label, #days-selector + label").addClass('unavailable');
if ($("#hours-selector").prop('checked')||$("#days-selector").prop('checked')) {
$("#years-selector").prop('checked', true);
$("#hours-selector, #days-selector").prop('checked', false);
changeData("years");
} else {
changeData($(".stat-data-selector input:checked + label").data("value"))
}
} else {
$("#hours-selector + label, #days-selector + label").removeClass('unavailable');
changeData($(".stat-data-selector input:checked + label").data("value"));
}
})
/*-------
Initialize the page
-------*/
$(function() {
changeData($(".stat-data-selector input:checked + label").data("value"));
})
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,723 @@
//{*<-- Getting and Displaying Activities -->*}
if (additional_filt_type)
{
object_filter = additional_filt_type;
}
get_user_activity(activity_page, uid_filter, action_filter, object_filter, [date_min_filter, date_max_filter], additional_filt_value);
function get_user_activity(page, uid, action, object, date, id) {
$.ajax({
url: "ws.php?format=json&method=pwg.activity.getList",
type: "POST",
dataType: "json",
data: {
page: page - 1,
uid: uid,
action : action,
object : object,
offset : page_offsets[page - 1],
date_min : date[0],
date_max : date[1],
id : additional_filt_value
},
beforeSend: () => {
$('.tab').contents(':not(#-1):not(.loading)').remove();
$(".loading").show();
$('.pagination-arrow.rigth').addClass('unavailable');
$('.pagination-arrow.left').addClass('unavailable');
$(".pagination-item-container").hide();
$(".user-update-spinner").addClass("icon-spin6");
},
success: (data) => {
/* console log to help debug
{* console.log(data); *}*/
uid_filter = uid;
action_filter = action;
object_filter = object;
date_min_filter = date[0];
date_max_filter = date[1];
//setCreationDate(data.result['result_lines'][data.result['result_lines'].length-1].date, data.result['result_lines'][0].date);
$(".loading").hide();
if (data.result['result_lines'].length > 0)
{
data.result['result_lines'].forEach(line => {
lineConstructor(line);
});
}
else
{
emptyLine();
}
current_page_offset = page_offsets[page - 1];
end_page = data.result['end_page'];
if (!(page_offsets.includes(data.result['page_offset'])))
{
page_offsets.push(data.result['page_offset']);
}
$(".user-update-spinner").removeClass("icon-spin6");
$(".pagination-item-container").show();
update_pagination_menu();
},
error: (e) => {
console.log("ajax call failed");
console.log(e);
}
})
}
function lineConstructor(line) {
let newLine = $("#-1").clone();
$(".tab-title").show();
$(".activity-noresult").hide();
newLine.removeClass("hide");
/* console log to help debug
{* console.log(line); *}*/
newLine.attr("id", line.id);
var final_albumInfos;
//{* Determines wich string need to be placed in the line constructed *}
if (line.counter > 1) {
// pluriel
switch (line.action) {
case "edit":
newLine.find(".action-type").addClass("icon-blue");
newLine.find(".user-pic").addClass(color_icons[line.user_id % 5]);
newLine.find(".action-icon").addClass("icon-pencil");
newLine.find(".action-name").html(actionType_edit);
switch (line.object) {
case "user":
final_albumInfos = actionInfos_users_edited.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-user-1");
break;
case "album":
final_albumInfos = actionInfos_albums_edited.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-folder-open");
break;
case "group":
final_albumInfos = actionInfos_groups_edited.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-users-1");
break;
case "photo":
final_albumInfos = actionInfos_photos_edited.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-picture");
break;
case "tag":
final_albumInfos = actionInfos_tags_edited.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-tags");
break;
default:
final_albumInfos = line.counter + " " +line.object + " " + line.action;
break;
}
break;
case "add":
newLine.find(".action-type").addClass("icon-green");
newLine.find(".user-pic").addClass(color_icons[line.user_id % 5]);
newLine.find(".action-icon").addClass("icon-plus");
newLine.find(".action-name").html(actionType_add);
switch (line.object) {
case "user":
final_albumInfos = actionInfos_users_added.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-user-1");
break;
case "album":
final_albumInfos = actionInfos_albums_added.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-folder-open");
break;
case "group":
final_albumInfos = actionInfos_groups_added.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-users-1");
break;
case "photo":
final_albumInfos = actionInfos_photos_added.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-picture");
break;
case "tag":
final_albumInfos = actionInfos_tags_added.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-tags");
break;
default:
final_albumInfos = line.counter + " " +line.object + " " + line.action;
break;
}
break;
case "delete":
newLine.find(".action-type").addClass("icon-red");
newLine.find(".user-pic").addClass(color_icons[line.user_id % 5]);
newLine.find(".action-icon").addClass("icon-trash-1");
newLine.find(".action-name").html(actionType_delete);
switch (line.object) {
case "user":
final_albumInfos = actionInfos_users_deleted.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-user-1");
break;
case "album":
final_albumInfos = actionInfos_albums_deleted.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-folder-open");
break;
case "group":
final_albumInfos = actionInfos_groups_deleted.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-users-1");
break;
case "photo":
final_albumInfos = actionInfos_photos_deleted.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-picture");
break;
case "tag":
final_albumInfos = actionInfos_tags_deleted.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-tags");
break;
default:
final_albumInfos = line.counter + " " +line.object + " " + line.action;
break;
}
break;
case "move":
newLine.find(".action-type").addClass("icon-yellow");
newLine.find(".user-pic").addClass(color_icons[line.user_id % 5]);
newLine.find(".action-icon").addClass("icon-move");
newLine.find(".action-name").html(actionType_move);
switch (line.object) {
case "album":
final_albumInfos = actionInfos_albums_moved.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-folder-open");
break;
case "group":
final_albumInfos = actionInfos_groups_moved.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-users-1");
break;
case "photo":
final_albumInfos = actionInfos_photos_moved.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-picture");
break;
case "tag":
final_albumInfos = actionInfos_tags_moved.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-tags");
break;
default:
final_albumInfos = line.counter + " " +line.object + " " + line.action;
break;
}
break;
case "login":
newLine.find(".action-type").addClass("icon-purple");
newLine.find(".user-pic").addClass(color_icons[line.user_id % 5]);
newLine.find(".action-icon").addClass("icon-key");
newLine.find(".action-section").addClass("icon-user-1");
newLine.find(".action-name").html(actionType_login);
final_albumInfos = actionInfos_users_logged_in.replace('%d', line.counter);
break;
case "logout":
newLine.find(".action-type").addClass("icon-purple");
if (line.user_id != 2) {
newLine.find(".user-pic").addClass(color_icons[line.user_id % 5]);
} else {
newLine.find(".user-pic").addClass(color_icons[line.object_id[0] % 5]);
}
newLine.find(".action-icon").addClass("icon-logout");
newLine.find(".action-section").addClass("icon-user-1");
newLine.find(".action-name").html(actionType_logout);
final_albumInfos = actionInfos_users_logged_out.replace('%d', line.counter);
break;
default:
newLine.find(".action-type").addClass("icon-purple");
newLine.find(".user-pic").addClass(color_icons[line.user_id % 5]);
newLine.find(".action-section").addClass("icon-user-1");
newLine.find(".action-name").html(line.action);
final_albumInfos = 'x' + line.counter;
break;
}
} else {
// singulier
switch (line.action) {
case "edit":
newLine.find(".action-type").addClass("icon-blue");
newLine.find(".user-pic").addClass(color_icons[line.user_id % 5]);
newLine.find(".action-icon").addClass("icon-pencil");
newLine.find(".action-name").html(actionType_edit);
switch (line.object) {
case "user":
final_albumInfos = actionInfos_user_edited.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-user-1");
break;
case "album":
final_albumInfos = actionInfos_album_edited.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-folder-open");
break;
case "group":
final_albumInfos = actionInfos_group_edited.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-users-1");
break;
case "photo":
final_albumInfos = actionInfos_photo_edited.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-picture");
break;
case "tag":
final_albumInfos = actionInfos_tag_edited.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-tags");
break;
default:
final_albumInfos = line.counter + " " +line.object + " " + line.action;
break;
}
break;
case "add":
newLine.find(".action-type").addClass("icon-green");
newLine.find(".user-pic").addClass(color_icons[line.user_id % 5]);
newLine.find(".action-icon").addClass("icon-plus");
newLine.find(".action-name").html(actionType_add);
switch (line.object) {
case "user":
final_albumInfos = actionInfos_user_added.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-user-1");
break;
case "album":
final_albumInfos = actionInfos_album_added.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-folder-open");
break;
case "group":
final_albumInfos = actionInfos_group_added.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-users-1");
break;
case "photo":
final_albumInfos = actionInfos_photo_added.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-picture");
break;
case "tag":
final_albumInfos = actionInfos_tag_added.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-tags");
break;
default:
final_albumInfos = line.counter + " " +line.object + " " + line.action;
break;
}
break;
case "delete":
newLine.find(".action-type").addClass("icon-red");
newLine.find(".user-pic").addClass(color_icons[line.user_id % 5]);
newLine.find(".action-icon").addClass("icon-trash-1");
newLine.find(".action-name").html(actionType_delete);
switch (line.object) {
case "user":
final_albumInfos = actionInfos_user_deleted.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-user-1");
break;
case "album":
final_albumInfos = actionInfos_album_deleted.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-folder-open");
break;
case "group":
final_albumInfos = actionInfos_group_deleted.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-users-1");
break;
case "photo":
final_albumInfos = actionInfos_photo_deleted.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-picture");
break;
case "tag":
final_albumInfos = actionInfos_tag_deleted.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-tags");
break;
default:
final_albumInfos = line.counter + " " +line.object + " " + line.action;
break;
}
break;
case "move":
newLine.find(".action-type").addClass("icon-yellow");
newLine.find(".user-pic").addClass(color_icons[line.user_id % 5]);
newLine.find(".action-icon").addClass("icon-move");
newLine.find(".action-name").html(actionType_move);
switch (line.object) {
case "album":
final_albumInfos = actionInfos_album_moved.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-folder-open");
break;
case "group":
final_albumInfos = actionInfos_group_moved.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-users-1");
break;
case "photo":
final_albumInfos = actionInfos_photo_moved.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-picture");
break;
case "tag":
final_albumInfos = actionInfos_tag_moved.replace('%d', line.counter);
newLine.find(".action-section").addClass("icon-tags");
break;
default:
final_albumInfos = line.counter + " " +line.object + " " + line.action;
break;
}
break;
case "login":
newLine.find(".action-type").addClass("icon-purple");
newLine.find(".user-pic").addClass(color_icons[line.user_id % 5]);
newLine.find(".action-icon").addClass("icon-key");
newLine.find(".action-section").addClass("icon-user-1");
newLine.find(".action-name").html(actionType_login);
final_albumInfos = actionInfos_user_logged_in.replace('%d', line.counter);
break;
case "logout":
newLine.find(".action-type").addClass("icon-purple");
if (line.user_id != 2) {
newLine.find(".user-pic").addClass(color_icons[line.user_id % 5]);
} else {
newLine.find(".user-pic").addClass(color_icons[line.object_id[0] % 5]);
}
newLine.find(".action-icon").addClass("icon-logout");
newLine.find(".action-section").addClass("icon-user-1");
newLine.find(".action-name").html(actionType_logout);
final_albumInfos = actionInfos_user_logged_out.replace('%d', line.counter);
break;
default:
newLine.find(".action-type").addClass("icon-purple");
newLine.find(".user-pic").addClass(color_icons[line.user_id % 5]);
newLine.find(".action-section").addClass("icon-user-1");
newLine.find(".action-name").html(line.action);
final_albumInfos = 'x' + line.counter;
break;
}
}
newLine.find(".action-infos-test").html(final_albumInfos);
/* Action_section */
newLine.find(".nb_items").html(line.counter);
/* Date_section */
newLine.find(".date-day").html(line.date);
newLine.find(".date-hour").html(line.hour);
/* User _Section */
newLine.find(".user-name").html(line.username);
newLine.find(".user-pic").html(get_initials(line.username));
/* Detail_section */
newLine.find(".detail-item-1").html(line.ip_address);
newLine.find(".detail-item-1").attr("title", "IP: " + line.ip_address);
if (line.detailsType == "script") {
newLine.find(".detail-item-2").html(line.details.script);
newLine.find(".detail-item-2").attr('title', 'Script');
} else if (line.detailsType == "method") {
newLine.find(".detail-item-2").html(line.details.method);
newLine.find(".detail-item-2").attr('title', 'API Method');
}
if (line.details.agent) {
const api_key = line.details.connected_with ? 'API Key, ' : '';
const details = line.details.connected_with ? '<i class="icon-key"></i>' + line.details.agent : line.details.agent;
newLine.find(".detail-item-3").html(details);
newLine.find(".detail-item-3").attr('title', api_key + 'User-Agent: ' + line.details.agent);
} else if (line.details.users && line.action != "logout" && line.action != "login") {
const user_string = [...new Set(line.details.users)].toString();
newLine.find(".detail-item-3").html(user_string);
newLine.find(".detail-item-3").attr('title', users_key + ": " + user_string);
} else {
newLine.find(".detail-item-3").remove();
}
newLine.addClass("uid-" + line.user_id);
displayLine(newLine);
}
function displayLine(line) {
$(".tab").append(line);
}
function emptyLine() {
$(".tab-title").hide();
$(".activity-noresult").show();
}
function get_initials(username) {
let words = username.toUpperCase().split(" ");
let res = words[0][0];
if (words.length > 1 && words[1][0] !== undefined ) {
res += words[1][0];
}
return res;
}
function setCreationDate(startDate, endDate) {
$(".start-date").html(startDate)
$(".end-date").html(endDate)
}
//{* Pagination *}
function move_to_page(page) {
if (page < 0)
return;
actual_page = page;
update_pagination_menu(page);
get_user_activity(page, uid_filter, action_filter, object_filter, [date_min_filter, date_max_filter], additional_filt_value);
}
$('.pagination-arrow.rigth').on('click', () => {
move_to_page(actual_page + 1);
})
$('.pagination-arrow.left').on('click', () => {
move_to_page(actual_page - 1);
})
function update_pagination_menu(page) {
updateArrows();
update_pagination_items();
if (end_page && actual_page == 1) {
$('.pagination-container').hide();
} else {
$('.pagination-container').show();
}
}
function updateArrows() {
if (actual_page == 1) {
$('.pagination-arrow.left').addClass('unavailable');
} else {
$('.pagination-arrow.left').removeClass('unavailable');
}
if (end_page) {
$('.pagination-arrow.rigth').addClass('unavailable');
} else {
$('.pagination-arrow.rigth').removeClass('unavailable');
}
}
function update_pagination_items() {
$('.pagination-item-container a').remove();
$('.pagination-item-container span').remove();
append_pagination_item(1);
if (actual_page > 2) {
append_pagination_item();
}
if (actual_page != 1) {
append_pagination_item(actual_page)
}
if (!end_page) {
append_pagination_item();
}
}
function append_pagination_item(page = null) {
if (page != null) {
let new_tag = $(page_item.replace(/%d/g, page));
$('.pagination-item-container').append(new_tag);
if (actual_page == page) {
new_tag.addClass('actual');
}
new_tag.on('click', () => {
move_to_page(new_tag.data('page'));
})
} else {
$('.pagination-item-container').append($(page_ellipsis));
}
}
function page_reset(){
activity_page = 1;
current_page_offset = 0;
page_offsets = [0];
actual_page = 1;
end_page = false;
}
$(document).ready(function () {
$("h1").append(`<span class='badge-number'>`+ (nb_users - 1) +`</span>`);
$('select.user-selecter').on('change', function (user) {
if ($(".user-selecter .selectize-input").hasClass("full")) {
page_reset();
if ($(".user-selecter .selectize-input .item").data("value") == 'none')
{
//{* call ajax sur activity list sans uid *}
get_user_activity(1, undefined, action_filter, object_filter, [date_min_filter, date_max_filter], additional_filt_value);
}
else
{
//{* call ajax sur activity list avec uid en param *}
get_user_activity(1, $(".user-selecter .selectize-input .item").data("value"), action_filter, object_filter, [date_min_filter, date_max_filter], additional_filt_value);
}
}
});
$('select.action-selecter').on('change', function (user) {
if ($(".action-selecter .selectize-input").hasClass("full")) {
page_reset();
if ($(".action-selecter .selectize-input .item").data("value") == 'none')
{
//{* call ajax sur activity list sans action et object *}
if (additional_filt_type)
{
get_user_activity(1, uid_filter, undefined, object_filter, [date_min_filter, date_max_filter], additional_filt_value);
}
else
{
get_user_activity(1, uid_filter, undefined, undefined, [date_min_filter, date_max_filter], additional_filt_value);
}
}
else
{
//{* call ajax sur activity list avec action et object en param *}
object = $(".action-selecter .selectize-input .item").data("value").split("/")[0];
action = $(".action-selecter .selectize-input .item").data("value").split("/")[1];
get_user_activity(1, uid_filter, action, object, [date_min_filter, date_max_filter], additional_filt_value);
}
}
});
$('#date_min_activity').on('change', function(user) {
page_reset();
if ($('#date_min_activity').val()=='')
{
document.getElementById('date_max_activity').setAttribute("min", date_min);
}
else
{
document.getElementById('date_max_activity').setAttribute("min", $('#date_min_activity').val());
}
get_user_activity(activity_page, uid_filter, action_filter, object_filter, [$('#date_min_activity').val(), date_max_filter], additional_filt_value);
})
$('#date_max_activity').on('change', function(user) {
page_reset();
if ($('#date_max_activity').val()=='')
{
document.getElementById('date_min_activity').setAttribute("max", date_max);
}
else
{
document.getElementById('date_min_activity').setAttribute("max", $('#date_max_activity').val());
}
get_user_activity(activity_page, uid_filter, action_filter, object_filter, [date_min_filter, $('#date_max_activity').val()], additional_filt_value);
})
jQuery('.user-selecter').selectize();
jQuery('.user-selecter')[0].selectize.setValue(null);
jQuery('.action-selecter').selectize();
jQuery('.action-selecter')[0].selectize.setValue(null);
if (additional_filt_type)
{
$("#activityMoreFilters").addClass("extend-padding");
}
else
{
$("#activityMoreFiltersContent").hide();
}
//var used to prevent the user to interfere with the collapsible when it's toggling, to avoid some problems
var toggleTriggered = false;
$("#activityMoreFilters").on("click", function(){
if ($("#activityMoreFiltersContent").css('display') == 'none' && toggleTriggered == false)
{
toggleTriggered = true;
$("#activityMoreFilters").addClass("extend-padding");
$("#activityMoreFiltersContent").slideToggle(function(){
toggleTriggered = false;
});
}
else if ($("#activityMoreFiltersContent").css('display') == 'flex' && toggleTriggered == false)
{
toggleTriggered = true;
$("#activityMoreFiltersContent").slideToggle(function(){
$("#activityMoreFilters").removeClass("extend-padding");
toggleTriggered = false;
});
}
})
});
File diff suppressed because it is too large Load Diff