first commit

This commit is contained in:
2025-07-18 16:20:14 +07:00
commit 98af45c018
16382 changed files with 3148096 additions and 0 deletions

17
pages/about.php Executable file
View File

@@ -0,0 +1,17 @@
<?php
include "../include/boot.php";
if (!hook("authenticate")) {
include "../include/authenticate.php";
}
include "../include/header.php";
?>
<div class="BasicsBox">
<h1><?php echo escape($lang["aboutus"]); ?></h1>
<p><?php echo escape(text("about")); ?></p>
</div>
<?php
include "../include/footer.php";

202
pages/admin/admin_content.php Executable file
View File

@@ -0,0 +1,202 @@
<?php
/**
* Manage content string page (part of System area)
*/
include "../../include/boot.php";
include "../../include/authenticate.php";
if (!checkperm("o")) {
exit("Permission denied.");
}
include "../../include/research_functions.php";
$offset = getval("offset", 0, true);
if (array_key_exists("findpage", $_POST) || array_key_exists("findname", $_POST) || array_key_exists("findtext", $_POST)) {
$offset = 0;
} # reset page counter when posting
$findpage = getval("findpage", "");
$findname = getval("findname", "");
$findtext = getval("findtext", "");
$page = getval("page", "");
$name = getval("name", "");
$extended = false;
if ($findpage != "" || $findname != "" || $findtext != "") {
# Extended view - show the language and user group columns when searching as multiple languages/groups may be returned rather than
# the single entry returned when not searching.
$extended = true;
$groups = get_usergroups();
}
if ($page && $name && enforcePostRequest(false)) {
redirect($baseurl_short . "pages/admin/admin_content_edit.php?page=$page&name=$name&offset=$offset&save=true&custom=1");
}
include "../../include/header.php";
?>
<div class="BasicsBox" style="position:relative;">
<h1><?php echo escape($lang["managecontent"]); ?></h1>
<?php
$links_trail = array(
array(
'title' => $lang["systemsetup"],
'href' => $baseurl_short . "pages/admin/admin_home.php",
'menu' => true
),
array(
'title' => $lang["managecontent"],
)
);
renderBreadcrumbs($links_trail);
$int_text = text("introtext");
echo empty($int_text) ? "" : "<p>" . $int_text . "</p>";
$text = get_all_site_text($findpage, $findname, $findtext);
# pager
$per_page = $default_perpage_list;
$results = count($text);
$totalpages = ceil($results / $per_page);
$curpage = floor($offset / $per_page) + 1;
$url = $baseurl_short . "pages/admin/admin_content.php?findpage=" . urlencode($findpage) . "&findname=" . urlencode($findname) . "&findtext=" . urlencode($findtext);
$jumpcount = 1;
?>
<div style="float:right;margin-top:-5px;"><?php pager();?></div>
<div class="Listview">
<table class="ListviewStyle">
<tr class="ListviewTitleStyle">
<th width="10%"><?php echo escape($lang["page"]); ?></th>
<th width="25%"><?php echo escape($lang["name"]); ?></th>
<?php if ($extended) { ?>
<th width="10%"><?php echo escape($lang["language"]); ?></th>
<th width="10%"><?php echo escape($lang["group"]); ?></th>
<?php } ?>
<th width="<?php echo $extended ? "40" : "55"; ?>%"><?php echo escape($lang["text"])?></th>
<th width="10%"><div class="ListTools"><?php echo escape($lang["tools"]); ?></div></th>
</tr>
<?php
for ($n = $offset; (($n < count($text)) && ($n < ($offset + $per_page))); $n++) {
$url = $baseurl_short . "pages/admin/admin_content_edit.php?page=" . urlencode($text[$n]["page"]) . "&name=" . urlencode($text[$n]["name"]) . "&editlanguage=" . urlencode($text[$n]["language"]) . "&editgroup=" . (is_null($text[$n]["group"]) ? "" : urlencode($text[$n]["group"])) . "&findpage=" . urlencode($findpage) . "&findname=" . urlencode($findname) . "&findtext=" . urlencode($findtext) . "&offset=" . urlencode($offset);
?>
<tr>
<td>
<div class="ListTitle">
<a href="<?php echo $url ?>">
<?php echo highlightkeywords(($text[$n]["page"] == "" || $text[$n]["page"] == "all" ? $lang["all"] : $text[$n]["page"]), escape($findpage), true);?>
</a>
</div>
</td>
<td>
<div class="ListTitle">
<a href="<?php echo $url ?>" onClick="return CentralSpaceLoad(this,true);">
<?php echo highlightkeywords($text[$n]["name"], escape($findname), true)?>
</a>
</div>
</td>
<?php if ($extended) {
# Extended view. Show the language and group when searching, as these variants are expanded out when searching.
# Resolve the user group name.
$group_resolved = $lang["deleted"];
if ($text[$n]["group"] == "") {
$group_resolved = $lang["all"];
} else {
# resolve
foreach ($groups as $group) {
if ($group["ref"] == $text[$n]["group"]) {
$group_resolved = $group["name"];
}
}
}
?>
<td><?php echo $text[$n]["language"]; ?></td>
<td><?php echo $group_resolved ?></td>
<?php } ?>
<td>
<a href="<?php echo $url ?>" onClick="return CentralSpaceLoad(this,true);">
<?php echo highlightkeywords(tidy_trim(escape($text[$n]["text"]), 100), escape($findtext), true, '', 1, STR_HIGHLIGHT_SIMPLE & STR_HIGHLIGHT_STRIPLINKS); ?>
</a>
</td>
<td>
<div class="ListTools">
<a href="<?php echo $url ?>" onClick="return CentralSpaceLoad(this,true);">
<i class="fa fa-edit"></i>&nbsp;<?php echo escape($lang["action-edit"]); ?>
</a>
</div>
</td>
</tr>
<?php
}
?>
</table>
</div>
<div class="BottomInpageNav">
<?php
$url = $baseurl_short . 'pages/admin/admin_content.php?findpage=' . urlencode($findpage) . '&findname=' . urlencode($findname) . '&findtext=' . urlencode($findtext);
pager(false);
?>
</div>
</div>
<div class="BasicsBox">
<form method="post" action="<?php echo $baseurl_short?>pages/admin/admin_content.php" onsubmit="return CentralSpacePost(this);">
<?php generateFormToken("admin_content_find"); ?>
<div class="Question">
<label for="find"><?php echo escape($lang["searchcontent"]); ?><br/><?php echo escape($lang["searchcontenteg"]); ?></label>
<div class="tickset">
<div class="Inline">
<input type=text placeholder="<?php echo escape($lang['searchbypage']); ?>" name="findpage" id="findpage" value="<?php echo escape($findpage)?>" maxlength="100" class="shrtwidth" />
<input type=text placeholder="<?php echo escape($lang['searchbyname']); ?>" name="findname" id="findname" value="<?php echo escape($findname)?>" maxlength="100" class="shrtwidth" />
<input type=text placeholder="<?php echo escape($lang['searchbytext']); ?>" name="findtext" id="findtext" value="<?php echo escape($findtext)?>" maxlength="100" class="shrtwidth" />
<input type="button" value="<?php echo escape($lang['clearall']); ?>" onClick="jQuery('#findtext').val('');jQuery('#findpage').val('');jQuery('#findname').val('');form.submit();" />
<input name="Submit" type="submit" value="<?php echo escape($lang["searchbutton"]); ?>" />
</div>
</div>
<div class="clearerleft"></div>
</div>
</form>
</div>
<?php if ($site_text_custom_create) { ?>
<div class="BasicsBox">
<form method="post" action="<?php echo $baseurl_short?>pages/admin/admin_content.php">
<input type="hidden" name="custom" value="1"/>
<?php generateFormToken("admin_content_new"); ?>
<div class="Question">
<label for="find"><?php echo escape($lang["addnewcontent"]); ?></label>
<div class="tickset">
<div class="Inline">
<input type=text name="page" id="page" maxlength="50" class="shrtwidth" />
</div>
<div class="Inline">
<input type=text name="name" id="name" maxlength="50" class="shrtwidth" />
</div>
<div class="Inline">
<input name="Submit" type="submit" value="<?php echo escape($lang["create"]); ?>" />
</div>
</div>
<div class="clearerleft"> </div>
</div>
</form>
</div>
<?php } ?>
<?php
include "../../include/footer.php";
?>

View File

@@ -0,0 +1,252 @@
<?php
/**
* Edit content strings page (part of System area)
*/
include "../../include/boot.php";
include "../../include/authenticate.php";
if (!checkperm("o")) {
exit("Permission denied.");
}
include "../../include/research_functions.php";
$offset = getval('offset', 0);
$page = getval('page', '');
$name = getval('name', '');
$findpage = getval('findpage', '');
$findname = getval('findname', '');
$findtext = getval('findtext', '');
$newhelp = getval('newhelp', '');
$editlanguage = getval('editlanguage', $language);
$editgroup = getval('editgroup', '');
$save = getval('save', '');
$text = getval('text', '');
// Validate HTML
$html_validation = validate_html($text);
# get custom value from database, unless it has been newly passed from admin_content.php
if (getval('custom', '') == 1) {
$custom = 1;
$newcustom = true;
} else {
$custom = check_site_text_custom($page, $name);
$newcustom = false;
}
if (($save != '') && getval('langswitch', '') == '' && $html_validation === true && enforcePostRequest(false)) {
# Save data
save_site_text($page, $name, $editlanguage, $editgroup);
if (
$newhelp != ''
&& getval('returntolist', '') == ''
) {
redirect($baseurl_short . "pages/admin/admin_content_edit.php?page=help&name=" . urlencode($newhelp) . "&offset=" . urlencode($offset) . "&findpage=" . urlencode($findpage) . "&findname=" . urlencode($findname) . "&findtext=" . urlencode($findtext));
}
if (
getval('custom', '') == 1
&& getval('returntolist', '') == ''
) {
redirect($baseurl_short . "pages/admin/admin_content_edit.php?page=" . urlencode($page) . "&name=" . urlencode($name) . "&offset=" . urlencode($offset) . "&findpage=" . urlencode($findpage) . "&findname=" . urlencode($findname) . "&findtext=" . urlencode($findtext));
}
if (getval('returntolist', '') != '') {
redirect($baseurl_short . "pages/admin/admin_content.php?nc=" . time() . "&findpage=" . urlencode($findpage) . "&findname=" . urlencode($findname) . "&findtext=" . urlencode($findtext) . "&offset=" . urlencode($offset));
}
}
// Need to save $lang and $language so we can revert after finding specific text
$langsaved = $lang;
$languagesaved = $language;
$text = get_site_text($page, $name, $editlanguage, $editgroup);
$defaulttext = get_site_text($page, $name, $defaultlanguage, '');
# Default text? Show that this is the case
$text_default = false;
if ($text == $defaulttext && ($editlanguage != $defaultlanguage || $editgroup != '')) {
$text_default = true;
}
// Revert to original values
$lang = $langsaved;
$language = $languagesaved;
include "../../include/header.php";
?>
<div class="BasicsBox">
<h1><?php echo escape($lang["editcontent"]); ?></h1>
<?php
$links_trail = array(
array(
'title' => $lang["systemsetup"],
'href' => $baseurl_short . "pages/admin/admin_home.php",
'menu' => true
),
array(
'title' => $lang["managecontent"],
'href' => $baseurl_short . "pages/admin/admin_content.php?nc=" . time() . "&findpage=" . urlencode($findpage) . "&findname=" . urlencode($findname) . "&findtext=" . urlencode($findtext) . "&offset=" . urlencode($offset)
),
array(
'title' => $lang["editcontent"]
)
);
renderBreadcrumbs($links_trail);
if ($html_validation !== true && $html_validation !== '') { ?>
<div class="PageInformal"><?php echo escape($lang['error_check_html_first']); ?></div>
<?php
} ?>
<form method="post" id="mainform" action="<?php echo $baseurl_short; ?>pages/admin/admin_content_edit.php?page=<?php echo urlencode($page);?>&name=<?php echo urlencode($name);?>&editlanguage=<?php echo urlencode($editlanguage);?>&editgroup=<?php echo urlencode($editgroup);?>&findpage=<?php echo urlencode($findpage)?>&findname=<?php echo urlencode($findname)?>&findtext=<?php echo urlencode($findtext)?>&offset=<?php echo urlencode($offset)?>">
<?php generateFormToken("mainform"); ?>
<input type=hidden name=page value="<?php echo escape($page)?>">
<input type=hidden name=name value="<?php echo escape($name)?>">
<input type=hidden name=copyme id="copyme" value="">
<input type=hidden name=langswitch id="langswitch" value="">
<input type=hidden name=groupswitch id="groupswitch" value="">
<input type="hidden" name="custom" value="<?php echo getval('custom', 0, true)?>">
<div class="Question">
<label><?php echo escape($lang["page"]); ?></label>
<div class="Fixed"><?php echo escape(($page == "" ? $lang["all"] : $page)) ?></div>
<div class="clearerleft"></div>
</div>
<?php if ($page == 'help') { ?>
<div class="Question">
<label for="name"><?php echo escape($lang["name"]); ?></label>
<input type=text name="name" class="stdwidth" value="<?php echo escape($name)?>">
<div class="clearerleft"></div>
</div>
<?php } else { ?>
<div class="Question">
<label><?php echo escape($lang["name"]); ?></label>
<div class="Fixed"><?php echo escape($name) ?></div>
<div class="clearerleft"></div>
</div>
<?php } ?>
<div class="Question">
<label for="editlanguage"><?php echo escape($lang["language"]); ?></label>
<select class="stdwidth" name="editlanguage" onchange="document.getElementById('langswitch').value='yes';document.getElementById('mainform').submit();">
<?php foreach ($languages as $key => $value) { ?>
<option value="<?php echo $key?>" <?php echo ($editlanguage == $key) ? "selected" : ''; ?>>
<?php echo $value; ?>
</option>
<?php } ?>
</select>
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="editgroup"><?php echo escape($lang["group"]); ?></label>
<select class="stdwidth" name="editgroup" onchange="document.getElementById('groupswitch').value='yes';document.getElementById('copyme').value='yes';document.getElementById('mainform').submit();">
<option value=""></option>
<?php
$groups = get_usergroups();
for ($n = 0; $n < count($groups); $n++) {
?>
<option value="<?php echo $groups[$n]["ref"]; ?>" <?php echo ($editgroup == $groups[$n]["ref"]) ? "selected" : ''; ?>>
<?php echo $groups[$n]["name"]; ?>
</option>
<?php
}
?>
</select>
<div class="clearerleft"></div>
</div>
<?php
# Default text? Show that this is the case
if ($text_default) {
render_fixed_text_question($lang["default"], str_replace("?", $languages[$defaultlanguage], $lang['managecontent_defaulttextused']));
}
?>
<div class="Question">
<label for="text"><?php echo escape($lang['text']); ?></label>
<textarea id="text" class="stdwidth" name="text" rows=15 cols=50><?php echo escape($text); ?></textarea>
<div class="clearerleft"></div>
</div>
<?php
# Add special ability to create and remove help pages
if ($page == 'help') {
if ($name != 'introtext') {
?>
<div class="Question">
<label for="deleteme"><?php echo escape($lang["ticktodeletehelp"]); ?></label>
<input id="deleteme" class="deleteBox" name="deleteme" type="checkbox" value="yes">
<div class="clearerleft"></div>
</div>
<?php
}
?>
<br />
<br />
<div class="Question">
<label for="newhelp"><?php echo escape($lang["createnewhelp"]); ?></label>
<input name="newhelp" type=text value="" />
<div class="clearerleft"></div>
</div>
<?php
}
# Add ability to delete custom page/name entries
if ($custom == 1 && $page != 'help') {
?>
<div class="Question">
<label for="deletecustom"><?php echo escape($lang["ticktodeletehelp"]); ?></label>
<input id="deletecustom" class="deleteBox" name="deletecustom" type="checkbox" value="yes" />
<div class="clearerleft"> </div>
</div>
<?php
}
?>
<input type=hidden id="returntolist" name="returntolist" value=""/>
<div id="submissionResponse"></div>
<div class="QuestionSubmit">
<label for="save"></label>
<input type="submit" name="checkhtml" id="checkhtml" value="Check HTML" />
<input type="submit" name="save" value="<?php echo escape($lang["save"]); ?>" />
<input type="submit" name="save" value="<?php echo escape($lang['saveandreturntolist']); ?>" onClick="jQuery('#returntolist').val(true);" />
</div>
</form>
</div><!-- End of BasicsBox -->
<script>
// When to take us back to manage content list
jQuery('#deleteme, #deletecustom').change(function() {
if (jQuery(this).is(':checked')) {
jQuery('#returntolist').val(true);
} else {
jQuery('#returntolist').val(null);
}
});
// Manually check HTML:
jQuery('#checkhtml').click(function(e) {
var checktext = jQuery('#text').val();
jQuery.post(
'../tools/check_html.php',
{
'text': checktext,
<?php echo generateAjaxToken('admin_content_edit'); ?>,
}, function(response, status, xhr) {
CentralSpaceHideProcessing();
jQuery('#submissionResponse').html(response);
}
);
e.preventDefault();
});
</script>
<?php
include "../../include/footer.php";

View File

@@ -0,0 +1,87 @@
<?php
include '../../include/boot.php';
include '../../include/authenticate.php';
if (!checkperm('a')) {
exit('Permission denied.');
}
$ref = getval('ref', 0, true);
$copied = '';
$current = get_resource_type_field($ref);
$title = $current["title"];
# Perform copy
if (getval("saveform", "") != "" && $ref > 0 && enforcePostRequest(false)) {
$allcolumns = columns_in("resource_type_field", null, null, true);
$allcolumns = array_diff($allcolumns, ["name"]);
$insert = array_diff($allcolumns, ["ref","name"]);
// Create new short name
$allcolumns[] = "name";
$newname = $current["name"] . "copy";
ps_query("INSERT INTO resource_type_field (" . implode(",", $allcolumns) . ") SELECT NULL, " . implode(",", $insert) . ",? FROM resource_type_field WHERE ref = ?", ["s",$newname,"i",$ref]);
$copied = sql_insert_id();
// Copy any field mappings
ps_query("INSERT INTO resource_type_field_resource_type (resource_type_field,resource_type) SELECT ?,resource_type FROM resource_type_field_resource_type WHERE resource_type_field = ?", ["i",$copied,"i",$ref]);
// Copy nodes if resource type is a fixed list type:
copy_resource_type_field_nodes($ref, $copied);
log_activity(null, LOG_CODE_COPIED, "{$lang['copy_of']} {$ref}", 'resource_type_field', '', $copied);
redirect($baseurl_short . "pages/admin/admin_resource_type_field_edit.php?ref=" . $copied);
}
if ($copied != '') {
$saved_text = str_replace('?', $copied, $lang['copy-completed']);
}
include "../../include/header.php";
?>
<div class="BasicsBox">
<?php
$links_trail = array(
array(
'title' => $lang["systemsetup"],
'href' => $baseurl_short . "pages/admin/admin_home.php",
'menu' => true
),
array(
'title' => $lang["admin_resource_type_fields"],
'href' => $baseurl_short . "pages/admin/admin_resource_type_fields.php"
),
array(
'title' => $lang["admin_resource_type_field"] . ": " . i18n_get_translated($title),
'href' => $baseurl_short . "pages/admin/admin_resource_type_field_edit.php?ref=" . $ref
),
array(
'title' => $lang['copy-field'] . ": " . i18n_get_translated($title),
'help' => "managing-metadata"
)
);
renderBreadcrumbs($links_trail);
if (isset($saved_text)) {
?>
<div class="PageInformal"><?php echo escape($saved_text); ?></div>
<?php
}
?>
<form method="post" action="admin_copy_field.php">
<?php generateFormToken("admin_copy_field"); ?>
<input type="hidden" name="saveform" value="true">
<input type="hidden" name="ref" value="<?php echo $ref; ?>">
<p align="right">
<input type="submit" name="copy" value="<?php echo escape($lang['copy']) ; ?>" style="width:100px;">
</p>
</form>
</div><!--End of BasicsBox -->
<?php
include "../../include/footer.php";

View File

@@ -0,0 +1,101 @@
<?php
include '../../include/boot.php';
include '../../include/authenticate.php';
if (!(checkperm('a') && checkperm("v"))) {
exit('Permission denied.');
}
include_once '../../include/config_functions.php';
if (!extension_loaded("zip")) {
$error = str_replace("[module]", "php-zip", $lang["error_server_missing_module"]);
} elseif (!$offline_job_queue) {
$error = str_replace("[config_option]", "\$offline_job_queue", $lang["error_check_config"]);
} elseif (!isset($mysql_bin_path)) {
$error = str_replace("[config_option]", "\$mysql_bin_path", $lang["error_check_config"]);
} elseif (!$system_download_config) {
$error = str_replace("[config_option]", "\$system_download_config", $lang["error_check_config"]);
}
$export = getval("export", "") != "";
$exportcollection = getval("exportcollection", 0, true);
$obfuscate = ($system_download_config_force_obfuscation || getval("obfuscate", "") !== "" || defined("SYSTEM_DOWNLOAD_CONFIG_FORCE_OBFUSCATION"));
$separatesql = getval("separatesql", "") !== "";
if (!isset($error) && $export != "" && enforcePostRequest(false)) {
$exporttables = get_export_tables($exportcollection);
// Create offline job
$job_data = array();
$job_data["exporttables"] = $exporttables;
$job_data["obfuscate"] = $obfuscate;
$job_data["userref"] = $userref;
$job_data["separatesql"] = $separatesql;
$job_code = "system_export_" . md5($userref . $exportcollection . ($obfuscate ? "1" : "0") . ($separatesql ? "1" : "0")); // unique code for this job, used to prevent duplicate job creation.
$jobadded = job_queue_add("config_export", $job_data, $userref, '', $lang["exportcomplete"], $lang["exportfailed"], $job_code);
if (!$jobadded) {
$message = $lang["oj-creation-failure-text"];
} else {
$message = str_replace("[jobnumber]", $jobadded, $lang["oj-creation-success"]);
}
}
// This page will create an offline job that creates a zip file containing system configuration information and data
include '../../include/header.php';
?>
<div class="BasicsBox">
<p>
<a href="<?php echo $baseurl_short; ?>pages/admin/admin_home.php" onClick="return CentralSpaceLoad(this, true);"><?php echo LINK_CARET_BACK ?><?php echo escape($lang['back']); ?></a>
</p>
<h1><?php echo escape($lang['exportdata']); ?></h1>
<?php
if (isset($error)) {
echo "<div class=\"FormError\">" . $lang["error"] . ":&nbsp;" . escape($error) . "</div>";
} elseif (isset($message)) {
echo "<div class=\"PageInformal\">" . escape($message) . "</div>";
}
?>
<p><?php echo strip_tags_and_attributes($lang['exportdata-instructions']);
render_help_link("admin/download-config");?></p>
<form method="post" action="<?php echo $baseurl_short?>pages/admin/admin_download_config.php" onSubmit="return CentralSpacePost(this,true);">
<input type="hidden" name="export" value="true" />
<?php
if (!$system_download_config_force_obfuscation) {
?>
<div class="Question">
<label><?php echo escape($lang['exportobfuscate']); ?></label>
<input type="checkbox" name="obfuscate" value="1" <?php echo $obfuscate ? "checked" : "";?> />
<div class="clearerleft"> </div>
</div>
<?php
}?>
<div class="Question">
<label><?php echo escape($lang['exportcollection']); ?></label>
<input type="number" name="exportcollection" value="<?php echo (int)$exportcollection; ?>"></input>
<div class="clearerleft"> </div>
</div>
<div class="Question">
<label><?php echo escape($lang['export_separate_sql']); ?></label>
<input type="checkbox" name="separatesql" value="1" <?php echo $separatesql ? "checked" : "";?> />
<div class="clearerleft"> </div>
</div>
<div class="Question" <?php echo isset($error) ? 'style="display: none;"' : ''; ?>>
<input type="button" name="export" value="<?php echo escape($lang["export"]); ?>" onClick="jQuery(this.form).submit();" >
<div class="clearerleft"> </div>
</div>
<?php generateFormToken("download_config"); ?>
</form>
</div>
<?php
include '../../include/footer.php';

View File

@@ -0,0 +1,291 @@
<?php
include "../../include/boot.php";
include "../../include/authenticate.php";
$filterid = getval("filter", 0, true);
if (!checkperm("a")) {
exit("Permission denied.");
}
$backurl = getval("backurl", "");
if ($backurl == "") {
$filterorder = getval("filterorder", "ref");
$filtersort = getval("filtersort", "ASC");
$revsort = ($filtersort == "ASC") ? "DESC" : "ASC";
$filterfind = getval("filterfind", "");
$filter_manage_url = $baseurl . "/pages/admin/admin_filter_manage.php";
$params = array(
"filterfind" => $filterfind,
"filtersort" => $filtersort,
"filterorder" => $filterorder
);
$backurl = generateURL($filter_manage_url, $params);
} else {
$backurl = urlencode($backurl);
}
$delete_filter = getval('delete_filter', '');
$delete_filter_rule = getval('delete_filter_rule', '');
$filter_rule = getval("filter_rule", "");
$filter_copy_from = getval("copy_from", 0, true);
// Process ajax requests
if ($delete_filter != "" && enforcePostRequest("admin_filter_edit")) {
$result = delete_filter($delete_filter);
if ($result === true) {
if (getval("filter_manage_page", "") != "") {
$response = array('deleted' => $result);
exit(json_encode($response));
} else {
?>
<script>
CentralSpaceLoad('<?php echo $backurl; ?>',true);
</script>
<?php
exit();
}
} else {
$response = array('deleted' => false);
$errors = array();
$errors[] = escape($lang["filter_delete_error"]) . ":- ";
foreach ($result["groups"] as $group) {
$errors[] = escape($lang["group"]) . ": <a href='" . $baseurl_short . "/pages/admin/admin_group_management_edit.php?ref=" . (int) $group . "' target='_blank' >" . (int) $group . "</a>";
}
foreach ($result["users"] as $user) {
$errors[] = escape($lang["user"]) . ": <a href='" . $baseurl_short . "?u=" . (int) $user . "' target='_blank' >" . (int) $user . "</a>";
}
if (getval("filter_manage_page", "") != "") {
$response['errors'] = $errors;
exit(json_encode($response));
}
}
}
if ($delete_filter_rule != "" && enforcePostRequest("delete_filter_rule")) {
$result = delete_filter_rule($delete_filter_rule);
$response = array('success' => $result);
exit(json_encode($response));
} elseif ($filter_rule != "" && enforcePostRequest("filter_rule_edit")) {
// Process saved rules
$ruledata = getval("filter_rule_data", "");
save_filter_rule($filter_rule, $filterid, $ruledata);
} elseif ($filterid != "" && getval("save", "") != "" && enforcePostRequest("admin_filter_edit")) {
// Save the filter
$filter_name = getval("filter_name", "");
$filter_condition = getval("filter_condition", RS_FILTER_ALL, true);
if ($filterid == 0 && $filter_copy_from != 0) {
// Copy rules to new filter
$newfilterid = copy_filter($filter_copy_from);
$filterid = $newfilterid;
} else {
save_filter($filterid, $filter_name, $filter_condition);
if (getval("filter_manage_page", "") == "" && !isset($errors) && empty($errors)) {
redirect($backurl);
}
}
}
// Get all fields so we can resolve node field names
$allfields = get_resource_type_fields();
$filter = get_filter($filterid);
$filter_rules = get_filter_rules($filterid);
$filter_edit_url = generateURL($baseurl . "/pages/admin/admin_filter_edit.php", array("filter" => $filterid));
$rule_add_url = generateURL($baseurl . "/pages/admin/ajax/admin_filter_rule_edit.php", array("ref" => "new","filter" => $filterid));
// Convert filter so we can display it in a user friendly way
$rules = array();
foreach ($filter_rules as $fr_id => $frule) {
foreach ($frule["nodes_on"] as $rulenode) {
$nodeinfo = array();
get_node($rulenode, $nodeinfo);
if (!$nodeinfo) {
debug("filter rule #" . $fr_id . " - node " . $rulenode . " not found ");
// Node does not exist
continue;
}
$field_index = array_search($nodeinfo["resource_type_field"], array_column($allfields, 'ref'));
if ($field_index !== false) {
if (!isset($rules[$fr_id]["fields"][$allfields[$field_index]["ref"]])) {
$rules[$fr_id]["fields"][$allfields[$field_index]["ref"]]["fieldname"] = i18n_get_translated($allfields[$field_index]["name"]);
$rules[$fr_id]["fields"][$allfields[$field_index]["ref"]]["values_on"] = array();
}
$rules[$fr_id]["fields"][$allfields[$field_index]["ref"]]["values_on"][] = i18n_get_translated($nodeinfo["name"]);
} else {
echo "filter - node field " . $nodeinfo["resource_type_field"] . " for node:" . $rulenode . " not found ";
}
}
foreach ($frule["nodes_off"] as $rulenode) {
$nodeinfo = array();
get_node($rulenode, $nodeinfo);
if (!$nodeinfo) {
debug("filter rule #" . $fr_id . " - node " . $rulenode . " not found ");
// Node does not exist
continue;
}
$field_index = array_search($nodeinfo["resource_type_field"], array_column($allfields, 'ref'));
if ($field_index !== false) {
if (!isset($rules[$fr_id]["fields"][$allfields[$field_index]["ref"]])) {
$rules[$fr_id]["fields"][$allfields[$field_index]["ref"]]["fieldname"] = i18n_get_translated($allfields[$field_index]["name"]);
$rules[$fr_id]["fields"][$allfields[$field_index]["ref"]]["values_off"] = array();
}
$rules[$fr_id]["fields"][$allfields[$field_index]["ref"]]["values_off"][] = i18n_get_translated($nodeinfo["name"]);
} else {
echo "filter - node field " . $nodeinfo["resource_type_field"] . " for node:" . $rulenode . " not found ";
}
}
}
include "../../include/header.php";
?>
<div id="CentralSpaceContainer">
<div id="CentralSpace">
<div class="BasicsBox">
<h1><?php echo escape($filterid == 0 ? $lang["filter_new"] : $lang["filter_edit"]); ?></h1>
<?php
$links_trail = array(
array(
'title' => $lang["systemsetup"],
'href' => $baseurl_short . "pages/admin/admin_home.php",
'menu' => true
),
array(
'title' => $lang["filter_manage"],
'href' => $backurl
),
array(
'title' => $filterid == 0 ? $lang["filter_new"] : $lang["filter_edit"],
)
);
renderBreadcrumbs($links_trail);
?>
<h2>
<?php
echo escape($lang["filter_edit_text"]);
render_help_link("systemadmin/search-filters");
?>
</h2>
<form id="filter_edit_form" name="filter_edit_form" method="post" class="FormWide" action="<?php echo $filter_edit_url; ?>">
<input type="hidden" name="filter" value="<?php echo escape($filterid); ?>" />
<input type="hidden" name="save" value="true" />
<?php generateFormToken("admin_filter_edit"); ?>
<div class="Question" id="filter_name_question">
<label for="filter_name"><?php echo escape($lang["filter_name"]); ?></label>
<input class="stdwidth" type="text" name="filter_name" id="filter_name" value="<?php echo i18n_get_translated($filter["name"]) ?>" />
<div class="clearerleft"> </div>
</div>
<div class="Question" id="filter_condition_question" title="" style="height: 50px;">
<label><?php echo escape($lang["filter_condition_label"]); ?></label>
<select class="stdwidth" name="filter_condition">
<?php
foreach (array(RS_FILTER_ALL => "filter_criteria_all",RS_FILTER_NONE => "filter_criteria_none",RS_FILTER_ANY => "filter_criteria_any") as $filter_condition => $description) {
echo "<option value='" . escape($filter_condition) . "' " . ($filter["filter_condition"] == $filter_condition ? "selected " : "") . ">" . escape($lang[$description]) . "</option>";
}?>
</select>
<div class="clearerleft"> </div>
</div>
<div class="Question" id="fr_question">
<label for="fr_list"><?php echo escape($lang["filter_rules"]); ?></label>
<div id="fr_list" class="stdwidth">
<table class="OptionTable">
<?php
if (count($rules) == 0) {
echo escape($lang["filter_rules_none"]);
} else {
foreach ($rules as $ruleid => $ruleinfo) {
$ruletext = array();
foreach ($ruleinfo["fields"] as $rulefield) {
if (isset($rulefield["values_on"]) && count($rulefield["values_on"]) > 0) {
$ruletext[] = $rulefield["fieldname"] . " " . $lang["filter_is_in"] . " ('" . implode("'&nbsp;" . $lang["filter_or"] . "&nbsp;'", $rulefield["values_on"]) . "')";
}
if (isset($rulefield["values_off"]) && count($rulefield["values_off"]) > 0) {
$ruletext[] = $rulefield["fieldname"] . " " . $lang["filter_is_not_in"] . " ('" . implode("'&nbsp;" . $lang["filter_or"] . "&nbsp;'", $rulefield["values_off"]) . "')";
}
}
$rule_edit_url = generateURL($baseurl . "/pages/admin/ajax/admin_filter_rule_edit.php", array("ref" => $ruleid,"filter" => $filterid));
echo "<tr><td><div class='keywordselected tag_inline' id='filter_rule_" . escape($ruleid) . "'> <a href={$rule_edit_url} onclick ='return ModalLoad(this,true);'>" . implode("&nbsp;" . escape($lang["filter_or"]) . "&nbsp;", $ruletext) . "</a><a href='#' onclick ='deleteFilterRule(" . escape($ruleid) . ");return false;'>[<i class='fa fa-remove'></i>]</a></input></td></tr>";
}
}
?>
</table>
</div> <!-- End of fr_list -->
<div class="clearerleft"> </div>
</div><!-- End of fr_question -->
<div class="Question">
<input name="ruleadd" type="button" onclick="addFilterRule();"value="<?php echo escape($lang["filter_rule_add"]); ?>">
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="delete_filter"><?php echo escape($lang["action-delete"]); ?></label>
<input id="delete_filter" name="delete_filter" type="checkbox" value="<?php echo escape($filterid); ?>" >
<div class="clearerleft"></div>
</div>
<div class="QuestionSubmit">
<input name="save" type="submit" value="<?php echo escape($lang["save"]);?>" onClick="return CentralSpacePost(this.form,true);">
</div>
</form>
</div> <!-- End of BasicsBox -->
</div> <!-- End of CentralSpace -->
</div> <!-- End of CentralSpaceContainer -->
<script>
function addFilterRule() {
ModalLoad('<?php echo $rule_add_url; ?>',true,true,'left');
ModalCentre();
return true;
}
function deleteFilterRule(rule) {
var post_data = {
ajax: true,
delete_filter_rule: rule,
<?php echo generateAjaxToken("delete_filter_rule"); ?>
};
jQuery.post(window.location.href, post_data, function(response) {
if (response.success === true) {
jQuery('#filter_rule_' + rule).remove();
} else {
styledalert('<?php echo escape($lang["error"]); ?>',response);
}
}, 'json');
return false;
}
jQuery(document).ready(function() {
let errors = <?php echo isset($errors) ? json_encode($errors) : '""';?>;
if (errors.length > 0) {
error_message = '';
for (var i in errors) {
error_message += errors[i] + "<br />";
}
console.log(error_message);
styledalert("<?php echo escape($lang['error']); ?>", error_message);
}
});
</script>
<?php
include "../../include/footer.php";

View File

@@ -0,0 +1,175 @@
<?php
include "../../include/boot.php";
include "../../include/authenticate.php";
if (!checkperm("a")) {
exit("Permission denied.");
}
$filterorder = getval("filterorder", "ref");
$filtersort = getval("filtersort", "ASC");
$revsort = ($filtersort == "ASC") ? "DESC" : "ASC";
$filterfind = getval("filterfind", "");
$copy_from = getval('copy_from', 0, true);
$new_filter_name = getval("filter_name", "");
$filters = get_filters($filterorder, $filtersort, $filterfind);
$filter_edit_url = $baseurl . "/pages/admin/admin_filter_edit.php";
$filter_manage_url = $baseurl . "/pages/admin/admin_filter_manage.php";
$params = array(
"filterfind" => $filterfind,
"filtersort" => $filtersort,
"filterorder" => $filterorder
);
if ($copy_from > 0 && enforcePostRequest(false)) {
$new_filter_id = copy_filter($copy_from);
$filter_details = get_filter($new_filter_id);
save_filter($new_filter_id, $filter_details['name'] . ' (' . $lang['copy'] . ')', $filter_details['filter_condition']);
redirect($baseurl_short . "pages/admin/admin_filter_edit.php?filter=" . $new_filter_id);
} elseif (trim($new_filter_name) == '' && getval('save', '') == 'true' && enforcePostRequest(false)) {
error_alert($lang['error-invalid_name'], false);
exit();
} elseif ($new_filter_name != "" && enforcePostRequest(false)) {
$new_filter_id = save_filter(0, $new_filter_name, RS_FILTER_ALL);
clear_query_cache("schema");
redirect($baseurl_short . "pages/admin/admin_filter_edit.php?filter=" . $new_filter_id);
}
include "../../include/header.php";
?>
<div id="CentralSpaceContainer">
<div id="CentralSpace">
<div class="BasicsBox">
<h1><?php echo escape($lang["filter_manage"]); ?></h1>
<?php
$links_trail = array(
array(
'title' => $lang["systemsetup"],
'href' => $baseurl_short . "pages/admin/admin_home.php",
'menu' => true
),
array(
'title' => $lang["filter_manage"],
'help' => 'systemadmin/search-filters'
)
);
renderBreadcrumbs($links_trail);
?>
<div class="Listview">
<table id="filter_list_table" class="ListviewStyle">
<tbody>
<tr class="ListviewTitleStyle">
<th>
<a href="<?php echo generateURL($filter_manage_url, $params, array("filterorder" => "ref", "sort" => $revsort)); ?>" onclick="return CentralSpaceLoad(this);">
<?php echo escape($lang['property-reference']); ?>
</a>
</th>
<th>
<a href="<?php echo generateURL($filter_manage_url, $params, array("filterorder" => "name", "sort" => $revsort)); ?>" onclick="return CentralSpaceLoad(this);">
<?php echo escape($lang['property-name']); ?>
</a>
</th>
<th><div class="ListTools"><?php echo escape($lang['tools']); ?></div></th>
</tr>
<?php for ($n = 0; $n < count($filters); $n++) { ?>
<tr class="filter_row" id="field_sort_<?php echo $filters[$n]["ref"];?>">
<td>
<a href="<?php echo generateURL($filter_edit_url, $params, array("ref" => $filters[$n]["ref"])); ?>" onclick="return CentralSpaceLoad(this);">
<?php echo $filters[$n]["ref"]; ?>
</a>
</td>
<td>
<div class="ListTitle">
<a href="<?php echo generateURL($filter_edit_url, $params, array("filter" => $filters[$n]["ref"])); ?>" onclick="return CentralSpaceLoad(this);">
<?php echo str_highlight(i18n_get_translated($filters[$n]["name"]), $filterfind, STR_HIGHLIGHT_SIMPLE); ?>
</a>
</div>
</td>
<td>
<div class="ListTools">
<a href="#" onClick="jQuery('#form_copy_from').val('<?php echo escape($filters[$n]["ref"]); ?>');return CentralSpacePost(document.getElementById('admin_filter_form'),true)" >
<?php echo '<i class="fas fa-copy"></i>&nbsp;' . escape($lang["copy"]); ?>
</a>
<a href="<?php echo generateURL($filter_edit_url, $params, array("filter" => $filters[$n]["ref"])); ?>" onClick="return CentralSpaceLoad(this,true);">
<?php echo '<i class="fas fa-edit"></i>&nbsp;' . escape($lang["action-edit"]); ?>
</a>
<a
href="#"
onClick='
event.preventDefault();
if (confirm("<?php echo escape($lang["confirm-deletion"]); ?>")) {
var post_data = {
ajax: true,
filter_manage_page: true,
filter: <?php echo urlencode($filters[$n]['ref']); ?>,
delete_filter: <?php echo urlencode($filters[$n]['ref']); ?>,
<?php echo generateAjaxToken('admin_filter_edit'); ?>
};
jQuery.post("<?php echo $filter_edit_url; ?>", post_data, function(response) {
if (response.deleted) {
var redirect_link = document.createElement("a");
redirect_link.href = "<?php echo generateURL($filter_manage_url, $params, array("deleted" => $filters[$n]["ref"])); ?>";
CentralSpaceLoad(redirect_link, true);
} else {
errors = "";
console.log(response.errors);
for (var i in response.errors) {
errors += response.errors[i] + "<br />";
}
styledalert("<?php echo escape($lang["error"]); ?>",errors);
}
}, "json");
return false;
} else {
return false;
}
'>
<?php echo '<i class="fa fa-trash"></i>&nbsp;' . escape($lang["action-delete"]); ?>
</a>
</div>
</td>
</tr>
<?php
} ?>
</tbody>
</table>
</div>
</div> <!-- End of BasicsBox -->
<div class="BasicsBox">
<form method="post" id="admin_filter_form" action="<?php echo $baseurl_short; ?>pages/admin/admin_filter_manage.php" onsubmit="return CentralSpacePost(this,false);">
<?php generateFormToken("admin_filter_edit"); ?>
<input type="hidden" name="filter" value="0" />
<input type="hidden" id="form_copy_from" name="copy_from" value="" />
<input type="hidden" name="save" value="true" />
<div class="Question">
<label for="filter_name"><?php echo escape($lang["filter_create_name"]); ?></label>
<div class="tickset">
<div class="Inline">
<input type=text name="filter_name" id="filter_name" maxlength="100" class="shrtwidth" />
</div>
<div class="Inline">
<input name="save" type="submit" value="&nbsp;&nbsp;<?php echo escape($lang["create"]); ?>&nbsp;&nbsp;" onclick="return CentralSpacePost(this.form,true);" />
</div>
</div>
<div class="clearerleft"> </div>
</div>
</form>
</div>
</div> <!-- End of CentralSpace -->
</div> <!-- End of CentralSpaceContainer -->
<?php
include "../../include/footer.php";

View File

@@ -0,0 +1,278 @@
<?php
include "../../include/boot.php";
include "../../include/authenticate.php";
if (!checkperm("a")) {
exit("Permission denied.");
}
$ref = (int) getval('ref', 0, true, 'is_int_loose');
if ($ref === 0) {
exit('No user group ref supplied.');
}
$offset = getval("offset", 0, true);
$order_by = getval("orderby", "");
$filter_by_parent = getval("filterbyparent", "");
$find = getval("find", "");
$filter_by_permissions = getval("filterbypermissions", "");
$url_params = [
'ref' => $ref,
];
if ($offset) {
$url_params['offset'] = $offset;
}
if ($order_by) {
$url_params['orderby'] = $order_by;
}
if ($filter_by_parent) {
$url_params['filterbyparent'] = $filter_by_parent;
}
if ($find) {
$url_params['find'] = $find;
}
if ($filter_by_permissions) {
$url_params['filterbypermissions'] = $filter_by_permissions;
}
$group = get_usergroup($ref);
$selected_usergroup_permissions = explode(',', $group['permissions']);
$enable_disable_options = array($lang['userpreference_disable_option'], $lang['userpreference_enable_option']);
$yes_no_options = array($lang['no'], $lang['yes']);
# Rendering of user group preferences area.
if ((int) $group['parent'] > 0 && in_array("preferences", $group['inherit'])) {
$page_def[] = config_add_html('<p>' . $lang["group_config_inherit"] . '</p>');
} else {
$page_def[] = config_add_html('<p>' . $lang["action-title_usergroup_override_detail"] . '</p>');
// User interface section
$page_def[] = config_add_html('<h3 class="CollapsibleSectionHead collapsed">' . $lang['userpreference_user_interface'] . '</h3><div id="UsergroupConfigUserInterfaceSection" class="CollapsibleSection">');
$page_def[] = config_add_colouroverride_input('header_colour_style_override', $lang["setup-headercolourstyleoverride"], '', null, true);
$page_def[] = config_add_colouroverride_input('header_link_style_override', $lang["setup-headerlinkstyleoverride"], '', null, true);
$page_def[] = config_add_colouroverride_input('home_colour_style_override', $lang["setup-homecolourstyleoverride"], '', null, true);
$page_def[] = config_add_colouroverride_input('collection_bar_background_override', $lang["setup-collectionbarbackground"], '', null, true);
$page_def[] = config_add_colouroverride_input('collection_bar_foreground_override', $lang["setup-collectionbarforeground"], '', null, true);
$page_def[] = config_add_colouroverride_input('button_colour_override', $lang["setup-buttoncolouroverride"], '', null, true);
$page_def[] = config_add_single_select('thumbs_default', $lang['userpreference_thumbs_default_label'], array('show' => $lang['showthumbnails'], 'hide' => $lang['hidethumbnails']), true, 300, '', true);
$page_def[] = config_add_boolean_select('basic_simple_search', $lang['userpreference_basic_simple_search_label'], $enable_disable_options, 300, '', true);
$page_def[] = config_add_boolean_select('hide_search_resource_types', $lang['userpreference_hide_search_resource_types'], $enable_disable_options, 300, '', true);
$page_def[] = config_add_single_select('upload_then_edit', $lang['upload_sequence'], array(true => $lang['upload_first_then_set_metadata'], false => $lang['set_metadata_then_upload']), true, 300, '', true);
$page_def[] = config_add_boolean_select('modal_default', $lang['userpreference_modal_default'], $enable_disable_options, 300, '', true);
$page_def[] = config_add_boolean_select('keyboard_navigation', $lang['userpreference_keyboard_navigation'], $enable_disable_options, 300, '', true);
$page_def[] = config_add_boolean_select('tilenav', $lang['userpreference_tilenav'], $enable_disable_options, 300, '', true, 'TileNav=(value==1);');
$page_def[] = config_add_boolean_select('byte_prefix_mode_decimal', $lang['byte_prefix_mode_decimal'], $enable_disable_options, 300, '', true);
$page_def[] = config_add_single_select('user_local_timezone', $lang['systemconfig_user_local_timezone'], timezone_identifiers_list(), false, 300, '', true);
$page_def[] = config_add_html('</div>');
// Search section
$page_def[] = config_add_html('<h3 class="CollapsibleSectionHead collapsed">' . $lang['searchcapability'] . '</h3><div id="SystemConfigSearchSection" class="CollapsibleSection">');
$sort_order_fields = array('relevance' => $lang['relevance']);
if ($popularity_sort) {
$sort_order_fields['popularity'] = $lang['popularity'];
}
if ($orderbyrating) {
$sort_order_fields['rating'] = $lang['rating'];
}
if ($date_column) {
$sort_order_fields['date'] = $lang['date'];
}
if ($colour_sort) {
$sort_order_fields['colour'] = $lang['colour'];
}
if ($order_by_resource_id) {
$sort_order_fields['resourceid'] = $lang['resourceid'];
}
$sort_order_fields['resourcetype'] = $lang['type'];
foreach ($sort_fields as $field) {
$field_data = get_resource_type_field($field);
if ($field_data !== false) {
$sort_order_fields["field$field"] = $field_data["title"];
}
}
$page_def[] = config_add_single_select('default_sort', $lang['userpreference_default_sort_label'], $sort_order_fields, true, 420, '', true);
$page_def[] = config_add_single_select('default_sort_direction', $lang['userpreference_default_sort_order_label'], ['ASC' => 'Ascending', 'DESC' => 'Descending'], true, 420, '', true);
$default_display_array = array();
$default_display_array['thumbs'] = $lang['largethumbstitle'];
if ($xlthumbs || $GLOBALS['default_display'] == 'xlthumbs') {
$default_display_array['xlthumbs'] = $lang['xlthumbstitle'];
}
$default_display_array['list'] = $lang['listtitle'];
$default_display_array['strip'] = $lang['striptitle'];
$page_def[] = config_add_single_select('default_perpage', $lang['userpreference_default_perpage_label'], $results_display_array, false, 420, '', true);
$page_def[] = config_add_single_select('default_display', $lang['userpreference_default_display_label'], $default_display_array, true, 420, '', true);
$page_def[] = config_add_html('</div>');
// System notifications section - used to disable system generated messages
$page_def[] = config_add_html('<h3 class="CollapsibleSectionHead collapsed">' . $lang['mymessages'] . '</h3><div id="UsergroupMessageSection" class="CollapsibleSection">');
$page_def[] = config_add_boolean_select('user_pref_show_notifications', $lang['user_pref_show_notifications'], $enable_disable_options, 300, '', true);
$page_def[] = config_add_boolean_select('user_pref_resource_notifications', $lang['userpreference_resource_notifications'], $enable_disable_options, 300, '', true);
if (in_array('a', $selected_usergroup_permissions)) {
$page_def[] = config_add_boolean_select('user_pref_system_management_notifications', $lang['userpreference_system_management_notifications'], $enable_disable_options, 300, '', true);
}
if (in_array('u', $selected_usergroup_permissions)) {
$page_def[] = config_add_boolean_select('user_pref_user_management_notifications', $lang['userpreference_user_management_notifications'], $enable_disable_options, 300, '', true);
}
if (in_array('R', $selected_usergroup_permissions)) {
$page_def[] = config_add_boolean_select('user_pref_resource_access_notifications', $lang['userpreference_resource_access_notifications'], $enable_disable_options, 300, '', true);
}
$page_def[] = config_add_html('</div>');
// Email section, only show if user has got an email address
if ($useremail != "") {
$page_def[] = config_add_html('<h3 class="CollapsibleSectionHead collapsed">' . $lang['email'] . '</h3><div id="UsergroupEmailSection" class="CollapsibleSection">');
$page_def[] = config_add_boolean_select('email_user_notifications', $lang['userpreference_email_me_label'], $enable_disable_options, 300, '', true);
$page_def[] = config_add_boolean_select('email_and_user_notifications', $lang['user_pref_email_and_user_notifications'], $enable_disable_options, 300, '', true);
$page_def[] = config_add_boolean_select('user_pref_daily_digest', $lang['user_pref_daily_digest'], $enable_disable_options, 300, '', true);
$page_def[] = config_add_html('</div>');
}
// Actions section - used to configure the alerts that appear in 'My actions'
// Create an array for the archive states
$available_archive_states = array();
$all_archive_states = array_merge(range(-2, 3), $additional_archive_states);
foreach ($all_archive_states as $archive_state_ref) {
if (in_array('e' . $archive_state_ref, $selected_usergroup_permissions)) {
$available_archive_states[$archive_state_ref] = (isset($lang["status" . $archive_state_ref])) ? $lang["status" . $archive_state_ref] : $archive_state_ref;
}
}
if ($actions_on) {
$page_def[] = config_add_html('<h3 class="CollapsibleSectionHead collapsed">' . $lang['actions_myactions'] . '</h3><div id="UsergroupActionSection" class="CollapsibleSection">');
if (in_array('R', $selected_usergroup_permissions)) {
$page_def[] = config_add_boolean_select('actions_resource_requests', $lang['actions_resource_requests'], $enable_disable_options, 300, '', true);
}
if (in_array('u', $selected_usergroup_permissions)) {
$statesjs = "if(jQuery(this).val()==1){
jQuery('#question_actions_approve_groups').slideDown();
}
else {
jQuery('#question_actions_approve_groups').slideUp();
}";
$page_def[] = config_add_boolean_select('actions_account_requests', $lang['actions_account_requests'], $enable_disable_options, 300, '', true, $statesjs);
$page_def[] = config_add_checkbox_select('actions_approve_hide_groups', $lang['actions_approve_hide_groups'], get_usergroups(true, '', true), true, 300, 1, true, null, !$actions_account_requests);
}
// Make sure all states are unchecked if they had the deprecated option $actions_resource_review set to false.
// Also only show this option if it is disabled
get_config_option(['usergroup' => $ref], 'actions_resource_review', $legacy_resource_review, true);
if (!$legacy_resource_review) {
$page_def[] = config_add_boolean_select('actions_resource_review', $lang['actions_resource_review'], $enable_disable_options, 300, '', true);
}
$page_def[] = config_add_checkbox_select('actions_notify_states', $lang['actions_notify_states'], $available_archive_states, true, 300, 1, true, null);
$rtypes = get_resource_types();
foreach ($rtypes as $rtype) {
$actionrestypes[$rtype["ref"]] = $rtype["name"];
}
$page_def[] = config_add_checkbox_select('actions_resource_types_hide', $lang['actions_resource_types_hide'], $actionrestypes, true, 300, 1, true, null);
$page_def[] = config_add_boolean_select('actions_modal', $lang['actions_modal'], $enable_disable_options, 300, '', true);
$page_def[] = "AFTER_ACTIONS_MARKER"; // Added so that hook add_user_preference_page_def can locate this position in array
$page_def[] = config_add_html('</div>');
// End of actions section
}
// Browse Bar section
$page_def[] = config_add_html('<h3 class="CollapsibleSectionHead collapsed">' . $lang['systemconfig_browse_bar_section'] . '</h3><div id="UsergroupFeaturedCollectionSection" class="CollapsibleSection">');
$page_def[] = config_add_boolean_select('browse_bar', $lang['systemconfig_browse_bar_enable'], $yes_no_options, 420, '', true);
$page_def[] = config_add_boolean_select('browse_bar_workflow', $lang['systemconfig_browse_bar_workflow'], $yes_no_options, 420, '', true);
$page_def[] = config_add_html('</div>');
// Featured Collection section
$page_def[] = config_add_html('<h3 class="CollapsibleSectionHead collapsed">' . $lang['systemconfig_featured_collections'] . '</h3><div id="UsergroupFeaturedCollectionSection" class="CollapsibleSection">');
$page_def[] = config_add_boolean_select('enable_themes', $lang['systemconfig_enable_themes'], $yes_no_options, 420, '', true);
$page_def[] = config_add_boolean_select('themes_simple_view', $lang['systemconfig_themes_simple_view'], $yes_no_options, 420, '', true);
$page_def[] = config_add_html('</div>');
}
// Process autosaving requests
// Note: $page_def must be defined by now in order to make sure we only save options that we've defined
if ('true' === getval('ajax', '') && 'true' === getval('autosave', '')) {
$response['success'] = true;
$response['message'] = '';
$autosave_option_name = getval('autosave_option_name', '');
$autosave_option_value = getval('autosave_option_value', '');
// Search for the option name within our defined (allowed) options
// if it is not there, error and don't allow saving it
$page_def_option_index = array_search($autosave_option_name, array_column($page_def, 1));
if (false === $page_def_option_index) {
$response['success'] = false;
$response['message'] = $lang['systemconfig_option_not_allowed_error'];
echo json_encode($response);
exit();
}
if (!set_usergroup_config_option($ref, $autosave_option_name, $autosave_option_value)) {
$response['success'] = false;
}
echo json_encode($response);
exit();
}
include "../../include/header.php";
?>
<div id="UsergroupConfig">
<h1><?php echo escape($lang["page-title_usergroup_config"] . ' - ' . $group["name"]); ?></h1>
<?php render_config_filter_by_search(getval("filter", ""), getval("only_modified", "no")); ?>
<div class="CollapsibleSections">
<?php
$links_trail = array(
array(
'title' => $lang["systemsetup"],
'href' => $baseurl_short . "pages/admin/admin_home.php",
'menu' => true
),
array(
'title' => $lang["page-title_user_group_management"],
'href' => $baseurl_short . "pages/admin/admin_group_management.php"
),
array(
'title' => $lang["page-title_user_group_management_edit"],
'href' => generateURL("{$baseurl_short}pages/admin/admin_group_management_edit.php", $url_params),
),
array(
'title' => $lang["page-title_usergroup_config"] . " - " . escape($group["name"])
)
);
renderBreadcrumbs($links_trail);
$page_def = config_filter_by_search($page_def, ['usergroup' => $ref], getval("filter", ""), getval("only_modified", "no"));
config_remove_user_preferences($page_def);
// Get user group config after page loads, header.php etc.
process_config_options(array('usergroup' => $ref));
config_generate_html($page_def);
config_generate_AutoSaveConfigOption_function(generateURL($baseurl . "/pages/admin/admin_group_config_edit.php", $url_params));
// Put back system / user preferences to avoid applying user group config for admin
process_config_options(array());
process_config_options(array('usergroup' => $usergroup));
process_config_options(array('user' => $userref));
?>
</div>
</div>
<script>
registerCollapsibleSections();
</script>
<?php
include "../../include/footer.php";

View File

@@ -0,0 +1,347 @@
<?php
include "../../include/boot.php";
include "../../include/authenticate.php";
if (!checkperm("a")) {
exit("Permission denied.");
}
include "../../include/header.php";
$find = getval("find", "");
$filter_by_parent = getval("filterbyparent", "");
$filter_by_permissions = getval("filterbypermissions", "");
$sql_permission_filter_params = array();
if ($filter_by_permissions != "") {
foreach (explode(",", $filter_by_permissions) as $permission) {
$permission = trim($permission);
if ($permission == "") {
continue;
}
if (isset($sql_permission_filter)) {
$sql_permission_filter .= " and
";
} else {
$sql_permission_filter = "(";
}
# The filter will include usergroups with this permission either at the usergroup level or (if permissions are inherited) at the parent usergroup level
$sql_permission_filter .= " ( FIND_IN_SET(binary ?,usergroup.permissions) OR ( FIND_IN_SET('permissions', usergroup.inherit_flags) AND FIND_IN_SET(binary ?,parentusergroup.permissions) ) ) ";
$sql_permission_filter_params = array_merge($sql_permission_filter_params, array("s",$permission, "s",$permission));
}
$sql_permission_filter .= ")";
}
$offset = getval("offset", 0, true);
$order_by = getval("orderby", "name");
$sql_where = "";
$sql_params = array();
if ($find != "") {
$sql_where = " and (usergroup.ref like ? or usergroup.name like ? or parentusergroup.name like ?)";
$sql_params = array_merge($sql_params, array("s", "%" . $find . "%", "s", "%" . $find . "%", "s", "%" . $find . "%"));
}
if ($filter_by_parent != "") {
$sql_where .= " and parentusergroup.ref = ?";
$sql_params = array_merge($sql_params, array("i", $filter_by_parent));
}
if ($filter_by_permissions != "") {
$sql_where .= " and $sql_permission_filter";
$sql_params = array_merge($sql_params, $sql_permission_filter_params);
}
$offset = getval("offset", 0, true);
$order_by = getval("orderby", "name");
if (!in_array($order_by, array("ref","name","users","pname","ref desc","name desc","users desc","pname desc"))) {
$order_by = "name";
}
$groups = ps_query(
"
select
usergroup.ref as ref,
usergroup.name as name,
count(user.ref) as users,
if (usergroup.parent is not null and usergroup.parent<>'' and usergroup.parent<>'0' and (parentusergroup.name is null or parentusergroup.name=''),usergroup.ref,parentusergroup.ref) as pref,
if (usergroup.parent is not null and usergroup.parent<>'' and usergroup.parent<>'0' and (parentusergroup.name is null or parentusergroup.name=''),'orphaned',parentusergroup.name) as pname,
(usergroup.parent is not null and usergroup.parent<>'' and usergroup.parent<>'0' and (parentusergroup.name is null or parentusergroup.name='')) as orphaned
from
usergroup
left outer join usergroup parentusergroup
on
usergroup.parent=parentusergroup.ref
left outer join user
on
usergroup.ref=user.usergroup where true" . $sql_where .
" group by
usergroup.ref
order by {$order_by}",
$sql_params
);
# pager
$per_page = $default_perpage_list;
$results = count($groups);
$totalpages = ceil($results / $per_page);
$curpage = floor($offset / $per_page) + 1;
$url = "admin_group_management.php";
$url_params = array("find" => $find,"orderby" => $order_by);
function addColumnHeader($orderName, $labelKey)
{
global $baseurl, $order_by, $filter_by_parent, $filter_by_permissions, $find, $lang;
if ($order_by == $orderName) {
$image = '<span class="ASC"></span>';
} elseif ($order_by == $orderName . ' desc') {
$image = '<span class="DESC"></span>';
} else {
$image = '';
}
?>
<th>
<a href="<?php echo $baseurl ?>/pages/admin/admin_group_management.php?<?php
if ($find != "") {
?>&find=<?php echo escape($find);
}
if ($filter_by_parent != "") {
?>&filterbyparent=<?php echo escape($filter_by_parent);
}
if ($filter_by_permissions != "") {
?>&filterbypermissions=<?php echo escape($filter_by_permissions);
}
?>&orderby=<?php echo $orderName . ($order_by == $orderName ? '+desc' : ''); ?>"
onClick="return CentralSpaceLoad(this);"><?php echo escape($lang[$labelKey]) . $image ?>
</a>
</th>
<?php
}
?>
<div class="BasicsBox">
<h1><?php echo escape($lang["page-title_user_group_management"]); ?></h1>
<?php
$links_trail = array(
array(
'title' => $lang["systemsetup"],
'href' => $baseurl_short . "pages/admin/admin_home.php",
'menu' => true
),
array(
'title' => $lang["page-title_user_group_management"],
)
);
renderBreadcrumbs($links_trail);
?>
<p>
<?php
echo escape($lang['page-subtitle_user_group_management']);
render_help_link("systemadmin/creating-user-groups");
?>
</p>
<div class="TopInpageNav">
<div class="TopInpageNavLeft">
<div class="InpageNavLeftBlock">&nbsp;</div>
</div>
<?php pager(false); ?>
<div class="clearerleft"></div>
</div>
<div class="Listview">
<table class="ListviewStyle">
<tr class="ListviewTitleStyle">
<?php addColumnHeader("ref", "property-reference"); ?>
<?php addColumnHeader("name", "property-user_group"); ?>
<?php addColumnHeader("users", "users"); ?>
<?php addColumnHeader("pname", "property-user_group_parent"); ?>
<th>
<div class="ListTools"><?php echo escape($lang["tools"]); ?></div>
</th>
</tr>
<?php
$url_params = array(
"offset" => $offset ?? '',
"orderby" => $order_by ?? '',
"filterbyparent" => $filter_by_parent ?? '',
"find" => $find ?? '',
"filterbypermissions" => $filter_by_permissions ?? ''
);
for ($n = $offset; (($n < count($groups)) && ($n < ($offset + $per_page))); $n++) {
$edit_url = generateURL($baseurl_short . "pages/admin/admin_group_management_edit.php", array_merge(["ref" => $groups[$n]["ref"]], $url_params));
$users_url = generateURL($baseurl_short . "pages/team/team_user.php", ["group" => $groups[$n]["ref"], "backlink" => generateURL($baseurl_short . "pages/admin/admin_group_management.php", $url_params)]);
?>
<tr>
<td>
<a href="<?php echo $edit_url; ?>" onClick="return CentralSpaceLoad(this,true);">
<?php echo str_highlight($groups[$n]["ref"], $find, STR_HIGHLIGHT_SIMPLE); ?>
</a>
</td>
<td>
<a href="<?php echo $edit_url; ?>" onClick="return CentralSpaceLoad(this,true);">
<?php echo strip_tags_and_attributes(str_highlight($groups[$n]["name"], $find, STR_HIGHLIGHT_SIMPLE)); ?>
</a>
</td>
<td>
<a href="<?php echo $users_url; ?>" onClick="return CentralSpaceLoad(this,true);">
<?php echo $groups[$n]["users"]; ?>
</a>
</td>
<td>
<?php if ($groups[$n]["orphaned"]) { ?>
<a href="<?php echo $edit_url; ?>" onClick="return CentralSpaceLoad(this,true);">
&lt;<?php echo escape($groups[$n]["pname"]) ;?>&gt;
</a>
<?php } else { ?>
<a
href="<?php echo $baseurl_short; ?>pages/admin/admin_group_management.php?filterbyparent=<?php echo $groups[$n]["pref"]; ?>"
onClick="return CentralSpaceLoad(this,false);">
<?php echo strip_tags_and_attributes(str_highlight($groups[$n]["pname"], $find, STR_HIGHLIGHT_SIMPLE)); ?>
</a>
<?php } ?>
</td>
<td>
<div class="ListTools">
<a href="<?php echo $edit_url; ?>" onClick="return CentralSpaceLoad(this,true);">
<i class="fas fa-edit"></i>&nbsp;<?php echo escape($lang["action-edit"]); ?>
</a>
&nbsp;
<a href="<?php echo $users_url; ?>" onClick="return CentralSpaceLoad(this,true);">
<i class="fas fa-users"></i>&nbsp;<?php echo escape($lang["users"]); ?>
</a>
</div>
</td>
</tr>
<?php
}
?>
</table>
</div>
<div class="BottomInpageNav">
<?php
$url = "admin_group_management.php";
$url_params = array("find" => $find,"orderby" => $order_by);
pager(false);
?>
</div>
</div><!-- end of BasicsBox -->
<div class="BasicsBox">
<form method="post" action="<?php echo $baseurl_short?>pages/admin/admin_group_management.php" onSubmit="return CentralSpacePost(this,false);">
<?php generateFormToken("admin_group_management_find"); ?>
<input type="hidden" name="orderby" value="<?php echo $order_by; ?>">
<div class="Question">
<label for="find"><?php echo escape($lang["property-search_filter"]); ?></label>
<input name="find" type="text" class="medwidth" value="<?php echo escape($find); ?>">
<input name="save" type="submit" value="<?php echo escape($lang["searchbutton"]); ?>">
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="filterbyparent"><?php echo escape($lang['action-title_filter_by_parent_group']); ?></label>
<div class="tickset">
<select name="filterbyparent" class="medwidth" onchange="this.form.submit();">
<option value="">
<?php if ($filter_by_parent != "") {
echo escape($lang["removethisfilter"]);
} ?>
</option>
<?php
$groups = ps_query("
SELECT distinct
parentusergroup.ref AS ref,
parentusergroup.name AS name
FROM
usergroup
LEFT OUTER JOIN usergroup parentusergroup
ON
usergroup.parent=parentusergroup.ref
WHERE parentusergroup.ref IS NOT null
ORDER BY usergroup.name");
foreach ($groups as $group) { ?>
<option
<?php if ($filter_by_parent != "" && $filter_by_parent == $group['ref']) { ?>
selected="true"
<?php } ?>
value="<?php echo $group['ref']; ?>">
<?php echo $group['name']; ?>
</option>
<?php
} ?>
</select>
</div>
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="filterbypermissions"><?php echo escape($lang["action-title_filter_by_permissions"]); ?></label>
<input name="filterbypermissions" type="text" class="medwidth" value="<?php echo escape($filter_by_permissions); ?>">
<input name="save" type="submit" value="<?php echo escape($lang["action-title_apply"]); ?>">
<div class="clearerleft"></div>
</div>
<div class="FormHelp">
<div class="FormHelpInner"><?php echo escape($lang["fieldhelp-permissions_filter"]); ?></div>
</div>
<?php if ($find != "" || $filter_by_permissions != "" || $filter_by_parent != "") { ?>
<div class="QuestionSubmit">
<input
name="buttonsave"
type="submit"
onclick="CentralSpaceLoad('admin_group_management.php?orderby=<?php echo $order_by; ?>',false);"
value="<?php echo escape($lang["clearall"]); ?>"
>
</div>
<?php } ?>
</form>
</div>
<div class="BasicsBox">
<form method="post" action="<?php echo $baseurl_short; ?>pages/admin/admin_group_management_edit.php" onSubmit="return CentralSpacePost(this,false);">
<?php generateFormToken("admin_group_management"); ?>
<div class="Question">
<label for="name"><?php echo escape($lang['action-title_create_user_group_called']); ?></label>
<div class="tickset">
<div class="Inline">
<input name="newusergroupname" type="text" value="" class="shrtwidth">
</div>
<div class="Inline">
<input name="Submit" type="submit" value="<?php echo escape($lang["create"]); ?>" onclick="return (this.form.elements[0].value!='');">
</div>
</div>
<div class="clearerleft"></div>
</div>
<?php if ($offset) { ?>
<input type="hidden" name="offset" value="<?php echo $offset; ?>">
<?php
}
if ($order_by) { ?>
<input type="hidden" name="order_by" value="<?php echo $order_by; ?>">
<?php
}
?>
</form>
</div>
<?php
include "../../include/footer.php";
?>

View File

@@ -0,0 +1,550 @@
<?php
include "../../include/boot.php";
include "../../include/authenticate.php";
if (!checkperm("a")) {
exit("Permission denied.");
}
$offset = getval("offset", 0, true);
$order_by = getval("orderby", "");
$filter_by_parent = getval("filterbyparent", "");
$find = getval("find", "");
$filter_by_permissions = getval("filterbypermissions", "");
$url_params =
($offset ? "&offset={$offset}" : "") .
($order_by ? "&orderby={$order_by}" : "") .
($filter_by_parent ? "&filterbyparent={$filter_by_parent}" : "") .
($find ? "&find={$find}" : "") .
($filter_by_permissions ? "&filterbypermissions={$filter_by_permissions}" : "");
# create new record from callback
$new_group_name = getval("newusergroupname", "");
if ($new_group_name != "" && enforcePostRequest(false)) {
$setoptions = array("request_mode" => 1, "name" => $new_group_name);
$ref = save_usergroup(0, $setoptions);
log_activity(null, LOG_CODE_CREATED, null, 'usergroup', null, $ref);
log_activity(null, LOG_CODE_CREATED, $new_group_name, 'usergroup', 'name', $ref, null, '');
log_activity(null, LOG_CODE_CREATED, '1', 'usergroup', 'request_mode', $ref, null, '');
redirect($baseurl_short . "pages/admin/admin_group_management_edit.php?ref={$ref}{$url_params}"); // redirect to prevent repost and expose of form data
exit;
}
$ref = (int) getval('ref', 0, true, 'is_int_loose');
if ($ref === 0) {
exit('No user group ref supplied.');
}
if (!ps_value("select ref as value from usergroup where ref = ?", array("i", $ref), false)) {
redirect("{$baseurl_short}pages/admin/admin_group_management.php?{$url_params}"); // fail safe by returning to the user group management page if duff ref passed
exit;
}
$dependant_user_count = ps_value("select count(*) as value from user where usergroup = ?", array("i", $ref), 0);
$dependant_groups = ps_value("select count(*) as value from usergroup where parent = ?", array("i", $ref), 0);
$has_dependants = $dependant_user_count + $dependant_groups > 0;
if (!$has_dependants && getval("deleteme", false) && enforcePostRequest(false)) {
delete_usergroup($ref);
redirect("{$baseurl_short}pages/admin/admin_group_management.php?{$url_params}"); // return to the user group management page
exit;
}
$record = get_usergroup($ref);
if (getval("save", false) && enforcePostRequest(false)) {
$error = false;
$logo_dir = "{$storagedir}/admin/groupheaderimg/";
// Remove group specific logo
if (isset($_POST['removelogo'])) {
$logo_extension = ps_value("select group_specific_logo as value from usergroup where ref = ?", array("i", $ref), false);
$logo_filename = "{$logo_dir}/group{$ref}.{$logo_extension}";
if ($logo_extension && file_exists($logo_filename) && unlink($logo_filename)) {
$logo_extension = "";
} else {
unset($logo_extension);
}
}
// Remove group specific logo - dark
if (isset($_POST['removelogodark'])) {
$logo_dark_extension = ps_value("select group_specific_logo_dark as value from usergroup where ref = ?", array("i", $ref), false);
$logo_dark_filename = "{$logo_dir}/group{$ref}_dark.{$logo_dark_extension}";
if ($logo_dark_extension && file_exists($logo_dark_filename) && unlink($logo_dark_filename)) {
$logo_dark_extension = "";
} else {
unset($logo_dark_extension);
}
}
// Upload group specific logo
if (isset($_FILES['grouplogo']['tmp_name']) && is_uploaded_file($_FILES['grouplogo']['tmp_name'])) {
if (!(file_exists($logo_dir) && is_dir($logo_dir))) {
mkdir($logo_dir, 0777, true);
}
$logo_extension = parse_filename_extension($_FILES['grouplogo']['name']);
$process_file_upload = process_file_upload(
$_FILES['grouplogo'],
new SplFileInfo("{$logo_dir}/group{$ref}.{$logo_extension}"),
['allow_extensions' => ['jpg', 'jpeg', 'gif', 'svg', 'png']]
);
if (!$process_file_upload['success']) {
unset($logo_extension);
$error = true;
$onload_message = [
'title' => $lang['error'],
'text' => match ($process_file_upload['error']) {
ProcessFileUploadErrorCondition::InvalidExtension => str_replace(
'%EXTENSIONS',
'JPG, GIF, SVG, PNG',
$lang['allowedextensions-extensions']
),
default => $process_file_upload['error']->i18n($lang),
},
];
}
}
// Upload group specific logo - dark
if (isset($_FILES['grouplogodark']['tmp_name']) && is_uploaded_file($_FILES['grouplogodark']['tmp_name'])) {
if (!(file_exists($logo_dir) && is_dir($logo_dir))) {
mkdir($logo_dir, 0777, true);
}
$logo_dark_extension = parse_filename_extension($_FILES['grouplogodark']['name']);
$process_file_upload = process_file_upload(
$_FILES['grouplogodark'],
new SplFileInfo("{$logo_dir}/group{$ref}_dark.{$logo_dark_extension}"),
['allow_extensions' => ['jpg', 'jpeg', 'gif', 'svg', 'png']]
);
if (!$process_file_upload['success']) {
unset($logo_dark_extension);
$error = true;
$onload_message = [
'title' => $lang['error'],
'text' => match ($process_file_upload['error']) {
ProcessFileUploadErrorCondition::InvalidExtension => str_replace(
'%EXTENSIONS',
'JPG, GIF, SVG, PNG',
$lang['allowedextensions-extensions']
),
default => $process_file_upload['error']->i18n($lang),
},
];
}
}
if (isset($logo_extension)) {
ps_query("UPDATE usergroup SET group_specific_logo = ? WHERE ref = ?", array("s", $logo_extension, "i", $ref));
log_activity(null, null, null, 'usergroup', 'group_specific_logo', $ref);
clear_query_cache('usergroup');
}
if (isset($logo_dark_extension)) {
ps_query("UPDATE usergroup SET group_specific_logo_dark = ? WHERE ref = ?", array("s", $logo_dark_extension, "i", $ref));
log_activity(null, null, null, 'usergroup', 'group_specific_logo_dark', $ref);
}
$update_sql_params = array();
foreach (
array("name","permissions","parent","search_filter","search_filter_id","edit_filter","edit_filter_id","derestrict_filter",
"derestrict_filter_id","resource_defaults","config_options","welcome_message","ip_restrict","request_mode",
"allow_registration_selection","inherit_flags", "download_limit","download_log_days") as $column
) {
if ($execution_lockout && $column == "config_options") {
# Do not allow config overrides to be changed from UI if $execution_lockout is set.
continue;
}
if (in_array($column, array("allow_registration_selection"))) {
$groupoptions[$column] = getval($column, "0") ? "1" : "0";
} elseif ($column == "inherit_flags" && getval($column, [], false, 'is_array') !== []) {
$groupoptions[$column] = implode(',', getval($column, [], false, 'is_array'));
} elseif (in_array($column, array("parent","download_limit","download_log_days","search_filter_id","edit_filter_id","derestrict_filter_id"))) {
$groupoptions[$column] = getval($column, 0, true);
} elseif ($column == "request_mode") {
$groupoptions[$column] = getval($column, 1, true);
} else {
$groupoptions[$column] = getval($column, "");
}
}
foreach ($groupoptions as $column_name => $column_value) {
log_activity(null, LOG_CODE_EDITED, $column_value, 'usergroup', $column_name, $ref);
}
save_usergroup($ref, $groupoptions);
hook("usergroup_edit_add_form_save", "", array($ref));
if (!$error) {
redirect("{$baseurl_short}pages/admin/admin_group_management.php?{$url_params}"); // return to the user group management page
exit;
}
}
include "../../include/header.php";
$url_params_edit = array(
"ref" => $ref,
"offset" => $offset,
"order_by" => $order_by,
"filterbyparent" => $filter_by_parent,
"find" => $find,
"filterbypermissions" => $filter_by_permissions
);
?>
<form
method="post"
enctype="multipart/form-data"
action="<?php echo generateURL($baseurl_short . 'pages/admin/admin_group_management_edit.php', $url_params_edit);?>"
id="mainform"
class="FormWide">
<?php generateFormToken("mainform"); ?>
<div class="BasicsBox">
<h1><?php echo escape($lang["page-title_user_group_management_edit"]); ?></h1>
<?php
$links_trail = array(
array(
'title' => $lang["systemsetup"],
'href' => $baseurl_short . "pages/admin/admin_home.php",
'menu' => true
),
array(
'title' => $lang["page-title_user_group_management"],
'href' => $baseurl_short . "pages/admin/admin_group_management.php?" . $url_params
),
array(
'title' => $lang["page-title_user_group_management_edit"]
)
);
renderBreadcrumbs($links_trail);
?>
<p>
<?php
echo escape($lang['page-subtitle_user_group_management_edit']);
render_help_link("systemadmin/creating-user-groups");
?>
</p>
<input type="hidden" name="save" value="1">
<div class="Question">
<label for="reference"><?php echo escape($lang["property-reference"]); ?></label>
<div class="Fixed"><?php echo (int)$ref; ?></div>
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="name"><?php echo escape($lang["property-name"]); ?></label>
<input name="name" type="text" class="stdwidth" value="<?php echo escape($record['name']); ?>">
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="dependants"><?php echo escape($lang["property-contains"]); ?></label>
<div class="Fixed">
<?php echo $dependant_user_count; ?>&nbsp;<?php echo escape($lang['users']); ?>, <?php echo $dependant_groups; ?>&nbsp;<?php echo escape($lang['property-groups']); ?>
</div>
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="permissions"><?php echo escape($lang["property-permissions"]); ?></label>
<?php if ($record['parent']) { ?>
<label for="permissions_inherit"><?php echo escape($lang["property-permissions_inherit"]); ?></label>
<input id="permissions_inherit" name="inherit_flags[]" type="checkbox" value="permissions" onClick="if(jQuery('#permissions_inherit').is(':checked')){jQuery('#permissions_area').slideUp();}else{jQuery('#permissions_area').slideDown();}" <?php echo (in_array("permissions", $record['inherit'])) ? "checked" : ''; ?>>
<div class="clearerleft"></div>
<?php
} ?>
<div id ="permissions_area" <?php echo (in_array("permissions", $record['inherit'])) ? 'style="display:none;"' : ''; ?>>
<input type="button" class="stdwidth<?php echo $record['parent'] ? ' label-spacer' : ''; ?>" onclick="return CentralSpaceLoad('<?php echo $baseurl_short; ?>pages/admin/admin_group_permissions.php?ref=<?php echo escape($ref . $url_params); ?>',true);" value="<?php echo escape($lang["launchpermissionsmanager"]); ?>"></input>
<div class="clearerleft"></div>
<label></label>
<textarea name="permissions" class="stdwidth" rows="5" cols="50"><?php echo escape((string) $record['permissions']); ?></textarea>
<div class="clearerleft"></div>
</div> <!-- End of permissions_area -->
</div>
<div class="Question">
<label for="group_override_config"><?php echo escape($lang["fieldtitle-usergroup_config"]); ?></label>
<?php if ($record['parent']) { ?>
<label for="group_override_config_inherit"><?php echo escape($lang["property-group_preferences_inherit"]); ?></label>
<input id="group_override_config_inherit" name="inherit_flags[]" type="checkbox" value="preferences" onClick="if(jQuery('#group_override_config_inherit').is(':checked')){jQuery('#group_override_config_area').slideUp();}else{jQuery('#group_override_config_area').slideDown();}" <?php echo (in_array("preferences", $record['inherit'])) ? "checked" : ''; ?>>
<div class="clearerleft"></div>
<?php
} ?>
<div id ="group_override_config_area" <?php echo (in_array("preferences", $record['inherit'])) ? 'style="display:none;"' : ''; ?>>
<input type="button" class="stdwidth<?php echo $record['parent'] ? ' label-spacer' : ''; ?>" onclick="return CentralSpaceLoad('<?php echo $baseurl_short; ?>pages/admin/admin_group_config_edit.php?ref=<?php echo escape($ref . $url_params); ?>',true);" value="<?php echo escape($lang["editgroupconfigoverrides"]); ?>"></input>
<div class="clearerleft"></div>
</div>
</div>
<div class="Question">
<label for="parent"><?php echo escape($lang["property-parent"]); ?></label>
<select name="parent" class="stdwidth">
<option value="0" >
<?php echo ($record['parent']) ? escape($lang["property-user_group_remove_parent"]) : ''; ?>
</option>
<?php
$groups = get_usergroups();
foreach ($groups as $group) {
// Not allowed to be the parent of itself
if ($group['ref'] == $ref) {
continue;
}
?>
<option <?php echo ($record['parent'] == $group['ref']) ? 'selected="true"' : ''; ?> value="<?php echo $group['ref']; ?>">
<?php echo $group['name']; ?>
</option>
<?php
}
?>
</select>
<div class="clearerleft"></div>
</div>
</div>
<h2 class="CollapsibleSectionHead collapsed"><?php echo escape($lang["fieldtitle-advanced_options"]); ?></h2>
<div class="CollapsibleSection" style="display:none;">
<p><?php echo strip_tags_and_attributes($lang["action-title_see_wiki_for_user_group_advanced_options"], ["a"], ["href"]); ?></p>
<?php
$filters = get_filters("name", "ASC");
$filters[] = array("ref" => -1, "name" => $lang["disabled"]);
// Show filter selector if already migrated or no filter has been set
// Add the option to indicate filter migration failed
?>
<div class="Question">
<label for="search_filter_id"><?php echo escape($lang["property-search_filter"]); ?></label>
<select name="search_filter_id" class="stdwidth">
<?php
echo "<option value='0' >" . escape($record['search_filter_id'] ? $lang["filter_none"] : $lang["select"]) . "</option>";
foreach ($filters as $filter) {
echo "<option value='" . $filter['ref'] . "' " . ($record['search_filter_id'] == $filter['ref'] ? " selected " : "") . ">" . i18n_get_translated($filter['name']) . "</option>";
}
?>
</select>
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="edit_filter_id"><?php echo escape($lang["property-edit_filter"]); ?></label>
<select name="edit_filter_id" class="stdwidth">
<?php
echo "<option value='0' >" . escape($record['edit_filter_id'] ? $lang["filter_none"] : $lang["select"]) . "</option>";
foreach ($filters as $filter) {
echo "<option value='" . $filter['ref'] . "' " . ($record['edit_filter_id'] == $filter['ref'] ? " selected " : "") . ">" . i18n_get_translated($filter['name']) . "</option>";
}
?>
</select>
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="derestrict_filter_id"><?php echo escape($lang["fieldtitle-derestrict_filter"]); ?></label>
<select name="derestrict_filter_id" class="stdwidth">
<?php
echo "<option value='0' >" . escape($record['derestrict_filter_id'] ? $lang["filter_none"] : $lang["select"]) . "</option>";
foreach ($filters as $filter) {
echo "<option value='" . $filter['ref'] . "' " . ($record['derestrict_filter_id'] == $filter['ref'] ? " selected " : "") . ">" . i18n_get_translated($filter['name']) . "</option>";
}
?>
</select>
<div class="clearerleft"></div>
<div class="FormHelp">
<div class="FormHelpInner"><?php echo escape($lang["information-derestrict_filter"]); ?></div>
</div>
</div>
<div class="Question">
<label for="download_limit"><?php echo escape($lang["group_download_limit_title"]); ?></label>
<input name="download_limit" type="number" class="vshrtwidth" value="<?php echo escape((string)$record['download_limit']); ?>">
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="download_log_days"><?php echo escape($lang["group_download_limit_period"]); ?></label>
<input name="download_log_days" type="number" class="vshrtwidth" value="<?php echo escape((string)$record['download_log_days']); ?>">
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="resource_defaults"><?php echo escape($lang["property-resource_defaults"]); ?></label>
<textarea name="resource_defaults" class="stdwidth" rows="3" cols="50"><?php echo $record['resource_defaults']; ?></textarea>
<div class="clearerleft"></div>
</div>
<?php if (!$execution_lockout) { ?>
<div class="Question">
<label for="config_options"><?php echo escape($lang["property-override_config_options"]); ?></label>
<?php if ($record['parent']) { ?>
<label for="config_inherit"><?php echo escape($lang["property-config_inherit"]); ?></label>
<input id="config_inherit" name="inherit_flags[]" type="checkbox" value="config_options" onClick="if(jQuery('#config_inherit').is(':checked')){jQuery('#config_area').slideUp();}else{jQuery('#config_area').slideDown();}" <?php echo (in_array("config_options", $record['inherit'])) ? "checked" : ''; ?>>
<div class="clearerleft"></div>
<?php
} ?>
<div id ="config_area" <?php echo (in_array("config_options", $record['inherit'])) ? "style=display:none;" : ''; ?>>
<textarea name="config_options" id="configOptionsBox" class="stdwidth<?php echo $record['parent'] ? ' label-spacer' : ''; ?>" rows="12" cols="50" ><?php echo $record['config_options']; ?></textarea>
<div class="clearerleft"></div>
</div>
</div>
<?php } ?>
<div class="Question">
<label for="welcome_message"><?php echo escape($lang["property-email_welcome_message"]); ?></label>
<textarea name="welcome_message" class="stdwidth" rows="12" cols="50"><?php echo $record['welcome_message']; ?></textarea>
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="ip_restrict"><?php echo escape($lang["property-ip_address_restriction"]); ?></label>
<input name="ip_restrict" type="text" class="stdwidth" value="<?php echo $record['ip_restrict']; ?>">
<div class="clearerleft"></div>
<div class="FormHelp">
<div class="FormHelpInner"><?php echo escape($lang["information-ip_address_restriction"]); ?></div>
</div>
</div>
<div class="Question">
<label for="request_mode"><?php echo escape($lang["property-request_mode"]); ?></label>
<select name="request_mode" class="stdwidth">
<?php for ($i = 0; $i < 2; $i++) { ?>
<option
<?php echo ($record['request_mode'] == $i) ? 'selected="true" ' : ''; ?>
value="<?php echo $i; ?>"><?php echo escape($lang["resourcerequesttype{$i}"]); ?>
</option>
<?php
}
?>
</select>
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="allow_registration_selection"><?php echo escape($lang["property-allow_registration_selection"]); ?></label>
<input
name="allow_registration_selection"
type="checkbox"
value="1"
<?php echo ($record['allow_registration_selection'] == 1) ? 'checked="checked"' : ''; ?>>
<div class="clearerleft"></div>
</div>
<?php if ($record['group_specific_logo']) {
$linkedheaderimgsrc = (isset($storageurl) ? $storageurl : $baseurl . "/filestore") . "/admin/groupheaderimg/group" . $record['ref'] . "." . $record["group_specific_logo"];
?>
<div class="Question">
<label for="grouplogocurrent"><?php echo escape($lang["fieldtitle-group_logo"]); ?></label>
<img src="<?php echo $linkedheaderimgsrc;?>" alt="Group logo" height='126'>
</div>
<div class="Question">
<label for="grouplogo"><?php echo escape($lang["fieldtitle-group_logo_replace"]); ?></label>
<input name="grouplogo" type="file">
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="removelogo"><?php echo escape($lang["action-title_remove_user_group_logo"]); ?></label>
<input name="removelogo" type="checkbox" value="1">
<div class="clearerleft"></div>
</div>
<?php } else { ?>
<div class="Question">
<label for="grouplogo"><?php echo escape($lang["fieldtitle-group_logo"]); ?></label>
<input name="grouplogo" type="file">
<div class="clearerleft"></div>
</div>
<?php } ?>
<?php if ($record['group_specific_logo_dark']) {
$linkedheaderimgsrc_dark = (isset($storageurl) ? $storageurl : $baseurl . "/filestore") . "/admin/groupheaderimg/group" . $record['ref'] . "_dark." . $record["group_specific_logo_dark"];
?>
<div class="Question">
<label for="grouplogodarkcurrent"><?php echo escape($lang["fieldtitle-group_logo_dark"]); ?></label>
<img src="<?php echo $linkedheaderimgsrc_dark;?>" alt="Group logo - Dark" height='126'>
</div>
<div class="Question">
<label for="grouplogodark"><?php echo escape($lang["fieldtitle-group_logo_dark_replace"]); ?></label>
<input name="grouplogodark" type="file">
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="removelogodark"><?php echo escape($lang["action-title_remove_user_group_logo_dark"]); ?></label>
<input name="removelogodark" type="checkbox" value="1">
<div class="clearerleft"></div>
</div>
<?php } else { ?>
<div class="Question">
<label for="grouplogodark"><?php echo escape($lang["fieldtitle-group_logo_dark"]); ?></label>
<input name="grouplogodark" type="file">
<div class="clearerleft"></div>
</div>
<?php } ?>
</div><!-- end of advanced options -->
<div class="BasicsBox">
<div class="Question">
<label for="delete_user_group"><?php echo escape($lang["fieldtitle-tick_to_delete_group"]); ?></label>
<input
id="delete_user_group"
name="deleteme"
type="checkbox"
value="yes"
<?php echo ($has_dependants) ? 'disabled="disabled"' : ''; ?>>
<div class="clearerleft"></div>
<div class="FormHelp">
<div class="FormHelpInner"><?php echo escape($lang["fieldhelp-tick_to_delete_group"]); ?></div>
</div>
</div>
<div class="QuestionSubmit">
<input name="buttonsave" type="submit" value="<?php echo escape($lang["save"]); ?>">
</div>
</div>
</form>
<script>
registerCollapsibleSections();
jQuery('#delete_user_group').click(function () {
<?php
$language_specific_results = ps_value('SELECT count(*) AS `value` FROM site_text WHERE specific_to_group = ?', array("i",$ref), 0);
$alert_message = str_replace('[recordscount]', $language_specific_results, $lang["delete_user_group_checkbox_alert_message"]);
?>
if (<?php echo $language_specific_results; ?> > 0 && jQuery('#delete_user_group').is(':checked')) {
alert("<?php echo escape($alert_message); ?>");
}
});
</script>
<?php
include "../../include/footer.php";

View File

@@ -0,0 +1,555 @@
<?php
include "../../include/boot.php";
include "../../include/authenticate.php";
include "../../include/ajax_functions.php";
if (!checkperm("a")) {
exit("Permission denied.");
}
$ref = getval("ref", "");
$offset = getval("offset", 0, true);
$order_by = getval("orderby", "");
$filter_by_parent = getval("filterbyparent", "");
$find = getval("find", "");
$filter_by_permissions = getval("filterbypermissions", "");
$copy_from = getval("copyfrom", "");
$save = getval('save', '');
$url_params = [
'ref' => $ref,
];
if ($offset) {
$url_params['offset'] = $offset;
}
if ($order_by) {
$url_params['orderby'] = $order_by;
}
if ($filter_by_parent) {
$url_params['filterbyparent'] = $filter_by_parent;
}
if ($find) {
$url_params['find'] = $find;
}
if ($filter_by_permissions) {
$url_params['filterbypermissions'] = $filter_by_permissions;
}
$admin_group_permissions_url = generateURL("{$baseurl_short}pages/admin/admin_group_permissions.php", $url_params);
if ($save !== '' && $copy_from === '' && enforcePostRequest(getval('ajax', '') == 'true')) {
$group = get_usergroup($ref);
if (
$group !== false
&& isset($group['inherit'])
&& is_array($group['inherit'])
&& in_array('permissions', $group['inherit'])
) {
ajax_unauthorized();
}
$permissions = trim_array(explode(',', (string) $group['permissions']));
$permissions_to_add = $permissions_to_remove = [];
$processing_permissions = $_POST['permissions'] ?? [];
foreach ($processing_permissions as $perm) {
if (!isset($perm['permission'], $perm['reverse'], $perm['checked'])) {
ajax_send_response(400, ajax_response_fail(ajax_build_message($lang['error_invalid_input'])));
}
$permission = $perm['permission'];
$reverse = $perm['reverse'] == 1;
$checked = $perm['checked'] === 'true';
if (
// Normal permissions
(!$reverse && $checked)
// Negative permissions
|| ($reverse && !$checked)
) {
$permissions_to_add[] = base64_decode($permission);
} else {
$permissions_to_remove[] = base64_decode($permission);
}
}
$perms = array_values(array_unique(
array_diff(
array_merge($permissions, $permissions_to_add),
$permissions_to_remove
)
));
$perms_csv = join(',', $perms);
save_usergroup($ref, array('permissions' => $perms_csv));
log_activity(null, LOG_CODE_EDITED, $perms_csv, 'usergroup', 'permissions', $ref, null, null, null, true);
ajax_send_response(200, ajax_response_ok_no_data());
} elseif ($save !== '' && $copy_from !== '' && enforcePostRequest(getval('ajax', '') == 'true')) {
copy_usergroup_permissions($copy_from, $ref);
}
$group = get_usergroup($ref);
if (isset($group['inherit']) && is_array($group['inherit']) && in_array("permissions", $group['inherit'])) {
exit($lang["error-permissiondenied"]);
}
$permissions = trim_array(explode(",", (string)$group["permissions"]));
$permissions_done = array();
include "../../include/header.php";
?>
<div class="BasicsBox">
<h1><?php echo escape($lang["page-title_user_group_permissions_edit"] . " - " . $group["name"]); ?></h1>
<?php
$links_trail = array(
array(
'title' => $lang["systemsetup"],
'href' => $baseurl_short . "pages/admin/admin_home.php",
'menu' => true
),
array(
'title' => $lang["page-title_user_group_management"],
'href' => $baseurl_short . "pages/admin/admin_group_management.php"
),
array(
'title' => $lang["page-title_user_group_management_edit"],
'href' => generateURL("{$baseurl_short}pages/admin/admin_group_management_edit.php", $url_params),
),
array(
'title' => $lang["page-title_user_group_permissions_edit"] . " - " . escape($group["name"])
)
);
renderBreadcrumbs($links_trail);
?>
<p>
<?php
echo escape($lang['page-subtitle_user_group_permissions_edit']);
render_help_link("systemadmin/all-user-permissions");
?>
</p>
<?php if (getval("submitted", false)) { ?>
<div class="PageInformal"><?php echo escape($lang['changessaved']);?></div>
<?php } ?>
<form method="post" id="copypermissions" action="<?php echo $admin_group_permissions_url; ?>" onsubmit="return CentralSpacePost(this,true);">
<?php generateFormToken("permissions"); ?>
<input type="hidden" name="save" value="1">
<div class="BasicsBox">
<label><?php echo escape($lang["copypermissions"]);?></label>
<input type="text" name="copyfrom">
<input name="save" type="submit" value="<?php echo escape($lang["copy"]); ?>" onClick="return confirm('<?php echo escape($lang["confirmcopypermissions"]); ?>');">
</div>
</form>
<form method="post" id="permissions" action="<?php echo $admin_group_permissions_url; ?>" onsubmit="event.preventDefault();">
<?php if ($offset) { ?>
<input type="hidden" name="offset" value="<?php echo escape($offset); ?>">
<?php }
if ($order_by) { ?>
<input type="hidden" name="order_by" value="<?php echo escape($order_by); ?>">
<?php } ?>
<div class="Listview">
<table class="ListviewStyle">
<tr class="ListviewTitleStyle">
<th colspan=3 class="permheader"><?php echo escape($lang["searching_and_access"]) ?></th>
</tr>
<?php
DrawOption("s", $lang["searchcapability"]);
DrawOption("v", $lang["access_to_restricted_and_confidential_resources"], false);
# ------------ View access to workflow states
for ($n = -2; $n <= 3; $n++) {
DrawOption("z" . $n, $lang["hide_view_access_to_workflow_state"] . " '" . $lang["status" . $n] . "'", false);
}
foreach ($additional_archive_states as $additional_archive_state) {
DrawOption("z" . $additional_archive_state, $lang["hide_view_access_to_workflow_state"] . " '" . (isset($lang["status" . $additional_archive_state]) ? $lang["status" . $additional_archive_state] : $additional_archive_state) . "'", false);
}
DrawOption("g", $lang["restrict_access_to_all_available_resources"], true);
// Permission for restricting access to resources per workflow state
$default_workflow_states = range(-2, 3);
$workflow_states = array_merge($default_workflow_states, $additional_archive_states);
foreach ($workflow_states as $workflow_state_number) {
DrawOption(
"rws{$workflow_state_number}",
str_replace('%workflow_state_name', "'{$lang["status{$workflow_state_number}"]}'", $lang["restrict_access_to_workflow_state"]),
false
);
}
DrawOption("q", $lang["can_make_resource_requests"], false);
DrawOption("w", $lang["show_watermarked_previews_and_thumbnails"]);
?>
<tr class="ListviewTitleStyle">
<th colspan=3 class="permheader"><?php echo escape($lang["metadatafields"]); ?></th>
</tr>
<?php
# ------------ View access to fields
DrawOption("f*", $lang["can_see_all_fields"], false, true);
$fields = ps_query("select " . columns_in("resource_type_field") . " from resource_type_field order by active desc,order_by", array(), "schema");
foreach ($fields as $field) {
if (!in_array("f*", $permissions)) {
# Render disabled fields with strikethrough
$fieldprefix = "";
$fieldsuffix = "";
if ($field["active"] == 0) {
$fieldprefix = "<span class=FieldDisabled>";
$fieldsuffix = "</span>";
}
DrawOption("f" . $field["ref"], "&nbsp;&nbsp; - " . $lang["can_see_field"] . " '" . $fieldprefix . lang_or_i18n_get_translated($field["title"], "fieldtitle-") . $fieldsuffix . "'" . (($field["name"] == "") ? "" : "<em> (" . escape($field["name"]) . ")</em>"));
} else {
# Add it to the 'done' list so it is discarded.
$permissions_done[] = "f" . $field["ref"];
}
}
DrawOption("F*", $lang["can_edit_all_fields"], true, true);
$fields = ps_query("select " . columns_in("resource_type_field") . " from resource_type_field order by active desc,order_by", array(), "schema");
foreach ($fields as $field) {
if (in_array("F*", $permissions)) {
# Render disabled fields with strikethrough
$fieldprefix = "";
$fieldsuffix = "";
if ($field["active"] == 0) {
$fieldprefix = "<span class=FieldDisabled>";
$fieldsuffix = "</span>";
}
DrawOption("F-" . $field["ref"], "&nbsp;&nbsp; - " . $lang["can_edit_field"] . " '" . $fieldprefix . lang_or_i18n_get_translated($field["title"], "fieldtitle-") . $fieldsuffix . "'" . (($field["name"] == "") ? "" : "<em> (" . escape($field["name"]) . ")</em>"), false);
} else {
# Add it to the 'done' list so it is discarded.
$permissions_done[] = "F-" . $field["ref"];
}
}
?>
<tr class="ListviewTitleStyle">
<th colspan=3 class="permheader"><?php echo escape($lang["resourcetypes"]); ?></th>
</tr>
<?php
# ------------ View access to resource types
# All resource types need to be visible so get_resource_types() is unsuitable
# If the user can edit their own permissions they can access any resource type by editing the special permissons anyway
$rtypes = get_all_resource_types();
foreach ($rtypes as $rtype) {
DrawOption("T" . $rtype["ref"], str_replace(array("%TYPE"), array(lang_or_i18n_get_translated($rtype["name"], "resourcetype-")), $lang["can_see_resource_type"]), true);
}
# ------------ Restricted access to resource types
foreach ($rtypes as $rtype) {
DrawOption("X" . $rtype["ref"], $lang["restricted_access_only_to_resource_type"] . " '" . lang_or_i18n_get_translated($rtype["name"], "resourcetype-") . "'", false);
}
# ------------ Restricted upload for resource of type
foreach ($rtypes as $rtype) {
DrawOption("XU" . $rtype["ref"], $lang["restricted_upload_for_resource_of_type"] . " '" . lang_or_i18n_get_translated($rtype["name"], "resourcetype-") . "'", false);
}
# ------------ Edit access to resource types (in any archive state to which the group has access)
foreach ($rtypes as $rtype) {
DrawOption("ert" . $rtype["ref"], $lang["force_edit_resource_type"] . " '" . lang_or_i18n_get_translated($rtype["name"], "resourcetype-") . "'");
}
foreach ($rtypes as $rtype) {
DrawOption("XE" . $rtype["ref"], $lang["deny_edit_resource_type"] . " '" . lang_or_i18n_get_translated($rtype["name"], "resourcetype-") . "'");
}
DrawOption("XE", $lang["deny_edit_all_resource_types"], false, true);
# ------------ Allow edit access to specified resource types
if (in_array("XE", $permissions)) {
foreach ($rtypes as $rtype) {
DrawOption("XE-" . $rtype["ref"], str_replace("[resourcetype]", "'" . lang_or_i18n_get_translated($rtype["name"], "resourcetype-") . "'", $lang["can_edit_resource_type"]));
}
}
?>
<tr class="ListviewTitleStyle">
<th colspan=3 class="permheader"><?php echo escape($lang["resource_creation_and_management"]); ?></th>
</tr>
<?php
# ------------ Edit access to workflow states
for ($n = -2; $n <= 3; $n++) {
DrawOption("e" . $n, $lang["edit_access_to_workflow_state"] . " '" . $lang["status" . $n] . "'", false);
}
foreach ($additional_archive_states as $additional_archive_state) {
DrawOption("e" . $additional_archive_state, $lang["edit_access_to_workflow_state"] . " '" . (isset($lang["status" . $additional_archive_state]) ? $lang["status" . $additional_archive_state] : $additional_archive_state) . "'", false);
}
for ($n = 0; $n <= ($custom_access ? 3 : 2); $n++) {
DrawOption("ea" . $n, str_replace(array("[state]"), array($lang["access" . $n]), $lang["edit_access_to_access"]), true);
}
DrawOption("c", $lang["can_create_resources_and_upload_files-admins"]);
DrawOption("d", $lang["can_create_resources_and_upload_files-general_users"]);
DrawOption("D", $lang["can_delete_resources"], true);
DrawOption("i", $lang["can_manage_archive_resources"]);
DrawOption('A', $lang["can_manage_alternative_files"], true);
DrawOption("xupr", $lang["can_upload_preview_images"], true);
?>
<tr class="ListviewTitleStyle">
<th colspan=3 class="permheader"><?php echo escape($lang["themes_and_collections"]); ?></th>
</tr>
<?php
DrawOption("b", $lang["enable_bottom_collection_bar"], true);
DrawOption("h", $lang["can_publish_collections_as_themes"], false, true);
DrawOption("exup", $lang["permission_share_upload_link"], false, true);
if (in_array('h', $permissions)) {
DrawOption('hdta', $lang['manage_all_dash_h'], true, false);
DrawOption('hdt_ug', $lang['manage_user_group_dash_tiles'], false, false);
} else {
DrawOption('dta', $lang['manage_all_dash_perm'], false, false);
}
DrawOption("dtu", $lang["manage_own_dash"], true, false);
# ------------ Access to featured collection categories
DrawOption("j*", $lang["can_see_all_theme_categories"], false, true);
if (!in_array("j*", $permissions)) {
render_featured_collections_category_permissions(array("permissions" => $permissions));
# Add any 'loose' featured collections at top level of the tree that contain resources (so aren't in a category)
$loose_fcs = array_values(array_filter(get_featured_collections(0, ["access_control" => false]), function ($fc) {
return $fc["has_resources"] > 0;
}));
foreach ($loose_fcs as $loose_fc) {
$description = $lang["can_see_featured_collection"] . i18n_get_translated($loose_fc["name"]);
DrawOption('j' . $loose_fc["ref"], $description, false, false);
}
}
DrawOption("J", $lang["display_only_resources_within_accessible_themes"]);
# ---------- end of featured collection categories
# ---------- End of Dash Tiles
?>
<tr class="ListviewTitleStyle">
<th colspan=3 class="permheader"><?php echo escape($lang["administration"]); ?></th>
</tr>
<?php
DrawOption("t", $lang["can_access_team_centre"], false, true);
if (in_array("t", $permissions)) {
# Admin options
DrawOption("r", $lang["can_manage_research_requests"]);
DrawOption("R", $lang["can_manage_resource_requests"], false, true);
if (in_array("R", $permissions)) {
DrawOption("Ra", $lang["can_assign_resource_requests"]);
DrawOption("Rb", $lang["can_be_assigned_resource_requests"]);
}
DrawOption("o", $lang["can_manage_content"]);
DrawOption("m", $lang["can_bulk-mail_users"]);
DrawOption("u", $lang["can_manage_users"]);
DrawOption("k", $lang["can_manage_keywords"]);
DrawOption("a", $lang["can_access_system_setup"], false, true);
} else {
$permissions_done[] = "r";
$permissions_done[] = "R";
$permissions_done[] = "o";
$permissions_done[] = "m";
$permissions_done[] = "u";
$permissions_done[] = "k";
$permissions_done[] = "a";
}
DrawOption('ex', $lang['permission_manage_external_shares']);
?>
<tr class="ListviewTitleStyle">
<th colspan=3 class="permheader"><?php echo escape($lang["other"]); ?></th>
</tr>
<?php
DrawOption("p", $lang["can_change_own_password"], true);
DrawOption("U", $lang["can_manage_users_in_children_groups"]);
DrawOption("E", $lang["can_email_resources_to_own_and_children_and_parent_groups"]);
DrawOption("x", $lang["allow_user_group_selection_for_access_when_sharing_externally"]);
DrawOption("noex", $lang["prevent_user_group_sharing_externally"]);
DrawOption("nolock", $lang["permission_nolock"]);
hook("additionalperms");
$custom_permissions = join(",", array_diff($permissions, $permissions_done));
?>
</table>
</div><!-- end of Listview -->
<div class="Question">
<label for="other"><?php echo escape($lang["custompermissions"]); ?></label>
<textarea
name="other"
class="stdwidth"
rows="3"
cols="50"
data-custom_permissions_copy="<?php echo escape($custom_permissions); ?>"
><?php echo escape($custom_permissions); ?></textarea>
<div class="clearerleft"></div>
</div>
<div class="QuestionSubmit">
<input
name="save"
type="button"
onclick="SaveCustomPermissions();"
value="<?php echo escape($lang["save"]); ?>"
>
</div>
</form>
</div> <!-- end of BasicsBox -->
<script>
/**
* Save specific permissions
* @param {array} perms List of permissions to get information for, if applicable, and save. A permission can either be
* a base64 encoded permission or an object:
* {
* permission: same base64 value,
* reverse: 1 for negative permissions, 0 otherwise
* checked: bool
* }
* @return {void}
*/
function SavePermissions(perms, formsubmit) {
console.debug('SavePermissions(perms = %o)', perms);
CentralSpaceShowProcessing();
let permissions_list = ProcessDisabledPermissions(perms).map(function(perm) {
// Custom Permissions are provided with all the required info
if (
typeof perm === 'object'
&& perm.hasOwnProperty('permission')
&& perm.hasOwnProperty('reverse')
&& perm.hasOwnProperty('checked')
) {
return perm;
} else {
// Auto saving a permission will only provide its base64 value
let el = jQuery("input[name='checked_" + perm + "']");
if (el.length === 0) {
console.error('Unable to find permission!');
return null;
}
return {
permission: perm,
reverse: el.data('reverse'),
checked: el.prop('checked'),
};
}
});
let found_perms = permissions_list.filter(x => x);
jQuery.ajax({
type: 'POST',
url: '<?php echo $admin_group_permissions_url; ?>',
data: {
ajax: true,
save: '1',
permissions: found_perms,
<?php echo generateAjaxToken('SaveUsergroupPermission'); ?>
},
dataType: "json"
})
.done(function(response, textStatus, jqXHR) {
CentralSpaceHideProcessing();
// redraw page to show/hide any dependendant permissions
CentralSpaceLoad('<?php echo $admin_group_permissions_url; ?>' + (formsubmit?'&submitted=true':''), false);
if (formsubmit) {
pageScrolltop(scrolltopElementCentral);
}
})
.fail(function(data, textStatus, jqXHR) {
if (typeof data.responseJSON === 'undefined') {
console.debug('data = %o', data);
styledalert('', "<?php echo escape($lang['error_generic']); ?>");
return;
}
let response = data.responseJSON;
styledalert(jqXHR, response.data.message);
})
.always(function() {
CentralSpaceHideProcessing();
});
return;
}
/**
* Save custom permissions. Removed permissions will be marked accordingly.
* @return {void}
*/
function SaveCustomPermissions() {
console.debug('SaveCustomPermissions()');
let custom_perms_el = jQuery("textarea[name='other']");
let perms = custom_perms_el.val().split(',');
let diff = custom_perms_el
.data('custom_permissions_copy')
.split(',')
.filter(x => !perms.includes(x));
// Current custom permissions added by user
let custom_perms = perms.map(function(perm) {
return {
permission: btoa(perm),
reverse: 0,
checked: true,
};
});
// Custom permissions removed by user
jQuery.each(diff, function(idx, perm) {
custom_perms.push({
permission: btoa(perm),
reverse: 0,
checked: false,
});
});
SavePermissions(custom_perms, true);
}
/**
* Process disabled permissions. Known use cases behaviour:
* - normal permissions simply get disabled (ie not submitted). Usually when another permission is enabled instead
* (e.g perm "a" - licensemanager).
* - disabled negative permissions always get added when (auto)saving a permission. This was legacy behaviour.
*
* @param {array} perms List of permissions
* @return {array} List of disabled negative permissions
*/
function ProcessDisabledPermissions(perms) {
jQuery("input[name^='checked_'][data-reverse=1]:disabled").each(function(idx, disabled_negative_perm) {
perms.push({
permission: jQuery(disabled_negative_perm).attr('name').substring(8),
reverse: 1,
checked: false,
});
});
return perms;
}
</script>
<?php
include "../../include/footer.php";

172
pages/admin/admin_home.php Executable file
View File

@@ -0,0 +1,172 @@
<?php
include "../../include/boot.php";
include "../../include/authenticate.php";
if (!checkperm("a")) {
exit("Permission denied.");
}
include "../../include/header.php";
?>
<div class="BasicsBox">
<h1><?php echo escape($lang["systemsetup"]); ?></h1>
<?php if (getval("modal", "") == "") { ?>
<p><?php echo text("introtext")?></p>
<?php } ?>
<div class="<?php echo $tilenav ? "TileNav" : "VerticalNav TileReflow"; ?>">
<ul>
<li title="<?php echo escape($lang['page-title_user_group_management-tooltip']); ?>">
<a href="<?php echo $baseurl_short?>pages/admin/admin_group_management.php" onclick="return CentralSpaceLoad(this,true);" >
<i aria-hidden="true" class="fa fa-fw fa-users"></i>
<br /><?php echo escape($lang['page-title_user_group_management']); ?>
</a>
</li>
<li title="<?php echo escape($lang['resource_types_manage-tooltip']); ?>">
<a href="<?php echo $baseurl_short?>pages/admin/admin_resource_types.php" onclick="return CentralSpaceLoad(this,true);">
<i aria-hidden="true" class="fa fa-fw fa-cubes"></i>
<br /><?php echo escape($lang["resource_types_manage"]); ?>
</a>
</li>
<li title="<?php echo escape($lang['admin_resource_type_fields-tooltip']); ?>">
<a href="<?php echo $baseurl_short?>pages/admin/admin_resource_type_fields.php" onclick="return CentralSpaceLoad(this,true);">
<i aria-hidden="true" class="fa fa-fw fa-bars"></i>
<br /><?php echo escape($lang["admin_resource_type_fields"]); ?>
</a>
</li>
<li title="<?php echo escape($lang['filter_manage-tooltip']); ?>">
<a href="<?php echo $baseurl_short?>pages/admin/admin_filter_manage.php" onclick="return CentralSpaceLoad(this,true);">
<i aria-hidden="true" class="fa fa-fw fa-filter"></i>
<br /><?php echo escape($lang["filter_manage"]); ?>
</a>
</li>
<li title="<?php echo escape($lang['page-title_report_management-tooltip']); ?>">
<a href="<?php echo $baseurl_short?>pages/admin/admin_report_management.php" onclick="return CentralSpaceLoad(this,true);">
<i aria-hidden="true" class="fa fa-fw fa-table"></i>
<br /><?php echo escape($lang['page-title_report_management']); ?>
</a>
</li>
<li title="<?php echo escape($lang['page-title_size_management-tooltip']); ?>">
<a href="<?php echo $baseurl_short?>pages/admin/admin_size_management.php" onclick="return CentralSpaceLoad(this,true);">
<i aria-hidden="true" class="fa fa-fw fa-files-o"></i>
<br /><?php echo escape($lang["page-title_size_management"]); ?>
</a>
</li>
<?php if (checkperm("o")) { ?>
<li title="<?php echo escape($lang['managecontent-tooltip']); ?>">
<a href="<?php echo $baseurl_short?>pages/admin/admin_content.php" onClick="return CentralSpaceLoad(this,true);">
<i aria-hidden="true" class="fa fa-fw fa-pencil-square-o"></i>
<br /><?php echo escape($lang["managecontent"]); ?>
</a>
</li>
<?php } ?>
<li title="<?php echo escape($lang['pluginssetup-tooltip']); ?>">
<a href="<?php echo $baseurl_short?>pages/team/team_plugins.php" onClick="return CentralSpaceLoad(this,true);">
<i aria-hidden="true" class="fa fa-fw fa-plug"></i>
<br /><?php echo escape($lang["pluginssetup"]); ?>
</a>
</li>
<?php
if (checkperm('a')) {
$failedjobs = job_queue_get_jobs("", STATUS_ERROR);
$failedjobcount = count($failedjobs);
?>
<li title="<?php echo escape($lang['manage_slideshow-tooltip']); ?>">
<a href="<?php echo $baseurl_short; ?>pages/admin/admin_manage_slideshow.php" onClick="return CentralSpaceLoad(this, true);">
<i aria-hidden="true" class="fa fa-fw fa-picture-o"></i>
<br /><?php echo escape($lang['manage_slideshow']); ?>
</a>
</li>
<li title="<?php echo escape($lang['manage_jobs-tooltip']); ?>">
<a href="<?php echo $baseurl_short; ?>pages/manage_jobs.php" onClick="return CentralSpaceLoad(this, true);">
<i aria-hidden="true" class="fa fa-fw fa-tasks"></i>
<br /><?php echo escape($lang['manage_jobs']);?>
</a>
<?php if ($failedjobcount > 0) { ?>
&nbsp;<span class="Pill"><?php echo $failedjobcount ?></span>
<?php } ?>
</li>
<?php
}
// A place to add links to setup pages keeping them away from the more "sysadmin" type pages towards the bottom.
hook("customadminsetup");
if ('' != $mysql_bin_path && $system_download_config) { ?>
<li title="<?php echo escape($lang['exportdata-tooltip']); ?>">
<a href="<?php echo $baseurl_short?>pages/admin/admin_download_config.php" onClick="return CentralSpaceLoad(this,true);">
<i aria-hidden="true" class="fa fa-fw fa-database"></i>
<br /><?php echo escape($lang["exportdata"]); ?>
</a>
</li>
<?php
}
if (checkperm('a')) {
if ($enable_remote_apis) {
?>
<li title="<?php echo escape($lang['api-test-tool-tooltip']); ?>">
<a href="<?php echo $baseurl_short?>pages/api_test.php" onClick="return CentralSpaceLoad(this,true);">
<i aria-hidden="true" class="fa fa-fw fa-stethoscope"></i>
<br /><?php echo escape($lang["api-test-tool"]); ?>
</a>
</li>
<?php
}
?>
<li title="<?php echo escape($lang['system_tabs-tooltip']); ?>">
<a href="<?php echo $baseurl_short; ?>pages/admin/tabs.php" onclick="return CentralSpaceLoad(this, true);">
<i aria-hidden="true" class="fa fa-window-restore"></i>
<br /><?php echo escape($lang['system_tabs']); ?>
</a>
</li>
<li title="<?php echo escape($lang['installationcheck-tooltip']); ?>">
<a href="<?php echo $baseurl_short?>pages/check.php" onClick="return CentralSpaceLoad(this,true);">
<i aria-hidden="true" class="fa fa-fw fa-check-square"></i>
<br /><?php echo escape($lang["installationcheck"]); ?>
</a>
</li>
<li title="<?php echo escape($lang['systemlog-tooltip']); ?>">
<a href="<?php echo $baseurl_short; ?>pages/admin/admin_system_log.php" onClick="return CentralSpaceLoad(this,true);">
<i aria-hidden="true" class="fa fa-fw fa-history"></i>
<br /><?php echo escape($lang["systemlog"]); ?>
</a>
</li>
<li title="<?php echo escape($lang['system_performance-tooltip']); ?>">
<a href="<?php echo $baseurl_short?>pages/admin/admin_system_performance.php" onClick="return CentralSpaceLoad(this,true);">
<i aria-hidden="true" class="fa fa-fw fa-bolt"></i>
<br /><?php echo escape($lang["system_performance"]); ?>
</a>
</li>
<li title="<?php echo escape($lang['systemconfig-tooltip']); ?>">
<a href="<?php echo $baseurl; ?>/pages/admin/admin_system_config.php" onClick="return CentralSpaceLoad(this, true);">
<i aria-hidden="true" class="fa fa-fw fa-cog"></i>
<br /><?php echo escape($lang['systemconfig']); ?>
</a>
</li>
<?php
}
hook("customadminfunction");
?>
</ul>
</div>
</div> <!-- End of BasicsBox -->
<?php
include "../../include/footer.php";

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,450 @@
<?php
include '../../include/boot.php';
include '../../include/authenticate.php';
if (!checkperm('a')) {
header('HTTP/1.1 401 Unauthorized');
exit('Permission denied.');
}
include '../../include/slideshow_functions.php';
$slideshow_files = get_slideshow_files_data();
$ajax = getval('ajax', '');
$action = getval('action', '');
$slideshow_id = getval('slideshow_id', null, true);
$manageurl = "{$baseurl}/pages/admin/admin_manage_slideshow.php";
/* Re-order */
if (
'true' === $ajax
&& ('moveup' === $action || 'movedown' === $action)
&& !is_null($slideshow_id)
&& enforcePostRequest($ajax)
) {
$response['sibling'] = null;
$response['is_first_sibling'] = false;
$response['is_last_sibling'] = false;
$allow_reorder = false;
$slideshow_id_index = array_search($slideshow_id, array_column($slideshow_files, 'ref'));
if ($slideshow_id_index === false) {
http_response_code(500);
$response['error'] = "{$lang["error-failed-to-move"]} {$lang['slideshow-image']} #{$slideshow_id}";
$response['success'] = false;
echo json_encode($response);
exit();
}
// Set current slideshow entry to the entry which has the id to be moved
reset($slideshow_files);
while (current($slideshow_files) !== $slideshow_files[$slideshow_id_index]) {
next($slideshow_files);
}
if (count($slideshow_files) > 1) {
// Based on current pointer and direction of movement we can find the "to" element
switch ($action) {
case 'moveup':
prev($slideshow_files);
$to = key($slideshow_files);
reset($slideshow_files);
$response['is_first_sibling'] = ($slideshow_files[$to] == current($slideshow_files));
$allow_reorder = true;
break;
case 'movedown':
next($slideshow_files);
$to = key($slideshow_files);
$response['is_last_sibling'] = ($slideshow_files[$to] === end($slideshow_files));
$allow_reorder = true;
break;
}
}
if ($allow_reorder && reorder_slideshow_images($slideshow_files[$slideshow_id_index], $slideshow_files[$to])) {
$response['sibling'] = $slideshow_files[$to]["ref"];
}
echo json_encode($response);
exit();
}
/* Delete */
if ('true' === $ajax && 'delete' === $action && !is_null($slideshow_id) && enforcePostRequest($ajax)) {
$response['error'] = '';
$response['success'] = true;
$slideshow_id_index = array_search($slideshow_id, array_column($slideshow_files, 'ref'));
if ($slideshow_id_index !== false) {
$slideshow_file_info = $slideshow_files[$slideshow_id_index];
} else {
$slideshow_file_info = array();
http_response_code(500);
$response['error'] = "{$lang['error-failed-to-delete']} {$lang['slideshow-image']} #{$slideshow_id}";
$response['success'] = false;
}
if (!empty($slideshow_file_info) && !delete_slideshow($slideshow_file_info['ref'])) {
http_response_code(500);
$response['error'] = "{$lang['error-failed-to-delete']} '{$slideshow_file_info['file_path']}'";
$response['success'] = false;
}
echo json_encode($response);
exit();
}
/*
Set slideshow flags
===================
Available options:
- homepage_show
- featured_collections_show
- login_show
*/
if ($ajax === 'true' && $action == 'set_flag' && enforcePostRequest($ajax)) {
$slideshow_id_index = array_search($slideshow_id, array_column($slideshow_files, 'ref'));
if ($slideshow_id_index !== false) {
$slideshow = $slideshow_files[$slideshow_id_index];
}
$update_status = false;
$flag = getval('flag', '');
$value = getval('value', false, true);
if ($value !== false && $flag != '') {
$slideshow[$flag] = $value;
$update_status = set_slideshow(
$slideshow_id,
$slideshow['resource_ref'],
$slideshow['homepage_show'],
$slideshow['featured_collections_show'],
$slideshow['login_show']
);
}
if ($update_status !== false) {
http_response_code(200);
exit();
}
http_response_code(400);
exit();
}
if ('true' === $ajax && getval("static", "") != "") {
if (getval("static", "") == "true") {
set_config_option(null, 'static_slideshow_image', true);
} else {
set_config_option(null, 'static_slideshow_image', false);
}
}
include '../../include/header.php';
?>
<style>
button:disabled,
button[disabled] {
color: #666666;
cursor: not-allowed;
background: white;
box-shadow: unset;
}
</style>
<div class="BasicsBox">
<h1><?php echo escape($lang["manage_slideshow"]); ?></h1>
<?php
$links_trail = array(
array(
'title' => $lang["systemsetup"],
'href' => $baseurl_short . "pages/admin/admin_home.php",
'menu' => true
),
array(
'title' => $lang["manage_slideshow"]
)
);
renderBreadcrumbs($links_trail);
?>
<p>
<?php
echo escape($lang['manage-slideshow-instructions']);
render_help_link("resourceadmin/homepage-slideshow");
?>
</p>
<div class="Listview">
<table class="ListviewStyle">
<tbody>
<tr class="ListviewTitleStyle">
<th><?php echo escape($lang["preview"]); ?></th>
<th><?php echo escape($lang["home_page"]); ?></th>
<th><?php echo escape($lang["theme"]); ?></th>
<th><?php echo escape($lang["login_word"]); ?></th>
<th><?php echo escape($lang["tools"]); ?></th>
</tr>
<?php
foreach ($slideshow_files as $slideshow_index => $slideshow_file_info) {
$moveup_disabled = '';
$movedown_disabled = '';
if ($slideshow_index == 0 || count($slideshow_files) == 1) {
$moveup_disabled = ' disabled';
}
if (($slideshow_index == (count($slideshow_files) - 1)) || count($slideshow_files) == 1) {
$movedown_disabled = ' disabled';
}
$delete_btn_disabled = '';
if (count($slideshow_files) == 1) {
$delete_btn_disabled = ' disabled';
}
$homepage_show = ($slideshow_file_info['homepage_show'] == 1 ? 'checked' : '');
$featured_collections_show = ($slideshow_file_info['featured_collections_show'] == 1 ? 'checked' : '');
$login_show = ($slideshow_file_info['login_show'] == 1 ? 'checked' : '');
$slideshow_ref = $slideshow_file_info['ref'];
?>
<tr id="slideshow_<?php echo $slideshow_ref; ?>">
<td>
<?php if (isset($slideshow_file_info['link'])) { ?>
<a href="<?php echo $slideshow_file_info['link']; ?>" onclick="return ModalLoad(this, true);">
<img
id="slideshow_img_<?php echo $slideshow_ref; ?>"
src="<?php echo $slideshow_file_info['file_url']; ?>"
alt="Slideshow Image <?php echo $slideshow_ref; ?>"
width="150"
height="80"
>
</a>
<?php } else { ?>
<img
id="slideshow_img_<?php echo $slideshow_ref; ?>"
src="<?php echo $slideshow_file_info['file_url']; ?>"
alt="Slideshow Image <?php echo $slideshow_ref; ?>"
width="150"
height="80"
>
<?php } ?>
</td>
<td>
<input
type="checkbox"
name="homepage_show"
value="1"
onclick="SetSlideshowFlag(this);"
<?php echo $homepage_show; ?>
>
</td>
<td>
<input
type="checkbox"
name="featured_collections_show"
value="1"
onclick="SetSlideshowFlag(this);"
<?php echo $featured_collections_show; ?>
>
</td>
<td>
<input
type="checkbox"
name="login_show"
value="1"
onclick="SetSlideshowFlag(this);"
<?php echo $login_show; ?>
>
</td>
<td>
<button
id="slideshow_<?php echo $slideshow_ref; ?>_moveup"
type="submit" slideMoveUpButton
onclick="ReorderSlideshowImage(this, 'moveup');"
<?php echo $moveup_disabled; ?>>
<?php echo escape($lang['action-move-up']); ?>
</button>
<button
id="slideshow_<?php echo $slideshow_ref; ?>_movedown"
type="submit" slideMoveDownButton
onclick="ReorderSlideshowImage(this, 'movedown');"
<?php echo $movedown_disabled; ?>>
<?php echo escape($lang['action-move-down']); ?>
</button>
<?php hook('render_replace_button_for_manage_slideshow', '', array($slideshow_ref, $slideshow_file_info)); ?>
<button
id="slideshow_<?php echo $slideshow_ref; ?>_delete"
type="submit" slideDeleteButton
onclick="DeleteSlideshowImage(this);"
<?php echo $delete_btn_disabled; ?>>
<?php echo escape($lang['action-delete']); ?>
</button>
<?php hook('render_replace_slideshow_form_for_manage_slideshow', '', array($slideshow_ref, $slideshow_files)); ?>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<div id="slideshow_static_image" class="Question">
<label for="slideshow_static_image_checkbox"><?php echo escape($lang["slideshow_use_static_image"]); ?></label>
<input
type="checkbox"
name="slideshow_static_image"
id="slideshow_static_image_checkbox"
<?php echo ($static_slideshow_image) ? "checked" : ''; ?>
onchange="if(this.checked){jQuery.get('<?php echo $manageurl ?>?ajax=true&static=true');}else{jQuery.get('<?php echo $manageurl ?>?ajax=true&static=false');}">
</input>
<div class="clearerleft"></div>
</div>
<?php hook('render_new_element_for_manage_slideshow', '', array($slideshow_files)); ?>
</div>
<script>
function SetSlideshowFlag(element) {
var input = jQuery(element);
// Extract reference from row identifier r from "slideshow_r"
var slideshow_row_id = element.parentElement.parentElement.id.substr(10);
var flag_value = 0;
if (element.checked) {
flag_value = 1;
}
var post_url = '<?php echo $manageurl; ?>';
var post_data = {
ajax: true,
action: 'set_flag',
slideshow_id: slideshow_row_id,
flag: input.attr('name'),
value: flag_value,
<?php echo generateAjaxToken("SetSlideshowFlag"); ?>
};
CentralSpaceShowProcessing();
jQuery.ajax({
type: 'POST',
url: post_url,
data: post_data,
}).fail(function(data, textStatus, jqXHR) {
styledalert(data.status, data.statusText);
}).always(function() {
CentralSpaceHideProcessing();
});
return false;
}
function ReorderSlideshowImage(element, direction) {
var post_url = '<?php echo $manageurl ?>';
// Extract reference from row identifier r from "slideshow_r"
var slideshow_row_id = element.parentElement.parentElement.id.substr(10);
var post_data = {
ajax: true,
action: direction,
slideshow_id: slideshow_row_id,
<?php echo generateAjaxToken("ReorderSlideshowImage"); ?>
};
jQuery.post(post_url, post_data, function(response) {
if (response.sibling !== false) {
// Establish row elements and their corresponding button elements
var moving_row = jQuery('#slideshow_' + slideshow_row_id);
var moving_moveup = jQuery('#slideshow_' + slideshow_row_id + '_moveup');
var moving_movedown = jQuery('#slideshow_' + slideshow_row_id + '_movedown');
var target_row = jQuery('#slideshow_' + response.sibling);
var target_moveup = jQuery('#slideshow_' + response.sibling + '_moveup');
var target_movedown = jQuery('#slideshow_' + response.sibling + '_movedown');
// Swap rows
if(direction == 'moveup')
{
jQuery(moving_row).insertBefore(target_row);
}
else // movedown
{
jQuery(moving_row).insertAfter(target_row);
}
// Swap row identifiers
jQuery(moving_row).attr("id","slideshow_"+response.sibling);
jQuery(target_row).attr("id","slideshow_"+slideshow_row_id);
ResetSlideshowButtons();
}
}, 'json').fail(function(data, textStatus, jqXHR) {
styledalert(data.statusText, data.responseText);
});
return false;
}
function DeleteSlideshowImage(element) {
var post_url = '<?php echo $manageurl ?>';
// Extract reference from row identifier r from "slideshow_r"
var slideshow_row_id = element.parentElement.parentElement.id.substr(10);
var post_data = {
ajax: true,
action: 'delete',
slideshow_id: slideshow_row_id,
<?php echo generateAjaxToken("DeleteSlideshowImage"); ?>
};
jQuery.post(post_url, post_data, function(response) {
if (response.success) {
jQuery('#slideshow_' + slideshow_row_id).remove();
ResetSlideshowButtons();
}
}, 'json').fail(function(data, textStatus, jqXHR) {
styledalert(data.statusText, data.responseJSON.error);
});
return false;
}
function ResetSlideshowButtons() {
// Re-establish move button availability
jQuery("[slideMoveUpButton]").prop("disabled",false);
jQuery("[slideMoveDownButton]").prop("disabled",false);
// Cannot move first row up
jQuery("[slideMoveUpButton]:first").prop("disabled",true);
// Cannot move last row down
jQuery("[slideMoveDownButton]:last").prop("disabled",true);
// Disable delete button if only one slide present
if (jQuery("[slideDeleteButton]").length == 1) {
jQuery("[slideDeleteButton]").prop("disabled",true);
}
}
</script>
<?php
include '../../include/footer.php';

View File

@@ -0,0 +1,220 @@
<?php
include "../../include/boot.php";
include "../../include/authenticate.php";
if (!checkperm("a")) {
exit("Permission denied.");
}
include "../../include/header.php";
$find = getval("find", "");
$order_by = getval("orderby", "name");
$order_by_list = ["ref","ref desc","name","name desc","support_non_correlated_sql","support_non_correlated_sql desc"];
if (!in_array(strtolower($order_by), $order_by_list)) {
$order_by[0] = "name";
}
$url_params = array("find" => $find, "orderby" => $order_by);
$url = generateURL($baseurl . "/pages/admin/admin_report_management.php", $url_params);
$find_sql = "";
if ($find != "") {
$find_sql = " WHERE ref LIKE ? OR name LIKE ?";
$sql_params = ["s","%" . $find . "%","s","%" . $find . "%"];
}
$reports = ps_query("SELECT ref, `name`, support_non_correlated_sql FROM report {$find_sql} ORDER BY {$order_by}", $sql_params ?? []);
?>
<div class="BasicsBox">
<h1><?php echo escape($lang["page-title_report_management"]); ?></h1>
<?php
$links_trail = array(
array(
'title' => $lang["systemsetup"],
'href' => $baseurl_short . "pages/admin/admin_home.php",
'menu' => true
),
array(
'title' => $lang["page-title_report_management"],
)
);
renderBreadcrumbs($links_trail);
?>
<p>
<?php
echo escape($lang['page-subtitle_report_management_edit']);
render_help_link("resourceadmin/reports-and-statistics");
?>
</p>
<form
method="post"
id="copy_report"
action="admin_report_management_edit.php"
onsubmit="return CentralSpacePost(this, true);">
<input type="hidden" name="copyreport" value="true">
<input type="hidden" name="ref" value="">
<?php generateFormToken("copy_report"); ?>
</form>
<script>
function copyReport(ref) {
frm = document.forms["copy_report"];
frm.ref.value=ref;
frm.submit();
}
</script>
<?php
function addColumnHeader($orderName, $labelKey)
{
global $baseurl, $order_by, $find, $lang;
if ($order_by == $orderName) {
$image = '<span class="ASC"></span>';
} elseif ($order_by == $orderName . ' desc') {
$image = '<span class="DESC"></span>';
} else {
$image = '';
}
?>
<th>
<a
href="<?php echo $baseurl ?>/pages/admin/admin_report_management.php?<?php
echo ($find != "") ? "&find=" . escape($find) : ''; ?>&orderby=<?php
echo $orderName . ($order_by == $orderName ? '+desc' : ''); ?>"
onClick="return CentralSpaceLoad(this);">
<?php echo escape($lang[$labelKey]) . $image ?>
</a>
</th>
<?php
}
?>
<div class="Listview">
<table class="ListviewStyle">
<tr class="ListviewTitleStyle">
<?php
addColumnHeader("ref", "property-reference");
addColumnHeader("name", "property-name");
addColumnHeader('support_non_correlated_sql', 'property-support_non_correlated_sql');
?>
<th>
<div class="ListTools"><?php echo escape($lang["tools"]); ?></div>
</th>
</tr>
<?php
foreach ($reports as $report) {
$support_non_correlated_sql = ((bool)$report['support_non_correlated_sql'] === true);
$edit_url_extra = array();
$edit_url_extra = ($find == "" ? $edit_url_extra : array_merge($edit_url_extra, array("find" => $find)));
$edit_url_extra = ($order_by == "name" ? $edit_url_extra : array_merge($edit_url_extra, array("orderby" => $order_by)));
$edit_url = generateURL("{$baseurl_short}pages/admin/admin_report_management_edit.php", array("ref" => $report["ref"]), $edit_url_extra);
$view_url = "{$baseurl_short}pages/team/team_report.php?report={$report['ref']}&backurl=" . urlencode($url);
$a_href = (!(!db_use_multiple_connection_modes() && $execution_lockout) ? $edit_url : $view_url);
?>
<tr>
<td>
<a href="<?php echo $a_href; ?>" onClick="return CentralSpaceLoad(this,true);">
<?php echo str_highlight($report["ref"], escape($find), STR_HIGHLIGHT_SIMPLE); ?>
</a>
</td>
<td>
<a href="<?php echo $a_href; ?>" onClick="return CentralSpaceLoad(this,true);">
<?php echo str_highlight($report["name"], escape($find), STR_HIGHLIGHT_SIMPLE); ?>
</a>
</td>
<td><?php echo escape($support_non_correlated_sql ? $lang['yes'] : $lang['no']); ?></td>
<td>
<div class="ListView ListTools" align="right">
<?php
if (!$support_non_correlated_sql) { ?>
<a href="<?php echo $view_url; ?>" onclick="return CentralSpaceLoad(this, true);">
<i class="fas fa-table"></i>&nbsp;<?php echo escape($lang["action-view"]); ?>
</a>
<?php
}
if (db_use_multiple_connection_modes() || !$execution_lockout) { ?>
<a href="<?php echo $edit_url; ?>" onclick="return CentralSpaceLoad(this, true);">
<i class="fa fa-edit"></i>&nbsp;<?php echo escape($lang["action-edit"]); ?>
</a>
<a href="javascript:copyReport('<?php echo $report["ref"]; ?>')">
<i class="fas fa-copy"></i>&nbsp;<?php echo escape($lang["copy"]); ?>
</a>
<?php
}
?>
</div>
</td>
</tr>
<?php
}
?>
</table>
</div>
</div><!-- end of BasicsBox -->
<div class="BasicsBox">
<form method="post" action="<?php echo $baseurl_short?>pages/admin/admin_report_management.php" onSubmit="return CentralSpacePost(this,false);">
<?php generateFormToken("admin_report_management_find"); ?>
<div class="Question">
<label for="find"><?php echo escape($lang["property-search_filter"]); ?></label>
<input name="find" type="text" class="medwidth" value="<?php echo escape($find); ?>">
<input name="save" type="submit" value="<?php echo escape($lang["searchbutton"]); ?>">
<div class="clearerleft"></div>
</div>
<?php if ($find != "") { ?>
<div class="QuestionSubmit">
<input
name="buttonsave"
type="button"
onclick="CentralSpaceLoad('admin_report_management.php',false);"
value="<?php echo escape($lang["clearbutton"]); ?>"
>
</div>
<?php } ?>
</form>
</div>
<div class="BasicsBox">
<form method="post" action="<?php echo $baseurl_short; ?>pages/admin/admin_report_management_edit.php" onSubmit="return CentralSpacePost(this,false);">
<?php generateFormToken("admin_report_management"); ?>
<div class="Question">
<label for="name"><?php echo escape($lang['action-title_create_report_called']); ?></label>
<div class="tickset">
<div class="Inline">
<input name="newreportname" type="text" value="" class="shrtwidth">
</div>
<div class="Inline">
<input name="Submit" type="submit" value="<?php echo escape($lang["create"]); ?>" onclick="return (this.form.elements[0].value!='');">
</div>
</div>
<div class="clearerleft"></div>
</div>
<?php
if ($order_by) { ?>
<input type="hidden" name="orderby" value="<?php echo escape($order_by); ?>">
<?php
}
if ($find) { ?>
<input type="hidden" name="find" value="<?php echo escape($find); ?>">
<?php
}
?>
</form>
</div>
<?php
include "../../include/footer.php";

View File

@@ -0,0 +1,149 @@
<?php
include "../../include/boot.php";
include "../../include/authenticate.php";
if ((!db_use_multiple_connection_modes() && $execution_lockout) || !checkperm("a")) {
exit("Permission denied.");
}
$find = getval("find", "");
$order_by = getval("orderby", "");
$url_params = ($order_by ? "&orderby={$order_by}" : "") . ($find ? "&find={$find}" : "");
$ref = getval("ref", "");
$copyreport = getval("copyreport", "");
# create new record from callback
$new_report_name = getval("newreportname", "");
if ($new_report_name != "" && enforcePostRequest(false)) {
ps_query("INSERT into report (name) values(?)", array("s",$new_report_name));
$ref = sql_insert_id();
log_activity(null, LOG_CODE_CREATED, $new_report_name, 'report', 'name', $ref);
redirect($baseurl_short . "pages/admin/admin_report_management_edit.php?ref={$ref}{$url_params}"); // redirect to prevent repost and expose form data
exit;
} elseif ($copyreport != "" && enforcePostRequest(false)) {
// Copy report?
ps_query("INSERT into report (name, query) select concat('" . $lang["copy_of"] . " ',name), query from report where ref=?", array("i",$ref));
$from_ref = $ref;
$ref = sql_insert_id();
$new_copied_name = ps_value("SELECT `name` AS 'value' FROM `report` WHERE `ref`=?", array("i",$ref), '');
log_activity($lang["copy_of"] . ' ' . $from_ref, LOG_CODE_COPIED, $new_copied_name, 'report', 'name', $ref, null, '');
} elseif (!ps_value("select ref as value from report where ref=?", array("i",$ref), false)) {
redirect("{$baseurl_short}pages/admin/admin_report_management.php?{$url_params}"); // fail safe by returning to the report management page if duff ref passed
exit;
}
if (getval("deleteme", false) && enforcePostRequest(false)) {
log_activity(null, LOG_CODE_DELETED, null, 'report', 'name', $ref);
ps_query("DELETE from report where ref=?", array("i",$ref));
redirect("{$baseurl_short}pages/admin/admin_report_management.php?{$url_params}"); // return to the report management page
exit;
}
$name = getval("name", "");
$query = getval("query", "");
if (getval("save", false)) {
if (strlen(trim($query)) == 0) {
$error = $lang["report_query_required"];
}
if (!isset($error) && enforcePostRequest(false)) {
log_activity(null, LOG_CODE_EDITED, $name, 'report', 'name', $ref, null, ps_value("SELECT `name` AS value FROM `report` WHERE ref=?", array("i",$ref), ""));
log_activity(null, LOG_CODE_EDITED, $query, 'report', 'query', $ref, null, ps_value("SELECT `query` AS value FROM `report` WHERE ref=?", array("i",$ref), ""), null, true);
$support_non_correlated_sql = (int) (mb_strpos($query, REPORT_PLACEHOLDER_NON_CORRELATED_SQL) !== false);
$parameters = array("s",$name, "s",$query, "i",$support_non_correlated_sql, "i",$ref);
ps_query("UPDATE report SET name = ?, query = ?, support_non_correlated_sql = ? WHERE ref = ?", $parameters);
redirect("{$baseurl_short}pages/admin/admin_report_management.php?{$url_params}");
exit;
}
}
$record = ps_query("select " . columns_in("report") . " from report where ref=?", array("i",$ref));
$record = $record[0];
include "../../include/header.php";
$url_params_edit = array(
"ref" => $ref,
"orderby" => $order_by,
"find" => $find
);
if (isset($error)) { ?>
<div class="FormError">!! <?php echo $error?> !!</div>
<?php
}
?>
<form
method="post"
enctype="multipart/form-data"
action="<?php echo generateURL($baseurl_short . 'pages/admin/admin_report_management_edit.php', $url_params_edit);?>"
id="mainform"
onSubmit="return CentralSpacePost(this,true);" class="FormWide">
<?php generateFormToken("mainform"); ?>
<div class="BasicsBox">
<h1><?php echo escape($lang["page-title_report_management_edit"]); ?></h1>
<?php
$links_trail = array(
array(
'title' => $lang["systemsetup"],
'href' => $baseurl_short . "pages/admin/admin_home.php",
'menu' => true
),
array(
'title' => $lang["page-title_report_management"],
'href' => $baseurl_short . "pages/admin/admin_report_management_edit.php?" . $url_params
),
array(
'title' => $lang["page-title_report_management_edit"]
)
);
renderBreadcrumbs($links_trail);
?>
<p>
<?php
echo escape($lang['page-subtitle_report_management_edit']);
render_help_link("resourceadmin/custom_reports");
?>
</p>
<input type="hidden" name="save" value="1">
<div class="Question">
<label for="reference"><?php echo escape($lang["property-reference"]); ?></label>
<div class="Fixed"><?php echo (int)$ref; ?></div>
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="name"><?php echo escape($lang["property-name"]); ?></label>
<input name="name" type="text" class="stdwidth" value="<?php echo $record['name']; ?>">
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="query"><?php echo escape($lang["property-query"]); ?></label>
<textarea name="query" class="stdwidth" style="height: 300px;"><?php echo $record['query']; ?></textarea>
<div class="clearerleft"></div>
</div>
<div class="Question">
<label><?php echo escape($lang["fieldtitle-tick_to_delete_report"]); ?></label>
<input name="deleteme" type="checkbox" value="yes">
<div class="clearerleft"></div>
</div>
<div class="QuestionSubmit">
<input name="buttonsave" type="submit" value="&nbsp;&nbsp;<?php echo escape($lang["save"]); ?>&nbsp;&nbsp;">
</div>
</div>
</form>
<?php
include "../../include/footer.php";

View File

@@ -0,0 +1,270 @@
<?php
include "../../include/boot.php";
include "../../include/authenticate.php";
include "../../lib/fontawesome/resourcespace/icon_classes.php";
if (!checkperm("a")) {
exit($lang["error-permissiondenied"]);
}
$ref = getval('ref', '', true);
$name = getval('name', '');
$config_options = getval('config_options', '');
$allowed_extensions = getval('allowed_extensions', '');
$tab = (int) getval('tab', 0);
$colour = getval('colour', 0, true);
$push_metadata = getval('push_metadata', 0, true);
$pull_images = getval('pull_images', 0, true);
$icon = getval('icon', '');
$allrestypes = get_resource_types('', true, true, true);
$restype_order_by = getval("restype_order_by", "rt");
$restype_sort = getval("restype_sort", "asc");
$url_params = array("ref" => $ref,
"restype_order_by" => $restype_order_by,
"restype_sort" => $restype_sort);
$url = generateURL($baseurl . "/pages/admin/admin_resource_type_edit.php", $url_params);
$backurl = getval("backurl", "");
if ($backurl == "") {
$backurl = $baseurl . "/pages/admin/admin_resource_types.php?ref=" . $ref;
}
if (getval("restype_save", "") != "" && enforcePostRequest(false)) {
# Save resource type data
$savedata = [
"name" => $name,
"allowed_extensions" => $allowed_extensions,
"tab" => $tab,
"push_metadata" => $push_metadata,
"pull_images" => $pull_images,
"colour" => $colour,
"icon" => $icon,
];
if (!$execution_lockout) {
$savedata["config_options"] = $config_options;
}
$saved = save_resource_type($ref, $savedata);
if ($saved) {
$saved_text = $lang['saved'];
} else {
$error_text = $lang['error_generic'];
}
}
$confirm_delete = false;
$confirm_move_associated_rtf = false;
if (getval("restype_delete", "") != "" && enforcePostRequest(false)) {
$targettype = getval("targettype", -1, true);
$prereq_action = getval("prereq_action", "");
$validtargets = array_column($allrestypes, "ref");
$affectedresources = ps_array("SELECT ref value FROM resource WHERE resource_type=? AND ref>0", array("i",$ref), 0);
$affected_rtfs = get_resource_type_fields(array($ref), "ref", "asc", "", array(), true);
$dependentfields = [];
foreach ($affected_rtfs as $affected_rtf) {
if ($affected_rtf["global"] == 0 && count(explode(",", $affected_rtf["resource_types"])) == 1) {
// Field only applies to this resource type
$dependentfields[] = $affected_rtf["ref"];
}
}
// If we have a target type, move the current resources to the new resource type
if ($targettype > -1 && $targettype != $ref) {
if (in_array($targettype, $validtargets) && $prereq_action == "move_affected_resources") {
foreach ($affectedresources as $affectedresource) {
update_resource_type($affectedresource, $targettype);
}
$affectedresources = [];
}
if (in_array($targettype, array_merge($validtargets, [0])) && $prereq_action == "move_affected_rtfs") {
foreach ($dependentfields as $dependentfield) {
update_resource_type_field_resource_types($dependentfield, [$targettype]);
}
$dependentfields = [];
}
}
if (count($affectedresources) > 0) {
// User needs to confirm a new resource type
$confirm_delete = true;
} elseif (count($dependentfields) > 0) {
$confirm_move_associated_rtf = true;
} else {
// Safe to delete
ps_query("DELETE from resource_type where ref=?", array("i",$ref));
clear_query_cache("schema");
redirect(generateURL($baseurl_short . "pages/admin/admin_resource_types.php", $url_params));
}
}
$actions_required = ($confirm_delete || $confirm_move_associated_rtf);
# Fetch data
$restypedata = rs_get_resource_type($ref);
if (count($restypedata) == 0) {
exit("Resource type not found.");
} // Should arrive here unless someone has an old/incorrect URL.
$restypedata = $restypedata[0];
include "../../include/header.php";
?>
<script src="<?php echo $baseurl_short ?>lib/chosen/chosen.jquery.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="<?php echo $baseurl_short ?>lib/chosen/chosen.min.css">
<div class="BasicsBox">
<h1><?php echo escape(i18n_get_translated($restypedata["name"])); ?></h1>
<?php
$links_trail = array(
array(
'title' => $lang["systemsetup"],
'href' => $baseurl_short . "pages/admin/admin_home.php",
'menu' => true
),
array(
'title' => $lang["resource_types_manage"],
'href' => $backurl
),
array(
'title' => escape(i18n_get_translated($restypedata["name"])),
'help' => "resourceadmin/resource-types"
)
);
renderBreadcrumbs($links_trail);
if (isset($error_text)) { ?>
<div class="FormError"><?php echo $error_text?></div>
<?php
}
if (isset($saved_text)) { ?>
<div class="PageInfoMessage"><?php echo $saved_text?></div>
<?php
} ?>
<form method=post action="<?php echo $baseurl_short?>pages/admin/admin_resource_type_edit.php?ref=<?php echo (int)$ref ?>&backurl=<?php echo urlencode($backurl) ?>" onSubmit="return CentralSpacePost(this,true);">
<input type="hidden" name="ref" value="<?php echo urlencode($ref) ?>">
<input type="hidden" id="restype_save" name="restype_save" value="">
<input type="hidden" id="restype_delete" name="restype_delete" value="">
<?php
generateFormToken("admin_resource_type_edit");
if ($actions_required) {
?>
<div class="PageInfoMessage">
<?php
if ($confirm_delete) {
echo escape(str_replace("[resource_count]", count($affectedresources), $lang["resource_type_delete_confirmation"])) . "<br />";
?>
<input type="hidden" name="prereq_action" value="move_affected_resources">
<?php
} elseif ($confirm_move_associated_rtf) {
echo escape(str_replace("%COUNT", count($dependentfields), $lang["resource_type_delete_assoc_rtf_confirm"])) . "<br>";
?>
<input type="hidden" name="prereq_action" value="move_affected_rtfs">
<?php
}
echo escape($lang["resource_type_delete_select_new"]) ;
?>
</div>
<div class="Question">
<label for="targettype"><?php echo escape($lang["resourcetype"]) ; ?></label>
<div class="tickset">
<div class="Inline">
<select name="targettype" id="targettype">
<option value="" selected ><?php echo escape($lang["select"]) ; ?></option>
<?php if ($confirm_move_associated_rtf) { ?>
<option value="0"><?php echo escape($lang["resourcetype-global_field"]) ; ?></option>
<?php
}
for ($n = 0; $n < count($allrestypes); $n++) {
if ($allrestypes[$n]["ref"] != $ref) { ?>
<option value="<?php echo $allrestypes[$n]["ref"]; ?>"><?php echo escape(i18n_get_translated($allrestypes[$n]["name"])); ?></option>
<?php
}
}
?>
</select>
</div>
</div>
<div class="clearerleft"></div>
</div>
<div class="QuestionSubmit">
<input name="cancel" type="submit" value="<?php echo escape($lang["cancel"]) ?>" onClick="history.go(-1);return false;"/>
<input name="delete" type="submit" value="<?php echo escape($lang["action-delete"]) ?>" onClick="if(confirm('<?php echo escape($lang["confirm-deletion"]) ?>')){jQuery('#restype_delete').val('yes');this.form.submit();}else{jQuery('#restype_delete').val('');}return false;"/>
</div>
<?php
exit();
} else {
?>
<div class="Question">
<label><?php echo escape($lang["property-reference"]) ?></label>
<div class="Fixed"><?php echo $restypedata["ref"]; ?></div>
<div class="clearerleft"></div>
</div>
<div class="Question">
<label><?php echo escape($lang["property-name"]) ?></label>
<input name="name" type="text" class="stdwidth" value="<?php echo escape((string)$restypedata["name"])?>" />
<div class="clearerleft"></div>
</div>
<?php render_fa_icon_selector($lang["property-icon"], "icon", ($restypedata['icon'] ?? "")); ?>
<div class="Question">
<label><?php echo escape($lang["property-allowed_extensions"]) ?></label>
<input name="allowed_extensions" type="text" class="stdwidth" value="<?php echo escape((string)$restypedata["allowed_extensions"])?>" />
<div class="FormHelp" style="padding:0;clear:left;" >
<div class="FormHelpInner"><?php echo escape($lang["information-allowed_extensions"]); ?></div>
</div>
<div class="clearerleft"></div>
</div>
<?php if (!$execution_lockout) { ?>
<div class="Question">
<label><?php echo escape($lang["property-override_config_options"]); ?></label>
<textarea name="config_options" class="stdwidth" rows=5 cols=50><?php echo escape((string)$restypedata["config_options"])?></textarea>
<div class="FormHelp" style="padding:0;clear:left;">
<div class="FormHelpInner">
<?php echo escape($lang["information-resource_type_config_override"]); ?>
</div>
</div>
<div class="clearerleft"> </div>
</div>
<?php }
render_dropdown_question($lang['property-tab_name'], 'tab', get_tab_name_options(), $restypedata['tab']);
$MARKER_COLORS[-1] = $lang["select"];
ksort($MARKER_COLORS);
render_dropdown_question($lang['resource_type_marker_colour'], "colour", $MARKER_COLORS, $restypedata["colour"], '', array("input_class" => "stdwidth"));
config_boolean_select("push_metadata", $lang["property-push_metadata"], (int)$restypedata["push_metadata"], '', 420, null, false, null, false, $lang["information-push_metadata"]);
config_boolean_select("pull_images", $lang["pull_images"], (int)$restypedata["pull_images"], '', 420, null, false, null, false, $lang["pull_images_text"]);
?>
<div class="QuestionSubmit">
<input name="save" type="submit" value="<?php echo escape($lang["save"])?>" onClick="jQuery('#restype_save').val('yes');this.form.submit();return false;"/>
<input name="delete" type="submit" value="<?php echo escape($lang["action-delete"])?>" onClick="if(confirm('<?php echo escape($lang["confirm-deletion"]) ?>')){jQuery('#restype_delete').val('yes');this.form.submit()}else{jQuery('#restype_delete').val('');}return false;"/>
</div>
<?php
} // End of normal page (not confirm deletion)
?>
</form>
</div><!-- End of Basics Box -->
<?php
include "../../include/footer.php";
?>

View File

@@ -0,0 +1,263 @@
<?php
include "../../include/boot.php";
include "../../include/authenticate.php";
if (!checkperm("a")) {
exit("Permission denied.");
}
$ref = getval("ref", "", true);
$find = getval("find", "");
$restypefilter = getval("restypefilter", "", true);
$field_order_by = getval("field_order_by", "ref");
$field_sort = getval("field_sort", "asc");
$newfield = getval("newfield", "") != "";
$ajax = getval('ajax', '');
$url_params = array("ref" => $ref,
"restypefilter" => $restypefilter,
"$field_order_by" => $field_order_by,
"field_sort" => $field_sort,
"find" => $find);
$backurl = getval("backurl", "");
if ($backurl == "") {
$backurl = generateURL($baseurl . "/pages/admin/admin_resource_type_fields.php", $url_params);
} else {
$back_url_params = parse_url($backurl, PHP_URL_QUERY);
# the first parameter of the back url is needed here but isn't captured
$back_url_params = explode('&', $back_url_params);
foreach ($back_url_params as $param) {
$param_parts = explode('=', $param);
switch ($param_parts[0]) {
case 'restypefilter':
$restypefilter = $param_parts[1];
break;
case 'field_order_by':
$field_order_by = $param_parts[1];
break;
case 'field_sort':
$field_sort = $param_parts[1];
break;
case 'find':
$find = $param_parts[1];
break;
}
}
}
$url = generateURL($baseurl . "/pages/admin/admin_resource_type_field_edit.php", $url_params);
// Define array of field properties containing title and associated lang help text, with a flag to indicate if it is a boolean value that we will save from POST data and boolean to indicate will be set with any 'synced' fields
// example field :-
// "name of table column"=>array(
// 0: <language string for the friendly name of this property>,
// 1: <lang string for the help text explaining what this property means>,
// 2: <value to denote the field type(0=text,1=boolean,2=text area),
// 3: < boolean value to indicate whether this is a field that is synchronised? 0=No 1=Yes >
// )
// IMPORTANT - Make sure advanced field properties are listed after the 'partial_index' so that these will be hidden from users by default
$fieldcolumns = get_resource_type_field_columns();
$type_change = false;
if (getval("save", "") != "" && getval("delete", "") == "" && enforcePostRequest(false)) {
$saved = save_resource_type_field($ref, $fieldcolumns, $_POST);
if ($saved) {
$saved_text = $lang['saved'];
} else {
$error_text = $lang['error_generic'];
}
}
$confirm_delete = false;
if (getval("delete", "") != "" && enforcePostRequest($ajax)) {
$confirmdelete = getval("confirmdelete", "");
# Check for resources of this type
$affected_resources = ps_array("SELECT resource value FROM resource_node rn LEFT JOIN node n ON n.ref = rn.node WHERE n.resource_type_field = ?", ["i",$ref]);
$affected_resources_count = count($affected_resources);
if ($affected_resources_count == 0 || $confirmdelete != "") {
$result = delete_resource_type_field($ref);
if ($result === true) {
if ($ajax) {
echo json_encode(
array(
'deleted' => $ref
)
);
exit();
} else {
redirect(generateURL($baseurl . "/pages/admin/admin_resource_type_fields.php", $url_params, array("ref" => "","deleted" => urlencode($ref))));
}
} elseif (is_string($result)) {
if ($ajax) {
echo json_encode(
array(
'message' => $result
)
);
exit();
} else {
$error_text = $result;
}
}
} else {
// User needs to confirm deletion as data will be lost
$error_text = str_replace("[affected_resources]", $affected_resources_count, $lang["admin_delete_field_confirm"]);
$error_text .= "<br /><a target=\"_blank\" href=\"" . $baseurl . "/pages/search.php?search=!hasdata" . $ref . "\">" . $lang["show_resources"] . "</a>";
$confirm_delete = true;
}
}
# Fetch data
$allfields = get_resource_type_fields();
$fielddata = get_resource_type_field($ref);
$existingrestypes = $fielddata["resource_types"] ? explode(",", (string)$fielddata["resource_types"]) : [];
include "../../include/header.php";
?>
<script>
var fixed_list_fields = [<?php echo implode(",", $FIXED_LIST_FIELD_TYPES) ?>];
var text_fields = [<?php echo implode(",", $TEXT_FIELD_TYPES) ?>];
var current_type = <?php echo '' != $fielddata['type'] ? $fielddata['type'] : 0; ?>;
<?php if (isset($migrate_data)) { ?>
jQuery(document).ready(function() {
window.location.href = '<?php echo $baseurl ?>/pages/tools/migrate_data_to_fixed.php?field=<?php echo $ref ?>';
});
<?php } ?>
</script>
<div class="BasicsBox">
<h1><?php echo escape($lang["admin_resource_type_field"] . ": " . i18n_get_translated($fielddata["title"])); ?></h1>
<?php
$links_trail = array(
array(
'title' => $lang["systemsetup"],
'href' => $baseurl_short . "pages/admin/admin_home.php",
'menu' => true
),
array(
'title' => $lang["admin_resource_type_fields"],
'href' => $backurl
),
array(
'title' => $lang["admin_resource_type_field"] . ": " . i18n_get_translated($fielddata["title"]),
'help' => "resourceadmin/configure-metadata-field"
)
);
renderBreadcrumbs($links_trail);
$url_params_edit = array(
"ref" => (int)$fielddata["ref"],
"restypefilter" => (int)$restypefilter,
"field_order_by" => $field_order_by,
"field_sort" => $field_sort,
"find" => $find
);
?>
<form
method="post"
class="FormWide"
action="<?php echo generateURL($baseurl . '/pages/admin/admin_resource_type_field_edit.php', $url_params_edit);?>"
onSubmit="return CentralSpacePost(this,true);">
<?php generateFormToken("admin_resource_type_field_edit"); ?>
<input type="hidden" name="ref" value="<?php echo urlencode($ref) ?>">
<input type="hidden" name="newfield" value="<?php echo ($newfield) ? "TRUE" : ""; ?>">
<?php
if (isset($error_text)) { ?>
<div class="PageInformal"><?php echo $error_text?></div>
<?php
}
if (isset($saved_text)) { ?>
<div class="PageInformal">
<span class="fa fa-fw fa-check"></span>&nbsp;<?php echo $saved_text?>
</div>
<?php
}
if ($confirm_delete) {
?>
<input name="confirmdelete" id="confirmdelete" type="hidden" value="">
<div class="textcenter">
<input name="delete" type="button" value="<?php echo escape($lang["action-delete"])?>" onClick="jQuery('#field_edit_delete').val('yes');jQuery('#confirmdelete').val('yes');this.form.submit();" />
<input type="button" class="button" onClick="CentralSpaceLoad('<?php generateURL($baseurl_short . "/pages/admin/admin_resource_type_field_edit.php", $url_params, array("ref" => "")); ?>',true);return false;" value="&nbsp;&nbsp;<?php echo escape($lang["cancel"]); ?>&nbsp;&nbsp;" >
</div>
<?php
} else {
?>
<div class="Question">
<label><?php echo escape($lang["property-field_id"]); ?></label>
<div class="Fixed"><?php echo $fielddata["ref"]; ?></div>
<div class="clearerleft"></div>
</div>
<?php
$system_date_field = $ref == $date_field ? true : false;
foreach ($fieldcolumns as $column => $column_detail) {
if (!hook("admin_field_replace_question", "admin_resource_type_field_edit", [$ref,$column,$column_detail, $fielddata])) {
if ($column == "partial_index") { // Start the hidden advanced section here
?>
<h2 id="showhiddenfields" class="CollapsibleSectionHead collapsed" ><?php echo escape($lang["admin_advanced_field_properties"]); ?></h2>
<div class="CollapsibleSection" id="admin_hidden_field_properties" >
<script>
function handleIndexOptions(currentId, otherId) {
const otherCheckbox = document.getElementById(otherId);
otherCheckbox.disabled = currentId.checked;
}
function initializeIndexOptions() {
const partialIndex = document.getElementById('field_edit_partial_index');
const completeIndex = document.getElementById('field_edit_complete_index');
if (partialIndex.checked) {
completeIndex.disabled=true;
} else if (completeIndex.checked) {
partialIndex.disabled=true;
}
}
</script>
<?php
}
admin_resource_type_field_option($column, $column_detail[0], $column_detail[1], $column_detail[2], $fielddata[$column], (int)$fielddata["type"], $system_date_field);
}
}
?>
</div><!-- End of hidden advanced section -->
<div class="QuestionSubmit">
<input name="save" type="submit" value="<?php echo escape($lang["save"]); ?>" />&nbsp;&nbsp;
<input type="button" class="button" onClick="CentralSpaceLoad('<?php echo $baseurl . "/pages/admin/admin_copy_field.php?ref=" . $ref . "&backurl=" . $url ?>',true);return false;" value="<?php echo escape($lang["copy-field"]); ?>">
<input name="migrate_data" id="migrate_data" type="hidden" value="">
<?php if ($fielddata["active"] == 0) { ?>
<input name="delete" type="button" value="<?php echo escape($lang["action-delete"])?>" onClick="if(confirm('<?php echo escape($lang["confirm-deletion"]) ?>')){jQuery('#field_edit_delete').val('yes');this.form.submit();}else{jQuery('#delete').val('');}" />
<?php } ?>
</div>
<?php
} ?>
<input type="hidden" name="save" id="field_edit_save" value="yes"/>
<input type="hidden" name="delete" id="field_edit_delete" value=""/>
</form>
</div><!-- End of Basics Box -->
<script>
registerCollapsibleSections();
initializeIndexOptions();
</script>
<?php
include "../../include/footer.php";

View File

@@ -0,0 +1,447 @@
<?php
include "../../include/boot.php";
include "../../include/authenticate.php";
if (!checkperm("a")) {
exit("Permission denied.");
}
$find = getval("find", "");
$offset = getval("offset", 0, true);
if (array_key_exists("find", $_POST)) {
$offset = 0;
} # reset page counter when posting
$restypefilter = getval("restypefilter", "");
$restypesfilter = ($restypefilter != "") ? array((int)$restypefilter) : [];
$field_order_by = getval("field_order_by", "order_by");
$field_sort = getval("field_sort", "asc");
$reorder_view = getval("reorder_view", false);
$backurl = getval("backurl", "");
if ($backurl == "") {
$backurl = $baseurl . "/pages/admin/admin_home.php";
}
$allow_reorder = false;
// Allow sorting if we are ordering metadata fields for all resource types (ie Resource type == "All" and $restypefilter=="")
if ($restypefilter == "" && $reorder_view) {
$allow_reorder = true;
}
include "../../include/header.php";
$url_params = array("restypefilter" => $restypefilter,
"field_order_by" => $field_order_by,
"field_sort" => $field_sort,
"find" => $find);
$url = generateURL($baseurl . "/pages/admin/admin_resource_type_fields.php", $url_params);
// Common ResourceSpace URL params are used as an override when calling {@see generateURL()}
$common_rs_url_params = [
'backurl' => $url,
];
if (getval("newfield", "") != "" && enforcePostRequest(false)) {
$newfieldname = getval("newfield", "");
$newfieldtype = getval("field_type", 0, true);
$newfieldrestype = getval("newfieldrestype", 0, true);
$new = create_resource_type_field($newfieldname, $newfieldrestype, $newfieldtype, "", true);
redirect($baseurl_short . 'pages/admin/admin_resource_type_field_edit.php?ref=' . $new . '&newfield=true');
}
function addColumnHeader($orderName, $labelKey)
{
global $baseurl, $group, $field_order_by, $field_sort, $find, $lang, $restypefilter, $url_params;
if ($field_order_by == $orderName && $field_sort == "asc") {
$arrow = '<span class="DESC"></span>';
} elseif ($field_order_by == $orderName && $field_sort == "desc") {
$arrow = '<span class="ASC"></span>';
} else {
$arrow = '';
}
$newparams = array();
$newparams["field_order_by"] = $orderName;
$newparams["field_sort"] = ($field_sort == "desc" || $field_order_by == "order_by") ? 'asc' : 'desc';
?>
<th>
<a
href="<?php echo generateURL($baseurl . "/pages/admin/admin_resource_type_fields.php", $url_params, $newparams); ?>"
onClick="return CentralSpaceLoad(this);">
<?php echo escape($lang[$labelKey]) . $arrow ?>
</a>
</th>
<?php
}
$links_trail = array(
array(
'title' => $lang["systemsetup"],
'href' => $baseurl_short . "pages/admin/admin_home.php",
'menu' => true
),
array(
'title' => $lang["admin_resource_type_fields"],
'help' => "resourceadmin/configure-metadata-field"
)
);
?>
<div class="BasicsBox">
<h1><?php echo escape($lang["admin_resource_type_fields"]); ?></h1>
<?php
renderBreadcrumbs($links_trail);
$introtext = text("introtext");
if ($introtext != "") {
echo "<p>" . text("introtext") . "</p>";
}
$fields = get_resource_type_fields($restypesfilter, $field_order_by, $field_sort, $find, array(), true);
if (!empty($restypesfilter) && !in_array(0, $restypesfilter)) {
// Don't show global fields as a specific resource type has been selected
$fields = array_values(array_filter($fields, function ($field) {
return $field["global"] != 1;
}));
}
$resource_types = get_resource_types();
$arr_restypes = array_column($resource_types, "name", "ref");
$results = count($fields);
?>
<div class="FormError" id="PageError"
<?php if (!isset($error_text)) { ?>
style="display:none;">
<?php
} else {
echo ">" . $error_text ;
} ?>
</div>
<?php
if ($allow_reorder) {
?>
<p><?php echo escape($lang["admin_resource_type_field_reorder_information"]); ?></p>
<?php
} elseif ($restypefilter == "") {
?>
<a
href="<?php echo generateURL($baseurl . "/pages/admin/admin_resource_type_fields.php", $url_params, array("restypefilter" => (($use_order_by_tab_view) ? "" : $restypefilter),"field_order_by" => "order_by","fieldsort" => "asc","reorder_view" => "true")); ?>"
onClick="return CentralSpaceLoad(this,true);">
<?php
echo LINK_CARET;
if ($use_order_by_tab_view) {
echo escape($lang["admin_resource_type_field_reorder_mode_all"]);
} else {
echo escape($lang["admin_resource_type_field_reorder_mode"]);
}
?>
</a>
<?php
} else {
?>
<p><?php echo escape($lang["admin_resource_type_field_reorder_select_restype"]); ?></p>
<?php
}
?>
<form method="post" id="AdminResourceTypeFieldForm" onSubmit="return CentralSpacePost(this,true);" action="<?php echo generateURL($baseurl . "/pages/admin/admin_resource_type_fields.php", $url_params); ?>" >
<?php generateFormToken("AdminResourceTypeFieldForm"); ?>
<div class="Question">
<label for="restypefilter"><?php echo escape($lang["property-resource_type"]); ?></label>
<div class="tickset">
<div class="Inline">
<select name="restypefilter" id="restypefilter" onChange="return CentralSpacePost(this.form,true);">
<option value="" <?php echo ($restypefilter == "") ? " selected" : ''; ?>>
<?php echo escape($lang["all"]); ?>
</option>
<option value="0" <?php echo ($restypefilter == "0") ? " selected" : ''; ?>>
<?php echo escape($lang["resourcetype-global_field"]); ?>
</option>
<?php for ($n = 0; $n < count($resource_types); $n++) { ?>
<option
value="<?php echo $resource_types[$n]["ref"]; ?>"
<?php echo ($restypefilter == $resource_types[$n]["ref"]) ? " selected" : ''; ?>>
<?php echo i18n_get_translated($resource_types[$n]["name"]); ?>
</option>
<?php } ?>
</select>
</div>
</div>
<div class="clearerleft"></div>
</div>
</form>
<div class="Listview">
<table id="resource_type_field_table" class="ListviewStyle">
<tr class="ListviewTitleStyle">
<?php
$system_tabs = get_tab_name_options();
addColumnHeader('ref', 'property-reference');
addColumnHeader('title', 'property-title');
addColumnHeader('name', 'property-shorthand_name');
addColumnHeader('type', 'property-field_type');
addColumnHeader('resource_type', 'resourcetypes');
if (!hook('replacetabnamecolumnheader')) {
addColumnHeader('tab_name', 'property-tab_name');
}
?>
<th>
<div class="ListTools"><?php echo escape($lang["tools"]); ?></div>
</th>
</tr>
<tbody id="resource_type_field_table_body">
<?php for ($n = 0; $n < count($fields); $n++) { ?>
<tr
class="resource_type_field_row <?php echo ($fields[$n]["active"] == 0) ? "FieldDisabled" : ''; ?>"
id="field_sort_<?php echo $fields[$n]["ref"];?>">
<td>
<?php echo str_highlight($fields[$n]["ref"], escape($find), STR_HIGHLIGHT_SIMPLE); ?>
</td>
<td>
<div class="ListTitle">
<a
href="<?php echo generateURL($baseurl . "/pages/admin/admin_resource_type_field_edit.php", $url_params, array("ref" => $fields[$n]["ref"],"backurl" => $url)); ?>"
onClick="jQuery('#resource_type_field_table_body').sortable('cancel');return CentralSpaceLoad(this,true);">
<span><?php echo str_highlight(i18n_get_translated($fields[$n]["title"]), escape($find), STR_HIGHLIGHT_SIMPLE); ?></span>
</a>
</div>
</td>
<td>
<?php echo str_highlight($fields[$n]["name"], escape($find), STR_HIGHLIGHT_SIMPLE); ?>
</td>
<td>
<?php
// If no field value is set it is treated as type 0 (single line text)
echo escape($fields[$n]["type"] != "" ? $lang[$field_types[$fields[$n]["type"]]] : $lang[$field_types[0]]);
?>
</td>
<?php
# Resolve resource type names
if ((bool)$fields[$n]["global"] == 1) {
$restypestring = $lang["resourcetype-global_field"];
} else {
$fieldrestypes = explode(",", (string)$fields[$n]["resource_types"]);
$restypestring = implode(", ", array_intersect_key($arr_restypes, array_flip($fieldrestypes)));
} ?>
<td title="<?php echo escape($restypestring); ?>">
<?php echo escape(tidy_trim($restypestring, 30)); ?>
</td>
<?php if (!hook('replacetabnamecolumn')) { ?>
<td>
<?php echo str_highlight($system_tabs[(int) $fields[$n]['tab']] ?? '', escape($find), STR_HIGHLIGHT_SIMPLE); ?>
</td>
<?php } ?>
<td>
<div class="ListTools">
<?php if ($field_order_by == "order_by" && $allow_reorder) { ?>
<a href="javascript:void(0)" class="movelink movedownlink" <?php echo ($n == count($fields) - 1) ? " disabled" : ''; ?>>
<i class="fas fa-arrow-down"></i>&nbsp;<?php echo escape($lang['action-move-down']); ?>
</a>
<a href="javascript:void(0)" class="movelink moveuplink" <?php echo ($n == 0) ? " disabled" : ''; ?>>
<i class="fas fa-arrow-up"></i>&nbsp;<?php echo escape($lang['action-move-up']); ?>
</a>
<?php } ?>
<a href="<?php echo generateURL("{$baseurl}/pages/admin/admin_copy_field.php", ['ref' => $fields[$n]["ref"]], $common_rs_url_params); ?>" onClick="CentralSpaceLoad(this,true)">
<i class="fas fa-copy"></i>&nbsp;<?php echo escape($lang["copy"]); ?>
</a>
<a href="<?php echo generateURL("{$baseurl}/pages/admin/admin_resource_type_field_edit.php", ['ref' => $fields[$n]["ref"]], $common_rs_url_params); ?>" onClick="jQuery('#resource_type_field_table_body').sortable('cancel');return CentralSpaceLoad(this,true);">
<i class="fas fa-edit"></i>&nbsp;&nbsp;<?php echo escape($lang["action-edit"]); ?>
</a>
<a href="<?php echo generateURL("{$baseurl}/pages/admin/admin_system_log.php", ['table' => 'resource_type_field', 'table_reference' => $fields[$n]['ref']], $common_rs_url_params); ?>" onclick="return CentralSpaceLoad(this, true);">
<i class="fas fa-history"></i>&nbsp;<?php echo escape($lang["log"]); ?>
</a>
</div>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<form method="post" id="AdminResourceTypeFieldForm2" onSubmit="return CentralSpacePost(this,true);" action="<?php echo generateURL($baseurl . "/pages/admin/admin_resource_type_fields.php", $url_params); ?>" >
<?php generateFormToken("AdminResourceTypeFieldForm2"); ?>
<div class="Question">
<label for="find"><?php echo escape($lang["find"]); ?></label>
<div class="tickset">
<div class="Inline">
<input type=text name="find" id="find" value="<?php echo escape($find)?>" maxlength="100" class="shrtwidth" />
</div>
<div class="Inline">
<input name="Submit" type="submit" value="<?php echo escape($lang["searchbutton"]); ?>" />
</div>
<?php if ($find != "") { ?>
<div class="Inline">
<input
name="resetform"
class="resetform"
type="submit"
value="<?php echo escape($lang["clearbutton"]); ?>"
onclick="CentralSpaceLoad('<?php echo generateURL($baseurl . "/pages/admin/admin_resource_type_fields.php", $url_params, array("find" => "")); ?>',false);return false;"
/>
</div>
<?php } ?>
</div>
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="newfield"><?php echo escape($lang["admin_resource_type_field_create"]); ?></label>
<div class="tickset">
<input type="hidden" name="newfieldrestype" value="<?php echo escape($restypefilter) ?>"/>
<div class="Inline">
<input type=text name="newfield" id="newtype" maxlength="100" class="shrtwidth" />
</div>
<div class="Inline">
<select name="field_type" id="new_field_type_select" class="medwidth">
<?php foreach ($field_types as $field_type => $field_type_description) { ?>
<option value="<?php echo $field_type ?>"><?php echo escape($lang[$field_type_description]) ; ?></option>
<?php } ?>
</select>
</div>
<div class="Inline">
<input name="Submit" type="submit" value="<?php echo escape($lang["create"]); ?>" />
</div>
</div>
<div class="clearerleft"></div>
</div>
</form>
</div><!-- End of BasicsBox -->
<script>
function ReorderResourceTypeFields(idsInOrder) {
var newOrder = [];
jQuery.each(idsInOrder, function() {
newOrder.push(this.substring(11));
});
jQuery.ajax({
type: 'POST',
url: '<?php echo generateURL($baseurl_short . "pages/admin/ajax/update_resource_type_field_order.php", $url_params, array("reorder" => "true")); ?>',
data: {
order: JSON.stringify(newOrder),
<?php echo generateAjaxToken('reorder_resource_type_fields');?>
},
success: function() {
jQuery('.movedownlink:last').prop( "disabled", true);
jQuery('.moveuplink:first').prop( "disabled", true);
jQuery('.movedownlink:not(:last)').prop( "disabled",false);
jQuery('.moveuplink:not(:first)').prop( "disabled", false);
}
});
}
function enableFieldsort(){
var fixHelperModified = function(e, tr) {
var $originals = tr.children();
var $helper = tr.clone();
$helper.children().each(function(index) {
jQuery(this).width($originals.eq(index).width())
});
return $helper;
};
jQuery('#resource_type_field_table_body').sortable({
items: "tr",
axis: "y",
cursor: 'move',
opacity: 0.6,
distance: 20,
stop: function(event, ui) {
<?php
if ($allow_reorder) {
?>
var idsInOrder = jQuery('#resource_type_field_table_body').sortable("toArray");
ReorderResourceTypeFields(idsInOrder);
<?php
} else {
if ($use_order_by_tab_view && $restypefilter != "") {
$errormessage = $lang["admin_resource_type_field_reorder_information_tab_order"];
} elseif (!$use_order_by_tab_view && $restypefilter == "" && $field_order_by == "order_by") {
$errormessage = $lang["admin_resource_type_field_reorder_select_restype"];
?>
hideinfo = true;
<?php
} else {
$errormessage = $lang["admin_resource_type_field_reorder_information_normal_order"];
}
?>
jQuery('#PageError').html("<?php echo $errormessage ?>");
jQuery('#PageError').show();
if (hideinfo !== undefined) {
jQuery('#PageInfo').hide();
}
jQuery("#resource_type_field_table_body").sortable("cancel");
<?php
}
?>
},
helper: fixHelperModified
}).disableSelection();
}
<?php if ($allow_reorder) { ?>
enableFieldsort();
<?php } ?>
jQuery(".moveuplink").click(function() {
if (jQuery(this).prop('disabled')) {
event.preventDefault();
event.stopImmediatePropagation();
}
curvalue = parseInt(jQuery(this).parents(".resource_type_field_row").children('.order_by_value').html());
parentvalue = parseInt(jQuery(this).parents(".resource_type_field_row").prev().children('.order_by_value').html());
jQuery(this).parents(".resource_type_field_row").children('.order_by_value').html(curvalue - 10);
jQuery(this).parents(".resource_type_field_row").prev().children('.order_by_value').html(parentvalue + 10);
jQuery(this).parents(".resource_type_field_row").insertBefore(jQuery(this).parents(".resource_type_field_row").prev());
var idsInOrder = jQuery('#resource_type_field_table_body').sortable("toArray");
ReorderResourceTypeFields(idsInOrder);
});
jQuery(".movedownlink").click(function() {
if (jQuery(this).prop('disabled')) {
event.preventDefault();
event.stopImmediatePropagation();
}
curvalue = parseInt(jQuery(this).parents(".resource_type_field_row").children('.order_by_value').html());
childvalue = parseInt(jQuery(this).parents(".resource_type_field_row").next().children('.order_by_value').html());
jQuery(this).parents(".resource_type_field_row").children('.order_by_value').html(curvalue + 10);
jQuery(this).parents(".resource_type_field_row").next().children('.order_by_value').html(childvalue - 10);
jQuery(this).parents(".resource_type_field_row").insertAfter(jQuery(this).parents(".resource_type_field_row").next());
var idsInOrder = jQuery('#resource_type_field_table_body').sortable("toArray");
ReorderResourceTypeFields(idsInOrder);
});
</script>
<?php
include "../../include/footer.php";
?>

View File

@@ -0,0 +1,279 @@
<?php
include "../../include/boot.php";
include "../../include/authenticate.php";
if (!checkperm("a")) {
exit($lang["error-permissiondenied"]);
}
$restype_order_by = getval("restype_order_by", "ref");
$restype_sort = strtolower(getval("restype_sort", "asc") == "asc") ? "asc" : "desc";
$url_params = array("restype_order_by" => $restype_order_by,"restype_sort" => $restype_sort);
$url = generateURL($baseurl . "/pages/admin/admin_resource_types.php", $url_params);
$sql_restype_order_by = $restype_order_by == "order_by" ? "CAST(order_by AS UNSIGNED)" : $restype_order_by;
$backurl = getval("backurl", "");
if ($backurl == "") {
$backurl = $baseurl . "/pages/admin/admin_home.php";
}
$newtype = getval("newtype", "");
if ($newtype != "" && enforcePostRequest(false)) {
$new = create_resource_type($newtype);
redirect($baseurl_short . "pages/admin/admin_resource_type_edit.php?ref=" . $new);
}
$resource_types = get_resource_types();
foreach ($resource_types as &$resource_type) {
$resource_type["fieldcount"] = count($resource_type["resource_type_fields"]);
}
// Sort resource types
if (isset($resource_types[0][$restype_order_by])) {
usort($resource_types, function ($a, $b) use ($restype_order_by, $restype_sort) {
return $restype_sort == "asc" ? $a[$restype_order_by] <=> $b[$restype_order_by] : $b[$restype_order_by] <=> $a[$restype_order_by];
});
}
include "../../include/header.php";
function addColumnHeader($orderName, $labelKey)
{
global $baseurl, $url, $restype_order_by, $restype_sort, $find, $lang;
if ($restype_order_by == $orderName) {
$arrow = '<span class="' . strtoupper($restype_sort) . '"></span>';
$linksort = ($restype_sort == "asc") ? 'desc' : 'asc';
} else {
$arrow = '';
$linksort = 'asc';
}
?>
<th>
<a href="<?php echo $baseurl ?>/pages/admin/admin_resource_types.php?restype_order_by=<?php echo escape($orderName) ?>&restype_sort=<?php echo $linksort; ?>&find=<?php echo urlencode((string)$find)?>&backurl=<?php echo urlencode((string)$url) ?>" onClick="return CentralSpaceLoad(this);">
<?php echo escape($lang[$labelKey]) . $arrow ?>
</a>
</th>
<?php
}
?>
<div class="BasicsBox">
<h1><?php echo escape($lang["resource_types_manage"]); ?></h1>
<?php
$links_trail = array(
array(
'title' => $lang["systemsetup"],
'href' => $baseurl_short . "pages/admin/admin_home.php",
'menu' => true
),
array(
'title' => $lang["resource_types_manage"],
'help' => "resourceadmin/resource-types"
)
);
renderBreadcrumbs($links_trail);
$introtext = text("introtext");
if ($introtext != "") {
echo "<p>" . escape(text("introtext")) . "</p>";
}
$allow_reorder = false;
// Allow sorting if we are ordering a single resource type, or if $use_order_by_tab_view is true (which means order_by values are across all resource types) and we can see all fields
if ($restype_order_by == "order_by") {
$allow_reorder = true;
}
if (!$allow_reorder) { ?>
<a href="<?php echo $baseurl . "/pages/admin/admin_resource_types.php?restype_order_by=order_by&restype_sort=asc" ?>" onClick="return CentralSpaceLoad(this,true);">
<?php echo LINK_CARET ?><?php echo escape($lang["admin_resource_type_reorder_mode"]) ?>
</a>
</p>
<?php
}
?>
<div class="FormError" id="PageError"
<?php if (!isset($error_text)) { ?>
style="display:none;">
<?php } else {
echo ">" . escape($error_text) ;
} ?>
</div>
<div class="Listview ListviewTight">
<table class="ListviewStyle">
<tr class="ListviewTitleStyle">
<?php
addColumnHeader('ref', 'property-reference');
addColumnHeader('name', 'property-name');
addColumnHeader('fieldcount', 'admin_resource_type_field_count');
?>
<th>
<div class="ListTools"><?php echo escape($lang["tools"]) ?></div>
</th>
</tr>
<tbody id="resource_type_table_body">
<?php for ($n = 0; $n < count($resource_types); $n++) { ?>
<tr class="resource_type_row" id="restype_sort_<?php echo $resource_types[$n]["ref"];?>">
<td>
<?php echo $resource_types[$n]["ref"];?>
</td>
<td>
<div class="ListTitle">
<a href="<?php echo $baseurl_short?>pages/admin/admin_resource_type_edit.php?ref=<?php echo $resource_types[$n]["ref"]; ?>&backurl=<?php echo urlencode($url) ?>" onClick="return CentralSpaceLoad(this,true);">
<?php echo escape(i18n_get_translated($resource_types[$n]["name"]));?>
</a>
</div>
</td>
<td>
<div class="ListTitle">
<?php if ($resource_types[$n]["resource_type_fields"] != "") { ?>
<a href="<?php echo $baseurl_short?>pages/admin/admin_resource_type_fields.php?restypefilter=<?php echo $resource_types[$n]["ref"] . "&backurl=" . urlencode($url) ?>" onClick="return CentralSpaceLoad(this,true);">
<?php echo $resource_types[$n]["fieldcount"]; ?>
</a>
<?php
} else {
echo "0";
} ?>
</div>
</td>
<td>
<div class="ListTools">
<?php if ($restype_order_by == "order_by") { ?>
<a
href="javascript:void(0)"
class="movelink movedownlink"
<?php echo ($n == count($resource_types) - 1) ? "disabled" : ''; ?>>
<?php echo LINK_CARET . escape($lang['action-move-down']) ?>
</a>
<a
href="javascript:void(0)"
class="movelink moveuplink"
<?php echo ($n == 0) ? "disabled" : ''; ?>>
<?php echo LINK_CARET . escape($lang['action-move-up'])?>
</a>
<?php
}
?>
<a href="<?php echo $baseurl ?>/pages/admin/admin_resource_type_edit.php?ref=<?php echo $resource_types[$n]["ref"]; ?>&backurl=<?php echo urlencode($url) ?>" onClick="return CentralSpaceLoad(this,true);">
<i class="fas fa-edit"></i>&nbsp;<?php echo escape($lang["action-edit"]); ?>
</a>
<a href="<?php echo $baseurl ?>/pages/admin/admin_resource_type_fields.php?restypefilter=<?php echo $resource_types[$n]["ref"] . "&backurl=" . urlencode($url) ?>" onClick="return CentralSpaceLoad(this,true);">
<i class="fas fa-bars"></i>&nbsp;<?php echo escape($lang["metadatafields"]) ?>
</a>
</div>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
<div class="BasicsBox">
<form method="post" action="<?php echo $baseurl_short?>pages/admin/admin_resource_types.php" onSubmit="return CentralSpacePost(this,true);">
<?php generateFormToken("admin_resource_types"); ?>
<div class="Question">
<label for="newtype"><?php echo escape($lang["admin_resource_type_create"]) ?></label>
<div class="tickset">
<div class="Inline"><input type=text name="newtype" id="newtype" maxlength="100" class="shrtwidth" /></div>
<div class="Inline"><input name="Submit" type="submit" value="<?php echo escape($lang["create"]) ?>" /></div>
</div>
<div class="clearerleft"></div>
</div>
<input type="hidden" name="save" id="save" value="yes"/>
</form>
</div>
<script>
function ReorderResourceTypes(idsInOrder) {
var newOrder = [];
jQuery.each(idsInOrder, function() {
newOrder.push(this.substring(13));
});
jQuery.ajax({
type: 'POST',
url: '<?php echo $baseurl_short?>pages/admin/ajax/update_resource_type_order.php?reorder=true',
data: {
order:JSON.stringify(newOrder),
<?php echo generateAjaxToken('ReorderResourceTypes'); ?>
},
success: function() {
jQuery('.movedownlink:last').prop("disabled",true);
jQuery('.moveuplink:first').prop("disabled",true);
jQuery('.movedownlink:not(:last)').prop("disabled",false);
jQuery('.moveuplink:not(:first)').prop("disabled",false);
}
});
}
function enableRestypesort() {
var fixHelperModified = function(e, tr) {
var $originals = tr.children();
var $helper = tr.clone();
$helper.children().each(function(index)
{
jQuery(this).width($originals.eq(index).width())
});
return $helper;
};
jQuery('#resource_type_table_body').sortable({
items: ".resource_type_row",
axis: "y",
cursor: 'move',
opacity: 0.6,
distance: 20,
stop: function(event, ui) {
<?php if ($allow_reorder) { ?>
var idsInOrder = jQuery('#resource_type_table_body').sortable("toArray");
ReorderResourceTypes(idsInOrder);
<?php } else {
$errormessage = $lang["admin_resource_type_reorder_information_tab_order"];
?>
jQuery('#PageError').html("<?php echo escape($errormessage) ?>").show();
jQuery( "#resource_type_table_body" ).sortable( "cancel" );
<?php
} ?>
},
helper: fixHelperModified
}).disableSelection();
}
enableRestypesort();
jQuery(".moveuplink").click(function(e) {
if (jQuery(this).prop('disabled')) {
e.preventDefault();
e.stopImmediatePropagation();
}
jQuery(this).parents(".resource_type_row").insertBefore(jQuery(this).parents(".resource_type_row").prev());
var idsInOrder = jQuery('#resource_type_table_body').sortable("toArray");
ReorderResourceTypes(idsInOrder);
});
jQuery(".movedownlink").click(function(e) {
if (jQuery(this).prop('disabled')) {
e.preventDefault();
e.stopImmediatePropagation();
}
jQuery(this).parents(".resource_type_row").insertAfter(jQuery(this).parents(".resource_type_row").next());
var idsInOrder = jQuery('#resource_type_table_body').sortable("toArray");
ReorderResourceTypes(idsInOrder);
});
</script>
<?php
include "../../include/footer.php";

View File

@@ -0,0 +1,229 @@
<?php
include "../../include/boot.php";
include "../../include/authenticate.php";
if (!checkperm("a")) {
exit("Permission denied.");
}
include "../../include/header.php";
$find = getval("find", "");
$order_by = getval("orderby", "width");
// Construct the search query.
$sql = "SELECT ref, id, internal, width, height, name FROM preview_size";
$params = array();
if ($find != "") {
$sql .= " where id like ? or name like ? or width like ? or height like ?";
$params[] = "s";
$params[] = "%{$find}%";
$params[] = "s";
$params[] = "%{$find}%";
$params[] = "s";
$params[] = "%{$find}%";
$params[] = "s";
$params[] = "%{$find}%";
}
$order_by = in_array($order_by, array("width","height","id","name")) ? $order_by : "width"; // Force $order_by to something we expect so it's SQL safe.
$sql .= " ORDER BY {$order_by}";
$sizes = ps_query($sql, $params);
?>
<div class="BasicsBox">
<h1><?php echo escape($lang["page-title_size_management"]); ?></h1>
<?php
$links_trail = array(
array(
'title' => $lang["systemsetup"],
'href' => $baseurl_short . "pages/admin/admin_home.php",
'menu' => true
),
array(
'title' => $lang["page-title_size_management"]
)
);
renderBreadcrumbs($links_trail);
?>
<p>
<?php
echo escape($lang['page-subtitle_size_management']);
render_help_link('systemadmin/manage_sizes');
?>
</p>
<?php
function addColumnHeader($orderName, $labelKey)
{
global $baseurl, $order_by, $find, $lang;
if ($order_by == $orderName) {
$image = '<span class="ASC"></span>';
} elseif ($order_by == $orderName . ' desc') {
$image = '<span class="DESC"></span>';
} else {
$image = '';
}
?>
<th>
<a
href="<?php echo $baseurl ?>/pages/admin/admin_size_management.php?<?php
echo ($find != "") ? "&find=" . escape($find) : ''; ?>&orderby=<?php
echo $orderName . ($order_by == $orderName ? '+desc' : ''); ?>"
onClick="return CentralSpaceLoad(this);">
<?php echo escape($lang[$labelKey]) . $image ?>
</a>
</th>
<?php
}
?>
<div class="Listview">
<table class="ListviewStyle">
<tr class="ListviewTitleStyle">
<?php addColumnHeader("id", "property-id"); ?>
<?php addColumnHeader("name", "property-name"); ?>
<?php addColumnHeader("width", "property-width"); ?>
<?php addColumnHeader("height", "property-height"); ?>
<th>
<div class="ListTools"><?php echo escape($lang["tools"]); ?></div>
</th>
</tr>
<?php
foreach ($sizes as $size) {
if ($size['internal'] == '1' && !$internal_preview_sizes_editable) {
$edit_url = "";
} else {
$edit_url = "{$baseurl_short}pages/admin/admin_size_management_edit.php?ref={$size["ref"]}" . ($find == "" ? "" : "&find={$find}") . ($order_by == "name" ? "" : "&orderby={$order_by}");
}
?>
<tr>
<td>
<?php if ($edit_url != "") { ?>
<a href="<?php echo escape($edit_url); ?>" onClick="return CentralSpaceLoad(this,true);">
<?php }
echo str_highlight($size["id"], $find, STR_HIGHLIGHT_SIMPLE);
if ($edit_url != "") { ?>
</a>
<?php
} ?>
</td>
<td>
<?php if ($edit_url != "") { ?>
<a href="<?php echo escape($edit_url); ?>" onClick="return CentralSpaceLoad(this,true);">
<?php }
echo str_highlight($size["name"], $find, STR_HIGHLIGHT_SIMPLE);
if ($edit_url != "") { ?>
</a>
<?php
} ?>
</td>
<td>
<?php if ($edit_url != "") { ?>
<a href="<?php echo escape($edit_url); ?>" onClick="return CentralSpaceLoad(this,true);">
<?php
}
echo str_highlight($size["width"], $find, STR_HIGHLIGHT_SIMPLE);
if ($edit_url != "") { ?>
</a>
<?php
} ?>
</td>
<td>
<?php if ($edit_url != "") { ?>
<a href="<?php echo escape($edit_url); ?>" onClick="return CentralSpaceLoad(this,true);">
<?php
}
echo str_highlight($size["height"], $find, STR_HIGHLIGHT_SIMPLE);
if ($edit_url != "") { ?>
</a>
<?php
} ?>
</td>
<td>
<?php if ($edit_url != "") { ?>
<div class="ListTools">
<a href="<?php echo escape($edit_url); ?>" onClick="return CentralSpaceLoad(this,true);">
<i class="fa fa-edit"></i>&nbsp;<?php echo escape($lang["action-edit"]); ?>
</a>
</div>
<?php
}
?>
</td>
</tr>
<?php
}
?>
</table>
</div>
</div><!-- end of BasicsBox -->
<div class="BasicsBox">
<form method="post" action="<?php echo $baseurl_short?>pages/admin/admin_size_management.php" onSubmit="return CentralSpacePost(this,false);">
<?php generateFormToken("admin_size_management"); ?>
<div class="Question">
<label for="find"><?php echo escape($lang["property-search_filter"]); ?></label>
<input name="find" type="text" class="medwidth" value="<?php echo escape($find); ?>">
<input name="save" type="submit" value="<?php echo escape($lang["searchbutton"]); ?>">
<div class="clearerleft"></div>
</div>
<?php if ($find != "") { ?>
<div class="QuestionSubmit">
<input
name="buttonsave"
type="button"
onclick="CentralSpaceLoad('admin_size_management.php',false);"
value="<?php echo escape($lang["clearbutton"]); ?>"
>
</div>
<?php
}
?>
</form>
</div>
<div class="BasicsBox">
<form method="post" action="<?php echo $baseurl_short; ?>pages/admin/admin_size_management_edit.php" onSubmit="return CentralSpacePost(this,false);">
<?php generateFormToken("admin_size_management_edit"); ?>
<div class="Question">
<label for="name"><?php echo escape($lang['action-title_create_size_with_id']); ?></label>
<div class="tickset">
<div class="Inline">
<input name="newsizeid" type="text" value="" class="shrtwidth" maxlength="3">
</div>
<div class="Inline">
<input name="Submit" type="submit" value="<?php echo escape($lang["create"]); ?>" onclick="return (this.form.elements[0].value!='');">
</div>
</div>
<div class="clearerleft"></div>
</div>
<?php if ($order_by) { ?>
<input type="hidden" name="orderby" value="<?php echo $order_by; ?>">
<?php
}
if ($find) { ?>
<input type="hidden" name="find" value="<?php echo escape($find); ?>">
<?php
}
?>
</form>
</div>
<?php
include "../../include/footer.php";

View File

@@ -0,0 +1,186 @@
<?php
include "../../include/boot.php";
include "../../include/authenticate.php";
if (!checkperm("a")) {
exit("Permission denied.");
}
$find = getval("find", "");
$order_by = getval("orderby", "");
$url_params = ($order_by ? "&orderby={$order_by}" : "") . ($find ? "&find={$find}" : "");
# create new record from callback
$new_size_id = getval("newsizeid", "");
if ($new_size_id != "" && enforcePostRequest(false)) {
ps_query("INSERT INTO preview_size(id,name,internal,width,height) VALUES(?,?,0,0,0)", array("s",strtolower($new_size_id),"s",$new_size_id));
$ref = sql_insert_id();
log_activity(null, LOG_CODE_CREATED, $new_size_id, 'preview_size', 'id', $ref, null, '');
clear_query_cache("schema");
redirect("{$baseurl_short}pages/admin/admin_size_management_edit.php?ref={$ref}{$url_params}"); // redirect to prevent repost and expose form data
exit;
}
$ref = getval('ref', '');
if (!ps_value("select ref as value from preview_size where ref=? and internal<>'1'", array("i",$ref), false) && !$internal_preview_sizes_editable) { // note that you are not allowed to edit internal sizes without $internal_preview_sizes_editable=true
redirect("{$baseurl_short}pages/admin/admin_size_management.php?{$url_params}"); // fail safe by returning to the size management page if duff ref passed
exit;
}
if (getval("deleteme", false) && enforcePostRequest(false)) {
ps_query("DELETE FROM preview_size WHERE ref=?", array("i",$ref));
log_activity(null, LOG_CODE_DELETED, null, 'preview_size', null, $ref);
clear_query_cache("schema");
redirect("{$baseurl_short}pages/admin/admin_size_management.php?{$url_params}"); // return to the size management page
exit;
}
if (getval("save", false) && enforcePostRequest(false)) {
$cols = array();
$name = getval("name", "");
if ($name != "") {
$cols["name"] = $name;
}
$width = getval("width", -1, true);
if ($width >= 0) {
$cols["width"] = $width;
}
$height = getval("height", -1, true);
if ($height >= 0) {
$cols["height"] = $height;
}
$cols["allow_preview"] = (getval('allowpreview', false) ? "1" : "0");
$cols["allow_restricted"] = (getval('allowrestricted', false) ? "1" : "0");
foreach ($cols as $col => $val) {
if (isset($sql_columns)) {
$sql_columns .= ",";
} else {
$sql_columns = "";
$params = array();
}
$sql_columns .= "{$col}=?";
$params[] = "s";
$params[] = $val;
log_activity(null, LOG_CODE_EDITED, $val, 'preview_size', $col, $ref);
}
if (isset($sql_columns)) {
$params[] = "i";
$params[] = $ref;
ps_query("UPDATE preview_size SET {$sql_columns} WHERE ref=?", $params);
clear_query_cache("schema");
}
redirect("{$baseurl_short}pages/admin/admin_size_management.php?{$url_params}"); // return to the size management page
exit;
}
$record = ps_query("SELECT ref, id, width, height, padtosize, `name`, internal, allow_preview, allow_restricted, quality FROM preview_size WHERE ref = ?", array("i",$ref));
$record = $record[0];
include "../../include/header.php";
$url_params_edit = array(
"ref" => $ref,
"orderby" => $order_by,
"find" => $find
);
?>
<form
method="post"
enctype="multipart/form-data"
action="<?php echo generateURL($baseurl_short . 'pages/admin/admin_size_management_edit.php', $url_params_edit);?>"
id="mainform"
onSubmit="return CentralSpacePost(this, true);">
<?php generateFormToken("mainform"); ?>
<div class="BasicsBox">
<h1><?php echo escape($lang["page-title_size_management_edit"]); ?></h1>
<?php
$links_trail = array(
array(
'title' => $lang["systemsetup"],
'href' => $baseurl_short . "pages/admin/admin_home.php",
'menu' => true
),
array(
'title' => $lang["page-title_size_management"],
'href' => $baseurl_short . "pages/admin/admin_size_management.php?" . $url_params
),
array(
'title' => $lang["page-title_size_management_edit"]
)
);
renderBreadcrumbs($links_trail);
?>
<p>
<?php
echo escape($lang['page-subtitle_size_management_edit']);
render_help_link('systemadmin/manage_sizes');
?>
</p>
<input type="hidden" name="save" value="1">
<div class="Question">
<label for="reference"><?php echo escape($lang["property-id"]); ?></label>
<div class="Fixed"><?php echo $record['id']; ?></div>
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="name"><?php echo escape($lang["property-name"]); ?></label>
<input name="name" type="text" class="stdwidth" value="<?php echo $record['name']; ?>">
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="name"><?php echo escape($lang["property-width"]); ?></label>
<input name="width" type="text" class="shrtwidth" value="<?php echo $record['width']; ?>">
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="name"><?php echo escape($lang["property-height"]); ?></label>
<input name="height" type="text" class="shrtwidth" value="<?php echo $record['height']; ?>">
<div class="clearerleft"></div>
</div>
<div class="Question">
<label><?php echo escape($lang['property-allow_preview']); ?></label>
<input name="allowpreview" type="checkbox" value="1"<?php echo ($record['allow_preview']) ? 'checked="checked"' : ''; ?>>
<div class="clearerleft"></div>
</div>
<div class="Question">
<label><?php echo escape($lang['property-allow_restricted_download']); ?></label>
<input name="allowrestricted" type="checkbox" value="1"<?php echo ($record['allow_restricted']) ? 'checked="checked"' : ''; ?>>
<div class="clearerleft"></div>
</div>
<?php if (!$record['internal']) { ?>
<div class="Question">
<label><?php echo escape($lang["fieldtitle-tick_to_delete_size"])?></label>
<input name="deleteme" type="checkbox" value="1">
<div class="clearerleft"></div>
</div>
<?php
}
?>
<div class="QuestionSubmit">
<input name="buttonsave" type="submit" value="<?php echo escape($lang["save"]); ?>">
</div>
</div>
</form>
<?php
include "../../include/footer.php";

View File

@@ -0,0 +1,741 @@
<?php
include '../../include/boot.php';
include '../../include/authenticate.php';
if (!checkperm('a')) {
exit('Permission denied.');
}
include_once '../../include/config_functions.php';
include_once '../../include/ajax_functions.php';
$ajax = getval('ajax', '') === 'true';
// Common config fields' options
$enable_disable_options = array($lang['userpreference_disable_option'], $lang['userpreference_enable_option']);
$yes_no_options = array($lang['no'], $lang['yes']);
// System section
$page_def[] = config_add_html('<h3 class="CollapsibleSectionHead">' . $lang['systemsetup'] . '</h3><div id="SystemConfigSystemSection" class="CollapsibleSection">');
$page_def[] = config_add_text_input('applicationname', $lang['setup-applicationname'], false, 420, false, '', true);
$page_def[] = config_add_text_input('email_from', $lang['setup-emailfrom'], false, 420, false, '', true);
$page_def[] = config_add_text_input('email_notify', $lang['setup-emailnotify'], false, 420, false, '', true);
$page_def[] = config_add_single_select(
'user_local_timezone',
$lang['systemconfig_user_local_timezone'],
timezone_identifiers_list(),
false,
420,
'',
true
);
$page_def[] = config_add_text_input(
'download_filename_format',
$lang['setup-download_filename_format'],
false,
420,
false,
'',
true,
false,
'resourceadmin/download_filename_format'
);
$page_def[] = config_add_html('</div>');
// User interface section
$page_def[] = config_add_html('<h3 class="CollapsibleSectionHead collapsed">' . $lang['userpreference_user_interface'] . '</h3><div id="SystemConfigUserInterfaceSection" class="CollapsibleSection">');
// Font selection
$fontsdir = scandir(__DIR__ . "/../../css/fonts/");
$fonts = array();
foreach ($fontsdir as $f) {
if (strpos($f, ".css") !== false) { // Valid font CSS definition
$fn = substr($f, 0, strlen($f) - 4);
$fonts[$fn] = $fn;
}
}
$page_def[] = config_add_single_select('global_font', $lang['font'], $fonts, true, 420, '', true, "jQuery('#global_font_link').attr('href','" . $baseurl . "/css/fonts/' + this.value + '.css');");
$page_def[] = config_add_file_input(
'custom_font',
$lang['systemconfig_customfont_label'],
$baseurl . '/pages/admin/admin_system_config.php',
316,
array('woff2', 'woff', 'ttf', 'otf')
);
$page_def[] = config_add_file_input(
'linkedheaderimgsrc',
$lang['systemconfig_linkedheaderimgsrc_label'],
$baseurl . '/pages/admin/admin_system_config.php',
316,
array('gif','jpg','png','svg'),
true
);
$page_def[] = config_add_file_input(
'linkedheaderimgsrc_dark',
$lang['systemconfig_linkedheaderimgsrc_dark_label'],
$baseurl . '/pages/admin/admin_system_config.php',
316,
array('gif','jpg','png','svg'),
true
);
$page_def[] = config_add_file_input(
'header_favicon',
$lang['systemconfig_header_favicon_label'],
$baseurl . '/pages/admin/admin_system_config.php',
316,
array('ico','png','svg'),
true
);
$page_def[] = config_add_colouroverride_input(
'header_colour_style_override',
$lang["setup-headercolourstyleoverride"],
'',
null,
true,
"jQuery('#Header').css('background',value);"
);
$page_def[] = config_add_colouroverride_input(
'header_link_style_override',
$lang["setup-headerlinkstyleoverride"],
'',
null,
true,
"jQuery('#HeaderNav1 li a').css('color',value);jQuery('#HeaderNav1 li.UploadButton a').css('color','white');jQuery('#HeaderNav2 a').css('color',value);jQuery('#HeaderNav2 li').css('border-color', value);"
);
$page_def[] = config_add_colouroverride_input(
'home_colour_style_override',
$lang["setup-homecolourstyleoverride"],
'',
null,
true,
"jQuery('#SearchBox').css('background',value); jQuery('#HomeSiteText.dashtext').css('background',value); jQuery('.HomePanelIN').css('background',value); jQuery('#BrowseBar').css('background',value); jQuery('.SearchBarTab.SearchBarTabSelected').css('background', value);"
);
$page_def[] = config_add_colouroverride_input(
'collection_bar_background_override',
$lang["setup-collectionbarbackground"],
'',
null,
true,
"jQuery('.CollectBack').css('background',value);"
);
$page_def[] = config_add_colouroverride_input(
'collection_bar_foreground_override',
$lang["setup-collectionbarforeground"],
'',
null,
true,
"jQuery('.CollectionPanelShell').css('background-color',value);jQuery('#CollectionDiv select').css('background-color',value); jQuery('.ui-layout-resizer').css('background',value);"
);
$page_def[] = config_add_colouroverride_input(
'button_colour_override',
$lang["setup-buttoncolouroverride"],
'',
null,
true,
"jQuery('button:not(.search-icon),input[type=submit],input[type=button],.RecordPanel .RecordDownloadSpace .DownloadDBlend a,.UploadButton a').css('background-color',value);"
);
$page_def[] = config_add_single_select('thumbs_default', $lang['userpreference_thumbs_default_label'], array('show' => $lang['showthumbnails'], 'hide' => $lang['hidethumbnails']), true, 420, '', true);
$page_def[] = config_add_boolean_select('resource_view_modal', $lang['userpreference_resource_view_modal_label'], $enable_disable_options, 420, '', true);
$page_def[] = config_add_boolean_select('modal_default', $lang['systemconfig_modal_default'], $enable_disable_options, 420, '', true);
$page_def[] = config_add_boolean_select('basic_simple_search', $lang['userpreference_basic_simple_search_label'], $enable_disable_options, 420, '', true);
$page_def[] = config_add_boolean_select('comments_resource_enable', $lang['systemconfig_comments'], $enable_disable_options, 420, '', true);
$page_def[] = config_add_single_select('upload_then_edit', $lang['default_upload_sequence'], array(true => $lang['upload_first_then_set_metadata'], false => $lang['set_metadata_then_upload']), true, 420, '', true);
$page_def[] = config_add_boolean_select('byte_prefix_mode_decimal', $lang['byte_prefix_mode_decimal'], $enable_disable_options, 420, '', true);
$page_def[] = config_add_boolean_select('tilenav', $lang['userpreference_tilenavdefault'], $enable_disable_options, 420, '', true);
$page_def[] = config_add_boolean_select(
'use_native_input_for_date_field',
$lang['systemconfig_use_native_input_for_date_field'],
$enable_disable_options,
420,
'',
true,
null,
false,
$lang['systemconfig_native_date_input_no_partials_supported'],
);
$page_def[] = config_add_html('</div>');
// Watermark section
$page_def[] = config_add_html('<h3 class="CollapsibleSectionHead collapsed">' . $lang['watermark_header'] . '</h3><div id="SystemConfigWatermarkSection" class="CollapsibleSection">');
$page_def[] = config_add_file_input(
'watermark',
$lang['watermark_label'],
$baseurl . '/pages/admin/admin_system_config.php',
316,
array('png'),
true
);
$page_def[] = config_add_html('</div>');
// Multilingual section
$page_def[] = config_add_html('<h3 class="CollapsibleSectionHead collapsed">' . $lang['systemconfig_multilingual'] . '</h3><div id="SystemConfigMultilingualSection" class="CollapsibleSection">');
// Add localised language for display when selecting languages.
$display_languages = $languages;
foreach ($display_languages as $key => $value) {
$display_languages[$key] = get_display_language($key, $value);
}
$page_def[] = config_add_single_select('defaultlanguage', $lang['systemconfig_default_language_label'], $display_languages, true, 420, '', true);
$page_def[] = config_add_boolean_select('disable_languages', $lang['disable_languages'], $yes_no_options, 420, '', true);
$page_def[] = config_add_boolean_select('browser_language', $lang['systemconfig_browser_language_label'], $enable_disable_options, 420, '', true);
$page_def[] = config_add_html('</div>');
// Search section
$page_def[] = config_add_html('<h3 class="CollapsibleSectionHead collapsed">' . $lang['searchcapability'] . '</h3><div id="SystemConfigSearchSection" class="CollapsibleSection">');
$sort_order_fields = array('relevance' => $lang['relevance']);
if ($popularity_sort) {
$sort_order_fields['popularity'] = $lang['popularity'];
}
if ($orderbyrating) {
$sort_order_fields['rating'] = $lang['rating'];
}
if ($date_column) {
$sort_order_fields['date'] = $lang['date'];
}
if ($colour_sort) {
$sort_order_fields['colour'] = $lang['colour'];
}
if ($order_by_resource_id) {
$sort_order_fields['resourceid'] = $lang['resourceid'];
}
$sort_order_fields['resourcetype'] = $lang['type'];
foreach ($sort_fields as $field) {
$field_data = get_resource_type_field($field);
if ($field_data !== false) {
$sort_order_fields["field$field"] = $field_data["title"];
}
}
$page_def[] = config_add_single_select(
'default_sort',
$lang['userpreference_default_sort_label'],
$sort_order_fields,
true,
420,
'',
true
);
$page_def[] = config_add_single_select(
'default_sort_direction',
$lang['userpreference_default_sort_order_label'],
['ASC' => 'Ascending', 'DESC' => 'Descending'],
true,
420,
'',
true
);
$default_display_array = array();
$default_display_array['thumbs'] = $lang['largethumbstitle'];
if ($xlthumbs || $GLOBALS['default_display'] == 'xlthumbs') {
$default_display_array['xlthumbs'] = $lang['xlthumbstitle'];
}
$default_display_array['list'] = $lang['listtitle'];
$default_display_array['strip'] = $lang['striptitle'];
$page_def[] = config_add_single_select('default_perpage', $lang['userpreference_default_perpage_label'], $results_display_array, false, 420, '', true);
$page_def[] = config_add_single_select(
'default_display',
$lang['userpreference_default_display_label'],
$default_display_array,
true,
420,
'',
true
);
$page_def[] = config_add_boolean_select('archive_search', $lang['stat-archivesearch'], $enable_disable_options, 420, '', true);
$page_def[] = config_add_boolean_select('display_resource_id_in_thumbnail', $lang['systemconfig_display_resource_id_in_thumbnail_label'], $enable_disable_options, 420, '', true);
$page_def[] = config_add_boolean_select('advanced_search_contributed_by', $lang['systemconfig_advanced_search_contributed_by_label'], $enable_disable_options, 420, '', true);
$page_def[] = config_add_boolean_select('advanced_search_media_section', $lang['systemconfig_advanced_search_media_section_label'], $enable_disable_options, 420, '', true);
$page_def[] = config_add_html('</div>');
// Navigation section
$page_def[] = config_add_html('<h3 class="CollapsibleSectionHead collapsed">' . $lang['systemconfig_navigation'] . '</h3><div id="SystemConfigNavigationSection" class="CollapsibleSection">');
$page_def[] = config_add_boolean_select('help_link', $lang['systemconfig_help_link_label'], $yes_no_options, 420, '', true);
$page_def[] = config_add_boolean_select('recent_link', $lang['systemconfig_recent_link_label'], $yes_no_options, 420, '', true);
$page_def[] = config_add_boolean_select('mycollections_link', $lang['systemconfig_mycollections_link_label'], $yes_no_options, 420, '', true);
$page_def[] = config_add_boolean_select('myrequests_link', $lang['systemconfig_myrequests_link_label'], $yes_no_options, 420, '', true);
$page_def[] = config_add_boolean_select('research_link', $lang['systemconfig_research_link_label'], $yes_no_options, 420, '', true);
$page_def[] = config_add_boolean_select('themes_navlink', $lang['systemconfig_themes_navlink_label'], $yes_no_options, 420, '', true);
$page_def[] = config_add_boolean_select('use_theme_as_home', $lang['systemconfig_use_theme_as_home_label'], $yes_no_options, 420, '', true);
$page_def[] = config_add_boolean_select('use_recent_as_home', $lang['systemconfig_use_recent_as_home_label'], $yes_no_options, 420, '', true);
$page_def[] = config_add_html('</div>');
// Browse Bar section
$page_def[] = config_add_html('<h3 class="CollapsibleSectionHead collapsed">' . $lang['systemconfig_browse_bar_section'] . '</h3><div id="SystemConfigFeaturedCollectionSection" class="CollapsibleSection">');
$page_def[] = config_add_boolean_select('browse_bar', $lang['systemconfig_browse_bar_enable'], $yes_no_options, 420, '', true);
$page_def[] = config_add_boolean_select('browse_bar_workflow', $lang['systemconfig_browse_bar_workflow'], $yes_no_options, 420, '', true);
$page_def[] = config_add_html('</div>');
// Collection section
$page_def[] = config_add_html('<h3 class="CollapsibleSectionHead collapsed">' . $lang['collections'] . '</h3><div id="SystemConfigCollectionSection" class="CollapsibleSection">');
$page_def[] = config_add_boolean_select('show_collection_name', $lang['systemconfig_show_collection_name'], $yes_no_options, 420, '', true);
$page_def[] = config_add_html('</div>');
// Featured Collection section
$page_def[] = config_add_html('<h3 class="CollapsibleSectionHead collapsed">' . $lang['systemconfig_featured_collections'] . '</h3><div id="SystemConfigFeaturedCollectionSection" class="CollapsibleSection">');
$page_def[] = config_add_boolean_select('enable_themes', $lang['systemconfig_enable_themes'], $yes_no_options, 420, '', true);
$page_def[] = config_add_boolean_select('themes_simple_view', $lang['systemconfig_themes_simple_view'], $yes_no_options, 420, '', true);
$page_def[] = config_add_html('</div>');
// Workflow section
$page_def[] = config_add_html('<h3 class="CollapsibleSectionHead collapsed">' . $lang['systemconfig_workflow'] . '</h3><div id="SystemConfigWorkflowSection" class="CollapsibleSection">');
$page_def[] = config_add_boolean_select('research_request', $lang['researchrequest'], $enable_disable_options, 420, '', true);
$page_def[] = config_add_html('</div>');
// Actions section
$page_def[] = config_add_html('<h3 class="CollapsibleSectionHead collapsed">' . $lang['actions'] . '</h3><div id="SystemConfigActionsSection" class="CollapsibleSection">');
$page_def[] = config_add_boolean_select('actions_enable', $lang['actions-enable'], $enable_disable_options, 420, '', true);
$page_def[] = config_add_boolean_select('actions_resource_requests', $lang['actions_resource_requests_default'], $enable_disable_options, 420, '', true);
$page_def[] = config_add_boolean_select('actions_account_requests', $lang['actions_account_requests_default'], $enable_disable_options, 420, '', true);
$page_def[] = config_add_html('</div>');
// Metadata section
$page_def[] = config_add_html('<h3 class="CollapsibleSectionHead collapsed">' . $lang['metadata'] . '</h3><div id="SystemConfigMetadataSection" class="CollapsibleSection">');
$page_def[] = config_add_boolean_select('metadata_report', $lang['metadata-report'], $enable_disable_options, 420, '', true);
$page_def[] = config_add_boolean_select('metadata_read_default', $lang['embedded_metadata'], array($lang['embedded_metadata_donot_extract_option'], $lang['embedded_metadata_extract_option']), 420, '', true);
$page_def[] = config_add_html('</div>');
// User accounts section
$page_def[] = config_add_html('<h3 class="CollapsibleSectionHead collapsed">' . $lang['systemconfig_user_accounts'] . '</h3><div id="SystemConfigUserAccountsSection" class="CollapsibleSection">');
$page_def[] = config_add_boolean_select('allow_account_request', $lang['systemconfig_allow_account_request_label'], $yes_no_options, 420, '', true);
$page_def[] = config_add_boolean_select('terms_download', $lang['systemconfig_terms_download_label'], $enable_disable_options, 420, '', true);
$page_def[] = config_add_boolean_select('terms_login', $lang['systemconfig_terms_login_label'], $enable_disable_options, 420, '', true);
$page_def[] = config_add_boolean_select('terms_upload', $lang['systemconfig_terms_upload_label'], $enable_disable_options, 420, '', true);
$page_def[] = config_add_boolean_select('user_rating', $lang['systemconfig_user_rating_label'], $enable_disable_options, 420, '', true);
$page_def[] = config_add_html('</div>');
// Security section
$page_def[] = config_add_html('<h3 class="CollapsibleSectionHead collapsed">' . $lang['systemconfig_security'] . '</h3><div id="SystemConfigSecuritySection" class="CollapsibleSection">');
$page_def[] = config_add_single_select(
'password_min_length',
$lang['systemconfig_password_min_length_label'],
range(0, 30),
false,
420,
'',
true
);
$page_def[] = config_add_single_select(
'password_min_alpha',
$lang['systemconfig_password_min_alpha_label'],
range(0, 30),
false,
420,
'',
true
);
$page_def[] = config_add_single_select(
'password_min_numeric',
$lang['systemconfig_password_min_numeric_label'],
range(0, 30),
false,
420,
'',
true
);
$page_def[] = config_add_single_select(
'password_min_uppercase',
$lang['systemconfig_password_min_uppercase_label'],
range(0, 30),
false,
420,
'',
true
);
$page_def[] = config_add_single_select(
'password_min_special',
$lang['systemconfig_password_min_special_label'],
range(0, 30),
false,
420,
'',
true
);
$page_def[] = config_add_single_select(
'password_expiry',
$lang['systemconfig_password_expiry_label'],
array_merge(array(0 => $lang['never']), range(1, 90)),
true,
420,
'',
true
);
$page_def[] = config_add_single_select(
'max_login_attempts_per_ip',
$lang['systemconfig_max_login_attempts_per_ip_label'],
range(10, 50),
false,
420,
'',
true
);
$page_def[] = config_add_single_select(
'max_login_attempts_per_username',
$lang['systemconfig_max_login_attempts_per_username_label'],
range(0, 30),
false,
420,
'',
true
);
$page_def[] = config_add_single_select(
'max_login_attempts_wait_minutes',
$lang['systemconfig_max_login_attempts_wait_minutes_label'],
range(0, 30),
false,
420,
'',
true
);
$page_def[] = config_add_single_select(
'password_brute_force_delay',
$lang['systemconfig_password_brute_force_delay_label'],
range(0, 30),
false,
420,
'',
true
);
$page_def[] = config_add_boolean_select('share_password_required', $lang['systemconfig_external_share_requires_password_label'], $enable_disable_options, 420, '', true);
$page_def[] = config_add_html('</div>');
// API section
$page_def[] = config_add_html('<h3 class="CollapsibleSectionHead collapsed">' . $lang['systemconfig_api'] . '</h3><div id="SystemConfigAPISection" class="CollapsibleSection">');
$page_def[] = config_add_boolean_select('iiif_enabled', $lang['iiif_enable_option'], $enable_disable_options, 420, '', true);
$page_def[] = config_add_html('</div>');
// Search engines section
$page_def[] = config_add_html('<h3 class="CollapsibleSectionHead collapsed">' . $lang['system_config_search_engines'] . '</h3><div id="SystemConfigSearchEngineSection" class="CollapsibleSection">');
$page_def[] = config_add_boolean_select('search_engine_noindex', $lang['search_engine_noindex'], $enable_disable_options, 420, '', true);
$page_def[] = config_add_boolean_select('search_engine_noindex_external_shares', $lang['search_engine_noindex_external_shares'], $enable_disable_options, 420, '', true);
$page_def[] = config_add_html('</div>');
// Debug section
$page_def[] = config_add_html(
'<h3 class="CollapsibleSectionHead collapsed">' . escape($lang['systemconfig_debug']) . '</h3>'
. '<div id="SystemConfigDebugSection" class="CollapsibleSection">'
);
// Determine the time left on debug log override
$debug_log_default_duration = 300;
$time_left = get_sysvar('debug_override_expires', time()) - time();
if ($time_left > 0) {
$debug_log_override_time_left = $time_left;
$system_config_debug_log_duration_question_class = '';
$debug_log_override_timer_active = true;
} else {
// reset
remove_config_option(null, 'system_config_debug_log_interim');
$system_config_debug_log_duration_question_class = 'DisplayNone';
$debug_log_override_timer_active = false;
}
$debug_log_override_time_left ??= $debug_log_default_duration;
// "Faking" a config option so that we can apply some logic before deciding to override debug_log
$system_config_debug_log_interim = $lang['off'];
$debug_log_options = [
$lang['systemconsoleonallusers'],
$lang['systemconfig_debug_log_on_specific_user'],
$lang['off'],
];
if ($debug_log) {
$debug_log_options = [$lang['systemconsoleonpermallusers']];
$system_config_debug_log_interim = $lang['systemconsoleonpermallusers'];
}
get_config_option([], 'system_config_debug_log_interim', $system_config_debug_log_interim);
$page_def[] = config_add_single_select(
'system_config_debug_log_interim',
$lang['systemconsoledebuglog'],
$debug_log_options,
false,
420,
'',
true,
'debug_log_selector_onchange(this);'
);
// Create a temp OB for render_text_question() call below to prevent modifying header information when we include header.php later
ob_start();
$autocomplete_user_scope = 'SystemConfigDebugLogSpecificUser_';
$debug_override_user = (int) get_sysvar('debug_override_user', -1);
$single_user_select_field_id = 'debug_override_user';
$single_user_select_field_value = $debug_override_user;
$single_user_select_field_onchange = 'create_debug_log_override();';
$SystemConfigDebugForUser_class = $system_config_debug_log_interim === $lang['systemconfig_debug_log_on_specific_user']
? ''
: 'DisplayNone';
?>
<div id="SystemConfigDebugForUser" class="Question <?php echo escape($SystemConfigDebugForUser_class); ?>">
<label></label>
<?php include dirname(__DIR__, 2) . "/include/user_select.php"; ?>
<div class="clearerleft"></div>
</div>
<?php
render_text_question(
"{$lang['systemconsoleturnoffafter']} X {$lang['seconds']}",
'system_config_debug_log_duration',
sprintf(
'<span class="MarginLeft1rem"><span id="DebugLogOverrideTimerText">%s</span>s %s</span>',
$debug_log_override_time_left,
escape($lang['remaining'])
),
true,
' onchange="create_debug_log_override(undefined, this.value);"',
$debug_log_default_duration,
['div_class' => [$system_config_debug_log_duration_question_class]]
);
$user_select_html = ob_get_contents();
ob_end_clean();
$page_def[] = config_add_html($user_select_html);
$page_def[] = config_add_html('</div>');
// End of Debug section
// Let plugins hook onto page definition and add their own configs if needed
// or manipulate the list
$plugin_specific_definition = hook('add_system_config_page_def', '', array($page_def));
if (is_array($plugin_specific_definition) && !empty($plugin_specific_definition)) {
$page_def = $plugin_specific_definition;
}
// Strip out any configs that are blocked from being edited in the UI.
if (count($system_config_hide) > 0) {
$new_page_def = array();
for ($n = 0; $n < count($page_def); $n++) {
if (!in_array($page_def[$n][1], $system_config_hide)) {
$new_page_def[] = $page_def[$n];
} // Add if not blocked
}
$page_def = $new_page_def;
}
// Process autosaving requests
// Note: $page_def must be defined by now in order to make sure we only save options that we've defined
if ('true' === getval('ajax', '') && 'true' === getval('autosave', '')) {
$response['success'] = true;
$response['message'] = '';
$autosave_option_name = getval('autosave_option_name', '');
$autosave_option_value = getval('autosave_option_value', '');
// Search for the option name within our defined (allowed) options
// if it is not there, error and don't allow saving it
$page_def_option_index = array_search($autosave_option_name, array_column($page_def, 1));
if (false === $page_def_option_index) {
$response['success'] = false;
$response['message'] = $lang['systemconfig_option_not_allowed_error'];
echo json_encode($response);
exit();
}
if (!set_config_option(null, $autosave_option_name, $autosave_option_value)) {
$response['success'] = false;
}
echo json_encode($response);
exit();
}
if ($ajax && getval('action', '') === 'create_debug_log_override' && enforcePostRequest($ajax)) {
$debug_user = getval('debug_override_user', '');
$debug_expires = getval('debug_override_expires', '');
if ($debug_user !== '' && $debug_expires !== '') {
create_debug_log_override($debug_user, $debug_expires);
unset($GLOBALS['debug_log_override']);
ajax_send_response(200, ajax_response_ok_no_data());
}
ajax_send_response(400, ajax_response_fail(ajax_build_message($lang['error_invalid_input'])));
}
config_process_file_input($page_def, 'system/config', $baseurl . '/pages/admin/admin_system_config.php');
config_remove_user_preferences($page_def);
# $lang is not a config option!
unset($system_wide_config_options['lang']);
foreach ($system_wide_config_options as $key => $value) {
// Some varible names are used multiple times, only get the first value
$GLOBALS[$key] = $GLOBALS[$key] ?? $value;
}
# Get user ref for use in header.php when loading profile image.
if (!isset($userref)) {
$userref = $userdata[0]['ref'];
}
$page_def = config_filter_by_search($page_def, [], getval("filter", ""), getval("only_modified", "no"));
include '../../include/header.php';
?>
<div class="BasicsBox">
<h1 class="inline_config_search"><?php echo escape($lang["systemconfig"]); ?></h1>
<?php
render_config_filter_by_search(getval("filter", ""), getval("only_modified", "no"));
$links_trail = array(
array(
'title' => $lang["systemsetup"],
'href' => $baseurl_short . "pages/admin/admin_home.php",
'menu' => true
),
array(
'title' => $lang["systemconfig"],
)
);
renderBreadcrumbs($links_trail);
?>
<p><?php echo escape($lang['systemconfig_description']); ?></p>
<div class="CollapsibleSections">
<?php config_generate_html($page_def); ?>
</div>
<script>registerCollapsibleSections(false);</script>
<?php if ($custom_font != "") { ?>
<script>document.getElementById("question_global_font").hidden = true;</script>
<?php
}
config_generate_AutoSaveConfigOption_function($baseurl . '/pages/admin/admin_system_config.php');
?>
<script>
function debug_log_selector_onchange(el) {
let value = jQuery(el).val();
let options_to_show_duration = <?php echo json_encode([
escape($lang['systemconsoleonallusers']),
escape($lang['systemconfig_debug_log_on_specific_user']),
]);?>;
// Display the user selection (if applicable)
if (value === '<?php echo escape($lang['systemconfig_debug_log_on_specific_user']); ?>') {
jQuery('#SystemConfigDebugForUser').removeClass('DisplayNone');
} else {
jQuery('#SystemConfigDebugForUser').addClass('DisplayNone');
}
// Display the timer
if (options_to_show_duration.includes(value)) {
jQuery('#question_system_config_debug_log_duration').removeClass('DisplayNone');
create_debug_log_override();
} else {
jQuery('#question_system_config_debug_log_duration').addClass('DisplayNone');
}
if (value === '<?php echo escape($lang['off']); ?>') {
create_debug_log_override(-1, -1);
}
return;
}
function create_debug_log_override(user_id, duration) {
user_id = Number(typeof user_id !== 'undefined' ? user_id : jQuery('#debug_override_user').val());
duration = Number(typeof duration !== 'undefined' ? duration : jQuery('#system_config_debug_log_duration_input').val());
// Clearing the user is the same as having this enabled for all users.
if (user_id === 0) {
user_id = -1;
}
console.debug('create_debug_log_override(user_id = %o, duration = %o)', user_id, duration);
jQuery.post(
baseurl + '/pages/admin/admin_system_config.php',
{
ajax: true,
action: 'create_debug_log_override',
debug_override_user: user_id,
debug_override_expires: duration,
<?php echo generateAjaxToken('create_debug_log_override'); ?>
},
null,
'json'
)
.done(function(data) {
let system_config_debug_log_interim = jQuery('#system_config_debug_log_interim');
if (system_config_debug_log_interim.data('timer_started')) {
system_config_debug_log_interim.data('reset_expiry', duration);
} else {
debug_log_override_timer(duration, 'DebugLogOverrideTimerText')
.then(debug_log_override_timer_done);
system_config_debug_log_interim.data('timer_started', true);
}
})
.fail(function(jqXHR, textStatus, errorThrown) {
let response = typeof jqXHR.responseJSON.data.message !== 'undefined'
? jqXHR.responseJSON.data.message
: textStatus;
console.error("create_debug_log_override: %s - %s", errorThrown, response);
});
return;
}
function debug_log_override_timer(time_left, update_el) {
console.debug('debug_log_override_timer(time_left = %o, update_el = %o)', time_left, update_el);
return new Promise((resolve, reject) => {
var debug_log_override_timer = setInterval(() => {
let system_config_debug_log_interim = jQuery('#system_config_debug_log_interim');
let reset_expiry = system_config_debug_log_interim.data('reset_expiry');
// Reset the time left if the user changed settings while still running
if (typeof reset_expiry !== 'undefined') {
time_left = Number(reset_expiry);
system_config_debug_log_interim.removeData('reset_expiry');
}
--time_left;
document.getElementById(update_el).textContent = time_left;
console.log('debug_log_override_timer: tick');
if (time_left <= 0) {
document.getElementById(update_el).textContent = 0;
clearInterval(debug_log_override_timer);
resolve(true);
}
},
1000);
});
}
function debug_log_override_timer_done() {
console.debug('debug_log_override_timer_done');
let option_off = '<?php echo escape($lang['off']); ?>';
let system_config_debug_log_interim = jQuery('#system_config_debug_log_interim');
system_config_debug_log_interim.removeData('timer_started');
if (system_config_debug_log_interim.val() !== option_off) {
system_config_debug_log_interim.val(option_off).change();
}
}
<?php if ($debug_log_override_timer_active) { ?>
jQuery(function() {
let system_config_debug_log_interim = jQuery('#system_config_debug_log_interim');
debug_log_override_timer(<?php echo (int) $debug_log_override_time_left; ?>, 'DebugLogOverrideTimerText')
.then(debug_log_override_timer_done);
system_config_debug_log_interim.data('timer_started', true);
});
<?php } ?>
</script>
</div>
<?php
include '../../include/footer.php';

View File

@@ -0,0 +1,395 @@
<?php
include "../../include/boot.php";
include "../../include/authenticate.php";
if (!checkperm_user_edit($userref)) {
redirect($baseurl_short . "login.php?error=error-permissions-login&url={$baseurl_short}pages/admin/admin_system_log.php");
exit;
}
$log_search = getval("log_search", "");
$backurl = getval("backurl", "");
$requesteduser = getval('actasuser', 0, true);
$actasuser = $requesteduser === $userref ? $userref : $requesteduser;
// Filter by a particular table and its reference
$table = getval('table', '');
$table_reference = getval('table_reference', 0, true);
$tables_data = array(
'resource_type_field' => array(
'display_title' => $lang['field'],
'title_column' => 'title',
'get_data_function' => 'get_resource_type_field',
'get_data_function_params' => array($table_reference),
),
'user' => array(
'display_title' => $lang['user'],
'title_column' => 'fullname',
'get_data_function' => 'get_user',
'get_data_function_params' => array($table_reference),
),
'resource' => array(
'display_title' => "resource",
'title_column' => 'field' . $view_title_field,
'get_data_function' => 'get_resource_data',
'get_data_function_params' => array($table_reference),
),
);
// TODO: over time, these can be put under tables_data once we can use the referenced information (ie. if there is a function to do so - see examples above)
$no_reference_data_tables = ps_array(
'
SELECT DISTINCT remote_table AS "value"
FROM activity_log
WHERE remote_table IS NOT NULL AND remote_table <> ""
',
array(),
""
);
if (!checkperm('a') || $requesteduser == $actasuser && $requesteduser != 0) {
$log_tables_where_statements = array(
'activity_log' => "`activity_log`.`user`='{$actasuser}' AND ",
'resource_log' => "`resource_log`.`user`='{$actasuser}' AND ",
'collection_log' => "`collection_log`.`user`='{$actasuser}' AND ",
);
} else {
// Admins see all user activity by default
$log_tables_where_statements = array(
'activity_log' => "TRUE AND ",
'resource_log' => "TRUE AND ",
'collection_log' => "TRUE AND ",
);
}
// Add date restriction
$curmonth = date('m');
$curyear = date('Y');
$logmonth = getval("logmonth", ($log_search != "" ? "" : $curmonth), true);
$logyear = getval("logyear", ($log_search != "" ? "" : $curyear), true);
// Add filtering if not searching
if ($logmonth != 0 || $logyear != 0) {
$logmonth = (int)$logmonth;
$logyear = (int)$logyear;
$monthstart = $logmonth == 0 ? 1 : $logmonth;
$monthend = $logmonth == 0 ? 12 : $logmonth;
$datevals = " BETWEEN CAST('$logyear-$monthstart-01' AS DATETIME)
AND CAST( CONCAT( LAST_DAY('$logyear-$monthend-01'),' 23:59:59') AS DATETIME) ";
$log_tables_where_statements['activity_log'] .= "(logged " . $datevals . ") AND ";
$log_tables_where_statements['resource_log'] .= "(date " . $datevals . ") AND ";
$log_tables_where_statements['collection_log'] .= "(date " . $datevals . ") AND ";
}
// Paging functionality
$url = generateURL(
"{$baseurl_short}pages/admin/admin_system_log.php",
array(
'log_search' => $log_search,
'backurl' => $backurl,
'actasuser' => $requesteduser,
'table' => $table,
'table_reference' => $table_reference,
'logmonth' => $logmonth,
'logyear' => $logyear,
)
);
$offset = (int) getval('offset', 0, true);
$per_page = (int) getval('per_page_list', $default_perpage_list, true);
$all_records = get_activity_log($log_search, null, null, $log_tables_where_statements, $table, $table_reference, true);
$totalpages = ceil($all_records / $per_page);
$curpage = floor($offset / $per_page) + 1;
$jumpcount = 0;
// End of paging functionality
include "../../include/header.php";
?>
<script>
jQuery(document).ready(function() {
jQuery('#logyear').change(function() {
if (jQuery(this).val() == 0) {
jQuery('#logmonth').val(0);
}
});
jQuery('#logmonth').change(function() {
if (jQuery(this).val()!=0 && jQuery('#logyear').val()==0) {
jQuery('#logyear').val(<?php echo $curyear?>);
}
});
});
</script>
<div class="BasicsBox">
<?php
$title = $lang["systemlog"];
if ($table != '' && $table_reference > 0 && array_key_exists($table, $tables_data)) {
$table_data = $tables_data[$table];
$table_reference_data = call_user_func_array($table_data['get_data_function'], $table_data['get_data_function_params']);
if ($table_reference_data !== false) {
$title .= " - {$table_data['display_title']}: {$table_reference_data[$table_data['title_column']]}";
}
}
// Breadcrumbs
if (strpos($backurl, 'pages/admin/admin_resource_type_fields.php') !== false) {
$links_trail = [
['title' => $lang["systemsetup"], 'href' => "{$baseurl_short}pages/admin/admin_home.php"],
['title' => $lang["admin_resource_type_fields"], 'href' => $backurl],
];
} elseif (strpos($backurl, "pages/team/team_user.php") !== false) {
// Arrived from Manage users page
$links_trail = array(
array(
'title' => $lang["teamcentre"],
'href' => $baseurl_short . "pages/team/team_home.php",
'menu' => true
),
array(
'title' => $lang["manageusers"],
'href' => $backurl
)
);
} elseif (strpos($backurl, "pages/team/team_user_edit.php") !== false) {
// Arrived from edit user page. This may also have a separate backurl
$back2url = $baseurl_short . "pages/team/team_user.php";
$url_parse = parse_url($backurl);
if (isset($url_parse['query'])) {
parse_str($url_parse['query'], $url2_qs);
if (strpos($url2_qs["backurl"] ?? "", "pages/team/team_user.php") !== false) {
$back2url = $url2_qs["backurl"];
}
}
$links_trail = array(
array(
'title' => $lang["teamcentre"],
'href' => $baseurl_short . "pages/team/team_home.php",
'menu' => true
),
array(
'title' => $lang["manageusers"],
'href' => $back2url,
),
array(
'title' => $lang["edituser"],
'href' => $backurl
)
);
} else {
$links_trail = [
['title' => $lang["systemsetup"], 'href' => "{$baseurl_short}pages/admin/admin_home.php"]
];
}
$links_trail[] = array(
'title' => escape($title)
);
?>
<h1><?php echo escape($title); ?></h1>
<?php renderBreadcrumbs($links_trail); ?>
<h1>
<form class="ResultsFilterTopRight" method="get">
<input type="hidden" name="actasuser" value="<?php echo $actasuser; ?>">
<input type="hidden" name="backurl" value="<?php echo urlencode($backurl); ?>">
<input type="hidden" name="table" value="<?php echo escape($table); ?>">
<input type="hidden" name="table_reference" value="<?php echo $table_reference; ?>">
<input type="hidden" name="logyear" value="<?php echo $logyear; ?>">
<input type="hidden" name="logmonth" value="<?php echo $logmonth; ?>">
<input type="text" name="log_search" placeholder="<?php echo escape($log_search); ?>">
<input type="submit" name="searching" value="<?php echo escape($lang["searchbutton"]); ?>">
<?php if ($log_search != "") { ?>
<input type="submit" name="clear_search" value="<?php echo escape($lang["clearbutton"]); ?>">
<?php } ?>
</form>
</h1>
<?php
$select_table_url = generateURL(
"{$baseurl_short}pages/admin/admin_system_log.php",
array(
'log_search' => $log_search,
'backurl' => $backurl,
'actasuser' => $requesteduser
)
);
?>
<form id="TableFilterForm" method="get" action="<?php echo $select_table_url; ?>">
<?php generateFormToken('TableFilterForm'); ?>
<div class="Question" id="QuestionFilter">
<div class="SplitSearch">
<select class="SplitSearch" id="logmonth" name="logmonth">
<?php
// Not filtered by default when searching, add option to filter by month
echo "<option " . ($logmonth == "" ? " selected" : "") . " value='0'>" . escape($lang["anymonth"]) . "</option>\n";
for ($m = 1; $m <= 12; $m++) {
echo "<option " . ($m == $logmonth ? " selected" : "") . " value=\"" . sprintf("%02d", $m) . "\">" . escape($lang["months"][$m - 1]) . "</option>\n";
}
?>
</select>
</div>
<div class="SplitSearch" id="Questionyear">
<select class="SplitSearch" id="logyear" name="logyear">
<?php
// Not filtered by default when searching, add option to filter by month
echo "<option " . ($logyear == "" ? " selected" : "") . " value='0'>" . escape($lang["anyyear"]) . "</option>\n";
for ($n = $curyear; $n >= $minyear; $n--) {
echo "<option " . ($n == $logyear ? " selected" : "") . " value=\"" . $n . "\">" . $n . "</option>\n";
}
?>
</select>
</div>
<?php if ($table_reference == "") { ?>
<select class="SplitSearch" name="table">
<option value=""><?php echo escape($lang['filter_by_table']); ?></option>
<?php foreach ($tables_data as $select_table => $select_table_data) { ?>
<option
value="<?php echo $select_table; ?>"
<?php echo $select_table == $table ? " selected" : ""; ?>
>
<?php echo $select_table; ?>
</option>
<?php
}
foreach ($no_reference_data_tables as $no_reference_data_table) {
if (!isset($tables_data[$no_reference_data_table])) { ?>
<option
value="<?php echo $no_reference_data_table; ?>"
<?php echo $no_reference_data_table == $table ? " selected" : ""; ?>
>
<?php echo $no_reference_data_table; ?>
</option>
<?php
}
}
?>
</select>
<?php } else { ?>
<input type="hidden" name="table" value="<?php echo escape($table);?>">
<?php
}
if ($table_reference != '') {
?>
<input type="hidden" name="table_reference" value="<?php echo $table_reference;?>">
<?php
}
if ($log_search != '') {
?>
<input type="hidden" name="log_search" value="<?php echo escape($log_search);?>">
<?php
}
?>
<input type="button" id="datesubmit" class="searchbutton" value="<?php echo escape($lang['filterbutton']); ?>" onclick="return CentralSpacePost(document.getElementById('TableFilterForm'));">
<div class="clearerleft"></div>
</div>
</form>
<div class="TopInpageNav">
<div class="TopInpageNavLeft">&nbsp;</div>
<?php pager(false); ?>
<div class="clearerleft"></div>
</div>
<div class="Listview">
<table class="ListviewStyle">
<tbody>
<tr class="ListviewTitleStyle">
<th><?php echo escape($lang['fieldtype-date_and_time']); ?></th>
<th><?php echo escape($lang['user']); ?></th>
<th><?php echo escape($lang['property-operation']); ?></th>
<th><?php echo escape($lang['fieldtitle-notes']); ?></th>
<th><?php echo escape($lang['property-resource-field']); ?></th>
<th><?php echo escape($lang['property-old_value']); ?></th>
<th><?php echo escape($lang['property-new_value']); ?></th>
<th><?php echo escape($lang['difference']); ?></th>
<?php if ($table == '' || $table_reference == 0) { ?>
<th><?php echo escape($lang['property-table']); ?></th>
<?php } ?>
<th><?php echo escape($lang['property-column']); ?></th>
<?php if ($table == '' || $table_reference == 0) { ?>
<th><?php echo escape($lang['property-table_reference']); ?></th>
<?php } ?>
</tr>
<?php
$original_permitted_html_tags = $permitted_html_tags;
$permitted_html_tags = array("html", "body");
$activity_log_records = get_activity_log($log_search, $offset, $per_page, $log_tables_where_statements, $table, $table_reference);
foreach ($activity_log_records as $record) {
?>
<tr>
<td><?php echo escape((string) nicedate($record['datetime'], true, true, true)); ?></td>
<td><?php echo escape((string) $record['user']); ?></td>
<td><?php echo escape((string) $record['operation']); ?></td>
<td><?php echo hook("userdisplay", "", array(array("access_key" => $record['access_key'],'username' => $record['user']))) ? "" : escape((string) $record['notes']); ?></td>
<td><?php echo escape((string) $record['resource_field']); ?></td>
<td><?php echo escape((string) $record['old_value']); ?></td>
<td><?php echo escape((string) $record['new_value']); ?></td>
<td><?php echo strip_tags_and_attributes($record['difference'], array("pre")); ?></td>
<?php if ($table == '' || $table_reference == 0) { ?>
<td><?php echo escape((string) $record['table']); ?></td>
<?php } ?>
<td><?php echo escape((string) $record['column']); ?></td>
<?php
if ($table != '' && $table_reference == 0 && array_key_exists($record['table'], $tables_data)) {
$record_table_data = $tables_data[$record['table']];
$record_table_reference_data = call_user_func_array(
$record_table_data['get_data_function'],
array($record['table_reference'])
);
if ($record_table_reference_data !== false) {
?>
<td><?php echo escape($record_table_reference_data[$record_table_data['title_column']]); ?></td>
<?php
}
} elseif ($table == '' || $table_reference == 0) {
$ref = escape((string) $record['table_reference']);
switch ($record['column']) {
// if this is resource ref, then add link to view resource
case "ref":
if ($record['table'] == "resource") { // only display links where ref field is in resource table
?>
<td>
<a href="<?php echo "$baseurl/pages/view.php?search=&order_by=&ref=$ref" ?>" title="View resource" onclick="return ModalLoad(this,true);">
<?php echo $ref ?>
</a>
</td>
<?php
}
break;
default:
print "<td>$ref</td>";
break;
}
}
?>
</tr>
<?php
}
$permitted_html_tags = $original_permitted_html_tags;
?>
</tbody>
</table>
</div><!-- end of ListView -->
<div class="BottomInpageNav">
<div class="BottomInpageNavRight">
<?php pager(false, false); ?>
</div>
</div>
</div> <!-- End of BasicBox -->
<?php
include "../../include/footer.php";

View File

@@ -0,0 +1,98 @@
<?php
include '../../include/boot.php';
include '../../include/authenticate.php';
if (!checkperm('a')) {
exit('Permission denied.');
}
include "../../include/header.php";
# Baseline metrics (reported metrics are a percentage of these)
# Based on an Intel NUC with a quad core Intel Core i5-4250U CPU @ 1.30GHz, 8GB RAM and a Samsung SSD hard disk (Dan's desktop PC)
$mysql_baseline = 85;
$cpu_baseline = 970410;
$disk_baseline = 20558;
?>
<div class="BasicsBox">
<h1><?php echo escape($lang["system_performance"]); ?></h1>
<?php
renderBreadcrumbs([
['title' => $lang["systemsetup"], 'href' => $baseurl_short . "pages/admin/admin_home.php", 'menu' => true],
['title' => $lang["system_performance"]]
]);
?>
<p>
<a href="admin_system_performance.php?reload=<?php echo time() ?>" onClick="return CentralSpaceLoad(this,false);">
<?php echo '<i aria-hidden="true" class="fa fa-sync-alt"></i>&nbsp;' . escape($lang["reload"]); ?>
</a>
</p>
<?php
# Database read/write speed
ps_query("drop table if exists performance_test");
ps_query("create table performance_test (c int(11),d char(64))");
$timer = microtime(true);
$counter = 0;
while (microtime(true) < ($timer + 1)) { // Run for one second
$d = md5(microtime());
ps_query("insert into performance_test(c,d) values (?,?)", array("i",$counter,"s",$d));
ps_query("select c,d from performance_test where c=?", array("i",$counter));
$counter++;
}
ps_query("drop table if exists performance_test");
?>
<div class="Question">
<label><?php echo escape($lang["mysql_throughput"]); ?></label>
<div class="Fixed"><?php echo round(($counter / $mysql_baseline) * 100, 1) ?></div>
<div class="clearerleft"></div>
</div>
<?php
# CPU speed
$timer = microtime(true);
$counter = 0;
while (microtime(true) < ($timer + 1)) { // Run for one second
$x = md5(microtime());
$counter++;
}
?>
<div class="Question">
<label><?php echo escape($lang["cpu_benchmark"]); ?></label>
<div class="Fixed"><?php echo round(($counter / $cpu_baseline) * 100, 1) ?></div>
<div class="clearerleft"></div>
</div>
<?php
# Disk write test
$tmp = get_temp_dir();
$timer = microtime(true);
$counter = 0;
$f = fopen($tmp . "/performance_test.txt", "w");
while (microtime(true) < ($timer + 1)) { // Run for one second
fwrite($f, str_pad("", 10000, "X"));
$counter++;
}
fclose($f);
unlink($tmp . "/performance_test.txt");
?>
<div class="Question">
<label><?php echo escape($lang["disk_write_speed"]); ?></label>
<div class="Fixed"><?php echo round(($counter / $disk_baseline) * 100, 1) ?></div>
<div class="clearerleft"></div>
</div>
</div>
<?php
include "../../include/footer.php";
?>

View File

@@ -0,0 +1,208 @@
<?php
include "../../../include/boot.php";
include "../../../include/authenticate.php";
$ruleid = getval("ref", "");
$filterid = getval("filter", 0, true);
if (!checkperm("a") || !(((string)(int)$ruleid == (string)$ruleid) || $ruleid == "new")) {
exit($lang["error-permissiondenied"]);
}
if ($ruleid != "new") {
$filter_rule = get_filter_rule($ruleid);
if (!$filter_rule) {
exit($lang["error"]);
}
} else {
$filter_rule = array();
}
$allfields = get_resource_type_fields();
$saveparams = array();
$saveparams["ref"] = $filterid;
$saveurl = generateURL($baseurl . "/pages/admin/admin_filter_edit.php", $saveparams);
?>
<script src="<?php echo $baseurl_short ?>lib/chosen/chosen.jquery.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="<?php echo $baseurl_short ?>lib/chosen/chosen.min.css">
<div class="BasicsBox">
<h1><?php echo escape($lang["filter_rule_add"]); ?></h1>
<h2><?php echo escape($lang["filter_rule_edit_text"]); ?></h2>
<form id="filter_edit_form" name="filter_edit_form" method="post" action="<?php echo $saveurl; ?>" onSubmit="processFilterRules();return CentralSpacePost(this,true);">
<input type="hidden" name="filter_rule" value="<?php echo (int)$ruleid; ?>" />
<input type="hidden" name="filter" value="<?php echo $filterid; ?>" />
<input type="hidden" name="filter_rule_data" id="filter_rule_data" value="" />
<?php generateFormToken("filter_rule_edit"); ?>
<?php
if ($ruleid != "new") {
foreach ($filter_rule as $filter_line) {
?>
<div class="Question filter_rule_question">
<select name="filter_rule_field" id="filter_rule_field" style="width:300px" onChange="updateFieldOptions(jQuery(this).parent());">
<option value='0' ><?php echo escape($lang["select"]); ?></option>
<?php
foreach ($allfields as $field) {
if (in_array($field["type"], $FIXED_LIST_FIELD_TYPES)) { ?>
<option
value="<?php echo $field["ref"];?>"
<?php echo ($field["ref"] == $filter_line["resource_type_field"]) ? 'selected' : ''; ?>>
<?php echo $field["title"]; ?>
</option>
<?php
}
}
?>
</select>
<select name="filter_rule_node_condition[]" class="filter_rule_node_condition" id="filter_rule_node_condition" style="width:150px">
<option value="0" <?php echo ($filter_line['node_condition'] == 0) ? 'selected' : ''; ?>>
<?php echo escape($lang["filter_is_not_in"]); ?>
</option>
<option value="1" <?php echo ($filter_line['node_condition'] == 1) ? 'selected' : ''; ?>>
<?php echo escape($lang["filter_is_in"]); ?>
</option>
</select>
<select name='filter_rule_nodes[]' class='filter_rule_nodes' multiple='multiple' size='7' style='width:420px'>
<?php
$field_options = get_field_options($filter_line["resource_type_field"], true);
foreach ($field_options as $option) {
?>
<option
value='<?php echo $option['ref'];?>'
<?php if (in_array($option["ref"], explode(',', $filter_line["nodes"]))) {
echo "selected";
} ?>>
<?php echo $option["name"]; ?>
</option>
<?php
}
?>
</select>
</div>
<?php
}
} else {
?>
<div class="Question filter_rule_question">
<select name="filter_rule_field" id="filter_rule_field" style="width:300px" onChange="updateFieldOptions(jQuery(this).parent());">
<option value='0' ><?php echo escape($lang["select"]); ?></option>
<?php
foreach ($allfields as $field) {
if (in_array($field["type"], $FIXED_LIST_FIELD_TYPES)) {
echo "<option value='" . $field["ref"] . "' >" . $field["title"] . "</option>\n";
}
}
?>
</select>
<select name="filter_rule_node_condition[]" class="filter_rule_node_condition" id="filter_rule_node_condition" style="width:150px">
<option value="0" selected ><?php echo escape($lang["filter_is_not_in"]); ?></option>
<option value="1" ><?php echo escape($lang["filter_is_in"]); ?></option>
</select>
<select name='filter_rule_nodes[]' class='filter_rule_nodes' multiple='multiple' size='7' style='width:420px'>
<option value='0' ><?php echo escape($lang["select"]); ?></option>
</select>
</div>
<?php
}
?>
<div class="Question">
<label for="conditionadd"></label>
<a href="#" onclick="return addFilterRuleItem(); return false;">
<i aria-hidden="true" class="fa fa-plus-circle"></i>&nbsp;Add condition
</a>
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="ruleadd"></label>
<input
name="ruleadd"
type="submit"
value="<?php
if ($ruleid != "new") {
echo escape($lang["filter_rule_save"]);
} else {
echo escape($lang["filter_rule_add"]);
} ?>">
<div class="clearerleft"></div>
</div>
</form>
</div> <!-- End of Basicsbox -->
<script>
function addFilterRuleItem() {
jQuery('.filter_rule_nodes').chosen('destroy');
lastrow = jQuery('.filter_rule_question').last();
newq = lastrow.clone();
console.log(lastrow.attr('row'));
newq.children('#filter_rule_field').val(0);
newq.children('.filter_rule_node_condition').val(0);
newq.children('.filter_rule_nodes').val('');
lastrow.after(newq);
jQuery('.filter_rule_nodes').chosen('');
}
function processFilterRules() {
rule_elements = new Array();
jQuery('.filter_rule_question').each(function () {
rule_nodes = jQuery(this).children('.filter_rule_nodes').val();
// Empty rule because no nodes selected, so skip this and move onto next filter rule in case there is one further down
if (rule_nodes.length!=0) {
rule_condition = jQuery(this).children('.filter_rule_node_condition').val();
rule_element = [rule_condition,rule_nodes];
rule_elements.push(rule_element);
}
});
jQuery ('#filter_rule_data').val(JSON.stringify(rule_elements));
// No rules present
if (rule_elements.length==0) {
return false;
}
}
function updateFieldOptions(question) {
jQuery(question).children('.filter_rule_nodes').html('');
jQuery('.filter_rule_nodes').chosen('destroy');
selectedField = jQuery(question).children('#filter_rule_field').val();
var post_data = {
'ref': selectedField,
'nodeinfo':true
};
api("get_field_options", post_data, function(response) {
if (response != false) {
nodeselect = jQuery(question).children('.filter_rule_nodes');
jQuery.each(response, function () {
nodeselect.append(jQuery('<option>', {
value: this.ref,
text : this.name
}));
});
jQuery('.filter_rule_nodes').chosen();
}
},
<?php echo generate_csrf_js_object('get_field_options'); ?>
);
jQuery('#modal').css('overflow', 'visible');
}
jQuery(document).ready(function(){
jQuery('.filter_rule_nodes').chosen();
});
</script>

View File

@@ -0,0 +1,18 @@
<?php
include __DIR__ . "/../../../include/boot.php";
include __DIR__ . "/../../../include/authenticate.php";
if (!checkperm("a")) {
exit("Permission denied.");
}
# Reordering capability
# Check for the parameter and reorder as necessary.
$reorder = getval("reorder", false);
if ($reorder) {
$neworder = json_decode(getval("order", false));
update_resource_type_field_order($neworder);
exit("SUCCESS");
}

View File

@@ -0,0 +1,18 @@
<?php
include __DIR__ . "/../../../include/boot.php";
include __DIR__ . "/../../../include/authenticate.php";
if (!checkperm("a")) {
exit("Permission denied.");
}
# Reordering capability
# Check for the parameter and reorder as necessary.
$reorder = getval("reorder", false);
if ($reorder) {
$neworder = json_decode(getval("order", false));
update_resource_type_order($neworder);
exit("SUCCESS");
}

View File

@@ -0,0 +1,18 @@
<?php
include __DIR__ . '/../../../include/boot.php';
include_once __DIR__ . '/../../../include/authenticate.php';
include_once __DIR__ . '/../../../include/ajax_functions.php';
$ref = getval("ref", 0, true);
if (!checkperm("a") || $ref == 0 || !metadata_field_view_access($ref)) {
ajax_permission_denied();
}
$new_shortname = getval("new_shortname", "");
$rtf_data = get_resource_type_field($ref);
$duplicate = (bool) ps_value("SELECT count(ref) AS `value` FROM resource_type_field WHERE `name` = ?", array("s",$new_shortname), 0, "schema");
$return["data"]["valid"] = $rtf_data["name"] != $new_shortname && !$duplicate;
echo json_encode($return);
exit();

296
pages/admin/tabs.php Normal file
View File

@@ -0,0 +1,296 @@
<?php
include '../../include/boot.php';
include '../../include/authenticate.php';
if (!acl_can_manage_tabs()) {
exit($lang['error-permissiondenied']);
}
// [Sorting functionality]
$tab_orderby = getval('tab_orderby', 'ref');
$tab_sort = (strtoupper(getval('tab_sort', 'ASC')) === 'DESC') ? 'DESC' : 'ASC';
// [URL]
$admin_tabs_management_page = "{$baseurl}/pages/admin/tabs.php";
$request_params = [
'tab_orderby' => $tab_orderby,
'tab_sort' => $tab_sort,
];
$admin_tabs_management_page_url = generateURL($admin_tabs_management_page, $request_params);
// [Action] Create new record
$new_tab_name = trim(getval('new_tab_name', ''));
if ($new_tab_name !== '' && enforcePostRequest(false)) {
$new_tab_ref = create_tab(['name' => $new_tab_name]);
if ($new_tab_ref !== false) {
redirect($admin_tabs_management_page_url);
}
$admin_tabs_management_error = "{$lang['error_fail_save']} -- $new_tab_name";
}
// [Paging functionality]
$per_page = (int) getval('per_page', $default_perpage_list, true);
$list_display_array[] = $default_perpage_list;
$list_display_array[] = $default_perpage;
if ($per_page === 99999) {
// all results option - see render_table()
$list_display_array['all'] = 99999;
$allow_reorder = true;
// When viewing all, switch to order by the "order_by" column since we also enabled re-ordering
$tab_orderby = 'order_by';
$tab_sort = 'ASC';
$request_params = [];
$admin_tabs_management_page_url = generateURL($admin_tabs_management_page, $request_params);
}
$list_display_array = array_unique($list_display_array);
natsort($list_display_array);
$per_page = in_array($per_page, $list_display_array) ? $per_page : $default_perpage;
rs_setcookie('per_page', $per_page);
$offset = (int) getval('offset', 0, true);
$tab_records = get_tabs_with_usage_count([
'order_by' => [$tab_orderby, $tab_sort],
'limit' => ['per_page' => $per_page, 'offset' => $offset],
]);
$tabsfound = count($tab_records["data"]) > 0;
if (!$tabsfound) {
// No results, go to last page
$offset = floor(($tab_records['total'] - 1) / $per_page) * $per_page;
$tab_records = get_tabs_with_usage_count([
'order_by' => [$tab_orderby, $tab_sort],
'limit' => ['per_page' => $per_page, 'offset' => $offset],
]);
}
$totalpages = ceil($tab_records['total'] / $per_page);
$curpage = floor($offset / $per_page) + 1;
$table_info = [
'class' => 'SystemTabs',
'headers' => [
'reorder_handle' => ['name' => '', 'sortable' => false, 'html' => true],
'ref' => ['name' => $lang['property-reference'], 'sortable' => !isset($allow_reorder)],
'name' => ['name' => $lang['name'], 'sortable' => false, 'html' => true, 'width' => '50%'],
'usage' => ['name' => $lang['usage'], 'sortable' => false],
'tools' => ['name' => $lang['tools'], 'sortable' => false, 'width' => '20%']
],
'orderbyname' => 'tab_orderby',
'orderby' => $tab_orderby,
'sortname' => 'tab_sort',
'sort' => $tab_sort,
'defaulturl' => $admin_tabs_management_page,
'params' => $request_params,
'pager' => [
'current' => $curpage,
'total' => $totalpages,
'per_page' => $per_page,
],
'data' => [],
];
foreach ($tab_records['data'] as $tab_record) {
$tab_record['reorder_handle'] = isset($allow_reorder) ? '<i class="fas fa-sort"></i>' : '';
$tab_record['name'] = sprintf(
'<span>%s</span><input name="tab_name_inline_edit_%s" type="text" class="DisplayNone" value="%s">',
escape(i18n_get_translated($tab_record['name'])),
escape($tab_record['ref']),
escape($tab_record['name'])
);
$tab_record['usage'] = sprintf(
'%s %s, %s %s',
$tab_record['usage_rtf'],
mb_strtolower($lang['admin_resource_type_fields']),
$tab_record['usage_rt'],
mb_strtolower($lang['resourcetypes'])
);
// Allow users to delete tabs except the Default one which is always ID #1 (created by dbstruct).
if ($tab_record['ref'] > 1) {
$tab_record['tools'] = [
[
'icon' => 'fa fa-fw fa-trash',
'text' => $lang['action-delete'],
'url' => '#',
'modal' => false,
'onclick' => "return delete_tabs(this, [{$tab_record['ref']}]);",
],
];
}
$tab_record['tools'][] = [
'icon' => 'fa fa-fw fa-edit',
'text' => $lang['action-edit'],
'url' => '#',
'modal' => false,
'onclick' => "return update_tab(this, {$tab_record['ref']}, \"init_edit\");"
];
// Save & Cancel buttons for when editing a tab record
$tab_record['tools'][] = [
'icon' => 'fa fa-solid fa-xmark',
'text' => $lang['cancel'],
'url' => '#',
'url:class' => 'DisplayNone',
'modal' => false,
'onclick' => "return update_tab(this, {$tab_record['ref']}, \"cancel\");"
];
$tab_record['tools'][] = [
'icon' => 'fa fa-regular fa-floppy-disk',
'text' => $lang['save'],
'url' => '#',
'url:class' => 'DisplayNone',
'modal' => false,
'onclick' => "return update_tab(this, {$tab_record['ref']}, \"save\");"
];
$table_info['data'][] = $tab_record;
}
include '../../include/header.php';
?>
<div class="BasicsBox">
<h1><?php echo escape($lang["system_tabs"]); ?></h1>
<?php
render_top_page_error_style($admin_tabs_management_error ?? '');
renderBreadcrumbs([
['title' => $lang['systemsetup'], 'href' => "{$baseurl_short}pages/admin/admin_home.php"],
['title' => $lang['system_tabs']],
]); ?>
<p>
<?php
echo escape($lang['manage_tabs_instructions']);
render_help_link('systemadmin/manage-tabs');
?>
</p>
<?php render_table($table_info); ?>
<!-- Create new tab form -->
<form method="post" action="<?php echo $admin_tabs_management_page_url; ?>" onsubmit="return CentralSpacePost(this, false);">
<?php generateFormToken('admin_tabs'); ?>
<div class="Question">
<label for="new_tab_name"><?php echo escape($lang['tabs_create_new']); ?></label>
<div class="tickset">
<div class="Inline">
<input name="new_tab_name" type="text" value="" id="new_tab_name" class="shrtwidth">
</div>
<div class="Inline">
<input
name="action_create"
type="submit"
value="<?php echo escape($lang['create']); ?>"
onclick="return (this.form.elements[0].value != '');"
>
</div>
</div>
<div class="clearerleft"></div>
</div>
</form>
</div>
<script>
// Re-order capability
jQuery(function() {
// Disable for touch screens
if (is_touch_device()) {
return false;
}
// Make all table rows sortable (except the header)
jQuery('.BasicsBox .Listview.SystemTabs > table').sortable({
items: 'tr:not(:first-child)',
handle: 'td > i.fa-sort',
containment: 'div.SystemTabs > table',
distance: 20,
update: function(event, ui) {
let tabs_new_order = jQuery(event.target)
.find('tr:not(:first-child) > td:nth-child(2)')
.map((i, val) => parseInt(jQuery(val).text())).get();
console.debug('[Re-ordering tabs] tabs_new_order = %o', tabs_new_order);
api('reorder_tabs', {'refs': tabs_new_order}, null, <?php echo generate_csrf_js_object('reorder_tabs'); ?>);
}
});
});
function delete_tabs(el, refs) {
console.debug('Called delete_tabs(refs = %o)', refs);
if (confirm('<?php echo escape($lang["confirm-deletion"]); ?>')) {
api('delete_tabs', {'refs': refs}, function(successful) {
if (successful) {
// Remove row from table
jQuery(el).parents('tr').remove();
} else {
styledalert("<?php echo escape($lang["error"]); ?>", "<?php echo escape($lang["error-failed-to-delete"]); ?>");
}
},
<?php echo generate_csrf_js_object('delete_tabs'); ?>
);
};
return false;
}
function update_tab(el, ref, action) {
console.debug('Called update_tab(ref = %o, action = %o)', ref, action);
let el_obj = jQuery(el);
let record = el_obj.parents('tr');
let tools = el_obj.parents('div.ListTools');
let tools_edit_save_cancel = tools.find('a i.fa-edit, a i.fa-floppy-disk, a i.fa-xmark').parents('a');
let record_name_inline_edit = record.find('input[name="tab_name_inline_edit_' + ref + '"');
let record_name_translated = record_name_inline_edit.siblings().first();
if (action === 'init_edit') {
// Hide the translated tab name and show the inline edit input
record_name_translated.toggleClass('DisplayNone');
record_name_inline_edit.toggleClass('DisplayNone');
// Hide the edit tool and show the Save & Cancel ones
tools_edit_save_cancel.toggleClass('DisplayNone');
} else if (action === 'save') {
api(
'save_tab',
{
tab: {
ref: ref,
name: record_name_inline_edit.val()
}
},
function(response) {
if (response.status === 'success') {
record_name_translated.text(response.data.name_translated);
} else {
styledalert("<?php echo escape($lang["error"]); ?>", response.data.message);
}
},
<?php echo generate_csrf_js_object('save_tab'); ?>
);
// Show the translated tab name and hide the inline edit input
record_name_translated.toggleClass('DisplayNone');
record_name_inline_edit.toggleClass('DisplayNone');
// Show the edit tool and hide the Save & Cancel ones
tools_edit_save_cancel.toggleClass('DisplayNone');
} else if (action === 'cancel') {
// Show the translated tab name and hide the inline edit input
record_name_translated.toggleClass('DisplayNone');
record_name_inline_edit.toggleClass('DisplayNone');
// Show the edit tool and hide the Save & Cancel ones
tools_edit_save_cancel.toggleClass('DisplayNone');
}
}
</script>
<?php
include '../../include/footer.php';

157
pages/ajax/annotations.php Normal file
View File

@@ -0,0 +1,157 @@
<?php
include __DIR__ . '/../../include/boot.php';
include __DIR__ . '/../../include/authenticate.php';
include_once __DIR__ . '/../../include/node_functions.php';
include_once __DIR__ . '/../../include/annotation_functions.php';
if (!$annotate_enabled) {
header('HTTP/1.1 401 Unauthorized');
$return['error'] = array(
'status' => 401,
'title' => 'Unauthorized',
'detail' => $lang['error-permissiondenied']);
echo json_encode($return);
exit();
}
$return = array();
$action = getval('action', '');
$resource = getval('resource', 0, true);
$page = getval('page', 0, true);
// Get annotation data if an ID has been provided
$annotation_id = getval('annotation_id', 0, true);
$annotation = getval('annotation', [], false, 'is_array');
debug(sprintf('[annotations][annotations.php] AJAX request: action = %s | resource = %s | annotation_id = %s', $action, $resource, $annotation_id));
if (0 < $annotation_id) {
$annotation = getAnnotation($annotation_id);
}
if ('get_resource_annotations' == $action) {
$return['data'] = getAnnotoriousResourceAnnotations($resource, $page);
}
// Create new annotation
if ('create' == $action && 0 < $resource) {
debug('[annotations][annotations.php] Request to create new annotation...');
debug('[annotations][annotations.php] annotation object is ' . json_encode($annotation));
if (0 === count($annotation)) {
debug('[annotations][annotations.php][error] No annotation object');
$return['error'] = array(
'status' => 400,
'title' => 'Bad Request',
'detail' => 'ResourceSpace expects an annotation object');
echo json_encode($return);
exit();
}
$annotation_id = createAnnotation($annotation);
debug('[annotations][annotations.php] newly created annotation_id = ' . json_encode($annotation_id));
if (false === $annotation_id) {
debug('[annotations][annotations.php][error] No annotation_id!');
$return['error'] = array(
'status' => 500,
'title' => 'Internal Server Error',
'detail' => 'ResourceSpace was not able to create the annotation.');
echo json_encode($return);
exit();
}
$return['data'] = $annotation_id;
}
// Update annotation
if ('update' == $action && 0 < $resource) {
if (0 === count($annotation)) {
$return['error'] = array(
'status' => 400,
'title' => 'Bad Request',
'detail' => 'ResourceSpace expects an annotation object');
echo json_encode($return);
exit();
}
$return['data'] = updateAnnotation($annotation);
}
// Delete annotation
if ('delete' == $action && 0 < $annotation_id && 0 !== count($annotation)) {
$return['data'] = deleteAnnotation($annotation);
}
// Get available fields (white listed) for annotations
if ('get_allowed_fields' == $action) {
foreach (array_unique($annotate_fields, SORT_NUMERIC) as $annotate_field) {
$field_data = get_resource_type_field($annotate_field);
// Make sure user has access to this field
if (metadata_field_view_access($annotate_field)) {
$return['data'][] =
array(
"ref" => $annotate_field,
"title" => i18n_get_translated($field_data['title']),
"name" => $field_data['name'],
"order_by" => $field_data['order_by'],
"type" => $field_data['type']
);
}
}
if (!isset($return['data'])) {
$return['error'] = array(
'status' => 404,
'title' => 'Not Found',
'detail' => '$annotate_fields config option does not have any fields set (i.e. it is empty)');
echo json_encode($return);
exit();
}
}
// Check if this user can add new tags to a field
// REQUIRES: check if field is dynamic keyword list and user has bermission to add new fields
if ('check_allow_new_tags' == $action) {
$resource_type_field = getval('resource_type_field', 0, true);
if (0 == $resource_type_field || !in_array($resource_type_field, $annotate_fields)) {
$return['data'] = false;
echo json_encode($return);
exit();
}
$field_data = get_resource_type_field($resource_type_field);
if (FIELD_TYPE_DYNAMIC_KEYWORDS_LIST == $field_data['type'] && !checkperm("bdk{$resource_type_field}")) {
$return['data'] = true;
echo json_encode($return);
exit();
}
$return['data'] = false;
echo json_encode($return);
exit();
}
// If by this point we still don't have a response for the request,
// create one now telling client code this is a bad request
if (0 === count($return)) {
$return['error'] = array(
'status' => 400,
'title' => 'Bad Request',
'detail' => 'The request could not be handled by annotations.php. This is the default response!');
}
echo json_encode($return);
exit();

View File

@@ -0,0 +1,37 @@
<?php
# Feeder page for AJAX search auto-completion.
include "../../include/boot.php";
include "../../include/authenticate.php";
$field = getval("field", ""); # get field name if doing a simple search completion (to get it easily from $_GET)
$ref = getval("fieldref", "", true); #get field ref if doing simple search completion (for get_suggested_keywords())
$search = getval("term", "");
# Find last keyword user is searching for
$s = explode(" ", $search);
$last = $s[count($s) - 1];
# Merge the words back together so existing words can be added to the results.
array_pop($s);
$otherwords = join(" ", $s);
?>[<?php
if (strlen($last) >= 2) { # Activate when last entered keyword >=3 chars long
?>
<?php
$keywords = get_suggested_keywords($last, $ref);
for ($n = 0; $n < count($keywords); $n++) {
if ($n > 0) {
echo ", ";
}
?>
"<?php echo (($otherwords != "") ? escape($otherwords) . " " : "") . escape($keywords[$n]) ?>"
<?php
}
?>
<?php
}
?>
]

View File

@@ -0,0 +1,121 @@
<?php
# Feeder page for AJAX user/group search for the user selection include file.
include "../../include/boot.php";
include "../../include/authenticate.php";
$find = getval("term", "");
$getrefs = (getval("getrefs", "") != "") ? true : false;
$getuserref = (getval("getuserref", ""));
if (!empty($getuserref)) {
ob_clean();
echo ps_value("select max(ref) as value from user where username=?", array("s",$getuserref), '');
return;
}
$usersgroup_subordinates = get_approver_usergroups($usergroup);
$usersgroup_approvers = get_usergroup_approvers($usergroup);
$ignoregroups = (getval("nogroups", "") != "") ? true : false;
$ignoresmartgroups = (getval("nosmartgroups", "") != "") ? true : false;
$first = true;
?> [ <?php
if (!$ignoregroups) {
$groups = get_usergroups(true, $find);
for ($n = 0; $n < count($groups) && $n <= 20; $n++) {
$show = true;
if (
checkperm("E") && ($groups[$n]["ref"] != $usergroup) && ($groups[$n]["parent"] != $usergroup) && ($groups[$n]["ref"] != $usergroupparent)
&& !in_array($groups[$n]["ref"], $usersgroup_approvers) && (!in_array($groups[$n]["ref"], $usersgroup_subordinates))
) {
$show = false;
}
if ($show) {
$users = get_users($groups[$n]["ref"]);
$ulist = "";
for ($m = 0; $m < count($users); $m++) {
if ($ulist != "") {
$ulist .= ", ";
}
$ulist .= $users[$m]["username"];
}
if ($ulist != "") {
if (!$first) {
?>, <?php
}
$first = false;
?>{ "label": "<?php echo escape($lang["group"]); ?>: <?php echo $groups[$n]["name"]; ?>", "value": "<?php echo escape($lang["group"]); ?>: <?php echo $groups[$n]["name"]; ?>" <?php if ($getrefs) {
?>, "ref": "<?php echo $groups[$n]["ref"]; ?>"<?php
}?> }<?php
}
}
}
}
if (!$ignoregroups && !$ignoresmartgroups) {
if (!isset($groups)) {
$groups = get_usergroups(true, $find);
}
for ($n = 0; $n < count($groups) && $n <= 20; $n++) {
$show = true;
if (
checkperm("E") && ($groups[$n]["ref"] != $usergroup) && ($groups[$n]["parent"] != $usergroup) && ($groups[$n]["ref"] != $usergroupparent)
&& !in_array($groups[$n]["ref"], $usersgroup_approvers) && (!in_array($groups[$n]["ref"], $usersgroup_subordinates))
) {
$show = false;
}
if ($show) {
$users = get_users($groups[$n]["ref"]);
$ulist = "";
for ($m = 0; $m < count($users); $m++) {
if ($ulist != "") {
$ulist .= ", ";
}
$ulist .= $users[$m]["username"];
}
if ($ulist != "") {
if (!$first) {
?>, <?php
}
$first = false;
?>{ "label": "<?php echo escape($lang["groupsmart"]); ?>: <?php echo $groups[$n]["name"]; ?>", "value": "<?php echo escape($lang["groupsmart"]); ?>: <?php echo $groups[$n]["name"]; ?>" <?php if ($getrefs) {
?>, "ref": "<?php echo $groups[$n]["ref"]; ?>"<?php
}?> }<?php
}
}
}
}
$users = get_users(0, $find);
for ($n = 0; $n < count($users) && $n <= 20; $n++) {
$show = true;
if (
checkperm("E") && ($users[$n]["groupref"] != $usergroup) && ($users[$n]["groupparent"] != $usergroup) && ($users[$n]["groupref"] != $usergroupparent)
&& !in_array($users[$n]["groupref"], $usersgroup_approvers) && (!in_array($users[$n]["groupref"], $usersgroup_subordinates))
) {
$show = false;
}
if ($show) {
if (!$first) {
?>, <?php
}
$first = false;
?>{ "label": "<?php echo $users[$n]["fullname"]; ?>", "value": "<?php echo $users[$n]["username"]; ?>" <?php if ($getrefs) {
?>, "ref": "<?php echo $users[$n]["ref"]; ?>"<?php
}?> } <?php
}
}
?> ]

View File

@@ -0,0 +1,22 @@
<?php
# Feeder page for userlist names
include "../../include/boot.php";
include "../../include/authenticate.php";
$find = getval("term", " ");
$userlists = ps_query("select userlist_name from user_userlist where user= ? and userlist_name like ?", ['i', $userref, 's', '%' . $find . '%']);
$first = true;
?>[
<?php
$users = get_users(0, $find);
for ($n = 0; $n < count($userlists) && $n <= 20; $n++) {
if (!$first) {
?>, <?php
}
$first = false;
?>{
"value": "<?php echo $userlists[$n]['userlist_name']; ?>"}<?php
}
?>
]

66
pages/ajax/browse_action.php Executable file
View File

@@ -0,0 +1,66 @@
<?php
include_once '../../include/boot.php';
include_once '../../include/authenticate.php';
// Browse bar action endpoint
$action = getval('action', '');
$resource = getval("resource", 0, true);
$return = array();
$return['status'] = 400; // set to default
if (enforcePostRequest("browse_action")) {
switch ($action) {
case 'add_node':
$node = getval("node", 0, true);
$nodeinfo = array();
get_node($node, $nodeinfo);
$field = get_resource_type_field($nodeinfo["resource_type_field"]);
if (!get_edit_access($resource) || !metadata_field_edit_access($nodeinfo["resource_type_field"]) || !in_array($field["type"], $FIXED_LIST_FIELD_TYPES)) {
$return['status'] = 400;
$return['message'] = $lang["error-permissiondenied"];
break;
}
// Check valid change
$curnodes = get_resource_nodes($resource, $nodeinfo["resource_type_field"]);
$multifields = array(FIELD_TYPE_CATEGORY_TREE,FIELD_TYPE_DYNAMIC_KEYWORDS_LIST,FIELD_TYPE_CHECK_BOX_LIST);
$valid = count($curnodes) == 0 || in_array($field["type"], $multifields);
if ($valid) {
$nodestoadd = array($node);
// We need to add all parent nodes for category trees
if ($field['type'] == FIELD_TYPE_CATEGORY_TREE && $category_tree_add_parents) {
$parent_nodes = get_parent_nodes($node);
foreach ($parent_nodes as $parent_node_ref => $parent_node_name) {
$nodestoadd[] = $parent_node_ref;
}
}
add_resource_nodes($resource, $nodestoadd);
$return['status'] = 200;
} else {
$return['status'] = 400;
$return['message'] = $lang['error-invalid_browse_action'];
}
break;
case 'collection_add':
$collection = getval("collection", 0, true);
if (collection_writeable($collection) && add_resource_to_collection($resource, $collection, false)) {
$return['status'] = 200;
}
break;
default:
$return['message'] = $lang["error_generic"] ;
break;
}
}
http_response_code($return['status']);
header('Content-type: application/json');
echo json_encode($return);
exit();

View File

@@ -0,0 +1,400 @@
<?php
include '../../include/boot.php';
include '../../include/authenticate.php';
// generate JSON data to populate bar
$id = getval('id', '');
// Use id to work out search string for link and path to data requested e.g. to get field id for node expansion
$target_search = array();
$fc_parent = 0;
$parent_nodes = array();
$browse_field = 0;
$browse_elements = explode("-", $id);
$bcount = count($browse_elements);
$n = 0;
for ($n = 0; $n < $bcount; $n++) {
$browseparts = explode(":", $browse_elements[$n]);
$type = $browseparts[0];
$browseid = isset($browseparts[1]) ? $browseparts[1] : 0;
switch ($type) {
case "RT":
$target_search["restypes"] = $browseid;
$target_search["archive"] = "";
break;
case "F":
$browse_field = $browseid;
break;
case "N":
$parent_nodes[] = $browseid;
break;
case "FC":
if ($browseid != "") {
$fc_parent = $browseid;
}
break;
}
if ($n == $bcount - 1) {
// Last id - this decided what is requested
$returntype = $type;
$returnid = $browseid;
}
}
// Generate data to return
$return_items = array();
$n = 0;
switch ($returntype) {
case "R":
// Add resource types
$restypes = get_resource_types();
if (checkperm("a")) {
// Add 'create new' option
$return_items[$n] = array();
$return_items[$n]["id"] = $id . "-RT:new";
$return_items[$n]["name"] = $lang["resource_type_new"];
$return_items[$n]["class"] = "New";
$return_items[$n]["expandable"] = "false";
$tgtparams = array();
$tgtparams["type"] = "resource_type";
$tgtparams["noreload"] = "true";
$tgturl = generateURL($baseurl_short . "pages/ajax/create_new.php", $tgtparams);
$return_items[$n]["link"] = $tgturl;
$return_items[$n]["modal"] = true;
$n++;
}
foreach ($restypes as $restype) {
if (!in_array($restype['ref'], $hide_resource_types)) {
// Create link based on parent and current restype
$return_items[$n] = array();
$return_items[$n]["id"] = $id . "-RT:" . $restype["ref"];
$return_items[$n]["name"] = escape(i18n_get_translated($restype["name"]));
$return_items[$n]["class"] = "Restype";
$return_items[$n]["expandable"] = "true";
$tgtparams = array();
$tgtparams["restypes"] = $restype["ref"];
$tgtparams["noreload"] = "true";
$tgtparams["search"] = "";
$tgturl = generateURL($baseurl_short . "pages/search.php", $tgtparams);
$return_items[$n]["link"] = $tgturl;
$return_items[$n]["modal"] = false;
$n++;
}
}
$return_data["success"] = true;
$return_data["items"] = $return_items;
break;
case "RT":
// Resource type - get all applicable fields
if (checkperm("a")) {
// Add 'create new' option
$return_items[$n] = array();
$return_items[$n]["id"] = $id . "-F:new";
$return_items[$n]["name"] = $lang["resource_type_field_new"];
$return_items[$n]["class"] = "New";
$return_items[$n]["expandable"] = "false";
$tgtparams = array();
$tgtparams["restypes"] = "new";
$tgtparams["type"] = "resource_type_field";
$tgtparams["noreload"] = "true";
$tgturl = generateURL($baseurl_short . "pages/ajax/create_new.php", $tgtparams);
$return_items[$n]["link"] = $tgturl;
$return_items[$n]["modal"] = true;
$n++;
}
$gettypes = [0,(int)$returnid]; // add selected resource type fields
$allfields = get_resource_type_fields($gettypes, "order_by", 'asc', '', $FIXED_LIST_FIELD_TYPES);
foreach ($allfields as $field) {
if ($field["browse_bar"] && metadata_field_view_access($field["ref"]) && $field["type"] != FIELD_TYPE_DYNAMIC_KEYWORDS_LIST) {
// Create link based on parent and current restype
$return_items[$n] = array();
$return_items[$n]["id"] = $id . "-F:" . $field["ref"];
$return_items[$n]["name"] = i18n_get_translated($field["title"]);
$return_items[$n]["class"] = "Field";
$return_items[$n]["expandable"] = "true";
$return_items[$n]["link"] = "";
$return_items[$n]["modal"] = false;
$n++;
}
}
$return_data["success"] = true;
$return_data["items"] = $return_items;
break;
case "F":
// Get nodes for field
if (isset($parentnode) && $parentnode > 0) {
$parent = $parentnode;
} else {
$parent = null;
}
if (metadata_field_view_access($returnid)) {
$fielddata = get_resource_type_field($returnid);
if (!$fielddata["browse_bar"] || !metadata_field_view_access($returnid) || !in_array($fielddata["type"], $FIXED_LIST_FIELD_TYPES) || $fielddata["type"] == FIELD_TYPE_DYNAMIC_KEYWORDS_LIST) {
break;
}
if (checkperm("k") || checkperm('a') || ($fielddata["type"] == FIELD_TYPE_DYNAMIC_KEYWORDS_LIST && !checkperm("bdk" . $returnid))) {
// Add 'create new' option
$return_items[$n] = array();
$return_items[$n]["id"] = $id . "-N:new";
$return_items[$n]["name"] = $lang["add"];
$return_items[$n]["class"] = "New";
$return_items[$n]["expandable"] = "false";
$tgtparams = array();
$tgtparams["type"] = "node";
$tgtparams["field"] = $returnid;
$tgtparams["parent"] = $parent;
$tgtparams["noreload"] = "true";
$tgturl = generateURL($baseurl_short . "pages/ajax/create_new.php", $tgtparams);
$return_items[$n]["link"] = $tgturl;
$return_items[$n]["modal"] = true;
$n++;
}
$nodes = get_nodes($returnid, $parent, false);
if ((bool) $fielddata['automatic_nodes_ordering']) {
$nodes = reorder_nodes($nodes);
}
foreach ($nodes as $node) {
// Create link based on parent and current restype
$return_items[$n] = array();
$return_items[$n]["id"] = $id . "-N:" . $node["ref"];
$return_items[$n]["name"] = escape(i18n_get_translated($node["name"]));
$return_items[$n]["class"] = "Node";
$return_items[$n]["expandable"] = (is_parent_node($node["ref"])) ? "true" : "false";
$tgtparams = array();
$tgtparams["search"] = NODE_TOKEN_PREFIX . $node["ref"];
$tgtparams["noreload"] = "true";
$tgturl = generateURL($baseurl_short . "pages/search.php", $tgtparams, $target_search);
$return_items[$n]["link"] = $tgturl;
$return_items[$n]["modal"] = false;
$return_items[$n]["drop"] = true;
$n++;
}
$return_data["success"] = true;
$return_data["items"] = $return_items;
}
break;
case "N":
// Get subnodes for node
if (metadata_field_view_access($browse_field)) {
$fielddata = get_resource_type_field($browse_field);
if (!$fielddata["browse_bar"] || !metadata_field_view_access($browse_field) || !in_array($fielddata["type"], $FIXED_LIST_FIELD_TYPES) || $fielddata["type"] == FIELD_TYPE_DYNAMIC_KEYWORDS_LIST) {
break;
}
if (checkperm("k") || checkperm('a') || ($fielddata["type"] == FIELD_TYPE_DYNAMIC_KEYWORDS_LIST && !checkperm("bdk" . $returnid))) {
// Add 'create new' option
$return_items[$n] = array();
$return_items[$n]["id"] = $id . "-N:new";
$return_items[$n]["name"] = $lang["add"];
$return_items[$n]["class"] = "New";
$return_items[$n]["expandable"] = "false";
$tgtparams = array();
$tgtparams["type"] = "node";
$tgtparams["field"] = $browse_field;
$tgtparams["parent_nodes"] = implode(",", $parent_nodes);
$tgtparams["noreload"] = "true";
$tgturl = generateURL($baseurl_short . "pages/ajax/create_new.php", $tgtparams);
$return_items[$n]["link"] = $tgturl;
$return_items[$n]["modal"] = true;
$n++;
}
$nodes = get_nodes($browse_field, $returnid, false);
if ((bool) $fielddata['automatic_nodes_ordering']) {
$nodes = reorder_nodes($nodes);
}
foreach ($nodes as $node) {
$return_items[$n] = array();
$return_items[$n]["id"] = $id . "-N:" . $node["ref"];
$return_items[$n]["name"] = escape(i18n_get_translated($node["name"]));
$return_items[$n]["class"] = "Node";
$return_items[$n]["expandable"] = (is_parent_node($node["ref"])) ? "true" : "false";
$tgtparams = array();
$tgtparams["search"] = NODE_TOKEN_PREFIX . $node["ref"];
$tgtparams["noreload"] = "true";
$tgturl = generateURL($baseurl_short . "pages/search.php", $tgtparams, $target_search);
$return_items[$n]["link"] = $tgturl;
$return_items[$n]["modal"] = false;
$return_items[$n]["drop"] = true;
$n++;
}
$return_data["success"] = true;
$return_data["items"] = $return_items;
}
break;
// Featured collection
case "FC":
$fc_parent = validate_collection_parent(array("parent" => $fc_parent));
$can_create = checkperm("h") && can_create_collections();
// Add 'create new' option
if ($can_create) {
$item = array(
"id" => "{$id}-FC:new",
"name" => escape($lang["create"]),
"class" => "New",
"expandable" => "false",
"link" => generateURL(
"{$baseurl_short}pages/collections_featured.php",
array(
"new" => "true",
"cta" => "true",
"parent" => $fc_parent,
)
),
"modal" => true,
);
$return_items[$n] = $item;
$n++;
}
$featured_collections = get_featured_collections($fc_parent, array());
usort($featured_collections, "order_featured_collections");
foreach ($featured_collections as $fc) {
$is_featured_collection_category = is_featured_collection_category($fc);
$child_collection_count = count(get_featured_collections($fc['ref'], []));
$id_part = ($is_featured_collection_category ? "FC" : "C");
$link = generateURL("{$baseurl_short}pages/search.php", array("search" => "!collection{$fc["ref"]}", "noreload" => "true"));
if ($is_featured_collection_category) {
$link = generateURL("{$baseurl_short}pages/collections_featured.php", array("parent" => $fc["ref"], "noreload" => "true"));
}
$item = array(
"id" => "{$id}-{$id_part}:{$fc["ref"]}",
"name" => escape(strip_prefix_chars(i18n_get_translated($fc["name"]), "*")),
"class" => ($is_featured_collection_category ? "Featured" : "Col"),
"expandable" => (($is_featured_collection_category && $child_collection_count > 0) || ($can_create && $id_part === 'FC') ? "true" : "false"), # js/browsebar_js.php requires this to be a string.
"link" => $link,
"modal" => false,
"drop" => !$is_featured_collection_category,
);
$return_items[$n] = $item;
$n++;
}
$return_data["success"] = true;
$return_data["items"] = $return_items;
break;
case "C":
// My collections
if (can_create_collections()) {
// Add 'create new' option
$return_items[$n] = array();
$return_items[$n]["id"] = $id . "-C:new";
$return_items[$n]["name"] = $lang["createnewcollection"];
$return_items[$n]["class"] = "New";
$return_items[$n]["expandable"] = "false";
$tgtparams = array();
$tgtparams["type"] = "collection";
$tgtparams["noreload"] = "true";
$tgturl = generateURL($baseurl_short . "pages/ajax/create_new.php", $tgtparams);
$return_items[$n]["link"] = $tgturl;
$return_items[$n]["modal"] = true;
$n++;
}
$mycols = get_user_collections($userref);
foreach ($mycols as $mycol) {
// Create link based on parent
$return_items[$n] = array();
$return_items[$n]["id"] = $id . "-C:" . $mycol["ref"];
$return_items[$n]["name"] = i18n_get_collection_name($mycol["name"]);
$return_items[$n]["class"] = "Col";
$return_items[$n]["expandable"] = "false";
$tgtparams = array();
$tgtparams["search"] = "!collection" . $mycol["ref"];
$tgtparams["noreload"] = "true";
$tgturl = generateURL($baseurl_short . "pages/search.php", $tgtparams);
$return_items[$n]["link"] = $tgturl;
$return_items[$n]["modal"] = false;
$return_items[$n]["drop"] = true;
$n++;
}
$return_data["success"] = true;
$return_data["items"] = $return_items;
break;
case "WF":
// Workflow states
$showstates = array();
for ($s = -2; $s <= 3; $s++) {
if (!checkperm("z" . $s)) {
$showstates[] = $s;
}
}
foreach ($additional_archive_states as $additional_archive_state) {
if (!checkperm("z" . $additional_archive_state)) {
$showstates[] = $additional_archive_state;
}
}
foreach ($showstates as $showstate) {
// Create link based on parent
$return_items[$n] = array();
$return_items[$n]["id"] = $id . "-A:" . $showstate;
$return_items[$n]["name"] = isset($lang["status" . $showstate]) ? $lang["status" . $showstate] : $showstate;
$return_items[$n]["class"] = "State";
$return_items[$n]["expandable"] = "false";
$tgtparams = array();
$tgtparams["search"] = "";
$tgtparams["restypes"] = "";
$tgtparams["archive"] = $showstate;
$tgtparams["noreload"] = "true";
$tgturl = generateURL($baseurl_short . "pages/search.php", $tgtparams);
$return_items[$n]["link"] = $tgturl;
$return_items[$n]["modal"] = false;
// Set an icon
$icon = $workflowicons[$showstate] ?? (WORKFLOW_DEFAULT_ICONS[$showstate] ?? WORKFLOW_DEFAULT_ICON);
$return_items[$n]["icon"] = "<i class='fa-fw " . escape($icon) . "'></i>";
$n++;
}
$return_data["success"] = true;
$return_data["items"] = $return_items;
break;
default:
// TODO Return an error
$return_data["success"] = false;
$return_data["message"] = "ERROR";
break;
}
echo json_encode($return_data);
exit();

View File

@@ -0,0 +1,64 @@
<?php
include '../../include/boot.php';
$k = getval('k', '');
$upload_collection = getval('upload_share_active', '');
if ($k == "" || (!check_access_key_collection($upload_collection, $k))) {
include "../../include/authenticate.php";
}
// Initialise
$ajax = ('' != getval('ajax', '') ? true : false);
$node_ref = getval('node_ref', null, true);
$field = (int) getval('field', '', true);
$selected_nodes = getval('selected_nodes', [], false, 'is_array');
$opened_nodes = array();
$js_tree_data = array();
$nodes = array_filter(get_nodes($field, $node_ref), 'node_is_active');
// Find the ancestor nodes for any of the searched nodes
// Most of the nodes will most likely be a tree leaf.
// This allows us to know which tree nodes we need to
// expand from the beginning
foreach ($selected_nodes as $selected_node) {
$tree_level = get_tree_node_level($selected_node);
if (0 === $tree_level) {
continue;
}
$found_all_parents = get_all_ancestors_for_node($selected_node, $tree_level);
if (is_array($found_all_parents)) {
foreach ($found_all_parents[0] as $p_key => $p_ref) {
$opened_nodes[] = $p_ref;
}
}
}
foreach ($nodes as $node) {
$node_opened = false;
if (in_array($node['ref'], $opened_nodes)) {
$node_opened = true;
}
$js_tree_data[] = array(
'id' => $node['ref'],
'parent' => ('' == $node['parent'] ? '#' : $node['parent']),
'text' => escape(i18n_get_translated($node['name'])),
'li_attr' => array(
'title' => escape(i18n_get_translated($node['name'])),
'class' => 'show_tooltip'
),
'state' => array(
'opened' => $node_opened,
'selected' => in_array($node['ref'], $selected_nodes)
),
'children' => is_parent_node($node['ref'], true)
);
}
header('Content-Type: application/json');
echo json_encode($js_tree_data);

View File

@@ -0,0 +1,33 @@
<?php
include "../../include/boot.php";
$uniqid = getval("id", "");
$user = getval("user", ""); // Need to get this from query string since we haven't authenticated
$usertempdir = get_temp_dir(false, "rs_" . $user . "_" . $uniqid);
$progress_file = $usertempdir . "/progress_file.txt";
if (!file_exists($progress_file)) {
touch($progress_file);
}
$content = file_get_contents($progress_file);
if ($content == "") {
echo escape($lang['preparingzip']);
} elseif ($content == "zipping") {
$files = scandir($usertempdir);
echo "Zipping ";
foreach ($files as $file) {
if (strpos($file, ".zip") !== false) {
echo formatfilesize(filesize($usertempdir . "/" . $file));
}
}
} elseif ($content == "nothing_to_download") {
echo 'nothing_to_download';
} else {
ob_start();
echo $content;
ob_flush();
exit();
} // echo whatever the script has placed here.

203
pages/ajax/collections.php Normal file
View File

@@ -0,0 +1,203 @@
<?php
$rsroot = dirname(dirname(__DIR__));
include "{$rsroot}/include/boot.php";
include "{$rsroot}/include/authenticate.php";
include_once "{$rsroot}/include/ajax_functions.php";
$collection = getval("collection", 0, true);
if (checkperm("b") && !(isset($anonymous_login) && $username == $anonymous_login && $anonymous_user_session_collection)) {
// Only has access to the result selection collection
$selection_collection_only = true;
$collection = $USER_SELECTION_COLLECTION;
}
$allowed_actions = array(
"clear_selection_collection_resources",
"get_selected_resources_counter",
"render_selected_resources_counter",
"render_edit_selected_btn",
"render_clear_selected_btn",
"remove_selected_from_collection",
"add_resource",
"remove_resource",
"add_multiple_resources",
"remove_multiple_resources"
);
if ($collection == 0 && isset($anonymous_login) && $username == $anonymous_login) {
if (is_null($USER_SELECTION_COLLECTION)) {
// No selection collection is created for anonymous users until an action is performed by the user so create one now
$USER_SELECTION_COLLECTION = create_collection($userref, "Selection Collection (for batch edit)", 0, 1);
update_collection_type($USER_SELECTION_COLLECTION, COLLECTION_TYPE_SELECTION);
}
$collection = $USER_SELECTION_COLLECTION;
}
if (isset($selection_collection_only) && $collection != $USER_SELECTION_COLLECTION) {
ajax_unauthorized();
}
$return = array();
$action = trim(getval("action", ""));
if ($action == "" || !in_array($action, $allowed_actions)) {
$fail_msg = str_replace("%key", "action", $lang["error-request-missing-key"]);
ajax_send_response(400, ajax_response_fail(ajax_build_message($fail_msg)));
}
if ($action == "clear_selection_collection_resources") {
remove_all_resources_from_collection($USER_SELECTION_COLLECTION);
ajax_send_response(200, ajax_response_ok_no_data());
}
if ($action == "get_selected_resources_counter") {
$counter = count(get_collection_resources($USER_SELECTION_COLLECTION));
ajax_send_response(200, ajax_response_ok(array("selected" => $counter)));
}
if ($action == "render_selected_resources_counter") {
$counter = count(get_collection_resources($USER_SELECTION_COLLECTION));
ajax_send_text_response(200, render_selected_resources_counter($counter));
}
if ($action == "render_clear_selected_btn") {
ajax_send_text_response(200, cast_echo_to_string('render_clear_selected_btn'));
}
if ($action == "render_edit_selected_btn") {
include_once "{$rsroot}/include/do_search.php";
$restypes = getval("restypes", "");
$archive = getval("archive", "");
ajax_send_text_response(200, cast_echo_to_string('render_edit_selected_btn'));
}
if ($action == "remove_selected_from_collection") {
if (isset($selection_collection_only)) {
ajax_unauthorized();
}
if (!collection_readable($usercollection)) {
$fail_msg = str_replace("%ref", $usercollection, $lang["error-collection-unreadable"]);
ajax_send_response(400, ajax_response_fail(ajax_build_message($fail_msg)));
}
$selected_resources = get_collection_resources($USER_SELECTION_COLLECTION);
$usercollection_resources = get_collection_resources($usercollection);
$refs_to_remove = array_intersect($selected_resources, $usercollection_resources);
foreach (array_intersect($selected_resources, $usercollection_resources) as $ref) {
remove_resource_from_collection($ref, $usercollection);
}
ajax_send_response(200, ajax_response_ok_no_data());
}
if ($action == "add_resource") {
$resource = getval("resource", null, true);
$smartadd = getval("smartadd", false);
$size = getval("size", "");
$addtype = getval("addtype", "");
$collection_data = get_collection($collection);
if ($collection_data["type"] == COLLECTION_TYPE_UPLOAD) {
ajax_send_response(200, ajax_response_fail(ajax_build_message($lang["cantmodifycollection"])));
}
$allow_add = true;
// If collection has been shared externally need to check access and permissions
$external_keys = get_collection_external_access($collection);
if (is_array($external_keys) && !empty($external_keys)) {
if (checkperm("noex")) {
$allow_add = false;
} else {
// Not permitted if share is open and access is restricted
if (min(array_column($external_keys, "access")) < get_resource_access($add)) {
$allow_add = false;
}
}
if (!$allow_add) {
ajax_send_response(200, ajax_response_fail(ajax_build_message($lang["sharedcollectionaddblocked"])));
}
}
if ($allow_add) {
if (!add_resource_to_collection($resource, $collection, $smartadd, $size, $addtype)) {
ajax_send_response(200, ajax_response_fail(ajax_build_message($lang["cantmodifycollection"])));
}
daily_stat("Add resource to collection", $resource);
}
ajax_send_response(200, ajax_response_ok_no_data());
}
if ($action == "add_multiple_resources") {
$resource_list = json_decode(getval("resource_list", false));
$smartadd = getval("smartadd", false);
$size = getval("size", "");
$addtype = getval("addtype", "");
$collection_data = get_collection($collection);
if ($collection_data["type"] == COLLECTION_TYPE_UPLOAD) {
ajax_send_response(200, ajax_response_fail(ajax_build_message($lang["cantmodifycollection"])));
}
$allow_add = true;
// If collection has been shared externally need to check access and permissions
$external_keys = get_collection_external_access($collection);
if (is_array($external_keys) && !empty($external_keys)) {
if (checkperm("noex")) {
$allow_add = false;
} else {
// Not permitted if share is open and access is restricted
if (min(array_column($external_keys, "access")) < get_resource_access($add)) {
$allow_add = false;
}
}
if (!$allow_add) {
ajax_send_response(200, ajax_response_fail(ajax_build_message($lang["sharedcollectionaddblocked"])));
}
}
if ($allow_add) {
foreach ($resource_list as $resource) {
if (!add_resource_to_collection($resource, $collection, $smartadd, $size, $addtype)) {
ajax_send_response(200, ajax_response_fail(ajax_build_message($lang["cantmodifycollection"])));
}
}
}
ajax_send_response(200, ajax_response_ok_no_data());
}
if ($action == "remove_resource") {
$resource = getval("resource", null, true);
$smartadd = getval("smartadd", false);
$size = getval("size", "");
if (remove_resource_from_collection($resource, $collection, $smartadd)) {
daily_stat("Removed resource from collection", $resource);
ajax_send_response(200, ajax_response_ok_no_data());
}
ajax_send_response(200, ajax_response_fail(ajax_build_message($lang["cantmodifycollection"])));
}
if ($action == "remove_multiple_resources") {
$resource_list = json_decode(getval("resource_list", false));
$smartadd = getval("smartadd", false);
$size = getval("size", "");
foreach ($resource_list as $resource) {
if (remove_resource_from_collection($resource, $collection, $smartadd)) {
daily_stat("Removed resource from collection", $resource);
} else {
ajax_send_response(200, ajax_response_fail(ajax_build_message($lang["cantmodifycollection"])));
}
}
ajax_send_response(200, ajax_response_ok_no_data());
}

View File

@@ -0,0 +1,18 @@
<?php
include "../../include/boot.php";
include "../../include/authenticate.php";
include "../../include/comment_functions.php";
if (
'POST' == $_SERVER['REQUEST_METHOD']
&& !empty($username)
) {
comments_submit();
}
$ref = getval('ref', 0, true);
$collection_mode = ('' != getval('collection_mode', '') ? true : false);
comments_show($ref, $collection_mode);

198
pages/ajax/contactadmin.php Normal file
View File

@@ -0,0 +1,198 @@
<?php
include "../../include/boot.php";
include "../../include/authenticate.php";
# Is this an ajax call from the view page?
$insert = getval("insert", "");
$ref = getval("ref", "", true);
# Load access level
$access = get_resource_access($ref);
# check permissions (error message is not pretty but they shouldn't ever arrive at this page unless entering a URL manually)
if ($access == 2) {
exit("This is a confidential resource.");
}
# Fetch resource data
$resource = get_resource_data($ref);
if ($resource === false) {
exit($lang['resourcenotfound']);
}
$imagename = i18n_get_translated($resource["field" . $view_title_field]);
if (getval("send", "") != "" && enforcePostRequest(false)) {
# If an anonymous user is trying to send a message
# validate that the anti-spam code has been filled in
if (isset($anonymous_login) && $anonymous_login == $username) {
$errors = false;
$spamcode = getval("antispamcode", "");
$usercode = getval("antispam", "");
$spamtime = getval("antispamtime", 0);
if ($spamtime < (time() - 180) || $spamtime > time()) {
$errors = true;
$antispam_error = $lang["expiredantispam"];
} elseif (!hook('replaceantispam_check') && !verify_antispam($spamcode, $usercode, $spamtime)) {
$errors = true;
$antispam_error = $lang["requiredantispam"];
}
if ($errors) {
exit(escape($antispam_error));
}
}
$messagetext = getval("messagetext", "");
$templatevars['url'] = $baseurl . "/?r=" . $ref;
$templatevars['fromusername'] = ($userfullname == "" ? $username : $userfullname);
$templatevars['resourcename'] = $imagename;
$templatevars['emailfrom'] = $useremail;
$subject = $templatevars['fromusername'] . $lang["contactadminemailtext"];
$templatevars['message'] = $messagetext;
$message = $templatevars['fromusername'] . ($useremail != "" ? " (" . $useremail . ")" : "") . $lang["contactadminemailtext"] . "\n\n" . $messagetext . "\n\n" . $lang["clicktoviewresource"] . "\n\n" . $templatevars['url'];
$notification_message = $templatevars['fromusername'] . ($useremail != "" ? " (" . $useremail . ")" : "") . $lang["contactadminemailtext"] . "\n\n" . $messagetext . "\n\n" . $lang["clicktoviewresource"];
global $watermark;
$templatevars['thumbnail'] = get_resource_path($ref, true, "thm", false, "jpg", $scramble = -1, $page = 1, ($watermark) ? (($access == 1) ? true : false) : false);
if (!file_exists($templatevars['thumbnail'])) {
$templatevars['thumbnail'] = "../gfx/no_preview/default.png";
}
# Build message and send.
$admin_notify_emails = array();
$admin_notify_users = array();
$notify_users = get_notification_users("RESOURCE_ADMIN");
foreach ($notify_users as $notify_user) {
get_config_option(['user' => $notify_user['ref'], 'usergroup' => $notify_user['usergroup']], 'user_pref_resource_notifications', $send_message);
if (!$send_message) {
continue;
}
get_config_option(['user' => $notify_user['ref'], 'usergroup' => $notify_user['usergroup']], 'email_user_notifications', $send_email);
if ($send_email && $notify_user["email"] != "") {
$admin_notify_emails[] = $notify_user['email'];
} else {
$admin_notify_users[] = $notify_user["ref"];
}
}
foreach ($admin_notify_emails as $admin_notify_email) {
send_mail($admin_notify_email, $subject, unescape($message), $applicationname, $email_from, "emailcontactadmin", $templatevars, $applicationname);
}
if (count($admin_notify_users) > 0) {
message_add($admin_notify_users, $notification_message, $templatevars['url']);
}
exit("SUCCESS");
}
if ($insert == "") {
# Fetch search details (for next/back browsing and forwarding of search params)
$search = getval("search", "");
$order_by = getval("order_by", "relevance");
$offset = getval("offset", 0, true);
$default_sort_direction = "DESC";
if (substr($order_by, 0, 5) == "field") {
$default_sort_direction = "ASC";
}
$sort = getval("sort", $default_sort_direction);
$archive = getval("archive", 0, true);
include "../../include/header.php";
?>
<p>
<a href="<?php echo $baseurl ?>/pages/view.php?ref=<?php echo urlencode($ref) ?>&search=<?php echo urlencode($search)?>&offset=<?php echo urlencode($offset) ?>&order_by=<?php echo urlencode($order_by) ?>&sort=<?php echo urlencode($sort) ?>&archive=<?php echo urlencode($archive) ?>" onClick="return CentralSpaceLoad(this,true);">
<?php echo LINK_CARET_BACK ?><?php echo escape($lang["backtoresourceview"]); ?>
</a>
</p>
<h1><?php echo escape($lang["contactadmin"]); ?></h1>
<div>
<?php
if ((int) $resource["has_image"] != RESOURCE_PREVIEWS_NONE) { ?>
<img
align="top"
src="<?php echo get_resource_path($ref, false, ($edit_large_preview ? "pre" : "thm"), false, $resource["preview_extension"], -1, 1, checkperm("w"))?>"
alt="<?php echo $imagename ?>" class="Picture"/>
<br />
<?php
} else {
# Show the no-preview icon
?>
<img src="<?php echo $baseurl_short ?>gfx/no_preview/default.png" alt="<?php echo $imagename ?>" class="Picture"/>
<?php
} ?>
</div>
<?php
} ?>
<script>
function sendResourceMessage() {
if (!jQuery('#messagetext').val() || (jQuery('#antispam').length && !jQuery('#antispam').val())) {
alert('<?php echo escape($lang["requiredfields-general"]); ?>');
return false;
}
jQuery.ajax({
type: "POST",
data: jQuery('#contactadminform').serialize(),
url: baseurl_short+"pages/ajax/contactadmin.php?ref="+<?php echo $ref ?>+"&insert=true&send=true",
success: function(html) {
//jQuery('#RecordDownload li:last-child').after(html);
if (html=="SUCCESS") {
alert('<?php echo escape($lang["emailsent"]); ?>');
jQuery('#contactadminboxcontainer').remove();
} else {
alert('<?php echo escape($lang["error"]); ?>: ' + html);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('<?php echo escape($lang["error"]); ?>\n' + textStatus);
}
});
}
</script>
<div class="clearerleft"></div>
<div id="contactadminbox" style="display: none">
<p><?php echo escape($lang["contactadmin"]); ?></p>
<form name="contactadminform" method=post id="contactadminform" action="<?php echo $baseurl_short?>pages/ajax/contactadmin.php?ref=<?php echo $ref ?>">
<?php generateFormToken("contactadminform"); ?>
<input type=hidden name=ref value="<?php echo urlencode($ref) ?>">
<div>
<p><?php echo escape($lang["contactadminintro"]); ?><sup>*</sup></p>
<textarea rows=6 name="messagetext" id="messagetext"></textarea>
<div class="clearerleft"></div>
<div id="contactadminbuttons">
<?php if (isset($anonymous_login) && $anonymous_login == $username && !hook("replaceantispam")) {
if (isset($antispam_error)) {
error_alert($antispam_error, false);
}
render_antispam_question();
} ?>
<input
name="send"
type="submit"
class="contactadminbutton"
value="&nbsp;&nbsp;<?php echo escape($lang["send"]); ?>&nbsp;&nbsp;"
onClick="sendResourceMessage();return false;"
/>
<input
name="cancel"
type="submit"
class="contactadminbutton"
value="&nbsp;&nbsp;<?php echo escape($lang["cancel"]); ?>&nbsp;&nbsp;"
onClick="jQuery('#contactadminbox').slideUp();return false;"
/>
</div>
</div>
</form>
</div>
<?php
if ($insert == "") {
include "../../include/footer.php";
}

361
pages/ajax/contactsheet.php Normal file
View File

@@ -0,0 +1,361 @@
<?php
#
# PDF Contact Sheet Functionality
#
include '../../include/boot.php';
include '../../include/authenticate.php';
include_once '../../include/image_processing.php';
include_once '../../include/pdf_functions.php';
require_once '../../lib/html2pdf/vendor/autoload.php';
use Spipu\Html2Pdf\Html2Pdf;
use Spipu\Html2Pdf\Exception\Html2PdfException;
use Spipu\Html2Pdf\Exception\ExceptionFormatter;
use Montala\ResourceSpace\CommandPlaceholderArg;
$collection = getval('c', 0, true);
$size = getval('size', '');
if (strpos($size, "x") !== false) {
$size = explode("x", $size);
} else {
$size = strtoupper($size);
}
$columns = getval('columns', 1);
$order_by = getval('order_by', 'collection');
$sort = getval('sort', 'asc');
$orientation = getval('orientation', '');
$sheetstyle = getval('sheetstyle', 'thumbnails');
$preview = ('true' == getval('preview', ''));
$previewpage = getval('previewpage', 1, true);
$includeheader = getval('includeheader', '');
$addlink = getval('addlink', '');
$addlogo = getval('addlogo', '');
$addfieldname = getval('addfieldname', '');
$force_watermark = getval('force_watermark', '');
$field_value_limit = getval('field_value_limit', 0, true);
if ($force_watermark === 'true') {
$force_watermark = true;
} elseif ($force_watermark === 'false') {
$force_watermark = false;
}
// Check access
if (!collection_readable($collection)) {
exit($lang['no_access_to_collection']);
}
// Contact sheet options:
$contactsheet_header = ('' != $includeheader ? filter_var($includeheader, FILTER_VALIDATE_BOOLEAN) : $contact_sheet_include_header);
$add_contactsheet_logo = ('' != $addlogo ? filter_var($addlogo, FILTER_VALIDATE_BOOLEAN) : $include_contactsheet_logo);
$contact_sheet_add_link = ('' != $addlink ? filter_var($addlink, FILTER_VALIDATE_BOOLEAN) : $contact_sheet_add_link);
$contact_sheet_field_name = ('' != $addfieldname ? filter_var($addfieldname, FILTER_VALIDATE_BOOLEAN) : false);
$selected_contact_sheet_fields = getval('selected_contact_sheet_fields', array(), false, 'is_array_of_pos_or_zero_ints');
$pdf_properties = array();
$resources = array();
$collectiondata = get_collection($collection);
$user = get_user($collectiondata['user']);
$title = i18n_get_collection_name($collectiondata) . ' - ' . nicedate(date('Y-m-d H:i:s'), $contact_sheet_date_include_time, $contact_sheet_date_wordy);
// Get data
if (is_numeric($order_by)) {
$order_by = "field{$order_by}";
}
$results = do_search("!collection{$collection}", '', $order_by, 0, -1, $sort);
if ($contactsheet_use_field_templates && !isset($contactsheet_field_template)) {
$contactsheet_use_field_templates = false;
}
if ($contactsheet_use_field_templates) {
$field_template = getval('field_template', 0, true);
$getfields = $contactsheet_field_template[$field_template]['fields'];
} else {
switch ($sheetstyle) {
case 'thumbnails':
$getfields = $config_sheetthumb_fields;
break;
case 'list':
$getfields = $config_sheetlist_fields;
break;
case 'single':
$getfields = $config_sheetsingle_fields;
break;
}
}
// If user has specified which fields to show, then respect it
if (!empty($selected_contact_sheet_fields) && $selected_contact_sheet_fields[0] != 0) {
$getfields = $selected_contact_sheet_fields;
}
$csf = array();
foreach ($getfields as $field_id) {
$csf[] = get_resource_type_field($field_id);
}
$pdf_template_path = get_template_path("{$sheetstyle}.php", 'contact_sheet');
$filename_uid = generateUserFilenameUID($userref);
$PDF_filename = get_temp_dir(false, '') . "/contactsheet_" . $collection . "_" . md5($username . $filename_uid . $scramble_key) . ".pdf";
$placeholders = array(
'date' => nicedate(date('Y-m-d H:i:s'), $contact_sheet_date_include_time, $contact_sheet_date_wordy),
'titlefontsize' => $titlefontsize,
'refnumberfontsize' => $refnumberfontsize,
'title' => $title,
'columns' => $columns,
'config_sheetthumb_include_ref' => $config_sheetthumb_include_ref,
'contact_sheet_metadata_under_thumbnail' => $contact_sheet_metadata_under_thumbnail,
'contact_sheet_include_applicationname' => $contact_sheet_include_applicationname
);
if ($contactsheet_header) {
$placeholders['contactsheet_header'] = $contactsheet_header;
}
if ($add_contactsheet_logo) {
$placeholders['add_contactsheet_logo'] = $add_contactsheet_logo;
$placeholders['contact_sheet_logo'] = "$baseurl/$contact_sheet_logo";
$placeholders['contact_sheet_logo_resize'] = $contact_sheet_logo_resize;
}
if ($contact_sheet_add_link) {
$placeholders['contact_sheet_add_link'] = $contact_sheet_add_link;
}
if ($contact_sheet_footer) {
$placeholders['contact_sheet_footer'] = $contact_sheet_footer;
}
// Set PDF properties:
$pdf_properties['orientation'] = $orientation;
$pdf_properties['format'] = $size;
$pdf_properties['author'] = $user['fullname'];
$pdf_properties['subject'] = "{$applicationname} - {$lang['contactsheet']}";
$pdf_properties['font'] = $contact_sheet_font;
$pdf_properties['language'] = resolve_pdf_language();
if (isset($contact_sheet_custom_size_settings[$sheetstyle]["margins"])) {
$pdf_properties['margins'] = $contact_sheet_custom_size_settings[$sheetstyle]["margins"];
} else {
$pdf_properties['margins'] = array(10, 12, 10, 7);
}
if (isset($contact_sheet_custom_size_settings[$sheetstyle]["title"])) {
$pdf_properties['title'] = $contact_sheet_custom_size_settings[$sheetstyle]["title"];
} else {
$pdf_properties['title'] = $title;
}
// Choose the image size requirements
$img_size = ('single' == $sheetstyle ? getval('ressize', 'lpr') : 'pre');
if ($preview) {
$img_size = 'col';
}
if ('single' == $sheetstyle && $preview) {
$img_size = 'pre';
}
foreach ($results as $result_data) {
$access = get_resource_access($result_data);
// Skip confidential resources
if (2 == $access) {
continue;
}
$placeholders['resources'][$result_data['ref']]['contact_sheet_fields'] = array();
foreach ($csf as $contact_sheet_field) {
$contact_sheet_value = '';
$ref = isset($contact_sheet_field['ref']) ? $contact_sheet_field['ref'] : "";
if ($ref == "") {
continue;
}
if (
array_key_exists("field{$ref}", $result_data)
&& !($contact_sheet_field['hide_when_restricted'] && 1 == $access) # Include field unless hide restriction is in effect
) {
$contact_sheet_value = trim(get_data_by_field($result_data['ref'], $contact_sheet_field['ref']));
// By default we don't limit the field but if HTML2PDF throws an error because of TD tags spreading across
// multiple pages, then truncate the value.
if (0 < $field_value_limit) {
$contact_sheet_value = mb_substr($contact_sheet_value, 0, $field_value_limit);
}
// Clean fixed list types of their front comma
if (in_array($contact_sheet_field['type'], $FIXED_LIST_FIELD_TYPES)) {
$contact_sheet_value = tidylist($contact_sheet_value);
}
$placeholders['resources'][$result_data['ref']]['contact_sheet_fields'][$contact_sheet_field['title']] =
array( "title" => i18n_get_translated($contact_sheet_field['title']),
"value" => tidylist(i18n_get_translated($contact_sheet_value)),
"type" => $contact_sheet_field["type"]);
}
}
// Add the preview image
$use_watermark = $force_watermark;
if ('' == $use_watermark) {
$use_watermark = check_use_watermark();
}
// Determine the image path. If no file is found then do not continue.
$img_path = dirname(__DIR__, 2) . "/gfx/no_preview/default.png";
foreach ([$img_size, 'lpr', 'scr', 'pre'] as $img_preview_size) {
if (
!resource_has_access_denied_by_RT_size($result_data['resource_type'], $img_preview_size)
&& ($img_preview_size_path = get_resource_path($result_data['ref'], true, $img_preview_size, false, $result_data['preview_extension'], -1, 1, $use_watermark))
&& file_exists($img_preview_size_path)
) {
$img_path = $img_preview_size_path;
break;
}
}
// Note: _drawImage from html2pdf.class.php supports paths. If using URLs, allow_url_fopen should be turned ON but on
// some systems, even with allow_url_fopen On, it still couldn't load the image. Using the path seemed to have fixed
// the issue.
$placeholders['resources'][$result_data['ref']]['preview_src'] = $img_path;
unset($img_path);
}
if (!headers_sent()) {
// If CSRF is enabled it will break the download function unless the vary header is removed.
header_remove('Vary');
}
try {
$html2pdf = new Html2Pdf($pdf_properties['orientation'], $pdf_properties['format'], $pdf_properties['language'], true, 'UTF-8', $pdf_properties['margins']);
$html2pdf->pdf->SetTitle($pdf_properties['title']);
$html2pdf->pdf->SetAuthor($pdf_properties['author']);
$html2pdf->pdf->SetSubject($pdf_properties['subject']);
$html2pdf->setDefaultFont($pdf_properties['font']);
$available_width = $html2pdf->pdf->getW() - ($html2pdf->pdf->getlMargin() + $html2pdf->pdf->getrMargin());
$available_height = $html2pdf->pdf->getH() - ($html2pdf->pdf->gettMargin() + $html2pdf->pdf->getbMargin());
$placeholders['available_width'] = floor($available_width / (25.4 / 96));
$placeholders['available_height'] = floor($available_height / (25.4 / 96));
// Column width is made as "[column width in mm] / (25.4 / 96) - [adjustment]"
// IMPORTANT: [adjustment] is needed so that the content would be within the margins of the document
$placeholders['column_width'] = floor(floor($available_width / $columns) / (25.4 / 96) - 10);
$pdf_content = process_template($pdf_template_path, $placeholders);
$html2pdf->writeHTML($pdf_content);
} catch (Html2PdfException $e) {
$formatter = new ExceptionFormatter($e);
$contactsheetmessage = $e->getMessage();
debug('CONTACT-SHEET:' . $contactsheetmessage);
debug('CONTACT-SHEET:' . $e->getTraceAsString());
// Starting point
if ($field_value_limit === 0) {
$field_value_limit = 1100;
}
$parameters = array(
'ref' => $collection,
'field_value_limit' => $field_value_limit - 100,
);
if (strpos($contactsheetmessage, "does not fit on only one page") !== false) {
$parameters["error"] = "contactsheet_data_toolong";
}
redirect(generateURL("{$baseurl}/pages/contactsheet_settings.php", $parameters));
echo $formatter->getHtmlMessage();
exit();
}
// Make AJAX preview
if ($preview && isset($imagemagick_path)) {
$contact_sheet_rip = get_temp_dir(false, '') . "/contactsheetrip_" . $collection . "_" . md5($username . $filename_uid . $scramble_key) . ".jpg";
if (file_exists($contact_sheet_rip)) {
unlink($contact_sheet_rip);
}
$contact_sheet_preview_img = get_temp_dir(false, '') . "/contactsheet_" . $collection . "_" . md5($username . $filename_uid . $scramble_key) . ".jpg";
if (file_exists($contact_sheet_preview_img)) {
unlink($contact_sheet_preview_img);
}
if (file_exists($PDF_filename)) {
unlink($PDF_filename);
}
echo $html2pdf->pdf->GetPage();
$html2pdf->Output($PDF_filename, 'F');
// Set up
putenv("MAGICK_HOME={$imagemagick_path}");
$ghostscript_fullpath = get_utility_path('ghostscript');
$convert_fullpath = get_utility_path('im-convert');
if (!$convert_fullpath) {
exit("Could not find ImageMagick 'convert' utility at location '{$imagemagick_path}'");
}
$command = "{$ghostscript_fullpath} -sDEVICE=jpeg -dFirstPage=%%PREVIEWPAGE%% -o -r300 -dJPEGQ=100 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -dLastPage=%%PREVIEWPAGE%% -sOutputFile=%%CONTACT_SHEET_RIP%% %%PDF_FILENAME%%"
. (($config_windows) ? '' : ' 2>&1');
$cmdparams = [
'%%PREVIEWPAGE%%' => $previewpage,
'%%CONTACT_SHEET_RIP%%' => new CommandPlaceholderArg($contact_sheet_rip, 'is_safe_basename'),
'%%PDF_FILENAME%%' => new CommandPlaceholderArg($PDF_filename, 'is_safe_basename'),
];
run_command($command, false, $cmdparams);
$command = "{$convert_fullpath} -resize %%CONTACT_SHEET_PREVIEW_SIZE%% -quality 90 -colorspace %%IMAGEMAGICK_COLORSPACE%% %%CONTACT_SHEET_RIP%% %%CONTACT_SHEET_PREVIEW_IMG%%"
. (($config_windows) ? '' : ' 2>&1');
$cmdparams = [
'%%CONTACT_SHEET_PREVIEW_SIZE%%' => new CommandPlaceholderArg(
$contact_sheet_preview_size,
'is_valid_contact_sheet_preview_size'
),
'%%IMAGEMAGICK_COLORSPACE%%' => $imagemagick_colorspace,
'%%CONTACT_SHEET_RIP%%' => new CommandPlaceholderArg($contact_sheet_rip, 'is_safe_basename'),
'%%CONTACT_SHEET_PREVIEW_IMG%%' => new CommandPlaceholderArg($contact_sheet_preview_img, 'is_safe_basename'),
];
run_command($command, false, $cmdparams);
exit();
}
// Create a resource based on this PDF file or download it?
if ($contact_sheet_resource && enforcePostRequest(getval("ajax", false))) {
$new_resource = create_resource($contact_sheet_resource_type, 0, -1, $lang["createdfromcontactsheet"]);
update_field($new_resource, 8, i18n_get_collection_name($collectiondata) . ' ' . nicedate(date('Y-m-d H:i:s'), $contact_sheet_date_include_time, $contact_sheet_date_wordy));
update_field($new_resource, $filename_field, "{$new_resource}.pdf");
// Relate all resources in collection to the new contact sheet resource
relate_to_collection($new_resource, $collection);
ps_query("UPDATE resource SET file_extension = 'pdf' WHERE ref = ?", array("i",$new_resource));
// Create the file in the new resource folder:
$path = get_resource_path($new_resource, true, '', true, 'pdf');
$html2pdf->Output($path, 'F');
// Create thumbnails and redirect browser to the new contact sheet resource
create_previews($new_resource, true, 'pdf');
redirect("{$baseurl_short}pages/view.php?ref={$new_resource}");
}
// Generate PDF file
$PDF_filename = i18n_get_collection_name($collectiondata) . '.pdf';
$html2pdf->Output($PDF_filename);
hook('endscript');

91
pages/ajax/create_new.php Normal file
View File

@@ -0,0 +1,91 @@
<?php
// Generic modal page to create new resource types or metadata fields
include_once __DIR__ . "/../../include/boot.php";
include_once __DIR__ . "/../../include/authenticate.php";
$newtype = getval("type", "");
if ($newtype == "") {
http_response_code(401);
exit($lang['error-permissiondenied']);
}
$extraparams = array();
switch ($newtype) {
case "resource_type":
$targeturl = $baseurl_short . "pages/admin/admin_resource_types.php";
$newparam = "newtype";
$newtext = $lang["admin_resource_type_create"];
$csrf_code = "admin_resource_types";
break;
case "resource_type_field":
$targeturl = $baseurl_short . "pages/admin/admin_resource_type_fields.php";
$newparam = "newfield";
$newtext = $lang["admin_resource_type_field_create"];
$extraparams["fieldtype"] = FIELD_TYPE_CHECK_BOX_LIST;
$csrf_code = "admin_resource_type_fields";
break;
case "collection":
$targeturl = $baseurl_short . "pages/collections.php";
$newparam = "newcolname";
$newtext = $lang["createnewcollection"];
$extraparams["collection"] = "new";
$csrf_code = "newcollection";
$customformaction = "var newcolname=encodeURIComponent(jQuery('#newcolname').val());CollectionDivLoad('" . $baseurl_short . "pages/collections.php?collection=new&entername='+newcolname);ModalClose();ReloadBrowseBar();";
break;
case "node":
$field = getval("field", 0, true);
if ($field < 1) {
http_response_code(401);
exit($lang['error-permissiondenied']);
}
$parent_nodes = getval("parent_nodes", "");
$targeturl = generateURL($baseurl_short . "pages/admin/admin_manage_field_options.php", array("field" => $field));
$extraparams["submit_new_option"] = "add_new";
$parents = explode(",", $parent_nodes);
$parent = end($parents);
$extraparams["new_option_parent"] = $parent;
$extraparams["expand_nodes"] = $parent_nodes;
$extraparams["reload"] = "true";
$newparam = "new_option_name";
$newtext = $lang["add"];
$csrf_code = "newcollection";
break;
}
?>
<div class="BasicsBox" id="create_new">
<form action="<?php echo $targeturl; ?>" onsubmit="<?php echo isset($customformaction) ? $customformaction : "return CentralSpacePost(this,true);"; ?>">
<div class="Question">
<label><?php echo $newtext; ?></label>
<?php generateFormToken($csrf_code);
foreach ($extraparams as $extraparam => $extravalue) {
echo "<input type=hidden name='" . escape($extraparam) . "' value='" . escape($extravalue) . "'>";
} ?>
<input type="text" class="medwidth" name="<?php echo $newparam ?>" id="<?php echo $newparam ?>" value="">
<div class="clearerleft"></div>
</div>
<?php if ($newtype == "resource_type_field") { ?>
<div class="Question">
<label><?php echo escape($lang["property-field_type"]); ?></label>
<select name="field_type" class="medwidth">
<?php foreach ($field_types as $field_type => $field_type_description) { ?>
<option value="<?php echo $field_type ?>"><?php echo escape($lang[$field_type_description]) ; ?></option>
<?php
} ?>
</select>
</div>
<?php } ?>
<div class="Question">
<input type="submit" class="medcomplementwidth" value="<?php echo escape($lang["save"]); ?>" />
<input type="submit" class="medcomplementwidth" value="<?php echo escape($lang["cancel"]); ?>" onclick="ModalClose();" />
<div class="clearerleft"></div>
</div>
</form>
</div>

View File

@@ -0,0 +1,76 @@
<?php
# Ajax page to return all fixed list field nodes for a given field in the search results (collection or search).
# This information is then displayed when editing multiple resources to provide a sample of the options in use already.
include "../../include/boot.php";
include "../../include/authenticate.php";
$ajax = filter_var(getval('ajax', false), FILTER_VALIDATE_BOOLEAN);
if (!$ajax) {
header('HTTP/1.1 400 Bad Request');
die('AJAX only accepted!');
}
$search = getval('search', '', false);
$restypes = getval('restypes', '', false);
$archive = getval('archive', false);
$field = getval('field', '', false, 'is_numeric');
$question_ref = getval('question', '', false, 'is_numeric');
if ($field == '' || $question_ref == '') {
exit();
}
if (!$archive) {
$archive = 0;
}
$field = (int) $field;
if (checkperm("F" . $field) || (checkperm("F*") && !checkperm("F-" . $field))) {
exit();
}
$resources = do_search($search, $restypes, 'resourceid', $archive, -1, 'ASC', false, 0, false, false, '', false, false, true, true, false);
$resources = array_column($resources, 'ref');
$all_selected_nodes = get_resource_nodes_batch($resources, array($field), true);
$sorted_nodes = array();
foreach ($resources as $resource) {
if (isset($all_selected_nodes[$resource])) {
$resource_nodes = $all_selected_nodes[$resource][$field];
foreach ($resource_nodes as $node) {
if (array_key_exists($node['name'], $sorted_nodes)) {
$sorted_nodes[$node['name']]++;
} else {
$sorted_nodes[$node['name']] = 1;
}
}
}
}
$total_nodes_count = count($sorted_nodes);
if ($total_nodes_count > 0) {
asort($sorted_nodes, SORT_NUMERIC);
$sorted_nodes = array_reverse($sorted_nodes, true);
$sorted_nodes = array_slice($sorted_nodes, 0, 100, true);
$return = '';
$show = 1; # Only show the first 5 results.
foreach ($sorted_nodes as $node_to_return => $count) {
$return .= '<div class="currenteditmulti keywordselected currentmultiquestion' . (int) $question_ref . '"';
if ($show > 5) {
$return .= 'style="display:none;"';
}
$return .= '>' . escape($node_to_return) . " ($count)</div>";
$show++;
}
if ($total_nodes_count > 100) {
$return .= '<div class="currentmultiquestion' . (int) $question_ref . '" style="display:none;">' . escape($lang["edit_multiple_too_many"]) . '</div>';
}
echo $return;
}
exit();

145
pages/ajax/dash_tile.php Executable file
View File

@@ -0,0 +1,145 @@
<?php
/*
* Home Dash Ajax Interface - Montala Ltd, Jethro Dew
* Requests from the dash interactions are processed here.
*/
include "../../include/boot.php";
include "../../include/authenticate.php";
include "../../include/dash_functions.php";
/* You must correctly use exit calls when functionality is complete. */
global $userref,$baseurl_short;
/* Tile */
$rawtile = getval("tile", null, true);
if (isset($rawtile) && !empty($rawtile)) {
if (!is_numeric($rawtile)) {
exit($lang["invaliddashtile"]);
}
$tile = get_tile($rawtile);
if (!$tile) {
exit($lang["nodashtilefound"]);
}
}
/* User Tile */
$user_rawtile = getval("user_tile", null, true);
if (isset($user_rawtile) && !empty($user_rawtile)) {
if (!is_numeric($user_rawtile)) {
exit($lang["invaliddashtile"]);
}
$usertile = get_user_tile($user_rawtile, $userref);
if (!$usertile) {
exit($lang["nodashtilefound"]);
}
}
/*
* Reorder Tile
*/
$index = getval('new_index', '', true);
$selected_user_group = getval('selected_user_group', '', true);
// Re-order user tiles
if (!empty($index) && isset($usertile) && '' == $selected_user_group && enforcePostRequest(true)) {
if ($index > $usertile["order_by"]) {
$index += 5;
} else {
$index -= 5;
}
update_user_dash_tile_order($userref, $usertile["ref"], $index);
reorder_user_dash($userref);
exit("Tile " . $usertile["ref"] . " at index: " . ($index));
}
// Re-order user group tiles
if (!empty($index) && isset($tile) && !isset($usertile) && '' != $selected_user_group && enforcePostRequest(true)) {
$usergroup_tile = get_usergroup_tile($tile['ref'], $selected_user_group);
if (0 == count($usergroup_tile)) {
exit($lang['nodashtilefound']);
}
if ($index > $usergroup_tile['default_order_by']) {
$index += 5;
} else {
$index -= 5;
}
update_usergroup_dash_tile_order($selected_user_group, $usergroup_tile['dash_tile'], $index);
reorder_usergroup_dash($selected_user_group);
log_activity($lang['dashtile'], LOG_CODE_REORDERED, $index, 'usergroup_dash_tile', 'default_order_by', $usergroup_tile['dash_tile']);
exit("Tile {$usergroup_tile['dash_tile']} at index: {$index}");
}
// Re-order default dash tiles
if (!empty($index) && isset($tile) && !isset($usertile) && '' == $selected_user_group && enforcePostRequest(true)) {
if ($index > $tile["default_order_by"]) {
$index += 5;
} else {
$index -= 5;
}
update_default_dash_tile_order($tile["ref"], $index);
reorder_default_dash();
echo "Tile " . $tile["ref"] . " at index: " . ($index);
log_activity($lang["dashtile"], LOG_CODE_REORDERED, $index, 'dash_tile', 'default_order_by', $tile["ref"]);
exit();
}
/*
* Delete Tile
*/
$delete = getval("delete", false);
if ($delete && isset($usertile) && enforcePostRequest(true)) {
if (!checkPermission_dashmanage()) {
exit($lang["error-permissiondenied"]);
}
delete_user_dash_tile($usertile["ref"], $userref);
reorder_user_dash($userref);
echo "Deleted U" . $usertile['ref'];
exit();
}
if ($delete && isset($tile) && !isset($usertile) && enforcePostRequest(true)) {
if (!checkPermission_dashcreate()) {
exit($lang["error-permissiondenied"]);
}
#Check config tiles for permanent deletion
$force = false;
$search_string = explode('?', $tile["url"]);
parse_str(str_replace("&amp;", "&", $search_string[1]), $search_string);
if ($search_string["tltype"] == "conf") {
$force = !checkTileConfig($tile, $search_string["tlstyle"]);
}
delete_dash_tile($tile["ref"], true, $force);
log_activity($lang['manage_all_dash'], LOG_CODE_DELETED, $tile["title"], 'dash_tile', null, $tile["ref"]);
reorder_default_dash();
echo "Deleted " . $tile['ref'];
exit();
}
if (!isset($usertile) && !isset($tile)) {
exit($lang["nodashtilefound"]);
}
/*
* Generating Tiles
*/
$tile_type = getval("tltype", "");
$tile['tlsize'] = ('double' === getval('tlsize', '') ? 'double' : '');
$tile_style = getval("tlstyle", "");
$tile_id = (isset($usertile)) ? "contents_user_tile" . $usertile["ref"] : "contents_tile" . $tile["ref"];
$tile_width = getval("tlwidth", ($tile['tlsize'] === 'double' ? 515 : 250), true);
$tile_height = getval("tlheight", 180, true);
if (!is_numeric($tile_width) || !is_numeric($tile_height) || $tile_width <= 0 || $tile_height <= 0) {
exit($lang["error-missingtileheightorwidth"]);
}
include "../../include/dash_tile_generation.php";
tile_select($tile_type, $tile_style, $tile, $tile_id, $tile_width, $tile_height);
exit($lang["nodashtilefound"]);

View File

@@ -0,0 +1,45 @@
<?php
/*
* Ajax generation handling for dash tile previews - Montala Ltd, Jethro Dew
* Separated out into a new file as there is no existing dash tile record to pull information from
* Content for the tile is sent via ajax to this page. Standard build functions available from include/dash_tile_generation.php
*/
include "../../include/boot.php";
include "../../include/authenticate.php";
include "../../include/dash_functions.php";
global $userref,$baseurl_short;
$tile_type = getval("tltype", "");
$tile_style = getval("tlstyle", "");
$promoted_image = getval('promimg', '');
$tile = array();
$tile['ref'] = getval('edit', '');
$tile['link'] = getval('tllink', '');
$tile['txt'] = getval('tltxt', '');
$tile['title'] = getval('tltitle', '');
$tile['resource_count'] = getval('tlrcount', '');
$tile['tlsize'] = ('double' === getval('tlsize', '') ? 'double' : '');
// Simulate URL so we can preview based on requested params
$tile['url'] = generateURL(
'pages/ajax/dash_tile_preview.php',
[
'tltype' => $tile_type,
'tlsize' => $tile['tlsize'],
'tlstyle' => $tile_style,
'promimg' => $promoted_image,
]
);
$tile_id = "previewdashtile";
$tile_width = getval("tlwidth", ($tile['tlsize'] === 'double' ? 515 : 250), true);
$tile_height = getval("tlheight", 180, true);
if (!is_numeric($tile_width) || !is_numeric($tile_height) || $tile_width <= 0 || $tile_height <= 0) {
exit($lang["error-missingtileheightorwidth"]);
}
include "../../include/dash_tile_generation.php";
tile_select($tile_type, $tile_style, $tile, $tile_id, $tile_width, $tile_height);
exit($lang["nodashtilefound"]);

View File

@@ -0,0 +1,132 @@
<?php
include __DIR__ . '/../../include/boot.php';
include __DIR__ . '/../../include/authenticate.php';
include_once __DIR__ . '/../../include/facial_recognition_functions.php';
$return = array();
$action = getval('action', '');
$resource = getval('resource', 0, true);
if (
!$facial_recognition_active ||
!get_edit_access($resource) ||
!metadata_field_edit_access($facial_recognition_tag_field)
) {
header('HTTP/1.1 401 Unauthorized');
$return['error'] = array(
'status' => 401,
'title' => 'Unauthorized',
'detail' => $lang['error-permissiondenied']);
echo json_encode($return);
exit();
}
if ('prepare_selected_area' == $action) {
$shape = getval('shape', [], false, 'is_array');
if (
!isset($shape['geometry']['x']) ||
!isset($shape['geometry']['y']) ||
!isset($shape['geometry']['width']) ||
!isset($shape['geometry']['height'])
) {
$return['error'] = array(
'status' => 400,
'title' => 'Bad Request',
'detail' => 'The shape provided was not correctly formatted!');
}
$image_path = get_resource_path(
$resource,
true,
'pre',
true,
ps_value("SELECT preview_extension AS `value` FROM resource WHERE ref = ?", ['i', $resource], 'jpg')
);
$prepared_image_path = get_resource_path(
$resource,
true,
FACIAL_RECOGNITION_CROP_SIZE_PREFIX . 'test',
true,
FACIAL_RECOGNITION_PREPARED_IMAGE_EXT
);
$return['data'] = prepareFaceImage(
$image_path,
$prepared_image_path,
$shape['geometry']['x'],
$shape['geometry']['y'],
$shape['geometry']['width'],
$shape['geometry']['height']
);
}
if ('predict_label' == $action) {
$model_file_path = "{$facial_recognition_face_recognizer_models_location}/lbph_model.xml";
$prepared_image_path = get_resource_path(
$resource,
true,
FACIAL_RECOGNITION_CROP_SIZE_PREFIX . 'test',
true,
FACIAL_RECOGNITION_PREPARED_IMAGE_EXT
);
$prediction = faceRecognizerPredict($model_file_path, $prepared_image_path);
if (false === $prediction && file_exists($model_file_path) && file_exists($prepared_image_path)) {
$return['error'] = array(
'status' => 500,
'title' => 'Internal Server Error',
'detail' => 'ResourceSpace was not able to predict a label.');
echo json_encode($return);
exit();
}
// When facial recognition has never been trained, it won't have lbph model states so faceRecognizerPredict() will
// return false because the files do not exist. Basically this should be seen as an unknown person rather than a
// system error
elseif (false === $prediction && (!file_exists($model_file_path) || !file_exists($prepared_image_path))) {
$prediction = [];
$prediction[0] = -1;
}
// Unknown
if (-1 === $prediction[0]) {
$return['data'] = array(
'ref' => null,
'resource_type_field' => $facial_recognition_tag_field,
'name' => $lang['unknown'],
'parent' => null,
'order_by' => null
);
echo json_encode($return);
exit();
}
$tag = array();
if (get_node($prediction[0], $tag)) {
$return['data'] = $tag;
// Remove the file since it is used only once. Once we have tagged it, the trainer will come later
// and learn who this person is anyway, regardless of this prediction
unlink($prepared_image_path);
echo json_encode($return, JSON_NUMERIC_CHECK);
exit();
}
}
// If by this point we still don't have a response for the request,
// create one now telling client code this is a bad request
if (0 === count($return)) {
$return['error'] = array(
'status' => 400,
'title' => 'Bad Request',
'detail' => 'The request could not be handled by facial_recognition.php. This is the default response!');
}
echo json_encode($return);
exit();

View File

@@ -0,0 +1,32 @@
<?php
include "../../include/boot.php";
$ref = getval("ref", "", true);
$k = getval("k", "");
if (($k == "") || (!check_access_key($ref, $k))) {
include "../../include/authenticate.php";
}
// Get resource info and access, would usually be available in ../pages/view.php.
// Load resource data.
$resource = get_resource_data($ref);
if ($resource === false) {
exit($lang['resourcenotfound']);
}
// Load resource field data.
$fields = get_resource_field_data($ref, false, !hook("customgetresourceperms"), null, $k != "", $use_order_by_tab_view);
$edit_access = get_edit_access($ref, $resource["archive"], $resource);
if ($k != "") {
$edit_access = 0;
}
// If we are here, we have specifically requested it, so make sure it is displayed.
$geolocation_panel_only = true;
include "../../include/geocoding_view.php";

96
pages/ajax/get_nodes.php Normal file
View File

@@ -0,0 +1,96 @@
<?php
include __DIR__ . '/../../include/boot.php';
include __DIR__ . '/../../include/authenticate.php';
include_once __DIR__ . '/../../include/node_functions.php';
/*
This allows Asynchronous searches for nodes, either by: node ID or simply by searching for a name (fuzzy search)
Expected functionality:
If we search by node ID, then if found we get its details back
Otherwise, we get all results back based on the name we've searched for.
*/
$node = getval('node', 0, true);
$resource_type_field = getval('resource_type_field', 0, true);
$name = trim(getval('name', ''));
$rows = getval('rows', 10, true);
// Prevent access to fields to which user does not have access to
if (!metadata_field_view_access($resource_type_field)) {
header('HTTP/1.1 401 Unauthorized');
$return['error'] = array(
'status' => 401,
'title' => 'Unauthorized',
'detail' => $lang['error-permissiondenied']);
echo json_encode($return);
exit();
}
$return = array();
$found_node_by_ref = array();
$current_node_pointer = 0;
if ($node > 0 && get_node($node, $found_node_by_ref)) {
$found_node_by_ref['name'] = i18n_get_translated($found_node_by_ref['name']);
$return['data'] = $found_node_by_ref;
echo json_encode($return);
exit();
}
// Fuzzy search by node name:
// Translate (i18l) all options and return those that have a match for what client code searched (fuzzy searching still applies)
if ($name != "") {
// Set $keywords_remove_diacritics so as to only add versions with diacritics to return array if none are in the submitted string
$keywords_remove_diacritics = mb_strlen($name) === strlen($name);
$name = normalize_keyword($name);
foreach (get_nodes($resource_type_field, null, true, null, $rows, $name) as $node) {
if ($rows == $current_node_pointer) {
break;
}
$i18l_name = i18n_get_translated($node['name']);
$compare = normalize_keyword($i18l_name);
// Skip any translated (i18l) names that don't contain what client code searched for
if (false === mb_strpos(mb_strtolower($compare), mb_strtolower($name))) {
continue;
}
$node['name'] = $i18l_name;
$return['data'][] = $node;
// Increment only when valid nodes have been added to the result set
$current_node_pointer++;
}
}
// Search did not return any results back. This is still considered a successful request!
if (($node > 0 || $name != "") && !isset($return['data']) && 0 === count($return)) {
$return['data'] = array();
}
// Only resource type field specified? That means client code is querying for all options of this field
if ($resource_type_field > 0 && $name == "") {
foreach (get_nodes($resource_type_field, null, true) as $node) {
$node['name'] = i18n_get_translated($node["name"]);
$return['data'][] = $node;
}
}
// If by this point we still don't have a response for the request,
// create one now telling client code this is a bad request
if (0 === count($return)) {
$return['error'] = array(
'status' => 400,
'title' => 'Bad Request',
'detail' => 'The request could not be handled by get_nodes.php!');
}
echo json_encode($return);
exit();

View File

@@ -0,0 +1,22 @@
<?php
include "../../include/boot.php";
include "../../include/authenticate.php";
$force_appearance = getval("force_appearance", "");
# User group specific logo
if (isset($usergroup)) {
$curr_group = get_usergroup($usergroup);
if (!empty($curr_group["group_specific_logo"])) {
$linkedheaderimgsrc = (isset($storageurl) ? $storageurl : $baseurl . "/filestore") . "/admin/groupheaderimg/group" . $usergroup . "." . $curr_group["group_specific_logo"];
}
if (!empty($curr_group["group_specific_logo_dark"])) {
$linkedheaderimgsrc_dark = (isset($storageurl) ? $storageurl : $baseurl . "/filestore") . "/admin/groupheaderimg/group" . $usergroup . "_dark." . $curr_group["group_specific_logo_dark"];
}
}
header('Content-Type: text/plain');
echo get_header_image(false, true, $force_appearance);

View File

@@ -0,0 +1,70 @@
<?php
include '../../include/boot.php';
include '../../include/authenticate.php';
$forpage = getval('page', '');
$type = getval('actiontype', '');
$ref = getval('ref', '', true);
switch ($type) {
case "collection":
hook('render_themes_list_tools', '', $ref);
$collection_data = get_collection($ref);
render_actions($collection_data, false, false, $ref, array(), true, $forpage);
break;
case "selection_collection":
render_selected_collection_actions();
break;
case "search":
$search = getval("search", "");
$restypes = getval("restypes", "");
$order_by = getval("order_by", "relevance");
$archive = getval("archive", "0");
$per_page = getval("per_page", null, true);
$offset = getval("offset", null, true);
$fetchrows = (!is_null($per_page) || !is_null($offset) ? $per_page + $offset : -1);
$sort = getval("sort", "desc");
$recent_search_daylimit = getval("recent_search_daylimit", "");
$go = getval("go", "");
$editable_only = getval("foredit", "") == "true";
$result = do_search(
$search,
$restypes,
$order_by,
$archive,
$fetchrows,
$sort,
false,
DEPRECATED_STARSEARCH,
false,
false,
$recent_search_daylimit,
$go,
true,
false,
$editable_only
);
$resources_count = is_array($result) ? count($result) : 0;
// Is this a collection search?
$collectiondata = array();
$collection_search_strpos = strpos($search, "!collection");
$collectionsearch = $collection_search_strpos !== false && $collection_search_strpos === 0; // We want the default collection order to be applied
if ($collectionsearch) {
// Collection search may also have extra search keywords passed to search within a collection
$search_trimmed = substr($search, 11); // The collection search must always be the first part of the search string
$search_elements = split_keywords($search_trimmed, false, false, false, false, true);
$collection = (int)array_shift($search_elements);
$search = "!collection" . $collection . " " . implode(", ", $search_elements);
$collectiondata = get_collection($collection);
}
render_actions($collectiondata, true, false);
break;
case "resource":
break;
}

398
pages/ajax/message.php Normal file
View File

@@ -0,0 +1,398 @@
<?php
DEFINE("MESSAGE_POLLING_ABSENT_USER_TIMEOUT_SECONDS", 30);
DEFINE("MESSAGE_FADEOUT_SECONDS", 5);
// check for callback, i.e. this file being called directly to get any new messages
if (basename(__FILE__) == basename($_SERVER['PHP_SELF'])) {
include_once __DIR__ . "/../../include/boot.php";
include __DIR__ . "/../../include/authenticate.php";
if ($actions_on) {
include_once __DIR__ . "/../../include/action_functions.php";
include_once __DIR__ . "/../../include/request_functions.php";
}
if (getval("check_upgrade_in_progress", "") != "") {
$data["upgrade_in_progress"] = false;
if (is_process_lock("process_lock_upgrade_in_progress")) {
$data["upgrade_in_progress"] = true;
}
echo json_encode(array(
"status" => "success",
"data" => $data));
exit();
}
$user = getval('user', 0, true);
$seen = getval('seen', 0, true);
$unseen = getval('unseen', 0, true);
$allseen = getval('allseen', 0, true);
$deleteselusrmsg = getval('deleteselusrmsg', "");
$selectedseen = getval('selectedseen', "");
$selectedunseen = getval('selectedunseen', "");
$getrefs = getval('getrefs', 0, true);
if (0 < $user) {
if (is_numeric($user) && !checkperm_user_edit($user)) {
exit($lang['error-permissiondenied']);
}
} else {
// no user specified so default to the current user
$user = $userref;
}
// It is an acknowledgement so set as seen and get out of here
if (0 < $seen) {
message_seen($seen);
return;
}
if (0 < $unseen) {
message_unseen($unseen);
return;
}
// Acknowledgement all messages then get out of here
if (0 < $allseen) {
message_seen_all($allseen);
return;
}
// Purge messages that have an expired TTL then get out of here
if ('' != getval('purge', '')) {
message_purge();
return;
}
// Delete all selected messages
if ($deleteselusrmsg != "") {
message_deleteselusrmsg($deleteselusrmsg);
return;
}
// Mark all selected messages as seen
if ($selectedseen != "") {
message_selectedseen($selectedseen);
return;
}
// Mark all selected messages as unseen
if ($selectedunseen != "") {
message_selectedunseen($selectedunseen);
return;
}
// Return list of references of all messages
if ($getrefs > 0) {
message_getrefs($getrefs);
return;
}
// Check if there are messages
$messages = array();
message_get($messages, $user); // note: messages are passed by reference
$extramessage = array('ref' => 0);
$extramessages = false;
if ($actions_on) {
$actioncount = get_user_actions(true);
if ($actioncount > 0) {
$extramessage['actioncount'] = $actioncount;
$extramessages = true;
}
}
if ($offline_job_queue) {
$userfailedjobs = count(job_queue_get_jobs("", STATUS_ERROR, (checkperm('a') ? 0 : $userref)));
$allfailedjobs = count(job_queue_get_jobs("", STATUS_ERROR));
$jobcounts = [];
if ($userfailedjobs > 0) {
$jobcounts['user'] = $userfailedjobs;
}
if ($allfailedjobs > 0) {
$jobcounts['all'] = $allfailedjobs;
}
if (!empty($jobcounts)) {
$extramessage['failedjobcount'] = $jobcounts;
$extramessages = true;
}
}
if ($extramessages) {
$messages[] = $extramessage;
}
ob_clean(); // just in case we have any stray whitespace at the start of this file
echo json_encode($messages);
return;
}
?><script>
var activeSeconds=<?php echo MESSAGE_POLLING_ABSENT_USER_TIMEOUT_SECONDS; ?>;
var message_timer = null;
var message_refs = new Array();
var message_poll_first_run = true;
function message_poll()
{
if (message_timer != null)
{
clearTimeout(message_timer);
message_timer = null;
}
activeSeconds-=<?php echo $message_polling_interval_seconds; ?>;
<?php
if ($message_polling_interval_seconds > 0) {
?>if(activeSeconds < 0)
{
message_timer = window.setTimeout(message_poll,<?php echo $message_polling_interval_seconds; ?> * 1000);
return;
}
<?php
}
?>
jQuery.ajax({
url: '<?php echo $baseurl; ?>/pages/ajax/message.php?ajax=true',
type: 'GET',
success: function(messages, textStatus, xhr) {
if(xhr.status==200 && isJson(messages) && (messages=jQuery.parseJSON(messages)) && jQuery(messages).length>0)
{
messagecount = messages.length;
if(messages[messages.length - 1]['ref'] == 0)
{
// The last message is a dummy entry with a count of actions and failed jobs
messagecount = messagecount-1;
}
totalcount = messagecount;
actioncount=0;
failedjobcount=0;
if (typeof(messages[messages.length - 1]['actioncount']) !== 'undefined') // There are actions as well as messages
{
actioncount=parseInt(messages[messagecount]['actioncount']);
totalcount=totalcount+actioncount;
}
if (typeof(messages[messages.length - 1]['failedjobcount']) !== 'undefined')
{
userfailedjobcount = parseInt(messages[messagecount]['failedjobcount']['user']);
totalcount = totalcount + userfailedjobcount;
failedjobcount = parseInt(messages[messagecount]['failedjobcount']['all']);
}
jQuery('span.MessageTotalCountPill').html(totalcount).fadeIn();
if (activeSeconds > 0 || message_poll_first_run)
{
for(var i=0; i < messagecount; i++)
{
var ref = messages[i]['ref'];
if (message_poll_first_run)
{
message_refs.push(ref);
continue;
}
if (message_refs.indexOf(ref)!=-1)
{
continue;
}
message_refs.push(ref);
var message = nl2br(messages[i]['message']);
var url = messages[i]['url'];
if(messages[i]['type'] & <?php echo MESSAGE_ENUM_NOTIFICATION_TYPE_USER_MESSAGE ?> && pagename =='user_message' && parseInt(messages[i]['ownerid']) == parseInt(msgto))
{
// Show the message directly on the page if on user_message.php and communicating with this user
showUserMessage(messages[i]['message'],false);
}
else
{
// Show message popup if configured
<?php
if ($user_pref_show_notifications) {
?>
message_display(message, url, ref, function (ref) {
jQuery.get('<?php echo $baseurl; ?>/pages/ajax/message.php?ajax=true&seen=' + ref);
});
<?php
}
?>
}
message_poll();
}
}
if (actioncount>0)
{
jQuery('span.ActionCountPill').html(actioncount).fadeIn();
}
else
{
jQuery('span.ActionCountPill').hide();
}
if (messagecount>0)
{
jQuery('span.MessageCountPill').html(messagecount).fadeIn();
}
else
{
jQuery('span.MessageCountPill').hide();
}
if (failedjobcount>0)
{
jQuery('span.FailedJobCountPill').html(failedjobcount).fadeIn();
let teampill = jQuery('#TeamMessages');
if(teampill.attr('data-value') != undefined)
{
failedjobcount = failedjobcount + teampill.attr('data-value');
}
teampill.html(failedjobcount).fadeIn();
}
else
{
jQuery('span.FailedJobCountPill').hide();
}
}
else
{
jQuery('span.MessageTotalCountPill').hide();
jQuery('span.MessageCountPill').hide();
jQuery('span.ActionCountPill').hide();
}
}
}).done(function() {
<?php if ($message_polling_interval_seconds > 0) {
?>message_timer = window.setTimeout(message_poll,<?php echo $message_polling_interval_seconds; ?> * 1000);
<?php
}
?>
message_poll_first_run = false;
});
check_upgrade_in_progress();
}
jQuery(document).bind("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error",
function() {
activeSeconds=<?php echo MESSAGE_POLLING_ABSENT_USER_TIMEOUT_SECONDS; ?>;
});
jQuery(document).ready(function () {
message_poll();
});
function message_display(message, url, ref, callback)
{
if (typeof ref==="undefined")
{
ref=new Date().getTime();
}
if (typeof url==="undefined")
{
url="";
}
if (url!="")
{
url=decodeURIComponent(url);
url="<a href='" + url + "'><?php echo escape($lang['link']); ?></a>";
}
var id='message' + ref;
if (jQuery("#" + id).length) // already being displayed
{
return;
}
jQuery('div#MessageContainer')
.append("<div class='MessageBox' style='display: none;' id='" + id + "'>" + nl2br(DOMPurify.sanitize(message)) + "<br />" + url + "</div>")
.after(function()
{
var t = window.setTimeout(function()
{
jQuery("div#" + id).fadeOut("fast",function()
{
this.remove()
}
)
},<?php echo MESSAGE_FADEOUT_SECONDS; ?>000);
jQuery("div#" + id).show().bind("click",function()
{
jQuery("div#" + id).fadeOut("fast", function()
{
jQuery("div#" + id).remove();
jQuery.get('<?php echo $baseurl; ?>/pages/ajax/message.php?ajax=true&seen=' + ref);
if (typeof callback === 'function')
{
callback();
}
});
});
jQuery("div#" + id).bind("mouseenter",function()
{
window.clearTimeout(t);
jQuery("div#" + id).fadeIn("fast");
});
jQuery("div#" + id).bind("mouseleave",function()
{
window.clearTimeout(t);
t = window.setTimeout(function()
{
jQuery("div#" + id).fadeOut("fast",function()
{
this.remove();
}
)},<?php echo ceil(MESSAGE_FADEOUT_SECONDS / 2); ?>000);
});
});
}
function message_modal(message, url, ref, owner)
{
if (typeof ref==="undefined")
{
ref=new Date().getTime();
}
if (typeof url==="undefined")
{
url="";
}
if (url!="")
{
url=decodeURIComponent(url);
url=DOMPurify.sanitize(url);
url="<a class='message_link' href='" + url + "'><?php echo escape($lang['link']); ?></a>";
}
if (typeof owner==="undefined" || owner=='')
{
owner = '<?php echo escape($applicationname); ?>';
}
jQuery("#modal_dialog").html("<div class='MessageText'>" + nl2br(DOMPurify.sanitize(message)) + "</div>" + url);
jQuery("#modal_dialog").addClass('message_dialog');
jQuery("#modal_dialog").dialog({
title: '<?php echo escape($lang['message'] . " " . strtolower($lang["from"])) . " "; ?>' + owner,
modal: true,
resizable: false,
buttons: [{text: "<?php echo escape($lang['ok']); ?>",
click: function() {
jQuery( this ).dialog( "close" );
}}],
dialogClass: 'message',
width: (jQuery(window).width() <= 1280) ? jQuery(window).width()*0.7 : 600,
maxHeight: jQuery(window).height()*0.8,
draggable: true,
open: function(event, ui) {
jQuery('.ui-widget-overlay').bind('click', function(){ jQuery("#modal_dialog").dialog('close'); });
jQuery( ".ui-dialog-content" ).scrollTop(0);
},
close: function( event, ui ) {
jQuery('#modal_dialog').html('');
jQuery("#modal_dialog").removeClass('message_dialog');
jQuery.get('<?php echo $baseurl; ?>/pages/ajax/message.php?ajax=true&seen=' + ref);
},
dialogClass: 'no-close'
});
}
</script>

View File

@@ -0,0 +1,296 @@
<?php
include "../../include/boot.php";
include "../../include/authenticate.php";
if (!$metadata_report) {
exit("This function is not enabled.");
}
$exiftool_fullpath = get_utility_path("exiftool");
if (!$exiftool_fullpath) {
echo escape($lang["exiftoolnotfound"]);
} else {
$ref = getval("ref", "");
$resource = get_resource_data($ref);
if ($resource === false) {
exit("Could not fetch resource data.");
} // Should not occur - invalid ref?
$ext = $resource['file_extension'];
if ($ext == "") {
die($lang['nometadatareport']);
}
$resource_type = $resource['resource_type'];
$type_name = get_resource_type_name($resource_type);
$image = get_resource_path($ref, true, "", false, $ext);
if (!file_exists($image)) {
die($lang['error']);
}
#test if filetype is supported by exiftool
$command = $exiftool_fullpath . " -listf";
$formats = run_command($command);
$ext = strtoupper($ext);
if (strlen(strstr($formats, $ext)) < 2) {
die(str_replace_formatted_placeholder("%extension", $ext, $lang['filetypenotsupported']));
}
if (in_array(strtolower($ext), $exiftool_no_process)) {
die(str_replace_formatted_placeholder("%extension", $ext, $lang['exiftoolprocessingdisabledforfiletype']));
}
#build array of writable tags
$command = $exiftool_fullpath . " -listw";
$writable_tags = run_command($command);
$writable_tags = strtolower(str_replace("\n", "", $writable_tags));
$writable_tags_array = explode(" ", $writable_tags);
$command = $exiftool_fullpath . " -ver";
$exiftool_version = run_command($command);
if (preg_match('/Warning: Library/', $exiftool_version) === 1) {
echo escape($lang["exiftoolconflictingversions"]);
exit();
}
if ($exiftool_version >= 7.4) {
#build array of writable formats
$command = $exiftool_fullpath . " -listwf";
$writable_formats = run_command($command);
$writable_formats = str_replace("\n", "", $writable_formats);
$writable_formats_array = explode(" ", $writable_formats);
$file_writability = in_array($ext, $writable_formats_array);
}
# Create a report for the original file.
$command = $exiftool_fullpath . " -s -t -G --filename --exiftoolversion --filepermissions --NativeDigest --History --Directory " . escapeshellarg($image) . " 2>&1";
$report_original = run_command($command);
# Create a temporary file (simulate download) and create a report for it.
$tmpfile = write_metadata($image, $ref);
if ($tmpfile === false || !file_exists($tmpfile)) {
$tmpfile = $image;
$donotdelete = true;
}
$command = $exiftool_fullpath . " -s -t -G --filename --exiftoolversion --filepermissions --NativeDigest --History --Directory " . escapeshellarg($tmpfile) . " 2>&1";
$report_simulated = run_command($command);
# Remove the temporary file.
if (!isset($donotdelete)) {
unlink($tmpfile);
}
# Process the report of the simulated download.
$results_simulated = array();
$i = 0;
$fields_simulated = explode("\n", $report_simulated);
foreach ($fields_simulated as $field_simulated) {
$tag_value = explode("\t", $field_simulated);
if (count($tag_value) == 3) {
$results_simulated[$i]["group"] = trim(strtolower($tag_value[0]));
$results_simulated[$i]["tag"] = trim(strtolower($tag_value[1]));
$results_simulated[$i]["value"] = trim($tag_value[2]);
$tagprops = "";
if (in_array($results_simulated[$i]["tag"], $writable_tags_array) && $file_writability) {
$tagprops .= "w";
}
if ($tagprops != "") {
$results_simulated[$i]["tagprops"] = "($tagprops)";
} else {
$results_simulated[$i]["tagprops"] = "";
}
$i++;
}
}
# Create a list of resource fields which are mapped to exiftool tags.
$write_to = get_exiftool_fields($resource_type); # Returns an array of exiftool tags for the particular resource type, which are basically RS resource fields with an 'exiftool field' set.
for ($i = 0; $i < count($write_to); $i++) { # Loop through all the found fields.
# Populate the resourcefields array.
$tags = explode(",", $write_to[$i]['exiftool_field']); # Each 'exiftool field' may contain more than one tag.
foreach ($tags as $tag) {
$tag = strtolower($tag);
$resourcefields[$tag]['ref'] = $write_to[$i]['ref'];
$resourcefields[$tag]['listed'] = false;
}
}
# Build report:
# Work out the write status.
if (!isset($file_writability)) {
$file_writability = true;
$writability_comment = $lang['notallfileformatsarewritable'];
} else {
$writability_comment = "";
}
($exiftool_write && $file_writability) ? $write_status = $lang['metadatatobewritten'] . " " . $writability_comment : $write_status = $lang['nowritewillbeattempted'];
echo "<table class=\"InfoTable\">";
echo "<tr><td colspan=\"5\">" . escape("{$lang['resourcetype']}: {$type_name}") . "</td></tr>";
echo "<tr><td colspan=\"5\">" . escape($lang['existing_tags']) . "</td></tr>";
echo "<tr><td width=\"150\">" . escape($applicationname) . "</td><td width=\"50\">" . escape($lang['group']) . "</td><td width=\"150\">" . escape($lang['exiftooltag']) . "</td><td>" . escape($lang['embeddedvalue']) . "</td><td>" . escape($write_status) . "</td>";
hook('more_metadata_report_headings');
echo "</tr>";
# Process the report of the original file.
$fields = explode("\n", $report_original);
foreach ($fields as $field) {
echo "<tr>";
$tag_value = explode("\t", $field);
if (count($tag_value) == 3) {
$group = trim(strtolower($tag_value[0]));
$tag = trim(strtolower($tag_value[1]));
$value = trim($tag_value[2]);
$tagprops = "";
if (in_array($tag, $writable_tags_array) && $file_writability) {
$tagprops .= "w";
}
if ($tagprops != "") {
$tagprops = "($tagprops)";
}
$RS_field_ref = '';
$RS_field_name = '';
# Check if the tag is mapped to an RS resource field.
if (isset($resourcefields[$tag]['ref']) || isset($resourcefields[$group . ":" . $tag]['ref'])) {
# Work out the RS resource field ref and title for the tag, set the listed status of the tag.
if (isset($resourcefields[$tag]['ref'])) {
$RS_field_ref = $resourcefields[$tag]['ref'];
$resourcefields[$tag]['listed'] = true;
} elseif (isset($resourcefields[$group . ":" . $tag]['ref'])) {
$RS_field_ref = $resourcefields[$group . ":" . $tag]['ref'];
$resourcefields[$group . ":" . $tag]['listed'] = true;
}
$RS_field_name = ps_query("select title from resource_type_field where ref = ?", array("i",$RS_field_ref), "schema");
$RS_field_name = lang_or_i18n_get_translated($RS_field_name[0]['title'], "fieldtitle-");
# Display the RS resource field ref, title, exiftool group, tag and properties.
echo "<td>" . escape(str_replace(array('%ref%', '%name%'), array($RS_field_ref, $RS_field_name), $lang['field_ref_and_name'])) . "</td><td>" . escape($group) . "</td><td>" . escape("{$tag} {$tagprops}") . "</td>";
} else {
# Not an RS resource field; display exiftool group, tag and properties.
echo "<td></td><td>" . escape($group) . "</td><td>" . escape("{$tag} {$tagprops}") . "</td>";
}
# Look for the tag in the simulated download.
$exists_in_simulated = false;
foreach ($results_simulated as $simulated_result) {
if ($simulated_result["group"] == $group && $simulated_result["tag"] == $tag) {
$exists_in_simulated = true;
break;
}
}
if ($exists_in_simulated) {
# The tag exists also in the simulated download.
$newvalue = $simulated_result['value'];
# Compare the values from the original file and the simulated download.
if ($value != $newvalue && $tag != "filesize" && $tag != "filemodifydate") {
echo "<td>- " . escape($value) . "</td><td>+ " . escape($newvalue) . "</td>";
} else {
if ($tag == "filemodifydate") {
echo "<td>" . escape($value) . "</td><td>+ " . escape($lang["date_of_download"]) . "</td>";
} else {
echo "<td>" . escape($value) . "</td><td></td>";
}
}
} else {
# The tag is removed in the simulated download.
echo "<td>- " . escape($value) . "</td><td>+</td>";
}
hook('more_metadata_report_cells');
echo "</tr>";
}
}
$fits = get_utility_path('fits');
if (false !== $fits) {
// $image should contain the original file
$fits_xml = runFitsForFile($image);
// Get a list of all the fields that have a FITS field set
$allfields = get_resource_type_fields($resource_type);
$rs_fields_to_read_for = array_filter($allfields, function ($field) {
return trim((string)$field["fits_field"]) != "";
});
?>
<tr>
<td colspan="5"><?php echo escape($lang['metadata-report-fits_section']) ; ?></td>
</tr>
<?php
foreach ($rs_fields_to_read_for as $rs_field) {
$fits_fields = explode(',', (string)$rs_field['fits_field']);
?>
<tr>
<?php
foreach ($fits_fields as $fits_field) {
if ($fits_xml !== false) {
$fits_field_value = getFitsMetadataFieldValue($fits_xml, $fits_field);
} else {
$fits_field_value = $lang["notavailableshort"];
}
if ('' == $fits_field_value) {
continue;
}
?>
<td>
<?php echo escape(str_replace(
array('%ref%', '%name%'),
array($rs_field['ref'], lang_or_i18n_get_translated($rs_field['title'], 'fieldtitle-')),
$lang['field_ref_and_name']
));
?>
</td>
<td>fits</td>
<td><?php echo escape($fits_field); ?></td>
<td><?php echo escape($fits_field_value); ?></td>
<td></td>
</tr>
<?php
}
}
}
# Add tags which don't exist in the original file?
if ($exiftool_write && $file_writability) {
echo "<tr><td colspan=\"5\">" . escape($lang['new_tags']) . "</td></tr>";
echo "<tr><td width=\"150\">" . escape($applicationname) . "</td><td width=\"50\">" . escape($lang['group']) . "</td><td width=\"150\">" . escape($lang['exiftooltag']) . "</td><td>" . escape($lang['embeddedvalue']) . "</td><td>" . escape($write_status) . "</td></tr>";
# Process the report of the original file.
foreach ($results_simulated as $result_simulated) {
$group = $result_simulated["group"];
$tag = $result_simulated["tag"];
$value = $result_simulated["value"];
$tagprops = $result_simulated["tagprops"];
# Check if the tag hasn't been displayed already.
if ((isset($resourcefields[$tag]['listed']) && !($resourcefields[$tag]['listed'])) || (isset($resourcefields[$group . ":" . $tag]['listed']) && !($resourcefields[$group . ":" . $tag]['listed']))) {
# Work out the RS resource field ref and title for the tag.
echo "<tr>";
if (isset($resourcefields[$tag]['ref'])) {
$RS_field_ref = $resourcefields[$tag]['ref'];
} elseif (isset($resourcefields[$group . ":" . $tag]['ref'])) {
$RS_field_ref = $resourcefields[$group . ":" . $tag]['ref'];
}
$RS_field_name = ps_query("select title from resource_type_field where ref = ?", array("i",$RS_field_ref), "schema");
$RS_field_name = lang_or_i18n_get_translated($RS_field_name[0]['title'], "fieldtitle-");
# Display the RS resource field ref, title, exiftool group, tag and properties.
echo "<td>" . escape(str_replace(array('%ref%', '%name%'), array($RS_field_ref, $RS_field_name), $lang['field_ref_and_name'])) . "</td><td>" . escape($group) . "</td><td>" . escape("{$tag} {$tagprops}") . "</td>";
# Display the value.
if ($tag != "filesize" && $tag != "filemodifydate") {
echo "<td></td><td>+ " . escape($value) . "</td>";
}
echo "</tr>";
}
}
}
echo "</table>";
}

27
pages/ajax/relate_resources.php Executable file
View File

@@ -0,0 +1,27 @@
<?php
include_once '../../include/boot.php';
include_once '../../include/authenticate.php';
$ref = getval('ref', 0, true);
$related = getval('related', 0, true);
$add = getval('action', 'add') == "add";
$collection = getval('collection', 0, true);
$success = false;
if ($collection > 0) {
if (allow_multi_edit($collection)) {
$success = relate_all_collection($collection, false);
}
} else {
if (get_edit_access($ref) && get_edit_access($related)) {
$success = update_related_resource($ref, $related, $add);
}
}
if ($success) {
exit("SUCCESS");
} else {
http_response_code(403);
exit(escape($lang["error-permissiondenied"]));
}

View File

@@ -0,0 +1,5 @@
<?php
include_once '../../include/boot.php';
include_once '../../include/authenticate.php';
include_once '../../include/header_links.php';

View File

@@ -0,0 +1,33 @@
<?php
include_once '../../include/boot.php';
include_once '../../include/authenticate.php';
if ($simple_search_reset_after_search) {
$restypes = "";
$search = "";
$quicksearch = "";
} else {
# Pull values from cookies if necessary, for non-search pages where this info hasn't been submitted
if (!isset($restypes)) {
$restypes = isset($_COOKIE['restypes']) ? $_COOKIE['restypes'] : "";
}
if (!isset($search) || strpos($search, '!') !== false) {
$quicksearch = (isset($_COOKIE['search']) ? $_COOKIE['search'] : '') ;
} else {
$quicksearch = $search;
}
}
$initial_tags = explode(',', $quicksearch);
include_once '../../include/searchbar.php';
?>
<script type="text/javascript">
jQuery(document).ready(function() {
if (typeof AdditionalJs == 'function') {
AdditionalJs();
}
});
</script>

View File

@@ -0,0 +1,39 @@
<?php
include __DIR__ . '/../../include/boot.php';
include __DIR__ . '/../../include/authenticate.php';
$resource = getval('resource', '');
$ref = getval('ref', '');
$type = getval('type', '');
$resource_data = get_resource_data($resource);
// User should have edit access to this resource!
if (!get_edit_access($resource, $resource_data['archive'], $resource_data)) {
exit('Permission denied.');
}
if ($type == 'user') {
// Delete the user record from the database
ps_query(
"
DELETE FROM resource_custom_access
WHERE resource = ?
AND user = ?
",
array("i",$resource,"i",$ref)
);
} elseif ($type == 'usergroup') {
// Delete the user record from the database
ps_query(
"
DELETE FROM resource_custom_access
WHERE resource = ?
AND usergroup = ?;
",
array("i",$resource,"i",$ref)
);
} else {
exit('No type');
}

56
pages/ajax/search.php Normal file
View File

@@ -0,0 +1,56 @@
<?php
include_once '../../include/boot.php';
include_once '../../include/authenticate.php';
$ajax = filter_var(getval('ajax', false), FILTER_VALIDATE_BOOLEAN);
if (!$ajax) {
header('HTTP/1.1 400 Bad Request');
die('AJAX only accepted!');
}
/* Variables that should be available for any cases below, otherwise
they should be put in that use case only */
$return = array();
$search_string = getval('search_string', '');
// Generate search tags based on a search string
if (filter_var(getval('generate_tags', false), FILTER_VALIDATE_BOOLEAN)) {
/*
Space is not part of config separators so we have to make sure we have it for this case
Double space is used due to removal of quoted search strings which can lead to double spaces left
in the search string
*/
$tag_delimiters = array_merge(array(' ', ' '), $config_separators);
// Quoted search detected, so anything within double quotes should allow for white spaces
$double_quotes_pos = strpos($search_string, '"');
if (false !== $double_quotes_pos) {
$double_quotes_end_pos = strpos(substr($search_string, $double_quotes_pos + 1), '"');
$quoted_text = substr($search_string, $double_quotes_pos + 1, $double_quotes_end_pos);
$search_string = str_replace("\"{$quoted_text}\"", '', $search_string);
$return[] = $quoted_text;
}
$is_special_search = (false !== strpos($search_string, ':') ? true : false);
if ($is_special_search || false !== strpos($search_string, ',')) {
foreach (explode(',', $search_string) as $comma_split_keywords) {
// Special search found, add that to return
if (false !== strpos($comma_split_keywords, ':')) {
$return[] = cleanse_string($comma_split_keywords, true);
continue;
}
$return = array_merge($return, split_keywords($comma_split_keywords));
}
}
if (!$is_special_search) {
$return = array_merge($return, split_keywords($search_string));
}
echo json_encode($return);
exit();
}

View File

@@ -0,0 +1,18 @@
<?php
# AJAX ratings save
include "../../include/boot.php";
include "../../include/authenticate.php";
if (getval("action", "") == "showcollection") {
show_hide_collection(getval("collection", "", true), true, $userref);
exit("UNHIDDEN");
}
if (getval("action", "") == "hidecollection") {
show_hide_collection(getval("collection", "", true), false, $userref);
exit("HIDDEN");
}
exit("no action specified");

174
pages/ajax/tiles.php Normal file
View File

@@ -0,0 +1,174 @@
<?php
include_once __DIR__ . "/../../include/boot.php";
// Support externally shared images on view page or search page (map view)
$k = getval("k", "");
$resource = getval("resource", "", true, "is_positive_int_loose");
$collection = getval("collection", "", true, "is_positive_int_loose");
if (($k == "") || (!check_access_key($resource, $k) && !check_access_key_collection($collection, $k))) {
include __DIR__ . "/../../include/authenticate.php";
}
$provider = trim(getval("provider", ""));
$variant = trim(getval("variant", ""));
$provider = safe_file_name($provider);
$variant = safe_file_name($variant);
# Originally adapted from
# http://wiki.openstreetmap.org/wiki/ProxySimplePHP
# The main benefit is for SSL sites which don't want to be making HTTP calls which result in content warnings
// Check that requested tile is valid
$validatecode = $provider . ($variant != "" ? ("." . $variant) : "");
$valid_variants = [];
if (isset($geo_leaflet_sources)) {
foreach ($geo_leaflet_sources as $geo_leaflet_source) {
$code = $geo_leaflet_source["code"] ?? "";
$valid_variants[] = $code;
if (isset($geo_leaflet_source["variants"])) {
foreach ($geo_leaflet_source["variants"] as $variantid => $variantnames) {
$valid_variants[] = $code . "." . $variantid;
}
}
}
}
if (
!$geo_tile_caching
|| !in_array($validatecode, $valid_variants)
) {
http_response_code(403);
exit(escape($lang["error-permissiondenied"]));
}
if (isset($geo_tile_cache_directory) && $geo_tile_cache_directory != "") {
$tilecache = $geo_tile_cache_directory;
} else {
$tilecache = get_temp_dir() . "/tiles";
}
if ($provider != "") {
$tilecache .= "/" . $provider;
}
if ($variant != "") {
$tilecache .= "/" . $variant;
}
if (!is_dir($tilecache)) {
if (file_exists($tilecache)) {
unlink($tilecache);
}
mkdir($tilecache, 0777, true);
}
$ttl = 86400; //cache timeout in seconds
$x = intval(getval('x', 0, true));
$y = intval(getval('y', 0, true));
$z = intval(getval('z', 0, true));
$file = $tilecache . "/{$z}_{$x}_$y.png";
$gettile = true;
$allowed_types = ['image/png', 'image/jpeg'];
while (
(
!is_file($file)
|| (filemtime($file) < time() - $geo_tile_cache_lifetime)
|| array_intersect($allowed_types, get_mime_type($file)) === []
)
&& $gettile
) {
if (isset($geo_leaflet_sources) && count($geo_leaflet_sources) > 0) {
$geo_tile_urls = [];
foreach ($geo_leaflet_sources as $geo_leaflet_source) {
// If no provider is specified, default to the first one defined
if ($provider == "") {
$provider = $geo_leaflet_source["code"];
}
$geo_tile_urls[$geo_leaflet_source["code"]] = [];
$geo_tile_urls[$geo_leaflet_source["code"]]["url"] = $geo_leaflet_source["url"];
$geo_tile_urls[$geo_leaflet_source["code"]]["subdomains"] = isset($geo_leaflet_source["subdomains"]) ? $geo_leaflet_source["subdomains"] : "dd";
$geo_file_extension = isset($geo_leaflet_source["extension"]) ? $geo_leaflet_source["extension"] : "";
$geo_tile_urls[$geo_leaflet_source["code"]] ["extension"] = $geo_file_extension;
foreach ($geo_leaflet_source["variants"] as $mapvariant => $varopts) {
if (isset($varopts["url"])) {
$varcode = $geo_leaflet_source["code"] . "_" . mb_strtolower($mapvariant);
$geo_tile_urls[$varcode]["url"] = $varopts["url"];
$geo_tile_urls[$varcode]["subdomains"] = isset($geo_leaflet_source["subdomains"]) ? $geo_leaflet_source["subdomains"] : "#";
$geo_tile_urls[$varcode]["extension"] = $geo_file_extension;
}
}
}
if ($provider != "" && isset($geo_tile_urls[$provider])) {
$url = $geo_tile_urls[$provider]["url"];
$subdomains = isset($geo_tile_urls[$provider]["subdomains"]) ? $geo_tile_urls[$provider]["subdomains"] : "#";
$extension = $geo_tile_urls[$provider]["extension"];
if ($variant != "" && isset($geo_tile_urls[$provider . "_" . mb_strtolower($variant)])) {
$url = $geo_tile_urls[$provider . "_" . mb_strtolower($variant)]["url"];
$subdomains = $geo_tile_urls[$provider . "_" . mb_strtolower($variant)]["subdomains"];
}
while (strlen($subdomains) > 0) {
// Get a random subdomain
$subidx = substr($subdomains, 0, 1);
//$url = $subdomains[$subidx] . "." . $url;
// Replace placeholders in URL
$find = array("{x}","{y}","{z}","{ext}");
$replace = array($x,$y,$z,$extension);
if ($subidx != "#") {
$find[] = "{s}";
$replace[] = $subidx;
}
$url = str_replace($find, $replace, $url);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $geo_tile_user_agent);
curl_setopt($ch, CURLOPT_REFERER, $baseurl);
$cresponse = curl_exec($ch);
$cerror = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$headersize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($cresponse, 0, $headersize);
$body = substr($cresponse, $headersize);
curl_close($ch);
if ($cerror == 200) {
debug("Successfully retrieved tile from " . $url);
file_put_contents($file, $body);
$gettile = false;
$gettile = false;
} else {
debug("failed to retrieve tile from " . $url . ". Response: " . $cresponse);
}
$gettile = false;
// Remove this subdomain server from the array
$subdomains = substr($subdomains, 1);
}
}
} else {
debug('$geo_leaflet_sources is not configured');
$gettile = false;
}
}
if (!is_file($file) || array_intersect($allowed_types, get_mime_type($file)) === []) {
// No tiles available at requested resolution
http_response_code(404);
exit($lang["error-geotile-server-error"]);
}
$exp_gmt = gmdate("D, d M Y H:i:s", time() + $ttl * 60) . " GMT";
$mod_gmt = gmdate("D, d M Y H:i:s", filemtime($file)) . " GMT";
header("Expires: " . $exp_gmt);
header("Last-Modified: " . $mod_gmt);
header("Cache-Control: public, max-age=" . $ttl * 60);
header('Content-Type: image/png');
readfile($file);
exit();

View File

@@ -0,0 +1,19 @@
<?php
include_once '../../include/boot.php';
include_once '../../include/authenticate.php';
$collection = getval('collection', 0, true);
$success = false;
if ($collection > 0) {
$success = unrelate_all_collection($collection, true);
}
if ($success) {
exit("SUCCESS");
} else {
http_response_code(403);
exit(escape($lang["error-permissiondenied"]));
}

View File

@@ -0,0 +1,18 @@
<?php
include "../../include/boot.php";
include "../../include/authenticate.php";
$order_by = getval("order_by", '');
$sort = getval("sort", "DESC");
$search = getval("search", "");
$restypes = getval('restypes', '');
$archive = getval('archive', '');
$daylimit = getval('daylimit', '');
$offset = getval('offset', '');
$collection = getval('collection', '');
$resources_count = getval('resources_count', '');
$collection_data = get_collection($collection);
render_actions($collection_data, true, false, $collection);

View File

@@ -0,0 +1,13 @@
<?php
// Command line only script to process smart collections when $smart_collections_async is enabled.
include __DIR__ . "/../../include/boot.php";
command_line_only();
if (empty($_SERVER['argv'][1])) {
exit();
}
$smartsearch_ref = (int) $_SERVER['argv'][1];
update_smart_collection($smartsearch_ref);

78
pages/ajax/user_action.php Executable file
View File

@@ -0,0 +1,78 @@
<?php
include_once '../../include/boot.php';
include_once '../../include/authenticate.php';
// Generic endpoint that can be used for ajax calls
$action = getval('action', '');
$return = array();
$return['status'] = 400; // set to default
switch ($action) {
case 'submitpending':
// prevent search from returning all contributed resources (archive filter will not be ignored in this case)
$search_all_workflow_states = false;
$pending_items = do_search("!contributions" . $userref, "", "", -2, -1, "desc", false, 0, false, false, "", false, false, true);
$collection_add = getval('collection_add', 0, true);
$collection_resources = is_numeric($collection_add) ? get_collection_resources($collection_add) : array();
$submit = array();
$submitstates = array();
for ($r = 0; $r < count($pending_items); $r++) {
if ($collection_add == 0 || in_array($pending_items[$r]["ref"], $collection_resources)) {
// Add this resource to the array of resources to submit
$submit[] = $pending_items[$r]["ref"];
$submitstates[] = -2; // Needed so that from state is logged correctly by update_archive_status
}
}
if (count($submit) > 0) {
// Submit all the resources
update_archive_status($submit, -1, $submitstates, $collection_add);
}
$return['status'] = 200;
break;
case 'updatelock':
$resource = getval("ref", 0, true);
$lockaction = getval("lock", '') == "true";
$resource_data = get_resource_data($resource);
if (((string)(int)$resource != (string)$resource) || !$resource_data) {
$return['message'] = $lang["error_invalid_input"] ;
break;
}
$edit_access = get_edit_access($resource, $resource_data["archive"], $resource_data);
$lockuser = $resource_data["lock_user"];
if ($lockaction && $lockuser > 0 && $lockuser != $userref) {
// Already locked
$return['status'] = 403;
$return['message'] = get_resource_lock_message($lockuser);
} elseif (
checkperm("a")
||
$lockuser == $userref
||
($edit_access && $lockuser == 0 && !checkperm("nolock"))
) {
$success = update_resource_lock($resource, $lockaction, $userref, true);
if ($success) {
$return['status'] = 200;
}
} else {
$return['status'] = 403;
$return['message'] = $lang["error-permissiondenied"];
}
break;
default:
$return['message'] = $lang["error_generic"] ;
break;
}
http_response_code($return['status']);
header('Content-type: application/json');
echo json_encode($return);
exit();

View File

@@ -0,0 +1,8 @@
<?php
# AJAX ratings save
include "../../include/boot.php";
include "../../include/authenticate.php";
user_rating_save(getval("userref", "", true), getval("ref", "", true), getval("rating", ""));

View File

@@ -0,0 +1,21 @@
<?php
# Feeder page for AJAX user/group search for the user selection include file
include "../../include/boot.php";
include "../../include/authenticate.php";
$user = getval("userref", "");
$userstring = getval("userstring", "");
$userlistname = getval("userlistname", "");
$delete = getval("delete", "");
if ($delete != "") {
$userlistref = getval("userlistref", "", true);
ps_query("delete from user_userlist where ref= ?", ['i', $userlistref]);
}
if ($userstring != "" && $userstring != $lang['typeauserlistname'] && $userlistname != "") {
ps_query("delete from user_userlist where user= ? and userlist_name= ?", ['i', $user, 's', $userlistname]);
ps_query("insert into user_userlist (user,userlist_name,userlist_string) values (?, ?, ?)", ['i', $user, 's', $userlistname, 's', $userstring]);
}

View File

@@ -0,0 +1,26 @@
<?php
# Update the user select element
include "../../include/boot.php";
include "../../include/authenticate.php";
$userstring = getval("userstring", "");
?>
<?php $user_userlists = ps_query("select " . columns_in('user_userlist') . " from user_userlist where user= ?", ['i', $userref]);?>
<option value=""><?php echo escape($lang['loadasaveduserlist']); ?></option>
<?php
if (count($user_userlists) > 0) {
foreach ($user_userlists as $user_userlist) { ?>
<option
id="<?php echo $user_userlist['ref']; ?>"
value="<?php echo $user_userlist['userlist_string']; ?>"
<?php if ($userstring == $user_userlist['userlist_string']) {
?>selected<?php
} ?>
><?php echo $user_userlist['userlist_name']; ?></option>
<?php }
}

View File

@@ -0,0 +1,19 @@
<?php
# Feeder page for AJAX user/group search for the user selection include file
include "../../include/boot.php";
include "../../include/authenticate.php";
$userstring = getval("userstring", "");
$userstring = resolve_userlist_groups($userstring);
$userstring = array_unique(trim_array(explode(",", $userstring)));
sort($userstring);
$userstring = implode(", ", $userstring);
$groups = resolve_userlist_groups_smart($userstring);
if ($groups != "") {
$userstring .= "," . $groups;
}
echo $userstring;

257
pages/alternative_file.php Executable file
View File

@@ -0,0 +1,257 @@
<?php
include "../include/boot.php";
include "../include/authenticate.php";
include_once "../include/image_processing.php";
$ref = getval("ref", "", true);
$search = getval("search", "");
$offset = getval("offset", 0, true);
$order_by = getval("order_by", "");
$archive = getval("archive", "", true);
$restypes = getval("restypes", "");
if (strpos($search, "!") !== false) {
$restypes = "";
}
$modal = (getval("modal", "") == "true");
$context = getval("context", "");
$default_sort_direction = "DESC";
if (substr($order_by, 0, 5) == "field") {
$default_sort_direction = "ASC";
}
$sort = getval("sort", $default_sort_direction);
$resource = getval("resource", "", true);
# Fetch resource data.
$resourcedata = get_resource_data($resource);
if ($resourcedata === false) {
http_response_code(400);
exit(escape($lang["resourcenotfound"]));
}
if ($resourcedata["lock_user"] > 0 && $resourcedata["lock_user"] != $userref) {
$error = get_resource_lock_message($resourcedata["lock_user"]);
http_response_code(403);
exit($error);
}
# Load the configuration for the selected resource type. Allows for alternative notification addresses, etc.
resource_type_config_override($resourcedata["resource_type"]);
# Not allowed to edit this resource?
if ((!get_edit_access($resource, $resourcedata["archive"], $resourcedata) || checkperm('A')) && $resource > 0) {
exit("Permission denied.");
}
# Fetch alternative file data
$file = get_alternative_file($resource, $ref);
if ($file === false) {
exit("Alternative file not found.");
}
# Tweak images
if (getval("tweak", "") != "" && enforcePostRequest(false)) {
$tweak = getval("tweak", "");
switch ($tweak) {
case "rotateclock":
$wait = tweak_preview_images($resource, 270, 0, "jpg", $ref);
break;
case "rotateanti":
$wait = tweak_preview_images($resource, 90, 0, "jpg", $ref);
break;
case "restore":
if ($enable_thumbnail_creation_on_upload) {
$wait = create_previews($resource, false, "jpg", false, false, $ref);
}
break;
}
}
$url_params = [
"ref" => $resource,
"search" => $search,
"offset" => $offset,
"order_by" => $order_by,
"sort" => $sort,
"archive" => $archive,
];
if ($modal) {
$url_params["modal"] = "true";
if ($context == "Modal") {
$url_params["context"] = $context;
}
}
$altname = getval("name", "");
if (
$altname !== ""
&& getval("tweak", "") == ""
&& enforcePostRequest(false)
) {
// Do not do this during a tweak operation!
$alt_data = [
"name" => (string) $altname,
"description" => (string) getval("description", ""),
"alt_type" => (string) getval("alt_type", ""),
];
save_alternative_file($resource, $ref, $alt_data);
// Check to see if we need to notify users of this change
if ($notify_on_resource_change_days != 0) {
notify_resource_change($resource);
}
if (getval("tweak", "") != '') {
$url_params["ref"] = $ref;
$url_params = array_merge(["resource" => $resource], $url_params);
redirect(generateURL(
"{$baseurl_short}pages/alternative_file.php",
$url_params
));
} else {
redirect(generateURL("{$baseurl_short}pages/alternative_files.php", $url_params));
}
}
include "../include/header.php";
$backtoalternativefilesurl = generateURL("{$baseurl_short}pages/alternative_files.php", $url_params);
$backtoalternativefileurl = generateURL("{$baseurl_short}pages/alternative_file.php", $url_params);
?>
<div class="BasicsBox">
<p>
<a
onClick="return <?php echo $context != "Modal" ? "CentralSpace" : "Modal"; ?>Load(this,true);"
href="<?php echo $backtoalternativefilesurl?>">
<?php echo LINK_CARET_BACK . escape($lang["backtomanagealternativefiles"]); ?>
</a>
</p>
<h1>
<?php
echo escape($lang["editalternativefile"]);
render_help_link('user/alternative-files');
?>
</h1>
<form
method="post"
class="form"
id="fileform"
onsubmit="return <?php echo $context == 'Modal' ? 'Modal' : 'CentralSpace'; ?>Post(this, true);"
action="<?php echo $backtoalternativefileurl; ?>"
>
<?php
if ($modal) {
?>
<input type="hidden" name="modal" value="true">
<?php
if ($context == "Modal") {
?>
<input type="hidden" name="context" value="Modal">
<?php
}
}
generateFormToken('fileform'); ?>
<input type=hidden name=ref value="<?php echo escape($ref) ?>">
<input type=hidden name=resource value="<?php echo escape($resource) ?>">
<?php //display preview if exists
$previews_exist = false;
if (file_exists(get_resource_path($resource, true, 'thm', true, 'jpg', true, 1, false, '', $ref, true))) {
$previews_exist = true;
$fileurl = get_resource_path($resource, false, 'thm', true, 'jpg', true, 1, false, date('Y-m-d H:i:s'), $ref);
?>
<div class="Question" style="border: 0px;">
<img
alt="<?php echo escape(i18n_get_translated($file['name'] ?? "")); ?>"
id="preview"
align="top"
src="<?php echo $fileurl; ?>"
class="ImageBorder"
style="margin-right:10px;"
/>
<br />
<br />
<div class="clearerleft"></div>
</div>
<?php
}
?>
<div class="Question">
<label><?php echo escape($lang["resourceid"]); ?></label>
<div class="Fixed"><?php echo escape($resource) ?></div>
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="name"><?php echo escape($lang["name"]); ?></label>
<input type=text class="stdwidth" name="name" id="name" value="<?php echo escape($file["name"]) ?>" maxlength="100">
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="name"><?php echo escape($lang["description"]); ?></label>
<input type=text class="stdwidth" name="description" id="description" value="<?php echo escape($file["description"]) ?>" maxlength="200">
<div class="clearerleft"></div>
</div>
<?php
// If the system is configured to support a type selector for alt files, show it
if (isset($alt_types) && count($alt_types) > 1) {
echo "<div class='Question'>\n<label for='alt_type'>" . escape($lang["alternatetype"]) . "</label><select name='alt_type' id='alt_type'>";
foreach ($alt_types as $thealttype) {
if ($thealttype == $file['alt_type']) {
$alt_type_selected = " selected='selected'";
} else {
$alt_type_selected = '';
}
$thealttype = escape($thealttype);
echo "\n <option value='$thealttype' $alt_type_selected >$thealttype</option>";
}
echo "\n</select>\n<div class='clearerleft'> </div>\n</div>";
}
if ($previews_exist) { ?>
<div class="Question" id="question_imagecorrection">
<label>
<?php echo escape($lang["imagecorrection"]); ?>
<br/>
<?php echo escape($lang["previewthumbonly"]); ?>
</label>
<select name="tweak" id="tweak" onChange="form.submit()">
<option value=""><?php echo escape($lang["select"]); ?></option>
<?php
# On some PHP installations, the imagerotate() function is wrong and images are turned incorrectly.
# A local configuration setting allows this to be rectified
if (!$image_rotate_reverse_options) { ?>
<option value="rotateclock"><?php echo escape($lang["rotateclockwise"]); ?></option>
<option value="rotateanti"><?php echo escape($lang["rotateanticlockwise"]); ?></option>
<?php } else { ?>
<option value="rotateanti"><?php echo escape($lang["rotateclockwise"]); ?></option>
<option value="rotateclock"><?php echo escape($lang["rotateanticlockwise"]); ?></option>
<?php } ?>
<option value="restore"><?php echo escape($lang["recreatepreviews"]); ?></option>
</select>
<div class="clearerleft"></div>
</div>
<?php } ?>
<div class="QuestionSubmit">
<input name="save" type="submit" value="<?php echo escape($lang["save"]); ?>" />
</div>
</form>
</div>
<?php
include "../include/footer.php";
?>

335
pages/alternative_files.php Executable file
View File

@@ -0,0 +1,335 @@
<?php
include "../include/boot.php";
include "../include/authenticate.php";
$ref = getval("ref", "", true);
$alt = getval("alternative", "", true);
$search = getval("search", "");
$offset = getval("offset", 0, true);
$order_by = getval("order_by", "");
$archive = getval("archive", "", true);
$restypes = getval("restypes", "");
if (strpos($search, "!") !== false) {
$restypes = "";
}
$modal = (getval("modal", "") == "true");
$default_sort_direction = "DESC";
if (substr($order_by, 0, 5) == "field") {
$default_sort_direction = "ASC";
}
$sort = getval("sort", $default_sort_direction);
$curpos = getval("curpos", "");
$go = getval("go", "");
$urlparams = array(
'resource' => $ref,
'ref' => $ref,
'search' => $search,
'order_by' => $order_by,
'offset' => $offset,
'restypes' => $restypes,
'archive' => $archive,
'default_sort_direction' => $default_sort_direction,
'sort' => $sort,
'curpos' => $curpos,
"modal" => ($modal ? "true" : ""),
);
# Fetch resource data.
$resource = get_resource_data($ref);
if (!is_array($resource)) {
http_response_code(403);
exit($lang['resourcenotfound']);
}
$editaccess = get_edit_access($ref, $resource["archive"], $resource);
# Not allowed to edit this resource?
if (!($editaccess || checkperm('A')) && $ref > 0) {
exit("Permission denied.");
}
if ($resource["lock_user"] > 0 && $resource["lock_user"] != $userref) {
$error = get_resource_lock_message($resource["lock_user"]);
http_response_code(403);
exit($error);
}
# Handle deleting a file
if (getval("filedelete", "") != "" && enforcePostRequest(getval("ajax", false))) {
$filedelete = explode(',', getval('filedelete', ''));
foreach ($filedelete as $filedel) {
if (is_numeric($filedel) && $filedel != 'on') {// safety checks
delete_alternative_file($ref, $filedel);
}
}
}
$alt_order_by = "";
$alt_sort = "";
if ($alt_types_organize) {
$alt_order_by = "alt_type";
$alt_sort = "asc";
}
$files = get_alternative_files($ref, $alt_order_by, $alt_sort);
include "../include/header.php";
?>
<script type="text/javascript">
function clickDelete() {
var files = [];
var errors = 0;
jQuery('#altlistitems input:checked').not("#toggleall").each(function() {
files.push(this.value);
});
files.forEach((file) => {
postdata = {
'resource' : '<?php echo $ref;?>',
'ref' : file,
}
api(
'delete_alternative_file',
postdata,
function(response) {
if (response == true) {
document.getElementById('altlistrow' + file).remove();
} else {
error++;
}
},
<?php echo generate_csrf_js_object('delete_alternative_file'); ?>
);
});
if (errors > 0) {
styledalert('<?php echo escape($lang['error']); ?>','<?php echo escape($lang['altfilesdeletefail']); ?>');
return false;
} else {
return true;
}
}
function toggleAll() {
jQuery("#toggleall").click(function() {
var checkBoxes = jQuery("input[name=altcheckbox\\[\\]]");
checkBoxes.prop("checked", jQuery("#toggleall").prop("checked"));
});
}
</script>
<div class="BasicsBox">
<?php
if (getval("context", false) == 'Modal') {
$previous_page_modal = true;
} else {
$previous_page_modal = false;
}
if (!$modal) {
?>
<p>
<a onClick="return CentralSpaceLoad(this,true);" href="<?php echo generateURL($baseurl . "/pages/edit.php", $urlparams); ?>">
<?php echo LINK_CARET_BACK . escape($lang["backtoeditmetadata"]); ?>
</a>
<br>
<a onClick="return CentralSpaceLoad(this,true);" href="<?php echo generateURL($baseurl . "/pages/view.php", $urlparams); ?>">
<?php echo LINK_CARET_BACK . escape($lang["backtoresourceview"]); ?>
</a>
</p>
<?php
} elseif ($previous_page_modal) {
$urlparams["context"] = 'Modal';
?>
<p>
<a onClick="return ModalLoad(this,true);" href="<?php echo generateURL($baseurl . "/pages/edit.php", $urlparams); ?>">
<?php echo LINK_CARET_BACK . escape($lang["backtoeditmetadata"]); ?>
</a>
<br>
<a onClick="return ModalLoad(this,true);" href="<?php echo generateURL($baseurl . "/pages/view.php", $urlparams); ?>">
<?php echo LINK_CARET_BACK . escape($lang["backtoresourceview"]); ?>
</a>
</p>
<?php
}
?>
<div class="RecordHeader">
<div class="BackToResultsContainer">
<div class="backtoresults">
<?php if ($modal) { ?>
<a class="maxLink fa fa-expand" href="<?php echo generateURL($baseurl_short . "pages/alternative_files.php", $urlparams, array("modal" => "")); ?>" onclick="return CentralSpaceLoad(this);" title="<?php echo escape($lang["maximise"]); ?>"></a>
&nbsp;<a href="#" class="closeLink fa fa-times" onclick="ModalClose();" title="<?php echo escape($lang["close"]); ?>"></a>
<?php } ?>
</div>
</div>
</div>
<?php
if (
$alternative_file_resource_preview
&& file_exists(get_resource_path($resource['ref'], true, 'col', false))
) {
?>
<img alt="<?php echo escape(i18n_get_translated($resource['field' . $view_title_field] ?? "")); ?>" src="<?php echo get_resource_path($resource['ref'], false, 'col', false); ?>"/>
<?php
}
if (isset($resource['field' . $view_title_field])) {
echo "<h2>" . escape(i18n_get_translated($resource['field' . $view_title_field])) . "</h2><br/>";
}
?>
<h1>
<?php
echo escape($lang["managealternativefilestitle"]);
render_help_link('user/alternative-files');
?>
</h1>
<?php if (count($files) > 0) { ?>
<a
href="#"
id="deletechecked"
onclick="if (confirm('<?php echo escape($lang['confirm-deletion']); ?>')) {clickDelete();} return false;"
>
<?php echo LINK_CARET . escape($lang["action-deletechecked"]); ?>
</a>
<?php } ?>
<form method=post id="fileform" action="<?php echo generateURL($baseurl . "/pages/alternative_files.php", $urlparams); ?>">
<input type=hidden name="filedelete" id="filedelete" value="">
<?php generateFormToken("fileform"); ?>
<div class="Listview" id="altlistitems">
<table class="ListviewStyle">
<!--Title row-->
<tr class="ListviewTitleStyle">
<th>
<?php if (count($files) > 0) { ?>
<input type="checkbox" class="checkbox" onclick="toggleAll();" id="toggleall" />
<?php } ?>
</th>
<th><?php echo escape($lang["name"]); ?></th>
<th><?php echo escape($lang["description"]); ?></th>
<th><?php echo escape($lang["filetype"]); ?></th>
<th><?php echo escape($lang["filesize"]); ?></th>
<th><?php echo escape($lang["date"]); ?></th>
<?php if (count($alt_types) > 1) { ?>
<th><?php echo escape($lang["alternatetype"]); ?></th>
<?php } ?>
<th>
<div class="ListTools"><?php echo escape($lang["tools"]); ?></div>
</th>
</tr>
<?php for ($n = 0; $n < count($files); $n++) { ?>
<!--List Item-->
<tr
<?php echo ($files[$n]["ref"] == $alt) ? "class='Highlight' " : ''; ?>
id='altlistrow<?php echo $files[$n]['ref']; ?>'
>
<td>
<input type="checkbox" class="checkbox" name="altcheckbox[]" value="<?php echo $files[$n]["ref"];?>" />
</td>
<td><?php echo escape($files[$n]["name"])?></td>
<td><?php echo escape($files[$n]["description"])?>&nbsp;</td>
<td><?php echo escape($files[$n]["file_extension"] == "" ? $lang["notuploaded"] : str_replace_formatted_placeholder("%extension", $files[$n]["file_extension"], $lang["cell-fileoftype"])); ?></td>
<td><?php echo formatfilesize($files[$n]["file_size"])?></td>
<td><?php echo nicedate($files[$n]["creation_date"], true)?></td>
<?php if (count($alt_types) > 1) { ?>
<td><?php echo $files[$n]["alt_type"]; ?></td>
<?php } ?>
<td>
<div class="ListTools">
<a
href="#"
onclick="
if (confirm('<?php echo escape($lang['filedeleteconfirm']); ?>')) {
postdata = {
'resource' : '<?php echo $ref;?>',
'ref' : '<?php echo $files[$n]['ref'];?>',
}
api(
'delete_alternative_file',
postdata,
function(response) {
if (response == true) {
document.getElementById('altlistrow<?php echo $files[$n]['ref'];?>').remove();
return true;
} else {
styledalert('<?php echo escape($lang['error']) ?>','<?php echo escape($lang['altfiledeletefail'])?>');
}
},
<?php echo escape(generate_csrf_js_object('delete_alternative_file')); ?>
);
}
return false;"
>
<?php echo LINK_CARET . escape($lang["action-delete"])?>
</a>
&nbsp;
<a
onclick="return <?php echo $modal ? 'Modal' : 'CentralSpace'; ?>Load(this, true);"
href="<?php echo generateURL($baseurl . "/pages/alternative_file.php", $urlparams, array("ref" => $files[$n]["ref"])); ?>"
>
<?php echo LINK_CARET . escape($lang["action-edit"]); ?>
</a>
<?php
if (
$editaccess
&& (
file_exists(get_resource_path($ref, true, '', true, 'jpg', true, 1, false, '', $files[$n]["ref"], true))
|| file_exists(get_resource_path($ref, true, 'hpr', true, 'jpg', true, 1, false, '', $files[$n]["ref"], true))
)
) {
echo "<a href=\"#\" onclick=\"previewform=jQuery('#previewform');jQuery('#upload_pre_alt').val('" . escape($files[$n]["ref"]) . "');return " . ($modal ? "Modal" : "CentralSpace") . "Post(previewform, true);\">" . LINK_CARET . escape($lang["useaspreviewimage"]) . "</a>";
}
?>
</div>
</td>
</tr>
<?php
}
?>
</table>
</div>
<?php if (!resource_is_template($ref)) { ?>
<p>
<a onclick="return CentralSpaceLoad(this, true);" href="<?php echo generateURL($baseurl . "/pages/upload_batch.php", $urlparams, array('alternative' => $ref)); ?>">
<?php echo LINK_CARET . escape($lang["alternativebatchupload"]); ?>
</a>
</p>
<?php } ?>
</form>
<form method=post id="previewform" name="previewform" action="<?php echo generateURL($baseurl . "/pages/upload_preview.php", $urlparams) ; ?>">
<?php generateFormToken("previewform"); ?>
<input type=hidden name="ref", id="upload_ref" value="<?php echo escape($ref); ?>"/>
<input type=hidden name="previewref", id="upload_pre_ref" value="<?php echo escape($ref); ?>"/>
<input type=hidden name="previewalt", id="upload_pre_alt" value=""/>
</form>
</div> <!-- end of basicbox -->
<script type="text/javascript">
jQuery('#altlistitems').tshift(); // make the select all checkbox work
jQuery('#altlistitems input[type=checkbox]').click(function() {
if (jQuery(this).not(':checked').length) { // clear checkall
jQuery("#toggleall").prop("checked", false);
}
});
</script>
<?php
include "../include/footer.php";

224
pages/api_test.php Normal file
View File

@@ -0,0 +1,224 @@
<?php
include "../include/boot.php";
include "../include/authenticate.php";
include_once "../include/image_processing.php";
include_once "../include/api_functions.php";
include_once "../include/api_bindings.php";
include_once "../include/login_functions.php";
include_once "../include/dash_functions.php";
include_once "../include/ajax_functions.php";
include "../include/header.php";
if (!$enable_remote_apis) {
exit("API not enabled.");
}
if (!checkperm("a")) {
exit("Access denied");
}
$api_function = getval("api_function", "");
$api_functions = array_filter(get_defined_functions()['user'], function ($e) {
return strpos($e, 'api_') === 0;
});
if ($api_function != "") {
$index = array_search('api_' . $api_function, $api_functions);
if ($index !== false) {
$fct = new ReflectionFunction($api_functions[$index]);
$paramcount = $fct->getNumberOfParameters();
$rparamcount = $fct->getNumberOfRequiredParameters();
$fct_params = $fct->getParameters();
}
}
$output = "";
if (getval("submitting", "") != "" && $api_function != "") {
$output = "";
$query = "function=" . $api_function;
foreach ($fct_params as $fparam) {
$param_name = $fparam->getName();
$param_val = trim(getval($param_name, ""));
if ($fparam->isOptional() && $param_val == "") {
continue;
}
$query .= "&{$param_name}=" . urlencode($param_val);
}
$output .= "Query: " . $query . "\n\n";
$output .= "Response:\n";
$output .= execute_api_call($query, true);
}
?>
<div class="BasicsBox">
<h1><?php echo escape($lang['api-test-tool']); ?></h1>
<?php
renderBreadcrumbs([
['title' => $lang["systemsetup"], 'href' => $baseurl_short . "pages/admin/admin_home.php", 'menu' => true],
['title' => $lang['api-test-tool']]
]);
?>
<p>
<?php
echo strip_tags_and_attributes($lang["api-help"]);
render_help_link("api/");
?>
</p>
<form id="api-form" method="post" action="<?php echo $baseurl_short?>pages/api_test.php" onSubmit="return CentralSpacePost(this);">
<?php generateFormToken("api-form"); ?>
<div class="Question">
<label><?php echo escape($lang["api-function"]); ?></label>
<select class="stdwidth" name="api_function" onChange="CentralSpacePost(document.getElementById('api-form'));">
<option value=""><?php echo escape($lang["select"]); ?></option>
<?php
# Allow selection from built in functions
asort($api_functions);
foreach ($api_functions as $function) {
?>
<option <?php echo ($function == "api_" . $api_function) ? " selected" : ''; ?>>
<?php echo substr($function, 4); ?>
</option>
<?php
}
?>
</select>
<?php if ($api_function != "") { ?>
&nbsp;&nbsp;
<a target="_blank" href="https://www.resourcespace.com/knowledge-base/api/<?php echo escape($api_function) ?>">
<?php echo escape($lang["api-view-documentation"]); ?>
</a>
<?php } ?>
</div>
<?php
if ($api_function != "") {
foreach ($fct_params as $fparam) {
$param_name = $fparam->getName();
if ($fparam->isOptional()) {
$required = '';
$required_attr = '';
$send_param = getval("send_{$param_name}", '') === 'yes';
$send_param_input = sprintf(
'<input type="checkbox" name="send_%s" value="yes" %s onchange="ToggleSendParam(this);">',
$param_name,
($send_param ? 'checked' : '')
);
$disabled_attr = ($send_param ? '' : 'disabled');
} else {
$required = ' *';
$required_attr = 'required';
$send_param_input = '';
$disabled_attr = '';
}
?>
<div class="Question">
<label><?php echo $send_param_input . $param_name . $required; ?></label>
<input
type="text"
name="<?php echo $param_name; ?>"
class="stdwidth"
value="<?php echo escape(getval($param_name, "")); ?>"
<?php echo "{$required_attr} {$disabled_attr}"; ?>
>
</div>
<?php
}
}
?>
<div class="QuestionSubmit">
<input type="hidden" name="submitting" value="" id="submitting" />
<input type="submit" name="submit" value="<?php echo escape($lang["call-function"]) ?>" onclick="document.getElementById('submitting').value='true';" />
</div>
</form>
<?php if ($output != "") {
//rebuild params for output to include encoding if needed
$original_query = $query;
$query = "function=" . $api_function;
foreach ($fct_params as $fparam) {
$param_name = $fparam->getName();
$param_val = trim(getval($param_name, ""));
if ($fparam->isOptional() && $param_val == "") {
continue;
}
if (strpos(urlencode($param_val), '%') === false) {
$query .= '&' . $param_name . '=' . $param_val;
} else {
$query .= '&' . $param_name . '=" . urlencode("' . addslashes($param_val) . '") . "';
}
}
?>
<pre class="codeoutput"><?php echo escape($output); ?></pre>
<br />
<br />
<h2><?php echo escape($lang["api-php-code"]); ?></h2>
<p><?php echo escape($lang["api-php-help"]); ?></p>
<pre class="codeexample">
&lt;?php
<span class="codecomment">// Set the private API key for the user (from the user account page) and the user we're accessing the system as.</span>
$private_key = "<?php echo get_api_key($userref) ?>";
$user = <?php echo strpos(urlencode($username), '%') === false ? '"' . $username . '"' : 'urlencode("' . $username . '")'; ?>;
<span class="codecomment">// Formulate the query</span>
$query = "user=" . $user . "&amp;<?php echo substr($query, -4) != ' . "' ? escape($query) . '"' : substr(escape($query), 0, -9); ?>;
<span class="codecomment">// Sign the query using the private key</span>
$sign = hash("sha256", $private_key . $query);
<span class="codecomment">// Make the request and output the JSON results.</span>
$results = json_decode(file_get_contents("<?php echo escape($baseurl) ?>/api/?" . $query . "&sign=" . $sign));
print_r($results);</pre>
<h2><?php echo escape($lang["api-curl-example"]); ?></h2>
<p><?php echo escape($lang["api-curl-help"]); ?></p>
<pre class="codeexample">
private_key="<?php echo get_api_key($userref) ?>"; user=<?php echo escape(escapeshellarg($username)); ?>; query=<?php echo escape(escapeshellarg("user=" . $username . "&" . $original_query)); ?>; sign=$(echo -n "${private_key}${query}" | openssl dgst -sha256); curl -X POST "<?php echo $baseurl ?>/api/?${query}&sign=$(echo ${sign} | sed 's/^.* //')"</pre>
<?php } ?>
</div>
<script>
function ToggleSendParam(el) {
console.debug('ToggleSendParam(%o)', el);
var send_param = jQuery(el);
var param_name = send_param.attr('name').replace('send_', '');
var param_input = jQuery('input[name="' + param_name + '"]').not('[required]');
console.debug('param_name = %o', param_name);
console.debug('param_input = %o', param_input);
if (param_input.length == 0) {
console.error('Unable to find an input with name %o', param_name);
return false;
}
if (send_param.is(':checked')) {
param_input.prop('disabled', false);
} else {
param_input.prop('disabled', true);
}
return true;
}
</script>
<?php
include "../include/footer.php";

6
pages/blank.html Normal file
View File

@@ -0,0 +1,6 @@
<html>
<head><title>Blank</title></head>
<body>
<!-- A blank page to use as the default for iframes, to surpress IE errors awhen iframes have a blank source -->
</body>
</html>

53
pages/change_language.php Executable file
View File

@@ -0,0 +1,53 @@
<?php
include "../include/boot.php";
include "../include/authenticate.php";
if (getval("save", "") != "" && enforcePostRequest(false)) {
rs_setcookie("language", getval("language", ""), 1000); # Only used if not global cookies
rs_setcookie("language", getval("language", ""), 1000, $baseurl_short);
rs_setcookie("language", getval("language", ""), 1000, $baseurl_short . "pages/");
log_activity($lang["languageselection"], LOG_CODE_EDITED, getval("language", ""));
redirect(getval("uri", $baseurl_short . "pages/" . ($use_theme_as_home ? 'collections_featured.php' : ($use_recent_as_home ? "search.php?search=!last1000" : "home.php"))));
}
include "../include/header.php";
?>
<div class="BasicsBox">
<h1><?php echo escape($lang["languageselection"]); ?></h1>
<p>
<?php
echo text("introtext");
render_help_link('user/language-options');
?>
</p>
<form method="post" action="<?php echo $baseurl_short?>pages/change_language.php">
<?php generateFormToken("change_language"); ?>
<div class="Question">
<label for="password"><?php echo escape($lang["language"]); ?></label>
<select class="stdwidth" name="language">
<?php reset($languages);
foreach ($languages as $key => $value) { ?>
<option
value="<?php echo escape($key); ?>"
<?php if ($language == $key) { ?>
selected
<?php } ?>
>
<?php echo escape(get_display_language($key, $value)); ?>
</option>
<?php } ?>
</select>
<div class="clearerleft"></div>
</div>
<div class="QuestionSubmit">
<input name="save" type="submit" value="<?php echo escape($lang["save"]); ?>" />
</div>
</form>
</div>
<?php
include "../include/footer.php";
?>

550
pages/check.php Executable file
View File

@@ -0,0 +1,550 @@
<?php
include "../include/boot.php";
include "../include/authenticate.php";
if (!checkperm("a")) {
exit("Access denied.");
}
include "../include/header.php";
?>
<div class="BasicsBox">
<h1><?php echo escape($lang["installationcheck"]);
render_help_link("systemadmin/install_overview");?></h1>
<?php
renderBreadcrumbs([
['title' => $lang["systemsetup"], 'href' => $baseurl_short . "pages/admin/admin_home.php", 'menu' => true],
['title' => $lang["installationcheck"]]
]);
?>
<a onClick="jQuery('#repeat-spinner').addClass('fa-spin');return CentralSpaceLoad(this,true);" href="<?php echo $baseurl_short?>pages/check.php">
<?php echo '<i aria-hidden="true" id="repeat-spinner" class="fa fa-sync-alt"></i>&nbsp;' . escape($lang["repeatinstallationcheck"]); ?>
</a>
<br/><br/>
<table class="InfoTable">
<tr>
<td class="BorderBottom" colspan='3'>
<b><?php echo escape($applicationname); ?></b>
</td>
</tr>
<?php
# Check ResourceSpace Build
$build = '';
if (substr($productversion, 0, 3) == 'SVN') {
$p_version = 'Trunk (SVN)';
//Try to run svn info to determine revision number
$out = array();
exec('svn info ../', $out);
foreach ($out as $outline) {
$matches = array();
if (preg_match('/^Revision: (\d+)/i', $outline, $matches) != 0) {
$build .= "r" . $matches[1];
}
$matches = array();
if (preg_match('/^Relative URL: (.*)/i', $outline, $matches) != 0) {
$build = str_replace("^", "", $matches[1]) . " " . $build;
} elseif (strpos($outline, "URL: ") === 0) {
$urlparts = explode("/", $outline);
$build = end($urlparts) . " ";
}
}
}
?>
<tr>
<td nowrap="true"><?php echo escape(str_replace("?", "ResourceSpace", $lang["softwareversion"])); ?></td>
<td colspan="2"><?php echo escape(substr($productversion, 0, 3) == 'SVN' ? 'SVN ' . $build : $productversion); ?></td>
</tr>
<?php
# Check write access to filestore
$success = is_writable($storagedir);
if ($success === false) {
$result = $lang["status-fail"] . ": " . $storagedir . $lang["nowriteaccesstofilestore"];
} else {
$result = $lang["status-ok"];
}
?>
<tr>
<td><?php echo escape($lang['filestore']); ?></td>
<td><?php echo escape($lang['write_access_to'] . $storagedir); ?></td>
<td>
<b><?php echo escape($result); ?></b>
</td>
</tr>
<?php
# Check write access to homeanim (if transform plugin is installed)
if (in_array("transform", $plugins)) {
$success = is_writable(__DIR__ . "/../" . $homeanim_folder);
if ($success === false) {
$result = $lang["status-fail"] . ": " . $homeanim_folder . $lang["nowriteaccesstohomeanim"];
} else {
$result = $lang["status-ok"];
}
?>
<tr>
<td><?php echo escape($lang['manage_slideshow']); ?></td>
<td><?php echo escape($lang['write_access_to'] . $homeanim_folder); ?></td>
<td>
<b><?php echo escape($result); ?></b>
</td>
</tr>
<?php
}
// Check write access to $facial_recognition_face_recognizer_models_location (if $facial_recognition is enabled)
if ($facial_recognition) {
$success = is_writable($facial_recognition_face_recognizer_models_location);
if ($success === false) {
$result = $lang["status-fail"] . ": " . $facial_recognition_face_recognizer_models_location . $lang["nowriteaccesstohomeanim"];
} else {
$result = $lang["status-ok"];
}
?>
<tr>
<td><?php echo escape($lang["facial-recognition"]); ?></td>
<td><?php echo escape($lang['write_access_to'] . $facial_recognition_face_recognizer_models_location); ?></td>
<td>
<b><?php echo escape($result); ?></b>
</td>
</tr>
<?php
}
# Check flag set if code needs signing
if (get_sysvar("code_sign_required") == "YES") {
$result = $lang["status-fail"];
$result2 = $lang["code_sign_required_warning"];
} else {
$result = $lang["status-ok"];
$result2 = "";
}
?>
<tr>
<td><?php echo escape($lang["code_sign_required"]); ?></td>
<td><?php echo escape($result2); ?></td>
<td>
<b><?php echo escape($result); ?></b>
</td>
</tr>
<?php
# Check filestore folder browseability
$cfb = check_filestore_browseability();
?>
<tr>
<?php
printf(
'<td colspan="2">%1$s (<a href="%2$s" target="_blank">%2$s</a>)</td>',
escape($lang["blockedbrowsingoffilestore"]),
escape($cfb['filestore_url'])
);
?>
<td>
<b><?php echo escape($cfb['index_disabled'] ? $cfb['status'] : "{$cfb['status']}: {$cfb['info']}"); ?></b>
</td>
</tr>
<?php
# Check debug logging configured correctly
if ($debug_log) {
?>
<tr>
<td><?php echo escape($lang['systemconsoledebuglog']); ?></td>
<td><?php escape(printf('%s %s', $lang['write_access_to'], $debug_log_location)); ?></td>
<td>
<b><?php echo escape(is_writable($debug_log_location) ? $lang['status-ok'] : $lang['status-fail']); ?></b>
</td>
</tr>
<?php
}
# Check sql logging configured correctly
if ($mysql_log_transactions) {
?>
<tr>
<td colspan="2"><?php escape(printf('%s %s', $lang['writeaccess_sql_log'], $mysql_log_location)); ?></td>
<td>
<b><?php echo escape(is_writable($mysql_log_location) ? $lang['status-ok'] : $lang['status-fail']); ?></b>
</td>
</tr>
<?php
}
// Check ResourceSpace cron job
$last_cron = ps_value(
"SELECT datediff(now(), `value`) AS `value` FROM sysvars WHERE `name` = 'last_cron'",
[],
$lang['status-never']
);
?>
<tr>
<td><?php echo escape($lang["lastscheduledtaskexection"]); ?></td>
<td><?php echo escape($last_cron); ?></td>
<td>
<?php if ($last_cron > 2 || $last_cron == $lang["status-never"]) { ?>
<b><?php echo escape($lang["status-warning"]); ?></b>
<br/>
<?php
echo strip_tags_and_attributes($lang["executecronphp"]);
} else { ?>
<b><?php echo escape($lang["status-ok"]); ?></b>
<?php } ?>
</td>
</tr>
<tr>
<td class="BorderBottom" colspan='3'>
<b><?php echo escape($lang['web_server']); ?></b>
</td>
</tr>
<tr>
<td><?php echo escape($lang["serverplatform"]); ?></td>
<td colspan="2"><?php echo escape($_SERVER['SERVER_SOFTWARE']); ?></td>
</tr>
<?php
# Check MySQL version
$mysqlversion_num = mysqli_get_server_version($db["read_write"]);
$mysqlversion = mysqli_get_server_info($db["read_write"]);
if ($mysqlversion_num < (5 * 10_000 + 6 * 100)) {
$result = $lang["status-fail"] . ": " . str_replace("?", "5", $lang["shouldbeversion"]);
} else {
$result = $lang["status-ok"];
}
$encoding = mysqli_character_set_name($db["read_write"]);
$encoding_str = str_replace("%encoding", $encoding, $lang["client-encoding"]);
$db_encoding = ps_value("
SELECT default_character_set_name AS `value`
FROM information_schema.SCHEMATA
WHERE `schema_name` = ?;", array("s",$mysql_db), $lang["unknown"]);
$db_encoding_str = str_replace("%encoding", $db_encoding, $lang["db-default-encoding"]);
$encoding_output = "{$mysqlversion}&ensp;&ensp;{$encoding_str} {$db_encoding_str}";
?>
<tr>
<td class="BorderBottom" colspan='3'>
<b><?php echo escape($lang['setup-mysqlserver']); ?></b>
</td>
</tr>
<tr>
<td><?php echo escape(str_replace("?", "MySQL", $lang["softwareversion"])); ?></td>
<td><?php echo strip_tags_and_attributes($encoding_output); ?></td>
<td>
<b><?php echo escape($result); ?></b>
</td>
</tr>
<tr>
<td class="BorderBottom" colspan='3'>
<b><?php echo escape($lang['php']); ?></b>
</td>
</tr>
<?php
# Check PHP version
$phpinifile = php_ini_loaded_file();
if (version_compare(PHP_VERSION, '8.1.0', '<')) {
$result = $lang["status-fail"] . ": " . str_replace("?", "8.1", $lang["shouldbeversion"]);
} else {
$result = $lang["status-ok"];
}
?>
<tr>
<td><?php echo escape(str_replace("?", "PHP", $lang["softwareversion"])); ?></td>
<td><?php echo escape(PHP_VERSION) . '&ensp;&ensp;' . escape(str_replace("%file", $phpinifile, $lang["config_file"])); ?></td>
<td>
<b><?php echo escape($result); ?></b>
</td>
</tr>
<?php # Check if we are running 32 bit PHP. If so, no large file support. ?>
<tr>
<td colspan='2'><?php echo escape($lang['large_file_support_64_bit']); ?></td>
<td>
<b><?php echo escape(php_is_64bit() ? $lang["status-ok"] : $lang['large_file_warning_32_bit']); ?></b>
</td>
</tr>
<?php
# Check ini values for memory_limit, post_max_size, upload_max_filesize
$memory_limit = ini_get("memory_limit");
if (ResolveKB($memory_limit) < (200 * 1024)) {
$result = $lang["status-warning"] . ": " . str_replace("?", "200M", $lang["shouldbeormore"]);
} else {
$result = $lang["status-ok"];
}
?>
<tr>
<td><?php echo escape(str_replace("?", "memory_limit", $lang["phpinivalue"])); ?></td>
<td><?php echo escape($memory_limit); ?></td>
<td>
<b><?php echo escape($result); ?></b>
</td>
</tr>
<?php
$post_max_size = ini_get("post_max_size");
if (ResolveKB($post_max_size) < (100 * 1024)) {
$result = $lang["status-warning"] . ": " . str_replace("?", "100M", $lang["shouldbeormore"]);
} else {
$result = $lang["status-ok"];
}
?>
<tr>
<td><?php echo escape(str_replace("?", "post_max_size", $lang["phpinivalue"])); ?></td>
<td><?php echo escape($post_max_size); ?></td>
<td>
<b><?php echo escape($result); ?></b>
</td>
</tr>
<?php
$upload_max_filesize = ini_get("upload_max_filesize");
if (ResolveKB($upload_max_filesize) < (100 * 1024)) {
$result = $lang["status-warning"] . ": " . str_replace("?", "100M", $lang["shouldbeormore"]);
} else {
$result = $lang["status-ok"];
}
?>
<tr>
<td><?php echo escape(str_replace("?", "upload_max_filesize", $lang["phpinivalue"])); ?></td>
<td><?php echo escape($upload_max_filesize); ?></td>
<td>
<b><?php echo escape($result); ?></b>
</td>
</tr>
<?php
# Check PHP timezone identical to server (MySQL will use the server one) so we need to ensure they are the same
$php_tz = date_default_timezone_get();
$mysql_tz = ps_value(
"SELECT IF(@@session.time_zone = 'SYSTEM', @@system_time_zone, @@session.time_zone) AS `value`",
[],
''
);
$tz_check_fail_msg = str_replace(['%phptz%', '%mysqltz%'], [$php_tz, $mysql_tz], $lang['server_timezone_check_fail']);
$timezone_check = "{$lang['status-warning']}: {$tz_check_fail_msg}";
if (strtoupper($php_tz) == strtoupper($mysql_tz)) {
$timezone_check = $lang['status-ok'];
}
?>
<tr>
<td colspan="2"><?php echo escape($lang['server_timezone_check']); ?></td>
<td>
<b><?php echo escape($timezone_check); ?></b>
</td>
</tr>
<?php
// Check required PHP extensions
$extensions_required = SYSTEM_REQUIRED_PHP_MODULES;
ksort($extensions_required, SORT_STRING);
foreach ($extensions_required as $module => $required_fn) {
?>
<tr>
<td>php-<?php echo escape($module); ?></td>
<td><?php echo escape(phpversion($module)); ?></td>
<td>
<b>
<?php
if (function_exists($required_fn)) {
echo escape($lang['status-ok']);
} else {
echo escape($lang['server_' . $module . '_check_fail'] ?? $lang['status-fail']);
} ?>
</b>
</td>
</tr>
<?php
}
$extensions = get_loaded_extensions();
sort($extensions);
?>
<tr>
<td><?php echo escape($lang['phpextensions']); ?></td>
<td><?php echo escape(implode(' ', $extensions)); ?></td>
<td></td>
</tr>
<tr>
<td class="BorderBottom" colspan='3'>
<b><?php echo escape($lang['rs_ext_dependencies']); ?></b>
</td>
</tr>
<?php
// Check system utilities
foreach (RS_SYSTEM_UTILITIES as $sysu_name => $sysu) {
// Skip utilities which are a sub program (e.g ImageMagick has convert, identify, composite etc., checking for
// convert is enough) -or- are not required and configured
if (!$sysu['show_on_check_page'] || (!$sysu['required'] && !isset($GLOBALS[$sysu['path_var_name']]))) {
continue;
}
display_utility_status($sysu_name);
}
# Check archiver
if (
!$use_zip_extension
&& ($collection_download || isset($zipcommand)) # Only check if it is going to be used.
) {
$archiver_fullpath = get_utility_path("archiver", $path);
if ($path == null && !isset($zipcommand)) {
$result = $lang["status-notinstalled"];
} elseif ($collection_download && $archiver_fullpath != false) {
$result = $lang["status-ok"];
if (isset($zipcommand)) {
$result .= "<br/>" . $lang["zipcommand_overridden"];
}
} elseif (isset($zipcommand)) {
$result = $lang["status-warning"] . ": " . $lang["zipcommand_deprecated"];
} else {
$result = $lang["status-fail"] . ": " . str_replace("?", $path, $lang["softwarenotfound"]);
}
?>
<tr>
<td colspan="2"><?php echo escape($lang["archiver_utility"]); ?></td>
<td>
<b><?php echo escape($result); ?></b>
</td>
</tr>
<?php
}
hook("addinstallationcheck");
?>
</table>
</div>
<?php
include "../include/footer.php";
function display_utility_status(string $utilityname)
{
global $lang;
$utility = get_utility_version($utilityname);
?>
<tr>
<td <?php echo $utility["success"] ? '' : 'colspan="2"'; ?>><?php echo escape($utility["name"]); ?></td>
<?php if ($utility["success"]) { ?>
<td><?php echo escape($utility["version"]); ?></td>
<?php } ?>
<td>
<b>
<?php echo $utility['success'] ? escape($lang['status-ok']) : strip_tags_and_attributes($utility['error']); ?>
</b>
</td>
</tr>
<?php
}
function display_extension_status(string $extension)
{
global $lang;
?>
<tr>
<td colspan="2">php-<?php echo escape($extension); ?></td>
<td>
<b><?php echo escape(extension_loaded($extension) ? $lang["status-ok"] : $lang["status-fail"]); ?></b>
</td>
</tr>
<?php
}
function get_utility_version(string $utilityname)
{
global $lang;
$utilityname = strtolower(trim($utilityname));
// Is this a known utility? If not, mark it as such.
if (!isset(RS_SYSTEM_UTILITIES[$utilityname])) {
return ['name' => $utilityname, 'version' => '', 'success' => false, 'error' => $lang['unknown']];
}
$utility = RS_SYSTEM_UTILITIES[$utilityname];
$utility_fullpath = get_utility_path($utilityname, $path);
$name = $utility['display_name'] ?? $utilityname;
# Check path.
if ($path == null) {
# There was no complete path to check - the utility is not installed.
$error_msg = $lang["status-notinstalled"];
return array("name" => $name, "version" => "", "success" => false, "error" => $error_msg);
}
if ($utility_fullpath === false) {
# There was a path but it was incorrect - the utility couldn't be found.
$error_msg = $lang["status-fail"] . ":<br />" . str_replace("?", $path, $lang["softwarenotfound"]);
return array("name" => $name, "version" => "", "success" => false, "error" => $error_msg);
}
# Look up the argument to use to get the version.
$version_argument = $utility['version_check']['argument'] ?? '' ?: '-version';
# Check execution and find out version.
$version_command = $utility_fullpath . " " . $version_argument;
$utilities_with_version_on_STDERR = ['python', 'antiword', 'pdftotext', 'fits'];
$version = run_command($version_command, in_array($utilityname, $utilities_with_version_on_STDERR));
$version_check = call_user_func_array(
$utility['version_check']['callback']['fct_name'],
array_merge([$version, $utility], $utility['version_check']['callback']['args'])
);
$name = $version_check['utility']['display_name'] ?? $name;
$expected = $version_check['found'];
if (!$expected) {
# There was a correct path but the version check failed - unexpected output when executing the command.
# Check if version command returned a custom error message
if (isset($version_check['error_message'])) {
$error_msg = $version_check['error_message'];
} else {
$error_msg = "{$lang["status-fail"]}:<br />"
. str_replace(['%command', '%output'], [$version_command, $version], $lang['execution_failed']);
}
return array("name" => $name, "version" => "", "success" => false, "error" => $error_msg);
} else {
# There was a working path and the output was the expected - the version is returned.
$s = explode("\n", $version);
$version_line = $utilityname === 'antiword' ? $s[3] : $s[0];
return array("name" => $name, "version" => $version_line, "success" => true, "error" => "");
}
}
function php_is_64bit()
{
$int = "9223372036854775807";
$int = intval($int);
if ($int == 9223372036854775807) {
return true;
} elseif ($int == 2147483647) {
return false;
} else {
return "error";
}
}

121
pages/collection_comment.php Executable file
View File

@@ -0,0 +1,121 @@
<?php
include "../include/boot.php";
# External access support (authenticate only if no key provided, or if invalid access key provided)
$k = getval("k", "");
if (($k == "") || (!check_access_key(getval("ref", "", true), $k))) {
include "../include/authenticate.php";
}
$ref = getval("ref", "", true);
$collection = getval("collection", "", true);
# Fetch collection data
$cinfo = get_collection($collection);
if ($cinfo === false) {
exit($lang['error-collectionnotfound']);
}
$commentdata = get_collection_resource_comment($ref, $collection);
if ($commentdata === false) {
exit($lang['resourcenotfound']);
}
$comment = $commentdata["comment"];
$rating = $commentdata["rating"];
# Check access
if (!collection_readable($collection)) {
exit("Access denied.");
}
if (getval("submitted", "") != "" && enforcePostRequest(false)) {
# Save comment
$comment = trim(getval("comment", ""));
$rating = trim(getval("rating", ""));
# Clear cache for immediate display of thumbnail change.
clear_query_cache("themeimage");
save_collection_resource_comment($ref, $collection, $comment, $rating);
if ($k == "") {
redirect($baseurl_short . "pages/search.php?refreshcollectionframe=true&search=!collection" . $collection);
} else {
# Stay on this page for external access users (no access to search)
refresh_collection_frame();
}
}
include "../include/header.php";
?>
<div class="BasicsBox">
<h1><?php echo escape($lang["collectioncomments"]); ?></h1>
<p>
<?php
echo escape($lang["collectioncommentsinfo"]);
render_help_link("user/resource_commenting");
?>
</p>
<?php
$imagepath = get_resource_path($ref, true, "col", false, "jpg");
$imageurl = get_resource_path($ref, false, "col", false, "jpg");
if (file_exists($imagepath)) { ?>
<div class="Question">
<label for="image"><?php echo escape($lang["preview"]); ?></label>
<img src="<?php echo $imageurl?>?nc=<?php echo time()?>" alt="" class="Picture" />
<div class="clearerleft"></div>
</div>
<?php } ?>
<form method="post" action="<?php echo $baseurl_short?>pages/collection_comment.php" onSubmit="return CentralSpacePost(this, true, false, false);">
<?php generateFormToken("collection_comment"); ?>
<input type="hidden" name="ref" value="<?php echo escape($ref); ?>">
<input type="hidden" name="k" value="<?php echo escape($k); ?>">
<input type="hidden" name="collection" value="<?php echo escape($collection); ?>">
<input type="hidden" name="submitted" value="true">
<div class="Question">
<label for="name"><?php echo escape($lang["comment"]); ?></label>
<textarea class="stdwidth" style="width:450px;" rows=20 cols=80 name="comment" id="comment"><?php echo escape((string) $comment); ?></textarea>
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="name"><?php echo escape($lang["rating"]); ?></label>
<select class="stdwidth" name="rating">
<option value="" <?php echo ($rating == "") ? " selected" : ''; ?>></option>
<?php for ($n = 1; $n <= 5; $n++) { ?>
<option value="<?php echo $n?>" <?php echo ($rating == $n) ? " selected" : ''; ?>>
<?php echo str_pad("", $n, "*"); ?>
</option>
<?php } ?>
</select>
<div class="clearerleft"></div>
</div>
<?php if ($cinfo["type"] == COLLECTION_TYPE_FEATURED && checkperm("h")) { ?>
<div class="Question">
<label for="use_as_theme_thumbnail"><?php echo escape($lang["useasthemethumbnail"]); ?></label>
<input
name="use_as_theme_thumbnail"
id="use_as_theme_thumbnail"
type="checkbox"
value="yes"
<?php if ($commentdata["use_as_theme_thumbnail"] == 1) { ?>
checked
<?php } ?>
>
<div class="clearerleft"></div>
</div>
<?php } ?>
<div class="QuestionSubmit">
<input name="save" type="submit" value="<?php echo escape($lang["save"]); ?>" />
</div>
</form>
</div>
<?php
include "../include/footer.php";

View File

@@ -0,0 +1,81 @@
<?php
include "../include/boot.php";
include "../include/authenticate.php";
$ref = getval("ref", 0, true);
if (checkperm("b") || !collection_writeable($ref)) {
http_response_code(403);
$error = $lang["error-permissiondenied"];
error_alert($error, false);
exit();
}
# Fetch collection data
$list = get_user_collections($userref);
$collection = get_collection($ref);
if ($collection === false || (count($list) <= 1 && in_array($ref, array_column($list, "ref")))) {
// Collection not found or user is attempting to copy resources to one of their own collections but only has one collection
http_response_code(404);
$error = $lang['error-collectionnotfound'];
error_alert($error, false);
exit();
}
if (getval("submitted", "") != "" && enforcePostRequest(false)) {
$copyfrom = getval("collection_copy_from", 0, true);
if ($copyfrom > 0 && collection_readable($copyfrom)) {
copy_collection($copyfrom, $ref);
redirect($baseurl_short . "pages/search.php?search=!collection" . $ref);
exit();
}
}
include "../include/header.php";
?>
<div class="BasicsBox">
<h1><?php echo escape($lang["collection_copy_resources"]); ?></h1>
<p><?php echo text("introtext"); ?></p>
<form method=post id="collection_copy_form" action="<?php echo $baseurl_short?>pages/collection_copy_resources.php">
<?php generateFormToken("collection_copy_form"); ?>
<input type=hidden name=ref value="<?php echo escape($ref); ?>">
<input type=hidden name="submitted" value="true">
<div class="Question">
<label for="name"><?php echo escape($lang["collection"]); ?></label>
<div class="Fixed"><?php echo escape(i18n_get_collection_name($collection, $index = "name")); ?></div>
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for='collection_copy_from' id='label_collection'><?php echo escape($lang["copyfromcollection"]); ?></label>
<select name='collection_copy_from' id='collection_copy_from'>
<?php
for ($n = 0; $n < count($list); $n++) {
if ($ref == $list[$n]["ref"]) {
continue;
}
#show only active collections if a start date is set for $active_collections
if (
strtotime($list[$n]['created']) > ((isset($active_collections)) ? strtotime($active_collections) : 1)
|| ($list[$n]['name'] == "Default Collection" && $list[$n]['user'] == $userref)
) {
echo "<option value='" . $list[$n]["ref"] . "'>" . escape(i18n_get_collection_name($list[$n])) . "</option>\n";
}
}
?>
</select>
</div>
<div class="QuestionSubmit">
<input name="save" type="submit" value="<?php echo escape($lang["copy"]); ?>" />
</div>
</form>
</div>
<?php
include "../include/footer.php";

550
pages/collection_download.php Executable file
View File

@@ -0,0 +1,550 @@
<?php
ini_set('zlib.output_compression', 'off'); // disable PHP output compression since it breaks collection downloading
include __DIR__ . "/../include/boot.php";
// External access support (authenticate only if no key provided, or if invalid access key provided)
$k = getval("k", "");
if (($k == "") || (!check_access_key_collection(getval("collection", "", true), $k))) {
include "../include/authenticate.php";
}
include_once __DIR__ . "/../include/csv_export_functions.php";
include_once __DIR__ . "/../include/pdf_functions.php";
ob_end_clean();
$collection = getval("collection", "", true);
if ($k != "") {
$usercollection = $collection;
}
$size = getval("size", "original");
$submitted = getval("submitted", "") !== "";
$includetext = getval("includetext", "") === "true";
$useoriginal = getval("use_original", "") !== "";
$collectiondata = get_collection($collection);
$tardownload = getval("tardownload", "");
$include_csv_file = getval("include_csv_file", "") !== "";
$include_alternatives = getval("include_alternatives", "") !== "";
$email = getval('email', '');
if ($k != "" || (isset($anonymous_login) && $username == $anonymous_login)) {
// Disable offline jobs as there is currently no way to notify the user upon job completion
$offline_job_queue = false;
}
/// Get collection resources
$result = do_search("!collection" . $collection);
$modified_result = hook("modifycollectiondownload");
if (is_array($modified_result)) {
$result = $modified_result;
}
// Check size?
$totalsize = 0;
$totalsizeerror = false;
if (in_array($size, ['original', 'largest'])) {
// Estimate the total volume of files to zip if using largest or originals
for ($n = 0; $n < count($result); $n++) {
$totalsize += $result[$n]['file_size'];
}
if ($submitted && $totalsize > $collection_download_max_size) {
$totalsizeerror = true;
$onload_message = array("title" => $lang["error"], "text" => $lang["collection_download_too_large"]);
}
}
$show_download_format_selector = true;
// Determine if the download format selector should be shown
if ($collection_download_tar_size === 0 || $config_windows) {
$show_download_format_selector = false;
}
// Determine if TAR should be the default option
if ($show_download_format_selector && ($collection_download_tar_option || ($totalsize >= $collection_download_tar_size * 1024 * 1024))) {
$tar_as_default = true;
} else {
$tar_as_default = false;
}
// Determine selected download format selector value if submitted
if ($submitted && $show_download_format_selector) {
$tar_selected = ($tardownload == 'on');
} else {
$tar_selected = $tar_as_default;
}
$settings_id = (isset($collection_download_settings) && count($collection_download_settings) > 1) ? getval("settings", "") : 0;
$usage = getval('usage', '-1', true);
$usagecomment = getval('usagecomment', '');
// set the time limit to unlimited, default 300 is not sufficient here.
set_time_limit(0);
$archiver_fullpath = get_utility_path("archiver");
if (!$collection_download) {
exit(escape($lang["download-of-collections-not-enabled"]));
} elseif (!$use_zip_extension) {
if (!$archiver_fullpath) {
exit(escape($lang["archiver-utility-not-found"]));
}
if (!isset($collection_download_settings)) {
exit(escape($lang["collection_download_settings-not-defined"]));
} elseif (!is_array($collection_download_settings)) {
exit(escape($lang["collection_download_settings-not-an-array"]));
}
if (!isset($archiver_listfile_argument)) {
exit(escape($lang["listfile-argument-not-defined"]));
}
}
// Should the configured archiver be used
$archiver = (
$collection_download
&& $archiver_fullpath != false
&& (isset($archiver_listfile_argument))
&& (isset($collection_download_settings)
)
? is_array($collection_download_settings)
: false
);
// This array will store all the available downloads.
$available_sizes = array();
$count_data_only_types = 0;
// Build the available sizes array
for ($n = 0; $n < count($result); $n++) {
$ref = $result[$n]["ref"];
// Load access level (0,1,2) for this resource
$access = get_resource_access($result[$n]);
// Get all possible sizes for this resource. If largest available has been requested then include internal or user could end up with no file depite being able to see the preview
$sizes = get_all_image_sizes($size == "largest", $access >= 1);
// Check availability of original file
$p = get_resource_path($ref, true, "", false, $result[$n]["file_extension"]);
if (file_exists($p) && (($access == 0) || ($access == 1 && $restricted_full_download)) && resource_download_allowed($ref, '', $result[$n]['resource_type'], -1, true)) {
$available_sizes['original'][] = $ref;
}
// Check availability of each size and load it to the available_sizes array
foreach ($sizes as $sizeinfo) {
if (in_array($result[$n]['file_extension'], $ffmpeg_supported_extensions)) {
$size_id = $sizeinfo['id'];
// Video files will only have a 'pre' sized derivative so add to the sizes array
$p = get_resource_path($ref, true, 'pre', false, $result[$n]['file_extension']);
$size_id = 'pre';
if (
resource_download_allowed($ref, $size_id, $result[$n]['resource_type'], -1, true)
&& (hook('size_is_available', '', array($result[$n], $p, $size_id)) || file_exists($p))
) {
$available_sizes[$sizeinfo['id']][] = $ref;
}
} elseif (in_array($result[$n]['file_extension'], array_merge($ffmpeg_audio_extensions, ['mp3']))) {
// Audio files are ported to mp3 and do not have different preview sizes
$p = get_resource_path($ref, true, '', false, 'mp3');
if (
resource_download_allowed($ref, '', $result[$n]['resource_type'], -1, true)
&& (hook('size_is_available', '', array($result[$n], $p, '')) || file_exists($p))
) {
$available_sizes[$sizeinfo['id']][] = $ref;
}
} else {
$size_id = $sizeinfo['id'];
$size_extension = get_extension($result[$n], $size_id);
$p = get_resource_path($ref, true, $size_id, false, $size_extension);
if (
resource_download_allowed($ref, $size_id, $result[$n]['resource_type'], -1, true)
&& (hook('size_is_available', '', array($result[$n], $p, $size_id)) || file_exists($p))
) {
$available_sizes[$size_id][] = $ref;
}
}
}
if (in_array($result[$n]['resource_type'], $data_only_resource_types)) {
$count_data_only_types++;
}
}
if (isset($user_dl_limit) && intval($user_dl_limit) > 0) {
$download_limit_check = get_user_downloads($userref, $user_dl_days);
if ($download_limit_check + count($result) > $user_dl_limit) {
$dlsummary = $download_limit_check . "/" . $user_dl_limit;
$errormessage = $lang["download_limit_collection_error"] . " " . str_replace(array("[downloaded]","[limit]"), array($download_limit_check,$user_dl_limit), $lang['download_limit_summary']);
if (getval("ajax", "") != "") {
error_alert(escape($errormessage), true, 200);
} else {
include "../include/header.php";
$onload_message = array("title" => $lang["error"],"text" => $errormessage);
include "../include/footer.php";
}
exit();
}
}
if (count($available_sizes) === 0 && $count_data_only_types === 0) {
error_alert($lang["nodownloadcollection"], false);
exit();
}
$used_resources = array();
$subbed_original_resources = array();
if ($submitted & !$totalsizeerror) {
if ($exiftool_write && !$force_exiftool_write_metadata && !$tar_selected) {
$exiftool_write_option = getval('write_metadata_on_download', '') == "yes";
}
$id = uniqid("Col" . $collection);
$collection_download_data = [
'archiver' => $archiver,
'collection' => $collection,
'collectiondata' => $collectiondata,
'collection_resources' => $result,
'size' => $size,
'exiftool_write_option' => $exiftool_write_option,
'useoriginal' => $useoriginal,
'id' => $id,
'includetext' => $includetext,
'text' => $text ?? "",
'count_data_only_types' => $count_data_only_types,
'usage' => $usage,
'usagecomment' => str_replace(array('\r','\n'), " ", $usagecomment),
'settings_id' => $settings_id,
'include_csv_file' => $include_csv_file,
'include_alternatives' => $include_alternatives,
'collection_download_tar' => $tar_selected,
'k' => $k,
];
if ($offline_job_queue) {
// Only need to store resource IDS, not full search data
$collection_download_data["result"] = array_column($result, "ref", "ref");
// tar files are not an option with offline jobs
$collection_download_data['collection_download_tar'] = false;
$modified_job_data = hook("collection_download_modify_job", "", [$collection_download_data]);
if (is_array($modified_job_data)) {
$collection_download_data = $modified_job_data;
}
job_queue_add(
'collection_download',
$collection_download_data,
'',
'',
$lang["oj-collection-download-success-text"],
$lang["oj-collection-download-failure-text"],
'',
JOB_PRIORITY_USER
);
$job_created = true;
$onload_message = [
"title" => $lang['collection_download'],
"text" => $lang['jq_notify_user_preparing_archive'],
];
} else {
$zipinfo = process_collection_download($collection_download_data);
if (empty($zipinfo)) {
error_alert(escape($lang["download_limit_collection_error"]), true, 200);
}
if ($zipinfo["completed"] ?? false) {
// A tar file was requested and sent. Nothing further to do.
collection_log($collection, LOG_CODE_COLLECTION_COLLECTION_DOWNLOADED, "", "tar - " . $size);
exit();
} else {
// Get the file size of the archive.
$filesize = filesize_unlimited($zipinfo["path"]);
header("Content-Disposition: attachment; filename=" . $zipinfo["filename"]);
if ($archiver) {
header("Content-Type: " . $collection_download_settings[$settings_id]["mime"]);
} else {
header("Content-Type: application/zip");
}
if ($use_zip_extension) {
header("Content-Transfer-Encoding: binary");
}
header("Content-Length: " . $filesize);
ignore_user_abort(true); // collection download has a problem with leaving junk files when this script is aborted client side. This seems to fix that by letting the process run its course.
set_time_limit(0);
$sent = 0;
$handle = fopen($zipinfo["path"], "r");
// Now loop through the file and echo out chunks of file data
while ($sent < $filesize) {
echo fread($handle, $download_chunk_size);
$sent += $download_chunk_size;
}
// File send complete, log to daily stat
daily_stat('Downloaded KB', 0, floor($sent / 1024));
// Remove archive.
if ($use_zip_extension || $archiver) {
$GLOBALS["use_error_exception"] = true;
try {
$usertempdir = get_temp_dir(false, "rs_" . $GLOBALS["userref"] . "_" . $id);
rmdir($usertempdir);
} catch (Exception $e) {
debug("collection_download: Attempt delete temp folder failed. Reason: {$e->getMessage()}");
}
unset($GLOBALS["use_error_exception"]);
}
collection_log($collection, LOG_CODE_COLLECTION_COLLECTION_DOWNLOADED, "", $size);
hook('beforedownloadcollectionexit');
exit();
}
}
}
include "../include/header.php";
?>
<script>
jQuery(document).ready(function() {
jQuery('#tardownload').on('change', function(){
if (this.value == 'off') {
console.log('Enabling');
jQuery('#exiftool_question').slideDown();
jQuery('#write_metadata_on_download').prop('disabled', false);
jQuery('#archivesettings_question').slideDown();
jQuery('#archivesettings').prop('disabled', false);
} else {
console.log('Disabling');
jQuery('#exiftool_question').slideUp();
jQuery('#write_metadata_on_download').prop('disabled', 'disabled');
jQuery('#archivesettings_question').slideUp();
jQuery('#archivesettings').prop('disabled', 'disabled');
}
});
});
</script>
<div class="BasicsBox">
<?php if ($k != "") {
$urlparams = [
"search" => "!collection" . $collection,
"k" => $k,
];
?>
<p>
<a href="<?php echo generateURL($baseurl_short . "pages/search.php", $urlparams); ?>" onclick="return CentralSpaceLoad(this,true);">
<?php echo escape($lang['back'])?>
</a>
</p>
<?php
} ?>
<h1><?php echo escape($lang["downloadzip"]); ?></h1>
<?php
$intro = text("introtext");
if ($intro != "") {
?>
<p><?php echo strip_tags_and_attributes($intro); ?></p>
<?php
}
?>
<form id='collection_download_form' action="<?php echo $baseurl_short; ?>pages/collection_download.php?collection=<?php echo escape($collection . (($k != '') ? '&k=' . $k : '')); ?>" method=post>
<?php generateFormToken("collection_download_form"); ?>
<input type=hidden name="collection" value="<?php echo escape($collection); ?>">
<input type=hidden name="usage" value="<?php echo escape($usage); ?>">
<input type=hidden name="usagecomment" value="<?php echo escape($usagecomment); ?>">
<input type=hidden name="k" value="<?php echo escape($k); ?>">
<input type=hidden name="submitted" value="true">
<?php
hook("collectiondownloadmessage");
if ($count_data_only_types !== count($result)) { ?>
<div class="Question">
<label for="downloadsize"><?php echo strip_tags_and_attributes($lang["downloadsize"], array('a'), array('href', 'target')); ?></label>
<div class="tickset">
<?php
$maxaccess = collection_max_access($collection);
$sizes = get_all_image_sizes(false, $maxaccess >= 1);
$available_sizes = array_reverse($available_sizes, true);
// Analyze available sizes and present options
?>
<select name="size" class="stdwidth" id="downloadsize">
<?php
if (array_key_exists('original', $available_sizes)) {
display_size_option('original', $lang['original'], true, $size == 'original');
}
display_size_option('largest', $lang['imagesize-largest'], true, $size == 'largest');
foreach ($available_sizes as $key => $value) {
foreach ($sizes as $size_row) {
if ($size_row['id'] == $key) {
display_size_option($key, $size_row['name'], true, $key == $size);
break;
}
}
}
?>
</select>
<div class="clearerleft"></div>
</div>
<div class="clearerleft"></div>
</div>
<?php
}
if (
!hook('replaceuseoriginal')
&& $count_data_only_types !== count($result)
) {
?>
<div class="Question">
<label for="use_original"><?php echo escape($lang['use_original_if_size']); ?>
<br />
<?php display_size_option('original', $lang['original'], false); ?>
</label>
<input type=checkbox
id="use_original"
name="use_original"
value="yes"
<?php if ($useoriginal) {
echo "checked";
} ?>
>
<div class="clearerleft"></div>
</div>
<?php
}
if ($zipped_collection_textfile) {
?>
<div class="Question">
<label for="includetext"><?php echo escape($lang["zippedcollectiontextfile"]); ?></label>
<select name="includetext" class="shrtwidth" id="includetext"<?php echo (!empty($submitted)) ? ' disabled="disabled"' : ''; ?>>
<?php if ($zipped_collection_textfile_default_no) { ?>
<option value="false"><?php echo escape($lang["no"]); ?></option>
<option value="true"><?php echo escape($lang["yes"]); ?></option>
<?php } else { ?>
<option value="true"><?php echo escape($lang["yes"]); ?></option>
<option value="false"><?php echo escape($lang["no"]); ?></option>
<?php } ?>
</select>
<div class="clearerleft"></div>
</div>
<?php
}
?>
<!-- Add CSV file with the metadata of all the resources found in this collection -->
<div class="Question">
<label for="include_csv_file"><?php echo escape($lang['csvAddMetadataCSVToArchive']); ?></label>
<input type="checkbox"
id="include_csv_file"
name="include_csv_file"
value="yes"
<?php if ($include_csv_file) {
echo "checked";
} ?>
>
<div class="clearerleft"></div>
</div>
<!-- Alternatives? -->
<div class="Question">
<label for="include_alternatives"><?php echo escape($lang['collection_download_include_alternatives']); ?></label>
<input type="checkbox"
id="include_alternatives"
name="include_alternatives"
value="yes"
<?php if ($include_alternatives) {
echo "checked";
} ?>
>
<div class="clearerleft"></div>
</div>
<?php if ($exiftool_write && !$force_exiftool_write_metadata) { ?>
<!-- Let user say (if allowed - ie. not enforced by system admin) whether metadata should be written to the file or not -->
<div class="Question" id="exiftool_question" <?php echo $collection_download_tar_option ? "style=\"display:none;\"" : ''; ?>>
<label for="write_metadata_on_download"><?php echo escape($lang['collection_download__write_metadata_on_download_label']); ?></label>
<input type="checkbox"
id="write_metadata_on_download"
name="write_metadata_on_download"
value="yes"
<?php if (getval('write_metadata_on_download', '') !== '') {
echo "checked";
} ?>
>
<div class="clearerleft"></div>
</div>
<?php
}
if ($download_usage_email) {
?>
<input type="hidden" name="email" value="<?php echo escape($email); ?>"/>
<?php
}
// Legacy archiver settings
if ($archiver && count($collection_download_settings) > 1) { ?>
<div class="Question" id="archivesettings_question"
<?php if ($collection_download_tar_option) {
echo "style=\"display:none\"";
} ?>
>
<label for="archivesettings"><?php echo escape($lang["archivesettings"]); ?></label>
<div class="tickset">
<select name="settings" class="stdwidth" id="archivesettings" <?php
if ($submitted) {
echo ' disabled="disabled"';
} ?>
> <?php
foreach ($collection_download_settings as $key => $value) { ?>
<option value="<?php echo escape($key); ?>"><?php echo escape(lang_or_i18n_get_translated($value["name"], "archive-")); ?>
</option><?php
} ?>
</select>
</div>
<div class="clearerleft"></div>
</div> <?php
} ?>
<!-- Tar file download option -->
<div class="Question" <?php echo (!$show_download_format_selector) ? "style=\"display:none;\"" : ''; ?>>
<label for="tardownload"><?php echo escape($lang["collection_download_format"]); ?></label>
<div class="tickset">
<select name="tardownload" class="stdwidth" id="tardownload" >
<option value="off" <?php echo (!$tar_selected) ? " selected" : ''; ?>>
<?php echo escape($lang["collection_download_no_tar"]); ?>
</option>
<option value="on" <?php echo ($tar_selected) ? " selected" : ''; ?>>
<?php echo escape($lang["collection_download_use_tar"]); ?>
</option>
</select>
<div class="clearerleft"></div>
</div>
<br />
<div class="clearerleft"></div>
<label for="tarinfo"></label>
<div class="FormHelpInner tickset">
<?php echo escape($lang["collection_download_tar_info"]) . "<br />" . strip_tags_and_attributes($lang["collection_download_tar_applink"], array('a'), array('href', 'target')); ?>
</div>
<div class="clearerleft"></div>
</div>
<div class="QuestionSubmit" id="downloadbuttondiv">
<label for="download"> </label>
<input
type="submit"
value="<?php echo escape($lang["action-download"]); ?>"
<?php if ($job_created ?? false) {
echo "disabled";
} ?>
/>
<div class="clearerleft"></div>
</div>
</form>
</div>
<?php
include "../include/footer.php";

430
pages/collection_edit.php Executable file
View File

@@ -0,0 +1,430 @@
<?php
include "../include/boot.php";
include "../include/authenticate.php";
if (checkperm("b") || $system_read_only) {
exit("Permission denied.");
}
$ref = getval("ref", "", true);
$copycollectionremoveall = getval("copycollectionremoveall", "");
$offset = getval("offset", 0, true);
$find = getval("find", "");
$col_order_by = getval("col_order_by", "name");
$sort = getval("sort", "ASC");
$modal = getval("modal", "") == "true";
$redirection_endpoint = trim(urldecode(getval("redirection_endpoint", "")));
$redirect = getval("redirect", "") != "";
$name = getval("name", "");
$public = getval("public", "");
# Does this user have edit access to collections? Variable will be found in functions below.
$multi_edit = allow_multi_edit($ref);
# Check access
if (!collection_writeable($ref)) {
exit($lang["no_access_to_collection"]);
}
$collection = get_collection($ref);
if ($collection === false) {
$error = $lang['error-collectionnotfound'];
error_alert($error);
exit();
}
if (!in_array($collection["type"], array(COLLECTION_TYPE_STANDARD, COLLECTION_TYPE_PUBLIC, COLLECTION_TYPE_FEATURED))) {
error_alert($lang["error-permissiondenied"], true, 401);
exit();
} elseif ($collection["type"] == COLLECTION_TYPE_FEATURED && !featured_collection_check_access_control((int) $collection["ref"])) {
error_alert($lang["error-permissiondenied"], true, 403);
exit();
}
$resources = do_search("!collection" . $ref);
$colcount = count($resources);
# Collection copy functionality
$copy = getval("copy", "");
if ($copy != "") {
copy_collection($copy, $ref, $copycollectionremoveall != "");
refresh_collection_frame();
}
if (getval("submitted", "") != "" && enforcePostRequest(false)) {
# Save collection data
$coldata["name"] = getval("name", "");
$coldata["allow_changes"] = getval("allow_changes", "") != "" ? 1 : 0;
$coldata["public"] = getval('public', 0, true);
$coldata["keywords"] = getval("keywords", "");
$coldata["description"] = getval("description", "");
$coldata["result_limit"] = getval("result_limit", 0, true);
$coldata["users"] = getval("users", "");
if ($collection["public"] == 1 && getval("update_parent", "") == "true") {
// Prepare coldata for save_collection() for posted featured collections (if any changes have been made)
$current_branch_path = get_featured_collection_category_branch_by_leaf((int) $ref, array());
$featured_collections_changes = process_posted_featured_collection_categories(0, $current_branch_path);
if (!empty($featured_collections_changes)) {
$coldata["featured_collections_changes"] = $featured_collections_changes;
}
}
// User selected a background image
if ($enable_themes && $themes_simple_images && $collection["type"] == COLLECTION_TYPE_FEATURED && checkperm("h")) {
$thumbnail_selection_method = getval("thumbnail_selection_method", $FEATURED_COLLECTION_BG_IMG_SELECTION_OPTIONS["no_image"], true);
if (in_array($thumbnail_selection_method, $FEATURED_COLLECTION_BG_IMG_SELECTION_OPTIONS)) {
$coldata["featured_collections_changes"]["thumbnail_selection_method"] = $thumbnail_selection_method;
$bg_img_resource_ref = getval("bg_img_resource_ref", 0, true);
if (
$thumbnail_selection_method == $FEATURED_COLLECTION_BG_IMG_SELECTION_OPTIONS["manual"]
&& $bg_img_resource_ref > 0 && get_resource_access($bg_img_resource_ref) == RESOURCE_ACCESS_FULL
) {
$coldata["bg_img_resource_ref"] = $bg_img_resource_ref;
}
// If invalid bg_img_resource_ref or no full access to resource, then don't submit the change
elseif ($thumbnail_selection_method == $FEATURED_COLLECTION_BG_IMG_SELECTION_OPTIONS["manual"]) {
$reset_thumbnail_selection_method = (isset($collection['thumbnail_selection_method']) ? $collection['thumbnail_selection_method'] : $FEATURED_COLLECTION_BG_IMG_SELECTION_OPTIONS["no_image"]);
$coldata['featured_collections_changes']['thumbnail_selection_method'] = $reset_thumbnail_selection_method;
$coldata['bg_img_resource_ref'] = 0;
}
}
} elseif ($collection["type"] == COLLECTION_TYPE_FEATURED && checkperm("h")) {
$coldata['featured_collections_changes']['name'] = "";
}
if (checkperm("h")) {
$coldata["home_page_publish"] = (getval("home_page_publish", "") != "") ? "1" : "0";
$coldata["home_page_text"] = getval("home_page_text", "");
if (getval("home_page_image", "") != "") {
$coldata["home_page_image"] = getval("home_page_image", "");
}
}
if (
(
$coldata["public"] == 0
|| (
isset($coldata["featured_collections_changes"]["update_parent"])
&& $coldata["featured_collections_changes"]["update_parent"] == 0
&& getval("force_featured_collection_type", "") != "true"
)
)
&& is_featured_collection_category_by_children($collection["ref"])
) {
$error = $lang["error_save_not_allowed_fc_has_children"];
}
if (!isset($error)) {
save_collection($ref, $coldata);
if ($redirect) {
if ($redirection_endpoint == "") {
$redirection_endpoint = generateURL(
"{$baseurl_short}pages/collection_manage.php",
array(
"offset" => $offset,
"col_order_by" => $col_order_by,
"sort" => $sort,
"find" => $find,
"reload" => "true",
)
);
}
if ($modal) {
?>
<script>
ModalClose();
CentralSpaceLoad('<?php echo escape($redirection_endpoint); ?>');
</script>
<?php
} else {
redirect($redirection_endpoint);
}
exit();
}
# No redirect, we stay on this page. Reload the collection info.
$collection = get_collection($ref);
}
}
$search_params = get_search_params();
$url_params = array_merge(["ref" => $collection["ref"]], $search_params);
$form_action = generateURL("{$baseurl_short}pages/collection_edit.php", $url_params);
include "../include/header.php";
?>
<div class="BasicsBox">
<?php
if (isset($error)) {
render_top_page_error_style($error);
} else { ?>
<h1><?php echo escape($lang["editcollection"]);
render_help_link("user/edit-collection"); ?></h1>
<p><?php echo text("introtext"); ?></p>
<form method=post id="collectionform" action="<?php echo $form_action; ?>" onsubmit="return <?php echo $modal ? 'Modal' : 'CentralSpace'; ?>Post(this, false);">
<?php generateFormToken("collectionform"); ?>
<input type="hidden" name="modal" value="<?php echo $modal ? "true" : "false"; ?>">
<input type="hidden" name="redirection_endpoint" id="redirection_endpoint" value="<?php echo urlencode($redirection_endpoint); ?>">
<input type="hidden" name="redirect" id="redirect" value="yes" >
<input type="hidden" name="submitted" value="true">
<input type="hidden" name="update_parent" value="false">
<div class="Question">
<label for="name"><?php echo escape($lang["name"])?></label>
<input
type=text
class="stdwidth"
name="name"
id="name"
value="<?php echo escape($collection["name"]) ?>"
maxlength="100"
<?php if ($collection["cant_delete"] == 1) { ?>
readonly=true
<?php } ?>
>
<div class="clearerleft"></div>
</div>
<?php hook('additionalfields');?>
<div class="Question">
<label for="description"><?php echo escape($lang["collection_description"]); ?></label>
<textarea class="stdwidth" rows="4" name="description" id="description"><?php echo escape((string) $collection["description"])?></textarea>
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="keywords"><?php echo escape($lang["relatedkeywords"]); ?></label>
<textarea
class="stdwidth"
rows="3"
name="keywords"
id="keywords"
<?php if ($collection["cant_delete"] == 1) { ?>
readonly=true
<?php } ?>
><?php echo escape((string) $collection["keywords"])?></textarea>
<div class="clearerleft"></div>
</div>
<div class="Question">
<label><?php echo escape($lang["id"]); ?></label>
<div class="Fixed"><?php echo escape($collection["ref"]); ?></div>
<div class="clearerleft"></div>
</div>
<?php
if ($collection["savedsearch"] != "") {
$result_limit = ps_value("select result_limit value from collection_savedsearch where collection= ?", ['i', $ref], "");
?>
<div class="Question">
<label for="name"><?php echo escape($lang["smart_collection_result_limit"]); ?></label>
<input type=text class="stdwidth" name="result_limit" id="result_limit" value="<?php echo escape((string) $result_limit); ?>" />
<div class="clearerleft"></div>
</div>
<?php
} ?>
<div class="Question">
<label for="public"><?php echo escape($lang["access"]); ?></label>
<?php
if ($collection["cant_delete"] == 1) {
# This is a user's My Collection, which cannot be made public or turned into a theme. Display a warning.
?>
<input type="hidden" id="public" name="public" value="0">
<div class="Fixed"><?php echo escape($lang["mycollection_notpublic"]); ?></div>
<?php
} else { ?>
<select id="public" name="public" class="stdwidth" onchange="document.getElementById('redirect').value='';<?php echo $modal ? 'Modal' : 'CentralSpace'; ?>Post(document.getElementById('collectionform'));">
<option value="0" <?php echo ($collection["public"] != 1) ? " selected" : ''; ?>>
<?php echo escape($lang["private"])?>
</option>
<?php if ($collection["cant_delete"] != 1 && ($enable_public_collections || checkperm("h"))) { ?>
<option value="1" <?php echo ($collection["public"] == 1) ? " selected" : ''; ?>>
<?php echo escape($lang["public"])?>
</option>
<?php } ?>
</select>
<?php
} ?>
<div class="clearerleft"></div>
</div>
<?php
if (
$collection["public"] == 0
|| ($collection['type'] == COLLECTION_TYPE_PUBLIC && !$themes_in_my_collections)
|| ($collection['type'] == COLLECTION_TYPE_FEATURED && $themes_in_my_collections)
) {
?>
<div class="Question">
<label for="users"><?php echo escape($lang["attachedusers"]); ?></label>
<?php
$userstring = escape($collection["users"]);
if ($userstring != '') {
$userstring .= ",";
}
$userstring .= escape($collection["groups"]);
include "../include/user_select.php";
?>
<div class="clearerleft"></div>
</div>
<?php
}
if ($enable_themes && $collection["public"] == 1 && checkperm("h")) {
render_featured_collection_category_selector(
0,
array(
"collection" => $collection,
"depth" => 0,
"current_branch_path" => get_featured_collection_category_branch_by_leaf((int) $collection["ref"], array()),
"modal" => $modal,
)
);
if ($themes_simple_images && $collection["type"] == COLLECTION_TYPE_FEATURED) {
$configurable_options = array(
$FEATURED_COLLECTION_BG_IMG_SELECTION_OPTIONS["no_image"] => $lang["select"],
$FEATURED_COLLECTION_BG_IMG_SELECTION_OPTIONS["most_popular_image"] => $lang["background_most_popular_image"],
$FEATURED_COLLECTION_BG_IMG_SELECTION_OPTIONS["most_popular_images"] => str_replace("%n", $theme_images_number, $lang["background_most_popular_images"]),
$FEATURED_COLLECTION_BG_IMG_SELECTION_OPTIONS["most_recent_image"] => $lang["background_most_recent_image"],
$FEATURED_COLLECTION_BG_IMG_SELECTION_OPTIONS["manual"] => $lang["background_manual_selection"],
);
render_dropdown_question(
$lang["background_image"],
"thumbnail_selection_method",
$configurable_options,
$collection["thumbnail_selection_method"],
'class="stdwidth"',
array(
"onchange" => "toggle_fc_bg_image_txt_input(this, " . $FEATURED_COLLECTION_BG_IMG_SELECTION_OPTIONS["manual"] . ");",
)
);
$display_bg_img_ref = ($collection["thumbnail_selection_method"] == $FEATURED_COLLECTION_BG_IMG_SELECTION_OPTIONS["manual"] && $collection["bg_img_resource_ref"] > 0);
$current_bg_img_ref = ($display_bg_img_ref ? $collection["bg_img_resource_ref"] : "");
render_text_question(
$lang["background_manual_selection_resource_label"],
"bg_img_resource_ref",
"",
true,
'class="stdwidth"',
$current_bg_img_ref,
array(
"div_class" => ($display_bg_img_ref ? array() : array("DisplayNone")),
)
);
}
}
if (checkperm("h") && $collection['public'] == 1 && !$home_dash) {
# Option to publish to the home page.
?>
<div class="Question">
<label for="allow_changes"><?php echo escape($lang["theme_home_promote"]); ?></label>
<input
type="checkbox"
id="home_page_publish"
name="home_page_publish"
value="1"
<?php if ($collection["home_page_publish"] == 1) { ?>
checked
<?php } ?>
onclick="document.getElementById('redirect').value='';<?php echo $modal ? 'Modal' : 'CentralSpace'; ?>Post(document.getElementById('collectionform'));"
>
<div class="clearerleft"></div>
</div>
<?php
if ($collection["home_page_publish"]) {
# Option ticked - collect extra data
?>
<div class="Question">
<label for="home_page_text"><?php echo escape($lang["theme_home_page_text"]); ?></label>
<textarea class="stdwidth" rows="3" name="home_page_text" id="home_page_text"><?php echo escape($collection["home_page_text"] == "" ? $collection["name"] : $collection["home_page_text"])?></textarea>
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="home_page_image">
<?php echo escape($lang["theme_home_page_image"]); ?>
</label>
<select class="stdwidth" name="home_page_image" id="home_page_image">
<?php foreach ($resources as $resource) { ?>
<option
value="<?php echo escape($resource["ref"]) ?>"
<?php if ($resource["ref"] == $collection["home_page_image"]) { ?>
selected
<?php } ?>
>
<?php echo str_replace(array("%ref", "%title"), array($resource["ref"], i18n_get_translated($resource["field" . $view_title_field])), $lang["ref-title"]); ?>
</option>
<?php } ?>
</select>
<div class="clearerleft"></div>
</div>
<?php
}
}
if (!isset($collection['savedsearch']) || $collection['savedsearch'] == null) {
# disallowing share breaks smart collections
?>
<div class="Question">
<label for="allow_changes"><?php echo escape($lang["allowothersaddremove"]); ?></label>
<input
type="checkbox"
id="allow_changes"
name="allow_changes"
<?php if ($collection["allow_changes"] == 1) { ?>
checked
<?php } ?>
>
<div class="clearerleft"></div>
</div>
<?php
} else {
# allow changes by default
?>
<input type=hidden id="allow_changes" name="allow_changes" value="checked">
<?php
}
hook('additionalfields2');
hook('colleditformbottom');
if (file_exists("plugins/collection_edit.php")) {
include "plugins/collection_edit.php";
}
?>
<div class="QuestionSubmit">
<input name="save" type="submit" value="<?php echo escape($lang["save"]); ?>" />
<span id="pagesaved" style="display: none;" class="AutoSaveStatus"><?php echo escape($lang["saved"]); ?></span>
<?php if (getval("submitted", "") != "") { ?>
<script>
jQuery(document).ready(function (jQuery) {
jQuery('#pagesaved').show().fadeOut('slow');
});
</script>
<?php } ?>
</div>
</form>
<?php } ?>
</div>
<?php
if (getval("reload", "") == "true" && getval("ajax", "") != "") {
refresh_collection_frame();
}
include "../include/footer.php";

View File

@@ -0,0 +1,148 @@
<?php
include "../include/boot.php";
include "../include/authenticate.php";
include_once "../include/image_processing.php";
$ref = getval("ref", ($usercollection ?? 0), true);
$offset = getval("offset", 0, true);
$find = getval("find", "");
$col_order_by = getval("col_order_by", "name");
$order_by = getval("order_by", "");
$sort = getval("sort", "ASC");
# Fetch collection data
$collection_ref = $ref; // preserve collection id because tweaking resets $ref to resource ids
$collection = get_collection($ref);
if ($collection !== false) {
# Check access
if (!allow_multi_edit($collection_ref, $collection_ref)) {
exit(escape($lang["no_access_to_collection"]));
}
$resources = do_search("!collection" . $ref);
$colcount = count($resources);
if (getval("tweak", "") != "" && enforcePostRequest(false)) {
$tweak = getval("tweak", "");
switch ($tweak) {
case "rotateclock":
foreach ($resources as $resource) {
tweak_preview_images($resource['ref'], 270, 0, $resource["preview_extension"], -1, $resource['file_extension']);
}
$message = $lang["complete"];
break;
case "rotateanti":
foreach ($resources as $resource) {
tweak_preview_images($resource['ref'], 90, 0, $resource["preview_extension"], -1, $resource['file_extension']);
}
$message = $lang["complete"];
break;
case "gammaplus":
foreach ($resources as $resource) {
tweak_preview_images($resource['ref'], 0, 1.3, $resource["preview_extension"]);
}
$message = $lang["complete"];
break;
case "gammaminus":
foreach ($resources as $resource) {
tweak_preview_images($resource['ref'], 0, 0.7, $resource["preview_extension"]);
}
$message = $lang["complete"];
break;
case "restore":
if ($GLOBALS["offline_job_queue"]) {
foreach ($resources as $resource) {
$create_previews_job_data = [
'resource' => $resource['ref'],
'thumbonly' => false,
'extension' => $resource["file_extension"],
'previewonly' => false,
'previewbased' => false,
'alternative' => -1,
'ignoremaxsize' => true,
];
$create_previews_job_success_text = str_replace('%RESOURCE', $ref, $lang['jq_create_previews_success_text']);
$create_previews_job_failure_text = str_replace('%RESOURCE', $ref, $lang['jq_create_previews_failure_text']);
job_queue_add('create_previews', $create_previews_job_data, '', '', $create_previews_job_success_text, $create_previews_job_failure_text);
}
$message = $lang["recreatepreviews_pending"];
} elseif ($GLOBALS["enable_thumbnail_creation_on_upload"] === false || isset($GLOBALS["preview_generate_max_file_size"])) {
$params = array_merge(['i',RESOURCE_PREVIEWS_NONE], ps_param_fill(array_column($resources, "ref"), "i"));
ps_query("UPDATE resource SET has_image = ?, preview_attempts=0 WHERE ref IN (" . ps_param_insert(count($resources)) . ")", $params);
$message = $lang["recreatepreviews_pending"];
} else {
// No offline preview functionality enabled - to be created synchronously
foreach ($resources as $resource) {
$ingested = empty($resource['file_path']);
delete_previews($resource);
create_previews($resource['ref'], false, $resource["file_extension"], false, false, -1, true, $ingested);
$message = $lang["complete"];
}
}
$ref = $collection_ref; // restore collection id because tweaking resets $ref to resource ids
break;
}
set_processing_message(""); // Clear once complete or unread messages will hang around
refresh_collection_frame($collection_ref);
}
} else {
$message = $lang['error-collectionnotfound'];
}
include "../include/header.php";
?>
<div class="BasicsBox">
<h1><?php echo escape($lang["editresourcepreviews"]) ?></h1>
<p><?php echo text("introtext")?></p>
<?php if (isset($message)) { ?>
<div class="PageInformal"><?php echo escape($message); ?></div>
<?php
}
if ($collection) { ?>
<form
method=post
id="collectionform"
action="<?php echo $baseurl_short?>pages/collection_edit_previews.php"
>
<?php generateFormToken("collectionpreviewsform"); ?>
<input type=hidden value='<?php echo (int) $ref ?>' name="ref" id="ref"/>
<div class="Question">
<label><?php echo escape($lang["collection"]) ?></label>
<div class="Fixed"><?php echo escape(i18n_get_collection_name($collection)) ?></div>
<div class="clearerleft"></div>
</div>
<?php if (allow_multi_edit($resources, $ref)) { ?>
<div class="Question">
<label for="tweak">
<?php echo escape($lang["imagecorrection"])?>
<br/>
<?php echo escape($lang["previewthumbonly"])?>
</label>
<select class="stdwidth" name="tweak" id="tweak" onchange="return CentralSpacePost(this.form, true);">
<option value=""><?php echo escape($lang["select"])?></option>
<?php if (!$image_rotate_reverse_options) { ?>
<option value="rotateclock"><?php echo escape($lang["rotateclockwise"])?></option>
<option value="rotateanti"><?php echo escape($lang["rotateanticlockwise"])?></option>
<?php } else { ?>
<option value="rotateanti"><?php echo escape($lang["rotateclockwise"])?></option>
<option value="rotateclock"><?php echo escape($lang["rotateanticlockwise"])?></option>
<?php } ?>
<option value="gammaplus"><?php echo escape($lang["increasegamma"])?></option>
<option value="gammaminus"><?php echo escape($lang["decreasegamma"])?></option>
<option value="restore"><?php echo escape($lang["recreatepreviews"])?></option>
</select>
<div class="clearerleft"></div>
</div>
<?php } ?>
</form>
<?php
}
?>
</div>
<?php
include "../include/footer.php";

391
pages/collection_email.php Executable file
View File

@@ -0,0 +1,391 @@
<?php
include "../include/boot.php";
include "../include/authenticate.php";
$collection_url = getval("collection", "");
$find = getval('find', '');
$offset = getval("offset", 0, true);
$order_by = getval("order_by", "");
$sort = getval("sort", "");
$search = getval("search", "");
$ref = getval("ref", 0, true);
// Share options
$expires = getval("expires", "");
$access = getval("access", -1, true);
$group = getval("usergroup", 0, true);
$sharepwd = getval('sharepassword', '');
$collection = get_collection($ref);
if ($collection === false) {
error_alert($lang["error-collectionnotfound"], true, 403);
exit();
}
if ($collection["type"] == COLLECTION_TYPE_FEATURED) {
$collection_resources = get_collection_resources($collection["ref"]);
$collection["has_resources"] = (is_array($collection_resources) && !empty($collection_resources) ? 1 : 0);
}
// Check access controls
if (!collection_readable($ref)) {
exit($lang["no_access_to_collection"]);
} elseif (
$collection["type"] == COLLECTION_TYPE_FEATURED
&& !featured_collection_check_access_control((int) $collection["ref"])
&& !allow_featured_collection_share($collection)
) {
error_alert($lang["error-permissiondenied"], true, 403);
exit();
}
if (!$allow_share || checkperm("b")) {
error_alert($lang["error-permissiondenied"], true, 403);
exit();
}
$themeshare = false;
$themename = "";
$subthemes = (getval("subthemes", "true") != "false");
if (is_featured_collection_category($collection)) {
$themeshare = true;
$themename = i18n_get_translated($collection["name"]);
// Check this is not an empty FC category
if (empty(get_featured_collection_resources($collection, array("limit" => 1)))) {
error_alert($lang["cannotshareemptythemecategory"], true, 403);
exit();
}
// Further checks at collection-resource level. Recurse through category's sub FCs
if ($subthemes) {
$sub_fcs = get_featured_collection_categ_sub_fcs($collection);
} else {
$sub_fcs = get_featured_collections($collection["ref"], array());
$sub_fcs = array_filter($sub_fcs, function ($fc) {
return !is_featured_collection_category($fc);
});
$sub_fcs = array_values(array_column($sub_fcs, "ref"));
}
$collection["sub_fcs"] = $sub_fcs;
$collectionstates = false;
$sub_fcs_resources_states = array();
$sub_fcs_resources_minaccess = array();
foreach ($collection["sub_fcs"] as $sub_fc) {
// Check all featured collections contain only active resources
$collectionstates = is_collection_approved($sub_fc);
if (!$collection_allow_not_approved_share && $collectionstates === false) {
break;
} elseif (is_array($collectionstates)) {
$sub_fcs_resources_states = array_unique(array_merge($sub_fcs_resources_states, $collectionstates));
}
// Check minimum access is restricted or lower and sharing of restricted resources is not allowed
$sub_fcs_resources_minaccess[] = collection_min_access($sub_fc);
}
$collectionstates = (!empty($sub_fcs_resources_states) ? $sub_fcs_resources_states : $collectionstates);
if (!empty($sub_fcs_resources_minaccess)) {
$minaccess = max(array_unique($sub_fcs_resources_minaccess));
}
}
$collectionstates = (isset($collectionstates) ? $collectionstates : is_collection_approved($ref));
if (!$collection_allow_not_approved_share && !$collectionstates) {
$show_error = true;
$error = $lang["notapprovedsharecollection"];
}
# Minimum access is restricted or lower and sharing of restricted resources is not allowed. The user cannot share this collection.
$minaccess = (isset($minaccess) ? $minaccess : collection_min_access($ref));
if (!$restricted_share && $minaccess >= RESOURCE_ACCESS_RESTRICTED) {
$show_error = true;
$error = $lang["restrictedsharecollection"];
}
if (isset($show_error)) { ?>
<script type="text/javascript">
alert('<?php echo escape($error); ?>');
history.go(-1);
</script>
<?php
exit();
}
$internal_share_only = checkperm("noex") || (isset($user_dl_limit) && intval($user_dl_limit) > 0);
// Legacy way of working when sharing a FC category. It relies on a list of collections
$ref = ($themeshare ? join(",", array_merge(array($collection["ref"]), $collection["sub_fcs"])) : $ref);
$errors = "";
if (getval("save", "") != "" && enforcePostRequest(getval("ajax", false))) {
# Email / share collection
# Build a new list and insert
$users = getval("users", "");
$message = getval("message", "");
$add_internal_access = (getval("grant_internal_access", "") != "");
$feedback = getval("request_feedback", "");
if ($feedback == "") {
$feedback = false;
} else {
$feedback = true;
}
$list_recipients = getval("list_recipients", "");
if ($list_recipients == "") {
$list_recipients = false;
} else {
$list_recipients = true;
}
$user_email = "";
$from_name = $userfullname;
if (getval("ccme", false)) {
$cc = $useremail;
} else {
$cc = "";
}
enforceSharePassword($sharepwd);
$errors = email_collection($ref, i18n_get_collection_name($collection), $userfullname, $users, $message, $feedback, $access, $expires, $user_email, $from_name, $cc, $themeshare, $themename, "?parent=" . $collection["ref"], $list_recipients, $add_internal_access, $group, $sharepwd);
if ($errors == "") {
# Log this
// fix for bomb on multiple collections, daily stat object ref must be a single number.
$crefs = explode(",", $ref);
foreach ($crefs as $cref) {
daily_stat("E-mailed collection", $cref);
}
if (!hook("replacecollectionemailredirect")) {
redirect($baseurl_short . "pages/done.php?text=collection_email");
}
}
}
include "../include/header.php";
?>
<div class="BasicsBox">
<h1>
<?php if ($themeshare) {
echo escape($lang["email_theme_category"]);
} else {
echo escape($lang["emailcollectiontitle"]);
} ?>
</h1>
<?php
$link_array = array(
"ref" => $collection["ref"],
"search" => $search,
"offset" => $offset,
"order_by" => $order_by,
"sort" => $sort,
"collection" => $collection_url,
"find" => $find,
"k" => $k
);
$link_back = generateURL($baseurl . "/pages/collection_share.php", $link_array);
?>
<p>
<a onClick="return CentralSpaceLoad(this,true);" href="<?php echo $link_back ?>">
<?php echo LINK_CARET_BACK . escape($lang["backtosharecollection"]); ?>
</a>
</p>
<p>
<?php
if ($themeshare && text("introtextthemeshare") != "") {
echo text("introtextthemeshare");
} else {
echo text("introtext");
}
render_help_link("user/sharing-resources");
?>
</p>
<form
name="collectionform"
method=post
id="collectionform"
action="<?php echo $baseurl_short?>pages/collection_email.php?catshare=<?php echo $themeshare ? 'true' : 'false'; ?>"
>
<input type=hidden name=redirect id=redirect value=yes>
<input type=hidden name=ref id="ref" value="<?php echo escape($collection["ref"]); ?>">
<?php
generateFormToken("collectionform");
if ($themeshare) {
?>
<div class="Question">
<label for="subthemes"><?php echo escape($lang["share_theme_category_subcategories"]); ?></label>
<input type="checkbox" id="subthemes" name="subthemes" value="true" <?php echo $subthemes ? "checked" : ""; ?>>
<div class="clearerleft"></div>
</div>
<?php
} else {
?>
<div class="Question">
<label>
<?php if ($themeshare) {
echo escape($lang["themes"]);
} else {
echo escape($lang["collectionname"]);
} ?>
</label>
<div class="Fixed">
<?php
if (!$themeshare) {
echo i18n_get_collection_name($collection);
} else { ## this select copied from collections.php
?>
<select
name="collection"
multiple
size="10"
class="stdwidth MultiSelect"
style="height:100%;"
onchange="document.getElementById('ref').value = getSelected(this);"
>
<?php
$list = get_user_collections($userref);
$found = false;
for ($n = 0; $n < count($list); $n++) { ?>
<option
value="<?php echo $list[$n]["ref"]; ?>"
<?php if ($ref == $list[$n]["ref"]) { ?>
selected
<?php
$found = true;
} ?>
>
<?php echo i18n_get_collection_name($list[$n]); ?>
</option>
<?php
}
if (!$found) {
# Add this one at the end, it can't be found
$notfound = get_collection($ref);
if ($notfound !== false) {
?>
<option value="<?php echo urlencode($ref) ?>" selected><?php echo $notfound["name"]; ?></option>
<?php
}
}
?>
</select>
<?php
} ?>
</div>
<div class="clearerleft"></div>
</div>
<?php
}
?>
<div class="Question">
<label for="message"><?php echo escape($lang["message"]); ?></label>
<textarea class="stdwidth" rows=6 cols=50 name="message" id="message"></textarea>
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="users">
<?php echo strip_tags_and_attributes($internal_share_only ? $lang["emailtousers_internal"] : $lang["emailtousers"]); ?>
</label>
<?php
$userstring = getval("users", "");
include "../include/user_select.php";
?>
<div class="clearerleft"></div>
<?php if ($errors != "") { ?>
<div class="FormError">!! <?php echo $errors?> !!</div>
<?php } ?>
</div>
<?php if ($list_recipients) { ?>
<div class="Question">
<label for="list_recipients"><?php echo escape($lang["list-recipients-label"]); ?></label>
<input type=checkbox id="list_recipients" name="list_recipients">
<div class="clearerleft"></div>
</div>
<?php } ?>
<?php
$allow_edit = allow_multi_edit($ref);
if ($allow_edit) { ?>
<div class="Question">
<label for="grant_internal_access"><?php echo escape($lang["internal_share_grant_access"]); ?></label>
<input type=checkbox id="grant_internal_access" name="grant_internal_access" onclick="if(this.checked){jQuery('#question_internal_access').slideDown();}else{jQuery('#question_internal_access').slideUp()};">
<div class="clearerleft"></div>
</div>
<?php
}
if (!$internal_share_only) {
$shareoptions = array(
"password" => $sharepwd != "",
"editaccesslevel" => $access,
"editexpiration" => $expires,
"editgroup" => $group,
);
render_share_options($shareoptions);
}
if ($collection["user"] == $userref) { # Collection owner can request feedback.
?>
<div class="Question">
<label for="request_feedback"><?php echo strip_tags_and_attributes($lang["requestfeedback"]); ?></label>
<input type=checkbox id="request_feedback" name="request_feedback" value="yes">
<div class="clearerleft"></div>
</div>
<?php
}
if ($cc_me && $useremail != "") {
?>
<div class="Question">
<label for="ccme"><?php echo escape(str_replace("%emailaddress", $useremail, $lang["cc-emailaddress"])); ?></label>
<input type=checkbox checked id="ccme" name="ccme">
<div class="clearerleft"></div>
</div>
<?php
}
hook("additionalemailfield");
?>
<div class="QuestionSubmit">
<input
name="save"
type="submit"
onclick="<?php
if ($share_password_required) {
echo 'if (!enforceSharePassword(\'' . escape($lang['share-password-not-set']) . '\')) { return false; }; ';
} ?>"
value="<?php
if ($themeshare) {
echo escape($lang["email_theme_category"]);
} else {
echo escape($lang["emailcollectiontitle"]);
} ?>"
/>
</div>
</form>
</div>
<?php include "../include/footer.php";
?>

203
pages/collection_feedback.php Executable file
View File

@@ -0,0 +1,203 @@
<?php
include "../include/boot.php";
# External access support (authenticate only if no key provided, or if invalid access key provided)
$k = getval("k", "");
if (($k == "") || (!check_access_key_collection(getval("collection", "", true), $k))) {
include "../include/authenticate.php";
}
$collection = getval("collection", "", true);
$errors = "";
$done = false;
# Fetch collection data
$cinfo = get_collection($collection);
if ($cinfo === false) {
exit("Collection not found.");
}
# Check access
if (!collection_readable($collection)) {
exit($lang["no_access_to_collection"]);
}
if (!$cinfo["request_feedback"]) {
exit("Access denied.");
}
# Check that comments have been added.
$comments = get_collection_comments($collection);
global $internal_share_access, $userfullname;
if (
$collection_commenting
&& ($k == '' || $internal_share_access)
&& count($comments) == 0
&& !$feedback_resource_select
) {
$errors = $lang["feedbacknocomments"];
}
$comment = "";
if (getval("save", "") != "" && enforcePostRequest(false)) {
# Save comment
if (empty($userfullname) && $k !== '') {
$userfullname = getval('name', '');
}
$comment = trim(getval("comment", ""));
$saveerrors = send_collection_feedback($collection, $comment);
if (is_array($saveerrors)) {
foreach ($saveerrors as $saveerror) {
if ($errors == "") {
$errors = $saveerror;
} else {
$errors .= "<br /><br /> " . $saveerror;
}
}
} else {
# Stay on this page for external access users (no access to search)
refresh_collection_frame();
$done = true;
}
}
$headerinsert .= "<script src=\"../lib/lightbox/js/lightbox.min.js\" type=\"text/javascript\"></script>";
$headerinsert .= "<link type=\"text/css\" href=\"../lib/lightbox/css/lightbox.min.css?css_reload_key=" . $css_reload_key . "\" rel=\"stylesheet\">";
include "../include/header.php";
if ($errors != "") {
echo "<script>alert('" . str_replace(array("<br />","<br/>","<br />"), "\\n\\n", $errors) . "');</script>";
}
?>
<div class="BasicsBox">
<h1><?php echo escape($lang["sendfeedback"])?></h1>
<?php if ($done) { ?>
<p><?php echo escape($lang["feedbacksent"])?></p>
<?php } else { ?>
<form method="post" action="<?php echo $baseurl_short?>pages/collection_feedback.php">
<?php generateFormToken("collection_feedback"); ?>
<input type="hidden" name="k" value="<?php echo escape($k); ?>">
<input type="hidden" name="collection" value="<?php echo escape($collection); ?>">
<p>
<a
class="downloadcollection"
href="<?php echo $baseurl_short?>pages/collection_download.php?collection=<?php echo urlencode($collection)?>&k=<?php echo urlencode($k)?>"
onclick="return CentralSpaceLoad(this,true);"
>
<?php echo LINK_CARET . escape($lang["download_collection"]); ?>
</a>
</p>
<?php if ($feedback_resource_select) { ?>
<h2><?php echo escape($lang["selectedresources"])?>:</h2>
<?php
# Show thumbnails and allow the user to select resources.
$result = do_search("!collection" . $collection, "", "resourceid", 0, -1, "desc");
for ($n = 0; $n < count($result); $n++) {
$ref = $result[$n]["ref"];
$access = get_resource_access($ref);
$use_watermark = check_use_watermark();
$title = $ref . " : " . escape(tidy_trim(i18n_get_translated($result[$n]["field" . $view_title_field]), 60));
if (isset($collection_feedback_display_field)) {
$displaytitle = escape(get_data_by_field($ref, $collection_feedback_display_field));
} else {
$displaytitle = $title;
}
?>
<!--Resource Panel-->
<div class="ResourcePanelShell" id="ResourceShell<?php echo urlencode($ref)?>">
<div class="ResourcePanel">
<table border="0" class="ResourceAlign">
<tr>
<td>
<?php
if ($result[$n]["has_image"] == 1) {
$path = get_resource_path($ref, true, "scr", false, $result[$n]["preview_extension"], -1, 1, $use_watermark, $result[$n]["file_modified"]);
if (file_exists($path)) {
# Use 'scr' path
$path = get_resource_path($ref, false, "scr", false, $result[$n]["preview_extension"], -1, 1, $use_watermark, $result[$n]["file_modified"]);
} elseif (!file_exists($path)) {
# Attempt original file if jpeg
$path = get_resource_path($ref, false, "", false, $result[$n]["preview_extension"], -1, 1, $use_watermark, $result[$n]["file_modified"]);
}
?>
<a class="lightbox-feedback" href="<?php echo escape($path)?>" title="<?php echo escape($displaytitle); ?>">
<img
alt="<?php echo escape(i18n_get_translated($result[$n]['field' . $view_title_field] ?? "")); ?>"
width="<?php echo (int) $result[$n]["thumb_width"]; ?>"
height="<?php echo (int) $result[$n]["thumb_height"]; ?>"
src="<?php echo escape(get_resource_path($ref, false, "thm", false, $result[$n]["preview_extension"], -1, 1, (checkperm("w") || ($k != "" && $watermark !== "")) && $access == 1, $result[$n]["file_modified"]))?>"
class="ImageBorder"
>
</a>
<?php
} else {
echo get_nopreview_html((string) $result[$n]["file_extension"], $result[$n]["resource_type"]);
}
?>
</td>
</tr>
</table>
<span class="ResourceSelect">
<input type="checkbox" name="select_<?php echo urlencode($ref) ?>" value="yes">
</span>
<div class="ResourcePanelInfo"><?php echo escape($displaytitle) ?>&nbsp;</div>
<div class="clearer"></div>
</div>
</div>
<?php
}
?>
<div class="clearer"></div>
<?php
}
?>
<div class="Question">
<?php if ($errors != "") { ?>
<div class="FormError"><?php echo $errors?></div>
<?php } ?>
<label for="comment"><?php echo escape($lang["message"])?></label>
<textarea class="stdwidth" style="width:450px;" rows=20 cols=80 name="comment" id="comment"><?php echo escape($comment) ?></textarea>
<div class="clearerleft"></div>
</div>
<?php if (!isset($userfullname)) {
# For external users, ask for their name/e-mail in case this has been passed to several users.
?>
<div class="Question">
<label for="name"><?php echo escape($lang["yourname"]); ?></label>
<input type="text" class="stdwidth" name="name" id="name" value="<?php echo escape(getval("name", "")); ?>">
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="email"><?php echo escape($lang["youremailaddress"]); ?> *</label>
<input type="text" class="stdwidth" name="email" id="email" value="<?php echo escape(getval("email", "")); ?>">
<div class="clearerleft"></div>
</div>
<?php
}
?>
<div class="QuestionSubmit">
<input name="save" type="submit" value="<?php echo escape($lang["send"])?>" />
</div>
</form>
<?php } ?>
</div>
<?php
if ($feedback_resource_select) {
addLightBox('.lightbox-feedback');
}
include "../include/footer.php";
?>

158
pages/collection_log.php Normal file
View File

@@ -0,0 +1,158 @@
<?php
include "../include/boot.php";
include "../include/authenticate.php";
$offset = getval("offset", 0, true);
$ref = getval("ref", "", true);
# Check access
if (!collection_readable($ref)) {
exit($lang["no_access_to_collection"]);
}
if ((!is_numeric($offset)) || ($offset < 0)) {
$offset = 0;
}
# pager
$per_page = getval("per_page_list_log", 15);
rs_setcookie('per_page_list_log', $per_page);
include "../include/header.php";
$log = get_collection_log($ref, $offset + $per_page);
$results = $log["total"];
$log = $log["data"];
$totalpages = ceil($results / $per_page);
$curpage = floor($offset / $per_page) + 1;
$url = $baseurl . "/pages/collection_log.php?ref=" . $ref;
$jumpcount = 1;
# Fetch and translate collection name
$colinfo = get_collection($ref);
$colname = i18n_get_collection_name($colinfo);
if (!checkperm("b")) {
# Add selection link to collection name.
$colname = "<a href=\"" . $baseurl_short . "pages/collections.php?collection=" . $ref . "\" onClick=\"return CollectionDivLoad(this);\">" . $colname . "</a>";
}
?>
<div class="BasicsBox">
<h1>
<?php
echo str_replace("%collection", $colname, escape($lang["collectionlogheader"]));
render_help_link("user/collection-options");
?>
</h1>
<?php
$intro = text("introtext");
if ($intro != "") {
?>
<p><?php echo $intro ?></p>
<?php
}
?>
<div class="TopInpageNav">
<div class="InpageNavLeftBlock">
<?php echo escape($lang["resultsdisplay"]); ?>:
<?php
for ($n = 0; $n < count($list_display_array); $n++) {
if ($per_page == $list_display_array[$n]) {
?>
<span class="Selected"><?php echo $list_display_array[$n]; ?></span>
<?php
} else {
?>
<a onClick="return CentralSpaceLoad(this,true);" href="<?php echo $url; ?>&per_page_list_log=<?php echo $list_display_array[$n]; ?>">
<?php echo $list_display_array[$n]; ?>
</a>
<?php
} ?>&nbsp;|
<?php }
if ($per_page == 99999) {
?>
<span class="Selected"><?php echo escape($lang["all"]); ?></span>
<?php
} else {
?>
<a onClick="return CentralSpaceLoad(this,true);" href="<?php echo $url; ?>&per_page_list_log=99999">
<?php echo escape($lang["all"]); ?>
</a>
<?php
} ?>
</div>
<?php pager(false); ?>
</div>
<div class="Listview">
<table class="ListviewStyle">
<!--Title row-->
<tr class="ListviewTitleStyle">
<th><?php echo escape($lang["date"]); ?></th>
<th><?php echo escape($lang["user"]); ?></th>
<th><?php echo escape($lang["action"]); ?></th>
<th><?php echo escape($lang["resourceid"]); ?></th>
<th>
<?php
$field = get_fields(array($view_title_field));
if (!empty($field[0]["title"])) {
echo lang_or_i18n_get_translated($field[0]["title"], "fieldtitle-");
}
?>
</th>
<?php hook("log_extra_columns_header"); ?>
</tr>
<?php
for ($n = $offset; (($n < count($log)) && ($n < ($offset + $per_page))); $n++) {
if (!isset($lang["collectionlog-" . $log[$n]["type"]])) {
$lang["collectionlog-" . $log[$n]["type"]] = "";
}
?>
<!--List Item-->
<tr>
<td><?php echo escape(nicedate($log[$n]["date"], true, true, true)) ?></td>
<td><?php echo escape((string) $log[$n]["fullname"])?></td>
<td>
<?php
echo escape($lang["collectionlog-" . $log[$n]["type"]]) ;
if ($log[$n]["notes"] != "") {
## notes field contains user IDs, collection references and /or standard texts
## Translate the standard texts
$standard = array('#all_users', '#new_resource');
$translated = array($lang["all_users"], $lang["new_resource"]);
$newnotes = " - " . str_replace($standard, $translated, $log[$n]["notes"]);
echo escape($newnotes);
}
?>
</td>
<td>
<?php if ($log[$n]['resource'] != 0) { ?>
<a onClick="return CentralSpaceLoad(this,true);" href='<?php echo $baseurl_short?>pages/view.php?ref=<?php echo urlencode($log[$n]["resource"]) ?>'>
<?php echo $log[$n]["resource"]; ?>
</a>
<?php } ?>
</td>
<td>
<?php if ($log[$n]['resource'] != 0) { ?>
<a onClick="return CentralSpaceLoad(this,true);" href='<?php echo $baseurl_short?>pages/view.php?ref=<?php echo urlencode($log[$n]["resource"]) ?>'>
<?php echo i18n_get_translated($log[$n]["title"])?>
</a>
<?php } ?>
</td>
<?php hook("log_extra_columns_row", "", array($log[$n], $colinfo)); ?>
</tr>
<?php } ?>
</table>
</div> <!-- End of Listview -->
<div class="BottomInpageNav"><?php pager(false); ?></div>
</div> <!-- End of BasicsBox -->
<?php
include "../include/footer.php";
?>

797
pages/collection_manage.php Executable file
View File

@@ -0,0 +1,797 @@
<?php
include "../include/boot.php";
include "../include/authenticate.php";
if (checkperm("b")) {
exit("Permission denied");
}
$k = getval("k", "");
$offset = getval("offset", 0, true);
$find = getval("find", getval("saved_find", ""));
rs_setcookie('saved_find', $find);
$col_order_by = getval("col_order_by", getval("saved_col_order_by", "created"));
rs_setcookie('saved_col_order_by', $col_order_by);
$sort = getval('sort', getval('saved_col_sort', 'ASC', false, 'validate_sort_value'), false, 'validate_sort_value');
rs_setcookie('saved_col_sort', $sort);
$revsort = ($sort == "ASC") ? "DESC" : "ASC";
# pager
$per_page = getval("per_page_list", $default_perpage_list, true);
rs_setcookie('per_page_list', $per_page);
$collection_valid_order_bys = array("fullname","name","ref","count","type");
$modified_collection_valid_order_bys = hook("modifycollectionvalidorderbys");
if ($modified_collection_valid_order_bys) {
$collection_valid_order_bys = $modified_collection_valid_order_bys;
}
if (!in_array($col_order_by, $collection_valid_order_bys)) {
$col_order_by = "created";
} # Check the value is one of the valid values (SQL injection filter)
if (array_key_exists("find", $_POST)) {
$offset = 0;
} # reset page counter when posting
$name = getval('name', '');
if ('' != $name && can_create_collections() && enforcePostRequest(false)) {
// Create new collection
$new = create_collection($userref, $name);
$redirect_url = "pages/collection_edit.php?ref={$new}&reload=true";
// This is used to create featured collections directly from the featured collections page
if ($enable_themes && getval("call_to_action_tile", "") === "true" && checkperm("h")) {
$parent = (int) getval("parent", 0, true);
$coldata = array(
"name" => $name,
"featured_collections_changes" => array(
"update_parent" => $parent,
"force_featured_collection_type" => true,
"thumbnail_selection_method" => $FEATURED_COLLECTION_BG_IMG_SELECTION_OPTIONS["most_popular_image"],
),
);
$redirect_params = ($parent == 0 ? array() : array("parent" => $parent));
$redirect_url = generateURL("{$baseurl_short}pages/collections_featured.php", $redirect_params);
save_collection($new, $coldata);
}
set_user_collection($userref, $new);
daily_stat('New collection', $userref);
redirect($redirect_url);
}
$delete_collections = array();
if (getval("delete", "") != "") {
$delete_cols = explode(',', getval("delete", ""));
foreach ($delete_cols as $col_ref) {
$delete_collections[] = $col_ref;
}
}
foreach ($delete_collections as $delete) {
if ($delete != '' && enforcePostRequest(getval("ajax", false))) {
// Check user is actually allowed to delete the collection first
$collection_data = get_collection($delete);
if (!is_array($collection_data) || !can_delete_collection($collection_data, $userref, $k)) {
header('HTTP/1.1 401 Unauthorized');
die('Permission denied!');
}
# Delete collection
delete_collection($collection_data);
# Get count of collections
$c = get_user_collections($userref);
# If the user has just deleted the collection they were using, select a new collection
if ($usercollection == $delete && count($c) > 0) {
# Select the first collection in the dropdown box.
$usercollection = $c[0]["ref"];
set_user_collection($userref, $usercollection);
}
# User has deleted their last collection? add a new one.
if (count($c) == 0) {
# No collections to select. Create them a new collection.
$usercollection = create_collection($userref, "Default Collection");
set_user_collection($userref, $usercollection);
}
# To update the page only when all collections have been deleted, remove from the array those already processed.
$id_col_deleted = array_search($delete, $delete_collections);
if ($id_col_deleted !== false) {
unset($delete_collections[$id_col_deleted]);
}
if (getval('ajax', '') !== '' && getval('dropdown_actions', '') !== '' && count($delete_collections) == 0) {
$response = array(
'success' => 'Yes',
'redirect_to_collection' => $usercollection,
'k' => getval('k', ''),
'nc' => time()
);
echo json_encode($response);
exit();
}
}
}
refresh_collection_frame($usercollection);
$removeall = getval("removeall", "");
if ($removeall != "" && enforcePostRequest(false)) {
remove_all_resources_from_collection($removeall);
refresh_collection_frame($usercollection);
}
$remove = getval("remove", "");
if ($remove != "" && enforcePostRequest(false)) {
# Remove someone else's collection from your My Collections
remove_collection($userref, $remove);
# Get count of collections
$c = get_user_collections($userref);
# If the user has just removed the collection they were using, select a new collection
if ($usercollection == $remove && count($c) > 0) {
# Select the first collection in the dropdown box.
$usercollection = $c[0]["ref"];
set_user_collection($userref, $usercollection);
}
refresh_collection_frame();
}
$add = getval("add", "");
if ($add != "" && enforcePostRequest(false)) {
# Add someone else's collection to your My Collections
add_collection($userref, $add);
set_user_collection($userref, $add);
refresh_collection_frame();
# Log this
daily_stat("Add public collection", $userref);
}
$reload = getval("reload", "");
if ($reload != "") {
# Refresh the collection frame (just edited a collection)
refresh_collection_frame();
}
$purge = getval("purge", "");
$deleteall = getval("deleteall", "");
if (($purge != "" || $deleteall != "") && enforcePostRequest(false)) {
if ($purge != "") {
$deletecollection = $purge;
}
if ($deleteall != "") {
$deletecollection = $deleteall;
}
# Delete all resources in collection
if (!checkperm("D")) {
$resources = do_search("!collection" . $deletecollection);
for ($n = 0; $n < count($resources); $n++) {
if (checkperm("e" . $resources[$n]["archive"])) {
delete_resource($resources[$n]["ref"]);
collection_log($deletecollection, "D", $resources[$n]["ref"]);
}
}
}
if ($purge != "") {
# Delete collection
delete_collection($purge);
# Get count of collections
$c = get_user_collections($userref);
# If the user has just deleted the collection they were using, select a new collection
if ($usercollection == $purge && count($c) > 0) {
# Select the first collection in the dropdown box.
$usercollection = $c[0]["ref"];
set_user_collection($userref, $usercollection);
}
# User has deleted their last collection? add a new one.
if (count($c) == 0) {
# No collections to select. Create them a new collection.
$usercollection = create_collection($userref, "Default Collection");
set_user_collection($userref, $usercollection);
}
}
refresh_collection_frame($usercollection);
}
$deleteempty = getval("deleteempty", "");
if ($deleteempty != "" && enforcePostRequest(false)) {
$collections = get_user_collections($userref);
$deleted_usercoll = false;
for ($n = 0; $n < count($collections); $n++) {
// if count is zero and not Default Collection and collection is owned by user:
if ($collections[$n]['count'] == 0 && $collections[$n]['cant_delete'] != 1 && $collections[$n]['user'] == $userref) {
delete_collection($collections[$n]['ref']);
if ($collections[$n]['ref'] == $usercollection) {
$deleted_usercoll = true;
}
}
}
# Get count of collections
$c = get_user_collections($userref);
# If the user has just deleted the collection they were using, select a new collection
if ($deleted_usercoll && count($c) > 0) {
# Select the first collection in the dropdown box.
$usercollection = $c[0]["ref"];
set_user_collection($userref, $usercollection);
}
# User has deleted their last collection? add a new one.
if (count($c) == 0) {
# No collections to select. Create them a new collection.
$usercollection = create_collection($userref, "Default Collection");
set_user_collection($userref, $usercollection);
}
refresh_collection_frame($usercollection);
}
$removeall = getval("removeall", "");
if ($removeall != "" && enforcePostRequest(false)) {
remove_all_resources_from_collection($removeall);
refresh_collection_frame($usercollection);
}
include "../include/header.php";
?>
<div class="BasicsBox">
<h1><?php echo escape($lang["managemycollections"])?></h1>
<p class="tight">
<?php
echo text("introtext");
render_help_link("collections-public-and-themes");
?>
</p>
<br />
<div class="BasicsBox">
<form method="post" action="<?php echo $baseurl_short?>pages/collection_manage.php">
<?php generateFormToken("find"); ?>
<div class="Question">
<div class="tickset">
<div class="Inline">
<input type=text name="find" id="find" value="<?php echo escape(unescape($find)); ?>" maxlength="100" class="shrtwidth" />
</div>
<div class="Inline">
<input name="Submit" type="submit" value="<?php echo escape($lang["searchbutton"]); ?>" />
</div>
<div class="Inline">
<input name="Clear" type="button" onclick="document.getElementById('find').value='';submit();" value="<?php echo escape($lang["clearbutton"]); ?>" />
</div>
</div>
<div class="clearerleft"></div>
</div>
</form>
</div>
<?php
$collections = get_user_collections($userref, $find, $col_order_by, $sort);
$modified_collections = hook("modified_collections", "", array($userref,$find,$col_order_by,$sort));
if (!empty($modified_collections)) {
$collections = $modified_collections;
}
$results = count($collections);
$totalpages = ceil($results / $per_page);
$curpage = floor($offset / $per_page) + 1;
$jumpcount = 1;
# Create an a-z index
$atoz = "<div class=\"InpageNavLeftBlock\">";
if ($find == "") {
$atoz .= "<span class='Selected'>";
}
$atoz .= "<a href=\"" . $baseurl_short . "pages/collection_manage.php?col_order_by=name&find=\" onClick=\"return CentralSpaceLoad(this);\">" . $lang["viewall"] . "</a>";
if ($find == "") {
$atoz .= "</span>";
}
$atoz .= "&nbsp;&nbsp;&nbsp;&nbsp;";
for ($n = ord("A"); $n <= ord("Z"); $n++) {
if ($find == chr($n)) {
$atoz .= "<span class='Selected'>";
}
$atoz .= "<a href=\"" . $baseurl_short . "pages/collection_manage.php?col_order_by=name&find=" . chr($n) . "\" onClick=\"return CentralSpaceLoad(this);\">&nbsp;" . chr($n) . "&nbsp;</a> ";
if ($find == chr($n)) {
$atoz .= "</span>";
}
$atoz .= " ";
}
$atoz .= "</div>";
$url = $baseurl_short . "pages/collection_manage.php?paging=true&col_order_by=" . urlencode($col_order_by) . "&sort=" . urlencode($sort) . "&find=" . urlencode($find) . "";
?>
<div class="TopInpageNav">
<div class="TopInpageNavLeft">
<?php echo $atoz; ?>
<div class="InpageNavLeftBlock">
<?php echo escape($lang["resultsdisplay"]); ?>:
<?php
for ($n = 0; $n < count($list_display_array); $n++) {
if ($per_page == $list_display_array[$n]) {
?>
<span class="Selected"><?php echo escape($list_display_array[$n]) ?></span>
<?php
} else {
?>
<a href="<?php echo $url; ?>&per_page_list=<?php echo urlencode($list_display_array[$n])?>" onclick="return CentralSpaceLoad(this);">
<?php echo escape($list_display_array[$n]); ?>
</a>
<?php
} ?>&nbsp;|
<?php
}
if ($per_page == 99999) {
?>
<span class="Selected"><?php echo escape($lang["all"])?></span>
<?php
} else {
?>
<a href="<?php echo $url; ?>&per_page_list=99999" onclick="return CentralSpaceLoad(this);">
<?php echo escape($lang["all"]); ?>
</a>
<?php
}
?>
</div>
</div>
<?php pager(false, true, array("confirm_page_change" => "return promptBeforePaging();")); ?>
<div class="clearerleft"></div>
</div>
<script>
function check_delete_all(select_all) {
var check_value = select_all.checked;
var all_checkboxes = document.getElementsByClassName("check_delete");
for (var i = 0; i < all_checkboxes.length; i++) {
all_checkboxes[i].checked = check_value;
}
show_delete();
}
function show_delete() {
var display_opt = "hidden";
var all_checkboxes = document.getElementsByClassName("check_delete");
for (var i = 0; i < all_checkboxes.length; i++) {
if (all_checkboxes[i].checked == true) {
display_opt = "visible";
break;
}
}
document.getElementById("collection_delete").style.visibility = display_opt;
}
function delete_collections() {
var all_checkboxes = document.getElementsByClassName("check_delete");
var to_delete = "";
for (var i = 0; i < all_checkboxes.length; i++) {
if (all_checkboxes[i].checked == true) {
if (to_delete != "") {
to_delete += ",";
}
to_delete += all_checkboxes[i].value;
}
}
if (to_delete != "") {
if (confirm('<?php echo escape($lang["delete_multiple_collections"]) ?>')) {
var post_data = {
ajax: true,
dropdown_actions: true,
delete: to_delete,
<?php echo generateAjaxToken("delete_collection"); ?>
};
jQuery.post('<?php echo $baseurl; ?>/pages/collection_manage.php', post_data, function(response) {
if (response.success === 'Yes') {
CollectionDivLoad('<?php echo $baseurl; ?>/pages/collections.php?collection=' + response.redirect_to_collection + '&k=' + response.k + '&nc=' + response.nc);
CentralSpaceLoad(document.URL);
}
}, 'json');
}
}
}
jQuery(document).ready(function() {
var collection_starting = null; // Regular click collection marks the start of a range
var collection_ending = null; // Shifted click collection marks the end of a range
var primary_action = null;
// Process the clicked box
jQuery(".check_delete").click(function(e) {
var collection_selections = [];
var input = e.target;
var box_collection = jQuery(input).prop("value");
var box_checked = jQuery(input).prop("checked");
if (!e.shiftKey) {
// Regular click; note the action required if there is a range to be processed
primary_action = box_checked;
collection_starting = box_collection;
collection_ending = null;
} else {
if (!collection_starting) {
styledalert('<?php echo escape($lang["range_no_start_header"]); ?>', '<?php echo escape($lang["range_no_start"]); ?>');
if (jQuery(input).prop("checked")) {
this.removeAttribute("checked");
} else {
this.setAttribute("checked", "checked");
}
return false;
}
collection_ending = box_collection; // Shifted click collection
}
// Process all clicked boxes
jQuery(".check_delete").each(function() {
// Fetch the event and store it in the selection array
var toggle_event = jQuery.Event("click", { target: this });
var toggle_input = toggle_event.target;
var box_collection = jQuery(toggle_input).prop("value");
var box_checked = jQuery(toggle_input).prop("checked");
collection_selections.push({box_collection: box_collection, box_checked: box_checked});
});
// Process collections within a clicked range
var res_list = [];
if (collection_starting && collection_ending) {
console.log("PROCESS " + collection_starting + " TO " + collection_ending);
var found_start = false;
var found_end = false;
for (i = 0; i < collection_selections.length; i++) {
if (collection_selections[i].box_collection == collection_starting) {
// Range starting point is being processed; skip because already processed by single shot; move on
found_start = true;
} else if (collection_selections[i].box_collection == collection_ending) {
// Range ending point is being processed; process it and move on (because it may be before the startin point)
found_end = true;
res_list.push(collection_selections[i].box_collection); // collection to process
} else {
// Element is not at the starting point or ending point; check whether its within the range
if ( !found_start && !found_end ) {
// Range is not yet being processed; skip
} else if (found_start && found_end) {
// Both starting and ending points have been processed; quit loop
break;
} else {
// Process the element within the range
res_list.push(collection_selections[i].box_collection); // collection to process
}
}
}
collection_selections.forEach(function (collection) {
if (res_list.includes(collection.box_collection)) {
jQuery("#check_" + collection.box_collection).prop('checked', true);
}
});
// Reset processing points
collection_starting = null;
collection_ending = null;
primary_action = null;
} else if (collection_starting) {
console.log("PROCESS " + collection_starting + " ONLY");
} else if (collection_ending) {
console.log("ERROR - ENDING ONLY");
}
console.log("collection_LIST\n" + JSON.stringify(res_list));
});
// Load collection actions when dropdown is clicked
jQuery('.collectionactions').on("mouseover", function(e) {
var el = jQuery(this);
if (el.attr('data-actions-populating') != '0') {
return false
}
el.attr('data-actions-populating','1');
var action_selection_id = el.attr('id');
var colref = el.attr('data-col-id');
LoadActions('collections',action_selection_id,'collection',colref);
});
});
// Add confirmation message to advise selected collections will be cleared on paging.
function promptBeforePaging() {
if (document.getElementById("collection_delete").style.visibility == "visible") {
$proceed = confirm('<?php echo escape($lang["page_collections_message"]) ?>');
return $proceed;
}
}
</script>
<a id="collection_delete" style="visibility:hidden; margin-left:10px" title="<?php echo escape($lang["delete_all_selected"]) ?>" onclick="delete_collections()">
<i aria-hidden="true" class="fa fa-fw fa-trash"></i>
</a>
<form method=post id="collectionform" action="<?php echo $baseurl_short?>pages/collection_manage.php">
<?php generateFormToken("collectionform"); ?>
<input type=hidden name="delete" id="collectiondelete" value="">
<input type=hidden name="remove" id="collectionremove" value="">
<input type=hidden name="add" id="collectionadd" value="">
<input type=hidden name="collection_delete_multiple" id="collection_delete_multiple" value="">
<div class="Listview">
<table class="ListviewStyle">
<tr class="ListviewTitleStyle">
<th>
<input type="checkbox" onclick="check_delete_all(this)">
</th>
<th class="name">
<?php if ($col_order_by == "name") { ?>
<span class="Selected">
<?php } ?>
<a href="<?php echo $baseurl_short?>pages/collection_manage.php?offset=0&col_order_by=name&sort=<?php echo urlencode($revsort)?>&find=<?php echo urlencode($find)?>" onclick="return CentralSpaceLoad(this);">
<?php echo escape($lang["collectionname"]); ?>
</a>
<?php if ($col_order_by == "name") { ?>
<div class="<?php echo urlencode($sort); ?>">&nbsp;</div>
<?php } ?>
</th>
<th class="fullname">
<?php if ($col_order_by == "fullname") { ?>
<span class="Selected">
<?php } ?>
<a href="<?php echo $baseurl_short?>pages/collection_manage.php?offset=0&col_order_by=fullname&sort=<?php echo urlencode($revsort)?>&find=<?php echo urlencode($find)?>" onclick="return CentralSpaceLoad(this);">
<?php echo escape($lang["owner"]); ?>
</a>
<?php if ($col_order_by == "fullname") { ?>
<div class="<?php echo urlencode($sort); ?>">&nbsp;</div>
<?php } ?>
</th>
<th class="ref">
<?php if ($col_order_by == "ref") { ?>
<span class="Selected">
<?php } ?>
<a href="<?php echo $baseurl_short?>pages/collection_manage.php?offset=0&col_order_by=ref&sort=<?php echo urlencode($revsort)?>&find=<?php echo urlencode($find)?>" onclick="return CentralSpaceLoad(this);">
<?php echo escape($lang["id"]); ?>
</a>
<?php if ($col_order_by == "ref") { ?>
<div class="<?php echo urlencode($sort)?>">&nbsp;</div>
<?php } ?>
</th>
<th class="created">
<?php if ($col_order_by == "created") { ?>
<span class="Selected">
<?php } ?>
<a href="<?php echo $baseurl_short?>pages/collection_manage.php?offset=0&col_order_by=created&sort=<?php echo urlencode($revsort)?>&find=<?php echo urlencode($find)?>" onclick="return CentralSpaceLoad(this);">
<?php echo escape($lang["created"]); ?>
</a>
<?php if ($col_order_by == "created") { ?>
<div class="<?php echo urlencode($sort); ?>">&nbsp;</div>
<?php } ?>
</th>
<th class="count">
<?php if ($col_order_by == "count") { ?>
<span class="Selected">
<?php } ?>
<a href="<?php echo $baseurl_short?>pages/collection_manage.php?offset=0&col_order_by=count&sort=<?php echo urlencode($revsort)?>&find=<?php echo urlencode($find)?>" onclick="return CentralSpaceLoad(this);">
<?php echo escape($lang["itemstitle"]); ?>
</a>
<?php if ($col_order_by == "count") { ?>
<div class="<?php echo urlencode($sort)?>">&nbsp;</div>
<?php } ?>
</th>
<th class="access">
<?php if ($col_order_by == "type") { ?>
<span class="Selected">
<?php } ?>
<a href="<?php echo $baseurl_short?>pages/collection_manage.php?offset=0&col_order_by=type&sort=<?php echo urlencode($revsort)?>&find=<?php echo urlencode($find)?>" onclick="return CentralSpaceLoad(this);">
<?php echo escape($lang["access"])?>
</a>
<?php if ($col_order_by == "type") { ?>
<div class="<?php echo urlencode($sort)?>">&nbsp;</div>
<?php } ?>
</th>
<th class="collectionin"><?php echo escape($lang["showcollectionindropdown"]) ?></th>
<th class="tools">
<div class="ListTools"><?php echo escape($lang['actions'])?></div>
</th>
</tr>
<form method="get" name="colactions" id="colactions" action="<?php echo $baseurl_short?>pages/collection_manage.php">
<?php
for ($n = $offset; (($n < count($collections)) && ($n < ($offset + $per_page))); $n++) {
if ($collections[$n]['ref'] < 0) {
// Don't show special 'new uploads' collection
continue;
}
$colusername = $collections[$n]['fullname'];
$count_result = $collections[$n]["count"];
?>
<tr>
<td>
<?php if (can_delete_collection($collections[$n], $userref, $k)) {
echo '<input type="checkbox" class="check_delete" id="check_' . $collections[$n]['ref'] . '" value="' . $collections[$n]['ref'] . '" onClick="show_delete()">';
} ?>
</td>
<td class="name">
<div class="ListTitle">
<a
<?php if ($collections[$n]["type"] == COLLECTION_TYPE_FEATURED) { ?>
style="font-style: italic;"
<?php } ?>
href="<?php echo $baseurl_short?>pages/search.php?search=<?php echo urlencode("!collection" . $collections[$n]["ref"])?>"
onclick="return CentralSpaceLoad(this);"
>
<?php echo strip_tags_and_attributes(highlightkeywords(htmlspecialchars_decode(i18n_get_collection_name($collections[$n])), $find)); ?>
</a>
</div>
</td>
<td class="fullname"><?php echo strip_tags_and_attributes(highlightkeywords($colusername, $find)); ?></td>
<td class="ref"><?php echo strip_tags_and_attributes(highlightkeywords($collections[$n]["ref"], $find)); ?></td>
<td class="created"><?php echo nicedate($collections[$n]["created"], true); ?></td>
<td class="count"><?php echo $collections[$n]["count"]; ?></td>
<td class="access">
<?php
switch ($collections[$n]["type"]) {
case COLLECTION_TYPE_PUBLIC:
echo escape($lang["public"]);
break;
case COLLECTION_TYPE_FEATURED:
echo escape($lang["theme"]);
break;
case COLLECTION_TYPE_STANDARD:
default:
echo escape($lang["private"]);
break;
}
?>
</td>
<td class="collectionin">
<input
type="checkbox"
onclick='UpdateHiddenCollections(this, "<?php echo $collections[$n]['ref']; ?>", {<?php echo generateAjaxToken("colactions"); ?>});'
<?php if (!in_array($collections[$n]['ref'], $hidden_collections)) {
echo "checked";
} ?>
>
</td>
<?php $action_selection_id = 'collections_action_selection' . $collections[$n]['ref'] . "_bottom_" . $collections[$n]["ref"]; ?>
<td class="tools">
<div class="ListTools">
<div class="ActionsContainer">
<select class="collectionactions" id="<?php echo $action_selection_id ?>" data-actions-loaded="0" data-actions-populating="0" data-col-id="<?php echo $collections[$n]["ref"];?>" onchange="action_onchange_<?php echo $action_selection_id ?>(this.value);">
<option><?php echo escape($lang["actions-select"]); ?></option>
</select>
</div>
</div>
</td>
</tr>
<input type=hidden name="deleteempty" id="collectiondeleteempty" value="">
<?php
}
?>
</form>
</table>
</div>
</form>
<div class="BottomInpageNav">
<div class="BottomInpageNavLeft">
<?php
// count how many collections are owned by the user versus just shared, and show at top
$mycollcount = 0;
$othcollcount = 0;
for ($i = 0; $i < count($collections); $i++) {
if ($collections[$i]['user'] == $userref) {
$mycollcount++;
} else {
$othcollcount++;
}
}
$collcount = count($collections);
echo strip_tags_and_attributes($collcount == 1 ? $lang["total-collections-1"] : str_replace("%number", $collcount, $lang["total-collections-2"]));
echo " " . strip_tags_and_attributes($mycollcount == 1 ? $lang["owned_by_you-1"] : str_replace("%mynumber", $mycollcount, $lang["owned_by_you-2"])) . "<br />";
# The number of collections should never be equal to zero.
?>
</div>
<?php pager(false, true, array("confirm_page_change" => "return promptBeforePaging();")); ?>
<div class="clearerleft"></div>
</div>
</div>
<!--Create a collection-->
<div class="BasicsBox">
<h1><?php echo escape($lang["createnewcollection"])?></h1>
<p class="tight"><?php echo text("newcollection")?></p>
<form method="post" action="<?php echo $baseurl_short?>pages/collection_manage.php">
<?php generateFormToken("newcollection"); ?>
<div class="Question">
<label for="newcollection"><?php echo escape($lang["collectionname"])?></label>
<div class="tickset">
<div class="Inline">
<input type=text name="name" id="newcollection" value="" maxlength="100" class="shrtwidth">
</div>
<div class="Inline">
<input name="Submit" type="submit" value="<?php echo escape($lang["create"])?>" />
</div>
</div>
<div class="clearerleft"></div>
</div>
</form>
</div>
<!--Find a collection-->
<?php if ($enable_public_collections) { ?>
<div class="BasicsBox">
<h1><?php echo escape($lang["findpubliccollection"])?></h1>
<p class="tight"><?php echo text("findpublic")?></p>
<p>
<?php echo LINK_CARET ?>
<a href="<?php echo $baseurl_short?>pages/collection_public.php" onclick="return CentralSpaceLoad(this,true);">
<?php echo escape($lang["findpubliccollection"]); ?>
</a>
</p>
</div>
<?php } ?>
<div class="BasicsBox">
<h1><?php echo escape($lang["view_shared_collections"])?></h1>
<p>
<a href="<?php echo $baseurl_short?>pages/view_shares.php" onclick="return CentralSpaceLoad(this,true);">
<?php echo LINK_CARET . escape($lang["view_shared_collections"]); ?>
</a>
</p>
</div>
<?php
include "../include/footer.php";
?>

339
pages/collection_public.php Executable file
View File

@@ -0,0 +1,339 @@
<?php
include "../include/boot.php";
include "../include/authenticate.php";
$offset = getval("offset", 0, true);
$find = getval("find", getval("saved_find", ""));
rs_setcookie('saved_find', $find);
$col_order_by = getval("col_order_by", getval("saved_col_order_by", "created"));
rs_setcookie('saved_col_order_by', $col_order_by);
$sort = getval("sort", getval("saved_col_sort", "ASC"));
rs_setcookie('saved_col_sort', $sort);
$revsort = ($sort == "ASC") ? "DESC" : "ASC";
# pager
$per_page = getval("per_page_list", $default_perpage_list, true);
rs_setcookie('per_page_list', $per_page);
$collection_valid_order_bys = array("fullname","name","ref","count","type","created");
$modified_collection_valid_order_bys = hook("modifycollectionvalidorderbys");
if ($modified_collection_valid_order_bys) {
$collection_valid_order_bys = $modified_collection_valid_order_bys;
}
if (!in_array($col_order_by, $collection_valid_order_bys)) {
$col_order_by = "created";
} # Check the value is one of the valid values (SQL injection filter)
$override_group_restrict = getval("override_group_restrict", "false");
if (array_key_exists("find", $_POST)) {
$offset = 0;
} # reset page counter when posting
# pager
$add = getval("add", "");
if ($add != "" && enforcePostRequest(false)) {
# Add someone else's collection to your My Collections
add_collection($userref, $add);
set_user_collection($userref, $add);
refresh_collection_frame();
# Log this
daily_stat("Add public collection", $userref);
}
include "../include/header.php";
?>
<div class="BasicsBox">
<h1><?php echo escape($lang["findpubliccollection"])?></h1>
<p class="tight">
<?php
echo text("introtext");
render_help_link("collections-public-and-themes");
?>
</p>
<div class="BasicsBox">
<form method="post" id="pc_searchform" onsubmit="return CentralSpacePost(this,true);" action="<?php echo $baseurl_short?>pages/collection_public.php">
<?php generateFormToken("pc_searchform"); ?>
<div class="Question">
<label for="find"><?php echo escape($lang["searchpubliccollections"])?></label>
<div class="xtickset">
<div class="Inline">
<input type=text name="find" id="find" value="<?php echo escape(unescape($find)) ?>" maxlength="100" class="shrtwidth" />
</div>
<div class="Inline">
<input name="Submit" type="submit" value="<?php echo escape($lang["searchbutton"])?>" />
</div>
<div class="Inline">
<input name="Clear" type="button" onclick="document.getElementById('find').value='';CentralSpacePost(document.getElementById('pc_searchform'),true);" value="<?php echo escape($lang["clearbutton"]); ?>" />
</div>
</div>
<div class="clearerleft"></div>
</div>
</form>
</div>
<?php
$collections = search_public_collections($find, $col_order_by, $sort, $public_collections_exclude_themes, true, $override_group_restrict == "true");
$results = count($collections);
$totalpages = ceil($results / $per_page);
$curpage = floor($offset / $per_page) + 1;
$jumpcount = 1;
# Create an a-z index
$atoz = "<div class=\"InpageNavLeftBlock\">";
if ($find == "") {
$atoz .= "<span class='Selected'>";
}
if ($public_collections_confine_group) {
$atoz .= "<a onClick='return CentralSpaceLoad(this,true);' href=\"" . $baseurl_short . "pages/collection_public.php?col_order_by=name&override_group_restrict=false&find=\">" . $lang["viewmygroupsonly"] . "</a> &nbsp; | &nbsp;";
$atoz .= "<a onClick='return CentralSpaceLoad(this,true);' href=\"" . $baseurl_short . "pages/collection_public.php?col_order_by=name&override_group_restrict=true&find=\">" . $lang["viewall"] . "</a> &nbsp;&nbsp;&nbsp;";
} else {
$atoz .= "<a onClick='return CentralSpaceLoad(this,true);' href=\"" . $baseurl_short . "pages/collection_public.php?col_order_by=name&find=\">" . $lang["viewall"] . "</a>";
}
if ($find == "") {
$atoz .= "</span>";
}
$atoz .= "&nbsp;&nbsp;";
for ($n = ord("A"); $n <= ord("Z"); $n++) {
if ($find == chr($n)) {
$atoz .= "<span class='Selected'>";
}
$atoz .= "<a href=\"" . $baseurl_short . "pages/collection_public.php?col_order_by=name&find=" . chr($n) . "&override_group_restrict=" . urlencode($override_group_restrict) . "\" onClick=\"return CentralSpaceLoad(this);\">&nbsp;" . chr($n) . "&nbsp;</a> ";
if ($find == chr($n)) {
$atoz .= "</span>";
}
$atoz .= " ";
}
$atoz .= "</div>";
$url = $baseurl_short . "pages/collection_public.php?paging=true&col_order_by=" . urlencode($col_order_by) . "&sort=" . urlencode($sort) . "&find=" . urlencode($find) . "&override_group_restrict=" . urlencode($override_group_restrict);
?>
<div class="TopInpageNav">
<div class="TopInpageNavLeft">
<?php echo $atoz; ?>
<div class="InpageNavLeftBlock">
<?php echo escape($lang["resultsdisplay"])?>:
<?php
for ($n = 0; $n < count($list_display_array); $n++) {
if ($per_page == $list_display_array[$n]) {
?>
<span class="Selected"><?php echo $list_display_array[$n]; ?></span>
<?php
} else {
?>
<a href="<?php echo $url; ?>&per_page_list=<?php echo $list_display_array[$n]; ?>" onclick="return CentralSpaceLoad(this);">
<?php echo $list_display_array[$n]; ?>
</a>
<?php
} ?> &nbsp;| <?php
}
if ($per_page == 99999) {
?>
<span class="Selected"><?php echo escape($lang["all"])?></span>
<?php
} else {
?>
<a href="<?php echo $url; ?>&per_page_list=99999" onclick="return CentralSpaceLoad(this);">
<?php echo escape($lang["all"]); ?>
</a>
<?php
} ?>
</div>
</div>
<?php pager(false); ?>
<div class="clearerleft"></div>
</div>
<form method=post id="collectionform" onsubmit="return CentralSpacePost(this,true);" action="<?php echo $baseurl_short?>pages/collection_public.php">
<?php generateFormToken("collectionform"); ?>
<input type=hidden name="add" id="collectionadd" value="">
<?php
// count how many collections are owned by the user versus just shared, and show at top
$mycollcount = 0;
$othcollcount = 0;
for ($i = 0; $i < count($collections); $i++) {
if ($collections[$i]['user'] == $userref) {
$mycollcount++;
} else {
$othcollcount++;
}
}
$collcount = count($collections);
switch ($collcount) {
case 0:
echo strip_tags_and_attributes($lang["total-collections-0"]);
break;
case 1:
echo strip_tags_and_attributes($lang["total-collections-1"]);
break;
default:
echo strip_tags_and_attributes(str_replace("%number", $collcount, $lang["total-collections-2"]));
}
echo " ";
switch ($mycollcount) {
case 0:
echo strip_tags_and_attributes($lang["owned_by_you-0"]);
break;
case 1:
echo strip_tags_and_attributes($lang["owned_by_you-1"]);
break;
default:
echo strip_tags_and_attributes(str_replace("%mynumber", $mycollcount, $lang["owned_by_you-2"]));
}
echo "<br />";
?>
<div class="Listview">
<table class="ListviewStyle">
<tr class="ListviewTitleStyle">
<th class="name">
<?php if ($col_order_by == "name") { ?>
<span class="Selected">
<?php } ?>
<a href="<?php echo $baseurl_short?>pages/collection_public.php?offset=0&col_order_by=name&sort=<?php echo urlencode($revsort)?>&find=<?php echo urlencode($find)?>" onclick="return CentralSpaceLoad(this);">
<?php echo escape($lang["collectionname"]); ?>
</a>
<?php if ($col_order_by == "name") { ?>
<div class="<?php echo urlencode($sort); ?>">&nbsp;</div>
<?php } ?>
</th>
<th class="ref">
<?php if ($col_order_by == "ref") { ?>
<span class="Selected">
<?php } ?>
<a href="<?php echo $baseurl_short?>pages/collection_public.php?offset=0&col_order_by=ref&sort=<?php echo urlencode($revsort)?>&find=<?php echo urlencode($find)?>" onclick="return CentralSpaceLoad(this);">
<?php echo escape($lang["id"]); ?>
</a>
<?php if ($col_order_by == "ref") { ?>
<div class="<?php echo urlencode($sort); ?>">&nbsp;</div>
<?php } ?>
</th>
<th class="created">
<?php if ($col_order_by == "created") { ?>
<span class="Selected">
<?php } ?>
<a href="<?php echo $baseurl_short?>pages/collection_public.php?offset=0&col_order_by=created&sort=<?php echo urlencode($revsort)?>&find=<?php echo urlencode($find)?>" onclick="return CentralSpaceLoad(this);">
<?php echo escape($lang["created"]); ?>
</a>
<?php if ($col_order_by == "created") { ?>
<div class="<?php echo urlencode($sort); ?>">&nbsp;</div>
<?php } ?>
</th>
<th class="count">
<?php if ($col_order_by == "count") { ?>
<span class="Selected">
<?php } ?>
<a href="<?php echo $baseurl_short?>pages/collection_public.php?offset=0&col_order_by=count&sort=<?php echo urlencode($revsort)?>&find=<?php echo urlencode($find)?>" onclick="return CentralSpaceLoad(this);">
<?php echo escape($lang["itemstitle"]); ?>
</a>
<?php if ($col_order_by == "count") { ?>
<div class="<?php echo urlencode($sort)?>">&nbsp;</div>
<?php } ?>
</th>
<th class="access">
<?php if ($col_order_by == "type") { ?>
<span class="Selected">
<?php } ?>
<a href="<?php echo $baseurl_short?>pages/collection_public.php?offset=0&col_order_by=type&sort=<?php echo urlencode($revsort)?>&find=<?php echo urlencode($find)?>" onclick="return CentralSpaceLoad(this);">
<?php echo escape($lang["access"]); ?>
</a>
<?php if ($col_order_by == "public") { ?>
<div class="<?php echo urlencode($sort)?>">&nbsp;</div>
<?php } ?>
</th>
<th class="tools">
<div class="ListTools"><?php echo escape($lang['actions'])?></div>
</th>
</tr>
<?php for ($n = $offset; (($n < count($collections)) && ($n < ($offset + $per_page))); $n++) { ?>
<tr>
<td class="name">
<div class="ListTitle">
<a href="<?php echo $baseurl_short?>pages/search.php?search=<?php echo urlencode("!collection" . $collections[$n]["ref"])?>" onclick="return CentralSpaceLoad(this,true);">
<?php echo highlightkeywords(i18n_get_collection_name($collections[$n]), $find); ?>
</a>
</div>
</td>
<td class="ref"><?php echo highlightkeywords($collections[$n]["ref"], $find); ?></td>
<td class="created"><?php echo nicedate($collections[$n]["created"], true); ?></td>
<td class="count"><?php echo $collections[$n]["count"]; ?></td>
<?php
switch ($collections[$n]["type"]) {
case COLLECTION_TYPE_PUBLIC:
$access_str = $lang["public"];
break;
case COLLECTION_TYPE_FEATURED:
$access_str = $lang["theme"];
break;
default:
$access_str = $lang["private"];
break;
}
?>
<td class="access"><?php echo escape($access_str); ?></td>
<?php $action_selection_id = 'collectionpublic_action_selection' . $collections[$n]["ref"] . "_bottom_" . $collections[$n]["ref"]; ?>
<td class="tools">
<div class="ListTools">
<?php $count_result = $collections[$n]["count"]; ?>
<div class="ActionsContainer">
<div class="DropdownActionsLabel">Actions:</div>
<select class="collectionpublicactions" id="<?php echo $action_selection_id ?>" data-actions-loaded="0" data-actions-populating="0" data-col-id="<?php echo $collections[$n]["ref"];?>" onchange="action_onchange_<?php echo $action_selection_id ?>(this.value);">
<option><?php echo escape($lang["actions-select"])?></option>
</select>
</div>
</div>
</td>
</tr>
<script>
jQuery(document).ready(function() {
// Load collection actions when dropdown is clicked
jQuery('.collectionpublicactions').on("focus", function(e) {
var el = jQuery(this);
if (el.attr('data-actions-populating') != '0') {
return false
}
el.attr('data-actions-populating','1');
var action_selection_id = el.attr('id');
var colref = el.attr('data-col-id');
LoadActions('collectionpublic',action_selection_id,'collection',colref);
});
});
</script>
<?php } ?>
</table>
</div>
</form>
<div class="BottomInpageNav"><?php pager(false); ?></div>
</div>
<?php
include "../include/footer.php";

254
pages/collection_request.php Executable file
View File

@@ -0,0 +1,254 @@
<?php
include "../include/boot.php";
$ref = getval("ref", "", true);
$k = getval("k", "");
if ($k == "" || !check_access_key_collection($ref, $k)) {
include "../include/authenticate.php";
}
if (!checkperm('q')) {
exit("<br /><br /><strong>" . $lang["error-permissiondenied"] . "</strong>");
}
include "../include/request_functions.php";
if ($k != "" && (!isset($internal_share_access) || !$internal_share_access) && $prevent_external_requests) {
echo "<script>window.location = '" . $baseurl . "/login.php?error=" . (($allow_account_request) ? "signin_required_request_account" : "signin_required") . "'</script>";
exit();
}
if ($k == "" && isset($anonymous_login) && $username == $anonymous_login) {
$user_is_anon = true;
} else {
$user_is_anon = false;
}
$use_antispam = ($k !== '' || $user_is_anon);
if ($ref == "" && isset($usercollection)) {
$ref = $usercollection;
}
$cinfo = get_collection($ref);
$error = false;
# Determine the minimum access across all of the resources in the collection being requested
$collection_request_min_access = collection_min_access($ref);
# Check if any X?_ permissions are blocking sizes
$resource_types = get_resource_types();
foreach ($resource_types as $type) {
if (checkperm("X" . $type["ref"] . "_")) {
$collection_request_min_access = max($collection_request_min_access, 1);
break;
}
foreach (get_all_image_sizes() as $size) {
if (checkperm("X" . $type["ref"] . "_" . $size["id"])) {
$collection_request_min_access = max($collection_request_min_access, 1);
break;
}
}
}
# Prevent "request all" resources in a collection if the user has access to all of its resources
if ($collection_request_min_access == 0) {
exit("<br /><br /><strong>" . $lang["error-cant-request-all-are-open"] . "</strong>");
}
if (getval("save", "") != "" && enforcePostRequest(false)) {
$antispamcode = getval('antispamcode', '');
$antispam = getval('antispam', '');
$antispamtime = getval('antispamtime', 0);
// Check the anti-spam time is recent
if ($use_antispam && ($antispamtime < (time() - 180) || $antispamtime > time())) {
$result = false;
$error = $lang["expiredantispam"];
}
// Check the anti-spam code is correct
elseif ($use_antispam && !verify_antispam($antispamcode, $antispam, $antispamtime)) {
$result = false;
$error = $lang["requiredantispam"];
} elseif ($k != "" || $userrequestmode == 0 || $user_is_anon) {
if (($k != "" || $user_is_anon) && (getval("fullname", "") == "" || getval("email", "") == "")) {
$result = false; # Required fields not completed.
} else {
# Request mode 0 : Simply e-mail the request.
$result = email_collection_request($ref, getval("request", ""), getval("email", ""));
}
} else {
# Request mode 1 : "Managed" mode via Manage Requests / Orders
$result = managed_collection_request($ref, getval("request", ""));
}
if ($result === false) {
$error = $lang["requiredfields-general"];
} else {
?>
<script>
CentralSpaceLoad("<?php echo $baseurl_short ?>pages/done.php?text=resource_request&k=<?php echo escape($k); ?>",true);
</script>
<?php
}
}
include "../include/header.php";
?>
<div class="BasicsBox">
<?php
$backlink = getval("backlink", "");
if ($backlink != "") {
?>
<p>
<a href='<?php echo escape(rawurldecode($backlink)); ?>'>
<?php echo LINK_CARET_BACK . escape($lang['back']); ?>
</a>
</p>
<?php
}
?>
<h1>
<?php
echo escape($lang["requestcollection"]);
render_help_link("resourceadmin/user-resource-requests");
?>
</h1>
<p><?php echo escape(text("introtext"))?></p>
<form method="post" onsubmit="return CentralSpacePost(this,true);" action="<?php echo $baseurl_short?>pages/collection_request.php">
<?php generateFormToken("collection_request"); ?>
<input type=hidden name=ref value="<?php echo escape($ref); ?>">
<input type=hidden name="k" value="<?php echo escape($k); ?>">
<div class="Question">
<label><?php echo escape($lang["collectionname"]); ?></label>
<div class="Fixed"><?php echo escape(i18n_get_collection_name($cinfo)); ?></div>
<div class="clearerleft"></div>
</div>
<?php
# Only ask for user details if this is an external share. Otherwise this is already known from the user record.
if ($k != "" || $user_is_anon) {
?>
<div class="Question">
<label><?php echo escape($lang["fullname"]); ?> <sup>*</sup></label>
<input type="hidden" name="fullname_label" value="<?php echo escape($lang["fullname"]); ?>">
<input name="fullname" class="stdwidth" type="text" value="<?php echo escape(getval("fullname", "")); ?>">
<div class="clearerleft"></div>
</div>
<div class="Question">
<label><?php echo escape($lang["emailaddress"]); ?> <sup>*</sup></label>
<input type="hidden" name="email_label" value="<?php echo escape($lang["emailaddress"]); ?>">
<input name="email" class="stdwidth" type="text" value="<?php echo escape(getval("email", "")); ?>">
<div class="clearerleft"></div>
</div>
<div class="Question">
<label><?php echo escape($lang["contacttelephone"]); ?></label>
<input name="contact" class="stdwidth" type="text" value="<?php echo escape(getval("contact", "")); ?>">
<input type="hidden" name="contact_label" value="<?php echo escape($lang["contacttelephone"]); ?>">
<div class="clearerleft"></div>
</div>
<?php
} ?>
<div class="Question">
<label for="requestreason">
<?php
echo escape($lang["requestreason"]);
if ($resource_request_reason_required) {
?>
<sup>*</sup>
<?php
}
?>
</label>
<textarea class="stdwidth" name="request" id="request" rows=5 cols=50><?php echo escape(getval("request", "")); ?></textarea>
<div class="clearerleft"></div>
</div>
<?php # Add custom fields
if (isset($custom_request_fields)) {
$custom = explode(",", $custom_request_fields);
$required = explode(",", $custom_request_required);
for ($n = 0; $n < count($custom); $n++) {
$type = 1;
# Support different question types for the custom fields.
if (isset($custom_request_types[$custom[$n]])) {
$type = $custom_request_types[$custom[$n]];
}
if ($type == 4) {
# HTML type - just output the HTML.
echo $custom_request_html[$custom[$n]];
} else {
?>
<div class="Question">
<label for="custom<?php echo $n?>">
<?php
echo escape(i18n_get_translated($custom[$n]));
if (in_array($custom[$n], $required)) {
?>
<sup>*</sup>
<?php
}
?>
</label>
<?php if ($type == 1) { # Normal text box ?>
<input type=text name="custom<?php echo $n; ?>" id="custom<?php echo $n; ?>" class="stdwidth" value="<?php echo escape(getval("custom" . $n, "")); ?>">
<?php } ?>
<?php if ($type == 2) { # Large text box ?>
<textarea name="custom<?php echo $n; ?>" id="custom<?php echo $n; ?>" class="stdwidth" rows="5"><?php echo escape(getval("custom" . $n, "")); ?></textarea>
<?php } ?>
<?php if ($type == 3) { # Drop down box ?>
<select name="custom<?php echo $n; ?>" id="custom<?php echo $n; ?>" class="stdwidth">
<?php foreach ($custom_request_options[$custom[$n]] as $option) {
$val = i18n_get_translated($option);
?>
<option <?php echo (getval("custom" . $n, "") == $val) ? " selected" : ''; ?>>
<?php echo escape(i18n_get_translated($option)); ?>
</option>
<?php } ?>
</select>
<?php } ?>
<div class="clearerleft"></div>
</div>
<?php
}
}
}
if ($use_antispam) {
render_antispam_question();
}
?>
<div class="QuestionSubmit">
<?php if ($error) { ?>
<div class="FormError">!! <?php echo $error ?> !!</div>
<?php
} ?>
<input name="cancel" type="button" value="<?php echo escape($lang["cancel"]); ?>" onclick="document.location='<?php echo $baseurl_short?>pages/search.php?search=!collection<?php echo urlencode($ref) ?>';"/>&nbsp;
<input name="save" value="true" type="hidden" />
<input type="submit" value="<?php echo escape($lang["requestcollection"]); ?>" />
</div>
</form>
</div>
<?php
include "../include/footer.php";
?>

101
pages/collection_set_category.php Executable file
View File

@@ -0,0 +1,101 @@
<?php
include "../include/boot.php";
include "../include/authenticate.php";
if (!$enable_themes || checkperm("b") || !checkperm("h")) {
error_alert($lang["error-permissiondenied"], true, 403);
exit();
}
$ref = getval("ref", 0, true);
if (!collection_writeable($ref)) {
exit($lang["no_access_to_collection"]);
}
$collection = get_collection($ref);
if ($collection === false) {
error_alert($lang["error-collectionnotfound"], true);
exit();
}
if (
(!in_array($collection["type"], array(COLLECTION_TYPE_STANDARD, COLLECTION_TYPE_PUBLIC, COLLECTION_TYPE_FEATURED)))
|| ($collection["type"] == COLLECTION_TYPE_FEATURED
&& !featured_collection_check_access_control((int) $collection["ref"]))
) {
error_alert($lang["error-permissiondenied"], true, 403);
exit();
}
if (getval("submitted", "") != "" && enforcePostRequest(false)) {
$coldata = array();
if (getval("update_parent", "") == "true") {
// Prepare coldata for save_collection() for posted featured collections (if any changes have been made)
$current_branch_path = get_featured_collection_category_branch_by_leaf((int) $collection["ref"], array());
$featured_collections_changes = process_posted_featured_collection_categories(0, $current_branch_path);
if (!empty($featured_collections_changes)) {
$coldata["featured_collections_changes"] = $featured_collections_changes;
}
}
if (
!empty($coldata)
&& isset($coldata["featured_collections_changes"]["update_parent"])
&& $coldata["featured_collections_changes"]["update_parent"] == 0
&& getval("force_featured_collection_type", "") != "true"
&& is_featured_collection_category_by_children($collection["ref"])
) {
$error = $lang["error_save_not_allowed_fc_has_children"];
}
if (!empty($coldata) && !isset($error)) {
save_collection($collection["ref"], $coldata);
$collection = get_collection($collection["ref"]);
}
}
$action_url = generateURL("{$baseurl_short}pages/collection_set_category.php", array("ref" => $collection["ref"]));
include "../include/header.php";
?>
<div class="BasicsBox">
<?php
if (isset($error)) {
render_top_page_error_style($error);
}
?>
<h1>
<?php
echo escape($lang["collection_set_theme_category_title"]);
render_help_link("user/themes-public-collections");
?>
</h1>
<p><?php echo text("introtext"); ?></p>
<form method=post id="collectionform" action="<?php echo $action_url; ?>">
<?php generateFormToken("collectionform"); ?>
<input type=hidden name=ref value="<?php echo escape($ref); ?>">
<input type=hidden name="submitted" value="true">
<input type="hidden" name="redirect" id="redirect" value="yes" >
<input type=hidden name="update_parent" value="false">
<div class="Question">
<label for="name"><?php echo escape($lang["collection"]); ?></label>
<div class="Fixed"><?php echo escape(i18n_get_collection_name($collection, $index = "name")); ?></div>
<div class="clearerleft"></div>
</div>
<?php
render_featured_collection_category_selector(
0,
array(
"collection" => $collection,
"depth" => 0,
"current_branch_path" => get_featured_collection_category_branch_by_leaf((int) $collection["ref"], array()),
)
);
?>
</form>
</div>
<?php
include "../include/footer.php";

551
pages/collection_share.php Executable file
View File

@@ -0,0 +1,551 @@
<?php
include "../include/boot.php";
include "../include/authenticate.php";
$collection_url = getval('collection', '', true);
$col_order_by = getval('col_order_by', '', true);
$find = getval('find', '', true);
$offset = getval('offset', '', true);
$order_by = getval('order_by', '', true);
$ref = getval('ref', '', true);
$restypes = getval('restypes', '', true);
$search = getval('search', '', true);
$sort = getval('sort', '', true);
$user_group = getval('usergroup', '', true);
$backurl = getval('backurl', '');
// Check if editing existing external share
$editaccess = trim(getval("editaccess", ""));
$editing = ($editaccess != "");
$editexternalurl = (getval("editexternalurl", "") != "");
$deleteaccess = (getval("deleteaccess", "") != "");
$generateurl = (getval("generateurl", "") != "");
// Share options
if ($editing) {
$shareinfo = get_external_shares(array("share_collection" => $ref, "access_key" => $editaccess));
if (isset($shareinfo[0])) {
$shareinfo = $shareinfo[0];
} else {
error_alert($lang["error_invalid_key"], true);
exit();
}
$expires = getval("expires", $shareinfo["expires"]);
$access = getval("access", $shareinfo["access"], true);
$group = getval("usergroup", $shareinfo["usergroup"], true);
$sharepwd = getval('sharepassword', ($shareinfo["password_hash"] != "" ? "true" : ""));
} else {
$expires = getval("expires", "");
$access = getval("access", -1, true);
$group = getval("usergroup", 0, true);
$sharepwd = getval('sharepassword', '');
}
$collection = get_collection($ref);
if ($collection === false) {
$error = $lang['error-collectionnotfound'];
if (getval("ajax", "") != "") {
error_alert($error, false, 404);
} else {
include "../include/header.php";
$onload_message = array("title" => $lang["error"],"text" => $error);
include "../include/footer.php";
}
exit();
}
if ($collection["type"] == COLLECTION_TYPE_FEATURED) {
$collection_resources = get_collection_resources($collection["ref"]);
$collection["has_resources"] = (is_array($collection_resources) && !empty($collection_resources) ? 1 : 0);
}
if ($bypass_share_screen && $collection["type"] != COLLECTION_TYPE_SELECTION) {
redirect('pages/collection_email.php?ref=' . $ref) ;
}
// Check access controls
if (!collection_readable($ref)) {
exit($lang["no_access_to_collection"]);
} elseif (
$collection["type"] == COLLECTION_TYPE_FEATURED
&& !featured_collection_check_access_control((int) $collection["ref"])
&& !allow_featured_collection_share($collection)
) {
error_alert($lang["error-permissiondenied"], true, 403);
exit();
}
if (!$allow_share || checkperm("b")) {
$show_error = true;
$error = $lang["error-permissiondenied"];
}
$internal_share_only = checkperm("noex") || (isset($user_dl_limit) && intval($user_dl_limit) > 0);
// Special collection being shared - we need to make a copy of it and disable internal access
$share_selected_resources = false;
if ($collection["type"] == COLLECTION_TYPE_SELECTION) {
$share_selected_resources = true;
// disable a few options
$hide_internal_sharing_url = true;
$email_sharing = false;
$home_dash = false;
// Prevent users from sharing the real collection. Copy it instead
if (($generateurl && !$editing) || $editexternalurl || $deleteaccess) {
$ref = create_collection($userref, $collection["name"]);
copy_collection($collection["ref"], $ref);
$collection = get_collection($ref);
}
}
// Special collection being shared. Ensure certain features are enabled/disabled
elseif (is_featured_collection_category($collection)) {
// Check this is not an empty FC category
$fc_resources = get_featured_collection_resources($collection, array("limit" => 1));
if (empty($fc_resources)) {
error_alert($lang["cannotshareemptythemecategory"], true, 200);
exit();
}
// Further checks at collection-resource level. Recurse through category's sub FCs
$collection["sub_fcs"] = get_featured_collection_categ_sub_fcs($collection);
$collectionstates = false;
$sub_fcs_resources_states = array();
$sub_fcs_resources_minaccess = array();
foreach ($collection["sub_fcs"] as $sub_fc) {
// Check all featured collections contain only active resources
$collectionstates = is_collection_approved($sub_fc);
if (!$collection_allow_not_approved_share && $collectionstates === false) {
break;
} elseif (is_array($collectionstates)) {
$sub_fcs_resources_states = array_unique(array_merge($sub_fcs_resources_states, $collectionstates));
}
// Check minimum access is restricted or lower and sharing of restricted resources is not allowed
$sub_fcs_resources_minaccess[] = collection_min_access($sub_fc);
}
$collectionstates = (!empty($sub_fcs_resources_states) ? $sub_fcs_resources_states : $collectionstates);
if (!empty($sub_fcs_resources_minaccess)) {
$minaccess = max(array_unique($sub_fcs_resources_minaccess));
}
// To keep it in line with the legacy theme_category_share.php page, disable these features (home_dash, hide_internal_sharing_url)
$home_dash = false;
// Beyond this point mark accordingly any validations that have been enforced specifically for Featured Collections
// (categories or otherwise) type in a different way than for a normal collection
// IMPORTANT: make sure there's code above this point (within this block) dealing with these validations.
$collection_allow_empty_share = true;
}
$resource_count = count(get_collection_resources($ref));
// Sharing an empty collection?
if (!$collection_allow_empty_share && $resource_count == 0) {
$show_error = true;
$error = $lang["cannotshareemptycollection"];
}
#Check if any resources are not active
$collectionstates = (isset($collectionstates) ? $collectionstates : is_collection_approved($ref));
if (!$collection_allow_not_approved_share && !$collectionstates) {
$show_error = true;
$error = $lang["notapprovedsharecollection"];
}
if (is_array($collectionstates) && (count($collectionstates) > 1 || !in_array(0, $collectionstates))) {
$warningtext = $lang["collection_share_status_warning"];
foreach ($collectionstates as $collectionstate) {
$warningtext .= "<br />" . $lang["status" . $collectionstate];
}
}
# Minimum access is restricted or lower and sharing of restricted resources is not allowed. The user cannot share this collection.
# The same applies for collections where the user creating the share doesn't have access to all resources in the collection e.g. some resources are in states blocked by a z permission.
$minaccess = (isset($minaccess) ? $minaccess : collection_min_access($ref));
if (!$restricted_share && $minaccess >= RESOURCE_ACCESS_RESTRICTED || $resource_count != count(do_search("!collection{$ref}", '', 'relevance', 0, -1, 'desc', false, '', false, '', '', false, false))) {
$show_error = true;
$error = $lang["restrictedsharecollection"];
}
# Should those that have been granted open access to an otherwise restricted resource be able to share the resource? - as part of a collection
if (!$allow_custom_access_share && isset($customgroupaccess) && isset($customuseraccess) && ($customgroupaccess || $customuseraccess)) {
$show_error = true;
$error = $lang["customaccesspreventshare"];
}
# Process deletion of access keys
if ($deleteaccess && !isset($show_error) && enforcePostRequest(getval("ajax", false))) {
delete_collection_access_key($ref, getval("deleteaccess", ""));
}
include "../include/header.php";
if (isset($show_error)) { ?>
<script type="text/javascript">
alert('<?php echo escape($error); ?>');
history.go(-1);
</script>
<?php
exit();
}
?>
<div class="BasicsBox">
<form method=post id="collectionform" action="<?php echo $baseurl_short?>pages/collection_share.php?ref=<?php echo urlencode($ref)?>">
<input type="hidden" name="ref" id="ref" value="<?php echo escape($ref) ?>">
<input type="hidden" name="deleteaccess" id="deleteaccess" value="">
<input type="hidden" name="editaccess" id="editaccess" value="<?php echo escape($editaccess)?>">
<input type="hidden" name="editexpiration" id="editexpiration" value="">
<input type="hidden" name="editaccesslevel" id="editaccesslevel" value="">
<input type="hidden" name="editgroup" id="editgroup" value="">
<?php generateFormToken("collectionform");
$page_header = $lang["sharecollection"];
if ($editing && !$editexternalurl) {
$page_header .= " - {$lang["editingexternalshare"]} $editaccess";
}
if (strpos($backurl, "/pages/team/team_external_shares.php") !== false) {
$links_trail = array(
array(
'title' => $lang["teamcentre"],
'href' => $baseurl_short . "pages/team/team_home.php",
'menu' => true
),
array(
'title' => $lang["manage_external_shares"],
'href' => $baseurl . $backurl
),
array(
'title' => $page_header,
'help' => "user/sharing-resources"
)
);
renderBreadcrumbs($links_trail);
} else {
?>
<h1>
<?php
echo escape($page_header);
render_help_link("user/sharing-resources");
?>
</h1>
<?php
}
if (isset($warningtext)) {
echo "<div class='PageInformal'>" . $warningtext . "</div>";
}
if ($collection["type"] == COLLECTION_TYPE_FEATURED && is_featured_collection_category($collection)) {
echo "<p>" . escape($lang["share_fc_warning"]) . "</p>";
}
?>
<div class="VerticalNav">
<ul>
<?php
# Flag to prevent duplicate rendering of the "generateinternalurl" text and associated input field
$generateinternalurl_rendered = false;
$url_params = [
'ref' => $ref,
'search' => $search,
'collection' => $collection,
'restypes' => $restypes,
'order_by' => $order_by,
'col_order_by' => $col_order_by,
'sort' => $sort,
'offset' => $offset,
'find' => $find,
'k' => $k
];
if (!$editing || $editexternalurl) {
if ($email_sharing) {
?>
<li>
<i aria-hidden="true" class="fa fa-fw fa-envelope"></i>&nbsp;
<a onClick="return CentralSpaceLoad(this,true);" href="<?php echo generateURL($baseurl_short . 'pages/collection_email.php', $url_params); ?>">
<?php echo escape($lang["emailcollectiontitle"]); ?>
</a>
</li>
<?php
}
# Share as a dash tile.
global $home_dash,$anonymous_login,$username;
if ($home_dash && checkPermission_dashcreate() && !hook('replace_share_dash_create')) {
?>
<li>
<i aria-hidden="true" class="fa fa-fw fa-th"></i>&nbsp;
<a href="<?php echo $baseurl_short;?>pages/dash_tile.php?create=true&tltype=srch&promoted_resource=true&freetext=true&all_users=1&link=/pages/search.php?search=!collection<?php echo $ref?>&order_by=relevance&sort=DESC" onclick="return CentralSpaceLoad(this,true);">
<?php echo escape($lang["createnewdashtile"]); ?>
</a>
</li>
<?php
}
if (!$internal_share_only) {
?>
<li>
<i aria-hidden="true" class="fa fa-fw fa-link"></i>&nbsp;
<a onClick="return CentralSpaceLoad(this,true);" href="<?php echo generateURL($baseurl_short . 'pages/collection_share.php', $url_params, ['generateurl' => true]); ?>">
<?php echo escape($lang["generateurl"]); ?>
</a>
</li>
<?php
}
if (
!$hide_internal_sharing_url
&& ($collection["type"] == COLLECTION_TYPE_FEATURED
&& allow_featured_collection_share($collection)
|| $collection["public"] == 1 || $ignore_collection_access)
&& !$generateurl
) { // Just show the internal share URL straight away as there is no generate link
?>
<p><?php echo escape($lang["generateurlinternal"])?></p>
<p>
<input class="URLDisplay" type="text" value="<?php echo $baseurl; ?>/?c=<?php echo urlencode($ref); ?>">
<?php $generateinternalurl_rendered = true; ?>
</p>
<?php
}
hook("extra_share_options");
}
if (!$internal_share_only && ($editing || $generateurl)) {
if (!($hide_internal_sharing_url) && (!$editing || $editexternalurl) && $collection["public"] == 1 || $ignore_collection_access) {
# Only render "generateinternalurl" text and associated input field if it hasn't already been rendered
if (!$generateinternalurl_rendered) {
?>
<p><?php echo escape($lang["generateurlinternal"])?></p>
<p>
<input class="URLDisplay" type="text" value="<?php echo $baseurl?>/?c=<?php echo urlencode($ref) ?>">
<?php $generateinternalurl_rendered = true; ?>
</p>
<?php
}
}
if ($access == -1 || ($editing && !$editexternalurl)) {
?>
<p>
<?php if (!$editing || $editexternalurl) {
echo strip_tags_and_attributes($lang["selectgenerateurlexternal"]);
} ?>
</p>
<?php
if ($editing) {
echo "<div class='Question'><label>"
. escape($lang["collectionname"])
. "</label><div class='Fixed'>"
. i18n_get_collection_name($collection)
. "</div><div class='clearerleft'></div></div>";
}
$shareoptions = array(
"password" => ($sharepwd != "" ? true : false),
"editaccesslevel" => $access,
"editexpiration" => $expires,
"editgroup" => $group,
);
render_share_options($shareoptions);
?>
<div class="QuestionSubmit">
<?php if ($editing && !$editexternalurl) { ?>
<input
name="editexternalurl"
type="submit"
onclick="<?php
if ($share_password_required) {
echo 'if (!enforceSharePassword(\'' . escape($lang['share-password-not-set']) . '\')) { return false; }; ';
} ?>"
value="<?php echo escape($lang["save"]); ?>"
/>
<?php } else { ?>
<input
name="generateurl"
type="submit"
onclick="<?php
if ($share_password_required) {
echo 'if (!enforceSharePassword(\'' . escape($lang['share-password-not-set']) . '\')) { return false; }; ';
} ?>"
value="<?php echo escape($lang["generateexternalurl"]); ?>"
/>
<?php } ?>
</div>
<?php
} elseif ($editaccess == "" && !($editing && $editexternalurl)) {
// Access has been selected. Generate a new URL.
$generated_access_key = '';
enforceSharePassword($sharepwd);
if (empty($allowed_external_share_groups) || (!empty($allowed_external_share_groups) && in_array($user_group, $allowed_external_share_groups))) {
$generated_access_key = generate_collection_access_key($collection, 0, 'URL', $access, $expires, $user_group, $sharepwd);
} elseif (!empty($allowed_external_share_groups) && !in_array($usergroup, $allowed_external_share_groups)) {
// Not allowed to select usergroup but this usergroup can not be used, default to the first entry in allowed_external_share_groups
$generated_access_key = generate_collection_access_key($collection, 0, 'URL', $access, $expires, $allowed_external_share_groups[0], $sharepwd);
}
if ('' != $generated_access_key) {
?>
<p><?php echo escape($lang['generateurlexternal']); ?></p>
<p>
<input class="URLDisplay" type="text" value="<?php echo $baseurl?>/?c=<?php echo urlencode($ref) ?>&k=<?php echo $generated_access_key; ?>">
</p>
<?php
} else {
?>
<div class="PageInformal"><?php echo escape($lang['error_generating_access_key']); ?></div>
<?php
}
}
# Process editing of external share
if ($editexternalurl) {
enforceSharePassword($sharepwd);
$editsuccess = edit_collection_external_access($editaccess, $access, $expires, getval("usergroup", ""), $sharepwd);
if ($editsuccess) {
echo "<span style='font-weight:bold;'>"
. escape($lang['changessaved'])
. " - <em>" . escape($editaccess) . "</em>";
}
}
}
?>
</ul>
</div>
<?php
if (
collection_writeable($ref) ||
(isset($collection['savedsearch']) && $collection['savedsearch'] != null && ($userref == $collection["user"] || checkperm("h")))
) {
if (!($hide_internal_sharing_url) && (!$editing || $editexternalurl)) {
?>
<h2><?php echo escape($lang["internalusersharing"])?></h2>
<div class="Question">
<label for="users"><?php echo escape($lang["attachedusers"])?></label>
<div class="Fixed">
<?php echo escape($collection["users"] == "" ? $lang["noattachedusers"] : $collection["users"]); ?>
<br />
<br />
<a onclick="return CentralSpaceLoad(this, true);" href="<?php echo $baseurl_short?>pages/collection_edit.php?ref=<?php echo urlencode($ref); ?>">
<?php echo LINK_CARET . escape($lang["action-edit"]);?>
</a>
</div>
<div class="clearerleft"></div>
</div>
<p>&nbsp;</p>
<?php
}
if (!$internal_share_only) { ?>
<h2><?php echo escape($lang["externalusersharing"])?></h2>
<?php
$keys = get_external_shares(array("share_collection" => $ref));
if (count($keys) == 0) {
?>
<p><?php echo escape($lang["noexternalsharing"]) ?></p>
<?php
} else {
?>
<div class="Listview">
<table class="ListviewStyle">
<tr class="ListviewTitleStyle">
<th><?php echo escape($lang["accesskey"]);?></th>
<th><?php echo escape($lang["sharedby"]);?></th>
<th><?php echo escape($lang["sharedwith"]);?></th>
<th><?php echo escape($lang["lastupdated"]);?></th>
<th><?php echo escape($lang["lastused"]);?></th>
<th><?php echo escape($lang["expires"]);?></th>
<th><?php echo escape($lang["access"]);?></th>
<?php
global $social_media_links;
if (!empty($social_media_links)) {
?>
<th><?php echo escape($lang['social_media']); ?></th>
<?php
}
?>
<th>
<div class="ListTools"><?php echo escape($lang["tools"]); ?></div>
</th>
</tr>
<?php for ($n = 0; $n < count($keys); $n++) { ?>
<tr>
<td>
<div class="ListTitle">
<a target="_blank" href="<?php echo $baseurl . "?c=" . urlencode($ref) . "&k=" . urlencode($keys[$n]["access_key"]) ?>">
<?php echo escape($keys[$n]["access_key"]) ?>
</a>
</div>
</td>
<td><?php echo escape(resolve_users($keys[$n]["user"]) ?? "")?></td>
<td><?php echo escape($keys[$n]["email"] ?? "") ?></td>
<td><?php echo escape(nicedate($keys[$n]["date"], true, true, true) ?? ""); ?></td>
<td><?php echo escape(nicedate($keys[$n]["lastused"], true, true, true) ?? ""); ?></td>
<td><?php echo escape(($keys[$n]["expires"] == "") ? $lang["never"] : nicedate($keys[$n]["expires"], false) ?? "") ?></td>
<td><?php echo escape(($keys[$n]["access"] == -1) ? "" : $lang["access" . $keys[$n]["access"]] ?? ""); ?></td>
<?php if (!empty($social_media_links)) { ?>
<td><?php renderSocialMediaShareLinksForUrl(generateURL($baseurl, array('c' => $ref, 'k' => $keys[$n]['access_key']))); ?></td>
<?php }
$editlink = generateURL(
$baseurl . "/pages/collection_share.php",
array(
"ref" => $keys[$n]["collection"],
"editaccess" => $keys[$n]["access_key"],
)
);
?>
<td>
<div class="ListTools">
<a href="#" onclick="if (confirm('<?php echo escape($lang["confirmdeleteaccess"])?>')) {document.getElementById('deleteaccess').value='<?php echo escape($keys[$n]["access_key"]) ?>';document.getElementById('collectionform').submit(); return false;}">
<?php echo LINK_CARET . escape($lang["action-delete"]); ?>
</a>
<a onclick="return CentralSpaceLoad(this,true);" href="<?php echo $editlink; ?>">
<?php echo LINK_CARET . escape($lang["action-edit"]); ?>
</a>
</div>
</td>
</tr>
<?php } ?>
</table>
</div>
<?php
}
}
}
?>
</form>
</div>
<script>
jQuery('#collectionform').submit(function() {
CentralSpaceShowProcessing();
jQuery('#collectionform :input[type=submit]').hide();
});
</script>
<?php
include "../include/footer.php";
?>

1228
pages/collections.php Executable file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,338 @@
<?php
include_once "../include/boot.php";
$k = trim(getval("k", ""));
$parent = (int) getval("parent", $featured_collections_root_collection, true);
if ($k == "" || !check_access_key_collection($parent, $k)) {
include "../include/authenticate.php";
$parent = (int) getval("parent", $featured_collections_root_collection, true);
} else {
// Disable CSRF when someone is accessing an external share (public context)
$CSRF_enabled = false;
// Force simple view because otherwise it assumes you're logged in. The JS api function will use the native mode to
// get the resource count and loading the actions always authenticates and both actions will (obviously) error.
$themes_simple_view = true;
}
if (!$enable_themes) {
http_response_code(403);
exit($lang["error-permissiondenied"]);
}
// Access control
if ($parent > 0 && !featured_collection_check_access_control($parent)) {
error_alert($lang["error-permissiondenied"], true, 403);
exit();
}
$smart_rtf = (int) getval("smart_rtf", 0, true);
$smart_fc_parent = getval("smart_fc_parent", 0, true);
$smart_fc_parent = ($smart_fc_parent > 0 ? $smart_fc_parent : null);
$general_url_params = ($k == "" ? array() : array("k" => $k));
$parent_collection_data = get_collection($parent);
$parent_collection_data = (is_array($parent_collection_data) ? $parent_collection_data : array());
if (getval("new", "") == "true" && getval("cta", "") == "true") {
new_featured_collection_form($parent);
exit();
}
// List of all FCs. For huge trees, helps increase performance but might require an increase for memory_limit in php.ini
$all_fcs = get_all_featured_collections();
include "../include/header.php";
?>
<div class="BasicsBox FeaturedSimpleLinks">
<?php
if ($parent > 0) {
$links_trail = array(
array(
"title" => $lang["themes"],
"href" => generateURL("{$baseurl_short}pages/collections_featured.php", $general_url_params)
)
);
$fc_branch_path = move_featured_collection_branch_path_root(compute_node_branch_path($all_fcs, $parent));
if (empty($fc_branch_path)) {
$links_trail = [];
}
$branch_trail = array_map(function ($branch) use ($baseurl_short, $general_url_params) {
return array(
"title" => strip_prefix_chars(i18n_get_translated($branch["name"]), "*"),
"href" => generateURL("{$baseurl_short}pages/collections_featured.php", $general_url_params, array("parent" => $branch["ref"]))
);
}, $fc_branch_path);
renderBreadcrumbs(array_merge($links_trail, $branch_trail), "", "BreadcrumbsBoxTheme");
}
// Default rendering options (should apply to both FCs and smart FCs)
$full_width = !$themes_simple_view;
$rendering_options = array(
"full_width" => $full_width,
"general_url_params" => $general_url_params,
"all_fcs" => $all_fcs,
);
$featured_collections = ($smart_rtf == 0 ? get_featured_collections($parent, array()) : array());
usort($featured_collections, "order_featured_collections");
render_featured_collections(
array_merge($rendering_options, ["reorder" => can_reorder_featured_collections()]),
$featured_collections
);
$smart_fcs_list = array();
if ($parent == 0 && $smart_rtf == 0) {
// Root level - this is made up of all the fields that have a Smart theme name set.
$smart_fc_headers = array_filter(get_smart_theme_headers(), function (array $v) {
return metadata_field_view_access($v["ref"]);
});
$smart_fcs_list = array_map(function (array $v) use ($FEATURED_COLLECTION_BG_IMG_SELECTION_OPTIONS) {
return array(
"ref" => $v["ref"],
"name" => $v["smart_theme_name"],
"type" => COLLECTION_TYPE_FEATURED,
"parent" => null,
"thumbnail_selection_method" => $FEATURED_COLLECTION_BG_IMG_SELECTION_OPTIONS["most_popular_image"],
"has_resources" => 0,
"resource_type_field" => $v["ref"]);
},
$smart_fc_headers);
} elseif ($parent == 0 && $smart_rtf > 0 && metadata_field_view_access($smart_rtf)) {
// Smart fields. If a category tree, then a parent could be passed once user requests a lower level than root of the tree
$resource_type_field = get_resource_type_field($smart_rtf);
if ($resource_type_field !== false && in_array($resource_type_field["type"], $FIXED_LIST_FIELD_TYPES)) {
// We go one level at a time so we don't need it to search recursively even if this is a FIELD_TYPE_CATEGORY_TREE
$smart_fc_nodes = get_smart_themes_nodes($smart_rtf, false, $smart_fc_parent, $resource_type_field);
$smart_fcs_list = array_map(function (array $v) use ($smart_rtf, $FEATURED_COLLECTION_BG_IMG_SELECTION_OPTIONS) {
return array(
"ref" => $v["ref"],
"name" => $v["name"],
"type" => COLLECTION_TYPE_FEATURED,
"parent" => $v["ref"], # parent here is the node ID. When transformed to a FC this parent will be used for going to the next level down the branch
"thumbnail_selection_method" => $FEATURED_COLLECTION_BG_IMG_SELECTION_OPTIONS["most_popular_image"],
"has_resources" => 0,
"resource_type_field" => $smart_rtf,
"node_is_parent" => $v["is_parent"]
);
},
$smart_fc_nodes);
}
}
$rendering_options["smart"] = (count($smart_fcs_list) > 0);
render_featured_collections($rendering_options, $smart_fcs_list);
unset($rendering_options["smart"]);
if ($k == "" && $smart_rtf == 0) {
if (checkperm("h") && can_create_collections()) {
render_new_featured_collection_cta(
generateURL(
"{$baseurl_short}pages/collections_featured.php",
array(
"new" => "true",
"cta" => "true",
"parent" => $parent,
)
),
$rendering_options
);
}
if (allow_upload_to_collection($parent_collection_data)) {
$upload_url = generateURL(
"{$baseurl_short}pages/edit.php",
array(
"uploader" => $top_nav_upload_type,
"ref" => -$userref,
"collection_add" => $parent
)
);
if ($upload_then_edit) {
$upload_url = generateURL("{$baseurl_short}pages/upload_batch.php", array("collection_add" => $parent));
}
$rendering_options["html_h2_span_class"] = "fa fa-fw fa-upload";
$rendering_options["centralspaceload"] = true;
render_new_featured_collection_cta($upload_url, $rendering_options);
}
}
?>
</div><!-- End of BasicsBox FeaturedSimpleLinks -->
<script>
jQuery(document).ready(function () {
if (jQuery(window).width() > 600) {
jQuery('.FeaturedSimpleTile').hover(
function(e) {
tileid = jQuery(this).attr('id').substring(19);
jQuery('#FeaturedSimpleTileActions_' + tileid).stop(true, true).slideDown();
},
function(e) {
tileid = jQuery(this).attr('id').substring(19);
jQuery('#FeaturedSimpleTileActions_' + tileid).stop(true, true).slideUp();
});
} else {
jQuery('.FeaturedSimpleTileActions').css('display', 'block');
}
// Get and update display for total resource count for each of the rendered featured collections (@see render_featured_collection() for more info)
var fcs_waiting_total = jQuery('.FeaturedSimpleTile.FullWidth .FeaturedSimpleTileContents h2 span[data-tag="resources_count"]');
var fc_refs = [];
fcs_waiting_total.each(function(i, v) {
fc_refs.push(jQuery(v).data('fc-ref'));
});
if (fc_refs.length > 0) {
api('get_collections_resource_count', {'refs': fc_refs.join(',')}, function(response) {
var lang_resource = '<?php echo escape($lang['youfoundresource']); ?>';
var lang_resources = '<?php echo escape($lang['youfoundresources']); ?>';
Object.keys(response).forEach(function(k) {
var total_count = response[k];
jQuery('.FeaturedSimpleTile.FullWidth .FeaturedSimpleTileContents h2 span[data-tag="resources_count"][data-fc-ref="' + k + '"]')
.text(total_count + ' ' + (total_count == 1 ? lang_resource : lang_resources));
});
},
<?php echo generate_csrf_js_object('get_collections_resource_count'); ?>
);
}
<?php if (!$themes_simple_view) { ?>
// Load collection actions when dropdown is clicked
jQuery('.fcollectionactions').on("focus", function(e) {
var el = jQuery(this);
if (el.attr('data-actions-populating') != '0') {
return false
}
el.attr('data-actions-populating','1');
var action_selection_id = el.attr('id');
var colref = el.attr('data-col-id');
LoadActions('themes',action_selection_id,'collection',colref);
});
<?php } ?>
});
<?php if ($allow_fc_reorder) { ?>
// Re-order capability
jQuery(function() {
// Disable for touch screens
if (is_touch_device()) {
return false;
}
jQuery('.BasicsBox.FeaturedSimpleLinks').sortable({
items: '.SortableItem',
distance: 20,
update: function(event, ui) {
let html_ids_new_order = jQuery('.BasicsBox.FeaturedSimpleLinks').sortable('toArray');
let fcs_new_order = html_ids_new_order.map(id => jQuery('#' + id).data('fc-ref'));
console.debug('fcs_new_order=%o', fcs_new_order);
<?php if ($descthemesorder) { ?>
fcs_new_order = fcs_new_order.reverse();
console.debug('fcs_new_order_reversed=%o', fcs_new_order);
<?php } ?>
api(
'reorder_featured_collections',
{'refs': fcs_new_order},
null,
<?php echo generate_csrf_js_object('reorder_featured_collections'); ?>
);
}
});
});
<?php } ?>
</script>
<?php
if ($themes_show_background_image && !$full_width) {
$slideshow_files = get_slideshow_files_data();
if (!$featured_collection_static_bg && ($parent > 0 || ($smart_rtf > 0 && count($smart_fcs_list) > 0))) {
// Overwrite background_image_url with theme specific ones
$get_fc_imgs_ctx = array("limit" => 1);
if ($parent > 0) {
$collection_resources = get_collection_resources($parent);
$parent_collection_data["has_resources"] = (is_array($collection_resources) && !empty($collection_resources) ? 1 : 0);
// get_featured_collection_resources() is expecting a featured collection structure. $parent_collection_data being a
// collection structure is a superset containing the required information (ref, parent, has_resources) for the function to work
$get_fc_imgs_ctx["use_thumbnail_selection_method"] = true;
$get_fc_imgs_ctx["all_fcs"] = $all_fcs;
$bg_fc_images = get_featured_collection_resources($parent_collection_data, $get_fc_imgs_ctx);
$bg_fc_images = generate_featured_collection_image_urls($bg_fc_images, "scr");
} elseif (count($smart_fcs_list) > 0) {
$get_fc_imgs_ctx["smart"] = true;
foreach ($smart_fcs_list as $smart_fc) {
$smart_fc_images = get_featured_collection_resources($smart_fc, $get_fc_imgs_ctx);
$smart_fc_images = generate_featured_collection_image_urls($smart_fc_images, "scr");
if (!empty($smart_fc_images)) {
$bg_fc_images = $smart_fc_images;
break;
}
}
}
if (isset($bg_fc_images) && is_array($bg_fc_images) && !empty($bg_fc_images)) {
if (isset($bg_fc_images[0]["path"]) && strpos($bg_fc_images[0]["path"], '/gfx/') === false) {
$background_image_url = $bg_fc_images[0]["path"]; # get_fc_imgs_ctx is limiting to 1 so we know we have this
}
// Reset slideshow files as we want to use the featured collection image
$slideshow_files = array();
}
}
?>
<script>
var SlideshowImages = new Array();
var SlideshowCurrent = -1;
var big_slideshow_timer = <?php echo $slideshow_photo_delay; ?>;
<?php
foreach ($slideshow_files as $slideshow_file_info) {
if ((bool) $slideshow_file_info['featured_collections_show'] === false) {
continue;
}
$image_download_url = "{$baseurl_short}pages/download.php?slideshow={$slideshow_file_info['ref']}";
$image_resource = isset($slideshow_file_info['link']) ? $slideshow_file_info['link'] : '';
?>
RegisterSlideshowImage('<?php echo $image_download_url; ?>', '<?php echo $image_resource; ?>');
<?php
}
if (!$featured_collection_static_bg && isset($background_image_url) && trim($background_image_url) != '') {
?>
RegisterSlideshowImage('<?php echo $background_image_url; ?>', '', true);
<?php
}
?>
jQuery(document).ready(function() {
ClearTimers();
ActivateSlideshow();
});
</script>
<?php
}
include "../include/footer.php";

17
pages/contact.php Executable file
View File

@@ -0,0 +1,17 @@
<?php
include_once "../include/boot.php";
if (!hook("authenticate")) {
include "../include/authenticate.php";
}
include "../include/header.php";
?>
<div class="BasicsBox">
<h1><?php echo escape($lang["contactus"]); ?></h1>
<p><?php echo text("contact")?></p>
</div>
<?php
include "../include/footer.php";

View File

@@ -0,0 +1,541 @@
<?php
include '../include/boot.php';
include '../include/authenticate.php';
include_once '../include/pdf_functions.php';
$collection = getval('ref', '', true);
$collectiondata = get_collection($collection);
$ajax = ('true' == getval('ajax', '') ? true : false);
$sheetstyle = getval('sheetstyle', 'list');
$field_value_limit = getval('field_value_limit', 0);
$filename_uid = generateUserFilenameUID($userref);
$error = getval("error", "");
$order_by = getval("order_by", "");
if ($contactsheet_use_field_templates && !isset($contactsheet_field_template)) {
$contactsheet_use_field_templates = false;
}
$templates = get_pdf_templates("contact_sheet");
if ($contactsheet_use_field_templates) {
$field_template = getval('field_template', 0, true);
$sheetstyle_fields = $contactsheet_field_template[$field_template]['fields'];
} else {
switch ($sheetstyle) {
case 'thumbnails':
$sheetstyle_fields = $config_sheetthumb_fields;
break;
case 'list':
$sheetstyle_fields = $config_sheetlist_fields;
break;
case 'single':
$sheetstyle_fields = $config_sheetsingle_fields;
break;
}
}
/* Depending on the style, users get different fields to select from.
Super Admins decide what fields they can see based on config options (e.g. $config_sheetthumb_fields)and permissions
Note: By default we use thumbnails fields
*/
$available_contact_sheet_fields = array();
if (!$contactsheet_use_field_templates) {
$available_contact_sheet_fields[] = array(
'ref' => '',
'title' => $lang['allfields']
);
}
foreach (get_fields($sheetstyle_fields, true) as $field_data) {
$available_contact_sheet_fields[] = $field_data;
}
if ($ajax && 'get_sheetstyle_fields' == getval('action', '')) {
$response = array();
foreach ($available_contact_sheet_fields as $field_data) {
$response[] = array(
'ref' => $field_data['ref'],
'title' => i18n_get_translated($field_data['title']),
);
}
echo json_encode($response);
exit();
}
include '../include/header.php';
?>
<div class="BasicsBox" >
<h1><?php echo escape($lang['contactsheetconfiguration']); ?></h1>
<?php
# Check access
if (!collection_readable($collection)) {
echo escape($lang["no_access_to_collection"]);
echo "</div></div>";
include "../include/footer.php";
exit();
}
?>
<p>
<?php
echo strip_tags_and_attributes($lang["contactsheetintrotext"]);
render_help_link("user/contact-sheet");
?>
</p>
<?php if ($error != "" && isset($lang[$error])) {
echo "<div class='PageInformal' name='error' id='error'>" . escape($lang[$error]) . "</div>";
} ?>
<!-- each time the form is modified, the variables are sent to contactsheet.php with preview=true
contactsheet.php makes just the first page of the pdf (with col size images)
and then thumbnails it for the ajax request. This creates a very small but helpful
preview image that can be judged before initiating a download of sometimes several MB.-->
<form method="post" name="contactsheetform" id="contactsheetform" action="<?php echo $baseurl_short; ?>pages/ajax/contactsheet.php">
<?php generateFormToken("contactsheetform"); ?>
<input type=hidden name="c" value="<?php echo escape($collection); ?>">
<input type=hidden name="field_value_limit" value="<?php echo escape($field_value_limit); ?>">
<?php
if (!$contactsheet_sorting) {
?>
<input type=hidden name="order_by" value="<?php echo escape($order_by); ?>">
<?php
}
?>
<div class="BasicsBox" style="width:450px;float:left;margin-top:0;" >
<div id="contact-sheet--collectionname" class="Question">
<label><?php echo escape($lang["collectionname"]); ?></label>
<span><?php echo i18n_get_collection_name($collectiondata); ?></span>
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="sheetstyle"><?php echo escape($lang["display"]); ?></label>
<select
class="shrtwidth"
name="sheetstyle"
id="sheetstyle"
onchange="
if (jQuery('#sheetstyle').val()=='list') {
document.getElementById('OrientationOptions').style.display='block';
document.getElementById('ThumbnailOptions').style.display='none';
if (document.getElementById('size_options')) {
document.getElementById('size_options').style.display='none';
}
updateAvailableContactSheetFields('list');
} else if (jQuery('#sheetstyle').val()=='single') {
document.getElementById('ThumbnailOptions').style.display='none';
if (document.getElementById('size_options')) {
document.getElementById('size_options').style.display='block';
}
updateAvailableContactSheetFields('single');
} else if (jQuery('#sheetstyle').val()=='thumbnails') {
document.getElementById('OrientationOptions').style.display='block';
document.getElementById('ThumbnailOptions').style.display='block';
if (document.getElementById('size_options')) {
document.getElementById('size_options').style.display='none';
}
updateAvailableContactSheetFields('thumbnails');
}
jQuery().rsContactSheet('revert','<?php echo (int) $collection; ?>','<?php echo $filename_uid; ?>');"
>
<?php
foreach ($templates as $template) {
echo "<option value='" . escape($template) . "'>" . (isset($lang[$template]) ? $lang[$template] : escape($template)) . "</option>";
}
?>
</select>
<div class="clearerleft"></div>
<script>
function updateAvailableContactSheetFields(style) {
var contact_sheet_fields_selector = jQuery('#selected_contact_sheet_fields');
var post_url = '<?php echo $baseurl; ?>/pages/contactsheet_settings.php';
var post_data = {
ajax: true,
sheetstyle: style,
action: 'get_sheetstyle_fields',
};
jQuery.get(post_url, post_data, function(response) {
if (typeof response !== 'undefined') {
var response_obj = JSON.parse(response);
// Remove all options
contact_sheet_fields_selector.empty();
var x;
for (x in response_obj) {
var contact_sheet_field_obj = response_obj[x];
var fieldToAdd = '<span id="csf' + Number(contact_sheet_field_obj.ref) + '">';
fieldToAdd += '<input type="checkbox" ';
fieldToAdd += 'name="selected_contact_sheet_fields[]" ';
fieldToAdd += 'class="selected_contact_sheet_field' + (Number(contact_sheet_field_obj.ref) == 0 ? 'all" ' : '" ');
fieldToAdd += 'value="' + contact_sheet_field_obj.ref + '" ';
fieldToAdd += 'id="selected_contact_sheet_fields' + Number(contact_sheet_field_obj.ref) + '" checked>';
fieldToAdd += '<label for="selected_contact_sheet_fields' + Number(contact_sheet_field_obj.ref) + '">' + contact_sheet_field_obj.title + '</label><br /></span>';
contact_sheet_fields_selector.append(fieldToAdd);
}
jQuery(".selected_contact_sheet_fieldall").bind("change", checkAll);
jQuery(".selected_contact_sheet_field").bind("click", checkEachField);
return true;
}
});
return false;
}
</script>
</div>
<?php
if ($error != "contactsheet_data_toolong") {
echo "<input type=hidden name='field_value_limit' value=" . urlencode($field_value_limit) . ">";
} else {
?>
<div class="Question">
<label for="field_value_limit"><?php echo escape($lang["contactsheet_data_field_value_limit"]); ?></label>
<input type="number" name='field_value_limit' value='<?php echo urlencode($field_value_limit); ?>'>
<div class="clearerleft"></div>
</div>
<?php
}
if ($contact_sheet_include_header_option) {
?>
<div class="Question">
<label for="includeheader"><?php echo escape($lang["contact_sheet-include_header_option"]); ?></label>
<select class="shrtwidth" name="includeheader" id="includeheader" onchange="jQuery().rsContactSheet('revert','<?php echo (int) $collection; ?>','<?php echo $filename_uid; ?>');">
<option value="true"><?php echo escape($lang["yes"]); ?></option>
<option value="false" <?php echo (!$contact_sheet_include_header) ? " selected" : ''; ?>>
<?php echo escape($lang["no"]); ?>
</option>
</select>
<div class="clearerleft"></div>
</div>
<?php
}
if ($contact_sheet_single_select_size) {
$sizes = get_all_image_sizes(false, false);
?>
<div id="size_options" class="Question" style="display:none">
<label for="ressize"><?php echo escape($lang["contact_sheet-single_select_size"]); ?></label>
<select class="shrtwidth" name="ressize" id="ressize" onchange="jQuery().rsContactSheet('revert','<?php echo (int) $collection; ?>','<?php echo $filename_uid; ?>');">
<?php
foreach ($sizes as $size) {
echo ' <option value="' . $size['id'] . '"' . ($size['id'] == 'lpr' ? ' selected' : '') . '>' . escape($size['name']) . '</option>';
}
?>
</select>
<div class="clearerleft"></div>
</div>
<?php
}
if (isset($contact_sheet_logo_option) && $contact_sheet_logo_option && isset($contact_sheet_logo)) {
?>
<div class="Question">
<label for="addlogo"><?php echo escape($lang["contact_sheet-add_logo_option"]); ?></label>
<select class="shrtwidth" name="addlogo" id="addlogo" onchange="jQuery().rsContactSheet('revert','<?php echo (int) $collection; ?>','<?php echo $filename_uid; ?>');">
<option value="true"><?php echo escape($lang["yes"]); ?></option>
<option value="false"><?php echo escape($lang["no"]); ?></option>
</select>
<div class="clearerleft"></div>
</div>
<?php
}
if ($contact_sheet_add_link_option) {
?>
<div class="Question">
<label for="addlink"><?php echo escape($lang["contact_sheet-add_link_option"]); ?></label>
<select class="shrtwidth" name="addlink" id="addlink" onchange="jQuery().rsContactSheet('revert','<?php echo (int) $collection; ?>','<?php echo $filename_uid; ?>');">
<option value="true"><?php echo escape($lang["yes"]); ?></option>
<option value="false" <?php echo (!$contact_sheet_add_link) ? " selected" : ''; ?>>
<?php echo escape($lang["no"]); ?>
</option>
</select>
<div class="clearerleft"></div>
</div>
<?php
}
if ($contact_sheet_field_name_option) {
?>
<div class="Question">
<label for="addfieldname"><?php echo escape($lang["contact_sheet-field_name_option"]); ?></label>
<select class="shrtwidth" name="addfieldname" id="addfieldname" onchange="jQuery().rsContactSheet('revert','<?php echo (int) $collection; ?>','<?php echo $filename_uid; ?>');">
<option value="true"><?php echo escape($lang["yes"]); ?></option>
<option value="false"><?php echo escape($lang["no"]); ?></option>
</select>
<div class="clearerleft"></div>
</div>
<?php
}
if ($contactsheet_use_field_templates) {
?>
<div class="Question">
<label for="field_template"><?php echo escape($lang['contact_sheet_field_template']); ?></label>
<select id="field_template" class="shrtwidth" name="field_template" onchange="updateAvailableContactSheetFieldsTemplate(jQuery('#field_template').val());jQuery().rsContactSheet('revert','<?php echo (int) $collection; ?>','<?php echo $filename_uid; ?>');">
<?php
$t_count = count($contactsheet_field_template);
for ($t = 0; $t < $t_count; $t++) {
?>
<option value="<?php echo $t; ?>"<?php echo $field_template == $t ? 'selected' : ''; ?>>
<?php echo escape($contactsheet_field_template[$t]['name']); ?>
</option>
<?php
}
?>
</select>
<script>
function updateAvailableContactSheetFieldsTemplate(template) {
var contact_sheet_fields_selector = jQuery('#selected_contact_sheet_fields');
var post_url = '<?php echo $baseurl; ?>/pages/contactsheet_settings.php';
var post_data = {
ajax: true,
field_template: template,
action: 'get_sheetstyle_fields',
};
jQuery.get(post_url, post_data, function(response) {
if (typeof response !== 'undefined') {
var response_obj = JSON.parse(response);
// Remove all options
contact_sheet_fields_selector.empty();
var x;
for (x in response_obj) {
var contact_sheet_field_obj = response_obj[x];
contact_sheet_fields_selector.append(contact_sheet_field_obj.title + '<br/>');
}
return true;
}
});
return false;
}
</script>
</div>
<?php
}
?>
<div class="Question">
<label for="selected_contact_sheet_fields">
<?php echo escape($contactsheet_use_field_templates ? $lang['contact_sheet_field_template_fields'] : $lang['contact_sheet_select_fields']); ?>
</label>
<?php
if ($contactsheet_use_field_templates) {
$fieldlist = '';
foreach ($available_contact_sheet_fields as $contact_sheet_field) {
$fieldlist .= $contact_sheet_field['title'] . '<br/>';
}
?>
<span id="selected_contact_sheet_fields"><?php echo $fieldlist ?></span>
<?php
} else {
?>
<fieldset name="selected_contact_sheet_fields[]" id="selected_contact_sheet_fields" class="MultiRTypeSelect" style="width:420px;">
<?php
foreach ($available_contact_sheet_fields as $contact_sheet_field) {
?>
<span id="csf<?php echo (int) $contact_sheet_field['ref']; ?>">
<input
type="checkbox"
value="<?php echo (int) $contact_sheet_field['ref']; ?>"
class="selected_contact_sheet_field<?php echo (int) $contact_sheet_field['ref'] == 0 ? 'all' : ''; ?>"
name="selected_contact_sheet_fields[]"
id="selected_contact_sheet_fields<?php echo (int) $contact_sheet_field['ref']; ?>"
checked="checked"
/>
<label for="selected_contact_sheet_fields<?php echo (int) $contact_sheet_field['ref']; ?>"><?php echo escape(i18n_get_translated($contact_sheet_field['title'])); ?></label>
<br />
</span>
<?php
}
?>
</fieldset>
<script>
function checkAll(e) {
if (this.checked) {
jQuery(".selected_contact_sheet_field").each(function() {
this.checked = true;
})
} else {
jQuery(".selected_contact_sheet_field").each(function() {
this.checked = false;
})
}
}
function checkEachField(e) {
if (jQuery(this).is(":checked")) {
var isAllChecked = 0;
jQuery(".selected_contact_sheet_field").each(function() {
if (!this.checked) {
isAllChecked = 1;
}
});
if (isAllChecked == 0) {
jQuery(".selected_contact_sheet_fieldall").prop("checked", true);
}
} else {
jQuery(".selected_contact_sheet_fieldall").prop("checked", false);
}
}
jQuery(document).ready(function() {
jQuery(".selected_contact_sheet_fieldall").bind("change", checkAll);
jQuery(".selected_contact_sheet_field").bind("click", checkEachField);
});
</script>
<?php
}
?>
<div class="updatePreviewButton">
<a href="#" onclick="jQuery().rsContactSheet('preview','<?php echo (int) $collection; ?>','<?php echo $filename_uid; ?>'); return false;">
<i aria-hidden="true" class="fa fa-fw fa-arrows-rotate"></i>
<?php echo escape($lang["contact_sheet_update_preview"]); ?>
</a>
</div>
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="size"><?php echo escape($lang["size"]); ?></label>
<select class="shrtwidth" name="size" id="size" style="width: 300px;" onchange="jQuery().rsContactSheet('revert','<?php echo (int) $collection; ?>','<?php echo $filename_uid; ?>');">
<?php echo $papersize_select; ?>
</select>
<div class="clearerleft"> </div>
</div>
<?php
if ($contactsheet_sorting) {
$all_field_info = get_fields_for_search_display(array_unique(array_merge($thumbs_display_fields, $list_display_fields, $config_sheetlist_fields, $config_sheetthumb_fields)));
?>
<div class="Question">
<label for="orderby"><?php echo escape($lang["sortorder"]); ?></label>
<select class="shrtwidth" name="order_by" id="orderby" onchange="jQuery().rsContactSheet('preview','<?php echo (int) $collection; ?>','<?php echo $filename_uid; ?>');">
<option value="collection" selected><?php echo escape($lang["collection-order"]); ?></option>
<option value="date"><?php echo escape($lang["date"]); ?></option>
<option value="colour"><?php echo escape($lang["colour"]); ?></option>
<option value="resourceid"><?php echo escape($lang["resourceid"]); ?></option>
<?php
foreach ($all_field_info as $sortable_field) {
// don't display the ones we've already covered above.
if (!($sortable_field["title"] == $lang["date"] || $sortable_field["title"] == $lang["colour"])) {
?>
<option value="<?php echo $sortable_field['ref']; ?>"><?php echo escape($sortable_field["title"]) ?></option>
<?php
}
}
?>
</select>
<div class="clearerleft"></div>
</div>
<div class="Question">
<label for="sort"><?php echo escape($lang["sort-type"]) ?></label>
<select class="shrtwidth" name="sort" id="sort" onchange="jQuery().rsContactSheet('preview','<?php echo (int) $collection; ?>','<?php echo $filename_uid; ?>');">
<option value="asc" selected><?php echo escape($lang["ascending"]); ?></option>
<option value="desc"><?php echo escape($lang["descending"]); ?></option>
</select>
<div class="clearerleft"></div>
</div>
<?php
}
?>
<div id="ThumbnailOptions" class="Question">
<label for="ThumbnailOptions"><?php echo escape($lang["columns"]); ?></label>
<select class="shrtwidth" name="columns" id="ThumbnailOptions" onchange="jQuery().rsContactSheet('revert','<?php echo (int) $collection; ?>','<?php echo $filename_uid; ?>');">
<?php echo $columns_select ?>
</select>
<div class="clearerleft"></div>
</div>
<div id="OrientationOptions" class="Question">
<label for="orientation"><?php echo escape($lang["orientation"]); ?></label>
<select class="shrtwidth" name="orientation" id="orientation" onchange="jQuery().rsContactSheet('revert','<?php echo (int) $collection; ?>','<?php echo $filename_uid; ?>');">
<option value="P"><?php echo escape($lang["portrait"]); ?></option>
<option value="L"><?php echo escape($lang["landscape"]); ?></option>
</select>
<div class="clearerleft"></div>
</div>
<?php
if ($contact_sheet_force_watermarks) {
if ($contact_sheet_force_watermark_option) {
?>
<div id="WatermarkOptions" class="Question">
<label for="force_watermark"><?php echo escape($lang["show_watermarked_previews_and_thumbnails"]); ?></label>
<select class="shrtwidth" name="force_watermark" id="force_watermark" onchange="jQuery().rsContactSheet('revert','<?php echo (int) $collection; ?>','<?php echo $filename_uid; ?>');">
<option value="true"><?php echo escape($lang["yes"]); ?></option>
<option value="false"><?php echo escape($lang["no"]); ?></option>
</select>
<div class="clearerleft"></div>
</div>
<?php
} else {
?>
<input type="hidden" name="force_watermark" id="force_watermark" value="true" />
<?php
}
}
?>
<div name="previewPageOptions" id="previewPageOptions" class="Question" style="display:none">
<label for="previewpage"><?php echo escape($lang['previewpage']); ?></label>
<select class="shrtwidth" name="previewpage" id="previewpage" onchange="jQuery().rsContactSheet('preview','<?php echo (int) $collection; ?>','<?php echo $filename_uid; ?>');"></select>
</div>
<div class="QuestionSubmit">
<input name="save" type="submit" value="<?php echo escape($lang["create"]); ?>" />
</div>
</div> <!-- end of small BasicBox -->
</form>
</div>
<div>
<!-- this is the container for some Ajax fun. The image will go here...-->
<?php
$cs_size = explode("x", $contact_sheet_preview_size);
$height = $cs_size[1];
if ($contact_sheet_previews) {
?>
<div style="float:left;padding:0px -50px 15px 0;height:<?php echo escape($height) ?>px;margin-top:-15px;margin-right:-50px">
<img alt="" id="contact-sheet--previewimage" name="previewimage" src=""/>
</div>
<?php
}
?>
</div>
<script>
jQuery().setContactSheetCSRFTokenIdentifier('<?php echo $GLOBALS['CSRF_token_identifier']; ?>');
jQuery().rsContactSheet('preview','<?php echo (int) $collection; ?>','<?php echo $filename_uid; ?>');
</script>
<?php
include '../include/footer.php';

35
pages/content.php Normal file
View File

@@ -0,0 +1,35 @@
<?php
include_once "../include/boot.php";
include "../include/authenticate.php";
include "../include/header.php";
$content = getval("content", "");
if ($content != "") {
$content = text($content);
} else {
$content = "This is default content text. You can create text (including html) in Admin->Manage Content and display it here.";
}
$modal = getval("modal", "");
$allowed_tags = array_merge(array("a"), $permitted_html_tags);
$allowed_attributes = array_merge(array("href","target"), $permitted_html_attributes);
$content = strip_tags_and_attributes($content, $allowed_tags, $allowed_attributes);
?>
<div class="BasicsBox">
<?php if ($modal) { ?>
<div class="backtoresults">
<a href="#" onclick="ModalClose();" class="closeLink fa fa-times" title="<?php echo escape($lang["close"]); ?>"></a>
</div>
<?php
}
echo $content;
?>
</div>
<?php
include "../include/footer.php";
?>

70
pages/contribute.php Executable file
View File

@@ -0,0 +1,70 @@
<?php
require_once "../include/boot.php";
require_once "../include/authenticate.php";
if (!checkperm("d") && !(checkperm('c') && checkperm('e0'))) {
exit("Permission denied.");
}
include "../include/header.php";
?>
<div class="BasicsBox">
<h1><?php echo escape($lang["mycontributions"]); ?></h1>
<p>
<?php
echo text("introtext");
render_help_link("user/uploading");
?>
</p>
<div class="VerticalNav">
<ul>
<li>
<i class="fa fa-fw fa-upload"></i>
<a
onclick="return CentralSpaceLoad(this,true);"
<?php
#We need to point to the right upload sequence based on $upload_then_edit
if ($upload_then_edit == 1) { ?>
href="<?php echo $baseurl_short?>pages/upload_batch.php"
<?php } else { ?>
href="<?php echo $baseurl_short?>pages/edit.php?ref=-<?php echo urlencode($userref) ?>&uploader=batch"
<?php } ?>
>
<?php echo escape($lang["addresourcebatchbrowser"]);?>
</a>
</li>
<?php
foreach (get_workflow_states() as $workflow_state) {
if ($workflow_state != 0 && checkperm("z{$workflow_state}")) {
continue;
}
$ws_a_href = generateURL(
"{$baseurl_short}pages/search.php",
array(
'search' => "!contributions{$userref}",
'archive' => $workflow_state,
)
);
$ws_a_text = str_replace('%workflow_state_name', $lang["status{$workflow_state}"], $lang["view_my_contributions_ws"]);
$icon = $workflowicons[$workflow_state] ?? (WORKFLOW_DEFAULT_ICONS[$workflow_state] ?? WORKFLOW_DEFAULT_ICON);
?>
<li>
<a href="<?php echo $ws_a_href; ?>" onclick="return CentralSpaceLoad(this, true);">
<i class="fa-fw <?php echo escape($icon); ?>"></i>&nbsp;<?php echo escape($ws_a_text); ?>
</a>
</li>
<?php
}
?>
</ul>
</div>
</div>
<?php
include "../include/footer.php";

View File

@@ -0,0 +1,148 @@
<?php
include_once '../include/boot.php';
include_once '../include/authenticate.php';
include_once '../include/csv_export_functions.php';
$search = getval('search', '');
$restypes = getval('restypes', '');
$order_by = getval('order_by', '');
$archive = getval('archive', '');
$access = getval('access', null, true);
$sort = getval('sort', '');
$offline = getval("process_offline", "") != "";
$submitted = getval("submit", "") != "";
$personaldata = (getval('personaldata', '') != '');
$allavailable = (getval('allavailable', '') != '');
$do_search_result = do_search($search, $restypes, $order_by, $archive, 1, $sort, false, DEPRECATED_STARSEARCH, false, false, '', false, false, false, false, false, $access);
$resources_found = 0;
if (is_array($do_search_result)) {
$resources_found = count($do_search_result);
}
$resources_to_process = array();
if ($resources_found > 0) {
$search_chunk_size = 100000;
$chunk_offset = 0; // Return data in batches. Required for particularly large csv export where there is a risk of PHP memory_limit being exceeded by search returning too many results.
while ($chunk_offset < $resources_found) {
$search_results = do_search($search, $restypes, $order_by, $archive, array($chunk_offset, $search_chunk_size), $sort, false, DEPRECATED_STARSEARCH, false, false, '', false, false, true, false, false, $access, null);
$resources_to_process = array_merge($resources_to_process, array_column($search_results["data"], "ref"));
$chunk_offset = $chunk_offset + $search_chunk_size;
}
}
$resultcount = count($resources_to_process);
if ($resultcount == 0) {
$error = $lang["noresourcesfound"];
}
if ($submitted && $resultcount > 0) {
$findstrings = array("[search]","[time]");
$replacestrings = array(mb_substr(safe_file_name($search), 0, 150), date("Ymd-H:i", time()));
$csv_filename = str_replace($findstrings, $replacestrings, $lang["csv_export_filename"]);
$csv_filename_noext = strip_extension($csv_filename);
if ($offline || (($resultcount > $metadata_export_offline_limit) && $offline_job_queue)) {
// Generate offline job
$job_data = array();
$job_data["personaldata"] = $personaldata;
$job_data["allavailable"] = $allavailable;
$job_data["exportresources"] = $resources_to_process;
$job_data["search"] = $search;
$job_data["restypes"] = $restypes;
$job_data["archive"] = $archive;
$job_data["access"] = $access;
$job_data["sort"] = $sort;
$job_code = "csv_metadata_export_" . md5($userref . json_encode($job_data)); // unique code for this job, used to prevent duplicate job creation.
$jobadded = job_queue_add("csv_metadata_export", $job_data, $userref, '', $lang["csv_export_file_ready"] . " : " . $csv_filename, $lang["download_file_creation_failed"], $job_code);
if ((string)(int)$jobadded !== (string)$jobadded) {
$message = $lang["oj-creation-failure-text"];
} else {
$message = str_replace('[jobnumber]', $jobadded, $lang['oj-creation-success']);
}
} else {
log_activity($lang['csvExportResultsMetadata'], LOG_CODE_DOWNLOADED, $search . ($restypes == '' ? '' : ' (' . $restypes . ')'));
debug("csv_export_metadata created zip download file {$csv_filename}");
if (!hook('csvreplaceheader')) {
header("Content-type: application/octet-stream");
header("Content-disposition: attachment; filename=" . $csv_filename_noext . ".csv");
}
generateResourcesMetadataCSV($resources_to_process, $personaldata, $allavailable);
exit();
}
}
include "../include/header.php";
if (isset($error)) {
echo "<div class=\"FormError\">" . $lang["error"] . ":&nbsp;" . escape($error) . "</div>";
} elseif (isset($message)) {
echo "<div class=\"PageInformal\">" . escape($message) . "</div>";
}
?>
<div class="BasicsBox">
<!-- Below is intentionally not an AJAX POST -->
<form method="post" action="<?php echo $baseurl_short?>pages/csv_export_results_metadata.php" >
<?php generateFormToken("csv_export_results"); ?>
<input type="hidden" name="search" value="<?php echo escape((string)$search) ?>" />
<input type="hidden" name="restypes" value="<?php echo escape((string)$restypes) ?>" />
<input type="hidden" name="order_by" value="<?php echo escape((string)$order_by) ?>" />
<input type="hidden" name="archive" value="<?php echo escape((string)$archive) ?>" />
<input type="hidden" name="access" value="<?php echo escape((string)$access) ?>" />
<input type="hidden" name="sort" value="<?php echo escape((string)$sort) ?>" />
<h1>
<?php
echo escape($lang["csvExportResultsMetadata"]);
render_help_link("user/csv_export");
?>
</h1>
<div class="Question" id="question_personal">
<label for="personaldata"><?php echo escape($lang['csvExportResultsMetadataPersonal']) ?></label>
<input name="personaldata" id="personaldata" type="checkbox" value="true" style="margin-top:7px;" <?php echo $personaldata ? " checked " : ''; ?>>
<div class="clearerleft"></div>
</div>
<div class="Question" id="question_personal">
<label for="allavailable"><?php echo escape($lang['csvExportResultsMetadataAll']) ?></label>
<input name="allavailable" id="allavailable" type="checkbox" value="true" style="margin-top:7px;" <?php echo $allavailable ? " checked " : ''; ?>>
<div class="clearerleft"></div>
</div>
<div class="Question" >
<label for="process_offline"><?php echo escape($lang["csv_export_offline_option"]); ?></label>
<?php
if ($offline_job_queue) {
echo "<input type='checkbox' id='process_offline' name='process_offline' value='1' " . ($resultcount > $metadata_export_offline_limit ? "onclick='styledalert(\"" . escape($lang["csvExportResultsMetadata"]) . "\",\"" . escape(str_replace("[resource_count]", $metadata_export_offline_limit, $lang['csv_export_offline_only'])) . "\");return false;' checked" : ($submitted && !$offline ? "" : " checked ")) . ">";
} else {
echo "<div class='Fixed'>" . escape($lang["offline_processing_disabled"]) . "</div>";
}?>
<div class="clearerleft"></div>
</div>
<div class="QuestionSubmit">
<input type="hidden" name="submit" value="true" />
<input name="submit" type="submit" id="submit" value="<?php echo escape($lang["action-download"]); ?>" />
</div>
</form>
</div>
<?php
include "../include/footer.php";

762
pages/dash_tile.php Executable file
View File

@@ -0,0 +1,762 @@
<?php
/*
* User Dash - Tile Interface
* Page for building tiles for the homepage dash interface
*
*/
include "../include/boot.php";
$k = getval("k", "");
include "../include/authenticate.php";
include_once "../include/dash_functions.php";
if (!checkPermission_dashcreate()) {
exit($lang["error-permissiondenied"]);
}
global $baseurl,$baseurl_short,$userref,$managed_home_dash;
if ($managed_home_dash && !(checkperm("h") && !checkperm("hdta")) || (checkperm("dta") && !checkperm("h"))) {
exit($lang["error-permissiondenied"]);
}
$error = false;
$message = false;
/*
* Process Submitted Tile
*/
$submitdashtile = getval("submitdashtile", false);
if ($submitdashtile && enforcePostRequest(false)) {
$buildurl = getval("url", "");
$tlsize = ('double' === getval('tlsize', '') ? 'double' : '');
$buildurl = validate_build_url($buildurl);
if ($buildurl == "") {
$new_buildurl_tltype = getval('tltype', '');
$new_buildurl_tlstyle = getval('tlstyle', '');
$new_buildurl_tlstylecolour = urlencode(getval('tlstylecolour', ''));
# No URL provided - build a URL (standard title types).
$buildurl = "pages/ajax/dash_tile.php?tltype={$new_buildurl_tltype}&tlsize={$tlsize}&tlstyle={$new_buildurl_tlstyle}";
if ('' != $new_buildurl_tltype && allow_tile_colour_change($new_buildurl_tltype) && '' != $new_buildurl_tlstylecolour) {
$buildurl .= "&tlstylecolour={$new_buildurl_tlstylecolour}";
}
$promoted_image = getval('promoted_image', '');
if ('' != trim($promoted_image)) {
$buildurl .= '&promimg=' . $promoted_image;
}
}
/*
tile_audience can be:
- false for "only me"
- true for "all users"
- specific_user_groups
*/
$tile_audience = getval('tile_audience', '');
$specific_user_groups = getval('specific_user_groups', [], false, 'is_array');
if (checkPermission_dashadmin()) {
switch ($tile_audience) {
case 'true':
case 'specific_user_groups':
$all_users = true;
break;
case 'false':
$all_users = false;
break;
}
} else {
$all_users = false;
}
$title = getval("title", "");
$text = getval("freetext", "");
$default_order_by = getval("default_order_by", "UNSET");
$reload_interval = getval("reload_interval_secs", "");
$resource_count = getval("resource_count", false);
$link = str_replace("&amp;", "&", getval("link", ""));
if (strpos($link, $baseurl_short) === 0) {
$length = strlen($baseurl_short);
$link = substr_replace($link, "", 0, $length);
}
$link = preg_replace("/^\//", "", $link);
#Check for update rather than new
$updatetile = getval("editdashtile", false);
if ($updatetile && is_numeric($updatetile)) {
$tile = get_tile($updatetile);
$buildstring = explode('?', $tile["url"]);
parse_str(str_replace("&amp;", "&", ($buildstring[1] ?? "")), $buildstring);
$buildstring['tltype'] = $buildstring['tltype'] ?? 'ftxt';
#Change of tilestyle?
$tile_style = getval('tlstyle', false);
$promoted_image = getval('promoted_image', false);
$tlstylecolour = urlencode(getval('tlstylecolour', ''));
if ($tile_style) {
$buildurl = str_replace("tlstyle=" . $buildstring["tlstyle"], "tlstyle=" . $tile_style, $tile["url"]);
// If style changed and we can no longer support tile colours, remove it from url
if (!allow_tile_colour_change($buildstring['tltype'], $tile_style) && isset($buildstring['tlstylecolour'])) {
$buildurl = str_replace("&tlstylecolour={$buildstring['tlstylecolour']}", '', $buildurl);
}
// Style changed and we support tile colours
if (allow_tile_colour_change($buildstring['tltype'], $tile_style) && '' != trim($tlstylecolour)) {
if (isset($buildstring['tlstylecolour'])) {
$buildurl = str_replace('tlstylecolour=' . urlencode($buildstring['tlstylecolour']), "tlstylecolour={$tlstylecolour}", $buildurl);
} else {
$buildurl .= "&tlstylecolour={$tlstylecolour}";
}
}
} else {
// Allow changing colours for tile types that don't have a style (e.g ftxt)
if (allow_tile_colour_change($buildstring['tltype']) && '' != trim($tlstylecolour)) {
if (isset($buildstring['tlstylecolour'])) {
$buildurl = str_replace("tlstylecolour=" . urlencode($buildstring['tlstylecolour']), "tlstylecolour={$tlstylecolour}", $buildurl);
} else {
$buildurl .= "&tlstylecolour={$tlstylecolour}";
}
}
}
if ($promoted_image) {
if (isset($buildstring["promimg"])) {
$buildurl = str_replace("promimg=" . $buildstring["promimg"], "promimg=" . $promoted_image, $buildurl);
} else {
$buildurl .= "&promimg=" . escape($promoted_image);
}
}
if (isset($buildstring['tlsize'])) {
$buildurl = str_replace("tlsize={$buildstring['tlsize']}", "tlsize={$tlsize}", $buildurl);
}
if (($tile["all_users"] || $all_users ) && checkPermission_dashadmin()) {
log_activity($lang['manage_all_dash'], LOG_CODE_EDITED, $title . ($text == '' ? '' : " ({$text})"), 'dash_tile', null, $tile['ref']);
$current_specific_user_groups = get_tile_user_groups($tile['ref']);
update_dash_tile($tile, $buildurl, $link, $title, $reload_interval, $all_users, $tile_audience, $current_specific_user_groups, $specific_user_groups, $default_order_by, $resource_count, $text);
} elseif (!$tile["all_users"] && !$all_users) { # Not an all_users tile
$newtile = create_dash_tile($buildurl, $link, $title, $reload_interval, $all_users, $default_order_by, $resource_count, $text);
ps_query("UPDATE user_dash_tile SET dash_tile = ? WHERE dash_tile= ? AND user = ?", ['s', $newtile, 'i', $tile['ref'], 'i', $userref]);
cleanup_dash_tiles();
}
} else {
#CREATE NEW
# check for existing tile with same values
$existing_tile_ref = existing_dash_tile($buildurl, $link, $title, $text, (int) $reload_interval, (int) $all_users, (int) $resource_count);
if ($existing_tile_ref > 0 && !empty($specific_user_groups)) {
$message = str_replace("[existing_tile_ref]", $existing_tile_ref, $lang["existingdashtilefound-2"]) ;
}
$tile = create_dash_tile($buildurl, $link, $title, $reload_interval, $all_users, $default_order_by, $resource_count, $text, 1, $specific_user_groups);
if ($all_users || (!$all_users && !empty($specific_user_groups))) {
log_activity($lang['manage_all_dash'], LOG_CODE_CREATED, $title . ($text == '' ? '' : " ({$text})"), 'dash_tile', null, $tile);
} else {
$existing = add_user_dash_tile($userref, $tile, $default_order_by);
if (isset($existing[0])) {
$error = $lang["existingdashtilefound"];
}
}
}
/* SAVE SUCCESSFUL? */
if (!$error && !$message) {
redirect($baseurl);
exit();
}
include "../include/header.php";
?>
<h1>
<?php
echo escape($lang["createnewdashtile"]);
render_help_link("user/create-dash-tile");
?>
</h1>
<?php if ($error) { ?>
<p class="FormError" style="margin-left:5px;"><?php echo escape($error); ?></p>
<?php
}
if ($message) { ?>
<p style="margin-left:5px;"><?php echo escape($message); ?></p>
<?php
if (strpos($link, "pages/") === 0) {
$length = strlen("pages/");
$link = substr_replace($link, "", 0, $length);
}
}
?>
<a href="<?php echo $link;?>"><?php echo LINK_CARET . escape($lang["returntopreviouspage"]);?></a>
<?php
include "../include/footer.php";
exit();
}
/*
* For displaying a selector for the different styles of tile.
* Styles are config controlled.
*/
function tileStyle($tile_type, $existing = null, $tile_colour = '')
{
global $lang,$tile_styles,$promoted_resource,$resource_count;
if (count($tile_styles[$tile_type]) < 2) {
// If this tile type allows for changing its colour, show it
if (allow_tile_colour_change($tile_type)) {
foreach ($tile_styles[$tile_type] as $style) {
if (allow_tile_colour_change($tile_type, $style)) {
render_dash_tile_colour_chooser($style, $tile_colour);
}
}
}
return false;
}
?>
<div class="Question">
<label for="tltype"><?php echo escape($lang["dashtilestyle"]);?></label>
<table>
<tbody>
<tr>
<?php
$check = true;
foreach ($tile_styles[$tile_type] as $style) {
?>
<td width="10" valign="middle">
<input
type="radio"
class="tlstyle"
id="tile_style_<?php echo escape($style);?>"
name="tlstyle"
value="<?php echo $style;?>"
<?php
if (isset($existing) && $style == $existing) {
echo "checked";
} elseif (!isset($existing) && $check) {
echo "checked";
$check = false;
}
?>
/>
</td>
<td align="left" valign="middle">
<label class="customFieldLabel" for="tile_style_<?php echo escape($style);?>"><?php echo escape($lang["tile_" . $style]);?></label>
</td>
<?php
} ?>
</tr>
</tbody>
</table>
<div class="clearerleft"></div>
<?php
if (allow_tile_colour_change($tile_type)) {
foreach ($tile_styles[$tile_type] as $style) {
if (allow_tile_colour_change($tile_type, $style)) {
render_dash_tile_colour_chooser($style, $tile_colour);
}
}
}
?>
</div>
<?php
}
/*
* Tile Form Entry
*/
$create = getval("create", false);
$edit = getval("edit", false);
$validpage = false;
if ($create) {
$tile_type = getval("tltype", "");
$tile_style = getval('tlstyle', "");
$tile_nostyle = getval("nostyleoptions", false);
$allusers = getval("all_users", false);
$url = getval("url", "");
$modifylink = getval("modifylink", false);
$freetext = getval("freetext", false);
$notitle = getval("notitle", false);
$link = getval("link", "");
$title = getval("title", "");
$current_specific_user_groups = (isset($specific_user_groups) ? $specific_user_groups : array());
$tlsize = ('double' === getval('tlsize', '') ? 'double' : '');
// Promoted resources can be available for search tiles (srch) and feature collection tiles (fcthm)
$promoted_resource = (getval('promoted_resource', "") == "true");
if (!allow_tile_colour_change($tile_type, $tile_style)) {
$tile_nostyle = true;
}
if ($tile_type == "srch") {
$srch = getval("link", "");
$order_by = getval("order_by", "");
$sort = getval("sort", "");
$archive = getval("archive", "");
$daylimit = getval("daylimit", "");
$restypes = getval("restypes", "");
$title = getval("title", "");
$resource_count = getval("resource_count", 0, true);
unset($tile_style);
$srch = urldecode($srch);
$link = $srch . "&order_by=" . urlencode($order_by) . "&sort=" . urlencode($sort) . "&archive=" . urlencode($archive) . "&daylimit=" . urlencode($daylimit) . "&k=" . urlencode($k) . "&restypes=" . urlencode($restypes);
$title = preg_replace("/^.*search=/", "", $srch);
if (substr($title, 0, 11) == "!collection") {
$col = get_collection(preg_replace("/^!collection/", "", $title));
$promoted_resource = true;
$title = $col["name"];
} elseif (substr($title, 0, 7) == "!recent") {
$title = $lang["recent"];
} elseif (substr($title, 0, 5) == "!last") {
$last = preg_replace("/^!last/", "", $title);
$title = ($last != "") ? $lang["last"] . " " . $last : $lang["recent"];
} else {
$title_node = preg_replace("/^.*search=/", "", $srch);
$returned_title = array();
if (count(resolve_nodes_from_string($title_node)) != 0) {
$resolved_nodes = resolve_nodes_from_string($title_node);
$tmp_title = get_node($resolved_nodes[0], $returned_title);
$title = $returned_title['name'];
}
}
}
$pagetitle = $lang["createnewdashtile"];
$formextra = '<input type="hidden" name="submitdashtile" value="true" />';
$validpage = true;
$submittext = $lang["create"];
} elseif ($edit) {
#edit contains the dash_tile record ref
$tile = get_tile($edit);
$allusers = $tile["all_users"];
$url = $tile["url"];
$link = $tile["link"];
$title = $tile["title"];
$resource_count = $tile["resource_count"];
$current_specific_user_groups = get_tile_user_groups($edit);
if (!can_edit_tile($tile['ref'], $allusers, $userref)) {
$validpage = false;
} else {
#Get field data
$buildstring = explode('?', $tile["url"]);
if (isset($buildstring[1])) {
parse_str(str_replace("&amp;", "&", $buildstring[1]), $buildstring);
}
if (isset($buildstring["tltype"])) {
$tile_type = $buildstring["tltype"];
$tile_nostyle = isset($buildstring["tlstyle"]) && $tile_type != "conf" ? false : true;
$tile_style = $buildstring["tlstyle"];
$tile_style_colour = '';
if (allow_tile_colour_change($tile_type) && isset($buildstring['tlstylecolour'])) {
$tile_style_colour = $buildstring['tlstylecolour'];
}
} else {
$tile_type = "";
$tile_nostyle = true;
}
if (!isset($tile_style)) {
$tile_style = "";
}
# Show freetext field if the tile style is not analytics
if ($tile_style != 'analytics') {
$freetext = empty($tile["txt"]) ? "true" : $tile["txt"];
} else {
$freetext = false;
}
$promoted_resource = isset($buildstring["promimg"]) ? (int) $buildstring["promimg"] : true;
$tlsize = (isset($buildstring['tlsize']) && 'double' === $buildstring['tlsize'] ? $buildstring['tlsize'] : '');
$modifylink = ($tile_type == "ftxt") ? true : false;
$notitle = isset($buildstring["nottitle"]) ? true : false;
$pagetitle = $lang["editdashtile"];
$formextra = '<input type="hidden" name="submitdashtile" value="true" />';
$formextra .= '<input type="hidden" name="editdashtile" value="' . $tile["ref"] . '" />';
$validpage = true;
$submittext = $lang["save"];
}
}
/* Start Display*/
include "../include/header.php";
if (!$validpage) {
echo "<h2>" . escape($lang["error"]) . "</h2>";
echo "<p>" . escape($lang["error-dashactionmissing"]) . "</p>";
include "../include/footer.php";
exit;
}
?>
<div class="BasicsBox">
<h1>
<?php
echo $pagetitle;
render_help_link("user/create-dash-tile");
?>
</h1>
<form id="create_dash" name="create_dash" method="post">
<input type="hidden" name="tltype" value="<?php echo escape($tile_type)?>" />
<input type="hidden" name="url" value="<?php echo escape($url); ?>" />
<?php generateFormToken("create_dash"); ?>
<div class="Question">
<label><?php echo escape($lang["preview"]); ?></label>
<br />
<div class="HomePanel DashTile">
<div id="previewdashtile" class="dashtilepreview HomePanelIN HomePanelDynamicDash"></div>
</div>
<div class="clearerleft"></div>
</div>
<?php
echo $formextra;
if ($modifylink) {
?>
<div class="Question">
<label for="link"><?php echo escape($lang["dashtilelink"]);?></label>
<input type="text" name="link" value="<?php echo escape($link); ?>"/>
<div class="clearerleft"></div>
</div>
<?php
} else {
?>
<input type="hidden" name="link" id="previewlink" value="<?php echo escape($link); ?>" />
<?php
}
if (!$notitle) {
?>
<div class="Question">
<label for="title"><?php echo escape($lang["dashtiletitle"]);?></label>
<input type="text" id="previewtitle" name="title" value="<?php echo escape(ucfirst($title)); ?>"/>
<div class="clearerleft"></div>
</div>
<?php
} else { ?>
<input type="hidden" name="notitle" value="1" />
<?php
}
if ($freetext) {
if ($freetext == "true") {
$freetext = "";
}
?>
<div class="Question">
<label for="freetext"><?php echo escape($lang["dashtiletext"]);?></label>
<textarea class="stdwidth" rows="3" type="text" id="previewtext" name="freetext"><?php echo escape(ucfirst($freetext));?></textarea>
<div class="clearerleft"></div>
</div>
<?php
}
if ('' != $tile_type && $tile_type !== "conf") {
?>
<!-- Dash tile size selector -->
<div class="Question">
<label for="tlsize"><?php echo escape($lang['size']); ?></label>
<select id="DashTileSize" class="stdwidth" name="tlsize" onchange="updateDashTilePreview();">
<option value=""><?php echo escape($lang['single_width']); ?></option>
<option value="double"<?php echo 'double' === $tlsize ? ' selected' : ''; ?>><?php echo escape($lang['double_width']); ?></option>
</select>
<div class="clearerleft"></div>
</div>
<?php
}
if (!$tile_nostyle) {
if (isset($tile_style)) {
tileStyle($tile_type, $tile_style, $tile_style_colour);
} else {
tileStyle($tile_type);
}
}
if ($create && 'ftxt' == $tile_type && allow_tile_colour_change($tile_type)) {
render_dash_tile_colour_chooser('ftxt', '');
}
if ($tile_type == "srch") {
?>
<div class="Question" id="showresourcecount" >
<label for="tltype"><?php echo escape($lang["showresourcecount"]);?></label>
<table>
<tbody>
<tr>
<td width="10" valign="middle" >
<input type="checkbox" id="resource_count" name="resource_count" value="1" <?php echo $resource_count ? "checked" : "";?>/>
</td>
</tr>
</tbody>
</table>
<div class="clearerleft"></div>
</div>
<script>
jQuery(".tlstyle").change(function() {
checked = jQuery(".tlstyle:checked").val();
if (checked == "thmbs" || checked == "multi" || checked == "blank") {
jQuery("#showresourcecount").show();
} else {
jQuery("#showresourcecount").hide();
}
});
</script>
<?php
}
// Show promoted resource selector
if (($promoted_resource || 'fcthm' == $tile_type) && allowPromotedResources($tile_type)) {
$resources = array();
if ('srch' == $tile_type) {
$search_string = explode('?', $link);
parse_str(str_replace("&amp;", "&", $search_string[1]), $search_string);
$search = isset($search_string["search"]) ? $search_string["search"] : "";
$restypes = isset($search_string["restypes"]) ? $search_string["restypes"] : "";
$order_by = isset($search_string["order_by"]) ? $search_string["order_by"] : "";
$archive = isset($search_string["archive"]) ? $search_string["archive"] : "";
$sort = isset($search_string["sort"]) ? $search_string["sort"] : "";
$resources = do_search($search, $restypes, $order_by, $archive, -1, $sort);
} elseif ('fcthm' == $tile_type) {
$link_parts = explode('?', $link);
parse_str(str_replace('&amp;', '&', $link_parts[1]), $link_parts);
$parent = (isset($link_parts["parent"]) ? (int) validate_collection_parent(array("parent" => (int) $link_parts["parent"])) : 0);
$parent_col_data = get_collection($parent);
$parent_col_data = (is_array($parent_col_data) ? $parent_col_data : array());
$resources = dash_tile_featured_collection_get_resources($parent_col_data, array());
// The resource manually selected for a category doesn't have to be part of the branch (or any FCs). Add it
// to the list of resources as if it is.
if (
!empty($parent_col_data)
&& $parent_col_data["thumbnail_selection_method"] == $FEATURED_COLLECTION_BG_IMG_SELECTION_OPTIONS["manual"]
&& $parent_col_data["bg_img_resource_ref"] > 0 && get_resource_access($parent_col_data["bg_img_resource_ref"]) == RESOURCE_ACCESS_FULL
) {
$resources[] = array(
"ref" => $parent_col_data["bg_img_resource_ref"],
"field{$view_title_field}" => get_data_by_field($parent_col_data["bg_img_resource_ref"], $view_title_field)
);
}
if (!is_numeric($promoted_resource)) {
$promoted_resource = dash_tile_featured_collection_get_resources($parent_col_data, array("limit" => 1, "use_thumbnail_selection_method" => true));
$promoted_resource = (!empty($promoted_resource) ? $promoted_resource[0]["ref"] : 0);
}
}
if (count($resources) > 0) {
?>
<div class="Question" id="promotedresource">
<label for="promoted_image"><?php echo escape($lang['dashtileimage']); ?></label>
<select class="stdwidth" id="previewimage" name="promoted_image">
<?php foreach ($resources as $resource) { ?>
<option
value="<?php echo escape($resource["ref"]); ?>"
<?php echo $promoted_resource === $resource['ref'] ? 'selected="selected"' : ''; ?>
>
<?php
echo escape(str_replace(
array('%ref','%title'),
array(
$resource['ref'],
i18n_get_translated($resource['field' . $view_title_field])
),
$lang['ref-title']
));
?>
</option>
<?php } ?>
</select>
<div class="clearerleft"></div>
</div>
<script>
jQuery('.tlstyle').change(function() {
checked = jQuery('.tlstyle:checked').val();
if (checked == 'thmbs') {
jQuery('#promotedresource').show();
} else {
jQuery('#promotedresource').hide();
}
});
</script>
<?php
}
}
if (checkPermission_dashadmin()) {
?>
<div class="Question">
<label for="tile_audience"><?php echo escape($lang['who_should_see_dash_tile']); ?></label>
<table>
<tbody>
<tr>
<td width="10" valign="middle" >
<input type="radio" id="all_users_false" name="tile_audience" value="false" <?php echo $allusers ? '' : 'checked'; ?> />
</td>
<td align="left" valign="middle" >
<label class="customFieldLabel" for="all_users_false"><?php echo escape($lang['dash_tile_audience_me']); ?></label>
</td>
<td width="10" valign="middle" >
<input type="radio" id="all_users_true" name="tile_audience" value="true" <?php echo ($allusers && empty($current_specific_user_groups)) ? 'checked' : ''; ?> />
</td>
<td align="left" valign="middle" >
<label class="customFieldLabel" for="all_users_true"><?php echo escape($lang['dash_tile_audience_all_users']); ?></label>
</td>
<td width="10" valign="middle" >
<input type="radio" id="dash_tile_audience_user_group" name="tile_audience" value="specific_user_groups" <?php echo ($allusers && !empty($current_specific_user_groups)) ? 'checked' : ''; ?> />
</td>
<td align="left" valign="middle" >
<label class="customFieldLabel" for="dash_tile_audience_user_group"><?php echo escape($lang['dash_tile_audience_user_group']); ?></label>
</td>
</tr>
</tbody>
</table>
<span style='margin-top:10px;float:left;display:none;font-style:italic;' class='FormHelp clearerleft' id='all_userseditchange'><?php echo escape($lang["dasheditchangeall_users"]);?></span>
<div class="clearerleft"></div>
<?php if ($edit && $allusers && !$managed_home_dash) { ?>
<script>
jQuery("input:radio[name='tile_audience']").change(function() {
if (jQuery(this).prop("checked") && jQuery(this).val() == 'false') {
jQuery("#all_userseditchange").show();
} else {
jQuery("#all_userseditchange").hide();
}
});
</script>
<?php } ?>
</div>
<?php
render_user_group_checkbox_select('specific_user_groups', $current_specific_user_groups, 'padding-left: 310px; display: none;');
}
?>
<div class="QuestionSubmit">
<div class="Inline">
<input name="Submit" type="submit" value="<?php echo $submittext;?>" />
</div>
<div class="clearerleft"></div>
</div>
<script>
jQuery(document).ready(function() {
if (jQuery('#dash_tile_audience_user_group').prop('checked')) {
jQuery('#specific_user_groups').show();
}
jQuery('.tlstyle').trigger('change');
});
jQuery('input:radio[name="tile_audience"]').change(function() {
if (jQuery(this).prop('checked') && jQuery(this).val() == 'specific_user_groups') {
jQuery('#specific_user_groups').show();
} else {
jQuery('#specific_user_groups').hide();
}
});
</script>
</form>
<script>
function updateDashTilePreview() {
var prevstyle = jQuery(".tlstyle:checked").val();
var width = 250;
var height = 160;
var pretitle = encodeURIComponent(jQuery("#previewtitle").val());
var pretxt = encodeURIComponent(jQuery("#previewtext").val());
var prelink= encodeURIComponent(jQuery("#previewlink").val());
var tile = "&tllink="+prelink+"&tltitle="+pretitle+"&tltxt="+pretxt;
var tlsize = encodeURIComponent(jQuery('#DashTileSize :selected').val());
// Some tile types don't have style
if (typeof prevstyle === 'undefined') {
prevstyle = '<?php echo validate_tile_style($tile_type, (isset($tile_style) ? $tile_style : "")); ?>';
}
<?php
if ($tile_type == "srch") {
?>
var count = jQuery("#resource_count").is(':checked');
if (count) {
count = 1;
} else {
count = 0;
}
tile = tile + "&tlrcount=" + encodeURIComponent(count);
<?php
}
if ($promoted_resource && allowPromotedResources($tile_type)) {
?>
tile = tile + '&promimg=' + encodeURIComponent(jQuery('#previewimage').val());
<?php
}
#Preview URL
if (empty($url) || strpos($url, "pages/ajax/dash_tile.php") !== false) {
$previewurl = $baseurl_short . "pages/ajax/dash_tile_preview.php";
} else {
$previewurl = $baseurl_short . $url;
}
?>
// Change size if needed:
jQuery('#previewdashtile').removeClass('DoubleWidthDashTile');
if (
'double' == jQuery('#DashTileSize :selected').val()
|| (typeof event !== 'undefined' && event.type == 'change' && 'double' == jQuery(event.target).val())
) {
jQuery('#previewdashtile').addClass('DoubleWidthDashTile');
width = 515;
}
jQuery("#previewdashtile").load("<?php echo escape($previewurl); ?>?tltype=<?php echo urlencode($tile_type)?>&tlsize=" + tlsize + "&tlstyle="+prevstyle+"&tlwidth="+width+"&tlheight="+height+tile);
}
updateDashTilePreview();
jQuery("#previewtitle").change(updateDashTilePreview);
jQuery("#previewtext").change(updateDashTilePreview);
jQuery("#resource_count").change(updateDashTilePreview);
jQuery(".tlstyle").change(updateDashTilePreview);
jQuery("#promotedresource").change(updateDashTilePreview);
</script>
</div><!-- End of BasicsBox -->
<?php
include "../include/footer.php";

31
pages/dbtest.php Normal file
View File

@@ -0,0 +1,31 @@
<?php
error_reporting(1);
if (file_exists("../include/config.php")) {
die(1);
}
if ($_REQUEST['mysqlserver'] == '') {
echo '202';
exit();
}
if ($_REQUEST['mysqlusername'] == '') {
echo '201';
exit();
}
if ((isset($_REQUEST['mysqlserver'])) && (isset($_REQUEST['mysqlusername'])) && (isset($_REQUEST['mysqlpassword']))) {
$dbtest_connection = mysqli_connect(filter_var($_REQUEST['mysqlserver'], FILTER_SANITIZE_FULL_SPECIAL_CHARS), filter_var($_REQUEST['mysqlusername'], FILTER_SANITIZE_FULL_SPECIAL_CHARS), filter_var($_REQUEST['mysqlpassword'], FILTER_SANITIZE_FULL_SPECIAL_CHARS));
if (!$dbtest_connection) {
if (mysqli_errno($dbtest_connection) == 1045) {
echo '201';
} else {
echo '202';
}
} else {
if (mysqli_select_db($dbtest_connection, (filter_var($_REQUEST['mysqldb'], FILTER_SANITIZE_FULL_SPECIAL_CHARS)))) {
echo '200';
} else {
echo '203';
}
}
}

93
pages/done.php Executable file
View File

@@ -0,0 +1,93 @@
<?php
include "../include/boot.php";
if ((getval("user", "") != "" || isset($anonymous_login) || hook('provideusercredentials')) && getval("k", "") == "") {
// Authenticate if already logged in, so the correct theme is displayed when using user group specific themes.
include "../include/authenticate.php";
}
if (getval("refreshcollection", "") != "") {
refresh_collection_frame();
}
# fetch the current search
$search = getval("search", "");
$order_by = getval("order_by", "relevance");
$offset = getval("offset", 0, true);
$restypes = getval("restypes", "");
if (strpos($search, "!") !== false) {
$restypes = "";
}
$archive = getval("archive", "");
$default_sort_direction = "DESC";
if (substr($order_by, 0, 5) == "field") {
$default_sort_direction = "ASC";
}
$sort = getval("sort", $default_sort_direction);
$k = getval("k", "");
$text = getval("text", "");
$text = (is_array($text)) ? $text[0] : $text;
include "../include/header.php";
?>
<div class="BasicsBox">
<h1><?php echo escape($lang["complete"]); ?></h1>
<p><?php echo text(escape($text)) ?></p>
<?php
if ((getval("user", "") != "" || $k != "" || isset($anonymous_login) || hook('checkuserloggedin')) && getval("notloggedin", "") == "" && $text != "user_request") {
# User logged in?
# Ability to link back to a resource page
$resource = getval("resource", "");
if ($resource != "") {
?>
<p>
<a href="<?php echo generateURL($baseurl_short . 'pages/view.php', ['ref' => $resource, 'k' => $k, 'search' => $search, 'offset' => $offset, 'order_by' => $order_by, 'sort' => $sort, 'archive' => $archive]); ?>" onclick="return CentralSpaceLoad(this,true);">
<?php echo LINK_CARET . escape($lang["continuetoresourceview"]); ?>
</a>
</p>
<?php
}
if ($k == "") {
?>
<p>
<a href="<?php echo $baseurl_short?>pages/search.php?search=<?php echo urlencode($search)?>&offset=<?php echo urlencode($offset) ?>&order_by=<?php echo urlencode($order_by) ?>&sort=<?php echo urlencode($sort) ?>&archive=<?php echo urlencode($archive) ?>&amp;restypes=<?php echo urlencode($restypes); ?>" onclick="return CentralSpaceLoad(this,true);">
<?php echo LINK_CARET . escape($lang["continuetoresults"]); ?>
</a>
</p>
<p>
<a href="<?php echo $use_theme_as_home ? $baseurl_short . 'pages/collections_featured.php' : 'home.php'?>" onclick="return CentralSpaceLoad(this,true);">
<?php echo LINK_CARET . escape($lang["continuetohome"]); ?>
</a>
</p>
<?php
} elseif ($k != "" && upload_share_active()) {
$collection = getval("collection", 0, true);
$uploadurl = get_upload_url($collection, $k);
?>
<div class='clearerleft'></div>
<div>
<input type='button' value='<?php echo escape($lang["upload"]);?>' onclick='CentralSpaceLoad("<?php echo $uploadurl; ?>");'>
</div>
<?php
}
hook("extra");
} else { ?>
<p>
<a href="<?php echo $baseurl_short?>login.php" >
<?php echo LINK_CARET . escape($lang["continuetouser"]); ?>
</a>
</p>
<?php
} ?>
</div>
<?php
include "../include/footer.php";
?>

447
pages/download.php Executable file
View File

@@ -0,0 +1,447 @@
<?php
/* We will use output buffering to prevent any included files
from outputting stray characters that will mess up the binary download
we will clear the buffer and start over right before we download the file*/
ob_start();
$nocache = true;
$disable_browser_check = true;
include_once __DIR__ . '/../include/boot.php';
include_once __DIR__ . '/../include/image_processing.php';
ob_end_clean();
if ($download_no_session_cache_limiter) {
session_cache_limiter(false);
}
$ref = getval('ref', '', true);
$size = trim(getval('size', ''));
$alternative = getval('alternative', -1, true);
$page = getval('page', 1, true);
$iaccept = getval('iaccept', 'off');
$usage = getval('usage', '-1');
$usagecomment = getval('usagecomment', '');
$email = getval('email', '');
$ext = getval('ext', '');
$snapshot_frame = getval('snapshot_frame', 0, true);
$modal = (getval("modal", "") == "true");
$tempfile = getval("tempfile", "");
$slideshow = getval("slideshow", 0, true);
$userfiledownload = getval('userfile', '');
$write_exif_data = (getval('exif_write', '') == 'true');
$k = getval('k', '');
$download_temp_key = getval("access_key", '');
$watermarked = getval('watermarked', 0, true);
$override_temp_key = getval("override_key", '');
$noattach = getval('noattach', '') != '';
// Check for temporary download access using key (e.g. from API get_resource_path)
$valid_key = false;
if ($ref > 0 && ($download_temp_key !== '' || $override_temp_key !== '')) {
$valid_key = validate_temp_download_key($ref, trim($download_temp_key === '' ? $override_temp_key : $download_temp_key), $size);
}
// External access support (authenticate only if no key provided, or if invalid access key provided)
if (!$valid_key && ('' == $k || !check_access_key(getval('ref', '', true), $k)) && getval("slideshow", 0, true) <= 0) {
include __DIR__ . '/../include/authenticate.php';
}
// Set a flag for logged in users if $external_share_view_as_internal is set and logged on user is accessing an external share
$internal_share_access = internal_share_access();
$log_download = true;
// Ensure terms have been accepted and usage has been supplied when required. Not for slideshow files etc.
$checktermsusage = !in_array($size, $sizes_always_allowed)
&& $tempfile == ""
&& $slideshow == 0
&& $userfiledownload == ""
&& (!$video_preview_original && get_resource_access($ref));
if (
$terms_download
&& $checktermsusage
&& $iaccept != 'on'
) {
exit($lang["mustaccept"]);
}
if ($download_usage && $checktermsusage) {
if (!(is_numeric($usage) && $usage >= 0)) {
exit($lang["termsmustindicateusage"]);
}
if ($usagecomment == '' && !$usage_comment_blank) {
exit($lang["termsmustspecifyusagecomment"]);
}
}
if (is_banned_extension($ext)) {
$ext = 'jpg';
}
$override_key = false;
if ($ref > 0 && $override_temp_key !== '') {
// Check if the download should be allowed. Permissions have already been considered elsewhere.
// Used to display edit page resource preview image after upload where search filter has not yet been set.
$override_key = validate_temp_download_key($ref, trim($override_temp_key), $size, 2, false);
}
// Is this a user specific download?
if ('' != $userfiledownload) {
$noattach = false;
$log_download = true;
// Provide a way of overriding $exiftool_write = false depending on download source e.g. from format chooser
if ($exiftool_write && $write_exif_data) {
$exiftool_write = true;
} else {
$exiftool_write = false;
}
$filedetails = explode('_', $userfiledownload);
$ref = (int)$filedetails[0];
$downloadkey = strip_extension($filedetails[1]);
$ext = safe_file_name(substr($filedetails[1], strlen($downloadkey) + 1));
$path = get_temp_dir(false, 'user_downloads') . '/' . $ref . '_' . md5($username . $downloadkey . $scramble_key) . '.' . $ext;
$rqstname = getval("filename", "");
if ($rqstname != "") {
$filename = $rqstname . "." . $ext;
$filename_prefix = explode('_', $filename);
if (($filename_prefix[0] == 'Col' && $ext == 'zip') || ($filename_prefix[0] == 'metadata' && isset($filename_prefix[1]) && $filename_prefix[1] == 'export' && $ext == 'csv')) {
// For offline collection or offline csv download, $ref will be user ref not resource ref.
$log_download = false;
}
}
hook('modifydownloadpath');
} elseif ($slideshow != 0) {
$noattach = true;
$log_download = false;
$path = __DIR__ . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . $homeanim_folder . DIRECTORY_SEPARATOR . getval("slideshow", 0, true) . ".jpg";
} elseif ($tempfile != "") {
$noattach = true;
$log_download = false;
$exiftool_write = false;
$filedetails = explode('_', $tempfile);
if (count($filedetails) >= 3) {
$code = safe_file_name($filedetails[0]);
$ref = (int)$filedetails[1];
$downloadkey = strip_extension($filedetails[2]);
$ext = safe_file_name(substr($filedetails[2], strlen($downloadkey) + 1));
$path = get_temp_dir(false, "") . '/' . $code . '_' . $ref . "_" . md5($username . $downloadkey . $scramble_key) . '.' . $ext;
} else {
$error = $lang['downloadfile_nofile'];
if (getval('ajax', '') != '') {
error_alert($error, true, 200);
} else {
include "../include/header.php";
$onload_message = ['title' => $lang["error"],'text' => $error];
include "../include/footer.php";
}
exit();
}
} else {
$resource_data = get_resource_data($ref);
if (!is_array($resource_data)) {
$error = $lang["resourcenotfound"];
if (getval("ajax", "") != "") {
error_alert($error, true, 200);
} else {
include "../include/header.php";
$onload_message = array("title" => $lang["error"],"text" => $error);
include "../include/footer.php";
}
exit();
}
if ((int)$resource_data['has_image'] === 0 && $size != "") {
// If configured, try and use the preview from a related resource
$pullresource = related_resource_pull($resource_data);
if ($pullresource !== false) {
$resource_data = $pullresource;
$ref = $pullresource["ref"];
}
}
resource_type_config_override($resource_data['resource_type']);
// Check permissions
$allowed = $override_key ? true : resource_download_allowed($ref, $size, $resource_data['resource_type'], $alternative);
debug("PAGES/DOWNLOAD.PHP: \$allowed = " . ($allowed ? 'TRUE' : 'FALSE'));
if (!$allowed || $ref <= 0) {
$error = $lang['error-permissiondenied'];
if (getval("ajax", "") != "") {
error_alert($error, true, 200);
} else {
include "../include/header.php";
$onload_message = array("title" => $lang["error"],"text" => $error);
include "../include/footer.php";
}
exit();
}
// additional access check, as the resource download may be allowed, but access restriction should force watermark.
$access = get_resource_access($ref);
$use_watermark = check_use_watermark(getval("dl_key", ""), $ref) || $watermarked;
// If no extension was provided, we fallback to JPG.
if ('' == $ext) {
$ext = 'jpg';
}
// Where we are getting mp3 preview for videojs, clear size as we want to get the auto generated mp3 file rather than a custom size.
// Also allow mp4 files for videojs if $video_preview_original is enabled
if (
$size == 'videojs'
&& ($ext == 'mp3' || ($ext == 'mp4' && $video_preview_original))
) {
$size = "";
$log_download = false;
} elseif ($preview_tiles && $allowed && $size == '' && getval('tile_region', 0, true) == 1) {
// Provide a tile region if enabled and requested for the main resource.
$tile_scale = (int) getval('tile_scale', 1, true);
$tile_row = (int) getval('tile_row', 0, true);
$tile_col = (int) getval('tile_col', 0, true);
$fulljpgsize = strtolower($ext) != "jpg" ? "hpr" : "";
$fullpath = get_resource_path($ref, true, $fulljpgsize, false, "jpg");
$image_size = get_original_imagesize($ref, $fullpath, "jpg");
if ($image_size === false) {
debug("PAGES/DOWNLOAD.PHP: File does not exist!");
http_response_code(404);
exit($lang['downloadfile_nofile']);
} else {
$image_width = (int) $image_size[1];
$image_height = (int) $image_size[2];
debug(sprintf('PAGES/DOWNLOAD.PHP: Requesting a tile region with scale=%s, row=%s, col=%s', $tile_scale, $tile_row, $tile_col));
$tiles = compute_tiles_at_scale_factor($tile_scale, $image_width, $image_height);
foreach ($tiles as $tile) {
if ($tile['column'] == $tile_col && $tile['row'] == $tile_row) {
$size = $tile['id'];
$ext = 'jpg';
break;
}
}
}
}
// Establish nonwatermarked path for use when returning snapshot frames
$nowmpath = get_resource_path($ref, true, $size, false, $ext, -1, $page, false, '', $alternative, true);
$path = get_resource_path($ref, true, $size, false, $ext, -1, $page, $use_watermark && $alternative == -1, '', $alternative, true);
$download_extra = hook('download_resource_extra', '', array($path));
// Process depending on whether snapshot frame is to be returned
if ($snapshot_frame > 0 && $ffmpeg_snapshot_frames > 1) {
// Snapshot frame is to be returned, so adjust the path to be the actual frame requested
$path = str_replace('snapshot', "snapshot_{$snapshot_frame}", $nowmpath);
}
if ($snapshot_frame == 0 && $size == "pre" && $use_watermark && $ext == "mp4") {
// Video stream preview size is to be returned and watermark is specified
// In this case there is no such thing as a watermarked video preview size, so use the unwatermarked path
$path = $nowmpath;
}
hook('modifydownloadpath');
// Hook to modify the download path.
$path_modified = hook('modifydownloadpath2', '', array($download_extra));
if (isset($path_modified) && $path_modified != '' && is_string($path_modified)) {
$path = $path_modified;
}
if (!file_exists($path) && $noattach) {
# Return icon for file (for previews)
if(in_array($size,["thm","col"])) {
$path = '../gfx/no_preview/default_thm.png';
} else {
$path = '../gfx/no_preview/default.png';
}
}
if ($noattach) {
if (!allow_in_browser($path)) {
// Override the noattach request if file is not valid for display in browser
$noattach = false;
}
if (!($size == "" && $resource_data["file_extension"] == $ext)) {
// Do not log downloads for these unless accessing original resource files
$log_download = false;
}
}
// Process metadata
// Note: only for downloads (not previews)
if (!$noattach && -1 == $alternative) {
// Strip existing metadata only if we do not plan on writing metadata, otherwise this will be done twice
if ($exiftool_remove_existing && !$exiftool_write) {
$temp_file_stripped_metadata = createTempFile($path, '', '');
if ($temp_file_stripped_metadata !== false && stripMetadata($temp_file_stripped_metadata)) {
$path = $temp_file_stripped_metadata;
}
}
// writing RS metadata to files: exiftool
if ($exiftool_write) {
$tmpfile = write_metadata($path, $ref);
if (false !== $tmpfile && file_exists($tmpfile)) {
$path = $tmpfile;
}
}
}
}
debug("PAGES/DOWNLOAD.PHP: Preparing to download/ stream file '{$path}'");
if (!file_exists($path)) {
debug("PAGES/DOWNLOAD.PHP: File does not exist!");
http_response_code(404);
exit($lang['downloadfile_nofile']);
}
hook('modifydownloadfile');
$file_size = filesize_unlimited($path);
$file_handle = fopen($path, 'rb');
debug("PAGES/DOWNLOAD.PHP: \$file_size = {$file_size}");
if (!$file_handle) {
// File could not be opened
debug("PAGES/DOWNLOAD.PHP: File could not be opened!");
http_response_code(500);
exit();
}
if (
!$noattach
&& (!isset($filename) || $filename == "" || $alternative != -1)
) {
// Compute a file name for the download.
$filename = get_download_filename($ref, $size, $alternative, $ext);
}
if ($log_download) {
// Log this activity (download only, not preview)
daily_stat('Resource download', $ref);
$email_add_to_log = ($email != "") ? ' Downloaded by ' . $email : "";
resource_log($ref, LOG_CODE_DOWNLOADED, 0, $usagecomment . $email_add_to_log, '', '', $usage, $alternative);
hook('moredlactions');
// Update hit count if tracking downloads only
if ($resource_hit_count_on_downloads) {
// greatest() is used so the value is taken from the hit_count column in the event that new_hit_count
// is zero to support installations that did not previously have a new_hit_count column (i.e. upgrade compatability).
ps_query("UPDATE resource SET new_hit_count = greatest(hit_count, new_hit_count) + 1 WHERE ref = ?", ['i', $ref]);
}
}
// Set appropriate headers for attachment or streamed file
if (isset($filename)) {
header("Content-Disposition: attachment; filename=\"{$filename}\"");
debug("PAGES/DOWNLOAD.PHP: Set header for attachment file");
} else {
header("Content-Disposition: inline; filename=\"download.{$ext}\"");
header('Content-Transfer-Encoding: binary');
debug("PAGES/DOWNLOAD.PHP: Set header for streamed file");
}
// We declare the downloaded content mime type
$mime = get_mime_type($path)[0];
header("Content-Type: {$mime}");
header('X-Content-Type-Options: nosniff');
debug("PAGES/DOWNLOAD.PHP: Set MIME type to '{$mime}'");
// Check if http_range is sent by browser (or download manager)
$range_requested = false;
if (isset($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'], "=") !== false) { # Check it's set and also contains the expected = delimiter
debug("PAGES/DOWNLOAD.PHP: HTTP_RANGE is set to '{$_SERVER['HTTP_RANGE']}'");
list($size_unit, $range_orig) = explode('=', $_SERVER['HTTP_RANGE'], 2);
if ('bytes' == $size_unit) {
/* Multiple ranges could be specified at the same time, but for simplicity only serve the first range
http://tools.ietf.org/id/draft-ietf-http-range-retrieval-00.txt
IMPORTANT: If multiple ranges are not specified, PHP can return an error for "Undefined offset: 1",
so we pad the array with an empty string */
list($range, $extra_ranges) = array_pad(explode(',', $range_orig, 2), 2, '');
$range_requested = true;
} else {
debug("PAGES/DOWNLOAD.PHP: Requested range was not valid");
header('HTTP/1.1 416 Requested Range Not Satisfiable');
header("Content-Range: */{$file_size}");
exit();
}
} else {
debug("PAGES/DOWNLOAD.PHP: HTTP_RANGE is not set!");
$range = '';
}
debug("PAGES/DOWNLOAD.PHP: \$range = {$range}");
// Figure out download piece from range (if set)
list($seek_start, $seek_end) = array_pad(explode('-', $range, 2), 2, '');
// Set start and end based on range (if set), else set defaults
// also check for invalid ranges.
$seek_end = (empty($seek_end)) ? ($file_size - 1) : min(abs(intval($seek_end)), ($file_size - 1));
$seek_start = (empty($seek_start) || $seek_end < abs(intval($seek_start))) ? 0 : max(abs(intval($seek_start)), 0);
debug("PAGES/DOWNLOAD.PHP: \$seek_start = {$seek_start}");
debug("PAGES/DOWNLOAD.PHP: \$seek_end = {$seek_end}");
// Only send partial content header if downloading a piece of the file (IE workaround)
if (0 < $seek_start || $seek_end < ($file_size - 1)) {
header('HTTP/1.1 206 Partial Content');
header("Content-Range: bytes {$seek_start}-{$seek_end}/{$file_size}");
header('Content-Length: ' . ($seek_end - $seek_start + 1));
debug("PAGES/DOWNLOAD.PHP: Content-Range: bytes {$seek_start}-{$seek_end}/{$file_size}");
debug('PAGES/DOWNLOAD.PHP: Content-Length: ' . ($seek_end - $seek_start + 1));
$total_to_send = $seek_end - $seek_start + 1;
} else {
header("Content-Length: {$file_size}");
if ($range_requested) {
// Safari seems to require this
header("Content-Range: bytes {$seek_start}-{$seek_end}/{$file_size}");
}
debug("PAGES/DOWNLOAD.PHP: Content-Length: {$file_size}");
$total_to_send = $file_size;
}
header('Accept-Ranges: bytes');
set_time_limit(0);
$sent = (0 == fseek($file_handle, $seek_start) ? $seek_start : 0);
while ($sent < $file_size) {
echo fread($file_handle, $download_chunk_size);
ob_flush();
flush();
$sent += $download_chunk_size;
if (0 != connection_status()) {
break;
}
}
fclose($file_handle);
// File send complete, log to daily stat
daily_stat('Downloaded KB', $ref, floor($total_to_send / 1024));
// Deleting Exiftool temp File:
// Note: Only for downloads (not previews)
if (!$noattach && -1 == $alternative && $exiftool_write && isset($tmpfile) && file_exists($tmpfile)) {
delete_exif_tmpfile($tmpfile);
}
if (isset($download_extra)) {
hook('beforedownloadresourceexit', '', array($download_extra));
}
exit();

110
pages/download_progress.php Executable file
View File

@@ -0,0 +1,110 @@
<?php
include "../include/boot.php";
# External access support (authenticate only if no key provided, or if invalid access key provided)
$k = getval("k", "");
if (($k == "") || (!check_access_key(getval("ref", "", true), $k))) {
include "../include/authenticate.php";
}
$ref = getval("ref", "");
$size = getval("size", "");
$ext = getval("ext", "");
if (is_banned_extension($ext)) {
$ext = 'jpg';
}
$alternative = getval("alternative", -1);
$search = getval("search", "");
$iaccept = getval("iaccept", "off");
$usage = getval("usage", "-1");
$usagecomment = getval("usagecomment", "");
$email = getval('email', '');
$url = getval('url', '');
if ($url == '') {
$download_url_suffix = "?ref=" . urlencode($ref) . "&size=" . urlencode($size) . "&ext=" . urlencode($ext)
. "&k=" . urlencode($k) . "&alternative=" . urlencode($alternative) . "&iaccept=" . urlencode($iaccept);
$download_url_suffix .= hook("addtodownloadquerystring");
if ($download_usage && getval("usage", "") == "" && $terms_download) {
redirect($baseurl_short . "pages/download_usage.php" . $download_url_suffix);
}
if (!($url = hook("getdownloadurl", "", array($ref, $size, $ext, 1, $alternative, $usage, $usagecomment)))) { // used in remotedownload-plugin
$download_url_suffix .= "&usage=" . urlencode($usage) . "&usagecomment=" . urlencode($usagecomment) . "&email=" . urlencode($email);
$url = $baseurl . "/pages/download.php" . $download_url_suffix;
}
}
include "../include/header.php";
if (!$save_as) {
?>
<script type="text/javascript">
window.setTimeout("document.location='<?php echo str_replace('\'', '%27', $url); ?>'",1000);
</script>
<?php
}
?>
<div class="BasicsBox">
<?php if ($save_as) {
# $save_as set or Opera browser? Provide a download link instead. Opera blocks any attempt to send it a download (meta/js redirect) ?>
<h1><?php echo escape($lang["downloadresource"]); ?></h1>
<p style="font-weight:bold;">
<?php echo LINK_CARET ?>
<a href="<?php echo escape($url); ?>"><?php echo escape($lang["rightclicktodownload"]); ?></a>
</p>
<?php } else {
# Any other browser - standard 'your download will start shortly' text.
?>
<h1><?php echo escape($lang["downloadinprogress"]); ?></h1>
<p><?php echo text("introtext")?></p>
<?php }
$offset = getval("saved_offset", getval("offset", 0, true));
$order_by = getval("saved_order_by", getval("order_by", ""));
$sort = getval("saved_sort", getval("sort", ""));
$archive = getval("saved_archive", getval("archive", ""));
// Set parameters for links
$url_parameters = array(
"ref" => $ref,
"k" => $k,
"search" => getval("search", ""),
"offset" => $offset,
"order_by" => $order_by,
"sort" => $sort,
"archive" => $archive
);
?>
<p>
<a onclick="return CentralSpaceLoad(this,true);" href="<?php echo generateURL($baseurl_short . "pages/view.php", $url_parameters) ?>">
<?php echo LINK_CARET_BACK . escape($lang["backtoresourceview"]); ?>
</a>
</p>
<?php if (strpos($search, "!collection") !== false) { ?>
<p>
<a onclick="return CentralSpaceLoad(this,true);" href="<?php echo generateURL($baseurl_short . "pages/search.php", $url_parameters) ?>">
<?php echo LINK_CARET_BACK . escape($lang["backtoresults"]); ?>
</a>
</p>
<?php
}
if ($k == "") { ?>
<p>
<a onclick="return CentralSpaceLoad(this,true);" href="<?php echo generateURL($baseurl_short . "pages/home.php") ?>">
<?php echo LINK_CARET_BACK . escape($lang["backtohome"]); ?>
</a>
</p>
<?php
}
?>
</div>
<?php
include "../include/footer.php";

223
pages/download_usage.php Executable file
View File

@@ -0,0 +1,223 @@
<?php
include "../include/boot.php";
# External access support (authenticate only if no key provided, or if invalid access key provided)
$k = getval('k', '');
$ref = getval('ref', '', true);
$col = getval('collection', getval('col', -1, true), true);
$size = getval('size', '');
$ext = getval('ext', '');
$alternative = getval('alternative', -1);
$iaccept = getval('iaccept', 'off');
$url = getval('url', '');
$email = getval('email', '');
$usage = getval("usage", '', true);
$usagecomment = getval("usagecomment", '');
$error = array();
if (-1 != $col) {
$need_to_authenticate = !check_access_key_collection($col, $k);
} else {
$need_to_authenticate = !check_access_key($ref, $k);
}
if ('' == $k || $need_to_authenticate) {
include '../include/authenticate.php';
}
hook("pageevaluation");
$download_url_suffix = hook("addtodownloadquerystring");
if (getval("save", '') != '' && enforcePostRequest(false)) {
$fields["usage"] = $usage;
$fields["usagecomment"] = $usagecomment;
$fields["email"] = $email;
// validate input fields
$error = validate_input_download_usage($fields);
if (count($error) === 0) {
$download_url_suffix_params = [];
$download_url_suffix .= ($download_url_suffix == '') ? '?' : '&';
if ($download_usage && -1 != $col) {
$download_url_suffix_params["collection"] = $col;
$redirect_url = "pages/collection_download.php";
$download_url_suffix_params = array_merge($download_url_suffix_params, array("email" => $email));
} else {
$download_url_suffix_params["ref"] = $ref;
$redirect_url = "pages/download_progress.php";
}
$download_url_suffix_params = array_merge(
$download_url_suffix_params,
[
"size" => $size,
"ext" => $ext,
"k" => $k,
"alternative" => $alternative,
"iaccept" => $iaccept,
"usage" => $usage,
"usagecomment" => $usagecomment,
"offset" => getval("saved_offset", getval("offset", 0, true)),
"order_by" => getval("saved_order_by", getval("order_by", '')),
"sort" => getval("saved_sort", getval("sort", '')),
"archive" => getval("saved_archive", getval("archive", '')),
"email" => $email
]
);
$url_parts = [];
if (strpos($url, '?') !== false) {
parse_str(explode('?', $url)[1], $url_parts);
}
if (strpos($url, 'download.php') !== false && count($url_parts) > 0 && isset($url_parts['noattach']) && $url_parts['noattach'] == true) {
$redirect_url = $url;
} elseif (strpos($url, 'download.php') !== false && (strpos($url, $baseurl_short) !== false || strpos($url, $baseurl) !== false)) {
$download_url_suffix_params['url'] = $url;
}
redirect(generateURL($redirect_url, $download_url_suffix_params, $url_parts));
}
}
include "../include/header.php";
if (isset($download_usage_prevent_options)) { ?>
<script>
function checkvalidusage() {
validoptions = new Array(<?php echo "'" . implode("','", $download_usage_prevent_options) . "'" ?>);
if (jQuery.inArray(jQuery('#usage').find(":selected").text(), validoptions ) !=- 1) {
jQuery('#submit').prop('disabled', true).css("filter", "opacity(0.25)");
alert("<?php echo escape($lang["download_usage_option_blocked"]); ?>");
} else {
jQuery('#submit').prop('disabled', false).css("filter", "opacity(1)");
}
}
</script>
<?php
} ?>
<div class="BasicsBox">
<form method="post" action="<?php echo $baseurl_short?>pages/download_usage.php<?php echo $download_url_suffix ?>">
<?php
generateFormToken("download_usage");
if ($download_usage) { ?>
<input type="hidden" name="url" value="<?php echo escape($url); ?>" />
<?php if ($col != -1) { ?>
<input type="hidden" name="col" value="<?php echo escape($col); ?>" />
<?php }
} ?>
<input type="hidden" name="ref" value="<?php echo escape($ref) ?>" />
<input type="hidden" name="size" value="<?php echo escape($size) ?>" />
<input type="hidden" name="ext" value="<?php echo escape($ext) ?>" />
<input type="hidden" name="alternative" value="<?php echo escape($alternative) ?>" />
<input type="hidden" name="k" value="<?php echo escape($k) ?>" />
<input type="hidden" name="save" value="true" />
<input type="hidden" name="iaccept" value="<?php echo escape($iaccept) ?>" />
<h1><?php echo escape($lang["usage"]); ?></h1>
<p><?php echo strip_tags_and_attributes($lang["indicateusage"], array('a'), array('href', 'target')); ?></p>
<?php if ($download_usage_email) { ?>
<div class="Question">
<label><?php echo escape($lang["emailaddress"]); ?></label>
<input name="email" type="text" class="stdwidth" value="<?php echo escape($email); ?>">
<span class="error"><?php echo isset($error['email']) ? $error["email"] : "" ?></span>
<div class="clearerleft"></div>
</div>
<?php }
if (!$remove_usage_textbox && !$usage_textbox_below) {
echo html_usagecomments($usagecomment, $error);
} ?>
<div class="Question">
<label for="usage"><?php echo escape($lang["indicateusagemedium"]); ?></label>
<select class="stdwidth" name="usage" id="usage" <?php echo (isset($download_usage_prevent_options)) ? 'onchange="checkvalidusage();"' : ''; ?>>
<option value=""><?php echo escape($lang["select"]); ?></option>
<?php
for ($n = 0; $n < count($download_usage_options); $n++) {
$selected = ($n === $usage) ? "selected" : "";
?>
<option <?php echo $selected; ?> value="<?php echo $n; ?>">
<?php echo escape(i18n_get_translated($download_usage_options[$n])); ?>
</option>
<?php
} ?>
</select>
<span class="error"><?php echo isset($error['usage']) ? $error["usage"] : "" ?></span>
<div class="clearerleft"></div>
</div>
<?php if ($usage_textbox_below && !$remove_usage_textbox) {
echo html_usagecomments($usagecomment, $error);
} ?>
<div class="QuestionSubmit">
<input name="submit" type="submit" id="submit" value="<?php echo escape($lang["action-download"]); ?>" />
</div>
</form>
</div>
<?php
include "../include/footer.php";
/**
* HTML for usage comments input field
*
* @param string $usagecomment - submitted value for field
* @param array $error - array of form field validation error messages
*
* @return string $html - HTML string to display
*/
function html_usagecomments($usagecomment, $error)
{
global $lang;
$html = '<div class="Question"><label>{label}</label>
<textarea rows="5" name="usagecomment" id="usagecomment" type="text" class="stdwidth">{value}</textarea>
<span class="error">{error}</span>
<div class="clearerleft"></div></div>';
$replace = array(
"{label}" => $lang["usagecomments"],
"{error}" => isset($error["usagecomment"]) ? $error["usagecomment"] : "",
"{value}" => escape($usagecomment)
);
$html = str_replace(array_keys($replace), array_values($replace), $html);
return $html;
}
/**
* Validate download usage form field values. Uses config var $usage_comment_blank to determine whether to validate usagecomment
*
* @param array $fields - list of fields to validate
*
* @return array $error - list of fields with error messages
*/
function validate_input_download_usage($fields)
{
global $lang, $usage_comment_blank, $download_usage_email, $remove_usage_textbox;
$error = array();
$error["usage"] = $fields["usage"] == "" ? $lang["usageincorrect"] : "";
if (!$remove_usage_textbox) {
$error["usagecomment"] = $fields["usagecomment"] == "" && !$usage_comment_blank ? $lang["usageincorrect"] : "";
}
if ($download_usage_email) {
$error["email"] = !filter_var($fields["email"], FILTER_VALIDATE_EMAIL) ? $lang["error_invalid_email"] : "";
}
$error = array_filter($error);
return $error;
}
?>

Some files were not shown because too many files have changed in this diff Show More