diff --git a/.github/ISSUE_TEMPLATE/Bug_report.yml b/.github/ISSUE_TEMPLATE/Bug_report.yml index afa1a27f8..f6fb7d280 100644 --- a/.github/ISSUE_TEMPLATE/Bug_report.yml +++ b/.github/ISSUE_TEMPLATE/Bug_report.yml @@ -11,22 +11,35 @@ body: required: true - type: checkboxes attributes: - label: I've found a bug and checked that ... - description: Prior to placing the issue, please check following:** *(fill out each checkbox with an `X` once done)* + label: Checklist prior issue creation + description: Prior to creating the issue... options: - - label: ... I understand that not following the below instructions will result in immediate closure and/or deletion of my issue. + - label: I understand that failure to follow below instructions may cause this issue to be closed. required: true - - label: ... I have understood that this bug report is dedicated for bugs, and not for support-related inquiries. + - label: I understand that vague, incomplete or inaccurate information may cause this issue to be closed. required: true - - label: ... I have understood that answers are voluntary and community-driven, and not commercial support. + - label: I understand that this form is intended solely for reporting software bugs and not for support-related inquiries. required: true - - label: ... I have verified that my issue has not been already answered in the past. I also checked previous [issues](https://github.com/mailcow/mailcow-dockerized/issues). + - label: I understand that all responses are voluntary and community-driven, and do not constitute commercial support. + required: true + - label: I confirm that I have reviewed previous [issues](https://github.com/mailcow/mailcow-dockerized/issues) to ensure this matter has not already been addressed. + required: true + - label: I confirm that my environment meets all [prerequisite requirements](https://docs.mailcow.email/getstarted/prerequisite-system/) as specified in the official documentation. required: true - type: textarea attributes: label: Description - description: Please provide a brief description of the bug in 1-2 sentences. If applicable, add screenshots to help explain your problem. Very useful for bugs in mailcow UI. - render: plain text + description: Please provide a brief description of the bug. If applicable, add screenshots to help explain your problem. (Very useful for bugs in mailcow UI.) + validations: + required: true + - type: textarea + attributes: + label: "Steps to reproduce:" + description: "Please describe the steps to reproduce the bug. Screenshots can be added, if helpful." + placeholder: |- + 1. ... + 2. ... + 3. ... validations: required: true - type: textarea @@ -36,45 +49,36 @@ body: render: plain text validations: required: true - - type: textarea - attributes: - label: "Steps to reproduce:" - description: "Please describe the steps to reproduce the bug. Screenshots can be added, if helpful." - render: plain text - placeholder: |- - 1. ... - 2. ... - 3. ... - validations: - required: true - type: markdown attributes: value: | ## System information - ### In this stage we would kindly ask you to attach general system information about your setup. + In this stage we would kindly ask you to attach general system information about your setup. - type: dropdown attributes: label: "Which branch are you using?" - description: "#### `git rev-parse --abbrev-ref HEAD`" + description: "#### Run: `git rev-parse --abbrev-ref HEAD`" multiple: false options: - - master + - master (stable) + - staging - nightly validations: required: true - type: dropdown attributes: label: "Which architecture are you using?" - description: "#### `uname -m`" + description: "#### Run: `uname -m`" multiple: false options: - - x86 + - x86_64 - ARM64 (aarch64) validations: required: true - type: input attributes: label: "Operating System:" + description: "#### Run: `lsb_release -ds`" placeholder: "e.g. Ubuntu 22.04 LTS" validations: required: true @@ -93,43 +97,44 @@ body: - type: input attributes: label: "Virtualization technology:" - placeholder: "KVM, VMware, Xen, etc - **LXC and OpenVZ are not supported**" + description: "LXC and OpenVZ are not supported!" + placeholder: "KVM, VMware ESXi, Xen, etc" validations: required: true - type: input attributes: label: "Docker version:" - description: "#### `docker version`" + description: "#### Run: `docker version`" placeholder: "20.10.21" validations: required: true - type: input attributes: label: "docker-compose version or docker compose version:" - description: "#### `docker-compose version` or `docker compose version`" + description: "#### Run: `docker-compose version` or `docker compose version`" placeholder: "v2.12.2" validations: required: true - type: input attributes: label: "mailcow version:" - description: "#### ```git describe --tags `git rev-list --tags --max-count=1` ```" - placeholder: "2022-08" + description: "#### Run: ```git describe --tags `git rev-list --tags --max-count=1` ```" + placeholder: "2022-08x" validations: required: true - type: input attributes: label: "Reverse proxy:" - placeholder: "e.g. Nginx/Traefik" + placeholder: "e.g. nginx/Traefik, or none" validations: required: true - type: textarea attributes: label: "Logs of git diff:" - description: "#### Output of `git diff origin/master`, any other changes to the code? If so, **please post them**:" + description: "#### Output of `git diff origin/master`, any other changes to the code? Sanitize if needed. If so, **please post them**:" render: plain text validations: - required: true + required: false - type: textarea attributes: label: "Logs of iptables -L -vn:" diff --git a/.github/workflows/close_old_issues_and_prs.yml b/.github/workflows/close_old_issues_and_prs.yml index af5fd807d..85094394a 100644 --- a/.github/workflows/close_old_issues_and_prs.yml +++ b/.github/workflows/close_old_issues_and_prs.yml @@ -14,7 +14,7 @@ jobs: pull-requests: write steps: - name: Mark/Close Stale Issues and Pull Requests 🗑️ - uses: actions/stale@v9.1.0 + uses: actions/stale@v10.1.0 with: repo-token: ${{ secrets.STALE_ACTION_PAT }} days-before-stale: 60 diff --git a/.github/workflows/image_builds.yml b/.github/workflows/image_builds.yml index 27fc9a2d5..a5ebb902f 100644 --- a/.github/workflows/image_builds.yml +++ b/.github/workflows/image_builds.yml @@ -27,7 +27,7 @@ jobs: - "watchdog-mailcow" runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Setup Docker run: | curl -sSL https://get.docker.com/ | CHANNEL=stable sudo sh diff --git a/.github/workflows/pr_to_nightly.yml b/.github/workflows/pr_to_nightly.yml index 0cf59eeac..334dcf69a 100644 --- a/.github/workflows/pr_to_nightly.yml +++ b/.github/workflows/pr_to_nightly.yml @@ -8,11 +8,11 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: fetch-depth: 0 - name: Run the Action - uses: devops-infra/action-pull-request@v0.6.0 + uses: devops-infra/action-pull-request@v0.6.1 with: github_token: ${{ secrets.PRTONIGHTLY_ACTION_PAT }} title: Automatic PR to nightly from ${{ github.event.repository.updated_at}} diff --git a/.github/workflows/rebuild_backup_image.yml b/.github/workflows/rebuild_backup_image.yml index bf5caddf0..a8679d980 100644 --- a/.github/workflows/rebuild_backup_image.yml +++ b/.github/workflows/rebuild_backup_image.yml @@ -9,9 +9,11 @@ on: jobs: docker_image_build: runs-on: ubuntu-latest + permissions: + packages: write steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Set up QEMU uses: docker/setup-qemu-action@v3 @@ -19,11 +21,13 @@ jobs: - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 - - name: Login to Docker Hub + - name: Login to GHCR + if: github.event_name != 'pull_request' uses: docker/login-action@v3 with: - username: ${{ secrets.BACKUPIMAGEBUILD_ACTION_DOCKERHUB_USERNAME }} - password: ${{ secrets.BACKUPIMAGEBUILD_ACTION_DOCKERHUB_TOKEN }} + registry: ghcr.io + username: ${{ github.repository_owner }} + password: ${{ secrets.GITHUB_TOKEN }} - name: Build and push uses: docker/build-push-action@v6 @@ -32,4 +36,4 @@ jobs: platforms: linux/amd64,linux/arm64 file: data/Dockerfiles/backup/Dockerfile push: true - tags: mailcow/backup:latest + tags: ghcr.io/mailcow/backup:latest \ No newline at end of file diff --git a/.github/workflows/update_postscreen_access_list.yml b/.github/workflows/update_postscreen_access_list.yml index 3d79e801b..eed07876e 100644 --- a/.github/workflows/update_postscreen_access_list.yml +++ b/.github/workflows/update_postscreen_access_list.yml @@ -15,7 +15,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Generate postscreen_access.cidr run: | diff --git a/.gitignore b/.gitignore index c1c5e1b8f..a06c3da7f 100644 --- a/.gitignore +++ b/.gitignore @@ -45,6 +45,7 @@ data/conf/rspamd/local.d/* data/conf/rspamd/override.d/* data/conf/sogo/custom-theme.js data/conf/sogo/plist_ldap +data/conf/sogo/plist_ldap.sh data/conf/sogo/sieve.creds data/conf/sogo/cron.creds data/conf/sogo/custom-fulllogo.svg @@ -73,3 +74,5 @@ rebuild-images.sh refresh_images.sh update_diffs/ create_cold_standby.sh +!data/conf/nginx/mailcow_auth.conf +data/conf/postfix/postfix-tlspol \ No newline at end of file diff --git a/README.md b/README.md index dc9b76be0..40288f10e 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,22 @@ You can also [get a SAL](https://www.servercow.de/mailcow?lang=en#sal) which is Or just spread the word: moo. +## Many thanks to our GitHub Sponsors ❤️ +A big thank you to everyone supporting us on GitHub Sponsors—your contributions mean the world to us! Special thanks to the following amazing supporters: + +### 100$/Month Sponsors + + + +### 50$/Month Sponsors + + ## Info, documentation and support Please see [the official documentation](https://docs.mailcow.email/) for installation and support instructions. 🐄 diff --git a/_modules/scripts/core.sh b/_modules/scripts/core.sh new file mode 100644 index 000000000..f776c6212 --- /dev/null +++ b/_modules/scripts/core.sh @@ -0,0 +1,230 @@ +#!/usr/bin/env bash +# _modules/scripts/core.sh +# THIS SCRIPT IS DESIGNED TO BE RUNNING BY MAILCOW SCRIPTS ONLY! +# DO NOT, AGAIN, NOT TRY TO RUN THIS SCRIPT STANDALONE!!!!!! + +# ANSI color for red errors +RED='\e[31m' +GREEN='\e[32m' +YELLOW='\e[33m' +BLUE='\e[34m' +MAGENTA='\e[35m' +LIGHT_RED='\e[91m' +LIGHT_GREEN='\e[92m' +NC='\e[0m' + +caller="${BASH_SOURCE[1]##*/}" + +get_installed_tools(){ + for bin in openssl curl docker git awk sha1sum grep cut jq; do + if [[ -z $(command -v ${bin}) ]]; then + echo "Error: Cannot find command '${bin}'. Cannot proceed." + echo "Solution: Please review system requirements and install requirements. Then, re-run the script." + echo "See System Requirements: https://docs.mailcow.email/getstarted/install/" + echo "Exiting..." + exit 1 + fi + done + + if grep --help 2>&1 | head -n 1 | grep -q -i "busybox"; then echo -e "${LIGHT_RED}BusyBox grep detected, please install gnu grep, \"apk add --no-cache --upgrade grep\"${NC}"; exit 1; fi + # This will also cover sort + if cp --help 2>&1 | head -n 1 | grep -q -i "busybox"; then echo -e "${LIGHT_RED}BusyBox cp detected, please install coreutils, \"apk add --no-cache --upgrade coreutils\"${NC}"; exit 1; fi + if sed --help 2>&1 | head -n 1 | grep -q -i "busybox"; then echo -e "${LIGHT_RED}BusyBox sed detected, please install gnu sed, \"apk add --no-cache --upgrade sed\"${NC}"; exit 1; fi +} + +get_docker_version(){ + # Check Docker Version (need at least 24.X) + docker_version=$(docker version --format '{{.Server.Version}}' | cut -d '.' -f 1) +} + +get_compose_type(){ + if docker compose > /dev/null 2>&1; then + if docker compose version --short | grep -e "^2." -e "^v2." > /dev/null 2>&1; then + COMPOSE_VERSION=native + COMPOSE_COMMAND="docker compose" + if [[ "$caller" == "update.sh" ]]; then + sed -i 's/^DOCKER_COMPOSE_VERSION=.*/DOCKER_COMPOSE_VERSION=native/' "$SCRIPT_DIR/mailcow.conf" + fi + echo -e "\e[33mFound Docker Compose Plugin (native).\e[0m" + echo -e "\e[33mSetting the DOCKER_COMPOSE_VERSION Variable to native\e[0m" + sleep 2 + echo -e "\e[33mNotice: You'll have to update this Compose Version via your Package Manager manually!\e[0m" + else + echo -e "\e[31mCannot find Docker Compose with a Version Higher than 2.X.X.\e[0m" + echo -e "\e[31mPlease update/install it manually regarding to this doc site: https://docs.mailcow.email/install/\e[0m" + exit 1 + fi + elif docker-compose > /dev/null 2>&1; then + if ! [[ $(alias docker-compose 2> /dev/null) ]] ; then + if docker-compose version --short | grep "^2." > /dev/null 2>&1; then + COMPOSE_VERSION=standalone + COMPOSE_COMMAND="docker-compose" + if [[ "$caller" == "update.sh" ]]; then + sed -i 's/^DOCKER_COMPOSE_VERSION=.*/DOCKER_COMPOSE_VERSION=standalone/' "$SCRIPT_DIR/mailcow.conf" + fi + echo -e "\e[33mFound Docker Compose Standalone.\e[0m" + echo -e "\e[33mSetting the DOCKER_COMPOSE_VERSION Variable to standalone\e[0m" + sleep 2 + echo -e "\e[33mNotice: For an automatic update of docker-compose please use the update_compose.sh scripts located at the helper-scripts folder.\e[0m" + else + echo -e "\e[31mCannot find Docker Compose with a Version Higher than 2.X.X.\e[0m" + echo -e "\e[31mPlease update/install manually regarding to this doc site: https://docs.mailcow.email/install/\e[0m" + exit 1 + fi + fi + else + echo -e "\e[31mCannot find Docker Compose.\e[0m" + echo -e "\e[31mPlease install it regarding to this doc site: https://docs.mailcow.email/install/\e[0m" + exit 1 + fi +} + +detect_bad_asn() { + echo -e "\e[33mDetecting if your IP is listed on Spamhaus Bad ASN List...\e[0m" + response=$(curl --connect-timeout 15 --max-time 30 -s -o /dev/null -w "%{http_code}" "https://asn-check.mailcow.email") + if [ "$response" -eq 503 ]; then + if [ -z "$SPAMHAUS_DQS_KEY" ]; then + echo -e "\e[33mYour server's public IP uses an AS that is blocked by Spamhaus to use their DNS public blocklists for Postfix.\e[0m" + echo -e "\e[33mmailcow did not detected a value for the variable SPAMHAUS_DQS_KEY inside mailcow.conf!\e[0m" + sleep 2 + echo "" + echo -e "\e[33mTo use the Spamhaus DNS Blocklists again, you will need to create a FREE account for their Data Query Service (DQS) at: https://www.spamhaus.com/free-trial/sign-up-for-a-free-data-query-service-account\e[0m" + echo -e "\e[33mOnce done, enter your DQS API key in mailcow.conf and mailcow will do the rest for you!\e[0m" + echo "" + sleep 2 + else + echo -e "\e[33mYour server's public IP uses an AS that is blocked by Spamhaus to use their DNS public blocklists for Postfix.\e[0m" + echo -e "\e[32mmailcow detected a Value for the variable SPAMHAUS_DQS_KEY inside mailcow.conf. Postfix will use DQS with the given API key...\e[0m" + fi + elif [ "$response" -eq 200 ]; then + echo -e "\e[33mCheck completed! Your IP is \e[32mclean\e[0m" + elif [ "$response" -eq 429 ]; then + echo -e "\e[33mCheck completed! \e[31mYour IP seems to be rate limited on the ASN Check service... please try again later!\e[0m" + else + echo -e "\e[31mCheck failed! \e[0mMaybe a DNS or Network problem?\e[0m" + fi +} + +check_online_status() { + CHECK_ONLINE_DOMAINS=('https://github.com' 'https://hub.docker.com') + for domain in "${CHECK_ONLINE_DOMAINS[@]}"; do + if timeout 6 curl --head --silent --output /dev/null ${domain}; then + return 0 + fi + done + return 1 +} + +prefetch_images() { + [[ -z ${BRANCH} ]] && { echo -e "\e[33m\nUnknown branch...\e[0m"; exit 1; } + git fetch origin #${BRANCH} + while read image; do + RET_C=0 + until docker pull "${image}"; do + RET_C=$((RET_C + 1)) + echo -e "\e[33m\nError pulling $image, retrying...\e[0m" + [ ${RET_C} -gt 3 ] && { echo -e "\e[31m\nToo many failed retries, exiting\e[0m"; exit 1; } + sleep 1 + done + done < <(git show "origin/${BRANCH}:docker-compose.yml" | grep "image:" | awk '{ gsub("image:","", $3); print $2 }') +} + +docker_garbage() { + SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/../.." && pwd )" + IMGS_TO_DELETE=() + + declare -A IMAGES_INFO + COMPOSE_IMAGES=($(grep -oP "image: \K(ghcr\.io/)?mailcow.+" "${SCRIPT_DIR}/docker-compose.yml")) + + for existing_image in $(docker images --format "{{.ID}}:{{.Repository}}:{{.Tag}}" | grep -E '(mailcow/|ghcr\.io/mailcow/)'); do + ID=$(echo "$existing_image" | cut -d ':' -f 1) + REPOSITORY=$(echo "$existing_image" | cut -d ':' -f 2) + TAG=$(echo "$existing_image" | cut -d ':' -f 3) + + if [[ "$REPOSITORY" == "mailcow/backup" || "$REPOSITORY" == "ghcr.io/mailcow/backup" ]]; then + if [[ "$TAG" != "" ]]; then + continue + fi + fi + + if [[ " ${COMPOSE_IMAGES[@]} " =~ " ${REPOSITORY}:${TAG} " ]]; then + continue + else + IMGS_TO_DELETE+=("$ID") + IMAGES_INFO["$ID"]="$REPOSITORY:$TAG" + fi + done + + if [[ ! -z ${IMGS_TO_DELETE[*]} ]]; then + echo "The following unused mailcow images were found:" + for id in "${IMGS_TO_DELETE[@]}"; do + echo " ${IMAGES_INFO[$id]} ($id)" + done + + if [ -z "$FORCE" ]; then + read -r -p "Do you want to delete them to free up some space? [y/N] " response + if [[ "$response" =~ ^([yY][eE][sS]|[yY])+$ ]]; then + docker rmi ${IMGS_TO_DELETE[*]} + else + echo "OK, skipped." + fi + else + echo "Running in forced mode! Force removing old mailcow images..." + docker rmi ${IMGS_TO_DELETE[*]} + fi + echo -e "\e[32mFurther cleanup...\e[0m" + echo "If you want to cleanup further garbage collected by Docker, please make sure all containers are up and running before cleaning your system by executing \"docker system prune\"" + fi +} + +in_array() { + local e match="$1" + shift + for e; do [[ "$e" == "$match" ]] && return 0; done + return 1 +} + +detect_major_update() { + if [ ${BRANCH} == "master" ]; then + # Array with major versions + # Add major versions here + MAJOR_VERSIONS=( + "2025-02" + "2025-03" + "2025-09" + ) + + current_version="" + if [[ -f "${SCRIPT_DIR}/data/web/inc/app_info.inc.php" ]]; then + current_version=$(grep 'MAILCOW_GIT_VERSION' ${SCRIPT_DIR}/data/web/inc/app_info.inc.php | sed -E 's/.*MAILCOW_GIT_VERSION="([^"]+)".*/\1/') + fi + if [[ -z "$current_version" ]]; then + return 1 + fi + release_url="https://github.com/mailcow/mailcow-dockerized/releases/tag" + + updates_to_apply=() + + for version in "${MAJOR_VERSIONS[@]}"; do + if [[ "$current_version" < "$version" ]]; then + updates_to_apply+=("$version") + fi + done + + if [[ ${#updates_to_apply[@]} -gt 0 ]]; then + echo -e "\e[33m\nMAJOR UPDATES to be applied:\e[0m" + for update in "${updates_to_apply[@]}"; do + echo "$update - $release_url/$update" + done + + echo -e "\nPlease read the release notes before proceeding." + read -p "Do you want to proceed with the update? [y/n] " response + if [[ "${response}" =~ ^([yY][eE][sS]|[yY])+$ ]]; then + echo "Proceeding with the update..." + else + echo "Update canceled. Exiting." + exit 1 + fi + fi + fi +} diff --git a/_modules/scripts/ipv6_controller.sh b/_modules/scripts/ipv6_controller.sh new file mode 100644 index 000000000..a025ee178 --- /dev/null +++ b/_modules/scripts/ipv6_controller.sh @@ -0,0 +1,239 @@ +#!/usr/bin/env bash +# _modules/scripts/ipv6_controller.sh +# THIS SCRIPT IS DESIGNED TO BE RUNNING BY MAILCOW SCRIPTS ONLY! +# DO NOT, AGAIN, NOT TRY TO RUN THIS SCRIPT STANDALONE!!!!!! + +# 1) Check if the host supports IPv6 +get_ipv6_support() { + # ---- helper: probe external IPv6 connectivity without DNS ---- + _probe_ipv6_connectivity() { + # Use literal, always-on IPv6 echo responders (no DNS required) + local PROBE_IPS=("2001:4860:4860::8888" "2606:4700:4700::1111") + local ip rc=1 + + for ip in "${PROBE_IPS[@]}"; do + if command -v ping6 &>/dev/null; then + ping6 -c1 -W2 "$ip" &>/dev/null || ping6 -c1 -w2 "$ip" &>/dev/null + rc=$? + elif command -v ping &>/dev/null; then + ping -6 -c1 -W2 "$ip" &>/dev/null || ping -6 -c1 -w2 "$ip" &>/dev/null + rc=$? + else + rc=1 + fi + [[ $rc -eq 0 ]] && return 0 + done + return 1 + } + + if [[ ! -f /proc/net/if_inet6 ]] || grep -qs '^1' /proc/sys/net/ipv6/conf/all/disable_ipv6 2>/dev/null; then + DETECTED_IPV6=false + echo -e "${YELLOW}IPv6 not detected on host – ${LIGHT_RED}IPv6 is administratively disabled${YELLOW}.${NC}" + return + fi + + if ip -6 route show default 2>/dev/null | grep -qE '^default'; then + echo -e "${YELLOW}Default IPv6 route found – testing external IPv6 connectivity...${NC}" + if _probe_ipv6_connectivity; then + DETECTED_IPV6=true + echo -e "IPv6 detected on host – ${LIGHT_GREEN}leaving IPv6 support enabled${YELLOW}.${NC}" + else + DETECTED_IPV6=false + echo -e "${YELLOW}Default IPv6 route present but external IPv6 connectivity failed – ${LIGHT_RED}disabling IPv6 support${YELLOW}.${NC}" + fi + return + fi + + if ip -6 addr show scope global 2>/dev/null | grep -q 'inet6'; then + DETECTED_IPV6=false + echo -e "${YELLOW}Global IPv6 address present but no default route – ${LIGHT_RED}disabling IPv6 support${YELLOW}.${NC}" + return + fi + + if ip -6 addr show scope link 2>/dev/null | grep -q 'inet6'; then + echo -e "${YELLOW}Only link-local IPv6 addresses found – testing external IPv6 connectivity...${NC}" + if _probe_ipv6_connectivity; then + DETECTED_IPV6=true + echo -e "External IPv6 connectivity available – ${LIGHT_GREEN}leaving IPv6 support enabled${YELLOW}.${NC}" + else + DETECTED_IPV6=false + echo -e "${YELLOW}Only link-local IPv6 present and no external connectivity – ${LIGHT_RED}disabling IPv6 support${YELLOW}.${NC}" + fi + return + fi + + DETECTED_IPV6=false + echo -e "${YELLOW}IPv6 not detected on host – ${LIGHT_RED}disabling IPv6 support${YELLOW}.${NC}" +} + +# 2) Ensure Docker daemon.json has (or create) the required IPv6 settings +docker_daemon_edit(){ + DOCKER_DAEMON_CONFIG="/etc/docker/daemon.json" + DOCKER_MAJOR=$(docker version --format '{{.Server.Version}}' 2>/dev/null | cut -d. -f1) + MISSING=() + + _has_kv() { grep -Eq "\"$1\"[[:space:]]*:[[:space:]]*$2" "$DOCKER_DAEMON_CONFIG" 2>/dev/null; } + + if [[ -f "$DOCKER_DAEMON_CONFIG" ]]; then + + # reject empty or whitespace-only file immediately + if [[ ! -s "$DOCKER_DAEMON_CONFIG" ]] || ! grep -Eq '[{}]' "$DOCKER_DAEMON_CONFIG"; then + echo -e "${RED}ERROR: $DOCKER_DAEMON_CONFIG exists but is empty or contains no JSON braces – please initialize it with valid JSON (e.g. {}).${NC}" + exit 1 + fi + + # Validate JSON if jq is present + if command -v jq &>/dev/null && ! jq empty "$DOCKER_DAEMON_CONFIG" &>/dev/null; then + echo -e "${RED}ERROR: Invalid JSON in $DOCKER_DAEMON_CONFIG – please correct manually.${NC}" + exit 1 + fi + + # Gather missing keys + ! _has_kv ipv6 true && MISSING+=("ipv6: true") + + # For Docker < 28, keep requiring fixed-cidr-v6 (default bridge needs it on old engines) + if [[ -n "$DOCKER_MAJOR" && "$DOCKER_MAJOR" -lt 28 ]]; then + ! grep -Eq '"fixed-cidr-v6"[[:space:]]*:[[:space:]]*".+"' "$DOCKER_DAEMON_CONFIG" \ + && MISSING+=('fixed-cidr-v6: "fd00:dead:beef:c0::/80"') + fi + + # For Docker < 27, ip6tables needed and was tied to experimental in older releases + if [[ -n "$DOCKER_MAJOR" && "$DOCKER_MAJOR" -lt 27 ]]; then + _has_kv ipv6 true && ! _has_kv ip6tables true && MISSING+=("ip6tables: true") + ! _has_kv experimental true && MISSING+=("experimental: true") + fi + + # Fix if needed + if ((${#MISSING[@]}>0)); then + echo -e "${MAGENTA}Your daemon.json is missing: ${YELLOW}${MISSING[*]}${NC}" + if [[ -n "$FORCE" ]]; then + ans=Y + else + read -p "Would you like to update $DOCKER_DAEMON_CONFIG now? [Y/n] " ans + ans=${ans:-Y} + fi + + if [[ $ans =~ ^[Yy]$ ]]; then + cp "$DOCKER_DAEMON_CONFIG" "${DOCKER_DAEMON_CONFIG}.bak" + if command -v jq &>/dev/null; then + TMP=$(mktemp) + # Base filter: ensure ipv6 = true + JQ_FILTER='.ipv6 = true' + + # Add fixed-cidr-v6 only for Docker < 28 + if [[ -n "$DOCKER_MAJOR" && "$DOCKER_MAJOR" -lt 28 ]]; then + JQ_FILTER+=' | .["fixed-cidr-v6"] = (.["fixed-cidr-v6"] // "fd00:dead:beef:c0::/80")' + fi + + # Add ip6tables/experimental only for Docker < 27 + if [[ -n "$DOCKER_MAJOR" && "$DOCKER_MAJOR" -lt 27 ]]; then + JQ_FILTER+=' | .ip6tables = true | .experimental = true' + fi + + jq "$JQ_FILTER" "$DOCKER_DAEMON_CONFIG" >"$TMP" && mv "$TMP" "$DOCKER_DAEMON_CONFIG" + echo -e "${LIGHT_GREEN}daemon.json updated. Restarting Docker...${NC}" + (command -v systemctl &>/dev/null && systemctl restart docker) || service docker restart + echo -e "${YELLOW}Docker restarted.${NC}" + else + echo -e "${RED}Please install jq or manually update daemon.json and restart Docker.${NC}" + exit 1 + fi + else + echo -e "${YELLOW}User declined Docker update – please insert these changes manually:${NC}" + echo "${MISSING[*]}" + exit 1 + fi + fi + + else + # Create new daemon.json if missing + if [[ -n "$FORCE" ]]; then + ans=Y + else + read -p "$DOCKER_DAEMON_CONFIG not found. Create it with IPv6 settings? [Y/n] " ans + ans=${ans:-Y} + fi + + if [[ $ans =~ ^[Yy]$ ]]; then + mkdir -p "$(dirname "$DOCKER_DAEMON_CONFIG")" + if [[ -n "$DOCKER_MAJOR" && "$DOCKER_MAJOR" -lt 27 ]]; then + cat > "$DOCKER_DAEMON_CONFIG" < "$DOCKER_DAEMON_CONFIG" < "$DOCKER_DAEMON_CONFIG" </dev/null && systemctl restart docker) || service docker restart + echo "Docker restarted." + else + echo "User declined to create daemon.json – please manually merge the docker daemon with these configs:" + echo "${MISSING[*]}" + exit 1 + fi + fi +} + +# 3) Main wrapper for generate_config.sh and update.sh +configure_ipv6() { + # detect manual override if mailcow.conf is present + if [[ -n "$MAILCOW_CONF" && -f "$MAILCOW_CONF" ]] && grep -q '^ENABLE_IPV6=' "$MAILCOW_CONF"; then + MANUAL_SETTING=$(grep '^ENABLE_IPV6=' "$MAILCOW_CONF" | cut -d= -f2) + elif [[ -z "$MAILCOW_CONF" ]] && [[ -n "${ENABLE_IPV6:-}" ]]; then + MANUAL_SETTING="$ENABLE_IPV6" + else + MANUAL_SETTING="" + fi + + get_ipv6_support + + # if user manually set it, check for mismatch + if [[ "$DETECTED_IPV6" != "true" ]]; then + if [[ -n "$MAILCOW_CONF" && -f "$MAILCOW_CONF" ]]; then + if grep -q '^ENABLE_IPV6=' "$MAILCOW_CONF"; then + sed -i 's/^ENABLE_IPV6=.*/ENABLE_IPV6=false/' "$MAILCOW_CONF" + else + echo "ENABLE_IPV6=false" >> "$MAILCOW_CONF" + fi + else + export IPV6_BOOL=false + fi + echo "Skipping Docker IPv6 configuration because host does not support IPv6." + echo "Make sure to check if your docker daemon.json does not include \"enable_ipv6\": true if you do not want IPv6." + echo "IPv6 configuration complete: ENABLE_IPV6=false" + sleep 2 + return + fi + + docker_daemon_edit + + if [[ -n "$MAILCOW_CONF" && -f "$MAILCOW_CONF" ]]; then + if grep -q '^ENABLE_IPV6=' "$MAILCOW_CONF"; then + sed -i 's/^ENABLE_IPV6=.*/ENABLE_IPV6=true/' "$MAILCOW_CONF" + else + echo "ENABLE_IPV6=true" >> "$MAILCOW_CONF" + fi + else + export IPV6_BOOL=true + fi + + echo "IPv6 configuration complete: ENABLE_IPV6=true" +} \ No newline at end of file diff --git a/_modules/scripts/migrate_options.sh b/_modules/scripts/migrate_options.sh new file mode 100644 index 000000000..6a584b9f7 --- /dev/null +++ b/_modules/scripts/migrate_options.sh @@ -0,0 +1,96 @@ +#!/usr/bin/env bash +# _modules/scripts/migrate_options.sh +# THIS SCRIPT IS DESIGNED TO BE RUNNING BY MAILCOW SCRIPTS ONLY! +# DO NOT, AGAIN, NOT TRY TO RUN THIS SCRIPT STANDALONE!!!!!! + +migrate_config_options() { + + sed -i --follow-symlinks '$a\' mailcow.conf + + KEYS=( + SOLR_HEAP + SKIP_SOLR + SOLR_PORT + FLATCURVE_EXPERIMENTAL + DISABLE_IPv6 + ACME_CONTACT + ) + + for key in "${KEYS[@]}"; do + if grep -q "${key}" mailcow.conf; then + case "${key}" in + SOLR_HEAP) + echo "Removing ${key} in mailcow.conf" + sed -i '/# Solr heap size in MB\b/d' mailcow.conf + sed -i '/# Solr is a prone to run\b/d' mailcow.conf + sed -i '/SOLR_HEAP\b/d' mailcow.conf + ;; + SKIP_SOLR) + echo "Removing ${key} in mailcow.conf" + sed -i '/\bSkip Solr on low-memory\b/d' mailcow.conf + sed -i '/\bSolr is disabled by default\b/d' mailcow.conf + sed -i '/\bDisable Solr or\b/d' mailcow.conf + sed -i '/\bSKIP_SOLR\b/d' mailcow.conf + ;; + SOLR_PORT) + echo "Removing ${key} in mailcow.conf" + sed -i '/\bSOLR_PORT\b/d' mailcow.conf + ;; + FLATCURVE_EXPERIMENTAL) + echo "Removing ${key} in mailcow.conf" + sed -i '/\bFLATCURVE_EXPERIMENTAL\b/d' mailcow.conf + ;; + DISABLE_IPv6) + echo "Migrating ${key} to ENABLE_IPv6 in mailcow.conf" + local old=$(grep '^DISABLE_IPv6=' "mailcow.conf" | cut -d'=' -f2) + local new + if [[ "$old" == "y" ]]; then + new="false" + else + new="true" + fi + sed -i '/^DISABLE_IPv6=/d' "mailcow.conf" + echo "ENABLE_IPV6=$new" >> "mailcow.conf" + ;; + ACME_CONTACT) + echo "Deleting obsoleted ${key} in mailcow.conf" + sed -i '/^# Lets Encrypt registration contact information/d' mailcow.conf + sed -i '/^# Optional: Leave empty for none/d' mailcow.conf + sed -i '/^# This value is only used on first order!/d' mailcow.conf + sed -i '/^# Setting it at a later point will require the following steps:/d' mailcow.conf + sed -i '/^# https:\/\/docs.mailcow.email\/troubleshooting\/debug-reset_tls\//d' mailcow.conf + sed -i '/^ACME_CONTACT=.*/d' mailcow.conf + sed -i '/^#ACME_CONTACT=.*/d' mailcow.conf + ;; + esac + fi + done + + solr_volume=$(docker volume ls -qf name=^${COMPOSE_PROJECT_NAME}_solr-vol-1) + if [[ -n $solr_volume ]]; then + echo -e "\e[34mSolr has been replaced within mailcow since 2025-01.\nThe volume $solr_volume is unused.\e[0m" + sleep 1 + if [ ! "$FORCE" ]; then + read -r -p "Remove $solr_volume? [y/N] " response + if [[ "$response" =~ ^([yY][eE][sS]|[yY])+$ ]]; then + echo -e "\e[33mRemoving $solr_volume...\e[0m" + docker volume rm $solr_volume || echo -e "\e[31mFailed to remove. Remove it manually!\e[0m" + echo -e "\e[32mSuccessfully removed $solr_volume!\e[0m" + else + echo -e "Not removing $solr_volume. Run \`docker volume rm $solr_volume\` manually if needed." + fi + else + echo -e "\e[33mForce removing $solr_volume...\e[0m" + docker volume rm $solr_volume || echo -e "\e[31mFailed to remove. Remove it manually!\e[0m" + echo -e "\e[32mSuccessfully removed $solr_volume!\e[0m" + fi + fi + + # Delete old fts.conf before forced switch to flatcurve to ensure update is working properly + FTS_CONF_PATH="${SCRIPT_DIR}/data/conf/dovecot/conf.d/fts.conf" + if [[ -f "$FTS_CONF_PATH" ]]; then + if grep -q "Autogenerated by mailcow" "$FTS_CONF_PATH"; then + rm -rf $FTS_CONF_PATH + fi + fi +} \ No newline at end of file diff --git a/_modules/scripts/new_options.sh b/_modules/scripts/new_options.sh new file mode 100644 index 000000000..30c747b70 --- /dev/null +++ b/_modules/scripts/new_options.sh @@ -0,0 +1,300 @@ +#!/usr/bin/env bash +# _modules/scripts/new_options.sh +# THIS SCRIPT IS DESIGNED TO BE RUNNING BY MAILCOW SCRIPTS ONLY! +# DO NOT, AGAIN, NOT TRY TO RUN THIS SCRIPT STANDALONE!!!!!! + +adapt_new_options() { + + CONFIG_ARRAY=( + "AUTODISCOVER_SAN" + "SKIP_LETS_ENCRYPT" + "SKIP_SOGO" + "USE_WATCHDOG" + "WATCHDOG_NOTIFY_EMAIL" + "WATCHDOG_NOTIFY_WEBHOOK" + "WATCHDOG_NOTIFY_WEBHOOK_BODY" + "WATCHDOG_NOTIFY_BAN" + "WATCHDOG_NOTIFY_START" + "WATCHDOG_EXTERNAL_CHECKS" + "WATCHDOG_SUBJECT" + "SKIP_CLAMD" + "SKIP_OLEFY" + "SKIP_IP_CHECK" + "ADDITIONAL_SAN" + "DOVEADM_PORT" + "IPV4_NETWORK" + "IPV6_NETWORK" + "LOG_LINES" + "SNAT_TO_SOURCE" + "SNAT6_TO_SOURCE" + "COMPOSE_PROJECT_NAME" + "DOCKER_COMPOSE_VERSION" + "SQL_PORT" + "API_KEY" + "API_KEY_READ_ONLY" + "API_ALLOW_FROM" + "MAILDIR_GC_TIME" + "MAILDIR_SUB" + "ACL_ANYONE" + "FTS_HEAP" + "FTS_PROCS" + "SKIP_FTS" + "ENABLE_SSL_SNI" + "ALLOW_ADMIN_EMAIL_LOGIN" + "SKIP_HTTP_VERIFICATION" + "SOGO_EXPIRE_SESSION" + "SOGO_URL_ENCRYPTION_KEY" + "REDIS_PORT" + "REDISPASS" + "DOVECOT_MASTER_USER" + "DOVECOT_MASTER_PASS" + "MAILCOW_PASS_SCHEME" + "ADDITIONAL_SERVER_NAMES" + "WATCHDOG_VERBOSE" + "WEBAUTHN_ONLY_TRUSTED_VENDORS" + "SPAMHAUS_DQS_KEY" + "SKIP_UNBOUND_HEALTHCHECK" + "DISABLE_NETFILTER_ISOLATION_RULE" + "HTTP_REDIRECT" + "ENABLE_IPV6" + ) + + sed -i --follow-symlinks '$a\' mailcow.conf + for option in ${CONFIG_ARRAY[@]}; do + if grep -q "${option}" mailcow.conf; then + continue + fi + + echo "Adding new option \"${option}\" to mailcow.conf" + + case "${option}" in + AUTODISCOVER_SAN) + echo '# Obtain certificates for autodiscover.* and autoconfig.* domains.' >> mailcow.conf + echo '# This can be useful to switch off in case you are in a scenario where a reverse proxy already handles those.' >> mailcow.conf + echo '# There are mixed scenarios where ports 80,443 are occupied and you do not want to share certs' >> mailcow.conf + echo '# between services. So acme-mailcow obtains for maildomains and all web-things get handled' >> mailcow.conf + echo '# in the reverse proxy.' >> mailcow.conf + echo 'AUTODISCOVER_SAN=y' >> mailcow.conf + ;; + + DOCKER_COMPOSE_VERSION) + echo "# Used Docker Compose version" >> mailcow.conf + echo "# Switch here between native (compose plugin) and standalone" >> mailcow.conf + echo "# For more informations take a look at the mailcow docs regarding the configuration options." >> mailcow.conf + echo "# Normally this should be untouched but if you decided to use either of those you can switch it manually here." >> mailcow.conf + echo "# Please be aware that at least one of those variants should be installed on your machine or mailcow will fail." >> mailcow.conf + echo "" >> mailcow.conf + echo "DOCKER_COMPOSE_VERSION=${DOCKER_COMPOSE_VERSION}" >> mailcow.conf + ;; + + DOVEADM_PORT) + echo "DOVEADM_PORT=127.0.0.1:19991" >> mailcow.conf + ;; + + LOG_LINES) + echo '# Max log lines per service to keep in Redis logs' >> mailcow.conf + echo "LOG_LINES=9999" >> mailcow.conf + ;; + IPV4_NETWORK) + echo '# Internal IPv4 /24 subnet, format n.n.n. (expands to n.n.n.0/24)' >> mailcow.conf + echo "IPV4_NETWORK=172.22.1" >> mailcow.conf + ;; + IPV6_NETWORK) + echo '# Internal IPv6 subnet in fc00::/7' >> mailcow.conf + echo "IPV6_NETWORK=fd4d:6169:6c63:6f77::/64" >> mailcow.conf + ;; + SQL_PORT) + echo '# Bind SQL to 127.0.0.1 on port 13306' >> mailcow.conf + echo "SQL_PORT=127.0.0.1:13306" >> mailcow.conf + ;; + API_KEY) + echo '# Create or override API key for web UI' >> mailcow.conf + echo "#API_KEY=" >> mailcow.conf + ;; + API_KEY_READ_ONLY) + echo '# Create or override read-only API key for web UI' >> mailcow.conf + echo "#API_KEY_READ_ONLY=" >> mailcow.conf + ;; + API_ALLOW_FROM) + echo '# Must be set for API_KEY to be active' >> mailcow.conf + echo '# IPs only, no networks (networks can be set via UI)' >> mailcow.conf + echo "#API_ALLOW_FROM=" >> mailcow.conf + ;; + SNAT_TO_SOURCE) + echo '# Use this IPv4 for outgoing connections (SNAT)' >> mailcow.conf + echo "#SNAT_TO_SOURCE=" >> mailcow.conf + ;; + SNAT6_TO_SOURCE) + echo '# Use this IPv6 for outgoing connections (SNAT)' >> mailcow.conf + echo "#SNAT6_TO_SOURCE=" >> mailcow.conf + ;; + MAILDIR_GC_TIME) + echo '# Garbage collector cleanup' >> mailcow.conf + echo '# Deleted domains and mailboxes are moved to /var/vmail/_garbage/timestamp_sanitizedstring' >> mailcow.conf + echo '# How long should objects remain in the garbage until they are being deleted? (value in minutes)' >> mailcow.conf + echo '# Check interval is hourly' >> mailcow.conf + echo 'MAILDIR_GC_TIME=1440' >> mailcow.conf + ;; + ACL_ANYONE) + echo '# Set this to "allow" to enable the anyone pseudo user. Disabled by default.' >> mailcow.conf + echo '# When enabled, ACL can be created, that apply to "All authenticated users"' >> mailcow.conf + echo '# This should probably only be activated on mail hosts, that are used exclusively by one organisation.' >> mailcow.conf + echo '# Otherwise a user might share data with too many other users.' >> mailcow.conf + echo 'ACL_ANYONE=disallow' >> mailcow.conf + ;; + FTS_HEAP) + echo '# Dovecot Indexing (FTS) Process maximum heap size in MB, there is no recommendation, please see Dovecot docs.' >> mailcow.conf + echo '# Flatcurve is used as FTS Engine. It is supposed to be pretty efficient in CPU and RAM consumption.' >> mailcow.conf + echo '# Please always monitor your Resource consumption!' >> mailcow.conf + echo "FTS_HEAP=128" >> mailcow.conf + ;; + SKIP_FTS) + echo '# Skip FTS (Fulltext Search) for Dovecot on low-memory, low-threaded systems or if you simply want to disable it.' >> mailcow.conf + echo "# Dovecot inside mailcow use Flatcurve as FTS Backend." >> mailcow.conf + echo "SKIP_FTS=y" >> mailcow.conf + ;; + FTS_PROCS) + echo '# Controls how many processes the Dovecot indexing process can spawn at max.' >> mailcow.conf + echo '# Too many indexing processes can use a lot of CPU and Disk I/O' >> mailcow.conf + echo '# Please visit: https://doc.dovecot.org/configuration_manual/service_configuration/#indexer-worker for more informations' >> mailcow.conf + echo "FTS_PROCS=1" >> mailcow.conf + ;; + ENABLE_SSL_SNI) + echo '# Create seperate certificates for all domains - y/n' >> mailcow.conf + echo '# this will allow adding more than 100 domains, but some email clients will not be able to connect with alternative hostnames' >> mailcow.conf + echo '# see https://wiki.dovecot.org/SSL/SNIClientSupport' >> mailcow.conf + echo "ENABLE_SSL_SNI=n" >> mailcow.conf + ;; + SKIP_SOGO) + echo '# Skip SOGo: Will disable SOGo integration and therefore webmail, DAV protocols and ActiveSync support (experimental, unsupported, not fully implemented) - y/n' >> mailcow.conf + echo "SKIP_SOGO=n" >> mailcow.conf + ;; + MAILDIR_SUB) + echo '# MAILDIR_SUB defines a path in a users virtual home to keep the maildir in. Leave empty for updated setups.' >> mailcow.conf + echo "#MAILDIR_SUB=Maildir" >> mailcow.conf + echo "MAILDIR_SUB=" >> mailcow.conf + ;; + WATCHDOG_NOTIFY_WEBHOOK) + echo '# Send notifications to a webhook URL that receives a POST request with the content type "application/json".' >> mailcow.conf + echo '# You can use this to send notifications to services like Discord, Slack and others.' >> mailcow.conf + echo '#WATCHDOG_NOTIFY_WEBHOOK=https://discord.com/api/webhooks/XXXXXXXXXXXXXXXXXXX/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' >> mailcow.conf + ;; + WATCHDOG_NOTIFY_WEBHOOK_BODY) + echo '# JSON body included in the webhook POST request. Needs to be in single quotes.' >> mailcow.conf + echo '# Following variables are available: SUBJECT, BODY' >> mailcow.conf + WEBHOOK_BODY='{"username": "mailcow Watchdog", "content": "**${SUBJECT}**\n${BODY}"}' + echo "#WATCHDOG_NOTIFY_WEBHOOK_BODY='${WEBHOOK_BODY}'" >> mailcow.conf + ;; + WATCHDOG_NOTIFY_BAN) + echo '# Notify about banned IP. Includes whois lookup.' >> mailcow.conf + echo "WATCHDOG_NOTIFY_BAN=y" >> mailcow.conf + ;; + WATCHDOG_NOTIFY_START) + echo '# Send a notification when the watchdog is started.' >> mailcow.conf + echo "WATCHDOG_NOTIFY_START=y" >> mailcow.conf + ;; + WATCHDOG_SUBJECT) + echo '# Subject for watchdog mails. Defaults to "Watchdog ALERT" followed by the error message.' >> mailcow.conf + echo "#WATCHDOG_SUBJECT=" >> mailcow.conf + ;; + WATCHDOG_EXTERNAL_CHECKS) + echo '# Checks if mailcow is an open relay. Requires a SAL. More checks will follow.' >> mailcow.conf + echo '# No data is collected. Opt-in and anonymous.' >> mailcow.conf + echo '# Will only work with unmodified mailcow setups.' >> mailcow.conf + echo "WATCHDOG_EXTERNAL_CHECKS=n" >> mailcow.conf + ;; + SOGO_EXPIRE_SESSION) + echo '# SOGo session timeout in minutes' >> mailcow.conf + echo "SOGO_EXPIRE_SESSION=480" >> mailcow.conf + ;; + REDIS_PORT) + echo "REDIS_PORT=127.0.0.1:7654" >> mailcow.conf + ;; + DOVECOT_MASTER_USER) + echo '# DOVECOT_MASTER_USER and _PASS must _both_ be provided. No special chars.' >> mailcow.conf + echo '# Empty by default to auto-generate master user and password on start.' >> mailcow.conf + echo '# User expands to DOVECOT_MASTER_USER@mailcow.local' >> mailcow.conf + echo '# LEAVE EMPTY IF UNSURE' >> mailcow.conf + echo "DOVECOT_MASTER_USER=" >> mailcow.conf + ;; + DOVECOT_MASTER_PASS) + echo '# LEAVE EMPTY IF UNSURE' >> mailcow.conf + echo "DOVECOT_MASTER_PASS=" >> mailcow.conf + ;; + MAILCOW_PASS_SCHEME) + echo '# Password hash algorithm' >> mailcow.conf + echo '# Only certain password hash algorithm are supported. For a fully list of supported schemes,' >> mailcow.conf + echo '# see https://docs.mailcow.email/models/model-passwd/' >> mailcow.conf + echo "MAILCOW_PASS_SCHEME=BLF-CRYPT" >> mailcow.conf + ;; + ADDITIONAL_SERVER_NAMES) + echo '# Additional server names for mailcow UI' >> mailcow.conf + echo '#' >> mailcow.conf + echo '# Specify alternative addresses for the mailcow UI to respond to' >> mailcow.conf + echo '# This is useful when you set mail.* as ADDITIONAL_SAN and want to make sure mail.maildomain.com will always point to the mailcow UI.' >> mailcow.conf + echo '# If the server name does not match a known site, Nginx decides by best-guess and may redirect users to the wrong web root.' >> mailcow.conf + echo '# You can understand this as server_name directive in Nginx.' >> mailcow.conf + echo '# Comma separated list without spaces! Example: ADDITIONAL_SERVER_NAMES=a.b.c,d.e.f' >> mailcow.conf + echo 'ADDITIONAL_SERVER_NAMES=' >> mailcow.conf + ;; + WEBAUTHN_ONLY_TRUSTED_VENDORS) + echo "# WebAuthn device manufacturer verification" >> mailcow.conf + echo '# After setting WEBAUTHN_ONLY_TRUSTED_VENDORS=y only devices from trusted manufacturers are allowed' >> mailcow.conf + echo '# root certificates can be placed for validation under mailcow-dockerized/data/web/inc/lib/WebAuthn/rootCertificates' >> mailcow.conf + echo 'WEBAUTHN_ONLY_TRUSTED_VENDORS=n' >> mailcow.conf + ;; + SPAMHAUS_DQS_KEY) + echo "# Spamhaus Data Query Service Key" >> mailcow.conf + echo '# Optional: Leave empty for none' >> mailcow.conf + echo '# Enter your key here if you are using a blocked ASN (OVH, AWS, Cloudflare e.g) for the unregistered Spamhaus Blocklist.' >> mailcow.conf + echo '# If empty, it will completely disable Spamhaus blocklists if it detects that you are running on a server using a blocked AS.' >> mailcow.conf + echo '# Otherwise it will work as usual.' >> mailcow.conf + echo 'SPAMHAUS_DQS_KEY=' >> mailcow.conf + ;; + WATCHDOG_VERBOSE) + echo '# Enable watchdog verbose logging' >> mailcow.conf + echo 'WATCHDOG_VERBOSE=n' >> mailcow.conf + ;; + SKIP_UNBOUND_HEALTHCHECK) + echo '# Skip Unbound (DNS Resolver) Healthchecks (NOT Recommended!) - y/n' >> mailcow.conf + echo 'SKIP_UNBOUND_HEALTHCHECK=n' >> mailcow.conf + ;; + DISABLE_NETFILTER_ISOLATION_RULE) + echo '# Prevent netfilter from setting an iptables/nftables rule to isolate the mailcow docker network - y/n' >> mailcow.conf + echo '# CAUTION: Disabling this may expose container ports to other neighbors on the same subnet, even if the ports are bound to localhost' >> mailcow.conf + echo 'DISABLE_NETFILTER_ISOLATION_RULE=n' >> mailcow.conf + ;; + HTTP_REDIRECT) + echo '# Redirect HTTP connections to HTTPS - y/n' >> mailcow.conf + echo 'HTTP_REDIRECT=n' >> mailcow.conf + ;; + ENABLE_IPV6) + echo '# IPv6 Controller Section' >> mailcow.conf + echo '# This variable controls the usage of IPv6 within mailcow.' >> mailcow.conf + echo '# Can either be true or false | Defaults to true' >> mailcow.conf + echo '# WARNING: MAKE SURE TO PROPERLY CONFIGURE IPv6 ON YOUR HOST FIRST BEFORE ENABLING THIS AS FAULTY CONFIGURATIONS CAN LEAD TO OPEN RELAYS!' >> mailcow.conf + echo '# A COMPLETE DOCKER STACK REBUILD (compose down && compose up -d) IS NEEDED TO APPLY THIS.' >> mailcow.conf + echo ENABLE_IPV6=${IPV6_BOOL} >> mailcow.conf + ;; + SKIP_CLAMD) + echo '# Skip ClamAV (clamd-mailcow) anti-virus (Rspamd will auto-detect a missing ClamAV container) - y/n' >> mailcow.conf + echo 'SKIP_CLAMD=n' >> mailcow.conf + ;; + SKIP_OLEFY) + echo '# Skip Olefy (olefy-mailcow) anti-virus for Office documents (Rspamd will auto-detect a missing Olefy container) - y/n' >> mailcow.conf + echo 'SKIP_OLEFY=n' >> mailcow.conf + ;; + REDISPASS) + echo "REDISPASS=$(LC_ALL=C /dev/null | head -c 28)" >> mailcow.conf + ;; + SOGO_URL_ENCRYPTION_KEY) + echo '# SOGo URL encryption key (exactly 16 characters, limited to A–Z, a–z, 0–9)' >> mailcow.conf + echo '# This key is used to encrypt email addresses within SOGo URLs' >> mailcow.conf + echo "SOGO_URL_ENCRYPTION_KEY=$(LC_ALL=C /dev/null | head -c 16)" >> mailcow.conf + ;; + *) + echo "${option}=" >> mailcow.conf + ;; + esac + done +} \ No newline at end of file diff --git a/data/Dockerfiles/acme/Dockerfile b/data/Dockerfiles/acme/Dockerfile index 8aa16ad58..f6e990e57 100644 --- a/data/Dockerfiles/acme/Dockerfile +++ b/data/Dockerfiles/acme/Dockerfile @@ -1,8 +1,7 @@ -FROM alpine:3.20 +FROM alpine:3.21 LABEL maintainer = "The Infrastructure Company GmbH " - RUN apk upgrade --no-cache \ && apk add --update --no-cache \ bash \ @@ -15,7 +14,7 @@ RUN apk upgrade --no-cache \ tini \ tzdata \ python3 \ - acme-tiny --repository=http://dl-cdn.alpinelinux.org/alpine/edge/community/ + acme-tiny COPY acme.sh /srv/acme.sh COPY functions.sh /srv/functions.sh diff --git a/data/Dockerfiles/acme/acme.sh b/data/Dockerfiles/acme/acme.sh index 04ee1f5dc..357a1e56a 100755 --- a/data/Dockerfiles/acme/acme.sh +++ b/data/Dockerfiles/acme/acme.sh @@ -138,7 +138,7 @@ log_f "Resolver OK" log_f "Waiting for domain table..." while [[ -z ${DOMAIN_TABLE} ]]; do curl --silent http://nginx.${COMPOSE_PROJECT_NAME}_mailcow-network/ >/dev/null 2>&1 - DOMAIN_TABLE=$(mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SHOW TABLES LIKE 'domain'" -Bs) + DOMAIN_TABLE=$(mariadb --skip-ssl --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SHOW TABLES LIKE 'domain'" -Bs) [[ -z ${DOMAIN_TABLE} ]] && sleep 10 done log_f "OK" no_date @@ -159,18 +159,6 @@ while true; do fi if [[ ! -f ${ACME_BASE}/acme/account.pem ]]; then log_f "Generating missing Lets Encrypt account key..." - if [[ ! -z ${ACME_CONTACT} ]]; then - if ! verify_email "${ACME_CONTACT}"; then - log_f "Invalid email address, will not start registration!" - sleep 365d - exec $(readlink -f "$0") - else - ACME_CONTACT_PARAMETER="--contact mailto:${ACME_CONTACT}" - log_f "Valid email address, using ${ACME_CONTACT} for registration" - fi - else - ACME_CONTACT_PARAMETER="" - fi openssl genrsa 4096 > ${ACME_BASE}/acme/account.pem else log_f "Using existing Lets Encrypt account key ${ACME_BASE}/acme/account.pem" @@ -218,7 +206,7 @@ while true; do if [[ ${AUTODISCOVER_SAN} == "y" ]]; then # Fetch certs for autoconfig and autodiscover subdomains - ADDITIONAL_WC_ARR+=('autodiscover' 'autoconfig') + ADDITIONAL_WC_ARR+=('autodiscover' 'autoconfig' 'mta-sts') fi if [[ ${SKIP_IP_CHECK} != "y" ]]; then @@ -231,7 +219,7 @@ while true; do ######################################### # IP and webroot challenge verification # - SQL_DOMAINS=$(mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT domain FROM domain WHERE backupmx=0 and active=1" -Bs) + SQL_DOMAINS=$(mariadb --skip-ssl --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT domain FROM domain WHERE backupmx=0 and active=1" -Bs) if [[ ! $? -eq 0 ]]; then log_f "Failed to read SQL domains, retrying in 1 minute..." sleep 1m @@ -299,7 +287,7 @@ while true; do VALIDATED_CERTIFICATES+=("${CERT_NAME}") # obtain server certificate if required - ACME_CONTACT_PARAMETER=${ACME_CONTACT_PARAMETER} DOMAINS=${SERVER_SAN_VALIDATED[@]} /srv/obtain-certificate.sh rsa + DOMAINS=${SERVER_SAN_VALIDATED[@]} /srv/obtain-certificate.sh rsa RETURN="$?" if [[ "$RETURN" == "0" ]]; then # 0 = cert created successfully CERT_AMOUNT_CHANGED=1 diff --git a/data/Dockerfiles/acme/obtain-certificate.sh b/data/Dockerfiles/acme/obtain-certificate.sh index 7271fd5a7..97073d6be 100644 --- a/data/Dockerfiles/acme/obtain-certificate.sh +++ b/data/Dockerfiles/acme/obtain-certificate.sh @@ -93,8 +93,8 @@ until dig letsencrypt.org +time=3 +tries=1 @unbound > /dev/null; do sleep 2 done log_f "Resolver OK" -log_f "Using command acme-tiny ${DIRECTORY_URL} ${ACME_CONTACT_PARAMETER} --account-key ${ACME_BASE}/acme/account.pem --disable-check --csr ${CSR} --acme-dir /var/www/acme/" -ACME_RESPONSE=$(acme-tiny ${DIRECTORY_URL} ${ACME_CONTACT_PARAMETER} \ +log_f "Using command acme-tiny ${DIRECTORY_URL} --account-key ${ACME_BASE}/acme/account.pem --disable-check --csr ${CSR} --acme-dir /var/www/acme/" +ACME_RESPONSE=$(acme-tiny ${DIRECTORY_URL} \ --account-key ${ACME_BASE}/acme/account.pem \ --disable-check \ --csr ${CSR} \ diff --git a/data/Dockerfiles/backup/Dockerfile b/data/Dockerfiles/backup/Dockerfile index 61c8bbe58..6234e725b 100644 --- a/data/Dockerfiles/backup/Dockerfile +++ b/data/Dockerfiles/backup/Dockerfile @@ -1,3 +1,3 @@ FROM debian:bookworm-slim -RUN apt update && apt install pigz \ No newline at end of file +RUN apt update && apt install pigz -y --no-install-recommends \ No newline at end of file diff --git a/data/Dockerfiles/clamd/clamd.sh b/data/Dockerfiles/clamd/clamd.sh index 2c6e75dc6..c656be065 100755 --- a/data/Dockerfiles/clamd/clamd.sh +++ b/data/Dockerfiles/clamd/clamd.sh @@ -8,7 +8,7 @@ fi # Cleaning up garbage echo "Cleaning up tmp files..." -rm -rf /var/lib/clamav/clamav-*.tmp +rm -rf /var/lib/clamav/tmp.* # Prepare whitelist diff --git a/data/Dockerfiles/clamd/clamdcheck.sh b/data/Dockerfiles/clamd/clamdcheck.sh index 7884d48a9..e7e53a65f 100644 --- a/data/Dockerfiles/clamd/clamdcheck.sh +++ b/data/Dockerfiles/clamd/clamdcheck.sh @@ -11,4 +11,4 @@ if [ "${CLAMAV_NO_CLAMD:-}" != "false" ]; then echo "Clamd is up" fi -exit 0 \ No newline at end of file +exit 0 diff --git a/data/Dockerfiles/dockerapi/Dockerfile b/data/Dockerfiles/dockerapi/Dockerfile index bbd4542e6..872764317 100644 --- a/data/Dockerfiles/dockerapi/Dockerfile +++ b/data/Dockerfiles/dockerapi/Dockerfile @@ -1,4 +1,4 @@ -FROM alpine:3.20 +FROM alpine:3.21 LABEL maintainer = "The Infrastructure Company GmbH " diff --git a/data/Dockerfiles/dockerapi/main.py b/data/Dockerfiles/dockerapi/main.py index 95a590fab..748d2ec3d 100644 --- a/data/Dockerfiles/dockerapi/main.py +++ b/data/Dockerfiles/dockerapi/main.py @@ -241,9 +241,9 @@ async def handle_pubsub_messages(channel: aioredis.client.PubSub): else: dockerapi.logger.error("api call: missing container_name, post_action or request") else: - dockerapi.logger.error("Unknwon PubSub recieved - %s" % json.dumps(data_json)) + dockerapi.logger.error("Unknown PubSub received - %s" % json.dumps(data_json)) else: - dockerapi.logger.error("Unknwon PubSub recieved - %s" % json.dumps(data_json)) + dockerapi.logger.error("Unknown PubSub received - %s" % json.dumps(data_json)) await asyncio.sleep(0.0) except asyncio.TimeoutError: diff --git a/data/Dockerfiles/dovecot/Dockerfile b/data/Dockerfiles/dovecot/Dockerfile index 42019bbf4..611dd25eb 100644 --- a/data/Dockerfiles/dovecot/Dockerfile +++ b/data/Dockerfiles/dovecot/Dockerfile @@ -1,9 +1,9 @@ -FROM alpine:3.20 +FROM alpine:3.21 LABEL maintainer="The Infrastructure Company GmbH " # renovate: datasource=github-releases depName=tianon/gosu versioning=semver-coerced extractVersion=^(?.*)$ -ARG GOSU_VERSION=1.16 +ARG GOSU_VERSION=1.17 ENV LANG=C.UTF-8 ENV LC_ALL=C.UTF-8 @@ -34,9 +34,13 @@ RUN addgroup -g 5000 vmail \ lua5.3-sql-mysql \ icu-data-full \ mariadb-connector-c \ + lua-sec \ + mariadb-dev \ + glib-dev \ gcompat \ mariadb-client \ perl \ + perl-dev \ perl-ntlm \ perl-cgi \ perl-crypt-openssl-rsa \ @@ -65,7 +69,7 @@ RUN addgroup -g 5000 vmail \ perl-par-packer \ perl-parse-recdescent \ perl-lockfile-simple \ - libproc \ + libproc2 \ perl-readonly \ perl-regexp-common \ perl-sys-meminfo \ diff --git a/data/Dockerfiles/dovecot/clean_q_aged.sh b/data/Dockerfiles/dovecot/clean_q_aged.sh index 3ccb826ff..f68f9d02a 100755 --- a/data/Dockerfiles/dovecot/clean_q_aged.sh +++ b/data/Dockerfiles/dovecot/clean_q_aged.sh @@ -15,6 +15,6 @@ if ! [[ ${MAX_AGE} =~ ${NUM_REGEXP} ]] ; then exit 1 fi -TO_DELETE=$(mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT COUNT(id) FROM quarantine WHERE created < NOW() - INTERVAL ${MAX_AGE//[!0-9]/} DAY" -BN) -mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "DELETE FROM quarantine WHERE created < NOW() - INTERVAL ${MAX_AGE//[!0-9]/} DAY" +TO_DELETE=$(mariadb --skip-ssl --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT COUNT(id) FROM quarantine WHERE created < NOW() - INTERVAL ${MAX_AGE//[!0-9]/} DAY" -BN) +mariadb --skip-ssl --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "DELETE FROM quarantine WHERE created < NOW() - INTERVAL ${MAX_AGE//[!0-9]/} DAY" echo "Deleted ${TO_DELETE} items from quarantine table (max age is ${MAX_AGE//[!0-9]/} days)" diff --git a/data/Dockerfiles/dovecot/docker-entrypoint.sh b/data/Dockerfiles/dovecot/docker-entrypoint.sh index 842e6a31d..bda836c2e 100755 --- a/data/Dockerfiles/dovecot/docker-entrypoint.sh +++ b/data/Dockerfiles/dovecot/docker-entrypoint.sh @@ -28,7 +28,7 @@ ${VALKEY_CMDLINE} SET DOVECOT_REPL_HEALTH 1 > /dev/null # Create missing directories [[ ! -d /etc/dovecot/sql/ ]] && mkdir -p /etc/dovecot/sql/ -[[ ! -d /etc/dovecot/lua/ ]] && mkdir -p /etc/dovecot/lua/ +[[ ! -d /etc/dovecot/auth/ ]] && mkdir -p /etc/dovecot/auth/ [[ ! -d /etc/dovecot/conf.d/ ]] && mkdir -p /etc/dovecot/conf.d/ [[ ! -d /var/vmail/_garbage ]] && mkdir -p /var/vmail/_garbage [[ ! -d /var/vmail/sieve ]] && mkdir -p /var/vmail/sieve @@ -131,123 +131,6 @@ user_query = SELECT CONCAT(JSON_UNQUOTE(JSON_VALUE(attributes, '$.mailbox_format iterate_query = SELECT username FROM mailbox WHERE active = '1' OR active = '2'; EOF -cat < /etc/dovecot/lua/passwd-verify.lua -function auth_password_verify(req, pass) - - if req.domain == nil then - return dovecot.auth.PASSDB_RESULT_USER_UNKNOWN, "No such user" - end - - if cur == nil then - script_init() - end - - if req.user == nil then - req.user = '' - end - - respbody = {} - - -- check against mailbox passwds - local cur,errorString = con:execute(string.format([[SELECT password FROM mailbox - WHERE username = '%s' - AND active = '1' - AND domain IN (SELECT domain FROM domain WHERE domain='%s' AND active='1') - AND IFNULL(JSON_UNQUOTE(JSON_VALUE(mailbox.attributes, '$.force_pw_update')), 0) != '1' - AND IFNULL(JSON_UNQUOTE(JSON_VALUE(attributes, '$.%s_access')), 1) = '1']], con:escape(req.user), con:escape(req.domain), con:escape(req.service))) - local row = cur:fetch ({}, "a") - while row do - if req.password_verify(req, row.password, pass) == 1 then - con:execute(string.format([[REPLACE INTO sasl_log (service, app_password, username, real_rip) - VALUES ("%s", 0, "%s", "%s")]], con:escape(req.service), con:escape(req.user), con:escape(req.real_rip))) - cur:close() - con:close() - return dovecot.auth.PASSDB_RESULT_OK, "" - end - row = cur:fetch (row, "a") - end - - -- check against app passwds for imap and smtp - -- app passwords are only available for imap, smtp, sieve and pop3 when using sasl - if req.service == "smtp" or req.service == "imap" or req.service == "sieve" or req.service == "pop3" then - local cur,errorString = con:execute(string.format([[SELECT app_passwd.id, %s_access AS has_prot_access, app_passwd.password FROM app_passwd - INNER JOIN mailbox ON mailbox.username = app_passwd.mailbox - WHERE mailbox = '%s' - AND app_passwd.active = '1' - AND mailbox.active = '1' - AND app_passwd.domain IN (SELECT domain FROM domain WHERE domain='%s' AND active='1')]], con:escape(req.service), con:escape(req.user), con:escape(req.domain))) - local row = cur:fetch ({}, "a") - while row do - if req.password_verify(req, row.password, pass) == 1 then - -- if password is valid and protocol access is 1 OR real_rip matches SOGo, proceed - if tostring(req.real_rip) == "__IPV4_SOGO__" then - cur:close() - con:close() - return dovecot.auth.PASSDB_RESULT_OK, "" - elseif row.has_prot_access == "1" then - con:execute(string.format([[REPLACE INTO sasl_log (service, app_password, username, real_rip) - VALUES ("%s", %d, "%s", "%s")]], con:escape(req.service), row.id, con:escape(req.user), con:escape(req.real_rip))) - cur:close() - con:close() - return dovecot.auth.PASSDB_RESULT_OK, "" - end - end - row = cur:fetch (row, "a") - end - end - - cur:close() - con:close() - - return dovecot.auth.PASSDB_RESULT_PASSWORD_MISMATCH, "Failed to authenticate" - - -- PoC - -- local reqbody = string.format([[{ - -- "success":0, - -- "service":"%s", - -- "app_password":false, - -- "username":"%s", - -- "real_rip":"%s" - -- }]], con:escape(req.service), con:escape(req.user), con:escape(req.real_rip)) - -- http.request { - -- method = "POST", - -- url = "http://nginx:8081/sasl_log.php", - -- source = ltn12.source.string(reqbody), - -- headers = { - -- ["content-type"] = "application/json", - -- ["content-length"] = tostring(#reqbody) - -- }, - -- sink = ltn12.sink.table(respbody) - -- } - -end - -function auth_passdb_lookup(req) - return dovecot.auth.PASSDB_RESULT_USER_UNKNOWN, "" -end - -function script_init() - mysql = require "luasql.mysql" - http = require "socket.http" - http.TIMEOUT = 5 - ltn12 = require "ltn12" - env = mysql.mysql() - con = env:connect("__DBNAME__","__DBUSER__","__DBPASS__","localhost") - return 0 -end - -function script_deinit() - con:close() - env:close() -end -EOF - -# Replace patterns in app-passdb.lua -sed -i "s/__DBUSER__/${DBUSER}/g" /etc/dovecot/lua/passwd-verify.lua -sed -i "s/__DBPASS__/${DBPASS}/g" /etc/dovecot/lua/passwd-verify.lua -sed -i "s/__DBNAME__/${DBNAME}/g" /etc/dovecot/lua/passwd-verify.lua -sed -i "s/__IPV4_SOGO__/${IPV4_NETWORK}.248/g" /etc/dovecot/lua/passwd-verify.lua - # Migrate old sieve_after file [[ -f /etc/dovecot/sieve_after ]] && mv /etc/dovecot/sieve_after /etc/dovecot/global_sieve_after @@ -385,8 +268,8 @@ sievec /usr/lib/dovecot/sieve/report-ham.sieve # Fix permissions chown root:root /etc/dovecot/sql/*.conf -chown root:dovecot /etc/dovecot/sql/dovecot-dict-sql-sieve* /etc/dovecot/sql/dovecot-dict-sql-quota* /etc/dovecot/lua/passwd-verify.lua -chmod 640 /etc/dovecot/sql/*.conf /etc/dovecot/lua/passwd-verify.lua +chown root:dovecot /etc/dovecot/sql/dovecot-dict-sql-sieve* /etc/dovecot/sql/dovecot-dict-sql-quota* /etc/dovecot/auth/passwd-verify.lua +chmod 640 /etc/dovecot/sql/*.conf /etc/dovecot/auth/passwd-verify.lua chown -R vmail:vmail /var/vmail/sieve chown -R vmail:vmail /var/volatile chown -R vmail:vmail /var/vmail_index @@ -414,15 +297,15 @@ printenv | sed 's/^\(.*\)$/export \1/g' > /source_env.sh # Clean stopped imapsync jobs rm -f /tmp/imapsync_busy.lock -IMAPSYNC_TABLE=$(mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SHOW TABLES LIKE 'imapsync'" -Bs) -[[ ! -z ${IMAPSYNC_TABLE} ]] && mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "UPDATE imapsync SET is_running='0'" +IMAPSYNC_TABLE=$(mariadb --skip-ssl --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SHOW TABLES LIKE 'imapsync'" -Bs) +[[ ! -z ${IMAPSYNC_TABLE} ]] && mariadb --skip-ssl --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "UPDATE imapsync SET is_running='0'" # Envsubst maildir_gc echo "$(envsubst < /usr/local/bin/maildir_gc.sh)" > /usr/local/bin/maildir_gc.sh # GUID generation while [[ ${VERSIONS_OK} != 'OK' ]]; do - if [[ ! -z $(mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -B -e "SELECT 'OK' FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = \"${DBNAME}\" AND TABLE_NAME = 'versions'") ]]; then + if [[ ! -z $(mariadb --skip-ssl --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -B -e "SELECT 'OK' FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = \"${DBNAME}\" AND TABLE_NAME = 'versions'") ]]; then VERSIONS_OK=OK else echo "Waiting for versions table to be created..." @@ -433,11 +316,11 @@ PUBKEY_MCRYPT=$(doveconf -P 2> /dev/null | grep -i mail_crypt_global_public_key if [ -f ${PUBKEY_MCRYPT} ]; then GUID=$(cat <(echo ${MAILCOW_HOSTNAME}) /mail_crypt/ecpubkey.pem | sha256sum | cut -d ' ' -f1 | tr -cd "[a-fA-F0-9.:/] ") if [ ${#GUID} -eq 64 ]; then - mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} << EOF + mariadb --skip-ssl --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} << EOF REPLACE INTO versions (application, version) VALUES ("GUID", "${GUID}"); EOF else - mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} << EOF + mariadb --skip-ssl --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} << EOF REPLACE INTO versions (application, version) VALUES ("GUID", "INVALID"); EOF fi @@ -456,7 +339,7 @@ done # For some strange, unknown and stupid reason, Dovecot may run into a race condition, when this file is not touched before it is read by dovecot/auth # May be related to something inside Docker, I seriously don't know -touch /etc/dovecot/lua/passwd-verify.lua +touch /etc/dovecot/auth/passwd-verify.lua if [[ ! -z ${VALKEY_SLAVEOF_IP} ]]; then cp /etc/syslog-ng/syslog-ng-valkey_slave.conf /etc/syslog-ng/syslog-ng.conf diff --git a/data/Dockerfiles/dovecot/imapsync_runner.pl b/data/Dockerfiles/dovecot/imapsync_runner.pl index 9eaf5f431..1030603ce 100644 --- a/data/Dockerfiles/dovecot/imapsync_runner.pl +++ b/data/Dockerfiles/dovecot/imapsync_runner.pl @@ -132,8 +132,8 @@ while ($row = $sth->fetchrow_arrayref()) { "--tmpdir", "/tmp", "--nofoldersizes", "--addheader", - ($timeout1 gt "0" ? () : ('--timeout1', $timeout1)), - ($timeout2 gt "0" ? () : ('--timeout2', $timeout2)), + ($timeout1 le "0" ? () : ('--timeout1', $timeout1)), + ($timeout2 le "0" ? () : ('--timeout2', $timeout2)), ($exclude eq "" ? () : ("--exclude", $exclude)), ($subfolder2 eq "" ? () : ('--subfolder2', $subfolder2)), ($maxage eq "0" ? () : ('--maxage', $maxage)), diff --git a/data/Dockerfiles/dovecot/quarantine_notify.py b/data/Dockerfiles/dovecot/quarantine_notify.py index 1714efcf9..9fd8d6467 100755 --- a/data/Dockerfiles/dovecot/quarantine_notify.py +++ b/data/Dockerfiles/dovecot/quarantine_notify.py @@ -8,7 +8,8 @@ from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import COMMASPACE, formatdate import jinja2 -from jinja2 import Template +from jinja2 import TemplateError +from jinja2.sandbox import SandboxedEnvironment import json import redis import time @@ -75,22 +76,27 @@ try: def notify_rcpt(rcpt, msg_count, quarantine_acl, category): if category == "add_header": category = "add header" - meta_query = query_mysql('SELECT SHA2(CONCAT(id, qid), 256) AS qhash, id, subject, score, sender, created, action FROM quarantine WHERE notified = 0 AND rcpt = "%s" AND score < %f AND (action = "%s" OR "all" = "%s")' % (rcpt, max_score, category, category)) + meta_query = query_mysql('SELECT `qhash`, id, subject, score, sender, created, action FROM quarantine WHERE notified = 0 AND rcpt = "%s" AND score < %f AND (action = "%s" OR "all" = "%s")' % (rcpt, max_score, category, category)) print("%s: %d of %d messages qualify for notification" % (rcpt, len(meta_query), msg_count)) if len(meta_query) == 0: return msg_count = len(meta_query) + env = SandboxedEnvironment() if r.get('Q_HTML'): - try: - template = Template(r.get('Q_HTML')) - except: - print("Error: Cannot parse quarantine template, falling back to default template.") - with open('/templates/quarantine.tpl') as file_: - template = Template(file_.read()) + try: + template = env.from_string(r.get('Q_HTML')) + except Exception: + print("Error: Cannot parse quarantine template, falling back to default template.") + with open('/templates/quarantine.tpl') as file_: + template = env.from_string(file_.read()) else: - with open('/templates/quarantine.tpl') as file_: - template = Template(file_.read()) - html = template.render(meta=meta_query, username=rcpt, counter=msg_count, hostname=mailcow_hostname, quarantine_acl=quarantine_acl) + with open('/templates/quarantine.tpl') as file_: + template = env.from_string(file_.read()) + try: + html = template.render(meta=meta_query, username=rcpt, counter=msg_count, hostname=mailcow_hostname, quarantine_acl=quarantine_acl) + except (jinja2.exceptions.SecurityError, TemplateError) as ex: + print(f"SecurityError or TemplateError in template rendering: {ex}") + return text = html2text.html2text(html) count = 0 while count < 15: diff --git a/data/Dockerfiles/dovecot/quota_notify.py b/data/Dockerfiles/dovecot/quota_notify.py index decf84088..2f5d78451 100755 --- a/data/Dockerfiles/dovecot/quota_notify.py +++ b/data/Dockerfiles/dovecot/quota_notify.py @@ -6,7 +6,7 @@ from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import COMMASPACE, formatdate import jinja2 -from jinja2 import Template +from jinja2.sandbox import SandboxedEnvironment import redis import time import json @@ -33,16 +33,24 @@ while True: if r.get('QW_HTML'): try: - template = Template(r.get('QW_HTML')) - except: - print("Error: Cannot parse quarantine template, falling back to default template.") + env = SandboxedEnvironment() + template = env.from_string(r.get('QW_HTML')) + except Exception: + print("Error: Cannot parse quota template, falling back to default template.") with open('/templates/quota.tpl') as file_: - template = Template(file_.read()) + env = SandboxedEnvironment() + template = env.from_string(file_.read()) else: with open('/templates/quota.tpl') as file_: - template = Template(file_.read()) + env = SandboxedEnvironment() + template = env.from_string(file_.read()) + +try: + html = template.render(username=username, percent=percent) +except (jinja2.exceptions.SecurityError, jinja2.TemplateError) as ex: + print(f"SecurityError or TemplateError in template rendering: {ex}") + sys.exit(1) -html = template.render(username=username, percent=percent) text = html2text.html2text(html) try: diff --git a/data/Dockerfiles/netfilter/Dockerfile b/data/Dockerfiles/netfilter/Dockerfile index 86f9e3f69..57dbd6e94 100644 --- a/data/Dockerfiles/netfilter/Dockerfile +++ b/data/Dockerfiles/netfilter/Dockerfile @@ -1,4 +1,4 @@ -FROM alpine:3.20 +FROM alpine:3.21 LABEL maintainer = "The Infrastructure Company GmbH " diff --git a/data/Dockerfiles/netfilter/docker-entrypoint.sh b/data/Dockerfiles/netfilter/docker-entrypoint.sh index 47370a1fe..98cab0a72 100755 --- a/data/Dockerfiles/netfilter/docker-entrypoint.sh +++ b/data/Dockerfiles/netfilter/docker-entrypoint.sh @@ -1,6 +1,6 @@ #!/bin/sh -backend=iptables +backend=nftables nft list table ip filter &>/dev/null nftables_found=$? diff --git a/data/Dockerfiles/netfilter/main.py b/data/Dockerfiles/netfilter/main.py index 0f3e2fed5..04ef611bc 100644 --- a/data/Dockerfiles/netfilter/main.py +++ b/data/Dockerfiles/netfilter/main.py @@ -1,5 +1,7 @@ #!/usr/bin/env python3 +DEBUG = False + import re import os import sys @@ -20,10 +22,13 @@ from modules.Logger import Logger from modules.IPTables import IPTables from modules.NFTables import NFTables +def logdebug(msg): + if DEBUG: + logger.logInfo("DEBUG: %s" % msg) -# globals +# Globals WHITELIST = [] -BLACKLIST= [] +BLACKLIST = [] bans = {} quit_now = False exit_code = 0 @@ -33,12 +38,10 @@ r = None pubsub = None clear_before_quit = False - def refreshF2boptions(): global f2boptions global quit_now global exit_code - f2boptions = {} if not valkey.get('F2B_OPTIONS'): @@ -61,15 +64,15 @@ def refreshF2boptions(): valkey.set('F2B_OPTIONS', json.dumps(f2boptions, ensure_ascii=False)) def verifyF2boptions(f2boptions): - verifyF2boption(f2boptions,'ban_time', 1800) - verifyF2boption(f2boptions,'max_ban_time', 10000) - verifyF2boption(f2boptions,'ban_time_increment', True) - verifyF2boption(f2boptions,'max_attempts', 10) - verifyF2boption(f2boptions,'retry_window', 600) - verifyF2boption(f2boptions,'netban_ipv4', 32) - verifyF2boption(f2boptions,'netban_ipv6', 128) - verifyF2boption(f2boptions,'banlist_id', str(uuid.uuid4())) - verifyF2boption(f2boptions,'manage_external', 0) + verifyF2boption(f2boptions, 'ban_time', 1800) + verifyF2boption(f2boptions, 'max_ban_time', 10000) + verifyF2boption(f2boptions, 'ban_time_increment', True) + verifyF2boption(f2boptions, 'max_attempts', 10) + verifyF2boption(f2boptions, 'retry_window', 600) + verifyF2boption(f2boptions, 'netban_ipv4', 32) + verifyF2boption(f2boptions, 'netban_ipv6', 128) + verifyF2boption(f2boptions, 'banlist_id', str(uuid.uuid4())) + verifyF2boption(f2boptions, 'manage_external', 0) def verifyF2boption(f2boptions, f2boption, f2bdefault): f2boptions[f2boption] = f2boptions[f2boption] if f2boption in f2boptions and f2boptions[f2boption] is not None else f2bdefault @@ -111,7 +114,7 @@ def get_ip(address): def ban(address): global f2boptions global lock - + logdebug("ban() called with address=%s" % address) refreshF2boptions() MAX_ATTEMPTS = int(f2boptions['max_attempts']) RETRY_WINDOW = int(f2boptions['retry_window']) @@ -119,31 +122,43 @@ def ban(address): NETBAN_IPV6 = '/' + str(f2boptions['netban_ipv6']) ip = get_ip(address) - if not ip: return + if not ip: + logdebug("No valid IP -- skipping ban()") + return address = str(ip) self_network = ipaddress.ip_network(address) with lock: temp_whitelist = set(WHITELIST) - if temp_whitelist: - for wl_key in temp_whitelist: - wl_net = ipaddress.ip_network(wl_key, False) - if wl_net.overlaps(self_network): - logger.logInfo('Address %s is whitelisted by rule %s' % (self_network, wl_net)) - return + logdebug("Checking if %s overlaps with any WHITELIST entries" % self_network) + if temp_whitelist: + for wl_key in temp_whitelist: + wl_net = ipaddress.ip_network(wl_key, False) + logdebug("Checking overlap between %s and %s" % (self_network, wl_net)) + if wl_net.overlaps(self_network): + logger.logInfo( + 'Address %s is allowlisted by rule %s' % (self_network, wl_net)) + return - net = ipaddress.ip_network((address + (NETBAN_IPV4 if type(ip) is ipaddress.IPv4Address else NETBAN_IPV6)), strict=False) + net = ipaddress.ip_network( + (address + (NETBAN_IPV4 if type(ip) is ipaddress.IPv4Address else NETBAN_IPV6)), strict=False) net = str(net) + logdebug("Ban net: %s" % net) if not net in bans: bans[net] = {'attempts': 0, 'last_attempt': 0, 'ban_counter': 0} + logdebug("Initing new ban counter for %s" % net) current_attempt = time.time() + logdebug("Current attempt ts=%s, previous: %s, retry_window: %s" % + (current_attempt, bans[net]['last_attempt'], RETRY_WINDOW)) if current_attempt - bans[net]['last_attempt'] > RETRY_WINDOW: bans[net]['attempts'] = 0 + logdebug("Ban counter for %s reset as window expired" % net) bans[net]['attempts'] += 1 bans[net]['last_attempt'] = current_attempt + logdebug("%s attempts now %d" % (net, bans[net]['attempts'])) if bans[net]['attempts'] >= MAX_ATTEMPTS: cur_time = int(round(time.time())) @@ -151,34 +166,41 @@ def ban(address): logger.logCrit('Banning %s for %d minutes' % (net, NET_BAN_TIME / 60 )) if type(ip) is ipaddress.IPv4Address and int(f2boptions['manage_external']) != 1: with lock: + logdebug("Calling tables.banIPv4(%s)" % net) tables.banIPv4(net) elif int(f2boptions['manage_external']) != 1: with lock: + logdebug("Calling tables.banIPv6(%s)" % net) tables.banIPv6(net) + logdebug("Updating F2B_ACTIVE_BANS[%s]=%d" % + (net, cur_time + NET_BAN_TIME)) valkey.hset('F2B_ACTIVE_BANS', '%s' % net, cur_time + NET_BAN_TIME) else: - logger.logWarn('%d more attempts in the next %d seconds until %s is banned' % (MAX_ATTEMPTS - bans[net]['attempts'], RETRY_WINDOW, net)) + logger.logWarn('%d more attempts in the next %d seconds until %s is banned' % ( + MAX_ATTEMPTS - bans[net]['attempts'], RETRY_WINDOW, net)) def unban(net): global lock - + logdebug("Calling unban() with net=%s" % net) if not net in bans: - logger.logInfo('%s is not banned, skipping unban and deleting from queue (if any)' % net) - valkey.hdel('F2B_QUEUE_UNBAN', '%s' % net) - return - + logger.logInfo( + '%s is not banned, skipping unban and deleting from queue (if any)' % net) + valkey.hdel('F2B_QUEUE_UNBAN', '%s' % net) + return logger.logInfo('Unbanning %s' % net) if type(ipaddress.ip_network(net)) is ipaddress.IPv4Network: with lock: + logdebug("Calling tables.unbanIPv4(%s)" % net) tables.unbanIPv4(net) else: with lock: + logdebug("Calling tables.unbanIPv6(%s)" % net) tables.unbanIPv6(net) - valkey.hdel('F2B_ACTIVE_BANS', '%s' % net) valkey.hdel('F2B_QUEUE_UNBAN', '%s' % net) if net in bans: + logdebug("Unban for %s, setting attempts=0, ban_counter+=1" % net) bans[net]['attempts'] = 0 bans[net]['ban_counter'] += 1 @@ -204,17 +226,19 @@ def permBan(net, unban=False): if is_unbanned: valkey.hdel('F2B_PERM_BANS', '%s' % net) - logger.logCrit('Removed host/network %s from blacklist' % net) + logger.logCrit('Removed host/network %s from denylist' % net) elif is_banned: valkey.hset('F2B_PERM_BANS', '%s' % net, int(round(time.time()))) - logger.logCrit('Added host/network %s to blacklist' % net) + logger.logCrit('Added host/network %s to denylist' % net) def clear(): global lock logger.logInfo('Clearing all bans') for net in bans.copy(): + logdebug("Unbanning net: %s" % net) unban(net) with lock: + logdebug("Clearing IPv4/IPv6 table") tables.clearIPv4Table() tables.clearIPv6Table() try: @@ -275,21 +299,35 @@ def snat6(snat_target): def autopurge(): global f2boptions - + logdebug("autopurge thread started") while not quit_now: + logdebug("autopurge tick") time.sleep(10) refreshF2boptions() MAX_ATTEMPTS = int(f2boptions['max_attempts']) QUEUE_UNBAN = valkey.hgetall('F2B_QUEUE_UNBAN') + logdebug("QUEUE_UNBAN: %s" % QUEUE_UNBAN) if QUEUE_UNBAN: for net in QUEUE_UNBAN: + logdebug("Autopurge: unbanning queued net: %s" % net) unban(str(net)) - for net in bans.copy(): - if bans[net]['attempts'] >= MAX_ATTEMPTS: - NET_BAN_TIME = calcNetBanTime(bans[net]['ban_counter']) - TIME_SINCE_LAST_ATTEMPT = time.time() - bans[net]['last_attempt'] - if TIME_SINCE_LAST_ATTEMPT > NET_BAN_TIME: - unban(net) + # Only check expiry for actively banned IPs: + active_bans = r.hgetall('F2B_ACTIVE_BANS') + now = time.time() + for net_str, expire_str in active_bans.items(): + logdebug("Checking ban expiry for (actively banned): %s" % net_str) + # Defensive: always process if timer missing or expired + try: + expire = float(expire_str) + except Exception: + logdebug("Invalid expire time for %s; unbanning" % net_str) + unban(net_str) + continue + time_left = expire - now + logdebug("Time left for %s: %.1f seconds" % (net_str, time_left)) + if time_left <= 0: + logdebug("Ban expired for %s" % net_str) + unban(net_str) def mailcowChainOrder(): global lock @@ -359,7 +397,7 @@ def whitelistUpdate(): with lock: if Counter(new_whitelist) != Counter(WHITELIST): WHITELIST = new_whitelist - logger.logInfo('Whitelist was changed, it has %s entries' % len(WHITELIST)) + logger.logInfo('Allowlist was changed, it has %s entries' % len(WHITELIST)) time.sleep(60.0 - ((time.time() - start_time) % 60.0)) def blacklistUpdate(): @@ -375,7 +413,7 @@ def blacklistUpdate(): addban = set(new_blacklist).difference(BLACKLIST) delban = set(BLACKLIST).difference(new_blacklist) BLACKLIST = new_blacklist - logger.logInfo('Blacklist was changed, it has %s entries' % len(BLACKLIST)) + logger.logInfo('Denylist was changed, it has %s entries' % len(BLACKLIST)) if addban: for net in addban: permBan(net=net) @@ -386,42 +424,43 @@ def blacklistUpdate(): def sigterm_quit(signum, frame): global clear_before_quit + logdebug("SIGTERM received, setting clear_before_quit to True and exiting") clear_before_quit = True sys.exit(exit_code) -def berfore_quit(): +def before_quit(): + logdebug("before_quit called, clear_before_quit=%s" % clear_before_quit) if clear_before_quit: clear() if pubsub is not None: pubsub.unsubscribe() - if __name__ == '__main__': - atexit.register(berfore_quit) + logger = Logger() + logdebug("Sys.argv: %s" % sys.argv) + atexit.register(before_quit) signal.signal(signal.SIGTERM, sigterm_quit) - # init Logger - logger = Logger() - - # init backend backend = sys.argv[1] + logdebug("Backend: %s" % backend) if backend == "nftables": logger.logInfo('Using NFTables backend') tables = NFTables(chain_name, logger) else: logger.logInfo('Using IPTables backend') + logger.logWarn( + "DEPRECATION: iptables-legacy is deprecated and will be removed in future releases. " + "Please switch to nftables on your host to ensure complete compatibility." + ) + time.sleep(5) tables = IPTables(chain_name, logger) - # In case a previous session was killed without cleanup clear() - - # Reinit MAILCOW chain - # Is called before threads start, no locking logger.logInfo("Initializing mailcow netfilter chain") tables.initChainIPv4() tables.initChainIPv6() - if os.getenv("DISABLE_NETFILTER_ISOLATION_RULE").lower() in ("y", "yes"): + if os.getenv("DISABLE_NETFILTER_ISOLATION_RULE", "").lower() in ("y", "yes"): logger.logInfo(f"Skipping {chain_name} isolation") else: logger.logInfo(f"Setting {chain_name} isolation") @@ -432,23 +471,28 @@ if __name__ == '__main__': try: valkey_slaveof_ip = os.getenv('VALKEY_SLAVEOF_IP', '') valkey_slaveof_port = os.getenv('VALKEY_SLAVEOF_PORT', '') + logdebug( + "Connecting valkey (SLAVEOF_IP:%s, PORT:%s)" % (valkey_slaveof_ip, valkey_slaveof_port)) if "".__eq__(valkey_slaveof_ip): - valkey = redis.StrictRedis(host=os.getenv('IPV4_NETWORK', '172.22.1') + '.249', decode_responses=True, port=6379, db=0, password=os.environ['VALKEYPASS']) + valkey = redis.StrictRedis( + host=os.getenv('IPV4_NETWORK', '172.22.1') + '.249', decode_responses=True, port=6379, db=0, password=os.environ['VALKEYPASS']) else: - valkey = redis.StrictRedis(host=valkey_slaveof_ip, decode_responses=True, port=valkey_slaveof_port, db=0, password=os.environ['VALKEYPASS']) + valkey = redis.StrictRedis( + host=valkey_slaveof_ip, decode_responses=True, port=valkey_slaveof_port, db=0, password=os.environ['VALKEYPASS']) valkey.ping() pubsub = valkey.pubsub() except Exception as ex: - print('%s - trying again in 3 seconds' % (ex)) + logdebug( + 'Redis connection failed: %s - trying again in 3 seconds' % (ex)) time.sleep(3) else: break - logger.set_valkey(r) + logger.set_valkey(valkey) + logdebug("Valkey connection established, setting up F2B keys") - # rename fail2ban to netfilter if valkey.exists('F2B_LOG'): + logdebug("Renaming F2B_LOG to NETFILTER_LOG") valkey.rename('F2B_LOG', 'NETFILTER_LOG') - # clear bans in valkey valkey.delete('F2B_ACTIVE_BANS') valkey.delete('F2B_PERM_BANS') @@ -463,7 +507,7 @@ if __name__ == '__main__': snat_ip = os.getenv('SNAT_TO_SOURCE') snat_ipo = ipaddress.ip_address(snat_ip) if type(snat_ipo) is ipaddress.IPv4Address: - snat4_thread = Thread(target=snat4,args=(snat_ip,)) + snat4_thread = Thread(target=snat4, args=(snat_ip,)) snat4_thread.daemon = True snat4_thread.start() except ValueError: @@ -499,4 +543,5 @@ if __name__ == '__main__': while not quit_now: time.sleep(0.5) - sys.exit(exit_code) + logdebug("Exiting with code %s" % exit_code) + sys.exit(exit_code) \ No newline at end of file diff --git a/data/Dockerfiles/netfilter/modules/Logger.py b/data/Dockerfiles/netfilter/modules/Logger.py index 7f12cd7f6..2eec6a44b 100644 --- a/data/Dockerfiles/netfilter/modules/Logger.py +++ b/data/Dockerfiles/netfilter/modules/Logger.py @@ -1,5 +1,6 @@ import time import json +import datetime class Logger: def __init__(self): @@ -8,17 +9,28 @@ class Logger: def set_valkey(self, valkey): self.valkey = valkey + def _format_timestamp(self): + # Local time with milliseconds + return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + def log(self, priority, message): - tolog = {} - tolog['time'] = int(round(time.time())) - tolog['priority'] = priority - tolog['message'] = message - print(message) + # build valkey-friendly dict + tolog = { + 'time': int(round(time.time())), # keep raw timestamp for Valkey + 'priority': priority, + 'message': message + } + + # print human-readable message with timestamp + ts = self._format_timestamp() + print(f"{ts} {priority.upper()}: {message}", flush=True) + + # also push JSON to Redis if connected if self.valkey is not None: try: self.valkey.lpush('NETFILTER_LOG', json.dumps(tolog, ensure_ascii=False)) except Exception as ex: - print('Failed logging to valkey: %s' % (ex)) + print(f'{ts} WARN: Failed logging to valkey: {ex}', flush=True) def logWarn(self, message): self.log('warn', message) @@ -27,4 +39,4 @@ class Logger: self.log('crit', message) def logInfo(self, message): - self.log('info', message) + self.log('info', message) \ No newline at end of file diff --git a/data/Dockerfiles/nginx/bootstrap.py b/data/Dockerfiles/nginx/bootstrap.py index 11e6fc202..97ce7a4e1 100644 --- a/data/Dockerfiles/nginx/bootstrap.py +++ b/data/Dockerfiles/nginx/bootstrap.py @@ -10,7 +10,7 @@ def includes_conf(env, template_vars): server_name_config = f"server_name {template_vars['MAILCOW_HOSTNAME']} autodiscover.* autoconfig.* {' '.join(template_vars['ADDITIONAL_SERVER_NAMES'])};" listen_plain_config = f"listen {template_vars['HTTP_PORT']};" listen_ssl_config = f"listen {template_vars['HTTPS_PORT']};" - if not template_vars['DISABLE_IPv6']: + if template_vars['ENABLE_IPV6']: listen_plain_config += f"\nlisten [::]:{template_vars['HTTP_PORT']};" listen_ssl_config += f"\nlisten [::]:{template_vars['HTTPS_PORT']} ssl;" listen_ssl_config += "\nhttp2 on;" @@ -58,7 +58,7 @@ def prepare_template_vars(): 'SOGOHOST': os.getenv("SOGOHOST", ipv4_network + ".248"), 'RSPAMDHOST': os.getenv("RSPAMDHOST", "rspamd-mailcow"), 'PHPFPMHOST': os.getenv("PHPFPMHOST", "php-fpm-mailcow"), - 'DISABLE_IPv6': os.getenv("DISABLE_IPv6", "n").lower() in ("y", "yes"), + 'ENABLE_IPV6': os.getenv("ENABLE_IPV6", "true").lower() != "false", 'HTTP_REDIRECT': os.getenv("HTTP_REDIRECT", "n").lower() in ("y", "yes"), } diff --git a/data/Dockerfiles/olefy/Dockerfile b/data/Dockerfiles/olefy/Dockerfile index 3b2729134..845b125f6 100644 --- a/data/Dockerfiles/olefy/Dockerfile +++ b/data/Dockerfiles/olefy/Dockerfile @@ -1,4 +1,4 @@ -FROM alpine:3.20 +FROM alpine:3.21 LABEL maintainer = "The Infrastructure Company GmbH " diff --git a/data/Dockerfiles/olefy/olefy.py b/data/Dockerfiles/olefy/olefy.py index 776e78648..7c6880929 100644 --- a/data/Dockerfiles/olefy/olefy.py +++ b/data/Dockerfiles/olefy/olefy.py @@ -32,6 +32,13 @@ import time import magic import re +skip_olefy = os.getenv('SKIP_OLEFY', '') + +if skip_olefy.lower() in ['yes', 'y']: + print("SKIP_OLEFY=y, skipping Olefy...") + time.sleep(365 * 24 * 60 * 60) + sys.exit(0) + # merge variables from /etc/olefy.conf and the defaults olefy_listen_addr_string = os.getenv('OLEFY_BINDADDRESS', '127.0.0.1,::1') olefy_listen_port = int(os.getenv('OLEFY_BINDPORT', '10050')) @@ -113,7 +120,7 @@ def oletools( stream, tmp_file_name, lid ): out = bytes(out.decode('utf-8', 'ignore').replace(' ', ' ').replace('\t', '').replace('\n', '').replace('XLMMacroDeobfuscator: pywin32 is not installed (only is required if you want to use MS Excel)', ''), encoding="utf-8") failed = False if out.__len__() < 30: - logger.error('{} olevba returned <30 chars - rc: {!r}, response: {!r}, error: {!r}'.format(lid,cmd_tmp.returncode, + logger.error('{} olevba returned <30 chars - rc: {!r}, response: {!r}, error: {!r}'.format(lid,cmd_tmp.returncode, out.decode('utf-8', 'ignore'), err.decode('utf-8', 'ignore'))) out = b'[ { "error": "Unhandled error - too short olevba response" } ]' failed = True diff --git a/data/Dockerfiles/phpfpm/Dockerfile b/data/Dockerfiles/phpfpm/Dockerfile index 038c586a8..e7b43790b 100644 --- a/data/Dockerfiles/phpfpm/Dockerfile +++ b/data/Dockerfiles/phpfpm/Dockerfile @@ -1,19 +1,19 @@ -FROM php:8.2-fpm-alpine3.20 +FROM php:8.2-fpm-alpine3.21 LABEL maintainer = "The Infrastructure Company GmbH " # renovate: datasource=github-tags depName=krakjoe/apcu versioning=semver-coerced extractVersion=^v(?.*)$ -ARG APCU_PECL_VERSION=5.1.24 +ARG APCU_PECL_VERSION=5.1.26 # renovate: datasource=github-tags depName=Imagick/imagick versioning=semver-coerced extractVersion=(?.*)$ -ARG IMAGICK_PECL_VERSION=3.7.0 +ARG IMAGICK_PECL_VERSION=3.8.0 # renovate: datasource=github-tags depName=php/pecl-mail-mailparse versioning=semver-coerced extractVersion=^v(?.*)$ ARG MAILPARSE_PECL_VERSION=3.1.8 # renovate: datasource=github-tags depName=php-memcached-dev/php-memcached versioning=semver-coerced extractVersion=^v(?.*)$ -ARG MEMCACHED_PECL_VERSION=3.2.0 +ARG MEMCACHED_PECL_VERSION=3.3.0 # renovate: datasource=github-tags depName=phpredis/phpredis versioning=semver-coerced extractVersion=(?.*)$ -ARG REDIS_PECL_VERSION=6.1.0 +ARG REDIS_PECL_VERSION=6.2.0 # renovate: datasource=github-tags depName=composer/composer versioning=semver-coerced extractVersion=(?.*)$ -ARG COMPOSER_VERSION=2.6.6 +ARG COMPOSER_VERSION=2.8.6 RUN apk add -U --no-cache autoconf \ aspell-dev \ diff --git a/data/Dockerfiles/phpfpm/docker-entrypoint.sh b/data/Dockerfiles/phpfpm/docker-entrypoint.sh index 47c5dfc12..2598a92f3 100755 --- a/data/Dockerfiles/phpfpm/docker-entrypoint.sh +++ b/data/Dockerfiles/phpfpm/docker-entrypoint.sh @@ -81,7 +81,7 @@ if [ ${SQL_CHANGED} -eq 1 ]; then fi # Check mysql tz import (master and slave) -TZ_CHECK=$(mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT CONVERT_TZ('2019-11-02 23:33:00','Europe/Berlin','UTC') AS time;" -BN 2> /dev/null) +TZ_CHECK=$(mariadb --skip-ssl --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT CONVERT_TZ('2019-11-02 23:33:00','Europe/Berlin','UTC') AS time;" -BN 2> /dev/null) if [[ -z ${TZ_CHECK} ]] || [[ "${TZ_CHECK}" == "NULL" ]]; then SQL_FULL_TZINFO_IMPORT_RETURN=$(curl --silent --insecure -XPOST https://dockerapi.${COMPOSE_PROJECT_NAME}_mailcow-network/containers/${CONTAINER_ID}/exec -d '{"cmd":"system", "task":"mysql_tzinfo_to_sql"}' --silent -H 'Content-type: application/json') echo "MySQL mysql_tzinfo_to_sql - debug output:" @@ -120,11 +120,11 @@ if [[ "${MASTER}" =~ ^([yY][eE][sS]|[yY])+$ ]]; then while read line do DOMAIN_ARR+=("$line") - done < <(mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT domain FROM domain" -Bs) + done < <(mariadb --skip-ssl --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT domain FROM domain" -Bs) while read line do DOMAIN_ARR+=("$line") - done < <(mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT alias_domain FROM alias_domain" -Bs) + done < <(mariadb --skip-ssl --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT alias_domain FROM alias_domain" -Bs) if [[ ! -z ${DOMAIN_ARR} ]]; then for domain in "${DOMAIN_ARR[@]}"; do @@ -146,13 +146,13 @@ if [[ "${MASTER}" =~ ^([yY][eE][sS]|[yY])+$ ]]; then VALIDATED_IPS=$(array_by_comma ${VALIDATED_API_ALLOW_FROM_ARR[*]}) if [[ ! -z ${VALIDATED_IPS} ]]; then if [[ ${API_KEY} != "invalid" ]] && [[ ! -z ${API_KEY} ]]; then - mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} << EOF + mariadb --skip-ssl --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} << EOF DELETE FROM api WHERE access = 'rw'; INSERT INTO api (api_key, active, allow_from, access) VALUES ("${API_KEY}", "1", "${VALIDATED_IPS}", "rw"); EOF fi if [[ ${API_KEY_READ_ONLY} != "invalid" ]] && [[ ! -z ${API_KEY_READ_ONLY} ]]; then - mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} << EOF + mariadb --skip-ssl --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} << EOF DELETE FROM api WHERE access = 'ro'; INSERT INTO api (api_key, active, allow_from, access) VALUES ("${API_KEY_READ_ONLY}", "1", "${VALIDATED_IPS}", "ro"); EOF @@ -161,7 +161,7 @@ EOF fi # Create events (master only, STATUS for event on slave will be SLAVESIDE_DISABLED) - mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} << EOF + mariadb --skip-ssl --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} << EOF DROP EVENT IF EXISTS clean_spamalias; DELIMITER // CREATE EVENT clean_spamalias diff --git a/data/Dockerfiles/postfix-tlspol/Dockerfile b/data/Dockerfiles/postfix-tlspol/Dockerfile new file mode 100644 index 000000000..8ae51b05e --- /dev/null +++ b/data/Dockerfiles/postfix-tlspol/Dockerfile @@ -0,0 +1,50 @@ +FROM golang:1.25-bookworm AS builder +WORKDIR /src + +ENV CGO_ENABLED=0 \ + GO111MODULE=on \ + NOOPT=1 \ + VERSION=1.8.14 + +RUN git clone --branch v${VERSION} https://github.com/Zuplu/postfix-tlspol && \ + cd /src/postfix-tlspol && \ + scripts/build.sh build-only + + +FROM debian:bookworm-slim +LABEL maintainer="The Infrastructure Company GmbH " + +ARG DEBIAN_FRONTEND=noninteractive +ENV LC_ALL=C + +RUN apt-get update && apt-get install -y --no-install-recommends \ + ca-certificates \ + dirmngr \ + dnsutils \ + iputils-ping \ + sudo \ + supervisor \ + redis-tools \ + syslog-ng \ + syslog-ng-core \ + syslog-ng-mod-redis \ + tzdata \ + && rm -rf /var/lib/apt/lists/* \ + && touch /etc/default/locale + +COPY supervisord.conf /etc/supervisor/supervisord.conf +COPY syslog-ng.conf /etc/syslog-ng/syslog-ng.conf +COPY syslog-ng-valkey_slave.conf /etc/syslog-ng/syslog-ng-valkey_slave.conf +COPY postfix-tlspol.sh /opt/postfix-tlspol.sh +COPY stop-supervisor.sh /usr/local/sbin/stop-supervisor.sh +COPY docker-entrypoint.sh /docker-entrypoint.sh +COPY --from=builder /src/postfix-tlspol/build/postfix-tlspol /usr/local/bin/postfix-tlspol + +RUN chmod +x /opt/postfix-tlspol.sh \ + /usr/local/sbin/stop-supervisor.sh \ + /docker-entrypoint.sh +RUN rm -rf /tmp/* /var/tmp/* + +ENTRYPOINT ["/docker-entrypoint.sh"] + +CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/supervisord.conf"] \ No newline at end of file diff --git a/data/Dockerfiles/postfix-tlspol/docker-entrypoint.sh b/data/Dockerfiles/postfix-tlspol/docker-entrypoint.sh new file mode 100755 index 000000000..856a119ba --- /dev/null +++ b/data/Dockerfiles/postfix-tlspol/docker-entrypoint.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +if [[ ! -z ${VALKEY_SLAVEOF_IP} ]]; then + cp /etc/syslog-ng/syslog-ng-valkey_slave.conf /etc/syslog-ng/syslog-ng.conf +fi + +exec "$@" \ No newline at end of file diff --git a/data/Dockerfiles/postfix-tlspol/postfix-tlspol.sh b/data/Dockerfiles/postfix-tlspol/postfix-tlspol.sh new file mode 100755 index 000000000..0ab7c5a27 --- /dev/null +++ b/data/Dockerfiles/postfix-tlspol/postfix-tlspol.sh @@ -0,0 +1,52 @@ +#!/bin/bash + +LOGLVL=info + +if [ ${DEV_MODE} != "n" ]; then + echo -e "\e[31mEnabling debug mode\e[0m" + set -x + LOGLVL=debug +fi + +[[ ! -d /etc/postfix-tlspol ]] && mkdir -p /etc/postfix-tlspol +[[ ! -d /var/lib/postfix-tlspol ]] && mkdir -p /var/lib/postfix-tlspol + +until dig +short mailcow.email > /dev/null; do + echo "Waiting for DNS..." + sleep 1 +done + +# Do not attempt to write to slave +if [[ ! -z ${VALKEY_SLAVEOF_IP} ]]; then + export VALKEY_CMDLINE="redis-cli -h ${VALKEY_SLAVEOF_IP} -p ${VALKEY_SLAVEOF_PORT} -a ${VALKEYPASS} --no-auth-warning" +else + export VALKEY_CMDLINE="redis-cli -h valkey -p 6379 -a ${VALKEYPASS} --no-auth-warning" +fi + +until [[ $(${VALKEY_CMDLINE} PING) == "PONG" ]]; do + echo "Waiting for Valkey..." + sleep 2 +done + +echo "Waiting for Postfix..." +until ping postfix -c1 > /dev/null; do + sleep 1 +done +echo "Postfix OK" + +cat < /etc/postfix-tlspol/config.yaml +server: + address: 0.0.0.0:8642 + + log-level: ${LOGLVL} + + prefetch: true + + cache-file: /var/lib/postfix-tlspol/cache.db + +dns: + # must support DNSSEC + address: 127.0.0.11:53 +EOF + +/usr/local/bin/postfix-tlspol -config /etc/postfix-tlspol/config.yaml \ No newline at end of file diff --git a/data/Dockerfiles/postfix-tlspol/stop-supervisor.sh b/data/Dockerfiles/postfix-tlspol/stop-supervisor.sh new file mode 100755 index 000000000..5394490ce --- /dev/null +++ b/data/Dockerfiles/postfix-tlspol/stop-supervisor.sh @@ -0,0 +1,8 @@ +#!/bin/bash + +printf "READY\n"; + +while read line; do + echo "Processing Event: $line" >&2; + kill -3 $(cat "/var/run/supervisord.pid") +done < /dev/stdin diff --git a/data/Dockerfiles/postfix-tlspol/supervisord.conf b/data/Dockerfiles/postfix-tlspol/supervisord.conf new file mode 100644 index 000000000..90cf785ad --- /dev/null +++ b/data/Dockerfiles/postfix-tlspol/supervisord.conf @@ -0,0 +1,25 @@ +[supervisord] +pidfile=/var/run/supervisord.pid +nodaemon=true +user=root + +[program:syslog-ng] +command=/usr/sbin/syslog-ng --foreground --no-caps +stdout_logfile=/dev/stdout +stdout_logfile_maxbytes=0 +stderr_logfile=/dev/stderr +stderr_logfile_maxbytes=0 +autostart=true + +[program:postfix-tlspol] +startsecs=10 +autorestart=true +command=/opt/postfix-tlspol.sh +stdout_logfile=/dev/stdout +stdout_logfile_maxbytes=0 +stderr_logfile=/dev/stderr +stderr_logfile_maxbytes=0 + +[eventlistener:processes] +command=/usr/local/sbin/stop-supervisor.sh +events=PROCESS_STATE_STOPPED, PROCESS_STATE_EXITED, PROCESS_STATE_FATAL \ No newline at end of file diff --git a/data/Dockerfiles/postfix-tlspol/syslog-ng-valkey_slave.conf b/data/Dockerfiles/postfix-tlspol/syslog-ng-valkey_slave.conf new file mode 100644 index 000000000..e04dbe100 --- /dev/null +++ b/data/Dockerfiles/postfix-tlspol/syslog-ng-valkey_slave.conf @@ -0,0 +1,45 @@ +@version: 3.38 +@include "scl.conf" +options { + chain_hostnames(off); + flush_lines(0); + use_dns(no); + dns_cache(no); + use_fqdn(no); + owner("root"); group("adm"); perm(0640); + stats_freq(0); + bad_hostname("^gconfd$"); +}; +source s_src { + unix-stream("/dev/log"); + internal(); +}; +destination d_stdout { pipe("/dev/stdout"); }; +destination d_valkey_ui_log { + redis( + host("`VALKEY_SLAVEOF_IP`") + persist-name("valkey1") + port(`VALKEY_SLAVEOF_PORT`) + auth("`VALKEYPASS`") + command("LPUSH" "POSTFIX_MAILLOG" "$(format-json time=\"$S_UNIXTIME\" priority=\"$PRIORITY\" program=\"$PROGRAM\" message=\"$MESSAGE\")\n") + ); +}; +filter f_mail { facility(mail); }; +# start +# overriding warnings are still displayed when the entrypoint runs its initial check +# warnings logged by postfix-mailcow to syslog are hidden to reduce repeating msgs +# Some other warnings are ignored +filter f_ignore { + not match("overriding earlier entry" value("MESSAGE")); + not match("TLS SNI from checks.mailcow.email" value("MESSAGE")); + not match("no SASL support" value("MESSAGE")); + not facility (local0, local1, local2, local3, local4, local5, local6, local7); +}; +# end +log { + source(s_src); + filter(f_ignore); + destination(d_stdout); + filter(f_mail); + destination(d_valkey_ui_log); +}; diff --git a/data/Dockerfiles/postfix-tlspol/syslog-ng.conf b/data/Dockerfiles/postfix-tlspol/syslog-ng.conf new file mode 100644 index 000000000..8e9d33a6f --- /dev/null +++ b/data/Dockerfiles/postfix-tlspol/syslog-ng.conf @@ -0,0 +1,45 @@ +@version: 3.38 +@include "scl.conf" +options { + chain_hostnames(off); + flush_lines(0); + use_dns(no); + dns_cache(no); + use_fqdn(no); + owner("root"); group("adm"); perm(0640); + stats_freq(0); + bad_hostname("^gconfd$"); +}; +source s_src { + unix-stream("/dev/log"); + internal(); +}; +destination d_stdout { pipe("/dev/stdout"); }; +destination d_valkey_ui_log { + redis( + host("valkey-mailcow") + persist-name("valkey1") + port(6379) + auth("`VALKEYPASS`") + command("LPUSH" "POSTFIX_MAILLOG" "$(format-json time=\"$S_UNIXTIME\" priority=\"$PRIORITY\" program=\"$PROGRAM\" message=\"$MESSAGE\")\n") + ); +}; +filter f_mail { facility(mail); }; +# start +# overriding warnings are still displayed when the entrypoint runs its initial check +# warnings logged by postfix-mailcow to syslog are hidden to reduce repeating msgs +# Some other warnings are ignored +filter f_ignore { + not match("overriding earlier entry" value("MESSAGE")); + not match("TLS SNI from checks.mailcow.email" value("MESSAGE")); + not match("no SASL support" value("MESSAGE")); + not facility (local0, local1, local2, local3, local4, local5, local6, local7); +}; +# end +log { + source(s_src); + filter(f_ignore); + destination(d_stdout); + filter(f_mail); + destination(d_valkey_ui_log); +}; diff --git a/data/Dockerfiles/postfix/Dockerfile b/data/Dockerfiles/postfix/Dockerfile index b8b010394..5d9046b43 100644 --- a/data/Dockerfiles/postfix/Dockerfile +++ b/data/Dockerfiles/postfix/Dockerfile @@ -1,9 +1,9 @@ FROM debian:bookworm-slim -LABEL maintainer = "The Infrastructure Company GmbH " +LABEL maintainer="The Infrastructure Company GmbH " ARG DEBIAN_FRONTEND=noninteractive -ENV LC_ALL C +ENV LC_ALL=C RUN dpkg-divert --local --rename --add /sbin/initctl \ && ln -sf /bin/true /sbin/initctl \ diff --git a/data/Dockerfiles/postfix/postfix.sh b/data/Dockerfiles/postfix/postfix.sh index e5dbf88fc..0a6494ed6 100755 --- a/data/Dockerfiles/postfix/postfix.sh +++ b/data/Dockerfiles/postfix/postfix.sh @@ -524,4 +524,4 @@ if [[ $? != 0 ]]; then else postfix -c /opt/postfix/conf start sleep 126144000 -fi +fi \ No newline at end of file diff --git a/data/Dockerfiles/rspamd/Dockerfile b/data/Dockerfiles/rspamd/Dockerfile index 248312094..e46981aa4 100644 --- a/data/Dockerfiles/rspamd/Dockerfile +++ b/data/Dockerfiles/rspamd/Dockerfile @@ -2,11 +2,11 @@ FROM debian:bookworm-slim LABEL maintainer="The Infrastructure Company GmbH " ARG DEBIAN_FRONTEND=noninteractive -ARG RSPAMD_VER=rspamd_3.11.0-2~90a175b45 +ARG RSPAMD_VER=rspamd_3.12.1-1~6dbfca2fa ARG CODENAME=bookworm ENV LC_ALL=C -RUN apt-get update && apt-get install -y \ +RUN apt-get update && apt-get install -y --no-install-recommends \ tzdata \ ca-certificates \ gnupg2 \ diff --git a/data/Dockerfiles/rspamd/docker-entrypoint.sh b/data/Dockerfiles/rspamd/docker-entrypoint.sh index 9373799a0..efc24835a 100755 --- a/data/Dockerfiles/rspamd/docker-entrypoint.sh +++ b/data/Dockerfiles/rspamd/docker-entrypoint.sh @@ -81,6 +81,29 @@ EOF redis-cli -h valkey-mailcow -a ${VALKEYPASS} --no-auth-warning SLAVEOF NO ONE fi +if [[ "${SKIP_OLEFY}" =~ ^([yY][eE][sS]|[yY])+$ ]]; then + if [[ -f /etc/rspamd/local.d/external_services.conf ]]; then + rm /etc/rspamd/local.d/external_services.conf + fi +else + if [[ ! -f /etc/rspamd/local.d/external_services.conf ]]; then + cat < /etc/rspamd/local.d/external_services.conf +oletools { + # default olefy settings + servers = "olefy:10055"; + # needs to be set explicitly for Rspamd < 1.9.5 + scan_mime_parts = true; + # mime-part regex matching in content-type or filename + # block all macros + extended = true; + max_size = 3145728; + timeout = 20.0; + retransmits = 1; +} +EOF + fi +fi + # Provide additional lua modules ln -s /usr/lib/$(uname -m)-linux-gnu/liblua5.1-cjson.so.0.0.0 /usr/lib/rspamd/cjson.so diff --git a/data/Dockerfiles/sogo/Dockerfile b/data/Dockerfiles/sogo/Dockerfile index 07c26b434..611378e9d 100644 --- a/data/Dockerfiles/sogo/Dockerfile +++ b/data/Dockerfiles/sogo/Dockerfile @@ -47,6 +47,7 @@ COPY syslog-ng.conf /etc/syslog-ng/syslog-ng.conf COPY syslog-ng-valkey_slave.conf /etc/syslog-ng/syslog-ng-valkey_slave.conf COPY supervisord.conf /etc/supervisor/supervisord.conf COPY acl.diff /acl.diff +COPY navMailcowBtns.diff /navMailcowBtns.diff COPY stop-supervisor.sh /usr/local/sbin/stop-supervisor.sh COPY docker-entrypoint.sh / diff --git a/data/Dockerfiles/sogo/bootstrap-sogo.sh b/data/Dockerfiles/sogo/bootstrap-sogo.sh index 9cf36a805..af7d2a4db 100755 --- a/data/Dockerfiles/sogo/bootstrap-sogo.sh +++ b/data/Dockerfiles/sogo/bootstrap-sogo.sh @@ -14,118 +14,18 @@ do done # Wait for updated schema -DBV_NOW=$(mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT version FROM versions WHERE application = 'db_schema';" -BN) +DBV_NOW=$(mariadb --skip-ssl --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT version FROM versions WHERE application = 'db_schema';" -BN) DBV_NEW=$(grep -oE '\$db_version = .*;' init_db.inc.php | sed 's/$db_version = //g;s/;//g' | cut -d \" -f2) while [[ "${DBV_NOW}" != "${DBV_NEW}" ]]; do echo "Waiting for schema update..." - DBV_NOW=$(mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT version FROM versions WHERE application = 'db_schema';" -BN) + DBV_NOW=$(mariadb --skip-ssl --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT version FROM versions WHERE application = 'db_schema';" -BN) DBV_NEW=$(grep -oE '\$db_version = .*;' init_db.inc.php | sed 's/$db_version = //g;s/;//g' | cut -d \" -f2) sleep 5 done echo "DB schema is ${DBV_NOW}" -# Recreate view if [[ "${MASTER}" =~ ^([yY][eE][sS]|[yY])+$ ]]; then - echo "We are master, preparing sogo_view..." - mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "DROP VIEW IF EXISTS sogo_view" - while [[ ${VIEW_OK} != 'OK' ]]; do - mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} << EOF -CREATE VIEW sogo_view (c_uid, domain, c_name, c_password, c_cn, mail, aliases, ad_aliases, ext_acl, kind, multiple_bookings) AS -SELECT - mailbox.username, - mailbox.domain, - mailbox.username, - IF(JSON_UNQUOTE(JSON_VALUE(attributes, '$.force_pw_update')) = '0', IF(JSON_UNQUOTE(JSON_VALUE(attributes, '$.sogo_access')) = 1, password, '{SSHA256}A123A123A321A321A321B321B321B123B123B321B432F123E321123123321321'), '{SSHA256}A123A123A321A321A321B321B321B123B123B321B432F123E321123123321321'), - mailbox.name, - mailbox.username, - IFNULL(GROUP_CONCAT(ga.aliases ORDER BY ga.aliases SEPARATOR ' '), ''), - IFNULL(gda.ad_alias, ''), - IFNULL(external_acl.send_as_acl, ''), - mailbox.kind, - mailbox.multiple_bookings -FROM - mailbox - LEFT OUTER JOIN - grouped_mail_aliases ga - ON ga.username REGEXP CONCAT('(^|,)', mailbox.username, '($|,)') - LEFT OUTER JOIN - grouped_domain_alias_address gda - ON gda.username = mailbox.username - LEFT OUTER JOIN - grouped_sender_acl_external external_acl - ON external_acl.username = mailbox.username -WHERE - mailbox.active = '1' -GROUP BY - mailbox.username; -EOF - if [[ ! -z $(mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -B -e "SELECT 'OK' FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'sogo_view'") ]]; then - VIEW_OK=OK - else - echo "Will retry to setup SOGo view in 3s..." - sleep 3 - fi - done -else - while [[ ${VIEW_OK} != 'OK' ]]; do - if [[ ! -z $(mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -B -e "SELECT 'OK' FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'sogo_view'") ]]; then - VIEW_OK=OK - else - echo "Waiting for SOGo view to be created by master..." - sleep 3 - fi - done -fi - -# Wait for static view table if missing after update and update content -if [[ "${MASTER}" =~ ^([yY][eE][sS]|[yY])+$ ]]; then - echo "We are master, preparing _sogo_static_view..." - while [[ ${STATIC_VIEW_OK} != 'OK' ]]; do - if [[ ! -z $(mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -B -e "SELECT 'OK' FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '_sogo_static_view'") ]]; then - STATIC_VIEW_OK=OK - echo "Updating _sogo_static_view content..." - # If changed, also update init_db.inc.php - mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -B -e "REPLACE INTO _sogo_static_view (c_uid, domain, c_name, c_password, c_cn, mail, aliases, ad_aliases, ext_acl, kind, multiple_bookings) SELECT c_uid, domain, c_name, c_password, c_cn, mail, aliases, ad_aliases, ext_acl, kind, multiple_bookings from sogo_view;" - mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -B -e "DELETE FROM _sogo_static_view WHERE c_uid NOT IN (SELECT username FROM mailbox WHERE active = '1')" - else - echo "Waiting for database initialization..." - sleep 3 - fi - done -else - while [[ ${STATIC_VIEW_OK} != 'OK' ]]; do - if [[ ! -z $(mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -B -e "SELECT 'OK' FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '_sogo_static_view'") ]]; then - STATIC_VIEW_OK=OK - else - echo "Waiting for database initialization by master..." - sleep 3 - fi - done -fi - - -# Recreate password update trigger -if [[ "${MASTER}" =~ ^([yY][eE][sS]|[yY])+$ ]]; then - echo "We are master, preparing update trigger..." - mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "DROP TRIGGER IF EXISTS sogo_update_password" - while [[ ${TRIGGER_OK} != 'OK' ]]; do - mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} << EOF -DELIMITER - -CREATE TRIGGER sogo_update_password AFTER UPDATE ON _sogo_static_view -FOR EACH ROW -BEGIN -UPDATE mailbox SET password = NEW.c_password WHERE NEW.c_uid = username; -END; -- -DELIMITER ; -EOF - if [[ ! -z $(mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -B -e "SELECT 'OK' FROM INFORMATION_SCHEMA.TRIGGERS WHERE TRIGGER_NAME = 'sogo_update_password'") ]]; then - TRIGGER_OK=OK - else - echo "Will retry to setup SOGo password update trigger in 3s" - sleep 3 - fi - done + mariadb --skip-ssl --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "DROP TRIGGER IF EXISTS sogo_update_password" fi # cat /dev/urandom seems to hang here occasionally and is not recommended anyway, better use openssl @@ -150,6 +50,10 @@ cat < /var/lib/sogo/GNUstep/Defaults/sogod.plist YES SOGoEncryptionKey ${RAND_PASS} + SOGoURLEncryptionEnabled + YES + SOGoURLEncryptionPassphrase + ${SOGO_URL_ENCRYPTION_KEY} OCSAdminURL mysql://${DBUSER}:${DBPASS}@%2Fvar%2Frun%2Fmysqld%2Fmysqld.sock/${DBNAME}/sogo_admin OCSCacheFolderURL @@ -213,10 +117,10 @@ while read -r line gal " >> /var/lib/sogo/GNUstep/Defaults/sogod.plist # Generate alternative LDAP authentication dict, when SQL authentication fails # This will nevertheless read attributes from LDAP - line=${line} envsubst < /etc/sogo/plist_ldap >> /var/lib/sogo/GNUstep/Defaults/sogod.plist + /etc/sogo/plist_ldap.sh ${line} ${gal} >> /var/lib/sogo/GNUstep/Defaults/sogod.plist echo " " >> /var/lib/sogo/GNUstep/Defaults/sogod.plist -done < <(mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT domain, CASE gal WHEN '1' THEN 'YES' ELSE 'NO' END AS gal FROM domain;" -B -N) +done < <(mariadb --skip-ssl --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT domain, CASE gal WHEN '1' THEN 'YES' ELSE 'NO' END AS gal FROM domain;" -B -N) # Generate footer echo ' @@ -240,6 +144,10 @@ chmod 600 /var/lib/sogo/GNUstep/Defaults/sogod.plist # fi #fi +if patch -R -sfN --dry-run /usr/lib/GNUstep/SOGo/Templates/UIxTopnavToolbar.wox < /navMailcowBtns.diff > /dev/null; then + patch -R /usr/lib/GNUstep/SOGo/Templates/UIxTopnavToolbar.wox < /navMailcowBtns.diff; +fi + # Rename custom logo, if any [[ -f /etc/sogo/sogo-full.svg ]] && mv /etc/sogo/sogo-full.svg /etc/sogo/custom-fulllogo.svg diff --git a/data/Dockerfiles/sogo/navMailcowBtns.diff b/data/Dockerfiles/sogo/navMailcowBtns.diff new file mode 100644 index 000000000..2107b5b1f --- /dev/null +++ b/data/Dockerfiles/sogo/navMailcowBtns.diff @@ -0,0 +1,15 @@ +60,65d58 +< var:ng-click="navButtonClick" +< ng-href="/user"> +< build +< mailcow +< +< ng-show="::activeUser.path.logoff.length" +85c78 +< ng-href="#"> +--- +> ng-href="{{::activeUser.path.logoff}}"> diff --git a/data/Dockerfiles/unbound/Dockerfile b/data/Dockerfiles/unbound/Dockerfile index 7e4f18dec..4903750ed 100644 --- a/data/Dockerfiles/unbound/Dockerfile +++ b/data/Dockerfiles/unbound/Dockerfile @@ -1,4 +1,4 @@ -FROM alpine:3.20 +FROM alpine:3.21 LABEL maintainer = "The Infrastructure Company GmbH " diff --git a/data/Dockerfiles/watchdog/Dockerfile b/data/Dockerfiles/watchdog/Dockerfile index f8aa262bb..6d8541d79 100644 --- a/data/Dockerfiles/watchdog/Dockerfile +++ b/data/Dockerfiles/watchdog/Dockerfile @@ -1,4 +1,4 @@ -FROM alpine:3.20 +FROM alpine:3.21 LABEL maintainer = "The Infrastructure Company GmbH " @@ -16,7 +16,6 @@ RUN apk add --update \ fcgi \ openssl \ nagios-plugins-mysql \ - nagios-plugins-dns \ nagios-plugins-disk \ bind-tools \ redis \ @@ -32,9 +31,11 @@ RUN apk add --update \ tzdata \ whois \ && curl https://raw.githubusercontent.com/mludvig/smtp-cli/v3.10/smtp-cli -o /smtp-cli \ - && chmod +x smtp-cli + && chmod +x smtp-cli \ + && mkdir /usr/lib/mailcow COPY watchdog.sh /watchdog.sh COPY check_mysql_slavestatus.sh /usr/lib/nagios/plugins/check_mysql_slavestatus.sh +COPY check_dns.sh /usr/lib/mailcow/check_dns.sh CMD ["/watchdog.sh"] diff --git a/data/Dockerfiles/watchdog/check_dns.sh b/data/Dockerfiles/watchdog/check_dns.sh new file mode 100755 index 000000000..ce4cfa3b1 --- /dev/null +++ b/data/Dockerfiles/watchdog/check_dns.sh @@ -0,0 +1,39 @@ +#!/bin/sh + +while getopts "H:s:" opt; do + case "$opt" in + H) HOST="$OPTARG" ;; + s) SERVER="$OPTARG" ;; + *) echo "Usage: $0 -H host -s server"; exit 3 ;; + esac +done + +if [ -z "$SERVER" ]; then + echo "No DNS Server provided" + exit 3 +fi + +if [ -z "$HOST" ]; then + echo "No host to test provided" + exit 3 +fi + +# run dig and measure the time it takes to run +START_TIME=$(date +%s%3N) +dig_output=$(dig +short +timeout=2 +tries=1 "$HOST" @"$SERVER" 2>/dev/null) +dig_rc=$? +dig_output_ips=$(echo "$dig_output" | grep -E '^[0-9.]+$' | sort | paste -sd ',' -) +END_TIME=$(date +%s%3N) +ELAPSED_TIME=$((END_TIME - START_TIME)) + +# validate and perform nagios like output and exit codes +if [ $dig_rc -ne 0 ] || [ -z "$dig_output" ]; then + echo "Domain $HOST was not found by the server" + exit 2 +elif [ $dig_rc -eq 0 ]; then + echo "DNS OK: $ELAPSED_TIME ms response time. $HOST returns $dig_output_ips" + exit 0 +else + echo "Unknown error" + exit 3 +fi diff --git a/data/Dockerfiles/watchdog/check_mysql_slavestatus.sh b/data/Dockerfiles/watchdog/check_mysql_slavestatus.sh index ed4f0db4d..42eec59bb 100755 --- a/data/Dockerfiles/watchdog/check_mysql_slavestatus.sh +++ b/data/Dockerfiles/watchdog/check_mysql_slavestatus.sh @@ -49,7 +49,7 @@ # 2013101601 Optical clean up # # 2013101602 Rewrite help output # # 2013101700 Handle Slave IO in 'Connecting' state # -# 2013101701 Minor changes in output, handling UNKWNON situations now # +# 2013101701 Minor changes in output, handling UNKNOWN situations now # # 2013101702 Exit CRITICAL when Slave IO in Connecting state # # 2013123000 Slave_SQL_Running also matched Slave_SQL_Running_State # # 2015011600 Added 'moving' check to catch possible connection issues # @@ -131,10 +131,10 @@ elif [[ -n "${socket}" && (-z "${user}" || -z "${password}") ]]; then fi # Connect to the DB server and store output in vars -if [[ -n $socket ]]; then - ConnectionResult=$(mysql ${optfile} ${socket} ${user} -e "show slave ${connection} status\G" 2>&1) +if [[ -n $socket ]]; then + ConnectionResult=$(mariadb --skip-ssl ${optfile} ${socket} ${user} -e "show slave ${connection} status\G" 2>&1) else - ConnectionResult=$(mysql ${optfile} ${host} ${port} ${user} -e "show slave ${connection} status\G" 2>&1) + ConnectionResult=$(mariadb --skip-ssl ${optfile} ${host} ${port} ${user} -e "show slave ${connection} status\G" 2>&1) fi if [ -z "`echo "${ConnectionResult}" |grep Slave_IO_State`" ]; then @@ -178,33 +178,33 @@ if [ ${check} = ${ok} ] && [ ${checkio} = ${ok} ]; then then echo "CRITICAL: Slave is ${delayinfo} seconds behind Master | delay=${delayinfo}s"; exit ${STATE_CRITICAL} elif [[ ${delayinfo} -ge ${warn_delay} ]] then echo "WARNING: Slave is ${delayinfo} seconds behind Master | delay=${delayinfo}s"; exit ${STATE_WARNING} - else + else # Everything looks OK here but now let us check if the replication is moving if [[ -n ${moving} ]] && [[ -n ${tmpfile} ]] && [[ $readpos -eq $execpos ]] - then - #echo "Debug: Read pos is $readpos - Exec pos is $execpos" + then + #echo "Debug: Read pos is $readpos - Exec pos is $execpos" # Check if tmp file exists curtime=`date +%s` - if [[ -w $tmpfile ]] - then + if [[ -w $tmpfile ]] + then tmpfiletime=`date +%s -r $tmpfile` if [[ `expr $curtime - $tmpfiletime` -gt ${moving} ]] then exectmp=`cat $tmpfile` #echo "Debug: Exec pos in tmpfile is $exectmp" if [[ $exectmp -eq $execpos ]] - then + then # The value read from the tmp file and from db are the same. Replication hasnt moved! echo "WARNING: Slave replication has not moved in ${moving} seconds. Manual check required."; exit ${STATE_WARNING} - else + else # Replication has moved since the tmp file was written. Delete tmp file and output OK. rm $tmpfile echo "OK: Slave SQL running: ${check} Slave IO running: ${checkio} / master: ${masterinfo} / slave is ${delayinfo} seconds behind master | delay=${delayinfo}s"; exit ${STATE_OK}; fi - else + else echo "OK: Slave SQL running: ${check} Slave IO running: ${checkio} / master: ${masterinfo} / slave is ${delayinfo} seconds behind master | delay=${delayinfo}s"; exit ${STATE_OK}; fi - else + else echo "$execpos" > $tmpfile echo "OK: Slave SQL running: ${check} Slave IO running: ${checkio} / master: ${masterinfo} / slave is ${delayinfo} seconds behind master | delay=${delayinfo}s"; exit ${STATE_OK}; fi diff --git a/data/Dockerfiles/watchdog/watchdog.sh b/data/Dockerfiles/watchdog/watchdog.sh index 0906cbb76..cd1f817b3 100755 --- a/data/Dockerfiles/watchdog/watchdog.sh +++ b/data/Dockerfiles/watchdog/watchdog.sh @@ -1,5 +1,10 @@ #!/bin/bash +if [ "${DEV_MODE}" != "n" ]; then + echo -e "\e[31mEnabled Debug Mode\e[0m" + set -x +fi + trap "exit" INT TERM trap "kill 0" EXIT @@ -234,7 +239,7 @@ external_checks() { diff_c=0 THRESHOLD=${EXTERNAL_CHECKS_THRESHOLD} # Reduce error count by 2 after restarting an unhealthy container - GUID=$(mysql -u${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT version FROM versions WHERE application = 'GUID'" -BN) + GUID=$(mariadb --skip-ssl -u${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT version FROM versions WHERE application = 'GUID'" -BN) trap "[ ${err_count} -gt 1 ] && err_count=$(( ${err_count} - 2 ))" USR1 while [ ${err_count} -lt ${THRESHOLD} ]; do err_c_cur=${err_count} @@ -297,7 +302,7 @@ unbound_checks() { touch /tmp/unbound-mailcow; echo "$(tail -50 /tmp/unbound-mailcow)" > /tmp/unbound-mailcow host_ip=$(get_container_ip unbound-mailcow) err_c_cur=${err_count} - /usr/lib/nagios/plugins/check_dns -s ${host_ip} -H stackoverflow.com 2>> /tmp/unbound-mailcow 1>&2; err_count=$(( ${err_count} + $? )) + /usr/lib/mailcow/check_dns.sh -s ${host_ip} -H stackoverflow.com 2>> /tmp/unbound-mailcow 1>&2; err_count=$(( ${err_count} + $? )) DNSSEC=$(dig com +dnssec | egrep 'flags:.+ad') if [[ -z ${DNSSEC} ]]; then echo "DNSSEC failure" 2>> /tmp/unbound-mailcow 1>&2 @@ -445,6 +450,31 @@ postfix_checks() { return 1 } +postfix-tlspol_checks() { + err_count=0 + diff_c=0 + THRESHOLD=${POSTFIX_TLSPOL_THRESHOLD} + # Reduce error count by 2 after restarting an unhealthy container + trap "[ ${err_count} -gt 1 ] && err_count=$(( ${err_count} - 2 ))" USR1 + while [ ${err_count} -lt ${THRESHOLD} ]; do + touch /tmp/postfix-tlspol-mailcow; echo "$(tail -50 /tmp/postfix-tlspol-mailcow)" > /tmp/postfix-tlspol-mailcow + host_ip=$(get_container_ip postfix-tlspol-mailcow) + err_c_cur=${err_count} + /usr/lib/nagios/plugins/check_tcp -4 -H ${host_ip} -p 8642 2>> /tmp/postfix-tlspol-mailcow 1>&2; err_count=$(( ${err_count} + $? )) + [ ${err_c_cur} -eq ${err_count} ] && [ ! $((${err_count} - 1)) -lt 0 ] && err_count=$((${err_count} - 1)) diff_c=1 + [ ${err_c_cur} -ne ${err_count} ] && diff_c=$(( ${err_c_cur} - ${err_count} )) + progress "Postfix TLS Policy companion" ${THRESHOLD} $(( ${THRESHOLD} - ${err_count} )) ${diff_c} + if [[ $? == 10 ]]; then + diff_c=0 + sleep 1 + else + diff_c=0 + sleep $(( ( RANDOM % 60 ) + 20 )) + fi + done + return 1 +} + clamd_checks() { err_count=0 diff_c=0 @@ -922,6 +952,18 @@ PID=$! echo "Spawned mailq_checks with PID ${PID}" BACKGROUND_TASKS+=(${PID}) +( +while true; do + if ! postfix-tlspol_checks; then + log_msg "Postfix TLS Policy hit error limit" + echo postfix-tlspol-mailcow > /tmp/com_pipe + fi +done +) & +PID=$! +echo "Spawned postfix-tlspol_checks with PID ${PID}" +BACKGROUND_TASKS+=(${PID}) + ( while true; do if ! dovecot_checks; then @@ -994,6 +1036,7 @@ PID=$! echo "Spawned cert_checks with PID ${PID}" BACKGROUND_TASKS+=(${PID}) +if [[ "${SKIP_OLEFY}" =~ ^([nN][oO]|[nN])+$ ]]; then ( while true; do if ! olefy_checks; then @@ -1005,6 +1048,7 @@ done PID=$! echo "Spawned olefy_checks with PID ${PID}" BACKGROUND_TASKS+=(${PID}) +fi ( while true; do diff --git a/data/conf/dovecot/auth/mailcowauth.php b/data/conf/dovecot/auth/mailcowauth.php new file mode 100644 index 000000000..cf5a0313f --- /dev/null +++ b/data/conf/dovecot/auth/mailcowauth.php @@ -0,0 +1,115 @@ + false); +if(!isset($post['username']) || !isset($post['password']) || !isset($post['real_rip'])){ + error_log("MAILCOWAUTH: Bad Request"); + http_response_code(400); // Bad Request + echo json_encode($return); + exit(); +} + +require_once('../../../web/inc/vars.inc.php'); +if (file_exists('../../../web/inc/vars.local.inc.php')) { + include_once('../../../web/inc/vars.local.inc.php'); +} +require_once '../../../web/inc/lib/vendor/autoload.php'; + + +// Init Valkey +$valkey = new Redis(); +try { + if (!empty(getenv('VALKEY_SLAVEOF_IP'))) { + $valkey->connect(getenv('VALKEY_SLAVEOF_IP'), getenv('VALKEY_SLAVEOF_PORT')); + } + else { + $valkey->connect('valkey-mailcow', 6379); + } + $valkey->auth(getenv("VALKEYPASS")); +} +catch (Exception $e) { + error_log("MAILCOWAUTH: " . $e . PHP_EOL); + http_response_code(500); // Internal Server Error + echo json_encode($return); + exit; +} + +// Init database +$dsn = $database_type . ":unix_socket=" . $database_sock . ";dbname=" . $database_name; +$opt = [ + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + PDO::ATTR_EMULATE_PREPARES => false, +]; +try { + $pdo = new PDO($dsn, $database_user, $database_pass, $opt); +} +catch (PDOException $e) { + error_log("MAILCOWAUTH: " . $e . PHP_EOL); + http_response_code(500); // Internal Server Error + echo json_encode($return); + exit; +} + +// Load core functions first +require_once 'functions.inc.php'; +require_once 'functions.auth.inc.php'; +require_once 'sessions.inc.php'; +require_once 'functions.mailbox.inc.php'; +require_once 'functions.ratelimit.inc.php'; +require_once 'functions.acl.inc.php'; + + +$isSOGoRequest = $post['real_rip'] == getenv('IPV4_NETWORK') . '.248'; +$result = false; +if ($isSOGoRequest) { + // This is a SOGo Auth request. First check for SSO password. + $sogo_sso_pass = file_get_contents("/etc/sogo-sso/sogo-sso.pass"); + if ($sogo_sso_pass === $post['password']){ + error_log('MAILCOWAUTH: SOGo SSO auth for user ' . $post['username']); + set_sasl_log($post['username'], $post['real_rip'], "SOGO"); + $result = true; + } +} +if ($result === false){ + // If it's a SOGo Request, don't check for protocol access + $service = ($isSOGoRequest) ? false : array($post['service'] => true); + $result = apppass_login($post['username'], $post['password'], $service, array( + 'is_internal' => true, + 'remote_addr' => $post['real_rip'] + )); + if ($result) { + error_log('MAILCOWAUTH: App auth for user ' . $post['username'] . " with service " . $post['service'] . " from IP " . $post['real_rip']); + set_sasl_log($post['username'], $post['real_rip'], $post['service']); + } +} +if ($result === false){ + // Init Identity Provider + $iam_provider = identity_provider('init'); + $iam_settings = identity_provider('get'); + $result = user_login($post['username'], $post['password'], array('is_internal' => true, 'service' => $post['service'])); + if ($result) { + error_log('MAILCOWAUTH: User auth for user ' . $post['username'] . " with service " . $post['service'] . " from IP " . $post['real_rip']); + set_sasl_log($post['username'], $post['real_rip'], $post['service']); + } +} + +if ($result) { + http_response_code(200); // OK + $return['success'] = true; +} else { + error_log("MAILCOWAUTH: Login failed for user " . $post['username'] . " with service " . $post['service'] . " from IP " . $post['real_rip']); + http_response_code(401); // Unauthorized +} + + +echo json_encode($return); +session_destroy(); +exit; diff --git a/data/conf/dovecot/auth/passwd-verify.lua b/data/conf/dovecot/auth/passwd-verify.lua new file mode 100644 index 000000000..ea847932d --- /dev/null +++ b/data/conf/dovecot/auth/passwd-verify.lua @@ -0,0 +1,57 @@ +function auth_password_verify(request, password) + if request.domain == nil then + return dovecot.auth.PASSDB_RESULT_USER_UNKNOWN, "No such user" + end + + local json = require "cjson" + local ltn12 = require "ltn12" + local https = require "ssl.https" + https.TIMEOUT = 30 + + local req = { + username = request.user, + password = password, + real_rip = request.real_rip, + service = request.service + } + local req_json = json.encode(req) + local res = {} + + local b, c = https.request { + method = "POST", + url = "https://nginx:9082", + source = ltn12.source.string(req_json), + headers = { + ["content-type"] = "application/json", + ["content-length"] = tostring(#req_json) + }, + sink = ltn12.sink.table(res), + insecure = true + } + + -- Returning PASSDB_RESULT_PASSWORD_MISMATCH will reset the user's auth cache entry. + -- Returning PASSDB_RESULT_INTERNAL_FAILURE keeps the existing cache entry, + -- even if the TTL has expired. Useful to avoid cache eviction during backend issues. + if c ~= 200 and c ~= 401 then + dovecot.i_info("HTTP request failed with " .. c .. " for user " .. request.user) + return dovecot.auth.PASSDB_RESULT_PASSWORD_MISMATCH, "Upstream error" + end + + local response_str = table.concat(res) + local is_response_valid, response_json = pcall(json.decode, response_str) + + if not is_response_valid then + dovecot.i_info("Invalid JSON received: " .. response_str) + return dovecot.auth.PASSDB_RESULT_PASSWORD_MISMATCH, "Invalid response format" + end + + if response_json.success == true then + return dovecot.auth.PASSDB_RESULT_OK, "" + end + + return dovecot.auth.PASSDB_RESULT_PASSWORD_MISMATCH, "Failed to authenticate" +end + +function auth_passdb_lookup(req) + return dovecot.auth.PASSDB_RESULT_USER_UNKNOWN, "" +end diff --git a/data/conf/dovecot/dovecot.conf b/data/conf/dovecot/dovecot.conf index 52c258fc1..05d9264fa 100644 --- a/data/conf/dovecot/dovecot.conf +++ b/data/conf/dovecot/dovecot.conf @@ -53,7 +53,7 @@ mail_shared_explicit_inbox = yes mail_prefetch_count = 30 passdb { driver = lua - args = file=/etc/dovecot/lua/passwd-verify.lua blocking=yes + args = file=/etc/dovecot/auth/passwd-verify.lua blocking=yes cache_key=%s:%u:%w result_success = return-ok result_failure = continue result_internalfail = continue @@ -69,7 +69,7 @@ passdb { # a return of the following passdb is mandatory passdb { driver = lua - args = file=/etc/dovecot/lua/passwd-verify.lua blocking=yes + args = file=/etc/dovecot/auth/passwd-verify.lua blocking=yes } # Set doveadm_password=your-secret-password in data/conf/dovecot/extra.conf (create if missing) service doveadm { @@ -125,6 +125,7 @@ service managesieve-login { } service imap-login { service_count = 1 + process_min_avail = 2 process_limit = 10000 vsz_limit = 1G user = dovenull @@ -140,6 +141,7 @@ service imap-login { } service pop3-login { service_count = 1 + process_min_avail = 1 vsz_limit = 1G inet_listener pop3_haproxy { port = 10110 @@ -239,7 +241,7 @@ plugin { mail_crypt_global_public_key = diff --git a/data/conf/nginx/templates/nginx.conf.j2 b/data/conf/nginx/templates/nginx.conf.j2 index 2bb601c50..4b32ff15b 100644 --- a/data/conf/nginx/templates/nginx.conf.j2 +++ b/data/conf/nginx/templates/nginx.conf.j2 @@ -48,13 +48,21 @@ http { listen {{ HTTP_PORT }} default_server; listen [::]:{{ HTTP_PORT }} default_server; - server_name {{ MAILCOW_HOSTNAME }} autodiscover.* autoconfig.* {{ ADDITIONAL_SERVER_NAMES | join(' ') }}; + server_name {{ MAILCOW_HOSTNAME }} autodiscover.* autoconfig.* mta-sts.* {{ ADDITIONAL_SERVER_NAMES | join(' ') }}; if ( $request_uri ~* "%0A|%0D" ) { return 403; } location ^~ /.well-known/acme-challenge/ { allow all; default_type "text/plain"; } + location ^~ /.well-known/mta-sts.txt { + allow all; + fastcgi_split_path_info ^(.+\.php)(/.+)$; + fastcgi_pass {{ PHPFPMHOST }}:9002; + include /etc/nginx/fastcgi_params; + fastcgi_param SCRIPT_FILENAME $document_root/mta-sts.php; + fastcgi_param PATH_INFO $fastcgi_path_info; + } location / { return 301 https://$host$uri$is_args$args; } @@ -70,7 +78,7 @@ http { {%endif%} listen {{ HTTPS_PORT }}{% if NGINX_USE_PROXY_PROTOCOL %} proxy_protocol{%endif%} ssl; - {% if not DISABLE_IPv6 %} + {% if ENABLE_IPV6 %} {% if not HTTP_REDIRECT %} listen [::]:{{ HTTP_PORT }}{% if NGINX_USE_PROXY_PROTOCOL %} proxy_protocol{%endif%}; {%endif%} @@ -82,7 +90,7 @@ http { ssl_certificate /etc/ssl/mail/cert.pem; ssl_certificate_key /etc/ssl/mail/key.pem; - server_name {{ MAILCOW_HOSTNAME }} autodiscover.* autoconfig.*; + server_name {{ MAILCOW_HOSTNAME }} autodiscover.* autoconfig.* mta-sts.*; include /etc/nginx/includes/sites-default.conf; } @@ -97,7 +105,7 @@ http { {%endif%} listen {{ HTTPS_PORT }}{% if NGINX_USE_PROXY_PROTOCOL %} proxy_protocol{%endif%} ssl; - {% if not DISABLE_IPv6 %} + {% if ENABLE_IPV6 %} {% if not HTTP_REDIRECT %} listen [::]:{{ HTTP_PORT }}{% if NGINX_USE_PROXY_PROTOCOL %} proxy_protocol{%endif%}; {%endif%} @@ -118,7 +126,7 @@ http { # rspamd dynmaps: server { listen 8081; - {% if not DISABLE_IPv6 %} + {% if ENABLE_IPV6 %} listen [::]:8081; {%endif%} index index.php index.html; @@ -159,6 +167,31 @@ http { } } + server { + listen 9082 ssl http2; + + ssl_certificate /etc/ssl/mail/cert.pem; + ssl_certificate_key /etc/ssl/mail/key.pem; + + index mailcowauth.php; + server_name _; + error_log /var/log/nginx/error.log; + access_log /var/log/nginx/access.log; + root /mailcowauth; + client_max_body_size 10M; + location ~ \.php$ { + client_max_body_size 10M; + try_files $uri =404; + fastcgi_split_path_info ^(.+\.php)(/.+)$; + fastcgi_pass phpfpm:9001; + include fastcgi_params; + fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; + fastcgi_param PATH_INFO $fastcgi_path_info; + } + } + + include /etc/nginx/conf.d/*.conf; + {% for cert in valid_cert_dirs %} server { {% if not HTTP_REDIRECT %} @@ -166,7 +199,7 @@ http { {%endif%} listen {{ HTTPS_PORT }}{% if NGINX_USE_PROXY_PROTOCOL %} proxy_protocol{%endif%} ssl; - {% if not DISABLE_IPv6 %} + {% if ENABLE_IPV6 %} {% if not HTTP_REDIRECT %} listen [::]:{{ HTTP_PORT }}{% if NGINX_USE_PROXY_PROTOCOL %} proxy_protocol{%endif%}; {%endif%} @@ -183,6 +216,4 @@ http { include /etc/nginx/includes/sites-default.conf; } {% endfor %} - - include /etc/nginx/conf.d/*.conf; } diff --git a/data/conf/nginx/templates/sites-default.conf.j2 b/data/conf/nginx/templates/sites-default.conf.j2 index 574bdb052..23fe7b788 100644 --- a/data/conf/nginx/templates/sites-default.conf.j2 +++ b/data/conf/nginx/templates/sites-default.conf.j2 @@ -76,6 +76,14 @@ location ^~ /.well-known/acme-challenge/ { allow all; default_type "text/plain"; } +location ^~ /.well-known/mta-sts.txt { + allow all; + fastcgi_split_path_info ^(.+\.php)(/.+)$; + fastcgi_pass {{ PHPFPMHOST }}:9002; + include /etc/nginx/fastcgi_params; + fastcgi_param SCRIPT_FILENAME $document_root/mta-sts.php; + fastcgi_param PATH_INFO $fastcgi_path_info; +} rewrite ^/.well-known/caldav$ /SOGo/dav/ permanent; rewrite ^/.well-known/carddav$ /SOGo/dav/ permanent; diff --git a/data/conf/phpfpm/crons/keycloak-sync.php b/data/conf/phpfpm/crons/keycloak-sync.php new file mode 100644 index 000000000..3517b5bff --- /dev/null +++ b/data/conf/phpfpm/crons/keycloak-sync.php @@ -0,0 +1,231 @@ + PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + PDO::ATTR_EMULATE_PREPARES => false, +]; +try { + $pdo = new PDO($dsn, $database_user, $database_pass, $opt); +} +catch (PDOException $e) { + logMsg("err", $e->getMessage()); + session_destroy(); + exit; +} + +// Init Valkey +$valkey = new Redis(); +try { + if (!empty(getenv('VALKEY_SLAVEOF_IP'))) { + $valkey->connect(getenv('VALKEY_SLAVEOF_IP'), getenv('VALKEY_SLAVEOF_PORT')); + } + else { + $valkey->connect('valkey-mailcow', 6379); + } + $valkey->auth(getenv("VALKEYPASS")); +} +catch (Exception $e) { + echo "Exiting: " . $e->getMessage(); + session_destroy(); + exit; +} + +function logMsg($priority, $message, $task = "Keycloak Sync") { + global $valkey; + + $finalMsg = array( + "time" => time(), + "priority" => $priority, + "task" => $task, + "message" => $message + ); + $valkey->lPush('CRON_LOG', json_encode($finalMsg)); +} + +// Load core functions first +require_once __DIR__ . '/../web/inc/functions.inc.php'; +require_once __DIR__ . '/../web/inc/functions.auth.inc.php'; +require_once __DIR__ . '/../web/inc/sessions.inc.php'; +require_once __DIR__ . '/../web/inc/functions.mailbox.inc.php'; +require_once __DIR__ . '/../web/inc/functions.ratelimit.inc.php'; +require_once __DIR__ . '/../web/inc/functions.acl.inc.php'; + +$_SESSION['mailcow_cc_username'] = "admin"; +$_SESSION['mailcow_cc_role'] = "admin"; +$_SESSION['acl']['tls_policy'] = "1"; +$_SESSION['acl']['quarantine_notification'] = "1"; +$_SESSION['acl']['quarantine_category'] = "1"; +$_SESSION['acl']['ratelimit'] = "1"; +$_SESSION['acl']['sogo_access'] = "1"; +$_SESSION['acl']['protocol_access'] = "1"; +$_SESSION['acl']['mailbox_relayhost'] = "1"; +$_SESSION['acl']['unlimited_quota'] = "1"; + +$iam_settings = identity_provider('get'); +if ($iam_settings['authsource'] != "keycloak" || (intval($iam_settings['periodic_sync']) != 1 && intval($iam_settings['import_users']) != 1)) { + session_destroy(); + exit; +} + +// Set pagination variables +$start = 0; +$max = 100; + +// lock sync if already running +$lock_file = '/tmp/iam-sync.lock'; +if (file_exists($lock_file)) { + $lock_file_parts = explode("\n", file_get_contents($lock_file)); + $pid = $lock_file_parts[0]; + if (count($lock_file_parts) > 1){ + $last_execution = $lock_file_parts[1]; + $elapsed_time = (time() - $last_execution) / 60; + if ($elapsed_time < intval($iam_settings['sync_interval'])) { + logMsg("warning", "Sync not ready (".number_format((float)$elapsed_time, 2, '.', '')."min / ".$iam_settings['sync_interval']."min)"); + session_destroy(); + exit; + } + } + + if (posix_kill($pid, 0)) { + logMsg("warning", "Sync is already running"); + session_destroy(); + exit; + } else { + unlink($lock_file); + } +} +$lock_file_handle = fopen($lock_file, 'w'); +fwrite($lock_file_handle, getmypid()); +fclose($lock_file_handle); + +// Init Keycloak Provider +$iam_provider = identity_provider('init'); + +// Loop until all users have been retrieved +while (true) { + // Get admin access token + $admin_token = identity_provider("get-keycloak-admin-token"); + + // Make the API request to retrieve the users + $url = "{$iam_settings['server_url']}/admin/realms/{$iam_settings['realm']}/users?first=$start&max=$max"; + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_HTTPHEADER, [ + "Content-Type: application/json", + "Authorization: Bearer " . $admin_token + ]); + $response = curl_exec($ch); + $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); + curl_close($ch); + + if ($code != 200){ + logMsg("err", "Received HTTP {$code}"); + session_destroy(); + exit; + } + try { + $response = json_decode($response, true); + } catch (Exception $e) { + logMsg("err", $e->getMessage()); + break; + } + if (!is_array($response)){ + logMsg("err", "Received malformed response from keycloak api"); + break; + } + if (count($response) == 0) { + break; + } + + // Process the batch of users + foreach ($response as $user) { + if (empty($user['email'])){ + logMsg("warning", "No email address in keycloak found for user " . $user['name']); + continue; + } + + // try get mailbox user + $stmt = $pdo->prepare("SELECT + mailbox.*, + domain.active AS d_active + FROM `mailbox` + INNER JOIN domain on mailbox.domain = domain.domain + WHERE `kind` NOT REGEXP 'location|thing|group' + AND `username` = :user"); + $stmt->execute(array(':user' => $user['email'])); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + + // check if matching attribute mapping exists + $user_template = $user['attributes']['mailcow_template'][0]; + $mapper_key = array_search($user_template, $iam_settings['mappers']); + + $_SESSION['access_all_exception'] = '1'; + if (!$row && intval($iam_settings['import_users']) == 1){ + if ($mapper_key === false){ + if (!empty($iam_settings['default_template'])) { + $mbox_template = $iam_settings['default_template']; + logMsg("warning", "Using default template for user " . $user['email']); + } else { + logMsg("warning", "No matching attribute mapping found for user " . $user['email']); + continue; + } + } else { + $mbox_template = $iam_settings['templates'][$mapper_key]; + } + // mailbox user does not exist, create... + logMsg("info", "Creating user " . $user['email']); + $create_res = mailbox('add', 'mailbox_from_template', array( + 'domain' => explode('@', $user['email'])[1], + 'local_part' => explode('@', $user['email'])[0], + 'name' => $user['firstName'] . " " . $user['lastName'], + 'authsource' => 'keycloak', + 'template' => $mbox_template + )); + if (!$create_res){ + logMsg("err", "Could not create user " . $user['email']); + continue; + } + } else if ($row && intval($iam_settings['periodic_sync']) == 1 && $row['authsource'] == "keycloak") { + if ($mapper_key === false){ + logMsg("warning", "No matching attribute mapping found for user " . $user['email']); + continue; + } + $mbox_template = $iam_settings['templates'][$mapper_key]; + // mailbox user does exist, sync attribtues... + logMsg("info", "Syncing attributes for user " . $user['email']); + mailbox('edit', 'mailbox_from_template', array( + 'username' => $user['email'], + 'name' => $user['firstName'] . " " . $user['lastName'], + 'template' => $mbox_template + )); + } else { + // skip mailbox user + logMsg("info", "Skipping user " . $user['email']); + } + $_SESSION['access_all_exception'] = '0'; + + sleep(0.025); + } + + // Update the pagination variables for the next batch + $start += $max; + sleep(1); +} + +logMsg("info", "DONE!"); +// add last execution time to lock file +$lock_file_handle = fopen($lock_file, 'w'); +fwrite($lock_file_handle, getmypid() . "\n" . time()); +fclose($lock_file_handle); +session_destroy(); diff --git a/data/conf/phpfpm/crons/ldap-sync.php b/data/conf/phpfpm/crons/ldap-sync.php new file mode 100644 index 000000000..3012c8202 --- /dev/null +++ b/data/conf/phpfpm/crons/ldap-sync.php @@ -0,0 +1,198 @@ + PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + PDO::ATTR_EMULATE_PREPARES => false, +]; +try { + $pdo = new PDO($dsn, $database_user, $database_pass, $opt); +} +catch (PDOException $e) { + logMsg("err", $e->getMessage()); + session_destroy(); + exit; +} + +// Init Valkey +$valkey = new Redis(); +try { + if (!empty(getenv('VALKEY_SLAVEOF_IP'))) { + $valkey->connect(getenv('VALKEY_SLAVEOF_IP'), getenv('VALKEY_SLAVEOF_PORT')); + } + else { + $valkey->connect('valkey-mailcow', 6379); + } + $valkey->auth(getenv("VALKEYPASS")); +} +catch (Exception $e) { + echo "Exiting: " . $e->getMessage(); + session_destroy(); + exit; +} + +function logMsg($priority, $message, $task = "LDAP Sync") { + global $valkey; + + $finalMsg = array( + "time" => time(), + "priority" => $priority, + "task" => $task, + "message" => $message + ); + $valkey->lPush('CRON_LOG', json_encode($finalMsg)); +} + +// Load core functions first +require_once __DIR__ . '/../web/inc/functions.inc.php'; +require_once __DIR__ . '/../web/inc/functions.auth.inc.php'; +require_once __DIR__ . '/../web/inc/sessions.inc.php'; +require_once __DIR__ . '/../web/inc/functions.mailbox.inc.php'; +require_once __DIR__ . '/../web/inc/functions.ratelimit.inc.php'; +require_once __DIR__ . '/../web/inc/functions.acl.inc.php'; + +$_SESSION['mailcow_cc_username'] = "admin"; +$_SESSION['mailcow_cc_role'] = "admin"; +$_SESSION['acl']['tls_policy'] = "1"; +$_SESSION['acl']['quarantine_notification'] = "1"; +$_SESSION['acl']['quarantine_category'] = "1"; +$_SESSION['acl']['ratelimit'] = "1"; +$_SESSION['acl']['sogo_access'] = "1"; +$_SESSION['acl']['protocol_access'] = "1"; +$_SESSION['acl']['mailbox_relayhost'] = "1"; +$_SESSION['acl']['unlimited_quota'] = "1"; + +$iam_settings = identity_provider('get'); +if ($iam_settings['authsource'] != "ldap" || (intval($iam_settings['periodic_sync']) != 1 && intval($iam_settings['import_users']) != 1)) { + session_destroy(); + exit; +} + +// Set pagination variables +$start = 0; +$max = 100; + +// lock sync if already running +$lock_file = '/tmp/iam-sync.lock'; +if (file_exists($lock_file)) { + $lock_file_parts = explode("\n", file_get_contents($lock_file)); + $pid = $lock_file_parts[0]; + if (count($lock_file_parts) > 1){ + $last_execution = $lock_file_parts[1]; + $elapsed_time = (time() - $last_execution) / 60; + if ($elapsed_time < intval($iam_settings['sync_interval'])) { + logMsg("warning", "Sync not ready (".number_format((float)$elapsed_time, 2, '.', '')."min / ".$iam_settings['sync_interval']."min)"); + session_destroy(); + exit; + } + } + + if (posix_kill($pid, 0)) { + logMsg("warning", "Sync is already running"); + session_destroy(); + exit; + } else { + unlink($lock_file); + } +} +$lock_file_handle = fopen($lock_file, 'w'); +fwrite($lock_file_handle, getmypid()); +fclose($lock_file_handle); + +// Init Provider +$iam_provider = identity_provider('init'); + +// Get ldap users +$ldap_query = $iam_provider->query(); +if (!empty($iam_settings['filter'])) { + $ldap_query = $ldap_query->rawFilter($iam_settings['filter']); +} +$response = $ldap_query->where($iam_settings['username_field'], "*") + ->where($iam_settings['attribute_field'], "*") + ->select([$iam_settings['username_field'], $iam_settings['attribute_field'], 'displayname']) + ->paginate($max); + +// Process the users +foreach ($response as $user) { + // try get mailbox user + $stmt = $pdo->prepare("SELECT + mailbox.*, + domain.active AS d_active + FROM `mailbox` + INNER JOIN domain on mailbox.domain = domain.domain + WHERE `kind` NOT REGEXP 'location|thing|group' + AND `username` = :user"); + $stmt->execute(array(':user' => $user[$iam_settings['username_field']][0])); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + + // check if matching attribute mapping exists + $user_template = $user[$iam_settings['attribute_field']][0]; + $mapper_key = array_search($user_template, $iam_settings['mappers']); + + if (empty($user[$iam_settings['username_field']][0])){ + logMsg("warning", "Skipping user " . $user['displayname'][0] . " due to empty LDAP ". $iam_settings['username_field'] . " property."); + continue; + } + + $_SESSION['access_all_exception'] = '1'; + if (!$row && intval($iam_settings['import_users']) == 1){ + if ($mapper_key === false){ + if (!empty($iam_settings['default_template'])) { + $mbox_template = $iam_settings['default_template']; + } else { + logMsg("warning", "No matching attribute mapping found for user " . $user[$iam_settings['username_field']][0]); + continue; + } + } else { + $mbox_template = $iam_settings['templates'][$mapper_key]; + } + // mailbox user does not exist, create... + logMsg("info", "Creating user " . $user[$iam_settings['username_field']][0]); + $create_res = mailbox('add', 'mailbox_from_template', array( + 'domain' => explode('@', $user[$iam_settings['username_field']][0])[1], + 'local_part' => explode('@', $user[$iam_settings['username_field']][0])[0], + 'name' => $user['displayname'][0], + 'authsource' => 'ldap', + 'template' => $mbox_template + )); + if (!$create_res){ + logMsg("err", "Could not create user " . $user[$iam_settings['username_field']][0]); + continue; + } + } else if ($row && intval($iam_settings['periodic_sync']) == 1 && $row['authsource'] == "ldap") { + if ($mapper_key === false){ + logMsg("warning", "No matching attribute mapping found for user " . $user[$iam_settings['username_field']][0]); + continue; + } + $mbox_template = $iam_settings['templates'][$mapper_key]; + // mailbox user does exist, sync attribtues... + logMsg("info", "Syncing attributes for user " . $user[$iam_settings['username_field']][0]); + mailbox('edit', 'mailbox_from_template', array( + 'username' => $user[$iam_settings['username_field']][0], + 'name' => $user['displayname'][0], + 'template' => $mbox_template + )); + } else { + // skip mailbox user + logMsg("info", "Skipping user " . $user[$iam_settings['username_field']][0]); + } + $_SESSION['access_all_exception'] = '0'; + + sleep(0.025); +} + +logMsg("info", "DONE!"); +// add last execution time to lock file +$lock_file_handle = fopen($lock_file, 'w'); +fwrite($lock_file_handle, getmypid() . "\n" . time()); +fclose($lock_file_handle); +session_destroy(); diff --git a/data/conf/postfix/main.cf b/data/conf/postfix/main.cf index 07065f045..f091cb3f9 100644 --- a/data/conf/postfix/main.cf +++ b/data/conf/postfix/main.cf @@ -152,7 +152,7 @@ smtp_sasl_auth_enable = yes smtp_sasl_password_maps = proxy:mysql:/opt/postfix/conf/sql/mysql_sasl_passwd_maps_sender_dependent.cf smtp_sasl_security_options = smtp_sasl_mechanism_filter = plain, login -smtp_tls_policy_maps = proxy:mysql:/opt/postfix/conf/sql/mysql_tls_policy_override_maps.cf +smtp_tls_policy_maps = proxy:mysql:/opt/postfix/conf/sql/mysql_tls_policy_override_maps.cf socketmap:inet:postfix-tlspol:8642:QUERY smtp_header_checks = pcre:/opt/postfix/conf/anonymize_headers.pcre mail_name = Postcow # local_transport map catches local destinations and prevents routing local dests when the next map would route "*" diff --git a/data/conf/postfix/postscreen_access.cidr b/data/conf/postfix/postscreen_access.cidr index 69be54247..9249520bc 100644 --- a/data/conf/postfix/postscreen_access.cidr +++ b/data/conf/postfix/postscreen_access.cidr @@ -1,32 +1,71 @@ -# Whitelist generated by Postwhite v3.4 on Sat Feb 1 00:18:03 UTC 2025 +# Whitelist generated by Postwhite v3.4 on Wed Oct 1 00:21:33 UTC 2025 # https://github.com/stevejenkins/postwhite/ -# 1984 total rules +# 2216 total rules 2a00:1450:4000::/36 permit 2a01:111:f400::/48 permit -2a01:111:f403:8000::/50 permit +2a01:111:f403:2800::/53 permit 2a01:111:f403:8000::/51 permit 2a01:111:f403::/49 permit 2a01:111:f403:c000::/51 permit +2a01:111:f403:d000::/53 permit 2a01:111:f403:f000::/52 permit +2a01:238:20a:202:5370::1 permit +2a01:238:20a:202:5372::1 permit +2a01:238:20a:202:5373::1 permit +2a01:238:400:101:53::1 permit +2a01:238:400:102:53::1 permit +2a01:238:400:103:53::1 permit +2a01:238:400:301:53::1 permit +2a01:238:400:302:53::1 permit +2a01:238:400:303:53::1 permit +2a01:238:400:470:53::1 permit +2a01:238:400:471:53::1 permit +2a01:238:400:472:53::1 permit +2a01:b747:3000:200::/56 permit +2a01:b747:3001:200::/56 permit +2a01:b747:3002:200::/56 permit +2a01:b747:3003:200::/56 permit +2a01:b747:3004:200::/56 permit +2a01:b747:3005:200::/56 permit +2a01:b747:3006:200::/56 permit 2a02:a60:0:5::/64 permit 2c0f:fb50:4000::/36 permit -2.207.151.53 permit +2.207.217.30 permit +3.64.237.68 permit +3.65.3.180 permit 3.70.123.177 permit +3.72.182.33 permit +3.74.81.189 permit +3.74.125.228 permit +3.75.33.185 permit 3.93.157.0/24 permit 3.94.40.108 permit +3.121.107.214 permit 3.129.120.190 permit 3.210.190.0/24 permit +3.211.80.218 permit +3.216.221.67 permit +3.221.209.22 permit 8.20.114.31 permit 8.25.194.0/23 permit 8.25.196.0/23 permit -10.162.0.0/16 permit +8.36.116.0/24 permit +8.39.54.0/23 permit +8.39.54.250/31 permit +8.39.144.0/24 permit +8.40.222.0/23 permit +8.40.222.250/31 permit 12.130.86.238 permit +13.107.213.41 permit +13.107.246.41 permit 13.110.208.0/21 permit 13.110.209.0/24 permit 13.110.216.0/22 permit 13.110.224.0/20 permit 13.111.0.0/16 permit 13.111.191.0/24 permit +13.216.7.111 permit +13.216.54.180 permit 15.200.21.50 permit 15.200.44.248 permit 15.200.201.185 permit @@ -35,25 +74,30 @@ 17.57.156.0/24 permit 17.58.0.0/16 permit 17.142.0.0/15 permit -17.143.234.140/30 permit +18.97.0.8/30 permit +18.97.1.184/29 permit +18.97.2.64/26 permit 18.156.89.250 permit +18.156.205.64 permit +18.157.70.148 permit +18.157.114.255 permit 18.157.243.190 permit +18.158.153.154 permit 18.194.95.56 permit +18.197.217.180 permit 18.198.96.88 permit +18.199.210.3 permit +18.207.52.234 permit 18.208.124.128/25 permit 18.216.232.154 permit 18.235.27.253 permit 18.236.40.242 permit -18.236.56.161 permit 20.51.6.32/30 permit -20.51.98.61 permit 20.52.52.2 permit 20.52.128.133 permit 20.59.80.4/30 permit 20.63.210.192/28 permit 20.69.8.108/30 permit -20.70.246.20 permit -20.76.201.171 permit 20.83.222.104/30 permit 20.88.157.184/30 permit 20.94.180.64/28 permit @@ -62,14 +106,11 @@ 20.98.194.68/30 permit 20.105.209.76/30 permit 20.107.239.64/30 permit -20.112.250.133 permit 20.118.139.208/30 permit 20.141.10.196 permit 20.185.214.0/27 permit 20.185.214.32/27 permit 20.185.214.64/27 permit -20.231.239.246 permit -20.236.44.162 permit 23.103.224.0/19 permit 23.249.208.0/20 permit 23.251.224.0/19 permit @@ -81,6 +122,7 @@ 23.253.183.147 permit 23.253.183.148 permit 23.253.183.150 permit +24.110.64.0/18 permit 27.123.204.128/30 permit 27.123.204.132/31 permit 27.123.204.148/30 permit @@ -93,19 +135,51 @@ 27.123.206.56/29 permit 27.123.206.76/30 permit 27.123.206.80/28 permit -31.25.48.222 permit 31.47.251.17 permit +31.186.239.0/24 permit +34.2.64.0/22 permit +34.2.68.0/23 permit +34.2.70.0/23 permit +34.2.71.64/26 permit +34.2.72.0/22 permit +34.2.75.0/26 permit +34.2.78.0/23 permit +34.2.80.0/23 permit +34.2.82.0/23 permit +34.2.84.0/24 permit +34.2.84.64/26 permit +34.2.85.0/24 permit +34.2.85.64/26 permit +34.2.86.0/23 permit +34.2.88.0/23 permit +34.2.90.0/23 permit +34.2.92.0/23 permit +34.2.94.0/23 permit +34.70.158.162 permit +34.74.74.140 permit +34.83.159.189 permit +34.141.160.224 permit +34.193.58.168 permit 34.195.217.107 permit +34.197.10.50 permit +34.197.254.9 permit +34.198.94.229 permit +34.198.218.121 permit 34.212.163.75 permit 34.215.104.144 permit -34.218.116.3 permit +34.218.115.239 permit 34.225.212.172 permit +34.241.242.183 permit +35.83.148.184 permit +35.155.198.111 permit +35.158.23.94 permit 35.161.32.253 permit +35.162.73.231 permit 35.167.93.243 permit +35.174.145.124 permit 35.176.132.251 permit -35.190.247.0/24 permit -35.191.0.0/16 permit 35.205.92.9 permit +35.228.216.85 permit 35.242.169.159 permit 37.188.97.188 permit 37.218.248.47 permit @@ -119,12 +193,21 @@ 40.233.64.216 permit 40.233.83.78 permit 40.233.88.28 permit +43.239.212.33 permit 44.206.138.57 permit +44.210.169.44 permit 44.217.45.156 permit 44.236.56.93 permit 44.238.220.251 permit +44.245.243.92 permit +44.246.1.125 permit +44.246.68.102 permit +44.246.77.92 permit 45.14.148.0/22 permit -46.19.170.16 permit +45.143.132.0/24 permit +45.143.133.0/24 permit +45.143.134.0/24 permit +45.143.135.0/24 permit 46.226.48.0/21 permit 46.228.36.37 permit 46.228.36.38/31 permit @@ -175,6 +258,7 @@ 46.243.88.177 permit 46.243.95.179 permit 46.243.95.180 permit +50.16.246.183 permit 50.18.45.249 permit 50.18.121.236 permit 50.18.121.248 permit @@ -188,14 +272,24 @@ 50.56.130.220 permit 50.56.130.221 permit 50.56.130.222 permit +50.112.246.219 permit 52.1.14.157 permit 52.5.230.59 permit +52.6.74.205 permit +52.12.53.23 permit +52.13.214.179 permit +52.26.1.71 permit 52.27.5.72 permit 52.27.28.47 permit 52.28.63.81 permit +52.28.197.132 permit +52.34.181.151 permit +52.35.192.45 permit 52.36.138.31 permit 52.37.142.146 permit +52.42.203.116 permit 52.50.24.208 permit +52.57.120.243 permit 52.58.216.183 permit 52.59.143.3 permit 52.60.41.5 permit @@ -238,23 +332,24 @@ 54.174.63.0/24 permit 54.186.193.102 permit 54.191.223.56 permit +54.211.126.101 permit 54.213.20.246 permit 54.214.39.184 permit 54.240.0.0/18 permit -54.240.64.0/19 permit -54.240.96.0/19 permit +54.240.64.0/18 permit 54.241.16.209 permit 54.244.54.130 permit 54.244.242.0/24 permit 54.255.61.23 permit +56.124.6.228 permit 57.103.64.0/18 permit +57.129.93.249 permit 62.13.128.0/24 permit 62.13.129.128/25 permit 62.13.136.0/21 permit 62.13.144.0/21 permit 62.13.152.0/21 permit 62.17.146.128/26 permit -62.179.121.0/24 permit 62.201.172.0/27 permit 62.201.172.32/27 permit 62.253.227.114 permit @@ -262,6 +357,9 @@ 63.128.21.0/24 permit 63.143.57.128/25 permit 63.143.59.128/25 permit +63.176.194.123 permit +63.178.132.221 permit +63.178.143.178 permit 64.18.0.0/20 permit 64.20.241.45 permit 64.69.212.0/24 permit @@ -274,6 +372,7 @@ 64.127.115.252 permit 64.132.88.0/23 permit 64.132.92.0/24 permit +64.181.194.190 permit 64.207.219.7 permit 64.207.219.8 permit 64.207.219.9 permit @@ -327,10 +426,10 @@ 65.110.161.77 permit 65.123.29.213 permit 65.123.29.220 permit +65.154.166.0/24 permit 65.212.180.36 permit 66.102.0.0/20 permit 66.119.150.192/26 permit -66.162.193.226/31 permit 66.163.184.0/24 permit 66.163.185.0/24 permit 66.163.186.0/24 permit @@ -536,7 +635,6 @@ 74.86.241.250/31 permit 74.112.67.243 permit 74.125.0.0/16 permit -74.202.227.40 permit 74.208.4.200 permit 74.208.4.201 permit 74.208.4.220 permit @@ -565,6 +663,11 @@ 77.238.189.142 permit 77.238.189.146/31 permit 77.238.189.148/30 permit +79.135.106.0/24 permit +79.135.107.0/24 permit +81.169.146.243 permit +81.169.146.245 permit +81.169.146.246 permit 81.223.46.0/27 permit 82.165.159.2 permit 82.165.159.3 permit @@ -580,10 +683,17 @@ 82.165.159.45 permit 82.165.159.130 permit 82.165.159.131 permit -84.116.6.0/23 permit -84.116.36.0/24 permit -84.116.50.0/23 permit +85.9.206.169 permit +85.9.210.45 permit 85.158.136.0/21 permit +85.215.255.39 permit +85.215.255.40 permit +85.215.255.41 permit +85.215.255.45 permit +85.215.255.46 permit +85.215.255.47 permit +85.215.255.48 permit +85.215.255.49 permit 86.61.88.25 permit 87.238.80.0/21 permit 87.248.103.12 permit @@ -623,12 +733,13 @@ 87.248.117.205 permit 87.253.232.0/21 permit 89.22.108.0/24 permit +91.198.2.0/24 permit 91.211.240.0/22 permit -94.169.2.0/23 permit 94.236.119.0/26 permit 94.245.112.0/27 permit 94.245.112.10/31 permit 95.131.104.0/21 permit +95.217.114.154 permit 96.43.144.0/20 permit 96.43.144.64/28 permit 96.43.144.64/31 permit @@ -1122,15 +1233,14 @@ 99.83.190.102 permit 103.9.96.0/22 permit 103.28.42.0/24 permit +103.84.217.238 permit +103.89.75.238 permit 103.151.192.0/23 permit 103.168.172.128/27 permit 103.237.104.0/22 permit 104.43.243.237 permit 104.44.112.128/25 permit 104.47.0.0/17 permit -104.47.20.0/23 permit -104.47.75.0/24 permit -104.47.108.0/23 permit 104.130.96.0/28 permit 104.130.122.0/23 permit 106.10.144.64/27 permit @@ -1256,6 +1366,7 @@ 106.50.16.0/28 permit 107.20.18.111 permit 107.20.210.250 permit +107.22.191.150 permit 108.174.0.0/24 permit 108.174.0.215 permit 108.174.3.0/24 permit @@ -1264,9 +1375,8 @@ 108.174.6.215 permit 108.175.18.45 permit 108.175.30.45 permit -108.177.8.0/21 permit -108.177.96.0/19 permit 108.179.144.0/20 permit +109.224.244.0/24 permit 109.237.142.0/24 permit 111.221.23.128/25 permit 111.221.26.0/27 permit @@ -1290,6 +1400,9 @@ 117.120.16.0/21 permit 119.42.242.52/31 permit 119.42.242.156 permit +121.244.91.48 permit +121.244.91.52 permit +122.15.156.182 permit 123.126.78.64/29 permit 124.108.96.24/31 permit 124.108.96.28/31 permit @@ -1338,7 +1451,6 @@ 129.213.195.191 permit 130.61.9.72 permit 130.162.39.83 permit -130.211.0.0/22 permit 130.248.172.0/24 permit 130.248.173.0/24 permit 131.253.30.0/24 permit @@ -1347,12 +1459,28 @@ 132.226.26.225 permit 132.226.49.32 permit 132.226.56.24 permit +134.128.64.0/19 permit +134.128.96.0/19 permit 134.170.27.8 permit 134.170.113.0/26 permit 134.170.141.64/26 permit 134.170.143.0/24 permit 134.170.174.0/24 permit +135.84.80.0/24 permit +135.84.81.0/24 permit +135.84.82.0/24 permit +135.84.83.0/24 permit 135.84.216.0/22 permit +136.143.160.0/24 permit +136.143.161.0/24 permit +136.143.162.0/24 permit +136.143.176.0/24 permit +136.143.177.0/24 permit +136.143.178.49 permit +136.143.182.0/23 permit +136.143.184.0/24 permit +136.143.188.0/24 permit +136.143.190.0/23 permit 136.147.128.0/20 permit 136.147.135.0/24 permit 136.147.176.0/20 permit @@ -1367,6 +1495,7 @@ 139.138.46.219 permit 139.138.57.55 permit 139.138.58.119 permit +139.167.79.86 permit 139.180.17.0/24 permit 140.238.148.191 permit 141.148.159.229 permit @@ -1401,6 +1530,7 @@ 146.20.215.0/24 permit 146.20.215.182 permit 146.88.28.0/24 permit +146.148.116.76 permit 147.154.32.0/25 permit 147.243.1.47 permit 147.243.1.48 permit @@ -1410,7 +1540,7 @@ 148.105.0.0/16 permit 148.105.8.0/21 permit 149.72.0.0/16 permit -149.72.223.204 permit +149.72.234.184 permit 149.72.248.236 permit 149.97.173.180 permit 150.230.98.160 permit @@ -1464,6 +1594,9 @@ 159.135.224.0/20 permit 159.135.228.10 permit 159.183.0.0/16 permit +159.183.68.71 permit +159.183.79.38 permit +159.183.129.172 permit 160.1.62.192 permit 161.38.192.0/20 permit 161.38.204.0/22 permit @@ -1480,8 +1613,14 @@ 163.114.132.120 permit 163.114.134.16 permit 163.114.135.16 permit +163.116.128.0/17 permit +163.192.116.87 permit 164.152.23.32 permit +164.152.25.241 permit 164.177.132.168/30 permit +165.173.128.0/24 permit +165.173.180.250/31 permit +165.173.182.250/31 permit 166.78.68.0/22 permit 166.78.68.221 permit 166.78.69.169 permit @@ -1506,20 +1645,28 @@ 168.138.5.36 permit 168.138.73.51 permit 168.138.77.31 permit +168.138.237.153 permit 168.245.0.0/17 permit 168.245.12.252 permit 168.245.46.9 permit 168.245.127.231 permit +169.148.129.0/24 permit +169.148.131.0/24 permit +169.148.138.0/24 permit +169.148.142.10 permit +169.148.142.33 permit +169.148.144.0/25 permit +169.148.144.10 permit +169.148.146.0/23 permit +169.148.175.3 permit +169.148.188.0/24 permit +169.148.188.182 permit 170.10.128.0/24 permit 170.10.129.0/24 permit 170.10.132.56/29 permit 170.10.132.64/29 permit 170.10.133.0/24 permit -172.217.0.0/19 permit 172.217.32.0/20 permit -172.217.128.0/19 permit -172.217.160.0/20 permit -172.217.192.0/19 permit 172.253.56.0/21 permit 172.253.112.0/20 permit 173.0.84.0/29 permit @@ -1549,9 +1696,14 @@ 182.50.78.64/28 permit 183.240.219.64/29 permit 185.4.120.0/22 permit +185.11.253.128/27 permit +185.11.255.0/24 permit 185.12.80.0/22 permit 185.28.196.0/22 permit 185.58.84.93 permit +185.70.40.0/24 permit +185.70.41.0/24 permit +185.70.43.0/24 permit 185.80.93.204 permit 185.80.93.227 permit 185.80.95.31 permit @@ -1559,6 +1711,8 @@ 185.138.56.128/25 permit 185.189.236.0/22 permit 185.211.120.0/22 permit +185.233.188.0/23 permit +185.233.190.0/23 permit 185.250.236.0/22 permit 185.250.239.148 permit 185.250.239.168 permit @@ -1611,6 +1765,7 @@ 188.125.85.234/31 permit 188.125.85.236/31 permit 188.125.85.238 permit +188.165.51.139 permit 188.172.128.0/20 permit 192.0.64.0/18 permit 192.18.139.154 permit @@ -1633,8 +1788,28 @@ 193.109.254.0/23 permit 193.122.128.100 permit 193.123.56.63 permit +193.142.157.0/24 permit +193.142.157.191 permit +193.142.157.198 permit 194.19.134.0/25 permit +194.25.134.16/28 permit +194.25.134.80/28 permit 194.64.234.129 permit +194.97.196.0/24 permit +194.97.196.3 permit +194.97.196.4 permit +194.97.196.11 permit +194.97.196.12 permit +194.97.204.0/24 permit +194.97.204.3 permit +194.97.204.4 permit +194.97.204.11 permit +194.97.204.12 permit +194.97.212.0/24 permit +194.97.212.3 permit +194.97.212.4 permit +194.97.212.11 permit +194.97.212.12 permit 194.106.220.0/23 permit 194.113.24.0/22 permit 194.154.193.192/27 permit @@ -1651,6 +1826,14 @@ 198.61.254.231 permit 198.178.234.57 permit 198.244.48.0/20 permit +198.244.56.107 permit +198.244.56.108 permit +198.244.56.109 permit +198.244.56.111 permit +198.244.56.112 permit +198.244.56.113 permit +198.244.56.114 permit +198.244.56.115 permit 198.244.59.30 permit 198.244.59.33 permit 198.244.59.35 permit @@ -1663,7 +1846,16 @@ 199.16.156.0/22 permit 199.33.145.1 permit 199.33.145.32 permit +199.34.22.36 permit 199.59.148.0/22 permit +199.67.80.2 permit +199.67.80.20 permit +199.67.82.2 permit +199.67.82.20 permit +199.67.84.0/24 permit +199.67.86.0/24 permit +199.67.88.0/24 permit +199.67.90.0/24 permit 199.101.161.130 permit 199.101.162.0/25 permit 199.122.120.0/21 permit @@ -1720,9 +1912,13 @@ 204.92.114.187 permit 204.92.114.203 permit 204.92.114.204/31 permit +204.141.32.0/23 permit +204.141.42.0/23 permit +204.216.164.202 permit 204.220.160.0/21 permit 204.220.168.0/21 permit 204.220.176.0/20 permit +204.220.181.105 permit 204.232.168.0/24 permit 205.139.110.0/24 permit 205.201.128.0/20 permit @@ -1797,8 +1993,6 @@ 208.71.42.212/31 permit 208.71.42.214 permit 208.72.249.240/29 permit -208.74.204.5 permit -208.74.204.9 permit 208.75.120.0/22 permit 208.76.62.0/24 permit 208.76.63.0/24 permit @@ -1862,6 +2056,8 @@ 212.227.15.4 permit 212.227.15.5 permit 212.227.15.6 permit +212.227.15.7 permit +212.227.15.8 permit 212.227.15.14 permit 212.227.15.15 permit 212.227.15.18 permit @@ -1878,21 +2074,36 @@ 212.227.15.53 permit 212.227.15.54 permit 212.227.15.55 permit +212.227.17.1 permit +212.227.17.2 permit +212.227.17.7 permit 212.227.17.11 permit 212.227.17.12 permit +212.227.17.16 permit +212.227.17.17 permit 212.227.17.18 permit 212.227.17.19 permit 212.227.17.20 permit 212.227.17.21 permit 212.227.17.22 permit 212.227.17.26 permit +212.227.17.27 permit 212.227.17.28 permit 212.227.17.29 permit +212.227.126.206 permit +212.227.126.207 permit +212.227.126.208 permit +212.227.126.209 permit +212.227.126.220 permit +212.227.126.221 permit +212.227.126.222 permit +212.227.126.223 permit 212.227.126.224 permit 212.227.126.225 permit 212.227.126.226 permit 212.227.126.227 permit -213.46.255.0/24 permit +213.95.19.64/27 permit +213.95.135.4 permit 213.199.128.139 permit 213.199.128.145 permit 213.199.138.181 permit @@ -1902,6 +2113,7 @@ 216.17.150.242 permit 216.17.150.251 permit 216.24.224.0/20 permit +216.27.86.152/31 permit 216.39.60.154/31 permit 216.39.60.156/30 permit 216.39.60.160/30 permit @@ -1939,6 +2151,8 @@ 216.99.5.68 permit 216.109.114.32/27 permit 216.109.114.64/29 permit +216.113.162.65 permit +216.113.163.65 permit 216.128.126.97 permit 216.136.162.65 permit 216.136.162.120/29 permit @@ -1966,12 +2180,30 @@ 2001:0868:0100:0600::/64 permit 2001:4860:4000::/36 permit 2001:748:100:40::2:0/112 permit +2001:748:400:1300::3 permit +2001:748:400:1300::4 permit +2001:748:400:1301::0/64 permit +2001:748:400:1301::3 permit +2001:748:400:1301::4 permit +2001:748:400:2300::3 permit +2001:748:400:2300::4 permit +2001:748:400:2301::0/64 permit +2001:748:400:2301::3 permit +2001:748:400:2301::4 permit +2001:748:400:3300::3 permit +2001:748:400:3300::4 permit +2001:748:400:3301::0/64 permit +2001:748:400:3301::3 permit +2001:748:400:3301::4 permit 2404:6800:4000::/36 permit 2603:1010:3:3::5b permit 2603:1020:201:10::10f permit 2603:1030:20e:3::23c permit 2603:1030:b:3::152 permit 2603:1030:c02:8::14 permit +2607:13c0:0001:0000:0000:0000:0000:7000/116 permit +2607:13c0:0002:0000:0000:0000:0000:1000/116 permit +2607:13c0:0004:0000:0000:0000:0000:0000/116 permit 2607:f8b0:4000::/36 permit 2620:109:c003:104::/64 permit 2620:109:c003:104::215 permit @@ -1985,4 +2217,5 @@ 2620:119:50c0:207::/64 permit 2620:119:50c0:207::215 permit 2800:3f0:4000::/36 permit -194.25.134.0/24 permit # t-online.de +49.12.4.251 permit # checks.mailcow.email +2a01:4f8:c17:7906::10 permit # checks.mailcow.email diff --git a/data/conf/rspamd/custom/fishy_tlds.map b/data/conf/rspamd/custom/fishy_tlds.map index 1b8b2b0d7..f19f70da5 100644 --- a/data/conf/rspamd/custom/fishy_tlds.map +++ b/data/conf/rspamd/custom/fishy_tlds.map @@ -24,7 +24,6 @@ /.+\.guru$/i /.+\.icu$/i /.+\.id$/i -/.+\.info$/i /.+\.in.net$/i /.+\.ir$/i /.+\.jetzt$/i diff --git a/data/conf/rspamd/dynmaps/aliasexp.php b/data/conf/rspamd/dynmaps/aliasexp.php index 3225130fb..ac90dd882 100644 --- a/data/conf/rspamd/dynmaps/aliasexp.php +++ b/data/conf/rspamd/dynmaps/aliasexp.php @@ -133,7 +133,7 @@ try { error_log("ALIAS EXPANDER: http pipe: goto address " . $goto . " is an alias branch for " . $goto_branch . PHP_EOL); $goto_branch_array = explode(',', $goto_branch); } else { - $stmt = $pdo->prepare("SELECT `target_domain` FROM `alias_domain` WHERE `alias_domain` = :domain AND `active` AND '1'"); + $stmt = $pdo->prepare("SELECT `target_domain` FROM `alias_domain` WHERE `alias_domain` = :domain AND `active` = '1'"); $stmt->execute(array(':domain' => $parsed_goto['domain'])); $goto_branch = $stmt->fetch(PDO::FETCH_ASSOC)['target_domain']; if ($goto_branch) { diff --git a/data/conf/rspamd/dynmaps/settings.php b/data/conf/rspamd/dynmaps/settings.php index 274e9da28..1b0e6b6e4 100644 --- a/data/conf/rspamd/dynmaps/settings.php +++ b/data/conf/rspamd/dynmaps/settings.php @@ -56,7 +56,7 @@ function normalize_email($email) { $email = explode('@', $email); $email[0] = str_replace('.', '', $email[0]); $email = implode('@', $email); - } + } $gm_alt = "@googlemail.com"; if (substr_compare($email, $gm_alt, -strlen($gm_alt)) == 0) { $email = explode('@', $email); @@ -114,7 +114,7 @@ function ucl_rcpts($object, $type) { $rcpt[] = str_replace('/', '\/', $row['address']); } // Aliases by alias domains - $stmt = $pdo->prepare("SELECT CONCAT(`local_part`, '@', `alias_domain`.`alias_domain`) AS `alias` FROM `mailbox` + $stmt = $pdo->prepare("SELECT CONCAT(`local_part`, '@', `alias_domain`.`alias_domain`) AS `alias` FROM `mailbox` LEFT OUTER JOIN `alias_domain` ON `mailbox`.`domain` = `alias_domain`.`target_domain` WHERE `mailbox`.`username` = :object"); $stmt->execute(array( @@ -184,7 +184,7 @@ while ($row = array_shift($rows)) { rcpt = ; prepare("SELECT `option`, `value` FROM `filterconf` + $stmt = $pdo->prepare("SELECT `option`, `value` FROM `filterconf` WHERE (`option` = 'highspamlevel' OR `option` = 'lowspamlevel') AND `object`= :object"); $stmt->execute(array(':object' => $row['object'])); @@ -468,4 +468,36 @@ while ($row = array_shift($rows)) { + +query("SELECT `id`, `address`, `domain` FROM `alias` WHERE `active` = '1' AND `internal` = '1'"); +$aliases = $stmt->fetchAll(PDO::FETCH_ASSOC); +while ($alias = array_shift($aliases)) { + // build allowed_domains regex and add target domain and alias domains + $stmt = $pdo->prepare("SELECT `alias_domain` FROM `alias_domain` WHERE `active` = '1' AND `target_domain` = :target_domain"); + $stmt->execute(array(':target_domain' => $alias['domain'])); + $allowed_domains = $stmt->fetchAll(PDO::FETCH_ASSOC); + $allowed_domains = array_map(function($item) { + return str_replace('.', '\.', $item['alias_domain']); + }, $allowed_domains); + $allowed_domains[] = str_replace('.', '\.', $alias['domain']); + $allowed_domains = implode('|', $allowed_domains); +?> + internal_alias_ { + priority = 10; + rcpt = ""; + from = "/^((?!.*@()).)*$/"; + apply "default" { + MAILCOW_INTERNAL_ALIAS = 9999.0; + } + symbols [ + "MAILCOW_INTERNAL_ALIAS" + ] + } + + } diff --git a/data/conf/rspamd/local.d/composites.conf b/data/conf/rspamd/local.d/composites.conf index 9bb84424a..4ce042aab 100644 --- a/data/conf/rspamd/local.d/composites.conf +++ b/data/conf/rspamd/local.d/composites.conf @@ -8,7 +8,7 @@ VIRUS_FOUND { } # Bad policy from free mail providers FREEMAIL_POLICY_FAILURE { - expression = "FREEMAIL_FROM & !DMARC_POLICY_ALLOW & !MAILLIST& !WHITELISTED_FWD_HOST & -g+:policies"; + expression = "FREEMAIL_FROM & !DMARC_POLICY_ALLOW & !MAILLIST & !WHITELISTED_FWD_HOST & -g+:policies"; score = 16.0; } # Applies to freemail with undisclosed recipients diff --git a/data/conf/rspamd/local.d/external_services.conf b/data/conf/rspamd/local.d/external_services.conf deleted file mode 100644 index 2b091ff23..000000000 --- a/data/conf/rspamd/local.d/external_services.conf +++ /dev/null @@ -1,12 +0,0 @@ -oletools { - # default olefy settings - servers = "olefy:10055"; - # needs to be set explicitly for Rspamd < 1.9.5 - scan_mime_parts = true; - # mime-part regex matching in content-type or filename - # block all macros - extended = true; - max_size = 3145728; - timeout = 20.0; - retransmits = 1; -} diff --git a/data/conf/rspamd/local.d/redis.conf b/data/conf/rspamd/local.d/redis.conf deleted file mode 100644 index 5ee0ac196..000000000 --- a/data/conf/rspamd/local.d/redis.conf +++ /dev/null @@ -1,2 +0,0 @@ -servers = "redis:6379"; -timeout = 10; diff --git a/data/conf/rspamd/lua/rspamd.local.lua b/data/conf/rspamd/lua/rspamd.local.lua index 5f23ef6b8..9d0a58bcf 100644 --- a/data/conf/rspamd/lua/rspamd.local.lua +++ b/data/conf/rspamd/lua/rspamd.local.lua @@ -102,7 +102,7 @@ rspamd_config:register_symbol({ local rcpt_split = rspamd_str_split(rcpt['addr'], '@') if #rcpt_split == 2 then if rcpt_split[1] == 'postmaster' then - task:set_pre_result('accept', 'whitelisting postmaster smtp rcpt') + task:set_pre_result('accept', 'whitelisting postmaster smtp rcpt', 'postmaster') return end end @@ -167,7 +167,7 @@ rspamd_config:register_symbol({ for k,v in pairs(data) do if (v and v ~= userdata and v == '1') then rspamd_logger.infox(rspamd_config, "found ip in keep_spam map, setting pre-result") - task:set_pre_result('accept', 'ip matched with forward hosts') + task:set_pre_result('accept', 'ip matched with forward hosts', 'keep_spam') end end end @@ -454,12 +454,18 @@ rspamd_config:register_symbol({ local redis_params = rspamd_parse_redis_server('dyn_rl') local rspamd_logger = require "rspamd_logger" local envfrom = task:get_from(1) + local envrcpt = task:get_recipients(1) or {} local uname = task:get_user() if not envfrom or not uname then return false end + local uname = uname:lower() + if #envrcpt == 1 and envrcpt[1].addr:lower() == uname then + return false + end + local env_from_domain = envfrom[1].domain:lower() -- get smtp from domain in lower case local function redis_cb_user(err, data) @@ -544,13 +550,13 @@ rspamd_config:register_symbol({ -- determine newline type local function newline(task) local t = task:get_newlines_type() - + if t == 'cr' then return '\r' elseif t == 'lf' then return '\n' end - + return '\r\n' end -- retrieve footer @@ -558,7 +564,7 @@ rspamd_config:register_symbol({ if err or type(data) ~= 'string' then rspamd_logger.infox(rspamd_config, "domain wide footer request for user %s returned invalid or empty data (\"%s\") or error (\"%s\")", uname, data, err) else - + -- parse json string local footer = cjson.decode(data) if not footer then @@ -607,26 +613,30 @@ rspamd_config:register_symbol({ if footer.plain and footer.plain ~= "" then footer.plain = lua_util.jinja_template(footer.plain, replacements, true) end - + -- add footer local out = {} local rewrite = lua_mime.add_text_footer(task, footer.html, footer.plain) or {} - + local seen_cte local newline_s = newline(task) - + local function rewrite_ct_cb(name, hdr) if rewrite.need_rewrite_ct then if name:lower() == 'content-type' then - local nct = string.format('%s: %s/%s; charset=utf-8', - 'Content-Type', rewrite.new_ct.type, rewrite.new_ct.subtype) + -- include boundary if present + local boundary_part = rewrite.new_ct.boundary and + string.format('; boundary="%s"', rewrite.new_ct.boundary) or '' + local nct = string.format('%s: %s/%s; charset=utf-8%s', + 'Content-Type', rewrite.new_ct.type, rewrite.new_ct.subtype, boundary_part) out[#out + 1] = nct - -- update Content-Type header + -- update Content-Type header (include boundary if present) task:set_milter_reply({ remove_headers = {['Content-Type'] = 0}, }) task:set_milter_reply({ - add_headers = {['Content-Type'] = string.format('%s/%s; charset=utf-8', rewrite.new_ct.type, rewrite.new_ct.subtype)} + add_headers = {['Content-Type'] = string.format('%s/%s; charset=utf-8%s', + rewrite.new_ct.type, rewrite.new_ct.subtype, boundary_part)} }) return elseif name:lower() == 'content-transfer-encoding' then @@ -645,16 +655,16 @@ rspamd_config:register_symbol({ end out[#out + 1] = hdr.raw:gsub('\r?\n?$', '') end - + task:headers_foreach(rewrite_ct_cb, {full = true}) - + if not seen_cte and rewrite.need_rewrite_ct then out[#out + 1] = string.format('%s: %s', 'Content-Transfer-Encoding', 'quoted-printable') end - + -- End of headers out[#out + 1] = newline_s - + if rewrite.out then for _,o in ipairs(rewrite.out) do out[#out + 1] = o diff --git a/data/conf/rspamd/meta_exporter/pipe.php b/data/conf/rspamd/meta_exporter/pipe.php index 179e2e39f..4dda40e0f 100644 --- a/data/conf/rspamd/meta_exporter/pipe.php +++ b/data/conf/rspamd/meta_exporter/pipe.php @@ -182,7 +182,7 @@ foreach (json_decode($rcpts, true) as $rcpt) { error_log("RCPT RESOVLER: http pipe: goto address " . $goto . " is an alias branch for " . $goto_branch . PHP_EOL); $goto_branch_array = explode(',', $goto_branch); } else { - $stmt = $pdo->prepare("SELECT `target_domain` FROM `alias_domain` WHERE `alias_domain` = :domain AND `active` AND '1'"); + $stmt = $pdo->prepare("SELECT `target_domain` FROM `alias_domain` WHERE `alias_domain` = :domain AND `active` = '1'"); $stmt->execute(array(':domain' => $parsed_goto['domain'])); $goto_branch = $stmt->fetch(PDO::FETCH_ASSOC)['target_domain']; if ($goto_branch) { @@ -236,6 +236,9 @@ foreach ($rcpt_final_mailboxes as $rcpt_final) { ':action' => $action, ':fuzzy_hashes' => $fuzzy )); + $lastId = $pdo->lastInsertId(); + $stmt_update = $pdo->prepare("UPDATE `quarantine` SET `qhash` = SHA2(CONCAT(`id`, `qid`), 256) WHERE `id` = :id"); + $stmt_update->execute(array(':id' => $lastId)); $stmt = $pdo->prepare('DELETE FROM `quarantine` WHERE `rcpt` = :rcpt AND `id` NOT IN ( SELECT `id` FROM ( diff --git a/data/conf/rspamd/meta_exporter/pushover.php b/data/conf/rspamd/meta_exporter/pushover.php index 8fa6b7d7e..373f9e43e 100644 --- a/data/conf/rspamd/meta_exporter/pushover.php +++ b/data/conf/rspamd/meta_exporter/pushover.php @@ -167,7 +167,7 @@ foreach (json_decode($rcpts, true) as $rcpt) { error_log("RCPT RESOVLER: http pipe: goto address " . $goto . " is an alias branch for " . $goto_branch . PHP_EOL); $goto_branch_array = explode(',', $goto_branch); } else { - $stmt = $pdo->prepare("SELECT `target_domain` FROM `alias_domain` WHERE `alias_domain` = :domain AND `active` AND '1'"); + $stmt = $pdo->prepare("SELECT `target_domain` FROM `alias_domain` WHERE `alias_domain` = :domain AND `active` = '1'"); $stmt->execute(array(':domain' => $parsed_goto['domain'])); $goto_branch = $stmt->fetch(PDO::FETCH_ASSOC)['target_domain']; if ($goto_branch) { diff --git a/data/conf/sogo/custom-sogo.js b/data/conf/sogo/custom-sogo.js index 9ee6daba1..d3b90b085 100644 --- a/data/conf/sogo/custom-sogo.js +++ b/data/conf/sogo/custom-sogo.js @@ -1,3 +1,21 @@ +// redirect to mailcow login form +document.addEventListener('DOMContentLoaded', function () { + var loginForm = document.forms.namedItem("loginForm"); + if (loginForm) { + window.location.href = '/user'; + } +}); +// logout function +function mc_logout() { + fetch("/", { + method: "POST", + headers: { + "Content-Type": "application/x-www-form-urlencoded" + }, + body: "logout=1" + }).then(() => window.location.href = '/'); +} + // Custom SOGo JS // Change the visible font-size in the editor, this does not change the font of a html message by default @@ -5,3 +23,4 @@ CKEDITOR.addCss("body {font-size: 16px !important}"); // Enable scayt by default //CKEDITOR.config.scayt_autoStartup = true; + diff --git a/data/conf/sogo/plist_ldap b/data/conf/sogo/plist_ldap.sh old mode 100644 new mode 100755 similarity index 85% rename from data/conf/sogo/plist_ldap rename to data/conf/sogo/plist_ldap.sh index d585a494f..1911cd18c --- a/data/conf/sogo/plist_ldap +++ b/data/conf/sogo/plist_ldap.sh @@ -1,28 +1,34 @@ - +#!/bin/bash + +domain="$1" +gal_status="$2" + +echo " + " diff --git a/data/conf/sogo/sogo.conf b/data/conf/sogo/sogo.conf index 8455f0cf3..2c8d80a12 100644 --- a/data/conf/sogo/sogo.conf +++ b/data/conf/sogo/sogo.conf @@ -16,6 +16,9 @@ SOGoFoldersSendEMailNotifications = YES; SOGoForwardEnabled = YES; + // Added with SOGo 5.12 - Allows users to cleanup there maildirectories by deleting mails oder than X + SOGoEnableMailCleaning = YES; + // Fixes "MODIFICATION_FAILED" error (HTTP 412) in Clients when accepting invitations from external services SOGoDisableOrganizerEventCheck = YES; @@ -91,7 +94,7 @@ //SoDebugBaseURL = YES; //ImapDebugEnabled = YES; //SOGoEASDebugEnabled = YES; - SOGoEASSearchInBody = YES; // Experimental. Enabled since 2023-10 + SOGoEASSearchInBody = YES; //LDAPDebugEnabled = YES; //PGDebugEnabled = YES; //MySQL4DebugEnabled = YES; diff --git a/data/conf/valkey/valkey-conf.sh b/data/conf/valkey/valkey-conf.sh index 5b6e51fbd..0cff196c6 100755 --- a/data/conf/valkey/valkey-conf.sh +++ b/data/conf/valkey/valkey-conf.sh @@ -9,4 +9,4 @@ if [ -n "$VALKEYMASTERPASS" ]; then echo "masterauth $VALKEYMASTERPASS" >> /valkey.conf fi -exec valkey-server /valkey.conf +exec "$@" diff --git a/data/web/debug.php b/data/web/admin/dashboard.php similarity index 76% rename from data/web/debug.php rename to data/web/admin/dashboard.php index 159007dfb..6b6d299aa 100644 --- a/data/web/debug.php +++ b/data/web/admin/dashboard.php @@ -1,21 +1,31 @@ Get('LICENSE_STATUS_CACHE')) { $_SESSION['gal'] = json_decode($license_cache, true); } -$js_minifier->add('/web/js/site/debug.js'); +$js_minifier->add('/web/js/site/dashboard.js'); // vmail df $exec_fields = array('cmd' => 'system', 'task' => 'df', 'dir' => '/var/vmail'); @@ -24,6 +34,7 @@ $vmail_df = explode(',', (string)json_decode(docker('post', 'dovecot-mailcow', ' // containers $containers_info = (array) docker('info'); if ($clamd_status === false) unset($containers_info['clamd-mailcow']); +if ($olefy_status === false) unset($containers_info['olefy-mailcow']); ksort($containers_info); $containers = array(); foreach ($containers_info as $container => $container_info) { @@ -59,7 +70,7 @@ foreach ($containers_info as $container => $container_info) { $hostname = getenv('MAILCOW_HOSTNAME'); $timezone = getenv('TZ'); -$template = 'debug.twig'; +$template = 'dashboard.twig'; $template_data = [ 'log_lines' => getenv('LOG_LINES'), 'vmail_df' => $vmail_df, @@ -68,6 +79,7 @@ $template_data = [ 'gal' => @$_SESSION['gal'], 'license_guid' => license('guid'), 'clamd_status' => $clamd_status, + 'olefy_status' => $olefy_status, 'containers' => $containers, 'ip_check' => customize('get', 'ip_check'), 'lang_admin' => json_encode($lang['admin']), diff --git a/data/web/admin/index.php b/data/web/admin/index.php new file mode 100644 index 000000000..9ae4a0380 --- /dev/null +++ b/data/web/admin/index.php @@ -0,0 +1,30 @@ + @$_SESSION['ldelay'], + 'custom_login' => customize('get', 'custom_login'), +]; + +$js_minifier->add('/web/js/site/index.js'); +require_once $_SERVER['DOCUMENT_ROOT'] . '/inc/footer.inc.php'; diff --git a/data/web/mailbox.php b/data/web/admin/mailbox.php similarity index 73% rename from data/web/mailbox.php rename to data/web/admin/mailbox.php index a84e32c47..d0073bbd6 100644 --- a/data/web/mailbox.php +++ b/data/web/admin/mailbox.php @@ -1,10 +1,20 @@ add('/web/js/site/mailbox.js'); $js_minifier->add('/web/js/presets/sieveMailbox.js'); $js_minifier->add('/web/js/site/pwgen.js'); -$role = ($_SESSION['mailcow_cc_role'] == "admin") ? 'admin' : 'domainadmin'; +$role = "admin"; $is_dual = (!empty($_SESSION["dual-login"]["username"])) ? 'true' : 'false'; $allow_admin_email_login = (preg_match("/^([yY][eE][sS]|[yY])+$/", $_ENV["ALLOW_ADMIN_EMAIL_LOGIN"])) ? 'true' : 'false'; diff --git a/data/web/queue.php b/data/web/admin/queue.php similarity index 55% rename from data/web/queue.php rename to data/web/admin/queue.php index ffce8d8b0..85ec59401 100644 --- a/data/web/queue.php +++ b/data/web/admin/queue.php @@ -1,8 +1,17 @@ add('/web/js/site/queue.js'); $_SESSION['return_to'] = $_SERVER['REQUEST_URI']; -$role = ($_SESSION['mailcow_cc_role'] == "admin") ? 'admin' : 'domainadmin'; +$role = "admin"; $template = 'queue.twig'; $template_data = [ diff --git a/data/web/admin.php b/data/web/admin/system.php similarity index 86% rename from data/web/admin.php rename to data/web/admin/system.php index f03e52e76..9fd44e0d8 100644 --- a/data/web/admin.php +++ b/data/web/admin/system.php @@ -1,8 +1,17 @@ customize('get', 'main_logo_specs'), 'logo_dark_specs' => customize('get', 'main_logo_dark_specs'), 'ip_check' => customize('get', 'ip_check'), + 'custom_login' => customize('get', 'custom_login'), 'password_complexity' => password_complexity('get'), 'show_rspamd_global_filters' => @$_SESSION['show_rspamd_global_filters'], 'cors_settings' => $cors_settings, 'is_https' => isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on', + 'iam_settings' => $iam_settings, + 'mbox_templates' => $mbox_templates, 'lang_admin' => json_encode($lang['admin']), 'lang_datatables' => json_encode($lang['datatables']) ]; diff --git a/data/web/api/openapi.yaml b/data/web/api/openapi.yaml index 21db37e33..81207b139 100644 --- a/data/web/api/openapi.yaml +++ b/data/web/api/openapi.yaml @@ -346,7 +346,8 @@ paths: description: the domain which emails should be forwarded type: string type: - description: the type of bcc map can be `sender` or `recipient` + description: the type of bcc map can be `sender` or `rcpt` + enum: [sender, rcpt] type: string type: object summary: Create BCC Map @@ -409,7 +410,7 @@ paths: description: a list of domains for which a dkim key should be generated type: string key_size: - description: the key size (1024 or 2048) + description: the key size (1024, 2048, 3072 or 4096) type: number type: object summary: Generate DKIM Key @@ -1112,6 +1113,7 @@ paths: domain: domain.tld local_part: info name: Full name + authsource: mailcow password: atedismonsin password2: atedismonsin quota: "3072" @@ -1132,11 +1134,16 @@ paths: name: description: Full name of the mailbox user type: string + authsource: + description: Specifies the authentication source for the mailbox. + type: string + enum: [mailcow, ldap, keycloak, generic-oidc] + default: mailcow password2: description: mailbox password for confirmation type: string password: - description: mailbox password + description: mailbox password when using `mailcow` as the authentication source. type: string quota: description: mailbox quota @@ -3374,6 +3381,7 @@ paths: active: "1" force_pw_update: "0" name: Full name + authsource: mailcow password: "" password2: "" quota: "3072" @@ -3398,11 +3406,15 @@ paths: name: description: Full name of the mailbox user type: string + authsource: + description: Specifies the authentication source for the mailbox. + type: string + enum: [mailcow, ldap, keycloak, generic-oidc] password2: description: new mailbox password for confirmation type: string password: - description: new mailbox password + description: new mailbox password when using `mailcow` as the authentication source. type: string quota: description: mailbox quota @@ -5687,7 +5699,7 @@ paths: - description: name of domain in: path name: domain - required: false + required: true schema: type: string - description: e.g. api-key-string @@ -5814,6 +5826,226 @@ paths: Using this endpoint you can get the global spam filter score or the spam filter score of a certain mailbox. operationId: Get mailbox or global spam filter score summary: Get mailbox or global spam filter score + /api/v1/edit/identity-provider: + post: + responses: + "401": + $ref: "#/components/responses/Unauthorized" + "200": + content: + application/json: + examples: + response: + value: + - type: "success" + log: + - "identity_provider" + - "edit" + - authsource: "keycloak" + server_url: "https://auth.mailcow.tld" + realm: "mailcow" + client_id: "mailcow_client" + client_secret: "*" + redirect_url: "https://mail.mailcow.tld" + redirect_url_extra: ["https://extramail.mailcow.tld"] + version: "26.1.3" + default_template: "Default" + mappers: + - "small_mbox" + - "medium_mbox" + templates: + - "small" + - "medium" + ignore_ssl_error: true + mailpassword_flow: true + periodic_sync: true + import_users: true + sync_interval: 30 + msg: + - "object_modified" + - "" + description: OK + headers: { } + tags: + - Identity Provider + description: >- + Configure an external Identity Provider to use as user authentication + operationId: Edit external Identity Provider settings + requestBody: + content: + application/json: + schema: + properties: + items: + type: array + default: ["identity-provider"] + attr: + type: object + properties: + authsource: + description: Specifies the type of the Identity Provider + type: string + enum: [ldap, keycloak, generic-oidc] + server_url: + description: The base URL of your Keycloak server. Required if `authsource` is keycloak. + type: string + realm: + description: The Keycloak realm where the mailcow client is configured. Required if `authsource` is keycloak. + type: string + client_id: + description: The Client ID assigned to mailcow Client in OIDC Provider. Required if `authsource` is keycloak or generic-oidc. + type: string + client_secret: + description: The Client Secret assigned to mailcow Client in OIDC Provider. Required if `authsource` is keycloak or generic-oidc. + type: string + redirect_url: + description: The redirect URL that OIDC Provider will use after authentication. Required if `authsource` is keycloak or generic-oidc. + type: string + redirect_url_extra: + description: Additional redirect URLs that OIDC Provider can use after authentication if valid. + type: array + version: + description: Specifies the Keycloak version. Required if `authsource` is keycloak. + type: string + default_template: + description: (Optional) If no matching Attribute Mapping exists for a User, the default template will be used for creating the mailbox, but not for updating the mailbox. + type: string + mappers: + description: (Optional) Attribute values used to match a mailbox template. Each element corresponds to the respective index in the templates array (i.e., the first element matches the first element of templates, the second matches the second, and so on). + type: array + templates: + description: (Optional) Defines the mailbox templates to be assigned. Each element corresponds to the respective index in the `mappers` array. + type: array + ignore_ssl_error: + description: If enabled, SSL certificate validation is bypassed + type: boolean + default: false + mailpassword_flow: + description: If enabled, mailcow will attempt to validate user credentials using the Keycloak Admin REST API instead of relying solely on the Authorization Code Flow. + type: boolean + default: false + periodic_sync: + description: If enabled, mailcow periodically performs a full sync of all users from Keycloak or LDAP. + type: boolean + default: false + import_users: + description: If enabled, new users are automatically imported from Keycloak or LDAP into mailcow. + type: boolean + default: false + sync_interval: + description: Defines the time interval (in minutes) for periodic synchronization and user imports. + type: number + default: 15 + host: + description: The address of your LDAP server. You can provide a single hostname or a comma-separated list of hosts for fallback in case the primary server is unreachable. Required if `authsource` is ldap. + type: string + port: + description: The port used to connect to the LDAP server. Required if `authsource` is ldap. + type: string + use_ssl: + description: enable LDAPS connection. If Port is set to 389 it will be overriden to 636. + type: boolean + default: false + use_tls: + description: enable TLS connection. TLS is recommended over SSL. SSL Ports cannot be used. + type: boolean + default: false + basedn: + description: The Distinguished Name (DN) from which searches will be performed. Required if `authsource` is ldap. + type: string + username_field: + description: The LDAP attribute used to identify users during authentication. Required if `authsource` is ldap. + type: string + default: mail + filter: + description: An optional LDAP search filter to refine which users can authenticate. + type: string + attribute_field: + description: Specifies an LDAP attribute that holds a specific value which can be mapped to a mailbox template using the Attribute Mapping section. Required if `authsource` is ldap. + type: string + binddn: + description: The Distinguished Name (DN) of the LDAP user that will be used to authenticate and perform LDAP searches. This account should have sufficient permissions to read the required attributes. Required if `authsource` is ldap. + type: string + bindpass: + description: The password for the Bind DN user. It is required for authentication when connecting to the LDAP server. Required if `authsource` is ldap. + type: string + authorize_url: + description: The OIDC provider's authorization server URL. Required if `authsource` is generic-oidc. + type: string + token_url: + description: The OIDC provider's token server URL. Required if `authsource` is generic-oidc. + type: string + userinfo_url: + description: The OIDC provider's user info server URL. Required if `authsource` is generic-oidc. + type: string + client_scopes: + description: Specifies the OIDC scopes requested during authentication. + type: string + default: "openid profile email mailcow_template" + examples: + keycloak: + value: + items: + - "identity-provider" + attr: + authsource: "keycloak" + server_url: "https://auth.mailcow.tld" + realm: "mailcow" + client_id: "mailcow_client" + client_secret: "Xy7GdPqvJ9m3R8sT2LkVZ5W1oNbCaYQf" + redirect_url: "https://mail.mailcow.tld" + redirect_url_extra: ["https://extramail.mailcow.tld"] + version: "26.1.3" + default_template: "Default" + mappers: ["small_mbox", "medium_mbox"] + templates: ["small", "medium"] + ignore_ssl_error: true + mailpassword_flow: true + periodic_sync: true + import_users: true + sync_interval: 30 + ldap: + value: + items: + - "identity-provider" + attr: + authsource: "ldap" + host: "127.0.0.1" + port: "389" + use_ssl: false + use_tls: false + ignore_ssl_error: false + basedn: "DC=mailcow,DC=local" + username_field: "mail" + filter: "(memberOf:1.2.840.113556.1.4.1941:=DC=mailcow,DC=local)" + attribute_field: "othermailbox" + binddn: "CN=LDAP Read Only,CN=Users,DC=mailcow,DC=local" + bindpass: "moohoo" + default_template: "Default" + mappers: ["small_mbox", "medium_mbox"] + templates: ["small", "medium"] + periodic_sync: true + import_users: true + sync_interval: 30 + generic-oidc: + value: + items: + - "identity-provider" + attr: + authsource: "generic-oidc" + authorize_url: "https://auth.mailcow.tld/application/o/authorize/" + token_url: "https://auth.mailcow.tld/application/o/token/" + userinfo_url: "https://auth.mailcow.tld/application/o/userinfo/" + client_id: "mailcow_client" + client_secret: "Xy7GdPqvJ9m3R8sT2LkVZ5W1oNbCaYQf" + redirect_url: "https://mail.mailcow.tld" + redirect_url_extra: ["https://extramail.mailcow.tld"] + client_scopes: "openid profile email mailcow_template" + default_template: "Default" + mappers: ["small_mbox", "medium_mbox"] + templates: ["small", "medium"] + ignore_ssl_error: true + summary: Edit external Identity Provider tags: - name: Domains @@ -5860,3 +6092,5 @@ tags: description: Edit domain ratelimits - name: Cross-Origin Resource Sharing (CORS) description: Manage Cross-Origin Resource Sharing (CORS) settings + - name: Identity Provider + description: Manage external Identity Provider settings diff --git a/data/web/autoconfig.php b/data/web/autoconfig.php index 95952df0d..6a528d4a2 100644 --- a/data/web/autoconfig.php +++ b/data/web/autoconfig.php @@ -85,7 +85,7 @@ if (count($records) == 0 || $records[0]['target'] != '') { ?> password-cleartext - + If you didn't change the password given to you by the administrator or if you didn't change it in a long time, please consider doing that now. Sollten Sie das Ihnen durch den Administrator vergebene Passwort noch nicht geändert haben, empfehlen wir dies nun zu tun. Auch ein altes Passwort sollte aus Sicherheitsgründen geändert werden. diff --git a/data/web/autodiscover.php b/data/web/autodiscover.php index a5a62764c..45041eddb 100644 --- a/data/web/autodiscover.php +++ b/data/web/autodiscover.php @@ -1,10 +1,13 @@ false, ]; $pdo = new PDO($dsn, $database_user, $database_pass, $opt); + +// Init Identity Provider +$iam_provider = identity_provider('init'); +$iam_settings = identity_provider('get'); + $login_user = strtolower(trim($_SERVER['PHP_AUTH_USER'])); $login_pass = trim(htmlspecialchars_decode($_SERVER['PHP_AUTH_PW'])); diff --git a/data/web/css/build/007-languages.min.css b/data/web/css/build/007-languages.min.css index 864e338df..9d8cb205d 100644 --- a/data/web/css/build/007-languages.min.css +++ b/data/web/css/build/007-languages.min.css @@ -1 +1 @@ -.flag-icon-background{background-size:contain;background-position:50%;background-repeat:no-repeat}.flag-icon{background-size:contain;background-position:50%;background-repeat:no-repeat;position:relative;display:inline-block;width:1.33333333em;line-height:1em}.flag-icon:before{content:'\00a0'}.flag-icon.flag-icon-squared{width:1em}.flag-icon-ad{background-image:url(../flags/4x3/ad.svg)}.flag-icon-ad.flag-icon-squared{background-image:url(../flags/1x1/ad.svg)}.flag-icon-ae{background-image:url(../flags/4x3/ae.svg)}.flag-icon-ae.flag-icon-squared{background-image:url(../flags/1x1/ae.svg)}.flag-icon-af{background-image:url(../flags/4x3/af.svg)}.flag-icon-af.flag-icon-squared{background-image:url(../flags/1x1/af.svg)}.flag-icon-ag{background-image:url(../flags/4x3/ag.svg)}.flag-icon-ag.flag-icon-squared{background-image:url(../flags/1x1/ag.svg)}.flag-icon-ai{background-image:url(../flags/4x3/ai.svg)}.flag-icon-ai.flag-icon-squared{background-image:url(../flags/1x1/ai.svg)}.flag-icon-al{background-image:url(../flags/4x3/al.svg)}.flag-icon-al.flag-icon-squared{background-image:url(../flags/1x1/al.svg)}.flag-icon-am{background-image:url(../flags/4x3/am.svg)}.flag-icon-am.flag-icon-squared{background-image:url(../flags/1x1/am.svg)}.flag-icon-ao{background-image:url(../flags/4x3/ao.svg)}.flag-icon-ao.flag-icon-squared{background-image:url(../flags/1x1/ao.svg)}.flag-icon-aq{background-image:url(../flags/4x3/aq.svg)}.flag-icon-aq.flag-icon-squared{background-image:url(../flags/1x1/aq.svg)}.flag-icon-ar{background-image:url(../flags/4x3/ar.svg)}.flag-icon-ar.flag-icon-squared{background-image:url(../flags/1x1/ar.svg)}.flag-icon-as{background-image:url(../flags/4x3/as.svg)}.flag-icon-as.flag-icon-squared{background-image:url(../flags/1x1/as.svg)}.flag-icon-at{background-image:url(../flags/4x3/at.svg)}.flag-icon-at.flag-icon-squared{background-image:url(../flags/1x1/at.svg)}.flag-icon-au{background-image:url(../flags/4x3/au.svg)}.flag-icon-au.flag-icon-squared{background-image:url(../flags/1x1/au.svg)}.flag-icon-aw{background-image:url(../flags/4x3/aw.svg)}.flag-icon-aw.flag-icon-squared{background-image:url(../flags/1x1/aw.svg)}.flag-icon-ax{background-image:url(../flags/4x3/ax.svg)}.flag-icon-ax.flag-icon-squared{background-image:url(../flags/1x1/ax.svg)}.flag-icon-az{background-image:url(../flags/4x3/az.svg)}.flag-icon-az.flag-icon-squared{background-image:url(../flags/1x1/az.svg)}.flag-icon-ba{background-image:url(../flags/4x3/ba.svg)}.flag-icon-ba.flag-icon-squared{background-image:url(../flags/1x1/ba.svg)}.flag-icon-bb{background-image:url(../flags/4x3/bb.svg)}.flag-icon-bb.flag-icon-squared{background-image:url(../flags/1x1/bb.svg)}.flag-icon-bd{background-image:url(../flags/4x3/bd.svg)}.flag-icon-bd.flag-icon-squared{background-image:url(../flags/1x1/bd.svg)}.flag-icon-be{background-image:url(../flags/4x3/be.svg)}.flag-icon-be.flag-icon-squared{background-image:url(../flags/1x1/be.svg)}.flag-icon-bf{background-image:url(../flags/4x3/bf.svg)}.flag-icon-bf.flag-icon-squared{background-image:url(../flags/1x1/bf.svg)}.flag-icon-bg{background-image:url(../flags/4x3/bg.svg)}.flag-icon-bg.flag-icon-squared{background-image:url(../flags/1x1/bg.svg)}.flag-icon-bh{background-image:url(../flags/4x3/bh.svg)}.flag-icon-bh.flag-icon-squared{background-image:url(../flags/1x1/bh.svg)}.flag-icon-bi{background-image:url(../flags/4x3/bi.svg)}.flag-icon-bi.flag-icon-squared{background-image:url(../flags/1x1/bi.svg)}.flag-icon-bj{background-image:url(../flags/4x3/bj.svg)}.flag-icon-bj.flag-icon-squared{background-image:url(../flags/1x1/bj.svg)}.flag-icon-bl{background-image:url(../flags/4x3/bl.svg)}.flag-icon-bl.flag-icon-squared{background-image:url(../flags/1x1/bl.svg)}.flag-icon-bm{background-image:url(../flags/4x3/bm.svg)}.flag-icon-bm.flag-icon-squared{background-image:url(../flags/1x1/bm.svg)}.flag-icon-bn{background-image:url(../flags/4x3/bn.svg)}.flag-icon-bn.flag-icon-squared{background-image:url(../flags/1x1/bn.svg)}.flag-icon-bo{background-image:url(../flags/4x3/bo.svg)}.flag-icon-bo.flag-icon-squared{background-image:url(../flags/1x1/bo.svg)}.flag-icon-bq{background-image:url(../flags/4x3/bq.svg)}.flag-icon-bq.flag-icon-squared{background-image:url(../flags/1x1/bq.svg)}.flag-icon-br{background-image:url(../flags/4x3/br.svg)}.flag-icon-br.flag-icon-squared{background-image:url(../flags/1x1/br.svg)}.flag-icon-bs{background-image:url(../flags/4x3/bs.svg)}.flag-icon-bs.flag-icon-squared{background-image:url(../flags/1x1/bs.svg)}.flag-icon-bt{background-image:url(../flags/4x3/bt.svg)}.flag-icon-bt.flag-icon-squared{background-image:url(../flags/1x1/bt.svg)}.flag-icon-bv{background-image:url(../flags/4x3/bv.svg)}.flag-icon-bv.flag-icon-squared{background-image:url(../flags/1x1/bv.svg)}.flag-icon-bw{background-image:url(../flags/4x3/bw.svg)}.flag-icon-bw.flag-icon-squared{background-image:url(../flags/1x1/bw.svg)}.flag-icon-by{background-image:url(../flags/4x3/by.svg)}.flag-icon-by.flag-icon-squared{background-image:url(../flags/1x1/by.svg)}.flag-icon-bz{background-image:url(../flags/4x3/bz.svg)}.flag-icon-bz.flag-icon-squared{background-image:url(../flags/1x1/bz.svg)}.flag-icon-ca{background-image:url(../flags/4x3/ca.svg)}.flag-icon-ca.flag-icon-squared{background-image:url(../flags/1x1/ca.svg)}.flag-icon-cc{background-image:url(../flags/4x3/cc.svg)}.flag-icon-cc.flag-icon-squared{background-image:url(../flags/1x1/cc.svg)}.flag-icon-cd{background-image:url(../flags/4x3/cd.svg)}.flag-icon-cd.flag-icon-squared{background-image:url(../flags/1x1/cd.svg)}.flag-icon-cf{background-image:url(../flags/4x3/cf.svg)}.flag-icon-cf.flag-icon-squared{background-image:url(../flags/1x1/cf.svg)}.flag-icon-cg{background-image:url(../flags/4x3/cg.svg)}.flag-icon-cg.flag-icon-squared{background-image:url(../flags/1x1/cg.svg)}.flag-icon-ch{background-image:url(../flags/4x3/ch.svg)}.flag-icon-ch.flag-icon-squared{background-image:url(../flags/1x1/ch.svg)}.flag-icon-ci{background-image:url(../flags/4x3/ci.svg)}.flag-icon-ci.flag-icon-squared{background-image:url(../flags/1x1/ci.svg)}.flag-icon-ck{background-image:url(../flags/4x3/ck.svg)}.flag-icon-ck.flag-icon-squared{background-image:url(../flags/1x1/ck.svg)}.flag-icon-cl{background-image:url(../flags/4x3/cl.svg)}.flag-icon-cl.flag-icon-squared{background-image:url(../flags/1x1/cl.svg)}.flag-icon-cm{background-image:url(../flags/4x3/cm.svg)}.flag-icon-cm.flag-icon-squared{background-image:url(../flags/1x1/cm.svg)}.flag-icon-zh{background-image:url(../flags/4x3/zh.svg)}.flag-iconzh.flag-icon-squared{background-image:url(../flags/1x1/zh.svg)}.flag-icon-cn{background-image:url(../flags/4x3/cn.svg)}.flag-icon-cn.flag-icon-squared{background-image:url(../flags/1x1/cn.svg)}.flag-icon-co{background-image:url(../flags/4x3/co.svg)}.flag-icon-co.flag-icon-squared{background-image:url(../flags/1x1/co.svg)}.flag-icon-cr{background-image:url(../flags/4x3/cr.svg)}.flag-icon-cr.flag-icon-squared{background-image:url(../flags/1x1/cr.svg)}.flag-icon-cu{background-image:url(../flags/4x3/cu.svg)}.flag-icon-cu.flag-icon-squared{background-image:url(../flags/1x1/cu.svg)}.flag-icon-cv{background-image:url(../flags/4x3/cv.svg)}.flag-icon-cv.flag-icon-squared{background-image:url(../flags/1x1/cv.svg)}.flag-icon-cw{background-image:url(../flags/4x3/cw.svg)}.flag-icon-cw.flag-icon-squared{background-image:url(../flags/1x1/cw.svg)}.flag-icon-cx{background-image:url(../flags/4x3/cx.svg)}.flag-icon-cx.flag-icon-squared{background-image:url(../flags/1x1/cx.svg)}.flag-icon-cy{background-image:url(../flags/4x3/cy.svg)}.flag-icon-cy.flag-icon-squared{background-image:url(../flags/1x1/cy.svg)}.flag-icon-cz{background-image:url(../flags/4x3/cz.svg)}.flag-icon-cz.flag-icon-squared{background-image:url(../flags/1x1/cz.svg)}.flag-icon-cs{background-image:url(../flags/4x3/cs.svg)}.flag-icon-cs.flag-icon-squared{background-image:url(../flags/1x1/cs.svg)}.flag-icon-de{background-image:url(../flags/4x3/de.svg)}.flag-icon-de.flag-icon-squared{background-image:url(../flags/1x1/de.svg)}.flag-icon-dj{background-image:url(../flags/4x3/dj.svg)}.flag-icon-dj.flag-icon-squared{background-image:url(../flags/1x1/dj.svg)}.flag-icon-da{background-image:url(../flags/4x3/da.svg)}.flag-icon-da.flag-icon-squared{background-image:url(../flags/1x1/d.svg)}.flag-icon-dk{background-image:url(../flags/4x3/dk.svg)}.flag-icon-dk.flag-icon-squared{background-image:url(../flags/1x1/dk.svg)}.flag-icon-dm{background-image:url(../flags/4x3/dm.svg)}.flag-icon-dm.flag-icon-squared{background-image:url(../flags/1x1/dm.svg)}.flag-icon-do{background-image:url(../flags/4x3/do.svg)}.flag-icon-do.flag-icon-squared{background-image:url(../flags/1x1/do.svg)}.flag-icon-dz{background-image:url(../flags/4x3/dz.svg)}.flag-icon-dz.flag-icon-squared{background-image:url(../flags/1x1/dz.svg)}.flag-icon-ec{background-image:url(../flags/4x3/ec.svg)}.flag-icon-ec.flag-icon-squared{background-image:url(../flags/1x1/ec.svg)}.flag-icon-ee{background-image:url(../flags/4x3/ee.svg)}.flag-icon-ee.flag-icon-squared{background-image:url(../flags/1x1/ee.svg)}.flag-icon-eg{background-image:url(../flags/4x3/eg.svg)}.flag-icon-eg.flag-icon-squared{background-image:url(../flags/1x1/eg.svg)}.flag-icon-eh{background-image:url(../flags/4x3/eh.svg)}.flag-icon-eh.flag-icon-squared{background-image:url(../flags/1x1/eh.svg)}.flag-icon-er{background-image:url(../flags/4x3/er.svg)}.flag-icon-er.flag-icon-squared{background-image:url(../flags/1x1/er.svg)}.flag-icon-es{background-image:url(../flags/4x3/es.svg)}.flag-icon-es.flag-icon-squared{background-image:url(../flags/1x1/es.svg)}.flag-icon-et{background-image:url(../flags/4x3/et.svg)}.flag-icon-et.flag-icon-squared{background-image:url(../flags/1x1/et.svg)}.flag-icon-fi{background-image:url(../flags/4x3/fi.svg)}.flag-icon-fi.flag-icon-squared{background-image:url(../flags/1x1/fi.svg)}.flag-icon-fj{background-image:url(../flags/4x3/fj.svg)}.flag-icon-fj.flag-icon-squared{background-image:url(../flags/1x1/fj.svg)}.flag-icon-fk{background-image:url(../flags/4x3/fk.svg)}.flag-icon-fk.flag-icon-squared{background-image:url(../flags/1x1/fk.svg)}.flag-icon-fm{background-image:url(../flags/4x3/fm.svg)}.flag-icon-fm.flag-icon-squared{background-image:url(../flags/1x1/fm.svg)}.flag-icon-fo{background-image:url(../flags/4x3/fo.svg)}.flag-icon-fo.flag-icon-squared{background-image:url(../flags/1x1/fo.svg)}.flag-icon-fr{background-image:url(../flags/4x3/fr.svg)}.flag-icon-fr.flag-icon-squared{background-image:url(../flags/1x1/fr.svg)}.flag-icon-ga{background-image:url(../flags/4x3/ga.svg)}.flag-icon-ga.flag-icon-squared{background-image:url(../flags/1x1/ga.svg)}.flag-icon-gb{background-image:url(../flags/4x3/en.svg)}.flag-icon-gb.flag-icon-squared{background-image:url(../flags/1x1/en.svg)}.flag-icon-gd{background-image:url(../flags/4x3/gd.svg)}.flag-icon-gd.flag-icon-squared{background-image:url(../flags/1x1/gd.svg)}.flag-icon-ge{background-image:url(../flags/4x3/ge.svg)}.flag-icon-ge.flag-icon-squared{background-image:url(../flags/1x1/ge.svg)}.flag-icon-gf{background-image:url(../flags/4x3/gf.svg)}.flag-icon-gf.flag-icon-squared{background-image:url(../flags/1x1/gf.svg)}.flag-icon-gg{background-image:url(../flags/4x3/gg.svg)}.flag-icon-gg.flag-icon-squared{background-image:url(../flags/1x1/gg.svg)}.flag-icon-gh{background-image:url(../flags/4x3/gh.svg)}.flag-icon-gh.flag-icon-squared{background-image:url(../flags/1x1/gh.svg)}.flag-icon-gi{background-image:url(../flags/4x3/gi.svg)}.flag-icon-gi.flag-icon-squared{background-image:url(../flags/1x1/gi.svg)}.flag-icon-gl{background-image:url(../flags/4x3/gl.svg)}.flag-icon-gl.flag-icon-squared{background-image:url(../flags/1x1/gl.svg)}.flag-icon-gm{background-image:url(../flags/4x3/gm.svg)}.flag-icon-gm.flag-icon-squared{background-image:url(../flags/1x1/gm.svg)}.flag-icon-gn{background-image:url(../flags/4x3/gn.svg)}.flag-icon-gn.flag-icon-squared{background-image:url(../flags/1x1/gn.svg)}.flag-icon-gp{background-image:url(../flags/4x3/gp.svg)}.flag-icon-gp.flag-icon-squared{background-image:url(../flags/1x1/gp.svg)}.flag-icon-gq{background-image:url(../flags/4x3/gq.svg)}.flag-icon-gq.flag-icon-squared{background-image:url(../flags/1x1/gq.svg)}.flag-icon-gr{background-image:url(../flags/4x3/gr.svg)}.flag-icon-gr.flag-icon-squared{background-image:url(../flags/1x1/gr.svg)}.flag-icon-gs{background-image:url(../flags/4x3/gs.svg)}.flag-icon-gs.flag-icon-squared{background-image:url(../flags/1x1/gs.svg)}.flag-icon-gt{background-image:url(../flags/4x3/gt.svg)}.flag-icon-gt.flag-icon-squared{background-image:url(../flags/1x1/gt.svg)}.flag-icon-gu{background-image:url(../flags/4x3/gu.svg)}.flag-icon-gu.flag-icon-squared{background-image:url(../flags/1x1/gu.svg)}.flag-icon-gw{background-image:url(../flags/4x3/gw.svg)}.flag-icon-gw.flag-icon-squared{background-image:url(../flags/1x1/gw.svg)}.flag-icon-gy{background-image:url(../flags/4x3/gy.svg)}.flag-icon-gy.flag-icon-squared{background-image:url(../flags/1x1/gy.svg)}.flag-icon-hk{background-image:url(../flags/4x3/hk.svg)}.flag-icon-hk.flag-icon-squared{background-image:url(../flags/1x1/hk.svg)}.flag-icon-hm{background-image:url(../flags/4x3/hm.svg)}.flag-icon-hm.flag-icon-squared{background-image:url(../flags/1x1/hm.svg)}.flag-icon-hn{background-image:url(../flags/4x3/hn.svg)}.flag-icon-hn.flag-icon-squared{background-image:url(../flags/1x1/hn.svg)}.flag-icon-hr{background-image:url(../flags/4x3/hr.svg)}.flag-icon-hr.flag-icon-squared{background-image:url(../flags/1x1/hr.svg)}.flag-icon-ht{background-image:url(../flags/4x3/ht.svg)}.flag-icon-ht.flag-icon-squared{background-image:url(../flags/1x1/ht.svg)}.flag-icon-hu{background-image:url(../flags/4x3/hu.svg)}.flag-icon-hu.flag-icon-squared{background-image:url(../flags/1x1/hu.svg)}.flag-icon-id{background-image:url(../flags/4x3/id.svg)}.flag-icon-id.flag-icon-squared{background-image:url(../flags/1x1/id.svg)}.flag-icon-ie{background-image:url(../flags/4x3/ie.svg)}.flag-icon-ie.flag-icon-squared{background-image:url(../flags/1x1/ie.svg)}.flag-icon-il{background-image:url(../flags/4x3/il.svg)}.flag-icon-il.flag-icon-squared{background-image:url(../flags/1x1/il.svg)}.flag-icon-im{background-image:url(../flags/4x3/im.svg)}.flag-icon-im.flag-icon-squared{background-image:url(../flags/1x1/im.svg)}.flag-icon-in{background-image:url(../flags/4x3/in.svg)}.flag-icon-in.flag-icon-squared{background-image:url(../flags/1x1/in.svg)}.flag-icon-io{background-image:url(../flags/4x3/io.svg)}.flag-icon-io.flag-icon-squared{background-image:url(../flags/1x1/io.svg)}.flag-icon-iq{background-image:url(../flags/4x3/iq.svg)}.flag-icon-iq.flag-icon-squared{background-image:url(../flags/1x1/iq.svg)}.flag-icon-ir{background-image:url(../flags/4x3/ir.svg)}.flag-icon-ir.flag-icon-squared{background-image:url(../flags/1x1/ir.svg)}.flag-icon-is{background-image:url(../flags/4x3/is.svg)}.flag-icon-is.flag-icon-squared{background-image:url(../flags/1x1/is.svg)}.flag-icon-it{background-image:url(../flags/4x3/it.svg)}.flag-icon-it.flag-icon-squared{background-image:url(../flags/1x1/it.svg)}.flag-icon-je{background-image:url(../flags/4x3/je.svg)}.flag-icon-je.flag-icon-squared{background-image:url(../flags/1x1/je.svg)}.flag-icon-jm{background-image:url(../flags/4x3/jm.svg)}.flag-icon-jm.flag-icon-squared{background-image:url(../flags/1x1/jm.svg)}.flag-icon-jo{background-image:url(../flags/4x3/jo.svg)}.flag-icon-jo.flag-icon-squared{background-image:url(../flags/1x1/jo.svg)}.flag-icon-jp{background-image:url(../flags/4x3/jp.svg)}.flag-icon-jp.flag-icon-squared{background-image:url(../flags/1x1/jp.svg)}.flag-icon-ke{background-image:url(../flags/4x3/ke.svg)}.flag-icon-ke.flag-icon-squared{background-image:url(../flags/1x1/ke.svg)}.flag-icon-kg{background-image:url(../flags/4x3/kg.svg)}.flag-icon-kg.flag-icon-squared{background-image:url(../flags/1x1/kg.svg)}.flag-icon-kh{background-image:url(../flags/4x3/kh.svg)}.flag-icon-kh.flag-icon-squared{background-image:url(../flags/1x1/kh.svg)}.flag-icon-ki{background-image:url(../flags/4x3/ki.svg)}.flag-icon-ki.flag-icon-squared{background-image:url(../flags/1x1/ki.svg)}.flag-icon-km{background-image:url(../flags/4x3/km.svg)}.flag-icon-km.flag-icon-squared{background-image:url(../flags/1x1/km.svg)}.flag-icon-kn{background-image:url(../flags/4x3/kn.svg)}.flag-icon-kn.flag-icon-squared{background-image:url(../flags/1x1/kn.svg)}.flag-icon-kp{background-image:url(../flags/4x3/kp.svg)}.flag-icon-kp.flag-icon-squared{background-image:url(../flags/1x1/kp.svg)}.flag-icon-ko{background-image:url(../flags/4x3/ko.svg)}.flag-icon-ko.flag-icon-squared{background-image:url(../flags/1x1/ko.svg)}.flag-icon-kr{background-image:url(../flags/4x3/kr.svg)}.flag-icon-kr.flag-icon-squared{background-image:url(../flags/1x1/kr.svg)}.flag-icon-kw{background-image:url(../flags/4x3/kw.svg)}.flag-icon-kw.flag-icon-squared{background-image:url(../flags/1x1/kw.svg)}.flag-icon-ky{background-image:url(../flags/4x3/ky.svg)}.flag-icon-ky.flag-icon-squared{background-image:url(../flags/1x1/ky.svg)}.flag-icon-kz{background-image:url(../flags/4x3/kz.svg)}.flag-icon-kz.flag-icon-squared{background-image:url(../flags/1x1/kz.svg)}.flag-icon-la{background-image:url(../flags/4x3/la.svg)}.flag-icon-la.flag-icon-squared{background-image:url(../flags/1x1/la.svg)}.flag-icon-lb{background-image:url(../flags/4x3/lb.svg)}.flag-icon-lb.flag-icon-squared{background-image:url(../flags/1x1/lb.svg)}.flag-icon-lc{background-image:url(../flags/4x3/lc.svg)}.flag-icon-lc.flag-icon-squared{background-image:url(../flags/1x1/lc.svg)}.flag-icon-li{background-image:url(../flags/4x3/li.svg)}.flag-icon-li.flag-icon-squared{background-image:url(../flags/1x1/li.svg)}.flag-icon-lk{background-image:url(../flags/4x3/lk.svg)}.flag-icon-lk.flag-icon-squared{background-image:url(../flags/1x1/lk.svg)}.flag-icon-lr{background-image:url(../flags/4x3/lr.svg)}.flag-icon-lr.flag-icon-squared{background-image:url(../flags/1x1/lr.svg)}.flag-icon-ls{background-image:url(../flags/4x3/ls.svg)}.flag-icon-ls.flag-icon-squared{background-image:url(../flags/1x1/ls.svg)}.flag-icon-lt{background-image:url(../flags/4x3/lt.svg)}.flag-icon-lt.flag-icon-squared{background-image:url(../flags/1x1/lt.svg)}.flag-icon-lu{background-image:url(../flags/4x3/lu.svg)}.flag-icon-lu.flag-icon-squared{background-image:url(../flags/1x1/lu.svg)}.flag-icon-lv{background-image:url(../flags/4x3/lv.svg)}.flag-icon-lv.flag-icon-squared{background-image:url(../flags/1x1/lv.svg)}.flag-icon-ly{background-image:url(../flags/4x3/ly.svg)}.flag-icon-ly.flag-icon-squared{background-image:url(../flags/1x1/ly.svg)}.flag-icon-ma{background-image:url(../flags/4x3/ma.svg)}.flag-icon-ma.flag-icon-squared{background-image:url(../flags/1x1/ma.svg)}.flag-icon-mc{background-image:url(../flags/4x3/mc.svg)}.flag-icon-mc.flag-icon-squared{background-image:url(../flags/1x1/mc.svg)}.flag-icon-md{background-image:url(../flags/4x3/md.svg)}.flag-icon-md.flag-icon-squared{background-image:url(../flags/1x1/md.svg)}.flag-icon-me{background-image:url(../flags/4x3/me.svg)}.flag-icon-me.flag-icon-squared{background-image:url(../flags/1x1/me.svg)}.flag-icon-mf{background-image:url(../flags/4x3/mf.svg)}.flag-icon-mf.flag-icon-squared{background-image:url(../flags/1x1/mf.svg)}.flag-icon-mg{background-image:url(../flags/4x3/mg.svg)}.flag-icon-mg.flag-icon-squared{background-image:url(../flags/1x1/mg.svg)}.flag-icon-mh{background-image:url(../flags/4x3/mh.svg)}.flag-icon-mh.flag-icon-squared{background-image:url(../flags/1x1/mh.svg)}.flag-icon-mk{background-image:url(../flags/4x3/mk.svg)}.flag-icon-mk.flag-icon-squared{background-image:url(../flags/1x1/mk.svg)}.flag-icon-ml{background-image:url(../flags/4x3/ml.svg)}.flag-icon-ml.flag-icon-squared{background-image:url(../flags/1x1/ml.svg)}.flag-icon-mm{background-image:url(../flags/4x3/mm.svg)}.flag-icon-mm.flag-icon-squared{background-image:url(../flags/1x1/mm.svg)}.flag-icon-mn{background-image:url(../flags/4x3/mn.svg)}.flag-icon-mn.flag-icon-squared{background-image:url(../flags/1x1/mn.svg)}.flag-icon-mo{background-image:url(../flags/4x3/mo.svg)}.flag-icon-mo.flag-icon-squared{background-image:url(../flags/1x1/mo.svg)}.flag-icon-mp{background-image:url(../flags/4x3/mp.svg)}.flag-icon-mp.flag-icon-squared{background-image:url(../flags/1x1/mp.svg)}.flag-icon-mq{background-image:url(../flags/4x3/mq.svg)}.flag-icon-mq.flag-icon-squared{background-image:url(../flags/1x1/mq.svg)}.flag-icon-mr{background-image:url(../flags/4x3/mr.svg)}.flag-icon-mr.flag-icon-squared{background-image:url(../flags/1x1/mr.svg)}.flag-icon-ms{background-image:url(../flags/4x3/ms.svg)}.flag-icon-ms.flag-icon-squared{background-image:url(../flags/1x1/ms.svg)}.flag-icon-mt{background-image:url(../flags/4x3/mt.svg)}.flag-icon-mt.flag-icon-squared{background-image:url(../flags/1x1/mt.svg)}.flag-icon-mu{background-image:url(../flags/4x3/mu.svg)}.flag-icon-mu.flag-icon-squared{background-image:url(../flags/1x1/mu.svg)}.flag-icon-mv{background-image:url(../flags/4x3/mv.svg)}.flag-icon-mv.flag-icon-squared{background-image:url(../flags/1x1/mv.svg)}.flag-icon-mw{background-image:url(../flags/4x3/mw.svg)}.flag-icon-mw.flag-icon-squared{background-image:url(../flags/1x1/mw.svg)}.flag-icon-mx{background-image:url(../flags/4x3/mx.svg)}.flag-icon-mx.flag-icon-squared{background-image:url(../flags/1x1/mx.svg)}.flag-icon-my{background-image:url(../flags/4x3/my.svg)}.flag-icon-my.flag-icon-squared{background-image:url(../flags/1x1/my.svg)}.flag-icon-mz{background-image:url(../flags/4x3/mz.svg)}.flag-icon-mz.flag-icon-squared{background-image:url(../flags/1x1/mz.svg)}.flag-icon-na{background-image:url(../flags/4x3/na.svg)}.flag-icon-na.flag-icon-squared{background-image:url(../flags/1x1/na.svg)}.flag-icon-nc{background-image:url(../flags/4x3/nc.svg)}.flag-icon-nc.flag-icon-squared{background-image:url(../flags/1x1/nc.svg)}.flag-icon-ne{background-image:url(../flags/4x3/ne.svg)}.flag-icon-ne.flag-icon-squared{background-image:url(../flags/1x1/ne.svg)}.flag-icon-nf{background-image:url(../flags/4x3/nf.svg)}.flag-icon-nf.flag-icon-squared{background-image:url(../flags/1x1/nf.svg)}.flag-icon-ng{background-image:url(../flags/4x3/ng.svg)}.flag-icon-ng.flag-icon-squared{background-image:url(../flags/1x1/ng.svg)}.flag-icon-ni{background-image:url(../flags/4x3/ni.svg)}.flag-icon-ni.flag-icon-squared{background-image:url(../flags/1x1/ni.svg)}.flag-icon-nl{background-image:url(../flags/4x3/nl.svg)}.flag-icon-nl.flag-icon-squared{background-image:url(../flags/1x1/nl.svg)}.flag-icon-no{background-image:url(../flags/4x3/no.svg)}.flag-icon-no.flag-icon-squared{background-image:url(../flags/1x1/no.svg)}.flag-icon-np{background-image:url(../flags/4x3/np.svg)}.flag-icon-np.flag-icon-squared{background-image:url(../flags/1x1/np.svg)}.flag-icon-nr{background-image:url(../flags/4x3/nr.svg)}.flag-icon-nr.flag-icon-squared{background-image:url(../flags/1x1/nr.svg)}.flag-icon-nu{background-image:url(../flags/4x3/nu.svg)}.flag-icon-nu.flag-icon-squared{background-image:url(../flags/1x1/nu.svg)}.flag-icon-nz{background-image:url(../flags/4x3/nz.svg)}.flag-icon-nz.flag-icon-squared{background-image:url(../flags/1x1/nz.svg)}.flag-icon-om{background-image:url(../flags/4x3/om.svg)}.flag-icon-om.flag-icon-squared{background-image:url(../flags/1x1/om.svg)}.flag-icon-pa{background-image:url(../flags/4x3/pa.svg)}.flag-icon-pa.flag-icon-squared{background-image:url(../flags/1x1/pa.svg)}.flag-icon-pe{background-image:url(../flags/4x3/pe.svg)}.flag-icon-pe.flag-icon-squared{background-image:url(../flags/1x1/pe.svg)}.flag-icon-pf{background-image:url(../flags/4x3/pf.svg)}.flag-icon-pf.flag-icon-squared{background-image:url(../flags/1x1/pf.svg)}.flag-icon-pg{background-image:url(../flags/4x3/pg.svg)}.flag-icon-pg.flag-icon-squared{background-image:url(../flags/1x1/pg.svg)}.flag-icon-ph{background-image:url(../flags/4x3/ph.svg)}.flag-icon-ph.flag-icon-squared{background-image:url(../flags/1x1/ph.svg)}.flag-icon-pk{background-image:url(../flags/4x3/pk.svg)}.flag-icon-pk.flag-icon-squared{background-image:url(../flags/1x1/pk.svg)}.flag-icon-pl{background-image:url(../flags/4x3/pl.svg)}.flag-icon-pl.flag-icon-squared{background-image:url(../flags/1x1/pl.svg)}.flag-icon-pm{background-image:url(../flags/4x3/pm.svg)}.flag-icon-pm.flag-icon-squared{background-image:url(../flags/1x1/pm.svg)}.flag-icon-pn{background-image:url(../flags/4x3/pn.svg)}.flag-icon-pn.flag-icon-squared{background-image:url(../flags/1x1/pn.svg)}.flag-icon-pr{background-image:url(../flags/4x3/pr.svg)}.flag-icon-pr.flag-icon-squared{background-image:url(../flags/1x1/pr.svg)}.flag-icon-ps{background-image:url(../flags/4x3/ps.svg)}.flag-icon-ps.flag-icon-squared{background-image:url(../flags/1x1/ps.svg)}.flag-icon-pt{background-image:url(../flags/4x3/pt.svg)}.flag-icon-pt.flag-icon-squared{background-image:url(../flags/1x1/pt.svg)}.flag-icon-pw{background-image:url(../flags/4x3/pw.svg)}.flag-icon-pw.flag-icon-squared{background-image:url(../flags/1x1/pw.svg)}.flag-icon-py{background-image:url(../flags/4x3/py.svg)}.flag-icon-py.flag-icon-squared{background-image:url(../flags/1x1/py.svg)}.flag-icon-qa{background-image:url(../flags/4x3/qa.svg)}.flag-icon-qa.flag-icon-squared{background-image:url(../flags/1x1/qa.svg)}.flag-icon-re{background-image:url(../flags/4x3/re.svg)}.flag-icon-re.flag-icon-squared{background-image:url(../flags/1x1/re.svg)}.flag-icon-ro{background-image:url(../flags/4x3/ro.svg)}.flag-icon-ro.flag-icon-squared{background-image:url(../flags/1x1/ro.svg)}.flag-icon-rs{background-image:url(../flags/4x3/rs.svg)}.flag-icon-rs.flag-icon-squared{background-image:url(../flags/1x1/rs.svg)}.flag-icon-ru{background-image:url(../flags/4x3/ru.svg)}.flag-icon-ru.flag-icon-squared{background-image:url(../flags/1x1/ru.svg)}.flag-icon-rw{background-image:url(../flags/4x3/rw.svg)}.flag-icon-rw.flag-icon-squared{background-image:url(../flags/1x1/rw.svg)}.flag-icon-sa{background-image:url(../flags/4x3/sa.svg)}.flag-icon-sa.flag-icon-squared{background-image:url(../flags/1x1/sa.svg)}.flag-icon-sb{background-image:url(../flags/4x3/sb.svg)}.flag-icon-sb.flag-icon-squared{background-image:url(../flags/1x1/sb.svg)}.flag-icon-sc{background-image:url(../flags/4x3/sc.svg)}.flag-icon-sc.flag-icon-squared{background-image:url(../flags/1x1/sc.svg)}.flag-icon-sd{background-image:url(../flags/4x3/sd.svg)}.flag-icon-sd.flag-icon-squared{background-image:url(../flags/1x1/sd.svg)}.flag-icon-se{background-image:url(../flags/4x3/se.svg)}.flag-icon-se.flag-icon-squared{background-image:url(../flags/1x1/se.svg)}.flag-icon-sg{background-image:url(../flags/4x3/sg.svg)}.flag-icon-sg.flag-icon-squared{background-image:url(../flags/1x1/sg.svg)}.flag-icon-sh{background-image:url(../flags/4x3/sh.svg)}.flag-icon-sh.flag-icon-squared{background-image:url(../flags/1x1/sh.svg)}.flag-icon-si{background-image:url(../flags/4x3/si.svg)}.flag-icon-si.flag-icon-squared{background-image:url(../flags/1x1/si.svg)}.flag-icon-sj{background-image:url(../flags/4x3/sj.svg)}.flag-icon-sj.flag-icon-squared{background-image:url(../flags/1x1/sj.svg)}.flag-icon-sk{background-image:url(../flags/4x3/sk.svg)}.flag-icon-sk.flag-icon-squared{background-image:url(../flags/1x1/sk.svg)}.flag-icon-sl{background-image:url(../flags/4x3/sl.svg)}.flag-icon-sl.flag-icon-squared{background-image:url(../flags/1x1/sl.svg)}.flag-icon-sm{background-image:url(../flags/4x3/sm.svg)}.flag-icon-sm.flag-icon-squared{background-image:url(../flags/1x1/sm.svg)}.flag-icon-sn{background-image:url(../flags/4x3/sn.svg)}.flag-icon-sn.flag-icon-squared{background-image:url(../flags/1x1/sn.svg)}.flag-icon-so{background-image:url(../flags/4x3/so.svg)}.flag-icon-so.flag-icon-squared{background-image:url(../flags/1x1/so.svg)}.flag-icon-sr{background-image:url(../flags/4x3/sr.svg)}.flag-icon-sr.flag-icon-squared{background-image:url(../flags/1x1/sr.svg)}.flag-icon-ss{background-image:url(../flags/4x3/ss.svg)}.flag-icon-ss.flag-icon-squared{background-image:url(../flags/1x1/ss.svg)}.flag-icon-st{background-image:url(../flags/4x3/st.svg)}.flag-icon-st.flag-icon-squared{background-image:url(../flags/1x1/st.svg)}.flag-icon-sv{background-image:url(../flags/4x3/sv.svg)}.flag-icon-sv.flag-icon-squared{background-image:url(../flags/1x1/sv.svg)}.flag-icon-sx{background-image:url(../flags/4x3/sx.svg)}.flag-icon-sx.flag-icon-squared{background-image:url(../flags/1x1/sx.svg)}.flag-icon-sy{background-image:url(../flags/4x3/sy.svg)}.flag-icon-sy.flag-icon-squared{background-image:url(../flags/1x1/sy.svg)}.flag-icon-sz{background-image:url(../flags/4x3/sz.svg)}.flag-icon-sz.flag-icon-squared{background-image:url(../flags/1x1/sz.svg)}.flag-icon-tc{background-image:url(../flags/4x3/tc.svg)}.flag-icon-tc.flag-icon-squared{background-image:url(../flags/1x1/tc.svg)}.flag-icon-td{background-image:url(../flags/4x3/td.svg)}.flag-icon-td.flag-icon-squared{background-image:url(../flags/1x1/td.svg)}.flag-icon-tf{background-image:url(../flags/4x3/tf.svg)}.flag-icon-tf.flag-icon-squared{background-image:url(../flags/1x1/tf.svg)}.flag-icon-tg{background-image:url(../flags/4x3/tg.svg)}.flag-icon-tg.flag-icon-squared{background-image:url(../flags/1x1/tg.svg)}.flag-icon-th{background-image:url(../flags/4x3/th.svg)}.flag-icon-th.flag-icon-squared{background-image:url(../flags/1x1/th.svg)}.flag-icon-tj{background-image:url(../flags/4x3/tj.svg)}.flag-icon-tj.flag-icon-squared{background-image:url(../flags/1x1/tj.svg)}.flag-icon-tk{background-image:url(../flags/4x3/tk.svg)}.flag-icon-tk.flag-icon-squared{background-image:url(../flags/1x1/tk.svg)}.flag-icon-tl{background-image:url(../flags/4x3/tl.svg)}.flag-icon-tl.flag-icon-squared{background-image:url(../flags/1x1/tl.svg)}.flag-icon-tm{background-image:url(../flags/4x3/tm.svg)}.flag-icon-tm.flag-icon-squared{background-image:url(../flags/1x1/tm.svg)}.flag-icon-tn{background-image:url(../flags/4x3/tn.svg)}.flag-icon-tn.flag-icon-squared{background-image:url(../flags/1x1/tn.svg)}.flag-icon-to{background-image:url(../flags/4x3/to.svg)}.flag-icon-to.flag-icon-squared{background-image:url(../flags/1x1/to.svg)}.flag-icon-tr{background-image:url(../flags/4x3/tr.svg)}.flag-icon-tr.flag-icon-squared{background-image:url(../flags/1x1/tr.svg)}.flag-icon-tt{background-image:url(../flags/4x3/tt.svg)}.flag-icon-tt.flag-icon-squared{background-image:url(../flags/1x1/tt.svg)}.flag-icon-tv{background-image:url(../flags/4x3/tv.svg)}.flag-icon-tv.flag-icon-squared{background-image:url(../flags/1x1/tv.svg)}.flag-icon-tw{background-image:url(../flags/4x3/tw.svg)}.flag-icon-tw.flag-icon-squared{background-image:url(../flags/1x1/tw.svg)}.flag-icon-tz{background-image:url(../flags/4x3/tz.svg)}.flag-icon-tz.flag-icon-squared{background-image:url(../flags/1x1/tz.svg)}.flag-icon-ua{background-image:url(../flags/4x3/ua.svg)}.flag-icon-ua.flag-icon-squared{background-image:url(../flags/1x1/ua.svg)}.flag-icon-ug{background-image:url(../flags/4x3/ug.svg)}.flag-icon-ug.flag-icon-squared{background-image:url(../flags/1x1/ug.svg)}.flag-icon-um{background-image:url(../flags/4x3/um.svg)}.flag-icon-um.flag-icon-squared{background-image:url(../flags/1x1/um.svg)}.flag-icon-us{background-image:url(../flags/4x3/us.svg)}.flag-icon-us.flag-icon-squared{background-image:url(../flags/1x1/us.svg)}.flag-icon-uy{background-image:url(../flags/4x3/uy.svg)}.flag-icon-uy.flag-icon-squared{background-image:url(../flags/1x1/uy.svg)}.flag-icon-uz{background-image:url(../flags/4x3/uz.svg)}.flag-icon-uz.flag-icon-squared{background-image:url(../flags/1x1/uz.svg)}.flag-icon-va{background-image:url(../flags/4x3/va.svg)}.flag-icon-va.flag-icon-squared{background-image:url(../flags/1x1/va.svg)}.flag-icon-vc{background-image:url(../flags/4x3/vc.svg)}.flag-icon-vc.flag-icon-squared{background-image:url(../flags/1x1/vc.svg)}.flag-icon-ve{background-image:url(../flags/4x3/ve.svg)}.flag-icon-ve.flag-icon-squared{background-image:url(../flags/1x1/ve.svg)}.flag-icon-vg{background-image:url(../flags/4x3/vg.svg)}.flag-icon-vg.flag-icon-squared{background-image:url(../flags/1x1/vg.svg)}.flag-icon-vi{background-image:url(../flags/4x3/vi.svg)}.flag-icon-vi.flag-icon-squared{background-image:url(../flags/1x1/vi.svg)}.flag-icon-vn{background-image:url(../flags/4x3/vn.svg)}.flag-icon-vn.flag-icon-squared{background-image:url(../flags/1x1/vn.svg)}.flag-icon-vu{background-image:url(../flags/4x3/vu.svg)}.flag-icon-vu.flag-icon-squared{background-image:url(../flags/1x1/vu.svg)}.flag-icon-wf{background-image:url(../flags/4x3/wf.svg)}.flag-icon-wf.flag-icon-squared{background-image:url(../flags/1x1/wf.svg)}.flag-icon-ws{background-image:url(../flags/4x3/ws.svg)}.flag-icon-ws.flag-icon-squared{background-image:url(../flags/1x1/ws.svg)}.flag-icon-ye{background-image:url(../flags/4x3/ye.svg)}.flag-icon-ye.flag-icon-squared{background-image:url(../flags/1x1/ye.svg)}.flag-icon-yt{background-image:url(../flags/4x3/yt.svg)}.flag-icon-yt.flag-icon-squared{background-image:url(../flags/1x1/yt.svg)}.flag-icon-za{background-image:url(../flags/4x3/za.svg)}.flag-icon-za.flag-icon-squared{background-image:url(../flags/1x1/za.svg)}.flag-icon-zm{background-image:url(../flags/4x3/zm.svg)}.flag-icon-zm.flag-icon-squared{background-image:url(../flags/1x1/zm.svg)}.flag-icon-zw{background-image:url(../flags/4x3/zw.svg)}.flag-icon-zw.flag-icon-squared{background-image:url(../flags/1x1/zw.svg)}.flag-icon-es-ct{background-image:url(../flags/4x3/es-ct.svg)}.flag-icon-es-ct.flag-icon-squared{background-image:url(../flags/1x1/es-ct.svg)}.flag-icon-es-ga{background-image:url(../flags/4x3/es-ga.svg)}.flag-icon-es-ga.flag-icon-squared{background-image:url(../flags/1x1/es-ga.svg)}.flag-icon-eu{background-image:url(../flags/4x3/eu.svg)}.flag-icon-eu.flag-icon-squared{background-image:url(../flags/1x1/eu.svg)}.flag-icon-gb-eng{background-image:url(../flags/4x3/gb-eng.svg)}.flag-icon-gb-eng.flag-icon-squared{background-image:url(../flags/1x1/gb-eng.svg)}.flag-icon-gb-nir{background-image:url(../flags/4x3/gb-nir.svg)}.flag-icon-gb-nir.flag-icon-squared{background-image:url(../flags/1x1/gb-nir.svg)}.flag-icon-gb-sct{background-image:url(../flags/4x3/gb-sct.svg)}.flag-icon-gb-sct.flag-icon-squared{background-image:url(../flags/1x1/gb-sct.svg)}.flag-icon-gb-wls{background-image:url(../flags/4x3/gb-wls.svg)}.flag-icon-gb-wls.flag-icon-squared{background-image:url(../flags/1x1/gb-wls.svg)}.flag-icon-un{background-image:url(../flags/4x3/un.svg)}.flag-icon-un.flag-icon-squared{background-image:url(../flags/1x1/un.svg)}.flag-icon-xk{background-image:url(../flags/4x3/xk.svg)}.flag-icon-xk.flag-icon-squared{background-image:url(../flags/1x1/xk.svg)} +.flag-icon-background{background-size:contain;background-position:50%;background-repeat:no-repeat}.flag-icon{background-size:contain;background-position:50%;background-repeat:no-repeat;position:relative;display:inline-block;width:1.33333333em;line-height:1em}.flag-icon:before{content:'\00a0'}.flag-icon.flag-icon-squared{width:1em}.flag-icon-ad{background-image:url(/css/flags/4x3/ad.svg)}.flag-icon-ad.flag-icon-squared{background-image:url(/css/flags/1x1/ad.svg)}.flag-icon-ae{background-image:url(/css/flags/4x3/ae.svg)}.flag-icon-ae.flag-icon-squared{background-image:url(/css/flags/1x1/ae.svg)}.flag-icon-af{background-image:url(/css/flags/4x3/af.svg)}.flag-icon-af.flag-icon-squared{background-image:url(/css/flags/1x1/af.svg)}.flag-icon-ag{background-image:url(/css/flags/4x3/ag.svg)}.flag-icon-ag.flag-icon-squared{background-image:url(/css/flags/1x1/ag.svg)}.flag-icon-ai{background-image:url(/css/flags/4x3/ai.svg)}.flag-icon-ai.flag-icon-squared{background-image:url(/css/flags/1x1/ai.svg)}.flag-icon-al{background-image:url(/css/flags/4x3/al.svg)}.flag-icon-al.flag-icon-squared{background-image:url(/css/flags/1x1/al.svg)}.flag-icon-am{background-image:url(/css/flags/4x3/am.svg)}.flag-icon-am.flag-icon-squared{background-image:url(/css/flags/1x1/am.svg)}.flag-icon-ao{background-image:url(/css/flags/4x3/ao.svg)}.flag-icon-ao.flag-icon-squared{background-image:url(/css/flags/1x1/ao.svg)}.flag-icon-aq{background-image:url(/css/flags/4x3/aq.svg)}.flag-icon-aq.flag-icon-squared{background-image:url(/css/flags/1x1/aq.svg)}.flag-icon-ar{background-image:url(/css/flags/4x3/ar.svg)}.flag-icon-ar.flag-icon-squared{background-image:url(/css/flags/1x1/ar.svg)}.flag-icon-as{background-image:url(/css/flags/4x3/as.svg)}.flag-icon-as.flag-icon-squared{background-image:url(/css/flags/1x1/as.svg)}.flag-icon-at{background-image:url(/css/flags/4x3/at.svg)}.flag-icon-at.flag-icon-squared{background-image:url(/css/flags/1x1/at.svg)}.flag-icon-au{background-image:url(/css/flags/4x3/au.svg)}.flag-icon-au.flag-icon-squared{background-image:url(/css/flags/1x1/au.svg)}.flag-icon-aw{background-image:url(/css/flags/4x3/aw.svg)}.flag-icon-aw.flag-icon-squared{background-image:url(/css/flags/1x1/aw.svg)}.flag-icon-ax{background-image:url(/css/flags/4x3/ax.svg)}.flag-icon-ax.flag-icon-squared{background-image:url(/css/flags/1x1/ax.svg)}.flag-icon-az{background-image:url(/css/flags/4x3/az.svg)}.flag-icon-az.flag-icon-squared{background-image:url(/css/flags/1x1/az.svg)}.flag-icon-ba{background-image:url(/css/flags/4x3/ba.svg)}.flag-icon-ba.flag-icon-squared{background-image:url(/css/flags/1x1/ba.svg)}.flag-icon-bb{background-image:url(/css/flags/4x3/bb.svg)}.flag-icon-bb.flag-icon-squared{background-image:url(/css/flags/1x1/bb.svg)}.flag-icon-bd{background-image:url(/css/flags/4x3/bd.svg)}.flag-icon-bd.flag-icon-squared{background-image:url(/css/flags/1x1/bd.svg)}.flag-icon-be{background-image:url(/css/flags/4x3/be.svg)}.flag-icon-be.flag-icon-squared{background-image:url(/css/flags/1x1/be.svg)}.flag-icon-bf{background-image:url(/css/flags/4x3/bf.svg)}.flag-icon-bf.flag-icon-squared{background-image:url(/css/flags/1x1/bf.svg)}.flag-icon-bg{background-image:url(/css/flags/4x3/bg.svg)}.flag-icon-bg.flag-icon-squared{background-image:url(/css/flags/1x1/bg.svg)}.flag-icon-bh{background-image:url(/css/flags/4x3/bh.svg)}.flag-icon-bh.flag-icon-squared{background-image:url(/css/flags/1x1/bh.svg)}.flag-icon-bi{background-image:url(/css/flags/4x3/bi.svg)}.flag-icon-bi.flag-icon-squared{background-image:url(/css/flags/1x1/bi.svg)}.flag-icon-bj{background-image:url(/css/flags/4x3/bj.svg)}.flag-icon-bj.flag-icon-squared{background-image:url(/css/flags/1x1/bj.svg)}.flag-icon-bl{background-image:url(/css/flags/4x3/bl.svg)}.flag-icon-bl.flag-icon-squared{background-image:url(/css/flags/1x1/bl.svg)}.flag-icon-bm{background-image:url(/css/flags/4x3/bm.svg)}.flag-icon-bm.flag-icon-squared{background-image:url(/css/flags/1x1/bm.svg)}.flag-icon-bn{background-image:url(/css/flags/4x3/bn.svg)}.flag-icon-bn.flag-icon-squared{background-image:url(/css/flags/1x1/bn.svg)}.flag-icon-bo{background-image:url(/css/flags/4x3/bo.svg)}.flag-icon-bo.flag-icon-squared{background-image:url(/css/flags/1x1/bo.svg)}.flag-icon-bq{background-image:url(/css/flags/4x3/bq.svg)}.flag-icon-bq.flag-icon-squared{background-image:url(/css/flags/1x1/bq.svg)}.flag-icon-br{background-image:url(/css/flags/4x3/br.svg)}.flag-icon-br.flag-icon-squared{background-image:url(/css/flags/1x1/br.svg)}.flag-icon-bs{background-image:url(/css/flags/4x3/bs.svg)}.flag-icon-bs.flag-icon-squared{background-image:url(/css/flags/1x1/bs.svg)}.flag-icon-bt{background-image:url(/css/flags/4x3/bt.svg)}.flag-icon-bt.flag-icon-squared{background-image:url(/css/flags/1x1/bt.svg)}.flag-icon-bv{background-image:url(/css/flags/4x3/bv.svg)}.flag-icon-bv.flag-icon-squared{background-image:url(/css/flags/1x1/bv.svg)}.flag-icon-bw{background-image:url(/css/flags/4x3/bw.svg)}.flag-icon-bw.flag-icon-squared{background-image:url(/css/flags/1x1/bw.svg)}.flag-icon-by{background-image:url(/css/flags/4x3/by.svg)}.flag-icon-by.flag-icon-squared{background-image:url(/css/flags/1x1/by.svg)}.flag-icon-bz{background-image:url(/css/flags/4x3/bz.svg)}.flag-icon-bz.flag-icon-squared{background-image:url(/css/flags/1x1/bz.svg)}.flag-icon-ca{background-image:url(/css/flags/4x3/ca.svg)}.flag-icon-ca.flag-icon-squared{background-image:url(/css/flags/1x1/ca.svg)}.flag-icon-cc{background-image:url(/css/flags/4x3/cc.svg)}.flag-icon-cc.flag-icon-squared{background-image:url(/css/flags/1x1/cc.svg)}.flag-icon-cd{background-image:url(/css/flags/4x3/cd.svg)}.flag-icon-cd.flag-icon-squared{background-image:url(/css/flags/1x1/cd.svg)}.flag-icon-cf{background-image:url(/css/flags/4x3/cf.svg)}.flag-icon-cf.flag-icon-squared{background-image:url(/css/flags/1x1/cf.svg)}.flag-icon-cg{background-image:url(/css/flags/4x3/cg.svg)}.flag-icon-cg.flag-icon-squared{background-image:url(/css/flags/1x1/cg.svg)}.flag-icon-ch{background-image:url(/css/flags/4x3/ch.svg)}.flag-icon-ch.flag-icon-squared{background-image:url(/css/flags/1x1/ch.svg)}.flag-icon-ci{background-image:url(/css/flags/4x3/ci.svg)}.flag-icon-ci.flag-icon-squared{background-image:url(/css/flags/1x1/ci.svg)}.flag-icon-ck{background-image:url(/css/flags/4x3/ck.svg)}.flag-icon-ck.flag-icon-squared{background-image:url(/css/flags/1x1/ck.svg)}.flag-icon-cl{background-image:url(/css/flags/4x3/cl.svg)}.flag-icon-cl.flag-icon-squared{background-image:url(/css/flags/1x1/cl.svg)}.flag-icon-cm{background-image:url(/css/flags/4x3/cm.svg)}.flag-icon-cm.flag-icon-squared{background-image:url(/css/flags/1x1/cm.svg)}.flag-icon-zh{background-image:url(/css/flags/4x3/zh.svg)}.flag-iconzh.flag-icon-squared{background-image:url(/css/flags/1x1/zh.svg)}.flag-icon-cn{background-image:url(/css/flags/4x3/cn.svg)}.flag-icon-cn.flag-icon-squared{background-image:url(/css/flags/1x1/cn.svg)}.flag-icon-co{background-image:url(/css/flags/4x3/co.svg)}.flag-icon-co.flag-icon-squared{background-image:url(/css/flags/1x1/co.svg)}.flag-icon-cr{background-image:url(/css/flags/4x3/cr.svg)}.flag-icon-cr.flag-icon-squared{background-image:url(/css/flags/1x1/cr.svg)}.flag-icon-cu{background-image:url(/css/flags/4x3/cu.svg)}.flag-icon-cu.flag-icon-squared{background-image:url(/css/flags/1x1/cu.svg)}.flag-icon-cv{background-image:url(/css/flags/4x3/cv.svg)}.flag-icon-cv.flag-icon-squared{background-image:url(/css/flags/1x1/cv.svg)}.flag-icon-cw{background-image:url(/css/flags/4x3/cw.svg)}.flag-icon-cw.flag-icon-squared{background-image:url(/css/flags/1x1/cw.svg)}.flag-icon-cx{background-image:url(/css/flags/4x3/cx.svg)}.flag-icon-cx.flag-icon-squared{background-image:url(/css/flags/1x1/cx.svg)}.flag-icon-cy{background-image:url(/css/flags/4x3/cy.svg)}.flag-icon-cy.flag-icon-squared{background-image:url(/css/flags/1x1/cy.svg)}.flag-icon-cz{background-image:url(/css/flags/4x3/cz.svg)}.flag-icon-cz.flag-icon-squared{background-image:url(/css/flags/1x1/cz.svg)}.flag-icon-cs{background-image:url(/css/flags/4x3/cs.svg)}.flag-icon-cs.flag-icon-squared{background-image:url(/css/flags/1x1/cs.svg)}.flag-icon-de{background-image:url(/css/flags/4x3/de.svg)}.flag-icon-de.flag-icon-squared{background-image:url(/css/flags/1x1/de.svg)}.flag-icon-dj{background-image:url(/css/flags/4x3/dj.svg)}.flag-icon-dj.flag-icon-squared{background-image:url(/css/flags/1x1/dj.svg)}.flag-icon-da{background-image:url(/css/flags/4x3/da.svg)}.flag-icon-da.flag-icon-squared{background-image:url(/css/flags/1x1/d.svg)}.flag-icon-dk{background-image:url(/css/flags/4x3/dk.svg)}.flag-icon-dk.flag-icon-squared{background-image:url(/css/flags/1x1/dk.svg)}.flag-icon-dm{background-image:url(/css/flags/4x3/dm.svg)}.flag-icon-dm.flag-icon-squared{background-image:url(/css/flags/1x1/dm.svg)}.flag-icon-do{background-image:url(/css/flags/4x3/do.svg)}.flag-icon-do.flag-icon-squared{background-image:url(/css/flags/1x1/do.svg)}.flag-icon-dz{background-image:url(/css/flags/4x3/dz.svg)}.flag-icon-dz.flag-icon-squared{background-image:url(/css/flags/1x1/dz.svg)}.flag-icon-ec{background-image:url(/css/flags/4x3/ec.svg)}.flag-icon-ec.flag-icon-squared{background-image:url(/css/flags/1x1/ec.svg)}.flag-icon-ee{background-image:url(/css/flags/4x3/ee.svg)}.flag-icon-ee.flag-icon-squared{background-image:url(/css/flags/1x1/ee.svg)}.flag-icon-eg{background-image:url(/css/flags/4x3/eg.svg)}.flag-icon-eg.flag-icon-squared{background-image:url(/css/flags/1x1/eg.svg)}.flag-icon-eh{background-image:url(/css/flags/4x3/eh.svg)}.flag-icon-eh.flag-icon-squared{background-image:url(/css/flags/1x1/eh.svg)}.flag-icon-er{background-image:url(/css/flags/4x3/er.svg)}.flag-icon-er.flag-icon-squared{background-image:url(/css/flags/1x1/er.svg)}.flag-icon-es{background-image:url(/css/flags/4x3/es.svg)}.flag-icon-es.flag-icon-squared{background-image:url(/css/flags/1x1/es.svg)}.flag-icon-et{background-image:url(/css/flags/4x3/et.svg)}.flag-icon-et.flag-icon-squared{background-image:url(/css/flags/1x1/et.svg)}.flag-icon-fi{background-image:url(/css/flags/4x3/fi.svg)}.flag-icon-fi.flag-icon-squared{background-image:url(/css/flags/1x1/fi.svg)}.flag-icon-fj{background-image:url(/css/flags/4x3/fj.svg)}.flag-icon-fj.flag-icon-squared{background-image:url(/css/flags/1x1/fj.svg)}.flag-icon-fk{background-image:url(/css/flags/4x3/fk.svg)}.flag-icon-fk.flag-icon-squared{background-image:url(/css/flags/1x1/fk.svg)}.flag-icon-fm{background-image:url(/css/flags/4x3/fm.svg)}.flag-icon-fm.flag-icon-squared{background-image:url(/css/flags/1x1/fm.svg)}.flag-icon-fo{background-image:url(/css/flags/4x3/fo.svg)}.flag-icon-fo.flag-icon-squared{background-image:url(/css/flags/1x1/fo.svg)}.flag-icon-fr{background-image:url(/css/flags/4x3/fr.svg)}.flag-icon-fr.flag-icon-squared{background-image:url(/css/flags/1x1/fr.svg)}.flag-icon-ga{background-image:url(/css/flags/4x3/ga.svg)}.flag-icon-ga.flag-icon-squared{background-image:url(/css/flags/1x1/ga.svg)}.flag-icon-gb{background-image:url(/css/flags/4x3/en.svg)}.flag-icon-gb.flag-icon-squared{background-image:url(/css/flags/1x1/en.svg)}.flag-icon-gd{background-image:url(/css/flags/4x3/gd.svg)}.flag-icon-gd.flag-icon-squared{background-image:url(/css/flags/1x1/gd.svg)}.flag-icon-ge{background-image:url(/css/flags/4x3/ge.svg)}.flag-icon-ge.flag-icon-squared{background-image:url(/css/flags/1x1/ge.svg)}.flag-icon-gf{background-image:url(/css/flags/4x3/gf.svg)}.flag-icon-gf.flag-icon-squared{background-image:url(/css/flags/1x1/gf.svg)}.flag-icon-gg{background-image:url(/css/flags/4x3/gg.svg)}.flag-icon-gg.flag-icon-squared{background-image:url(/css/flags/1x1/gg.svg)}.flag-icon-gh{background-image:url(/css/flags/4x3/gh.svg)}.flag-icon-gh.flag-icon-squared{background-image:url(/css/flags/1x1/gh.svg)}.flag-icon-gi{background-image:url(/css/flags/4x3/gi.svg)}.flag-icon-gi.flag-icon-squared{background-image:url(/css/flags/1x1/gi.svg)}.flag-icon-gl{background-image:url(/css/flags/4x3/gl.svg)}.flag-icon-gl.flag-icon-squared{background-image:url(/css/flags/1x1/gl.svg)}.flag-icon-gm{background-image:url(/css/flags/4x3/gm.svg)}.flag-icon-gm.flag-icon-squared{background-image:url(/css/flags/1x1/gm.svg)}.flag-icon-gn{background-image:url(/css/flags/4x3/gn.svg)}.flag-icon-gn.flag-icon-squared{background-image:url(/css/flags/1x1/gn.svg)}.flag-icon-gp{background-image:url(/css/flags/4x3/gp.svg)}.flag-icon-gp.flag-icon-squared{background-image:url(/css/flags/1x1/gp.svg)}.flag-icon-gq{background-image:url(/css/flags/4x3/gq.svg)}.flag-icon-gq.flag-icon-squared{background-image:url(/css/flags/1x1/gq.svg)}.flag-icon-gr{background-image:url(/css/flags/4x3/gr.svg)}.flag-icon-gr.flag-icon-squared{background-image:url(/css/flags/1x1/gr.svg)}.flag-icon-gs{background-image:url(/css/flags/4x3/gs.svg)}.flag-icon-gs.flag-icon-squared{background-image:url(/css/flags/1x1/gs.svg)}.flag-icon-gt{background-image:url(/css/flags/4x3/gt.svg)}.flag-icon-gt.flag-icon-squared{background-image:url(/css/flags/1x1/gt.svg)}.flag-icon-gu{background-image:url(/css/flags/4x3/gu.svg)}.flag-icon-gu.flag-icon-squared{background-image:url(/css/flags/1x1/gu.svg)}.flag-icon-gw{background-image:url(/css/flags/4x3/gw.svg)}.flag-icon-gw.flag-icon-squared{background-image:url(/css/flags/1x1/gw.svg)}.flag-icon-gy{background-image:url(/css/flags/4x3/gy.svg)}.flag-icon-gy.flag-icon-squared{background-image:url(/css/flags/1x1/gy.svg)}.flag-icon-hk{background-image:url(/css/flags/4x3/hk.svg)}.flag-icon-hk.flag-icon-squared{background-image:url(/css/flags/1x1/hk.svg)}.flag-icon-hm{background-image:url(/css/flags/4x3/hm.svg)}.flag-icon-hm.flag-icon-squared{background-image:url(/css/flags/1x1/hm.svg)}.flag-icon-hn{background-image:url(/css/flags/4x3/hn.svg)}.flag-icon-hn.flag-icon-squared{background-image:url(/css/flags/1x1/hn.svg)}.flag-icon-hr{background-image:url(/css/flags/4x3/hr.svg)}.flag-icon-hr.flag-icon-squared{background-image:url(/css/flags/1x1/hr.svg)}.flag-icon-ht{background-image:url(/css/flags/4x3/ht.svg)}.flag-icon-ht.flag-icon-squared{background-image:url(/css/flags/1x1/ht.svg)}.flag-icon-hu{background-image:url(/css/flags/4x3/hu.svg)}.flag-icon-hu.flag-icon-squared{background-image:url(/css/flags/1x1/hu.svg)}.flag-icon-id{background-image:url(/css/flags/4x3/id.svg)}.flag-icon-id.flag-icon-squared{background-image:url(/css/flags/1x1/id.svg)}.flag-icon-ie{background-image:url(/css/flags/4x3/ie.svg)}.flag-icon-ie.flag-icon-squared{background-image:url(/css/flags/1x1/ie.svg)}.flag-icon-il{background-image:url(/css/flags/4x3/il.svg)}.flag-icon-il.flag-icon-squared{background-image:url(/css/flags/1x1/il.svg)}.flag-icon-im{background-image:url(/css/flags/4x3/im.svg)}.flag-icon-im.flag-icon-squared{background-image:url(/css/flags/1x1/im.svg)}.flag-icon-in{background-image:url(/css/flags/4x3/in.svg)}.flag-icon-in.flag-icon-squared{background-image:url(/css/flags/1x1/in.svg)}.flag-icon-io{background-image:url(/css/flags/4x3/io.svg)}.flag-icon-io.flag-icon-squared{background-image:url(/css/flags/1x1/io.svg)}.flag-icon-iq{background-image:url(/css/flags/4x3/iq.svg)}.flag-icon-iq.flag-icon-squared{background-image:url(/css/flags/1x1/iq.svg)}.flag-icon-ir{background-image:url(/css/flags/4x3/ir.svg)}.flag-icon-ir.flag-icon-squared{background-image:url(/css/flags/1x1/ir.svg)}.flag-icon-is{background-image:url(/css/flags/4x3/is.svg)}.flag-icon-is.flag-icon-squared{background-image:url(/css/flags/1x1/is.svg)}.flag-icon-it{background-image:url(/css/flags/4x3/it.svg)}.flag-icon-it.flag-icon-squared{background-image:url(/css/flags/1x1/it.svg)}.flag-icon-je{background-image:url(/css/flags/4x3/je.svg)}.flag-icon-je.flag-icon-squared{background-image:url(/css/flags/1x1/je.svg)}.flag-icon-jm{background-image:url(/css/flags/4x3/jm.svg)}.flag-icon-jm.flag-icon-squared{background-image:url(/css/flags/1x1/jm.svg)}.flag-icon-jo{background-image:url(/css/flags/4x3/jo.svg)}.flag-icon-jo.flag-icon-squared{background-image:url(/css/flags/1x1/jo.svg)}.flag-icon-jp{background-image:url(/css/flags/4x3/jp.svg)}.flag-icon-jp.flag-icon-squared{background-image:url(/css/flags/1x1/jp.svg)}.flag-icon-ke{background-image:url(/css/flags/4x3/ke.svg)}.flag-icon-ke.flag-icon-squared{background-image:url(/css/flags/1x1/ke.svg)}.flag-icon-kg{background-image:url(/css/flags/4x3/kg.svg)}.flag-icon-kg.flag-icon-squared{background-image:url(/css/flags/1x1/kg.svg)}.flag-icon-kh{background-image:url(/css/flags/4x3/kh.svg)}.flag-icon-kh.flag-icon-squared{background-image:url(/css/flags/1x1/kh.svg)}.flag-icon-ki{background-image:url(/css/flags/4x3/ki.svg)}.flag-icon-ki.flag-icon-squared{background-image:url(/css/flags/1x1/ki.svg)}.flag-icon-km{background-image:url(/css/flags/4x3/km.svg)}.flag-icon-km.flag-icon-squared{background-image:url(/css/flags/1x1/km.svg)}.flag-icon-kn{background-image:url(/css/flags/4x3/kn.svg)}.flag-icon-kn.flag-icon-squared{background-image:url(/css/flags/1x1/kn.svg)}.flag-icon-kp{background-image:url(/css/flags/4x3/kp.svg)}.flag-icon-kp.flag-icon-squared{background-image:url(/css/flags/1x1/kp.svg)}.flag-icon-ko{background-image:url(/css/flags/4x3/ko.svg)}.flag-icon-ko.flag-icon-squared{background-image:url(/css/flags/1x1/ko.svg)}.flag-icon-kr{background-image:url(/css/flags/4x3/kr.svg)}.flag-icon-kr.flag-icon-squared{background-image:url(/css/flags/1x1/kr.svg)}.flag-icon-kw{background-image:url(/css/flags/4x3/kw.svg)}.flag-icon-kw.flag-icon-squared{background-image:url(/css/flags/1x1/kw.svg)}.flag-icon-ky{background-image:url(/css/flags/4x3/ky.svg)}.flag-icon-ky.flag-icon-squared{background-image:url(/css/flags/1x1/ky.svg)}.flag-icon-kz{background-image:url(/css/flags/4x3/kz.svg)}.flag-icon-kz.flag-icon-squared{background-image:url(/css/flags/1x1/kz.svg)}.flag-icon-la{background-image:url(/css/flags/4x3/la.svg)}.flag-icon-la.flag-icon-squared{background-image:url(/css/flags/1x1/la.svg)}.flag-icon-lb{background-image:url(/css/flags/4x3/lb.svg)}.flag-icon-lb.flag-icon-squared{background-image:url(/css/flags/1x1/lb.svg)}.flag-icon-lc{background-image:url(/css/flags/4x3/lc.svg)}.flag-icon-lc.flag-icon-squared{background-image:url(/css/flags/1x1/lc.svg)}.flag-icon-li{background-image:url(/css/flags/4x3/li.svg)}.flag-icon-li.flag-icon-squared{background-image:url(/css/flags/1x1/li.svg)}.flag-icon-lk{background-image:url(/css/flags/4x3/lk.svg)}.flag-icon-lk.flag-icon-squared{background-image:url(/css/flags/1x1/lk.svg)}.flag-icon-lr{background-image:url(/css/flags/4x3/lr.svg)}.flag-icon-lr.flag-icon-squared{background-image:url(/css/flags/1x1/lr.svg)}.flag-icon-ls{background-image:url(/css/flags/4x3/ls.svg)}.flag-icon-ls.flag-icon-squared{background-image:url(/css/flags/1x1/ls.svg)}.flag-icon-lt{background-image:url(/css/flags/4x3/lt.svg)}.flag-icon-lt.flag-icon-squared{background-image:url(/css/flags/1x1/lt.svg)}.flag-icon-lu{background-image:url(/css/flags/4x3/lu.svg)}.flag-icon-lu.flag-icon-squared{background-image:url(/css/flags/1x1/lu.svg)}.flag-icon-lv{background-image:url(/css/flags/4x3/lv.svg)}.flag-icon-lv.flag-icon-squared{background-image:url(/css/flags/1x1/lv.svg)}.flag-icon-ly{background-image:url(/css/flags/4x3/ly.svg)}.flag-icon-ly.flag-icon-squared{background-image:url(/css/flags/1x1/ly.svg)}.flag-icon-ma{background-image:url(/css/flags/4x3/ma.svg)}.flag-icon-ma.flag-icon-squared{background-image:url(/css/flags/1x1/ma.svg)}.flag-icon-mc{background-image:url(/css/flags/4x3/mc.svg)}.flag-icon-mc.flag-icon-squared{background-image:url(/css/flags/1x1/mc.svg)}.flag-icon-md{background-image:url(/css/flags/4x3/md.svg)}.flag-icon-md.flag-icon-squared{background-image:url(/css/flags/1x1/md.svg)}.flag-icon-me{background-image:url(/css/flags/4x3/me.svg)}.flag-icon-me.flag-icon-squared{background-image:url(/css/flags/1x1/me.svg)}.flag-icon-mf{background-image:url(/css/flags/4x3/mf.svg)}.flag-icon-mf.flag-icon-squared{background-image:url(/css/flags/1x1/mf.svg)}.flag-icon-mg{background-image:url(/css/flags/4x3/mg.svg)}.flag-icon-mg.flag-icon-squared{background-image:url(/css/flags/1x1/mg.svg)}.flag-icon-mh{background-image:url(/css/flags/4x3/mh.svg)}.flag-icon-mh.flag-icon-squared{background-image:url(/css/flags/1x1/mh.svg)}.flag-icon-mk{background-image:url(/css/flags/4x3/mk.svg)}.flag-icon-mk.flag-icon-squared{background-image:url(/css/flags/1x1/mk.svg)}.flag-icon-ml{background-image:url(/css/flags/4x3/ml.svg)}.flag-icon-ml.flag-icon-squared{background-image:url(/css/flags/1x1/ml.svg)}.flag-icon-mm{background-image:url(/css/flags/4x3/mm.svg)}.flag-icon-mm.flag-icon-squared{background-image:url(/css/flags/1x1/mm.svg)}.flag-icon-mn{background-image:url(/css/flags/4x3/mn.svg)}.flag-icon-mn.flag-icon-squared{background-image:url(/css/flags/1x1/mn.svg)}.flag-icon-mo{background-image:url(/css/flags/4x3/mo.svg)}.flag-icon-mo.flag-icon-squared{background-image:url(/css/flags/1x1/mo.svg)}.flag-icon-mp{background-image:url(/css/flags/4x3/mp.svg)}.flag-icon-mp.flag-icon-squared{background-image:url(/css/flags/1x1/mp.svg)}.flag-icon-mq{background-image:url(/css/flags/4x3/mq.svg)}.flag-icon-mq.flag-icon-squared{background-image:url(/css/flags/1x1/mq.svg)}.flag-icon-mr{background-image:url(/css/flags/4x3/mr.svg)}.flag-icon-mr.flag-icon-squared{background-image:url(/css/flags/1x1/mr.svg)}.flag-icon-ms{background-image:url(/css/flags/4x3/ms.svg)}.flag-icon-ms.flag-icon-squared{background-image:url(/css/flags/1x1/ms.svg)}.flag-icon-mt{background-image:url(/css/flags/4x3/mt.svg)}.flag-icon-mt.flag-icon-squared{background-image:url(/css/flags/1x1/mt.svg)}.flag-icon-mu{background-image:url(/css/flags/4x3/mu.svg)}.flag-icon-mu.flag-icon-squared{background-image:url(/css/flags/1x1/mu.svg)}.flag-icon-mv{background-image:url(/css/flags/4x3/mv.svg)}.flag-icon-mv.flag-icon-squared{background-image:url(/css/flags/1x1/mv.svg)}.flag-icon-mw{background-image:url(/css/flags/4x3/mw.svg)}.flag-icon-mw.flag-icon-squared{background-image:url(/css/flags/1x1/mw.svg)}.flag-icon-mx{background-image:url(/css/flags/4x3/mx.svg)}.flag-icon-mx.flag-icon-squared{background-image:url(/css/flags/1x1/mx.svg)}.flag-icon-my{background-image:url(/css/flags/4x3/my.svg)}.flag-icon-my.flag-icon-squared{background-image:url(/css/flags/1x1/my.svg)}.flag-icon-mz{background-image:url(/css/flags/4x3/mz.svg)}.flag-icon-mz.flag-icon-squared{background-image:url(/css/flags/1x1/mz.svg)}.flag-icon-na{background-image:url(/css/flags/4x3/na.svg)}.flag-icon-na.flag-icon-squared{background-image:url(/css/flags/1x1/na.svg)}.flag-icon-nc{background-image:url(/css/flags/4x3/nc.svg)}.flag-icon-nc.flag-icon-squared{background-image:url(/css/flags/1x1/nc.svg)}.flag-icon-ne{background-image:url(/css/flags/4x3/ne.svg)}.flag-icon-ne.flag-icon-squared{background-image:url(/css/flags/1x1/ne.svg)}.flag-icon-nf{background-image:url(/css/flags/4x3/nf.svg)}.flag-icon-nf.flag-icon-squared{background-image:url(/css/flags/1x1/nf.svg)}.flag-icon-ng{background-image:url(/css/flags/4x3/ng.svg)}.flag-icon-ng.flag-icon-squared{background-image:url(/css/flags/1x1/ng.svg)}.flag-icon-ni{background-image:url(/css/flags/4x3/ni.svg)}.flag-icon-ni.flag-icon-squared{background-image:url(/css/flags/1x1/ni.svg)}.flag-icon-nl{background-image:url(/css/flags/4x3/nl.svg)}.flag-icon-nl.flag-icon-squared{background-image:url(/css/flags/1x1/nl.svg)}.flag-icon-no{background-image:url(/css/flags/4x3/no.svg)}.flag-icon-no.flag-icon-squared{background-image:url(/css/flags/1x1/no.svg)}.flag-icon-np{background-image:url(/css/flags/4x3/np.svg)}.flag-icon-np.flag-icon-squared{background-image:url(/css/flags/1x1/np.svg)}.flag-icon-nr{background-image:url(/css/flags/4x3/nr.svg)}.flag-icon-nr.flag-icon-squared{background-image:url(/css/flags/1x1/nr.svg)}.flag-icon-nu{background-image:url(/css/flags/4x3/nu.svg)}.flag-icon-nu.flag-icon-squared{background-image:url(/css/flags/1x1/nu.svg)}.flag-icon-nz{background-image:url(/css/flags/4x3/nz.svg)}.flag-icon-nz.flag-icon-squared{background-image:url(/css/flags/1x1/nz.svg)}.flag-icon-om{background-image:url(/css/flags/4x3/om.svg)}.flag-icon-om.flag-icon-squared{background-image:url(/css/flags/1x1/om.svg)}.flag-icon-pa{background-image:url(/css/flags/4x3/pa.svg)}.flag-icon-pa.flag-icon-squared{background-image:url(/css/flags/1x1/pa.svg)}.flag-icon-pe{background-image:url(/css/flags/4x3/pe.svg)}.flag-icon-pe.flag-icon-squared{background-image:url(/css/flags/1x1/pe.svg)}.flag-icon-pf{background-image:url(/css/flags/4x3/pf.svg)}.flag-icon-pf.flag-icon-squared{background-image:url(/css/flags/1x1/pf.svg)}.flag-icon-pg{background-image:url(/css/flags/4x3/pg.svg)}.flag-icon-pg.flag-icon-squared{background-image:url(/css/flags/1x1/pg.svg)}.flag-icon-ph{background-image:url(/css/flags/4x3/ph.svg)}.flag-icon-ph.flag-icon-squared{background-image:url(/css/flags/1x1/ph.svg)}.flag-icon-pk{background-image:url(/css/flags/4x3/pk.svg)}.flag-icon-pk.flag-icon-squared{background-image:url(/css/flags/1x1/pk.svg)}.flag-icon-pl{background-image:url(/css/flags/4x3/pl.svg)}.flag-icon-pl.flag-icon-squared{background-image:url(/css/flags/1x1/pl.svg)}.flag-icon-pm{background-image:url(/css/flags/4x3/pm.svg)}.flag-icon-pm.flag-icon-squared{background-image:url(/css/flags/1x1/pm.svg)}.flag-icon-pn{background-image:url(/css/flags/4x3/pn.svg)}.flag-icon-pn.flag-icon-squared{background-image:url(/css/flags/1x1/pn.svg)}.flag-icon-pr{background-image:url(/css/flags/4x3/pr.svg)}.flag-icon-pr.flag-icon-squared{background-image:url(/css/flags/1x1/pr.svg)}.flag-icon-ps{background-image:url(/css/flags/4x3/ps.svg)}.flag-icon-ps.flag-icon-squared{background-image:url(/css/flags/1x1/ps.svg)}.flag-icon-pt{background-image:url(/css/flags/4x3/pt.svg)}.flag-icon-pt.flag-icon-squared{background-image:url(/css/flags/1x1/pt.svg)}.flag-icon-pw{background-image:url(/css/flags/4x3/pw.svg)}.flag-icon-pw.flag-icon-squared{background-image:url(/css/flags/1x1/pw.svg)}.flag-icon-py{background-image:url(/css/flags/4x3/py.svg)}.flag-icon-py.flag-icon-squared{background-image:url(/css/flags/1x1/py.svg)}.flag-icon-qa{background-image:url(/css/flags/4x3/qa.svg)}.flag-icon-qa.flag-icon-squared{background-image:url(/css/flags/1x1/qa.svg)}.flag-icon-re{background-image:url(/css/flags/4x3/re.svg)}.flag-icon-re.flag-icon-squared{background-image:url(/css/flags/1x1/re.svg)}.flag-icon-ro{background-image:url(/css/flags/4x3/ro.svg)}.flag-icon-ro.flag-icon-squared{background-image:url(/css/flags/1x1/ro.svg)}.flag-icon-rs{background-image:url(/css/flags/4x3/rs.svg)}.flag-icon-rs.flag-icon-squared{background-image:url(/css/flags/1x1/rs.svg)}.flag-icon-ru{background-image:url(/css/flags/4x3/ru.svg)}.flag-icon-ru.flag-icon-squared{background-image:url(/css/flags/1x1/ru.svg)}.flag-icon-rw{background-image:url(/css/flags/4x3/rw.svg)}.flag-icon-rw.flag-icon-squared{background-image:url(/css/flags/1x1/rw.svg)}.flag-icon-sa{background-image:url(/css/flags/4x3/sa.svg)}.flag-icon-sa.flag-icon-squared{background-image:url(/css/flags/1x1/sa.svg)}.flag-icon-sb{background-image:url(/css/flags/4x3/sb.svg)}.flag-icon-sb.flag-icon-squared{background-image:url(/css/flags/1x1/sb.svg)}.flag-icon-sc{background-image:url(/css/flags/4x3/sc.svg)}.flag-icon-sc.flag-icon-squared{background-image:url(/css/flags/1x1/sc.svg)}.flag-icon-sd{background-image:url(/css/flags/4x3/sd.svg)}.flag-icon-sd.flag-icon-squared{background-image:url(/css/flags/1x1/sd.svg)}.flag-icon-se{background-image:url(/css/flags/4x3/se.svg)}.flag-icon-se.flag-icon-squared{background-image:url(/css/flags/1x1/se.svg)}.flag-icon-sg{background-image:url(/css/flags/4x3/sg.svg)}.flag-icon-sg.flag-icon-squared{background-image:url(/css/flags/1x1/sg.svg)}.flag-icon-sh{background-image:url(/css/flags/4x3/sh.svg)}.flag-icon-sh.flag-icon-squared{background-image:url(/css/flags/1x1/sh.svg)}.flag-icon-si{background-image:url(/css/flags/4x3/si.svg)}.flag-icon-si.flag-icon-squared{background-image:url(/css/flags/1x1/si.svg)}.flag-icon-sj{background-image:url(/css/flags/4x3/sj.svg)}.flag-icon-sj.flag-icon-squared{background-image:url(/css/flags/1x1/sj.svg)}.flag-icon-sk{background-image:url(/css/flags/4x3/sk.svg)}.flag-icon-sk.flag-icon-squared{background-image:url(/css/flags/1x1/sk.svg)}.flag-icon-sl{background-image:url(/css/flags/4x3/sl.svg)}.flag-icon-sl.flag-icon-squared{background-image:url(/css/flags/1x1/sl.svg)}.flag-icon-sm{background-image:url(/css/flags/4x3/sm.svg)}.flag-icon-sm.flag-icon-squared{background-image:url(/css/flags/1x1/sm.svg)}.flag-icon-sn{background-image:url(/css/flags/4x3/sn.svg)}.flag-icon-sn.flag-icon-squared{background-image:url(/css/flags/1x1/sn.svg)}.flag-icon-so{background-image:url(/css/flags/4x3/so.svg)}.flag-icon-so.flag-icon-squared{background-image:url(/css/flags/1x1/so.svg)}.flag-icon-sr{background-image:url(/css/flags/4x3/sr.svg)}.flag-icon-sr.flag-icon-squared{background-image:url(/css/flags/1x1/sr.svg)}.flag-icon-ss{background-image:url(/css/flags/4x3/ss.svg)}.flag-icon-ss.flag-icon-squared{background-image:url(/css/flags/1x1/ss.svg)}.flag-icon-st{background-image:url(/css/flags/4x3/st.svg)}.flag-icon-st.flag-icon-squared{background-image:url(/css/flags/1x1/st.svg)}.flag-icon-sv{background-image:url(/css/flags/4x3/sv.svg)}.flag-icon-sv.flag-icon-squared{background-image:url(/css/flags/1x1/sv.svg)}.flag-icon-sx{background-image:url(/css/flags/4x3/sx.svg)}.flag-icon-sx.flag-icon-squared{background-image:url(/css/flags/1x1/sx.svg)}.flag-icon-sy{background-image:url(/css/flags/4x3/sy.svg)}.flag-icon-sy.flag-icon-squared{background-image:url(/css/flags/1x1/sy.svg)}.flag-icon-sz{background-image:url(/css/flags/4x3/sz.svg)}.flag-icon-sz.flag-icon-squared{background-image:url(/css/flags/1x1/sz.svg)}.flag-icon-tc{background-image:url(/css/flags/4x3/tc.svg)}.flag-icon-tc.flag-icon-squared{background-image:url(/css/flags/1x1/tc.svg)}.flag-icon-td{background-image:url(/css/flags/4x3/td.svg)}.flag-icon-td.flag-icon-squared{background-image:url(/css/flags/1x1/td.svg)}.flag-icon-tf{background-image:url(/css/flags/4x3/tf.svg)}.flag-icon-tf.flag-icon-squared{background-image:url(/css/flags/1x1/tf.svg)}.flag-icon-tg{background-image:url(/css/flags/4x3/tg.svg)}.flag-icon-tg.flag-icon-squared{background-image:url(/css/flags/1x1/tg.svg)}.flag-icon-th{background-image:url(/css/flags/4x3/th.svg)}.flag-icon-th.flag-icon-squared{background-image:url(/css/flags/1x1/th.svg)}.flag-icon-tj{background-image:url(/css/flags/4x3/tj.svg)}.flag-icon-tj.flag-icon-squared{background-image:url(/css/flags/1x1/tj.svg)}.flag-icon-tk{background-image:url(/css/flags/4x3/tk.svg)}.flag-icon-tk.flag-icon-squared{background-image:url(/css/flags/1x1/tk.svg)}.flag-icon-tl{background-image:url(/css/flags/4x3/tl.svg)}.flag-icon-tl.flag-icon-squared{background-image:url(/css/flags/1x1/tl.svg)}.flag-icon-tm{background-image:url(/css/flags/4x3/tm.svg)}.flag-icon-tm.flag-icon-squared{background-image:url(/css/flags/1x1/tm.svg)}.flag-icon-tn{background-image:url(/css/flags/4x3/tn.svg)}.flag-icon-tn.flag-icon-squared{background-image:url(/css/flags/1x1/tn.svg)}.flag-icon-to{background-image:url(/css/flags/4x3/to.svg)}.flag-icon-to.flag-icon-squared{background-image:url(/css/flags/1x1/to.svg)}.flag-icon-tr{background-image:url(/css/flags/4x3/tr.svg)}.flag-icon-tr.flag-icon-squared{background-image:url(/css/flags/1x1/tr.svg)}.flag-icon-tt{background-image:url(/css/flags/4x3/tt.svg)}.flag-icon-tt.flag-icon-squared{background-image:url(/css/flags/1x1/tt.svg)}.flag-icon-tv{background-image:url(/css/flags/4x3/tv.svg)}.flag-icon-tv.flag-icon-squared{background-image:url(/css/flags/1x1/tv.svg)}.flag-icon-tw{background-image:url(/css/flags/4x3/tw.svg)}.flag-icon-tw.flag-icon-squared{background-image:url(/css/flags/1x1/tw.svg)}.flag-icon-tz{background-image:url(/css/flags/4x3/tz.svg)}.flag-icon-tz.flag-icon-squared{background-image:url(/css/flags/1x1/tz.svg)}.flag-icon-ua{background-image:url(/css/flags/4x3/ua.svg)}.flag-icon-ua.flag-icon-squared{background-image:url(/css/flags/1x1/ua.svg)}.flag-icon-ug{background-image:url(/css/flags/4x3/ug.svg)}.flag-icon-ug.flag-icon-squared{background-image:url(/css/flags/1x1/ug.svg)}.flag-icon-um{background-image:url(/css/flags/4x3/um.svg)}.flag-icon-um.flag-icon-squared{background-image:url(/css/flags/1x1/um.svg)}.flag-icon-us{background-image:url(/css/flags/4x3/us.svg)}.flag-icon-us.flag-icon-squared{background-image:url(/css/flags/1x1/us.svg)}.flag-icon-uy{background-image:url(/css/flags/4x3/uy.svg)}.flag-icon-uy.flag-icon-squared{background-image:url(/css/flags/1x1/uy.svg)}.flag-icon-uz{background-image:url(/css/flags/4x3/uz.svg)}.flag-icon-uz.flag-icon-squared{background-image:url(/css/flags/1x1/uz.svg)}.flag-icon-va{background-image:url(/css/flags/4x3/va.svg)}.flag-icon-va.flag-icon-squared{background-image:url(/css/flags/1x1/va.svg)}.flag-icon-vc{background-image:url(/css/flags/4x3/vc.svg)}.flag-icon-vc.flag-icon-squared{background-image:url(/css/flags/1x1/vc.svg)}.flag-icon-ve{background-image:url(/css/flags/4x3/ve.svg)}.flag-icon-ve.flag-icon-squared{background-image:url(/css/flags/1x1/ve.svg)}.flag-icon-vg{background-image:url(/css/flags/4x3/vg.svg)}.flag-icon-vg.flag-icon-squared{background-image:url(/css/flags/1x1/vg.svg)}.flag-icon-vi{background-image:url(/css/flags/4x3/vi.svg)}.flag-icon-vi.flag-icon-squared{background-image:url(/css/flags/1x1/vi.svg)}.flag-icon-vn{background-image:url(/css/flags/4x3/vn.svg)}.flag-icon-vn.flag-icon-squared{background-image:url(/css/flags/1x1/vn.svg)}.flag-icon-vu{background-image:url(/css/flags/4x3/vu.svg)}.flag-icon-vu.flag-icon-squared{background-image:url(/css/flags/1x1/vu.svg)}.flag-icon-wf{background-image:url(/css/flags/4x3/wf.svg)}.flag-icon-wf.flag-icon-squared{background-image:url(/css/flags/1x1/wf.svg)}.flag-icon-ws{background-image:url(/css/flags/4x3/ws.svg)}.flag-icon-ws.flag-icon-squared{background-image:url(/css/flags/1x1/ws.svg)}.flag-icon-ye{background-image:url(/css/flags/4x3/ye.svg)}.flag-icon-ye.flag-icon-squared{background-image:url(/css/flags/1x1/ye.svg)}.flag-icon-yt{background-image:url(/css/flags/4x3/yt.svg)}.flag-icon-yt.flag-icon-squared{background-image:url(/css/flags/1x1/yt.svg)}.flag-icon-za{background-image:url(/css/flags/4x3/za.svg)}.flag-icon-za.flag-icon-squared{background-image:url(/css/flags/1x1/za.svg)}.flag-icon-zm{background-image:url(/css/flags/4x3/zm.svg)}.flag-icon-zm.flag-icon-squared{background-image:url(/css/flags/1x1/zm.svg)}.flag-icon-zw{background-image:url(/css/flags/4x3/zw.svg)}.flag-icon-zw.flag-icon-squared{background-image:url(/css/flags/1x1/zw.svg)}.flag-icon-es-ct{background-image:url(/css/flags/4x3/es-ct.svg)}.flag-icon-es-ct.flag-icon-squared{background-image:url(/css/flags/1x1/es-ct.svg)}.flag-icon-es-ga{background-image:url(/css/flags/4x3/es-ga.svg)}.flag-icon-es-ga.flag-icon-squared{background-image:url(/css/flags/1x1/es-ga.svg)}.flag-icon-eu{background-image:url(/css/flags/4x3/eu.svg)}.flag-icon-eu.flag-icon-squared{background-image:url(/css/flags/1x1/eu.svg)}.flag-icon-gb-eng{background-image:url(/css/flags/4x3/gb-eng.svg)}.flag-icon-gb-eng.flag-icon-squared{background-image:url(/css/flags/1x1/gb-eng.svg)}.flag-icon-gb-nir{background-image:url(/css/flags/4x3/gb-nir.svg)}.flag-icon-gb-nir.flag-icon-squared{background-image:url(/css/flags/1x1/gb-nir.svg)}.flag-icon-gb-sct{background-image:url(/css/flags/4x3/gb-sct.svg)}.flag-icon-gb-sct.flag-icon-squared{background-image:url(/css/flags/1x1/gb-sct.svg)}.flag-icon-gb-wls{background-image:url(/css/flags/4x3/gb-wls.svg)}.flag-icon-gb-wls.flag-icon-squared{background-image:url(/css/flags/1x1/gb-wls.svg)}.flag-icon-un{background-image:url(/css/flags/4x3/un.svg)}.flag-icon-un.flag-icon-squared{background-image:url(/css/flags/1x1/un.svg)}.flag-icon-xk{background-image:url(/css/flags/4x3/xk.svg)}.flag-icon-xk.flag-icon-squared{background-image:url(/css/flags/1x1/xk.svg)} diff --git a/data/web/css/build/013-datatables.css b/data/web/css/build/013-datatables.css index 57e2b6d94..2b19ba24e 100644 --- a/data/web/css/build/013-datatables.css +++ b/data/web/css/build/013-datatables.css @@ -8,9 +8,6 @@ .dtr-details { width: 100%; } -.table-striped>tbody>tr:nth-of-type(odd) { - background-color: #F2F2F2; -} td.child>ul>li { display: flex; } diff --git a/data/web/css/build/014-mailcow.css b/data/web/css/build/014-mailcow.css index 6c70a2a55..3e1ace79d 100644 --- a/data/web/css/build/014-mailcow.css +++ b/data/web/css/build/014-mailcow.css @@ -33,6 +33,13 @@ url('/fonts/noto-sans-v12-latin_greek_cyrillic-700italic.woff2') format('woff2'), url('/fonts/noto-sans-v12-latin_greek_cyrillic-700italic.woff') format('woff'); } + +body { + min-height: 100vh; + display: flex; + flex-direction: column; + background-color: #fbfbfb; +} #maxmsgsize { min-width: 80px; } #slider1 .slider-selection { background: #FFD700; @@ -74,10 +81,23 @@ align-items: center; padding: 0 10px !important; } -.navbar-fixed-bottom .navbar-collapse, +.navbar-fixed-bottom .navbar-collapse, .navbar-fixed-top .navbar-collapse { max-height: 1000px } +.nav-tabs .nav-link, .nav-tabs .nav-link.disabled, .nav-tabs .nav-link.disabled:hover, .nav-tabs .nav-link.disabled:focus { + border-color: #dfdfdf; +} +.nav-tabs .nav-link.active, .nav-tabs .nav-item.show .nav-link { + border-color: #dfdfdf; + border-bottom: 1px solid #ffffff; +} +.nav-tabs .nav-link:hover, .nav-tabs .nav-link:focus { + border-color: #dfdfdf; +} +.nav-tabs { + border-bottom: 1px solid #dfdfdf; +} .bi { display: inline-block; font-size: 12pt; @@ -123,18 +143,18 @@ } } @keyframes blink { - 50% { - color: transparent + 50% { + color: transparent } } -.loader-dot { - animation: 1s blink infinite +.loader-dot { + animation: 1s blink infinite } -.loader-dot:nth-child(2) { - animation-delay: 250ms +.loader-dot:nth-child(2) { + animation-delay: 250ms } -.loader-dot:nth-child(3) { - animation-delay: 500ms +.loader-dot:nth-child(3) { + animation-delay: 500ms } pre{white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-o-pre-wrap;word-wrap:break-word;} @@ -200,13 +220,13 @@ legend { } .haveibeenpwned { cursor: pointer; - -webkit-user-select: none; - -moz-user-select: none; - -ms-user-select: none; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; user-select: none; } .full-width-select { - width: 100%!important; + width: 100%!important; } .tooltip { font-family: inherit; @@ -330,7 +350,7 @@ code { .caret { transform: rotate(0deg); } -a[aria-expanded='true'] > .caret, +a[aria-expanded='true'] > .caret, button[aria-expanded='true'] > .caret { transform: rotate(-180deg); } @@ -340,7 +360,7 @@ button[aria-expanded='true'] > .caret { } .list-group-header { background: #f7f7f7; -} +} .bg-primary, .alert-primary, .btn-primary { @@ -366,12 +386,13 @@ button[aria-expanded='true'] > .caret { background-color: #f0f0f0; } .btn.btn-outline-secondary { - border-color: #cfcfcf !important; + color: #000000 !important; + border-color: #cfcfcf !important; } .btn-check:checked+.btn-outline-secondary, .btn-check:active+.btn-outline-secondary, .btn-outline-secondary:active, .btn-outline-secondary.active, .btn-outline-secondary.dropdown-toggle.show { background-color: #f0f0f0 !important; } -.btn-check:checked+.btn-light, .btn-check:active+.btn-light, .btn-light:active, .btn-light.active, .show>.btn-light.dropdown-toggle { +.btn-check:checked+.btn-light, .btn-check:active+.btn-light, .btn-light:active, .btn-light.active, .show>.btn-light.dropdown-toggle { color: #fff; background-color: #555; background-image: none; @@ -389,4 +410,26 @@ button[aria-expanded='true'] > .caret { .badge.bg-danger > a { color: #fff !important; text-decoration: none; +} + +.hr-title { + display: flex; + align-items: center; + text-align: center; + margin: 20px 0; +} + +.hr-title::before, +.hr-title::after { + content: ""; + flex: 1; + border-bottom: 1px solid #ccc; +} + +.hr-title:not(:empty)::before { + margin-right: 10px; +} + +.hr-title:not(:empty)::after { + margin-left: 10px; } \ No newline at end of file diff --git a/data/web/css/build/015-responsive.css b/data/web/css/build/015-responsive.css index 57ce80233..82be71069 100644 --- a/data/web/css/build/015-responsive.css +++ b/data/web/css/build/015-responsive.css @@ -6,15 +6,9 @@ max-width: 350px; } -.card-login .apps .btn { - width: auto; - float: left; - margin-right: 10px; - margin-top: auto; -} -.card-login .apps .btn:hover { - margin-top: 1px !important; - border-bottom-width: 3px; +.card .apps { + display: flex; + flex-wrap: wrap; } .responsive-tabs .nav-tabs { @@ -43,16 +37,6 @@ opacity: 1; } - .card-login .apps .btn { - width: 100%; - float: none; - margin-bottom: 10px; - } - - .card-login .apps .btn { - border-bottom-width: 4px; - } - .xs-show { display: block !important; } @@ -113,9 +97,6 @@ .btn-group.nowrap .dropdown-menu { width: 100%; } - .card-login .btn-group { - display: block; - } .mass-actions-user .btn-group { float: none; } @@ -191,9 +172,6 @@ .btn-group .btn i { margin-right: 5px; } - .card-login .btn-group .btn { - display: block !important; - } .dt-sm-head-hidden .dtr-title { display: none !important; @@ -206,7 +184,7 @@ .senders-mw220 { max-width: 100% !important; } - + table.dataTable.dtr-inline.collapsed>tbody>tr>td.dtr-control:before, table.dataTable.dtr-inline.collapsed>tbody>tr>th.dtr-control:before, table.dataTable td.dt-control:before { @@ -215,7 +193,7 @@ line-height: 2rem; margin-top: -15px; } - + li .dtr-data { padding: 0; } diff --git a/data/web/css/site/admin.css b/data/web/css/site/admin.css index e49046b00..b54148026 100644 --- a/data/web/css/site/admin.css +++ b/data/web/css/site/admin.css @@ -59,9 +59,6 @@ body.modal-open { .table-condensed > thead > tr > th, .table-condensed > tbody > tr > th, .table-condensed > tfoot > tr > th, .table-condensed > thead > tr > td, .table-condensed > tbody > tr > td, .table-condensed > tfoot > tr > td { padding: 3px; } -table tbody tr { - cursor: pointer; -} table tbody tr td input[type="checkbox"] { cursor: pointer; } diff --git a/data/web/domainadmin/index.php b/data/web/domainadmin/index.php new file mode 100644 index 000000000..0d70ec3ae --- /dev/null +++ b/data/web/domainadmin/index.php @@ -0,0 +1,29 @@ + @$_SESSION['ldelay'], + 'custom_login' => customize('get', 'custom_login'), +]; + +$js_minifier->add('/web/js/site/index.js'); +require_once $_SERVER['DOCUMENT_ROOT'] . '/inc/footer.inc.php'; diff --git a/data/web/domainadmin/mailbox.php b/data/web/domainadmin/mailbox.php new file mode 100644 index 000000000..bb2ef16f3 --- /dev/null +++ b/data/web/domainadmin/mailbox.php @@ -0,0 +1,58 @@ +add('/web/js/site/mailbox.js'); +$js_minifier->add('/web/js/presets/sieveMailbox.js'); +$js_minifier->add('/web/js/site/pwgen.js'); + +$role = "domainadmin"; +$is_dual = (!empty($_SESSION["dual-login"]["username"])) ? 'true' : 'false'; +$allow_admin_email_login = (preg_match("/^([yY][eE][sS]|[yY])+$/", $_ENV["ALLOW_ADMIN_EMAIL_LOGIN"])) ? 'true' : 'false'; + +// domains +$domains = mailbox('get', 'domains'); + +// mailboxes +$mailboxes = []; +foreach ($domains as $domain) { + foreach (mailbox('get', 'mailboxes', $domain) as $mailbox) { + $mailboxes[] = $mailbox; + } +} + +$template = 'mailbox.twig'; +$template_data = [ + 'acl' => $_SESSION['acl'], + 'acl_json' => json_encode($_SESSION['acl']), + 'role' => $role, + 'is_dual' => $is_dual, + 'allow_admin_email_login' => $allow_admin_email_login, + 'global_filters' => mailbox('get', 'global_filter_details'), + 'domains' => $domains, + 'mailboxes' => $mailboxes, + 'lang_mailbox' => json_encode($lang['mailbox']), + 'lang_rl' => json_encode($lang['ratelimit']), + 'lang_edit' => json_encode($lang['edit']), + 'lang_datatables' => json_encode($lang['datatables']), +]; + +require_once $_SERVER['DOCUMENT_ROOT'] . '/inc/footer.inc.php'; \ No newline at end of file diff --git a/data/web/domainadmin/user.php b/data/web/domainadmin/user.php new file mode 100644 index 000000000..7f1b392e0 --- /dev/null +++ b/data/web/domainadmin/user.php @@ -0,0 +1,44 @@ + "get_friendly_names")); + $username = $_SESSION['mailcow_cc_username']; + + $template = 'domainadmin.twig'; + $template_data = [ + 'acl' => $_SESSION['acl'], + 'acl_json' => json_encode($_SESSION['acl']), + 'user_spam_score' => mailbox('get', 'spam_score', $username), + 'tfa_data' => $tfa_data, + 'fido2_data' => $fido2_data, + 'lang_user' => json_encode($lang['user']), + 'lang_datatables' => json_encode($lang['datatables']), + ]; +} +elseif (isset($_SESSION['mailcow_cc_role']) && $_SESSION['mailcow_cc_role'] == 'admin') { + header('Location: /admin/dashboard'); + exit(); +} +elseif (isset($_SESSION['mailcow_cc_role']) && $_SESSION['mailcow_cc_role'] == 'user') { + header('Location: /user'); + exit(); +} +else { + header('Location: /domainadmin'); + exit(); +} + +$js_minifier->add('/web/js/site/user.js'); +$js_minifier->add('/web/js/site/pwgen.js'); + +require_once $_SERVER['DOCUMENT_ROOT'] . '/inc/footer.inc.php'; diff --git a/data/web/edit.php b/data/web/edit.php index b7544a5af..57cf24bd2 100644 --- a/data/web/edit.php +++ b/data/web/edit.php @@ -48,6 +48,12 @@ if (isset($_SESSION['mailcow_cc_role'])) { $rl = ratelimit('get', 'domain', $domain); $rlyhosts = relayhost('get'); $domain_footer = mailbox('get', 'domain_wide_footer', $domain); + $mta_sts = mailbox('get', 'mta_sts', $domain); + if (count($mta_sts) == 0) { + $mta_sts = false; + } elseif (isset($mta_sts['mx'])) { + $mta_sts['mx'] = implode(',', $mta_sts['mx']); + } $template = 'edit/domain.twig'; $template_data = [ 'acl' => $_SESSION['acl'], @@ -58,6 +64,7 @@ if (isset($_SESSION['mailcow_cc_role'])) { 'dkim' => dkim('details', $domain), 'domain_details' => $result, 'domain_footer' => $domain_footer, + 'mta_sts' => $mta_sts, 'mailboxes' => mailbox('get', 'mailboxes', $_GET["domain"]), 'aliases' => mailbox('get', 'aliases', $_GET["domain"], 'address'), 'alias_domains' => mailbox('get', 'alias_domains', $_GET["domain"]) @@ -125,13 +132,15 @@ if (isset($_SESSION['mailcow_cc_role'])) { 'mailbox' => $mailbox, 'rl' => $rl, 'pushover_data' => $pushover_data, + 'get_tagging_options' => mailbox('get', 'delimiter_action', $mailbox), 'quarantine_notification' => $quarantine_notification, 'quarantine_category' => $quarantine_category, 'get_tls_policy' => $get_tls_policy, 'rlyhosts' => $rlyhosts, 'sender_acl_handles' => mailbox('get', 'sender_acl_handles', $mailbox), 'user_acls' => acl('get', 'user', $mailbox), - 'mailbox_details' => $result + 'mailbox_details' => $result, + 'iam_settings' => $iam_settings, ]; } } diff --git a/data/web/favicon.png b/data/web/favicon.png index 69eb2fcd1..541361359 100644 Binary files a/data/web/favicon.png and b/data/web/favicon.png differ diff --git a/data/web/inc/ajax/dns_diagnostics.php b/data/web/inc/ajax/dns_diagnostics.php index 15cb3a30f..b48239e10 100644 --- a/data/web/inc/ajax/dns_diagnostics.php +++ b/data/web/inc/ajax/dns_diagnostics.php @@ -71,6 +71,7 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm // Init records array $spf_link = 'SPF Record Syntax
'; $dmarc_link = 'DMARC Assistant'; + $mtasts_report_link = 'TLS Report Record Syntax'; $records = array(); @@ -128,6 +129,27 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm ); } + $mta_sts = mailbox('get', 'mta_sts', $domain); + if (count($mta_sts) > 0 && $mta_sts['active'] == 1) { + if (!in_array($domain, $alias_domains)) { + $records[] = array( + 'mta-sts.' . $domain, + 'CNAME', + $mailcow_hostname + ); + } + $records[] = array( + '_mta-sts.' . $domain, + 'TXT', + "v={$mta_sts['version']};id={$mta_sts['id']};", + ); + $records[] = array( + '_smtp._tls.' . $domain, + 'TXT', + $mtasts_report_link, + ); + } + $records[] = array( $domain, 'TXT', @@ -341,15 +363,25 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm } foreach ($currents as &$current) { + if ($current['type'] == "TXT" && + stripos(strtolower($current['txt']), 'v=sts') === 0) { + if (strtolower($current[$data_field[$current['type']]]) == strtolower($record[2])) { + $state = state_good; + } + else { + $state = state_nomatch; + } + $state .= '
' . $current[$data_field[$current['type']]]; + } if ($current['type'] == 'TXT' && - stripos($current['txt'], 'v=dmarc') === 0 && - $record[2] == $dmarc_link) { + stripos($current['txt'], 'v=dmarc') === 0 && + $record[2] == $dmarc_link) { $current['txt'] = str_replace(' ', '', $current['txt']); $state = $current[$data_field[$current['type']]] . state_optional; } elseif ($current['type'] == 'TXT' && - stripos($current['txt'], 'v=spf') === 0 && - $record[2] == $spf_link) { + stripos($current['txt'], 'v=spf') === 0 && + $record[2] == $spf_link) { $state = state_nomatch; $rslt = get_spf_allowed_hosts($record[0], true); if (in_array($ip, $rslt) && in_array(expand_ipv6($ip6), $rslt)) { @@ -358,8 +390,8 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm $state .= '
' . $current[$data_field[$current['type']]] . state_optional; } elseif ($current['type'] == 'TXT' && - stripos($current['txt'], 'v=dkim') === 0 && - stripos($record[2], 'v=dkim') === 0) { + stripos($current['txt'], 'v=dkim') === 0 && + stripos($record[2], 'v=dkim') === 0) { preg_match('/v=DKIM1;.*k=rsa;.*p=([^;]*).*/i', $current[$data_field[$current['type']]], $dkim_matches_current); preg_match('/v=DKIM1;.*k=rsa;.*p=([^;]*).*/i', $record[2], $dkim_matches_good); if ($dkim_matches_current[1] == $dkim_matches_good[1]) { @@ -367,7 +399,7 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm } } elseif ($current['type'] != 'TXT' && - isset($data_field[$current['type']]) && $state != state_good) { + isset($data_field[$current['type']]) && $state != state_good) { $state = state_nomatch; if ($current[$data_field[$current['type']]] == $record[2]) { $state = state_good; diff --git a/data/web/inc/footer.inc.php b/data/web/inc/footer.inc.php index cd689cd14..ecc4ddce1 100644 --- a/data/web/inc/footer.inc.php +++ b/data/web/inc/footer.inc.php @@ -26,23 +26,25 @@ if (is_array($alertbox_log_parser)) { // map tfa details for twig $pending_tfa_authmechs = []; -foreach($_SESSION['pending_tfa_methods'] as $authdata){ - $pending_tfa_authmechs[$authdata['authmech']] = false; -} -if (isset($pending_tfa_authmechs['webauthn'])) { - $pending_tfa_authmechs['webauthn'] = true; -} -if (!isset($pending_tfa_authmechs['webauthn']) - && isset($pending_tfa_authmechs['yubi_otp'])) { - $pending_tfa_authmechs['yubi_otp'] = true; -} -if (!isset($pending_tfa_authmechs['webauthn']) - && !isset($pending_tfa_authmechs['yubi_otp']) - && isset($pending_tfa_authmechs['totp'])) { - $pending_tfa_authmechs['totp'] = true; -} -if (isset($pending_tfa_authmechs['u2f'])) { - $pending_tfa_authmechs['u2f'] = true; +if (array_key_exists('pending_tfa_methods', $_SESSION)) { + foreach($_SESSION['pending_tfa_methods'] as $authdata){ + $pending_tfa_authmechs[$authdata['authmech']] = false; + } + if (isset($pending_tfa_authmechs['webauthn'])) { + $pending_tfa_authmechs['webauthn'] = true; + } + if (!isset($pending_tfa_authmechs['webauthn']) + && isset($pending_tfa_authmechs['yubi_otp'])) { + $pending_tfa_authmechs['yubi_otp'] = true; + } + if (!isset($pending_tfa_authmechs['webauthn']) + && !isset($pending_tfa_authmechs['yubi_otp']) + && isset($pending_tfa_authmechs['totp'])) { + $pending_tfa_authmechs['totp'] = true; + } + if (isset($pending_tfa_authmechs['u2f'])) { + $pending_tfa_authmechs['u2f'] = true; + } } // globals @@ -66,6 +68,8 @@ $globalVariables = [ 'lang_acl' => json_encode($lang['acl']), 'lang_tfa' => json_encode($lang['tfa']), 'lang_fido2' => json_encode($lang['fido2']), + 'lang_success' => json_encode($lang['success']), + 'lang_danger' => json_encode($lang['danger']), 'docker_timeout' => $DOCKER_TIMEOUT, 'session_lifetime' => (int)$SESSION_LIFETIME, 'csrf_token' => $_SESSION['CSRF']['TOKEN'], diff --git a/data/web/inc/functions.acl.inc.php b/data/web/inc/functions.acl.inc.php index ffce9f44c..dde9b1236 100644 --- a/data/web/inc/functions.acl.inc.php +++ b/data/web/inc/functions.acl.inc.php @@ -1,5 +1,5 @@ 'danger', 'log' => array(__FUNCTION__, $_action, $_scope, $_data_log), @@ -34,7 +34,7 @@ function acl($_action, $_scope = null, $_data = null) { } // Read all available acl options by calling acl(get) // Set all available acl options we cannot find in the post data to 0, else 1 - $is_now = acl('get', 'user', $username); + $is_now = acl('get', 'user', $username, $_extra); if (!empty($is_now)) { foreach ($is_now as $acl_now_name => $acl_now_val) { $set_acls[$acl_now_name] = (isset($acl_post[$acl_now_name])) ? 1 : 0; diff --git a/data/web/inc/functions.app_passwd.inc.php b/data/web/inc/functions.app_passwd.inc.php index b493fc914..aacbb82df 100644 --- a/data/web/inc/functions.app_passwd.inc.php +++ b/data/web/inc/functions.app_passwd.inc.php @@ -1,7 +1,7 @@ 'danger', - 'log' => array(__FUNCTION__, $_action, $_data_log), - 'msg' => 'password_complexity' - ); - return false; - } - if ($password != $password2) { - $_SESSION['return'][] = array( - 'type' => 'danger', - 'log' => array(__FUNCTION__, $_action, $_data_log), - 'msg' => 'password_mismatch' - ); + if (password_check($password, $password2) !== true) { return false; } $password_hashed = hash_password($password); @@ -88,15 +75,15 @@ function app_passwd($_action, $_data = null) { 'log' => array(__FUNCTION__, $_action, $_data_log), 'msg' => 'app_passwd_added' ); - break; + break; case 'edit': $ids = (array)$_data['id']; foreach ($ids as $id) { $is_now = app_passwd('details', $id); if (!empty($is_now)) { $app_name = (!empty($_data['app_name'])) ? $_data['app_name'] : $is_now['name']; - $password = (!empty($_data['password'])) ? $_data['password'] : null; - $password2 = (!empty($_data['password2'])) ? $_data['password2'] : null; + $password = (!empty($_data['app_passwd'])) ? $_data['app_passwd'] : null; + $password2 = (!empty($_data['app_passwd2'])) ? $_data['app_passwd2'] : null; if (isset($_data['protocols'])) { $protocols = (array)$_data['protocols']; $imap_access = (in_array('imap_access', $protocols)) ? 1 : 0; @@ -126,20 +113,7 @@ function app_passwd($_action, $_data = null) { } $app_name = htmlspecialchars(trim($app_name)); if (!empty($password) && !empty($password2)) { - if (!preg_match('/' . $GLOBALS['PASSWD_REGEP'] . '/', $password)) { - $_SESSION['return'][] = array( - 'type' => 'danger', - 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), - 'msg' => 'password_complexity' - ); - continue; - } - if ($password != $password2) { - $_SESSION['return'][] = array( - 'type' => 'danger', - 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), - 'msg' => 'password_mismatch' - ); + if (password_check($password, $password2) !== true) { continue; } $password_hashed = hash_password($password); @@ -182,7 +156,7 @@ function app_passwd($_action, $_data = null) { 'msg' => array('object_modified', htmlspecialchars(implode(', ', $ids))) ); } - break; + break; case 'delete': $ids = (array)$_data['id']; foreach ($ids as $id) { @@ -213,19 +187,17 @@ function app_passwd($_action, $_data = null) { 'msg' => array('app_passwd_removed', htmlspecialchars($id)) ); } - break; + break; case 'get': $app_passwds = array(); $stmt = $pdo->prepare("SELECT `id`, `name` FROM `app_passwd` WHERE `mailbox` = :username"); $stmt->execute(array(':username' => $username)); $app_passwds = $stmt->fetchAll(PDO::FETCH_ASSOC); return $app_passwds; - break; + break; case 'details': $app_passwd_data = array(); - $stmt = $pdo->prepare("SELECT * - FROM `app_passwd` - WHERE `id` = :id"); + $stmt = $pdo->prepare("SELECT * FROM `app_passwd` WHERE `id` = :id"); $stmt->execute(array(':id' => $_data)); $app_passwd_data = $stmt->fetch(PDO::FETCH_ASSOC); if (empty($app_passwd_data)) { @@ -237,6 +209,6 @@ function app_passwd($_action, $_data = null) { } $app_passwd_data['name'] = htmlspecialchars(trim($app_passwd_data['name'])); return $app_passwd_data; - break; + break; } } diff --git a/data/web/inc/functions.auth.inc.php b/data/web/inc/functions.auth.inc.php new file mode 100644 index 000000000..879fb2af7 --- /dev/null +++ b/data/web/inc/functions.auth.inc.php @@ -0,0 +1,740 @@ +publish("F2B_CHANNEL", "mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']); + error_log("mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']); + } + elseif (!isset($_SESSION['mailcow_cc_username'])) { + $_SESSION['ldelay'] = $_SESSION['ldelay']+0.5; + $valkey->publish("F2B_CHANNEL", "mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']); + error_log("mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']); + } + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $user, '*'), + 'msg' => 'login_failed' + ); + + sleep($_SESSION['ldelay']); + return false; +} + +function admin_login($user, $pass){ + global $pdo; + + if (!filter_var($user, FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $user))) { + if (!$is_internal){ + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $user, '*'), + 'msg' => 'malformed_username' + ); + } + return false; + } + + $user = strtolower(trim($user)); + $stmt = $pdo->prepare("SELECT `password` FROM `admin` + WHERE `superadmin` = '1' + AND `active` = '1' + AND `username` = :user"); + $stmt->execute(array(':user' => $user)); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + + // verify password + if (verify_hash($row['password'], $pass)) { + // check for tfa authenticators + $authenticators = get_tfa($user); + if (isset($authenticators['additional']) && is_array($authenticators['additional']) && count($authenticators['additional']) > 0) { + // active tfa authenticators found, set pending user login + $_SESSION['pending_mailcow_cc_username'] = $user; + $_SESSION['pending_mailcow_cc_role'] = "admin"; + $_SESSION['pending_tfa_methods'] = $authenticators['additional']; + unset($_SESSION['ldelay']); + $_SESSION['return'][] = array( + 'type' => 'info', + 'log' => array(__FUNCTION__, $user, '*'), + 'msg' => 'awaiting_tfa_confirmation' + ); + return "pending"; + } else { + unset($_SESSION['ldelay']); + // Reactivate TFA if it was set to "deactivate TFA for next login" + $stmt = $pdo->prepare("UPDATE `tfa` SET `active`='1' WHERE `username` = :user"); + $stmt->execute(array(':user' => $user)); + $_SESSION['return'][] = array( + 'type' => 'success', + 'log' => array(__FUNCTION__, $user, '*'), + 'msg' => array('logged_in_as', $user) + ); + return "admin"; + } + } + + return false; +} +function domainadmin_login($user, $pass){ + global $pdo; + + if (!filter_var($user, FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $user))) { + if (!$is_internal){ + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $user, '*'), + 'msg' => 'malformed_username' + ); + } + return false; + } + + $stmt = $pdo->prepare("SELECT `password` FROM `admin` + WHERE `superadmin` = '0' + AND `active`='1' + AND `username` = :user"); + $stmt->execute(array(':user' => $user)); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + + // verify password + if (verify_hash($row['password'], $pass) !== false) { + // check for tfa authenticators + $authenticators = get_tfa($user); + if (isset($authenticators['additional']) && is_array($authenticators['additional']) && count($authenticators['additional']) > 0) { + $_SESSION['pending_mailcow_cc_username'] = $user; + $_SESSION['pending_mailcow_cc_role'] = "domainadmin"; + $_SESSION['pending_tfa_methods'] = $authenticators['additional']; + unset($_SESSION['ldelay']); + $_SESSION['return'][] = array( + 'type' => 'info', + 'log' => array(__FUNCTION__, $user, '*'), + 'msg' => 'awaiting_tfa_confirmation' + ); + return "pending"; + } + else { + unset($_SESSION['ldelay']); + // Reactivate TFA if it was set to "deactivate TFA for next login" + $stmt = $pdo->prepare("UPDATE `tfa` SET `active`='1' WHERE `username` = :user"); + $stmt->execute(array(':user' => $user)); + $_SESSION['return'][] = array( + 'type' => 'success', + 'log' => array(__FUNCTION__, $user, '*'), + 'msg' => array('logged_in_as', $user) + ); + return "domainadmin"; + } + } + + return false; +} +function user_login($user, $pass, $extra = null){ + global $pdo; + global $iam_provider; + global $iam_settings; + + $is_internal = $extra['is_internal']; + $service = $extra['service']; + + if (!filter_var($user, FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $user))) { + if (!$is_internal){ + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $user, '*'), + 'msg' => 'malformed_username' + ); + } + return false; + } + + $stmt = $pdo->prepare("SELECT + mailbox.*, + domain.active AS d_active + FROM `mailbox` + INNER JOIN domain on mailbox.domain = domain.domain + WHERE `kind` NOT REGEXP 'location|thing|group' + AND `username` = :user"); + $stmt->execute(array(':user' => $user)); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + + // user does not exist, try call idp login and create user if possible via rest flow + if (!$row){ + $result = false; + if ($iam_settings['authsource'] == 'keycloak' && intval($iam_settings['mailpassword_flow']) == 1){ + $result = keycloak_mbox_login_rest($user, $pass, array('is_internal' => $is_internal, 'create' => true)); + } else if ($iam_settings['authsource'] == 'ldap') { + $result = ldap_mbox_login($user, $pass, array('is_internal' => $is_internal, 'create' => true)); + } + if ($result !== false){ + // double check if mailbox is active + $stmt = $pdo->prepare("SELECT * FROM `mailbox` + INNER JOIN domain on mailbox.domain = domain.domain + WHERE `kind` NOT REGEXP 'location|thing|group' + AND `mailbox`.`active`='1' + AND `domain`.`active`='1' + AND `username` = :user"); + $stmt->execute(array(':user' => $user)); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + + if (!empty($row)) { + // check if user has access to service (imap, smtp, pop3, sieve) if service is set + $row['attributes'] = json_decode($row['attributes'], true); + if (isset($service)) { + $key = strtolower($service) . "_access"; + if (isset($row['attributes'][$key]) && $row['attributes'][$key] != '1') { + return false; + } + } + return true; + } + } + clear_session(); + return false; + } + + // check if user has access to service (imap, smtp, pop3, sieve) if service is set + $row['attributes'] = json_decode($row['attributes'], true); + if (isset($service)) { + $key = strtolower($service) . "_access"; + if (isset($row['attributes'][$key]) && $row['attributes'][$key] != '1') { + return false; + } + } + switch ($row['authsource']) { + case 'keycloak': + // user authsource is keycloak, try using via rest flow + if (intval($iam_settings['mailpassword_flow']) == 1){ + $result = keycloak_mbox_login_rest($user, $pass, array('is_internal' => $is_internal)); + if ($result !== false) { + // double check if mailbox and domain is active + $stmt = $pdo->prepare("SELECT * FROM `mailbox` + INNER JOIN domain on mailbox.domain = domain.domain + WHERE `kind` NOT REGEXP 'location|thing|group' + AND `mailbox`.`active`='1' + AND `domain`.`active`='1' + AND `username` = :user"); + $stmt->execute(array(':user' => $user)); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + if (empty($row)) { + return false; + } + + // check for tfa authenticators + $authenticators = get_tfa($user); + if (isset($authenticators['additional']) && is_array($authenticators['additional']) && count($authenticators['additional']) > 0 && !$is_internal) { + // authenticators found, init TFA flow + $_SESSION['pending_mailcow_cc_username'] = $user; + $_SESSION['pending_mailcow_cc_role'] = "user"; + $_SESSION['pending_tfa_methods'] = $authenticators['additional']; + unset($_SESSION['ldelay']); + $_SESSION['return'][] = array( + 'type' => 'success', + 'log' => array(__FUNCTION__, $user, '*', 'Provider: Keycloak'), + 'msg' => array('logged_in_as', $user) + ); + return "pending"; + } else if (!isset($authenticators['additional']) || !is_array($authenticators['additional']) || count($authenticators['additional']) == 0) { + // no authenticators found, login successfull + if (!$is_internal){ + unset($_SESSION['ldelay']); + // Reactivate TFA if it was set to "deactivate TFA for next login" + $stmt = $pdo->prepare("UPDATE `tfa` SET `active`='1' WHERE `username` = :user"); + $stmt->execute(array(':user' => $user)); + $_SESSION['return'][] = array( + 'type' => 'success', + 'log' => array(__FUNCTION__, $user, '*', 'Provider: Keycloak'), + 'msg' => array('logged_in_as', $user) + ); + } + return "user"; + } + } + return $result; + } else { + return false; + } + break; + case 'ldap': + // user authsource is ldap + $result = ldap_mbox_login($user, $pass, array('is_internal' => $is_internal)); + if ($result !== false) { + // double check if mailbox and domain is active + $stmt = $pdo->prepare("SELECT * FROM `mailbox` + INNER JOIN domain on mailbox.domain = domain.domain + WHERE `kind` NOT REGEXP 'location|thing|group' + AND `mailbox`.`active`='1' + AND `domain`.`active`='1' + AND `username` = :user"); + $stmt->execute(array(':user' => $user)); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + if (empty($row)) { + return false; + } + + // check for tfa authenticators + $authenticators = get_tfa($user); + if (isset($authenticators['additional']) && is_array($authenticators['additional']) && count($authenticators['additional']) > 0 && !$is_internal) { + // authenticators found, init TFA flow + $_SESSION['pending_mailcow_cc_username'] = $user; + $_SESSION['pending_mailcow_cc_role'] = "user"; + $_SESSION['pending_tfa_methods'] = $authenticators['additional']; + unset($_SESSION['ldelay']); + $_SESSION['return'][] = array( + 'type' => 'success', + 'log' => array(__FUNCTION__, $user, '*', 'Provider: LDAP'), + 'msg' => array('logged_in_as', $user) + ); + return "pending"; + } else if (!isset($authenticators['additional']) || !is_array($authenticators['additional']) || count($authenticators['additional']) == 0) { + // no authenticators found, login successfull + if (!$is_internal){ + unset($_SESSION['ldelay']); + // Reactivate TFA if it was set to "deactivate TFA for next login" + $stmt = $pdo->prepare("UPDATE `tfa` SET `active`='1' WHERE `username` = :user"); + $stmt->execute(array(':user' => $user)); + $_SESSION['return'][] = array( + 'type' => 'success', + 'log' => array(__FUNCTION__, $user, '*', 'Provider: LDAP'), + 'msg' => array('logged_in_as', $user) + ); + } + return "user"; + } + } + return $result; + break; + case 'mailcow': + if ($row['active'] != 1 || $row['d_active'] != 1) { + return false; + } + // verify password + if (verify_hash($row['password'], $pass) !== false) { + + if (intval($row['attributes']['force_pw_update']) == 1) { + $_SESSION['pending_pw_update'] = true; + } + + // check for tfa authenticators + $authenticators = get_tfa($user); + if (isset($authenticators['additional']) && is_array($authenticators['additional']) && count($authenticators['additional']) > 0 && !$is_internal) { + // authenticators found, init TFA flow + $_SESSION['pending_mailcow_cc_username'] = $user; + $_SESSION['pending_mailcow_cc_role'] = "user"; + $_SESSION['pending_tfa_methods'] = $authenticators['additional']; + unset($_SESSION['ldelay']); + $_SESSION['return'][] = array( + 'type' => 'success', + 'log' => array(__FUNCTION__, $user, '*', 'Provider: mailcow'), + 'msg' => array('logged_in_as', $user) + ); + return "pending"; + } else if (!isset($authenticators['additional']) || !is_array($authenticators['additional']) || count($authenticators['additional']) == 0) { + // no authenticators found, login successfull + if (!$is_internal){ + unset($_SESSION['ldelay']); + // Reactivate TFA if it was set to "deactivate TFA for next login" + $stmt = $pdo->prepare("UPDATE `tfa` SET `active`='1' WHERE `username` = :user"); + $stmt->execute(array(':user' => $user)); + $_SESSION['return'][] = array( + 'type' => 'success', + 'log' => array(__FUNCTION__, $user, '*', 'Provider: mailcow'), + 'msg' => array('logged_in_as', $user) + ); + } + return "user"; + } + } + break; + } + + return false; +} +function apppass_login($user, $pass, $app_passwd_data, $extra = null){ + global $pdo; + + $is_internal = $extra['is_internal']; + + if (!filter_var($user, FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $user))) { + if (!$is_internal){ + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $user, '*'), + 'msg' => 'malformed_username' + ); + } + return false; + } + + $protocol = false; + if ($app_passwd_data['eas']){ + $protocol = 'eas'; + } else if ($app_passwd_data['dav']){ + $protocol = 'dav'; + } else if ($app_passwd_data['smtp']){ + $protocol = 'smtp'; + } else if ($app_passwd_data['imap']){ + $protocol = 'imap'; + } else if ($app_passwd_data['sieve']){ + $protocol = 'sieve'; + } else if ($app_passwd_data['pop3']){ + $protocol = 'pop3'; + } else if (!$is_internal) { + return false; + } + + // fetch app password data + $stmt = $pdo->prepare("SELECT `app_passwd`.*, `app_passwd`.`password` as `password`, `app_passwd`.`id` as `app_passwd_id` FROM `app_passwd` + INNER JOIN `mailbox` ON `mailbox`.`username` = `app_passwd`.`mailbox` + INNER JOIN `domain` ON `mailbox`.`domain` = `domain`.`domain` + WHERE `mailbox`.`kind` NOT REGEXP 'location|thing|group' + AND `mailbox`.`active` = '1' + AND `domain`.`active` = '1' + AND `app_passwd`.`active` = '1' + AND `app_passwd`.`mailbox` = :user" + ); + // fetch password data + $stmt->execute(array( + ':user' => $user, + )); + $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); + + foreach ($rows as $row) { + if ($protocol && $row[$protocol . '_access'] != '1'){ + continue; + } + + // verify password + if (verify_hash($row['password'], $pass) !== false) { + $_SESSION['app_passwd_id'] = $row['app_passwd_id']; + unset($_SESSION['ldelay']); + return "user"; + } + } + + return false; +} +// Keycloak REST Api Flow - auth user by mailcow_password attribute +// This password will be used for direct UI, IMAP and SMTP Auth +// To use direct user credentials, only Authorization Code Flow is valid +function keycloak_mbox_login_rest($user, $pass, $extra = null){ + global $pdo; + global $iam_provider; + global $iam_settings; + + $is_internal = $extra['is_internal']; + $create = $extra['create']; + + if (!filter_var($user, FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $user))) { + if (!$is_internal){ + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $user, '*'), + 'msg' => 'malformed_username' + ); + } + return false; + } + if (!$iam_provider) { + return false; + } + + // get access_token for service account of mailcow client + $admin_token = identity_provider("get-keycloak-admin-token"); + + // get the mailcow_password attribute from keycloak user + $url = "{$iam_settings['server_url']}/admin/realms/{$iam_settings['realm']}/users"; + $queryParams = array('email' => $user, 'exact' => true); + $queryString = http_build_query($queryParams); + $curl = curl_init(); + curl_setopt($curl, CURLOPT_TIMEOUT, 7); + curl_setopt($curl, CURLOPT_URL, $url . '?' . $queryString); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curl, CURLOPT_HTTPHEADER, array( + 'Authorization: Bearer ' . $admin_token, + 'Content-Type: application/json' + )); + $user_res = json_decode(curl_exec($curl), true)[0]; + $code = curl_getinfo($curl, CURLINFO_HTTP_CODE); + curl_close($curl); + if ($code != 200) { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $user, '*', 'Identity Provider returned HTTP ' . $code), + 'msg' => 'generic_server_error' + ); + return false; + } + if (!isset($user_res['attributes']['mailcow_password']) || !is_array($user_res['attributes']['mailcow_password'])){ + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $user, '*', 'User has no mailcow_password attribute'), + 'msg' => 'generic_server_error' + ); + return false; + } + if (empty($user_res['attributes']['mailcow_password'][0])){ + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $user, '*', "User's mailcow_password attribute is empty"), + 'msg' => 'generic_server_error' + ); + return false; + } + + // validate mailcow_password + $mailcow_password = $user_res['attributes']['mailcow_password'][0]; + if (!verify_hash($mailcow_password, $pass)) { + return false; + } + + // get mapped template + $user_template = $user_res['attributes']['mailcow_template'][0]; + $mapper_key = array_search($user_template, $iam_settings['mappers']); + + if (!$create) { + // login success + if ($mapper_key !== false) { + // update user + $_SESSION['access_all_exception'] = '1'; + mailbox('edit', 'mailbox_from_template', array( + 'username' => $user, + 'name' => $user_res['name'], + 'template' => $iam_settings['templates'][$mapper_key] + )); + $_SESSION['access_all_exception'] = '0'; + } + return 'user'; + } + + // check if login provisioning is enabled before creating user + if (!$iam_settings['login_provisioning']){ + if (!$is_internal){ + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, "Auto-create users on login is deactivated"), + 'msg' => 'login_failed' + ); + } + return false; + } + // check if matching attribute exist + if (empty($iam_settings['mappers']) || !$user_template || $mapper_key === false) { + if (!empty($iam_settings['default_template'])) { + $mbox_template = $iam_settings['default_template']; + } else { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $user, '*', 'No matching attribute mapping was found'), + 'msg' => 'generic_server_error' + ); + return false; + } + } else { + $mbox_template = $iam_settings['templates'][$mapper_key]; + } + + // create mailbox + $_SESSION['access_all_exception'] = '1'; + $create_res = mailbox('add', 'mailbox_from_template', array( + 'domain' => explode('@', $user)[1], + 'local_part' => explode('@', $user)[0], + 'name' => $user_res['name'], + 'authsource' => 'keycloak', + 'template' => $mbox_template + )); + $_SESSION['access_all_exception'] = '0'; + if (!$create_res){ + clear_session(); + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $user, '*', 'Could not create mailbox on login'), + 'msg' => 'generic_server_error' + ); + return false; + } + + return 'user'; +} +function ldap_mbox_login($user, $pass, $extra = null){ + global $pdo; + global $iam_provider; + global $iam_settings; + + $is_internal = $extra['is_internal']; + $create = $extra['create']; + + if (!filter_var($user, FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $user))) { + if (!$is_internal){ + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $user, '*'), + 'msg' => 'malformed_username' + ); + } + return false; + } + if (!$iam_provider) { + return false; + } + + try { + $ldap_query = $iam_provider->query(); + if (!empty($iam_settings['filter'])) { + $ldap_query = $ldap_query->rawFilter($iam_settings['filter']); + } + $ldap_query = $ldap_query->where($iam_settings['username_field'], '=', $user) + ->select([$iam_settings['username_field'], $iam_settings['attribute_field'], 'displayname', 'distinguishedname', 'dn']); + + $user_res = $ldap_query->firstOrFail(); + } catch (Exception $e) { + // clear $_SESSION['return'] to not leak data + $_SESSION['return'] = array(); + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $user, '*', $e->getMessage()), + 'msg' => 'generic_server_error' + ); + return false; + } + try { + if (!$iam_provider->auth()->attempt($user_res['dn'], $pass)) { + return false; + } + } catch (Exception $e) { + // clear $_SESSION['return'] to not leak data + $_SESSION['return'] = array(); + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $user, '*', $e->getMessage()), + 'msg' => 'generic_server_error' + ); + return false; + } + + // get mapped template + $user_template = $user_res[$iam_settings['attribute_field']][0]; + $mapper_key = array_search($user_template, $iam_settings['mappers']); + + if (!$create) { + // login success + if ($mapper_key !== false) { + // update user + $_SESSION['access_all_exception'] = '1'; + mailbox('edit', 'mailbox_from_template', array( + 'username' => $user, + 'name' => $user_res['displayname'][0], + 'template' => $iam_settings['templates'][$mapper_key] + )); + $_SESSION['access_all_exception'] = '0'; + } + return 'user'; + } + + // check if login provisioning is enabled before creating user + if (!$iam_settings['login_provisioning']){ + if (!$is_internal){ + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, "Auto-create users on login is deactivated"), + 'msg' => 'login_failed' + ); + } + return false; + } + // check if matching attribute exist + if (empty($iam_settings['mappers']) || !$user_template || $mapper_key === false) { + if (!empty($iam_settings['default_template'])) { + $mbox_template = $iam_settings['default_template']; + } else { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $user, '*', 'No matching attribute mapping was found'), + 'msg' => 'generic_server_error' + ); + return false; + } + } else { + $mbox_template = $iam_settings['templates'][$mapper_key]; + } + + // create mailbox + $_SESSION['access_all_exception'] = '1'; + $create_res = mailbox('add', 'mailbox_from_template', array( + 'domain' => explode('@', $user)[1], + 'local_part' => explode('@', $user)[0], + 'name' => $user_res['displayname'][0], + 'authsource' => 'ldap', + 'template' => $mbox_template + )); + $_SESSION['access_all_exception'] = '0'; + if (!$create_res){ + clear_session(); + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $user, '*', 'Could not create mailbox on login'), + 'msg' => 'generic_server_error' + ); + return false; + } + + return 'user'; +} diff --git a/data/web/inc/functions.customize.inc.php b/data/web/inc/functions.customize.inc.php index 72ae389c7..0c0cff4e5 100644 --- a/data/web/inc/functions.customize.inc.php +++ b/data/web/inc/functions.customize.inc.php @@ -122,10 +122,16 @@ function customize($_action, $_item, $_data = null) { case 'app_links': $apps = (array)$_data['app']; $links = (array)$_data['href']; + $user_links = (array)$_data['user_href']; + $hide = (array)$_data['hide']; $out = array(); - if (count($apps) == count($links)) { + if (count($apps) == count($links) && count($apps) == count($user_links) && count($apps) == count($hide)) { for ($i = 0; $i < count($apps); $i++) { - $out[] = array($apps[$i] => $links[$i]); + $out[] = array($apps[$i] => array( + 'link' => $links[$i], + 'user_link' => $user_links[$i], + 'hide' => ($hide[$i] === '0' || $hide[$i] === 0) ? false : true + )); } try { $valkey->set('APP_LINKS', json_encode($out)); @@ -198,6 +204,35 @@ function customize($_action, $_item, $_data = null) { 'msg' => 'ip_check_opt_in_modified' ); break; + case 'custom_login': + $hide_user_quicklink = ($_data['hide_user_quicklink'] == "1") ? 1 : 0; + $hide_domainadmin_quicklink = ($_data['hide_domainadmin_quicklink'] == "1") ? 1 : 0; + $hide_admin_quicklink = ($_data['hide_admin_quicklink'] == "1") ? 1 : 0; + $force_sso = ($_data['force_sso'] == "1") ? 1 : 0; + + $custom_login = array( + "hide_user_quicklink" => $hide_user_quicklink, + "hide_domainadmin_quicklink" => $hide_domainadmin_quicklink, + "hide_admin_quicklink" => $hide_admin_quicklink, + "force_sso" => $force_sso, + ); + try { + $valkey->set('CUSTOM_LOGIN', json_encode($custom_login)); + } + catch (RedisException $e) { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_action, $_item, $_data), + 'msg' => array('redis_error', $e) + ); + return false; + } + $_SESSION['return'][] = array( + 'type' => 'success', + 'log' => array(__FUNCTION__, $_action, $_item, $_data), + 'msg' => 'custom_login_modified' + ); + break; } break; case 'delete': @@ -256,7 +291,23 @@ function customize($_action, $_item, $_data = null) { ); return false; } - return ($app_links) ? $app_links : false; + + if (empty($app_links)){ + return []; + } + + // convert from old style + foreach($app_links as $i => $entry){ + foreach($entry as $app => $link){ + if (empty($link['link']) && empty($link['user_link'])){ + $app_links[$i][$app] = array(); + $app_links[$i][$app]['link'] = $link; + $app_links[$i][$app]['user_link'] = $link; + } + } + } + + return $app_links; break; case 'main_logo': case 'main_logo_dark': @@ -274,8 +325,10 @@ function customize($_action, $_item, $_data = null) { break; case 'ui_texts': try { - $data['title_name'] = ($title_name = $valkey->get('TITLE_NAME')) ? $title_name : 'mailcow UI'; - $data['main_name'] = ($main_name = $valkey->get('MAIN_NAME')) ? $main_name : 'mailcow UI'; + $mailcow_hostname = strtolower(getenv("MAILCOW_HOSTNAME")); + + $data['title_name'] = ($title_name = $valkey->get('TITLE_NAME')) ? $title_name : "$mailcow_hostname - mail UI"; + $data['main_name'] = ($main_name = $valkey->get('MAIN_NAME')) ? $main_name : "$mailcow_hostname - mail UI"; $data['apps_name'] = ($apps_name = $valkey->get('APPS_NAME')) ? $apps_name : $lang['header']['apps']; $data['help_text'] = ($help_text = $valkey->get('HELP_TEXT')) ? $help_text : false; if (!empty($valkey->get('UI_IMPRESS'))) { @@ -335,6 +388,20 @@ function customize($_action, $_item, $_data = null) { return false; } break; + case 'custom_login': + try { + $custom_login = $valkey->get('CUSTOM_LOGIN'); + return $custom_login ? json_decode($custom_login, true) : array(); + } + catch (RedisException $e) { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_action, $_item, $_data), + 'msg' => array('redis_error', $e) + ); + return false; + } + break; } break; } diff --git a/data/web/inc/functions.dkim.inc.php b/data/web/inc/functions.dkim.inc.php index 8592592f7..1ae57a2ea 100644 --- a/data/web/inc/functions.dkim.inc.php +++ b/data/web/inc/functions.dkim.inc.php @@ -240,9 +240,12 @@ function dkim($_action, $_data = null, $privkey = false) { if (strlen($dkimdata['pubkey']) < 391) { $dkimdata['length'] = "1024"; } - elseif (strlen($dkimdata['pubkey']) < 736) { + elseif (strlen($dkimdata['pubkey']) < 564) { $dkimdata['length'] = "2048"; } + elseif (strlen($dkimdata['pubkey']) < 736) { + $dkimdata['length'] = "3072"; + } elseif (strlen($dkimdata['pubkey']) < 1416) { $dkimdata['length'] = "4096"; } diff --git a/data/web/inc/functions.inc.php b/data/web/inc/functions.inc.php index 982e86d40..b7f6814cf 100644 --- a/data/web/inc/functions.inc.php +++ b/data/web/inc/functions.inc.php @@ -350,6 +350,34 @@ function last_login($action, $username, $sasl_limit_days = 7, $ui_offset = 1) { } } +function set_sasl_log($username, $real_rip, $service){ + global $pdo; + + try { + if (!empty($_SESSION['app_passwd_id'])) { + $app_password = $_SESSION['app_passwd_id']; + } else { + $app_password = 0; + } + + $stmt = $pdo->prepare('REPLACE INTO `sasl_log` (`username`, `real_rip`, `service`, `app_password`) VALUES (:username, :real_rip, :service, :app_password)'); + $stmt->execute(array( + ':username' => $username, + ':real_rip' => $real_rip, + ':service' => $service, + ':app_password' => $app_password + )); + } catch (PDOException $e) { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_data_log), + 'msg' => array('mysql_error', $e) + ); + return false; + } + + return true; +} function flush_memcached() { try { $m = new Memcached(); @@ -538,10 +566,13 @@ function logger($_data = false) { } function hasDomainAccess($username, $role, $domain) { global $pdo; - if (!filter_var($username, FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $username))) { + if (empty($domain) || !is_valid_domain_name($domain)) { return false; } - if (empty($domain) || !is_valid_domain_name($domain)) { + if (isset($_SESSION['access_all_exception']) && $_SESSION['access_all_exception'] == "1") { + return true; + } + if (!filter_var($username, FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $username))) { return false; } if ($role != 'admin' && $role != 'domainadmin') { @@ -577,6 +608,9 @@ function hasDomainAccess($username, $role, $domain) { } function hasMailboxObjectAccess($username, $role, $object) { global $pdo; + if (isset($_SESSION['access_all_exception']) && $_SESSION['access_all_exception'] == "1") { + return true; + } if (empty($username) || empty($role) || empty($object)) { return false; } @@ -600,6 +634,9 @@ function hasMailboxObjectAccess($username, $role, $object) { // does also verify mailboxes as a mailbox is a alias == goto function hasAliasObjectAccess($username, $role, $object) { global $pdo; + if (isset($_SESSION['access_all_exception']) && $_SESSION['access_all_exception'] == "1") { + return true; + } if (empty($username) || empty($role) || empty($object)) { return false; } @@ -617,6 +654,16 @@ function hasAliasObjectAccess($username, $role, $object) { } return false; } +function hasACLAccess($type) { + if (isset($_SESSION['access_all_exception']) && $_SESSION['access_all_exception'] == "1") { + return true; + } + if (isset($_SESSION['acl'][$type]) && $_SESSION['acl'][$type] == "1") { + return true; + } + + return false; +} function pem_to_der($pem_key) { // Need to remove BEGIN/END PUBLIC KEY $lines = explode("\n", trim($pem_key)); @@ -811,200 +858,6 @@ function verify_hash($hash, $password) { } return false; } -function check_login($user, $pass, $app_passwd_data = false) { - global $pdo; - global $valkey; - global $imap_server; - - if (!filter_var($user, FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $user))) { - $_SESSION['return'][] = array( - 'type' => 'danger', - 'log' => array(__FUNCTION__, $user, '*'), - 'msg' => 'malformed_username' - ); - return false; - } - - // Validate admin - $user = strtolower(trim($user)); - $stmt = $pdo->prepare("SELECT `password` FROM `admin` - WHERE `superadmin` = '1' - AND `active` = '1' - AND `username` = :user"); - $stmt->execute(array(':user' => $user)); - $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); - foreach ($rows as $row) { - // verify password - if (verify_hash($row['password'], $pass)) { - // check for tfa authenticators - $authenticators = get_tfa($user); - if (isset($authenticators['additional']) && is_array($authenticators['additional']) && count($authenticators['additional']) > 0) { - // active tfa authenticators found, set pending user login - $_SESSION['pending_mailcow_cc_username'] = $user; - $_SESSION['pending_mailcow_cc_role'] = "admin"; - $_SESSION['pending_tfa_methods'] = $authenticators['additional']; - unset($_SESSION['ldelay']); - $_SESSION['return'][] = array( - 'type' => 'info', - 'log' => array(__FUNCTION__, $user, '*'), - 'msg' => 'awaiting_tfa_confirmation' - ); - return "pending"; - } else { - unset($_SESSION['ldelay']); - // Reactivate TFA if it was set to "deactivate TFA for next login" - $stmt = $pdo->prepare("UPDATE `tfa` SET `active`='1' WHERE `username` = :user"); - $stmt->execute(array(':user' => $user)); - $_SESSION['return'][] = array( - 'type' => 'success', - 'log' => array(__FUNCTION__, $user, '*'), - 'msg' => array('logged_in_as', $user) - ); - return "admin"; - } - } - } - - // Validate domain admin - $stmt = $pdo->prepare("SELECT `password` FROM `admin` - WHERE `superadmin` = '0' - AND `active`='1' - AND `username` = :user"); - $stmt->execute(array(':user' => $user)); - $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); - foreach ($rows as $row) { - // verify password - if (verify_hash($row['password'], $pass) !== false) { - // check for tfa authenticators - $authenticators = get_tfa($user); - if (isset($authenticators['additional']) && is_array($authenticators['additional']) && count($authenticators['additional']) > 0) { - $_SESSION['pending_mailcow_cc_username'] = $user; - $_SESSION['pending_mailcow_cc_role'] = "domainadmin"; - $_SESSION['pending_tfa_methods'] = $authenticators['additional']; - unset($_SESSION['ldelay']); - $_SESSION['return'][] = array( - 'type' => 'info', - 'log' => array(__FUNCTION__, $user, '*'), - 'msg' => 'awaiting_tfa_confirmation' - ); - return "pending"; - } - else { - unset($_SESSION['ldelay']); - // Reactivate TFA if it was set to "deactivate TFA for next login" - $stmt = $pdo->prepare("UPDATE `tfa` SET `active`='1' WHERE `username` = :user"); - $stmt->execute(array(':user' => $user)); - $_SESSION['return'][] = array( - 'type' => 'success', - 'log' => array(__FUNCTION__, $user, '*'), - 'msg' => array('logged_in_as', $user) - ); - return "domainadmin"; - } - } - } - - // Validate mailbox user - $stmt = $pdo->prepare("SELECT `password` FROM `mailbox` - INNER JOIN domain on mailbox.domain = domain.domain - WHERE `kind` NOT REGEXP 'location|thing|group' - AND `mailbox`.`active`='1' - AND `domain`.`active`='1' - AND `username` = :user"); - $stmt->execute(array(':user' => $user)); - $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); - if ($app_passwd_data['eas'] === true) { - $stmt = $pdo->prepare("SELECT `app_passwd`.`password` as `password`, `app_passwd`.`id` as `app_passwd_id` FROM `app_passwd` - INNER JOIN `mailbox` ON `mailbox`.`username` = `app_passwd`.`mailbox` - INNER JOIN `domain` ON `mailbox`.`domain` = `domain`.`domain` - WHERE `mailbox`.`kind` NOT REGEXP 'location|thing|group' - AND `mailbox`.`active` = '1' - AND `domain`.`active` = '1' - AND `app_passwd`.`active` = '1' - AND `app_passwd`.`eas_access` = '1' - AND `app_passwd`.`mailbox` = :user"); - $stmt->execute(array(':user' => $user)); - $rows = array_merge($rows, $stmt->fetchAll(PDO::FETCH_ASSOC)); - } - elseif ($app_passwd_data['dav'] === true) { - $stmt = $pdo->prepare("SELECT `app_passwd`.`password` as `password`, `app_passwd`.`id` as `app_passwd_id` FROM `app_passwd` - INNER JOIN `mailbox` ON `mailbox`.`username` = `app_passwd`.`mailbox` - INNER JOIN `domain` ON `mailbox`.`domain` = `domain`.`domain` - WHERE `mailbox`.`kind` NOT REGEXP 'location|thing|group' - AND `mailbox`.`active` = '1' - AND `domain`.`active` = '1' - AND `app_passwd`.`active` = '1' - AND `app_passwd`.`dav_access` = '1' - AND `app_passwd`.`mailbox` = :user"); - $stmt->execute(array(':user' => $user)); - $rows = array_merge($rows, $stmt->fetchAll(PDO::FETCH_ASSOC)); - } - foreach ($rows as $row) { - // verify password - if (verify_hash($row['password'], $pass) !== false) { - if (!array_key_exists("app_passwd_id", $row)){ - // password is not a app password - // check for tfa authenticators - $authenticators = get_tfa($user); - if (isset($authenticators['additional']) && is_array($authenticators['additional']) && count($authenticators['additional']) > 0 && - $app_passwd_data['eas'] !== true && $app_passwd_data['dav'] !== true) { - // authenticators found, init TFA flow - $_SESSION['pending_mailcow_cc_username'] = $user; - $_SESSION['pending_mailcow_cc_role'] = "user"; - $_SESSION['pending_tfa_methods'] = $authenticators['additional']; - unset($_SESSION['ldelay']); - return "pending"; - } else if (!isset($authenticators['additional']) || !is_array($authenticators['additional']) || count($authenticators['additional']) == 0) { - // no authenticators found, login successfull - // Reactivate TFA if it was set to "deactivate TFA for next login" - $stmt = $pdo->prepare("UPDATE `tfa` SET `active`='1' WHERE `username` = :user"); - $stmt->execute(array(':user' => $user)); - - unset($_SESSION['ldelay']); - $_SESSION['return'][] = array( - 'type' => 'success', - 'log' => array(__FUNCTION__, $user, '*'), - 'msg' => array('logged_in_as', $user) - ); - return "user"; - } - } elseif ($app_passwd_data['eas'] === true || $app_passwd_data['dav'] === true) { - // password is a app password - $service = ($app_passwd_data['eas'] === true) ? 'EAS' : 'DAV'; - $stmt = $pdo->prepare("REPLACE INTO sasl_log (`service`, `app_password`, `username`, `real_rip`) VALUES (:service, :app_id, :username, :remote_addr)"); - $stmt->execute(array( - ':service' => $service, - ':app_id' => $row['app_passwd_id'], - ':username' => $user, - ':remote_addr' => ($_SERVER['HTTP_X_REAL_IP'] ?? $_SERVER['REMOTE_ADDR']) - )); - - unset($_SESSION['ldelay']); - return "user"; - } - } - } - - if (!isset($_SESSION['ldelay'])) { - $_SESSION['ldelay'] = "0"; - $valkey->publish("F2B_CHANNEL", "mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']); - error_log("mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']); - } - elseif (!isset($_SESSION['mailcow_cc_username'])) { - $_SESSION['ldelay'] = $_SESSION['ldelay']+0.5; - $valkey->publish("F2B_CHANNEL", "mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']); - error_log("mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']); - } - - $_SESSION['return'][] = array( - 'type' => 'danger', - 'log' => array(__FUNCTION__, $user, '*'), - 'msg' => 'login_failed' - ); - - sleep($_SESSION['ldelay']); - return false; -} function formatBytes($size, $precision = 2) { if(!is_numeric($size)) { return "0"; @@ -1034,36 +887,60 @@ function update_sogo_static_view($mailbox = null) { } } - $query = "REPLACE INTO _sogo_static_view (`c_uid`, `domain`, `c_name`, `c_password`, `c_cn`, `mail`, `aliases`, `ad_aliases`, `ext_acl`, `kind`, `multiple_bookings`) - SELECT - mailbox.username, - mailbox.domain, - mailbox.username, - IF(JSON_UNQUOTE(JSON_VALUE(attributes, '$.force_pw_update')) = '0', - IF(JSON_UNQUOTE(JSON_VALUE(attributes, '$.sogo_access')) = 1, password, '{SSHA256}A123A123A321A321A321B321B321B123B123B321B432F123E321123123321321'), - '{SSHA256}A123A123A321A321A321B321B321B123B123B321B432F123E321123123321321'), - mailbox.name, - mailbox.username, - IFNULL(GROUP_CONCAT(ga.aliases ORDER BY ga.aliases SEPARATOR ' '), ''), - IFNULL(gda.ad_alias, ''), - IFNULL(external_acl.send_as_acl, ''), - mailbox.kind, - mailbox.multiple_bookings - FROM - mailbox - LEFT OUTER JOIN grouped_mail_aliases ga ON ga.username REGEXP CONCAT('(^|,)', mailbox.username, '($|,)') - LEFT OUTER JOIN grouped_domain_alias_address gda ON gda.username = mailbox.username - LEFT OUTER JOIN grouped_sender_acl_external external_acl ON external_acl.username = mailbox.username - WHERE - mailbox.active = '1'"; + // generate random password for sogo to deny direct login + $random_password = base64_encode(openssl_random_pseudo_bytes(24)); + $random_salt = base64_encode(openssl_random_pseudo_bytes(16)); + $random_hash = '{SSHA256}' . base64_encode(hash('sha256', base64_decode($password) . $salt, true) . $salt); + + $subquery = "GROUP BY mailbox.username"; + if ($mailbox_exists) { + $subquery = "AND mailbox.username = :mailbox"; + } + $query = "INSERT INTO _sogo_static_view (`c_uid`, `domain`, `c_name`, `c_password`, `c_cn`, `mail`, `aliases`, `ad_aliases`, `ext_acl`, `kind`, `multiple_bookings`) + SELECT + mailbox.username, + mailbox.domain, + mailbox.username, + :random_hash, + mailbox.name, + mailbox.username, + IFNULL(GROUP_CONCAT(ga.aliases ORDER BY ga.aliases SEPARATOR ' '), ''), + IFNULL(gda.ad_alias, ''), + IFNULL(external_acl.send_as_acl, ''), + mailbox.kind, + mailbox.multiple_bookings + FROM + mailbox + LEFT OUTER JOIN grouped_mail_aliases ga ON ga.username REGEXP CONCAT('(^|,)', mailbox.username, '($|,)') + LEFT OUTER JOIN grouped_domain_alias_address gda ON gda.username = mailbox.username + LEFT OUTER JOIN grouped_sender_acl_external external_acl ON external_acl.username = mailbox.username + WHERE + mailbox.active = '1' + $subquery + ON DUPLICATE KEY UPDATE + `domain` = VALUES(`domain`), + `c_name` = VALUES(`c_name`), + `c_password` = VALUES(`c_password`), + `c_cn` = VALUES(`c_cn`), + `mail` = VALUES(`mail`), + `aliases` = VALUES(`aliases`), + `ad_aliases` = VALUES(`ad_aliases`), + `ext_acl` = VALUES(`ext_acl`), + `kind` = VALUES(`kind`), + `multiple_bookings` = VALUES(`multiple_bookings`)"; + if ($mailbox_exists) { - $query .= " AND mailbox.username = :mailbox"; $stmt = $pdo->prepare($query); - $stmt->execute(array(':mailbox' => $mailbox)); + $stmt->execute(array( + ':random_hash' => $random_hash, + ':mailbox' => $mailbox + )); } else { - $query .= " GROUP BY mailbox.username"; - $stmt = $pdo->query($query); + $stmt = $pdo->prepare($query); + $stmt->execute(array( + ':random_hash' => $random_hash + )); } $stmt = $pdo->query("DELETE FROM _sogo_static_view WHERE `c_uid` NOT IN (SELECT `username` FROM `mailbox` WHERE `active` = '1');"); @@ -1097,7 +974,7 @@ function edit_user_account($_data) { if (!empty($password_old) && !empty($_data['user_new_pass']) && !empty($_data['user_new_pass2'])) { $stmt = $pdo->prepare("SELECT `password` FROM `mailbox` WHERE `kind` NOT REGEXP 'location|thing|group' - AND `username` = :user"); + AND `username` = :user AND authsource = 'mailcow'"); $stmt->execute(array(':user' => $username)); $row = $stmt->fetch(PDO::FETCH_ASSOC); @@ -1119,11 +996,12 @@ function edit_user_account($_data) { $stmt = $pdo->prepare("UPDATE `mailbox` SET `password` = :password_hashed, `attributes` = JSON_SET(`attributes`, '$.force_pw_update', '0'), `attributes` = JSON_SET(`attributes`, '$.passwd_update', NOW()) - WHERE `username` = :username"); + WHERE `username` = :username AND authsource = 'mailcow'"); $stmt->execute(array( ':password_hashed' => $password_hashed, ':username' => $username )); + $_SESSION['pending_pw_update'] = false; update_sogo_static_view(); } @@ -1140,7 +1018,7 @@ function edit_user_account($_data) { $pw_recovery_email = (!filter_var($pw_recovery_email, FILTER_VALIDATE_EMAIL)) ? '' : $pw_recovery_email; $stmt = $pdo->prepare("UPDATE `mailbox` SET `attributes` = JSON_SET(`attributes`, '$.recovery_email', :recovery_email) - WHERE `username` = :username"); + WHERE `username` = :username AND authsource = 'mailcow'"); $stmt->execute(array( ':recovery_email' => $pw_recovery_email, ':username' => $username @@ -1229,11 +1107,21 @@ function user_get_alias_details($username) { } return $data; } -function is_valid_domain_name($domain_name) { +function is_valid_domain_name($domain_name, $options = array()) { if (empty($domain_name)) { return false; } + + // Convert domain name to ASCII for validation $domain_name = idn_to_ascii($domain_name, 0, INTL_IDNA_VARIANT_UTS46); + + if (isset($options['allow_wildcard']) && $options['allow_wildcard'] == true) { + // Remove '*.' if wildcard subdomains are allowed + if (strpos($domain_name, '*.') === 0) { + $domain_name = substr($domain_name, 2); + } + } + return (preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $domain_name) && preg_match("/^.{1,253}$/", $domain_name) && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $domain_name)); @@ -1242,6 +1130,8 @@ function set_tfa($_data) { global $pdo; global $yubi; global $tfa; + global $iam_settings; + $_data_log = $_data; $access_denied = null; !isset($_data_log['confirm_password']) ?: $_data_log['confirm_password'] = '*'; @@ -1264,13 +1154,18 @@ function set_tfa($_data) { // check mailbox confirm password if ($access_denied === null) { - $stmt = $pdo->prepare("SELECT `password` FROM `mailbox` + $stmt = $pdo->prepare("SELECT `password`, `authsource` FROM `mailbox` WHERE `username` = :username"); $stmt->execute(array(':username' => $username)); $row = $stmt->fetch(PDO::FETCH_ASSOC); if ($row) { - if (!verify_hash($row['password'], $_data["confirm_password"])) $access_denied = true; - else $access_denied = false; + if ($row['authsource'] == 'ldap'){ + if (!ldap_mbox_login($username, $_data["confirm_password"], $iam_settings)) $access_denied = true; + else $access_denied = false; + } else { + if (!verify_hash($row['password'], $_data["confirm_password"])) $access_denied = true; + else $access_denied = false; + } } } @@ -1394,6 +1289,7 @@ function set_tfa($_data) { } function fido2($_data) { global $pdo; + global $WebAuthn; $_data_log = $_data; // Not logging registration data, only actions // Silent errors for "get" requests @@ -1527,6 +1423,84 @@ function fido2($_data) { 'msg' => array('object_modified', htmlspecialchars($username)) ); break; + case "verify": + $role = ""; + $tokenData = json_decode($_data['token']); + $clientDataJSON = base64_decode($tokenData->clientDataJSON); + $authenticatorData = base64_decode($tokenData->authenticatorData); + $signature = base64_decode($tokenData->signature); + $id = base64_decode($tokenData->id); + $challenge = $_SESSION['challenge']; + $process_fido2 = fido2(array("action" => "get_by_b64cid", "cid" => $tokenData->id)); + if ($process_fido2['pub_key'] === false) { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array("fido2_login", $_data['user'], $process_fido2['username']), + 'msg' => "login_failed" + ); + return false; + } + try { + $WebAuthn->processGet($clientDataJSON, $authenticatorData, $signature, $process_fido2['pub_key'], $challenge, null, $GLOBALS['FIDO2_UV_FLAG_LOGIN'], $GLOBALS['FIDO2_USER_PRESENT_FLAG']); + } + catch (Throwable $ex) { + unset($process_fido2); + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array("fido2_login", $_data['user'], $process_fido2['username'], $ex->getMessage()), + 'msg' => "login_failed" + ); + return false; + } + $return = new stdClass(); + $return->success = true; + $stmt = $pdo->prepare("SELECT `superadmin` FROM `admin` WHERE `username` = :username"); + $stmt->execute(array(':username' => $process_fido2['username'])); + $obj_props = $stmt->fetch(PDO::FETCH_ASSOC); + if ($obj_props['superadmin'] === 1 && (!$_data['user'] || $_data['user'] == "admin")) { + $role = "admin"; + } + elseif ($obj_props['superadmin'] === 0 && (!$_data['user'] || $_data['user'] == "domainadmin")) { + $role = "domainadmin"; + } + elseif (!isset($obj_props['superadmin']) && (!$_data['user'] || $_data['user'] == "user")) { + $stmt = $pdo->prepare("SELECT `username` FROM `mailbox` WHERE `username` = :username"); + $stmt->execute(array(':username' => $process_fido2['username'])); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + if ($row['username'] == $process_fido2['username']) { + $role = "user"; + } + } + else { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array("fido2_login", $_data['user'], $process_fido2['username']), + 'msg' => 'login_failed' + ); + return false; + } + if (empty($role)) { + session_unset(); + session_destroy(); + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array("fido2_login", $_data['user'], $process_fido2['username']), + 'msg' => 'login_failed' + ); + return false; + } + unset($_SESSION["challenge"]); + $_SESSION['return'][] = array( + 'type' => 'success', + 'log' => array("fido2_login", $_data['user'], $process_fido2['username']), + 'msg' => array('logged_in_as', $process_fido2['username']) + ); + return array( + "role" => $role, + "username" => $process_fido2['username'], + "cid" => $process_fido2['cid'] + ); + break; } } function unset_tfa_key($_data) { @@ -2247,7 +2221,7 @@ function cors($action, $data = null) { $cors_settings['allowed_origins'] = $allowed_origins[0]; if (in_array('*', $allowed_origins)){ $cors_settings['allowed_origins'] = '*'; - } else if (in_array($_SERVER['HTTP_ORIGIN'], $allowed_origins)) { + } else if (array_key_exists('HTTP_ORIGIN', $_SERVER) && in_array($_SERVER['HTTP_ORIGIN'], $allowed_origins)) { $cors_settings['allowed_origins'] = $_SERVER['HTTP_ORIGIN']; } // always allow OPTIONS for preflight request @@ -2306,6 +2280,691 @@ function uuid4() { return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4)); } +function identity_provider($_action = null, $_data = null, $_extra = null) { + global $pdo; + global $iam_provider; + global $iam_settings; + + $data_log = $_data; + if (isset($data_log['client_secret'])) $data_log['client_secret'] = '*'; + if (isset($data_log['access_token'])) $data_log['access_token'] = '*'; + + switch ($_action) { + case 'get': + $settings = array(); + $stmt = $pdo->prepare("SELECT * FROM `identity_provider`;"); + $stmt->execute(); + $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); + foreach($rows as $row){ + switch ($row["key"]) { + case "redirect_url_extra": + case "mappers": + case "templates": + $settings[$row["key"]] = json_decode($row["value"]); + break; + case "use_ssl": + case "use_tls": + case "login_provisioning": + case "ignore_ssl_errors": + $settings[$row["key"]] = boolval($row["value"]); + break; + default: + $settings[$row["key"]] = $row["value"]; + break; + } + } + // set login_provisioning if not exists + if (!array_key_exists('login_provisioning', $settings)) { + $settings['login_provisioning'] = 1; + } + // return default client_scopes for generic-oidc if none is set + if ($settings["authsource"] == "generic-oidc" && empty($settings["client_scopes"])){ + $settings["client_scopes"] = "openid profile email mailcow_template"; + } + if ($_extra['hide_sensitive']){ + $settings['client_secret'] = ''; + $settings['access_token'] = ''; + } + // return default ldap options + if ($settings["authsource"] == "ldap"){ + $settings['use_ssl'] = !isset($settings['use_ssl']) ? false : $settings['use_ssl']; + $settings['use_tls'] = !isset($settings['use_tls']) ? false : $settings['use_tls']; + $settings['ignore_ssl_errors'] = !isset($settings['ignore_ssl_errors']) ? false : $settings['ignore_ssl_errors']; + } + return $settings; + break; + case 'edit': + if ($_SESSION['mailcow_cc_role'] != "admin") { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_action, $_data), + 'msg' => 'access_denied' + ); + return false; + } + if (!isset($_data['authsource'])){ + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_action, $data_log), + 'msg' => array('required_data_missing', '') + ); + return false; + } + + $available_authsources = array( + "keycloak", + "generic-oidc", + "ldap" + ); + $_data['authsource'] = strtolower($_data['authsource']); + if (!in_array($_data['authsource'], $available_authsources)){ + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_action, $data_log), + 'msg' => array('invalid_authsource', $setting) + ); + return false; + } + + $stmt = $pdo->prepare("SELECT * FROM `mailbox` + WHERE `authsource` != 'mailcow' + AND `authsource` IS NOT NULL + AND `authsource` != :authsource"); + $stmt->execute(array(':authsource' => $_data['authsource'])); + $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); + if ($rows) { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_action, $data_log), + 'msg' => array('authsource_in_use', $setting) + ); + return false; + } + + $_data['ignore_ssl_error'] = isset($_data['ignore_ssl_error']) ? boolval($_data['ignore_ssl_error']) : false; + $_data['login_provisioning'] = isset($_data['login_provisioning']) ? boolval($_data['login_provisioning']) : false; + switch ($_data['authsource']) { + case "keycloak": + $_data['server_url'] = (!empty($_data['server_url'])) ? rtrim($_data['server_url'], '/') : null; + $_data['mailpassword_flow'] = isset($_data['mailpassword_flow']) ? intval($_data['mailpassword_flow']) : 0; + $_data['periodic_sync'] = isset($_data['periodic_sync']) ? intval($_data['periodic_sync']) : 0; + $_data['import_users'] = isset($_data['import_users']) ? intval($_data['import_users']) : 0; + $_data['sync_interval'] = (!empty($_data['sync_interval'])) ? intval($_data['sync_interval']) : 15; + $_data['sync_interval'] = $_data['sync_interval'] < 1 ? 1 : $_data['sync_interval']; + $required_settings = array('authsource', 'server_url', 'realm', 'client_id', 'client_secret', 'redirect_url', 'version', 'mailpassword_flow', 'periodic_sync', 'import_users', 'sync_interval', 'ignore_ssl_error', 'login_provisioning'); + break; + case "generic-oidc": + $_data['authorize_url'] = (!empty($_data['authorize_url'])) ? $_data['authorize_url'] : null; + $_data['token_url'] = (!empty($_data['token_url'])) ? $_data['token_url'] : null; + $_data['userinfo_url'] = (!empty($_data['userinfo_url'])) ? $_data['userinfo_url'] : null; + $_data['client_scopes'] = (!empty($_data['client_scopes'])) ? $_data['client_scopes'] : "openid profile email mailcow_template"; + $required_settings = array('authsource', 'authorize_url', 'token_url', 'client_id', 'client_secret', 'redirect_url', 'userinfo_url', 'client_scopes', 'ignore_ssl_error', 'login_provisioning'); + break; + case "ldap": + $_data['host'] = (!empty($_data['host'])) ? str_replace(" ", "", $_data['host']) : ""; + $_data['port'] = (!empty($_data['port'])) ? intval($_data['port']) : 389; + $_data['username_field'] = (!empty($_data['username_field'])) ? strtolower($_data['username_field']) : "mail"; + $_data['attribute_field'] = (!empty($_data['attribute_field'])) ? strtolower($_data['attribute_field']) : ""; + $_data['filter'] = (!empty($_data['filter'])) ? $_data['filter'] : ""; + $_data['periodic_sync'] = isset($_data['periodic_sync']) ? intval($_data['periodic_sync']) : 0; + $_data['import_users'] = isset($_data['import_users']) ? intval($_data['import_users']) : 0; + $_data['use_ssl'] = isset($_data['use_ssl']) ? boolval($_data['use_ssl']) : false; + $_data['use_tls'] = isset($_data['use_tls']) && !$_data['use_ssl'] ? boolval($_data['use_tls']) : false; + $_data['sync_interval'] = (!empty($_data['sync_interval'])) ? intval($_data['sync_interval']) : 15; + $_data['sync_interval'] = $_data['sync_interval'] < 1 ? 1 : $_data['sync_interval']; + $required_settings = array('authsource', 'host', 'port', 'basedn', 'username_field', 'filter', 'attribute_field', 'binddn', 'bindpass', 'periodic_sync', 'import_users', 'sync_interval', 'use_ssl', 'use_tls', 'ignore_ssl_error', 'login_provisioning'); + break; + } + + $pdo->beginTransaction(); + $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES (:key, :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);"); + // add connection settings + foreach($required_settings as $setting){ + if (!isset($_data[$setting])){ + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_action, $data_log), + 'msg' => array('required_data_missing', $setting) + ); + $pdo->rollback(); + return false; + } + + $stmt->bindParam(':key', $setting); + $stmt->bindParam(':value', $_data[$setting]); + $stmt->execute(); + } + $pdo->commit(); + + // add redirect_url_extra + if (isset($_data['redirect_url_extra'])){ + $_data['redirect_url_extra'] = (!is_array($_data['redirect_url_extra'])) ? array($_data['redirect_url_extra']) : $_data['redirect_url_extra']; + + $redirect_url_extra = array_filter($_data['redirect_url_extra']); + $redirect_url_extra = json_encode($redirect_url_extra); + + $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES ('redirect_url_extra', :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);"); + $stmt->bindParam(':value', $redirect_url_extra); + $stmt->execute(); + } + + // add default template + if (isset($_data['default_template'])) { + $_data['default_template'] = (empty($_data['default_template'])) ? "" : $_data['default_template']; + $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES ('default_template', :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);"); + $stmt->bindParam(':value', $_data['default_template']); + $stmt->execute(); + } + + // add mappers + if (isset($_data['mappers']) && isset($_data['templates'])){ + $_data['mappers'] = (!is_array($_data['mappers'])) ? array($_data['mappers']) : $_data['mappers']; + $_data['templates'] = (!is_array($_data['templates'])) ? array($_data['templates']) : $_data['templates']; + + $mappers = array_filter($_data['mappers']); + $templates = array_filter($_data['templates']); + if (count($mappers) == count($templates)){ + $mappers = json_encode($mappers); + $templates = json_encode($templates); + + $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES ('mappers', :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);"); + $stmt->bindParam(':value', $mappers); + $stmt->execute(); + $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES ('templates', :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);"); + $stmt->bindParam(':value', $templates); + $stmt->execute(); + } + } + + // delete old access_token + $stmt = $pdo->query("INSERT INTO identity_provider (`key`, `value`) VALUES ('access_token', '') ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);"); + + $_SESSION['return'][] = array( + 'type' => 'success', + 'log' => array(__FUNCTION__, $_action, $data_log), + 'msg' => array('object_modified', '') + ); + return true; + break; + case 'test': + if ($_SESSION['mailcow_cc_role'] != "admin") { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_action, $_data), + 'msg' => 'access_denied' + ); + return false; + } + + switch ($_data['authsource']) { + case 'keycloak': + $url = "{$_data['server_url']}/realms/{$_data['realm']}/protocol/openid-connect/token"; + $req = http_build_query(array( + 'grant_type' => 'client_credentials', + 'client_id' => $_data['client_id'], + 'client_secret' => $_data['client_secret'] + )); + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, $url); + curl_setopt($curl, CURLOPT_TIMEOUT, 7); + curl_setopt($curl, CURLOPT_POST, 1); + curl_setopt($curl, CURLOPT_POSTFIELDS, $req); + curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded')); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + if ($_data['ignore_ssl_error'] == "1"){ + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); + } + $res = curl_exec($curl); + $code = curl_getinfo($curl, CURLINFO_HTTP_CODE); + curl_close ($curl); + + if ($code != 200) { + return false; + } + break; + case 'generic-oidc': + $url = $_data['token_url']; + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, $url); + curl_setopt($curl, CURLOPT_TIMEOUT, 7); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "OPTIONS"); + if ($_data['ignore_ssl_error'] == "1"){ + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); + } + $res = curl_exec($curl); + $code = curl_getinfo($curl, CURLINFO_HTTP_CODE); + curl_close ($curl); + + if ($code != 200) { + return false; + } + break; + case 'ldap': + if (!$_data['host'] || !$_data['port'] || !$_data['basedn'] || + !$_data['binddn'] || !$_data['bindpass']){ + return false; + } + $_data['use_ssl'] = isset($_data['use_ssl']) ? boolval($_data['use_ssl']) : false; + $_data['use_tls'] = isset($_data['use_tls']) && !$_data['use_ssl'] ? boolval($_data['use_tls']) : false; + $_data['ignore_ssl_error'] = isset($_data['ignore_ssl_error']) ? boolval($_data['ignore_ssl_error']) : false; + $options = array(); + if ($_data['ignore_ssl_error']) { + $options[LDAP_OPT_X_TLS_REQUIRE_CERT] = LDAP_OPT_X_TLS_NEVER; + } + $provider = new \LdapRecord\Connection([ + 'hosts' => explode(",", $_data['host']), + 'port' => $_data['port'], + 'base_dn' => $_data['basedn'], + 'username' => $_data['binddn'], + 'password' => $_data['bindpass'], + 'use_ssl' => $_data['use_ssl'], + 'use_tls' => $_data['use_tls'], + 'options' => $options + ]); + try { + $provider->connect(); + } catch (Throwable $e) { + return false; + } + break; + } + + return true; + break; + case "delete": + if ($_SESSION['mailcow_cc_role'] != "admin") { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_action, $_data), + 'msg' => 'access_denied' + ); + return false; + } + + $stmt = $pdo->query("SELECT * FROM `mailbox` + WHERE `authsource` != 'mailcow' + AND `authsource` IS NOT NULL"); + $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); + if ($rows) { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_action, $data_log), + 'msg' => array('authsource_in_use', $setting) + ); + return false; + } + + $stmt = $pdo->query("DELETE FROM identity_provider;"); + + $_SESSION['return'][] = array( + 'type' => 'success', + 'log' => array(__FUNCTION__, $_action, $data_log), + 'msg' => array('item_deleted', '') + ); + return true; + break; + case "init": + $settings = identity_provider('get'); + $provider = null; + + switch ($settings['authsource']) { + case "keycloak": + if ($settings['server_url'] && $settings['realm'] && $settings['client_id'] && + $settings['client_secret'] && $settings['redirect_url'] && $settings['version']){ + $guzzyClient = new GuzzleHttp\Client([ + 'defaults' => [ + \GuzzleHttp\RequestOptions::CONNECT_TIMEOUT => 5, + \GuzzleHttp\RequestOptions::ALLOW_REDIRECTS => true], + \GuzzleHttp\RequestOptions::VERIFY => !$settings['ignore_ssl_error'], + ] + ); + $provider = new Stevenmaguire\OAuth2\Client\Provider\Keycloak([ + 'authServerUrl' => $settings['server_url'], + 'realm' => $settings['realm'], + 'clientId' => $settings['client_id'], + 'clientSecret' => $settings['client_secret'], + 'redirectUri' => $settings['redirect_url'], + 'version' => $settings['version'], + // 'encryptionAlgorithm' => 'RS256', // optional + // 'encryptionKeyPath' => '../key.pem' // optional + // 'encryptionKey' => 'contents_of_key_or_certificate' // optional + ]); + $provider->setHttpClient($guzzyClient); + } + break; + case "generic-oidc": + if ($settings['client_id'] && $settings['client_secret'] && $settings['redirect_url'] && + $settings['authorize_url'] && $settings['token_url'] && $settings['userinfo_url']){ + $guzzyClient = new GuzzleHttp\Client([ + 'defaults' => [ + \GuzzleHttp\RequestOptions::CONNECT_TIMEOUT => 5, + \GuzzleHttp\RequestOptions::ALLOW_REDIRECTS => true], + \GuzzleHttp\RequestOptions::VERIFY => !$settings['ignore_ssl_error'], + ] + ); + $provider = new \League\OAuth2\Client\Provider\GenericProvider([ + 'clientId' => $settings['client_id'], + 'clientSecret' => $settings['client_secret'], + 'redirectUri' => $settings['redirect_url'], + 'urlAuthorize' => $settings['authorize_url'], + 'urlAccessToken' => $settings['token_url'], + 'urlResourceOwnerDetails' => $settings['userinfo_url'], + 'scopes' => $settings['client_scopes'] + ]); + $provider->setHttpClient($guzzyClient); + } + break; + case "ldap": + if ($settings['host'] && $settings['port'] && $settings['basedn'] && + $settings['binddn'] && $settings['bindpass']){ + $options = array(); + if ($settings['ignore_ssl_error']) { + $options[LDAP_OPT_X_TLS_REQUIRE_CERT] = LDAP_OPT_X_TLS_NEVER; + } + $provider = new \LdapRecord\Connection([ + 'hosts' => explode(",", $settings['host']), + 'port' => $settings['port'], + 'base_dn' => $settings['basedn'], + 'username' => $settings['binddn'], + 'password' => $settings['bindpass'], + 'use_ssl' => $settings['use_ssl'], + 'use_tls' => $settings['use_tls'], + 'options' => $options + ]); + try { + $provider->connect(); + } catch (Throwable $e) { + $provider = null; + } + } + break; + } + return $provider; + break; + case "verify-sso": + if ($iam_settings['authsource'] != 'keycloak' && $iam_settings['authsource'] != 'generic-oidc'){ + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, "no OIDC provider configured"), + 'msg' => 'login_failed' + ); + return false; + } + + try { + $token = $iam_provider->getAccessToken('authorization_code', ['code' => $_GET['code']]); + $plain_token = $token->getToken(); + $plain_refreshtoken = $token->getRefreshToken(); + $info = $iam_provider->getResourceOwner($token)->toArray(); + } catch (Throwable $e) { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $e->getMessage()), + 'msg' => 'login_failed' + ); + return false; + } + // check if email address is given + if (empty($info['email'])) { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, 'No email address found for user'), + 'msg' => 'login_failed' + ); + return false; + } + + // get mapped template + $user_template = $info['mailcow_template']; + $mapper_key = array_search($user_template, $iam_settings['mappers']); + + // token valid, get mailbox + $stmt = $pdo->prepare("SELECT + mailbox.*, + domain.active AS d_active + FROM `mailbox` + INNER JOIN domain on mailbox.domain = domain.domain + WHERE `kind` NOT REGEXP 'location|thing|group' + AND `username` = :user"); + $stmt->execute(array(':user' => $info['email'])); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + if ($row){ + if (!in_array($row['authsource'], array("keycloak", "generic-oidc"))) { + clear_session(); + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $info['email'], "The user's authentication source is not of type OIDC"), + 'msg' => 'login_failed' + ); + return false; + } + if ($mapper_key !== false) { + // update user + $_SESSION['access_all_exception'] = '1'; + mailbox('edit', 'mailbox_from_template', array( + 'username' => $info['email'], + 'name' => $info['name'], + 'template' => $iam_settings['templates'][$mapper_key] + )); + $_SESSION['access_all_exception'] = '0'; + + // get updated row + $stmt = $pdo->prepare("SELECT + mailbox.*, + domain.active AS d_active + FROM `mailbox` + INNER JOIN domain on mailbox.domain = domain.domain + WHERE `kind` NOT REGEXP 'location|thing|group' + AND `username` = :user"); + $stmt->execute(array(':user' => $info['email'])); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + } + if ($row['active'] != 1 || $row['d_active'] != 1) { + clear_session(); + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $info['email'], 'Domain or mailbox is inactive'), + 'msg' => 'login_failed' + ); + return false; + } + set_user_loggedin_session($info['email']); + $_SESSION['iam_token'] = $plain_token; + $_SESSION['iam_refresh_token'] = $plain_refreshtoken; + $_SESSION['return'][] = array( + 'type' => 'success', + 'log' => array(__FUNCTION__, $_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role']), + 'msg' => array('logged_in_as', $_SESSION['mailcow_cc_username']) + ); + return true; + } + + // user doesn't exist, check if login provisioning is enabled + if (!$iam_settings['login_provisioning']){ + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, "Auto-create users on login is deactivated"), + 'msg' => 'login_failed' + ); + return false; + } + + if (empty($iam_settings['mappers']) || empty($user_template) || $mapper_key === false){ + if (!empty($iam_settings['default_template'])) { + $mbox_template = $iam_settings['default_template']; + } else { + clear_session(); + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $info['email'], 'No matching attribute mapping was found'), + 'msg' => 'login_failed' + ); + return false; + } + } else { + $mbox_template = $iam_settings['templates'][$mapper_key]; + } + + // create mailbox + $_SESSION['access_all_exception'] = '1'; + $create_res = mailbox('add', 'mailbox_from_template', array( + 'domain' => explode('@', $info['email'])[1], + 'local_part' => explode('@', $info['email'])[0], + 'name' => $info['name'], + 'authsource' => $iam_settings['authsource'], + 'template' => $mbox_template + )); + $_SESSION['access_all_exception'] = '0'; + if (!$create_res){ + clear_session(); + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $info['email'], 'Could not create mailbox on login'), + 'msg' => 'login_failed' + ); + return false; + } + + // double check if mailbox and domain is active + $stmt = $pdo->prepare("SELECT * FROM `mailbox` + INNER JOIN domain on mailbox.domain = domain.domain + WHERE `kind` NOT REGEXP 'location|thing|group' + AND `mailbox`.`active`='1' + AND `domain`.`active`='1' + AND `username` = :user"); + $stmt->execute(array(':user' => $info['email'])); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + if (empty($row)) { + clear_session(); + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $info['email'], 'Domain or mailbox is inactive'), + 'msg' => 'login_failed' + ); + return false; + } + + set_user_loggedin_session($info['email']); + $_SESSION['iam_token'] = $plain_token; + $_SESSION['iam_refresh_token'] = $plain_refreshtoken; + $_SESSION['return'][] = array( + 'type' => 'success', + 'log' => array(__FUNCTION__, $_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role']), + 'msg' => array('logged_in_as', $_SESSION['mailcow_cc_username']) + ); + return true; + break; + case "refresh-token": + try { + $token = $iam_provider->getAccessToken('refresh_token', ['refresh_token' => $_SESSION['iam_refresh_token']]); + $plain_token = $token->getToken(); + $plain_refreshtoken = $token->getRefreshToken(); + $info = $iam_provider->getResourceOwner($token)->toArray(); + } catch (Throwable $e) { + clear_session(); + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__), + 'msg' => array('refresh_login_failed', $e->getMessage()) + ); + return false; + } + + if (empty($info['email'])){ + clear_session(); + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role']), + 'msg' => 'refresh_login_failed' + ); + return false; + } + + set_user_loggedin_session($info['email']); + $_SESSION['iam_token'] = $plain_token; + $_SESSION['iam_refresh_token'] = $plain_refreshtoken; + return true; + break; + case "get-redirect": + if ($iam_settings['authsource'] != 'keycloak' && $iam_settings['authsource'] != 'generic-oidc') + return false; + $options = []; + if (isset($iam_settings['redirect_url_extra'])) { + // check if the current domain is used in an extra redirect URL + $targetDomain = strtolower($_SERVER['HTTP_HOST']); + foreach ($iam_settings['redirect_url_extra'] as $testUrl) { + $testUrlParsed = parse_url($testUrl); + if (isset($testUrlParsed['host']) && strtolower($testUrlParsed['host']) == $targetDomain) { + $options['redirect_uri'] = $testUrl; + break; + } + } + } + $authUrl = $iam_provider->getAuthorizationUrl($options); + $_SESSION['oauth2state'] = $iam_provider->getState(); + return $authUrl; + break; + case "get-keycloak-admin-token": + // get access_token for service account of mailcow client + if ($iam_settings['authsource'] !== 'keycloak') return false; + if (isset($iam_settings['access_token'])) { + // check if access_token is valid + $url = "{$iam_settings['server_url']}/realms/{$iam_settings['realm']}/protocol/openid-connect/token/introspect"; + $req = http_build_query(array( + 'token' => $iam_settings['access_token'], + 'client_id' => $iam_settings['client_id'], + 'client_secret' => $iam_settings['client_secret'] + )); + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, $url); + curl_setopt($curl, CURLOPT_TIMEOUT, 7); + curl_setopt($curl, CURLOPT_POST, 1); + curl_setopt($curl, CURLOPT_POSTFIELDS, $req); + curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded')); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curl, CURLOPT_TIMEOUT, 5); + $res = json_decode(curl_exec($curl), true); + $code = curl_getinfo($curl, CURLINFO_HTTP_CODE); + curl_close ($curl); + if ($code == 200 && $res['active'] == true) { + // token is valid + return $iam_settings['access_token']; + } + } + + $url = "{$iam_settings['server_url']}/realms/{$iam_settings['realm']}/protocol/openid-connect/token"; + $req = http_build_query(array( + 'grant_type' => 'client_credentials', + 'client_id' => $iam_settings['client_id'], + 'client_secret' => $iam_settings['client_secret'] + )); + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, $url); + curl_setopt($curl, CURLOPT_TIMEOUT, 7); + curl_setopt($curl, CURLOPT_POST, 1); + curl_setopt($curl, CURLOPT_POSTFIELDS, $req); + curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded')); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curl, CURLOPT_TIMEOUT, 5); + $res = json_decode(curl_exec($curl), true); + $code = curl_getinfo($curl, CURLINFO_HTTP_CODE); + curl_close ($curl); + if ($code != 200) { + return false; + } + + $stmt = $pdo->prepare("INSERT INTO identity_provider (`key`, `value`) VALUES (:key, :value) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);"); + $stmt->execute(array( + ':key' => 'access_token', + ':value' => $res['access_token'] + )); + return $res['access_token']; + break; + } +} function reset_password($action, $data = null) { global $pdo; global $valkey; @@ -2321,7 +2980,7 @@ function reset_password($action, $data = null) { case 'check': $token = $data; - $stmt = $pdo->prepare("SELECT `t1`.`username` FROM `reset_password` AS `t1` JOIN `mailbox` AS `t2` ON `t1`.`username` = `t2`.`username` WHERE `t1`.`token` = :token AND `t1`.`created` > DATE_SUB(NOW(), INTERVAL :lifetime MINUTE) AND `t2`.`active` = 1;"); + $stmt = $pdo->prepare("SELECT `t1`.`username` FROM `reset_password` AS `t1` JOIN `mailbox` AS `t2` ON `t1`.`username` = `t2`.`username` WHERE `t1`.`token` = :token AND `t1`.`created` > DATE_SUB(NOW(), INTERVAL :lifetime MINUTE) AND `t2`.`active` = 1 AND `t2`.`authsource` = 'mailcow';"); $stmt->execute(array( ':token' => preg_replace('/[^a-zA-Z0-9-]/', '', $token), ':lifetime' => $PW_RESET_TOKEN_LIFETIME @@ -2357,7 +3016,7 @@ function reset_password($action, $data = null) { } $stmt = $pdo->prepare("SELECT * FROM `mailbox` - WHERE `username` = :username"); + WHERE `username` = :username AND authsource = 'mailcow'"); $stmt->execute(array(':username' => $username)); $mailbox_data = $stmt->fetch(PDO::FETCH_ASSOC); @@ -2519,7 +3178,7 @@ function reset_password($action, $data = null) { $stmt = $pdo->prepare("UPDATE `mailbox` SET `password` = :password_hashed, `attributes` = JSON_SET(`attributes`, '$.passwd_update', NOW()) - WHERE `username` = :username"); + WHERE `username` = :username AND authsource = 'mailcow'"); $stmt->execute(array( ':password_hashed' => $password_hashed, ':username' => $username @@ -2687,8 +3346,23 @@ function reset_password($action, $data = null) { break; } } - - +function clear_session(){ + session_regenerate_id(true); + session_unset(); + session_destroy(); + session_write_close(); +} +function set_user_loggedin_session($user) { + session_regenerate_id(true); + $_SESSION['mailcow_cc_username'] = $user; + $_SESSION['mailcow_cc_role'] = 'user'; + $sogo_sso_pass = file_get_contents("/etc/sogo-sso/sogo-sso.pass"); + $_SESSION['sogo-sso-user-allowed'][] = $user; + $_SESSION['sogo-sso-pass'] = $sogo_sso_pass; + unset($_SESSION['pending_mailcow_cc_username']); + unset($_SESSION['pending_mailcow_cc_role']); + unset($_SESSION['pending_tfa_methods']); +} function get_logs($application, $lines = false) { if ($lines === false) { $lines = $GLOBALS['LOG_LINES'] - 1; @@ -2763,6 +3437,20 @@ function get_logs($application, $lines = false) { return $data_array; } } + if ($application == "cron-mailcow") { + if (isset($from) && isset($to)) { + $data = $valkey->lRange('CRON_LOG', $from - 1, $to - 1); + } + else { + $data = $valkey->lRange('CRON_LOG', 0, $lines); + } + if ($data) { + foreach ($data as $json_line) { + $data_array[] = json_decode($json_line, true); + } + return $data_array; + } + } if ($application == "postfix-mailcow") { if (isset($from) && isset($to)) { $data = $valkey->lRange('POSTFIX_MAILLOG', $from - 1, $to - 1); diff --git a/data/web/inc/functions.mailbox.inc.php b/data/web/inc/functions.mailbox.inc.php index 2b6320ac4..9cb65ada9 100644 --- a/data/web/inc/functions.mailbox.inc.php +++ b/data/web/inc/functions.mailbox.inc.php @@ -4,6 +4,8 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { global $valkey; global $lang; global $MAILBOX_DEFAULT_ATTRIBUTES; + global $iam_settings; + $_data_log = $_data; !isset($_data_log['password']) ?: $_data_log['password'] = '*'; !isset($_data_log['password2']) ?: $_data_log['password2'] = '*'; @@ -682,15 +684,16 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { return true; break; case 'alias': - $addresses = array_map('trim', preg_split( "/( |,|;|\n)/", $_data['address'])); - $gotos = array_map('trim', preg_split( "/( |,|;|\n)/", $_data['goto'])); - $active = intval($_data['active']); - $sogo_visible = intval($_data['sogo_visible']); - $goto_null = intval($_data['goto_null']); - $goto_spam = intval($_data['goto_spam']); - $goto_ham = intval($_data['goto_ham']); + $addresses = array_map('trim', preg_split( "/( |,|;|\n)/", $_data['address'])); + $gotos = array_map('trim', preg_split( "/( |,|;|\n)/", $_data['goto'])); + $internal = intval($_data['internal']); + $active = intval($_data['active']); + $sogo_visible = intval($_data['sogo_visible']); + $goto_null = intval($_data['goto_null']); + $goto_spam = intval($_data['goto_spam']); + $goto_ham = intval($_data['goto_ham']); $private_comment = $_data['private_comment']; - $public_comment = $_data['public_comment']; + $public_comment = $_data['public_comment']; if (strlen($private_comment) > 160 | strlen($public_comment) > 160){ $_SESSION['return'][] = array( 'type' => 'danger', @@ -840,8 +843,8 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { ); continue; } - $stmt = $pdo->prepare("INSERT INTO `alias` (`address`, `public_comment`, `private_comment`, `goto`, `domain`, `sogo_visible`, `active`) - VALUES (:address, :public_comment, :private_comment, :goto, :domain, :sogo_visible, :active)"); + $stmt = $pdo->prepare("INSERT INTO `alias` (`address`, `public_comment`, `private_comment`, `goto`, `domain`, `sogo_visible`, `internal`, `active`) + VALUES (:address, :public_comment, :private_comment, :goto, :domain, :sogo_visible, :internal, :active)"); if (!filter_var($address, FILTER_VALIDATE_EMAIL) === true) { $stmt->execute(array( ':address' => '@'.$domain, @@ -851,6 +854,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { ':goto' => $goto, ':domain' => $domain, ':sogo_visible' => $sogo_visible, + ':internal' => $internal, ':active' => $active )); } @@ -862,6 +866,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { ':goto' => $goto, ':domain' => $domain, ':sogo_visible' => $sogo_visible, + ':internal' => $internal, ':active' => $active )); } @@ -1005,6 +1010,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { $local_part = strtolower(trim($_data['local_part'])); $domain = idn_to_ascii(strtolower(trim($_data['domain'])), 0, INTL_IDNA_VARIANT_UTS46); $username = $local_part . '@' . $domain; + $authsource = 'mailcow'; if (!filter_var($username, FILTER_VALIDATE_EMAIL)) { $_SESSION['return'][] = array( 'type' => 'danger', @@ -1021,15 +1027,19 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { ); return false; } + if ($_data['authsource'] == "mailcow" || + in_array($_data['authsource'], array('keycloak', 'generic-oidc', 'ldap')) && $iam_settings['authsource'] == $_data['authsource']){ + $authsource = $_data['authsource']; + } if (empty($name)) { $name = $local_part; } $template_attr = null; if ($_data['template']){ - $template_attr = mailbox('get', 'mailbox_templates', $_data['template'])['attributes']; + $template_attr = mailbox('get', 'mailbox_templates', $_data['template'], $_extra)['attributes']; } if (empty($template_attr)) { - $template_attr = mailbox('get', 'mailbox_templates')[0]['attributes']; + $template_attr = mailbox('get', 'mailbox_templates', null, $_extra)[0]['attributes']; } $MAILBOX_DEFAULT_ATTRIBUTES = array_merge($MAILBOX_DEFAULT_ATTRIBUTES, $template_attr); @@ -1038,7 +1048,12 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { $name = ltrim(rtrim($_data['name'], '>'), '<'); $tags = (isset($_data['tags'])) ? $_data['tags'] : $MAILBOX_DEFAULT_ATTRIBUTES['tags']; $quota_m = (isset($_data['quota'])) ? intval($_data['quota']) : intval($MAILBOX_DEFAULT_ATTRIBUTES['quota']) / 1024 ** 2; - if ((!isset($_SESSION['acl']['unlimited_quota']) || $_SESSION['acl']['unlimited_quota'] != "1") && $quota_m === 0) { + if ($authsource != 'mailcow'){ + $password = ''; + $password2 = ''; + $password_hashed = ''; + } + if (!hasACLAccess("unlimited_quota") && $quota_m === 0) { $_SESSION['return'][] = array( 'type' => 'danger', 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), @@ -1067,6 +1082,10 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { $quarantine_notification = (isset($_data['quarantine_notification'])) ? strval($_data['quarantine_notification']) : strval($MAILBOX_DEFAULT_ATTRIBUTES['quarantine_notification']); $quarantine_category = (isset($_data['quarantine_category'])) ? strval($_data['quarantine_category']) : strval($MAILBOX_DEFAULT_ATTRIBUTES['quarantine_category']); $quota_b = ($quota_m * 1048576); + $attribute_hash = (!empty($_data['attribute_hash'])) ? $_data['attribute_hash'] : ''; + if (in_array($authsource, array('keycloak', 'generic-oidc', 'ldap'))){ + $force_pw_update = 0; + } $mailbox_attrs = json_encode( array( 'force_pw_update' => strval($force_pw_update), @@ -1081,7 +1100,8 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { 'passwd_update' => time(), 'mailbox_format' => strval($MAILBOX_DEFAULT_ATTRIBUTES['mailbox_format']), 'quarantine_notification' => strval($quarantine_notification), - 'quarantine_category' => strval($quarantine_category) + 'quarantine_category' => strval($quarantine_category), + 'attribute_hash' => $attribute_hash ) ); if (!is_valid_domain_name($domain)) { @@ -1156,10 +1176,12 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { ); return false; } - if (password_check($password, $password2) !== true) { - return false; + if ($authsource == 'mailcow'){ + if (password_check($password, $password2) !== true) { + return false; + } + $password_hashed = hash_password($password); } - $password_hashed = hash_password($password); if ($MailboxData['count'] >= $DomainData['mailboxes']) { $_SESSION['return'][] = array( 'type' => 'danger', @@ -1185,8 +1207,8 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { ); return false; } - $stmt = $pdo->prepare("INSERT INTO `mailbox` (`username`, `password`, `name`, `quota`, `local_part`, `domain`, `attributes`, `active`) - VALUES (:username, :password_hashed, :name, :quota_b, :local_part, :domain, :mailbox_attrs, :active)"); + $stmt = $pdo->prepare("INSERT INTO `mailbox` (`username`, `password`, `name`, `quota`, `local_part`, `domain`, `attributes`, `authsource`, `active`) + VALUES (:username, :password_hashed, :name, :quota_b, :local_part, :domain, :mailbox_attrs, :authsource, :active)"); $stmt->execute(array( ':username' => $username, ':password_hashed' => $password_hashed, @@ -1195,6 +1217,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { ':local_part' => $local_part, ':domain' => $domain, ':mailbox_attrs' => $mailbox_attrs, + ':authsource' => $authsource, ':active' => $active )); $stmt = $pdo->prepare("UPDATE `mailbox` SET @@ -1203,6 +1226,14 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { $stmt->execute(array( ':username' => $username )); + // save delimiter_action + if (isset($_data['tagged_mail_handler'])) { + mailbox('edit', 'delimiter_action', array( + 'username' => $username, + 'tagged_mail_handler' => $_data['tagged_mail_handler'] + )); + } + // save tags foreach($tags as $index => $tag){ if (empty($tag)) continue; @@ -1214,11 +1245,14 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { ); break; } - $stmt = $pdo->prepare("INSERT INTO `tags_mailbox` (`username`, `tag_name`) VALUES (:username, :tag_name)"); - $stmt->execute(array( - ':username' => $username, - ':tag_name' => $tag, - )); + try { + $stmt = $pdo->prepare("INSERT INTO `tags_mailbox` (`username`, `tag_name`) VALUES (:username, :tag_name)"); + $stmt->execute(array( + ':username' => $username, + ':tag_name' => $tag, + )); + } catch (Exception $e) { + } } $stmt = $pdo->prepare("INSERT INTO `quota2` (`username`, `bytes`, `messages`) VALUES (:username, '0', '0') ON DUPLICATE KEY UPDATE `bytes` = '0', `messages` = '0';"); @@ -1312,16 +1346,136 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { 'object' => $username, 'rl_frame' => $_data['rl_frame'], 'rl_value' => $_data['rl_value'] - )); + ), $_extra); } - update_sogo_static_view($username); + try { + update_sogo_static_view($username); + } catch (PDOException $e) { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), + 'msg' => $e->getMessage() + ); + } $_SESSION['return'][] = array( 'type' => 'success', 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), 'msg' => array('mailbox_added', htmlspecialchars($username)) ); - return true; + break; + case 'mailbox_from_template': + $stmt = $pdo->prepare("SELECT * FROM `templates` + WHERE `template` = :template AND type = 'mailbox'"); + $stmt->execute(array( + ":template" => $_data['template'] + )); + $mbox_template_data = $stmt->fetch(PDO::FETCH_ASSOC); + if (empty($mbox_template_data)){ + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), + 'msg' => 'template_missing' + ); + return false; + } + + $attribute_hash = sha1(json_encode($mbox_template_data["attributes"])); + $mbox_template_data = json_decode($mbox_template_data["attributes"], true); + $mbox_template_data['domain'] = $_data['domain']; + $mbox_template_data['name'] = $_data['name']; + $mbox_template_data['local_part'] = $_data['local_part']; + $mbox_template_data['authsource'] = $_data['authsource']; + $mbox_template_data['attribute_hash'] = $attribute_hash; + $mbox_template_data['quota'] = intval($mbox_template_data['quota'] / 1048576); + + $mailbox_attributes = array('acl' => array()); + foreach ($mbox_template_data as $key => $value){ + switch (true) { + case (strpos($key, 'acl_') === 0 && $value != 0): + array_push($mailbox_attributes['acl'], str_replace('acl_' , '', $key)); + break; + default: + $mailbox_attributes[$key] = $value; + break; + } + } + + return mailbox('add', 'mailbox', $mailbox_attributes); + break; + case 'mta_sts': + $domain = idn_to_ascii(strtolower(trim($_data['domain'])), 0, INTL_IDNA_VARIANT_UTS46); + $version = strtolower($_data['version']); + $mode = strtolower($_data['mode']); + $mx = explode(",", preg_replace('/\s+/', '', $_data['mx'])); + $max_age = intval($_data['max_age']); + $active = (intval($_data['active']) == 1) ? 1 : 0; + $id = date('YmdHis'); + + if (!hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $domain)) { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_action, $_type, $_data, $_attr), + 'msg' => 'access_denied' + ); + return false; + } + if (empty($version) || !in_array($version, array('stsv1'))) { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_action, $_type, $_data, $_attr), + 'msg' => array('version_invalid', htmlspecialchars($domain)) + ); + return false; + } + if (empty($mode) || !in_array($mode, array('enforce', 'testing', 'none'))) { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_action, $_type, $_data, $_attr), + 'msg' => array('mode_invalid', htmlspecialchars($domain)) + ); + return false; + } + if (empty($max_age) || $max_age < 0 || $max_age > 31536000) { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_action, $_type, $_data, $_attr), + 'msg' => array('max_age_invalid', htmlspecialchars($domain)) + ); + return false; + } + foreach ($mx as $index => $mx_domain) { + $mx_domain = idn_to_ascii(strtolower(trim($mx_domain)), 0, INTL_IDNA_VARIANT_UTS46); + if (!is_valid_domain_name($mx_domain, array('allow_wildcard' => true))) { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_action, $_type, $_data, $_attr), + 'msg' => array('mx_invalid', htmlspecialchars($mx_domain)) + ); + return false; + } + } + + try { + $stmt = $pdo->prepare("INSERT INTO `mta_sts` (`id`, `domain`, `version`, `mode`, `mx`, `max_age`, `active`) + VALUES (:id, :domain, :version, :mode, :mx, :max_age, :active)"); + $stmt->execute(array( + ':id' => $id, + ':domain' => $domain, + ':version' => $version, + ':mode' => $mode, + ':mx' => implode(",", $mx), + ':max_age' => $max_age, + ':active' => $active + )); + } catch (PDOException $e) { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_action, $_type, $_data), + 'msg' => $e->getMessage() + ); + return false; + } break; case 'resource': $domain = idn_to_ascii(strtolower(trim($_data['domain'])), 0, INTL_IDNA_VARIANT_UTS46); @@ -1544,6 +1698,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { $attr = array(); $attr["quota"] = isset($_data['quota']) ? intval($_data['quota']) * 1048576 : 0; $attr['tags'] = (isset($_data['tags'])) ? $_data['tags'] : array(); + $attr["tagged_mail_handler"] = (!empty($_data['tagged_mail_handler'])) ? $_data['tagged_mail_handler'] : strval($MAILBOX_DEFAULT_ATTRIBUTES['tagged_mail_handler']); $attr["quarantine_notification"] = (!empty($_data['quarantine_notification'])) ? $_data['quarantine_notification'] : strval($MAILBOX_DEFAULT_ATTRIBUTES['quarantine_notification']); $attr["quarantine_category"] = (!empty($_data['quarantine_category'])) ? $_data['quarantine_category'] : strval($MAILBOX_DEFAULT_ATTRIBUTES['quarantine_category']); $attr["rl_frame"] = (!empty($_data['rl_frame'])) ? $_data['rl_frame'] : "s"; @@ -1689,7 +1844,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { else { $usernames = $_data['username']; } - if (!isset($_SESSION['acl']['tls_policy']) || $_SESSION['acl']['tls_policy'] != "1" ) { + if (!hasACLAccess("tls_policy")) { $_SESSION['return'][] = array( 'type' => 'danger', 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), @@ -1698,7 +1853,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { return false; } foreach ($usernames as $username) { - if (!filter_var($username, FILTER_VALIDATE_EMAIL) || !hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $username)) { + if (!hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $username)) { $_SESSION['return'][] = array( 'type' => 'danger', 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), @@ -1706,7 +1861,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { ); continue; } - $is_now = mailbox('get', 'tls_policy', $username); + $is_now = mailbox('get', 'tls_policy', $username, $_extra); if (!empty($is_now)) { $tls_enforce_in = (isset($_data['tls_enforce_in'])) ? intval($_data['tls_enforce_in']) : $is_now['tls_enforce_in']; $tls_enforce_out = (isset($_data['tls_enforce_out'])) ? intval($_data['tls_enforce_out']) : $is_now['tls_enforce_out']; @@ -1743,7 +1898,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { else { $usernames = $_data['username']; } - if (!isset($_SESSION['acl']['quarantine_notification']) || $_SESSION['acl']['quarantine_notification'] != "1" ) { + if (!hasACLAccess("quarantine_notification")) { $_SESSION['return'][] = array( 'type' => 'danger', 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), @@ -1752,7 +1907,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { return false; } foreach ($usernames as $username) { - if (!filter_var($username, FILTER_VALIDATE_EMAIL) || !hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $username)) { + if (!hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $username)) { $_SESSION['return'][] = array( 'type' => 'danger', 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), @@ -1760,7 +1915,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { ); continue; } - $is_now = mailbox('get', 'quarantine_notification', $username); + $is_now = mailbox('get', 'quarantine_notification', $username, $_extra); if (!empty($is_now)) { $quarantine_notification = (isset($_data['quarantine_notification'])) ? $_data['quarantine_notification'] : $is_now['quarantine_notification']; } @@ -1802,7 +1957,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { else { $usernames = $_data['username']; } - if (!isset($_SESSION['acl']['quarantine_category']) || $_SESSION['acl']['quarantine_category'] != "1" ) { + if (!hasACLAccess("quarantine_category")) { $_SESSION['return'][] = array( 'type' => 'danger', 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), @@ -1811,7 +1966,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { return false; } foreach ($usernames as $username) { - if (!filter_var($username, FILTER_VALIDATE_EMAIL) || !hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $username)) { + if (!hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $username)) { $_SESSION['return'][] = array( 'type' => 'danger', 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), @@ -1819,7 +1974,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { ); continue; } - $is_now = mailbox('get', 'quarantine_category', $username); + $is_now = mailbox('get', 'quarantine_category', $username, $_extra); if (!empty($is_now)) { $quarantine_category = (isset($_data['quarantine_category'])) ? $_data['quarantine_category'] : $is_now['quarantine_category']; } @@ -2329,6 +2484,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { foreach ($ids as $id) { $is_now = mailbox('get', 'alias_details', $id); if (!empty($is_now)) { + $internal = (isset($_data['internal'])) ? intval($_data['internal']) : $is_now['internal']; $active = (isset($_data['active'])) ? intval($_data['active']) : $is_now['active']; $sogo_visible = (isset($_data['sogo_visible'])) ? intval($_data['sogo_visible']) : $is_now['sogo_visible']; $goto_null = (isset($_data['goto_null'])) ? intval($_data['goto_null']) : 0; @@ -2514,6 +2670,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { `domain` = :domain, `goto` = :goto, `sogo_visible`= :sogo_visible, + `internal`= :internal, `active`= :active WHERE `id` = :id"); $stmt->execute(array( @@ -2523,6 +2680,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { ':domain' => $domain, ':goto' => $goto, ':sogo_visible' => $sogo_visible, + ':internal' => $internal, ':active' => $active, ':id' => $is_now['id'] )); @@ -2863,7 +3021,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { ); continue; } - $is_now = mailbox('get', 'mailbox_details', $username); + $is_now = mailbox('get', 'mailbox_details', $username, $_extra); if (isset($_data['protocol_access'])) { $_data['protocol_access'] = (array)$_data['protocol_access']; $_data['imap_access'] = (in_array('imap', $_data['protocol_access'])) ? 1 : 0; @@ -2874,20 +3032,29 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { if (!empty($is_now)) { $active = (isset($_data['active'])) ? intval($_data['active']) : $is_now['active']; (int)$force_pw_update = (isset($_data['force_pw_update'])) ? intval($_data['force_pw_update']) : intval($is_now['attributes']['force_pw_update']); - (int)$sogo_access = (isset($_data['sogo_access']) && isset($_SESSION['acl']['sogo_access']) && $_SESSION['acl']['sogo_access'] == "1") ? intval($_data['sogo_access']) : intval($is_now['attributes']['sogo_access']); - (int)$imap_access = (isset($_data['imap_access']) && isset($_SESSION['acl']['protocol_access']) && $_SESSION['acl']['protocol_access'] == "1") ? intval($_data['imap_access']) : intval($is_now['attributes']['imap_access']); - (int)$pop3_access = (isset($_data['pop3_access']) && isset($_SESSION['acl']['protocol_access']) && $_SESSION['acl']['protocol_access'] == "1") ? intval($_data['pop3_access']) : intval($is_now['attributes']['pop3_access']); - (int)$smtp_access = (isset($_data['smtp_access']) && isset($_SESSION['acl']['protocol_access']) && $_SESSION['acl']['protocol_access'] == "1") ? intval($_data['smtp_access']) : intval($is_now['attributes']['smtp_access']); - (int)$sieve_access = (isset($_data['sieve_access']) && isset($_SESSION['acl']['protocol_access']) && $_SESSION['acl']['protocol_access'] == "1") ? intval($_data['sieve_access']) : intval($is_now['attributes']['sieve_access']); - (int)$relayhost = (isset($_data['relayhost']) && isset($_SESSION['acl']['mailbox_relayhost']) && $_SESSION['acl']['mailbox_relayhost'] == "1") ? intval($_data['relayhost']) : intval($is_now['attributes']['relayhost']); + (int)$sogo_access = (isset($_data['sogo_access']) && hasACLAccess("sogo_access")) ? intval($_data['sogo_access']) : intval($is_now['attributes']['sogo_access']); + (int)$imap_access = (isset($_data['imap_access']) && hasACLAccess("protocol_access")) ? intval($_data['imap_access']) : intval($is_now['attributes']['imap_access']); + (int)$pop3_access = (isset($_data['pop3_access']) && hasACLAccess("protocol_access")) ? intval($_data['pop3_access']) : intval($is_now['attributes']['pop3_access']); + (int)$smtp_access = (isset($_data['smtp_access']) && hasACLAccess("protocol_access")) ? intval($_data['smtp_access']) : intval($is_now['attributes']['smtp_access']); + (int)$sieve_access = (isset($_data['sieve_access']) && hasACLAccess("protocol_access")) ? intval($_data['sieve_access']) : intval($is_now['attributes']['sieve_access']); + (int)$relayhost = (isset($_data['relayhost']) && hasACLAccess("mailbox_relayhost")) ? intval($_data['relayhost']) : intval($is_now['attributes']['relayhost']); (int)$quota_m = (isset_has_content($_data['quota'])) ? intval($_data['quota']) : ($is_now['quota'] / 1048576); $name = (!empty($_data['name'])) ? ltrim(rtrim($_data['name'], '>'), '<') : $is_now['name']; $domain = $is_now['domain']; $quota_b = $quota_m * 1048576; $password = (!empty($_data['password'])) ? $_data['password'] : null; $password2 = (!empty($_data['password2'])) ? $_data['password2'] : null; - $pw_recovery_email = (isset($_data['pw_recovery_email'])) ? $_data['pw_recovery_email'] : $is_now['attributes']['recovery_email']; $tags = (is_array($_data['tags']) ? $_data['tags'] : array()); + $attribute_hash = (!empty($_data['attribute_hash'])) ? $_data['attribute_hash'] : ''; + $authsource = $is_now['authsource']; + if ($_data['authsource'] == "mailcow" || + in_array($_data['authsource'], array('keycloak', 'generic-oidc', 'ldap')) && $iam_settings['authsource'] == $_data['authsource']){ + $authsource = $_data['authsource']; + } + if (in_array($authsource, array('keycloak', 'generic-oidc', 'ldap'))){ + $force_pw_update = 0; + } + $pw_recovery_email = (isset($_data['pw_recovery_email']) && $authsource == 'mailcow') ? $_data['pw_recovery_email'] : $is_now['attributes']['recovery_email']; } else { $_SESSION['return'][] = array( @@ -2898,7 +3065,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { continue; } // if already 0 == ok - if ((!isset($_SESSION['acl']['unlimited_quota']) || $_SESSION['acl']['unlimited_quota'] != "1") && ($quota_m == 0 && $is_now['quota'] != 0)) { + if (!hasACLAccess("unlimited_quota") && ($quota_m == 0 && $is_now['quota'] != 0)) { $_SESSION['return'][] = array( 'type' => 'danger', 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), @@ -2914,7 +3081,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { ); continue; } - $DomainData = mailbox('get', 'domain_details', $domain); + $DomainData = mailbox('get', 'domain_details', $domain, $_extra); if ($quota_m > ($is_now['max_new_quota'] / 1048576)) { $_SESSION['return'][] = array( 'type' => 'danger', @@ -2933,7 +3100,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { } $extra_acls = array(); if (isset($_data['extended_sender_acl'])) { - if (!isset($_SESSION['acl']['extend_sender_acl']) || $_SESSION['acl']['extend_sender_acl'] != "1" ) { + if (!hasACLAccess("extend_sender_acl")) { $_SESSION['return'][] = array( 'type' => 'danger', 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), @@ -3126,7 +3293,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { $stmt = $pdo->prepare("UPDATE `mailbox` SET `password` = :password_hashed, `attributes` = JSON_SET(`attributes`, '$.passwd_update', NOW()) - WHERE `username` = :username"); + WHERE `username` = :username AND authsource = 'mailcow'"); $stmt->execute(array( ':password_hashed' => $password_hashed, ':username' => $username @@ -3145,6 +3312,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { `active` = :active, `name`= :name, `quota` = :quota_b, + `authsource` = :authsource, `attributes` = JSON_SET(`attributes`, '$.force_pw_update', :force_pw_update), `attributes` = JSON_SET(`attributes`, '$.sogo_access', :sogo_access), `attributes` = JSON_SET(`attributes`, '$.imap_access', :imap_access), @@ -3152,22 +3320,25 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { `attributes` = JSON_SET(`attributes`, '$.pop3_access', :pop3_access), `attributes` = JSON_SET(`attributes`, '$.relayhost', :relayhost), `attributes` = JSON_SET(`attributes`, '$.smtp_access', :smtp_access), - `attributes` = JSON_SET(`attributes`, '$.recovery_email', :recovery_email) + `attributes` = JSON_SET(`attributes`, '$.recovery_email', :recovery_email), + `attributes` = JSON_SET(`attributes`, '$.attribute_hash', :attribute_hash) WHERE `username` = :username"); - $stmt->execute(array( - ':active' => $active, - ':name' => $name, - ':quota_b' => $quota_b, - ':force_pw_update' => $force_pw_update, - ':sogo_access' => $sogo_access, - ':imap_access' => $imap_access, - ':pop3_access' => $pop3_access, - ':sieve_access' => $sieve_access, - ':smtp_access' => $smtp_access, - ':recovery_email' => $pw_recovery_email, - ':relayhost' => $relayhost, - ':username' => $username - )); + $stmt->execute(array( + ':active' => $active, + ':name' => $name, + ':quota_b' => $quota_b, + ':attribute_hash' => $attribute_hash, + ':force_pw_update' => $force_pw_update, + ':sogo_access' => $sogo_access, + ':imap_access' => $imap_access, + ':pop3_access' => $pop3_access, + ':sieve_access' => $sieve_access, + ':smtp_access' => $smtp_access, + ':recovery_email' => $pw_recovery_email, + ':relayhost' => $relayhost, + ':username' => $username, + ':authsource' => $authsource + )); } catch (PDOException $e) { $_SESSION['return'][] = array( @@ -3177,6 +3348,13 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { ); return false; } + // save delimiter_action + if (isset($_data['tagged_mail_handler'])) { + mailbox('edit', 'delimiter_action', array( + 'username' => $username, + 'tagged_mail_handler' => $_data['tagged_mail_handler'] + )); + } // save tags foreach($tags as $index => $tag){ if (empty($tag)) continue; @@ -3188,11 +3366,14 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { ); break; } - $stmt = $pdo->prepare("INSERT INTO `tags_mailbox` (`username`, `tag_name`) VALUES (:username, :tag_name)"); - $stmt->execute(array( - ':username' => $username, - ':tag_name' => $tag, - )); + try { + $stmt = $pdo->prepare("INSERT INTO `tags_mailbox` (`username`, `tag_name`) VALUES (:username, :tag_name)"); + $stmt->execute(array( + ':username' => $username, + ':tag_name' => $tag, + )); + } catch (Exception $e) { + } } $_SESSION['return'][] = array( @@ -3201,7 +3382,15 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { 'msg' => array('mailbox_modified', $username) ); - update_sogo_static_view($username); + try { + update_sogo_static_view($username); + } catch (PDOException $e) { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), + 'msg' => $e->getMessage() + ); + } } return true; break; @@ -3231,7 +3420,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { } $is_now = mailbox('get', 'mailbox_details', $old_username); - if (empty($is_now)) { + if (empty($is_now) || ($is_now['active'] != '1' && $is_now['active'] != '2')) { $_SESSION['return'][] = array( 'type' => 'danger', 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), @@ -3401,6 +3590,75 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { 'msg' => array('mailbox_renamed', $old_username, $new_username) ); break; + case 'mailbox_from_template': + $stmt = $pdo->prepare("SELECT * FROM `templates` + WHERE `template` = :template AND type = 'mailbox'"); + $stmt->execute(array( + ":template" => $_data['template'] + )); + $mbox_template_data = $stmt->fetch(PDO::FETCH_ASSOC); + if (empty($mbox_template_data)){ + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), + 'msg' => 'template_missing' + ); + return false; + } + + $attribute_hash = sha1(json_encode($mbox_template_data["attributes"])); + $is_now = mailbox('get', 'mailbox_details', $_data['username']); + $name = ltrim(rtrim($_data['name'], '>'), '<'); + if ($is_now['attributes']['attribute_hash'] == $attribute_hash && $is_now['name'] == $name) + return true; + + $mbox_template_data = json_decode($mbox_template_data["attributes"], true); + $mbox_template_data['attribute_hash'] = $attribute_hash; + $mbox_template_data['name'] = $name; + $quarantine_attributes = array('username' => $_data['username']); + $tls_attributes = array('username' => $_data['username']); + $ratelimit_attributes = array('object' => $_data['username']); + $acl_attributes = array('username' => $_data['username'], 'user_acl' => array()); + $mailbox_attributes = array('username' => $_data['username']); + foreach ($mbox_template_data as $key => $value){ + switch (true) { + case (strpos($key, 'quarantine_') === 0): + $quarantine_attributes[$key] = $value; + break; + case (strpos($key, 'tls_') === 0): + if ($value == null) + $value = 0; + $tls_attributes[$key] = $value; + break; + case (strpos($key, 'rl_') === 0): + $ratelimit_attributes[$key] = $value; + break; + case (strpos($key, 'acl_') === 0 && $value != 0): + array_push($acl_attributes['user_acl'], str_replace('acl_' , '', $key)); + break; + default: + $mailbox_attributes[$key] = $value; + break; + } + } + + $mailbox_attributes['quota'] = intval($mailbox_attributes['quota'] / 1048576); + $result = mailbox('edit', 'mailbox', $mailbox_attributes); + if ($result === false) return $result; + $result = mailbox('edit', 'tls_policy', $tls_attributes); + if ($result === false) return $result; + $result = mailbox('edit', 'quarantine_notification', $quarantine_attributes); + if ($result === false) return $result; + $result = mailbox('edit', 'quarantine_category', $quarantine_attributes); + if ($result === false) return $result; + $result = ratelimit('edit', 'mailbox', $ratelimit_attributes); + if ($result === false) return $result; + $result = acl('edit', 'user', $acl_attributes); + if ($result === false) return $result; + + $_SESSION['return'] = array(); + return true; + break; case 'mailbox_templates': if ($_SESSION['mailcow_cc_role'] != "admin") { $_SESSION['return'][] = array( @@ -3442,6 +3700,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { $attr = array(); $attr["quota"] = isset($_data['quota']) ? intval($_data['quota']) * 1048576 : 0; $attr['tags'] = (isset($_data['tags'])) ? $_data['tags'] : $is_now['tags']; + $attr["tagged_mail_handler"] = (!empty($_data['tagged_mail_handler'])) ? $_data['tagged_mail_handler'] : $is_now['tagged_mail_handler']; $attr["quarantine_notification"] = (!empty($_data['quarantine_notification'])) ? $_data['quarantine_notification'] : $is_now['quarantine_notification']; $attr["quarantine_category"] = (!empty($_data['quarantine_category'])) ? $_data['quarantine_category'] : $is_now['quarantine_category']; $attr["rl_frame"] = (!empty($_data['rl_frame'])) ? $_data['rl_frame'] : $is_now['rl_frame']; @@ -3562,6 +3821,125 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { return true; break; + case 'mta_sts': + if (!is_array($_data['domains'])) { + $domains = array(); + $domains[] = $_data['domains']; + } + else { + $domains = $_data['domains']; + } + + foreach ($domains as $domain) { + $domain = idn_to_ascii(strtolower(trim($domain)), 0, INTL_IDNA_VARIANT_UTS46); + + if (!hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $domain)) { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_action, $_type, $_data, $_attr), + 'msg' => 'access_denied' + ); + continue; + } + + $is_now = mailbox('get', 'mta_sts', $domain); + if (!empty($is_now)) { + $version = (isset($_data['version'])) ? strtolower($_data['version']) : $is_now['version']; + $active = (isset($_data['active'])) ? intval($_data['active']) : $is_now['active']; + $active = ($active == 1) ? 1 : 0; + $mode = (isset($_data['mode'])) ? strtolower($_data['mode']) : $is_now['mode']; + $mx = (isset($_data['mx'])) ? explode(",", preg_replace('/\s+/', '', $_data['mx'])) : $is_now['mx']; + $max_age = (isset($_data['max_age'])) ? intval($_data['max_age']) : $is_now['max_age']; + + // Update ID if neccesary + if ($version != strtolower($is_now['version']) || + $mode != strtolower($is_now['mode']) || + $mx != $is_now['mx'] || + $max_age != $is_now['max_age']) { + $id = date('YmdHis'); + } else { + $id = $is_now['id']; + } + + } else { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), + 'msg' => 'access_denied' + ); + continue; + } + + if (empty($version) || !in_array($version, array('stsv1'))) { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_action, $_type, $_data, $_attr), + 'msg' => array('version_invalid', htmlspecialchars($version)) + ); + continue; + } + if (empty($mode) || !in_array($mode, array('enforce', 'testing', 'none'))) { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_action, $_type, $_data, $_attr), + 'msg' => array('mode_invalid', htmlspecialchars($domain)) + ); + continue; + } + if (empty($max_age) || $max_age < 0 || $max_age > 31557600) { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_action, $_type, $_data, $_attr), + 'msg' => array('max_age_invalid', htmlspecialchars($domain)) + ); + continue; + } + foreach ($mx as $index => $mx_domain) { + $mx_domain = idn_to_ascii(strtolower(trim($mx_domain)), 0, INTL_IDNA_VARIANT_UTS46); + $invalid_mx = false; + if (!is_valid_domain_name($mx_domain, array('allow_wildcard' => true))) { + $invalid_mx = $mx_domain; + break; + } + } + if ($invalid_mx) { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_action, $_type, $_data, $_attr), + 'msg' => array('mx_invalid', htmlspecialchars($invalid_mx)) + ); + continue; + } + + try { + $stmt = $pdo->prepare("UPDATE `mta_sts` SET `id` = :id, `version` = :version, `mode` = :mode, `mx` = :mx, `max_age` = :max_age, `active` = :active WHERE `domain` = :domain"); + $stmt->execute(array( + ':id' => $id, + ':domain' => $domain, + ':version' => $version, + ':mode' => $mode, + ':mx' => implode(",", $mx), + ':max_age' => $max_age, + ':active' => $active + )); + } catch (PDOException $e) { + $_SESSION['return'][] = array( + 'type' => 'danger', + 'log' => array(__FUNCTION__, $_action, $_type, $_data), + 'msg' => $e->getMessage() + ); + continue; + } + + $_SESSION['return'][] = array( + 'type' => 'success', + 'log' => array(__FUNCTION__, $_action, $_type, $_data, $_attr), + 'msg' => array('object_modified', $domain) + ); + } + + return true; + break; case 'resource': if (!is_array($_data['name'])) { $names = array(); @@ -4328,6 +4706,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { `address`, `public_comment`, `private_comment`, + `internal`, `active`, `sogo_visible`, `created`, @@ -4358,6 +4737,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { $aliasdata['goto'] = $row['goto']; $aliasdata['address'] = $row['address']; (!filter_var($aliasdata['address'], FILTER_VALIDATE_EMAIL)) ? $aliasdata['is_catch_all'] = 1 : $aliasdata['is_catch_all'] = 0; + $aliasdata['internal'] = $row['internal']; $aliasdata['active'] = $row['active']; $aliasdata['active_int'] = $row['active']; $aliasdata['sogo_visible'] = $row['sogo_visible']; @@ -4666,6 +5046,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { `mailbox`.`quota`, `mailbox`.`created`, `mailbox`.`modified`, + `mailbox`.`authsource`, `quota2`.`bytes`, `attributes`, `custom_attributes`, @@ -4687,6 +5068,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { `mailbox`.`quota`, `mailbox`.`created`, `mailbox`.`modified`, + `mailbox`.`authsource`, `quota2replica`.`bytes`, `attributes`, `custom_attributes`, @@ -4716,6 +5098,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { $mailboxdata['percent_in_use'] = ($row['quota'] == 0) ? '- ' : round((intval($row['bytes']) / intval($row['quota'])) * 100); $mailboxdata['created'] = $row['created']; $mailboxdata['modified'] = $row['modified']; + $mailboxdata['authsource'] = ($row['authsource']) ? $row['authsource'] : 'mailcow'; if ($mailboxdata['percent_in_use'] === '- ') { $mailboxdata['percent_class'] = "info"; @@ -4746,7 +5129,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { else if ($SaslLogs['service'] == 'pop3') { $last_pop3_login = strtotime($SaslLogs['datetime']); } - else if ($SaslLogs['service'] == 'SSO') { + else if ($SaslLogs['service'] == 'SSO') { $last_sso_login = strtotime($SaslLogs['datetime']); } } @@ -4759,7 +5142,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { if (!isset($last_pop3_login) || $GLOBALS['SHOW_LAST_LOGIN'] === false) { $last_pop3_login = 0; } - if (!isset($last_sso_login) || $GLOBALS['SHOW_LAST_LOGIN'] === false) { + if (!isset($last_sso_login) || $GLOBALS['SHOW_LAST_LOGIN'] === false) { $last_sso_login = 0; } $mailboxdata['last_imap_login'] = $last_imap_login; @@ -4811,7 +5194,7 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { return $mailboxdata; break; case 'mailbox_templates': - if ($_SESSION['mailcow_cc_role'] != "admin" && $_SESSION['mailcow_cc_role'] != "domainadmin") { + if ($_SESSION['mailcow_cc_role'] != "admin" && $_SESSION['mailcow_cc_role'] != "domainadmin" && $_SESSION['access_all_exception'] != "1") { return false; } $_data = (isset($_data)) ? intval($_data) : null; @@ -4847,6 +5230,20 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { return $rows; } break; + case 'mta_sts': + $stmt = $pdo->prepare("SELECT * FROM `mta_sts` WHERE `domain` = :domain"); + $stmt->execute(array( + ':domain' => $_data, + )); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + if (empty($row)){ + return []; + } + $row['mx'] = explode(',', $row['mx']); + $row['version'] = strtoupper(substr($row['version'], 0, 3)) . substr($row['version'], 3); + + return $row; + break; case 'resource_details': $resourcedata = array(); if (!hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $_data)) { @@ -5232,6 +5629,10 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { $stmt->execute(array( ':domain' => $domain, )); + $stmt = $pdo->prepare("DELETE FROM `mta_sts` WHERE `domain` = :domain"); + $stmt->execute(array( + ':domain' => $domain, + )); $stmt = $pdo->query("DELETE FROM `admin` WHERE `superadmin` = 0 AND `username` NOT IN (SELECT `username`FROM `domain_admins`);"); $stmt = $pdo->query("DELETE FROM `da_acl` WHERE `username` NOT IN (SELECT `username`FROM `domain_admins`);"); try { @@ -5565,7 +5966,15 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { continue; } - update_sogo_static_view($username); + try { + update_sogo_static_view($username); + }catch (PDOException $e) { + $_SESSION['return'][] = array( + 'type' => 'success', + 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), + 'msg' => $e->getMessage() + ); + } $_SESSION['return'][] = array( 'type' => 'success', 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), @@ -5779,6 +6188,16 @@ function mailbox($_action, $_type, $_data = null, $_extra = null) { break; } if ($_action != 'get' && in_array($_type, array('domain', 'alias', 'alias_domain', 'resource')) && getenv('SKIP_SOGO') != "y") { - update_sogo_static_view(); + try { + update_sogo_static_view(); + }catch (PDOException $e) { + $_SESSION['return'][] = array( + 'type' => 'success', + 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), + 'msg' => $e->getMessage() + ); + } } + + return true; } diff --git a/data/web/inc/functions.quarantine.inc.php b/data/web/inc/functions.quarantine.inc.php index 8845fc77b..f099eb3be 100644 --- a/data/web/inc/functions.quarantine.inc.php +++ b/data/web/inc/functions.quarantine.inc.php @@ -22,7 +22,7 @@ function quarantine($_action, $_data = null) { return false; } $stmt = $pdo->prepare('SELECT `id` FROM `quarantine` LEFT OUTER JOIN `user_acl` ON `user_acl`.`username` = `rcpt` - WHERE SHA2(CONCAT(`id`, `qid`), 256) = :hash + WHERE `qhash` = :hash AND user_acl.quarantine = 1 AND rcpt IN (SELECT username FROM mailbox)'); $stmt->execute(array(':hash' => $hash)); @@ -65,7 +65,7 @@ function quarantine($_action, $_data = null) { return false; } $stmt = $pdo->prepare('SELECT `id` FROM `quarantine` LEFT OUTER JOIN `user_acl` ON `user_acl`.`username` = `rcpt` - WHERE SHA2(CONCAT(`id`, `qid`), 256) = :hash + WHERE `qhash` = :hash AND `user_acl`.`quarantine` = 1 AND `username` IN (SELECT `username` FROM `mailbox`)'); $stmt->execute(array(':hash' => $hash)); @@ -169,7 +169,7 @@ function quarantine($_action, $_data = null) { } } elseif ($release_format == 'raw') { - $detail_row['msg'] = preg_replace('/^X-Spam-Flag: (.*)/', 'X-Pre-Release-Spam-Flag $1', $detail_row['msg']); + $detail_row['msg'] = preg_replace('/^X-Spam-Flag: (.*)/m', 'X-Pre-Release-Spam-Flag: $1', $detail_row['msg']); $postfix_talk = array( array('220', 'HELO quarantine' . chr(10)), array('250', 'MAIL FROM: ' . $sender . chr(10)), @@ -464,7 +464,7 @@ function quarantine($_action, $_data = null) { } } elseif ($release_format == 'raw') { - $row['msg'] = preg_replace('/^X-Spam-Flag: (.*)/', 'X-Pre-Release-Spam-Flag $1', $row['msg']); + $row['msg'] = preg_replace('/^X-Spam-Flag: (.*)/m', 'X-Pre-Release-Spam-Flag: $1', $row['msg']); $postfix_talk = array( array('220', 'HELO quarantine' . chr(10)), array('250', 'MAIL FROM: ' . $sender . chr(10)), @@ -833,7 +833,7 @@ function quarantine($_action, $_data = null) { ))); return false; } - $stmt = $pdo->prepare('SELECT * FROM `quarantine` WHERE SHA2(CONCAT(`id`, `qid`), 256) = :hash'); + $stmt = $pdo->prepare('SELECT * FROM `quarantine` WHERE `qhash` = :hash'); $stmt->execute(array(':hash' => $hash)); return $stmt->fetch(PDO::FETCH_ASSOC); break; diff --git a/data/web/inc/functions.ratelimit.inc.php b/data/web/inc/functions.ratelimit.inc.php index 8323aa6c3..a82cd9d95 100644 --- a/data/web/inc/functions.ratelimit.inc.php +++ b/data/web/inc/functions.ratelimit.inc.php @@ -1,10 +1,10 @@ 'danger', 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr), @@ -93,7 +93,7 @@ function ratelimit($_action, $_scope, $_data = null) { continue; } if (!hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $object) - || ($_SESSION['mailcow_cc_role'] != 'admin' && $_SESSION['mailcow_cc_role'] != 'domainadmin')) { + || ($_SESSION['mailcow_cc_role'] != 'admin' && $_SESSION['mailcow_cc_role'] != 'domainadmin' && $_SESSION['access_all_exception'] != '1')) { $_SESSION['return'][] = array( 'type' => 'danger', 'log' => array(__FUNCTION__, $_action, $_scope, $_data_log), diff --git a/data/web/inc/header.inc.php b/data/web/inc/header.inc.php index 5fe25bef0..d2ce6f3d0 100644 --- a/data/web/inc/header.inc.php +++ b/data/web/inc/header.inc.php @@ -30,6 +30,44 @@ if(!file_exists($CSSPath)) { cleanupCSS($hash); } +$mailcow_apps_processed = $MAILCOW_APPS; +$app_links = customize('get', 'app_links'); +$app_links_processed = $app_links; +$hide_mailcow_apps = true; +for ($i = 0; $i < count($mailcow_apps_processed); $i++) { + if ($hide_mailcow_apps && !$mailcow_apps_processed[$i]['hide']){ + $hide_mailcow_apps = false; + } + if (!empty($_SESSION['mailcow_cc_username'])){ + if ($app_links_processed[$i]['user_link']) { + $mailcow_apps_processed[$i]['user_link'] = str_replace('%u', $_SESSION['mailcow_cc_username'], $mailcow_apps_processed[$i]['user_link']); + } else { + $mailcow_apps_processed[$i]['user_link'] = $mailcow_apps_processed[$i]['link']; + } + } +} +if ($app_links_processed){ + for ($i = 0; $i < count($app_links_processed); $i++) { + $key = array_key_first($app_links_processed[$i]); + if ($hide_mailcow_apps && !$app_links_processed[$i][$key]['hide']){ + $hide_mailcow_apps = false; + } + if (!empty($_SESSION['mailcow_cc_username'])){ + if ($app_links_processed[$i][$key]['user_link']) { + $app_links_processed[$i][$key]['user_link'] = str_replace('%u', $_SESSION['mailcow_cc_username'], $app_links_processed[$i][$key]['user_link']); + } else { + $app_links_processed[$i][$key]['user_link'] = $app_links_processed[$i][$key]['link']; + } + } + } +} + +// Workaround to get text with
straight to twig. +// Using "nl2br" doesn't work with Twig as it would escape everything by default. +if (isset($UI_TEXTS["ui_footer"])) { + $UI_TEXTS["ui_footer"] = nl2br($UI_TEXTS["ui_footer"]); +} + $globalVariables = [ 'mailcow_hostname' => getenv('MAILCOW_HOSTNAME'), 'mailcow_locale' => @$_SESSION['mailcow_locale'], @@ -45,8 +83,11 @@ $globalVariables = [ 'lang' => $lang, 'skip_sogo' => (getenv('SKIP_SOGO') == 'y'), 'allow_admin_email_login' => (getenv('ALLOW_ADMIN_EMAIL_LOGIN') == 'n'), + 'hide_mailcow_apps' => $hide_mailcow_apps, 'mailcow_apps' => $MAILCOW_APPS, - 'app_links' => customize('get', 'app_links'), + 'mailcow_apps_processed' => $mailcow_apps_processed, + 'app_links' => $app_links, + 'app_links_processed' => $app_links_processed, 'is_root_uri' => (parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) == '/'), 'uri' => $_SERVER['REQUEST_URI'], ]; diff --git a/data/web/inc/init_db.inc.php b/data/web/inc/init_db.inc.php index d8e7147b2..b8ab85253 100644 --- a/data/web/inc/init_db.inc.php +++ b/data/web/inc/init_db.inc.php @@ -4,7 +4,7 @@ function init_db_schema() try { global $pdo; - $db_version = "20112024_1105"; + $db_version = "07102025_1015"; $stmt = $pdo->query("SHOW TABLES LIKE 'versions'"); $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC)); @@ -184,6 +184,7 @@ function init_db_schema() "private_comment" => "TEXT", "public_comment" => "TEXT", "sogo_visible" => "TINYINT(1) NOT NULL DEFAULT '1'", + "internal" => "TINYINT(1) NOT NULL DEFAULT '0'", "active" => "TINYINT(1) NOT NULL DEFAULT '1'" ), "keys" => array( @@ -345,10 +346,14 @@ function init_db_schema() "notified" => "TINYINT(1) NOT NULL DEFAULT '0'", "created" => "DATETIME(0) NOT NULL DEFAULT NOW(0)", "user" => "VARCHAR(255) NOT NULL DEFAULT 'unknown'", + "qhash" => "VARCHAR(64)", ), "keys" => array( "primary" => array( "" => array("id") + ), + "key" => array( + "qhash" => array("qhash") ) ), "attr" => "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC" @@ -368,6 +373,7 @@ function init_db_schema() "custom_attributes" => "JSON NOT NULL DEFAULT ('{}')", "kind" => "VARCHAR(100) NOT NULL DEFAULT ''", "multiple_bookings" => "INT NOT NULL DEFAULT -1", + "authsource" => "ENUM('mailcow', 'keycloak', 'generic-oidc', 'ldap') DEFAULT 'mailcow'", "created" => "DATETIME(0) NOT NULL DEFAULT NOW(0)", "modified" => "DATETIME ON UPDATE CURRENT_TIMESTAMP", "active" => "TINYINT(1) NOT NULL DEFAULT '1'" @@ -470,6 +476,23 @@ function init_db_schema() ), "attr" => "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC" ), + "mta_sts" => array( + "cols" => array( + "id" => "BIGINT NOT NULL", + "domain" => "VARCHAR(255) NOT NULL", + "version" => "VARCHAR(255) NOT NULL", + "mode" => "VARCHAR(255) NOT NULL", + "mx" => "VARCHAR(255) NOT NULL", + "max_age" => "VARCHAR(255) NOT NULL", + "active" => "TINYINT(1) NOT NULL DEFAULT '1'" + ), + "keys" => array( + "primary" => array( + "" => array("domain") + ) + ), + "attr" => "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC" + ), "user_acl" => array( "cols" => array( "username" => "VARCHAR(255) NOT NULL", @@ -575,6 +598,20 @@ function init_db_schema() ), "attr" => "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC" ), + "identity_provider" => array( + "cols" => array( + "key" => "VARCHAR(255) NOT NULL", + "value" => "TEXT NOT NULL", + "created" => "DATETIME(0) NOT NULL DEFAULT NOW(0)", + "modified" => "DATETIME ON UPDATE CURRENT_TIMESTAMP" + ), + "keys" => array( + "primary" => array( + "" => array("key") + ) + ), + "attr" => "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC" + ), "logs" => array( "cols" => array( "id" => "INT NOT NULL AUTO_INCREMENT", @@ -1300,6 +1337,14 @@ function init_db_schema() $pdo->query($create); } + // Clear old app_passwd log entries + $pdo->exec("DELETE FROM logs + WHERE role != 'unauthenticated' + AND JSON_EXTRACT(`call`, '$[0]') = 'app_passwd' + AND JSON_EXTRACT(`call`, '$[1]') = 'edit' + AND (JSON_CONTAINS_PATH(`call`, 'one', '$[2].password') + OR JSON_CONTAINS_PATH(`call`, 'one', '$[2].password2'));"); + // Mitigate imapsync argument injection issue $pdo->query("UPDATE `imapsync` SET `custom_params` = '' WHERE `custom_params` LIKE '%pipemess%' @@ -1455,6 +1500,9 @@ function init_db_schema() )); } + // remove old sogo views and triggers + $pdo->query("DROP TRIGGER IF EXISTS sogo_update_password"); + if (php_sapi_name() == "cli") { echo "DB initialization completed" . PHP_EOL; } else { @@ -1464,6 +1512,10 @@ function init_db_schema() 'msg' => 'db_init_complete' ); } + + // fill quarantine.qhash + $pdo->query("UPDATE `quarantine` SET `qhash` = SHA2(CONCAT(`id`, `qid`), 256) WHERE ISNULL(`qhash`)"); + } catch (PDOException $e) { if (php_sapi_name() == "cli") { echo "DB initialization failed: " . print_r($e, true) . PHP_EOL; @@ -1478,6 +1530,7 @@ function init_db_schema() } if (php_sapi_name() == "cli") { include '/web/inc/vars.inc.php'; + include '/web/inc/functions.inc.php'; include '/web/inc/functions.docker.inc.php'; // $now = new DateTime(); // $mins = $now->getOffset() / 60; @@ -1499,9 +1552,7 @@ if (php_sapi_name() == "cli") { if (intval($res['OK_C']) === 2) { // Be more precise when replacing into _sogo_static_view, col orders may change try { - $stmt = $pdo->query("REPLACE INTO _sogo_static_view (`c_uid`, `domain`, `c_name`, `c_password`, `c_cn`, `mail`, `aliases`, `ad_aliases`, `ext_acl`, `kind`, `multiple_bookings`) - SELECT `c_uid`, `domain`, `c_name`, `c_password`, `c_cn`, `mail`, `aliases`, `ad_aliases`, `ext_acl`, `kind`, `multiple_bookings` from sogo_view"); - $stmt = $pdo->query("DELETE FROM _sogo_static_view WHERE `c_uid` NOT IN (SELECT `username` FROM `mailbox` WHERE `active` = '1');"); + update_sogo_static_view(); echo "Fixed _sogo_static_view" . PHP_EOL; } catch (Exception $e) { // Dunno diff --git a/data/web/inc/lib/composer.json b/data/web/inc/lib/composer.json index 78033ec9b..91a50bcbf 100644 --- a/data/web/inc/lib/composer.json +++ b/data/web/inc/lib/composer.json @@ -1,7 +1,6 @@ { "require": { "robthree/twofactorauth": "^1.6", - "yubico/u2flib-server": "^1.0", "phpmailer/phpmailer": "^6.1", "php-mime-mail-parser/php-mime-mail-parser": "^7", "soundasleep/html2text": "^0.5.0", @@ -9,7 +8,9 @@ "matthiasmullie/minify": "^1.3", "bshaffer/oauth2-server-php": "^1.11", "mustangostang/spyc": "^0.6.3", - "directorytree/ldaprecord": "^2.4", - "twig/twig": "^3.0" + "directorytree/ldaprecord": "^3.3", + "twig/twig": "^3.0", + "stevenmaguire/oauth2-keycloak": "^4.0", + "league/oauth2-client": "^2.7" } } diff --git a/data/web/inc/lib/composer.lock b/data/web/inc/lib/composer.lock index 422d353ab..fb1c3903b 100644 --- a/data/web/inc/lib/composer.lock +++ b/data/web/inc/lib/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "139c1e5dec323144cd778ce80fd1847e", + "content-hash": "8f5a147cdb147b935a158b86f47a4747", "packages": [ { "name": "bshaffer/oauth2-server-php", @@ -68,6 +68,75 @@ }, "time": "2018-12-04T00:29:32+00:00" }, + { + "name": "carbonphp/carbon-doctrine-types", + "version": "3.2.0", + "source": { + "type": "git", + "url": "https://github.com/CarbonPHP/carbon-doctrine-types.git", + "reference": "18ba5ddfec8976260ead6e866180bd5d2f71aa1d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/CarbonPHP/carbon-doctrine-types/zipball/18ba5ddfec8976260ead6e866180bd5d2f71aa1d", + "reference": "18ba5ddfec8976260ead6e866180bd5d2f71aa1d", + "shasum": "" + }, + "require": { + "php": "^8.1" + }, + "conflict": { + "doctrine/dbal": "<4.0.0 || >=5.0.0" + }, + "require-dev": { + "doctrine/dbal": "^4.0.0", + "nesbot/carbon": "^2.71.0 || ^3.0.0", + "phpunit/phpunit": "^10.3" + }, + "type": "library", + "autoload": { + "psr-4": { + "Carbon\\Doctrine\\": "src/Carbon/Doctrine/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "KyleKatarn", + "email": "kylekatarnls@gmail.com" + } + ], + "description": "Types to use Carbon in Doctrine", + "keywords": [ + "carbon", + "date", + "datetime", + "doctrine", + "time" + ], + "support": { + "issues": "https://github.com/CarbonPHP/carbon-doctrine-types/issues", + "source": "https://github.com/CarbonPHP/carbon-doctrine-types/tree/3.2.0" + }, + "funding": [ + { + "url": "https://github.com/kylekatarnls", + "type": "github" + }, + { + "url": "https://opencollective.com/Carbon", + "type": "open_collective" + }, + { + "url": "https://tidelift.com/funding/github/packagist/nesbot/carbon", + "type": "tidelift" + } + ], + "time": "2024-02-09T16:56:22+00:00" + }, { "name": "ddeboer/imap", "version": "1.13.1", @@ -145,27 +214,28 @@ }, { "name": "directorytree/ldaprecord", - "version": "v2.10.1", + "version": "v2.20.5", "source": { "type": "git", "url": "https://github.com/DirectoryTree/LdapRecord.git", - "reference": "bf512d9af7a7b0e2ed7a666ab29cefdd027bee88" + "reference": "5bd0a5a9d257cf1049ae83055dbba4c3479ddf16" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/DirectoryTree/LdapRecord/zipball/bf512d9af7a7b0e2ed7a666ab29cefdd027bee88", - "reference": "bf512d9af7a7b0e2ed7a666ab29cefdd027bee88", + "url": "https://api.github.com/repos/DirectoryTree/LdapRecord/zipball/5bd0a5a9d257cf1049ae83055dbba4c3479ddf16", + "reference": "5bd0a5a9d257cf1049ae83055dbba4c3479ddf16", "shasum": "" }, "require": { "ext-json": "*", "ext-ldap": "*", - "illuminate/contracts": "^5.0|^6.0|^7.0|^8.0|^9.0", + "illuminate/contracts": "^5.0|^6.0|^7.0|^8.0|^9.0|^10.0", "nesbot/carbon": "^1.0|^2.0", "php": ">=7.3", - "psr/log": "*", + "psr/log": "^1.0|^2.0|^3.0", "psr/simple-cache": "^1.0|^2.0", - "tightenco/collect": "^5.6|^6.0|^7.0|^8.0" + "symfony/polyfill-php80": "^1.25", + "tightenco/collect": "^5.6|^6.0|^7.0|^8.0|^9.0" }, "require-dev": { "mockery/mockery": "^1.0", @@ -214,31 +284,422 @@ "type": "github" } ], - "time": "2022-02-25T16:00:51+00:00" + "time": "2023-10-11T16:34:34+00:00" }, { - "name": "illuminate/contracts", - "version": "v9.3.0", + "name": "firebase/php-jwt", + "version": "v6.5.0", "source": { "type": "git", - "url": "https://github.com/illuminate/contracts.git", - "reference": "bf4b3c254c49d28157645d01e4883b5951b1e1d0" + "url": "https://github.com/firebase/php-jwt.git", + "reference": "e94e7353302b0c11ec3cfff7180cd0b1743975d2" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/illuminate/contracts/zipball/bf4b3c254c49d28157645d01e4883b5951b1e1d0", - "reference": "bf4b3c254c49d28157645d01e4883b5951b1e1d0", + "url": "https://api.github.com/repos/firebase/php-jwt/zipball/e94e7353302b0c11ec3cfff7180cd0b1743975d2", + "reference": "e94e7353302b0c11ec3cfff7180cd0b1743975d2", "shasum": "" }, "require": { - "php": "^8.0.2", + "php": "^7.4||^8.0" + }, + "require-dev": { + "guzzlehttp/guzzle": "^6.5||^7.4", + "phpspec/prophecy-phpunit": "^2.0", + "phpunit/phpunit": "^9.5", + "psr/cache": "^1.0||^2.0", + "psr/http-client": "^1.0", + "psr/http-factory": "^1.0" + }, + "suggest": { + "ext-sodium": "Support EdDSA (Ed25519) signatures", + "paragonie/sodium_compat": "Support EdDSA (Ed25519) signatures when libsodium is not present" + }, + "type": "library", + "autoload": { + "psr-4": { + "Firebase\\JWT\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Neuman Vong", + "email": "neuman+pear@twilio.com", + "role": "Developer" + }, + { + "name": "Anant Narayanan", + "email": "anant@php.net", + "role": "Developer" + } + ], + "description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.", + "homepage": "https://github.com/firebase/php-jwt", + "keywords": [ + "jwt", + "php" + ], + "support": { + "issues": "https://github.com/firebase/php-jwt/issues", + "source": "https://github.com/firebase/php-jwt/tree/v6.5.0" + }, + "time": "2023-05-12T15:47:07+00:00" + }, + { + "name": "guzzlehttp/guzzle", + "version": "7.5.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/guzzle.git", + "reference": "b50a2a1251152e43f6a37f0fa053e730a67d25ba" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/guzzle/zipball/b50a2a1251152e43f6a37f0fa053e730a67d25ba", + "reference": "b50a2a1251152e43f6a37f0fa053e730a67d25ba", + "shasum": "" + }, + "require": { + "ext-json": "*", + "guzzlehttp/promises": "^1.5", + "guzzlehttp/psr7": "^1.9 || ^2.4", + "php": "^7.2.5 || ^8.0", + "psr/http-client": "^1.0", + "symfony/deprecation-contracts": "^2.2 || ^3.0" + }, + "provide": { + "psr/http-client-implementation": "1.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.1", + "ext-curl": "*", + "php-http/client-integration-tests": "^3.0", + "phpunit/phpunit": "^8.5.29 || ^9.5.23", + "psr/log": "^1.1 || ^2.0 || ^3.0" + }, + "suggest": { + "ext-curl": "Required for CURL handler support", + "ext-intl": "Required for Internationalized Domain Name (IDN) support", + "psr/log": "Required for using the Log middleware" + }, + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + }, + "branch-alias": { + "dev-master": "7.5-dev" + } + }, + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "GuzzleHttp\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Jeremy Lindblom", + "email": "jeremeamia@gmail.com", + "homepage": "https://github.com/jeremeamia" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "description": "Guzzle is a PHP HTTP client library", + "keywords": [ + "client", + "curl", + "framework", + "http", + "http client", + "psr-18", + "psr-7", + "rest", + "web service" + ], + "support": { + "issues": "https://github.com/guzzle/guzzle/issues", + "source": "https://github.com/guzzle/guzzle/tree/7.5.0" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/guzzle", + "type": "tidelift" + } + ], + "time": "2022-08-28T15:39:27+00:00" + }, + { + "name": "guzzlehttp/promises", + "version": "1.5.2", + "source": { + "type": "git", + "url": "https://github.com/guzzle/promises.git", + "reference": "b94b2807d85443f9719887892882d0329d1e2598" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/promises/zipball/b94b2807d85443f9719887892882d0329d1e2598", + "reference": "b94b2807d85443f9719887892882d0329d1e2598", + "shasum": "" + }, + "require": { + "php": ">=5.5" + }, + "require-dev": { + "symfony/phpunit-bridge": "^4.4 || ^5.1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.5-dev" + } + }, + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "description": "Guzzle promises library", + "keywords": [ + "promise" + ], + "support": { + "issues": "https://github.com/guzzle/promises/issues", + "source": "https://github.com/guzzle/promises/tree/1.5.2" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/promises", + "type": "tidelift" + } + ], + "time": "2022-08-28T14:55:35+00:00" + }, + { + "name": "guzzlehttp/psr7", + "version": "2.4.5", + "source": { + "type": "git", + "url": "https://github.com/guzzle/psr7.git", + "reference": "0454e12ef0cd597ccd2adb036f7bda4e7fface66" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/0454e12ef0cd597ccd2adb036f7bda4e7fface66", + "reference": "0454e12ef0cd597ccd2adb036f7bda4e7fface66", + "shasum": "" + }, + "require": { + "php": "^7.2.5 || ^8.0", + "psr/http-factory": "^1.0", + "psr/http-message": "^1.0", + "ralouphie/getallheaders": "^3.0" + }, + "provide": { + "psr/http-factory-implementation": "1.0", + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.1", + "http-interop/http-factory-tests": "^0.9", + "phpunit/phpunit": "^8.5.29 || ^9.5.23" + }, + "suggest": { + "laminas/laminas-httphandlerrunner": "Emit PSR-7 responses" + }, + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://sagikazarmark.hu" + } + ], + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": [ + "http", + "message", + "psr-7", + "request", + "response", + "stream", + "uri", + "url" + ], + "support": { + "issues": "https://github.com/guzzle/psr7/issues", + "source": "https://github.com/guzzle/psr7/tree/2.4.5" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/psr7", + "type": "tidelift" + } + ], + "time": "2023-04-17T16:00:45+00:00" + }, + { + "name": "illuminate/contracts", + "version": "v10.44.0", + "source": { + "type": "git", + "url": "https://github.com/illuminate/contracts.git", + "reference": "8d7152c4a1f5d9cf7da3e8b71f23e4556f6138ac" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/illuminate/contracts/zipball/8d7152c4a1f5d9cf7da3e8b71f23e4556f6138ac", + "reference": "8d7152c4a1f5d9cf7da3e8b71f23e4556f6138ac", + "shasum": "" + }, + "require": { + "php": "^8.1", "psr/container": "^1.1.1|^2.0.1", "psr/simple-cache": "^1.0|^2.0|^3.0" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "9.x-dev" + "dev-master": "10.x-dev" } }, "autoload": { @@ -262,7 +723,77 @@ "issues": "https://github.com/laravel/framework/issues", "source": "https://github.com/laravel/framework" }, - "time": "2022-02-22T14:45:39+00:00" + "time": "2024-01-15T18:52:32+00:00" + }, + { + "name": "league/oauth2-client", + "version": "2.7.0", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/oauth2-client.git", + "reference": "160d6274b03562ebeb55ed18399281d8118b76c8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/oauth2-client/zipball/160d6274b03562ebeb55ed18399281d8118b76c8", + "reference": "160d6274b03562ebeb55ed18399281d8118b76c8", + "shasum": "" + }, + "require": { + "guzzlehttp/guzzle": "^6.0 || ^7.0", + "paragonie/random_compat": "^1 || ^2 || ^9.99", + "php": "^5.6 || ^7.0 || ^8.0" + }, + "require-dev": { + "mockery/mockery": "^1.3.5", + "php-parallel-lint/php-parallel-lint": "^1.3.1", + "phpunit/phpunit": "^5.7 || ^6.0 || ^9.5", + "squizlabs/php_codesniffer": "^2.3 || ^3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-2.x": "2.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "League\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Alex Bilbie", + "email": "hello@alexbilbie.com", + "homepage": "http://www.alexbilbie.com", + "role": "Developer" + }, + { + "name": "Woody Gilk", + "homepage": "https://github.com/shadowhand", + "role": "Contributor" + } + ], + "description": "OAuth 2.0 Client Library", + "keywords": [ + "Authentication", + "SSO", + "authorization", + "identity", + "idp", + "oauth", + "oauth2", + "single sign on" + ], + "support": { + "issues": "https://github.com/thephpleague/oauth2-client/issues", + "source": "https://github.com/thephpleague/oauth2-client/tree/2.7.0" + }, + "time": "2023-04-16T18:19:15+00:00" }, { "name": "matthiasmullie/minify", @@ -447,34 +978,41 @@ }, { "name": "nesbot/carbon", - "version": "2.57.0", + "version": "2.72.3", "source": { "type": "git", "url": "https://github.com/briannesbitt/Carbon.git", - "reference": "4a54375c21eea4811dbd1149fe6b246517554e78" + "reference": "0c6fd108360c562f6e4fd1dedb8233b423e91c83" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/briannesbitt/Carbon/zipball/4a54375c21eea4811dbd1149fe6b246517554e78", - "reference": "4a54375c21eea4811dbd1149fe6b246517554e78", + "url": "https://api.github.com/repos/briannesbitt/Carbon/zipball/0c6fd108360c562f6e4fd1dedb8233b423e91c83", + "reference": "0c6fd108360c562f6e4fd1dedb8233b423e91c83", "shasum": "" }, "require": { + "carbonphp/carbon-doctrine-types": "*", "ext-json": "*", "php": "^7.1.8 || ^8.0", + "psr/clock": "^1.0", "symfony/polyfill-mbstring": "^1.0", "symfony/polyfill-php80": "^1.16", "symfony/translation": "^3.4 || ^4.0 || ^5.0 || ^6.0" }, + "provide": { + "psr/clock-implementation": "1.0" + }, "require-dev": { - "doctrine/dbal": "^2.0 || ^3.0", - "doctrine/orm": "^2.7", + "doctrine/dbal": "^2.0 || ^3.1.4 || ^4.0", + "doctrine/orm": "^2.7 || ^3.0", "friendsofphp/php-cs-fixer": "^3.0", "kylekatarnls/multi-tester": "^2.0", + "ondrejmirtes/better-reflection": "*", "phpmd/phpmd": "^2.9", "phpstan/extension-installer": "^1.0", - "phpstan/phpstan": "^0.12.54 || ^1.0", - "phpunit/phpunit": "^7.5.20 || ^8.5.14", + "phpstan/phpstan": "^0.12.99 || ^1.7.14", + "phpunit/php-file-iterator": "^2.0.5 || ^3.0.6", + "phpunit/phpunit": "^7.5.20 || ^8.5.26 || ^9.5.20", "squizlabs/php_codesniffer": "^3.4" }, "bin": [ @@ -531,15 +1069,19 @@ }, "funding": [ { - "url": "https://opencollective.com/Carbon", - "type": "open_collective" + "url": "https://github.com/sponsors/kylekatarnls", + "type": "github" }, { - "url": "https://tidelift.com/funding/github/packagist/nesbot/carbon", + "url": "https://opencollective.com/Carbon#sponsor", + "type": "opencollective" + }, + { + "url": "https://tidelift.com/subscription/pkg/packagist-nesbot-carbon?utm_source=packagist-nesbot-carbon&utm_medium=referral&utm_campaign=readme", "type": "tidelift" } ], - "time": "2022-02-13T18:13:33+00:00" + "time": "2024-01-25T10:35:09+00:00" }, { "name": "paragonie/random_compat", @@ -760,6 +1302,54 @@ ], "time": "2022-02-28T15:31:21+00:00" }, + { + "name": "psr/clock", + "version": "1.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/clock.git", + "reference": "e41a24703d4560fd0acb709162f73b8adfc3aa0d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/clock/zipball/e41a24703d4560fd0acb709162f73b8adfc3aa0d", + "reference": "e41a24703d4560fd0acb709162f73b8adfc3aa0d", + "shasum": "" + }, + "require": { + "php": "^7.0 || ^8.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Psr\\Clock\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for reading the clock.", + "homepage": "https://github.com/php-fig/clock", + "keywords": [ + "clock", + "now", + "psr", + "psr-20", + "time" + ], + "support": { + "issues": "https://github.com/php-fig/clock/issues", + "source": "https://github.com/php-fig/clock/tree/1.0.0" + }, + "time": "2022-11-25T14:36:26+00:00" + }, { "name": "psr/container", "version": "2.0.2", @@ -813,6 +1403,166 @@ }, "time": "2021-11-05T16:47:00+00:00" }, + { + "name": "psr/http-client", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-client.git", + "reference": "2dfb5f6c5eff0e91e20e913f8c5452ed95b86621" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-client/zipball/2dfb5f6c5eff0e91e20e913f8c5452ed95b86621", + "reference": "2dfb5f6c5eff0e91e20e913f8c5452ed95b86621", + "shasum": "" + }, + "require": { + "php": "^7.0 || ^8.0", + "psr/http-message": "^1.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP clients", + "homepage": "https://github.com/php-fig/http-client", + "keywords": [ + "http", + "http-client", + "psr", + "psr-18" + ], + "support": { + "source": "https://github.com/php-fig/http-client/tree/master" + }, + "time": "2020-06-29T06:28:15+00:00" + }, + { + "name": "psr/http-factory", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-factory.git", + "reference": "12ac7fcd07e5b077433f5f2bee95b3a771bf61be" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-factory/zipball/12ac7fcd07e5b077433f5f2bee95b3a771bf61be", + "reference": "12ac7fcd07e5b077433f5f2bee95b3a771bf61be", + "shasum": "" + }, + "require": { + "php": ">=7.0.0", + "psr/http-message": "^1.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interfaces for PSR-7 HTTP message factories", + "keywords": [ + "factory", + "http", + "message", + "psr", + "psr-17", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-factory/tree/master" + }, + "time": "2019-04-30T12:38:16+00:00" + }, + { + "name": "psr/http-message", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-message/tree/master" + }, + "time": "2016-08-06T14:39:51+00:00" + }, { "name": "psr/log", "version": "3.0.0", @@ -914,6 +1664,50 @@ }, "time": "2021-10-29T13:22:09+00:00" }, + { + "name": "ralouphie/getallheaders", + "version": "3.0.3", + "source": { + "type": "git", + "url": "https://github.com/ralouphie/getallheaders.git", + "reference": "120b605dfeb996808c31b6477290a714d356e822" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/120b605dfeb996808c31b6477290a714d356e822", + "reference": "120b605dfeb996808c31b6477290a714d356e822", + "shasum": "" + }, + "require": { + "php": ">=5.6" + }, + "require-dev": { + "php-coveralls/php-coveralls": "^2.1", + "phpunit/phpunit": "^5 || ^6.5" + }, + "type": "library", + "autoload": { + "files": [ + "src/getallheaders.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ralph Khattar", + "email": "ralph.khattar@gmail.com" + } + ], + "description": "A polyfill for getallheaders.", + "support": { + "issues": "https://github.com/ralouphie/getallheaders/issues", + "source": "https://github.com/ralouphie/getallheaders/tree/develop" + }, + "time": "2019-03-08T08:55:37+00:00" + }, { "name": "robthree/twofactorauth", "version": "1.8.1", @@ -1039,6 +1833,67 @@ }, "time": "2017-04-19T22:01:50+00:00" }, + { + "name": "stevenmaguire/oauth2-keycloak", + "version": "4.0.0", + "source": { + "type": "git", + "url": "https://github.com/stevenmaguire/oauth2-keycloak.git", + "reference": "05ead6bb6bcd2b6f96dfae87c769dcd3e5f6129d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/stevenmaguire/oauth2-keycloak/zipball/05ead6bb6bcd2b6f96dfae87c769dcd3e5f6129d", + "reference": "05ead6bb6bcd2b6f96dfae87c769dcd3e5f6129d", + "shasum": "" + }, + "require": { + "firebase/php-jwt": "^4.0 || ^5.0 || ^6.0", + "league/oauth2-client": "^2.0", + "php": "~7.2 || ~8.0" + }, + "require-dev": { + "mockery/mockery": "~1.5.0", + "phpunit/phpunit": "~9.6.4", + "squizlabs/php_codesniffer": "~3.7.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Stevenmaguire\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Steven Maguire", + "email": "stevenmaguire@gmail.com", + "homepage": "https://github.com/stevenmaguire" + } + ], + "description": "Keycloak OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "keywords": [ + "authorisation", + "authorization", + "client", + "keycloak", + "oauth", + "oauth2" + ], + "support": { + "issues": "https://github.com/stevenmaguire/oauth2-keycloak/issues", + "source": "https://github.com/stevenmaguire/oauth2-keycloak/tree/4.0.0" + }, + "time": "2023-03-14T09:43:47+00:00" + }, { "name": "symfony/deprecation-contracts", "version": "v3.5.0", @@ -1190,16 +2045,16 @@ }, { "name": "symfony/polyfill-mbstring", - "version": "v1.24.0", + "version": "v1.29.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-mbstring.git", - "reference": "0abb51d2f102e00a4eefcf46ba7fec406d245825" + "reference": "9773676c8a1bb1f8d4340a62efe641cf76eda7ec" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/0abb51d2f102e00a4eefcf46ba7fec406d245825", - "reference": "0abb51d2f102e00a4eefcf46ba7fec406d245825", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/9773676c8a1bb1f8d4340a62efe641cf76eda7ec", + "reference": "9773676c8a1bb1f8d4340a62efe641cf76eda7ec", "shasum": "" }, "require": { @@ -1213,9 +2068,6 @@ }, "type": "library", "extra": { - "branch-alias": { - "dev-main": "1.23-dev" - }, "thanks": { "name": "symfony/polyfill", "url": "https://github.com/symfony/polyfill" @@ -1253,7 +2105,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.24.0" + "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.29.0" }, "funding": [ { @@ -1269,20 +2121,20 @@ "type": "tidelift" } ], - "time": "2021-11-30T18:21:41+00:00" + "time": "2024-01-29T20:11:03+00:00" }, { "name": "symfony/polyfill-php80", - "version": "v1.24.0", + "version": "v1.29.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-php80.git", - "reference": "57b712b08eddb97c762a8caa32c84e037892d2e9" + "reference": "87b68208d5c1188808dd7839ee1e6c8ec3b02f1b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/57b712b08eddb97c762a8caa32c84e037892d2e9", - "reference": "57b712b08eddb97c762a8caa32c84e037892d2e9", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/87b68208d5c1188808dd7839ee1e6c8ec3b02f1b", + "reference": "87b68208d5c1188808dd7839ee1e6c8ec3b02f1b", "shasum": "" }, "require": { @@ -1290,9 +2142,6 @@ }, "type": "library", "extra": { - "branch-alias": { - "dev-main": "1.23-dev" - }, "thanks": { "name": "symfony/polyfill", "url": "https://github.com/symfony/polyfill" @@ -1336,7 +2185,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-php80/tree/v1.24.0" + "source": "https://github.com/symfony/polyfill-php80/tree/v1.29.0" }, "funding": [ { @@ -1352,7 +2201,7 @@ "type": "tidelift" } ], - "time": "2021-09-13T13:58:33+00:00" + "time": "2024-01-29T20:11:03+00:00" }, { "name": "symfony/polyfill-php81", @@ -1432,28 +2281,31 @@ }, { "name": "symfony/translation", - "version": "v6.0.5", + "version": "v6.4.3", "source": { "type": "git", "url": "https://github.com/symfony/translation.git", - "reference": "e69501c71107cc3146b32aaa45f4edd0c3427875" + "reference": "637c51191b6b184184bbf98937702bcf554f7d04" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/translation/zipball/e69501c71107cc3146b32aaa45f4edd0c3427875", - "reference": "e69501c71107cc3146b32aaa45f4edd0c3427875", + "url": "https://api.github.com/repos/symfony/translation/zipball/637c51191b6b184184bbf98937702bcf554f7d04", + "reference": "637c51191b6b184184bbf98937702bcf554f7d04", "shasum": "" }, "require": { - "php": ">=8.0.2", + "php": ">=8.1", + "symfony/deprecation-contracts": "^2.5|^3", "symfony/polyfill-mbstring": "~1.0", - "symfony/translation-contracts": "^2.3|^3.0" + "symfony/translation-contracts": "^2.5|^3.0" }, "conflict": { "symfony/config": "<5.4", "symfony/console": "<5.4", "symfony/dependency-injection": "<5.4", + "symfony/http-client-contracts": "<2.5", "symfony/http-kernel": "<5.4", + "symfony/service-contracts": "<2.5", "symfony/twig-bundle": "<5.4", "symfony/yaml": "<5.4" }, @@ -1461,22 +2313,19 @@ "symfony/translation-implementation": "2.3|3.0" }, "require-dev": { + "nikic/php-parser": "^4.18|^5.0", "psr/log": "^1|^2|^3", - "symfony/config": "^5.4|^6.0", - "symfony/console": "^5.4|^6.0", - "symfony/dependency-injection": "^5.4|^6.0", - "symfony/finder": "^5.4|^6.0", - "symfony/http-client-contracts": "^1.1|^2.0|^3.0", - "symfony/http-kernel": "^5.4|^6.0", - "symfony/intl": "^5.4|^6.0", + "symfony/config": "^5.4|^6.0|^7.0", + "symfony/console": "^5.4|^6.0|^7.0", + "symfony/dependency-injection": "^5.4|^6.0|^7.0", + "symfony/finder": "^5.4|^6.0|^7.0", + "symfony/http-client-contracts": "^2.5|^3.0", + "symfony/http-kernel": "^5.4|^6.0|^7.0", + "symfony/intl": "^5.4|^6.0|^7.0", "symfony/polyfill-intl-icu": "^1.21", - "symfony/service-contracts": "^1.1.2|^2|^3", - "symfony/yaml": "^5.4|^6.0" - }, - "suggest": { - "psr/log-implementation": "To use logging capability in translator", - "symfony/config": "", - "symfony/yaml": "" + "symfony/routing": "^5.4|^6.0|^7.0", + "symfony/service-contracts": "^2.5|^3", + "symfony/yaml": "^5.4|^6.0|^7.0" }, "type": "library", "autoload": { @@ -1507,7 +2356,7 @@ "description": "Provides tools to internationalize your application", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/translation/tree/v6.0.5" + "source": "https://github.com/symfony/translation/tree/v6.4.3" }, "funding": [ { @@ -1523,32 +2372,29 @@ "type": "tidelift" } ], - "time": "2022-02-09T15:52:48+00:00" + "time": "2024-01-29T13:11:52+00:00" }, { "name": "symfony/translation-contracts", - "version": "v3.0.0", + "version": "v3.4.1", "source": { "type": "git", "url": "https://github.com/symfony/translation-contracts.git", - "reference": "1b6ea5a7442af5a12dba3dbd6d71034b5b234e77" + "reference": "06450585bf65e978026bda220cdebca3f867fde7" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/translation-contracts/zipball/1b6ea5a7442af5a12dba3dbd6d71034b5b234e77", - "reference": "1b6ea5a7442af5a12dba3dbd6d71034b5b234e77", + "url": "https://api.github.com/repos/symfony/translation-contracts/zipball/06450585bf65e978026bda220cdebca3f867fde7", + "reference": "06450585bf65e978026bda220cdebca3f867fde7", "shasum": "" }, "require": { - "php": ">=8.0.2" - }, - "suggest": { - "symfony/translation-implementation": "" + "php": ">=8.1" }, "type": "library", "extra": { "branch-alias": { - "dev-main": "3.0-dev" + "dev-main": "3.4-dev" }, "thanks": { "name": "symfony/contracts", @@ -1558,7 +2404,10 @@ "autoload": { "psr-4": { "Symfony\\Contracts\\Translation\\": "" - } + }, + "exclude-from-classmap": [ + "/Test/" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ @@ -1585,7 +2434,7 @@ "standards" ], "support": { - "source": "https://github.com/symfony/translation-contracts/tree/v3.0.0" + "source": "https://github.com/symfony/translation-contracts/tree/v3.4.1" }, "funding": [ { @@ -1601,42 +2450,39 @@ "type": "tidelift" } ], - "time": "2021-09-07T12:43:40+00:00" + "time": "2023-12-26T14:02:43+00:00" }, { "name": "symfony/var-dumper", - "version": "v6.0.5", + "version": "v6.4.3", "source": { "type": "git", "url": "https://github.com/symfony/var-dumper.git", - "reference": "60d6a756d5f485df5e6e40b337334848f79f61ce" + "reference": "0435a08f69125535336177c29d56af3abc1f69da" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/var-dumper/zipball/60d6a756d5f485df5e6e40b337334848f79f61ce", - "reference": "60d6a756d5f485df5e6e40b337334848f79f61ce", + "url": "https://api.github.com/repos/symfony/var-dumper/zipball/0435a08f69125535336177c29d56af3abc1f69da", + "reference": "0435a08f69125535336177c29d56af3abc1f69da", "shasum": "" }, "require": { - "php": ">=8.0.2", + "php": ">=8.1", + "symfony/deprecation-contracts": "^2.5|^3", "symfony/polyfill-mbstring": "~1.0" }, "conflict": { - "phpunit/phpunit": "<5.4.3", "symfony/console": "<5.4" }, "require-dev": { "ext-iconv": "*", - "symfony/console": "^5.4|^6.0", - "symfony/process": "^5.4|^6.0", - "symfony/uid": "^5.4|^6.0", + "symfony/console": "^5.4|^6.0|^7.0", + "symfony/error-handler": "^6.3|^7.0", + "symfony/http-kernel": "^5.4|^6.0|^7.0", + "symfony/process": "^5.4|^6.0|^7.0", + "symfony/uid": "^5.4|^6.0|^7.0", "twig/twig": "^2.13|^3.0.4" }, - "suggest": { - "ext-iconv": "To convert non-UTF-8 strings to UTF-8 (or symfony/polyfill-iconv in case ext-iconv cannot be used).", - "ext-intl": "To show region name in time zone dump", - "symfony/console": "To use the ServerDumpCommand and/or the bin/var-dump-server script" - }, "bin": [ "Resources/bin/var-dump-server" ], @@ -1673,7 +2519,7 @@ "dump" ], "support": { - "source": "https://github.com/symfony/var-dumper/tree/v6.0.5" + "source": "https://github.com/symfony/var-dumper/tree/v6.4.3" }, "funding": [ { @@ -1689,24 +2535,24 @@ "type": "tidelift" } ], - "time": "2022-02-21T17:15:17+00:00" + "time": "2024-01-23T14:53:30+00:00" }, { "name": "tightenco/collect", - "version": "v8.83.2", + "version": "v9.52.7", "source": { "type": "git", "url": "https://github.com/tighten/collect.git", - "reference": "d9c66d586ec2d216d8a31283d73f8df1400cc722" + "reference": "b15143cd11fe01a700fcc449df61adc64452fa6d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/tighten/collect/zipball/d9c66d586ec2d216d8a31283d73f8df1400cc722", - "reference": "d9c66d586ec2d216d8a31283d73f8df1400cc722", + "url": "https://api.github.com/repos/tighten/collect/zipball/b15143cd11fe01a700fcc449df61adc64452fa6d", + "reference": "b15143cd11fe01a700fcc449df61adc64452fa6d", "shasum": "" }, "require": { - "php": "^7.3|^8.0", + "php": "^8.0", "symfony/var-dumper": "^3.4 || ^4.0 || ^5.0 || ^6.0" }, "require-dev": { @@ -1741,9 +2587,9 @@ ], "support": { "issues": "https://github.com/tighten/collect/issues", - "source": "https://github.com/tighten/collect/tree/v8.83.2" + "source": "https://github.com/tighten/collect/tree/v9.52.7" }, - "time": "2022-02-16T16:15:54+00:00" + "time": "2023-04-14T21:51:36+00:00" }, { "name": "twig/twig", @@ -1823,47 +2669,6 @@ } ], "time": "2024-09-09T17:55:12+00:00" - }, - { - "name": "yubico/u2flib-server", - "version": "1.0.2", - "source": { - "type": "git", - "url": "https://github.com/Yubico/php-u2flib-server.git", - "reference": "55d813acf68212ad2cadecde07551600d6971939" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/Yubico/php-u2flib-server/zipball/55d813acf68212ad2cadecde07551600d6971939", - "reference": "55d813acf68212ad2cadecde07551600d6971939", - "shasum": "" - }, - "require": { - "ext-openssl": "*", - "paragonie/random_compat": ">= 1", - "php": ">=5.6" - }, - "require-dev": { - "phpunit/phpunit": "~5.7", - "vimeo/psalm": "^0|^1|^2" - }, - "type": "library", - "autoload": { - "classmap": [ - "src/" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "BSD-2-Clause" - ], - "description": "Library for U2F implementation", - "homepage": "https://developers.yubico.com/php-u2flib-server", - "support": { - "issues": "https://github.com/Yubico/php-u2flib-server/issues", - "source": "https://github.com/Yubico/php-u2flib-server/tree/1.0.2" - }, - "time": "2018-09-07T08:16:44+00:00" } ], "packages-dev": [], diff --git a/data/web/inc/lib/vendor/bin/carbon b/data/web/inc/lib/vendor/bin/carbon index 7b63379a0..86fbfdfd8 100755 --- a/data/web/inc/lib/vendor/bin/carbon +++ b/data/web/inc/lib/vendor/bin/carbon @@ -12,6 +12,7 @@ namespace Composer; +$GLOBALS['_composer_bin_dir'] = __DIR__; $GLOBALS['_composer_autoload_path'] = __DIR__ . '/..'.'/autoload.php'; if (PHP_VERSION_ID < 80000) { @@ -23,18 +24,17 @@ if (PHP_VERSION_ID < 80000) { { private $handle; private $position; + private $realpath; public function stream_open($path, $mode, $options, &$opened_path) { - // get rid of composer-bin-proxy:// prefix for __FILE__ & __DIR__ resolution - $opened_path = substr($path, 21); - $opened_path = realpath($opened_path) ?: $opened_path; - $this->handle = fopen($opened_path, $mode); + // get rid of phpvfscomposer:// prefix for __FILE__ & __DIR__ resolution + $opened_path = substr($path, 17); + $this->realpath = realpath($opened_path) ?: $opened_path; + $opened_path = $this->realpath; + $this->handle = fopen($this->realpath, $mode); $this->position = 0; - // remove all traces of this stream wrapper once it has been used - stream_wrapper_unregister('composer-bin-proxy'); - return (bool) $this->handle; } @@ -66,6 +66,16 @@ if (PHP_VERSION_ID < 80000) { return $operation ? flock($this->handle, $operation) : true; } + public function stream_seek($offset, $whence) + { + if (0 === fseek($this->handle, $offset, $whence)) { + $this->position = ftell($this->handle); + return true; + } + + return false; + } + public function stream_tell() { return $this->position; @@ -78,20 +88,32 @@ if (PHP_VERSION_ID < 80000) { public function stream_stat() { - return fstat($this->handle); + return array(); } public function stream_set_option($option, $arg1, $arg2) { return true; } + + public function url_stat($path, $flags) + { + $path = substr($path, 17); + if (file_exists($path)) { + return stat($path); + } + + return false; + } } } - if (function_exists('stream_wrapper_register') && stream_wrapper_register('composer-bin-proxy', 'Composer\BinProxyWrapper')) { - include("composer-bin-proxy://" . __DIR__ . '/..'.'/nesbot/carbon/bin/carbon'); - exit(0); + if ( + (function_exists('stream_get_wrappers') && in_array('phpvfscomposer', stream_get_wrappers(), true)) + || (function_exists('stream_wrapper_register') && stream_wrapper_register('phpvfscomposer', 'Composer\BinProxyWrapper')) + ) { + return include("phpvfscomposer://" . __DIR__ . '/..'.'/nesbot/carbon/bin/carbon'); } } -include __DIR__ . '/..'.'/nesbot/carbon/bin/carbon'; +return include __DIR__ . '/..'.'/nesbot/carbon/bin/carbon'; diff --git a/data/web/inc/lib/vendor/bin/var-dump-server b/data/web/inc/lib/vendor/bin/var-dump-server index 1eafd5d9b..18db1c1eb 100755 --- a/data/web/inc/lib/vendor/bin/var-dump-server +++ b/data/web/inc/lib/vendor/bin/var-dump-server @@ -12,6 +12,7 @@ namespace Composer; +$GLOBALS['_composer_bin_dir'] = __DIR__; $GLOBALS['_composer_autoload_path'] = __DIR__ . '/..'.'/autoload.php'; if (PHP_VERSION_ID < 80000) { @@ -23,18 +24,17 @@ if (PHP_VERSION_ID < 80000) { { private $handle; private $position; + private $realpath; public function stream_open($path, $mode, $options, &$opened_path) { - // get rid of composer-bin-proxy:// prefix for __FILE__ & __DIR__ resolution - $opened_path = substr($path, 21); - $opened_path = realpath($opened_path) ?: $opened_path; - $this->handle = fopen($opened_path, $mode); + // get rid of phpvfscomposer:// prefix for __FILE__ & __DIR__ resolution + $opened_path = substr($path, 17); + $this->realpath = realpath($opened_path) ?: $opened_path; + $opened_path = $this->realpath; + $this->handle = fopen($this->realpath, $mode); $this->position = 0; - // remove all traces of this stream wrapper once it has been used - stream_wrapper_unregister('composer-bin-proxy'); - return (bool) $this->handle; } @@ -66,6 +66,16 @@ if (PHP_VERSION_ID < 80000) { return $operation ? flock($this->handle, $operation) : true; } + public function stream_seek($offset, $whence) + { + if (0 === fseek($this->handle, $offset, $whence)) { + $this->position = ftell($this->handle); + return true; + } + + return false; + } + public function stream_tell() { return $this->position; @@ -78,20 +88,32 @@ if (PHP_VERSION_ID < 80000) { public function stream_stat() { - return fstat($this->handle); + return array(); } public function stream_set_option($option, $arg1, $arg2) { return true; } + + public function url_stat($path, $flags) + { + $path = substr($path, 17); + if (file_exists($path)) { + return stat($path); + } + + return false; + } } } - if (function_exists('stream_wrapper_register') && stream_wrapper_register('composer-bin-proxy', 'Composer\BinProxyWrapper')) { - include("composer-bin-proxy://" . __DIR__ . '/..'.'/symfony/var-dumper/Resources/bin/var-dump-server'); - exit(0); + if ( + (function_exists('stream_get_wrappers') && in_array('phpvfscomposer', stream_get_wrappers(), true)) + || (function_exists('stream_wrapper_register') && stream_wrapper_register('phpvfscomposer', 'Composer\BinProxyWrapper')) + ) { + return include("phpvfscomposer://" . __DIR__ . '/..'.'/symfony/var-dumper/Resources/bin/var-dump-server'); } } -include __DIR__ . '/..'.'/symfony/var-dumper/Resources/bin/var-dump-server'; +return include __DIR__ . '/..'.'/symfony/var-dumper/Resources/bin/var-dump-server'; diff --git a/data/web/inc/lib/vendor/carbonphp/carbon-doctrine-types/LICENSE b/data/web/inc/lib/vendor/carbonphp/carbon-doctrine-types/LICENSE new file mode 100644 index 000000000..2ee1671db --- /dev/null +++ b/data/web/inc/lib/vendor/carbonphp/carbon-doctrine-types/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Carbon + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/data/web/inc/lib/vendor/carbonphp/carbon-doctrine-types/README.md b/data/web/inc/lib/vendor/carbonphp/carbon-doctrine-types/README.md new file mode 100644 index 000000000..5a18121b6 --- /dev/null +++ b/data/web/inc/lib/vendor/carbonphp/carbon-doctrine-types/README.md @@ -0,0 +1,14 @@ +# carbonphp/carbon-doctrine-types + +Types to use Carbon in Doctrine + +## Documentation + +[Check how to use in the official Carbon documentation](https://carbon.nesbot.com/symfony/) + +This package is an externalization of [src/Carbon/Doctrine](https://github.com/briannesbitt/Carbon/tree/2.71.0/src/Carbon/Doctrine) +from `nestbot/carbon` package. + +Externalization allows to better deal with different versions of dbal. With +version 4.0 of dbal, it no longer sustainable to be compatible with all version +using a single code. diff --git a/data/web/inc/lib/vendor/carbonphp/carbon-doctrine-types/composer.json b/data/web/inc/lib/vendor/carbonphp/carbon-doctrine-types/composer.json new file mode 100644 index 000000000..abf45c5fb --- /dev/null +++ b/data/web/inc/lib/vendor/carbonphp/carbon-doctrine-types/composer.json @@ -0,0 +1,36 @@ +{ + "name": "carbonphp/carbon-doctrine-types", + "description": "Types to use Carbon in Doctrine", + "type": "library", + "keywords": [ + "date", + "time", + "DateTime", + "Carbon", + "Doctrine" + ], + "require": { + "php": "^8.1" + }, + "require-dev": { + "doctrine/dbal": "^4.0.0", + "nesbot/carbon": "^2.71.0 || ^3.0.0", + "phpunit/phpunit": "^10.3" + }, + "conflict": { + "doctrine/dbal": "<4.0.0 || >=5.0.0" + }, + "license": "MIT", + "autoload": { + "psr-4": { + "Carbon\\Doctrine\\": "src/Carbon/Doctrine/" + } + }, + "authors": [ + { + "name": "KyleKatarn", + "email": "kylekatarnls@gmail.com" + } + ], + "minimum-stability": "dev" +} diff --git a/data/web/inc/lib/vendor/carbonphp/carbon-doctrine-types/src/Carbon/Doctrine/CarbonDoctrineType.php b/data/web/inc/lib/vendor/carbonphp/carbon-doctrine-types/src/Carbon/Doctrine/CarbonDoctrineType.php new file mode 100644 index 000000000..a63a9b8d2 --- /dev/null +++ b/data/web/inc/lib/vendor/carbonphp/carbon-doctrine-types/src/Carbon/Doctrine/CarbonDoctrineType.php @@ -0,0 +1,16 @@ + - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +declare(strict_types=1); namespace Carbon\Doctrine; @@ -15,7 +8,12 @@ use Carbon\Carbon; use Carbon\CarbonInterface; use DateTimeInterface; use Doctrine\DBAL\Platforms\AbstractPlatform; -use Doctrine\DBAL\Types\ConversionException; +use Doctrine\DBAL\Platforms\DB2Platform; +use Doctrine\DBAL\Platforms\OraclePlatform; +use Doctrine\DBAL\Platforms\SQLitePlatform; +use Doctrine\DBAL\Platforms\SQLServerPlatform; +use Doctrine\DBAL\Types\Exception\InvalidType; +use Doctrine\DBAL\Types\Exception\ValueNotConvertible; use Exception; /** @@ -23,6 +21,14 @@ use Exception; */ trait CarbonTypeConverter { + /** + * This property differentiates types installed by carbonphp/carbon-doctrine-types + * from the ones embedded previously in nesbot/carbon source directly. + * + * @readonly + */ + public bool $external = true; + /** * @return class-string */ @@ -31,20 +37,12 @@ trait CarbonTypeConverter return Carbon::class; } - /** - * @return string - */ - public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform) + public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform): string { - $precision = $fieldDeclaration['precision'] ?: 10; - - if ($fieldDeclaration['secondPrecision'] ?? false) { - $precision = 0; - } - - if ($precision === 10) { - $precision = DateTimeDefaultPrecision::get(); - } + $precision = min( + $fieldDeclaration['precision'] ?? DateTimeDefaultPrecision::get(), + $this->getMaximumPrecision($platform), + ); $type = parent::getSQLDeclaration($fieldDeclaration, $platform); @@ -63,10 +61,25 @@ trait CarbonTypeConverter /** * @SuppressWarnings(PHPMD.UnusedFormalParameter) - * - * @return T|null */ - public function convertToPHPValue($value, AbstractPlatform $platform) + public function convertToDatabaseValue($value, AbstractPlatform $platform): ?string + { + if ($value === null) { + return $value; + } + + if ($value instanceof DateTimeInterface) { + return $value->format('Y-m-d H:i:s.u'); + } + + throw InvalidType::new( + $value, + static::class, + ['null', 'DateTime', 'Carbon'] + ); + } + + private function doConvertToPHPValue(mixed $value) { $class = $this->getCarbonClassName(); @@ -88,9 +101,9 @@ trait CarbonTypeConverter } if (!$date) { - throw ConversionException::conversionFailedFormat( + throw ValueNotConvertible::new( $value, - $this->getName(), + static::class, 'Y-m-d H:i:s.u or any format supported by '.$class.'::parse()', $error ); @@ -99,25 +112,20 @@ trait CarbonTypeConverter return $date; } - /** - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - * - * @return string|null - */ - public function convertToDatabaseValue($value, AbstractPlatform $platform) + private function getMaximumPrecision(AbstractPlatform $platform): int { - if ($value === null) { - return $value; + if ($platform instanceof DB2Platform) { + return 12; } - if ($value instanceof DateTimeInterface) { - return $value->format('Y-m-d H:i:s.u'); + if ($platform instanceof OraclePlatform) { + return 9; } - throw ConversionException::conversionFailedInvalidType( - $value, - $this->getName(), - ['null', 'DateTime', 'Carbon'] - ); + if ($platform instanceof SQLServerPlatform || $platform instanceof SQLitePlatform) { + return 3; + } + + return 6; } } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Doctrine/DateTimeDefaultPrecision.php b/data/web/inc/lib/vendor/carbonphp/carbon-doctrine-types/src/Carbon/Doctrine/DateTimeDefaultPrecision.php similarity index 70% rename from data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Doctrine/DateTimeDefaultPrecision.php rename to data/web/inc/lib/vendor/carbonphp/carbon-doctrine-types/src/Carbon/Doctrine/DateTimeDefaultPrecision.php index 642fd4135..cd9896f9c 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Doctrine/DateTimeDefaultPrecision.php +++ b/data/web/inc/lib/vendor/carbonphp/carbon-doctrine-types/src/Carbon/Doctrine/DateTimeDefaultPrecision.php @@ -1,13 +1,6 @@ - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +declare(strict_types=1); namespace Carbon\Doctrine; diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Doctrine/DateTimeImmutableType.php b/data/web/inc/lib/vendor/carbonphp/carbon-doctrine-types/src/Carbon/Doctrine/DateTimeImmutableType.php similarity index 58% rename from data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Doctrine/DateTimeImmutableType.php rename to data/web/inc/lib/vendor/carbonphp/carbon-doctrine-types/src/Carbon/Doctrine/DateTimeImmutableType.php index 499271031..fd6467e3d 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Doctrine/DateTimeImmutableType.php +++ b/data/web/inc/lib/vendor/carbonphp/carbon-doctrine-types/src/Carbon/Doctrine/DateTimeImmutableType.php @@ -1,12 +1,12 @@ */ use CarbonTypeConverter; + /** + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function convertToPHPValue(mixed $value, AbstractPlatform $platform): ?CarbonImmutable + { + return $this->doConvertToPHPValue($value); + } + /** * @return class-string */ diff --git a/data/web/inc/lib/vendor/carbonphp/carbon-doctrine-types/src/Carbon/Doctrine/DateTimeType.php b/data/web/inc/lib/vendor/carbonphp/carbon-doctrine-types/src/Carbon/Doctrine/DateTimeType.php new file mode 100644 index 000000000..89e4b7903 --- /dev/null +++ b/data/web/inc/lib/vendor/carbonphp/carbon-doctrine-types/src/Carbon/Doctrine/DateTimeType.php @@ -0,0 +1,24 @@ + */ + use CarbonTypeConverter; + + /** + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function convertToPHPValue(mixed $value, AbstractPlatform $platform): ?Carbon + { + return $this->doConvertToPHPValue($value); + } +} diff --git a/data/web/inc/lib/vendor/composer/autoload_classmap.php b/data/web/inc/lib/vendor/composer/autoload_classmap.php index 83b86c267..8e4b7d313 100644 --- a/data/web/inc/lib/vendor/composer/autoload_classmap.php +++ b/data/web/inc/lib/vendor/composer/autoload_classmap.php @@ -13,9 +13,4 @@ return array( 'Stringable' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Stringable.php', 'UnhandledMatchError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php', 'ValueError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/ValueError.php', - 'u2flib_server\\Error' => $vendorDir . '/yubico/u2flib-server/src/u2flib_server/U2F.php', - 'u2flib_server\\RegisterRequest' => $vendorDir . '/yubico/u2flib-server/src/u2flib_server/U2F.php', - 'u2flib_server\\Registration' => $vendorDir . '/yubico/u2flib-server/src/u2flib_server/U2F.php', - 'u2flib_server\\SignRequest' => $vendorDir . '/yubico/u2flib-server/src/u2flib_server/U2F.php', - 'u2flib_server\\U2F' => $vendorDir . '/yubico/u2flib-server/src/u2flib_server/U2F.php', ); diff --git a/data/web/inc/lib/vendor/composer/autoload_files.php b/data/web/inc/lib/vendor/composer/autoload_files.php index 526f6b6f4..c426e71df 100644 --- a/data/web/inc/lib/vendor/composer/autoload_files.php +++ b/data/web/inc/lib/vendor/composer/autoload_files.php @@ -6,8 +6,12 @@ $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( + '6e3fae29631ef280660b3cdad06f25a8' => $vendorDir . '/symfony/deprecation-contracts/function.php', '0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php', + '7b11c4dc42b3b3023073cb14e519683c' => $vendorDir . '/ralouphie/getallheaders/src/getallheaders.php', + 'c964ee0ededf28c96ebd9db5099ef910' => $vendorDir . '/guzzlehttp/promises/src/functions_include.php', 'a4a119a56e50fbb293281d9a48007e0e' => $vendorDir . '/symfony/polyfill-php80/bootstrap.php', + '37a3dc5111fe8f707ab4c132ef1dbc62' => $vendorDir . '/guzzlehttp/guzzle/src/functions_include.php', 'a1105708a18b76903365ca1c4aa61b02' => $vendorDir . '/symfony/translation/Resources/functions.php', '667aeda72477189d0494fecd327c3641' => $vendorDir . '/symfony/var-dumper/Resources/functions/dump.php', '6e3fae29631ef280660b3cdad06f25a8' => $vendorDir . '/symfony/deprecation-contracts/function.php', diff --git a/data/web/inc/lib/vendor/composer/autoload_psr4.php b/data/web/inc/lib/vendor/composer/autoload_psr4.php index 0a55fb6cd..eca85b846 100644 --- a/data/web/inc/lib/vendor/composer/autoload_psr4.php +++ b/data/web/inc/lib/vendor/composer/autoload_psr4.php @@ -15,17 +15,27 @@ return array( 'Symfony\\Contracts\\Translation\\' => array($vendorDir . '/symfony/translation-contracts'), 'Symfony\\Component\\VarDumper\\' => array($vendorDir . '/symfony/var-dumper'), 'Symfony\\Component\\Translation\\' => array($vendorDir . '/symfony/translation'), + 'Stevenmaguire\\OAuth2\\Client\\' => array($vendorDir . '/stevenmaguire/oauth2-keycloak/src'), 'RobThree\\Auth\\' => array($vendorDir . '/robthree/twofactorauth/lib'), 'Psr\\SimpleCache\\' => array($vendorDir . '/psr/simple-cache/src'), 'Psr\\Log\\' => array($vendorDir . '/psr/log/src'), + 'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-factory/src', $vendorDir . '/psr/http-message/src'), + 'Psr\\Http\\Client\\' => array($vendorDir . '/psr/http-client/src'), 'Psr\\Container\\' => array($vendorDir . '/psr/container/src'), + 'Psr\\Clock\\' => array($vendorDir . '/psr/clock/src'), 'PhpMimeMailParser\\' => array($vendorDir . '/php-mime-mail-parser/php-mime-mail-parser/src'), 'PHPMailer\\PHPMailer\\' => array($vendorDir . '/phpmailer/phpmailer/src'), 'MatthiasMullie\\PathConverter\\' => array($vendorDir . '/matthiasmullie/path-converter/src'), 'MatthiasMullie\\Minify\\' => array($vendorDir . '/matthiasmullie/minify/src'), + 'League\\OAuth2\\Client\\' => array($vendorDir . '/league/oauth2-client/src'), 'LdapRecord\\' => array($vendorDir . '/directorytree/ldaprecord/src'), 'Illuminate\\Contracts\\' => array($vendorDir . '/illuminate/contracts'), 'Html2Text\\' => array($vendorDir . '/soundasleep/html2text/src'), + 'GuzzleHttp\\Psr7\\' => array($vendorDir . '/guzzlehttp/psr7/src'), + 'GuzzleHttp\\Promise\\' => array($vendorDir . '/guzzlehttp/promises/src'), + 'GuzzleHttp\\' => array($vendorDir . '/guzzlehttp/guzzle/src'), + 'Firebase\\JWT\\' => array($vendorDir . '/firebase/php-jwt/src'), 'Ddeboer\\Imap\\' => array($vendorDir . '/ddeboer/imap/src'), + 'Carbon\\Doctrine\\' => array($vendorDir . '/carbonphp/carbon-doctrine-types/src/Carbon/Doctrine'), 'Carbon\\' => array($vendorDir . '/nesbot/carbon/src/Carbon'), ); diff --git a/data/web/inc/lib/vendor/composer/autoload_static.php b/data/web/inc/lib/vendor/composer/autoload_static.php index 6b2f04a5f..5375b0bea 100644 --- a/data/web/inc/lib/vendor/composer/autoload_static.php +++ b/data/web/inc/lib/vendor/composer/autoload_static.php @@ -7,8 +7,12 @@ namespace Composer\Autoload; class ComposerStaticInit873464e4bd965a3168f133248b1b218b { public static $files = array ( + '6e3fae29631ef280660b3cdad06f25a8' => __DIR__ . '/..' . '/symfony/deprecation-contracts/function.php', '0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/bootstrap.php', + '7b11c4dc42b3b3023073cb14e519683c' => __DIR__ . '/..' . '/ralouphie/getallheaders/src/getallheaders.php', + 'c964ee0ededf28c96ebd9db5099ef910' => __DIR__ . '/..' . '/guzzlehttp/promises/src/functions_include.php', 'a4a119a56e50fbb293281d9a48007e0e' => __DIR__ . '/..' . '/symfony/polyfill-php80/bootstrap.php', + '37a3dc5111fe8f707ab4c132ef1dbc62' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/functions_include.php', 'a1105708a18b76903365ca1c4aa61b02' => __DIR__ . '/..' . '/symfony/translation/Resources/functions.php', '667aeda72477189d0494fecd327c3641' => __DIR__ . '/..' . '/symfony/var-dumper/Resources/functions/dump.php', '6e3fae29631ef280660b3cdad06f25a8' => __DIR__ . '/..' . '/symfony/deprecation-contracts/function.php', @@ -24,12 +28,12 @@ class ComposerStaticInit873464e4bd965a3168f133248b1b218b ); public static $prefixLengthsPsr4 = array ( - 'T' => + 'T' => array ( 'Twig\\' => 5, 'Tightenco\\Collect\\' => 18, ), - 'S' => + 'S' => array ( 'Symfony\\Polyfill\\Php81\\' => 23, 'Symfony\\Polyfill\\Php80\\' => 23, @@ -38,141 +42,198 @@ class ComposerStaticInit873464e4bd965a3168f133248b1b218b 'Symfony\\Contracts\\Translation\\' => 30, 'Symfony\\Component\\VarDumper\\' => 28, 'Symfony\\Component\\Translation\\' => 30, + 'Stevenmaguire\\OAuth2\\Client\\' => 28, ), - 'R' => + 'R' => array ( 'RobThree\\Auth\\' => 14, ), - 'P' => + 'P' => array ( 'Psr\\SimpleCache\\' => 16, 'Psr\\Log\\' => 8, + 'Psr\\Http\\Message\\' => 17, + 'Psr\\Http\\Client\\' => 16, 'Psr\\Container\\' => 14, + 'Psr\\Clock\\' => 10, 'PhpMimeMailParser\\' => 18, 'PHPMailer\\PHPMailer\\' => 20, ), - 'M' => + 'M' => array ( 'MatthiasMullie\\PathConverter\\' => 29, 'MatthiasMullie\\Minify\\' => 22, ), - 'L' => + 'L' => array ( + 'League\\OAuth2\\Client\\' => 21, 'LdapRecord\\' => 11, ), - 'I' => + 'I' => array ( 'Illuminate\\Contracts\\' => 21, ), - 'H' => + 'H' => array ( 'Html2Text\\' => 10, ), - 'D' => + 'G' => + array ( + 'GuzzleHttp\\Psr7\\' => 16, + 'GuzzleHttp\\Promise\\' => 19, + 'GuzzleHttp\\' => 11, + ), + 'F' => + array ( + 'Firebase\\JWT\\' => 13, + ), + 'D' => array ( 'Ddeboer\\Imap\\' => 13, ), - 'C' => + 'C' => array ( + 'Carbon\\Doctrine\\' => 16, 'Carbon\\' => 7, ), ); public static $prefixDirsPsr4 = array ( - 'Twig\\' => + 'Twig\\' => array ( 0 => __DIR__ . '/..' . '/twig/twig/src', ), - 'Tightenco\\Collect\\' => + 'Tightenco\\Collect\\' => array ( 0 => __DIR__ . '/..' . '/tightenco/collect/src/Collect', ), - 'Symfony\\Polyfill\\Php81\\' => + 'Symfony\\Polyfill\\Php81\\' => array ( 0 => __DIR__ . '/..' . '/symfony/polyfill-php81', ), - 'Symfony\\Polyfill\\Php80\\' => + 'Symfony\\Polyfill\\Php80\\' => array ( 0 => __DIR__ . '/..' . '/symfony/polyfill-php80', ), - 'Symfony\\Polyfill\\Mbstring\\' => + 'Symfony\\Polyfill\\Mbstring\\' => array ( 0 => __DIR__ . '/..' . '/symfony/polyfill-mbstring', ), - 'Symfony\\Polyfill\\Ctype\\' => + 'Symfony\\Polyfill\\Ctype\\' => array ( 0 => __DIR__ . '/..' . '/symfony/polyfill-ctype', ), - 'Symfony\\Contracts\\Translation\\' => + 'Symfony\\Contracts\\Translation\\' => array ( 0 => __DIR__ . '/..' . '/symfony/translation-contracts', ), - 'Symfony\\Component\\VarDumper\\' => + 'Symfony\\Component\\VarDumper\\' => array ( 0 => __DIR__ . '/..' . '/symfony/var-dumper', ), - 'Symfony\\Component\\Translation\\' => + 'Symfony\\Component\\Translation\\' => array ( 0 => __DIR__ . '/..' . '/symfony/translation', ), - 'RobThree\\Auth\\' => + 'Stevenmaguire\\OAuth2\\Client\\' => + array ( + 0 => __DIR__ . '/..' . '/stevenmaguire/oauth2-keycloak/src', + ), + 'RobThree\\Auth\\' => array ( 0 => __DIR__ . '/..' . '/robthree/twofactorauth/lib', ), - 'Psr\\SimpleCache\\' => + 'Psr\\SimpleCache\\' => array ( 0 => __DIR__ . '/..' . '/psr/simple-cache/src', ), - 'Psr\\Log\\' => + 'Psr\\Log\\' => array ( 0 => __DIR__ . '/..' . '/psr/log/src', ), - 'Psr\\Container\\' => + 'Psr\\Http\\Message\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/http-factory/src', + 1 => __DIR__ . '/..' . '/psr/http-message/src', + ), + 'Psr\\Http\\Client\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/http-client/src', + ), + 'Psr\\Container\\' => array ( 0 => __DIR__ . '/..' . '/psr/container/src', ), - 'PhpMimeMailParser\\' => + 'Psr\\Clock\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/clock/src', + ), + 'PhpMimeMailParser\\' => array ( 0 => __DIR__ . '/..' . '/php-mime-mail-parser/php-mime-mail-parser/src', ), - 'PHPMailer\\PHPMailer\\' => + 'PHPMailer\\PHPMailer\\' => array ( 0 => __DIR__ . '/..' . '/phpmailer/phpmailer/src', ), - 'MatthiasMullie\\PathConverter\\' => + 'MatthiasMullie\\PathConverter\\' => array ( 0 => __DIR__ . '/..' . '/matthiasmullie/path-converter/src', ), - 'MatthiasMullie\\Minify\\' => + 'MatthiasMullie\\Minify\\' => array ( 0 => __DIR__ . '/..' . '/matthiasmullie/minify/src', ), - 'LdapRecord\\' => + 'League\\OAuth2\\Client\\' => + array ( + 0 => __DIR__ . '/..' . '/league/oauth2-client/src', + ), + 'LdapRecord\\' => array ( 0 => __DIR__ . '/..' . '/directorytree/ldaprecord/src', ), - 'Illuminate\\Contracts\\' => + 'Illuminate\\Contracts\\' => array ( 0 => __DIR__ . '/..' . '/illuminate/contracts', ), - 'Html2Text\\' => + 'Html2Text\\' => array ( 0 => __DIR__ . '/..' . '/soundasleep/html2text/src', ), - 'Ddeboer\\Imap\\' => + 'GuzzleHttp\\Psr7\\' => + array ( + 0 => __DIR__ . '/..' . '/guzzlehttp/psr7/src', + ), + 'GuzzleHttp\\Promise\\' => + array ( + 0 => __DIR__ . '/..' . '/guzzlehttp/promises/src', + ), + 'GuzzleHttp\\' => + array ( + 0 => __DIR__ . '/..' . '/guzzlehttp/guzzle/src', + ), + 'Firebase\\JWT\\' => + array ( + 0 => __DIR__ . '/..' . '/firebase/php-jwt/src', + ), + 'Ddeboer\\Imap\\' => array ( 0 => __DIR__ . '/..' . '/ddeboer/imap/src', ), - 'Carbon\\' => + 'Carbon\\Doctrine\\' => + array ( + 0 => __DIR__ . '/..' . '/carbonphp/carbon-doctrine-types/src/Carbon/Doctrine', + ), + 'Carbon\\' => array ( 0 => __DIR__ . '/..' . '/nesbot/carbon/src/Carbon', ), ); public static $prefixesPsr0 = array ( - 'O' => + 'O' => array ( - 'OAuth2' => + 'OAuth2' => array ( 0 => __DIR__ . '/..' . '/bshaffer/oauth2-server-php/src', ), @@ -187,11 +248,6 @@ class ComposerStaticInit873464e4bd965a3168f133248b1b218b 'Stringable' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Stringable.php', 'UnhandledMatchError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php', 'ValueError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/ValueError.php', - 'u2flib_server\\Error' => __DIR__ . '/..' . '/yubico/u2flib-server/src/u2flib_server/U2F.php', - 'u2flib_server\\RegisterRequest' => __DIR__ . '/..' . '/yubico/u2flib-server/src/u2flib_server/U2F.php', - 'u2flib_server\\Registration' => __DIR__ . '/..' . '/yubico/u2flib-server/src/u2flib_server/U2F.php', - 'u2flib_server\\SignRequest' => __DIR__ . '/..' . '/yubico/u2flib-server/src/u2flib_server/U2F.php', - 'u2flib_server\\U2F' => __DIR__ . '/..' . '/yubico/u2flib-server/src/u2flib_server/U2F.php', ); public static function getInitializer(ClassLoader $loader) diff --git a/data/web/inc/lib/vendor/composer/installed.json b/data/web/inc/lib/vendor/composer/installed.json index dfb2fb0cc..26e8bc42b 100644 --- a/data/web/inc/lib/vendor/composer/installed.json +++ b/data/web/inc/lib/vendor/composer/installed.json @@ -61,6 +61,78 @@ ], "install-path": "../bshaffer/oauth2-server-php" }, + { + "name": "carbonphp/carbon-doctrine-types", + "version": "3.2.0", + "version_normalized": "3.2.0.0", + "source": { + "type": "git", + "url": "https://github.com/CarbonPHP/carbon-doctrine-types.git", + "reference": "18ba5ddfec8976260ead6e866180bd5d2f71aa1d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/CarbonPHP/carbon-doctrine-types/zipball/18ba5ddfec8976260ead6e866180bd5d2f71aa1d", + "reference": "18ba5ddfec8976260ead6e866180bd5d2f71aa1d", + "shasum": "" + }, + "require": { + "php": "^8.1" + }, + "conflict": { + "doctrine/dbal": "<4.0.0 || >=5.0.0" + }, + "require-dev": { + "doctrine/dbal": "^4.0.0", + "nesbot/carbon": "^2.71.0 || ^3.0.0", + "phpunit/phpunit": "^10.3" + }, + "time": "2024-02-09T16:56:22+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Carbon\\Doctrine\\": "src/Carbon/Doctrine/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "KyleKatarn", + "email": "kylekatarnls@gmail.com" + } + ], + "description": "Types to use Carbon in Doctrine", + "keywords": [ + "carbon", + "date", + "datetime", + "doctrine", + "time" + ], + "support": { + "issues": "https://github.com/CarbonPHP/carbon-doctrine-types/issues", + "source": "https://github.com/CarbonPHP/carbon-doctrine-types/tree/3.2.0" + }, + "funding": [ + { + "url": "https://github.com/kylekatarnls", + "type": "github" + }, + { + "url": "https://opencollective.com/Carbon", + "type": "open_collective" + }, + { + "url": "https://tidelift.com/funding/github/packagist/nesbot/carbon", + "type": "tidelift" + } + ], + "install-path": "../carbonphp/carbon-doctrine-types" + }, { "name": "ddeboer/imap", "version": "1.13.1", @@ -141,35 +213,36 @@ }, { "name": "directorytree/ldaprecord", - "version": "v2.10.1", - "version_normalized": "2.10.1.0", + "version": "v2.20.5", + "version_normalized": "2.20.5.0", "source": { "type": "git", "url": "https://github.com/DirectoryTree/LdapRecord.git", - "reference": "bf512d9af7a7b0e2ed7a666ab29cefdd027bee88" + "reference": "5bd0a5a9d257cf1049ae83055dbba4c3479ddf16" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/DirectoryTree/LdapRecord/zipball/bf512d9af7a7b0e2ed7a666ab29cefdd027bee88", - "reference": "bf512d9af7a7b0e2ed7a666ab29cefdd027bee88", + "url": "https://api.github.com/repos/DirectoryTree/LdapRecord/zipball/5bd0a5a9d257cf1049ae83055dbba4c3479ddf16", + "reference": "5bd0a5a9d257cf1049ae83055dbba4c3479ddf16", "shasum": "" }, "require": { "ext-json": "*", "ext-ldap": "*", - "illuminate/contracts": "^5.0|^6.0|^7.0|^8.0|^9.0", + "illuminate/contracts": "^5.0|^6.0|^7.0|^8.0|^9.0|^10.0", "nesbot/carbon": "^1.0|^2.0", "php": ">=7.3", - "psr/log": "*", + "psr/log": "^1.0|^2.0|^3.0", "psr/simple-cache": "^1.0|^2.0", - "tightenco/collect": "^5.6|^6.0|^7.0|^8.0" + "symfony/polyfill-php80": "^1.25", + "tightenco/collect": "^5.6|^6.0|^7.0|^8.0|^9.0" }, "require-dev": { "mockery/mockery": "^1.0", "phpunit/phpunit": "^9.0", "spatie/ray": "^1.24" }, - "time": "2022-02-25T16:00:51+00:00", + "time": "2023-10-11T16:34:34+00:00", "type": "library", "installation-source": "dist", "autoload": { @@ -216,30 +289,433 @@ "install-path": "../directorytree/ldaprecord" }, { - "name": "illuminate/contracts", - "version": "v9.3.0", - "version_normalized": "9.3.0.0", + "name": "firebase/php-jwt", + "version": "v6.5.0", + "version_normalized": "6.5.0.0", "source": { "type": "git", - "url": "https://github.com/illuminate/contracts.git", - "reference": "bf4b3c254c49d28157645d01e4883b5951b1e1d0" + "url": "https://github.com/firebase/php-jwt.git", + "reference": "e94e7353302b0c11ec3cfff7180cd0b1743975d2" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/illuminate/contracts/zipball/bf4b3c254c49d28157645d01e4883b5951b1e1d0", - "reference": "bf4b3c254c49d28157645d01e4883b5951b1e1d0", + "url": "https://api.github.com/repos/firebase/php-jwt/zipball/e94e7353302b0c11ec3cfff7180cd0b1743975d2", + "reference": "e94e7353302b0c11ec3cfff7180cd0b1743975d2", "shasum": "" }, "require": { - "php": "^8.0.2", - "psr/container": "^1.1.1|^2.0.1", - "psr/simple-cache": "^1.0|^2.0|^3.0" + "php": "^7.4||^8.0" }, - "time": "2022-02-22T14:45:39+00:00", + "require-dev": { + "guzzlehttp/guzzle": "^6.5||^7.4", + "phpspec/prophecy-phpunit": "^2.0", + "phpunit/phpunit": "^9.5", + "psr/cache": "^1.0||^2.0", + "psr/http-client": "^1.0", + "psr/http-factory": "^1.0" + }, + "suggest": { + "ext-sodium": "Support EdDSA (Ed25519) signatures", + "paragonie/sodium_compat": "Support EdDSA (Ed25519) signatures when libsodium is not present" + }, + "time": "2023-05-12T15:47:07+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Firebase\\JWT\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Neuman Vong", + "email": "neuman+pear@twilio.com", + "role": "Developer" + }, + { + "name": "Anant Narayanan", + "email": "anant@php.net", + "role": "Developer" + } + ], + "description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.", + "homepage": "https://github.com/firebase/php-jwt", + "keywords": [ + "jwt", + "php" + ], + "support": { + "issues": "https://github.com/firebase/php-jwt/issues", + "source": "https://github.com/firebase/php-jwt/tree/v6.5.0" + }, + "install-path": "../firebase/php-jwt" + }, + { + "name": "guzzlehttp/guzzle", + "version": "7.5.0", + "version_normalized": "7.5.0.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/guzzle.git", + "reference": "b50a2a1251152e43f6a37f0fa053e730a67d25ba" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/guzzle/zipball/b50a2a1251152e43f6a37f0fa053e730a67d25ba", + "reference": "b50a2a1251152e43f6a37f0fa053e730a67d25ba", + "shasum": "" + }, + "require": { + "ext-json": "*", + "guzzlehttp/promises": "^1.5", + "guzzlehttp/psr7": "^1.9 || ^2.4", + "php": "^7.2.5 || ^8.0", + "psr/http-client": "^1.0", + "symfony/deprecation-contracts": "^2.2 || ^3.0" + }, + "provide": { + "psr/http-client-implementation": "1.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.1", + "ext-curl": "*", + "php-http/client-integration-tests": "^3.0", + "phpunit/phpunit": "^8.5.29 || ^9.5.23", + "psr/log": "^1.1 || ^2.0 || ^3.0" + }, + "suggest": { + "ext-curl": "Required for CURL handler support", + "ext-intl": "Required for Internationalized Domain Name (IDN) support", + "psr/log": "Required for using the Log middleware" + }, + "time": "2022-08-28T15:39:27+00:00", + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + }, + "branch-alias": { + "dev-master": "7.5-dev" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "GuzzleHttp\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Jeremy Lindblom", + "email": "jeremeamia@gmail.com", + "homepage": "https://github.com/jeremeamia" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "description": "Guzzle is a PHP HTTP client library", + "keywords": [ + "client", + "curl", + "framework", + "http", + "http client", + "psr-18", + "psr-7", + "rest", + "web service" + ], + "support": { + "issues": "https://github.com/guzzle/guzzle/issues", + "source": "https://github.com/guzzle/guzzle/tree/7.5.0" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/guzzle", + "type": "tidelift" + } + ], + "install-path": "../guzzlehttp/guzzle" + }, + { + "name": "guzzlehttp/promises", + "version": "1.5.2", + "version_normalized": "1.5.2.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/promises.git", + "reference": "b94b2807d85443f9719887892882d0329d1e2598" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/promises/zipball/b94b2807d85443f9719887892882d0329d1e2598", + "reference": "b94b2807d85443f9719887892882d0329d1e2598", + "shasum": "" + }, + "require": { + "php": ">=5.5" + }, + "require-dev": { + "symfony/phpunit-bridge": "^4.4 || ^5.1" + }, + "time": "2022-08-28T14:55:35+00:00", "type": "library", "extra": { "branch-alias": { - "dev-master": "9.x-dev" + "dev-master": "1.5-dev" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "description": "Guzzle promises library", + "keywords": [ + "promise" + ], + "support": { + "issues": "https://github.com/guzzle/promises/issues", + "source": "https://github.com/guzzle/promises/tree/1.5.2" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/promises", + "type": "tidelift" + } + ], + "install-path": "../guzzlehttp/promises" + }, + { + "name": "guzzlehttp/psr7", + "version": "2.4.5", + "version_normalized": "2.4.5.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/psr7.git", + "reference": "0454e12ef0cd597ccd2adb036f7bda4e7fface66" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/0454e12ef0cd597ccd2adb036f7bda4e7fface66", + "reference": "0454e12ef0cd597ccd2adb036f7bda4e7fface66", + "shasum": "" + }, + "require": { + "php": "^7.2.5 || ^8.0", + "psr/http-factory": "^1.0", + "psr/http-message": "^1.0", + "ralouphie/getallheaders": "^3.0" + }, + "provide": { + "psr/http-factory-implementation": "1.0", + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.1", + "http-interop/http-factory-tests": "^0.9", + "phpunit/phpunit": "^8.5.29 || ^9.5.23" + }, + "suggest": { + "laminas/laminas-httphandlerrunner": "Emit PSR-7 responses" + }, + "time": "2023-04-17T16:00:45+00:00", + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://sagikazarmark.hu" + } + ], + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": [ + "http", + "message", + "psr-7", + "request", + "response", + "stream", + "uri", + "url" + ], + "support": { + "issues": "https://github.com/guzzle/psr7/issues", + "source": "https://github.com/guzzle/psr7/tree/2.4.5" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/psr7", + "type": "tidelift" + } + ], + "install-path": "../guzzlehttp/psr7" + }, + { + "name": "illuminate/contracts", + "version": "v10.44.0", + "version_normalized": "10.44.0.0", + "source": { + "type": "git", + "url": "https://github.com/illuminate/contracts.git", + "reference": "8d7152c4a1f5d9cf7da3e8b71f23e4556f6138ac" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/illuminate/contracts/zipball/8d7152c4a1f5d9cf7da3e8b71f23e4556f6138ac", + "reference": "8d7152c4a1f5d9cf7da3e8b71f23e4556f6138ac", + "shasum": "" + }, + "require": { + "php": "^8.1", + "psr/container": "^1.1.1|^2.0.1", + "psr/simple-cache": "^1.0|^2.0|^3.0" + }, + "time": "2024-01-15T18:52:32+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "10.x-dev" } }, "installation-source": "dist", @@ -266,6 +742,79 @@ }, "install-path": "../illuminate/contracts" }, + { + "name": "league/oauth2-client", + "version": "2.7.0", + "version_normalized": "2.7.0.0", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/oauth2-client.git", + "reference": "160d6274b03562ebeb55ed18399281d8118b76c8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/oauth2-client/zipball/160d6274b03562ebeb55ed18399281d8118b76c8", + "reference": "160d6274b03562ebeb55ed18399281d8118b76c8", + "shasum": "" + }, + "require": { + "guzzlehttp/guzzle": "^6.0 || ^7.0", + "paragonie/random_compat": "^1 || ^2 || ^9.99", + "php": "^5.6 || ^7.0 || ^8.0" + }, + "require-dev": { + "mockery/mockery": "^1.3.5", + "php-parallel-lint/php-parallel-lint": "^1.3.1", + "phpunit/phpunit": "^5.7 || ^6.0 || ^9.5", + "squizlabs/php_codesniffer": "^2.3 || ^3.0" + }, + "time": "2023-04-16T18:19:15+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-2.x": "2.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "League\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Alex Bilbie", + "email": "hello@alexbilbie.com", + "homepage": "http://www.alexbilbie.com", + "role": "Developer" + }, + { + "name": "Woody Gilk", + "homepage": "https://github.com/shadowhand", + "role": "Contributor" + } + ], + "description": "OAuth 2.0 Client Library", + "keywords": [ + "Authentication", + "SSO", + "authorization", + "identity", + "idp", + "oauth", + "oauth2", + "single sign on" + ], + "support": { + "issues": "https://github.com/thephpleague/oauth2-client/issues", + "source": "https://github.com/thephpleague/oauth2-client/tree/2.7.0" + }, + "install-path": "../league/oauth2-client" + }, { "name": "matthiasmullie/minify", "version": "1.3.66", @@ -454,38 +1003,45 @@ }, { "name": "nesbot/carbon", - "version": "2.57.0", - "version_normalized": "2.57.0.0", + "version": "2.72.3", + "version_normalized": "2.72.3.0", "source": { "type": "git", "url": "https://github.com/briannesbitt/Carbon.git", - "reference": "4a54375c21eea4811dbd1149fe6b246517554e78" + "reference": "0c6fd108360c562f6e4fd1dedb8233b423e91c83" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/briannesbitt/Carbon/zipball/4a54375c21eea4811dbd1149fe6b246517554e78", - "reference": "4a54375c21eea4811dbd1149fe6b246517554e78", + "url": "https://api.github.com/repos/briannesbitt/Carbon/zipball/0c6fd108360c562f6e4fd1dedb8233b423e91c83", + "reference": "0c6fd108360c562f6e4fd1dedb8233b423e91c83", "shasum": "" }, "require": { + "carbonphp/carbon-doctrine-types": "*", "ext-json": "*", "php": "^7.1.8 || ^8.0", + "psr/clock": "^1.0", "symfony/polyfill-mbstring": "^1.0", "symfony/polyfill-php80": "^1.16", "symfony/translation": "^3.4 || ^4.0 || ^5.0 || ^6.0" }, + "provide": { + "psr/clock-implementation": "1.0" + }, "require-dev": { - "doctrine/dbal": "^2.0 || ^3.0", - "doctrine/orm": "^2.7", + "doctrine/dbal": "^2.0 || ^3.1.4 || ^4.0", + "doctrine/orm": "^2.7 || ^3.0", "friendsofphp/php-cs-fixer": "^3.0", "kylekatarnls/multi-tester": "^2.0", + "ondrejmirtes/better-reflection": "*", "phpmd/phpmd": "^2.9", "phpstan/extension-installer": "^1.0", - "phpstan/phpstan": "^0.12.54 || ^1.0", - "phpunit/phpunit": "^7.5.20 || ^8.5.14", + "phpstan/phpstan": "^0.12.99 || ^1.7.14", + "phpunit/php-file-iterator": "^2.0.5 || ^3.0.6", + "phpunit/phpunit": "^7.5.20 || ^8.5.26 || ^9.5.20", "squizlabs/php_codesniffer": "^3.4" }, - "time": "2022-02-13T18:13:33+00:00", + "time": "2024-01-25T10:35:09+00:00", "bin": [ "bin/carbon" ], @@ -541,11 +1097,15 @@ }, "funding": [ { - "url": "https://opencollective.com/Carbon", - "type": "open_collective" + "url": "https://github.com/sponsors/kylekatarnls", + "type": "github" }, { - "url": "https://tidelift.com/funding/github/packagist/nesbot/carbon", + "url": "https://opencollective.com/Carbon#sponsor", + "type": "opencollective" + }, + { + "url": "https://tidelift.com/subscription/pkg/packagist-nesbot-carbon?utm_source=packagist-nesbot-carbon&utm_medium=referral&utm_campaign=readme", "type": "tidelift" } ], @@ -779,6 +1339,57 @@ ], "install-path": "../phpmailer/phpmailer" }, + { + "name": "psr/clock", + "version": "1.0.0", + "version_normalized": "1.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/clock.git", + "reference": "e41a24703d4560fd0acb709162f73b8adfc3aa0d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/clock/zipball/e41a24703d4560fd0acb709162f73b8adfc3aa0d", + "reference": "e41a24703d4560fd0acb709162f73b8adfc3aa0d", + "shasum": "" + }, + "require": { + "php": "^7.0 || ^8.0" + }, + "time": "2022-11-25T14:36:26+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Clock\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for reading the clock.", + "homepage": "https://github.com/php-fig/clock", + "keywords": [ + "clock", + "now", + "psr", + "psr-20", + "time" + ], + "support": { + "issues": "https://github.com/php-fig/clock/issues", + "source": "https://github.com/php-fig/clock/tree/1.0.0" + }, + "install-path": "../psr/clock" + }, { "name": "psr/container", "version": "2.0.2", @@ -835,6 +1446,175 @@ }, "install-path": "../psr/container" }, + { + "name": "psr/http-client", + "version": "1.0.1", + "version_normalized": "1.0.1.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-client.git", + "reference": "2dfb5f6c5eff0e91e20e913f8c5452ed95b86621" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-client/zipball/2dfb5f6c5eff0e91e20e913f8c5452ed95b86621", + "reference": "2dfb5f6c5eff0e91e20e913f8c5452ed95b86621", + "shasum": "" + }, + "require": { + "php": "^7.0 || ^8.0", + "psr/http-message": "^1.0" + }, + "time": "2020-06-29T06:28:15+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Http\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP clients", + "homepage": "https://github.com/php-fig/http-client", + "keywords": [ + "http", + "http-client", + "psr", + "psr-18" + ], + "support": { + "source": "https://github.com/php-fig/http-client/tree/master" + }, + "install-path": "../psr/http-client" + }, + { + "name": "psr/http-factory", + "version": "1.0.1", + "version_normalized": "1.0.1.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-factory.git", + "reference": "12ac7fcd07e5b077433f5f2bee95b3a771bf61be" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-factory/zipball/12ac7fcd07e5b077433f5f2bee95b3a771bf61be", + "reference": "12ac7fcd07e5b077433f5f2bee95b3a771bf61be", + "shasum": "" + }, + "require": { + "php": ">=7.0.0", + "psr/http-message": "^1.0" + }, + "time": "2019-04-30T12:38:16+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interfaces for PSR-7 HTTP message factories", + "keywords": [ + "factory", + "http", + "message", + "psr", + "psr-17", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-factory/tree/master" + }, + "install-path": "../psr/http-factory" + }, + { + "name": "psr/http-message", + "version": "1.0.1", + "version_normalized": "1.0.1.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "time": "2016-08-06T14:39:51+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-message/tree/master" + }, + "install-path": "../psr/http-message" + }, { "name": "psr/log", "version": "3.0.0", @@ -942,6 +1722,53 @@ }, "install-path": "../psr/simple-cache" }, + { + "name": "ralouphie/getallheaders", + "version": "3.0.3", + "version_normalized": "3.0.3.0", + "source": { + "type": "git", + "url": "https://github.com/ralouphie/getallheaders.git", + "reference": "120b605dfeb996808c31b6477290a714d356e822" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/120b605dfeb996808c31b6477290a714d356e822", + "reference": "120b605dfeb996808c31b6477290a714d356e822", + "shasum": "" + }, + "require": { + "php": ">=5.6" + }, + "require-dev": { + "php-coveralls/php-coveralls": "^2.1", + "phpunit/phpunit": "^5 || ^6.5" + }, + "time": "2019-03-08T08:55:37+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "files": [ + "src/getallheaders.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ralph Khattar", + "email": "ralph.khattar@gmail.com" + } + ], + "description": "A polyfill for getallheaders.", + "support": { + "issues": "https://github.com/ralouphie/getallheaders/issues", + "source": "https://github.com/ralouphie/getallheaders/tree/develop" + }, + "install-path": "../ralouphie/getallheaders" + }, { "name": "robthree/twofactorauth", "version": "1.8.1", @@ -1068,6 +1895,70 @@ ], "install-path": "../soundasleep/html2text" }, + { + "name": "stevenmaguire/oauth2-keycloak", + "version": "4.0.0", + "version_normalized": "4.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/stevenmaguire/oauth2-keycloak.git", + "reference": "05ead6bb6bcd2b6f96dfae87c769dcd3e5f6129d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/stevenmaguire/oauth2-keycloak/zipball/05ead6bb6bcd2b6f96dfae87c769dcd3e5f6129d", + "reference": "05ead6bb6bcd2b6f96dfae87c769dcd3e5f6129d", + "shasum": "" + }, + "require": { + "firebase/php-jwt": "^4.0 || ^5.0 || ^6.0", + "league/oauth2-client": "^2.0", + "php": "~7.2 || ~8.0" + }, + "require-dev": { + "mockery/mockery": "~1.5.0", + "phpunit/phpunit": "~9.6.4", + "squizlabs/php_codesniffer": "~3.7.0" + }, + "time": "2023-03-14T09:43:47+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Stevenmaguire\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Steven Maguire", + "email": "stevenmaguire@gmail.com", + "homepage": "https://github.com/stevenmaguire" + } + ], + "description": "Keycloak OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "keywords": [ + "authorisation", + "authorization", + "client", + "keycloak", + "oauth", + "oauth2" + ], + "support": { + "issues": "https://github.com/stevenmaguire/oauth2-keycloak/issues", + "source": "https://github.com/stevenmaguire/oauth2-keycloak/tree/4.0.0" + }, + "install-path": "../stevenmaguire/oauth2-keycloak" + }, { "name": "symfony/deprecation-contracts", "version": "v3.5.0", @@ -1225,17 +2116,17 @@ }, { "name": "symfony/polyfill-mbstring", - "version": "v1.24.0", - "version_normalized": "1.24.0.0", + "version": "v1.29.0", + "version_normalized": "1.29.0.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-mbstring.git", - "reference": "0abb51d2f102e00a4eefcf46ba7fec406d245825" + "reference": "9773676c8a1bb1f8d4340a62efe641cf76eda7ec" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/0abb51d2f102e00a4eefcf46ba7fec406d245825", - "reference": "0abb51d2f102e00a4eefcf46ba7fec406d245825", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/9773676c8a1bb1f8d4340a62efe641cf76eda7ec", + "reference": "9773676c8a1bb1f8d4340a62efe641cf76eda7ec", "shasum": "" }, "require": { @@ -1247,12 +2138,9 @@ "suggest": { "ext-mbstring": "For best performance" }, - "time": "2021-11-30T18:21:41+00:00", + "time": "2024-01-29T20:11:03+00:00", "type": "library", "extra": { - "branch-alias": { - "dev-main": "1.23-dev" - }, "thanks": { "name": "symfony/polyfill", "url": "https://github.com/symfony/polyfill" @@ -1291,7 +2179,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.24.0" + "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.29.0" }, "funding": [ { @@ -1311,28 +2199,25 @@ }, { "name": "symfony/polyfill-php80", - "version": "v1.24.0", - "version_normalized": "1.24.0.0", + "version": "v1.29.0", + "version_normalized": "1.29.0.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-php80.git", - "reference": "57b712b08eddb97c762a8caa32c84e037892d2e9" + "reference": "87b68208d5c1188808dd7839ee1e6c8ec3b02f1b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/57b712b08eddb97c762a8caa32c84e037892d2e9", - "reference": "57b712b08eddb97c762a8caa32c84e037892d2e9", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/87b68208d5c1188808dd7839ee1e6c8ec3b02f1b", + "reference": "87b68208d5c1188808dd7839ee1e6c8ec3b02f1b", "shasum": "" }, "require": { "php": ">=7.1" }, - "time": "2021-09-13T13:58:33+00:00", + "time": "2024-01-29T20:11:03+00:00", "type": "library", "extra": { - "branch-alias": { - "dev-main": "1.23-dev" - }, "thanks": { "name": "symfony/polyfill", "url": "https://github.com/symfony/polyfill" @@ -1377,7 +2262,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-php80/tree/v1.24.0" + "source": "https://github.com/symfony/polyfill-php80/tree/v1.29.0" }, "funding": [ { @@ -1476,29 +2361,32 @@ }, { "name": "symfony/translation", - "version": "v6.0.5", - "version_normalized": "6.0.5.0", + "version": "v6.4.3", + "version_normalized": "6.4.3.0", "source": { "type": "git", "url": "https://github.com/symfony/translation.git", - "reference": "e69501c71107cc3146b32aaa45f4edd0c3427875" + "reference": "637c51191b6b184184bbf98937702bcf554f7d04" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/translation/zipball/e69501c71107cc3146b32aaa45f4edd0c3427875", - "reference": "e69501c71107cc3146b32aaa45f4edd0c3427875", + "url": "https://api.github.com/repos/symfony/translation/zipball/637c51191b6b184184bbf98937702bcf554f7d04", + "reference": "637c51191b6b184184bbf98937702bcf554f7d04", "shasum": "" }, "require": { - "php": ">=8.0.2", + "php": ">=8.1", + "symfony/deprecation-contracts": "^2.5|^3", "symfony/polyfill-mbstring": "~1.0", - "symfony/translation-contracts": "^2.3|^3.0" + "symfony/translation-contracts": "^2.5|^3.0" }, "conflict": { "symfony/config": "<5.4", "symfony/console": "<5.4", "symfony/dependency-injection": "<5.4", + "symfony/http-client-contracts": "<2.5", "symfony/http-kernel": "<5.4", + "symfony/service-contracts": "<2.5", "symfony/twig-bundle": "<5.4", "symfony/yaml": "<5.4" }, @@ -1506,24 +2394,21 @@ "symfony/translation-implementation": "2.3|3.0" }, "require-dev": { + "nikic/php-parser": "^4.18|^5.0", "psr/log": "^1|^2|^3", - "symfony/config": "^5.4|^6.0", - "symfony/console": "^5.4|^6.0", - "symfony/dependency-injection": "^5.4|^6.0", - "symfony/finder": "^5.4|^6.0", - "symfony/http-client-contracts": "^1.1|^2.0|^3.0", - "symfony/http-kernel": "^5.4|^6.0", - "symfony/intl": "^5.4|^6.0", + "symfony/config": "^5.4|^6.0|^7.0", + "symfony/console": "^5.4|^6.0|^7.0", + "symfony/dependency-injection": "^5.4|^6.0|^7.0", + "symfony/finder": "^5.4|^6.0|^7.0", + "symfony/http-client-contracts": "^2.5|^3.0", + "symfony/http-kernel": "^5.4|^6.0|^7.0", + "symfony/intl": "^5.4|^6.0|^7.0", "symfony/polyfill-intl-icu": "^1.21", - "symfony/service-contracts": "^1.1.2|^2|^3", - "symfony/yaml": "^5.4|^6.0" + "symfony/routing": "^5.4|^6.0|^7.0", + "symfony/service-contracts": "^2.5|^3", + "symfony/yaml": "^5.4|^6.0|^7.0" }, - "suggest": { - "psr/log-implementation": "To use logging capability in translator", - "symfony/config": "", - "symfony/yaml": "" - }, - "time": "2022-02-09T15:52:48+00:00", + "time": "2024-01-29T13:11:52+00:00", "type": "library", "installation-source": "dist", "autoload": { @@ -1554,7 +2439,7 @@ "description": "Provides tools to internationalize your application", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/translation/tree/v6.0.5" + "source": "https://github.com/symfony/translation/tree/v6.4.3" }, "funding": [ { @@ -1574,30 +2459,27 @@ }, { "name": "symfony/translation-contracts", - "version": "v3.0.0", - "version_normalized": "3.0.0.0", + "version": "v3.4.1", + "version_normalized": "3.4.1.0", "source": { "type": "git", "url": "https://github.com/symfony/translation-contracts.git", - "reference": "1b6ea5a7442af5a12dba3dbd6d71034b5b234e77" + "reference": "06450585bf65e978026bda220cdebca3f867fde7" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/translation-contracts/zipball/1b6ea5a7442af5a12dba3dbd6d71034b5b234e77", - "reference": "1b6ea5a7442af5a12dba3dbd6d71034b5b234e77", + "url": "https://api.github.com/repos/symfony/translation-contracts/zipball/06450585bf65e978026bda220cdebca3f867fde7", + "reference": "06450585bf65e978026bda220cdebca3f867fde7", "shasum": "" }, "require": { - "php": ">=8.0.2" + "php": ">=8.1" }, - "suggest": { - "symfony/translation-implementation": "" - }, - "time": "2021-09-07T12:43:40+00:00", + "time": "2023-12-26T14:02:43+00:00", "type": "library", "extra": { "branch-alias": { - "dev-main": "3.0-dev" + "dev-main": "3.4-dev" }, "thanks": { "name": "symfony/contracts", @@ -1608,7 +2490,10 @@ "autoload": { "psr-4": { "Symfony\\Contracts\\Translation\\": "" - } + }, + "exclude-from-classmap": [ + "/Test/" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ @@ -1635,7 +2520,7 @@ "standards" ], "support": { - "source": "https://github.com/symfony/translation-contracts/tree/v3.0.0" + "source": "https://github.com/symfony/translation-contracts/tree/v3.4.1" }, "funding": [ { @@ -1655,40 +2540,37 @@ }, { "name": "symfony/var-dumper", - "version": "v6.0.5", - "version_normalized": "6.0.5.0", + "version": "v6.4.3", + "version_normalized": "6.4.3.0", "source": { "type": "git", "url": "https://github.com/symfony/var-dumper.git", - "reference": "60d6a756d5f485df5e6e40b337334848f79f61ce" + "reference": "0435a08f69125535336177c29d56af3abc1f69da" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/var-dumper/zipball/60d6a756d5f485df5e6e40b337334848f79f61ce", - "reference": "60d6a756d5f485df5e6e40b337334848f79f61ce", + "url": "https://api.github.com/repos/symfony/var-dumper/zipball/0435a08f69125535336177c29d56af3abc1f69da", + "reference": "0435a08f69125535336177c29d56af3abc1f69da", "shasum": "" }, "require": { - "php": ">=8.0.2", + "php": ">=8.1", + "symfony/deprecation-contracts": "^2.5|^3", "symfony/polyfill-mbstring": "~1.0" }, "conflict": { - "phpunit/phpunit": "<5.4.3", "symfony/console": "<5.4" }, "require-dev": { "ext-iconv": "*", - "symfony/console": "^5.4|^6.0", - "symfony/process": "^5.4|^6.0", - "symfony/uid": "^5.4|^6.0", + "symfony/console": "^5.4|^6.0|^7.0", + "symfony/error-handler": "^6.3|^7.0", + "symfony/http-kernel": "^5.4|^6.0|^7.0", + "symfony/process": "^5.4|^6.0|^7.0", + "symfony/uid": "^5.4|^6.0|^7.0", "twig/twig": "^2.13|^3.0.4" }, - "suggest": { - "ext-iconv": "To convert non-UTF-8 strings to UTF-8 (or symfony/polyfill-iconv in case ext-iconv cannot be used).", - "ext-intl": "To show region name in time zone dump", - "symfony/console": "To use the ServerDumpCommand and/or the bin/var-dump-server script" - }, - "time": "2022-02-21T17:15:17+00:00", + "time": "2024-01-23T14:53:30+00:00", "bin": [ "Resources/bin/var-dump-server" ], @@ -1726,7 +2608,7 @@ "dump" ], "support": { - "source": "https://github.com/symfony/var-dumper/tree/v6.0.5" + "source": "https://github.com/symfony/var-dumper/tree/v6.4.3" }, "funding": [ { @@ -1746,21 +2628,21 @@ }, { "name": "tightenco/collect", - "version": "v8.83.2", - "version_normalized": "8.83.2.0", + "version": "v9.52.7", + "version_normalized": "9.52.7.0", "source": { "type": "git", "url": "https://github.com/tighten/collect.git", - "reference": "d9c66d586ec2d216d8a31283d73f8df1400cc722" + "reference": "b15143cd11fe01a700fcc449df61adc64452fa6d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/tighten/collect/zipball/d9c66d586ec2d216d8a31283d73f8df1400cc722", - "reference": "d9c66d586ec2d216d8a31283d73f8df1400cc722", + "url": "https://api.github.com/repos/tighten/collect/zipball/b15143cd11fe01a700fcc449df61adc64452fa6d", + "reference": "b15143cd11fe01a700fcc449df61adc64452fa6d", "shasum": "" }, "require": { - "php": "^7.3|^8.0", + "php": "^8.0", "symfony/var-dumper": "^3.4 || ^4.0 || ^5.0 || ^6.0" }, "require-dev": { @@ -1768,7 +2650,7 @@ "nesbot/carbon": "^2.23.0", "phpunit/phpunit": "^8.3" }, - "time": "2022-02-16T16:15:54+00:00", + "time": "2023-04-14T21:51:36+00:00", "type": "library", "installation-source": "dist", "autoload": { @@ -1797,7 +2679,7 @@ ], "support": { "issues": "https://github.com/tighten/collect/issues", - "source": "https://github.com/tighten/collect/tree/v8.83.2" + "source": "https://github.com/tighten/collect/tree/v9.52.7" }, "install-path": "../tightenco/collect" }, @@ -1882,46 +2764,6 @@ } ], "install-path": "../twig/twig" - }, - { - "name": "yubico/u2flib-server", - "version": "1.0.2", - "version_normalized": "1.0.2.0", - "source": { - "type": "git", - "url": "https://github.com/Yubico/php-u2flib-server.git", - "reference": "55d813acf68212ad2cadecde07551600d6971939" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/Yubico/php-u2flib-server/zipball/55d813acf68212ad2cadecde07551600d6971939", - "reference": "55d813acf68212ad2cadecde07551600d6971939", - "shasum": "" - }, - "require": { - "ext-openssl": "*", - "paragonie/random_compat": ">= 1", - "php": ">=5.6" - }, - "require-dev": { - "phpunit/phpunit": "~5.7", - "vimeo/psalm": "^0|^1|^2" - }, - "time": "2018-09-07T08:16:44+00:00", - "type": "library", - "installation-source": "dist", - "autoload": { - "classmap": [ - "src/" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "BSD-2-Clause" - ], - "description": "Library for U2F implementation", - "homepage": "https://developers.yubico.com/php-u2flib-server", - "install-path": "../yubico/u2flib-server" } ], "dev": true, diff --git a/data/web/inc/lib/vendor/composer/installed.php b/data/web/inc/lib/vendor/composer/installed.php index 5d78fc9f3..074ec9f80 100644 --- a/data/web/inc/lib/vendor/composer/installed.php +++ b/data/web/inc/lib/vendor/composer/installed.php @@ -28,6 +28,15 @@ 'aliases' => array(), 'dev_requirement' => false, ), + 'carbonphp/carbon-doctrine-types' => array( + 'pretty_version' => '3.2.0', + 'version' => '3.2.0.0', + 'reference' => '18ba5ddfec8976260ead6e866180bd5d2f71aa1d', + 'type' => 'library', + 'install_path' => __DIR__ . '/../carbonphp/carbon-doctrine-types', + 'aliases' => array(), + 'dev_requirement' => false, + ), 'ddeboer/imap' => array( 'pretty_version' => '1.13.1', 'version' => '1.13.1.0', @@ -38,9 +47,9 @@ 'dev_requirement' => false, ), 'directorytree/ldaprecord' => array( - 'pretty_version' => 'v2.10.1', - 'version' => '2.10.1.0', - 'reference' => 'bf512d9af7a7b0e2ed7a666ab29cefdd027bee88', + 'pretty_version' => 'v2.20.5', + 'version' => '2.20.5.0', + 'reference' => '5bd0a5a9d257cf1049ae83055dbba4c3479ddf16', 'type' => 'library', 'install_path' => __DIR__ . '/../directorytree/ldaprecord', 'aliases' => array(), @@ -52,15 +61,60 @@ 0 => '*', ), ), + 'firebase/php-jwt' => array( + 'pretty_version' => 'v6.5.0', + 'version' => '6.5.0.0', + 'reference' => 'e94e7353302b0c11ec3cfff7180cd0b1743975d2', + 'type' => 'library', + 'install_path' => __DIR__ . '/../firebase/php-jwt', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'guzzlehttp/guzzle' => array( + 'pretty_version' => '7.5.0', + 'version' => '7.5.0.0', + 'reference' => 'b50a2a1251152e43f6a37f0fa053e730a67d25ba', + 'type' => 'library', + 'install_path' => __DIR__ . '/../guzzlehttp/guzzle', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'guzzlehttp/promises' => array( + 'pretty_version' => '1.5.2', + 'version' => '1.5.2.0', + 'reference' => 'b94b2807d85443f9719887892882d0329d1e2598', + 'type' => 'library', + 'install_path' => __DIR__ . '/../guzzlehttp/promises', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'guzzlehttp/psr7' => array( + 'pretty_version' => '2.4.5', + 'version' => '2.4.5.0', + 'reference' => '0454e12ef0cd597ccd2adb036f7bda4e7fface66', + 'type' => 'library', + 'install_path' => __DIR__ . '/../guzzlehttp/psr7', + 'aliases' => array(), + 'dev_requirement' => false, + ), 'illuminate/contracts' => array( - 'pretty_version' => 'v9.3.0', - 'version' => '9.3.0.0', - 'reference' => 'bf4b3c254c49d28157645d01e4883b5951b1e1d0', + 'pretty_version' => 'v10.44.0', + 'version' => '10.44.0.0', + 'reference' => '8d7152c4a1f5d9cf7da3e8b71f23e4556f6138ac', 'type' => 'library', 'install_path' => __DIR__ . '/../illuminate/contracts', 'aliases' => array(), 'dev_requirement' => false, ), + 'league/oauth2-client' => array( + 'pretty_version' => '2.7.0', + 'version' => '2.7.0.0', + 'reference' => '160d6274b03562ebeb55ed18399281d8118b76c8', + 'type' => 'library', + 'install_path' => __DIR__ . '/../league/oauth2-client', + 'aliases' => array(), + 'dev_requirement' => false, + ), 'matthiasmullie/minify' => array( 'pretty_version' => '1.3.66', 'version' => '1.3.66.0', @@ -95,9 +149,9 @@ 'dev_requirement' => false, ), 'nesbot/carbon' => array( - 'pretty_version' => '2.57.0', - 'version' => '2.57.0.0', - 'reference' => '4a54375c21eea4811dbd1149fe6b246517554e78', + 'pretty_version' => '2.72.3', + 'version' => '2.72.3.0', + 'reference' => '0c6fd108360c562f6e4fd1dedb8233b423e91c83', 'type' => 'library', 'install_path' => __DIR__ . '/../nesbot/carbon', 'aliases' => array(), @@ -130,6 +184,21 @@ 'aliases' => array(), 'dev_requirement' => false, ), + 'psr/clock' => array( + 'pretty_version' => '1.0.0', + 'version' => '1.0.0.0', + 'reference' => 'e41a24703d4560fd0acb709162f73b8adfc3aa0d', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/clock', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/clock-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '1.0', + ), + ), 'psr/container' => array( 'pretty_version' => '2.0.2', 'version' => '2.0.2.0', @@ -139,6 +208,51 @@ 'aliases' => array(), 'dev_requirement' => false, ), + 'psr/http-client' => array( + 'pretty_version' => '1.0.1', + 'version' => '1.0.1.0', + 'reference' => '2dfb5f6c5eff0e91e20e913f8c5452ed95b86621', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/http-client', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/http-client-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '1.0', + ), + ), + 'psr/http-factory' => array( + 'pretty_version' => '1.0.1', + 'version' => '1.0.1.0', + 'reference' => '12ac7fcd07e5b077433f5f2bee95b3a771bf61be', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/http-factory', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/http-factory-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '1.0', + ), + ), + 'psr/http-message' => array( + 'pretty_version' => '1.0.1', + 'version' => '1.0.1.0', + 'reference' => 'f6561bf28d520154e4b0ec72be95418abe6d9363', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/http-message', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/http-message-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '1.0', + ), + ), 'psr/log' => array( 'pretty_version' => '3.0.0', 'version' => '3.0.0.0', @@ -157,6 +271,15 @@ 'aliases' => array(), 'dev_requirement' => false, ), + 'ralouphie/getallheaders' => array( + 'pretty_version' => '3.0.3', + 'version' => '3.0.3.0', + 'reference' => '120b605dfeb996808c31b6477290a714d356e822', + 'type' => 'library', + 'install_path' => __DIR__ . '/../ralouphie/getallheaders', + 'aliases' => array(), + 'dev_requirement' => false, + ), 'robthree/twofactorauth' => array( 'pretty_version' => '1.8.1', 'version' => '1.8.1.0', @@ -175,6 +298,15 @@ 'aliases' => array(), 'dev_requirement' => false, ), + 'stevenmaguire/oauth2-keycloak' => array( + 'pretty_version' => '4.0.0', + 'version' => '4.0.0.0', + 'reference' => '05ead6bb6bcd2b6f96dfae87c769dcd3e5f6129d', + 'type' => 'library', + 'install_path' => __DIR__ . '/../stevenmaguire/oauth2-keycloak', + 'aliases' => array(), + 'dev_requirement' => false, + ), 'symfony/deprecation-contracts' => array( 'pretty_version' => 'v3.5.0', 'version' => '3.5.0.0', @@ -194,18 +326,18 @@ 'dev_requirement' => false, ), 'symfony/polyfill-mbstring' => array( - 'pretty_version' => 'v1.24.0', - 'version' => '1.24.0.0', - 'reference' => '0abb51d2f102e00a4eefcf46ba7fec406d245825', + 'pretty_version' => 'v1.29.0', + 'version' => '1.29.0.0', + 'reference' => '9773676c8a1bb1f8d4340a62efe641cf76eda7ec', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/polyfill-mbstring', 'aliases' => array(), 'dev_requirement' => false, ), 'symfony/polyfill-php80' => array( - 'pretty_version' => 'v1.24.0', - 'version' => '1.24.0.0', - 'reference' => '57b712b08eddb97c762a8caa32c84e037892d2e9', + 'pretty_version' => 'v1.29.0', + 'version' => '1.29.0.0', + 'reference' => '87b68208d5c1188808dd7839ee1e6c8ec3b02f1b', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/polyfill-php80', 'aliases' => array(), @@ -221,18 +353,18 @@ 'dev_requirement' => false, ), 'symfony/translation' => array( - 'pretty_version' => 'v6.0.5', - 'version' => '6.0.5.0', - 'reference' => 'e69501c71107cc3146b32aaa45f4edd0c3427875', + 'pretty_version' => 'v6.4.3', + 'version' => '6.4.3.0', + 'reference' => '637c51191b6b184184bbf98937702bcf554f7d04', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/translation', 'aliases' => array(), 'dev_requirement' => false, ), 'symfony/translation-contracts' => array( - 'pretty_version' => 'v3.0.0', - 'version' => '3.0.0.0', - 'reference' => '1b6ea5a7442af5a12dba3dbd6d71034b5b234e77', + 'pretty_version' => 'v3.4.1', + 'version' => '3.4.1.0', + 'reference' => '06450585bf65e978026bda220cdebca3f867fde7', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/translation-contracts', 'aliases' => array(), @@ -245,18 +377,18 @@ ), ), 'symfony/var-dumper' => array( - 'pretty_version' => 'v6.0.5', - 'version' => '6.0.5.0', - 'reference' => '60d6a756d5f485df5e6e40b337334848f79f61ce', + 'pretty_version' => 'v6.4.3', + 'version' => '6.4.3.0', + 'reference' => '0435a08f69125535336177c29d56af3abc1f69da', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/var-dumper', 'aliases' => array(), 'dev_requirement' => false, ), 'tightenco/collect' => array( - 'pretty_version' => 'v8.83.2', - 'version' => '8.83.2.0', - 'reference' => 'd9c66d586ec2d216d8a31283d73f8df1400cc722', + 'pretty_version' => 'v9.52.7', + 'version' => '9.52.7.0', + 'reference' => 'b15143cd11fe01a700fcc449df61adc64452fa6d', 'type' => 'library', 'install_path' => __DIR__ . '/../tightenco/collect', 'aliases' => array(), @@ -271,14 +403,5 @@ 'aliases' => array(), 'dev_requirement' => false, ), - 'yubico/u2flib-server' => array( - 'pretty_version' => '1.0.2', - 'version' => '1.0.2.0', - 'reference' => '55d813acf68212ad2cadecde07551600d6971939', - 'type' => 'library', - 'install_path' => __DIR__ . '/../yubico/u2flib-server', - 'aliases' => array(), - 'dev_requirement' => false, - ), ), ); diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/.github/ISSUE_TEMPLATE/bug_report.md b/data/web/inc/lib/vendor/directorytree/ldaprecord/.github/ISSUE_TEMPLATE/bug_report.md index a56a2afbc..4cbf18f9c 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/.github/ISSUE_TEMPLATE/bug_report.md +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/.github/ISSUE_TEMPLATE/bug_report.md @@ -7,7 +7,10 @@ assignees: '' --- - + **Environment:** - LDAP Server Type: [e.g. ActiveDirectory / OpenLDAP / FreeIPA] - PHP Version: [e.g. 7.3 / 7.4 / 8.0] diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/.github/ISSUE_TEMPLATE/support---help-request.md b/data/web/inc/lib/vendor/directorytree/ldaprecord/.github/ISSUE_TEMPLATE/support---help-request.md index 230916cf1..731d5cea0 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/.github/ISSUE_TEMPLATE/support---help-request.md +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/.github/ISSUE_TEMPLATE/support---help-request.md @@ -11,7 +11,10 @@ assignees: '' - + **Environment:** - LDAP Server Type: [e.g. ActiveDirectory / OpenLDAP / FreeIPA] - PHP Version: [e.g. 7.3 / 7.4 / 8.0] diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/.github/workflows/run-integration-tests.yml b/data/web/inc/lib/vendor/directorytree/ldaprecord/.github/workflows/run-integration-tests.yml new file mode 100644 index 000000000..6a6b2f9e5 --- /dev/null +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/.github/workflows/run-integration-tests.yml @@ -0,0 +1,62 @@ +name: run-integration-tests + +on: + push: + pull_request: + schedule: + - cron: "0 0 * * *" + +jobs: + run-tests: + runs-on: ${{ matrix.os }} + + services: + ldap: + image: osixia/openldap:1.4.0 + env: + LDAP_TLS_VERIFY_CLIENT: try + LDAP_OPENLDAP_UID: 1000 + LDAP_OPENLDAP_GID: 1000 + LDAP_ORGANISATION: Local + LDAP_DOMAIN: local.com + LDAP_ADMIN_PASSWORD: secret + ports: + - 389:389 + - 636:636 + + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest] + php: [8.1, 8.0, 7.4] + + name: ${{ matrix.os }} - P${{ matrix.php }} + + steps: + - name: Checkout code + uses: actions/checkout@v2 + + - name: Cache dependencies + uses: actions/cache@v2 + with: + path: ~/.composer/cache/files + key: dependencies-php-${{ matrix.php }}-composer-${{ hashFiles('composer.json') }} + + - name: Set ldap.conf file permissions + run: sudo chown -R $USER:$USER /etc/ldap/ldap.conf + + - name: Create ldap.conf file disabling TLS verification + run: sudo echo "TLS_REQCERT never" > "/etc/ldap/ldap.conf" + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: ldap, json + coverage: none + + - name: Install dependencies + run: composer update --prefer-dist --no-interaction + + - name: Execute tests + run: vendor/bin/phpunit --testsuite Integration diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/.github/workflows/run-tests.yml b/data/web/inc/lib/vendor/directorytree/ldaprecord/.github/workflows/run-tests.yml index 44825dc20..6aaa3fd4a 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/.github/workflows/run-tests.yml +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/.github/workflows/run-tests.yml @@ -9,20 +9,20 @@ on: jobs: run-tests: runs-on: ${{ matrix.os }} + name: ${{ matrix.os }} - P${{ matrix.php }} + strategy: fail-fast: false matrix: os: [ubuntu-latest, windows-latest] php: [8.1, 8.0, 7.4, 7.3] - name: ${{ matrix.os }} - P${{ matrix.php }} - steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v2 - name: Cache dependencies - uses: actions/cache@v3 + uses: actions/cache@v2 with: path: ~/.composer/cache/files key: dependencies-php-${{ matrix.php }}-composer-${{ hashFiles('composer.json') }} @@ -38,41 +38,4 @@ jobs: run: composer update --prefer-dist --no-interaction - name: Execute tests - run: vendor/bin/phpunit - - run-analysis: - runs-on: ${{ matrix.os }} - name: Static code analysis (PHP ${{ matrix.php }}) - - strategy: - fail-fast: false - matrix: - os: [ubuntu-latest] - php: [8.0] - - steps: - - name: Checkout code - uses: actions/checkout@v4 - - - name: Cache dependencies - uses: actions/cache@v3 - with: - path: ~/.composer/cache/files - key: dependencies-php-${{ matrix.php }}-composer-${{ hashFiles('composer.json') }} - - - name: Setup PHP - uses: shivammathur/setup-php@v2 - with: - php-version: ${{ matrix.php }} - extensions: ldap, json - coverage: none - tools: psalm - - - name: Validate composer.json - run: composer validate - - - name: Install dependencies - run: composer update --prefer-dist --no-interaction - - - name: Run Psalm - run: psalm + run: vendor/bin/phpunit --testsuite Unit diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/.styleci.yml b/data/web/inc/lib/vendor/directorytree/ldaprecord/.styleci.yml index 9f5e38cfa..0285f1790 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/.styleci.yml +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/.styleci.yml @@ -1,8 +1 @@ preset: laravel -enabled: - - phpdoc_align - - phpdoc_separation - - unalign_double_arrow -disabled: - - laravel_phpdoc_alignment - - laravel_phpdoc_separation diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/composer.json b/data/web/inc/lib/vendor/directorytree/ldaprecord/composer.json index 35c605766..65d7dd8f6 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/composer.json +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/composer.json @@ -32,11 +32,12 @@ "php": ">=7.3", "ext-ldap": "*", "ext-json": "*", - "psr/log": "*", + "psr/log": "^1.0|^2.0|^3.0", "psr/simple-cache": "^1.0|^2.0", "nesbot/carbon": "^1.0|^2.0", - "tightenco/collect": "^5.6|^6.0|^7.0|^8.0", - "illuminate/contracts": "^5.0|^6.0|^7.0|^8.0|^9.0" + "tightenco/collect": "^5.6|^6.0|^7.0|^8.0|^9.0", + "illuminate/contracts": "^5.0|^6.0|^7.0|^8.0|^9.0|^10.0", + "symfony/polyfill-php80": "^1.25" }, "require-dev": { "phpunit/phpunit": "^9.0", diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/docker-compose.yml b/data/web/inc/lib/vendor/directorytree/ldaprecord/docker-compose.yml new file mode 100644 index 000000000..de96b1398 --- /dev/null +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/docker-compose.yml @@ -0,0 +1,35 @@ +version: '3' + +services: + ldap: + image: osixia/openldap:1.4.0 + container_name: ldap + restart: always + hostname: local.com + environment: + LDAP_TLS_VERIFY_CLIENT: try + LDAP_OPENLDAP_UID: 1000 + LDAP_OPENLDAP_GID: 1000 + LDAP_ORGANISATION: Local + LDAP_DOMAIN : local.com + LDAP_ADMIN_PASSWORD: secret + ports: + - "389:389" + - "636:636" + networks: + - local + + ldapadmin: + image: osixia/phpldapadmin:0.9.0 + container_name: ldapadmin + environment: + PHPLDAPADMIN_LDAP_HOSTS: ldap + restart: always + ports: + - "6443:443" + networks: + - local + +networks: + local: + driver: bridge diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/phpunit.xml b/data/web/inc/lib/vendor/directorytree/ldaprecord/phpunit.xml index d03fdc20e..aed09e4d6 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/phpunit.xml +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/phpunit.xml @@ -10,8 +10,11 @@ stopOnFailure="false" > - - ./tests/ + + ./tests/Unit + + + ./tests/Integration diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/psalm.xml b/data/web/inc/lib/vendor/directorytree/ldaprecord/psalm.xml deleted file mode 100644 index 7c0333df3..000000000 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/psalm.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/readme.md b/data/web/inc/lib/vendor/directorytree/ldaprecord/readme.md index 505d6992c..e00f8ef69 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/readme.md +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/readme.md @@ -6,7 +6,7 @@

- + @@ -45,7 +45,7 @@ ⏲ **Up and Running Fast** -Connect to your LDAP servers and start running queries at lightning speed. +Connect to your LDAP servers and start running queries in a matter of minutes. 💡 **Fluent Filter Builder** diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Auth/Events/Event.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Auth/Events/Event.php index 83716b422..7c1bb3c87 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Auth/Events/Event.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Auth/Events/Event.php @@ -30,9 +30,9 @@ abstract class Event /** * Constructor. * - * @param LdapInterface $connection - * @param string $username - * @param string $password + * @param LdapInterface $connection + * @param string $username + * @param string $password */ public function __construct(LdapInterface $connection, $username, $password) { diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Auth/Guard.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Auth/Guard.php index d41af1569..c00989ae6 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Auth/Guard.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Auth/Guard.php @@ -38,8 +38,8 @@ class Guard /** * Constructor. * - * @param LdapInterface $connection - * @param DomainConfiguration $configuration + * @param LdapInterface $connection + * @param DomainConfiguration $configuration */ public function __construct(LdapInterface $connection, DomainConfiguration $configuration) { @@ -50,10 +50,9 @@ class Guard /** * Attempt binding a user to the LDAP server. * - * @param string $username - * @param string $password - * @param bool $stayBound - * + * @param string $username + * @param string $password + * @param bool $stayBound * @return bool * * @throws UsernameRequiredException @@ -90,8 +89,8 @@ class Guard /** * Attempt binding a user to the LDAP server. Supports anonymous binding. * - * @param string|null $username - * @param string|null $password + * @param string|null $username + * @param string|null $password * * @throws BindException * @throws \LdapRecord\ConnectionException @@ -148,8 +147,7 @@ class Guard /** * Set the event dispatcher instance. * - * @param DispatcherInterface $dispatcher - * + * @param DispatcherInterface $dispatcher * @return void */ public function setDispatcher(DispatcherInterface $dispatcher) @@ -160,9 +158,8 @@ class Guard /** * Fire the attempting event. * - * @param string $username - * @param string $password - * + * @param string $username + * @param string $password * @return void */ protected function fireAttemptingEvent($username, $password) @@ -175,9 +172,8 @@ class Guard /** * Fire the passed event. * - * @param string $username - * @param string $password - * + * @param string $username + * @param string $password * @return void */ protected function firePassedEvent($username, $password) @@ -190,9 +186,8 @@ class Guard /** * Fire the failed event. * - * @param string $username - * @param string $password - * + * @param string $username + * @param string $password * @return void */ protected function fireFailedEvent($username, $password) @@ -205,9 +200,8 @@ class Guard /** * Fire the binding event. * - * @param string $username - * @param string $password - * + * @param string $username + * @param string $password * @return void */ protected function fireBindingEvent($username, $password) @@ -220,9 +214,8 @@ class Guard /** * Fire the bound event. * - * @param string $username - * @param string $password - * + * @param string $username + * @param string $password * @return void */ protected function fireBoundEvent($username, $password) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Configuration/DomainConfiguration.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Configuration/DomainConfiguration.php index d1124bfc9..f71f63d87 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Configuration/DomainConfiguration.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Configuration/DomainConfiguration.php @@ -58,7 +58,7 @@ class DomainConfiguration /** * Constructor. * - * @param array $options + * @param array $options * * @throws ConfigurationException When an option value given is an invalid type. */ @@ -74,9 +74,8 @@ class DomainConfiguration /** * Extend the configuration with a custom option, or override an existing. * - * @param string $option - * @param mixed $default - * + * @param string $option + * @param mixed $default * @return void */ public static function extend($option, $default = null) @@ -107,8 +106,8 @@ class DomainConfiguration /** * Set a configuration option. * - * @param string $key - * @param mixed $value + * @param string $key + * @param mixed $value * * @throws ConfigurationException When an option value given is an invalid type. */ @@ -122,8 +121,7 @@ class DomainConfiguration /** * Returns the value for the specified configuration options. * - * @param string $key - * + * @param string $key * @return mixed * * @throws ConfigurationException When the option specified does not exist. @@ -140,8 +138,7 @@ class DomainConfiguration /** * Checks if a configuration option exists. * - * @param string $key - * + * @param string $key * @return bool */ public function has($key) @@ -152,9 +149,8 @@ class DomainConfiguration /** * Validate the configuration option. * - * @param string $key - * @param mixed $value - * + * @param string $key + * @param mixed $value * @return bool * * @throws ConfigurationException When an option value given is an invalid type. diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Configuration/Validators/Validator.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Configuration/Validators/Validator.php index de2f13f56..d107314d5 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Configuration/Validators/Validator.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Configuration/Validators/Validator.php @@ -30,8 +30,8 @@ abstract class Validator /** * Constructor. * - * @param string $key - * @param mixed $value + * @param string $key + * @param mixed $value */ public function __construct($key, $value) { diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Connection.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Connection.php index d429aa462..6e55cffc9 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Connection.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Connection.php @@ -88,8 +88,8 @@ class Connection /** * Constructor. * - * @param array $config - * @param LdapInterface|null $ldap + * @param array|DomainConfiguration $config + * @param LdapInterface|null $ldap */ public function __construct($config = [], LdapInterface $ldap = null) { @@ -109,15 +109,18 @@ class Connection /** * Set the connection configuration. * - * @param array $config - * + * @param array|DomainConfiguration $config * @return $this * * @throws Configuration\ConfigurationException */ public function setConfiguration($config = []) { - $this->configuration = new DomainConfiguration($config); + if (! $config instanceof DomainConfiguration) { + $config = new DomainConfiguration($config); + } + + $this->configuration = $config; $this->hosts = $this->configuration->get('hosts'); @@ -129,8 +132,7 @@ class Connection /** * Set the LDAP connection. * - * @param LdapInterface $ldap - * + * @param LdapInterface $ldap * @return $this */ public function setLdapConnection(LdapInterface $ldap) @@ -143,8 +145,7 @@ class Connection /** * Set the event dispatcher. * - * @param DispatcherInterface $dispatcher - * + * @param DispatcherInterface $dispatcher * @return $this */ public function setDispatcher(DispatcherInterface $dispatcher) @@ -192,8 +193,7 @@ class Connection /** * Set the cache store. * - * @param CacheInterface $store - * + * @param CacheInterface $store * @return $this */ public function setCache(CacheInterface $store) @@ -238,9 +238,8 @@ class Connection * * If no username or password is specified, then the configured credentials are used. * - * @param string|null $username - * @param string|null $password - * + * @param string|null $username + * @param string|null $password * @return Connection * * @throws Auth\BindException @@ -298,6 +297,16 @@ class Connection $this->initialize(); } + /** + * Clone the connection. + * + * @return static + */ + public function replicate() + { + return new static($this->configuration, new $this->ldap); + } + /** * Disconnect from the LDAP server. * @@ -311,8 +320,7 @@ class Connection /** * Dispatch an event. * - * @param object $event - * + * @param object $event * @return void */ public function dispatch($event) @@ -335,8 +343,7 @@ class Connection /** * Perform the operation on the LDAP connection. * - * @param Closure $operation - * + * @param Closure $operation * @return mixed */ public function run(Closure $operation) @@ -359,11 +366,27 @@ class Connection } } + /** + * Perform the operation on an isolated LDAP connection. + * + * @param Closure $operation + * @return mixed + */ + public function isolate(Closure $operation) + { + $connection = $this->replicate(); + + try { + return $operation($connection); + } finally { + $connection->disconnect(); + } + } + /** * Attempt to get an exception for the cause of failure. * - * @param LdapRecordException $e - * + * @param LdapRecordException $e * @return mixed */ protected function getExceptionForCauseOfFailure(LdapRecordException $e) @@ -383,8 +406,7 @@ class Connection /** * Run the operation callback on the current LDAP connection. * - * @param Closure $operation - * + * @param Closure $operation * @return mixed * * @throws LdapRecordException @@ -439,9 +461,8 @@ class Connection /** * Attempt to retry an LDAP operation if due to a lost connection. * - * @param LdapRecordException $e - * @param Closure $operation - * + * @param LdapRecordException $e + * @param Closure $operation * @return mixed * * @throws LdapRecordException @@ -461,8 +482,7 @@ class Connection /** * Retry the operation on the current host. * - * @param Closure $operation - * + * @param Closure $operation * @return mixed * * @throws LdapRecordException @@ -483,9 +503,8 @@ class Connection /** * Attempt the operation again on the next host. * - * @param LdapRecordException $e - * @param Closure $operation - * + * @param LdapRecordException $e + * @param Closure $operation * @return mixed * * @throws LdapRecordException diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/ConnectionManager.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/ConnectionManager.php index 01b072b4e..0597f1f68 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/ConnectionManager.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/ConnectionManager.php @@ -81,9 +81,8 @@ class ConnectionManager /** * Forward missing method calls onto the instance. * - * @param string $method - * @param mixed $args - * + * @param string $method + * @param mixed $args * @return mixed */ public function __call($method, $args) @@ -104,9 +103,8 @@ class ConnectionManager /** * Add a new connection. * - * @param Connection $connection - * @param string|null $name - * + * @param Connection $connection + * @param string|null $name * @return $this */ public function add(Connection $connection, $name = null) @@ -123,8 +121,7 @@ class ConnectionManager /** * Remove a connection. * - * @param $name - * + * @param $name * @return $this */ public function remove($name) @@ -147,8 +144,7 @@ class ConnectionManager /** * Get a connection by name or return the default. * - * @param string|null $name - * + * @param string|null $name * @return Connection * * @throws ContainerException If the given connection does not exist. @@ -185,8 +181,7 @@ class ConnectionManager /** * Checks if the connection exists. * - * @param string $name - * + * @param string $name * @return bool */ public function exists($name) @@ -197,8 +192,7 @@ class ConnectionManager /** * Set the default connection name. * - * @param string $name - * + * @param string $name * @return $this */ public function setDefault($name = null) @@ -237,8 +231,7 @@ class ConnectionManager /** * Set the event logger to use. * - * @param LoggerInterface $logger - * + * @param LoggerInterface $logger * @return void */ public function setLogger(LoggerInterface $logger) @@ -299,8 +292,7 @@ class ConnectionManager /** * Set the event dispatcher. * - * @param DispatcherInterface $dispatcher - * + * @param DispatcherInterface $dispatcher * @return void */ public function setDispatcher(DispatcherInterface $dispatcher) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Container.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Container.php index f458951e7..0c125593d 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Container.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Container.php @@ -48,9 +48,8 @@ class Container /** * Forward missing static calls onto the current instance. * - * @param string $method - * @param mixed $args - * + * @param string $method + * @param mixed $args * @return mixed */ public static function __callStatic($method, $args) @@ -71,8 +70,7 @@ class Container /** * Set the container instance. * - * @param Container|null $container - * + * @param Container|null $container * @return Container|null */ public static function setInstance(self $container = null) @@ -103,9 +101,8 @@ class Container /** * Forward missing method calls onto the connection manager. * - * @param string $method - * @param mixed $args - * + * @param string $method + * @param mixed $args * @return mixed */ public function __call($method, $args) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/DetailedError.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/DetailedError.php index d61159ed3..fff528c98 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/DetailedError.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/DetailedError.php @@ -28,9 +28,9 @@ class DetailedError /** * Constructor. * - * @param int $errorCode - * @param string $errorMessage - * @param string $diagnosticMessage + * @param int $errorCode + * @param string $errorMessage + * @param string $diagnosticMessage */ public function __construct($errorCode, $errorMessage, $diagnosticMessage) { diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/DetectsErrors.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/DetectsErrors.php index e8997a931..61fc4a02e 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/DetectsErrors.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/DetectsErrors.php @@ -7,8 +7,7 @@ trait DetectsErrors /** * Determine if the error was caused by a lost connection. * - * @param string $error - * + * @param string $error * @return bool */ protected function causedByLostConnection($error) @@ -19,8 +18,7 @@ trait DetectsErrors /** * Determine if the error was caused by lack of pagination support. * - * @param string $error - * + * @param string $error * @return bool */ protected function causedByPaginationSupport($error) @@ -31,8 +29,7 @@ trait DetectsErrors /** * Determine if the error was caused by a size limit warning. * - * @param $error - * + * @param $error * @return bool */ protected function causedBySizeLimit($error) @@ -43,8 +40,7 @@ trait DetectsErrors /** * Determine if the error was caused by a "No such object" warning. * - * @param string $error - * + * @param string $error * @return bool */ protected function causedByNoSuchObject($error) @@ -55,15 +51,14 @@ trait DetectsErrors /** * Determine if the error contains the any of the messages. * - * @param string $error - * @param string|array $messages - * + * @param string $error + * @param string|array $messages * @return bool */ protected function errorContainsMessage($error, $messages = []) { foreach ((array) $messages as $message) { - if (strpos($error, $message) !== false) { + if (str_contains((string) $error, $message)) { return true; } } diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/EscapesValues.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/EscapesValues.php index acfc020bf..ea53a2f93 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/EscapesValues.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/EscapesValues.php @@ -9,10 +9,9 @@ trait EscapesValues /** * Prepare a value to be escaped. * - * @param string $value - * @param string $ignore - * @param int $flags - * + * @param string $value + * @param string $ignore + * @param int $flags * @return EscapedValue */ public function escape($value, $ignore = '', $flags = 0) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Events/ConnectionEvent.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Events/ConnectionEvent.php index e9c2c352c..d2d77e2fc 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Events/ConnectionEvent.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Events/ConnectionEvent.php @@ -16,7 +16,7 @@ abstract class ConnectionEvent /** * Constructor. * - * @param Connection $connection + * @param Connection $connection */ public function __construct(Connection $connection) { diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Events/Dispatcher.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Events/Dispatcher.php index a4ae3def0..4fedbc2ef 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Events/Dispatcher.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Events/Dispatcher.php @@ -46,7 +46,7 @@ class Dispatcher implements DispatcherInterface public function listen($events, $listener) { foreach ((array) $events as $event) { - if (strpos($event, '*') !== false) { + if (str_contains((string) $event, '*')) { $this->setupWildcardListen($event, $listener); } else { $this->listeners[$event][] = $this->makeListener($listener); @@ -57,9 +57,8 @@ class Dispatcher implements DispatcherInterface /** * Setup a wildcard listener callback. * - * @param string $event - * @param mixed $listener - * + * @param string $event + * @param mixed $listener * @return void */ protected function setupWildcardListen($event, $listener) @@ -134,9 +133,8 @@ class Dispatcher implements DispatcherInterface /** * Parse the given event and payload and prepare them for dispatching. * - * @param mixed $event - * @param mixed $payload - * + * @param mixed $event + * @param mixed $payload * @return array */ protected function parseEventAndPayload($event, $payload) @@ -168,8 +166,7 @@ class Dispatcher implements DispatcherInterface /** * Get the wildcard listeners for the event. * - * @param string $eventName - * + * @param string $eventName * @return array */ protected function getWildcardListeners($eventName) @@ -190,9 +187,8 @@ class Dispatcher implements DispatcherInterface * * This function is a direct excerpt from Laravel's Str::is(). * - * @param string $wildcard - * @param string $eventName - * + * @param string $wildcard + * @param string $eventName * @return bool */ protected function wildcardContainsEvent($wildcard, $eventName) @@ -229,9 +225,8 @@ class Dispatcher implements DispatcherInterface /** * Add the listeners for the event's interfaces to the given array. * - * @param string $eventName - * @param array $listeners - * + * @param string $eventName + * @param array $listeners * @return array */ protected function addInterfaceListeners($eventName, array $listeners = []) @@ -250,9 +245,8 @@ class Dispatcher implements DispatcherInterface /** * Register an event listener with the dispatcher. * - * @param \Closure|string $listener - * @param bool $wildcard - * + * @param \Closure|string $listener + * @param bool $wildcard * @return \Closure */ public function makeListener($listener, $wildcard = false) @@ -273,9 +267,8 @@ class Dispatcher implements DispatcherInterface /** * Create a class based listener. * - * @param string $listener - * @param bool $wildcard - * + * @param string $listener + * @param bool $wildcard * @return \Closure */ protected function createClassListener($listener, $wildcard = false) @@ -295,8 +288,7 @@ class Dispatcher implements DispatcherInterface /** * Create the class based event callable. * - * @param string $listener - * + * @param string $listener * @return callable */ protected function createClassCallable($listener) @@ -309,13 +301,12 @@ class Dispatcher implements DispatcherInterface /** * Parse the class listener into class and method. * - * @param string $listener - * + * @param string $listener * @return array */ protected function parseListenerCallback($listener) { - return strpos($listener, '@') !== false + return str_contains((string) $listener, '@') ? explode('@', $listener, 2) : [$listener, 'handle']; } @@ -325,7 +316,7 @@ class Dispatcher implements DispatcherInterface */ public function forget($event) { - if (strpos($event, '*') !== false) { + if (str_contains((string) $event, '*')) { unset($this->wildcards[$event]); } else { unset($this->listeners[$event]); diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Events/DispatcherInterface.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Events/DispatcherInterface.php index 6b7cb10c6..590328f09 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Events/DispatcherInterface.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Events/DispatcherInterface.php @@ -7,9 +7,8 @@ interface DispatcherInterface /** * Register an event listener with the dispatcher. * - * @param string|array $events - * @param mixed $listener - * + * @param string|array $events + * @param mixed $listener * @return void */ public function listen($events, $listener); @@ -17,8 +16,7 @@ interface DispatcherInterface /** * Determine if a given event has listeners. * - * @param string $eventName - * + * @param string $eventName * @return bool */ public function hasListeners($eventName); @@ -26,9 +24,8 @@ interface DispatcherInterface /** * Fire an event until the first non-null response is returned. * - * @param string|object $event - * @param mixed $payload - * + * @param string|object $event + * @param mixed $payload * @return array|null */ public function until($event, $payload = []); @@ -36,10 +33,9 @@ interface DispatcherInterface /** * Fire an event and call the listeners. * - * @param string|object $event - * @param mixed $payload - * @param bool $halt - * + * @param string|object $event + * @param mixed $payload + * @param bool $halt * @return mixed */ public function fire($event, $payload = [], $halt = false); @@ -47,10 +43,9 @@ interface DispatcherInterface /** * Fire an event and call the listeners. * - * @param string|object $event - * @param mixed $payload - * @param bool $halt - * + * @param string|object $event + * @param mixed $payload + * @param bool $halt * @return array|null */ public function dispatch($event, $payload = [], $halt = false); @@ -58,8 +53,7 @@ interface DispatcherInterface /** * Get all of the listeners for a given event name. * - * @param string $eventName - * + * @param string $eventName * @return array */ public function getListeners($eventName); @@ -67,8 +61,7 @@ interface DispatcherInterface /** * Remove a set of listeners from the dispatcher. * - * @param string $event - * + * @param string $event * @return void */ public function forget($event); diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Events/Logger.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Events/Logger.php index b2082e596..b8a849169 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Events/Logger.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Events/Logger.php @@ -21,7 +21,7 @@ class Logger /** * Constructor. * - * @param LoggerInterface|null $logger + * @param LoggerInterface|null $logger */ public function __construct(LoggerInterface $logger = null) { @@ -31,8 +31,7 @@ class Logger /** * Logs the given event. * - * @param mixed $event - * + * @param mixed $event * @return void */ public function log($event) @@ -53,8 +52,7 @@ class Logger /** * Logs an authentication event. * - * @param AuthEvent $event - * + * @param AuthEvent $event * @return void */ public function auth(AuthEvent $event) @@ -81,8 +79,7 @@ class Logger /** * Logs a model event. * - * @param ModelEvent $event - * + * @param ModelEvent $event * @return void */ public function model(ModelEvent $event) @@ -106,8 +103,7 @@ class Logger /** * Logs a query event. * - * @param QueryEvent $event - * + * @param QueryEvent $event * @return void */ public function query(QueryEvent $event) @@ -133,8 +129,7 @@ class Logger /** * Returns the operational name of the given event. * - * @param mixed $event - * + * @param mixed $event * @return string */ protected function getOperationName($event) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Events/NullDispatcher.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Events/NullDispatcher.php index 73b1f5a8e..7683d1f80 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Events/NullDispatcher.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Events/NullDispatcher.php @@ -14,7 +14,7 @@ class NullDispatcher implements DispatcherInterface /** * Constructor. * - * @param DispatcherInterface $dispatcher + * @param DispatcherInterface $dispatcher */ public function __construct(DispatcherInterface $dispatcher) { @@ -24,9 +24,8 @@ class NullDispatcher implements DispatcherInterface /** * Register an event listener with the dispatcher. * - * @param string|array $events - * @param mixed $listener - * + * @param string|array $events + * @param mixed $listener * @return void */ public function listen($events, $listener) @@ -37,8 +36,7 @@ class NullDispatcher implements DispatcherInterface /** * Determine if a given event has listeners. * - * @param string $eventName - * + * @param string $eventName * @return bool */ public function hasListeners($eventName) @@ -49,9 +47,8 @@ class NullDispatcher implements DispatcherInterface /** * Fire an event until the first non-null response is returned. * - * @param string|object $event - * @param mixed $payload - * + * @param string|object $event + * @param mixed $payload * @return null */ public function until($event, $payload = []) @@ -62,10 +59,9 @@ class NullDispatcher implements DispatcherInterface /** * Fire an event and call the listeners. * - * @param string|object $event - * @param mixed $payload - * @param bool $halt - * + * @param string|object $event + * @param mixed $payload + * @param bool $halt * @return null */ public function fire($event, $payload = [], $halt = false) @@ -76,10 +72,9 @@ class NullDispatcher implements DispatcherInterface /** * Fire an event and call the listeners. * - * @param string|object $event - * @param mixed $payload - * @param bool $halt - * + * @param string|object $event + * @param mixed $payload + * @param bool $halt * @return null */ public function dispatch($event, $payload = [], $halt = false) @@ -90,8 +85,7 @@ class NullDispatcher implements DispatcherInterface /** * Get all of the listeners for a given event name. * - * @param string $eventName - * + * @param string $eventName * @return array */ public function getListeners($eventName) @@ -102,8 +96,7 @@ class NullDispatcher implements DispatcherInterface /** * Remove a set of listeners from the dispatcher. * - * @param string $event - * + * @param string $event * @return void */ public function forget($event) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/HandlesConnection.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/HandlesConnection.php index 9af7ad751..4a2e27598 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/HandlesConnection.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/HandlesConnection.php @@ -148,8 +148,7 @@ trait HandlesConnection /** * Convert warnings to exceptions for the given operation. * - * @param Closure $operation - * + * @param Closure $operation * @return mixed * * @throws LdapRecordException @@ -190,8 +189,7 @@ trait HandlesConnection /** * Determine if the failed operation should be bypassed. * - * @param string $method - * + * @param string $method * @return bool */ protected function shouldBypassFailure($method) @@ -202,8 +200,7 @@ trait HandlesConnection /** * Determine if the error should be bypassed. * - * @param string $error - * + * @param string $error * @return bool */ protected function shouldBypassError($error) @@ -226,9 +223,8 @@ trait HandlesConnection /** * Generates an LDAP connection string for each host given. * - * @param string|array $hosts - * @param string $port - * + * @param string|array $hosts + * @param string $port * @return string */ protected function makeConnectionUris($hosts, $port) @@ -249,9 +245,8 @@ trait HandlesConnection /** * Assemble the host URI strings. * - * @param array|string $hosts - * @param string $port - * + * @param array|string $hosts + * @param string $port * @return array */ protected function assembleHostUris($hosts, $port) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Ldap.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Ldap.php index 0c3574f13..76c372040 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Ldap.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Ldap.php @@ -4,7 +4,6 @@ namespace LdapRecord; use LDAP\Connection as RawLdapConnection; -/** @psalm-suppress UndefinedClass */ class Ldap implements LdapInterface { use HandlesConnection, DetectsErrors; @@ -24,8 +23,7 @@ class Ldap implements LdapInterface * * @see http://php.net/manual/en/function.ldap-first-entry.php * - * @param resource $searchResults - * + * @param resource $searchResults * @return resource */ public function getFirstEntry($searchResults) @@ -40,8 +38,7 @@ class Ldap implements LdapInterface * * @see http://php.net/manual/en/function.ldap-next-entry.php * - * @param resource $entry - * + * @param resource $entry * @return resource */ public function getNextEntry($entry) @@ -56,8 +53,7 @@ class Ldap implements LdapInterface * * @see http://php.net/manual/en/function.ldap-get-attributes.php * - * @param resource $entry - * + * @param resource $entry * @return array|false */ public function getAttributes($entry) @@ -72,8 +68,7 @@ class Ldap implements LdapInterface * * @see http://php.net/manual/en/function.ldap-count-entries.php * - * @param resource $searchResults - * + * @param resource $searchResults * @return int */ public function countEntries($searchResults) @@ -88,10 +83,9 @@ class Ldap implements LdapInterface * * @see http://php.net/manual/en/function.ldap-compare.php * - * @param string $dn - * @param string $attribute - * @param string $value - * + * @param string $dn + * @param string $attribute + * @param string $value * @return mixed */ public function compare($dn, $attribute, $value) @@ -132,9 +126,8 @@ class Ldap implements LdapInterface * * @see http://php.net/manual/en/function.ldap-get-values-len.php * - * @param $entry - * @param $attribute - * + * @param $entry + * @param $attribute * @return array */ public function getValuesLen($entry, $attribute) @@ -167,8 +160,7 @@ class Ldap implements LdapInterface * * @see http://php.net/manual/en/function.ldap-set-rebind-proc.php * - * @param callable $callback - * + * @param callable $callback * @return bool */ public function setRebindCallback(callable $callback) @@ -304,7 +296,7 @@ class Ldap implements LdapInterface public function bind($username, $password) { return $this->bound = $this->executeFailableOperation(function () use ($username, $password) { - return ldap_bind($this->connection, $username, html_entity_decode($password)); + return ldap_bind($this->connection, $username, $password ? html_entity_decode($password) : null); }); } @@ -462,8 +454,7 @@ class Ldap implements LdapInterface /** * Extract the diagnostic code from the message. * - * @param string $message - * + * @param string $message * @return string|bool */ public function extractDiagnosticCode($message) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/LdapInterface.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/LdapInterface.php index c74fe4e89..fcff57f48 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/LdapInterface.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/LdapInterface.php @@ -9,28 +9,28 @@ interface LdapInterface * * @var string */ - const PROTOCOL_SSL = 'ldaps://'; + public const PROTOCOL_SSL = 'ldaps://'; /** * The standard LDAP protocol string. * * @var string */ - const PROTOCOL = 'ldap://'; + public const PROTOCOL = 'ldap://'; /** * The LDAP SSL port number. * * @var string */ - const PORT_SSL = 636; + public const PORT_SSL = 636; /** * The standard LDAP port number. * * @var string */ - const PORT = 389; + public const PORT = 389; /** * Various useful server control OID's. @@ -38,37 +38,36 @@ interface LdapInterface * @see https://ldap.com/ldap-oid-reference-guide/ * @see http://msdn.microsoft.com/en-us/library/cc223359.aspx */ - const OID_SERVER_START_TLS = '1.3.6.1.4.1.1466.20037'; - const OID_SERVER_PAGED_RESULTS = '1.2.840.113556.1.4.319'; - const OID_SERVER_SHOW_DELETED = '1.2.840.113556.1.4.417'; - const OID_SERVER_SORT = '1.2.840.113556.1.4.473'; - const OID_SERVER_CROSSDOM_MOVE_TARGET = '1.2.840.113556.1.4.521'; - const OID_SERVER_NOTIFICATION = '1.2.840.113556.1.4.528'; - const OID_SERVER_EXTENDED_DN = '1.2.840.113556.1.4.529'; - const OID_SERVER_LAZY_COMMIT = '1.2.840.113556.1.4.619'; - const OID_SERVER_SD_FLAGS = '1.2.840.113556.1.4.801'; - const OID_SERVER_TREE_DELETE = '1.2.840.113556.1.4.805'; - const OID_SERVER_DIRSYNC = '1.2.840.113556.1.4.841'; - const OID_SERVER_VERIFY_NAME = '1.2.840.113556.1.4.1338'; - const OID_SERVER_DOMAIN_SCOPE = '1.2.840.113556.1.4.1339'; - const OID_SERVER_SEARCH_OPTIONS = '1.2.840.113556.1.4.1340'; - const OID_SERVER_PERMISSIVE_MODIFY = '1.2.840.113556.1.4.1413'; - const OID_SERVER_ASQ = '1.2.840.113556.1.4.1504'; - const OID_SERVER_FAST_BIND = '1.2.840.113556.1.4.1781'; - const OID_SERVER_CONTROL_VLVREQUEST = '2.16.840.1.113730.3.4.9'; + public const OID_SERVER_START_TLS = '1.3.6.1.4.1.1466.20037'; + public const OID_SERVER_PAGED_RESULTS = '1.2.840.113556.1.4.319'; + public const OID_SERVER_SHOW_DELETED = '1.2.840.113556.1.4.417'; + public const OID_SERVER_SORT = '1.2.840.113556.1.4.473'; + public const OID_SERVER_CROSSDOM_MOVE_TARGET = '1.2.840.113556.1.4.521'; + public const OID_SERVER_NOTIFICATION = '1.2.840.113556.1.4.528'; + public const OID_SERVER_EXTENDED_DN = '1.2.840.113556.1.4.529'; + public const OID_SERVER_LAZY_COMMIT = '1.2.840.113556.1.4.619'; + public const OID_SERVER_SD_FLAGS = '1.2.840.113556.1.4.801'; + public const OID_SERVER_TREE_DELETE = '1.2.840.113556.1.4.805'; + public const OID_SERVER_DIRSYNC = '1.2.840.113556.1.4.841'; + public const OID_SERVER_VERIFY_NAME = '1.2.840.113556.1.4.1338'; + public const OID_SERVER_DOMAIN_SCOPE = '1.2.840.113556.1.4.1339'; + public const OID_SERVER_SEARCH_OPTIONS = '1.2.840.113556.1.4.1340'; + public const OID_SERVER_PERMISSIVE_MODIFY = '1.2.840.113556.1.4.1413'; + public const OID_SERVER_ASQ = '1.2.840.113556.1.4.1504'; + public const OID_SERVER_FAST_BIND = '1.2.840.113556.1.4.1781'; + public const OID_SERVER_CONTROL_VLVREQUEST = '2.16.840.1.113730.3.4.9'; /** * Query OID's. * * @see https://ldapwiki.com/wiki/LDAP_MATCHING_RULE_IN_CHAIN */ - const OID_MATCHING_RULE_IN_CHAIN = '1.2.840.113556.1.4.1941'; + public const OID_MATCHING_RULE_IN_CHAIN = '1.2.840.113556.1.4.1941'; /** * Set the current connection to use SSL. * - * @param bool $enabled - * + * @param bool $enabled * @return $this */ public function ssl(); @@ -83,8 +82,7 @@ interface LdapInterface /** * Set the current connection to use TLS. * - * @param bool $enabled - * + * @param bool $enabled * @return $this */ public function tls(); @@ -138,8 +136,7 @@ interface LdapInterface * * @see http://php.net/manual/en/function.ldap-get-entries.php * - * @param resource $searchResults - * + * @param resource $searchResults * @return array */ public function getEntries($searchResults); @@ -169,9 +166,8 @@ interface LdapInterface * * @see http://php.net/manual/en/function.ldap-set-option.php * - * @param int $option - * @param mixed $value - * + * @param int $option + * @param mixed $value * @return bool */ public function setOption($option, $value); @@ -179,8 +175,7 @@ interface LdapInterface /** * Set options on the current connection. * - * @param array $options - * + * @param array $options * @return void */ public function setOptions(array $options = []); @@ -190,9 +185,8 @@ interface LdapInterface * * @see https://www.php.net/manual/en/function.ldap-get-option.php * - * @param int $option - * @param mixed $value - * + * @param int $option + * @param mixed $value * @return mixed */ public function getOption($option, &$value = null); @@ -213,9 +207,8 @@ interface LdapInterface * * @see http://php.net/manual/en/function.ldap-start-tls.php * - * @param string|array $hosts - * @param int $port - * + * @param string|array $hosts + * @param int $port * @return resource|false */ public function connect($hosts = [], $port = 389); @@ -236,15 +229,14 @@ interface LdapInterface * * @see http://php.net/manual/en/function.ldap-search.php * - * @param string $dn - * @param string $filter - * @param array $fields - * @param bool $onlyAttributes - * @param int $size - * @param int $time - * @param int $deref - * @param array $serverControls - * + * @param string $dn + * @param string $filter + * @param array $fields + * @param bool $onlyAttributes + * @param int $size + * @param int $time + * @param int $deref + * @param array $serverControls * @return resource */ public function search($dn, $filter, array $fields, $onlyAttributes = false, $size = 0, $time = 0, $deref = LDAP_DEREF_NEVER, $serverControls = []); @@ -254,15 +246,14 @@ interface LdapInterface * * @see http://php.net/manual/en/function.ldap-list.php * - * @param string $dn - * @param string $filter - * @param array $fields - * @param bool $onlyAttributes - * @param int $size - * @param int $time - * @param int $deref - * @param array $serverControls - * + * @param string $dn + * @param string $filter + * @param array $fields + * @param bool $onlyAttributes + * @param int $size + * @param int $time + * @param int $deref + * @param array $serverControls * @return resource */ public function listing($dn, $filter, array $fields, $onlyAttributes = false, $size = 0, $time = 0, $deref = LDAP_DEREF_NEVER, $serverControls = []); @@ -272,15 +263,14 @@ interface LdapInterface * * @see http://php.net/manual/en/function.ldap-read.php * - * @param string $dn - * @param string $filter - * @param array $fields - * @param bool $onlyAttributes - * @param int $size - * @param int $time - * @param int $deref - * @param array $serverControls - * + * @param string $dn + * @param string $filter + * @param array $fields + * @param bool $onlyAttributes + * @param int $size + * @param int $time + * @param int $deref + * @param array $serverControls * @return resource */ public function read($dn, $filter, array $fields, $onlyAttributes = false, $size = 0, $time = 0, $deref = LDAP_DEREF_NEVER, $serverControls = []); @@ -290,13 +280,12 @@ interface LdapInterface * * @see https://www.php.net/manual/en/function.ldap-parse-result.php * - * @param resource $result - * @param int $errorCode - * @param ?string $dn - * @param ?string $errorMessage - * @param ?array $referrals - * @param ?array $serverControls - * + * @param resource $result + * @param int $errorCode + * @param ?string $dn + * @param ?string $errorMessage + * @param ?array $referrals + * @param ?array $serverControls * @return bool */ public function parseResult($result, &$errorCode, &$dn, &$errorMessage, &$referrals, &$serverControls = []); @@ -307,9 +296,8 @@ interface LdapInterface * * @see http://php.net/manual/en/function.ldap-bind.php * - * @param string $username - * @param string $password - * + * @param string $username + * @param string $password * @return bool * * @throws LdapRecordException @@ -321,9 +309,8 @@ interface LdapInterface * * @see http://php.net/manual/en/function.ldap-add.php * - * @param string $dn - * @param array $entry - * + * @param string $dn + * @param array $entry * @return bool * * @throws LdapRecordException @@ -335,8 +322,7 @@ interface LdapInterface * * @see http://php.net/manual/en/function.ldap-delete.php * - * @param string $dn - * + * @param string $dn * @return bool * * @throws LdapRecordException @@ -348,11 +334,10 @@ interface LdapInterface * * @see http://php.net/manual/en/function.ldap-rename.php * - * @param string $dn - * @param string $newRdn - * @param string $newParent - * @param bool $deleteOldRdn - * + * @param string $dn + * @param string $newRdn + * @param string $newParent + * @param bool $deleteOldRdn * @return bool * * @throws LdapRecordException @@ -364,9 +349,8 @@ interface LdapInterface * * @see http://php.net/manual/en/function.ldap-modify.php * - * @param string $dn - * @param array $entry - * + * @param string $dn + * @param array $entry * @return bool * * @throws LdapRecordException @@ -378,9 +362,8 @@ interface LdapInterface * * @see http://php.net/manual/en/function.ldap-modify-batch.php * - * @param string $dn - * @param array $values - * + * @param string $dn + * @param array $values * @return bool * * @throws LdapRecordException @@ -392,9 +375,8 @@ interface LdapInterface * * @see http://php.net/manual/en/function.ldap-mod-add.php * - * @param string $dn - * @param array $entry - * + * @param string $dn + * @param array $entry * @return bool * * @throws LdapRecordException @@ -406,9 +388,8 @@ interface LdapInterface * * @see http://php.net/manual/en/function.ldap-mod-replace.php * - * @param string $dn - * @param array $entry - * + * @param string $dn + * @param array $entry * @return bool * * @throws LdapRecordException @@ -420,9 +401,8 @@ interface LdapInterface * * @see http://php.net/manual/en/function.ldap-mod-del.php * - * @param string $dn - * @param array $entry - * + * @param string $dn + * @param array $entry * @return bool * * @throws LdapRecordException @@ -434,10 +414,9 @@ interface LdapInterface * * @see http://php.net/manual/en/function.ldap-control-paged-result.php * - * @param int $pageSize - * @param bool $isCritical - * @param string $cookie - * + * @param int $pageSize + * @param bool $isCritical + * @param string $cookie * @return bool */ public function controlPagedResult($pageSize = 1000, $isCritical = false, $cookie = ''); @@ -447,9 +426,8 @@ interface LdapInterface * * @see http://php.net/manual/en/function.ldap-control-paged-result-response.php * - * @param resource $result - * @param string $cookie - * + * @param resource $result + * @param string $cookie * @return bool */ public function controlPagedResultResponse($result, &$cookie); @@ -459,8 +437,7 @@ interface LdapInterface * * @see https://www.php.net/manual/en/function.ldap-free-result.php * - * @param resource $result - * + * @param resource $result * @return bool */ public function freeResult($result); @@ -479,8 +456,7 @@ interface LdapInterface * * @see http://php.net/manual/en/function.ldap-err2str.php * - * @param int $number - * + * @param int $number * @return string */ public function err2Str($number); diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/LdapRecordException.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/LdapRecordException.php index b2439bf83..0669b4c65 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/LdapRecordException.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/LdapRecordException.php @@ -16,9 +16,8 @@ class LdapRecordException extends Exception /** * Create a new Bind Exception with a detailed connection error. * - * @param Exception $e - * @param DetailedError|null $error - * + * @param Exception $e + * @param DetailedError|null $error * @return $this */ public static function withDetailedError(Exception $e, DetailedError $error = null) @@ -29,8 +28,7 @@ class LdapRecordException extends Exception /** * Set the detailed error. * - * @param DetailedError|null $error - * + * @param DetailedError|null $error * @return $this */ public function setDetailedError(DetailedError $error = null) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ActiveDirectory/Concerns/HasPrimaryGroup.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ActiveDirectory/Concerns/HasPrimaryGroup.php index 97fd3a1fb..b7138d30c 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ActiveDirectory/Concerns/HasPrimaryGroup.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ActiveDirectory/Concerns/HasPrimaryGroup.php @@ -9,10 +9,9 @@ trait HasPrimaryGroup /** * Returns a new has one primary group relationship. * - * @param mixed $related - * @param string $relationKey - * @param string $foreignKey - * + * @param mixed $related + * @param string $relationKey + * @param string $foreignKey * @return HasOnePrimaryGroup */ public function hasOnePrimaryGroup($related, $relationKey, $foreignKey = 'primarygroupid') diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ActiveDirectory/Entry.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ActiveDirectory/Entry.php index 652ad563f..e1a0233cc 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ActiveDirectory/Entry.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ActiveDirectory/Entry.php @@ -9,6 +9,7 @@ use LdapRecord\Models\Entry as BaseEntry; use LdapRecord\Models\Events\Updated; use LdapRecord\Models\Types\ActiveDirectory; use LdapRecord\Query\Model\ActiveDirectoryBuilder; +use LdapRecord\Support\Arr; /** @mixin ActiveDirectoryBuilder */ class Entry extends BaseEntry implements ActiveDirectory @@ -50,20 +51,46 @@ class Entry extends BaseEntry implements ActiveDirectory /** * @inheritdoc */ - public function getConvertedSid() + public function getConvertedSid($sid = null) { try { - return (string) new Sid($this->getObjectSid()); + return (string) $this->newObjectSid( + $sid ?? $this->getObjectSid() + ); } catch (InvalidArgumentException $e) { return; } } + /** + * @inheritdoc + */ + public function getBinarySid($sid = null) + { + try { + return $this->newObjectSid( + $sid ?? $this->getObjectSid() + )->getBinary(); + } catch (InvalidArgumentException $e) { + return; + } + } + + /** + * Make a new object Sid instance. + * + * @param string $value + * @return Sid + */ + protected function newObjectSid($value) + { + return new Sid($value); + } + /** * Create a new query builder. * - * @param Connection $connection - * + * @param Connection $connection * @return ActiveDirectoryBuilder */ public function newQueryBuilder(Connection $connection) @@ -84,8 +111,7 @@ class Entry extends BaseEntry implements ActiveDirectory /** * Restore a deleted object. * - * @param string|null $newParentDn - * + * @param string|null $newParentDn * @return bool * * @throws \LdapRecord\LdapRecordException @@ -114,24 +140,6 @@ class Entry extends BaseEntry implements ActiveDirectory $this->save(['isDeleted' => null]); } - /** - * Get the RootDSE (AD schema) record from the directory. - * - * @param string|null $connection - * - * @return static - * - * @throws \LdapRecord\Models\ModelNotFoundException - */ - public static function getRootDse($connection = null) - { - return static::on($connection ?? (new static())->getConnectionName()) - ->in(null) - ->read() - ->whereHas('objectclass') - ->firstOrFail(); - } - /** * Get the objects restore location. * @@ -143,22 +151,50 @@ class Entry extends BaseEntry implements ActiveDirectory } /** - * Converts attributes for JSON serialization. - * - * @param array $attributes + * Convert the attributes for JSON serialization. * + * @param array $attributes * @return array */ protected function convertAttributesForJson(array $attributes = []) { $attributes = parent::convertAttributesForJson($attributes); - if ($this->hasAttribute($this->sidKey)) { - // If the model has a SID set, we need to convert it due to it being in - // binary. Otherwise we will receive a JSON serialization exception. - return array_replace($attributes, [ - $this->sidKey => [$this->getConvertedSid()], - ]); + // If the model has a SID set, we need to convert it to its + // string format, due to it being in binary. Otherwise + // we will receive a JSON serialization exception. + if (isset($attributes[$this->sidKey])) { + $attributes[$this->sidKey] = [$this->getConvertedSid( + Arr::first($attributes[$this->sidKey]) + )]; + } + + return $attributes; + } + + /** + * Convert the attributes from JSON serialization. + * + * @param array $attributes + * @return array + */ + protected function convertAttributesFromJson(array $attributes = []) + { + $attributes = parent::convertAttributesFromJson($attributes); + + // Here we are converting the model's GUID and SID attributes + // back to their original values from serialization, so that + // their original value may be used and compared against. + if (isset($attributes[$this->guidKey])) { + $attributes[$this->guidKey] = [$this->getBinaryGuid( + Arr::first($attributes[$this->guidKey]) + )]; + } + + if (isset($attributes[$this->sidKey])) { + $attributes[$this->sidKey] = [$this->getBinarySid( + Arr::first($attributes[$this->sidKey]) + )]; } return $attributes; diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ActiveDirectory/Relations/HasOnePrimaryGroup.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ActiveDirectory/Relations/HasOnePrimaryGroup.php index 540ec7717..40350c97a 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ActiveDirectory/Relations/HasOnePrimaryGroup.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ActiveDirectory/Relations/HasOnePrimaryGroup.php @@ -10,8 +10,7 @@ class HasOnePrimaryGroup extends HasOne /** * Get the foreign model by the given value. * - * @param string $value - * + * @param string $value * @return Model|null */ protected function getForeignModelByValue($value) @@ -26,8 +25,7 @@ class HasOnePrimaryGroup extends HasOne * * Retrieves the last RID from the models Object SID. * - * @param Model $model - * + * @param Model $model * @return string */ protected function getForeignValueFromModel(Model $model) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ActiveDirectory/Scopes/HasServerRoleAttribute.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ActiveDirectory/Scopes/HasServerRoleAttribute.php index cd08648da..76df79ca3 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ActiveDirectory/Scopes/HasServerRoleAttribute.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ActiveDirectory/Scopes/HasServerRoleAttribute.php @@ -11,9 +11,8 @@ class HasServerRoleAttribute implements Scope /** * Includes condition of having a serverRole attribute. * - * @param Builder $query - * @param Model $model - * + * @param Builder $query + * @param Model $model * @return void */ public function apply(Builder $query, Model $model) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ActiveDirectory/Scopes/InConfigurationContext.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ActiveDirectory/Scopes/InConfigurationContext.php index 9f2fbe4d7..dc8a4d21b 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ActiveDirectory/Scopes/InConfigurationContext.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ActiveDirectory/Scopes/InConfigurationContext.php @@ -12,9 +12,8 @@ class InConfigurationContext implements Scope /** * Refines the base dn to be inside the configuration context. * - * @param Builder $query - * @param Model $model - * + * @param Builder $query + * @param Model $model * @return void * * @throws \LdapRecord\Models\ModelNotFoundException @@ -27,8 +26,7 @@ class InConfigurationContext implements Scope /** * Get the LDAP server configuration naming context distinguished name. * - * @param Model $model - * + * @param Model $model * @return mixed * * @throws \LdapRecord\Models\ModelNotFoundException diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ActiveDirectory/Scopes/RejectComputerObjectClass.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ActiveDirectory/Scopes/RejectComputerObjectClass.php index a616db1c0..9d00cf8fa 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ActiveDirectory/Scopes/RejectComputerObjectClass.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ActiveDirectory/Scopes/RejectComputerObjectClass.php @@ -11,9 +11,8 @@ class RejectComputerObjectClass implements Scope /** * Prevent computer objects from being included in results. * - * @param Builder $query - * @param Model $model - * + * @param Builder $query + * @param Model $model * @return void */ public function apply(Builder $query, Model $model) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ActiveDirectory/User.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ActiveDirectory/User.php index b735b03b2..c2ea0325d 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ActiveDirectory/User.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ActiveDirectory/User.php @@ -6,6 +6,7 @@ use Carbon\Carbon; use Illuminate\Contracts\Auth\Authenticatable; use LdapRecord\Models\ActiveDirectory\Concerns\HasPrimaryGroup; use LdapRecord\Models\ActiveDirectory\Scopes\RejectComputerObjectClass; +use LdapRecord\Models\Attributes\AccountControl; use LdapRecord\Models\Concerns\CanAuthenticate; use LdapRecord\Models\Concerns\HasPassword; use LdapRecord\Query\Model\Builder; @@ -71,6 +72,38 @@ class User extends Entry implements Authenticatable static::addGlobalScope(new RejectComputerObjectClass()); } + /** + * Determine if the user's account is enabled. + * + * @return bool + */ + public function isEnabled() + { + return ! $this->isDisabled(); + } + + /** + * Determine if the user's account is disabled. + * + * @return bool + */ + public function isDisabled() + { + return $this->accountControl()->has(AccountControl::ACCOUNTDISABLE); + } + + /** + * Get the user's account control. + * + * @return AccountControl + */ + public function accountControl() + { + return new AccountControl( + $this->getFirstAttribute('userAccountControl') + ); + } + /** * The groups relationship. * @@ -110,8 +143,7 @@ class User extends Entry implements Authenticatable /** * Scopes the query to exchange mailbox users. * - * @param Builder $query - * + * @param Builder $query * @return Builder */ public function scopeWhereHasMailbox(Builder $query) @@ -122,8 +154,7 @@ class User extends Entry implements Authenticatable /** * Scopes the query to users having a lockout value set. * - * @param Builder $query - * + * @param Builder $query * @return Builder */ public function scopeWhereHasLockout(Builder $query) @@ -137,9 +168,8 @@ class User extends Entry implements Authenticatable * @see https://ldapwiki.com/wiki/Active%20Directory%20Account%20Lockout * @see https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/account-lockout-duration * - * @param string|int $localTimezone - * @param int|null $durationInMinutes - * + * @param string|int $localTimezone + * @param int|null $durationInMinutes * @return bool */ public function isLockedOut($localTimezone, $durationInMinutes = null) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/AccountControl.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/AccountControl.php index 7e2414629..45fae214d 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/AccountControl.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/AccountControl.php @@ -6,49 +6,49 @@ use ReflectionClass; class AccountControl { - const SCRIPT = 1; + public const SCRIPT = 1; - const ACCOUNTDISABLE = 2; + public const ACCOUNTDISABLE = 2; - const HOMEDIR_REQUIRED = 8; + public const HOMEDIR_REQUIRED = 8; - const LOCKOUT = 16; + public const LOCKOUT = 16; - const PASSWD_NOTREQD = 32; + public const PASSWD_NOTREQD = 32; - const PASSWD_CANT_CHANGE = 64; + public const PASSWD_CANT_CHANGE = 64; - const ENCRYPTED_TEXT_PWD_ALLOWED = 128; + public const ENCRYPTED_TEXT_PWD_ALLOWED = 128; - const TEMP_DUPLICATE_ACCOUNT = 256; + public const TEMP_DUPLICATE_ACCOUNT = 256; - const NORMAL_ACCOUNT = 512; + public const NORMAL_ACCOUNT = 512; - const INTERDOMAIN_TRUST_ACCOUNT = 2048; + public const INTERDOMAIN_TRUST_ACCOUNT = 2048; - const WORKSTATION_TRUST_ACCOUNT = 4096; + public const WORKSTATION_TRUST_ACCOUNT = 4096; - const SERVER_TRUST_ACCOUNT = 8192; + public const SERVER_TRUST_ACCOUNT = 8192; - const DONT_EXPIRE_PASSWORD = 65536; + public const DONT_EXPIRE_PASSWORD = 65536; - const MNS_LOGON_ACCOUNT = 131072; + public const MNS_LOGON_ACCOUNT = 131072; - const SMARTCARD_REQUIRED = 262144; + public const SMARTCARD_REQUIRED = 262144; - const TRUSTED_FOR_DELEGATION = 524288; + public const TRUSTED_FOR_DELEGATION = 524288; - const NOT_DELEGATED = 1048576; + public const NOT_DELEGATED = 1048576; - const USE_DES_KEY_ONLY = 2097152; + public const USE_DES_KEY_ONLY = 2097152; - const DONT_REQ_PREAUTH = 4194304; + public const DONT_REQ_PREAUTH = 4194304; - const PASSWORD_EXPIRED = 8388608; + public const PASSWORD_EXPIRED = 8388608; - const TRUSTED_TO_AUTH_FOR_DELEGATION = 16777216; + public const TRUSTED_TO_AUTH_FOR_DELEGATION = 16777216; - const PARTIAL_SECRETS_ACCOUNT = 67108864; + public const PARTIAL_SECRETS_ACCOUNT = 67108864; /** * The account control flag values. @@ -60,7 +60,7 @@ class AccountControl /** * Constructor. * - * @param ?int $flag + * @param ?int $flag */ public function __construct($flag = null) { @@ -92,8 +92,7 @@ class AccountControl /** * Add the flag to the account control values. * - * @param int $flag - * + * @param int $flag * @return $this */ public function add($flag) @@ -108,8 +107,7 @@ class AccountControl /** * Remove the flag from the account control. * - * @param int $flag - * + * @param int $flag * @return $this */ public function remove($flag) @@ -122,8 +120,7 @@ class AccountControl /** * Extract and apply the flag. * - * @param int $flag - * + * @param int $flag * @return void */ public function apply($flag) @@ -134,8 +131,7 @@ class AccountControl /** * Determine if the account control contains the given UAC flag(s). * - * @param int $flag - * + * @param int $flag * @return bool */ public function has($flag) @@ -154,8 +150,7 @@ class AccountControl /** * Determine if the account control does not contain the given UAC flag(s). * - * @param int $flag - * + * @param int $flag * @return bool */ public function doesntHave($flag) @@ -441,8 +436,7 @@ class AccountControl /** * Set the account control values. * - * @param array $flags - * + * @param array $flags * @return void */ public function setValues(array $flags) @@ -483,8 +477,7 @@ class AccountControl /** * Extracts the given flag into an array of flags used. * - * @param int $flag - * + * @param int $flag * @return array */ public function extractFlags($flag) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/DistinguishedName.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/DistinguishedName.php index c6977a8e8..fc981299a 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/DistinguishedName.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/DistinguishedName.php @@ -19,7 +19,7 @@ class DistinguishedName /** * Constructor. * - * @param string|null $value + * @param string|null $value */ public function __construct($value = null) { @@ -39,8 +39,7 @@ class DistinguishedName /** * Alias of the "build" method. * - * @param string|null $value - * + * @param string|null $value * @return DistinguishedNameBuilder */ public static function of($value = null) @@ -51,8 +50,7 @@ class DistinguishedName /** * Get a new DN builder object from the given DN. * - * @param string|null $value - * + * @param string|null $value * @return DistinguishedNameBuilder */ public static function build($value = null) @@ -63,8 +61,7 @@ class DistinguishedName /** * Make a new distinguished name instance. * - * @param string|null $value - * + * @param string|null $value * @return static */ public static function make($value = null) @@ -75,8 +72,7 @@ class DistinguishedName /** * Determine if the given value is a valid distinguished name. * - * @param string $value - * + * @param string $value * @return bool */ public static function isValid($value) @@ -87,8 +83,7 @@ class DistinguishedName /** * Explode a distinguished name into relative distinguished names. * - * @param string $dn - * + * @param string $dn * @return array */ public static function explode($dn) @@ -111,8 +106,7 @@ class DistinguishedName /** * Un-escapes a hexadecimal string into its original string representation. * - * @param string $value - * + * @param string $value * @return string */ public static function unescape($value) @@ -125,8 +119,7 @@ class DistinguishedName /** * Explode the RDN into an attribute and value. * - * @param string $rdn - * + * @param string $rdn * @return array */ public static function explodeRdn($rdn) @@ -137,8 +130,7 @@ class DistinguishedName /** * Implode the component attribute and value into an RDN. * - * @param string $rdn - * + * @param string $rdn * @return string */ public static function makeRdn(array $component) @@ -159,8 +151,7 @@ class DistinguishedName /** * Set the underlying value. * - * @param string|null $value - * + * @param string|null $value * @return $this */ public function set($value) @@ -337,8 +328,7 @@ class DistinguishedName /** * Determine if the current distinguished name is a parent of the given child. * - * @param DistinguishedName $child - * + * @param DistinguishedName $child * @return bool */ public function isParentOf(self $child) @@ -349,8 +339,7 @@ class DistinguishedName /** * Determine if the current distinguished name is a child of the given parent. * - * @param DistinguishedName $parent - * + * @param DistinguishedName $parent * @return bool */ public function isChildOf(self $parent) @@ -370,8 +359,7 @@ class DistinguishedName /** * Determine if the current distinguished name is an ancestor of the descendant. * - * @param DistinguishedName $descendant - * + * @param DistinguishedName $descendant * @return bool */ public function isAncestorOf(self $descendant) @@ -382,8 +370,7 @@ class DistinguishedName /** * Determine if the current distinguished name is a descendant of the ancestor. * - * @param DistinguishedName $ancestor - * + * @param DistinguishedName $ancestor * @return bool */ public function isDescendantOf(self $ancestor) @@ -407,9 +394,8 @@ class DistinguishedName /** * Compare whether the two distinguished name values are equal. * - * @param array $values - * @param array $other - * + * @param array $values + * @param array $other * @return bool */ protected function compare(array $values, array $other) @@ -420,8 +406,7 @@ class DistinguishedName /** * Recase the array values. * - * @param array $values - * + * @param array $values * @return array */ protected function recase(array $values) @@ -432,8 +417,7 @@ class DistinguishedName /** * Normalize the string value. * - * @param string $value - * + * @param string $value * @return string */ protected function normalize($value) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/DistinguishedNameBuilder.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/DistinguishedNameBuilder.php index 601902bf7..a0d84d828 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/DistinguishedNameBuilder.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/DistinguishedNameBuilder.php @@ -26,7 +26,7 @@ class DistinguishedNameBuilder /** * Constructor. * - * @param string|null $value + * @param string|null $value */ public function __construct($dn = null) { @@ -38,9 +38,8 @@ class DistinguishedNameBuilder /** * Forward missing method calls onto the Distinguished Name object. * - * @param string $method - * @param array $args - * + * @param string $method + * @param array $args * @return mixed */ public function __call($method, $args) @@ -61,9 +60,8 @@ class DistinguishedNameBuilder /** * Prepend an RDN onto the DN. * - * @param string|array $attribute - * @param string|null $value - * + * @param string|array $attribute + * @param string|null $value * @return $this */ public function prepend($attribute, $value = null) @@ -79,9 +77,8 @@ class DistinguishedNameBuilder /** * Append an RDN onto the DN. * - * @param string|array $attribute - * @param string|null $value - * + * @param string|array $attribute + * @param string|null $value * @return $this */ public function append($attribute, $value = null) @@ -97,9 +94,8 @@ class DistinguishedNameBuilder /** * Componentize the attribute and value. * - * @param string|array $attribute - * @param string|null $value - * + * @param string|array $attribute + * @param string|null $value * @return array */ protected function componentize($attribute, $value = null) @@ -125,8 +121,7 @@ class DistinguishedNameBuilder /** * Make a componentized array by exploding the value if it's a string. * - * @param string $value - * + * @param string $value * @return array */ protected function makeComponentizedArray($value) @@ -137,9 +132,8 @@ class DistinguishedNameBuilder /** * Make an appendable component array from the attribute and value. * - * @param string|array $attribute - * @param string|null $value - * + * @param string|array $attribute + * @param string|null $value * @return array */ protected function makeAppendableComponent($attribute, $value = null) @@ -150,9 +144,8 @@ class DistinguishedNameBuilder /** * Pop an RDN off of the end of the DN. * - * @param int $amount - * @param array $removed - * + * @param int $amount + * @param array $removed * @return $this */ public function pop($amount = 1, &$removed = []) @@ -167,9 +160,8 @@ class DistinguishedNameBuilder /** * Shift an RDN off of the beginning of the DN. * - * @param int $amount - * @param array $removed - * + * @param int $amount + * @param array $removed * @return $this */ public function shift($amount = 1, &$removed = []) @@ -196,8 +188,7 @@ class DistinguishedNameBuilder /** * Get the components of the DN. * - * @param null|string $type - * + * @param null|string $type * @return array */ public function components($type = null) @@ -210,8 +201,7 @@ class DistinguishedNameBuilder /** * Get the components of a particular type. * - * @param string $type - * + * @param string $type * @return array */ protected function componentsOfType($type) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/EscapedValue.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/EscapedValue.php index 2f6111297..3c9d4db0a 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/EscapedValue.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/EscapedValue.php @@ -28,9 +28,9 @@ class EscapedValue /** * Constructor. * - * @param string $value - * @param string $ignore - * @param int $flags + * @param string $value + * @param string $ignore + * @param int $flags */ public function __construct($value, $ignore = '', $flags = 0) { @@ -72,8 +72,7 @@ class EscapedValue /** * Set the characters to exclude from being escaped. * - * @param string $characters - * + * @param string $characters * @return $this */ public function ignore($characters) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/Guid.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/Guid.php index d139f5f86..e04b5cd3f 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/Guid.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/Guid.php @@ -50,8 +50,7 @@ class Guid /** * Determines if the specified GUID is valid. * - * @param string $guid - * + * @param string $guid * @return bool */ public static function isValid($guid) @@ -62,7 +61,7 @@ class Guid /** * Constructor. * - * @param mixed $value + * @param mixed $value * * @throws InvalidArgumentException */ @@ -128,8 +127,7 @@ class Guid /** * Returns the string variant of a binary GUID. * - * @param string $binary - * + * @param string $binary * @return string|null */ protected function binaryGuidToString($binary) @@ -144,10 +142,9 @@ class Guid * * @see https://github.com/ldaptools/ldaptools * - * @param string $hex The full hex string. - * @param array $sections An array of start and length (unless octet is true, then length is always 2). - * @param bool $octet Whether this is for octet string form. - * + * @param string $hex The full hex string. + * @param array $sections An array of start and length (unless octet is true, then length is always 2). + * @param bool $octet Whether this is for octet string form. * @return string The concatenated sections in upper-case. */ protected function parseSection($hex, array $sections, $octet = false) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/MbString.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/MbString.php index 672e60df1..72d4c6f48 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/MbString.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/MbString.php @@ -7,8 +7,7 @@ class MbString /** * Get the integer value of a specific character. * - * @param $string - * + * @param $string * @return int */ public static function ord($string) @@ -27,8 +26,7 @@ class MbString /** * Get the character for a specific integer value. * - * @param $int - * + * @param $int * @return string */ public static function chr($int) @@ -43,8 +41,7 @@ class MbString /** * Split a string into its individual characters and return it as an array. * - * @param string $value - * + * @param string $value * @return string[] */ public static function split($value) @@ -55,8 +52,7 @@ class MbString /** * Detects if the given string is UTF 8. * - * @param $string - * + * @param $string * @return string|false */ public static function isUtf8($string) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/Password.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/Password.php index 644f0a8d3..d7047a375 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/Password.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/Password.php @@ -8,15 +8,14 @@ use ReflectionMethod; class Password { - const CRYPT_SALT_TYPE_MD5 = 1; - const CRYPT_SALT_TYPE_SHA256 = 5; - const CRYPT_SALT_TYPE_SHA512 = 6; + public const CRYPT_SALT_TYPE_MD5 = 1; + public const CRYPT_SALT_TYPE_SHA256 = 5; + public const CRYPT_SALT_TYPE_SHA512 = 6; /** * Make an encoded password for transmission over LDAP. * - * @param string $password - * + * @param string $password * @return string */ public static function encode($password) @@ -27,9 +26,8 @@ class Password /** * Make a salted md5 password. * - * @param string $password - * @param null|string $salt - * + * @param string $password + * @param null|string $salt * @return string */ public static function smd5($password, $salt = null) @@ -40,9 +38,8 @@ class Password /** * Make a salted SHA password. * - * @param string $password - * @param null|string $salt - * + * @param string $password + * @param null|string $salt * @return string */ public static function ssha($password, $salt = null) @@ -53,9 +50,8 @@ class Password /** * Make a salted SSHA256 password. * - * @param string $password - * @param null|string $salt - * + * @param string $password + * @param null|string $salt * @return string */ public static function ssha256($password, $salt = null) @@ -66,9 +62,8 @@ class Password /** * Make a salted SSHA384 password. * - * @param string $password - * @param null|string $salt - * + * @param string $password + * @param null|string $salt * @return string */ public static function ssha384($password, $salt = null) @@ -79,9 +74,8 @@ class Password /** * Make a salted SSHA512 password. * - * @param string $password - * @param null|string $salt - * + * @param string $password + * @param null|string $salt * @return string */ public static function ssha512($password, $salt = null) @@ -92,8 +86,7 @@ class Password /** * Make a non-salted SHA password. * - * @param string $password - * + * @param string $password * @return string */ public static function sha($password) @@ -104,8 +97,7 @@ class Password /** * Make a non-salted SHA256 password. * - * @param string $password - * + * @param string $password * @return string */ public static function sha256($password) @@ -116,8 +108,7 @@ class Password /** * Make a non-salted SHA384 password. * - * @param string $password - * + * @param string $password * @return string */ public static function sha384($password) @@ -128,8 +119,7 @@ class Password /** * Make a non-salted SHA512 password. * - * @param string $password - * + * @param string $password * @return string */ public static function sha512($password) @@ -140,8 +130,7 @@ class Password /** * Make a non-salted md5 password. * - * @param string $password - * + * @param string $password * @return string */ public static function md5($password) @@ -149,12 +138,22 @@ class Password return '{MD5}'.static::makeHash($password, 'md5'); } + /** + * Make a non-salted NThash password. + * + * @param string $password + * @return string + */ + public static function nthash($password) + { + return '{NTHASH}'.strtoupper(hash('md4', iconv('UTF-8', 'UTF-16LE', $password))); + } + /** * Crypt password with an MD5 salt. * - * @param string $password - * @param string $salt - * + * @param string $password + * @param string $salt * @return string */ public static function md5Crypt($password, $salt = null) @@ -165,9 +164,8 @@ class Password /** * Crypt password with a SHA256 salt. * - * @param string $password - * @param string $salt - * + * @param string $password + * @param string $salt * @return string */ public static function sha256Crypt($password, $salt = null) @@ -178,9 +176,8 @@ class Password /** * Crypt a password with a SHA512 salt. * - * @param string $password - * @param string $salt - * + * @param string $password + * @param string $salt * @return string */ public static function sha512Crypt($password, $salt = null) @@ -191,11 +188,10 @@ class Password /** * Make a new password hash. * - * @param string $password The password to make a hash of. - * @param string $method The hash function to use. - * @param string|null $algo The algorithm to use for hashing. - * @param string|null $salt The salt to append onto the hash. - * + * @param string $password The password to make a hash of. + * @param string $method The hash function to use. + * @param string|null $algo The algorithm to use for hashing. + * @param string|null $salt The salt to append onto the hash. * @return string */ protected static function makeHash($password, $method, $algo = null, $salt = null) @@ -208,10 +204,9 @@ class Password /** * Make a hashed password. * - * @param string $password - * @param int $type - * @param null|string $salt - * + * @param string $password + * @param int $type + * @param null|string $salt * @return string */ protected static function makeCrypt($password, $type, $salt = null) @@ -222,8 +217,7 @@ class Password /** * Make a salt for the crypt() method using the given type. * - * @param int $type - * + * @param int $type * @return string */ protected static function makeCryptSalt($type) @@ -242,8 +236,7 @@ class Password /** * Determine the crypt prefix and length. * - * @param int $type - * + * @param int $type * @return array * * @throws InvalidArgumentException @@ -265,8 +258,7 @@ class Password /** * Attempt to retrieve the hash method used for the password. * - * @param string $password - * + * @param string $password * @return string|void */ public static function getHashMethod($password) @@ -281,8 +273,7 @@ class Password /** * Attempt to retrieve the hash method and algorithm used for the password. * - * @param string $password - * + * @param string $password * @return array|void */ public static function getHashMethodAndAlgo($password) @@ -319,8 +310,7 @@ class Password /** * Determine if the hash method requires a salt to be given. * - * @param string $method - * + * @param string $method * @return bool * * @throws \ReflectionException diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/Sid.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/Sid.php index 4ec46ea71..7760453ce 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/Sid.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/Sid.php @@ -17,8 +17,7 @@ class Sid /** * Determines if the specified SID is valid. * - * @param string $sid - * + * @param string $sid * @return bool */ public static function isValid($sid) @@ -29,7 +28,7 @@ class Sid /** * Constructor. * - * @param mixed $value + * @param mixed $value * * @throws InvalidArgumentException */ @@ -90,8 +89,7 @@ class Sid /** * Returns the string variant of a binary SID. * - * @param string $binary - * + * @param string $binary * @return string|null */ protected function binarySidToString($binary) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/TSProperty.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/TSProperty.php index ad56aa130..499579f82 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/TSProperty.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/TSProperty.php @@ -7,7 +7,7 @@ class TSProperty /** * Nibble control values. The first value for each is if the nibble is <= 9, otherwise the second value is used. */ - const NIBBLE_CONTROL = [ + public const NIBBLE_CONTROL = [ 'X' => ['001011', '011010'], 'Y' => ['001110', '011010'], ]; @@ -15,12 +15,12 @@ class TSProperty /** * The nibble header. */ - const NIBBLE_HEADER = '1110'; + public const NIBBLE_HEADER = '1110'; /** * Conversion factor needed for time values in the TSPropertyArray (stored in microseconds). */ - const TIME_CONVERSION = 60 * 1000; + public const TIME_CONVERSION = 60 * 1000; /** * A simple map to help determine how the property needs to be decoded/encoded from/to its binary value. @@ -85,7 +85,7 @@ class TSProperty /** * Pass binary TSProperty data to construct its object representation. * - * @param string|null $value + * @param string|null $value */ public function __construct($value = null) { @@ -97,8 +97,7 @@ class TSProperty /** * Set the name for the TSProperty. * - * @param string $name - * + * @param string $name * @return TSProperty */ public function setName($name) @@ -121,8 +120,7 @@ class TSProperty /** * Set the value for the TSProperty. * - * @param string|int $value - * + * @param string|int $value * @return TSProperty */ public function setValue($value) @@ -169,7 +167,7 @@ class TSProperty /** * Given a TSProperty blob, decode the name/value/type/etc. * - * @param string $tsProperty + * @param string $tsProperty */ protected function decode($tsProperty) { @@ -186,9 +184,8 @@ class TSProperty /** * Based on the property name/value in question, get its encoded form. * - * @param string $propName - * @param string|int $propValue - * + * @param string $propName + * @param string|int $propValue * @return string */ protected function getEncodedValueForProp($propName, $propValue) @@ -210,9 +207,8 @@ class TSProperty /** * Based on the property name in question, get its actual value from the binary blob value. * - * @param string $propName - * @param string $propValue - * + * @param string $propName + * @param string $propValue * @return string|int */ protected function getDecodedValueForProp($propName, $propValue) @@ -238,9 +234,8 @@ class TSProperty * Decode the property by inspecting the nibbles of each blob, checking * the control, and adding up the results into a final value. * - * @param string $hex - * @param bool $string Whether or not this is simple string data. - * + * @param string $hex + * @param bool $string Whether or not this is simple string data. * @return string */ protected function decodePropValue($hex, $string = false) @@ -272,9 +267,8 @@ class TSProperty /** * Get the encoded property value as a binary blob. * - * @param string $value - * @param bool $string - * + * @param string $value + * @param bool $string * @return string */ protected function encodePropValue($value, $string = false) @@ -314,9 +308,8 @@ class TSProperty * a workaround that turns a literal bit-string into a * packed byte-string with 8 bits per byte. * - * @param string $bits - * @param bool $len - * + * @param string $bits + * @param bool $len * @return string */ protected function packBitString($bits, $len) @@ -337,9 +330,8 @@ class TSProperty /** * Based on the control, adjust the nibble accordingly. * - * @param string $nibble - * @param string $control - * + * @param string $nibble + * @param string $control * @return string */ protected function nibbleControl($nibble, $control) @@ -362,9 +354,8 @@ class TSProperty * the control for X or Y equals 011010. Additionally, if the dec value of the nibble is > 9, then the nibble value * must be subtracted by 9 before the final value is constructed. * - * @param string $nibbleType Either X or Y - * @param string $nibble - * + * @param string $nibbleType Either X or Y + * @param string $nibble * @return string */ protected function getNibbleWithControl($nibbleType, $nibble) @@ -384,9 +375,8 @@ class TSProperty /** * Need to make sure hex values are always an even length, so pad as needed. * - * @param int $int - * @param int $padLength The hex string must be padded to this length (with zeros). - * + * @param int $int + * @param int $padLength The hex string must be padded to this length (with zeros). * @return string */ protected function dec2hex($int, $padLength = 2) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/TSPropertyArray.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/TSPropertyArray.php index 18316888f..8320dd8ed 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/TSPropertyArray.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/TSPropertyArray.php @@ -9,14 +9,14 @@ class TSPropertyArray /** * Represents that the TSPropertyArray data is valid. */ - const VALID_SIGNATURE = 'P'; + public const VALID_SIGNATURE = 'P'; /** * The default values for the TSPropertyArray structure. * * @var array */ - const DEFAULTS = [ + public const DEFAULTS = [ 'CtxCfgPresent' => 2953518677, 'CtxWFProfilePath' => '', 'CtxWFProfilePathW' => '', @@ -71,7 +71,7 @@ class TSPropertyArray * - Pass the userParameters binary value. The object representation of that will be decoded and constructed. * - Pass nothing and a default set of TSProperty key => value pairs will be used (See DEFAULTS constant). * - * @param mixed $tsPropertyArray + * @param mixed $tsPropertyArray */ public function __construct($tsPropertyArray = null) { @@ -93,8 +93,7 @@ class TSPropertyArray /** * Check if a specific TSProperty exists by its property name. * - * @param string $propName - * + * @param string $propName * @return bool */ public function has($propName) @@ -105,8 +104,7 @@ class TSPropertyArray /** * Get a TSProperty object by its property name (ie. CtxWFProfilePath). * - * @param string $propName - * + * @param string $propName * @return TSProperty */ public function get($propName) @@ -119,8 +117,7 @@ class TSPropertyArray /** * Add a TSProperty object. If it already exists, it will be overwritten. * - * @param TSProperty $tsProperty - * + * @param TSProperty $tsProperty * @return $this */ public function add(TSProperty $tsProperty) @@ -133,8 +130,7 @@ class TSPropertyArray /** * Remove a TSProperty by its property name (ie. CtxMinEncryptionLevel). * - * @param string $propName - * + * @param string $propName * @return $this */ public function remove($propName) @@ -151,9 +147,8 @@ class TSPropertyArray /** * Set the value for a specific TSProperty by its name. * - * @param string $propName - * @param mixed $propValue - * + * @param string $propName + * @param mixed $propValue * @return $this */ public function set($propName, $propValue) @@ -214,7 +209,7 @@ class TSPropertyArray /** * Validates that the given property name exists. * - * @param string $propName + * @param string $propName */ protected function validateProp($propName) { @@ -224,8 +219,7 @@ class TSPropertyArray } /** - * @param string $propName - * + * @param string $propName * @return TSProperty */ protected function getTsPropObj($propName) @@ -236,8 +230,7 @@ class TSPropertyArray /** * Get an associative array with all of the userParameters property names and values. * - * @param string $userParameters - * + * @param string $userParameters * @return void */ protected function decodeUserParameters($userParameters) @@ -260,7 +253,7 @@ class TSPropertyArray // Reserved data length + (count and sig length == 4) + the added lengths of the TSPropertyArray // This saves anything after that variable TSPropertyArray data, so as to not squash anything stored there if (strlen($userParameters) > (96 + 4 + $length)) { - $this->postBinary = hex2bin(substr($userParameters, (96 + 4 + $length))); + $this->postBinary = hex2bin(substr($userParameters, 96 + 4 + $length)); } } @@ -270,9 +263,8 @@ class TSPropertyArray * individual TSProperty structures. Return the full length * of the TSPropertyArray data. * - * @param string $tsPropertyArray - * @param int $tsPropCount - * + * @param string $tsPropertyArray + * @param int $tsPropCount * @return int The length of the data in the TSPropertyArray */ protected function addTSPropData($tsPropertyArray, $tsPropCount) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/Timestamp.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/Timestamp.php index e5d9dc341..0f07bc5a0 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/Timestamp.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Attributes/Timestamp.php @@ -5,11 +5,14 @@ namespace LdapRecord\Models\Attributes; use Carbon\Carbon; use Carbon\CarbonInterface; use DateTime; +use DateTimeZone; use LdapRecord\LdapRecordException; use LdapRecord\Utilities; class Timestamp { + public const WINDOWS_INT_MAX = 9223372036854775807; + /** * The current timestamp type. * @@ -31,7 +34,7 @@ class Timestamp /** * Constructor. * - * @param string $type + * @param string $type * * @throws LdapRecordException */ @@ -43,7 +46,7 @@ class Timestamp /** * Set the type of timestamp to convert from / to. * - * @param string $type + * @param string $type * * @throws LdapRecordException */ @@ -59,8 +62,7 @@ class Timestamp /** * Converts the value to an LDAP date string. * - * @param mixed $value - * + * @param mixed $value * @return float|string * * @throws LdapRecordException @@ -107,21 +109,19 @@ class Timestamp /** * Determine if the value given is in Windows Integer (NTFS Filetime) format. * - * @param int|string $value - * + * @param int|string $value * @return bool */ protected function valueIsWindowsIntegerType($value) { - return is_numeric($value) && strlen((string) $value) === 18; + return is_numeric($value) && in_array(strlen((string) $value), [18, 19]); } /** * Converts the LDAP timestamp value to a Carbon instance. * - * @param mixed $value - * - * @return Carbon|false + * @param mixed $value + * @return Carbon|int|false * * @throws LdapRecordException */ @@ -153,14 +153,13 @@ class Timestamp /** * Converts standard LDAP timestamps to a date time object. * - * @param string $value - * + * @param string $value * @return DateTime|false */ protected function convertLdapTimeToDateTime($value) { return DateTime::createFromFormat( - strpos($value, 'Z') !== false ? 'YmdHis\Z' : 'YmdHisT', + str_contains((string) $value, 'Z') ? 'YmdHis\Z' : 'YmdHisT', $value ); } @@ -168,8 +167,7 @@ class Timestamp /** * Converts date objects to a standard LDAP timestamp. * - * @param DateTime $date - * + * @param DateTime $date * @return string */ protected function convertDateTimeToLdapTime(DateTime $date) @@ -182,23 +180,22 @@ class Timestamp /** * Converts standard windows timestamps to a date time object. * - * @param string $value - * + * @param string $value * @return DateTime|false */ protected function convertWindowsTimeToDateTime($value) { return DateTime::createFromFormat( - strpos($value, '0Z') !== false ? 'YmdHis.0\Z' : 'YmdHis.0T', - $value + str_contains((string) $value, '0Z') ? 'YmdHis.0\Z' : 'YmdHis.0T', + $value, + new DateTimeZone('UTC') ); } /** * Converts date objects to a windows timestamp. * - * @param DateTime $date - * + * @param DateTime $date * @return string */ protected function convertDateTimeToWindows(DateTime $date) @@ -211,20 +208,25 @@ class Timestamp /** * Converts standard windows integer dates to a date time object. * - * @param int $value - * - * @return DateTime|false + * @param int $value + * @return DateTime|int|false * * @throws \Exception */ protected function convertWindowsIntegerTimeToDateTime($value) { - // ActiveDirectory dates that contain integers may return - // "0" when they are not set. We will validate that here. - if (! $value) { + if (is_null($value) || $value === '') { return false; } + if ($value == 0) { + return (int) $value; + } + + if ($value == static::WINDOWS_INT_MAX) { + return (int) $value; + } + return (new DateTime())->setTimestamp( Utilities::convertWindowsTimeToUnixTime($value) ); @@ -233,8 +235,7 @@ class Timestamp /** * Converts date objects to a windows integer timestamp. * - * @param DateTime $date - * + * @param DateTime $date * @return float */ protected function convertDateTimeToWindowsInteger(DateTime $date) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/BatchModification.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/BatchModification.php index 37f0e876b..954c58fcf 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/BatchModification.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/BatchModification.php @@ -11,9 +11,9 @@ class BatchModification /** * The array keys to be used in batch modifications. */ - const KEY_ATTRIB = 'attrib'; - const KEY_MODTYPE = 'modtype'; - const KEY_VALUES = 'values'; + public const KEY_ATTRIB = 'attrib'; + public const KEY_MODTYPE = 'modtype'; + public const KEY_VALUES = 'values'; /** * The attribute of the modification. @@ -46,9 +46,9 @@ class BatchModification /** * Constructor. * - * @param string|null $attribute - * @param string|int|null $type - * @param array $values + * @param string|null $attribute + * @param string|int|null $type + * @param array $values */ public function __construct($attribute = null, $type = null, array $values = []) { @@ -60,8 +60,7 @@ class BatchModification /** * Set the original value of the attribute before modification. * - * @param array|string $original - * + * @param array|string $original * @return $this */ public function setOriginal($original = []) @@ -84,8 +83,7 @@ class BatchModification /** * Set the attribute of the modification. * - * @param string $attribute - * + * @param string $attribute * @return $this */ public function setAttribute($attribute) @@ -108,8 +106,7 @@ class BatchModification /** * Set the values of the modification. * - * @param array $values - * + * @param array $values * @return $this */ public function setValues(array $values = []) @@ -127,8 +124,7 @@ class BatchModification /** * Normalize all of the attribute values. * - * @param array|string $values - * + * @param array|string $values * @return array */ protected function normalizeAttributeValues($values = []) @@ -152,8 +148,7 @@ class BatchModification /** * Set the type of the modification. * - * @param int|null $type - * + * @param int|null $type * @return $this */ public function setType($type = null) @@ -207,7 +202,7 @@ class BatchModification case empty($this->original) && ! empty($this->values): return $this->setType(LDAP_MODIFY_BATCH_ADD); default: - return $this->determineBatchTypeFromOriginal(); + return $this->determineBatchTypeFromOriginal(); } } @@ -291,8 +286,7 @@ class BatchModification /** * Determines if the given modtype is valid. * - * @param int $type - * + * @param int $type * @return bool */ protected function isValidType($type) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Collection.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Collection.php index 850167b7e..11b4ca522 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Collection.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Collection.php @@ -9,11 +9,22 @@ use LdapRecord\Support\Arr; class Collection extends QueryCollection { + /** + * Get a collection of the model's distinguished names. + * + * @return static + */ + public function modelDns() + { + return $this->map(function (Model $model) { + return $model->getDn(); + }); + } + /** * Determine if the collection contains all of the given models, or any models. * - * @param mixed $models - * + * @param mixed $models * @return bool */ public function exists($models = null) @@ -47,10 +58,9 @@ class Collection extends QueryCollection /** * Determine if any of the given models are contained in the collection. * - * @param mixed $key - * @param mixed $operator - * @param mixed $value - * + * @param mixed $key + * @param mixed $operator + * @param mixed $value * @return bool */ public function contains($key, $operator = null, $value = null) @@ -78,8 +88,7 @@ class Collection extends QueryCollection /** * Get the provided models as an array. * - * @param mixed $models - * + * @param mixed $models * @return array */ protected function getArrayableModels($models = null) @@ -92,17 +101,16 @@ class Collection extends QueryCollection /** * Compare the related model with the given. * - * @param Model|string $model - * @param Model $related - * + * @param Model|string $model + * @param Model $related * @return bool */ protected function compareModelWithRelated($model, $related) { if (is_string($model)) { return $this->isValidDn($model) - ? $related->getDn() == $model - : $related->getName() == $model; + ? strcasecmp($related->getDn(), $model) === 0 + : strcasecmp($related->getName(), $model) === 0; } return $related->is($model); @@ -111,8 +119,7 @@ class Collection extends QueryCollection /** * Determine if the given string is a valid distinguished name. * - * @param string $dn - * + * @param string $dn * @return bool */ protected function isValidDn($dn) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/CanAuthenticate.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/CanAuthenticate.php index 451738abe..6e8d4fb5d 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/CanAuthenticate.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/CanAuthenticate.php @@ -2,6 +2,7 @@ namespace LdapRecord\Models\Concerns; +/** @mixin \LdapRecord\Models\Model */ trait CanAuthenticate { /** @@ -17,7 +18,7 @@ trait CanAuthenticate /** * Get the unique identifier for the user. * - * @return mixed + * @return string */ public function getAuthIdentifier() { @@ -47,8 +48,7 @@ trait CanAuthenticate /** * Set the token value for the "remember me" session. * - * @param string $value - * + * @param string $value * @return void */ public function setRememberToken($value) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/HasAttributes.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/HasAttributes.php index b5f333579..a3d9df7d9 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/HasAttributes.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/HasAttributes.php @@ -74,6 +74,18 @@ trait HasAttributes */ protected static $mutatorCache = []; + /** + * Convert the model's original attributes to an array. + * + * @return array + */ + public function originalToArray() + { + return $this->encodeAttributes( + $this->convertAttributesForJson($this->original) + ); + } + /** * Convert the model's attributes to an array. * @@ -111,11 +123,38 @@ trait HasAttributes return $this->encodeAttributes($attributes); } + /** + * Convert the model's serialized original attributes to their original form. + * + * @param array $attributes + * @return array + */ + public function arrayToOriginal(array $attributes) + { + return $this->decodeAttributes( + $this->convertAttributesFromJson($attributes) + ); + } + + /** + * Convert the model's serialized attributes to their original form. + * + * @param array $attributes + * @return array + */ + public function arrayToAttributes(array $attributes) + { + $attributes = $this->restoreDateAttributesFromArray($attributes); + + return $this->decodeAttributes( + $this->convertAttributesFromJson($attributes) + ); + } + /** * Add the date attributes to the attributes array. * - * @param array $attributes - * + * @param array $attributes * @return array */ protected function addDateAttributesToArray(array $attributes) @@ -135,11 +174,31 @@ trait HasAttributes return $attributes; } + /** + * Restore the date attributes to their true value from serialized attributes. + * + * @param array $attributes + * @return array + */ + protected function restoreDateAttributesFromArray(array $attributes) + { + foreach ($this->getDates() as $attribute => $type) { + if (! isset($attributes[$attribute])) { + continue; + } + + $date = $this->fromDateTime($type, $attributes[$attribute]); + + $attributes[$attribute] = Arr::wrap($date); + } + + return $attributes; + } + /** * Prepare a date for array / JSON serialization. * - * @param DateTimeInterface $date - * + * @param DateTimeInterface $date * @return string */ protected function serializeDate(DateTimeInterface $date) @@ -162,10 +221,24 @@ trait HasAttributes } /** - * Encode the given value for proper serialization. + * Recursively UTF-8 decode the given attributes. * - * @param string $value + * @param array $attributes + * @return array + */ + public function decodeAttributes($attributes) + { + array_walk_recursive($attributes, function (&$value) { + $value = $this->decodeValue($value); + }); + + return $attributes; + } + + /** + * Encode the value for serialization. * + * @param string $value * @return string */ protected function encodeValue($value) @@ -173,15 +246,33 @@ trait HasAttributes // If we are able to detect the encoding, we will // encode only the attributes that need to be, // so that we do not double encode values. - return MbString::isLoaded() && MbString::isUtf8($value) ? $value : utf8_encode($value); + if (MbString::isLoaded() && MbString::isUtf8($value)) { + return $value; + } + + return utf8_encode($value); + } + + /** + * Decode the value from serialization. + * + * @param string $value + * @return string + */ + protected function decodeValue($value) + { + if (MbString::isLoaded() && MbString::isUtf8($value)) { + return mb_convert_encoding($value, 'UTF-8', 'ISO-8859-1'); + } + + return $value; } /** * Add the mutated attributes to the attributes array. * - * @param array $attributes - * @param array $mutatedAttributes - * + * @param array $attributes + * @param array $mutatedAttributes * @return array */ protected function addMutatedAttributesToArray(array $attributes, array $mutatedAttributes) @@ -221,8 +312,7 @@ trait HasAttributes /** * Fills the entry with the supplied attributes. * - * @param array $attributes - * + * @param array $attributes * @return $this */ public function fill(array $attributes = []) @@ -237,9 +327,8 @@ trait HasAttributes /** * Returns the models attribute by its key. * - * @param int|string $key - * @param mixed $default - * + * @param int|string $key + * @param mixed $default * @return mixed */ public function getAttribute($key, $default = null) @@ -254,9 +343,8 @@ trait HasAttributes /** * Get an attributes value. * - * @param string $key - * @param mixed $default - * + * @param string $key + * @param mixed $default * @return mixed */ public function getAttributeValue($key, $default = null) @@ -282,8 +370,7 @@ trait HasAttributes /** * Determine if the given attribute is a date. * - * @param string $key - * + * @param string $key * @return bool */ public function isDateAttribute($key) @@ -310,9 +397,8 @@ trait HasAttributes /** * Convert the given date value to an LDAP compatible value. * - * @param string $type - * @param mixed $value - * + * @param string $type + * @param mixed $value * @return float|string * * @throws LdapRecordException @@ -325,9 +411,8 @@ trait HasAttributes /** * Convert the given LDAP date value to a Carbon instance. * - * @param mixed $value - * @param string $type - * + * @param mixed $value + * @param string $type * @return Carbon|false * * @throws LdapRecordException @@ -340,9 +425,8 @@ trait HasAttributes /** * Determine whether an attribute should be cast to a native type. * - * @param string $key - * @param array|string|null $types - * + * @param string $key + * @param array|string|null $types * @return bool */ public function hasCast($key, $types = null) @@ -367,8 +451,7 @@ trait HasAttributes /** * Determine whether a value is JSON castable for inbound manipulation. * - * @param string $key - * + * @param string $key * @return bool */ protected function isJsonCastable($key) @@ -379,8 +462,7 @@ trait HasAttributes /** * Get the type of cast for a model attribute. * - * @param string $key - * + * @param string $key * @return string */ protected function getCastType($key) @@ -399,8 +481,7 @@ trait HasAttributes /** * Determine if the cast is a decimal. * - * @param string $cast - * + * @param string $cast * @return bool */ protected function isDecimalCast($cast) @@ -411,8 +492,7 @@ trait HasAttributes /** * Determine if the cast is a datetime. * - * @param string $cast - * + * @param string $cast * @return bool */ protected function isDateTimeCast($cast) @@ -423,8 +503,7 @@ trait HasAttributes /** * Determine if the given attribute must be casted. * - * @param string $key - * + * @param string $key * @return bool */ protected function isCastedAttribute($key) @@ -435,9 +514,8 @@ trait HasAttributes /** * Cast an attribute to a native PHP type. * - * @param string $key - * @param array|null $value - * + * @param string $key + * @param array|null $value * @return mixed */ protected function castAttribute($key, $value) @@ -490,9 +568,8 @@ trait HasAttributes /** * Cast the given attribute to JSON. * - * @param string $key - * @param mixed $value - * + * @param string $key + * @param mixed $value * @return string */ protected function castAttributeAsJson($key, $value) @@ -522,8 +599,7 @@ trait HasAttributes /** * Encode the given value as JSON. * - * @param mixed $value - * + * @param mixed $value * @return string */ protected function asJson($value) @@ -534,9 +610,8 @@ trait HasAttributes /** * Decode the given JSON back into an array or object. * - * @param string $value - * @param bool $asObject - * + * @param string $value + * @param bool $asObject * @return mixed */ public function fromJson($value, $asObject = false) @@ -547,8 +622,7 @@ trait HasAttributes /** * Decode the given float. * - * @param mixed $value - * + * @param mixed $value * @return mixed */ public function fromFloat($value) @@ -568,8 +642,7 @@ trait HasAttributes /** * Cast the value to a boolean. * - * @param mixed $value - * + * @param mixed $value * @return bool */ protected function asBoolean($value) @@ -582,9 +655,8 @@ trait HasAttributes /** * Cast a decimal value as a string. * - * @param float $value - * @param int $decimals - * + * @param float $value + * @param int $decimals * @return string */ protected function asDecimal($value, $decimals) @@ -605,8 +677,7 @@ trait HasAttributes /** * Get an attribute array of all arrayable values. * - * @param array $values - * + * @param array $values * @return array */ protected function getArrayableItems(array $values) @@ -651,8 +722,7 @@ trait HasAttributes /** * Set the date format used by the model for serialization. * - * @param string $format - * + * @param string $format * @return $this */ public function setDateFormat($format) @@ -665,8 +735,7 @@ trait HasAttributes /** * Get an attribute from the $attributes array. * - * @param string $key - * + * @param string $key * @return mixed */ protected function getAttributeFromArray($key) @@ -687,9 +756,8 @@ trait HasAttributes /** * Returns the first attribute by the specified key. * - * @param string $key - * @param mixed $default - * + * @param string $key + * @param mixed $default * @return mixed */ public function getFirstAttribute($key, $default = null) @@ -712,9 +780,8 @@ trait HasAttributes /** * Set an attribute value by the specified key. * - * @param string $key - * @param mixed $value - * + * @param string $key + * @param mixed $value * @return $this */ public function setAttribute($key, $value) @@ -743,9 +810,8 @@ trait HasAttributes /** * Set an attribute on the model. No checking is done. * - * @param string $key - * @param mixed $value - * + * @param string $key + * @param mixed $value * @return $this */ public function setRawAttribute($key, $value) @@ -760,9 +826,8 @@ trait HasAttributes /** * Set the models first attribute value. * - * @param string $key - * @param mixed $value - * + * @param string $key + * @param mixed $value * @return $this */ public function setFirstAttribute($key, $value) @@ -773,9 +838,8 @@ trait HasAttributes /** * Add a unique value to the given attribute. * - * @param string $key - * @param mixed $value - * + * @param string $key + * @param mixed $value * @return $this */ public function addAttributeValue($key, $value) @@ -791,8 +855,7 @@ trait HasAttributes /** * Determine if a get mutator exists for an attribute. * - * @param string $key - * + * @param string $key * @return bool */ public function hasGetMutator($key) @@ -803,8 +866,7 @@ trait HasAttributes /** * Determine if a set mutator exists for an attribute. * - * @param string $key - * + * @param string $key * @return bool */ public function hasSetMutator($key) @@ -815,9 +877,8 @@ trait HasAttributes /** * Set the value of an attribute using its mutator. * - * @param string $key - * @param mixed $value - * + * @param string $key + * @param mixed $value * @return mixed */ protected function setMutatedAttributeValue($key, $value) @@ -828,9 +889,8 @@ trait HasAttributes /** * Get the value of an attribute using its mutator. * - * @param string $key - * @param mixed $value - * + * @param string $key + * @param mixed $value * @return mixed */ protected function getMutatedAttributeValue($key, $value) @@ -843,8 +903,7 @@ trait HasAttributes * * Hyphenated attributes will use pascal cased methods. * - * @param string $key - * + * @param string $key * @return mixed */ protected function getMutatorMethodName($key) @@ -857,9 +916,8 @@ trait HasAttributes /** * Get the value of an attribute using its mutator for array conversion. * - * @param string $key - * @param mixed $value - * + * @param string $key + * @param mixed $value * @return array */ protected function mutateAttributeForArray($key, $value) @@ -874,8 +932,7 @@ trait HasAttributes * * Used when constructing an existing LDAP record. * - * @param array $attributes - * + * @param array $attributes * @return $this */ public function setRawAttributes(array $attributes = []) @@ -915,9 +972,8 @@ trait HasAttributes /** * Filters the count key recursively from raw LDAP attributes. * - * @param array $attributes - * @param array $keys - * + * @param array $attributes + * @param array $keys * @return array */ public function filterRawAttributes(array $attributes = [], array $keys = ['count', 'dn']) @@ -938,8 +994,7 @@ trait HasAttributes /** * Determine if the model has the given attribute. * - * @param int|string $key - * + * @param int|string $key * @return bool */ public function hasAttribute($key) @@ -991,8 +1046,7 @@ trait HasAttributes /** * Determine if the given attribute is dirty. * - * @param string $key - * + * @param string $key * @return bool */ public function isDirty($key) @@ -1013,8 +1067,7 @@ trait HasAttributes /** * Set the accessors to append to model arrays. * - * @param array $appends - * + * @param array $appends * @return $this */ public function setAppends(array $appends) @@ -1027,8 +1080,7 @@ trait HasAttributes /** * Return whether the accessor attribute has been appended. * - * @param string $attribute - * + * @param string $attribute * @return bool */ public function hasAppended($attribute) @@ -1039,8 +1091,7 @@ trait HasAttributes /** * Returns a normalized attribute key. * - * @param string $key - * + * @param string $key * @return string */ public function normalizeAttributeKey($key) @@ -1056,8 +1107,7 @@ trait HasAttributes /** * Determine if the new and old values for a given key are equivalent. * - * @param string $key - * + * @param string $key * @return bool */ protected function originalIsEquivalent($key) @@ -1097,8 +1147,7 @@ trait HasAttributes /** * Extract and cache all the mutated attributes of a class. * - * @param string $class - * + * @param string $class * @return void */ public static function cacheMutatedAttributes($class) @@ -1113,8 +1162,7 @@ trait HasAttributes /** * Get all of the attribute mutator methods. * - * @param mixed $class - * + * @param mixed $class * @return array */ protected static function getMutatorMethods($class) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/HasEvents.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/HasEvents.php index 5adec96ea..d9a41b892 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/HasEvents.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/HasEvents.php @@ -4,15 +4,17 @@ namespace LdapRecord\Models\Concerns; use Closure; use LdapRecord\Events\NullDispatcher; +use LdapRecord\Models\Events; use LdapRecord\Models\Events\Event; +use LdapRecord\Support\Arr; +/** @mixin \LdapRecord\Models\Model */ trait HasEvents { /** * Execute the callback without raising any events. * - * @param Closure $callback - * + * @param Closure $callback * @return mixed */ protected static function withoutEvents(Closure $callback) @@ -37,10 +39,37 @@ trait HasEvents } /** - * Fires the specified model event. + * Dispatch the given model events. * - * @param Event $event + * @param string|array $events + * @param array $args + * @return void + */ + protected function dispatch($events, array $args = []) + { + foreach (Arr::wrap($events) as $name) { + $this->fireCustomModelEvent($name, $args); + } + } + + /** + * Fire a custom model event. * + * @param string $name + * @param array $args + * @return mixed + */ + protected function fireCustomModelEvent($name, array $args = []) + { + $event = implode('\\', [Events::class, ucfirst($name)]); + + return $this->fireModelEvent(new $event($this, ...$args)); + } + + /** + * Fire a model event. + * + * @param Event $event * @return mixed */ protected function fireModelEvent(Event $event) @@ -49,11 +78,10 @@ trait HasEvents } /** - * Listens to a model event. - * - * @param string $event - * @param Closure $listener + * Listen to a model event. * + * @param string $event + * @param Closure $listener * @return mixed */ protected function listenForModelEvent($event, Closure $listener) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/HasGlobalScopes.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/HasGlobalScopes.php index f7552c1b4..4d0f2968f 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/HasGlobalScopes.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/HasGlobalScopes.php @@ -6,14 +6,14 @@ use Closure; use InvalidArgumentException; use LdapRecord\Models\Scope; +/** @mixin \LdapRecord\Models\Model */ trait HasGlobalScopes { /** * Register a new global scope on the model. * - * @param Scope|Closure|string $scope - * @param Closure|null $implementation - * + * @param Scope|Closure|string $scope + * @param Closure|null $implementation * @return mixed * * @throws InvalidArgumentException @@ -34,8 +34,7 @@ trait HasGlobalScopes /** * Determine if a model has a global scope. * - * @param Scope|string $scope - * + * @param Scope|string $scope * @return bool */ public static function hasGlobalScope($scope) @@ -46,8 +45,7 @@ trait HasGlobalScopes /** * Get a global scope registered with the model. * - * @param Scope|string $scope - * + * @param Scope|string $scope * @return Scope|Closure|null */ public static function getGlobalScope($scope) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/HasPassword.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/HasPassword.php index 1a938c144..194efa8cf 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/HasPassword.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/HasPassword.php @@ -6,12 +6,13 @@ use LdapRecord\ConnectionException; use LdapRecord\LdapRecordException; use LdapRecord\Models\Attributes\Password; +/** @mixin \LdapRecord\Models\Model */ trait HasPassword { /** * Set the password on the user. * - * @param string|array $password + * @param string|array $password * * @throws ConnectionException */ @@ -48,7 +49,7 @@ trait HasPassword /** * Alias for setting the password on the user. * - * @param string|array $password + * @param string|array $password * * @throws ConnectionException */ @@ -106,10 +107,9 @@ trait HasPassword /** * Set the changed password. * - * @param string $oldPassword - * @param string $newPassword - * @param string $attribute - * + * @param string $oldPassword + * @param string $newPassword + * @param string $attribute * @return void */ protected function setChangedPassword($oldPassword, $newPassword, $attribute) @@ -136,9 +136,8 @@ trait HasPassword /** * Set the password on the model. * - * @param string $password - * @param string $attribute - * + * @param string $password + * @param string $attribute * @return void */ protected function setPassword($password, $attribute) @@ -155,10 +154,9 @@ trait HasPassword /** * Encode / hash the given password. * - * @param string $method - * @param string $password - * @param string $salt - * + * @param string $method + * @param string $password + * @param string $salt * @return string * * @throws LdapRecordException @@ -203,8 +201,7 @@ trait HasPassword /** * Attempt to retrieve the password's salt. * - * @param string $method - * + * @param string $method * @return string|null */ public function getPasswordSalt($method) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/HasRelationships.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/HasRelationships.php index a8a5cacf2..87c0a7cc8 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/HasRelationships.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/HasRelationships.php @@ -5,6 +5,7 @@ namespace LdapRecord\Models\Concerns; use LdapRecord\Models\Relations\HasMany; use LdapRecord\Models\Relations\HasManyIn; use LdapRecord\Models\Relations\HasOne; +use LdapRecord\Models\Relations\Relation; use LdapRecord\Support\Arr; trait HasRelationships @@ -12,10 +13,9 @@ trait HasRelationships /** * Returns a new has one relationship. * - * @param mixed $related - * @param string $relationKey - * @param string $foreignKey - * + * @param mixed $related + * @param string $relationKey + * @param string $foreignKey * @return HasOne */ public function hasOne($related, $relationKey, $foreignKey = 'dn') @@ -26,10 +26,9 @@ trait HasRelationships /** * Returns a new has many relationship. * - * @param mixed $related - * @param string $relationKey - * @param string $foreignKey - * + * @param mixed $related + * @param string $relationKey + * @param string $foreignKey * @return HasMany */ public function hasMany($related, $relationKey, $foreignKey = 'dn') @@ -40,10 +39,9 @@ trait HasRelationships /** * Returns a new has many in relationship. * - * @param mixed $related - * @param string $relationKey - * @param string $foreignKey - * + * @param mixed $related + * @param string $relationKey + * @param string $foreignKey * @return HasManyIn */ public function hasManyIn($related, $relationKey, $foreignKey = 'dn') @@ -51,6 +49,29 @@ trait HasRelationships return new HasManyIn($this->newQuery(), $this, $related, $relationKey, $foreignKey, $this->guessRelationshipName()); } + /** + * Get a relationship by its name. + * + * @param string $relationName + * @return Relation|null + */ + public function getRelation($relationName) + { + if (! method_exists($this, $relationName)) { + return; + } + + if (! $relation = $this->{$relationName}()) { + return; + } + + if (! $relation instanceof Relation) { + return; + } + + return $relation; + } + /** * Get the relationships name. * diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/HasScopes.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/HasScopes.php index 6c97cf925..cb227fecc 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/HasScopes.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/HasScopes.php @@ -2,6 +2,7 @@ namespace LdapRecord\Models\Concerns; +/** @mixin \LdapRecord\Models\Model */ trait HasScopes { /** diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/HidesAttributes.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/HidesAttributes.php index 9cc210057..ecd328dab 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/HidesAttributes.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/HidesAttributes.php @@ -6,6 +6,8 @@ namespace LdapRecord\Models\Concerns; * @author Taylor Otwell * * @see https://laravel.com + * + * @mixin \LdapRecord\Models\Model */ trait HidesAttributes { @@ -38,8 +40,7 @@ trait HidesAttributes /** * Set the hidden attributes for the model. * - * @param array $hidden - * + * @param array $hidden * @return $this */ public function setHidden(array $hidden) @@ -52,8 +53,7 @@ trait HidesAttributes /** * Add hidden attributes for the model. * - * @param array|string|null $attributes - * + * @param array|string|null $attributes * @return void */ public function addHidden($attributes = null) @@ -79,8 +79,7 @@ trait HidesAttributes /** * Set the visible attributes for the model. * - * @param array $visible - * + * @param array $visible * @return $this */ public function setVisible(array $visible) @@ -93,8 +92,7 @@ trait HidesAttributes /** * Add visible attributes for the model. * - * @param array|string|null $attributes - * + * @param array|string|null $attributes * @return void */ public function addVisible($attributes = null) @@ -108,8 +106,7 @@ trait HidesAttributes /** * Make the given, typically hidden, attributes visible. * - * @param array|string $attributes - * + * @param array|string $attributes * @return $this */ public function makeVisible($attributes) @@ -126,8 +123,7 @@ trait HidesAttributes /** * Make the given, typically visible, attributes hidden. * - * @param array|string $attributes - * + * @param array|string $attributes * @return $this */ public function makeHidden($attributes) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/SerializesAndRestoresPropertyValues.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/SerializesAndRestoresPropertyValues.php new file mode 100644 index 000000000..cf550c749 --- /dev/null +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/SerializesAndRestoresPropertyValues.php @@ -0,0 +1,47 @@ +originalToArray(); + } + + if ($property === 'attributes') { + return $this->attributesToArray(); + } + + return $value; + } + + /** + * Get the unserialized property value after deserialization. + * + * @param string $property + * @param mixed $value + * @return mixed + */ + protected function getUnserializedPropertyValue($property, $value) + { + if ($property === 'original') { + return $this->arrayToOriginal($value); + } + + if ($property === 'attributes') { + return $this->arrayToAttributes($value); + } + + return $value; + } +} diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/SerializesProperties.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/SerializesProperties.php new file mode 100644 index 000000000..91f4bcfe3 --- /dev/null +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Concerns/SerializesProperties.php @@ -0,0 +1,143 @@ +getProperties(); + + foreach ($properties as $property) { + $property->setValue($this, $this->getSerializedPropertyValue( + $property->getName(), + $this->getPropertyValue($property) + )); + } + + return array_values(array_filter(array_map(function ($p) { + return $p->isStatic() ? null : $p->getName(); + }, $properties))); + } + + /** + * Restore the attributes after serialization. + * + * @return void + */ + public function __wakeup() + { + foreach ((new ReflectionClass($this))->getProperties() as $property) { + if ($property->isStatic()) { + continue; + } + + $property->setValue($this, $this->getUnserializedPropertyValue( + $property->getName(), + $this->getPropertyValue($property) + )); + } + } + + /** + * Prepare the model for serialization. + * + * @return array + */ + public function __serialize() + { + $values = []; + + $properties = (new ReflectionClass($this))->getProperties(); + + $class = get_class($this); + + foreach ($properties as $property) { + if ($property->isStatic()) { + continue; + } + + $property->setAccessible(true); + + if (! $property->isInitialized($this)) { + continue; + } + + $name = $property->getName(); + + if ($property->isPrivate()) { + $name = "\0{$class}\0{$name}"; + } elseif ($property->isProtected()) { + $name = "\0*\0{$name}"; + } + + $values[$name] = $this->getSerializedPropertyValue( + $property->getName(), + $this->getPropertyValue($property) + ); + } + + return $values; + } + + /** + * Restore the model after serialization. + * + * @param array $values + * @return void + */ + public function __unserialize(array $values) + { + $properties = (new ReflectionClass($this))->getProperties(); + + $class = get_class($this); + + foreach ($properties as $property) { + if ($property->isStatic()) { + continue; + } + + $name = $property->getName(); + + if ($property->isPrivate()) { + $name = "\0{$class}\0{$name}"; + } elseif ($property->isProtected()) { + $name = "\0*\0{$name}"; + } + + if (! array_key_exists($name, $values)) { + continue; + } + + $property->setAccessible(true); + + $property->setValue( + $this, + $this->getUnserializedPropertyValue($property->getName(), $values[$name]) + ); + } + } + + /** + * Get the property value for the given property. + * + * @param ReflectionProperty $property + * @return mixed + */ + protected function getPropertyValue(ReflectionProperty $property) + { + $property->setAccessible(true); + + return $property->getValue($this); + } +} diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/DetectsResetIntegers.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/DetectsResetIntegers.php index 8712ef755..7b8d1830e 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/DetectsResetIntegers.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/DetectsResetIntegers.php @@ -11,8 +11,7 @@ trait DetectsResetIntegers * LDAP attributes to instruct the server to reset the * value to an 'unset' or 'cleared' state. * - * @param mixed $value - * + * @param mixed $value * @return bool */ protected function valueIsResetInteger($value) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/DirectoryServer/Entry.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/DirectoryServer/Entry.php index 1bf832587..a67200e94 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/DirectoryServer/Entry.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/DirectoryServer/Entry.php @@ -3,8 +3,9 @@ namespace LdapRecord\Models\DirectoryServer; use LdapRecord\Models\Model; +use LdapRecord\Models\Types\DirectoryServer; -class Entry extends Model +class Entry extends Model implements DirectoryServer { /** * The attribute key that contains the models object GUID. diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Events/Event.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Events/Event.php index 20de0b7a6..8dbd1d29a 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Events/Event.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Events/Event.php @@ -16,7 +16,7 @@ abstract class Event /** * Constructor. * - * @param Model $model + * @param Model $model */ public function __construct(Model $model) { diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Events/Renaming.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Events/Renaming.php index 83427ca1a..5e7be97d7 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Events/Renaming.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Events/Renaming.php @@ -23,9 +23,9 @@ class Renaming extends Event /** * Constructor. * - * @param Model $model - * @param string $rdn - * @param string $newParentDn + * @param Model $model + * @param string $rdn + * @param string $newParentDn */ public function __construct(Model $model, $rdn, $newParentDn) { diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/FreeIPA/Entry.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/FreeIPA/Entry.php index 7fdda9c86..be6322b15 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/FreeIPA/Entry.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/FreeIPA/Entry.php @@ -44,8 +44,7 @@ class Entry extends BaseEntry implements FreeIPA /** * Create a new query builder. * - * @param Connection $connection - * + * @param Connection $connection * @return FreeIpaBuilder */ public function newQueryBuilder(Connection $connection) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/FreeIPA/Scopes/AddEntryUuidToSelects.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/FreeIPA/Scopes/AddEntryUuidToSelects.php index 039c05e4f..581b5beed 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/FreeIPA/Scopes/AddEntryUuidToSelects.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/FreeIPA/Scopes/AddEntryUuidToSelects.php @@ -11,9 +11,8 @@ class AddEntryUuidToSelects implements Scope /** * Add the entry UUID to the selected attributes. * - * @param Builder $query - * @param Model $model - * + * @param Builder $query + * @param Model $model * @return void */ public function apply(Builder $query, Model $model) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Model.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Model.php index 2e11696b4..932c1a3b1 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Model.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Model.php @@ -11,8 +11,6 @@ use LdapRecord\Container; use LdapRecord\EscapesValues; use LdapRecord\Models\Attributes\DistinguishedName; use LdapRecord\Models\Attributes\Guid; -use LdapRecord\Models\Events\Renamed; -use LdapRecord\Models\Events\Renaming; use LdapRecord\Query\Model\Builder; use LdapRecord\Support\Arr; use UnexpectedValueException; @@ -27,6 +25,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable use Concerns\HasGlobalScopes; use Concerns\HidesAttributes; use Concerns\HasRelationships; + use Concerns\SerializesProperties; /** * Indicates if the model exists in the directory. @@ -115,7 +114,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Constructor. * - * @param array $attributes + * @param array $attributes */ public function __construct(array $attributes = []) { @@ -163,9 +162,8 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Handle dynamic method calls into the model. * - * @param string $method - * @param array $parameters - * + * @param string $method + * @param array $parameters * @return mixed */ public function __call($method, $parameters) @@ -180,9 +178,8 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Handle dynamic static method calls into the method. * - * @param string $method - * @param array $parameters - * + * @param string $method + * @param array $parameters * @return mixed */ public static function __callStatic($method, $parameters) @@ -203,8 +200,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Set the models distinguished name. * - * @param string $dn - * + * @param string $dn * @return $this */ public function setDn($dn) @@ -217,8 +213,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * A mutator for setting the models distinguished name. * - * @param string $dn - * + * @param string $dn * @return $this */ public function setDnAttribute($dn) @@ -229,8 +224,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * A mutator for setting the models distinguished name. * - * @param string $dn - * + * @param string $dn * @return $this */ public function setDistinguishedNameAttribute($dn) @@ -261,8 +255,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Set the connection associated with the model. * - * @param string $name - * + * @param string $name * @return $this */ public function setConnection($name) @@ -272,11 +265,21 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable return $this; } + /** + * Make a new model instance. + * + * @param array $attributes + * @return static + */ + public static function make($attributes = []) + { + return new static($attributes); + } + /** * Begin querying the model on a given connection. * - * @param string|null $connection - * + * @param string|null $connection * @return Builder */ public static function on($connection = null) @@ -291,8 +294,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Get all the models from the directory. * - * @param array|mixed $attributes - * + * @param array|mixed $attributes * @return Collection|static[] */ public static function all($attributes = ['*']) @@ -301,15 +303,45 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable } /** - * Make a new model instance. + * Get the RootDSE (AD schema) record from the directory. * - * @param array $attributes + * @param string|null $connection + * @return Model * - * @return static + * @throws \LdapRecord\Models\ModelNotFoundException */ - public static function make($attributes = []) + public static function getRootDse($connection = null) { - return new static($attributes); + $model = static::getRootDseModel(); + + return $model::on($connection ?? (new $model)->getConnectionName()) + ->in(null) + ->read() + ->whereHas('objectclass') + ->firstOrFail(); + } + + /** + * Get the root DSE model. + * + * @return class-string + */ + protected static function getRootDseModel() + { + $instance = (new static); + + switch (true) { + case $instance instanceof Types\ActiveDirectory: + return ActiveDirectory\Entry::class; + case $instance instanceof Types\DirectoryServer: + return OpenLDAP\Entry::class; + case $instance instanceof Types\OpenLDAP: + return OpenLDAP\Entry::class; + case $instance instanceof Types\FreeIPA: + return FreeIPA\Entry::class; + default: + return Entry::class; + } } /** @@ -349,8 +381,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Create a new query builder. * - * @param Connection $connection - * + * @param Connection $connection * @return Builder */ public function newQueryBuilder(Connection $connection) @@ -361,8 +392,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Create a new model instance. * - * @param array $attributes - * + * @param array $attributes * @return static */ public function newInstance(array $attributes = []) @@ -373,8 +403,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Resolve a connection instance. * - * @param string|null $connection - * + * @param string|null $connection * @return Connection */ public static function resolveConnection($connection = null) @@ -405,8 +434,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Set the connection container. * - * @param Container $container - * + * @param Container $container * @return void */ public static function setConnectionContainer(Container $container) @@ -427,8 +455,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Register the query scopes for this builder instance. * - * @param Builder $builder - * + * @param Builder $builder * @return Builder */ public function registerModelScopes($builder) @@ -443,8 +470,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Register the global model scopes. * - * @param Builder $builder - * + * @param Builder $builder * @return Builder */ public function registerGlobalScopes($builder) @@ -459,8 +485,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Apply the model object class scopes to the given builder instance. * - * @param Builder $query - * + * @param Builder $query * @return void */ public function applyObjectClassScopes(Builder $query) @@ -483,10 +508,9 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Returns a new batch modification. * - * @param string|null $attribute - * @param string|int|null $type - * @param array $values - * + * @param string|null $attribute + * @param string|int|null $type + * @param array $values * @return BatchModification */ public function newBatchModification($attribute = null, $type = null, $values = []) @@ -497,8 +521,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Returns a new collection with the specified items. * - * @param mixed $items - * + * @param mixed $items * @return Collection */ public function newCollection($items = []) @@ -509,9 +532,8 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Dynamically retrieve attributes on the object. * - * @param mixed $key - * - * @return bool + * @param string $key + * @return mixed */ public function __get($key) { @@ -521,9 +543,8 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Dynamically set attributes on the object. * - * @param mixed $key - * @param mixed $value - * + * @param string $key + * @param mixed $value * @return $this */ public function __set($key, $value) @@ -534,8 +555,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Determine if the given offset exists. * - * @param string $offset - * + * @param string $offset * @return bool */ #[\ReturnTypeWillChange] @@ -547,8 +567,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Get the value for a given offset. * - * @param string $offset - * + * @param string $offset * @return mixed */ #[\ReturnTypeWillChange] @@ -560,9 +579,8 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Set the value at the given offset. * - * @param string $offset - * @param mixed $value - * + * @param string $offset + * @param mixed $value * @return void */ #[\ReturnTypeWillChange] @@ -574,8 +592,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Unset the value at the given offset. * - * @param string $offset - * + * @param string $offset * @return void */ #[\ReturnTypeWillChange] @@ -587,8 +604,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Determine if an attribute exists on the model. * - * @param string $key - * + * @param string $key * @return bool */ public function __isset($key) @@ -599,8 +615,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Unset an attribute on the model. * - * @param string $key - * + * @param string $key * @return void */ public function __unset($key) @@ -630,26 +645,36 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable } /** - * Converts extra attributes for JSON serialization. - * - * @param array $attributes + * Convert the attributes for JSON serialization. * + * @param array $attributes * @return array */ protected function convertAttributesForJson(array $attributes = []) { - // If the model has a GUID set, we need to convert - // it due to it being in binary. Otherwise we'll - // receive a JSON serialization exception. - if ($this->hasAttribute($this->guidKey)) { - return array_replace($attributes, [ - $this->guidKey => [$this->getConvertedGuid()], - ]); + // If the model has a GUID set, we need to convert it to its + // string format, due to it being in binary. Otherwise + // we will receive a JSON serialization exception. + if (isset($attributes[$this->guidKey])) { + $attributes[$this->guidKey] = [$this->getConvertedGuid( + Arr::first($attributes[$this->guidKey]) + )]; } return $attributes; } + /** + * Convert the attributes from JSON serialization. + * + * @param array $attributes + * @return array + */ + protected function convertAttributesFromJson(array $attributes = []) + { + return $attributes; + } + /** * Reload a fresh model instance from the directory. * @@ -667,8 +692,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Determine if two models have the same distinguished name and belong to the same connection. * - * @param Model|null $model - * + * @param Model|null $model * @return bool */ public function is($model) @@ -681,8 +705,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Determine if two models are not the same. * - * @param Model|null $model - * + * @param Model|null $model * @return bool */ public function isNot($model) @@ -693,8 +716,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Hydrate a new collection of models from search results. * - * @param array $records - * + * @param array $records * @return Collection */ public function hydrate($records) @@ -709,8 +731,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Converts the current model into the given model. * - * @param Model $into - * + * @param Model $into * @return Model */ public function convert(self $into) @@ -760,8 +781,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Set the models batch modifications. * - * @param array $modifications - * + * @param array $modifications * @return $this */ public function setModifications(array $modifications = []) @@ -778,8 +798,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Adds a batch modification to the model. * - * @param array|BatchModification $mod - * + * @param array|BatchModification $mod * @return $this * * @throws InvalidArgumentException @@ -824,8 +843,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Get the name of the model, or the given DN. * - * @param string|null $dn - * + * @param string|null $dn * @return string|null */ public function getName($dn = null) @@ -836,8 +854,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Get the head attribute of the model, or the given DN. * - * @param string|null $dn - * + * @param string|null $dn * @return string|null */ public function getHead($dn = null) @@ -849,7 +866,6 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable * Get the RDN of the model, of the given DN. * * @param string|null - * * @return string|null */ public function getRdn($dn = null) @@ -861,7 +877,6 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable * Get the parent distinguished name of the model, or the given DN. * * @param string|null - * * @return string|null */ public function getParentDn($dn = null) @@ -872,8 +887,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Create a new Distinguished Name object. * - * @param string|null $dn - * + * @param string|null $dn * @return DistinguishedName */ public function newDn($dn = null) @@ -910,28 +924,58 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable */ public function getObjectClasses() { - return $this->getAttribute('objectclass') ?: []; + return $this->getAttribute('objectclass', static::$objectClasses); } /** * Get the model's string GUID. * + * @param string|null $guid * @return string|null */ - public function getConvertedGuid() + public function getConvertedGuid($guid = null) { try { - return (string) new Guid($this->getObjectGuid()); + return (string) $this->newObjectGuid( + $guid ?? $this->getObjectGuid() + ); } catch (InvalidArgumentException $e) { return; } } + /** + * Get the model's binary GUID. + * + * @param string|null $guid + * @return string|null + */ + public function getBinaryGuid($guid = null) + { + try { + return $this->newObjectGuid( + $guid ?? $this->getObjectGuid() + )->getBinary(); + } catch (InvalidArgumentException $e) { + return; + } + } + + /** + * Make a new object Guid instance. + * + * @param string $value + * @return Guid + */ + protected function newObjectGuid($value) + { + return new Guid($value); + } + /** * Determine if the current model is a direct descendant of the given. * - * @param static|string $parent - * + * @param static|string $parent * @return bool */ public function isChildOf($parent) @@ -944,8 +988,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Determine if the current model is a direct ascendant of the given. * - * @param static|string $child - * + * @param static|string $child * @return bool */ public function isParentOf($child) @@ -958,8 +1001,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Determine if the current model is a descendant of the given. * - * @param static|string $model - * + * @param static|string $model * @return bool */ public function isDescendantOf($model) @@ -970,8 +1012,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Determine if the current model is a ancestor of the given. * - * @param static|string $model - * + * @param static|string $model * @return bool */ public function isAncestorOf($model) @@ -982,9 +1023,8 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Determines if the DN is inside of the parent DN. * - * @param static|string $dn - * @param static|string $parentDn - * + * @param static|string $dn + * @param static|string $parentDn * @return bool */ protected function dnIsInside($dn, $parentDn) @@ -997,8 +1037,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Set the base DN of where the model should be created in. * - * @param static|string $dn - * + * @param static|string $dn * @return $this */ public function inside($dn) @@ -1011,8 +1050,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Save the model to the directory without raising any events. * - * @param array $attributes - * + * @param array $attributes * @return void * * @throws \LdapRecord\LdapRecordException @@ -1027,8 +1065,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Save the model to the directory. * - * @param array $attributes The attributes to update or create for the current entry. - * + * @param array $attributes The attributes to update or create for the current entry. * @return void * * @throws \LdapRecord\LdapRecordException @@ -1037,11 +1074,13 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable { $this->fill($attributes); - $this->fireModelEvent(new Events\Saving($this)); + $this->dispatch('saving'); $this->exists ? $this->performUpdate() : $this->performInsert(); - $this->fireModelEvent(new Events\Saved($this)); + $this->dispatch('saved'); + + $this->modifications = []; $this->in = null; } @@ -1071,7 +1110,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable $this->setDn($this->getCreatableDn()); } - $this->fireModelEvent(new Events\Creating($this)); + $this->dispatch('creating'); // Here we perform the insert of new object in the directory, // but filter out any empty attributes before sending them @@ -1079,7 +1118,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable // attributes have been given empty or null values. $query->insert($this->getDn(), array_filter($this->getAttributes())); - $this->fireModelEvent(new Events\Created($this)); + $this->dispatch('created'); $this->syncOriginal(); @@ -1101,22 +1140,19 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable return; } - $this->fireModelEvent(new Events\Updating($this)); + $this->dispatch('updating'); $this->newQuery()->update($this->dn, $modifications); - $this->fireModelEvent(new Events\Updated($this)); + $this->dispatch('updated'); $this->syncOriginal(); - - $this->modifications = []; } /** * Create the model in the directory. * - * @param array $attributes The attributes for the new entry. - * + * @param array $attributes The attributes for the new entry. * @return Model * * @throws \LdapRecord\LdapRecordException @@ -1133,9 +1169,8 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Create an attribute on the model. * - * @param string $attribute The attribute to create - * @param mixed $value The value of the new attribute - * + * @param string $attribute The attribute to create + * @param mixed $value The value of the new attribute * @return void * * @throws ModelDoesNotExistException @@ -1143,18 +1178,21 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable */ public function createAttribute($attribute, $value) { - $this->requireExistence(); + $this->assertExists(); + + $this->dispatch(['saving', 'updating']); $this->newQuery()->insertAttributes($this->dn, [$attribute => (array) $value]); $this->addAttributeValue($attribute, $value); + + $this->dispatch(['updated', 'saved']); } /** * Update the model. * - * @param array $attributes The attributes to update for the current entry. - * + * @param array $attributes The attributes to update for the current entry. * @return void * * @throws ModelDoesNotExistException @@ -1162,7 +1200,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable */ public function update(array $attributes = []) { - $this->requireExistence(); + $this->assertExists(); $this->save($attributes); } @@ -1170,9 +1208,8 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Update the model attribute with the specified value. * - * @param string $attribute The attribute to modify - * @param mixed $value The new value for the attribute - * + * @param string $attribute The attribute to modify + * @param mixed $value The new value for the attribute * @return void * * @throws ModelDoesNotExistException @@ -1180,19 +1217,22 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable */ public function updateAttribute($attribute, $value) { - $this->requireExistence(); + $this->assertExists(); + + $this->dispatch(['saving', 'updating']); $this->newQuery()->updateAttributes($this->dn, [$attribute => (array) $value]); $this->addAttributeValue($attribute, $value); + + $this->dispatch(['updated', 'saved']); } /** * Destroy the models for the given distinguished names. * - * @param Collection|array|string $dns - * @param bool $recursive - * + * @param Collection|array|string $dns + * @param bool $recursive * @return int * * @throws \LdapRecord\LdapRecordException @@ -1201,11 +1241,17 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable { $count = 0; - $dns = is_string($dns) ? (array) $dns : $dns; - $instance = new static(); - foreach ($dns as $dn) { + if ($dns instanceof Collection) { + $dns = $dns->modelDns()->toArray(); + } + + // Here we are iterating through each distinguished name and locating + // the associated model. While it's more resource intensive, we must + // do this in case of leaf nodes being given alongside any parent + // node, ensuring they can be deleted inside of the directory. + foreach ((array) $dns as $dn) { if (! $model = $instance->find($dn)) { continue; } @@ -1224,8 +1270,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable * Throws a ModelNotFoundException if the current model does * not exist or does not contain a distinguished name. * - * @param bool $recursive Whether to recursively delete leaf nodes (models that are children). - * + * @param bool $recursive Whether to recursively delete leaf nodes (models that are children). * @return void * * @throws ModelDoesNotExistException @@ -1233,9 +1278,9 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable */ public function delete($recursive = false) { - $this->requireExistence(); + $this->assertExists(); - $this->fireModelEvent(new Events\Deleting($this)); + $this->dispatch('deleting'); if ($recursive) { $this->deleteLeafNodes(); @@ -1248,7 +1293,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable // developers can hook in and run further operations. $this->exists = false; - $this->fireModelEvent(new Events\Deleted($this)); + $this->dispatch('deleted'); } /** @@ -1263,15 +1308,15 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable $this->newQueryWithoutScopes() ->in($this->dn) ->listing() - ->chunk(250, function ($models) { - $models->each->delete($recursive = true); + ->each(function (Model $model) { + $model->delete($recursive = true); }); } /** * Delete an attribute on the model. * - * @param string|array $attributes The attribute(s) to delete + * @param string|array $attributes The attribute(s) to delete * * Delete specific values in attributes: * @@ -1280,7 +1325,6 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable * Delete an entire attribute: * * ["memberuid" => []] - * * @return void * * @throws ModelDoesNotExistException @@ -1288,10 +1332,12 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable */ public function deleteAttribute($attributes) { - $this->requireExistence(); + $this->assertExists(); $attributes = $this->makeDeletableAttributes($attributes); + $this->dispatch(['saving', 'updating']); + $this->newQuery()->deleteAttributes($this->dn, $attributes); foreach ($attributes as $attribute => $value) { @@ -1311,14 +1357,15 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable } } + $this->dispatch(['updated', 'saved']); + $this->syncOriginal(); } /** * Make a deletable attribute array. * - * @param string|array $attributes - * + * @param string|array $attributes * @return array */ protected function makeDeletableAttributes($attributes) @@ -1339,9 +1386,8 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable * * For example: $user->move($ou); * - * @param static|string $newParentDn The new parent of the current model. - * @param bool $deleteOldRdn Whether to delete the old models relative distinguished name once renamed / moved. - * + * @param static|string $newParentDn The new parent of the current model. + * @param bool $deleteOldRdn Whether to delete the old models relative distinguished name once renamed / moved. * @return void * * @throws UnexpectedValueException @@ -1350,7 +1396,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable */ public function move($newParentDn, $deleteOldRdn = true) { - $this->requireExistence(); + $this->assertExists(); if (! $rdn = $this->getRdn()) { throw new UnexpectedValueException('Current model does not contain an RDN to move.'); @@ -1362,10 +1408,9 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Rename the model to a new RDN and new parent. * - * @param string $rdn The models new relative distinguished name. Example: "cn=JohnDoe" - * @param static|string|null $newParentDn The models new parent distinguished name (if moving). Leave this null if you are only renaming. Example: "ou=MovedUsers,dc=acme,dc=org" - * @param bool|true $deleteOldRdn Whether to delete the old models relative distinguished name once renamed / moved. - * + * @param string $rdn The models new relative distinguished name. Example: "cn=JohnDoe" + * @param static|string|null $newParentDn The models new parent distinguished name (if moving). Leave this null if you are only renaming. Example: "ou=MovedUsers,dc=acme,dc=org" + * @param bool|true $deleteOldRdn Whether to delete the old models relative distinguished name once renamed / moved. * @return void * * @throws ModelDoesNotExistException @@ -1373,7 +1418,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable */ public function rename($rdn, $newParentDn = null, $deleteOldRdn = true) { - $this->requireExistence(); + $this->assertExists(); if ($newParentDn instanceof self) { $newParentDn = $newParentDn->getDn(); @@ -1400,7 +1445,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable $rdn = $this->getUpdateableRdn($rdn); } - $this->fireModelEvent(new Renaming($this, $rdn, $newParentDn)); + $this->dispatch('renaming', [$rdn, $newParentDn]); $this->newQuery()->rename($this->dn, $rdn, $newParentDn, $deleteOldRdn); @@ -1420,7 +1465,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable = $this->original[$modelNameAttribute] = [reset($map[$modelNameAttribute])]; - $this->fireModelEvent(new Renamed($this)); + $this->dispatch('renamed'); $this->wasRecentlyRenamed = true; } @@ -1428,8 +1473,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Get an updateable RDN for the model. * - * @param string $name - * + * @param string $name * @return string */ public function getUpdateableRdn($name) @@ -1440,9 +1484,8 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Get a distinguished name that is creatable for the model. * - * @param string|null $name - * @param string|null $attribute - * + * @param string|null $name + * @param string|null $attribute * @return string */ public function getCreatableDn($name = null, $attribute = null) @@ -1456,9 +1499,8 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Get a creatable (escaped) RDN for the model. * - * @param string|null $name - * @param string|null $attribute - * + * @param string|null $name + * @param string|null $attribute * @return string */ public function getCreatableRdn($name = null, $attribute = null) @@ -1485,8 +1527,7 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Determines if the given modification is valid. * - * @param mixed $mod - * + * @param mixed $mod * @return bool */ protected function isValidModification($mod) @@ -1528,11 +1569,25 @@ abstract class Model implements ArrayAccess, Arrayable, JsonSerializable /** * Throw an exception if the model does not exist. * + * @deprecated + * * @return void * * @throws ModelDoesNotExistException */ protected function requireExistence() + { + return $this->assertExists(); + } + + /** + * Throw an exception if the model does not exist. + * + * @return void + * + * @throws ModelDoesNotExistException + */ + protected function assertExists() { if (! $this->exists || is_null($this->dn)) { throw ModelDoesNotExistException::forModel($this); diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ModelDoesNotExistException.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ModelDoesNotExistException.php index 2dd2ba9bd..508414911 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ModelDoesNotExistException.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/ModelDoesNotExistException.php @@ -16,8 +16,7 @@ class ModelDoesNotExistException extends LdapRecordException /** * Create a new exception for the given model. * - * @param Model $model - * + * @param Model $model * @return ModelDoesNotExistException */ public static function forModel(Model $model) @@ -28,8 +27,7 @@ class ModelDoesNotExistException extends LdapRecordException /** * Set the model that does not exist. * - * @param Model $model - * + * @param Model $model * @return ModelDoesNotExistException */ public function setModel(Model $model) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/OpenLDAP/Entry.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/OpenLDAP/Entry.php index b7ad37a44..c11ca72d4 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/OpenLDAP/Entry.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/OpenLDAP/Entry.php @@ -34,8 +34,7 @@ class Entry extends BaseEntry implements OpenLDAP /** * Create a new query builder. * - * @param Connection $connection - * + * @param Connection $connection * @return OpenLdapBuilder */ public function newQueryBuilder(Connection $connection) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/OpenLDAP/Group.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/OpenLDAP/Group.php index 2d8d94e39..a9a682a06 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/OpenLDAP/Group.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/OpenLDAP/Group.php @@ -13,4 +13,16 @@ class Group extends Entry 'top', 'groupofuniquenames', ]; + + /** + * The members relationship. + * + * Retrieves members that are apart of the group. + * + * @return \LdapRecord\Models\Relations\HasMany + */ + public function members() + { + return $this->hasMany([static::class, User::class], 'memberUid'); + } } diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/OpenLDAP/Scopes/AddEntryUuidToSelects.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/OpenLDAP/Scopes/AddEntryUuidToSelects.php index 54376c2ba..780a633f3 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/OpenLDAP/Scopes/AddEntryUuidToSelects.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/OpenLDAP/Scopes/AddEntryUuidToSelects.php @@ -11,9 +11,8 @@ class AddEntryUuidToSelects implements Scope /** * Add the entry UUID to the selected attributes. * - * @param Builder $query - * @param Model $model - * + * @param Builder $query + * @param Model $model * @return void */ public function apply(Builder $query, Model $model) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/OpenLDAP/User.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/OpenLDAP/User.php index b37f39056..c8626de6d 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/OpenLDAP/User.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/OpenLDAP/User.php @@ -40,7 +40,7 @@ class User extends Entry implements Authenticatable /** * The groups relationship. * - * Retrieves groups that the user is apart of. + * Retrieve groups that the user is a part of. * * @return \LdapRecord\Models\Relations\HasMany */ diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Relations/HasMany.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Relations/HasMany.php index ae36720c2..583f81c30 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Relations/HasMany.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Relations/HasMany.php @@ -5,9 +5,9 @@ namespace LdapRecord\Models\Relations; use Closure; use LdapRecord\DetectsErrors; use LdapRecord\LdapRecordException; +use LdapRecord\Models\Collection; use LdapRecord\Models\Model; use LdapRecord\Models\ModelNotFoundException; -use LdapRecord\Query\Collection; class HasMany extends OneToMany { @@ -51,9 +51,8 @@ class HasMany extends OneToMany /** * Set the model and attribute to use for attaching / detaching. * - * @param Model $using - * @param string $usingKey - * + * @param Model $using + * @param string $usingKey * @return $this */ public function using(Model $using, $usingKey) @@ -67,8 +66,7 @@ class HasMany extends OneToMany /** * Set the pagination page size of the relation query. * - * @param int $pageSize - * + * @param int $pageSize * @return $this */ public function setPageSize($pageSize) @@ -81,8 +79,7 @@ class HasMany extends OneToMany /** * Paginate the relation using the given page size. * - * @param int $pageSize - * + * @param int $pageSize * @return Collection */ public function paginate($pageSize = 1000) @@ -93,8 +90,7 @@ class HasMany extends OneToMany /** * Paginate the relation using the page size once. * - * @param int $pageSize - * + * @param int $pageSize * @return Collection */ protected function paginateOnceUsing($pageSize) @@ -108,18 +104,67 @@ class HasMany extends OneToMany return $result; } + /** + * Execute a callback over each result while chunking. + * + * @param Closure $callback + * @param int $pageSize + * @return bool + */ + public function each(Closure $callback, $pageSize = 1000) + { + $this->chunk($pageSize, function ($results) use ($callback) { + foreach ($results as $key => $value) { + if ($callback($value, $key) === false) { + return false; + } + } + }); + } + /** * Chunk the relation results using the given callback. * - * @param int $pageSize - * @param Closure $callback - * - * @return void + * @param int $pageSize + * @param Closure $callback + * @param array $loaded + * @return bool */ public function chunk($pageSize, Closure $callback) { - $this->getRelationQuery()->chunk($pageSize, function ($entries) use ($callback) { - $callback($this->transformResults($entries)); + return $this->chunkRelation($pageSize, $callback); + } + + /** + * Execute the callback over chunks of relation results. + * + * @param int $pageSize + * @param Closure $callback + * @param array $loaded + * @return bool + */ + protected function chunkRelation($pageSize, Closure $callback, $loaded = []) + { + return $this->getRelationQuery()->chunk($pageSize, function (Collection $results) use ($pageSize, $callback, $loaded) { + $models = $this->transformResults($results)->when($this->recursive, function (Collection $models) use ($loaded) { + return $models->reject(function (Model $model) use ($loaded) { + return in_array($model->getDn(), $loaded); + }); + }); + + if ($callback($models) === false) { + return false; + } + + $models->when($this->recursive, function (Collection $models) use ($pageSize, $callback, $loaded) { + $models->each(function (Model $model) use ($pageSize, $callback, $loaded) { + if ($relation = $model->getRelation($this->relationName)) { + $loaded[] = $model->getDn(); + + return $relation->recursive()->chunkRelation($pageSize, $callback, $loaded); + } + }); + }); }); } @@ -168,8 +213,7 @@ class HasMany extends OneToMany /** * Attach a model to the relation. * - * @param Model|string $model - * + * @param Model|string $model * @return Model|string|false */ public function attach($model) @@ -184,8 +228,7 @@ class HasMany extends OneToMany /** * Build the attach callback. * - * @param Model|string $model - * + * @param Model|string $model * @return \Closure */ protected function buildAttachCallback($model) @@ -208,8 +251,7 @@ class HasMany extends OneToMany /** * Attach a collection of models to the parent instance. * - * @param iterable $models - * + * @param iterable $models * @return iterable */ public function attachMany($models) @@ -224,8 +266,7 @@ class HasMany extends OneToMany /** * Detach the model from the relation. * - * @param Model|string $model - * + * @param Model|string $model * @return Model|string|false */ public function detach($model) @@ -237,11 +278,29 @@ class HasMany extends OneToMany ); } + /** + * Detach the model or delete the parent if the relation is empty. + * + * @param Model|string $model + * @return void + */ + public function detachOrDeleteParent($model) + { + $count = $this->onceWithoutMerging(function () { + return $this->count(); + }); + + if ($count <= 1) { + return $this->getParent()->delete(); + } + + return $this->detach($model); + } + /** * Build the detach callback. * - * @param Model|string $model - * + * @param Model|string $model * @return \Closure */ protected function buildDetachCallback($model) @@ -264,8 +323,7 @@ class HasMany extends OneToMany /** * Get the attachable foreign value from the model. * - * @param Model|string $model - * + * @param Model|string $model * @return string */ protected function getAttachableForeignValue($model) @@ -282,8 +340,7 @@ class HasMany extends OneToMany /** * Get the foreign model by the given value, or fail. * - * @param string $model - * + * @param string $model * @return Model * * @throws ModelNotFoundException @@ -305,10 +362,9 @@ class HasMany extends OneToMany * * If a bypassable exception is encountered, the value will be returned. * - * @param callable $operation - * @param string|array $bypass - * @param mixed $value - * + * @param callable $operation + * @param string|array $bypass + * @param mixed $value * @return mixed * * @throws LdapRecordException @@ -341,4 +397,24 @@ class HasMany extends OneToMany }); }); } + + /** + * Detach all relation models or delete the model if its relation is empty. + * + * @return Collection + */ + public function detachAllOrDelete() + { + return $this->onceWithoutMerging(function () { + return $this->get()->each(function (Model $model) { + $relation = $model->getRelation($this->relationName); + + if ($relation && $relation->count() >= 1) { + $model->delete(); + } else { + $this->detach($model); + } + }); + }); + } } diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Relations/HasOne.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Relations/HasOne.php index 7bad4ab63..243cd2ed9 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Relations/HasOne.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Relations/HasOne.php @@ -25,8 +25,7 @@ class HasOne extends Relation /** * Attach a model instance to the parent model. * - * @param Model|string $model - * + * @param Model|string $model * @return Model|string * * @throws \LdapRecord\LdapRecordException diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Relations/OneToMany.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Relations/OneToMany.php index 6d14c8574..aa873b60b 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Relations/OneToMany.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Relations/OneToMany.php @@ -32,12 +32,12 @@ abstract class OneToMany extends Relation /** * Constructor. * - * @param Builder $query - * @param Model $parent - * @param string $related - * @param string $relationKey - * @param string $foreignKey - * @param string $relationName + * @param Builder $query + * @param Model $parent + * @param string $related + * @param string $relationKey + * @param string $foreignKey + * @param string $relationName */ public function __construct(Builder $query, Model $parent, $related, $relationKey, $foreignKey, $relationName) { @@ -49,8 +49,7 @@ abstract class OneToMany extends Relation /** * Set the relation to load with its parent. * - * @param Relation $relation - * + * @param Relation $relation * @return $this */ public function with(Relation $relation) @@ -63,8 +62,7 @@ abstract class OneToMany extends Relation /** * Whether to include recursive results. * - * @param bool $enable - * + * @param bool $enable * @return $this */ public function recursive($enable = true) @@ -100,8 +98,7 @@ abstract class OneToMany extends Relation /** * Execute the callback excluding the merged query result. * - * @param callable $callback - * + * @param callable $callback * @return mixed */ protected function onceWithoutMerging($callback) @@ -142,8 +139,7 @@ abstract class OneToMany extends Relation /** * Get the results for the models relation recursively. * - * @param string[] $loaded The distinguished names of models already loaded - * + * @param string[] $loaded The distinguished names of models already loaded * @return Collection */ protected function getRecursiveResults(array $loaded = []) @@ -172,15 +168,14 @@ abstract class OneToMany extends Relation /** * Get the recursive relation results for given model. * - * @param Model $model - * @param array $loaded - * + * @param Model $model + * @param array $loaded * @return Collection */ protected function getRecursiveRelationResults(Model $model, array $loaded) { - return method_exists($model, $this->relationName) - ? $model->{$this->relationName}()->getRecursiveResults($loaded) + return ($relation = $model->getRelation($this->relationName)) + ? $relation->getRecursiveResults($loaded) : $model->newCollection(); } } diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Relations/Relation.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Relations/Relation.php index 1b108fd91..31b0969c9 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Relations/Relation.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Relations/Relation.php @@ -2,6 +2,7 @@ namespace LdapRecord\Models\Relations; +use Closure; use LdapRecord\Models\Entry; use LdapRecord\Models\Model; use LdapRecord\Query\Collection; @@ -9,7 +10,8 @@ use LdapRecord\Query\Model\Builder; /** * @method bool exists($models = null) Determine if the relation contains all of the given models, or any models - * @method bool contains($models) Determine if any of the given models are contained in the relation + * @method bool contains($models) Determine if any of the given models are contained in the relation + * @method bool count() Retrieve the "count" result of the query. */ abstract class Relation { @@ -28,7 +30,7 @@ abstract class Relation protected $parent; /** - * The related models. + * The related model class names. * * @var array */ @@ -55,14 +57,28 @@ abstract class Relation */ protected $default = Entry::class; + /** + * The callback to use for resolving relation models. + * + * @var Closure + */ + protected static $modelResolver; + + /** + * The methods that should be passed along to a relation collection. + * + * @var string[] + */ + protected $passthru = ['count', 'exists', 'contains']; + /** * Constructor. * - * @param Builder $query - * @param Model $parent - * @param mixed $related - * @param string $relationKey - * @param string $foreignKey + * @param Builder $query + * @param Model $parent + * @param string|array $related + * @param string $relationKey + * @param string $foreignKey */ public function __construct(Builder $query, Model $parent, $related, $relationKey, $foreignKey) { @@ -72,20 +88,23 @@ abstract class Relation $this->relationKey = $relationKey; $this->foreignKey = $foreignKey; + static::$modelResolver = static::$modelResolver ?? function (array $modelObjectClasses, array $relationMap) { + return array_search($modelObjectClasses, $relationMap); + }; + $this->initRelation(); } /** * Handle dynamic method calls to the relationship. * - * @param string $method - * @param array $parameters - * + * @param string $method + * @param array $parameters * @return mixed */ public function __call($method, $parameters) { - if (in_array($method, ['exists', 'contains'])) { + if (in_array($method, $this->passthru)) { return $this->get('objectclass')->$method(...$parameters); } @@ -98,6 +117,45 @@ abstract class Relation return $result; } + /** + * Set the callback to use for resolving models from relation results. + * + * @param Closure $callback + * @return void + */ + public static function resolveModelsUsing(Closure $callback) + { + static::$modelResolver = $callback; + } + + /** + * Only return objects matching the related model's object classes. + * + * @return $this + */ + public function onlyRelated() + { + $relations = []; + + foreach ($this->related as $related) { + $relations[$related] = $related::$objectClasses; + } + + $relations = array_filter($relations); + + if (empty($relations)) { + return $this; + } + + $this->query->andFilter(function (Builder $query) use ($relations) { + foreach ($relations as $relation => $objectClasses) { + $query->whereIn('objectclass', $objectClasses); + } + }); + + return $this; + } + /** * Get the results of the relationship. * @@ -108,8 +166,7 @@ abstract class Relation /** * Execute the relationship query. * - * @param array|string $columns - * + * @param array|string $columns * @return Collection */ public function get($columns = ['*']) @@ -122,8 +179,7 @@ abstract class Relation * * If the query columns are empty, the given columns are applied. * - * @param array $columns - * + * @param array $columns * @return Collection */ protected function getResultsWithColumns($columns) @@ -138,8 +194,7 @@ abstract class Relation /** * Get the first result of the relationship. * - * @param array|string $columns - * + * @param array|string $columns * @return Model|null */ public function first($columns = ['*']) @@ -162,6 +217,21 @@ abstract class Relation return $this; } + /** + * Set the underlying query for the relation. + * + * @param Builder $query + * @return $this + */ + public function setQuery(Builder $query) + { + $this->query = $query; + + $this->initRelation(); + + return $this; + } + /** * Get the underlying query for the relation. * @@ -239,8 +309,7 @@ abstract class Relation /** * Get the foreign model by the given value. * - * @param string $value - * + * @param string $value * @return Model|null */ protected function getForeignModelByValue($value) @@ -253,8 +322,7 @@ abstract class Relation /** * Returns the escaped foreign key value for use in an LDAP filter from the model. * - * @param Model $model - * + * @param Model $model * @return string */ protected function getEscapedForeignValueFromModel(Model $model) @@ -277,8 +345,7 @@ abstract class Relation /** * Get the foreign key value from the model. * - * @param Model $model - * + * @param Model $model * @return string */ protected function getForeignValueFromModel(Model $model) @@ -291,9 +358,8 @@ abstract class Relation /** * Get the first attribute value from the model. * - * @param Model $model - * @param string $attribute - * + * @param Model $model + * @param string $attribute * @return string|null */ protected function getFirstAttributeValue(Model $model, $attribute) @@ -304,20 +370,21 @@ abstract class Relation /** * Transforms the results by converting the models into their related. * - * @param Collection $results - * + * @param Collection $results * @return Collection */ protected function transformResults(Collection $results) { - $related = []; + $relationMap = []; foreach ($this->related as $relation) { - $related[$relation] = $relation::$objectClasses; + $relationMap[$relation] = $this->normalizeObjectClasses( + $relation::$objectClasses + ); } - return $results->transform(function (Model $entry) use ($related) { - $model = $this->determineModelFromRelated($entry, $related); + return $results->transform(function (Model $entry) use ($relationMap) { + $model = $this->determineModelFromRelated($entry, $relationMap); return class_exists($model) ? $entry->convert(new $model()) : $entry; }); @@ -334,29 +401,33 @@ abstract class Relation } /** - * Determines the model from the given relations. + * Determines the model from the given relation map. * - * @param Model $model - * @param array $related - * - * @return string|bool + * @param Model $model + * @param array $relationMap + * @return class-string|bool */ - protected function determineModelFromRelated(Model $model, array $related) + protected function determineModelFromRelated(Model $model, array $relationMap) { // We must normalize all the related models object class // names to the same case so we are able to properly // determine the owning model from search results. - return array_search( - $this->normalizeObjectClasses($model->getObjectClasses()), - array_map([$this, 'normalizeObjectClasses'], $related) + $modelObjectClasses = $this->normalizeObjectClasses( + $model->getObjectClasses() + ); + + return call_user_func( + static::$modelResolver, + $modelObjectClasses, + $relationMap, + $model, ); } /** * Sort and normalize the object classes. * - * @param array $classes - * + * @param array $classes * @return array */ protected function normalizeObjectClasses($classes) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Scope.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Scope.php index 321cae357..f61cf686b 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Scope.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Scope.php @@ -9,9 +9,8 @@ interface Scope /** * Apply the scope to the given query. * - * @param Builder $query - * @param Model $model - * + * @param Builder $query + * @param Model $model * @return void */ public function apply(Builder $query, Model $model); diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Types/ActiveDirectory.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Types/ActiveDirectory.php index 61d21ef28..3edcf88c9 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Types/ActiveDirectory.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Types/ActiveDirectory.php @@ -23,7 +23,16 @@ interface ActiveDirectory extends TypeInterface /** * Returns the model's SID. * + * @param string|null $sid * @return string|null */ - public function getConvertedSid(); + public function getConvertedSid($sid = null); + + /** + * Returns the model's binary SID. + * + * @param string|null $sid + * @return string|null + */ + public function getBinarySid($sid = null); } diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Types/DirectoryServer.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Types/DirectoryServer.php new file mode 100644 index 000000000..f06216cd5 --- /dev/null +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Models/Types/DirectoryServer.php @@ -0,0 +1,8 @@ +chunk($count, function ($results) use ($callback) { + return $this->chunk($pageSize, function ($results) use ($callback) { foreach ($results as $key => $value) { if ($callback($value, $key) === false) { return false; } } - }); + }, $isCritical, $isolate); } /** * Chunk the results of a paginated LDAP query. * - * @param int $pageSize - * @param Closure $callback - * @param bool $isCritical - * + * @param int $pageSize + * @param Closure $callback + * @param bool $isCritical + * @param bool $isolate * @return bool */ - public function chunk($pageSize, Closure $callback, $isCritical = false) + public function chunk($pageSize, Closure $callback, $isCritical = false, $isolate = false) { $start = microtime(true); - $query = $this->getQuery(); + $chunk = function (Builder $query) use ($pageSize, $callback, $isCritical) { + $page = 1; - $page = 1; + foreach ($query->runChunk($this->getQuery(), $pageSize, $isCritical) as $chunk) { + if ($callback($this->process($chunk), $page) === false) { + return false; + } - foreach ($this->runChunk($query, $pageSize, $isCritical) as $chunk) { - if ($callback($this->process($chunk), $page) === false) { - return false; + $page++; } + }; - $page++; - } + $isolate ? $this->connection->isolate(function (Connection $replicate) use ($chunk) { + $chunk($this->clone()->setConnection($replicate)); + }) : $chunk($this); $this->logQuery($this, 'chunk', $this->getElapsedTime($start)); @@ -561,11 +549,10 @@ class Builder /** * Runs the chunk operation with the given filter. * - * @param string $filter - * @param int $perPage - * @param bool $isCritical - * - * @return array + * @param string $filter + * @param int $perPage + * @param bool $isCritical + * @return \Generator */ protected function runChunk($filter, $perPage, $isCritical) { @@ -574,11 +561,61 @@ class Builder }); } + /** + * Create a slice of the LDAP query into a page. + * + * @param int $page + * @param int $perPage + * @param string $orderBy + * @param string $orderByDir + * @return Slice + */ + public function slice($page = 1, $perPage = 100, $orderBy = 'cn', $orderByDir = 'asc') + { + $results = $this->forPage($page, $perPage, $orderBy, $orderByDir); + + $total = $this->controlsResponse[LDAP_CONTROL_VLVRESPONSE]['value']['count'] ?? 0; + + // Some LDAP servers seem to have an issue where the last result in a virtual + // list view will always be returned, regardless of the offset being larger + // than the result itself. In this case, we will manually return an empty + // response so that no objects are deceivingly included in the slice. + $objects = $page > max((int) ceil($total / $perPage), 1) + ? ($this instanceof ModelBuilder ? $this->model->newCollection() : []) + : $results; + + return new Slice($objects, $total, $perPage, $page); + } + + /** + * Get the results of a query for a given page. + * + * @param int $page + * @param int $perPage + * @param string $orderBy + * @param string $orderByDir + * @return Collection|array + */ + public function forPage($page = 1, $perPage = 100, $orderBy = 'cn', $orderByDir = 'asc') + { + if (! $this->hasOrderBy()) { + $this->orderBy($orderBy, $orderByDir); + } + + $this->addControl(LDAP_CONTROL_VLVREQUEST, true, [ + 'before' => 0, + 'after' => $perPage - 1, + 'offset' => ($page * $perPage) - $perPage + 1, + 'count' => 0, + ]); + + return $this->get(); + } + /** * Processes and converts the given LDAP results into models. * - * @param array $results - * + * @param array $results * @return array */ protected function process(array $results) @@ -595,8 +632,7 @@ class Builder /** * Flattens LDAP paged results into a single array. * - * @param array $pages - * + * @param array $pages * @return array */ protected function flattenPages(array $pages) @@ -615,9 +651,8 @@ class Builder /** * Get the cached response or execute and cache the callback value. * - * @param string $query - * @param Closure $callback - * + * @param string $query + * @param Closure $callback * @return mixed */ protected function getCachedResponse($query, Closure $callback) @@ -638,8 +673,7 @@ class Builder /** * Runs the query operation with the given filter. * - * @param string $filter - * + * @param string $filter * @return resource */ public function run($filter) @@ -668,8 +702,7 @@ class Builder /** * Parses the given LDAP resource by retrieving its entries. * - * @param resource $resource - * + * @param resource $resource * @return array */ public function parse($resource) @@ -708,13 +741,14 @@ class Builder /** * Returns the cache key. * - * @param string $query - * + * @param string $query * @return string */ protected function getCacheKey($query) { - $host = $this->connection->getLdapConnection()->getHost(); + $host = $this->connection->run(function (LdapInterface $ldap) { + return $ldap->getHost(); + }); $key = $host .$this->type @@ -730,8 +764,7 @@ class Builder /** * Returns the first entry in a search result. * - * @param array|string $columns - * + * @param array|string $columns * @return Model|null */ public function first($columns = ['*']) @@ -746,8 +779,7 @@ class Builder * * If no entry is found, an exception is thrown. * - * @param array|string $columns - * + * @param array|string $columns * @return Model|array * * @throws ObjectNotFoundException @@ -764,8 +796,7 @@ class Builder /** * Return the first entry in a result, or execute the callback. * - * @param Closure $callback - * + * @param Closure $callback * @return Model|mixed */ public function firstOr(Closure $callback) @@ -776,8 +807,7 @@ class Builder /** * Execute the query and get the first result if it's the sole matching record. * - * @param array|string $columns - * + * @param array|string $columns * @return Model|array * * @throws ObjectsNotFoundException @@ -821,8 +851,7 @@ class Builder /** * Execute the given callback if no rows exist for the current query. * - * @param Closure $callback - * + * @param Closure $callback * @return bool|mixed */ public function existsOr(Closure $callback) @@ -833,8 +862,8 @@ class Builder /** * Throws a not found exception. * - * @param string $query - * @param string $dn + * @param string $query + * @param string $dn * * @throws ObjectNotFoundException */ @@ -846,10 +875,9 @@ class Builder /** * Finds a record by the specified attribute and value. * - * @param string $attribute - * @param string $value - * @param array|string $columns - * + * @param string $attribute + * @param string $value + * @param array|string $columns * @return Model|static|null */ public function findBy($attribute, $value, $columns = ['*']) @@ -866,10 +894,9 @@ class Builder * * If no record is found an exception is thrown. * - * @param string $attribute - * @param string $value - * @param array|string $columns - * + * @param string $attribute + * @param string $value + * @param array|string $columns * @return Model * * @throws ObjectNotFoundException @@ -882,9 +909,8 @@ class Builder /** * Find many records by distinguished name. * - * @param array $dns - * @param array $columns - * + * @param string|array $dns + * @param array $columns * @return array|Collection */ public function findMany($dns, $columns = ['*']) @@ -895,7 +921,7 @@ class Builder $objects = []; - foreach ($dns as $dn) { + foreach ((array) $dns as $dn) { if (! is_null($object = $this->find($dn, $columns))) { $objects[] = $object; } @@ -907,10 +933,9 @@ class Builder /** * Finds many records by the specified attribute. * - * @param string $attribute - * @param array $values - * @param array $columns - * + * @param string $attribute + * @param array $values + * @param array $columns * @return Collection */ public function findManyBy($attribute, array $values = [], $columns = ['*']) @@ -927,9 +952,8 @@ class Builder /** * Finds a record by its distinguished name. * - * @param string|array $dn - * @param array|string $columns - * + * @param string|array $dn + * @param array|string $columns * @return Model|static|array|Collection|null */ public function find($dn, $columns = ['*']) @@ -950,9 +974,8 @@ class Builder * * Fails upon no records returned. * - * @param string $dn - * @param array|string $columns - * + * @param string $dn + * @param array|string $columns * @return Model|static * * @throws ObjectNotFoundException @@ -968,8 +991,7 @@ class Builder /** * Adds the inserted fields to query on the current LDAP connection. * - * @param array|string $columns - * + * @param array|string $columns * @return $this */ public function select($columns = ['*']) @@ -986,8 +1008,7 @@ class Builder /** * Add a new select column to the query. * - * @param array|mixed $column - * + * @param array|mixed $column * @return $this */ public function addSelect($column) @@ -1002,9 +1023,8 @@ class Builder /** * Add an order by control to the query. * - * @param string $attribute - * @param string $direction - * + * @param string $attribute + * @param string $direction * @return $this */ public function orderBy($attribute, $direction = 'asc') @@ -1017,8 +1037,7 @@ class Builder /** * Add an order by descending control to the query. * - * @param string $attribute - * + * @param string $attribute * @return $this */ public function orderByDesc($attribute) @@ -1026,11 +1045,20 @@ class Builder return $this->orderBy($attribute, 'desc'); } + /** + * Determine if the query has a sotr request control header. + * + * @return bool + */ + public function hasOrderBy() + { + return $this->hasControl(LDAP_CONTROL_SORTREQUEST); + } + /** * Adds a raw filter to the current query. * - * @param array|string $filters - * + * @param array|string $filters * @return $this */ public function rawFilter($filters = []) @@ -1047,8 +1075,7 @@ class Builder /** * Adds a nested 'and' filter to the current query. * - * @param Closure $closure - * + * @param Closure $closure * @return $this */ public function andFilter(Closure $closure) @@ -1063,8 +1090,7 @@ class Builder /** * Adds a nested 'or' filter to the current query. * - * @param Closure $closure - * + * @param Closure $closure * @return $this */ public function orFilter(Closure $closure) @@ -1079,8 +1105,7 @@ class Builder /** * Adds a nested 'not' filter to the current query. * - * @param Closure $closure - * + * @param Closure $closure * @return $this */ public function notFilter(Closure $closure) @@ -1095,12 +1120,11 @@ class Builder /** * Adds a where clause to the current query. * - * @param string|array $field - * @param string $operator - * @param string $value - * @param string $boolean - * @param bool $raw - * + * @param string|array $field + * @param string $operator + * @param string $value + * @param string $boolean + * @param bool $raw * @return $this * * @throws InvalidArgumentException @@ -1138,10 +1162,9 @@ class Builder /** * Prepare the value for being queried. * - * @param string $field - * @param string $value - * @param bool $raw - * + * @param string $field + * @param string $value + * @param bool $raw * @return string */ protected function prepareWhereValue($field, $value, $raw = false) @@ -1154,10 +1177,9 @@ class Builder * * Values given to this method are not escaped. * - * @param string|array $field - * @param string $operator - * @param string $value - * + * @param string|array $field + * @param string $operator + * @param string $value * @return $this */ public function whereRaw($field, $operator = null, $value = null) @@ -1168,9 +1190,8 @@ class Builder /** * Adds a 'where equals' clause to the current query. * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return $this */ public function whereEquals($field, $value) @@ -1181,9 +1202,8 @@ class Builder /** * Adds a 'where not equals' clause to the current query. * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return $this */ public function whereNotEquals($field, $value) @@ -1194,9 +1214,8 @@ class Builder /** * Adds a 'where approximately equals' clause to the current query. * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return $this */ public function whereApproximatelyEquals($field, $value) @@ -1207,8 +1226,7 @@ class Builder /** * Adds a 'where has' clause to the current query. * - * @param string $field - * + * @param string $field * @return $this */ public function whereHas($field) @@ -1219,8 +1237,7 @@ class Builder /** * Adds a 'where not has' clause to the current query. * - * @param string $field - * + * @param string $field * @return $this */ public function whereNotHas($field) @@ -1231,9 +1248,8 @@ class Builder /** * Adds a 'where contains' clause to the current query. * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return $this */ public function whereContains($field, $value) @@ -1244,9 +1260,8 @@ class Builder /** * Adds a 'where contains' clause to the current query. * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return $this */ public function whereNotContains($field, $value) @@ -1257,9 +1272,8 @@ class Builder /** * Query for entries that match any of the values provided for the given field. * - * @param string $field - * @param array $values - * + * @param string $field + * @param array $values * @return $this */ public function whereIn($field, array $values) @@ -1274,9 +1288,8 @@ class Builder /** * Adds a 'between' clause to the current query. * - * @param string $field - * @param array $values - * + * @param string $field + * @param array $values * @return $this */ public function whereBetween($field, array $values) @@ -1290,9 +1303,8 @@ class Builder /** * Adds a 'where starts with' clause to the current query. * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return $this */ public function whereStartsWith($field, $value) @@ -1303,9 +1315,8 @@ class Builder /** * Adds a 'where *not* starts with' clause to the current query. * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return $this */ public function whereNotStartsWith($field, $value) @@ -1316,9 +1327,8 @@ class Builder /** * Adds a 'where ends with' clause to the current query. * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return $this */ public function whereEndsWith($field, $value) @@ -1329,9 +1339,8 @@ class Builder /** * Adds a 'where *not* ends with' clause to the current query. * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return $this */ public function whereNotEndsWith($field, $value) @@ -1362,10 +1371,9 @@ class Builder /** * Add a server control to the query. * - * @param string $oid - * @param bool $isCritical - * @param mixed $value - * + * @param string $oid + * @param bool $isCritical + * @param mixed $value * @return $this */ public function addControl($oid, $isCritical = false, $value = null) @@ -1378,8 +1386,7 @@ class Builder /** * Determine if the server control exists on the query. * - * @param string $oid - * + * @param string $oid * @return bool */ public function hasControl($oid) @@ -1390,10 +1397,9 @@ class Builder /** * Adds an 'or where' clause to the current query. * - * @param array|string $field - * @param string|null $operator - * @param string|null $value - * + * @param array|string $field + * @param string|null $operator + * @param string|null $value * @return $this */ public function orWhere($field, $operator = null, $value = null) @@ -1406,10 +1412,9 @@ class Builder * * Values given to this method are not escaped. * - * @param string $field - * @param string $operator - * @param string $value - * + * @param string $field + * @param string $operator + * @param string $value * @return $this */ public function orWhereRaw($field, $operator = null, $value = null) @@ -1420,8 +1425,7 @@ class Builder /** * Adds an 'or where has' clause to the current query. * - * @param string $field - * + * @param string $field * @return $this */ public function orWhereHas($field) @@ -1432,8 +1436,7 @@ class Builder /** * Adds a 'where not has' clause to the current query. * - * @param string $field - * + * @param string $field * @return $this */ public function orWhereNotHas($field) @@ -1444,9 +1447,8 @@ class Builder /** * Adds an 'or where equals' clause to the current query. * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return $this */ public function orWhereEquals($field, $value) @@ -1457,9 +1459,8 @@ class Builder /** * Adds an 'or where not equals' clause to the current query. * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return $this */ public function orWhereNotEquals($field, $value) @@ -1470,9 +1471,8 @@ class Builder /** * Adds a 'or where approximately equals' clause to the current query. * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return $this */ public function orWhereApproximatelyEquals($field, $value) @@ -1483,9 +1483,8 @@ class Builder /** * Adds an 'or where contains' clause to the current query. * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return $this */ public function orWhereContains($field, $value) @@ -1496,9 +1495,8 @@ class Builder /** * Adds an 'or where *not* contains' clause to the current query. * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return $this */ public function orWhereNotContains($field, $value) @@ -1509,9 +1507,8 @@ class Builder /** * Adds an 'or where starts with' clause to the current query. * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return $this */ public function orWhereStartsWith($field, $value) @@ -1522,9 +1519,8 @@ class Builder /** * Adds an 'or where *not* starts with' clause to the current query. * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return $this */ public function orWhereNotStartsWith($field, $value) @@ -1535,9 +1531,8 @@ class Builder /** * Adds an 'or where ends with' clause to the current query. * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return $this */ public function orWhereEndsWith($field, $value) @@ -1548,9 +1543,8 @@ class Builder /** * Adds an 'or where *not* ends with' clause to the current query. * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return $this */ public function orWhereNotEndsWith($field, $value) @@ -1561,9 +1555,8 @@ class Builder /** * Adds a filter binding onto the current query. * - * @param string $type The type of filter to add. - * @param array $bindings The bindings of the filter. - * + * @param string $type The type of filter to add. + * @param array $bindings The bindings of the filter. * @return $this * * @throws InvalidArgumentException @@ -1591,8 +1584,7 @@ class Builder /** * Extract any missing required binding keys. * - * @param array $bindings - * + * @param array $bindings * @return array */ protected function missingBindingKeys($bindings) @@ -1704,8 +1696,7 @@ class Builder /** * Whether to mark the current query as nested. * - * @param bool $nested - * + * @param bool $nested * @return $this */ public function nested($nested = true) @@ -1720,9 +1711,8 @@ class Builder * * If flushing is enabled, the query cache will be flushed and then re-cached. * - * @param DateTimeInterface $until When to expire the query cache. - * @param bool $flush Whether to force-flush the query cache. - * + * @param DateTimeInterface $until When to expire the query cache. + * @param bool $flush Whether to force-flush the query cache. * @return $this */ public function cache(DateTimeInterface $until = null, $flush = false) @@ -1757,9 +1747,8 @@ class Builder /** * Insert an entry into the directory. * - * @param string $dn - * @param array $attributes - * + * @param string $dn + * @param array $attributes * @return bool * * @throws LdapRecordException @@ -1784,9 +1773,8 @@ class Builder /** * Create attributes on the entry in the directory. * - * @param string $dn - * @param array $attributes - * + * @param string $dn + * @param array $attributes * @return bool */ public function insertAttributes($dn, array $attributes) @@ -1799,9 +1787,8 @@ class Builder /** * Update the entry with the given modifications. * - * @param string $dn - * @param array $modifications - * + * @param string $dn + * @param array $modifications * @return bool */ public function update($dn, array $modifications) @@ -1814,9 +1801,8 @@ class Builder /** * Update an entries attribute in the directory. * - * @param string $dn - * @param array $attributes - * + * @param string $dn + * @param array $attributes * @return bool */ public function updateAttributes($dn, array $attributes) @@ -1829,8 +1815,7 @@ class Builder /** * Delete an entry from the directory. * - * @param string $dn - * + * @param string $dn * @return bool */ public function delete($dn) @@ -1843,9 +1828,8 @@ class Builder /** * Delete attributes on the entry in the directory. * - * @param string $dn - * @param array $attributes - * + * @param string $dn + * @param array $attributes * @return bool */ public function deleteAttributes($dn, array $attributes) @@ -1858,11 +1842,10 @@ class Builder /** * Rename an entry in the directory. * - * @param string $dn - * @param string $rdn - * @param string $newParentDn - * @param bool $deleteOldRdn - * + * @param string $dn + * @param string $rdn + * @param string $newParentDn + * @param bool $deleteOldRdn * @return bool */ public function rename($dn, $rdn, $newParentDn, $deleteOldRdn = true) @@ -1872,12 +1855,21 @@ class Builder }); } + /** + * Clone the query. + * + * @return static + */ + public function clone() + { + return clone $this; + } + /** * Handle dynamic method calls on the query builder. * - * @param string $method - * @param array $parameters - * + * @param string $method + * @param array $parameters * @return mixed * * @throws BadMethodCallException @@ -1901,9 +1893,8 @@ class Builder /** * Handles dynamic "where" clauses to the query. * - * @param string $method - * @param array $parameters - * + * @param string $method + * @param array $parameters * @return $this */ public function dynamicWhere($method, $parameters) @@ -1943,10 +1934,9 @@ class Builder /** * Adds an array of wheres to the current query. * - * @param array $wheres - * @param string $boolean - * @param bool $raw - * + * @param array $wheres + * @param string $boolean + * @param bool $raw * @return $this */ protected function addArrayOfWheres($wheres, $boolean, $raw) @@ -1975,11 +1965,10 @@ class Builder /** * Add a single dynamic where clause statement to the query. * - * @param string $segment - * @param string $connector - * @param array $parameters - * @param int $index - * + * @param string $segment + * @param string $connector + * @param array $parameters + * @param int $index * @return void */ protected function addDynamic($segment, $connector, $parameters, $index) @@ -1996,10 +1985,9 @@ class Builder /** * Logs the given executed query information by firing its query event. * - * @param Builder $query - * @param string $type - * @param null|float $time - * + * @param Builder $query + * @param string $type + * @param null|float $time * @return void */ protected function logQuery($query, $type, $time = null) @@ -2030,8 +2018,7 @@ class Builder /** * Fires the given query event. * - * @param QueryExecuted $event - * + * @param QueryExecuted $event * @return void */ protected function fireQueryEvent(QueryExecuted $event) @@ -2042,8 +2029,7 @@ class Builder /** * Get the elapsed time since a given starting point. * - * @param int $start - * + * @param int $start * @return float */ protected function getElapsedTime($start) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Cache.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Cache.php index dfbf8cd28..d6057bfb3 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Cache.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Cache.php @@ -21,7 +21,7 @@ class Cache /** * Constructor. * - * @param CacheInterface $store + * @param CacheInterface $store */ public function __construct(CacheInterface $store) { @@ -31,8 +31,7 @@ class Cache /** * Get an item from the cache. * - * @param string $key - * + * @param string $key * @return mixed */ public function get($key) @@ -43,10 +42,9 @@ class Cache /** * Store an item in the cache. * - * @param string $key - * @param mixed $value - * @param DateTimeInterface|DateInterval|int|null $ttl - * + * @param string $key + * @param mixed $value + * @param DateTimeInterface|DateInterval|int|null $ttl * @return bool */ public function put($key, $value, $ttl = null) @@ -63,10 +61,9 @@ class Cache /** * Get an item from the cache, or execute the given Closure and store the result. * - * @param string $key - * @param DateTimeInterface|DateInterval|int|null $ttl - * @param Closure $callback - * + * @param string $key + * @param DateTimeInterface|DateInterval|int|null $ttl + * @param Closure $callback * @return mixed */ public function remember($key, $ttl, Closure $callback) @@ -85,8 +82,7 @@ class Cache /** * Delete an item from the cache. * - * @param string $key - * + * @param string $key * @return bool */ public function delete($key) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Events/QueryExecuted.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Events/QueryExecuted.php index 4f17ea2a4..8ed8f835d 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Events/QueryExecuted.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Events/QueryExecuted.php @@ -23,8 +23,8 @@ class QueryExecuted /** * Constructor. * - * @param Builder $query - * @param null|float $time + * @param Builder $query + * @param null|float $time */ public function __construct(Builder $query, $time = null) { diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Filter/ConditionNode.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Filter/ConditionNode.php new file mode 100644 index 000000000..6203360c5 --- /dev/null +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Filter/ConditionNode.php @@ -0,0 +1,100 @@ +=', '<=', '~=', '=']; + + /** + * Constructor. + * + * @param string $filter + */ + public function __construct($filter) + { + $this->raw = $filter; + + [$this->attribute, $this->value] = $this->extractComponents($filter); + } + + /** + * Get the condition's attribute. + * + * @return string + */ + public function getAttribute() + { + return $this->attribute; + } + + /** + * Get the condition's operator. + * + * @return string + */ + public function getOperator() + { + return $this->operator; + } + + /** + * Get the condition's value. + * + * @return string + */ + public function getValue() + { + return $this->value; + } + + /** + * Extract the condition components from the filter. + * + * @param string $filter + * @return array + */ + protected function extractComponents($filter) + { + $components = Str::whenContains( + $filter, + $this->operators, + function ($operator, $filter) { + return explode($this->operator = $operator, $filter, 2); + }, + function ($filter) { + throw new ParserException("Invalid query condition. No operator found in [$filter]"); + }, + ); + + return $components; + } +} diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Filter/GroupNode.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Filter/GroupNode.php new file mode 100644 index 000000000..1a3596f3e --- /dev/null +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Filter/GroupNode.php @@ -0,0 +1,54 @@ +raw = $filter; + + $this->operator = substr($filter, 0, 1); + + $this->nodes = Parser::parse($filter); + } + + /** + * Get the group's operator. + * + * @return string + */ + public function getOperator() + { + return $this->operator; + } + + /** + * Get the group's sub-nodes. + * + * @return Node[] + */ + public function getNodes() + { + return $this->nodes; + } +} diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Filter/Node.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Filter/Node.php new file mode 100644 index 000000000..faf88d41f --- /dev/null +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Filter/Node.php @@ -0,0 +1,30 @@ +raw; + } +} diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Filter/Parser.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Filter/Parser.php new file mode 100644 index 000000000..7717ac522 --- /dev/null +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Filter/Parser.php @@ -0,0 +1,162 @@ + '"("', 1 => '")"']; + + throw new ParserException( + sprintf('Unclosed filter group. Missing %s parenthesis', $errors[$open <=> $close]) + ); + } + + return static::buildNodes( + array_map('trim', static::match($string)) + ); + } + + /** + * Perform a match for all filters in the string. + * + * @param string $string + * @return array + */ + protected static function match($string) + { + preg_match_all("/\((((?>[^()]+)|(?R))*)\)/", trim($string), $matches); + + return $matches[1] ?? []; + } + + /** + * Assemble the parsed nodes into a single filter. + * + * @param Node|Node[] $nodes + * @return string + */ + public static function assemble($nodes = []) + { + return array_reduce(Arr::wrap($nodes), function ($carry, Node $node) { + return $carry .= static::compileNode($node); + }); + } + + /** + * Assemble the node into its string based format. + * + * @param GroupNode|ConditionNode $node + * @return string + */ + protected static function compileNode(Node $node) + { + switch (true) { + case $node instanceof GroupNode: + return static::wrap($node->getOperator().static::assemble($node->getNodes())); + case $node instanceof ConditionNode: + return static::wrap($node->getAttribute().$node->getOperator().$node->getValue()); + default: + return $node->getRaw(); + } + } + + /** + * Build an array of nodes from the given filters. + * + * @param string[] $filters + * @return (ConditionNode|GroupNode)[] + * + * @throws ParserException + */ + protected static function buildNodes(array $filters = []) + { + return array_map(function ($filter) { + if (static::isWrapped($filter)) { + $filter = static::unwrap($filter); + } + + if (static::isGroup($filter) && ! Str::endsWith($filter, ')')) { + throw new ParserException(sprintf('Unclosed filter group [%s]', Str::afterLast($filter, ')'))); + } + + return static::isGroup($filter) + ? new GroupNode($filter) + : new ConditionNode($filter); + }, $filters); + } + + /** + * Count the open and close parenthesis of the sting. + * + * @param string $string + * @return array + */ + protected static function countParenthesis($string) + { + return [Str::substrCount($string, '('), Str::substrCount($string, ')')]; + } + + /** + * Wrap the value in parentheses. + * + * @param string $value + * @return string + */ + protected static function wrap($value) + { + return "($value)"; + } + + /** + * Recursively unwrwap the value from its parentheses. + * + * @param string $value + * @return string + */ + protected static function unwrap($value) + { + $nodes = static::parse($value); + + $unwrapped = Arr::first($nodes); + + return $unwrapped instanceof Node ? $unwrapped->getRaw() : $value; + } + + /** + * Determine if the filter is wrapped. + * + * @param string $filter + * @return bool + */ + protected static function isWrapped($filter) + { + return Str::startsWith($filter, '(') && Str::endsWith($filter, ')'); + } + + /** + * Determine if the filter is a group. + * + * @param string $filter + * @return bool + */ + protected static function isGroup($filter) + { + return Str::startsWith($filter, ['&', '|', '!']); + } +} diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Filter/ParserException.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Filter/ParserException.php new file mode 100644 index 000000000..68a4ca171 --- /dev/null +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Filter/ParserException.php @@ -0,0 +1,9 @@ +=', $count = 1) @@ -250,9 +239,8 @@ class Grammar * * Produces: (field=value) * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return string */ public function compileEquals($field, $value) @@ -265,9 +253,8 @@ class Grammar * * Produces: (!(field=value)) * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return string */ public function compileDoesNotEqual($field, $value) @@ -282,9 +269,8 @@ class Grammar * * Produces: (!(field=value)) * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return string */ public function compileDoesNotEqualAlias($field, $value) @@ -297,9 +283,8 @@ class Grammar * * Produces: (field>=value) * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return string */ public function compileGreaterThanOrEquals($field, $value) @@ -312,9 +297,8 @@ class Grammar * * Produces: (field<=value) * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return string */ public function compileLessThanOrEquals($field, $value) @@ -327,9 +311,8 @@ class Grammar * * Produces: (field~=value) * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return string */ public function compileApproximatelyEquals($field, $value) @@ -342,9 +325,8 @@ class Grammar * * Produces: (field=value*) * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return string */ public function compileStartsWith($field, $value) @@ -357,9 +339,8 @@ class Grammar * * Produces: (!(field=*value)) * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return string */ public function compileNotStartsWith($field, $value) @@ -374,9 +355,8 @@ class Grammar * * Produces: (field=*value) * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return string */ public function compileEndsWith($field, $value) @@ -389,9 +369,8 @@ class Grammar * * Produces: (!(field=value*)) * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return string */ public function compileNotEndsWith($field, $value) @@ -404,9 +383,8 @@ class Grammar * * Produces: (field=*value*) * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return string */ public function compileContains($field, $value) @@ -419,9 +397,8 @@ class Grammar * * Produces: (!(field=*value*)) * - * @param string $field - * @param string $value - * + * @param string $field + * @param string $value * @return string */ public function compileNotContains($field, $value) @@ -436,8 +413,7 @@ class Grammar * * Produces: (field=*) * - * @param string $field - * + * @param string $field * @return string */ public function compileHas($field) @@ -450,8 +426,7 @@ class Grammar * * Produces: (!(field=*)) * - * @param string $field - * + * @param string $field * @return string */ public function compileNotHas($field) @@ -466,8 +441,7 @@ class Grammar * * Produces: (&query) * - * @param string $query - * + * @param string $query * @return string */ public function compileAnd($query) @@ -480,8 +454,7 @@ class Grammar * * Produces: (|query) * - * @param string $query - * + * @param string $query * @return string */ public function compileOr($query) @@ -492,8 +465,7 @@ class Grammar /** * Wraps the inserted query inside an NOT operator. * - * @param string $query - * + * @param string $query * @return string */ public function compileNot($query) @@ -504,8 +476,7 @@ class Grammar /** * Assembles a single where query. * - * @param array $where - * + * @param array $where * @return string * * @throws UnexpectedValueException @@ -520,8 +491,7 @@ class Grammar /** * Make the compile method name for the operator. * - * @param string $operator - * + * @param string $operator * @return string * * @throws UnexpectedValueException @@ -538,8 +508,7 @@ class Grammar /** * Determine if the operator exists. * - * @param string $operator - * + * @param string $operator * @return bool */ protected function operatorExists($operator) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/InteractsWithTime.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/InteractsWithTime.php index 1562ec0a4..e8024c033 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/InteractsWithTime.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/InteractsWithTime.php @@ -16,8 +16,7 @@ trait InteractsWithTime /** * Get the number of seconds until the given DateTime. * - * @param DateTimeInterface|DateInterval|int $delay - * + * @param DateTimeInterface|DateInterval|int $delay * @return int */ protected function secondsUntil($delay) @@ -32,8 +31,7 @@ trait InteractsWithTime /** * Get the "available at" UNIX timestamp. * - * @param DateTimeInterface|DateInterval|int $delay - * + * @param DateTimeInterface|DateInterval|int $delay * @return int */ protected function availableAt($delay = 0) @@ -48,8 +46,7 @@ trait InteractsWithTime /** * If the given value is an interval, convert it to a DateTime instance. * - * @param DateTimeInterface|DateInterval|int $delay - * + * @param DateTimeInterface|DateInterval|int $delay * @return DateTimeInterface|int */ protected function parseDateInterval($delay) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Model/ActiveDirectoryBuilder.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Model/ActiveDirectoryBuilder.php index c3911d80e..3b0e96f79 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Model/ActiveDirectoryBuilder.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Model/ActiveDirectoryBuilder.php @@ -12,9 +12,8 @@ class ActiveDirectoryBuilder extends Builder /** * Finds a record by its Object SID. * - * @param string $sid - * @param array|string $columns - * + * @param string $sid + * @param array|string $columns * @return \LdapRecord\Models\ActiveDirectory\Entry|static|null */ public function findBySid($sid, $columns = []) @@ -31,9 +30,8 @@ class ActiveDirectoryBuilder extends Builder * * Fails upon no records returned. * - * @param string $sid - * @param array|string $columns - * + * @param string $sid + * @param array|string $columns * @return \LdapRecord\Models\ActiveDirectory\Entry|static * * @throws ModelNotFoundException @@ -70,9 +68,8 @@ class ActiveDirectoryBuilder extends Builder /** * Adds a 'where member' filter to the current query. * - * @param string $dn - * @param bool $nested - * + * @param string $dn + * @param bool $nested * @return $this */ public function whereMember($dn, $nested = false) @@ -85,9 +82,8 @@ class ActiveDirectoryBuilder extends Builder /** * Adds an 'or where member' filter to the current query. * - * @param string $dn - * @param bool $nested - * + * @param string $dn + * @param bool $nested * @return $this */ public function orWhereMember($dn, $nested = false) @@ -100,9 +96,8 @@ class ActiveDirectoryBuilder extends Builder /** * Adds a 'where member of' filter to the current query. * - * @param string $dn - * @param bool $nested - * + * @param string $dn + * @param bool $nested * @return $this */ public function whereMemberOf($dn, $nested = false) @@ -115,9 +110,8 @@ class ActiveDirectoryBuilder extends Builder /** * Adds a 'where not member of' filter to the current query. * - * @param string $dn - * @param bool $nested - * + * @param string $dn + * @param bool $nested * @return $this */ public function whereNotMemberof($dn, $nested = false) @@ -130,9 +124,8 @@ class ActiveDirectoryBuilder extends Builder /** * Adds an 'or where member of' filter to the current query. * - * @param string $dn - * @param bool $nested - * + * @param string $dn + * @param bool $nested * @return $this */ public function orWhereMemberOf($dn, $nested = false) @@ -145,9 +138,8 @@ class ActiveDirectoryBuilder extends Builder /** * Adds a 'or where not member of' filter to the current query. * - * @param string $dn - * @param bool $nested - * + * @param string $dn + * @param bool $nested * @return $this */ public function orWhereNotMemberof($dn, $nested = false) @@ -160,9 +152,8 @@ class ActiveDirectoryBuilder extends Builder /** * Adds a 'where manager' filter to the current query. * - * @param string $dn - * @param bool $nested - * + * @param string $dn + * @param bool $nested * @return $this */ public function whereManager($dn, $nested = false) @@ -175,9 +166,8 @@ class ActiveDirectoryBuilder extends Builder /** * Adds a 'where not manager' filter to the current query. * - * @param string $dn - * @param bool $nested - * + * @param string $dn + * @param bool $nested * @return $this */ public function whereNotManager($dn, $nested = false) @@ -190,9 +180,8 @@ class ActiveDirectoryBuilder extends Builder /** * Adds an 'or where manager' filter to the current query. * - * @param string $dn - * @param bool $nested - * + * @param string $dn + * @param bool $nested * @return $this */ public function orWhereManager($dn, $nested = false) @@ -205,9 +194,8 @@ class ActiveDirectoryBuilder extends Builder /** * Adds an 'or where not manager' filter to the current query. * - * @param string $dn - * @param bool $nested - * + * @param string $dn + * @param bool $nested * @return $this */ public function orWhereNotManager($dn, $nested = false) @@ -220,10 +208,9 @@ class ActiveDirectoryBuilder extends Builder /** * Execute the callback with a nested match attribute. * - * @param Closure $callback - * @param string $attribute - * @param bool $nested - * + * @param Closure $callback + * @param string $attribute + * @param bool $nested * @return $this */ protected function nestedMatchQuery(Closure $callback, $attribute, $nested = false) @@ -236,8 +223,7 @@ class ActiveDirectoryBuilder extends Builder /** * Make a "nested match" filter attribute for querying descendants. * - * @param string $attribute - * + * @param string $attribute * @return string */ protected function makeNestedMatchAttribute($attribute) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Model/Builder.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Model/Builder.php index 234dd0ad7..a6886ea96 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Model/Builder.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Model/Builder.php @@ -44,9 +44,8 @@ class Builder extends BaseBuilder /** * Dynamically handle calls into the query instance. * - * @param string $method - * @param array $parameters - * + * @param string $method + * @param array $parameters * @return mixed */ public function __call($method, $parameters) @@ -61,9 +60,8 @@ class Builder extends BaseBuilder /** * Apply the given scope on the current builder instance. * - * @param callable $scope - * @param array $parameters - * + * @param callable $scope + * @param array $parameters * @return mixed */ protected function callScope(callable $scope, $parameters = []) @@ -91,8 +89,7 @@ class Builder extends BaseBuilder /** * Set the model instance for the model being queried. * - * @param Model $model - * + * @param Model $model * @return $this */ public function setModel(Model $model) @@ -115,8 +112,7 @@ class Builder extends BaseBuilder /** * Get a new model query builder instance. * - * @param string|null $baseDn - * + * @param string|null $baseDn * @return static */ public function newInstance($baseDn = null) @@ -127,9 +123,8 @@ class Builder extends BaseBuilder /** * Finds a model by its distinguished name. * - * @param array|string $dn - * @param array|string|string[] $columns - * + * @param array|string $dn + * @param array|string|string[] $columns * @return Model|\LdapRecord\Query\Collection|static|null */ public function find($dn, $columns = ['*']) @@ -142,9 +137,8 @@ class Builder extends BaseBuilder /** * Finds a record using ambiguous name resolution. * - * @param string|array $value - * @param array|string $columns - * + * @param string|array $value + * @param array|string $columns * @return Model|\LdapRecord\Query\Collection|static|null */ public function findByAnr($value, $columns = ['*']) @@ -178,9 +172,8 @@ class Builder extends BaseBuilder * * If a record is not found, an exception is thrown. * - * @param string $value - * @param array|string $columns - * + * @param string $value + * @param array|string $columns * @return Model * * @throws ModelNotFoundException @@ -197,8 +190,8 @@ class Builder extends BaseBuilder /** * Throws a not found exception. * - * @param string $query - * @param string $dn + * @param string $query + * @param string $dn * * @throws ModelNotFoundException */ @@ -210,9 +203,8 @@ class Builder extends BaseBuilder /** * Finds multiple records using ambiguous name resolution. * - * @param array $values - * @param array $columns - * + * @param array $values + * @param array $columns * @return \LdapRecord\Query\Collection */ public function findManyByAnr(array $values = [], $columns = ['*']) @@ -233,8 +225,7 @@ class Builder extends BaseBuilder /** * Creates an ANR equivalent query for LDAP distributions that do not support ANR. * - * @param string $value - * + * @param string $value * @return $this */ protected function prepareAnrEquivalentQuery($value) @@ -249,9 +240,8 @@ class Builder extends BaseBuilder /** * Finds a record by its string GUID. * - * @param string $guid - * @param array|string $columns - * + * @param string $guid + * @param array|string $columns * @return Model|static|null */ public function findByGuid($guid, $columns = ['*']) @@ -268,9 +258,8 @@ class Builder extends BaseBuilder * * Fails upon no records returned. * - * @param string $guid - * @param array|string $columns - * + * @param string $guid + * @param array|string $columns * @return Model|static * * @throws ModelNotFoundException @@ -299,8 +288,7 @@ class Builder extends BaseBuilder /** * Apply the query scopes and execute the callback. * - * @param Closure $callback - * + * @param Closure $callback * @return mixed */ protected function afterScopes(Closure $callback) @@ -339,9 +327,8 @@ class Builder extends BaseBuilder /** * Register a new global scope. * - * @param string $identifier - * @param Scope|\Closure $scope - * + * @param string $identifier + * @param Scope|\Closure $scope * @return $this */ public function withGlobalScope($identifier, $scope) @@ -354,8 +341,7 @@ class Builder extends BaseBuilder /** * Remove a registered global scope. * - * @param Scope|string $scope - * + * @param Scope|string $scope * @return $this */ public function withoutGlobalScope($scope) @@ -374,8 +360,7 @@ class Builder extends BaseBuilder /** * Remove all or passed registered global scopes. * - * @param array|null $scopes - * + * @param array|null $scopes * @return $this */ public function withoutGlobalScopes(array $scopes = null) @@ -414,8 +399,7 @@ class Builder extends BaseBuilder /** * Processes and converts the given LDAP results into models. * - * @param array $results - * + * @param array $results * @return \LdapRecord\Query\Collection */ protected function process(array $results) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/ObjectNotFoundException.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/ObjectNotFoundException.php index c22563cfa..99c2e85e3 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/ObjectNotFoundException.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/ObjectNotFoundException.php @@ -23,9 +23,8 @@ class ObjectNotFoundException extends LdapRecordException /** * Create a new exception for the executed filter. * - * @param string $query - * @param ?string $baseDn - * + * @param string $query + * @param ?string $baseDn * @return static */ public static function forQuery($query, $baseDn = null) @@ -36,9 +35,8 @@ class ObjectNotFoundException extends LdapRecordException /** * Set the query that was used. * - * @param string $query - * @param string|null $baseDn - * + * @param string $query + * @param string|null $baseDn * @return $this */ public function setQuery($query, $baseDn = null) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Pagination/AbstractPaginator.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Pagination/AbstractPaginator.php index e2b048242..11e2dc547 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Pagination/AbstractPaginator.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Pagination/AbstractPaginator.php @@ -38,7 +38,7 @@ abstract class AbstractPaginator /** * Constructor. * - * @param Builder $query + * @param Builder $query */ public function __construct(Builder $query, $filter, $perPage, $isCritical) { @@ -51,8 +51,7 @@ abstract class AbstractPaginator /** * Execute the pagination request. * - * @param LdapInterface $ldap - * + * @param LdapInterface $ldap * @return array */ public function execute(LdapInterface $ldap) @@ -107,8 +106,7 @@ abstract class AbstractPaginator /** * Apply the server controls. * - * @param LdapInterface $ldap - * + * @param LdapInterface $ldap * @return void */ abstract protected function applyServerControls(LdapInterface $ldap); @@ -116,8 +114,7 @@ abstract class AbstractPaginator /** * Reset the server controls. * - * @param LdapInterface $ldap - * + * @param LdapInterface $ldap * @return void */ abstract protected function resetServerControls(LdapInterface $ldap); @@ -125,9 +122,8 @@ abstract class AbstractPaginator /** * Update the server controls. * - * @param LdapInterface $ldap - * @param resource $resource - * + * @param LdapInterface $ldap + * @param resource $resource * @return void */ abstract protected function updateServerControls(LdapInterface $ldap, $resource); diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Pagination/LazyPaginator.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Pagination/LazyPaginator.php index b9df77e4e..8b12d526c 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Pagination/LazyPaginator.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Pagination/LazyPaginator.php @@ -9,8 +9,7 @@ class LazyPaginator extends Paginator /** * Execute the pagination request. * - * @param LdapInterface $ldap - * + * @param LdapInterface $ldap * @return \Generator */ public function execute(LdapInterface $ldap) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Slice.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Slice.php new file mode 100644 index 000000000..12faa5bd1 --- /dev/null +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Query/Slice.php @@ -0,0 +1,283 @@ +items = $items; + $this->total = $total; + $this->perPage = $perPage; + $this->lastPage = max((int) ceil($total / $perPage), 1); + $this->currentPage = $currentPage ?? 1; + } + + /** + * Get the slice of items being paginated. + * + * @return \LdapRecord\Query\Collection|array + */ + public function items() + { + return $this->items; + } + + /** + * Get the total number of items being paginated. + * + * @return int + */ + public function total() + { + return $this->total; + } + + /** + * Get the number of items shown per page. + * + * @return int + */ + public function perPage() + { + return $this->perPage; + } + + /** + * Determine if there are more items in the data source. + * + * @return bool + */ + public function hasMorePages() + { + return $this->currentPage() < $this->lastPage(); + } + + /** + * Determine if there are enough items to split into multiple pages. + * + * @return bool + */ + public function hasPages() + { + return $this->currentPage() != 1 || $this->hasMorePages(); + } + + /** + * Determine if the paginator is on the first page. + * + * @return bool + */ + public function onFirstPage() + { + return $this->currentPage() <= 1; + } + + /** + * Determine if the paginator is on the last page. + * + * @return bool + */ + public function onLastPage() + { + return ! $this->hasMorePages(); + } + + /** + * Get the current page. + * + * @return int + */ + public function currentPage() + { + return $this->currentPage; + } + + /** + * Get the last page. + * + * @return int + */ + public function lastPage() + { + return $this->lastPage; + } + + /** + * Get an iterator for the items. + * + * @return \ArrayIterator + */ + #[\ReturnTypeWillChange] + public function getIterator() + { + return new ArrayIterator($this->items); + } + + /** + * Determine if the list of items is empty. + * + * @return bool + */ + public function isEmpty() + { + return empty($this->items); + } + + /** + * Determine if the list of items is not empty. + * + * @return bool + */ + public function isNotEmpty() + { + return ! $this->isEmpty(); + } + + /** + * Get the number of items for the current page. + * + * @return int + */ + #[\ReturnTypeWillChange] + public function count() + { + return count($this->items); + } + + /** + * Determine if the given item exists. + * + * @param mixed $key + * @return bool + */ + #[\ReturnTypeWillChange] + public function offsetExists($key) + { + return array_key_exists($key, $this->items); + } + + /** + * Get the item at the given offset. + * + * @param mixed $key + * @return mixed + */ + #[\ReturnTypeWillChange] + public function offsetGet($key) + { + return $this->items[$key] ?? null; + } + + /** + * Set the item at the given offset. + * + * @param mixed $key + * @param mixed $value + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetSet($key, $value) + { + $this->items[$key] = $value; + } + + /** + * Unset the item at the given key. + * + * @param mixed $key + * @return void + */ + #[\ReturnTypeWillChange] + public function offsetUnset($key) + { + unset($this->items[$key]); + } + + /** + * Convert the object into something JSON serializable. + * + * @return array + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return $this->toArray(); + } + + /** + * Get the arrayable items. + * + * @return array + */ + public function getArrayableItems() + { + return $this->items instanceof Collection + ? $this->items->all() + : $this->items; + } + + /** + * Get the instance as an array. + * + * @return array + */ + public function toArray() + { + return [ + 'current_page' => $this->currentPage(), + 'data' => $this->getArrayableItems(), + 'last_page' => $this->lastPage(), + 'per_page' => $this->perPage(), + 'total' => $this->total(), + ]; + } +} diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Support/Arr.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Support/Arr.php index 8fa87a2b3..7475859ae 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Support/Arr.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Support/Arr.php @@ -9,8 +9,7 @@ class Arr /** * Determine whether the given value is array accessible. * - * @param mixed $value - * + * @param mixed $value * @return bool */ public static function accessible($value) @@ -21,9 +20,8 @@ class Arr /** * Determine if the given key exists in the provided array. * - * @param \ArrayAccess|array $array - * @param string|int $key - * + * @param \ArrayAccess|array $array + * @param string|int $key * @return bool */ public static function exists($array, $key) @@ -38,8 +36,7 @@ class Arr /** * If the given value is not an array and not null, wrap it in one. * - * @param mixed $value - * + * @param mixed $value * @return array */ public static function wrap($value) @@ -54,10 +51,9 @@ class Arr /** * Return the first element in an array passing a given truth test. * - * @param iterable $array - * @param callable|null $callback - * @param mixed $default - * + * @param iterable $array + * @param callable|null $callback + * @param mixed $default * @return mixed */ public static function first($array, callable $callback = null, $default = null) @@ -84,10 +80,9 @@ class Arr /** * Return the last element in an array passing a given truth test. * - * @param array $array - * @param callable|null $callback - * @param mixed $default - * + * @param array $array + * @param callable|null $callback + * @param mixed $default * @return mixed */ public static function last($array, callable $callback = null, $default = null) @@ -102,10 +97,9 @@ class Arr /** * Get an item from an array using "dot" notation. * - * @param ArrayAccess|array $array - * @param string|int|null $key - * @param mixed $default - * + * @param ArrayAccess|array $array + * @param string|int|null $key + * @param mixed $default * @return mixed */ public static function get($array, $key, $default = null) @@ -122,7 +116,7 @@ class Arr return $array[$key]; } - if (strpos($key, '.') === false) { + if (str_contains($key, '.')) { return $array[$key] ?? Helpers::value($default); } diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Support/Helpers.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Support/Helpers.php index a55d1d22a..ab217d6ff 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Support/Helpers.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Support/Helpers.php @@ -9,12 +9,12 @@ class Helpers /** * Return the default value of the given value. * - * @param mixed $value - * + * @param mixed $value + * @param mixed $args * @return mixed */ - public static function value($value) + public static function value($value, ...$args) { - return $value instanceof Closure ? $value() : $value; + return $value instanceof Closure ? $value(...$args) : $value; } } diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Support/Str.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Support/Str.php new file mode 100644 index 000000000..820834e21 --- /dev/null +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Support/Str.php @@ -0,0 +1,129 @@ + $arg) { - if (! $arg instanceof Constraint) { - $args[$key] = new IsEqual($arg); + $this->args = array_map(function ($arg) { + if ($arg instanceof Closure) { + return new Callback($arg); } - } - $this->args = $args; + if (! $arg instanceof Constraint) { + return new IsEqual($arg); + } + + return $arg; + }, is_array($args) ? $args : func_get_args()); return $this; } @@ -114,8 +117,7 @@ class LdapExpectation /** * Set the expected value to return. * - * @param mixed $value - * + * @param mixed $value * @return $this */ public function andReturn($value) @@ -128,10 +130,9 @@ class LdapExpectation /** * The error message to return from the expectation. * - * @param int $code - * @param string $error - * @param string $diagnosticMessage - * + * @param int $code + * @param string $error + * @param string $diagnosticMessage * @return $this */ public function andReturnError($code = 1, $error = '', $diagnosticMessage = '') @@ -148,8 +149,7 @@ class LdapExpectation /** * Set the expected exception to throw. * - * @param string|\Exception|LdapRecordException $exception - * + * @param string|\Exception|LdapRecordException $exception * @return $this */ public function andThrow($exception) @@ -186,8 +186,7 @@ class LdapExpectation /** * Set the expectation to be called the given number of times. * - * @param int $count - * + * @param int $count * @return $this */ public function times($count = 1) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Testing/LdapFake.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Testing/LdapFake.php index 00470e14a..5a0003549 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Testing/LdapFake.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Testing/LdapFake.php @@ -47,8 +47,7 @@ class LdapFake implements LdapInterface /** * Create a new expected operation. * - * @param string $method - * + * @param string $method * @return LdapExpectation */ public static function operation($method) @@ -59,8 +58,7 @@ class LdapFake implements LdapInterface /** * Set the user that will pass binding. * - * @param string $dn - * + * @param string $dn * @return $this */ public function shouldAuthenticateWith($dn) @@ -73,8 +71,7 @@ class LdapFake implements LdapInterface /** * Add an LDAP method expectation. * - * @param LdapExpectation|array $expectations - * + * @param LdapExpectation|array $expectations * @return $this */ public function expect($expectations = []) @@ -105,8 +102,7 @@ class LdapFake implements LdapInterface /** * Determine if the method has any expectations. * - * @param string $method - * + * @param string $method * @return bool */ public function hasExpectations($method) @@ -117,8 +113,7 @@ class LdapFake implements LdapInterface /** * Get expectations by method. * - * @param string $method - * + * @param string $method * @return LdapExpectation[]|mixed */ public function getExpectations($method) @@ -129,9 +124,8 @@ class LdapFake implements LdapInterface /** * Remove an expectation by method and key. * - * @param string $method - * @param int $key - * + * @param string $method + * @param int $key * @return void */ public function removeExpectation($method, $key) @@ -142,8 +136,7 @@ class LdapFake implements LdapInterface /** * Set the error number of a failed bind attempt. * - * @param int $number - * + * @param int $number * @return $this */ public function shouldReturnErrorNumber($number = 1) @@ -156,8 +149,7 @@ class LdapFake implements LdapInterface /** * Set the last error of a failed bind attempt. * - * @param string $message - * + * @param string $message * @return $this */ public function shouldReturnError($message = '') @@ -170,8 +162,7 @@ class LdapFake implements LdapInterface /** * Set the diagnostic message of a failed bind attempt. * - * @param string $message - * + * @param string $message * @return $this */ public function shouldReturnDiagnosticMessage($message = '') @@ -261,6 +252,16 @@ class LdapFake implements LdapInterface : $this->bound; } + /** + * @inheritdoc + */ + public function getHost() + { + return $this->hasExpectations('getHost') + ? $this->resolveExpectation('getHost') + : $this->host; + } + /** * @inheritdoc */ @@ -454,9 +455,8 @@ class LdapFake implements LdapInterface /** * Resolve the methods expectations. * - * @param string $method - * @param array $args - * + * @param string $method + * @param array $args * @return mixed * * @throws Exception @@ -489,8 +489,7 @@ class LdapFake implements LdapInterface /** * Apply the expectation error to the fake. * - * @param LdapExpectation $expectation - * + * @param LdapExpectation $expectation * @return void */ protected function applyExpectationError(LdapExpectation $expectation) @@ -503,10 +502,9 @@ class LdapFake implements LdapInterface /** * Assert that the expected arguments match the operations arguments. * - * @param string $method - * @param Constraint[] $expectedArgs - * @param array $methodArgs - * + * @param string $method + * @param Constraint[] $expectedArgs + * @param array $methodArgs * @return void */ protected function assertMethodArgumentsMatch($method, array $expectedArgs = [], array $methodArgs = []) diff --git a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Utilities.php b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Utilities.php index 01d55c797..c4f5190d8 100644 --- a/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Utilities.php +++ b/data/web/inc/lib/vendor/directorytree/ldaprecord/src/Utilities.php @@ -10,14 +10,13 @@ class Utilities * This will also decode hex characters into their true * UTF-8 representation embedded inside the DN as well. * - * @param string $dn - * @param bool $removeAttributePrefixes - * + * @param string $dn + * @param bool $removeAttributePrefixes * @return array|false */ public static function explodeDn($dn, $removeAttributePrefixes = true) { - $dn = ldap_explode_dn($dn, ($removeAttributePrefixes ? 1 : 0)); + $dn = ldap_explode_dn($dn, $removeAttributePrefixes ? 1 : 0); if (! is_array($dn)) { return false; @@ -39,8 +38,7 @@ class Utilities /** * Un-escapes a hexadecimal string into its original string representation. * - * @param string $value - * + * @param string $value * @return string */ public static function unescape($value) @@ -58,8 +56,7 @@ class Utilities * @see https://github.com/ChadSikorra * @see https://stackoverflow.com/questions/39533560/php-ldap-get-user-sid * - * @param string $value The Binary SID - * + * @param string $value The Binary SID * @return string|null */ public static function binarySidToString($value) @@ -106,8 +103,7 @@ class Utilities /** * Convert a binary GUID to a string GUID. * - * @param string $binGuid - * + * @param string $binGuid * @return string|null */ public static function binaryGuidToString($binGuid) @@ -130,8 +126,7 @@ class Utilities /** * Converts a string GUID to it's hex variant. * - * @param string $string - * + * @param string $string * @return string */ public static function stringGuidToHex($string) @@ -149,21 +144,19 @@ class Utilities * Round a Windows timestamp down to seconds and remove * the seconds between 1601-01-01 and 1970-01-01. * - * @param float $windowsTime - * - * @return float + * @param int $windowsTime + * @return int */ public static function convertWindowsTimeToUnixTime($windowsTime) { - return round($windowsTime / 10000000) - 11644473600; + return (int) (round($windowsTime / 10000000) - 11644473600); } /** * Convert a Unix timestamp to Windows timestamp. * - * @param float $unixTime - * - * @return float + * @param int $unixTime + * @return int */ public static function convertUnixTimeToWindowsTime($unixTime) { @@ -173,8 +166,7 @@ class Utilities /** * Validates that the inserted string is an object SID. * - * @param string $sid - * + * @param string $sid * @return bool */ public static function isValidSid($sid) @@ -185,8 +177,7 @@ class Utilities /** * Validates that the inserted string is an object GUID. * - * @param string $guid - * + * @param string $guid * @return bool */ public static function isValidGuid($guid) diff --git a/data/web/inc/lib/vendor/firebase/php-jwt/CHANGELOG.md b/data/web/inc/lib/vendor/firebase/php-jwt/CHANGELOG.md new file mode 100644 index 000000000..35e97fe86 --- /dev/null +++ b/data/web/inc/lib/vendor/firebase/php-jwt/CHANGELOG.md @@ -0,0 +1,117 @@ +# Changelog + +## [6.5.0](https://github.com/firebase/php-jwt/compare/v6.4.0...v6.5.0) (2023-05-12) + + +### Bug Fixes + +* allow KID of '0' ([#505](https://github.com/firebase/php-jwt/issues/505)) ([9dc46a9](https://github.com/firebase/php-jwt/commit/9dc46a9c3e5801294249cfd2554c5363c9f9326a)) + + +### Miscellaneous Chores + +* drop support for PHP 7.3 ([#495](https://github.com/firebase/php-jwt/issues/495)) + +## [6.4.0](https://github.com/firebase/php-jwt/compare/v6.3.2...v6.4.0) (2023-02-08) + + +### Features + +* add support for W3C ES256K ([#462](https://github.com/firebase/php-jwt/issues/462)) ([213924f](https://github.com/firebase/php-jwt/commit/213924f51936291fbbca99158b11bd4ae56c2c95)) +* improve caching by only decoding jwks when necessary ([#486](https://github.com/firebase/php-jwt/issues/486)) ([78d3ed1](https://github.com/firebase/php-jwt/commit/78d3ed1073553f7d0bbffa6c2010009a0d483d5c)) + +## [6.3.2](https://github.com/firebase/php-jwt/compare/v6.3.1...v6.3.2) (2022-11-01) + + +### Bug Fixes + +* check kid before using as array index ([bad1b04](https://github.com/firebase/php-jwt/commit/bad1b040d0c736bbf86814c6b5ae614f517cf7bd)) + +## [6.3.1](https://github.com/firebase/php-jwt/compare/v6.3.0...v6.3.1) (2022-11-01) + + +### Bug Fixes + +* casing of GET for PSR compat ([#451](https://github.com/firebase/php-jwt/issues/451)) ([60b52b7](https://github.com/firebase/php-jwt/commit/60b52b71978790eafcf3b95cfbd83db0439e8d22)) +* string interpolation format for php 8.2 ([#446](https://github.com/firebase/php-jwt/issues/446)) ([2e07d8a](https://github.com/firebase/php-jwt/commit/2e07d8a1524d12b69b110ad649f17461d068b8f2)) + +## 6.3.0 / 2022-07-15 + + - Added ES256 support to JWK parsing ([#399](https://github.com/firebase/php-jwt/pull/399)) + - Fixed potential caching error in `CachedKeySet` by caching jwks as strings ([#435](https://github.com/firebase/php-jwt/pull/435)) + +## 6.2.0 / 2022-05-14 + + - Added `CachedKeySet` ([#397](https://github.com/firebase/php-jwt/pull/397)) + - Added `$defaultAlg` parameter to `JWT::parseKey` and `JWT::parseKeySet` ([#426](https://github.com/firebase/php-jwt/pull/426)). + +## 6.1.0 / 2022-03-23 + + - Drop support for PHP 5.3, 5.4, 5.5, 5.6, and 7.0 + - Add parameter typing and return types where possible + +## 6.0.0 / 2022-01-24 + + - **Backwards-Compatibility Breaking Changes**: See the [Release Notes](https://github.com/firebase/php-jwt/releases/tag/v6.0.0) for more information. + - New Key object to prevent key/algorithm type confusion (#365) + - Add JWK support (#273) + - Add ES256 support (#256) + - Add ES384 support (#324) + - Add Ed25519 support (#343) + +## 5.0.0 / 2017-06-26 +- Support RS384 and RS512. + See [#117](https://github.com/firebase/php-jwt/pull/117). Thanks [@joostfaassen](https://github.com/joostfaassen)! +- Add an example for RS256 openssl. + See [#125](https://github.com/firebase/php-jwt/pull/125). Thanks [@akeeman](https://github.com/akeeman)! +- Detect invalid Base64 encoding in signature. + See [#162](https://github.com/firebase/php-jwt/pull/162). Thanks [@psignoret](https://github.com/psignoret)! +- Update `JWT::verify` to handle OpenSSL errors. + See [#159](https://github.com/firebase/php-jwt/pull/159). Thanks [@bshaffer](https://github.com/bshaffer)! +- Add `array` type hinting to `decode` method + See [#101](https://github.com/firebase/php-jwt/pull/101). Thanks [@hywak](https://github.com/hywak)! +- Add all JSON error types. + See [#110](https://github.com/firebase/php-jwt/pull/110). Thanks [@gbalduzzi](https://github.com/gbalduzzi)! +- Bugfix 'kid' not in given key list. + See [#129](https://github.com/firebase/php-jwt/pull/129). Thanks [@stampycode](https://github.com/stampycode)! +- Miscellaneous cleanup, documentation and test fixes. + See [#107](https://github.com/firebase/php-jwt/pull/107), [#115](https://github.com/firebase/php-jwt/pull/115), + [#160](https://github.com/firebase/php-jwt/pull/160), [#161](https://github.com/firebase/php-jwt/pull/161), and + [#165](https://github.com/firebase/php-jwt/pull/165). Thanks [@akeeman](https://github.com/akeeman), + [@chinedufn](https://github.com/chinedufn), and [@bshaffer](https://github.com/bshaffer)! + +## 4.0.0 / 2016-07-17 +- Add support for late static binding. See [#88](https://github.com/firebase/php-jwt/pull/88) for details. Thanks to [@chappy84](https://github.com/chappy84)! +- Use static `$timestamp` instead of `time()` to improve unit testing. See [#93](https://github.com/firebase/php-jwt/pull/93) for details. Thanks to [@josephmcdermott](https://github.com/josephmcdermott)! +- Fixes to exceptions classes. See [#81](https://github.com/firebase/php-jwt/pull/81) for details. Thanks to [@Maks3w](https://github.com/Maks3w)! +- Fixes to PHPDoc. See [#76](https://github.com/firebase/php-jwt/pull/76) for details. Thanks to [@akeeman](https://github.com/akeeman)! + +## 3.0.0 / 2015-07-22 +- Minimum PHP version updated from `5.2.0` to `5.3.0`. +- Add `\Firebase\JWT` namespace. See +[#59](https://github.com/firebase/php-jwt/pull/59) for details. Thanks to +[@Dashron](https://github.com/Dashron)! +- Require a non-empty key to decode and verify a JWT. See +[#60](https://github.com/firebase/php-jwt/pull/60) for details. Thanks to +[@sjones608](https://github.com/sjones608)! +- Cleaner documentation blocks in the code. See +[#62](https://github.com/firebase/php-jwt/pull/62) for details. Thanks to +[@johanderuijter](https://github.com/johanderuijter)! + +## 2.2.0 / 2015-06-22 +- Add support for adding custom, optional JWT headers to `JWT::encode()`. See +[#53](https://github.com/firebase/php-jwt/pull/53/files) for details. Thanks to +[@mcocaro](https://github.com/mcocaro)! + +## 2.1.0 / 2015-05-20 +- Add support for adding a leeway to `JWT:decode()` that accounts for clock skew +between signing and verifying entities. Thanks to [@lcabral](https://github.com/lcabral)! +- Add support for passing an object implementing the `ArrayAccess` interface for +`$keys` argument in `JWT::decode()`. Thanks to [@aztech-dev](https://github.com/aztech-dev)! + +## 2.0.0 / 2015-04-01 +- **Note**: It is strongly recommended that you update to > v2.0.0 to address + known security vulnerabilities in prior versions when both symmetric and + asymmetric keys are used together. +- Update signature for `JWT::decode(...)` to require an array of supported + algorithms to use when verifying token signatures. diff --git a/data/web/inc/lib/vendor/yubico/u2flib-server/COPYING b/data/web/inc/lib/vendor/firebase/php-jwt/LICENSE similarity index 83% rename from data/web/inc/lib/vendor/yubico/u2flib-server/COPYING rename to data/web/inc/lib/vendor/firebase/php-jwt/LICENSE index 427c91756..11c014665 100644 --- a/data/web/inc/lib/vendor/yubico/u2flib-server/COPYING +++ b/data/web/inc/lib/vendor/firebase/php-jwt/LICENSE @@ -1,9 +1,9 @@ -Copyright (c) 2014 Yubico AB +Copyright (c) 2011, Neuman Vong + All rights reserved. Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: +modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. @@ -13,6 +13,10 @@ met: disclaimer in the documentation and/or other materials provided with the distribution. + * Neither the name of the copyright holder nor the names of other + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR diff --git a/data/web/inc/lib/vendor/firebase/php-jwt/README.md b/data/web/inc/lib/vendor/firebase/php-jwt/README.md new file mode 100644 index 000000000..f03826673 --- /dev/null +++ b/data/web/inc/lib/vendor/firebase/php-jwt/README.md @@ -0,0 +1,419 @@ +![Build Status](https://github.com/firebase/php-jwt/actions/workflows/tests.yml/badge.svg) +[![Latest Stable Version](https://poser.pugx.org/firebase/php-jwt/v/stable)](https://packagist.org/packages/firebase/php-jwt) +[![Total Downloads](https://poser.pugx.org/firebase/php-jwt/downloads)](https://packagist.org/packages/firebase/php-jwt) +[![License](https://poser.pugx.org/firebase/php-jwt/license)](https://packagist.org/packages/firebase/php-jwt) + +PHP-JWT +======= +A simple library to encode and decode JSON Web Tokens (JWT) in PHP, conforming to [RFC 7519](https://tools.ietf.org/html/rfc7519). + +Installation +------------ + +Use composer to manage your dependencies and download PHP-JWT: + +```bash +composer require firebase/php-jwt +``` + +Optionally, install the `paragonie/sodium_compat` package from composer if your +php is < 7.2 or does not have libsodium installed: + +```bash +composer require paragonie/sodium_compat +``` + +Example +------- +```php +use Firebase\JWT\JWT; +use Firebase\JWT\Key; + +$key = 'example_key'; +$payload = [ + 'iss' => 'http://example.org', + 'aud' => 'http://example.com', + 'iat' => 1356999524, + 'nbf' => 1357000000 +]; + +/** + * IMPORTANT: + * You must specify supported algorithms for your application. See + * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40 + * for a list of spec-compliant algorithms. + */ +$jwt = JWT::encode($payload, $key, 'HS256'); +$decoded = JWT::decode($jwt, new Key($key, 'HS256')); + +print_r($decoded); + +/* + NOTE: This will now be an object instead of an associative array. To get + an associative array, you will need to cast it as such: +*/ + +$decoded_array = (array) $decoded; + +/** + * You can add a leeway to account for when there is a clock skew times between + * the signing and verifying servers. It is recommended that this leeway should + * not be bigger than a few minutes. + * + * Source: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#nbfDef + */ +JWT::$leeway = 60; // $leeway in seconds +$decoded = JWT::decode($jwt, new Key($key, 'HS256')); +``` +Example encode/decode headers +------- +Decoding the JWT headers without verifying the JWT first is NOT recommended, and is not supported by +this library. This is because without verifying the JWT, the header values could have been tampered with. +Any value pulled from an unverified header should be treated as if it could be any string sent in from an +attacker. If this is something you still want to do in your application for whatever reason, it's possible to +decode the header values manually simply by calling `json_decode` and `base64_decode` on the JWT +header part: +```php +use Firebase\JWT\JWT; + +$key = 'example_key'; +$payload = [ + 'iss' => 'http://example.org', + 'aud' => 'http://example.com', + 'iat' => 1356999524, + 'nbf' => 1357000000 +]; + +$headers = [ + 'x-forwarded-for' => 'www.google.com' +]; + +// Encode headers in the JWT string +$jwt = JWT::encode($payload, $key, 'HS256', null, $headers); + +// Decode headers from the JWT string WITHOUT validation +// **IMPORTANT**: This operation is vulnerable to attacks, as the JWT has not yet been verified. +// These headers could be any value sent by an attacker. +list($headersB64, $payloadB64, $sig) = explode('.', $jwt); +$decoded = json_decode(base64_decode($headersB64), true); + +print_r($decoded); +``` +Example with RS256 (openssl) +---------------------------- +```php +use Firebase\JWT\JWT; +use Firebase\JWT\Key; + +$privateKey = << 'example.org', + 'aud' => 'example.com', + 'iat' => 1356999524, + 'nbf' => 1357000000 +]; + +$jwt = JWT::encode($payload, $privateKey, 'RS256'); +echo "Encode:\n" . print_r($jwt, true) . "\n"; + +$decoded = JWT::decode($jwt, new Key($publicKey, 'RS256')); + +/* + NOTE: This will now be an object instead of an associative array. To get + an associative array, you will need to cast it as such: +*/ + +$decoded_array = (array) $decoded; +echo "Decode:\n" . print_r($decoded_array, true) . "\n"; +``` + +Example with a passphrase +------------------------- + +```php +use Firebase\JWT\JWT; +use Firebase\JWT\Key; + +// Your passphrase +$passphrase = '[YOUR_PASSPHRASE]'; + +// Your private key file with passphrase +// Can be generated with "ssh-keygen -t rsa -m pem" +$privateKeyFile = '/path/to/key-with-passphrase.pem'; + +// Create a private key of type "resource" +$privateKey = openssl_pkey_get_private( + file_get_contents($privateKeyFile), + $passphrase +); + +$payload = [ + 'iss' => 'example.org', + 'aud' => 'example.com', + 'iat' => 1356999524, + 'nbf' => 1357000000 +]; + +$jwt = JWT::encode($payload, $privateKey, 'RS256'); +echo "Encode:\n" . print_r($jwt, true) . "\n"; + +// Get public key from the private key, or pull from from a file. +$publicKey = openssl_pkey_get_details($privateKey)['key']; + +$decoded = JWT::decode($jwt, new Key($publicKey, 'RS256')); +echo "Decode:\n" . print_r((array) $decoded, true) . "\n"; +``` + +Example with EdDSA (libsodium and Ed25519 signature) +---------------------------- +```php +use Firebase\JWT\JWT; +use Firebase\JWT\Key; + +// Public and private keys are expected to be Base64 encoded. The last +// non-empty line is used so that keys can be generated with +// sodium_crypto_sign_keypair(). The secret keys generated by other tools may +// need to be adjusted to match the input expected by libsodium. + +$keyPair = sodium_crypto_sign_keypair(); + +$privateKey = base64_encode(sodium_crypto_sign_secretkey($keyPair)); + +$publicKey = base64_encode(sodium_crypto_sign_publickey($keyPair)); + +$payload = [ + 'iss' => 'example.org', + 'aud' => 'example.com', + 'iat' => 1356999524, + 'nbf' => 1357000000 +]; + +$jwt = JWT::encode($payload, $privateKey, 'EdDSA'); +echo "Encode:\n" . print_r($jwt, true) . "\n"; + +$decoded = JWT::decode($jwt, new Key($publicKey, 'EdDSA')); +echo "Decode:\n" . print_r((array) $decoded, true) . "\n"; +```` + +Example with multiple keys +-------------------------- +```php +use Firebase\JWT\JWT; +use Firebase\JWT\Key; + +// Example RSA keys from previous example +// $privateKey1 = '...'; +// $publicKey1 = '...'; + +// Example EdDSA keys from previous example +// $privateKey2 = '...'; +// $publicKey2 = '...'; + +$payload = [ + 'iss' => 'example.org', + 'aud' => 'example.com', + 'iat' => 1356999524, + 'nbf' => 1357000000 +]; + +$jwt1 = JWT::encode($payload, $privateKey1, 'RS256', 'kid1'); +$jwt2 = JWT::encode($payload, $privateKey2, 'EdDSA', 'kid2'); +echo "Encode 1:\n" . print_r($jwt1, true) . "\n"; +echo "Encode 2:\n" . print_r($jwt2, true) . "\n"; + +$keys = [ + 'kid1' => new Key($publicKey1, 'RS256'), + 'kid2' => new Key($publicKey2, 'EdDSA'), +]; + +$decoded1 = JWT::decode($jwt1, $keys); +$decoded2 = JWT::decode($jwt2, $keys); + +echo "Decode 1:\n" . print_r((array) $decoded1, true) . "\n"; +echo "Decode 2:\n" . print_r((array) $decoded2, true) . "\n"; +``` + +Using JWKs +---------- + +```php +use Firebase\JWT\JWK; +use Firebase\JWT\JWT; + +// Set of keys. The "keys" key is required. For example, the JSON response to +// this endpoint: https://www.gstatic.com/iap/verify/public_key-jwk +$jwks = ['keys' => []]; + +// JWK::parseKeySet($jwks) returns an associative array of **kid** to Firebase\JWT\Key +// objects. Pass this as the second parameter to JWT::decode. +JWT::decode($payload, JWK::parseKeySet($jwks)); +``` + +Using Cached Key Sets +--------------------- + +The `CachedKeySet` class can be used to fetch and cache JWKS (JSON Web Key Sets) from a public URI. +This has the following advantages: + +1. The results are cached for performance. +2. If an unrecognized key is requested, the cache is refreshed, to accomodate for key rotation. +3. If rate limiting is enabled, the JWKS URI will not make more than 10 requests a second. + +```php +use Firebase\JWT\CachedKeySet; +use Firebase\JWT\JWT; + +// The URI for the JWKS you wish to cache the results from +$jwksUri = 'https://www.gstatic.com/iap/verify/public_key-jwk'; + +// Create an HTTP client (can be any PSR-7 compatible HTTP client) +$httpClient = new GuzzleHttp\Client(); + +// Create an HTTP request factory (can be any PSR-17 compatible HTTP request factory) +$httpFactory = new GuzzleHttp\Psr\HttpFactory(); + +// Create a cache item pool (can be any PSR-6 compatible cache item pool) +$cacheItemPool = Phpfastcache\CacheManager::getInstance('files'); + +$keySet = new CachedKeySet( + $jwksUri, + $httpClient, + $httpFactory, + $cacheItemPool, + null, // $expiresAfter int seconds to set the JWKS to expire + true // $rateLimit true to enable rate limit of 10 RPS on lookup of invalid keys +); + +$jwt = 'eyJhbGci...'; // Some JWT signed by a key from the $jwkUri above +$decoded = JWT::decode($jwt, $keySet); +``` + +Miscellaneous +------------- + +#### Exception Handling + +When a call to `JWT::decode` is invalid, it will throw one of the following exceptions: + +```php +use Firebase\JWT\JWT; +use Firebase\JWT\SignatureInvalidException; +use Firebase\JWT\BeforeValidException; +use Firebase\JWT\ExpiredException; +use DomainException; +use InvalidArgumentException; +use UnexpectedValueException; + +try { + $decoded = JWT::decode($payload, $keys); +} catch (InvalidArgumentException $e) { + // provided key/key-array is empty or malformed. +} catch (DomainException $e) { + // provided algorithm is unsupported OR + // provided key is invalid OR + // unknown error thrown in openSSL or libsodium OR + // libsodium is required but not available. +} catch (SignatureInvalidException $e) { + // provided JWT signature verification failed. +} catch (BeforeValidException $e) { + // provided JWT is trying to be used before "nbf" claim OR + // provided JWT is trying to be used before "iat" claim. +} catch (ExpiredException $e) { + // provided JWT is trying to be used after "exp" claim. +} catch (UnexpectedValueException $e) { + // provided JWT is malformed OR + // provided JWT is missing an algorithm / using an unsupported algorithm OR + // provided JWT algorithm does not match provided key OR + // provided key ID in key/key-array is empty or invalid. +} +``` + +All exceptions in the `Firebase\JWT` namespace extend `UnexpectedValueException`, and can be simplified +like this: + +```php +try { + $decoded = JWT::decode($payload, $keys); +} catch (LogicException $e) { + // errors having to do with environmental setup or malformed JWT Keys +} catch (UnexpectedValueException $e) { + // errors having to do with JWT signature and claims +} +``` + +#### Casting to array + +The return value of `JWT::decode` is the generic PHP object `stdClass`. If you'd like to handle with arrays +instead, you can do the following: + +```php +// return type is stdClass +$decoded = JWT::decode($payload, $keys); + +// cast to array +$decoded = json_decode(json_encode($decoded), true); +``` + +Tests +----- +Run the tests using phpunit: + +```bash +$ pear install PHPUnit +$ phpunit --configuration phpunit.xml.dist +PHPUnit 3.7.10 by Sebastian Bergmann. +..... +Time: 0 seconds, Memory: 2.50Mb +OK (5 tests, 5 assertions) +``` + +New Lines in private keys +----- + +If your private key contains `\n` characters, be sure to wrap it in double quotes `""` +and not single quotes `''` in order to properly interpret the escaped characters. + +License +------- +[3-Clause BSD](http://opensource.org/licenses/BSD-3-Clause). diff --git a/data/web/inc/lib/vendor/firebase/php-jwt/composer.json b/data/web/inc/lib/vendor/firebase/php-jwt/composer.json new file mode 100644 index 000000000..e23dfe378 --- /dev/null +++ b/data/web/inc/lib/vendor/firebase/php-jwt/composer.json @@ -0,0 +1,42 @@ +{ + "name": "firebase/php-jwt", + "description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.", + "homepage": "https://github.com/firebase/php-jwt", + "keywords": [ + "php", + "jwt" + ], + "authors": [ + { + "name": "Neuman Vong", + "email": "neuman+pear@twilio.com", + "role": "Developer" + }, + { + "name": "Anant Narayanan", + "email": "anant@php.net", + "role": "Developer" + } + ], + "license": "BSD-3-Clause", + "require": { + "php": "^7.4||^8.0" + }, + "suggest": { + "paragonie/sodium_compat": "Support EdDSA (Ed25519) signatures when libsodium is not present", + "ext-sodium": "Support EdDSA (Ed25519) signatures" + }, + "autoload": { + "psr-4": { + "Firebase\\JWT\\": "src" + } + }, + "require-dev": { + "guzzlehttp/guzzle": "^6.5||^7.4", + "phpspec/prophecy-phpunit": "^2.0", + "phpunit/phpunit": "^9.5", + "psr/cache": "^1.0||^2.0", + "psr/http-client": "^1.0", + "psr/http-factory": "^1.0" + } +} diff --git a/data/web/inc/lib/vendor/firebase/php-jwt/src/BeforeValidException.php b/data/web/inc/lib/vendor/firebase/php-jwt/src/BeforeValidException.php new file mode 100644 index 000000000..c147852b9 --- /dev/null +++ b/data/web/inc/lib/vendor/firebase/php-jwt/src/BeforeValidException.php @@ -0,0 +1,7 @@ + + */ +class CachedKeySet implements ArrayAccess +{ + /** + * @var string + */ + private $jwksUri; + /** + * @var ClientInterface + */ + private $httpClient; + /** + * @var RequestFactoryInterface + */ + private $httpFactory; + /** + * @var CacheItemPoolInterface + */ + private $cache; + /** + * @var ?int + */ + private $expiresAfter; + /** + * @var ?CacheItemInterface + */ + private $cacheItem; + /** + * @var array> + */ + private $keySet; + /** + * @var string + */ + private $cacheKey; + /** + * @var string + */ + private $cacheKeyPrefix = 'jwks'; + /** + * @var int + */ + private $maxKeyLength = 64; + /** + * @var bool + */ + private $rateLimit; + /** + * @var string + */ + private $rateLimitCacheKey; + /** + * @var int + */ + private $maxCallsPerMinute = 10; + /** + * @var string|null + */ + private $defaultAlg; + + public function __construct( + string $jwksUri, + ClientInterface $httpClient, + RequestFactoryInterface $httpFactory, + CacheItemPoolInterface $cache, + int $expiresAfter = null, + bool $rateLimit = false, + string $defaultAlg = null + ) { + $this->jwksUri = $jwksUri; + $this->httpClient = $httpClient; + $this->httpFactory = $httpFactory; + $this->cache = $cache; + $this->expiresAfter = $expiresAfter; + $this->rateLimit = $rateLimit; + $this->defaultAlg = $defaultAlg; + $this->setCacheKeys(); + } + + /** + * @param string $keyId + * @return Key + */ + public function offsetGet($keyId): Key + { + if (!$this->keyIdExists($keyId)) { + throw new OutOfBoundsException('Key ID not found'); + } + return JWK::parseKey($this->keySet[$keyId], $this->defaultAlg); + } + + /** + * @param string $keyId + * @return bool + */ + public function offsetExists($keyId): bool + { + return $this->keyIdExists($keyId); + } + + /** + * @param string $offset + * @param Key $value + */ + public function offsetSet($offset, $value): void + { + throw new LogicException('Method not implemented'); + } + + /** + * @param string $offset + */ + public function offsetUnset($offset): void + { + throw new LogicException('Method not implemented'); + } + + /** + * @return array + */ + private function formatJwksForCache(string $jwks): array + { + $jwks = json_decode($jwks, true); + + if (!isset($jwks['keys'])) { + throw new UnexpectedValueException('"keys" member must exist in the JWK Set'); + } + + if (empty($jwks['keys'])) { + throw new InvalidArgumentException('JWK Set did not contain any keys'); + } + + $keys = []; + foreach ($jwks['keys'] as $k => $v) { + $kid = isset($v['kid']) ? $v['kid'] : $k; + $keys[(string) $kid] = $v; + } + + return $keys; + } + + private function keyIdExists(string $keyId): bool + { + if (null === $this->keySet) { + $item = $this->getCacheItem(); + // Try to load keys from cache + if ($item->isHit()) { + // item found! retrieve it + $this->keySet = $item->get(); + // If the cached item is a string, the JWKS response was cached (previous behavior). + // Parse this into expected format array instead. + if (\is_string($this->keySet)) { + $this->keySet = $this->formatJwksForCache($this->keySet); + } + } + } + + if (!isset($this->keySet[$keyId])) { + if ($this->rateLimitExceeded()) { + return false; + } + $request = $this->httpFactory->createRequest('GET', $this->jwksUri); + $jwksResponse = $this->httpClient->sendRequest($request); + $this->keySet = $this->formatJwksForCache((string) $jwksResponse->getBody()); + + if (!isset($this->keySet[$keyId])) { + return false; + } + + $item = $this->getCacheItem(); + $item->set($this->keySet); + if ($this->expiresAfter) { + $item->expiresAfter($this->expiresAfter); + } + $this->cache->save($item); + } + + return true; + } + + private function rateLimitExceeded(): bool + { + if (!$this->rateLimit) { + return false; + } + + $cacheItem = $this->cache->getItem($this->rateLimitCacheKey); + if (!$cacheItem->isHit()) { + $cacheItem->expiresAfter(1); // # of calls are cached each minute + } + + $callsPerMinute = (int) $cacheItem->get(); + if (++$callsPerMinute > $this->maxCallsPerMinute) { + return true; + } + $cacheItem->set($callsPerMinute); + $this->cache->save($cacheItem); + return false; + } + + private function getCacheItem(): CacheItemInterface + { + if (\is_null($this->cacheItem)) { + $this->cacheItem = $this->cache->getItem($this->cacheKey); + } + + return $this->cacheItem; + } + + private function setCacheKeys(): void + { + if (empty($this->jwksUri)) { + throw new RuntimeException('JWKS URI is empty'); + } + + // ensure we do not have illegal characters + $key = preg_replace('|[^a-zA-Z0-9_\.!]|', '', $this->jwksUri); + + // add prefix + $key = $this->cacheKeyPrefix . $key; + + // Hash keys if they exceed $maxKeyLength of 64 + if (\strlen($key) > $this->maxKeyLength) { + $key = substr(hash('sha256', $key), 0, $this->maxKeyLength); + } + + $this->cacheKey = $key; + + if ($this->rateLimit) { + // add prefix + $rateLimitKey = $this->cacheKeyPrefix . 'ratelimit' . $key; + + // Hash keys if they exceed $maxKeyLength of 64 + if (\strlen($rateLimitKey) > $this->maxKeyLength) { + $rateLimitKey = substr(hash('sha256', $rateLimitKey), 0, $this->maxKeyLength); + } + + $this->rateLimitCacheKey = $rateLimitKey; + } + } +} diff --git a/data/web/inc/lib/vendor/firebase/php-jwt/src/ExpiredException.php b/data/web/inc/lib/vendor/firebase/php-jwt/src/ExpiredException.php new file mode 100644 index 000000000..81ba52d43 --- /dev/null +++ b/data/web/inc/lib/vendor/firebase/php-jwt/src/ExpiredException.php @@ -0,0 +1,7 @@ + + * @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD + * @link https://github.com/firebase/php-jwt + */ +class JWK +{ + private const OID = '1.2.840.10045.2.1'; + private const ASN1_OBJECT_IDENTIFIER = 0x06; + private const ASN1_SEQUENCE = 0x10; // also defined in JWT + private const ASN1_BIT_STRING = 0x03; + private const EC_CURVES = [ + 'P-256' => '1.2.840.10045.3.1.7', // Len: 64 + 'secp256k1' => '1.3.132.0.10', // Len: 64 + // 'P-384' => '1.3.132.0.34', // Len: 96 (not yet supported) + // 'P-521' => '1.3.132.0.35', // Len: 132 (not supported) + ]; + + /** + * Parse a set of JWK keys + * + * @param array $jwks The JSON Web Key Set as an associative array + * @param string $defaultAlg The algorithm for the Key object if "alg" is not set in the + * JSON Web Key Set + * + * @return array An associative array of key IDs (kid) to Key objects + * + * @throws InvalidArgumentException Provided JWK Set is empty + * @throws UnexpectedValueException Provided JWK Set was invalid + * @throws DomainException OpenSSL failure + * + * @uses parseKey + */ + public static function parseKeySet(array $jwks, string $defaultAlg = null): array + { + $keys = []; + + if (!isset($jwks['keys'])) { + throw new UnexpectedValueException('"keys" member must exist in the JWK Set'); + } + + if (empty($jwks['keys'])) { + throw new InvalidArgumentException('JWK Set did not contain any keys'); + } + + foreach ($jwks['keys'] as $k => $v) { + $kid = isset($v['kid']) ? $v['kid'] : $k; + if ($key = self::parseKey($v, $defaultAlg)) { + $keys[(string) $kid] = $key; + } + } + + if (0 === \count($keys)) { + throw new UnexpectedValueException('No supported algorithms found in JWK Set'); + } + + return $keys; + } + + /** + * Parse a JWK key + * + * @param array $jwk An individual JWK + * @param string $defaultAlg The algorithm for the Key object if "alg" is not set in the + * JSON Web Key Set + * + * @return Key The key object for the JWK + * + * @throws InvalidArgumentException Provided JWK is empty + * @throws UnexpectedValueException Provided JWK was invalid + * @throws DomainException OpenSSL failure + * + * @uses createPemFromModulusAndExponent + */ + public static function parseKey(array $jwk, string $defaultAlg = null): ?Key + { + if (empty($jwk)) { + throw new InvalidArgumentException('JWK must not be empty'); + } + + if (!isset($jwk['kty'])) { + throw new UnexpectedValueException('JWK must contain a "kty" parameter'); + } + + if (!isset($jwk['alg'])) { + if (\is_null($defaultAlg)) { + // The "alg" parameter is optional in a KTY, but an algorithm is required + // for parsing in this library. Use the $defaultAlg parameter when parsing the + // key set in order to prevent this error. + // @see https://datatracker.ietf.org/doc/html/rfc7517#section-4.4 + throw new UnexpectedValueException('JWK must contain an "alg" parameter'); + } + $jwk['alg'] = $defaultAlg; + } + + switch ($jwk['kty']) { + case 'RSA': + if (!empty($jwk['d'])) { + throw new UnexpectedValueException('RSA private keys are not supported'); + } + if (!isset($jwk['n']) || !isset($jwk['e'])) { + throw new UnexpectedValueException('RSA keys must contain values for both "n" and "e"'); + } + + $pem = self::createPemFromModulusAndExponent($jwk['n'], $jwk['e']); + $publicKey = \openssl_pkey_get_public($pem); + if (false === $publicKey) { + throw new DomainException( + 'OpenSSL error: ' . \openssl_error_string() + ); + } + return new Key($publicKey, $jwk['alg']); + case 'EC': + if (isset($jwk['d'])) { + // The key is actually a private key + throw new UnexpectedValueException('Key data must be for a public key'); + } + + if (empty($jwk['crv'])) { + throw new UnexpectedValueException('crv not set'); + } + + if (!isset(self::EC_CURVES[$jwk['crv']])) { + throw new DomainException('Unrecognised or unsupported EC curve'); + } + + if (empty($jwk['x']) || empty($jwk['y'])) { + throw new UnexpectedValueException('x and y not set'); + } + + $publicKey = self::createPemFromCrvAndXYCoordinates($jwk['crv'], $jwk['x'], $jwk['y']); + return new Key($publicKey, $jwk['alg']); + default: + // Currently only RSA is supported + break; + } + + return null; + } + + /** + * Converts the EC JWK values to pem format. + * + * @param string $crv The EC curve (only P-256 is supported) + * @param string $x The EC x-coordinate + * @param string $y The EC y-coordinate + * + * @return string + */ + private static function createPemFromCrvAndXYCoordinates(string $crv, string $x, string $y): string + { + $pem = + self::encodeDER( + self::ASN1_SEQUENCE, + self::encodeDER( + self::ASN1_SEQUENCE, + self::encodeDER( + self::ASN1_OBJECT_IDENTIFIER, + self::encodeOID(self::OID) + ) + . self::encodeDER( + self::ASN1_OBJECT_IDENTIFIER, + self::encodeOID(self::EC_CURVES[$crv]) + ) + ) . + self::encodeDER( + self::ASN1_BIT_STRING, + \chr(0x00) . \chr(0x04) + . JWT::urlsafeB64Decode($x) + . JWT::urlsafeB64Decode($y) + ) + ); + + return sprintf( + "-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----\n", + wordwrap(base64_encode($pem), 64, "\n", true) + ); + } + + /** + * Create a public key represented in PEM format from RSA modulus and exponent information + * + * @param string $n The RSA modulus encoded in Base64 + * @param string $e The RSA exponent encoded in Base64 + * + * @return string The RSA public key represented in PEM format + * + * @uses encodeLength + */ + private static function createPemFromModulusAndExponent( + string $n, + string $e + ): string { + $mod = JWT::urlsafeB64Decode($n); + $exp = JWT::urlsafeB64Decode($e); + + $modulus = \pack('Ca*a*', 2, self::encodeLength(\strlen($mod)), $mod); + $publicExponent = \pack('Ca*a*', 2, self::encodeLength(\strlen($exp)), $exp); + + $rsaPublicKey = \pack( + 'Ca*a*a*', + 48, + self::encodeLength(\strlen($modulus) + \strlen($publicExponent)), + $modulus, + $publicExponent + ); + + // sequence(oid(1.2.840.113549.1.1.1), null)) = rsaEncryption. + $rsaOID = \pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA + $rsaPublicKey = \chr(0) . $rsaPublicKey; + $rsaPublicKey = \chr(3) . self::encodeLength(\strlen($rsaPublicKey)) . $rsaPublicKey; + + $rsaPublicKey = \pack( + 'Ca*a*', + 48, + self::encodeLength(\strlen($rsaOID . $rsaPublicKey)), + $rsaOID . $rsaPublicKey + ); + + return "-----BEGIN PUBLIC KEY-----\r\n" . + \chunk_split(\base64_encode($rsaPublicKey), 64) . + '-----END PUBLIC KEY-----'; + } + + /** + * DER-encode the length + * + * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See + * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information. + * + * @param int $length + * @return string + */ + private static function encodeLength(int $length): string + { + if ($length <= 0x7F) { + return \chr($length); + } + + $temp = \ltrim(\pack('N', $length), \chr(0)); + + return \pack('Ca*', 0x80 | \strlen($temp), $temp); + } + + /** + * Encodes a value into a DER object. + * Also defined in Firebase\JWT\JWT + * + * @param int $type DER tag + * @param string $value the value to encode + * @return string the encoded object + */ + private static function encodeDER(int $type, string $value): string + { + $tag_header = 0; + if ($type === self::ASN1_SEQUENCE) { + $tag_header |= 0x20; + } + + // Type + $der = \chr($tag_header | $type); + + // Length + $der .= \chr(\strlen($value)); + + return $der . $value; + } + + /** + * Encodes a string into a DER-encoded OID. + * + * @param string $oid the OID string + * @return string the binary DER-encoded OID + */ + private static function encodeOID(string $oid): string + { + $octets = explode('.', $oid); + + // Get the first octet + $first = (int) array_shift($octets); + $second = (int) array_shift($octets); + $oid = \chr($first * 40 + $second); + + // Iterate over subsequent octets + foreach ($octets as $octet) { + if ($octet == 0) { + $oid .= \chr(0x00); + continue; + } + $bin = ''; + + while ($octet) { + $bin .= \chr(0x80 | ($octet & 0x7f)); + $octet >>= 7; + } + $bin[0] = $bin[0] & \chr(0x7f); + + // Convert to big endian if necessary + if (pack('V', 65534) == pack('L', 65534)) { + $oid .= strrev($bin); + } else { + $oid .= $bin; + } + } + + return $oid; + } +} diff --git a/data/web/inc/lib/vendor/firebase/php-jwt/src/JWT.php b/data/web/inc/lib/vendor/firebase/php-jwt/src/JWT.php new file mode 100644 index 000000000..c83ff0990 --- /dev/null +++ b/data/web/inc/lib/vendor/firebase/php-jwt/src/JWT.php @@ -0,0 +1,642 @@ + + * @author Anant Narayanan + * @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD + * @link https://github.com/firebase/php-jwt + */ +class JWT +{ + private const ASN1_INTEGER = 0x02; + private const ASN1_SEQUENCE = 0x10; + private const ASN1_BIT_STRING = 0x03; + + /** + * When checking nbf, iat or expiration times, + * we want to provide some extra leeway time to + * account for clock skew. + * + * @var int + */ + public static $leeway = 0; + + /** + * Allow the current timestamp to be specified. + * Useful for fixing a value within unit testing. + * Will default to PHP time() value if null. + * + * @var ?int + */ + public static $timestamp = null; + + /** + * @var array + */ + public static $supported_algs = [ + 'ES384' => ['openssl', 'SHA384'], + 'ES256' => ['openssl', 'SHA256'], + 'ES256K' => ['openssl', 'SHA256'], + 'HS256' => ['hash_hmac', 'SHA256'], + 'HS384' => ['hash_hmac', 'SHA384'], + 'HS512' => ['hash_hmac', 'SHA512'], + 'RS256' => ['openssl', 'SHA256'], + 'RS384' => ['openssl', 'SHA384'], + 'RS512' => ['openssl', 'SHA512'], + 'EdDSA' => ['sodium_crypto', 'EdDSA'], + ]; + + /** + * Decodes a JWT string into a PHP object. + * + * @param string $jwt The JWT + * @param Key|ArrayAccess|array $keyOrKeyArray The Key or associative array of key IDs + * (kid) to Key objects. + * If the algorithm used is asymmetric, this is + * the public key. + * Each Key object contains an algorithm and + * matching key. + * Supported algorithms are 'ES384','ES256', + * 'HS256', 'HS384', 'HS512', 'RS256', 'RS384' + * and 'RS512'. + * + * @return stdClass The JWT's payload as a PHP object + * + * @throws InvalidArgumentException Provided key/key-array was empty or malformed + * @throws DomainException Provided JWT is malformed + * @throws UnexpectedValueException Provided JWT was invalid + * @throws SignatureInvalidException Provided JWT was invalid because the signature verification failed + * @throws BeforeValidException Provided JWT is trying to be used before it's eligible as defined by 'nbf' + * @throws BeforeValidException Provided JWT is trying to be used before it's been created as defined by 'iat' + * @throws ExpiredException Provided JWT has since expired, as defined by the 'exp' claim + * + * @uses jsonDecode + * @uses urlsafeB64Decode + */ + public static function decode( + string $jwt, + $keyOrKeyArray + ): stdClass { + // Validate JWT + $timestamp = \is_null(static::$timestamp) ? \time() : static::$timestamp; + + if (empty($keyOrKeyArray)) { + throw new InvalidArgumentException('Key may not be empty'); + } + $tks = \explode('.', $jwt); + if (\count($tks) !== 3) { + throw new UnexpectedValueException('Wrong number of segments'); + } + list($headb64, $bodyb64, $cryptob64) = $tks; + $headerRaw = static::urlsafeB64Decode($headb64); + if (null === ($header = static::jsonDecode($headerRaw))) { + throw new UnexpectedValueException('Invalid header encoding'); + } + $payloadRaw = static::urlsafeB64Decode($bodyb64); + if (null === ($payload = static::jsonDecode($payloadRaw))) { + throw new UnexpectedValueException('Invalid claims encoding'); + } + if (\is_array($payload)) { + // prevent PHP Fatal Error in edge-cases when payload is empty array + $payload = (object) $payload; + } + if (!$payload instanceof stdClass) { + throw new UnexpectedValueException('Payload must be a JSON object'); + } + $sig = static::urlsafeB64Decode($cryptob64); + if (empty($header->alg)) { + throw new UnexpectedValueException('Empty algorithm'); + } + if (empty(static::$supported_algs[$header->alg])) { + throw new UnexpectedValueException('Algorithm not supported'); + } + + $key = self::getKey($keyOrKeyArray, property_exists($header, 'kid') ? $header->kid : null); + + // Check the algorithm + if (!self::constantTimeEquals($key->getAlgorithm(), $header->alg)) { + // See issue #351 + throw new UnexpectedValueException('Incorrect key for this algorithm'); + } + if (\in_array($header->alg, ['ES256', 'ES256K', 'ES384'], true)) { + // OpenSSL expects an ASN.1 DER sequence for ES256/ES256K/ES384 signatures + $sig = self::signatureToDER($sig); + } + if (!self::verify("{$headb64}.{$bodyb64}", $sig, $key->getKeyMaterial(), $header->alg)) { + throw new SignatureInvalidException('Signature verification failed'); + } + + // Check the nbf if it is defined. This is the time that the + // token can actually be used. If it's not yet that time, abort. + if (isset($payload->nbf) && $payload->nbf > ($timestamp + static::$leeway)) { + throw new BeforeValidException( + 'Cannot handle token prior to ' . \date(DateTime::ISO8601, $payload->nbf) + ); + } + + // Check that this token has been created before 'now'. This prevents + // using tokens that have been created for later use (and haven't + // correctly used the nbf claim). + if (isset($payload->iat) && $payload->iat > ($timestamp + static::$leeway)) { + throw new BeforeValidException( + 'Cannot handle token prior to ' . \date(DateTime::ISO8601, $payload->iat) + ); + } + + // Check if this token has expired. + if (isset($payload->exp) && ($timestamp - static::$leeway) >= $payload->exp) { + throw new ExpiredException('Expired token'); + } + + return $payload; + } + + /** + * Converts and signs a PHP array into a JWT string. + * + * @param array $payload PHP array + * @param string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate $key The secret key. + * @param string $alg Supported algorithms are 'ES384','ES256', 'ES256K', 'HS256', + * 'HS384', 'HS512', 'RS256', 'RS384', and 'RS512' + * @param string $keyId + * @param array $head An array with header elements to attach + * + * @return string A signed JWT + * + * @uses jsonEncode + * @uses urlsafeB64Encode + */ + public static function encode( + array $payload, + $key, + string $alg, + string $keyId = null, + array $head = null + ): string { + $header = ['typ' => 'JWT', 'alg' => $alg]; + if ($keyId !== null) { + $header['kid'] = $keyId; + } + if (isset($head) && \is_array($head)) { + $header = \array_merge($head, $header); + } + $segments = []; + $segments[] = static::urlsafeB64Encode((string) static::jsonEncode($header)); + $segments[] = static::urlsafeB64Encode((string) static::jsonEncode($payload)); + $signing_input = \implode('.', $segments); + + $signature = static::sign($signing_input, $key, $alg); + $segments[] = static::urlsafeB64Encode($signature); + + return \implode('.', $segments); + } + + /** + * Sign a string with a given key and algorithm. + * + * @param string $msg The message to sign + * @param string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate $key The secret key. + * @param string $alg Supported algorithms are 'ES384','ES256', 'ES256K', 'HS256', + * 'HS384', 'HS512', 'RS256', 'RS384', and 'RS512' + * + * @return string An encrypted message + * + * @throws DomainException Unsupported algorithm or bad key was specified + */ + public static function sign( + string $msg, + $key, + string $alg + ): string { + if (empty(static::$supported_algs[$alg])) { + throw new DomainException('Algorithm not supported'); + } + list($function, $algorithm) = static::$supported_algs[$alg]; + switch ($function) { + case 'hash_hmac': + if (!\is_string($key)) { + throw new InvalidArgumentException('key must be a string when using hmac'); + } + return \hash_hmac($algorithm, $msg, $key, true); + case 'openssl': + $signature = ''; + $success = \openssl_sign($msg, $signature, $key, $algorithm); // @phpstan-ignore-line + if (!$success) { + throw new DomainException('OpenSSL unable to sign data'); + } + if ($alg === 'ES256' || $alg === 'ES256K') { + $signature = self::signatureFromDER($signature, 256); + } elseif ($alg === 'ES384') { + $signature = self::signatureFromDER($signature, 384); + } + return $signature; + case 'sodium_crypto': + if (!\function_exists('sodium_crypto_sign_detached')) { + throw new DomainException('libsodium is not available'); + } + if (!\is_string($key)) { + throw new InvalidArgumentException('key must be a string when using EdDSA'); + } + try { + // The last non-empty line is used as the key. + $lines = array_filter(explode("\n", $key)); + $key = base64_decode((string) end($lines)); + if (\strlen($key) === 0) { + throw new DomainException('Key cannot be empty string'); + } + return sodium_crypto_sign_detached($msg, $key); + } catch (Exception $e) { + throw new DomainException($e->getMessage(), 0, $e); + } + } + + throw new DomainException('Algorithm not supported'); + } + + /** + * Verify a signature with the message, key and method. Not all methods + * are symmetric, so we must have a separate verify and sign method. + * + * @param string $msg The original message (header and body) + * @param string $signature The original signature + * @param string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate $keyMaterial For HS*, a string key works. for RS*, must be an instance of OpenSSLAsymmetricKey + * @param string $alg The algorithm + * + * @return bool + * + * @throws DomainException Invalid Algorithm, bad key, or OpenSSL failure + */ + private static function verify( + string $msg, + string $signature, + $keyMaterial, + string $alg + ): bool { + if (empty(static::$supported_algs[$alg])) { + throw new DomainException('Algorithm not supported'); + } + + list($function, $algorithm) = static::$supported_algs[$alg]; + switch ($function) { + case 'openssl': + $success = \openssl_verify($msg, $signature, $keyMaterial, $algorithm); // @phpstan-ignore-line + if ($success === 1) { + return true; + } + if ($success === 0) { + return false; + } + // returns 1 on success, 0 on failure, -1 on error. + throw new DomainException( + 'OpenSSL error: ' . \openssl_error_string() + ); + case 'sodium_crypto': + if (!\function_exists('sodium_crypto_sign_verify_detached')) { + throw new DomainException('libsodium is not available'); + } + if (!\is_string($keyMaterial)) { + throw new InvalidArgumentException('key must be a string when using EdDSA'); + } + try { + // The last non-empty line is used as the key. + $lines = array_filter(explode("\n", $keyMaterial)); + $key = base64_decode((string) end($lines)); + if (\strlen($key) === 0) { + throw new DomainException('Key cannot be empty string'); + } + if (\strlen($signature) === 0) { + throw new DomainException('Signature cannot be empty string'); + } + return sodium_crypto_sign_verify_detached($signature, $msg, $key); + } catch (Exception $e) { + throw new DomainException($e->getMessage(), 0, $e); + } + case 'hash_hmac': + default: + if (!\is_string($keyMaterial)) { + throw new InvalidArgumentException('key must be a string when using hmac'); + } + $hash = \hash_hmac($algorithm, $msg, $keyMaterial, true); + return self::constantTimeEquals($hash, $signature); + } + } + + /** + * Decode a JSON string into a PHP object. + * + * @param string $input JSON string + * + * @return mixed The decoded JSON string + * + * @throws DomainException Provided string was invalid JSON + */ + public static function jsonDecode(string $input) + { + $obj = \json_decode($input, false, 512, JSON_BIGINT_AS_STRING); + + if ($errno = \json_last_error()) { + self::handleJsonError($errno); + } elseif ($obj === null && $input !== 'null') { + throw new DomainException('Null result with non-null input'); + } + return $obj; + } + + /** + * Encode a PHP array into a JSON string. + * + * @param array $input A PHP array + * + * @return string JSON representation of the PHP array + * + * @throws DomainException Provided object could not be encoded to valid JSON + */ + public static function jsonEncode(array $input): string + { + if (PHP_VERSION_ID >= 50400) { + $json = \json_encode($input, \JSON_UNESCAPED_SLASHES); + } else { + // PHP 5.3 only + $json = \json_encode($input); + } + if ($errno = \json_last_error()) { + self::handleJsonError($errno); + } elseif ($json === 'null') { + throw new DomainException('Null result with non-null input'); + } + if ($json === false) { + throw new DomainException('Provided object could not be encoded to valid JSON'); + } + return $json; + } + + /** + * Decode a string with URL-safe Base64. + * + * @param string $input A Base64 encoded string + * + * @return string A decoded string + * + * @throws InvalidArgumentException invalid base64 characters + */ + public static function urlsafeB64Decode(string $input): string + { + $remainder = \strlen($input) % 4; + if ($remainder) { + $padlen = 4 - $remainder; + $input .= \str_repeat('=', $padlen); + } + return \base64_decode(\strtr($input, '-_', '+/')); + } + + /** + * Encode a string with URL-safe Base64. + * + * @param string $input The string you want encoded + * + * @return string The base64 encode of what you passed in + */ + public static function urlsafeB64Encode(string $input): string + { + return \str_replace('=', '', \strtr(\base64_encode($input), '+/', '-_')); + } + + + /** + * Determine if an algorithm has been provided for each Key + * + * @param Key|ArrayAccess|array $keyOrKeyArray + * @param string|null $kid + * + * @throws UnexpectedValueException + * + * @return Key + */ + private static function getKey( + $keyOrKeyArray, + ?string $kid + ): Key { + if ($keyOrKeyArray instanceof Key) { + return $keyOrKeyArray; + } + + if (empty($kid) && $kid !== '0') { + throw new UnexpectedValueException('"kid" empty, unable to lookup correct key'); + } + + if ($keyOrKeyArray instanceof CachedKeySet) { + // Skip "isset" check, as this will automatically refresh if not set + return $keyOrKeyArray[$kid]; + } + + if (!isset($keyOrKeyArray[$kid])) { + throw new UnexpectedValueException('"kid" invalid, unable to lookup correct key'); + } + + return $keyOrKeyArray[$kid]; + } + + /** + * @param string $left The string of known length to compare against + * @param string $right The user-supplied string + * @return bool + */ + public static function constantTimeEquals(string $left, string $right): bool + { + if (\function_exists('hash_equals')) { + return \hash_equals($left, $right); + } + $len = \min(self::safeStrlen($left), self::safeStrlen($right)); + + $status = 0; + for ($i = 0; $i < $len; $i++) { + $status |= (\ord($left[$i]) ^ \ord($right[$i])); + } + $status |= (self::safeStrlen($left) ^ self::safeStrlen($right)); + + return ($status === 0); + } + + /** + * Helper method to create a JSON error. + * + * @param int $errno An error number from json_last_error() + * + * @throws DomainException + * + * @return void + */ + private static function handleJsonError(int $errno): void + { + $messages = [ + JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', + JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON', + JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', + JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON', + JSON_ERROR_UTF8 => 'Malformed UTF-8 characters' //PHP >= 5.3.3 + ]; + throw new DomainException( + isset($messages[$errno]) + ? $messages[$errno] + : 'Unknown JSON error: ' . $errno + ); + } + + /** + * Get the number of bytes in cryptographic strings. + * + * @param string $str + * + * @return int + */ + private static function safeStrlen(string $str): int + { + if (\function_exists('mb_strlen')) { + return \mb_strlen($str, '8bit'); + } + return \strlen($str); + } + + /** + * Convert an ECDSA signature to an ASN.1 DER sequence + * + * @param string $sig The ECDSA signature to convert + * @return string The encoded DER object + */ + private static function signatureToDER(string $sig): string + { + // Separate the signature into r-value and s-value + $length = max(1, (int) (\strlen($sig) / 2)); + list($r, $s) = \str_split($sig, $length); + + // Trim leading zeros + $r = \ltrim($r, "\x00"); + $s = \ltrim($s, "\x00"); + + // Convert r-value and s-value from unsigned big-endian integers to + // signed two's complement + if (\ord($r[0]) > 0x7f) { + $r = "\x00" . $r; + } + if (\ord($s[0]) > 0x7f) { + $s = "\x00" . $s; + } + + return self::encodeDER( + self::ASN1_SEQUENCE, + self::encodeDER(self::ASN1_INTEGER, $r) . + self::encodeDER(self::ASN1_INTEGER, $s) + ); + } + + /** + * Encodes a value into a DER object. + * + * @param int $type DER tag + * @param string $value the value to encode + * + * @return string the encoded object + */ + private static function encodeDER(int $type, string $value): string + { + $tag_header = 0; + if ($type === self::ASN1_SEQUENCE) { + $tag_header |= 0x20; + } + + // Type + $der = \chr($tag_header | $type); + + // Length + $der .= \chr(\strlen($value)); + + return $der . $value; + } + + /** + * Encodes signature from a DER object. + * + * @param string $der binary signature in DER format + * @param int $keySize the number of bits in the key + * + * @return string the signature + */ + private static function signatureFromDER(string $der, int $keySize): string + { + // OpenSSL returns the ECDSA signatures as a binary ASN.1 DER SEQUENCE + list($offset, $_) = self::readDER($der); + list($offset, $r) = self::readDER($der, $offset); + list($offset, $s) = self::readDER($der, $offset); + + // Convert r-value and s-value from signed two's compliment to unsigned + // big-endian integers + $r = \ltrim($r, "\x00"); + $s = \ltrim($s, "\x00"); + + // Pad out r and s so that they are $keySize bits long + $r = \str_pad($r, $keySize / 8, "\x00", STR_PAD_LEFT); + $s = \str_pad($s, $keySize / 8, "\x00", STR_PAD_LEFT); + + return $r . $s; + } + + /** + * Reads binary DER-encoded data and decodes into a single object + * + * @param string $der the binary data in DER format + * @param int $offset the offset of the data stream containing the object + * to decode + * + * @return array{int, string|null} the new offset and the decoded object + */ + private static function readDER(string $der, int $offset = 0): array + { + $pos = $offset; + $size = \strlen($der); + $constructed = (\ord($der[$pos]) >> 5) & 0x01; + $type = \ord($der[$pos++]) & 0x1f; + + // Length + $len = \ord($der[$pos++]); + if ($len & 0x80) { + $n = $len & 0x1f; + $len = 0; + while ($n-- && $pos < $size) { + $len = ($len << 8) | \ord($der[$pos++]); + } + } + + // Value + if ($type === self::ASN1_BIT_STRING) { + $pos++; // Skip the first contents octet (padding indicator) + $data = \substr($der, $pos, $len - 1); + $pos += $len - 1; + } elseif (!$constructed) { + $data = \substr($der, $pos, $len); + $pos += $len; + } else { + $data = null; + } + + return [$pos, $data]; + } +} diff --git a/data/web/inc/lib/vendor/firebase/php-jwt/src/Key.php b/data/web/inc/lib/vendor/firebase/php-jwt/src/Key.php new file mode 100644 index 000000000..00cf7f2ed --- /dev/null +++ b/data/web/inc/lib/vendor/firebase/php-jwt/src/Key.php @@ -0,0 +1,64 @@ +keyMaterial = $keyMaterial; + $this->algorithm = $algorithm; + } + + /** + * Return the algorithm valid for this key + * + * @return string + */ + public function getAlgorithm(): string + { + return $this->algorithm; + } + + /** + * @return string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate + */ + public function getKeyMaterial() + { + return $this->keyMaterial; + } +} diff --git a/data/web/inc/lib/vendor/firebase/php-jwt/src/SignatureInvalidException.php b/data/web/inc/lib/vendor/firebase/php-jwt/src/SignatureInvalidException.php new file mode 100644 index 000000000..d35dee9f1 --- /dev/null +++ b/data/web/inc/lib/vendor/firebase/php-jwt/src/SignatureInvalidException.php @@ -0,0 +1,7 @@ += 5.5 +* Updated to use PSR-7 + * Requires immutable messages, which basically means an event based system + owned by a request instance is no longer possible. + * Utilizing the [Guzzle PSR-7 package](https://github.com/guzzle/psr7). + * Removed the dependency on `guzzlehttp/streams`. These stream abstractions + are available in the `guzzlehttp/psr7` package under the `GuzzleHttp\Psr7` + namespace. +* Added middleware and handler system + * Replaced the Guzzle event and subscriber system with a middleware system. + * No longer depends on RingPHP, but rather places the HTTP handlers directly + in Guzzle, operating on PSR-7 messages. + * Retry logic is now encapsulated in `GuzzleHttp\Middleware::retry`, which + means the `guzzlehttp/retry-subscriber` is now obsolete. + * Mocking responses is now handled using `GuzzleHttp\Handler\MockHandler`. +* Asynchronous responses + * No longer supports the `future` request option to send an async request. + Instead, use one of the `*Async` methods of a client (e.g., `requestAsync`, + `getAsync`, etc.). + * Utilizing `GuzzleHttp\Promise` instead of React's promise library to avoid + recursion required by chaining and forwarding react promises. See + https://github.com/guzzle/promises + * Added `requestAsync` and `sendAsync` to send request asynchronously. + * Added magic methods for `getAsync()`, `postAsync()`, etc. to send requests + asynchronously. +* Request options + * POST and form updates + * Added the `form_fields` and `form_files` request options. + * Removed the `GuzzleHttp\Post` namespace. + * The `body` request option no longer accepts an array for POST requests. + * The `exceptions` request option has been deprecated in favor of the + `http_errors` request options. + * The `save_to` request option has been deprecated in favor of `sink` request + option. +* Clients no longer accept an array of URI template string and variables for + URI variables. You will need to expand URI templates before passing them + into a client constructor or request method. +* Client methods `get()`, `post()`, `put()`, `patch()`, `options()`, etc. are + now magic methods that will send synchronous requests. +* Replaced `Utils.php` with plain functions in `functions.php`. +* Removed `GuzzleHttp\Collection`. +* Removed `GuzzleHttp\BatchResults`. Batched pool results are now returned as + an array. +* Removed `GuzzleHttp\Query`. Query string handling is now handled using an + associative array passed into the `query` request option. The query string + is serialized using PHP's `http_build_query`. If you need more control, you + can pass the query string in as a string. +* `GuzzleHttp\QueryParser` has been replaced with the + `GuzzleHttp\Psr7\parse_query`. + +## 5.2.0 - 2015-01-27 + +* Added `AppliesHeadersInterface` to make applying headers to a request based + on the body more generic and not specific to `PostBodyInterface`. +* Reduced the number of stack frames needed to send requests. +* Nested futures are now resolved in the client rather than the RequestFsm +* Finishing state transitions is now handled in the RequestFsm rather than the + RingBridge. +* Added a guard in the Pool class to not use recursion for request retries. + +## 5.1.0 - 2014-12-19 + +* Pool class no longer uses recursion when a request is intercepted. +* The size of a Pool can now be dynamically adjusted using a callback. + See https://github.com/guzzle/guzzle/pull/943. +* Setting a request option to `null` when creating a request with a client will + ensure that the option is not set. This allows you to overwrite default + request options on a per-request basis. + See https://github.com/guzzle/guzzle/pull/937. +* Added the ability to limit which protocols are allowed for redirects by + specifying a `protocols` array in the `allow_redirects` request option. +* Nested futures due to retries are now resolved when waiting for synchronous + responses. See https://github.com/guzzle/guzzle/pull/947. +* `"0"` is now an allowed URI path. See + https://github.com/guzzle/guzzle/pull/935. +* `Query` no longer typehints on the `$query` argument in the constructor, + allowing for strings and arrays. +* Exceptions thrown in the `end` event are now correctly wrapped with Guzzle + specific exceptions if necessary. + +## 5.0.3 - 2014-11-03 + +This change updates query strings so that they are treated as un-encoded values +by default where the value represents an un-encoded value to send over the +wire. A Query object then encodes the value before sending over the wire. This +means that even value query string values (e.g., ":") are url encoded. This +makes the Query class match PHP's http_build_query function. However, if you +want to send requests over the wire using valid query string characters that do +not need to be encoded, then you can provide a string to Url::setQuery() and +pass true as the second argument to specify that the query string is a raw +string that should not be parsed or encoded (unless a call to getQuery() is +subsequently made, forcing the query-string to be converted into a Query +object). + +## 5.0.2 - 2014-10-30 + +* Added a trailing `\r\n` to multipart/form-data payloads. See + https://github.com/guzzle/guzzle/pull/871 +* Added a `GuzzleHttp\Pool::send()` convenience method to match the docs. +* Status codes are now returned as integers. See + https://github.com/guzzle/guzzle/issues/881 +* No longer overwriting an existing `application/x-www-form-urlencoded` header + when sending POST requests, allowing for customized headers. See + https://github.com/guzzle/guzzle/issues/877 +* Improved path URL serialization. + + * No longer double percent-encoding characters in the path or query string if + they are already encoded. + * Now properly encoding the supplied path to a URL object, instead of only + encoding ' ' and '?'. + * Note: This has been changed in 5.0.3 to now encode query string values by + default unless the `rawString` argument is provided when setting the query + string on a URL: Now allowing many more characters to be present in the + query string without being percent encoded. See https://tools.ietf.org/html/rfc3986#appendix-A + +## 5.0.1 - 2014-10-16 + +Bugfix release. + +* Fixed an issue where connection errors still returned response object in + error and end events event though the response is unusable. This has been + corrected so that a response is not returned in the `getResponse` method of + these events if the response did not complete. https://github.com/guzzle/guzzle/issues/867 +* Fixed an issue where transfer statistics were not being populated in the + RingBridge. https://github.com/guzzle/guzzle/issues/866 + +## 5.0.0 - 2014-10-12 + +Adding support for non-blocking responses and some minor API cleanup. + +### New Features + +* Added support for non-blocking responses based on `guzzlehttp/guzzle-ring`. +* Added a public API for creating a default HTTP adapter. +* Updated the redirect plugin to be non-blocking so that redirects are sent + concurrently. Other plugins like this can now be updated to be non-blocking. +* Added a "progress" event so that you can get upload and download progress + events. +* Added `GuzzleHttp\Pool` which implements FutureInterface and transfers + requests concurrently using a capped pool size as efficiently as possible. +* Added `hasListeners()` to EmitterInterface. +* Removed `GuzzleHttp\ClientInterface::sendAll` and marked + `GuzzleHttp\Client::sendAll` as deprecated (it's still there, just not the + recommended way). + +### Breaking changes + +The breaking changes in this release are relatively minor. The biggest thing to +look out for is that request and response objects no longer implement fluent +interfaces. + +* Removed the fluent interfaces (i.e., `return $this`) from requests, + responses, `GuzzleHttp\Collection`, `GuzzleHttp\Url`, + `GuzzleHttp\Query`, `GuzzleHttp\Post\PostBody`, and + `GuzzleHttp\Cookie\SetCookie`. This blog post provides a good outline of + why I did this: https://ocramius.github.io/blog/fluent-interfaces-are-evil/. + This also makes the Guzzle message interfaces compatible with the current + PSR-7 message proposal. +* Removed "functions.php", so that Guzzle is truly PSR-4 compliant. Except + for the HTTP request functions from function.php, these functions are now + implemented in `GuzzleHttp\Utils` using camelCase. `GuzzleHttp\json_decode` + moved to `GuzzleHttp\Utils::jsonDecode`. `GuzzleHttp\get_path` moved to + `GuzzleHttp\Utils::getPath`. `GuzzleHttp\set_path` moved to + `GuzzleHttp\Utils::setPath`. `GuzzleHttp\batch` should now be + `GuzzleHttp\Pool::batch`, which returns an `objectStorage`. Using functions.php + caused problems for many users: they aren't PSR-4 compliant, require an + explicit include, and needed an if-guard to ensure that the functions are not + declared multiple times. +* Rewrote adapter layer. + * Removing all classes from `GuzzleHttp\Adapter`, these are now + implemented as callables that are stored in `GuzzleHttp\Ring\Client`. + * Removed the concept of "parallel adapters". Sending requests serially or + concurrently is now handled using a single adapter. + * Moved `GuzzleHttp\Adapter\Transaction` to `GuzzleHttp\Transaction`. The + Transaction object now exposes the request, response, and client as public + properties. The getters and setters have been removed. +* Removed the "headers" event. This event was only useful for changing the + body a response once the headers of the response were known. You can implement + a similar behavior in a number of ways. One example might be to use a + FnStream that has access to the transaction being sent. For example, when the + first byte is written, you could check if the response headers match your + expectations, and if so, change the actual stream body that is being + written to. +* Removed the `asArray` parameter from + `GuzzleHttp\Message\MessageInterface::getHeader`. If you want to get a header + value as an array, then use the newly added `getHeaderAsArray()` method of + `MessageInterface`. This change makes the Guzzle interfaces compatible with + the PSR-7 interfaces. +* `GuzzleHttp\Message\MessageFactory` no longer allows subclasses to add + custom request options using double-dispatch (this was an implementation + detail). Instead, you should now provide an associative array to the + constructor which is a mapping of the request option name mapping to a + function that applies the option value to a request. +* Removed the concept of "throwImmediately" from exceptions and error events. + This control mechanism was used to stop a transfer of concurrent requests + from completing. This can now be handled by throwing the exception or by + cancelling a pool of requests or each outstanding future request individually. +* Updated to "GuzzleHttp\Streams" 3.0. + * `GuzzleHttp\Stream\StreamInterface::getContents()` no longer accepts a + `maxLen` parameter. This update makes the Guzzle streams project + compatible with the current PSR-7 proposal. + * `GuzzleHttp\Stream\Stream::__construct`, + `GuzzleHttp\Stream\Stream::factory`, and + `GuzzleHttp\Stream\Utils::create` no longer accept a size in the second + argument. They now accept an associative array of options, including the + "size" key and "metadata" key which can be used to provide custom metadata. + +## 4.2.2 - 2014-09-08 + +* Fixed a memory leak in the CurlAdapter when reusing cURL handles. +* No longer using `request_fulluri` in stream adapter proxies. +* Relative redirects are now based on the last response, not the first response. + +## 4.2.1 - 2014-08-19 + +* Ensuring that the StreamAdapter does not always add a Content-Type header +* Adding automated github releases with a phar and zip + +## 4.2.0 - 2014-08-17 + +* Now merging in default options using a case-insensitive comparison. + Closes https://github.com/guzzle/guzzle/issues/767 +* Added the ability to automatically decode `Content-Encoding` response bodies + using the `decode_content` request option. This is set to `true` by default + to decode the response body if it comes over the wire with a + `Content-Encoding`. Set this value to `false` to disable decoding the + response content, and pass a string to provide a request `Accept-Encoding` + header and turn on automatic response decoding. This feature now allows you + to pass an `Accept-Encoding` header in the headers of a request but still + disable automatic response decoding. + Closes https://github.com/guzzle/guzzle/issues/764 +* Added the ability to throw an exception immediately when transferring + requests in parallel. Closes https://github.com/guzzle/guzzle/issues/760 +* Updating guzzlehttp/streams dependency to ~2.1 +* No longer utilizing the now deprecated namespaced methods from the stream + package. + +## 4.1.8 - 2014-08-14 + +* Fixed an issue in the CurlFactory that caused setting the `stream=false` + request option to throw an exception. + See: https://github.com/guzzle/guzzle/issues/769 +* TransactionIterator now calls rewind on the inner iterator. + See: https://github.com/guzzle/guzzle/pull/765 +* You can now set the `Content-Type` header to `multipart/form-data` + when creating POST requests to force multipart bodies. + See https://github.com/guzzle/guzzle/issues/768 + +## 4.1.7 - 2014-08-07 + +* Fixed an error in the HistoryPlugin that caused the same request and response + to be logged multiple times when an HTTP protocol error occurs. +* Ensuring that cURL does not add a default Content-Type when no Content-Type + has been supplied by the user. This prevents the adapter layer from modifying + the request that is sent over the wire after any listeners may have already + put the request in a desired state (e.g., signed the request). +* Throwing an exception when you attempt to send requests that have the + "stream" set to true in parallel using the MultiAdapter. +* Only calling curl_multi_select when there are active cURL handles. This was + previously changed and caused performance problems on some systems due to PHP + always selecting until the maximum select timeout. +* Fixed a bug where multipart/form-data POST fields were not correctly + aggregated (e.g., values with "&"). + +## 4.1.6 - 2014-08-03 + +* Added helper methods to make it easier to represent messages as strings, + including getting the start line and getting headers as a string. + +## 4.1.5 - 2014-08-02 + +* Automatically retrying cURL "Connection died, retrying a fresh connect" + errors when possible. +* cURL implementation cleanup +* Allowing multiple event subscriber listeners to be registered per event by + passing an array of arrays of listener configuration. + +## 4.1.4 - 2014-07-22 + +* Fixed a bug that caused multi-part POST requests with more than one field to + serialize incorrectly. +* Paths can now be set to "0" +* `ResponseInterface::xml` now accepts a `libxml_options` option and added a + missing default argument that was required when parsing XML response bodies. +* A `save_to` stream is now created lazily, which means that files are not + created on disk unless a request succeeds. + +## 4.1.3 - 2014-07-15 + +* Various fixes to multipart/form-data POST uploads +* Wrapping function.php in an if-statement to ensure Guzzle can be used + globally and in a Composer install +* Fixed an issue with generating and merging in events to an event array +* POST headers are only applied before sending a request to allow you to change + the query aggregator used before uploading +* Added much more robust query string parsing +* Fixed various parsing and normalization issues with URLs +* Fixing an issue where multi-valued headers were not being utilized correctly + in the StreamAdapter + +## 4.1.2 - 2014-06-18 + +* Added support for sending payloads with GET requests + +## 4.1.1 - 2014-06-08 + +* Fixed an issue related to using custom message factory options in subclasses +* Fixed an issue with nested form fields in a multi-part POST +* Fixed an issue with using the `json` request option for POST requests +* Added `ToArrayInterface` to `GuzzleHttp\Cookie\CookieJar` + +## 4.1.0 - 2014-05-27 + +* Added a `json` request option to easily serialize JSON payloads. +* Added a `GuzzleHttp\json_decode()` wrapper to safely parse JSON. +* Added `setPort()` and `getPort()` to `GuzzleHttp\Message\RequestInterface`. +* Added the ability to provide an emitter to a client in the client constructor. +* Added the ability to persist a cookie session using $_SESSION. +* Added a trait that can be used to add event listeners to an iterator. +* Removed request method constants from RequestInterface. +* Fixed warning when invalid request start-lines are received. +* Updated MessageFactory to work with custom request option methods. +* Updated cacert bundle to latest build. + +4.0.2 (2014-04-16) +------------------ + +* Proxy requests using the StreamAdapter now properly use request_fulluri (#632) +* Added the ability to set scalars as POST fields (#628) + +## 4.0.1 - 2014-04-04 + +* The HTTP status code of a response is now set as the exception code of + RequestException objects. +* 303 redirects will now correctly switch from POST to GET requests. +* The default parallel adapter of a client now correctly uses the MultiAdapter. +* HasDataTrait now initializes the internal data array as an empty array so + that the toArray() method always returns an array. + +## 4.0.0 - 2014-03-29 + +* For information on changes and upgrading, see: + https://github.com/guzzle/guzzle/blob/master/UPGRADING.md#3x-to-40 +* Added `GuzzleHttp\batch()` as a convenience function for sending requests in + parallel without needing to write asynchronous code. +* Restructured how events are added to `GuzzleHttp\ClientInterface::sendAll()`. + You can now pass a callable or an array of associative arrays where each + associative array contains the "fn", "priority", and "once" keys. + +## 4.0.0.rc-2 - 2014-03-25 + +* Removed `getConfig()` and `setConfig()` from clients to avoid confusion + around whether things like base_url, message_factory, etc. should be able to + be retrieved or modified. +* Added `getDefaultOption()` and `setDefaultOption()` to ClientInterface +* functions.php functions were renamed using snake_case to match PHP idioms +* Added support for `HTTP_PROXY`, `HTTPS_PROXY`, and + `GUZZLE_CURL_SELECT_TIMEOUT` environment variables +* Added the ability to specify custom `sendAll()` event priorities +* Added the ability to specify custom stream context options to the stream + adapter. +* Added a functions.php function for `get_path()` and `set_path()` +* CurlAdapter and MultiAdapter now use a callable to generate curl resources +* MockAdapter now properly reads a body and emits a `headers` event +* Updated Url class to check if a scheme and host are set before adding ":" + and "//". This allows empty Url (e.g., "") to be serialized as "". +* Parsing invalid XML no longer emits warnings +* Curl classes now properly throw AdapterExceptions +* Various performance optimizations +* Streams are created with the faster `Stream\create()` function +* Marked deprecation_proxy() as internal +* Test server is now a collection of static methods on a class + +## 4.0.0-rc.1 - 2014-03-15 + +* See https://github.com/guzzle/guzzle/blob/master/UPGRADING.md#3x-to-40 + +## 3.8.1 - 2014-01-28 + +* Bug: Always using GET requests when redirecting from a 303 response +* Bug: CURLOPT_SSL_VERIFYHOST is now correctly set to false when setting `$certificateAuthority` to false in + `Guzzle\Http\ClientInterface::setSslVerification()` +* Bug: RedirectPlugin now uses strict RFC 3986 compliance when combining a base URL with a relative URL +* Bug: The body of a request can now be set to `"0"` +* Sending PHP stream requests no longer forces `HTTP/1.0` +* Adding more information to ExceptionCollection exceptions so that users have more context, including a stack trace of + each sub-exception +* Updated the `$ref` attribute in service descriptions to merge over any existing parameters of a schema (rather than + clobbering everything). +* Merging URLs will now use the query string object from the relative URL (thus allowing custom query aggregators) +* Query strings are now parsed in a way that they do no convert empty keys with no value to have a dangling `=`. + For example `foo&bar=baz` is now correctly parsed and recognized as `foo&bar=baz` rather than `foo=&bar=baz`. +* Now properly escaping the regular expression delimiter when matching Cookie domains. +* Network access is now disabled when loading XML documents + +## 3.8.0 - 2013-12-05 + +* Added the ability to define a POST name for a file +* JSON response parsing now properly walks additionalProperties +* cURL error code 18 is now retried automatically in the BackoffPlugin +* Fixed a cURL error when URLs contain fragments +* Fixed an issue in the BackoffPlugin retry event where it was trying to access all exceptions as if they were + CurlExceptions +* CURLOPT_PROGRESS function fix for PHP 5.5 (69fcc1e) +* Added the ability for Guzzle to work with older versions of cURL that do not support `CURLOPT_TIMEOUT_MS` +* Fixed a bug that was encountered when parsing empty header parameters +* UriTemplate now has a `setRegex()` method to match the docs +* The `debug` request parameter now checks if it is truthy rather than if it exists +* Setting the `debug` request parameter to true shows verbose cURL output instead of using the LogPlugin +* Added the ability to combine URLs using strict RFC 3986 compliance +* Command objects can now return the validation errors encountered by the command +* Various fixes to cache revalidation (#437 and 29797e5) +* Various fixes to the AsyncPlugin +* Cleaned up build scripts + +## 3.7.4 - 2013-10-02 + +* Bug fix: 0 is now an allowed value in a description parameter that has a default value (#430) +* Bug fix: SchemaFormatter now returns an integer when formatting to a Unix timestamp + (see https://github.com/aws/aws-sdk-php/issues/147) +* Bug fix: Cleaned up and fixed URL dot segment removal to properly resolve internal dots +* Minimum PHP version is now properly specified as 5.3.3 (up from 5.3.2) (#420) +* Updated the bundled cacert.pem (#419) +* OauthPlugin now supports adding authentication to headers or query string (#425) + +## 3.7.3 - 2013-09-08 + +* Added the ability to get the exception associated with a request/command when using `MultiTransferException` and + `CommandTransferException`. +* Setting `additionalParameters` of a response to false is now honored when parsing responses with a service description +* Schemas are only injected into response models when explicitly configured. +* No longer guessing Content-Type based on the path of a request. Content-Type is now only guessed based on the path of + an EntityBody. +* Bug fix: ChunkedIterator can now properly chunk a \Traversable as well as an \Iterator. +* Bug fix: FilterIterator now relies on `\Iterator` instead of `\Traversable`. +* Bug fix: Gracefully handling malformed responses in RequestMediator::writeResponseBody() +* Bug fix: Replaced call to canCache with canCacheRequest in the CallbackCanCacheStrategy of the CachePlugin +* Bug fix: Visiting XML attributes first before visiting XML children when serializing requests +* Bug fix: Properly parsing headers that contain commas contained in quotes +* Bug fix: mimetype guessing based on a filename is now case-insensitive + +## 3.7.2 - 2013-08-02 + +* Bug fix: Properly URL encoding paths when using the PHP-only version of the UriTemplate expander + See https://github.com/guzzle/guzzle/issues/371 +* Bug fix: Cookie domains are now matched correctly according to RFC 6265 + See https://github.com/guzzle/guzzle/issues/377 +* Bug fix: GET parameters are now used when calculating an OAuth signature +* Bug fix: Fixed an issue with cache revalidation where the If-None-Match header was being double quoted +* `Guzzle\Common\AbstractHasDispatcher::dispatch()` now returns the event that was dispatched +* `Guzzle\Http\QueryString::factory()` now guesses the most appropriate query aggregator to used based on the input. + See https://github.com/guzzle/guzzle/issues/379 +* Added a way to add custom domain objects to service description parsing using the `operation.parse_class` event. See + https://github.com/guzzle/guzzle/pull/380 +* cURL multi cleanup and optimizations + +## 3.7.1 - 2013-07-05 + +* Bug fix: Setting default options on a client now works +* Bug fix: Setting options on HEAD requests now works. See #352 +* Bug fix: Moving stream factory before send event to before building the stream. See #353 +* Bug fix: Cookies no longer match on IP addresses per RFC 6265 +* Bug fix: Correctly parsing header parameters that are in `<>` and quotes +* Added `cert` and `ssl_key` as request options +* `Host` header can now diverge from the host part of a URL if the header is set manually +* `Guzzle\Service\Command\LocationVisitor\Request\XmlVisitor` was rewritten to change from using SimpleXML to XMLWriter +* OAuth parameters are only added via the plugin if they aren't already set +* Exceptions are now thrown when a URL cannot be parsed +* Returning `false` if `Guzzle\Http\EntityBody::getContentMd5()` fails +* Not setting a `Content-MD5` on a command if calculating the Content-MD5 fails via the CommandContentMd5Plugin + +## 3.7.0 - 2013-06-10 + +* See UPGRADING.md for more information on how to upgrade. +* Requests now support the ability to specify an array of $options when creating a request to more easily modify a + request. You can pass a 'request.options' configuration setting to a client to apply default request options to + every request created by a client (e.g. default query string variables, headers, curl options, etc.). +* Added a static facade class that allows you to use Guzzle with static methods and mount the class to `\Guzzle`. + See `Guzzle\Http\StaticClient::mount`. +* Added `command.request_options` to `Guzzle\Service\Command\AbstractCommand` to pass request options to requests + created by a command (e.g. custom headers, query string variables, timeout settings, etc.). +* Stream size in `Guzzle\Stream\PhpStreamRequestFactory` will now be set if Content-Length is returned in the + headers of a response +* Added `Guzzle\Common\Collection::setPath($path, $value)` to set a value into an array using a nested key + (e.g. `$collection->setPath('foo/baz/bar', 'test'); echo $collection['foo']['bar']['bar'];`) +* ServiceBuilders now support storing and retrieving arbitrary data +* CachePlugin can now purge all resources for a given URI +* CachePlugin can automatically purge matching cached items when a non-idempotent request is sent to a resource +* CachePlugin now uses the Vary header to determine if a resource is a cache hit +* `Guzzle\Http\Message\Response` now implements `\Serializable` +* Added `Guzzle\Cache\CacheAdapterFactory::fromCache()` to more easily create cache adapters +* `Guzzle\Service\ClientInterface::execute()` now accepts an array, single command, or Traversable +* Fixed a bug in `Guzzle\Http\Message\Header\Link::addLink()` +* Better handling of calculating the size of a stream in `Guzzle\Stream\Stream` using fstat() and caching the size +* `Guzzle\Common\Exception\ExceptionCollection` now creates a more readable exception message +* Fixing BC break: Added back the MonologLogAdapter implementation rather than extending from PsrLog so that older + Symfony users can still use the old version of Monolog. +* Fixing BC break: Added the implementation back in for `Guzzle\Http\Message\AbstractMessage::getTokenizedHeader()`. + Now triggering an E_USER_DEPRECATED warning when used. Use `$message->getHeader()->parseParams()`. +* Several performance improvements to `Guzzle\Common\Collection` +* Added an `$options` argument to the end of the following methods of `Guzzle\Http\ClientInterface`: + createRequest, head, delete, put, patch, post, options, prepareRequest +* Added an `$options` argument to the end of `Guzzle\Http\Message\Request\RequestFactoryInterface::createRequest()` +* Added an `applyOptions()` method to `Guzzle\Http\Message\Request\RequestFactoryInterface` +* Changed `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $body = null)` to + `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $options = array())`. You can still pass in a + resource, string, or EntityBody into the $options parameter to specify the download location of the response. +* Changed `Guzzle\Common\Collection::__construct($data)` to no longer accepts a null value for `$data` but a + default `array()` +* Added `Guzzle\Stream\StreamInterface::isRepeatable` +* Removed `Guzzle\Http\ClientInterface::setDefaultHeaders(). Use + $client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. or + $client->getConfig()->setPath('request.options/headers', array('header_name' => 'value'))`. +* Removed `Guzzle\Http\ClientInterface::getDefaultHeaders(). Use $client->getConfig()->getPath('request.options/headers')`. +* Removed `Guzzle\Http\ClientInterface::expandTemplate()` +* Removed `Guzzle\Http\ClientInterface::setRequestFactory()` +* Removed `Guzzle\Http\ClientInterface::getCurlMulti()` +* Removed `Guzzle\Http\Message\RequestInterface::canCache` +* Removed `Guzzle\Http\Message\RequestInterface::setIsRedirect` +* Removed `Guzzle\Http\Message\RequestInterface::isRedirect` +* Made `Guzzle\Http\Client::expandTemplate` and `getUriTemplate` protected methods. +* You can now enable E_USER_DEPRECATED warnings to see if you are using a deprecated method by setting + `Guzzle\Common\Version::$emitWarnings` to true. +* Marked `Guzzle\Http\Message\Request::isResponseBodyRepeatable()` as deprecated. Use + `$request->getResponseBody()->isRepeatable()` instead. +* Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use + `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +* Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use + `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +* Marked `Guzzle\Http\Message\Request::setIsRedirect()` as deprecated. Use the HistoryPlugin instead. +* Marked `Guzzle\Http\Message\Request::isRedirect()` as deprecated. Use the HistoryPlugin instead. +* Marked `Guzzle\Cache\CacheAdapterFactory::factory()` as deprecated +* Marked 'command.headers', 'command.response_body' and 'command.on_complete' as deprecated for AbstractCommand. + These will work through Guzzle 4.0 +* Marked 'request.params' for `Guzzle\Http\Client` as deprecated. Use [request.options][params]. +* Marked `Guzzle\Service\Client::enableMagicMethods()` as deprecated. Magic methods can no longer be disabled on a Guzzle\Service\Client. +* Marked `Guzzle\Service\Client::getDefaultHeaders()` as deprecated. Use $client->getConfig()->getPath('request.options/headers')`. +* Marked `Guzzle\Service\Client::setDefaultHeaders()` as deprecated. Use $client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. +* Marked `Guzzle\Parser\Url\UrlParser` as deprecated. Just use PHP's `parse_url()` and percent encode your UTF-8. +* Marked `Guzzle\Common\Collection::inject()` as deprecated. +* Marked `Guzzle\Plugin\CurlAuth\CurlAuthPlugin` as deprecated. Use `$client->getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest');` +* CacheKeyProviderInterface and DefaultCacheKeyProvider are no longer used. All of this logic is handled in a + CacheStorageInterface. These two objects and interface will be removed in a future version. +* Always setting X-cache headers on cached responses +* Default cache TTLs are now handled by the CacheStorageInterface of a CachePlugin +* `CacheStorageInterface::cache($key, Response $response, $ttl = null)` has changed to `cache(RequestInterface + $request, Response $response);` +* `CacheStorageInterface::fetch($key)` has changed to `fetch(RequestInterface $request);` +* `CacheStorageInterface::delete($key)` has changed to `delete(RequestInterface $request);` +* Added `CacheStorageInterface::purge($url)` +* `DefaultRevalidation::__construct(CacheKeyProviderInterface $cacheKey, CacheStorageInterface $cache, CachePlugin + $plugin)` has changed to `DefaultRevalidation::__construct(CacheStorageInterface $cache, + CanCacheStrategyInterface $canCache = null)` +* Added `RevalidationInterface::shouldRevalidate(RequestInterface $request, Response $response)` + +## 3.6.0 - 2013-05-29 + +* ServiceDescription now implements ToArrayInterface +* Added command.hidden_params to blacklist certain headers from being treated as additionalParameters +* Guzzle can now correctly parse incomplete URLs +* Mixed casing of headers are now forced to be a single consistent casing across all values for that header. +* Messages internally use a HeaderCollection object to delegate handling case-insensitive header resolution +* Removed the whole changedHeader() function system of messages because all header changes now go through addHeader(). +* Specific header implementations can be created for complex headers. When a message creates a header, it uses a + HeaderFactory which can map specific headers to specific header classes. There is now a Link header and + CacheControl header implementation. +* Removed from interface: Guzzle\Http\ClientInterface::setUriTemplate +* Removed from interface: Guzzle\Http\ClientInterface::setCurlMulti() +* Removed Guzzle\Http\Message\Request::receivedRequestHeader() and implemented this functionality in + Guzzle\Http\Curl\RequestMediator +* Removed the optional $asString parameter from MessageInterface::getHeader(). Just cast the header to a string. +* Removed the optional $tryChunkedTransfer option from Guzzle\Http\Message\EntityEnclosingRequestInterface +* Removed the $asObjects argument from Guzzle\Http\Message\MessageInterface::getHeaders() +* Removed Guzzle\Parser\ParserRegister::get(). Use getParser() +* Removed Guzzle\Parser\ParserRegister::set(). Use registerParser(). +* All response header helper functions return a string rather than mixing Header objects and strings inconsistently +* Removed cURL blacklist support. This is no longer necessary now that Expect, Accept, etc. are managed by Guzzle + directly via interfaces +* Removed the injecting of a request object onto a response object. The methods to get and set a request still exist + but are a no-op until removed. +* Most classes that used to require a `Guzzle\Service\Command\CommandInterface` typehint now request a + `Guzzle\Service\Command\ArrayCommandInterface`. +* Added `Guzzle\Http\Message\RequestInterface::startResponse()` to the RequestInterface to handle injecting a response + on a request while the request is still being transferred +* The ability to case-insensitively search for header values +* Guzzle\Http\Message\Header::hasExactHeader +* Guzzle\Http\Message\Header::raw. Use getAll() +* Deprecated cache control specific methods on Guzzle\Http\Message\AbstractMessage. Use the CacheControl header object + instead. +* `Guzzle\Service\Command\CommandInterface` now extends from ToArrayInterface and ArrayAccess +* Added the ability to cast Model objects to a string to view debug information. + +## 3.5.0 - 2013-05-13 + +* Bug: Fixed a regression so that request responses are parsed only once per oncomplete event rather than multiple times +* Bug: Better cleanup of one-time events across the board (when an event is meant to fire once, it will now remove + itself from the EventDispatcher) +* Bug: `Guzzle\Log\MessageFormatter` now properly writes "total_time" and "connect_time" values +* Bug: Cloning an EntityEnclosingRequest now clones the EntityBody too +* Bug: Fixed an undefined index error when parsing nested JSON responses with a sentAs parameter that reference a + non-existent key +* Bug: All __call() method arguments are now required (helps with mocking frameworks) +* Deprecating Response::getRequest() and now using a shallow clone of a request object to remove a circular reference + to help with refcount based garbage collection of resources created by sending a request +* Deprecating ZF1 cache and log adapters. These will be removed in the next major version. +* Deprecating `Response::getPreviousResponse()` (method signature still exists, but it's deprecated). Use the + HistoryPlugin for a history. +* Added a `responseBody` alias for the `response_body` location +* Refactored internals to no longer rely on Response::getRequest() +* HistoryPlugin can now be cast to a string +* HistoryPlugin now logs transactions rather than requests and responses to more accurately keep track of the requests + and responses that are sent over the wire +* Added `getEffectiveUrl()` and `getRedirectCount()` to Response objects + +## 3.4.3 - 2013-04-30 + +* Bug fix: Fixing bug introduced in 3.4.2 where redirect responses are duplicated on the final redirected response +* Added a check to re-extract the temp cacert bundle from the phar before sending each request + +## 3.4.2 - 2013-04-29 + +* Bug fix: Stream objects now work correctly with "a" and "a+" modes +* Bug fix: Removing `Transfer-Encoding: chunked` header when a Content-Length is present +* Bug fix: AsyncPlugin no longer forces HEAD requests +* Bug fix: DateTime timezones are now properly handled when using the service description schema formatter +* Bug fix: CachePlugin now properly handles stale-if-error directives when a request to the origin server fails +* Setting a response on a request will write to the custom request body from the response body if one is specified +* LogPlugin now writes to php://output when STDERR is undefined +* Added the ability to set multiple POST files for the same key in a single call +* application/x-www-form-urlencoded POSTs now use the utf-8 charset by default +* Added the ability to queue CurlExceptions to the MockPlugin +* Cleaned up how manual responses are queued on requests (removed "queued_response" and now using request.before_send) +* Configuration loading now allows remote files + +## 3.4.1 - 2013-04-16 + +* Large refactoring to how CurlMulti handles work. There is now a proxy that sits in front of a pool of CurlMulti + handles. This greatly simplifies the implementation, fixes a couple bugs, and provides a small performance boost. +* Exceptions are now properly grouped when sending requests in parallel +* Redirects are now properly aggregated when a multi transaction fails +* Redirects now set the response on the original object even in the event of a failure +* Bug fix: Model names are now properly set even when using $refs +* Added support for PHP 5.5's CurlFile to prevent warnings with the deprecated @ syntax +* Added support for oauth_callback in OAuth signatures +* Added support for oauth_verifier in OAuth signatures +* Added support to attempt to retrieve a command first literally, then ucfirst, the with inflection + +## 3.4.0 - 2013-04-11 + +* Bug fix: URLs are now resolved correctly based on https://tools.ietf.org/html/rfc3986#section-5.2. #289 +* Bug fix: Absolute URLs with a path in a service description will now properly override the base URL. #289 +* Bug fix: Parsing a query string with a single PHP array value will now result in an array. #263 +* Bug fix: Better normalization of the User-Agent header to prevent duplicate headers. #264. +* Bug fix: Added `number` type to service descriptions. +* Bug fix: empty parameters are removed from an OAuth signature +* Bug fix: Revalidating a cache entry prefers the Last-Modified over the Date header +* Bug fix: Fixed "array to string" error when validating a union of types in a service description +* Bug fix: Removed code that attempted to determine the size of a stream when data is written to the stream +* Bug fix: Not including an `oauth_token` if the value is null in the OauthPlugin. +* Bug fix: Now correctly aggregating successful requests and failed requests in CurlMulti when a redirect occurs. +* The new default CURLOPT_TIMEOUT setting has been increased to 150 seconds so that Guzzle works on poor connections. +* Added a feature to EntityEnclosingRequest::setBody() that will automatically set the Content-Type of the request if + the Content-Type can be determined based on the entity body or the path of the request. +* Added the ability to overwrite configuration settings in a client when grabbing a throwaway client from a builder. +* Added support for a PSR-3 LogAdapter. +* Added a `command.after_prepare` event +* Added `oauth_callback` parameter to the OauthPlugin +* Added the ability to create a custom stream class when using a stream factory +* Added a CachingEntityBody decorator +* Added support for `additionalParameters` in service descriptions to define how custom parameters are serialized. +* The bundled SSL certificate is now provided in the phar file and extracted when running Guzzle from a phar. +* You can now send any EntityEnclosingRequest with POST fields or POST files and cURL will handle creating bodies +* POST requests using a custom entity body are now treated exactly like PUT requests but with a custom cURL method. This + means that the redirect behavior of POST requests with custom bodies will not be the same as POST requests that use + POST fields or files (the latter is only used when emulating a form POST in the browser). +* Lots of cleanup to CurlHandle::factory and RequestFactory::createRequest + +## 3.3.1 - 2013-03-10 + +* Added the ability to create PHP streaming responses from HTTP requests +* Bug fix: Running any filters when parsing response headers with service descriptions +* Bug fix: OauthPlugin fixes to allow for multi-dimensional array signing, and sorting parameters before signing +* Bug fix: Removed the adding of default empty arrays and false Booleans to responses in order to be consistent across + response location visitors. +* Bug fix: Removed the possibility of creating configuration files with circular dependencies +* RequestFactory::create() now uses the key of a POST file when setting the POST file name +* Added xmlAllowEmpty to serialize an XML body even if no XML specific parameters are set + +## 3.3.0 - 2013-03-03 + +* A large number of performance optimizations have been made +* Bug fix: Added 'wb' as a valid write mode for streams +* Bug fix: `Guzzle\Http\Message\Response::json()` now allows scalar values to be returned +* Bug fix: Fixed bug in `Guzzle\Http\Message\Response` where wrapping quotes were stripped from `getEtag()` +* BC: Removed `Guzzle\Http\Utils` class +* BC: Setting a service description on a client will no longer modify the client's command factories. +* BC: Emitting IO events from a RequestMediator is now a parameter that must be set in a request's curl options using + the 'emit_io' key. This was previously set under a request's parameters using 'curl.emit_io' +* BC: `Guzzle\Stream\Stream::getWrapper()` and `Guzzle\Stream\Stream::getSteamType()` are no longer converted to + lowercase +* Operation parameter objects are now lazy loaded internally +* Added ErrorResponsePlugin that can throw errors for responses defined in service description operations' errorResponses +* Added support for instantiating responseType=class responseClass classes. Classes must implement + `Guzzle\Service\Command\ResponseClassInterface` +* Added support for additionalProperties for top-level parameters in responseType=model responseClasses. These + additional properties also support locations and can be used to parse JSON responses where the outermost part of the + JSON is an array +* Added support for nested renaming of JSON models (rename sentAs to name) +* CachePlugin + * Added support for stale-if-error so that the CachePlugin can now serve stale content from the cache on error + * Debug headers can now added to cached response in the CachePlugin + +## 3.2.0 - 2013-02-14 + +* CurlMulti is no longer reused globally. A new multi object is created per-client. This helps to isolate clients. +* URLs with no path no longer contain a "/" by default +* Guzzle\Http\QueryString does no longer manages the leading "?". This is now handled in Guzzle\Http\Url. +* BadResponseException no longer includes the full request and response message +* Adding setData() to Guzzle\Service\Description\ServiceDescriptionInterface +* Adding getResponseBody() to Guzzle\Http\Message\RequestInterface +* Various updates to classes to use ServiceDescriptionInterface type hints rather than ServiceDescription +* Header values can now be normalized into distinct values when multiple headers are combined with a comma separated list +* xmlEncoding can now be customized for the XML declaration of a XML service description operation +* Guzzle\Http\QueryString now uses Guzzle\Http\QueryAggregator\QueryAggregatorInterface objects to add custom value + aggregation and no longer uses callbacks +* The URL encoding implementation of Guzzle\Http\QueryString can now be customized +* Bug fix: Filters were not always invoked for array service description parameters +* Bug fix: Redirects now use a target response body rather than a temporary response body +* Bug fix: The default exponential backoff BackoffPlugin was not giving when the request threshold was exceeded +* Bug fix: Guzzle now takes the first found value when grabbing Cache-Control directives + +## 3.1.2 - 2013-01-27 + +* Refactored how operation responses are parsed. Visitors now include a before() method responsible for parsing the + response body. For example, the XmlVisitor now parses the XML response into an array in the before() method. +* Fixed an issue where cURL would not automatically decompress responses when the Accept-Encoding header was sent +* CURLOPT_SSL_VERIFYHOST is never set to 1 because it is deprecated (see 5e0ff2ef20f839e19d1eeb298f90ba3598784444) +* Fixed a bug where redirect responses were not chained correctly using getPreviousResponse() +* Setting default headers on a client after setting the user-agent will not erase the user-agent setting + +## 3.1.1 - 2013-01-20 + +* Adding wildcard support to Guzzle\Common\Collection::getPath() +* Adding alias support to ServiceBuilder configs +* Adding Guzzle\Service\Resource\CompositeResourceIteratorFactory and cleaning up factory interface + +## 3.1.0 - 2013-01-12 + +* BC: CurlException now extends from RequestException rather than BadResponseException +* BC: Renamed Guzzle\Plugin\Cache\CanCacheStrategyInterface::canCache() to canCacheRequest() and added CanCacheResponse() +* Added getData to ServiceDescriptionInterface +* Added context array to RequestInterface::setState() +* Bug: Removing hard dependency on the BackoffPlugin from Guzzle\Http +* Bug: Adding required content-type when JSON request visitor adds JSON to a command +* Bug: Fixing the serialization of a service description with custom data +* Made it easier to deal with exceptions thrown when transferring commands or requests in parallel by providing + an array of successful and failed responses +* Moved getPath from Guzzle\Service\Resource\Model to Guzzle\Common\Collection +* Added Guzzle\Http\IoEmittingEntityBody +* Moved command filtration from validators to location visitors +* Added `extends` attributes to service description parameters +* Added getModels to ServiceDescriptionInterface + +## 3.0.7 - 2012-12-19 + +* Fixing phar detection when forcing a cacert to system if null or true +* Allowing filename to be passed to `Guzzle\Http\Message\Request::setResponseBody()` +* Cleaning up `Guzzle\Common\Collection::inject` method +* Adding a response_body location to service descriptions + +## 3.0.6 - 2012-12-09 + +* CurlMulti performance improvements +* Adding setErrorResponses() to Operation +* composer.json tweaks + +## 3.0.5 - 2012-11-18 + +* Bug: Fixing an infinite recursion bug caused from revalidating with the CachePlugin +* Bug: Response body can now be a string containing "0" +* Bug: Using Guzzle inside of a phar uses system by default but now allows for a custom cacert +* Bug: QueryString::fromString now properly parses query string parameters that contain equal signs +* Added support for XML attributes in service description responses +* DefaultRequestSerializer now supports array URI parameter values for URI template expansion +* Added better mimetype guessing to requests and post files + +## 3.0.4 - 2012-11-11 + +* Bug: Fixed a bug when adding multiple cookies to a request to use the correct glue value +* Bug: Cookies can now be added that have a name, domain, or value set to "0" +* Bug: Using the system cacert bundle when using the Phar +* Added json and xml methods to Response to make it easier to parse JSON and XML response data into data structures +* Enhanced cookie jar de-duplication +* Added the ability to enable strict cookie jars that throw exceptions when invalid cookies are added +* Added setStream to StreamInterface to actually make it possible to implement custom rewind behavior for entity bodies +* Added the ability to create any sort of hash for a stream rather than just an MD5 hash + +## 3.0.3 - 2012-11-04 + +* Implementing redirects in PHP rather than cURL +* Added PECL URI template extension and using as default parser if available +* Bug: Fixed Content-Length parsing of Response factory +* Adding rewind() method to entity bodies and streams. Allows for custom rewinding of non-repeatable streams. +* Adding ToArrayInterface throughout library +* Fixing OauthPlugin to create unique nonce values per request + +## 3.0.2 - 2012-10-25 + +* Magic methods are enabled by default on clients +* Magic methods return the result of a command +* Service clients no longer require a base_url option in the factory +* Bug: Fixed an issue with URI templates where null template variables were being expanded + +## 3.0.1 - 2012-10-22 + +* Models can now be used like regular collection objects by calling filter, map, etc. +* Models no longer require a Parameter structure or initial data in the constructor +* Added a custom AppendIterator to get around a PHP bug with the `\AppendIterator` + +## 3.0.0 - 2012-10-15 + +* Rewrote service description format to be based on Swagger + * Now based on JSON schema + * Added nested input structures and nested response models + * Support for JSON and XML input and output models + * Renamed `commands` to `operations` + * Removed dot class notation + * Removed custom types +* Broke the project into smaller top-level namespaces to be more component friendly +* Removed support for XML configs and descriptions. Use arrays or JSON files. +* Removed the Validation component and Inspector +* Moved all cookie code to Guzzle\Plugin\Cookie +* Magic methods on a Guzzle\Service\Client now return the command un-executed. +* Calling getResult() or getResponse() on a command will lazily execute the command if needed. +* Now shipping with cURL's CA certs and using it by default +* Added previousResponse() method to response objects +* No longer sending Accept and Accept-Encoding headers on every request +* Only sending an Expect header by default when a payload is greater than 1MB +* Added/moved client options: + * curl.blacklist to curl.option.blacklist + * Added ssl.certificate_authority +* Added a Guzzle\Iterator component +* Moved plugins from Guzzle\Http\Plugin to Guzzle\Plugin +* Added a more robust backoff retry strategy (replaced the ExponentialBackoffPlugin) +* Added a more robust caching plugin +* Added setBody to response objects +* Updating LogPlugin to use a more flexible MessageFormatter +* Added a completely revamped build process +* Cleaning up Collection class and removing default values from the get method +* Fixed ZF2 cache adapters + +## 2.8.8 - 2012-10-15 + +* Bug: Fixed a cookie issue that caused dot prefixed domains to not match where popular browsers did + +## 2.8.7 - 2012-09-30 + +* Bug: Fixed config file aliases for JSON includes +* Bug: Fixed cookie bug on a request object by using CookieParser to parse cookies on requests +* Bug: Removing the path to a file when sending a Content-Disposition header on a POST upload +* Bug: Hardening request and response parsing to account for missing parts +* Bug: Fixed PEAR packaging +* Bug: Fixed Request::getInfo +* Bug: Fixed cases where CURLM_CALL_MULTI_PERFORM return codes were causing curl transactions to fail +* Adding the ability for the namespace Iterator factory to look in multiple directories +* Added more getters/setters/removers from service descriptions +* Added the ability to remove POST fields from OAuth signatures +* OAuth plugin now supports 2-legged OAuth + +## 2.8.6 - 2012-09-05 + +* Added the ability to modify and build service descriptions +* Added the use of visitors to apply parameters to locations in service descriptions using the dynamic command +* Added a `json` parameter location +* Now allowing dot notation for classes in the CacheAdapterFactory +* Using the union of two arrays rather than an array_merge when extending service builder services and service params +* Ensuring that a service is a string before doing strpos() checks on it when substituting services for references + in service builder config files. +* Services defined in two different config files that include one another will by default replace the previously + defined service, but you can now create services that extend themselves and merge their settings over the previous +* The JsonLoader now supports aliasing filenames with different filenames. This allows you to alias something like + '_default' with a default JSON configuration file. + +## 2.8.5 - 2012-08-29 + +* Bug: Suppressed empty arrays from URI templates +* Bug: Added the missing $options argument from ServiceDescription::factory to enable caching +* Added support for HTTP responses that do not contain a reason phrase in the start-line +* AbstractCommand commands are now invokable +* Added a way to get the data used when signing an Oauth request before a request is sent + +## 2.8.4 - 2012-08-15 + +* Bug: Custom delay time calculations are no longer ignored in the ExponentialBackoffPlugin +* Added the ability to transfer entity bodies as a string rather than streamed. This gets around curl error 65. Set `body_as_string` in a request's curl options to enable. +* Added a StreamInterface, EntityBodyInterface, and added ftell() to Guzzle\Common\Stream +* Added an AbstractEntityBodyDecorator and a ReadLimitEntityBody decorator to transfer only a subset of a decorated stream +* Stream and EntityBody objects will now return the file position to the previous position after a read required operation (e.g. getContentMd5()) +* Added additional response status codes +* Removed SSL information from the default User-Agent header +* DELETE requests can now send an entity body +* Added an EventDispatcher to the ExponentialBackoffPlugin and added an ExponentialBackoffLogger to log backoff retries +* Added the ability of the MockPlugin to consume mocked request bodies +* LogPlugin now exposes request and response objects in the extras array + +## 2.8.3 - 2012-07-30 + +* Bug: Fixed a case where empty POST requests were sent as GET requests +* Bug: Fixed a bug in ExponentialBackoffPlugin that caused fatal errors when retrying an EntityEnclosingRequest that does not have a body +* Bug: Setting the response body of a request to null after completing a request, not when setting the state of a request to new +* Added multiple inheritance to service description commands +* Added an ApiCommandInterface and added `getParamNames()` and `hasParam()` +* Removed the default 2mb size cutoff from the Md5ValidatorPlugin so that it now defaults to validating everything +* Changed CurlMulti::perform to pass a smaller timeout to CurlMulti::executeHandles + +## 2.8.2 - 2012-07-24 + +* Bug: Query string values set to 0 are no longer dropped from the query string +* Bug: A Collection object is no longer created each time a call is made to `Guzzle\Service\Command\AbstractCommand::getRequestHeaders()` +* Bug: `+` is now treated as an encoded space when parsing query strings +* QueryString and Collection performance improvements +* Allowing dot notation for class paths in filters attribute of a service descriptions + +## 2.8.1 - 2012-07-16 + +* Loosening Event Dispatcher dependency +* POST redirects can now be customized using CURLOPT_POSTREDIR + +## 2.8.0 - 2012-07-15 + +* BC: Guzzle\Http\Query + * Query strings with empty variables will always show an equal sign unless the variable is set to QueryString::BLANK (e.g. ?acl= vs ?acl) + * Changed isEncodingValues() and isEncodingFields() to isUrlEncoding() + * Changed setEncodeValues(bool) and setEncodeFields(bool) to useUrlEncoding(bool) + * Changed the aggregation functions of QueryString to be static methods + * Can now use fromString() with querystrings that have a leading ? +* cURL configuration values can be specified in service descriptions using `curl.` prefixed parameters +* Content-Length is set to 0 before emitting the request.before_send event when sending an empty request body +* Cookies are no longer URL decoded by default +* Bug: URI template variables set to null are no longer expanded + +## 2.7.2 - 2012-07-02 + +* BC: Moving things to get ready for subtree splits. Moving Inflection into Common. Moving Guzzle\Http\Parser to Guzzle\Parser. +* BC: Removing Guzzle\Common\Batch\Batch::count() and replacing it with isEmpty() +* CachePlugin now allows for a custom request parameter function to check if a request can be cached +* Bug fix: CachePlugin now only caches GET and HEAD requests by default +* Bug fix: Using header glue when transferring headers over the wire +* Allowing deeply nested arrays for composite variables in URI templates +* Batch divisors can now return iterators or arrays + +## 2.7.1 - 2012-06-26 + +* Minor patch to update version number in UA string +* Updating build process + +## 2.7.0 - 2012-06-25 + +* BC: Inflection classes moved to Guzzle\Inflection. No longer static methods. Can now inject custom inflectors into classes. +* BC: Removed magic setX methods from commands +* BC: Magic methods mapped to service description commands are now inflected in the command factory rather than the client __call() method +* Verbose cURL options are no longer enabled by default. Set curl.debug to true on a client to enable. +* Bug: Now allowing colons in a response start-line (e.g. HTTP/1.1 503 Service Unavailable: Back-end server is at capacity) +* Guzzle\Service\Resource\ResourceIteratorApplyBatched now internally uses the Guzzle\Common\Batch namespace +* Added Guzzle\Service\Plugin namespace and a PluginCollectionPlugin +* Added the ability to set POST fields and files in a service description +* Guzzle\Http\EntityBody::factory() now accepts objects with a __toString() method +* Adding a command.before_prepare event to clients +* Added BatchClosureTransfer and BatchClosureDivisor +* BatchTransferException now includes references to the batch divisor and transfer strategies +* Fixed some tests so that they pass more reliably +* Added Guzzle\Common\Log\ArrayLogAdapter + +## 2.6.6 - 2012-06-10 + +* BC: Removing Guzzle\Http\Plugin\BatchQueuePlugin +* BC: Removing Guzzle\Service\Command\CommandSet +* Adding generic batching system (replaces the batch queue plugin and command set) +* Updating ZF cache and log adapters and now using ZF's composer repository +* Bug: Setting the name of each ApiParam when creating through an ApiCommand +* Adding result_type, result_doc, deprecated, and doc_url to service descriptions +* Bug: Changed the default cookie header casing back to 'Cookie' + +## 2.6.5 - 2012-06-03 + +* BC: Renaming Guzzle\Http\Message\RequestInterface::getResourceUri() to getResource() +* BC: Removing unused AUTH_BASIC and AUTH_DIGEST constants from +* BC: Guzzle\Http\Cookie is now used to manage Set-Cookie data, not Cookie data +* BC: Renaming methods in the CookieJarInterface +* Moving almost all cookie logic out of the CookiePlugin and into the Cookie or CookieJar implementations +* Making the default glue for HTTP headers ';' instead of ',' +* Adding a removeValue to Guzzle\Http\Message\Header +* Adding getCookies() to request interface. +* Making it easier to add event subscribers to HasDispatcherInterface classes. Can now directly call addSubscriber() + +## 2.6.4 - 2012-05-30 + +* BC: Cleaning up how POST files are stored in EntityEnclosingRequest objects. Adding PostFile class. +* BC: Moving ApiCommand specific functionality from the Inspector and on to the ApiCommand +* Bug: Fixing magic method command calls on clients +* Bug: Email constraint only validates strings +* Bug: Aggregate POST fields when POST files are present in curl handle +* Bug: Fixing default User-Agent header +* Bug: Only appending or prepending parameters in commands if they are specified +* Bug: Not requiring response reason phrases or status codes to match a predefined list of codes +* Allowing the use of dot notation for class namespaces when using instance_of constraint +* Added any_match validation constraint +* Added an AsyncPlugin +* Passing request object to the calculateWait method of the ExponentialBackoffPlugin +* Allowing the result of a command object to be changed +* Parsing location and type sub values when instantiating a service description rather than over and over at runtime + +## 2.6.3 - 2012-05-23 + +* [BC] Guzzle\Common\FromConfigInterface no longer requires any config options. +* [BC] Refactoring how POST files are stored on an EntityEnclosingRequest. They are now separate from POST fields. +* You can now use an array of data when creating PUT request bodies in the request factory. +* Removing the requirement that HTTPS requests needed a Cache-Control: public directive to be cacheable. +* [Http] Adding support for Content-Type in multipart POST uploads per upload +* [Http] Added support for uploading multiple files using the same name (foo[0], foo[1]) +* Adding more POST data operations for easier manipulation of POST data. +* You can now set empty POST fields. +* The body of a request is only shown on EntityEnclosingRequest objects that do not use POST files. +* Split the Guzzle\Service\Inspector::validateConfig method into two methods. One to initialize when a command is created, and one to validate. +* CS updates + +## 2.6.2 - 2012-05-19 + +* [Http] Better handling of nested scope requests in CurlMulti. Requests are now always prepares in the send() method rather than the addRequest() method. + +## 2.6.1 - 2012-05-19 + +* [BC] Removing 'path' support in service descriptions. Use 'uri'. +* [BC] Guzzle\Service\Inspector::parseDocBlock is now protected. Adding getApiParamsForClass() with cache. +* [BC] Removing Guzzle\Common\NullObject. Use https://github.com/mtdowling/NullObject if you need it. +* [BC] Removing Guzzle\Common\XmlElement. +* All commands, both dynamic and concrete, have ApiCommand objects. +* Adding a fix for CurlMulti so that if all of the connections encounter some sort of curl error, then the loop exits. +* Adding checks to EntityEnclosingRequest so that empty POST files and fields are ignored. +* Making the method signature of Guzzle\Service\Builder\ServiceBuilder::factory more flexible. + +## 2.6.0 - 2012-05-15 + +* [BC] Moving Guzzle\Service\Builder to Guzzle\Service\Builder\ServiceBuilder +* [BC] Executing a Command returns the result of the command rather than the command +* [BC] Moving all HTTP parsing logic to Guzzle\Http\Parsers. Allows for faster C implementations if needed. +* [BC] Changing the Guzzle\Http\Message\Response::setProtocol() method to accept a protocol and version in separate args. +* [BC] Moving ResourceIterator* to Guzzle\Service\Resource +* [BC] Completely refactored ResourceIterators to iterate over a cloned command object +* [BC] Moved Guzzle\Http\UriTemplate to Guzzle\Http\Parser\UriTemplate\UriTemplate +* [BC] Guzzle\Guzzle is now deprecated +* Moving Guzzle\Common\Guzzle::inject to Guzzle\Common\Collection::inject +* Adding Guzzle\Version class to give version information about Guzzle +* Adding Guzzle\Http\Utils class to provide getDefaultUserAgent() and getHttpDate() +* Adding Guzzle\Curl\CurlVersion to manage caching curl_version() data +* ServiceDescription and ServiceBuilder are now cacheable using similar configs +* Changing the format of XML and JSON service builder configs. Backwards compatible. +* Cleaned up Cookie parsing +* Trimming the default Guzzle User-Agent header +* Adding a setOnComplete() method to Commands that is called when a command completes +* Keeping track of requests that were mocked in the MockPlugin +* Fixed a caching bug in the CacheAdapterFactory +* Inspector objects can be injected into a Command object +* Refactoring a lot of code and tests to be case insensitive when dealing with headers +* Adding Guzzle\Http\Message\HeaderComparison for easy comparison of HTTP headers using a DSL +* Adding the ability to set global option overrides to service builder configs +* Adding the ability to include other service builder config files from within XML and JSON files +* Moving the parseQuery method out of Url and on to QueryString::fromString() as a static factory method. + +## 2.5.0 - 2012-05-08 + +* Major performance improvements +* [BC] Simplifying Guzzle\Common\Collection. Please check to see if you are using features that are now deprecated. +* [BC] Using a custom validation system that allows a flyweight implementation for much faster validation. No longer using Symfony2 Validation component. +* [BC] No longer supporting "{{ }}" for injecting into command or UriTemplates. Use "{}" +* Added the ability to passed parameters to all requests created by a client +* Added callback functionality to the ExponentialBackoffPlugin +* Using microtime in ExponentialBackoffPlugin to allow more granular backoff strategies. +* Rewinding request stream bodies when retrying requests +* Exception is thrown when JSON response body cannot be decoded +* Added configurable magic method calls to clients and commands. This is off by default. +* Fixed a defect that added a hash to every parsed URL part +* Fixed duplicate none generation for OauthPlugin. +* Emitting an event each time a client is generated by a ServiceBuilder +* Using an ApiParams object instead of a Collection for parameters of an ApiCommand +* cache.* request parameters should be renamed to params.cache.* +* Added the ability to set arbitrary curl options on requests (disable_wire, progress, etc.). See CurlHandle. +* Added the ability to disable type validation of service descriptions +* ServiceDescriptions and ServiceBuilders are now Serializable diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/LICENSE b/data/web/inc/lib/vendor/guzzlehttp/guzzle/LICENSE new file mode 100644 index 000000000..fd2375d88 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/LICENSE @@ -0,0 +1,27 @@ +The MIT License (MIT) + +Copyright (c) 2011 Michael Dowling +Copyright (c) 2012 Jeremy Lindblom +Copyright (c) 2014 Graham Campbell +Copyright (c) 2015 Márk Sági-Kazár +Copyright (c) 2015 Tobias Schultze +Copyright (c) 2016 Tobias Nyholm +Copyright (c) 2016 George Mponos + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/README.md b/data/web/inc/lib/vendor/guzzlehttp/guzzle/README.md new file mode 100644 index 000000000..f287fa98d --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/README.md @@ -0,0 +1,94 @@ +![Guzzle](.github/logo.png?raw=true) + +# Guzzle, PHP HTTP client + +[![Latest Version](https://img.shields.io/github/release/guzzle/guzzle.svg?style=flat-square)](https://github.com/guzzle/guzzle/releases) +[![Build Status](https://img.shields.io/github/workflow/status/guzzle/guzzle/CI?label=ci%20build&style=flat-square)](https://github.com/guzzle/guzzle/actions?query=workflow%3ACI) +[![Total Downloads](https://img.shields.io/packagist/dt/guzzlehttp/guzzle.svg?style=flat-square)](https://packagist.org/packages/guzzlehttp/guzzle) + +Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and +trivial to integrate with web services. + +- Simple interface for building query strings, POST requests, streaming large + uploads, streaming large downloads, using HTTP cookies, uploading JSON data, + etc... +- Can send both synchronous and asynchronous requests using the same interface. +- Uses PSR-7 interfaces for requests, responses, and streams. This allows you + to utilize other PSR-7 compatible libraries with Guzzle. +- Supports PSR-18 allowing interoperability between other PSR-18 HTTP Clients. +- Abstracts away the underlying HTTP transport, allowing you to write + environment and transport agnostic code; i.e., no hard dependency on cURL, + PHP streams, sockets, or non-blocking event loops. +- Middleware system allows you to augment and compose client behavior. + +```php +$client = new \GuzzleHttp\Client(); +$response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle'); + +echo $response->getStatusCode(); // 200 +echo $response->getHeaderLine('content-type'); // 'application/json; charset=utf8' +echo $response->getBody(); // '{"id": 1420053, "name": "guzzle", ...}' + +// Send an asynchronous request. +$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org'); +$promise = $client->sendAsync($request)->then(function ($response) { + echo 'I completed! ' . $response->getBody(); +}); + +$promise->wait(); +``` + +## Help and docs + +We use GitHub issues only to discuss bugs and new features. For support please refer to: + +- [Documentation](https://docs.guzzlephp.org) +- [Stack Overflow](https://stackoverflow.com/questions/tagged/guzzle) +- [#guzzle](https://app.slack.com/client/T0D2S9JCT/CE6UAAKL4) channel on [PHP-HTTP Slack](https://slack.httplug.io/) +- [Gitter](https://gitter.im/guzzle/guzzle) + + +## Installing Guzzle + +The recommended way to install Guzzle is through +[Composer](https://getcomposer.org/). + +```bash +composer require guzzlehttp/guzzle +``` + + +## Version Guidance + +| Version | Status | Packagist | Namespace | Repo | Docs | PSR-7 | PHP Version | +|---------|----------------|---------------------|--------------|---------------------|---------------------|-------|--------------| +| 3.x | EOL | `guzzle/guzzle` | `Guzzle` | [v3][guzzle-3-repo] | [v3][guzzle-3-docs] | No | >=5.3.3,<7.0 | +| 4.x | EOL | `guzzlehttp/guzzle` | `GuzzleHttp` | [v4][guzzle-4-repo] | N/A | No | >=5.4,<7.0 | +| 5.x | EOL | `guzzlehttp/guzzle` | `GuzzleHttp` | [v5][guzzle-5-repo] | [v5][guzzle-5-docs] | No | >=5.4,<7.4 | +| 6.x | Security fixes | `guzzlehttp/guzzle` | `GuzzleHttp` | [v6][guzzle-6-repo] | [v6][guzzle-6-docs] | Yes | >=5.5,<8.0 | +| 7.x | Latest | `guzzlehttp/guzzle` | `GuzzleHttp` | [v7][guzzle-7-repo] | [v7][guzzle-7-docs] | Yes | >=7.2.5,<8.2 | + +[guzzle-3-repo]: https://github.com/guzzle/guzzle3 +[guzzle-4-repo]: https://github.com/guzzle/guzzle/tree/4.x +[guzzle-5-repo]: https://github.com/guzzle/guzzle/tree/5.3 +[guzzle-6-repo]: https://github.com/guzzle/guzzle/tree/6.5 +[guzzle-7-repo]: https://github.com/guzzle/guzzle +[guzzle-3-docs]: https://guzzle3.readthedocs.io/ +[guzzle-5-docs]: https://docs.guzzlephp.org/en/5.3/ +[guzzle-6-docs]: https://docs.guzzlephp.org/en/6.5/ +[guzzle-7-docs]: https://docs.guzzlephp.org/en/latest/ + + +## Security + +If you discover a security vulnerability within this package, please send an email to security@tidelift.com. All security vulnerabilities will be promptly addressed. Please do not disclose security-related issues publicly until a fix has been announced. Please see [Security Policy](https://github.com/guzzle/guzzle/security/policy) for more information. + +## License + +Guzzle is made available under the MIT License (MIT). Please see [License File](LICENSE) for more information. + +## For Enterprise + +Available as part of the Tidelift Subscription + +The maintainers of Guzzle and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-guzzle?utm_source=packagist-guzzlehttp-guzzle&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/UPGRADING.md b/data/web/inc/lib/vendor/guzzlehttp/guzzle/UPGRADING.md new file mode 100644 index 000000000..45417a7e1 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/UPGRADING.md @@ -0,0 +1,1253 @@ +Guzzle Upgrade Guide +==================== + +6.0 to 7.0 +---------- + +In order to take advantage of the new features of PHP, Guzzle dropped the support +of PHP 5. The minimum supported PHP version is now PHP 7.2. Type hints and return +types for functions and methods have been added wherever possible. + +Please make sure: +- You are calling a function or a method with the correct type. +- If you extend a class of Guzzle; update all signatures on methods you override. + +#### Other backwards compatibility breaking changes + +- Class `GuzzleHttp\UriTemplate` is removed. +- Class `GuzzleHttp\Exception\SeekException` is removed. +- Classes `GuzzleHttp\Exception\BadResponseException`, `GuzzleHttp\Exception\ClientException`, + `GuzzleHttp\Exception\ServerException` can no longer be initialized with an empty + Response as argument. +- Class `GuzzleHttp\Exception\ConnectException` now extends `GuzzleHttp\Exception\TransferException` + instead of `GuzzleHttp\Exception\RequestException`. +- Function `GuzzleHttp\Exception\ConnectException::getResponse()` is removed. +- Function `GuzzleHttp\Exception\ConnectException::hasResponse()` is removed. +- Constant `GuzzleHttp\ClientInterface::VERSION` is removed. Added `GuzzleHttp\ClientInterface::MAJOR_VERSION` instead. +- Function `GuzzleHttp\Exception\RequestException::getResponseBodySummary` is removed. + Use `\GuzzleHttp\Psr7\get_message_body_summary` as an alternative. +- Function `GuzzleHttp\Cookie\CookieJar::getCookieValue` is removed. +- Request option `exception` is removed. Please use `http_errors`. +- Request option `save_to` is removed. Please use `sink`. +- Pool option `pool_size` is removed. Please use `concurrency`. +- We now look for environment variables in the `$_SERVER` super global, due to thread safety issues with `getenv`. We continue to fallback to `getenv` in CLI environments, for maximum compatibility. +- The `get`, `head`, `put`, `post`, `patch`, `delete`, `getAsync`, `headAsync`, `putAsync`, `postAsync`, `patchAsync`, and `deleteAsync` methods are now implemented as genuine methods on `GuzzleHttp\Client`, with strong typing. The original `__call` implementation remains unchanged for now, for maximum backwards compatibility, but won't be invoked under normal operation. +- The `log` middleware will log the errors with level `error` instead of `notice` +- Support for international domain names (IDN) is now disabled by default, and enabling it requires installing ext-intl, linked against a modern version of the C library (ICU 4.6 or higher). + +#### Native functions calls + +All internal native functions calls of Guzzle are now prefixed with a slash. This +change makes it impossible for method overloading by other libraries or applications. +Example: + +```php +// Before: +curl_version(); + +// After: +\curl_version(); +``` + +For the full diff you can check [here](https://github.com/guzzle/guzzle/compare/6.5.4..master). + +5.0 to 6.0 +---------- + +Guzzle now uses [PSR-7](https://www.php-fig.org/psr/psr-7/) for HTTP messages. +Due to the fact that these messages are immutable, this prompted a refactoring +of Guzzle to use a middleware based system rather than an event system. Any +HTTP message interaction (e.g., `GuzzleHttp\Message\Request`) need to be +updated to work with the new immutable PSR-7 request and response objects. Any +event listeners or subscribers need to be updated to become middleware +functions that wrap handlers (or are injected into a +`GuzzleHttp\HandlerStack`). + +- Removed `GuzzleHttp\BatchResults` +- Removed `GuzzleHttp\Collection` +- Removed `GuzzleHttp\HasDataTrait` +- Removed `GuzzleHttp\ToArrayInterface` +- The `guzzlehttp/streams` dependency has been removed. Stream functionality + is now present in the `GuzzleHttp\Psr7` namespace provided by the + `guzzlehttp/psr7` package. +- Guzzle no longer uses ReactPHP promises and now uses the + `guzzlehttp/promises` library. We use a custom promise library for three + significant reasons: + 1. React promises (at the time of writing this) are recursive. Promise + chaining and promise resolution will eventually blow the stack. Guzzle + promises are not recursive as they use a sort of trampolining technique. + Note: there has been movement in the React project to modify promises to + no longer utilize recursion. + 2. Guzzle needs to have the ability to synchronously block on a promise to + wait for a result. Guzzle promises allows this functionality (and does + not require the use of recursion). + 3. Because we need to be able to wait on a result, doing so using React + promises requires wrapping react promises with RingPHP futures. This + overhead is no longer needed, reducing stack sizes, reducing complexity, + and improving performance. +- `GuzzleHttp\Mimetypes` has been moved to a function in + `GuzzleHttp\Psr7\mimetype_from_extension` and + `GuzzleHttp\Psr7\mimetype_from_filename`. +- `GuzzleHttp\Query` and `GuzzleHttp\QueryParser` have been removed. Query + strings must now be passed into request objects as strings, or provided to + the `query` request option when creating requests with clients. The `query` + option uses PHP's `http_build_query` to convert an array to a string. If you + need a different serialization technique, you will need to pass the query + string in as a string. There are a couple helper functions that will make + working with query strings easier: `GuzzleHttp\Psr7\parse_query` and + `GuzzleHttp\Psr7\build_query`. +- Guzzle no longer has a dependency on RingPHP. Due to the use of a middleware + system based on PSR-7, using RingPHP and it's middleware system as well adds + more complexity than the benefits it provides. All HTTP handlers that were + present in RingPHP have been modified to work directly with PSR-7 messages + and placed in the `GuzzleHttp\Handler` namespace. This significantly reduces + complexity in Guzzle, removes a dependency, and improves performance. RingPHP + will be maintained for Guzzle 5 support, but will no longer be a part of + Guzzle 6. +- As Guzzle now uses a middleware based systems the event system and RingPHP + integration has been removed. Note: while the event system has been removed, + it is possible to add your own type of event system that is powered by the + middleware system. + - Removed the `Event` namespace. + - Removed the `Subscriber` namespace. + - Removed `Transaction` class + - Removed `RequestFsm` + - Removed `RingBridge` + - `GuzzleHttp\Subscriber\Cookie` is now provided by + `GuzzleHttp\Middleware::cookies` + - `GuzzleHttp\Subscriber\HttpError` is now provided by + `GuzzleHttp\Middleware::httpError` + - `GuzzleHttp\Subscriber\History` is now provided by + `GuzzleHttp\Middleware::history` + - `GuzzleHttp\Subscriber\Mock` is now provided by + `GuzzleHttp\Handler\MockHandler` + - `GuzzleHttp\Subscriber\Prepare` is now provided by + `GuzzleHttp\PrepareBodyMiddleware` + - `GuzzleHttp\Subscriber\Redirect` is now provided by + `GuzzleHttp\RedirectMiddleware` +- Guzzle now uses `Psr\Http\Message\UriInterface` (implements in + `GuzzleHttp\Psr7\Uri`) for URI support. `GuzzleHttp\Url` is now gone. +- Static functions in `GuzzleHttp\Utils` have been moved to namespaced + functions under the `GuzzleHttp` namespace. This requires either a Composer + based autoloader or you to include functions.php. +- `GuzzleHttp\ClientInterface::getDefaultOption` has been renamed to + `GuzzleHttp\ClientInterface::getConfig`. +- `GuzzleHttp\ClientInterface::setDefaultOption` has been removed. +- The `json` and `xml` methods of response objects has been removed. With the + migration to strictly adhering to PSR-7 as the interface for Guzzle messages, + adding methods to message interfaces would actually require Guzzle messages + to extend from PSR-7 messages rather then work with them directly. + +## Migrating to middleware + +The change to PSR-7 unfortunately required significant refactoring to Guzzle +due to the fact that PSR-7 messages are immutable. Guzzle 5 relied on an event +system from plugins. The event system relied on mutability of HTTP messages and +side effects in order to work. With immutable messages, you have to change your +workflow to become more about either returning a value (e.g., functional +middlewares) or setting a value on an object. Guzzle v6 has chosen the +functional middleware approach. + +Instead of using the event system to listen for things like the `before` event, +you now create a stack based middleware function that intercepts a request on +the way in and the promise of the response on the way out. This is a much +simpler and more predictable approach than the event system and works nicely +with PSR-7 middleware. Due to the use of promises, the middleware system is +also asynchronous. + +v5: + +```php +use GuzzleHttp\Event\BeforeEvent; +$client = new GuzzleHttp\Client(); +// Get the emitter and listen to the before event. +$client->getEmitter()->on('before', function (BeforeEvent $e) { + // Guzzle v5 events relied on mutation + $e->getRequest()->setHeader('X-Foo', 'Bar'); +}); +``` + +v6: + +In v6, you can modify the request before it is sent using the `mapRequest` +middleware. The idiomatic way in v6 to modify the request/response lifecycle is +to setup a handler middleware stack up front and inject the handler into a +client. + +```php +use GuzzleHttp\Middleware; +// Create a handler stack that has all of the default middlewares attached +$handler = GuzzleHttp\HandlerStack::create(); +// Push the handler onto the handler stack +$handler->push(Middleware::mapRequest(function (RequestInterface $request) { + // Notice that we have to return a request object + return $request->withHeader('X-Foo', 'Bar'); +})); +// Inject the handler into the client +$client = new GuzzleHttp\Client(['handler' => $handler]); +``` + +## POST Requests + +This version added the [`form_params`](http://guzzle.readthedocs.org/en/latest/request-options.html#form_params) +and `multipart` request options. `form_params` is an associative array of +strings or array of strings and is used to serialize an +`application/x-www-form-urlencoded` POST request. The +[`multipart`](http://guzzle.readthedocs.org/en/latest/request-options.html#multipart) +option is now used to send a multipart/form-data POST request. + +`GuzzleHttp\Post\PostFile` has been removed. Use the `multipart` option to add +POST files to a multipart/form-data request. + +The `body` option no longer accepts an array to send POST requests. Please use +`multipart` or `form_params` instead. + +The `base_url` option has been renamed to `base_uri`. + +4.x to 5.0 +---------- + +## Rewritten Adapter Layer + +Guzzle now uses [RingPHP](http://ringphp.readthedocs.org/en/latest) to send +HTTP requests. The `adapter` option in a `GuzzleHttp\Client` constructor +is still supported, but it has now been renamed to `handler`. Instead of +passing a `GuzzleHttp\Adapter\AdapterInterface`, you must now pass a PHP +`callable` that follows the RingPHP specification. + +## Removed Fluent Interfaces + +[Fluent interfaces were removed](https://ocramius.github.io/blog/fluent-interfaces-are-evil/) +from the following classes: + +- `GuzzleHttp\Collection` +- `GuzzleHttp\Url` +- `GuzzleHttp\Query` +- `GuzzleHttp\Post\PostBody` +- `GuzzleHttp\Cookie\SetCookie` + +## Removed functions.php + +Removed "functions.php", so that Guzzle is truly PSR-4 compliant. The following +functions can be used as replacements. + +- `GuzzleHttp\json_decode` -> `GuzzleHttp\Utils::jsonDecode` +- `GuzzleHttp\get_path` -> `GuzzleHttp\Utils::getPath` +- `GuzzleHttp\Utils::setPath` -> `GuzzleHttp\set_path` +- `GuzzleHttp\Pool::batch` -> `GuzzleHttp\batch`. This function is, however, + deprecated in favor of using `GuzzleHttp\Pool::batch()`. + +The "procedural" global client has been removed with no replacement (e.g., +`GuzzleHttp\get()`, `GuzzleHttp\post()`, etc.). Use a `GuzzleHttp\Client` +object as a replacement. + +## `throwImmediately` has been removed + +The concept of "throwImmediately" has been removed from exceptions and error +events. This control mechanism was used to stop a transfer of concurrent +requests from completing. This can now be handled by throwing the exception or +by cancelling a pool of requests or each outstanding future request +individually. + +## headers event has been removed + +Removed the "headers" event. This event was only useful for changing the +body a response once the headers of the response were known. You can implement +a similar behavior in a number of ways. One example might be to use a +FnStream that has access to the transaction being sent. For example, when the +first byte is written, you could check if the response headers match your +expectations, and if so, change the actual stream body that is being +written to. + +## Updates to HTTP Messages + +Removed the `asArray` parameter from +`GuzzleHttp\Message\MessageInterface::getHeader`. If you want to get a header +value as an array, then use the newly added `getHeaderAsArray()` method of +`MessageInterface`. This change makes the Guzzle interfaces compatible with +the PSR-7 interfaces. + +3.x to 4.0 +---------- + +## Overarching changes: + +- Now requires PHP 5.4 or greater. +- No longer requires cURL to send requests. +- Guzzle no longer wraps every exception it throws. Only exceptions that are + recoverable are now wrapped by Guzzle. +- Various namespaces have been removed or renamed. +- No longer requiring the Symfony EventDispatcher. A custom event dispatcher + based on the Symfony EventDispatcher is + now utilized in `GuzzleHttp\Event\EmitterInterface` (resulting in significant + speed and functionality improvements). + +Changes per Guzzle 3.x namespace are described below. + +## Batch + +The `Guzzle\Batch` namespace has been removed. This is best left to +third-parties to implement on top of Guzzle's core HTTP library. + +## Cache + +The `Guzzle\Cache` namespace has been removed. (Todo: No suitable replacement +has been implemented yet, but hoping to utilize a PSR cache interface). + +## Common + +- Removed all of the wrapped exceptions. It's better to use the standard PHP + library for unrecoverable exceptions. +- `FromConfigInterface` has been removed. +- `Guzzle\Common\Version` has been removed. The VERSION constant can be found + at `GuzzleHttp\ClientInterface::VERSION`. + +### Collection + +- `getAll` has been removed. Use `toArray` to convert a collection to an array. +- `inject` has been removed. +- `keySearch` has been removed. +- `getPath` no longer supports wildcard expressions. Use something better like + JMESPath for this. +- `setPath` now supports appending to an existing array via the `[]` notation. + +### Events + +Guzzle no longer requires Symfony's EventDispatcher component. Guzzle now uses +`GuzzleHttp\Event\Emitter`. + +- `Symfony\Component\EventDispatcher\EventDispatcherInterface` is replaced by + `GuzzleHttp\Event\EmitterInterface`. +- `Symfony\Component\EventDispatcher\EventDispatcher` is replaced by + `GuzzleHttp\Event\Emitter`. +- `Symfony\Component\EventDispatcher\Event` is replaced by + `GuzzleHttp\Event\Event`, and Guzzle now has an EventInterface in + `GuzzleHttp\Event\EventInterface`. +- `AbstractHasDispatcher` has moved to a trait, `HasEmitterTrait`, and + `HasDispatcherInterface` has moved to `HasEmitterInterface`. Retrieving the + event emitter of a request, client, etc. now uses the `getEmitter` method + rather than the `getDispatcher` method. + +#### Emitter + +- Use the `once()` method to add a listener that automatically removes itself + the first time it is invoked. +- Use the `listeners()` method to retrieve a list of event listeners rather than + the `getListeners()` method. +- Use `emit()` instead of `dispatch()` to emit an event from an emitter. +- Use `attach()` instead of `addSubscriber()` and `detach()` instead of + `removeSubscriber()`. + +```php +$mock = new Mock(); +// 3.x +$request->getEventDispatcher()->addSubscriber($mock); +$request->getEventDispatcher()->removeSubscriber($mock); +// 4.x +$request->getEmitter()->attach($mock); +$request->getEmitter()->detach($mock); +``` + +Use the `on()` method to add a listener rather than the `addListener()` method. + +```php +// 3.x +$request->getEventDispatcher()->addListener('foo', function (Event $event) { /* ... */ } ); +// 4.x +$request->getEmitter()->on('foo', function (Event $event, $name) { /* ... */ } ); +``` + +## Http + +### General changes + +- The cacert.pem certificate has been moved to `src/cacert.pem`. +- Added the concept of adapters that are used to transfer requests over the + wire. +- Simplified the event system. +- Sending requests in parallel is still possible, but batching is no longer a + concept of the HTTP layer. Instead, you must use the `complete` and `error` + events to asynchronously manage parallel request transfers. +- `Guzzle\Http\Url` has moved to `GuzzleHttp\Url`. +- `Guzzle\Http\QueryString` has moved to `GuzzleHttp\Query`. +- QueryAggregators have been rewritten so that they are simply callable + functions. +- `GuzzleHttp\StaticClient` has been removed. Use the functions provided in + `functions.php` for an easy to use static client instance. +- Exceptions in `GuzzleHttp\Exception` have been updated to all extend from + `GuzzleHttp\Exception\TransferException`. + +### Client + +Calling methods like `get()`, `post()`, `head()`, etc. no longer create and +return a request, but rather creates a request, sends the request, and returns +the response. + +```php +// 3.0 +$request = $client->get('/'); +$response = $request->send(); + +// 4.0 +$response = $client->get('/'); + +// or, to mirror the previous behavior +$request = $client->createRequest('GET', '/'); +$response = $client->send($request); +``` + +`GuzzleHttp\ClientInterface` has changed. + +- The `send` method no longer accepts more than one request. Use `sendAll` to + send multiple requests in parallel. +- `setUserAgent()` has been removed. Use a default request option instead. You + could, for example, do something like: + `$client->setConfig('defaults/headers/User-Agent', 'Foo/Bar ' . $client::getDefaultUserAgent())`. +- `setSslVerification()` has been removed. Use default request options instead, + like `$client->setConfig('defaults/verify', true)`. + +`GuzzleHttp\Client` has changed. + +- The constructor now accepts only an associative array. You can include a + `base_url` string or array to use a URI template as the base URL of a client. + You can also specify a `defaults` key that is an associative array of default + request options. You can pass an `adapter` to use a custom adapter, + `batch_adapter` to use a custom adapter for sending requests in parallel, or + a `message_factory` to change the factory used to create HTTP requests and + responses. +- The client no longer emits a `client.create_request` event. +- Creating requests with a client no longer automatically utilize a URI + template. You must pass an array into a creational method (e.g., + `createRequest`, `get`, `put`, etc.) in order to expand a URI template. + +### Messages + +Messages no longer have references to their counterparts (i.e., a request no +longer has a reference to it's response, and a response no loger has a +reference to its request). This association is now managed through a +`GuzzleHttp\Adapter\TransactionInterface` object. You can get references to +these transaction objects using request events that are emitted over the +lifecycle of a request. + +#### Requests with a body + +- `GuzzleHttp\Message\EntityEnclosingRequest` and + `GuzzleHttp\Message\EntityEnclosingRequestInterface` have been removed. The + separation between requests that contain a body and requests that do not + contain a body has been removed, and now `GuzzleHttp\Message\RequestInterface` + handles both use cases. +- Any method that previously accepts a `GuzzleHttp\Response` object now accept a + `GuzzleHttp\Message\ResponseInterface`. +- `GuzzleHttp\Message\RequestFactoryInterface` has been renamed to + `GuzzleHttp\Message\MessageFactoryInterface`. This interface is used to create + both requests and responses and is implemented in + `GuzzleHttp\Message\MessageFactory`. +- POST field and file methods have been removed from the request object. You + must now use the methods made available to `GuzzleHttp\Post\PostBodyInterface` + to control the format of a POST body. Requests that are created using a + standard `GuzzleHttp\Message\MessageFactoryInterface` will automatically use + a `GuzzleHttp\Post\PostBody` body if the body was passed as an array or if + the method is POST and no body is provided. + +```php +$request = $client->createRequest('POST', '/'); +$request->getBody()->setField('foo', 'bar'); +$request->getBody()->addFile(new PostFile('file_key', fopen('/path/to/content', 'r'))); +``` + +#### Headers + +- `GuzzleHttp\Message\Header` has been removed. Header values are now simply + represented by an array of values or as a string. Header values are returned + as a string by default when retrieving a header value from a message. You can + pass an optional argument of `true` to retrieve a header value as an array + of strings instead of a single concatenated string. +- `GuzzleHttp\PostFile` and `GuzzleHttp\PostFileInterface` have been moved to + `GuzzleHttp\Post`. This interface has been simplified and now allows the + addition of arbitrary headers. +- Custom headers like `GuzzleHttp\Message\Header\Link` have been removed. Most + of the custom headers are now handled separately in specific + subscribers/plugins, and `GuzzleHttp\Message\HeaderValues::parseParams()` has + been updated to properly handle headers that contain parameters (like the + `Link` header). + +#### Responses + +- `GuzzleHttp\Message\Response::getInfo()` and + `GuzzleHttp\Message\Response::setInfo()` have been removed. Use the event + system to retrieve this type of information. +- `GuzzleHttp\Message\Response::getRawHeaders()` has been removed. +- `GuzzleHttp\Message\Response::getMessage()` has been removed. +- `GuzzleHttp\Message\Response::calculateAge()` and other cache specific + methods have moved to the CacheSubscriber. +- Header specific helper functions like `getContentMd5()` have been removed. + Just use `getHeader('Content-MD5')` instead. +- `GuzzleHttp\Message\Response::setRequest()` and + `GuzzleHttp\Message\Response::getRequest()` have been removed. Use the event + system to work with request and response objects as a transaction. +- `GuzzleHttp\Message\Response::getRedirectCount()` has been removed. Use the + Redirect subscriber instead. +- `GuzzleHttp\Message\Response::isSuccessful()` and other related methods have + been removed. Use `getStatusCode()` instead. + +#### Streaming responses + +Streaming requests can now be created by a client directly, returning a +`GuzzleHttp\Message\ResponseInterface` object that contains a body stream +referencing an open PHP HTTP stream. + +```php +// 3.0 +use Guzzle\Stream\PhpStreamRequestFactory; +$request = $client->get('/'); +$factory = new PhpStreamRequestFactory(); +$stream = $factory->fromRequest($request); +$data = $stream->read(1024); + +// 4.0 +$response = $client->get('/', ['stream' => true]); +// Read some data off of the stream in the response body +$data = $response->getBody()->read(1024); +``` + +#### Redirects + +The `configureRedirects()` method has been removed in favor of a +`allow_redirects` request option. + +```php +// Standard redirects with a default of a max of 5 redirects +$request = $client->createRequest('GET', '/', ['allow_redirects' => true]); + +// Strict redirects with a custom number of redirects +$request = $client->createRequest('GET', '/', [ + 'allow_redirects' => ['max' => 5, 'strict' => true] +]); +``` + +#### EntityBody + +EntityBody interfaces and classes have been removed or moved to +`GuzzleHttp\Stream`. All classes and interfaces that once required +`GuzzleHttp\EntityBodyInterface` now require +`GuzzleHttp\Stream\StreamInterface`. Creating a new body for a request no +longer uses `GuzzleHttp\EntityBody::factory` but now uses +`GuzzleHttp\Stream\Stream::factory` or even better: +`GuzzleHttp\Stream\create()`. + +- `Guzzle\Http\EntityBodyInterface` is now `GuzzleHttp\Stream\StreamInterface` +- `Guzzle\Http\EntityBody` is now `GuzzleHttp\Stream\Stream` +- `Guzzle\Http\CachingEntityBody` is now `GuzzleHttp\Stream\CachingStream` +- `Guzzle\Http\ReadLimitEntityBody` is now `GuzzleHttp\Stream\LimitStream` +- `Guzzle\Http\IoEmittyinEntityBody` has been removed. + +#### Request lifecycle events + +Requests previously submitted a large number of requests. The number of events +emitted over the lifecycle of a request has been significantly reduced to make +it easier to understand how to extend the behavior of a request. All events +emitted during the lifecycle of a request now emit a custom +`GuzzleHttp\Event\EventInterface` object that contains context providing +methods and a way in which to modify the transaction at that specific point in +time (e.g., intercept the request and set a response on the transaction). + +- `request.before_send` has been renamed to `before` and now emits a + `GuzzleHttp\Event\BeforeEvent` +- `request.complete` has been renamed to `complete` and now emits a + `GuzzleHttp\Event\CompleteEvent`. +- `request.sent` has been removed. Use `complete`. +- `request.success` has been removed. Use `complete`. +- `error` is now an event that emits a `GuzzleHttp\Event\ErrorEvent`. +- `request.exception` has been removed. Use `error`. +- `request.receive.status_line` has been removed. +- `curl.callback.progress` has been removed. Use a custom `StreamInterface` to + maintain a status update. +- `curl.callback.write` has been removed. Use a custom `StreamInterface` to + intercept writes. +- `curl.callback.read` has been removed. Use a custom `StreamInterface` to + intercept reads. + +`headers` is a new event that is emitted after the response headers of a +request have been received before the body of the response is downloaded. This +event emits a `GuzzleHttp\Event\HeadersEvent`. + +You can intercept a request and inject a response using the `intercept()` event +of a `GuzzleHttp\Event\BeforeEvent`, `GuzzleHttp\Event\CompleteEvent`, and +`GuzzleHttp\Event\ErrorEvent` event. + +See: http://docs.guzzlephp.org/en/latest/events.html + +## Inflection + +The `Guzzle\Inflection` namespace has been removed. This is not a core concern +of Guzzle. + +## Iterator + +The `Guzzle\Iterator` namespace has been removed. + +- `Guzzle\Iterator\AppendIterator`, `Guzzle\Iterator\ChunkedIterator`, and + `Guzzle\Iterator\MethodProxyIterator` are nice, but not a core requirement of + Guzzle itself. +- `Guzzle\Iterator\FilterIterator` is no longer needed because an equivalent + class is shipped with PHP 5.4. +- `Guzzle\Iterator\MapIterator` is not really needed when using PHP 5.5 because + it's easier to just wrap an iterator in a generator that maps values. + +For a replacement of these iterators, see https://github.com/nikic/iter + +## Log + +The LogPlugin has moved to https://github.com/guzzle/log-subscriber. The +`Guzzle\Log` namespace has been removed. Guzzle now relies on +`Psr\Log\LoggerInterface` for all logging. The MessageFormatter class has been +moved to `GuzzleHttp\Subscriber\Log\Formatter`. + +## Parser + +The `Guzzle\Parser` namespace has been removed. This was previously used to +make it possible to plug in custom parsers for cookies, messages, URI +templates, and URLs; however, this level of complexity is not needed in Guzzle +so it has been removed. + +- Cookie: Cookie parsing logic has been moved to + `GuzzleHttp\Cookie\SetCookie::fromString`. +- Message: Message parsing logic for both requests and responses has been moved + to `GuzzleHttp\Message\MessageFactory::fromMessage`. Message parsing is only + used in debugging or deserializing messages, so it doesn't make sense for + Guzzle as a library to add this level of complexity to parsing messages. +- UriTemplate: URI template parsing has been moved to + `GuzzleHttp\UriTemplate`. The Guzzle library will automatically use the PECL + URI template library if it is installed. +- Url: URL parsing is now performed in `GuzzleHttp\Url::fromString` (previously + it was `Guzzle\Http\Url::factory()`). If custom URL parsing is necessary, + then developers are free to subclass `GuzzleHttp\Url`. + +## Plugin + +The `Guzzle\Plugin` namespace has been renamed to `GuzzleHttp\Subscriber`. +Several plugins are shipping with the core Guzzle library under this namespace. + +- `GuzzleHttp\Subscriber\Cookie`: Replaces the old CookiePlugin. Cookie jar + code has moved to `GuzzleHttp\Cookie`. +- `GuzzleHttp\Subscriber\History`: Replaces the old HistoryPlugin. +- `GuzzleHttp\Subscriber\HttpError`: Throws errors when a bad HTTP response is + received. +- `GuzzleHttp\Subscriber\Mock`: Replaces the old MockPlugin. +- `GuzzleHttp\Subscriber\Prepare`: Prepares the body of a request just before + sending. This subscriber is attached to all requests by default. +- `GuzzleHttp\Subscriber\Redirect`: Replaces the RedirectPlugin. + +The following plugins have been removed (third-parties are free to re-implement +these if needed): + +- `GuzzleHttp\Plugin\Async` has been removed. +- `GuzzleHttp\Plugin\CurlAuth` has been removed. +- `GuzzleHttp\Plugin\ErrorResponse\ErrorResponsePlugin` has been removed. This + functionality should instead be implemented with event listeners that occur + after normal response parsing occurs in the guzzle/command package. + +The following plugins are not part of the core Guzzle package, but are provided +in separate repositories: + +- `Guzzle\Http\Plugin\BackoffPlugin` has been rewritten to be much simpler + to build custom retry policies using simple functions rather than various + chained classes. See: https://github.com/guzzle/retry-subscriber +- `Guzzle\Http\Plugin\Cache\CachePlugin` has moved to + https://github.com/guzzle/cache-subscriber +- `Guzzle\Http\Plugin\Log\LogPlugin` has moved to + https://github.com/guzzle/log-subscriber +- `Guzzle\Http\Plugin\Md5\Md5Plugin` has moved to + https://github.com/guzzle/message-integrity-subscriber +- `Guzzle\Http\Plugin\Mock\MockPlugin` has moved to + `GuzzleHttp\Subscriber\MockSubscriber`. +- `Guzzle\Http\Plugin\Oauth\OauthPlugin` has moved to + https://github.com/guzzle/oauth-subscriber + +## Service + +The service description layer of Guzzle has moved into two separate packages: + +- http://github.com/guzzle/command Provides a high level abstraction over web + services by representing web service operations using commands. +- http://github.com/guzzle/guzzle-services Provides an implementation of + guzzle/command that provides request serialization and response parsing using + Guzzle service descriptions. + +## Stream + +Stream have moved to a separate package available at +https://github.com/guzzle/streams. + +`Guzzle\Stream\StreamInterface` has been given a large update to cleanly take +on the responsibilities of `Guzzle\Http\EntityBody` and +`Guzzle\Http\EntityBodyInterface` now that they have been removed. The number +of methods implemented by the `StreamInterface` has been drastically reduced to +allow developers to more easily extend and decorate stream behavior. + +## Removed methods from StreamInterface + +- `getStream` and `setStream` have been removed to better encapsulate streams. +- `getMetadata` and `setMetadata` have been removed in favor of + `GuzzleHttp\Stream\MetadataStreamInterface`. +- `getWrapper`, `getWrapperData`, `getStreamType`, and `getUri` have all been + removed. This data is accessible when + using streams that implement `GuzzleHttp\Stream\MetadataStreamInterface`. +- `rewind` has been removed. Use `seek(0)` for a similar behavior. + +## Renamed methods + +- `detachStream` has been renamed to `detach`. +- `feof` has been renamed to `eof`. +- `ftell` has been renamed to `tell`. +- `readLine` has moved from an instance method to a static class method of + `GuzzleHttp\Stream\Stream`. + +## Metadata streams + +`GuzzleHttp\Stream\MetadataStreamInterface` has been added to denote streams +that contain additional metadata accessible via `getMetadata()`. +`GuzzleHttp\Stream\StreamInterface::getMetadata` and +`GuzzleHttp\Stream\StreamInterface::setMetadata` have been removed. + +## StreamRequestFactory + +The entire concept of the StreamRequestFactory has been removed. The way this +was used in Guzzle 3 broke the actual interface of sending streaming requests +(instead of getting back a Response, you got a StreamInterface). Streaming +PHP requests are now implemented through the `GuzzleHttp\Adapter\StreamAdapter`. + +3.6 to 3.7 +---------- + +### Deprecations + +- You can now enable E_USER_DEPRECATED warnings to see if you are using any deprecated methods.: + +```php +\Guzzle\Common\Version::$emitWarnings = true; +``` + +The following APIs and options have been marked as deprecated: + +- Marked `Guzzle\Http\Message\Request::isResponseBodyRepeatable()` as deprecated. Use `$request->getResponseBody()->isRepeatable()` instead. +- Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +- Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +- Marked `Guzzle\Http\Message\Request::setIsRedirect()` as deprecated. Use the HistoryPlugin instead. +- Marked `Guzzle\Http\Message\Request::isRedirect()` as deprecated. Use the HistoryPlugin instead. +- Marked `Guzzle\Cache\CacheAdapterFactory::factory()` as deprecated +- Marked `Guzzle\Service\Client::enableMagicMethods()` as deprecated. Magic methods can no longer be disabled on a Guzzle\Service\Client. +- Marked `Guzzle\Parser\Url\UrlParser` as deprecated. Just use PHP's `parse_url()` and percent encode your UTF-8. +- Marked `Guzzle\Common\Collection::inject()` as deprecated. +- Marked `Guzzle\Plugin\CurlAuth\CurlAuthPlugin` as deprecated. Use + `$client->getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest|NTLM|Any'));` or + `$client->setDefaultOption('auth', array('user', 'pass', 'Basic|Digest|NTLM|Any'));` + +3.7 introduces `request.options` as a parameter for a client configuration and as an optional argument to all creational +request methods. When paired with a client's configuration settings, these options allow you to specify default settings +for various aspects of a request. Because these options make other previous configuration options redundant, several +configuration options and methods of a client and AbstractCommand have been deprecated. + +- Marked `Guzzle\Service\Client::getDefaultHeaders()` as deprecated. Use `$client->getDefaultOption('headers')`. +- Marked `Guzzle\Service\Client::setDefaultHeaders()` as deprecated. Use `$client->setDefaultOption('headers/{header_name}', 'value')`. +- Marked 'request.params' for `Guzzle\Http\Client` as deprecated. Use `$client->setDefaultOption('params/{param_name}', 'value')` +- Marked 'command.headers', 'command.response_body' and 'command.on_complete' as deprecated for AbstractCommand. These will work through Guzzle 4.0 + + $command = $client->getCommand('foo', array( + 'command.headers' => array('Test' => '123'), + 'command.response_body' => '/path/to/file' + )); + + // Should be changed to: + + $command = $client->getCommand('foo', array( + 'command.request_options' => array( + 'headers' => array('Test' => '123'), + 'save_as' => '/path/to/file' + ) + )); + +### Interface changes + +Additions and changes (you will need to update any implementations or subclasses you may have created): + +- Added an `$options` argument to the end of the following methods of `Guzzle\Http\ClientInterface`: + createRequest, head, delete, put, patch, post, options, prepareRequest +- Added an `$options` argument to the end of `Guzzle\Http\Message\Request\RequestFactoryInterface::createRequest()` +- Added an `applyOptions()` method to `Guzzle\Http\Message\Request\RequestFactoryInterface` +- Changed `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $body = null)` to + `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $options = array())`. You can still pass in a + resource, string, or EntityBody into the $options parameter to specify the download location of the response. +- Changed `Guzzle\Common\Collection::__construct($data)` to no longer accepts a null value for `$data` but a + default `array()` +- Added `Guzzle\Stream\StreamInterface::isRepeatable` +- Made `Guzzle\Http\Client::expandTemplate` and `getUriTemplate` protected methods. + +The following methods were removed from interfaces. All of these methods are still available in the concrete classes +that implement them, but you should update your code to use alternative methods: + +- Removed `Guzzle\Http\ClientInterface::setDefaultHeaders(). Use + `$client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. or + `$client->getConfig()->setPath('request.options/headers', array('header_name' => 'value'))` or + `$client->setDefaultOption('headers/{header_name}', 'value')`. or + `$client->setDefaultOption('headers', array('header_name' => 'value'))`. +- Removed `Guzzle\Http\ClientInterface::getDefaultHeaders(). Use `$client->getConfig()->getPath('request.options/headers')`. +- Removed `Guzzle\Http\ClientInterface::expandTemplate()`. This is an implementation detail. +- Removed `Guzzle\Http\ClientInterface::setRequestFactory()`. This is an implementation detail. +- Removed `Guzzle\Http\ClientInterface::getCurlMulti()`. This is a very specific implementation detail. +- Removed `Guzzle\Http\Message\RequestInterface::canCache`. Use the CachePlugin. +- Removed `Guzzle\Http\Message\RequestInterface::setIsRedirect`. Use the HistoryPlugin. +- Removed `Guzzle\Http\Message\RequestInterface::isRedirect`. Use the HistoryPlugin. + +### Cache plugin breaking changes + +- CacheKeyProviderInterface and DefaultCacheKeyProvider are no longer used. All of this logic is handled in a + CacheStorageInterface. These two objects and interface will be removed in a future version. +- Always setting X-cache headers on cached responses +- Default cache TTLs are now handled by the CacheStorageInterface of a CachePlugin +- `CacheStorageInterface::cache($key, Response $response, $ttl = null)` has changed to `cache(RequestInterface + $request, Response $response);` +- `CacheStorageInterface::fetch($key)` has changed to `fetch(RequestInterface $request);` +- `CacheStorageInterface::delete($key)` has changed to `delete(RequestInterface $request);` +- Added `CacheStorageInterface::purge($url)` +- `DefaultRevalidation::__construct(CacheKeyProviderInterface $cacheKey, CacheStorageInterface $cache, CachePlugin + $plugin)` has changed to `DefaultRevalidation::__construct(CacheStorageInterface $cache, + CanCacheStrategyInterface $canCache = null)` +- Added `RevalidationInterface::shouldRevalidate(RequestInterface $request, Response $response)` + +3.5 to 3.6 +---------- + +* Mixed casing of headers are now forced to be a single consistent casing across all values for that header. +* Messages internally use a HeaderCollection object to delegate handling case-insensitive header resolution +* Removed the whole changedHeader() function system of messages because all header changes now go through addHeader(). + For example, setHeader() first removes the header using unset on a HeaderCollection and then calls addHeader(). + Keeping the Host header and URL host in sync is now handled by overriding the addHeader method in Request. +* Specific header implementations can be created for complex headers. When a message creates a header, it uses a + HeaderFactory which can map specific headers to specific header classes. There is now a Link header and + CacheControl header implementation. +* Moved getLinks() from Response to just be used on a Link header object. + +If you previously relied on Guzzle\Http\Message\Header::raw(), then you will need to update your code to use the +HeaderInterface (e.g. toArray(), getAll(), etc.). + +### Interface changes + +* Removed from interface: Guzzle\Http\ClientInterface::setUriTemplate +* Removed from interface: Guzzle\Http\ClientInterface::setCurlMulti() +* Removed Guzzle\Http\Message\Request::receivedRequestHeader() and implemented this functionality in + Guzzle\Http\Curl\RequestMediator +* Removed the optional $asString parameter from MessageInterface::getHeader(). Just cast the header to a string. +* Removed the optional $tryChunkedTransfer option from Guzzle\Http\Message\EntityEnclosingRequestInterface +* Removed the $asObjects argument from Guzzle\Http\Message\MessageInterface::getHeaders() + +### Removed deprecated functions + +* Removed Guzzle\Parser\ParserRegister::get(). Use getParser() +* Removed Guzzle\Parser\ParserRegister::set(). Use registerParser(). + +### Deprecations + +* The ability to case-insensitively search for header values +* Guzzle\Http\Message\Header::hasExactHeader +* Guzzle\Http\Message\Header::raw. Use getAll() +* Deprecated cache control specific methods on Guzzle\Http\Message\AbstractMessage. Use the CacheControl header object + instead. + +### Other changes + +* All response header helper functions return a string rather than mixing Header objects and strings inconsistently +* Removed cURL blacklist support. This is no longer necessary now that Expect, Accept, etc. are managed by Guzzle + directly via interfaces +* Removed the injecting of a request object onto a response object. The methods to get and set a request still exist + but are a no-op until removed. +* Most classes that used to require a `Guzzle\Service\Command\CommandInterface` typehint now request a + `Guzzle\Service\Command\ArrayCommandInterface`. +* Added `Guzzle\Http\Message\RequestInterface::startResponse()` to the RequestInterface to handle injecting a response + on a request while the request is still being transferred +* `Guzzle\Service\Command\CommandInterface` now extends from ToArrayInterface and ArrayAccess + +3.3 to 3.4 +---------- + +Base URLs of a client now follow the rules of https://tools.ietf.org/html/rfc3986#section-5.2.2 when merging URLs. + +3.2 to 3.3 +---------- + +### Response::getEtag() quote stripping removed + +`Guzzle\Http\Message\Response::getEtag()` no longer strips quotes around the ETag response header + +### Removed `Guzzle\Http\Utils` + +The `Guzzle\Http\Utils` class was removed. This class was only used for testing. + +### Stream wrapper and type + +`Guzzle\Stream\Stream::getWrapper()` and `Guzzle\Stream\Stream::getStreamType()` are no longer converted to lowercase. + +### curl.emit_io became emit_io + +Emitting IO events from a RequestMediator is now a parameter that must be set in a request's curl options using the +'emit_io' key. This was previously set under a request's parameters using 'curl.emit_io' + +3.1 to 3.2 +---------- + +### CurlMulti is no longer reused globally + +Before 3.2, the same CurlMulti object was reused globally for each client. This can cause issue where plugins added +to a single client can pollute requests dispatched from other clients. + +If you still wish to reuse the same CurlMulti object with each client, then you can add a listener to the +ServiceBuilder's `service_builder.create_client` event to inject a custom CurlMulti object into each client as it is +created. + +```php +$multi = new Guzzle\Http\Curl\CurlMulti(); +$builder = Guzzle\Service\Builder\ServiceBuilder::factory('/path/to/config.json'); +$builder->addListener('service_builder.create_client', function ($event) use ($multi) { + $event['client']->setCurlMulti($multi); +} +}); +``` + +### No default path + +URLs no longer have a default path value of '/' if no path was specified. + +Before: + +```php +$request = $client->get('http://www.foo.com'); +echo $request->getUrl(); +// >> http://www.foo.com/ +``` + +After: + +```php +$request = $client->get('http://www.foo.com'); +echo $request->getUrl(); +// >> http://www.foo.com +``` + +### Less verbose BadResponseException + +The exception message for `Guzzle\Http\Exception\BadResponseException` no longer contains the full HTTP request and +response information. You can, however, get access to the request and response object by calling `getRequest()` or +`getResponse()` on the exception object. + +### Query parameter aggregation + +Multi-valued query parameters are no longer aggregated using a callback function. `Guzzle\Http\Query` now has a +setAggregator() method that accepts a `Guzzle\Http\QueryAggregator\QueryAggregatorInterface` object. This object is +responsible for handling the aggregation of multi-valued query string variables into a flattened hash. + +2.8 to 3.x +---------- + +### Guzzle\Service\Inspector + +Change `\Guzzle\Service\Inspector::fromConfig` to `\Guzzle\Common\Collection::fromConfig` + +**Before** + +```php +use Guzzle\Service\Inspector; + +class YourClient extends \Guzzle\Service\Client +{ + public static function factory($config = array()) + { + $default = array(); + $required = array('base_url', 'username', 'api_key'); + $config = Inspector::fromConfig($config, $default, $required); + + $client = new self( + $config->get('base_url'), + $config->get('username'), + $config->get('api_key') + ); + $client->setConfig($config); + + $client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json')); + + return $client; + } +``` + +**After** + +```php +use Guzzle\Common\Collection; + +class YourClient extends \Guzzle\Service\Client +{ + public static function factory($config = array()) + { + $default = array(); + $required = array('base_url', 'username', 'api_key'); + $config = Collection::fromConfig($config, $default, $required); + + $client = new self( + $config->get('base_url'), + $config->get('username'), + $config->get('api_key') + ); + $client->setConfig($config); + + $client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json')); + + return $client; + } +``` + +### Convert XML Service Descriptions to JSON + +**Before** + +```xml + + + + + + Get a list of groups + + + Uses a search query to get a list of groups + + + + Create a group + + + + + Delete a group by ID + + + + + + + Update a group + + + + + + +``` + +**After** + +```json +{ + "name": "Zendesk REST API v2", + "apiVersion": "2012-12-31", + "description":"Provides access to Zendesk views, groups, tickets, ticket fields, and users", + "operations": { + "list_groups": { + "httpMethod":"GET", + "uri": "groups.json", + "summary": "Get a list of groups" + }, + "search_groups":{ + "httpMethod":"GET", + "uri": "search.json?query=\"{query} type:group\"", + "summary": "Uses a search query to get a list of groups", + "parameters":{ + "query":{ + "location": "uri", + "description":"Zendesk Search Query", + "type": "string", + "required": true + } + } + }, + "create_group": { + "httpMethod":"POST", + "uri": "groups.json", + "summary": "Create a group", + "parameters":{ + "data": { + "type": "array", + "location": "body", + "description":"Group JSON", + "filters": "json_encode", + "required": true + }, + "Content-Type":{ + "type": "string", + "location":"header", + "static": "application/json" + } + } + }, + "delete_group": { + "httpMethod":"DELETE", + "uri": "groups/{id}.json", + "summary": "Delete a group", + "parameters":{ + "id":{ + "location": "uri", + "description":"Group to delete by ID", + "type": "integer", + "required": true + } + } + }, + "get_group": { + "httpMethod":"GET", + "uri": "groups/{id}.json", + "summary": "Get a ticket", + "parameters":{ + "id":{ + "location": "uri", + "description":"Group to get by ID", + "type": "integer", + "required": true + } + } + }, + "update_group": { + "httpMethod":"PUT", + "uri": "groups/{id}.json", + "summary": "Update a group", + "parameters":{ + "id": { + "location": "uri", + "description":"Group to update by ID", + "type": "integer", + "required": true + }, + "data": { + "type": "array", + "location": "body", + "description":"Group JSON", + "filters": "json_encode", + "required": true + }, + "Content-Type":{ + "type": "string", + "location":"header", + "static": "application/json" + } + } + } +} +``` + +### Guzzle\Service\Description\ServiceDescription + +Commands are now called Operations + +**Before** + +```php +use Guzzle\Service\Description\ServiceDescription; + +$sd = new ServiceDescription(); +$sd->getCommands(); // @returns ApiCommandInterface[] +$sd->hasCommand($name); +$sd->getCommand($name); // @returns ApiCommandInterface|null +$sd->addCommand($command); // @param ApiCommandInterface $command +``` + +**After** + +```php +use Guzzle\Service\Description\ServiceDescription; + +$sd = new ServiceDescription(); +$sd->getOperations(); // @returns OperationInterface[] +$sd->hasOperation($name); +$sd->getOperation($name); // @returns OperationInterface|null +$sd->addOperation($operation); // @param OperationInterface $operation +``` + +### Guzzle\Common\Inflection\Inflector + +Namespace is now `Guzzle\Inflection\Inflector` + +### Guzzle\Http\Plugin + +Namespace is now `Guzzle\Plugin`. Many other changes occur within this namespace and are detailed in their own sections below. + +### Guzzle\Http\Plugin\LogPlugin and Guzzle\Common\Log + +Now `Guzzle\Plugin\Log\LogPlugin` and `Guzzle\Log` respectively. + +**Before** + +```php +use Guzzle\Common\Log\ClosureLogAdapter; +use Guzzle\Http\Plugin\LogPlugin; + +/** @var \Guzzle\Http\Client */ +$client; + +// $verbosity is an integer indicating desired message verbosity level +$client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $verbosity = LogPlugin::LOG_VERBOSE); +``` + +**After** + +```php +use Guzzle\Log\ClosureLogAdapter; +use Guzzle\Log\MessageFormatter; +use Guzzle\Plugin\Log\LogPlugin; + +/** @var \Guzzle\Http\Client */ +$client; + +// $format is a string indicating desired message format -- @see MessageFormatter +$client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $format = MessageFormatter::DEBUG_FORMAT); +``` + +### Guzzle\Http\Plugin\CurlAuthPlugin + +Now `Guzzle\Plugin\CurlAuth\CurlAuthPlugin`. + +### Guzzle\Http\Plugin\ExponentialBackoffPlugin + +Now `Guzzle\Plugin\Backoff\BackoffPlugin`, and other changes. + +**Before** + +```php +use Guzzle\Http\Plugin\ExponentialBackoffPlugin; + +$backoffPlugin = new ExponentialBackoffPlugin($maxRetries, array_merge( + ExponentialBackoffPlugin::getDefaultFailureCodes(), array(429) + )); + +$client->addSubscriber($backoffPlugin); +``` + +**After** + +```php +use Guzzle\Plugin\Backoff\BackoffPlugin; +use Guzzle\Plugin\Backoff\HttpBackoffStrategy; + +// Use convenient factory method instead -- see implementation for ideas of what +// you can do with chaining backoff strategies +$backoffPlugin = BackoffPlugin::getExponentialBackoff($maxRetries, array_merge( + HttpBackoffStrategy::getDefaultFailureCodes(), array(429) + )); +$client->addSubscriber($backoffPlugin); +``` + +### Known Issues + +#### [BUG] Accept-Encoding header behavior changed unintentionally. + +(See #217) (Fixed in 09daeb8c666fb44499a0646d655a8ae36456575e) + +In version 2.8 setting the `Accept-Encoding` header would set the CURLOPT_ENCODING option, which permitted cURL to +properly handle gzip/deflate compressed responses from the server. In versions affected by this bug this does not happen. +See issue #217 for a workaround, or use a version containing the fix. diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/composer.json b/data/web/inc/lib/vendor/guzzlehttp/guzzle/composer.json new file mode 100644 index 000000000..f369ce67e --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/composer.json @@ -0,0 +1,105 @@ +{ + "name": "guzzlehttp/guzzle", + "description": "Guzzle is a PHP HTTP client library", + "keywords": [ + "framework", + "http", + "rest", + "web service", + "curl", + "client", + "HTTP client", + "PSR-7", + "PSR-18" + ], + "license": "MIT", + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Jeremy Lindblom", + "email": "jeremeamia@gmail.com", + "homepage": "https://github.com/jeremeamia" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "require": { + "php": "^7.2.5 || ^8.0", + "ext-json": "*", + "guzzlehttp/promises": "^1.5", + "guzzlehttp/psr7": "^1.9 || ^2.4", + "psr/http-client": "^1.0", + "symfony/deprecation-contracts": "^2.2 || ^3.0" + }, + "provide": { + "psr/http-client-implementation": "1.0" + }, + "require-dev": { + "ext-curl": "*", + "bamarni/composer-bin-plugin": "^1.8.1", + "php-http/client-integration-tests": "^3.0", + "phpunit/phpunit": "^8.5.29 || ^9.5.23", + "psr/log": "^1.1 || ^2.0 || ^3.0" + }, + "suggest": { + "ext-curl": "Required for CURL handler support", + "ext-intl": "Required for Internationalized Domain Name (IDN) support", + "psr/log": "Required for using the Log middleware" + }, + "config": { + "allow-plugins": { + "bamarni/composer-bin-plugin": true + }, + "preferred-install": "dist", + "sort-packages": true + }, + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + }, + "branch-alias": { + "dev-master": "7.5-dev" + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "autoload-dev": { + "psr-4": { + "GuzzleHttp\\Tests\\": "tests/" + } + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/BodySummarizer.php b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/BodySummarizer.php new file mode 100644 index 000000000..6eca94ef9 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/BodySummarizer.php @@ -0,0 +1,28 @@ +truncateAt = $truncateAt; + } + + /** + * Returns a summarized message body. + */ + public function summarize(MessageInterface $message): ?string + { + return $this->truncateAt === null + ? \GuzzleHttp\Psr7\Message::bodySummary($message) + : \GuzzleHttp\Psr7\Message::bodySummary($message, $this->truncateAt); + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/BodySummarizerInterface.php b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/BodySummarizerInterface.php new file mode 100644 index 000000000..3e02e036e --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/BodySummarizerInterface.php @@ -0,0 +1,13 @@ + 'http://www.foo.com/1.0/', + * 'timeout' => 0, + * 'allow_redirects' => false, + * 'proxy' => '192.168.16.1:10' + * ]); + * + * Client configuration settings include the following options: + * + * - handler: (callable) Function that transfers HTTP requests over the + * wire. The function is called with a Psr7\Http\Message\RequestInterface + * and array of transfer options, and must return a + * GuzzleHttp\Promise\PromiseInterface that is fulfilled with a + * Psr7\Http\Message\ResponseInterface on success. + * If no handler is provided, a default handler will be created + * that enables all of the request options below by attaching all of the + * default middleware to the handler. + * - base_uri: (string|UriInterface) Base URI of the client that is merged + * into relative URIs. Can be a string or instance of UriInterface. + * - **: any request option + * + * @param array $config Client configuration settings. + * + * @see \GuzzleHttp\RequestOptions for a list of available request options. + */ + public function __construct(array $config = []) + { + if (!isset($config['handler'])) { + $config['handler'] = HandlerStack::create(); + } elseif (!\is_callable($config['handler'])) { + throw new InvalidArgumentException('handler must be a callable'); + } + + // Convert the base_uri to a UriInterface + if (isset($config['base_uri'])) { + $config['base_uri'] = Psr7\Utils::uriFor($config['base_uri']); + } + + $this->configureDefaults($config); + } + + /** + * @param string $method + * @param array $args + * + * @return PromiseInterface|ResponseInterface + * + * @deprecated Client::__call will be removed in guzzlehttp/guzzle:8.0. + */ + public function __call($method, $args) + { + if (\count($args) < 1) { + throw new InvalidArgumentException('Magic request methods require a URI and optional options array'); + } + + $uri = $args[0]; + $opts = $args[1] ?? []; + + return \substr($method, -5) === 'Async' + ? $this->requestAsync(\substr($method, 0, -5), $uri, $opts) + : $this->request($method, $uri, $opts); + } + + /** + * Asynchronously send an HTTP request. + * + * @param array $options Request options to apply to the given + * request and to the transfer. See \GuzzleHttp\RequestOptions. + */ + public function sendAsync(RequestInterface $request, array $options = []): PromiseInterface + { + // Merge the base URI into the request URI if needed. + $options = $this->prepareDefaults($options); + + return $this->transfer( + $request->withUri($this->buildUri($request->getUri(), $options), $request->hasHeader('Host')), + $options + ); + } + + /** + * Send an HTTP request. + * + * @param array $options Request options to apply to the given + * request and to the transfer. See \GuzzleHttp\RequestOptions. + * + * @throws GuzzleException + */ + public function send(RequestInterface $request, array $options = []): ResponseInterface + { + $options[RequestOptions::SYNCHRONOUS] = true; + return $this->sendAsync($request, $options)->wait(); + } + + /** + * The HttpClient PSR (PSR-18) specify this method. + * + * @inheritDoc + */ + public function sendRequest(RequestInterface $request): ResponseInterface + { + $options[RequestOptions::SYNCHRONOUS] = true; + $options[RequestOptions::ALLOW_REDIRECTS] = false; + $options[RequestOptions::HTTP_ERRORS] = false; + + return $this->sendAsync($request, $options)->wait(); + } + + /** + * Create and send an asynchronous HTTP request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string $method HTTP method + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. See \GuzzleHttp\RequestOptions. + */ + public function requestAsync(string $method, $uri = '', array $options = []): PromiseInterface + { + $options = $this->prepareDefaults($options); + // Remove request modifying parameter because it can be done up-front. + $headers = $options['headers'] ?? []; + $body = $options['body'] ?? null; + $version = $options['version'] ?? '1.1'; + // Merge the URI into the base URI. + $uri = $this->buildUri(Psr7\Utils::uriFor($uri), $options); + if (\is_array($body)) { + throw $this->invalidBody(); + } + $request = new Psr7\Request($method, $uri, $headers, $body, $version); + // Remove the option so that they are not doubly-applied. + unset($options['headers'], $options['body'], $options['version']); + + return $this->transfer($request, $options); + } + + /** + * Create and send an HTTP request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string $method HTTP method. + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. See \GuzzleHttp\RequestOptions. + * + * @throws GuzzleException + */ + public function request(string $method, $uri = '', array $options = []): ResponseInterface + { + $options[RequestOptions::SYNCHRONOUS] = true; + return $this->requestAsync($method, $uri, $options)->wait(); + } + + /** + * Get a client configuration option. + * + * These options include default request options of the client, a "handler" + * (if utilized by the concrete client), and a "base_uri" if utilized by + * the concrete client. + * + * @param string|null $option The config option to retrieve. + * + * @return mixed + * + * @deprecated Client::getConfig will be removed in guzzlehttp/guzzle:8.0. + */ + public function getConfig(?string $option = null) + { + return $option === null + ? $this->config + : ($this->config[$option] ?? null); + } + + private function buildUri(UriInterface $uri, array $config): UriInterface + { + if (isset($config['base_uri'])) { + $uri = Psr7\UriResolver::resolve(Psr7\Utils::uriFor($config['base_uri']), $uri); + } + + if (isset($config['idn_conversion']) && ($config['idn_conversion'] !== false)) { + $idnOptions = ($config['idn_conversion'] === true) ? \IDNA_DEFAULT : $config['idn_conversion']; + $uri = Utils::idnUriConvert($uri, $idnOptions); + } + + return $uri->getScheme() === '' && $uri->getHost() !== '' ? $uri->withScheme('http') : $uri; + } + + /** + * Configures the default options for a client. + */ + private function configureDefaults(array $config): void + { + $defaults = [ + 'allow_redirects' => RedirectMiddleware::$defaultSettings, + 'http_errors' => true, + 'decode_content' => true, + 'verify' => true, + 'cookies' => false, + 'idn_conversion' => false, + ]; + + // Use the standard Linux HTTP_PROXY and HTTPS_PROXY if set. + + // We can only trust the HTTP_PROXY environment variable in a CLI + // process due to the fact that PHP has no reliable mechanism to + // get environment variables that start with "HTTP_". + if (\PHP_SAPI === 'cli' && ($proxy = Utils::getenv('HTTP_PROXY'))) { + $defaults['proxy']['http'] = $proxy; + } + + if ($proxy = Utils::getenv('HTTPS_PROXY')) { + $defaults['proxy']['https'] = $proxy; + } + + if ($noProxy = Utils::getenv('NO_PROXY')) { + $cleanedNoProxy = \str_replace(' ', '', $noProxy); + $defaults['proxy']['no'] = \explode(',', $cleanedNoProxy); + } + + $this->config = $config + $defaults; + + if (!empty($config['cookies']) && $config['cookies'] === true) { + $this->config['cookies'] = new CookieJar(); + } + + // Add the default user-agent header. + if (!isset($this->config['headers'])) { + $this->config['headers'] = ['User-Agent' => Utils::defaultUserAgent()]; + } else { + // Add the User-Agent header if one was not already set. + foreach (\array_keys($this->config['headers']) as $name) { + if (\strtolower($name) === 'user-agent') { + return; + } + } + $this->config['headers']['User-Agent'] = Utils::defaultUserAgent(); + } + } + + /** + * Merges default options into the array. + * + * @param array $options Options to modify by reference + */ + private function prepareDefaults(array $options): array + { + $defaults = $this->config; + + if (!empty($defaults['headers'])) { + // Default headers are only added if they are not present. + $defaults['_conditional'] = $defaults['headers']; + unset($defaults['headers']); + } + + // Special handling for headers is required as they are added as + // conditional headers and as headers passed to a request ctor. + if (\array_key_exists('headers', $options)) { + // Allows default headers to be unset. + if ($options['headers'] === null) { + $defaults['_conditional'] = []; + unset($options['headers']); + } elseif (!\is_array($options['headers'])) { + throw new InvalidArgumentException('headers must be an array'); + } + } + + // Shallow merge defaults underneath options. + $result = $options + $defaults; + + // Remove null values. + foreach ($result as $k => $v) { + if ($v === null) { + unset($result[$k]); + } + } + + return $result; + } + + /** + * Transfers the given request and applies request options. + * + * The URI of the request is not modified and the request options are used + * as-is without merging in default options. + * + * @param array $options See \GuzzleHttp\RequestOptions. + */ + private function transfer(RequestInterface $request, array $options): PromiseInterface + { + $request = $this->applyOptions($request, $options); + /** @var HandlerStack $handler */ + $handler = $options['handler']; + + try { + return P\Create::promiseFor($handler($request, $options)); + } catch (\Exception $e) { + return P\Create::rejectionFor($e); + } + } + + /** + * Applies the array of request options to a request. + */ + private function applyOptions(RequestInterface $request, array &$options): RequestInterface + { + $modify = [ + 'set_headers' => [], + ]; + + if (isset($options['headers'])) { + if (array_keys($options['headers']) === range(0, count($options['headers']) - 1)) { + throw new InvalidArgumentException('The headers array must have header name as keys.'); + } + $modify['set_headers'] = $options['headers']; + unset($options['headers']); + } + + if (isset($options['form_params'])) { + if (isset($options['multipart'])) { + throw new InvalidArgumentException('You cannot use ' + . 'form_params and multipart at the same time. Use the ' + . 'form_params option if you want to send application/' + . 'x-www-form-urlencoded requests, and the multipart ' + . 'option to send multipart/form-data requests.'); + } + $options['body'] = \http_build_query($options['form_params'], '', '&'); + unset($options['form_params']); + // Ensure that we don't have the header in different case and set the new value. + $options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']); + $options['_conditional']['Content-Type'] = 'application/x-www-form-urlencoded'; + } + + if (isset($options['multipart'])) { + $options['body'] = new Psr7\MultipartStream($options['multipart']); + unset($options['multipart']); + } + + if (isset($options['json'])) { + $options['body'] = Utils::jsonEncode($options['json']); + unset($options['json']); + // Ensure that we don't have the header in different case and set the new value. + $options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']); + $options['_conditional']['Content-Type'] = 'application/json'; + } + + if (!empty($options['decode_content']) + && $options['decode_content'] !== true + ) { + // Ensure that we don't have the header in different case and set the new value. + $options['_conditional'] = Psr7\Utils::caselessRemove(['Accept-Encoding'], $options['_conditional']); + $modify['set_headers']['Accept-Encoding'] = $options['decode_content']; + } + + if (isset($options['body'])) { + if (\is_array($options['body'])) { + throw $this->invalidBody(); + } + $modify['body'] = Psr7\Utils::streamFor($options['body']); + unset($options['body']); + } + + if (!empty($options['auth']) && \is_array($options['auth'])) { + $value = $options['auth']; + $type = isset($value[2]) ? \strtolower($value[2]) : 'basic'; + switch ($type) { + case 'basic': + // Ensure that we don't have the header in different case and set the new value. + $modify['set_headers'] = Psr7\Utils::caselessRemove(['Authorization'], $modify['set_headers']); + $modify['set_headers']['Authorization'] = 'Basic ' + . \base64_encode("$value[0]:$value[1]"); + break; + case 'digest': + // @todo: Do not rely on curl + $options['curl'][\CURLOPT_HTTPAUTH] = \CURLAUTH_DIGEST; + $options['curl'][\CURLOPT_USERPWD] = "$value[0]:$value[1]"; + break; + case 'ntlm': + $options['curl'][\CURLOPT_HTTPAUTH] = \CURLAUTH_NTLM; + $options['curl'][\CURLOPT_USERPWD] = "$value[0]:$value[1]"; + break; + } + } + + if (isset($options['query'])) { + $value = $options['query']; + if (\is_array($value)) { + $value = \http_build_query($value, '', '&', \PHP_QUERY_RFC3986); + } + if (!\is_string($value)) { + throw new InvalidArgumentException('query must be a string or array'); + } + $modify['query'] = $value; + unset($options['query']); + } + + // Ensure that sink is not an invalid value. + if (isset($options['sink'])) { + // TODO: Add more sink validation? + if (\is_bool($options['sink'])) { + throw new InvalidArgumentException('sink must not be a boolean'); + } + } + + $request = Psr7\Utils::modifyRequest($request, $modify); + if ($request->getBody() instanceof Psr7\MultipartStream) { + // Use a multipart/form-data POST if a Content-Type is not set. + // Ensure that we don't have the header in different case and set the new value. + $options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']); + $options['_conditional']['Content-Type'] = 'multipart/form-data; boundary=' + . $request->getBody()->getBoundary(); + } + + // Merge in conditional headers if they are not present. + if (isset($options['_conditional'])) { + // Build up the changes so it's in a single clone of the message. + $modify = []; + foreach ($options['_conditional'] as $k => $v) { + if (!$request->hasHeader($k)) { + $modify['set_headers'][$k] = $v; + } + } + $request = Psr7\Utils::modifyRequest($request, $modify); + // Don't pass this internal value along to middleware/handlers. + unset($options['_conditional']); + } + + return $request; + } + + /** + * Return an InvalidArgumentException with pre-set message. + */ + private function invalidBody(): InvalidArgumentException + { + return new InvalidArgumentException('Passing in the "body" request ' + . 'option as an array to send a request is not supported. ' + . 'Please use the "form_params" request option to send a ' + . 'application/x-www-form-urlencoded request, or the "multipart" ' + . 'request option to send a multipart/form-data request.'); + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/ClientInterface.php b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/ClientInterface.php new file mode 100644 index 000000000..6aaee61af --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/ClientInterface.php @@ -0,0 +1,84 @@ +request('GET', $uri, $options); + } + + /** + * Create and send an HTTP HEAD request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + * + * @throws GuzzleException + */ + public function head($uri, array $options = []): ResponseInterface + { + return $this->request('HEAD', $uri, $options); + } + + /** + * Create and send an HTTP PUT request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + * + * @throws GuzzleException + */ + public function put($uri, array $options = []): ResponseInterface + { + return $this->request('PUT', $uri, $options); + } + + /** + * Create and send an HTTP POST request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + * + * @throws GuzzleException + */ + public function post($uri, array $options = []): ResponseInterface + { + return $this->request('POST', $uri, $options); + } + + /** + * Create and send an HTTP PATCH request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + * + * @throws GuzzleException + */ + public function patch($uri, array $options = []): ResponseInterface + { + return $this->request('PATCH', $uri, $options); + } + + /** + * Create and send an HTTP DELETE request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + * + * @throws GuzzleException + */ + public function delete($uri, array $options = []): ResponseInterface + { + return $this->request('DELETE', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string $method HTTP method + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + abstract public function requestAsync(string $method, $uri, array $options = []): PromiseInterface; + + /** + * Create and send an asynchronous HTTP GET request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function getAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('GET', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP HEAD request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function headAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('HEAD', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP PUT request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function putAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('PUT', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP POST request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function postAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('POST', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP PATCH request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function patchAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('PATCH', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP DELETE request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function deleteAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('DELETE', $uri, $options); + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Cookie/CookieJar.php b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Cookie/CookieJar.php new file mode 100644 index 000000000..9985a9814 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Cookie/CookieJar.php @@ -0,0 +1,317 @@ +strictMode = $strictMode; + + foreach ($cookieArray as $cookie) { + if (!($cookie instanceof SetCookie)) { + $cookie = new SetCookie($cookie); + } + $this->setCookie($cookie); + } + } + + /** + * Create a new Cookie jar from an associative array and domain. + * + * @param array $cookies Cookies to create the jar from + * @param string $domain Domain to set the cookies to + */ + public static function fromArray(array $cookies, string $domain): self + { + $cookieJar = new self(); + foreach ($cookies as $name => $value) { + $cookieJar->setCookie(new SetCookie([ + 'Domain' => $domain, + 'Name' => $name, + 'Value' => $value, + 'Discard' => true + ])); + } + + return $cookieJar; + } + + /** + * Evaluate if this cookie should be persisted to storage + * that survives between requests. + * + * @param SetCookie $cookie Being evaluated. + * @param bool $allowSessionCookies If we should persist session cookies + */ + public static function shouldPersist(SetCookie $cookie, bool $allowSessionCookies = false): bool + { + if ($cookie->getExpires() || $allowSessionCookies) { + if (!$cookie->getDiscard()) { + return true; + } + } + + return false; + } + + /** + * Finds and returns the cookie based on the name + * + * @param string $name cookie name to search for + * + * @return SetCookie|null cookie that was found or null if not found + */ + public function getCookieByName(string $name): ?SetCookie + { + foreach ($this->cookies as $cookie) { + if ($cookie->getName() !== null && \strcasecmp($cookie->getName(), $name) === 0) { + return $cookie; + } + } + + return null; + } + + /** + * @inheritDoc + */ + public function toArray(): array + { + return \array_map(static function (SetCookie $cookie): array { + return $cookie->toArray(); + }, $this->getIterator()->getArrayCopy()); + } + + /** + * @inheritDoc + */ + public function clear(?string $domain = null, ?string $path = null, ?string $name = null): void + { + if (!$domain) { + $this->cookies = []; + return; + } elseif (!$path) { + $this->cookies = \array_filter( + $this->cookies, + static function (SetCookie $cookie) use ($domain): bool { + return !$cookie->matchesDomain($domain); + } + ); + } elseif (!$name) { + $this->cookies = \array_filter( + $this->cookies, + static function (SetCookie $cookie) use ($path, $domain): bool { + return !($cookie->matchesPath($path) && + $cookie->matchesDomain($domain)); + } + ); + } else { + $this->cookies = \array_filter( + $this->cookies, + static function (SetCookie $cookie) use ($path, $domain, $name) { + return !($cookie->getName() == $name && + $cookie->matchesPath($path) && + $cookie->matchesDomain($domain)); + } + ); + } + } + + /** + * @inheritDoc + */ + public function clearSessionCookies(): void + { + $this->cookies = \array_filter( + $this->cookies, + static function (SetCookie $cookie): bool { + return !$cookie->getDiscard() && $cookie->getExpires(); + } + ); + } + + /** + * @inheritDoc + */ + public function setCookie(SetCookie $cookie): bool + { + // If the name string is empty (but not 0), ignore the set-cookie + // string entirely. + $name = $cookie->getName(); + if (!$name && $name !== '0') { + return false; + } + + // Only allow cookies with set and valid domain, name, value + $result = $cookie->validate(); + if ($result !== true) { + if ($this->strictMode) { + throw new \RuntimeException('Invalid cookie: ' . $result); + } + $this->removeCookieIfEmpty($cookie); + return false; + } + + // Resolve conflicts with previously set cookies + foreach ($this->cookies as $i => $c) { + // Two cookies are identical, when their path, and domain are + // identical. + if ($c->getPath() != $cookie->getPath() || + $c->getDomain() != $cookie->getDomain() || + $c->getName() != $cookie->getName() + ) { + continue; + } + + // The previously set cookie is a discard cookie and this one is + // not so allow the new cookie to be set + if (!$cookie->getDiscard() && $c->getDiscard()) { + unset($this->cookies[$i]); + continue; + } + + // If the new cookie's expiration is further into the future, then + // replace the old cookie + if ($cookie->getExpires() > $c->getExpires()) { + unset($this->cookies[$i]); + continue; + } + + // If the value has changed, we better change it + if ($cookie->getValue() !== $c->getValue()) { + unset($this->cookies[$i]); + continue; + } + + // The cookie exists, so no need to continue + return false; + } + + $this->cookies[] = $cookie; + + return true; + } + + public function count(): int + { + return \count($this->cookies); + } + + /** + * @return \ArrayIterator + */ + public function getIterator(): \ArrayIterator + { + return new \ArrayIterator(\array_values($this->cookies)); + } + + public function extractCookies(RequestInterface $request, ResponseInterface $response): void + { + if ($cookieHeader = $response->getHeader('Set-Cookie')) { + foreach ($cookieHeader as $cookie) { + $sc = SetCookie::fromString($cookie); + if (!$sc->getDomain()) { + $sc->setDomain($request->getUri()->getHost()); + } + if (0 !== \strpos($sc->getPath(), '/')) { + $sc->setPath($this->getCookiePathFromRequest($request)); + } + if (!$sc->matchesDomain($request->getUri()->getHost())) { + continue; + } + // Note: At this point `$sc->getDomain()` being a public suffix should + // be rejected, but we don't want to pull in the full PSL dependency. + $this->setCookie($sc); + } + } + } + + /** + * Computes cookie path following RFC 6265 section 5.1.4 + * + * @link https://tools.ietf.org/html/rfc6265#section-5.1.4 + */ + private function getCookiePathFromRequest(RequestInterface $request): string + { + $uriPath = $request->getUri()->getPath(); + if ('' === $uriPath) { + return '/'; + } + if (0 !== \strpos($uriPath, '/')) { + return '/'; + } + if ('/' === $uriPath) { + return '/'; + } + $lastSlashPos = \strrpos($uriPath, '/'); + if (0 === $lastSlashPos || false === $lastSlashPos) { + return '/'; + } + + return \substr($uriPath, 0, $lastSlashPos); + } + + public function withCookieHeader(RequestInterface $request): RequestInterface + { + $values = []; + $uri = $request->getUri(); + $scheme = $uri->getScheme(); + $host = $uri->getHost(); + $path = $uri->getPath() ?: '/'; + + foreach ($this->cookies as $cookie) { + if ($cookie->matchesPath($path) && + $cookie->matchesDomain($host) && + !$cookie->isExpired() && + (!$cookie->getSecure() || $scheme === 'https') + ) { + $values[] = $cookie->getName() . '=' + . $cookie->getValue(); + } + } + + return $values + ? $request->withHeader('Cookie', \implode('; ', $values)) + : $request; + } + + /** + * If a cookie already exists and the server asks to set it again with a + * null value, the cookie must be deleted. + */ + private function removeCookieIfEmpty(SetCookie $cookie): void + { + $cookieValue = $cookie->getValue(); + if ($cookieValue === null || $cookieValue === '') { + $this->clear( + $cookie->getDomain(), + $cookie->getPath(), + $cookie->getName() + ); + } + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php new file mode 100644 index 000000000..7df374b5b --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php @@ -0,0 +1,79 @@ + + */ +interface CookieJarInterface extends \Countable, \IteratorAggregate +{ + /** + * Create a request with added cookie headers. + * + * If no matching cookies are found in the cookie jar, then no Cookie + * header is added to the request and the same request is returned. + * + * @param RequestInterface $request Request object to modify. + * + * @return RequestInterface returns the modified request. + */ + public function withCookieHeader(RequestInterface $request): RequestInterface; + + /** + * Extract cookies from an HTTP response and store them in the CookieJar. + * + * @param RequestInterface $request Request that was sent + * @param ResponseInterface $response Response that was received + */ + public function extractCookies(RequestInterface $request, ResponseInterface $response): void; + + /** + * Sets a cookie in the cookie jar. + * + * @param SetCookie $cookie Cookie to set. + * + * @return bool Returns true on success or false on failure + */ + public function setCookie(SetCookie $cookie): bool; + + /** + * Remove cookies currently held in the cookie jar. + * + * Invoking this method without arguments will empty the whole cookie jar. + * If given a $domain argument only cookies belonging to that domain will + * be removed. If given a $domain and $path argument, cookies belonging to + * the specified path within that domain are removed. If given all three + * arguments, then the cookie with the specified name, path and domain is + * removed. + * + * @param string|null $domain Clears cookies matching a domain + * @param string|null $path Clears cookies matching a domain and path + * @param string|null $name Clears cookies matching a domain, path, and name + */ + public function clear(?string $domain = null, ?string $path = null, ?string $name = null): void; + + /** + * Discard all sessions cookies. + * + * Removes cookies that don't have an expire field or a have a discard + * field set to true. To be called when the user agent shuts down according + * to RFC 2965. + */ + public function clearSessionCookies(): void; + + /** + * Converts the cookie jar to an array. + */ + public function toArray(): array; +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php new file mode 100644 index 000000000..290236d54 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php @@ -0,0 +1,101 @@ +filename = $cookieFile; + $this->storeSessionCookies = $storeSessionCookies; + + if (\file_exists($cookieFile)) { + $this->load($cookieFile); + } + } + + /** + * Saves the file when shutting down + */ + public function __destruct() + { + $this->save($this->filename); + } + + /** + * Saves the cookies to a file. + * + * @param string $filename File to save + * + * @throws \RuntimeException if the file cannot be found or created + */ + public function save(string $filename): void + { + $json = []; + /** @var SetCookie $cookie */ + foreach ($this as $cookie) { + if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) { + $json[] = $cookie->toArray(); + } + } + + $jsonStr = Utils::jsonEncode($json); + if (false === \file_put_contents($filename, $jsonStr, \LOCK_EX)) { + throw new \RuntimeException("Unable to save file {$filename}"); + } + } + + /** + * Load cookies from a JSON formatted file. + * + * Old cookies are kept unless overwritten by newly loaded ones. + * + * @param string $filename Cookie file to load. + * + * @throws \RuntimeException if the file cannot be loaded. + */ + public function load(string $filename): void + { + $json = \file_get_contents($filename); + if (false === $json) { + throw new \RuntimeException("Unable to load file {$filename}"); + } + if ($json === '') { + return; + } + + $data = Utils::jsonDecode($json, true); + if (\is_array($data)) { + foreach ($data as $cookie) { + $this->setCookie(new SetCookie($cookie)); + } + } elseif (\is_scalar($data) && !empty($data)) { + throw new \RuntimeException("Invalid cookie file: {$filename}"); + } + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php new file mode 100644 index 000000000..5d51ca982 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php @@ -0,0 +1,77 @@ +sessionKey = $sessionKey; + $this->storeSessionCookies = $storeSessionCookies; + $this->load(); + } + + /** + * Saves cookies to session when shutting down + */ + public function __destruct() + { + $this->save(); + } + + /** + * Save cookies to the client session + */ + public function save(): void + { + $json = []; + /** @var SetCookie $cookie */ + foreach ($this as $cookie) { + if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) { + $json[] = $cookie->toArray(); + } + } + + $_SESSION[$this->sessionKey] = \json_encode($json); + } + + /** + * Load the contents of the client session into the data array + */ + protected function load(): void + { + if (!isset($_SESSION[$this->sessionKey])) { + return; + } + $data = \json_decode($_SESSION[$this->sessionKey], true); + if (\is_array($data)) { + foreach ($data as $cookie) { + $this->setCookie(new SetCookie($cookie)); + } + } elseif (\strlen($data)) { + throw new \RuntimeException("Invalid cookie data"); + } + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Cookie/SetCookie.php b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Cookie/SetCookie.php new file mode 100644 index 000000000..a613c77bf --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Cookie/SetCookie.php @@ -0,0 +1,446 @@ + null, + 'Value' => null, + 'Domain' => null, + 'Path' => '/', + 'Max-Age' => null, + 'Expires' => null, + 'Secure' => false, + 'Discard' => false, + 'HttpOnly' => false + ]; + + /** + * @var array Cookie data + */ + private $data; + + /** + * Create a new SetCookie object from a string. + * + * @param string $cookie Set-Cookie header string + */ + public static function fromString(string $cookie): self + { + // Create the default return array + $data = self::$defaults; + // Explode the cookie string using a series of semicolons + $pieces = \array_filter(\array_map('trim', \explode(';', $cookie))); + // The name of the cookie (first kvp) must exist and include an equal sign. + if (!isset($pieces[0]) || \strpos($pieces[0], '=') === false) { + return new self($data); + } + + // Add the cookie pieces into the parsed data array + foreach ($pieces as $part) { + $cookieParts = \explode('=', $part, 2); + $key = \trim($cookieParts[0]); + $value = isset($cookieParts[1]) + ? \trim($cookieParts[1], " \n\r\t\0\x0B") + : true; + + // Only check for non-cookies when cookies have been found + if (!isset($data['Name'])) { + $data['Name'] = $key; + $data['Value'] = $value; + } else { + foreach (\array_keys(self::$defaults) as $search) { + if (!\strcasecmp($search, $key)) { + $data[$search] = $value; + continue 2; + } + } + $data[$key] = $value; + } + } + + return new self($data); + } + + /** + * @param array $data Array of cookie data provided by a Cookie parser + */ + public function __construct(array $data = []) + { + /** @var array|null $replaced will be null in case of replace error */ + $replaced = \array_replace(self::$defaults, $data); + if ($replaced === null) { + throw new \InvalidArgumentException('Unable to replace the default values for the Cookie.'); + } + + $this->data = $replaced; + // Extract the Expires value and turn it into a UNIX timestamp if needed + if (!$this->getExpires() && $this->getMaxAge()) { + // Calculate the Expires date + $this->setExpires(\time() + $this->getMaxAge()); + } elseif (null !== ($expires = $this->getExpires()) && !\is_numeric($expires)) { + $this->setExpires($expires); + } + } + + public function __toString() + { + $str = $this->data['Name'] . '=' . ($this->data['Value'] ?? '') . '; '; + foreach ($this->data as $k => $v) { + if ($k !== 'Name' && $k !== 'Value' && $v !== null && $v !== false) { + if ($k === 'Expires') { + $str .= 'Expires=' . \gmdate('D, d M Y H:i:s \G\M\T', $v) . '; '; + } else { + $str .= ($v === true ? $k : "{$k}={$v}") . '; '; + } + } + } + + return \rtrim($str, '; '); + } + + public function toArray(): array + { + return $this->data; + } + + /** + * Get the cookie name. + * + * @return string + */ + public function getName() + { + return $this->data['Name']; + } + + /** + * Set the cookie name. + * + * @param string $name Cookie name + */ + public function setName($name): void + { + if (!is_string($name)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Name'] = (string) $name; + } + + /** + * Get the cookie value. + * + * @return string|null + */ + public function getValue() + { + return $this->data['Value']; + } + + /** + * Set the cookie value. + * + * @param string $value Cookie value + */ + public function setValue($value): void + { + if (!is_string($value)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Value'] = (string) $value; + } + + /** + * Get the domain. + * + * @return string|null + */ + public function getDomain() + { + return $this->data['Domain']; + } + + /** + * Set the domain of the cookie. + * + * @param string|null $domain + */ + public function setDomain($domain): void + { + if (!is_string($domain) && null !== $domain) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Domain'] = null === $domain ? null : (string) $domain; + } + + /** + * Get the path. + * + * @return string + */ + public function getPath() + { + return $this->data['Path']; + } + + /** + * Set the path of the cookie. + * + * @param string $path Path of the cookie + */ + public function setPath($path): void + { + if (!is_string($path)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Path'] = (string) $path; + } + + /** + * Maximum lifetime of the cookie in seconds. + * + * @return int|null + */ + public function getMaxAge() + { + return null === $this->data['Max-Age'] ? null : (int) $this->data['Max-Age']; + } + + /** + * Set the max-age of the cookie. + * + * @param int|null $maxAge Max age of the cookie in seconds + */ + public function setMaxAge($maxAge): void + { + if (!is_int($maxAge) && null !== $maxAge) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an int or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Max-Age'] = $maxAge === null ? null : (int) $maxAge; + } + + /** + * The UNIX timestamp when the cookie Expires. + * + * @return string|int|null + */ + public function getExpires() + { + return $this->data['Expires']; + } + + /** + * Set the unix timestamp for which the cookie will expire. + * + * @param int|string|null $timestamp Unix timestamp or any English textual datetime description. + */ + public function setExpires($timestamp): void + { + if (!is_int($timestamp) && !is_string($timestamp) && null !== $timestamp) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an int, string or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Expires'] = null === $timestamp ? null : (\is_numeric($timestamp) ? (int) $timestamp : \strtotime((string) $timestamp)); + } + + /** + * Get whether or not this is a secure cookie. + * + * @return bool + */ + public function getSecure() + { + return $this->data['Secure']; + } + + /** + * Set whether or not the cookie is secure. + * + * @param bool $secure Set to true or false if secure + */ + public function setSecure($secure): void + { + if (!is_bool($secure)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Secure'] = (bool) $secure; + } + + /** + * Get whether or not this is a session cookie. + * + * @return bool|null + */ + public function getDiscard() + { + return $this->data['Discard']; + } + + /** + * Set whether or not this is a session cookie. + * + * @param bool $discard Set to true or false if this is a session cookie + */ + public function setDiscard($discard): void + { + if (!is_bool($discard)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Discard'] = (bool) $discard; + } + + /** + * Get whether or not this is an HTTP only cookie. + * + * @return bool + */ + public function getHttpOnly() + { + return $this->data['HttpOnly']; + } + + /** + * Set whether or not this is an HTTP only cookie. + * + * @param bool $httpOnly Set to true or false if this is HTTP only + */ + public function setHttpOnly($httpOnly): void + { + if (!is_bool($httpOnly)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['HttpOnly'] = (bool) $httpOnly; + } + + /** + * Check if the cookie matches a path value. + * + * A request-path path-matches a given cookie-path if at least one of + * the following conditions holds: + * + * - The cookie-path and the request-path are identical. + * - The cookie-path is a prefix of the request-path, and the last + * character of the cookie-path is %x2F ("/"). + * - The cookie-path is a prefix of the request-path, and the first + * character of the request-path that is not included in the cookie- + * path is a %x2F ("/") character. + * + * @param string $requestPath Path to check against + */ + public function matchesPath(string $requestPath): bool + { + $cookiePath = $this->getPath(); + + // Match on exact matches or when path is the default empty "/" + if ($cookiePath === '/' || $cookiePath == $requestPath) { + return true; + } + + // Ensure that the cookie-path is a prefix of the request path. + if (0 !== \strpos($requestPath, $cookiePath)) { + return false; + } + + // Match if the last character of the cookie-path is "/" + if (\substr($cookiePath, -1, 1) === '/') { + return true; + } + + // Match if the first character not included in cookie path is "/" + return \substr($requestPath, \strlen($cookiePath), 1) === '/'; + } + + /** + * Check if the cookie matches a domain value. + * + * @param string $domain Domain to check against + */ + public function matchesDomain(string $domain): bool + { + $cookieDomain = $this->getDomain(); + if (null === $cookieDomain) { + return true; + } + + // Remove the leading '.' as per spec in RFC 6265. + // https://tools.ietf.org/html/rfc6265#section-5.2.3 + $cookieDomain = \ltrim(\strtolower($cookieDomain), '.'); + + $domain = \strtolower($domain); + + // Domain not set or exact match. + if ('' === $cookieDomain || $domain === $cookieDomain) { + return true; + } + + // Matching the subdomain according to RFC 6265. + // https://tools.ietf.org/html/rfc6265#section-5.1.3 + if (\filter_var($domain, \FILTER_VALIDATE_IP)) { + return false; + } + + return (bool) \preg_match('/\.' . \preg_quote($cookieDomain, '/') . '$/', $domain); + } + + /** + * Check if the cookie is expired. + */ + public function isExpired(): bool + { + return $this->getExpires() !== null && \time() > $this->getExpires(); + } + + /** + * Check if the cookie is valid according to RFC 6265. + * + * @return bool|string Returns true if valid or an error message if invalid + */ + public function validate() + { + $name = $this->getName(); + if ($name === '') { + return 'The cookie name must not be empty'; + } + + // Check if any of the invalid characters are present in the cookie name + if (\preg_match( + '/[\x00-\x20\x22\x28-\x29\x2c\x2f\x3a-\x40\x5c\x7b\x7d\x7f]/', + $name + )) { + return 'Cookie name must not contain invalid characters: ASCII ' + . 'Control characters (0-31;127), space, tab and the ' + . 'following characters: ()<>@,;:\"/?={}'; + } + + // Value must not be null. 0 and empty string are valid. Empty strings + // are technically against RFC 6265, but known to happen in the wild. + $value = $this->getValue(); + if ($value === null) { + return 'The cookie value must not be empty'; + } + + // Domains must not be empty, but can be 0. "0" is not a valid internet + // domain, but may be used as server name in a private network. + $domain = $this->getDomain(); + if ($domain === null || $domain === '') { + return 'The cookie domain must not be empty'; + } + + return true; + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Exception/BadResponseException.php b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Exception/BadResponseException.php new file mode 100644 index 000000000..a80956c9d --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Exception/BadResponseException.php @@ -0,0 +1,39 @@ +request = $request; + $this->handlerContext = $handlerContext; + } + + /** + * Get the request that caused the exception + */ + public function getRequest(): RequestInterface + { + return $this->request; + } + + /** + * Get contextual information about the error from the underlying handler. + * + * The contents of this array will vary depending on which handler you are + * using. It may also be just an empty array. Relying on this data will + * couple you to a specific handler, but can give more debug information + * when needed. + */ + public function getHandlerContext(): array + { + return $this->handlerContext; + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Exception/GuzzleException.php b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Exception/GuzzleException.php new file mode 100644 index 000000000..fa3ed6998 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Exception/GuzzleException.php @@ -0,0 +1,9 @@ +getStatusCode() : 0; + parent::__construct($message, $code, $previous); + $this->request = $request; + $this->response = $response; + $this->handlerContext = $handlerContext; + } + + /** + * Wrap non-RequestExceptions with a RequestException + */ + public static function wrapException(RequestInterface $request, \Throwable $e): RequestException + { + return $e instanceof RequestException ? $e : new RequestException($e->getMessage(), $request, null, $e); + } + + /** + * Factory method to create a new exception with a normalized error message + * + * @param RequestInterface $request Request sent + * @param ResponseInterface $response Response received + * @param \Throwable|null $previous Previous exception + * @param array $handlerContext Optional handler context + * @param BodySummarizerInterface|null $bodySummarizer Optional body summarizer + */ + public static function create( + RequestInterface $request, + ResponseInterface $response = null, + \Throwable $previous = null, + array $handlerContext = [], + BodySummarizerInterface $bodySummarizer = null + ): self { + if (!$response) { + return new self( + 'Error completing request', + $request, + null, + $previous, + $handlerContext + ); + } + + $level = (int) \floor($response->getStatusCode() / 100); + if ($level === 4) { + $label = 'Client error'; + $className = ClientException::class; + } elseif ($level === 5) { + $label = 'Server error'; + $className = ServerException::class; + } else { + $label = 'Unsuccessful request'; + $className = __CLASS__; + } + + $uri = $request->getUri(); + $uri = static::obfuscateUri($uri); + + // Client Error: `GET /` resulted in a `404 Not Found` response: + // ... (truncated) + $message = \sprintf( + '%s: `%s %s` resulted in a `%s %s` response', + $label, + $request->getMethod(), + $uri->__toString(), + $response->getStatusCode(), + $response->getReasonPhrase() + ); + + $summary = ($bodySummarizer ?? new BodySummarizer())->summarize($response); + + if ($summary !== null) { + $message .= ":\n{$summary}\n"; + } + + return new $className($message, $request, $response, $previous, $handlerContext); + } + + /** + * Obfuscates URI if there is a username and a password present + */ + private static function obfuscateUri(UriInterface $uri): UriInterface + { + $userInfo = $uri->getUserInfo(); + + if (false !== ($pos = \strpos($userInfo, ':'))) { + return $uri->withUserInfo(\substr($userInfo, 0, $pos), '***'); + } + + return $uri; + } + + /** + * Get the request that caused the exception + */ + public function getRequest(): RequestInterface + { + return $this->request; + } + + /** + * Get the associated response + */ + public function getResponse(): ?ResponseInterface + { + return $this->response; + } + + /** + * Check if a response was received + */ + public function hasResponse(): bool + { + return $this->response !== null; + } + + /** + * Get contextual information about the error from the underlying handler. + * + * The contents of this array will vary depending on which handler you are + * using. It may also be just an empty array. Relying on this data will + * couple you to a specific handler, but can give more debug information + * when needed. + */ + public function getHandlerContext(): array + { + return $this->handlerContext; + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Exception/ServerException.php b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Exception/ServerException.php new file mode 100644 index 000000000..8055e067c --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Exception/ServerException.php @@ -0,0 +1,10 @@ +maxHandles = $maxHandles; + } + + public function create(RequestInterface $request, array $options): EasyHandle + { + if (isset($options['curl']['body_as_string'])) { + $options['_body_as_string'] = $options['curl']['body_as_string']; + unset($options['curl']['body_as_string']); + } + + $easy = new EasyHandle; + $easy->request = $request; + $easy->options = $options; + $conf = $this->getDefaultConf($easy); + $this->applyMethod($easy, $conf); + $this->applyHandlerOptions($easy, $conf); + $this->applyHeaders($easy, $conf); + unset($conf['_headers']); + + // Add handler options from the request configuration options + if (isset($options['curl'])) { + $conf = \array_replace($conf, $options['curl']); + } + + $conf[\CURLOPT_HEADERFUNCTION] = $this->createHeaderFn($easy); + $easy->handle = $this->handles ? \array_pop($this->handles) : \curl_init(); + curl_setopt_array($easy->handle, $conf); + + return $easy; + } + + public function release(EasyHandle $easy): void + { + $resource = $easy->handle; + unset($easy->handle); + + if (\count($this->handles) >= $this->maxHandles) { + \curl_close($resource); + } else { + // Remove all callback functions as they can hold onto references + // and are not cleaned up by curl_reset. Using curl_setopt_array + // does not work for some reason, so removing each one + // individually. + \curl_setopt($resource, \CURLOPT_HEADERFUNCTION, null); + \curl_setopt($resource, \CURLOPT_READFUNCTION, null); + \curl_setopt($resource, \CURLOPT_WRITEFUNCTION, null); + \curl_setopt($resource, \CURLOPT_PROGRESSFUNCTION, null); + \curl_reset($resource); + $this->handles[] = $resource; + } + } + + /** + * Completes a cURL transaction, either returning a response promise or a + * rejected promise. + * + * @param callable(RequestInterface, array): PromiseInterface $handler + * @param CurlFactoryInterface $factory Dictates how the handle is released + */ + public static function finish(callable $handler, EasyHandle $easy, CurlFactoryInterface $factory): PromiseInterface + { + if (isset($easy->options['on_stats'])) { + self::invokeStats($easy); + } + + if (!$easy->response || $easy->errno) { + return self::finishError($handler, $easy, $factory); + } + + // Return the response if it is present and there is no error. + $factory->release($easy); + + // Rewind the body of the response if possible. + $body = $easy->response->getBody(); + if ($body->isSeekable()) { + $body->rewind(); + } + + return new FulfilledPromise($easy->response); + } + + private static function invokeStats(EasyHandle $easy): void + { + $curlStats = \curl_getinfo($easy->handle); + $curlStats['appconnect_time'] = \curl_getinfo($easy->handle, \CURLINFO_APPCONNECT_TIME); + $stats = new TransferStats( + $easy->request, + $easy->response, + $curlStats['total_time'], + $easy->errno, + $curlStats + ); + ($easy->options['on_stats'])($stats); + } + + /** + * @param callable(RequestInterface, array): PromiseInterface $handler + */ + private static function finishError(callable $handler, EasyHandle $easy, CurlFactoryInterface $factory): PromiseInterface + { + // Get error information and release the handle to the factory. + $ctx = [ + 'errno' => $easy->errno, + 'error' => \curl_error($easy->handle), + 'appconnect_time' => \curl_getinfo($easy->handle, \CURLINFO_APPCONNECT_TIME), + ] + \curl_getinfo($easy->handle); + $ctx[self::CURL_VERSION_STR] = \curl_version()['version']; + $factory->release($easy); + + // Retry when nothing is present or when curl failed to rewind. + if (empty($easy->options['_err_message']) && (!$easy->errno || $easy->errno == 65)) { + return self::retryFailedRewind($handler, $easy, $ctx); + } + + return self::createRejection($easy, $ctx); + } + + private static function createRejection(EasyHandle $easy, array $ctx): PromiseInterface + { + static $connectionErrors = [ + \CURLE_OPERATION_TIMEOUTED => true, + \CURLE_COULDNT_RESOLVE_HOST => true, + \CURLE_COULDNT_CONNECT => true, + \CURLE_SSL_CONNECT_ERROR => true, + \CURLE_GOT_NOTHING => true, + ]; + + if ($easy->createResponseException) { + return P\Create::rejectionFor( + new RequestException( + 'An error was encountered while creating the response', + $easy->request, + $easy->response, + $easy->createResponseException, + $ctx + ) + ); + } + + // If an exception was encountered during the onHeaders event, then + // return a rejected promise that wraps that exception. + if ($easy->onHeadersException) { + return P\Create::rejectionFor( + new RequestException( + 'An error was encountered during the on_headers event', + $easy->request, + $easy->response, + $easy->onHeadersException, + $ctx + ) + ); + } + + $message = \sprintf( + 'cURL error %s: %s (%s)', + $ctx['errno'], + $ctx['error'], + 'see https://curl.haxx.se/libcurl/c/libcurl-errors.html' + ); + $uriString = (string) $easy->request->getUri(); + if ($uriString !== '' && false === \strpos($ctx['error'], $uriString)) { + $message .= \sprintf(' for %s', $uriString); + } + + // Create a connection exception if it was a specific error code. + $error = isset($connectionErrors[$easy->errno]) + ? new ConnectException($message, $easy->request, null, $ctx) + : new RequestException($message, $easy->request, $easy->response, null, $ctx); + + return P\Create::rejectionFor($error); + } + + /** + * @return array + */ + private function getDefaultConf(EasyHandle $easy): array + { + $conf = [ + '_headers' => $easy->request->getHeaders(), + \CURLOPT_CUSTOMREQUEST => $easy->request->getMethod(), + \CURLOPT_URL => (string) $easy->request->getUri()->withFragment(''), + \CURLOPT_RETURNTRANSFER => false, + \CURLOPT_HEADER => false, + \CURLOPT_CONNECTTIMEOUT => 150, + ]; + + if (\defined('CURLOPT_PROTOCOLS')) { + $conf[\CURLOPT_PROTOCOLS] = \CURLPROTO_HTTP | \CURLPROTO_HTTPS; + } + + $version = $easy->request->getProtocolVersion(); + if ($version == 1.1) { + $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_1; + } elseif ($version == 2.0) { + $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_2_0; + } else { + $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_0; + } + + return $conf; + } + + private function applyMethod(EasyHandle $easy, array &$conf): void + { + $body = $easy->request->getBody(); + $size = $body->getSize(); + + if ($size === null || $size > 0) { + $this->applyBody($easy->request, $easy->options, $conf); + return; + } + + $method = $easy->request->getMethod(); + if ($method === 'PUT' || $method === 'POST') { + // See https://tools.ietf.org/html/rfc7230#section-3.3.2 + if (!$easy->request->hasHeader('Content-Length')) { + $conf[\CURLOPT_HTTPHEADER][] = 'Content-Length: 0'; + } + } elseif ($method === 'HEAD') { + $conf[\CURLOPT_NOBODY] = true; + unset( + $conf[\CURLOPT_WRITEFUNCTION], + $conf[\CURLOPT_READFUNCTION], + $conf[\CURLOPT_FILE], + $conf[\CURLOPT_INFILE] + ); + } + } + + private function applyBody(RequestInterface $request, array $options, array &$conf): void + { + $size = $request->hasHeader('Content-Length') + ? (int) $request->getHeaderLine('Content-Length') + : null; + + // Send the body as a string if the size is less than 1MB OR if the + // [curl][body_as_string] request value is set. + if (($size !== null && $size < 1000000) || !empty($options['_body_as_string'])) { + $conf[\CURLOPT_POSTFIELDS] = (string) $request->getBody(); + // Don't duplicate the Content-Length header + $this->removeHeader('Content-Length', $conf); + $this->removeHeader('Transfer-Encoding', $conf); + } else { + $conf[\CURLOPT_UPLOAD] = true; + if ($size !== null) { + $conf[\CURLOPT_INFILESIZE] = $size; + $this->removeHeader('Content-Length', $conf); + } + $body = $request->getBody(); + if ($body->isSeekable()) { + $body->rewind(); + } + $conf[\CURLOPT_READFUNCTION] = static function ($ch, $fd, $length) use ($body) { + return $body->read($length); + }; + } + + // If the Expect header is not present, prevent curl from adding it + if (!$request->hasHeader('Expect')) { + $conf[\CURLOPT_HTTPHEADER][] = 'Expect:'; + } + + // cURL sometimes adds a content-type by default. Prevent this. + if (!$request->hasHeader('Content-Type')) { + $conf[\CURLOPT_HTTPHEADER][] = 'Content-Type:'; + } + } + + private function applyHeaders(EasyHandle $easy, array &$conf): void + { + foreach ($conf['_headers'] as $name => $values) { + foreach ($values as $value) { + $value = (string) $value; + if ($value === '') { + // cURL requires a special format for empty headers. + // See https://github.com/guzzle/guzzle/issues/1882 for more details. + $conf[\CURLOPT_HTTPHEADER][] = "$name;"; + } else { + $conf[\CURLOPT_HTTPHEADER][] = "$name: $value"; + } + } + } + + // Remove the Accept header if one was not set + if (!$easy->request->hasHeader('Accept')) { + $conf[\CURLOPT_HTTPHEADER][] = 'Accept:'; + } + } + + /** + * Remove a header from the options array. + * + * @param string $name Case-insensitive header to remove + * @param array $options Array of options to modify + */ + private function removeHeader(string $name, array &$options): void + { + foreach (\array_keys($options['_headers']) as $key) { + if (!\strcasecmp($key, $name)) { + unset($options['_headers'][$key]); + return; + } + } + } + + private function applyHandlerOptions(EasyHandle $easy, array &$conf): void + { + $options = $easy->options; + if (isset($options['verify'])) { + if ($options['verify'] === false) { + unset($conf[\CURLOPT_CAINFO]); + $conf[\CURLOPT_SSL_VERIFYHOST] = 0; + $conf[\CURLOPT_SSL_VERIFYPEER] = false; + } else { + $conf[\CURLOPT_SSL_VERIFYHOST] = 2; + $conf[\CURLOPT_SSL_VERIFYPEER] = true; + if (\is_string($options['verify'])) { + // Throw an error if the file/folder/link path is not valid or doesn't exist. + if (!\file_exists($options['verify'])) { + throw new \InvalidArgumentException("SSL CA bundle not found: {$options['verify']}"); + } + // If it's a directory or a link to a directory use CURLOPT_CAPATH. + // If not, it's probably a file, or a link to a file, so use CURLOPT_CAINFO. + if ( + \is_dir($options['verify']) || + ( + \is_link($options['verify']) === true && + ($verifyLink = \readlink($options['verify'])) !== false && + \is_dir($verifyLink) + ) + ) { + $conf[\CURLOPT_CAPATH] = $options['verify']; + } else { + $conf[\CURLOPT_CAINFO] = $options['verify']; + } + } + } + } + + if (!isset($options['curl'][\CURLOPT_ENCODING]) && !empty($options['decode_content'])) { + $accept = $easy->request->getHeaderLine('Accept-Encoding'); + if ($accept) { + $conf[\CURLOPT_ENCODING] = $accept; + } else { + // The empty string enables all available decoders and implicitly + // sets a matching 'Accept-Encoding' header. + $conf[\CURLOPT_ENCODING] = ''; + // But as the user did not specify any acceptable encodings we need + // to overwrite this implicit header with an empty one. + $conf[\CURLOPT_HTTPHEADER][] = 'Accept-Encoding:'; + } + } + + if (!isset($options['sink'])) { + // Use a default temp stream if no sink was set. + $options['sink'] = \GuzzleHttp\Psr7\Utils::tryFopen('php://temp', 'w+'); + } + $sink = $options['sink']; + if (!\is_string($sink)) { + $sink = \GuzzleHttp\Psr7\Utils::streamFor($sink); + } elseif (!\is_dir(\dirname($sink))) { + // Ensure that the directory exists before failing in curl. + throw new \RuntimeException(\sprintf('Directory %s does not exist for sink value of %s', \dirname($sink), $sink)); + } else { + $sink = new LazyOpenStream($sink, 'w+'); + } + $easy->sink = $sink; + $conf[\CURLOPT_WRITEFUNCTION] = static function ($ch, $write) use ($sink): int { + return $sink->write($write); + }; + + $timeoutRequiresNoSignal = false; + if (isset($options['timeout'])) { + $timeoutRequiresNoSignal |= $options['timeout'] < 1; + $conf[\CURLOPT_TIMEOUT_MS] = $options['timeout'] * 1000; + } + + // CURL default value is CURL_IPRESOLVE_WHATEVER + if (isset($options['force_ip_resolve'])) { + if ('v4' === $options['force_ip_resolve']) { + $conf[\CURLOPT_IPRESOLVE] = \CURL_IPRESOLVE_V4; + } elseif ('v6' === $options['force_ip_resolve']) { + $conf[\CURLOPT_IPRESOLVE] = \CURL_IPRESOLVE_V6; + } + } + + if (isset($options['connect_timeout'])) { + $timeoutRequiresNoSignal |= $options['connect_timeout'] < 1; + $conf[\CURLOPT_CONNECTTIMEOUT_MS] = $options['connect_timeout'] * 1000; + } + + if ($timeoutRequiresNoSignal && \strtoupper(\substr(\PHP_OS, 0, 3)) !== 'WIN') { + $conf[\CURLOPT_NOSIGNAL] = true; + } + + if (isset($options['proxy'])) { + if (!\is_array($options['proxy'])) { + $conf[\CURLOPT_PROXY] = $options['proxy']; + } else { + $scheme = $easy->request->getUri()->getScheme(); + if (isset($options['proxy'][$scheme])) { + $host = $easy->request->getUri()->getHost(); + if (!isset($options['proxy']['no']) || !Utils::isHostInNoProxy($host, $options['proxy']['no'])) { + $conf[\CURLOPT_PROXY] = $options['proxy'][$scheme]; + } + } + } + } + + if (isset($options['cert'])) { + $cert = $options['cert']; + if (\is_array($cert)) { + $conf[\CURLOPT_SSLCERTPASSWD] = $cert[1]; + $cert = $cert[0]; + } + if (!\file_exists($cert)) { + throw new \InvalidArgumentException("SSL certificate not found: {$cert}"); + } + # OpenSSL (versions 0.9.3 and later) also support "P12" for PKCS#12-encoded files. + # see https://curl.se/libcurl/c/CURLOPT_SSLCERTTYPE.html + $ext = pathinfo($cert, \PATHINFO_EXTENSION); + if (preg_match('#^(der|p12)$#i', $ext)) { + $conf[\CURLOPT_SSLCERTTYPE] = strtoupper($ext); + } + $conf[\CURLOPT_SSLCERT] = $cert; + } + + if (isset($options['ssl_key'])) { + if (\is_array($options['ssl_key'])) { + if (\count($options['ssl_key']) === 2) { + [$sslKey, $conf[\CURLOPT_SSLKEYPASSWD]] = $options['ssl_key']; + } else { + [$sslKey] = $options['ssl_key']; + } + } + + $sslKey = $sslKey ?? $options['ssl_key']; + + if (!\file_exists($sslKey)) { + throw new \InvalidArgumentException("SSL private key not found: {$sslKey}"); + } + $conf[\CURLOPT_SSLKEY] = $sslKey; + } + + if (isset($options['progress'])) { + $progress = $options['progress']; + if (!\is_callable($progress)) { + throw new \InvalidArgumentException('progress client option must be callable'); + } + $conf[\CURLOPT_NOPROGRESS] = false; + $conf[\CURLOPT_PROGRESSFUNCTION] = static function ($resource, int $downloadSize, int $downloaded, int $uploadSize, int $uploaded) use ($progress) { + $progress($downloadSize, $downloaded, $uploadSize, $uploaded); + }; + } + + if (!empty($options['debug'])) { + $conf[\CURLOPT_STDERR] = Utils::debugResource($options['debug']); + $conf[\CURLOPT_VERBOSE] = true; + } + } + + /** + * This function ensures that a response was set on a transaction. If one + * was not set, then the request is retried if possible. This error + * typically means you are sending a payload, curl encountered a + * "Connection died, retrying a fresh connect" error, tried to rewind the + * stream, and then encountered a "necessary data rewind wasn't possible" + * error, causing the request to be sent through curl_multi_info_read() + * without an error status. + * + * @param callable(RequestInterface, array): PromiseInterface $handler + */ + private static function retryFailedRewind(callable $handler, EasyHandle $easy, array $ctx): PromiseInterface + { + try { + // Only rewind if the body has been read from. + $body = $easy->request->getBody(); + if ($body->tell() > 0) { + $body->rewind(); + } + } catch (\RuntimeException $e) { + $ctx['error'] = 'The connection unexpectedly failed without ' + . 'providing an error. The request would have been retried, ' + . 'but attempting to rewind the request body failed. ' + . 'Exception: ' . $e; + return self::createRejection($easy, $ctx); + } + + // Retry no more than 3 times before giving up. + if (!isset($easy->options['_curl_retries'])) { + $easy->options['_curl_retries'] = 1; + } elseif ($easy->options['_curl_retries'] == 2) { + $ctx['error'] = 'The cURL request was retried 3 times ' + . 'and did not succeed. The most likely reason for the failure ' + . 'is that cURL was unable to rewind the body of the request ' + . 'and subsequent retries resulted in the same error. Turn on ' + . 'the debug option to see what went wrong. See ' + . 'https://bugs.php.net/bug.php?id=47204 for more information.'; + return self::createRejection($easy, $ctx); + } else { + $easy->options['_curl_retries']++; + } + + return $handler($easy->request, $easy->options); + } + + private function createHeaderFn(EasyHandle $easy): callable + { + if (isset($easy->options['on_headers'])) { + $onHeaders = $easy->options['on_headers']; + + if (!\is_callable($onHeaders)) { + throw new \InvalidArgumentException('on_headers must be callable'); + } + } else { + $onHeaders = null; + } + + return static function ($ch, $h) use ( + $onHeaders, + $easy, + &$startingResponse + ) { + $value = \trim($h); + if ($value === '') { + $startingResponse = true; + try { + $easy->createResponse(); + } catch (\Exception $e) { + $easy->createResponseException = $e; + return -1; + } + if ($onHeaders !== null) { + try { + $onHeaders($easy->response); + } catch (\Exception $e) { + // Associate the exception with the handle and trigger + // a curl header write error by returning 0. + $easy->onHeadersException = $e; + return -1; + } + } + } elseif ($startingResponse) { + $startingResponse = false; + $easy->headers = [$value]; + } else { + $easy->headers[] = $value; + } + return \strlen($h); + }; + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php new file mode 100644 index 000000000..fe57ed5d5 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php @@ -0,0 +1,25 @@ +factory = $options['handle_factory'] + ?? new CurlFactory(3); + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + if (isset($options['delay'])) { + \usleep($options['delay'] * 1000); + } + + $easy = $this->factory->create($request, $options); + \curl_exec($easy->handle); + $easy->errno = \curl_errno($easy->handle); + + return CurlFactory::finish($this, $easy, $this->factory); + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php new file mode 100644 index 000000000..4356d0247 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php @@ -0,0 +1,262 @@ + An array of delay times, indexed by handle id in `addRequest`. + * + * @see CurlMultiHandler::addRequest + */ + private $delays = []; + + /** + * @var array An associative array of CURLMOPT_* options and corresponding values for curl_multi_setopt() + */ + private $options = []; + + /** + * This handler accepts the following options: + * + * - handle_factory: An optional factory used to create curl handles + * - select_timeout: Optional timeout (in seconds) to block before timing + * out while selecting curl handles. Defaults to 1 second. + * - options: An associative array of CURLMOPT_* options and + * corresponding values for curl_multi_setopt() + */ + public function __construct(array $options = []) + { + $this->factory = $options['handle_factory'] ?? new CurlFactory(50); + + if (isset($options['select_timeout'])) { + $this->selectTimeout = $options['select_timeout']; + } elseif ($selectTimeout = Utils::getenv('GUZZLE_CURL_SELECT_TIMEOUT')) { + @trigger_error('Since guzzlehttp/guzzle 7.2.0: Using environment variable GUZZLE_CURL_SELECT_TIMEOUT is deprecated. Use option "select_timeout" instead.', \E_USER_DEPRECATED); + $this->selectTimeout = (int) $selectTimeout; + } else { + $this->selectTimeout = 1; + } + + $this->options = $options['options'] ?? []; + } + + /** + * @param string $name + * + * @return resource|\CurlMultiHandle + * + * @throws \BadMethodCallException when another field as `_mh` will be gotten + * @throws \RuntimeException when curl can not initialize a multi handle + */ + public function __get($name) + { + if ($name !== '_mh') { + throw new \BadMethodCallException("Can not get other property as '_mh'."); + } + + $multiHandle = \curl_multi_init(); + + if (false === $multiHandle) { + throw new \RuntimeException('Can not initialize curl multi handle.'); + } + + $this->_mh = $multiHandle; + + foreach ($this->options as $option => $value) { + // A warning is raised in case of a wrong option. + curl_multi_setopt($this->_mh, $option, $value); + } + + return $this->_mh; + } + + public function __destruct() + { + if (isset($this->_mh)) { + \curl_multi_close($this->_mh); + unset($this->_mh); + } + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + $easy = $this->factory->create($request, $options); + $id = (int) $easy->handle; + + $promise = new Promise( + [$this, 'execute'], + function () use ($id) { + return $this->cancel($id); + } + ); + + $this->addRequest(['easy' => $easy, 'deferred' => $promise]); + + return $promise; + } + + /** + * Ticks the curl event loop. + */ + public function tick(): void + { + // Add any delayed handles if needed. + if ($this->delays) { + $currentTime = Utils::currentTime(); + foreach ($this->delays as $id => $delay) { + if ($currentTime >= $delay) { + unset($this->delays[$id]); + \curl_multi_add_handle( + $this->_mh, + $this->handles[$id]['easy']->handle + ); + } + } + } + + // Step through the task queue which may add additional requests. + P\Utils::queue()->run(); + + if ($this->active && \curl_multi_select($this->_mh, $this->selectTimeout) === -1) { + // Perform a usleep if a select returns -1. + // See: https://bugs.php.net/bug.php?id=61141 + \usleep(250); + } + + while (\curl_multi_exec($this->_mh, $this->active) === \CURLM_CALL_MULTI_PERFORM); + + $this->processMessages(); + } + + /** + * Runs until all outstanding connections have completed. + */ + public function execute(): void + { + $queue = P\Utils::queue(); + + while ($this->handles || !$queue->isEmpty()) { + // If there are no transfers, then sleep for the next delay + if (!$this->active && $this->delays) { + \usleep($this->timeToNext()); + } + $this->tick(); + } + } + + private function addRequest(array $entry): void + { + $easy = $entry['easy']; + $id = (int) $easy->handle; + $this->handles[$id] = $entry; + if (empty($easy->options['delay'])) { + \curl_multi_add_handle($this->_mh, $easy->handle); + } else { + $this->delays[$id] = Utils::currentTime() + ($easy->options['delay'] / 1000); + } + } + + /** + * Cancels a handle from sending and removes references to it. + * + * @param int $id Handle ID to cancel and remove. + * + * @return bool True on success, false on failure. + */ + private function cancel($id): bool + { + if (!is_int($id)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an integer to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + // Cannot cancel if it has been processed. + if (!isset($this->handles[$id])) { + return false; + } + + $handle = $this->handles[$id]['easy']->handle; + unset($this->delays[$id], $this->handles[$id]); + \curl_multi_remove_handle($this->_mh, $handle); + \curl_close($handle); + + return true; + } + + private function processMessages(): void + { + while ($done = \curl_multi_info_read($this->_mh)) { + if ($done['msg'] !== \CURLMSG_DONE) { + // if it's not done, then it would be premature to remove the handle. ref https://github.com/guzzle/guzzle/pull/2892#issuecomment-945150216 + continue; + } + $id = (int) $done['handle']; + \curl_multi_remove_handle($this->_mh, $done['handle']); + + if (!isset($this->handles[$id])) { + // Probably was cancelled. + continue; + } + + $entry = $this->handles[$id]; + unset($this->handles[$id], $this->delays[$id]); + $entry['easy']->errno = $done['result']; + $entry['deferred']->resolve( + CurlFactory::finish($this, $entry['easy'], $this->factory) + ); + } + } + + private function timeToNext(): int + { + $currentTime = Utils::currentTime(); + $nextTime = \PHP_INT_MAX; + foreach ($this->delays as $time) { + if ($time < $nextTime) { + $nextTime = $time; + } + } + + return ((int) \max(0, $nextTime - $currentTime)) * 1000000; + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Handler/EasyHandle.php b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Handler/EasyHandle.php new file mode 100644 index 000000000..224344d7c --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Handler/EasyHandle.php @@ -0,0 +1,112 @@ +headers); + + $normalizedKeys = Utils::normalizeHeaderKeys($headers); + + if (!empty($this->options['decode_content']) && isset($normalizedKeys['content-encoding'])) { + $headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']]; + unset($headers[$normalizedKeys['content-encoding']]); + if (isset($normalizedKeys['content-length'])) { + $headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']]; + + $bodyLength = (int) $this->sink->getSize(); + if ($bodyLength) { + $headers[$normalizedKeys['content-length']] = $bodyLength; + } else { + unset($headers[$normalizedKeys['content-length']]); + } + } + } + + // Attach a response to the easy handle with the parsed headers. + $this->response = new Response( + $status, + $headers, + $this->sink, + $ver, + $reason + ); + } + + /** + * @param string $name + * + * @return void + * + * @throws \BadMethodCallException + */ + public function __get($name) + { + $msg = $name === 'handle' ? 'The EasyHandle has been released' : 'Invalid property: ' . $name; + throw new \BadMethodCallException($msg); + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Handler/HeaderProcessor.php b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Handler/HeaderProcessor.php new file mode 100644 index 000000000..a0988845f --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Handler/HeaderProcessor.php @@ -0,0 +1,42 @@ +|null $queue The parameters to be passed to the append function, as an indexed array. + * @param callable|null $onFulfilled Callback to invoke when the return value is fulfilled. + * @param callable|null $onRejected Callback to invoke when the return value is rejected. + */ + public function __construct(array $queue = null, callable $onFulfilled = null, callable $onRejected = null) + { + $this->onFulfilled = $onFulfilled; + $this->onRejected = $onRejected; + + if ($queue) { + // array_values included for BC + $this->append(...array_values($queue)); + } + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + if (!$this->queue) { + throw new \OutOfBoundsException('Mock queue is empty'); + } + + if (isset($options['delay']) && \is_numeric($options['delay'])) { + \usleep((int) $options['delay'] * 1000); + } + + $this->lastRequest = $request; + $this->lastOptions = $options; + $response = \array_shift($this->queue); + + if (isset($options['on_headers'])) { + if (!\is_callable($options['on_headers'])) { + throw new \InvalidArgumentException('on_headers must be callable'); + } + try { + $options['on_headers']($response); + } catch (\Exception $e) { + $msg = 'An error was encountered during the on_headers event'; + $response = new RequestException($msg, $request, $response, $e); + } + } + + if (\is_callable($response)) { + $response = $response($request, $options); + } + + $response = $response instanceof \Throwable + ? P\Create::rejectionFor($response) + : P\Create::promiseFor($response); + + return $response->then( + function (?ResponseInterface $value) use ($request, $options) { + $this->invokeStats($request, $options, $value); + if ($this->onFulfilled) { + ($this->onFulfilled)($value); + } + + if ($value !== null && isset($options['sink'])) { + $contents = (string) $value->getBody(); + $sink = $options['sink']; + + if (\is_resource($sink)) { + \fwrite($sink, $contents); + } elseif (\is_string($sink)) { + \file_put_contents($sink, $contents); + } elseif ($sink instanceof StreamInterface) { + $sink->write($contents); + } + } + + return $value; + }, + function ($reason) use ($request, $options) { + $this->invokeStats($request, $options, null, $reason); + if ($this->onRejected) { + ($this->onRejected)($reason); + } + return P\Create::rejectionFor($reason); + } + ); + } + + /** + * Adds one or more variadic requests, exceptions, callables, or promises + * to the queue. + * + * @param mixed ...$values + */ + public function append(...$values): void + { + foreach ($values as $value) { + if ($value instanceof ResponseInterface + || $value instanceof \Throwable + || $value instanceof PromiseInterface + || \is_callable($value) + ) { + $this->queue[] = $value; + } else { + throw new \TypeError('Expected a Response, Promise, Throwable or callable. Found ' . Utils::describeType($value)); + } + } + } + + /** + * Get the last received request. + */ + public function getLastRequest(): ?RequestInterface + { + return $this->lastRequest; + } + + /** + * Get the last received request options. + */ + public function getLastOptions(): array + { + return $this->lastOptions; + } + + /** + * Returns the number of remaining items in the queue. + */ + public function count(): int + { + return \count($this->queue); + } + + public function reset(): void + { + $this->queue = []; + } + + /** + * @param mixed $reason Promise or reason. + */ + private function invokeStats( + RequestInterface $request, + array $options, + ResponseInterface $response = null, + $reason = null + ): void { + if (isset($options['on_stats'])) { + $transferTime = $options['transfer_time'] ?? 0; + $stats = new TransferStats($request, $response, $transferTime, $reason); + ($options['on_stats'])($stats); + } + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Handler/Proxy.php b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Handler/Proxy.php new file mode 100644 index 000000000..f045b526c --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Handler/Proxy.php @@ -0,0 +1,51 @@ +withoutHeader('Expect'); + + // Append a content-length header if body size is zero to match + // cURL's behavior. + if (0 === $request->getBody()->getSize()) { + $request = $request->withHeader('Content-Length', '0'); + } + + return $this->createResponse( + $request, + $options, + $this->createStream($request, $options), + $startTime + ); + } catch (\InvalidArgumentException $e) { + throw $e; + } catch (\Exception $e) { + // Determine if the error was a networking error. + $message = $e->getMessage(); + // This list can probably get more comprehensive. + if (false !== \strpos($message, 'getaddrinfo') // DNS lookup failed + || false !== \strpos($message, 'Connection refused') + || false !== \strpos($message, "couldn't connect to host") // error on HHVM + || false !== \strpos($message, "connection attempt failed") + ) { + $e = new ConnectException($e->getMessage(), $request, $e); + } else { + $e = RequestException::wrapException($request, $e); + } + $this->invokeStats($options, $request, $startTime, null, $e); + + return P\Create::rejectionFor($e); + } + } + + private function invokeStats( + array $options, + RequestInterface $request, + ?float $startTime, + ResponseInterface $response = null, + \Throwable $error = null + ): void { + if (isset($options['on_stats'])) { + $stats = new TransferStats($request, $response, Utils::currentTime() - $startTime, $error, []); + ($options['on_stats'])($stats); + } + } + + /** + * @param resource $stream + */ + private function createResponse(RequestInterface $request, array $options, $stream, ?float $startTime): PromiseInterface + { + $hdrs = $this->lastHeaders; + $this->lastHeaders = []; + + try { + [$ver, $status, $reason, $headers] = HeaderProcessor::parseHeaders($hdrs); + } catch (\Exception $e) { + return P\Create::rejectionFor( + new RequestException('An error was encountered while creating the response', $request, null, $e) + ); + } + + [$stream, $headers] = $this->checkDecode($options, $headers, $stream); + $stream = Psr7\Utils::streamFor($stream); + $sink = $stream; + + if (\strcasecmp('HEAD', $request->getMethod())) { + $sink = $this->createSink($stream, $options); + } + + try { + $response = new Psr7\Response($status, $headers, $sink, $ver, $reason); + } catch (\Exception $e) { + return P\Create::rejectionFor( + new RequestException('An error was encountered while creating the response', $request, null, $e) + ); + } + + if (isset($options['on_headers'])) { + try { + $options['on_headers']($response); + } catch (\Exception $e) { + return P\Create::rejectionFor( + new RequestException('An error was encountered during the on_headers event', $request, $response, $e) + ); + } + } + + // Do not drain when the request is a HEAD request because they have + // no body. + if ($sink !== $stream) { + $this->drain($stream, $sink, $response->getHeaderLine('Content-Length')); + } + + $this->invokeStats($options, $request, $startTime, $response, null); + + return new FulfilledPromise($response); + } + + private function createSink(StreamInterface $stream, array $options): StreamInterface + { + if (!empty($options['stream'])) { + return $stream; + } + + $sink = $options['sink'] ?? Psr7\Utils::tryFopen('php://temp', 'r+'); + + return \is_string($sink) ? new Psr7\LazyOpenStream($sink, 'w+') : Psr7\Utils::streamFor($sink); + } + + /** + * @param resource $stream + */ + private function checkDecode(array $options, array $headers, $stream): array + { + // Automatically decode responses when instructed. + if (!empty($options['decode_content'])) { + $normalizedKeys = Utils::normalizeHeaderKeys($headers); + if (isset($normalizedKeys['content-encoding'])) { + $encoding = $headers[$normalizedKeys['content-encoding']]; + if ($encoding[0] === 'gzip' || $encoding[0] === 'deflate') { + $stream = new Psr7\InflateStream(Psr7\Utils::streamFor($stream)); + $headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']]; + + // Remove content-encoding header + unset($headers[$normalizedKeys['content-encoding']]); + + // Fix content-length header + if (isset($normalizedKeys['content-length'])) { + $headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']]; + $length = (int) $stream->getSize(); + if ($length === 0) { + unset($headers[$normalizedKeys['content-length']]); + } else { + $headers[$normalizedKeys['content-length']] = [$length]; + } + } + } + } + } + + return [$stream, $headers]; + } + + /** + * Drains the source stream into the "sink" client option. + * + * @param string $contentLength Header specifying the amount of + * data to read. + * + * @throws \RuntimeException when the sink option is invalid. + */ + private function drain(StreamInterface $source, StreamInterface $sink, string $contentLength): StreamInterface + { + // If a content-length header is provided, then stop reading once + // that number of bytes has been read. This can prevent infinitely + // reading from a stream when dealing with servers that do not honor + // Connection: Close headers. + Psr7\Utils::copyToStream( + $source, + $sink, + (\strlen($contentLength) > 0 && (int) $contentLength > 0) ? (int) $contentLength : -1 + ); + + $sink->seek(0); + $source->close(); + + return $sink; + } + + /** + * Create a resource and check to ensure it was created successfully + * + * @param callable $callback Callable that returns stream resource + * + * @return resource + * + * @throws \RuntimeException on error + */ + private function createResource(callable $callback) + { + $errors = []; + \set_error_handler(static function ($_, $msg, $file, $line) use (&$errors): bool { + $errors[] = [ + 'message' => $msg, + 'file' => $file, + 'line' => $line + ]; + return true; + }); + + try { + $resource = $callback(); + } finally { + \restore_error_handler(); + } + + if (!$resource) { + $message = 'Error creating resource: '; + foreach ($errors as $err) { + foreach ($err as $key => $value) { + $message .= "[$key] $value" . \PHP_EOL; + } + } + throw new \RuntimeException(\trim($message)); + } + + return $resource; + } + + /** + * @return resource + */ + private function createStream(RequestInterface $request, array $options) + { + static $methods; + if (!$methods) { + $methods = \array_flip(\get_class_methods(__CLASS__)); + } + + if (!\in_array($request->getUri()->getScheme(), ['http', 'https'])) { + throw new RequestException(\sprintf("The scheme '%s' is not supported.", $request->getUri()->getScheme()), $request); + } + + // HTTP/1.1 streams using the PHP stream wrapper require a + // Connection: close header + if ($request->getProtocolVersion() == '1.1' + && !$request->hasHeader('Connection') + ) { + $request = $request->withHeader('Connection', 'close'); + } + + // Ensure SSL is verified by default + if (!isset($options['verify'])) { + $options['verify'] = true; + } + + $params = []; + $context = $this->getDefaultContext($request); + + if (isset($options['on_headers']) && !\is_callable($options['on_headers'])) { + throw new \InvalidArgumentException('on_headers must be callable'); + } + + if (!empty($options)) { + foreach ($options as $key => $value) { + $method = "add_{$key}"; + if (isset($methods[$method])) { + $this->{$method}($request, $context, $value, $params); + } + } + } + + if (isset($options['stream_context'])) { + if (!\is_array($options['stream_context'])) { + throw new \InvalidArgumentException('stream_context must be an array'); + } + $context = \array_replace_recursive($context, $options['stream_context']); + } + + // Microsoft NTLM authentication only supported with curl handler + if (isset($options['auth'][2]) && 'ntlm' === $options['auth'][2]) { + throw new \InvalidArgumentException('Microsoft NTLM authentication only supported with curl handler'); + } + + $uri = $this->resolveHost($request, $options); + + $contextResource = $this->createResource( + static function () use ($context, $params) { + return \stream_context_create($context, $params); + } + ); + + return $this->createResource( + function () use ($uri, &$http_response_header, $contextResource, $context, $options, $request) { + $resource = @\fopen((string) $uri, 'r', false, $contextResource); + $this->lastHeaders = $http_response_header ?? []; + + if (false === $resource) { + throw new ConnectException(sprintf('Connection refused for URI %s', $uri), $request, null, $context); + } + + if (isset($options['read_timeout'])) { + $readTimeout = $options['read_timeout']; + $sec = (int) $readTimeout; + $usec = ($readTimeout - $sec) * 100000; + \stream_set_timeout($resource, $sec, $usec); + } + + return $resource; + } + ); + } + + private function resolveHost(RequestInterface $request, array $options): UriInterface + { + $uri = $request->getUri(); + + if (isset($options['force_ip_resolve']) && !\filter_var($uri->getHost(), \FILTER_VALIDATE_IP)) { + if ('v4' === $options['force_ip_resolve']) { + $records = \dns_get_record($uri->getHost(), \DNS_A); + if (false === $records || !isset($records[0]['ip'])) { + throw new ConnectException(\sprintf("Could not resolve IPv4 address for host '%s'", $uri->getHost()), $request); + } + return $uri->withHost($records[0]['ip']); + } + if ('v6' === $options['force_ip_resolve']) { + $records = \dns_get_record($uri->getHost(), \DNS_AAAA); + if (false === $records || !isset($records[0]['ipv6'])) { + throw new ConnectException(\sprintf("Could not resolve IPv6 address for host '%s'", $uri->getHost()), $request); + } + return $uri->withHost('[' . $records[0]['ipv6'] . ']'); + } + } + + return $uri; + } + + private function getDefaultContext(RequestInterface $request): array + { + $headers = ''; + foreach ($request->getHeaders() as $name => $value) { + foreach ($value as $val) { + $headers .= "$name: $val\r\n"; + } + } + + $context = [ + 'http' => [ + 'method' => $request->getMethod(), + 'header' => $headers, + 'protocol_version' => $request->getProtocolVersion(), + 'ignore_errors' => true, + 'follow_location' => 0, + ], + 'ssl' => [ + 'peer_name' => $request->getUri()->getHost(), + ], + ]; + + $body = (string) $request->getBody(); + + if (!empty($body)) { + $context['http']['content'] = $body; + // Prevent the HTTP handler from adding a Content-Type header. + if (!$request->hasHeader('Content-Type')) { + $context['http']['header'] .= "Content-Type:\r\n"; + } + } + + $context['http']['header'] = \rtrim($context['http']['header']); + + return $context; + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_proxy(RequestInterface $request, array &$options, $value, array &$params): void + { + $uri = null; + + if (!\is_array($value)) { + $uri = $value; + } else { + $scheme = $request->getUri()->getScheme(); + if (isset($value[$scheme])) { + if (!isset($value['no']) || !Utils::isHostInNoProxy($request->getUri()->getHost(), $value['no'])) { + $uri = $value[$scheme]; + } + } + } + + if (!$uri) { + return; + } + + $parsed = $this->parse_proxy($uri); + $options['http']['proxy'] = $parsed['proxy']; + + if ($parsed['auth']) { + if (!isset($options['http']['header'])) { + $options['http']['header'] = []; + } + $options['http']['header'] .= "\r\nProxy-Authorization: {$parsed['auth']}"; + } + } + + /** + * Parses the given proxy URL to make it compatible with the format PHP's stream context expects. + */ + private function parse_proxy(string $url): array + { + $parsed = \parse_url($url); + + if ($parsed !== false && isset($parsed['scheme']) && $parsed['scheme'] === 'http') { + if (isset($parsed['host']) && isset($parsed['port'])) { + $auth = null; + if (isset($parsed['user']) && isset($parsed['pass'])) { + $auth = \base64_encode("{$parsed['user']}:{$parsed['pass']}"); + } + + return [ + 'proxy' => "tcp://{$parsed['host']}:{$parsed['port']}", + 'auth' => $auth ? "Basic {$auth}" : null, + ]; + } + } + + // Return proxy as-is. + return [ + 'proxy' => $url, + 'auth' => null, + ]; + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_timeout(RequestInterface $request, array &$options, $value, array &$params): void + { + if ($value > 0) { + $options['http']['timeout'] = $value; + } + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_verify(RequestInterface $request, array &$options, $value, array &$params): void + { + if ($value === false) { + $options['ssl']['verify_peer'] = false; + $options['ssl']['verify_peer_name'] = false; + + return; + } + + if (\is_string($value)) { + $options['ssl']['cafile'] = $value; + if (!\file_exists($value)) { + throw new \RuntimeException("SSL CA bundle not found: $value"); + } + } elseif ($value !== true) { + throw new \InvalidArgumentException('Invalid verify request option'); + } + + $options['ssl']['verify_peer'] = true; + $options['ssl']['verify_peer_name'] = true; + $options['ssl']['allow_self_signed'] = false; + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_cert(RequestInterface $request, array &$options, $value, array &$params): void + { + if (\is_array($value)) { + $options['ssl']['passphrase'] = $value[1]; + $value = $value[0]; + } + + if (!\file_exists($value)) { + throw new \RuntimeException("SSL certificate not found: {$value}"); + } + + $options['ssl']['local_cert'] = $value; + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_progress(RequestInterface $request, array &$options, $value, array &$params): void + { + self::addNotification( + $params, + static function ($code, $a, $b, $c, $transferred, $total) use ($value) { + if ($code == \STREAM_NOTIFY_PROGRESS) { + // The upload progress cannot be determined. Use 0 for cURL compatibility: + // https://curl.se/libcurl/c/CURLOPT_PROGRESSFUNCTION.html + $value($total, $transferred, 0, 0); + } + } + ); + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_debug(RequestInterface $request, array &$options, $value, array &$params): void + { + if ($value === false) { + return; + } + + static $map = [ + \STREAM_NOTIFY_CONNECT => 'CONNECT', + \STREAM_NOTIFY_AUTH_REQUIRED => 'AUTH_REQUIRED', + \STREAM_NOTIFY_AUTH_RESULT => 'AUTH_RESULT', + \STREAM_NOTIFY_MIME_TYPE_IS => 'MIME_TYPE_IS', + \STREAM_NOTIFY_FILE_SIZE_IS => 'FILE_SIZE_IS', + \STREAM_NOTIFY_REDIRECTED => 'REDIRECTED', + \STREAM_NOTIFY_PROGRESS => 'PROGRESS', + \STREAM_NOTIFY_FAILURE => 'FAILURE', + \STREAM_NOTIFY_COMPLETED => 'COMPLETED', + \STREAM_NOTIFY_RESOLVE => 'RESOLVE', + ]; + static $args = ['severity', 'message', 'message_code', 'bytes_transferred', 'bytes_max']; + + $value = Utils::debugResource($value); + $ident = $request->getMethod() . ' ' . $request->getUri()->withFragment(''); + self::addNotification( + $params, + static function (int $code, ...$passed) use ($ident, $value, $map, $args): void { + \fprintf($value, '<%s> [%s] ', $ident, $map[$code]); + foreach (\array_filter($passed) as $i => $v) { + \fwrite($value, $args[$i] . ': "' . $v . '" '); + } + \fwrite($value, "\n"); + } + ); + } + + private static function addNotification(array &$params, callable $notify): void + { + // Wrap the existing function if needed. + if (!isset($params['notification'])) { + $params['notification'] = $notify; + } else { + $params['notification'] = self::callArray([ + $params['notification'], + $notify + ]); + } + } + + private static function callArray(array $functions): callable + { + return static function (...$args) use ($functions) { + foreach ($functions as $fn) { + $fn(...$args); + } + }; + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/HandlerStack.php b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/HandlerStack.php new file mode 100644 index 000000000..e0a1d1191 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/HandlerStack.php @@ -0,0 +1,275 @@ +push(Middleware::httpErrors(), 'http_errors'); + $stack->push(Middleware::redirect(), 'allow_redirects'); + $stack->push(Middleware::cookies(), 'cookies'); + $stack->push(Middleware::prepareBody(), 'prepare_body'); + + return $stack; + } + + /** + * @param (callable(RequestInterface, array): PromiseInterface)|null $handler Underlying HTTP handler. + */ + public function __construct(callable $handler = null) + { + $this->handler = $handler; + } + + /** + * Invokes the handler stack as a composed handler + * + * @return ResponseInterface|PromiseInterface + */ + public function __invoke(RequestInterface $request, array $options) + { + $handler = $this->resolve(); + + return $handler($request, $options); + } + + /** + * Dumps a string representation of the stack. + * + * @return string + */ + public function __toString() + { + $depth = 0; + $stack = []; + + if ($this->handler !== null) { + $stack[] = "0) Handler: " . $this->debugCallable($this->handler); + } + + $result = ''; + foreach (\array_reverse($this->stack) as $tuple) { + $depth++; + $str = "{$depth}) Name: '{$tuple[1]}', "; + $str .= "Function: " . $this->debugCallable($tuple[0]); + $result = "> {$str}\n{$result}"; + $stack[] = $str; + } + + foreach (\array_keys($stack) as $k) { + $result .= "< {$stack[$k]}\n"; + } + + return $result; + } + + /** + * Set the HTTP handler that actually returns a promise. + * + * @param callable(RequestInterface, array): PromiseInterface $handler Accepts a request and array of options and + * returns a Promise. + */ + public function setHandler(callable $handler): void + { + $this->handler = $handler; + $this->cached = null; + } + + /** + * Returns true if the builder has a handler. + */ + public function hasHandler(): bool + { + return $this->handler !== null ; + } + + /** + * Unshift a middleware to the bottom of the stack. + * + * @param callable(callable): callable $middleware Middleware function + * @param string $name Name to register for this middleware. + */ + public function unshift(callable $middleware, ?string $name = null): void + { + \array_unshift($this->stack, [$middleware, $name]); + $this->cached = null; + } + + /** + * Push a middleware to the top of the stack. + * + * @param callable(callable): callable $middleware Middleware function + * @param string $name Name to register for this middleware. + */ + public function push(callable $middleware, string $name = ''): void + { + $this->stack[] = [$middleware, $name]; + $this->cached = null; + } + + /** + * Add a middleware before another middleware by name. + * + * @param string $findName Middleware to find + * @param callable(callable): callable $middleware Middleware function + * @param string $withName Name to register for this middleware. + */ + public function before(string $findName, callable $middleware, string $withName = ''): void + { + $this->splice($findName, $withName, $middleware, true); + } + + /** + * Add a middleware after another middleware by name. + * + * @param string $findName Middleware to find + * @param callable(callable): callable $middleware Middleware function + * @param string $withName Name to register for this middleware. + */ + public function after(string $findName, callable $middleware, string $withName = ''): void + { + $this->splice($findName, $withName, $middleware, false); + } + + /** + * Remove a middleware by instance or name from the stack. + * + * @param callable|string $remove Middleware to remove by instance or name. + */ + public function remove($remove): void + { + if (!is_string($remove) && !is_callable($remove)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a callable or string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->cached = null; + $idx = \is_callable($remove) ? 0 : 1; + $this->stack = \array_values(\array_filter( + $this->stack, + static function ($tuple) use ($idx, $remove) { + return $tuple[$idx] !== $remove; + } + )); + } + + /** + * Compose the middleware and handler into a single callable function. + * + * @return callable(RequestInterface, array): PromiseInterface + */ + public function resolve(): callable + { + if ($this->cached === null) { + if (($prev = $this->handler) === null) { + throw new \LogicException('No handler has been specified'); + } + + foreach (\array_reverse($this->stack) as $fn) { + /** @var callable(RequestInterface, array): PromiseInterface $prev */ + $prev = $fn[0]($prev); + } + + $this->cached = $prev; + } + + return $this->cached; + } + + private function findByName(string $name): int + { + foreach ($this->stack as $k => $v) { + if ($v[1] === $name) { + return $k; + } + } + + throw new \InvalidArgumentException("Middleware not found: $name"); + } + + /** + * Splices a function into the middleware list at a specific position. + */ + private function splice(string $findName, string $withName, callable $middleware, bool $before): void + { + $this->cached = null; + $idx = $this->findByName($findName); + $tuple = [$middleware, $withName]; + + if ($before) { + if ($idx === 0) { + \array_unshift($this->stack, $tuple); + } else { + $replacement = [$tuple, $this->stack[$idx]]; + \array_splice($this->stack, $idx, 1, $replacement); + } + } elseif ($idx === \count($this->stack) - 1) { + $this->stack[] = $tuple; + } else { + $replacement = [$this->stack[$idx], $tuple]; + \array_splice($this->stack, $idx, 1, $replacement); + } + } + + /** + * Provides a debug string for a given callable. + * + * @param callable|string $fn Function to write as a string. + */ + private function debugCallable($fn): string + { + if (\is_string($fn)) { + return "callable({$fn})"; + } + + if (\is_array($fn)) { + return \is_string($fn[0]) + ? "callable({$fn[0]}::{$fn[1]})" + : "callable(['" . \get_class($fn[0]) . "', '{$fn[1]}'])"; + } + + /** @var object $fn */ + return 'callable(' . \spl_object_hash($fn) . ')'; + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/MessageFormatter.php b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/MessageFormatter.php new file mode 100644 index 000000000..da499547f --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/MessageFormatter.php @@ -0,0 +1,198 @@ +>>>>>>>\n{request}\n<<<<<<<<\n{response}\n--------\n{error}"; + public const SHORT = '[{ts}] "{method} {target} HTTP/{version}" {code}'; + + /** + * @var string Template used to format log messages + */ + private $template; + + /** + * @param string $template Log message template + */ + public function __construct(?string $template = self::CLF) + { + $this->template = $template ?: self::CLF; + } + + /** + * Returns a formatted message string. + * + * @param RequestInterface $request Request that was sent + * @param ResponseInterface|null $response Response that was received + * @param \Throwable|null $error Exception that was received + */ + public function format(RequestInterface $request, ?ResponseInterface $response = null, ?\Throwable $error = null): string + { + $cache = []; + + /** @var string */ + return \preg_replace_callback( + '/{\s*([A-Za-z_\-\.0-9]+)\s*}/', + function (array $matches) use ($request, $response, $error, &$cache) { + if (isset($cache[$matches[1]])) { + return $cache[$matches[1]]; + } + + $result = ''; + switch ($matches[1]) { + case 'request': + $result = Psr7\Message::toString($request); + break; + case 'response': + $result = $response ? Psr7\Message::toString($response) : ''; + break; + case 'req_headers': + $result = \trim($request->getMethod() + . ' ' . $request->getRequestTarget()) + . ' HTTP/' . $request->getProtocolVersion() . "\r\n" + . $this->headers($request); + break; + case 'res_headers': + $result = $response ? + \sprintf( + 'HTTP/%s %d %s', + $response->getProtocolVersion(), + $response->getStatusCode(), + $response->getReasonPhrase() + ) . "\r\n" . $this->headers($response) + : 'NULL'; + break; + case 'req_body': + $result = $request->getBody()->__toString(); + break; + case 'res_body': + if (!$response instanceof ResponseInterface) { + $result = 'NULL'; + break; + } + + $body = $response->getBody(); + + if (!$body->isSeekable()) { + $result = 'RESPONSE_NOT_LOGGEABLE'; + break; + } + + $result = $response->getBody()->__toString(); + break; + case 'ts': + case 'date_iso_8601': + $result = \gmdate('c'); + break; + case 'date_common_log': + $result = \date('d/M/Y:H:i:s O'); + break; + case 'method': + $result = $request->getMethod(); + break; + case 'version': + $result = $request->getProtocolVersion(); + break; + case 'uri': + case 'url': + $result = $request->getUri()->__toString(); + break; + case 'target': + $result = $request->getRequestTarget(); + break; + case 'req_version': + $result = $request->getProtocolVersion(); + break; + case 'res_version': + $result = $response + ? $response->getProtocolVersion() + : 'NULL'; + break; + case 'host': + $result = $request->getHeaderLine('Host'); + break; + case 'hostname': + $result = \gethostname(); + break; + case 'code': + $result = $response ? $response->getStatusCode() : 'NULL'; + break; + case 'phrase': + $result = $response ? $response->getReasonPhrase() : 'NULL'; + break; + case 'error': + $result = $error ? $error->getMessage() : 'NULL'; + break; + default: + // handle prefixed dynamic headers + if (\strpos($matches[1], 'req_header_') === 0) { + $result = $request->getHeaderLine(\substr($matches[1], 11)); + } elseif (\strpos($matches[1], 'res_header_') === 0) { + $result = $response + ? $response->getHeaderLine(\substr($matches[1], 11)) + : 'NULL'; + } + } + + $cache[$matches[1]] = $result; + return $result; + }, + $this->template + ); + } + + /** + * Get headers from message as string + */ + private function headers(MessageInterface $message): string + { + $result = ''; + foreach ($message->getHeaders() as $name => $values) { + $result .= $name . ': ' . \implode(', ', $values) . "\r\n"; + } + + return \trim($result); + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/MessageFormatterInterface.php b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/MessageFormatterInterface.php new file mode 100644 index 000000000..a39ac248e --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/MessageFormatterInterface.php @@ -0,0 +1,18 @@ +withCookieHeader($request); + return $handler($request, $options) + ->then( + static function (ResponseInterface $response) use ($cookieJar, $request): ResponseInterface { + $cookieJar->extractCookies($request, $response); + return $response; + } + ); + }; + }; + } + + /** + * Middleware that throws exceptions for 4xx or 5xx responses when the + * "http_errors" request option is set to true. + * + * @param BodySummarizerInterface|null $bodySummarizer The body summarizer to use in exception messages. + * + * @return callable(callable): callable Returns a function that accepts the next handler. + */ + public static function httpErrors(BodySummarizerInterface $bodySummarizer = null): callable + { + return static function (callable $handler) use ($bodySummarizer): callable { + return static function ($request, array $options) use ($handler, $bodySummarizer) { + if (empty($options['http_errors'])) { + return $handler($request, $options); + } + return $handler($request, $options)->then( + static function (ResponseInterface $response) use ($request, $bodySummarizer) { + $code = $response->getStatusCode(); + if ($code < 400) { + return $response; + } + throw RequestException::create($request, $response, null, [], $bodySummarizer); + } + ); + }; + }; + } + + /** + * Middleware that pushes history data to an ArrayAccess container. + * + * @param array|\ArrayAccess $container Container to hold the history (by reference). + * + * @return callable(callable): callable Returns a function that accepts the next handler. + * + * @throws \InvalidArgumentException if container is not an array or ArrayAccess. + */ + public static function history(&$container): callable + { + if (!\is_array($container) && !$container instanceof \ArrayAccess) { + throw new \InvalidArgumentException('history container must be an array or object implementing ArrayAccess'); + } + + return static function (callable $handler) use (&$container): callable { + return static function (RequestInterface $request, array $options) use ($handler, &$container) { + return $handler($request, $options)->then( + static function ($value) use ($request, &$container, $options) { + $container[] = [ + 'request' => $request, + 'response' => $value, + 'error' => null, + 'options' => $options + ]; + return $value; + }, + static function ($reason) use ($request, &$container, $options) { + $container[] = [ + 'request' => $request, + 'response' => null, + 'error' => $reason, + 'options' => $options + ]; + return P\Create::rejectionFor($reason); + } + ); + }; + }; + } + + /** + * Middleware that invokes a callback before and after sending a request. + * + * The provided listener cannot modify or alter the response. It simply + * "taps" into the chain to be notified before returning the promise. The + * before listener accepts a request and options array, and the after + * listener accepts a request, options array, and response promise. + * + * @param callable $before Function to invoke before forwarding the request. + * @param callable $after Function invoked after forwarding. + * + * @return callable Returns a function that accepts the next handler. + */ + public static function tap(callable $before = null, callable $after = null): callable + { + return static function (callable $handler) use ($before, $after): callable { + return static function (RequestInterface $request, array $options) use ($handler, $before, $after) { + if ($before) { + $before($request, $options); + } + $response = $handler($request, $options); + if ($after) { + $after($request, $options, $response); + } + return $response; + }; + }; + } + + /** + * Middleware that handles request redirects. + * + * @return callable Returns a function that accepts the next handler. + */ + public static function redirect(): callable + { + return static function (callable $handler): RedirectMiddleware { + return new RedirectMiddleware($handler); + }; + } + + /** + * Middleware that retries requests based on the boolean result of + * invoking the provided "decider" function. + * + * If no delay function is provided, a simple implementation of exponential + * backoff will be utilized. + * + * @param callable $decider Function that accepts the number of retries, + * a request, [response], and [exception] and + * returns true if the request is to be retried. + * @param callable $delay Function that accepts the number of retries and + * returns the number of milliseconds to delay. + * + * @return callable Returns a function that accepts the next handler. + */ + public static function retry(callable $decider, callable $delay = null): callable + { + return static function (callable $handler) use ($decider, $delay): RetryMiddleware { + return new RetryMiddleware($decider, $handler, $delay); + }; + } + + /** + * Middleware that logs requests, responses, and errors using a message + * formatter. + * + * @phpstan-param \Psr\Log\LogLevel::* $logLevel Level at which to log requests. + * + * @param LoggerInterface $logger Logs messages. + * @param MessageFormatterInterface|MessageFormatter $formatter Formatter used to create message strings. + * @param string $logLevel Level at which to log requests. + * + * @return callable Returns a function that accepts the next handler. + */ + public static function log(LoggerInterface $logger, $formatter, string $logLevel = 'info'): callable + { + // To be compatible with Guzzle 7.1.x we need to allow users to pass a MessageFormatter + if (!$formatter instanceof MessageFormatter && !$formatter instanceof MessageFormatterInterface) { + throw new \LogicException(sprintf('Argument 2 to %s::log() must be of type %s', self::class, MessageFormatterInterface::class)); + } + + return static function (callable $handler) use ($logger, $formatter, $logLevel): callable { + return static function (RequestInterface $request, array $options = []) use ($handler, $logger, $formatter, $logLevel) { + return $handler($request, $options)->then( + static function ($response) use ($logger, $request, $formatter, $logLevel): ResponseInterface { + $message = $formatter->format($request, $response); + $logger->log($logLevel, $message); + return $response; + }, + static function ($reason) use ($logger, $request, $formatter): PromiseInterface { + $response = $reason instanceof RequestException ? $reason->getResponse() : null; + $message = $formatter->format($request, $response, P\Create::exceptionFor($reason)); + $logger->error($message); + return P\Create::rejectionFor($reason); + } + ); + }; + }; + } + + /** + * This middleware adds a default content-type if possible, a default + * content-length or transfer-encoding header, and the expect header. + */ + public static function prepareBody(): callable + { + return static function (callable $handler): PrepareBodyMiddleware { + return new PrepareBodyMiddleware($handler); + }; + } + + /** + * Middleware that applies a map function to the request before passing to + * the next handler. + * + * @param callable $fn Function that accepts a RequestInterface and returns + * a RequestInterface. + */ + public static function mapRequest(callable $fn): callable + { + return static function (callable $handler) use ($fn): callable { + return static function (RequestInterface $request, array $options) use ($handler, $fn) { + return $handler($fn($request), $options); + }; + }; + } + + /** + * Middleware that applies a map function to the resolved promise's + * response. + * + * @param callable $fn Function that accepts a ResponseInterface and + * returns a ResponseInterface. + */ + public static function mapResponse(callable $fn): callable + { + return static function (callable $handler) use ($fn): callable { + return static function (RequestInterface $request, array $options) use ($handler, $fn) { + return $handler($request, $options)->then($fn); + }; + }; + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Pool.php b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Pool.php new file mode 100644 index 000000000..6277c61fb --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Pool.php @@ -0,0 +1,125 @@ + $rfn) { + if ($rfn instanceof RequestInterface) { + yield $key => $client->sendAsync($rfn, $opts); + } elseif (\is_callable($rfn)) { + yield $key => $rfn($opts); + } else { + throw new \InvalidArgumentException('Each value yielded by the iterator must be a Psr7\Http\Message\RequestInterface or a callable that returns a promise that fulfills with a Psr7\Message\Http\ResponseInterface object.'); + } + } + }; + + $this->each = new EachPromise($requests(), $config); + } + + /** + * Get promise + */ + public function promise(): PromiseInterface + { + return $this->each->promise(); + } + + /** + * Sends multiple requests concurrently and returns an array of responses + * and exceptions that uses the same ordering as the provided requests. + * + * IMPORTANT: This method keeps every request and response in memory, and + * as such, is NOT recommended when sending a large number or an + * indeterminate number of requests concurrently. + * + * @param ClientInterface $client Client used to send the requests + * @param array|\Iterator $requests Requests to send concurrently. + * @param array $options Passes through the options available in + * {@see \GuzzleHttp\Pool::__construct} + * + * @return array Returns an array containing the response or an exception + * in the same order that the requests were sent. + * + * @throws \InvalidArgumentException if the event format is incorrect. + */ + public static function batch(ClientInterface $client, $requests, array $options = []): array + { + $res = []; + self::cmpCallback($options, 'fulfilled', $res); + self::cmpCallback($options, 'rejected', $res); + $pool = new static($client, $requests, $options); + $pool->promise()->wait(); + \ksort($res); + + return $res; + } + + /** + * Execute callback(s) + */ + private static function cmpCallback(array &$options, string $name, array &$results): void + { + if (!isset($options[$name])) { + $options[$name] = static function ($v, $k) use (&$results) { + $results[$k] = $v; + }; + } else { + $currentFn = $options[$name]; + $options[$name] = static function ($v, $k) use (&$results, $currentFn) { + $currentFn($v, $k); + $results[$k] = $v; + }; + } + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php new file mode 100644 index 000000000..7ca628338 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php @@ -0,0 +1,104 @@ +nextHandler = $nextHandler; + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + $fn = $this->nextHandler; + + // Don't do anything if the request has no body. + if ($request->getBody()->getSize() === 0) { + return $fn($request, $options); + } + + $modify = []; + + // Add a default content-type if possible. + if (!$request->hasHeader('Content-Type')) { + if ($uri = $request->getBody()->getMetadata('uri')) { + if (is_string($uri) && $type = Psr7\MimeType::fromFilename($uri)) { + $modify['set_headers']['Content-Type'] = $type; + } + } + } + + // Add a default content-length or transfer-encoding header. + if (!$request->hasHeader('Content-Length') + && !$request->hasHeader('Transfer-Encoding') + ) { + $size = $request->getBody()->getSize(); + if ($size !== null) { + $modify['set_headers']['Content-Length'] = $size; + } else { + $modify['set_headers']['Transfer-Encoding'] = 'chunked'; + } + } + + // Add the expect header if needed. + $this->addExpectHeader($request, $options, $modify); + + return $fn(Psr7\Utils::modifyRequest($request, $modify), $options); + } + + /** + * Add expect header + */ + private function addExpectHeader(RequestInterface $request, array $options, array &$modify): void + { + // Determine if the Expect header should be used + if ($request->hasHeader('Expect')) { + return; + } + + $expect = $options['expect'] ?? null; + + // Return if disabled or if you're not using HTTP/1.1 or HTTP/2.0 + if ($expect === false || $request->getProtocolVersion() < 1.1) { + return; + } + + // The expect header is unconditionally enabled + if ($expect === true) { + $modify['set_headers']['Expect'] = '100-Continue'; + return; + } + + // By default, send the expect header when the payload is > 1mb + if ($expect === null) { + $expect = 1048576; + } + + // Always add if the body cannot be rewound, the size cannot be + // determined, or the size is greater than the cutoff threshold + $body = $request->getBody(); + $size = $body->getSize(); + + if ($size === null || $size >= (int) $expect || !$body->isSeekable()) { + $modify['set_headers']['Expect'] = '100-Continue'; + } + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php new file mode 100644 index 000000000..f67d448be --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php @@ -0,0 +1,228 @@ + 5, + 'protocols' => ['http', 'https'], + 'strict' => false, + 'referer' => false, + 'track_redirects' => false, + ]; + + /** + * @var callable(RequestInterface, array): PromiseInterface + */ + private $nextHandler; + + /** + * @param callable(RequestInterface, array): PromiseInterface $nextHandler Next handler to invoke. + */ + public function __construct(callable $nextHandler) + { + $this->nextHandler = $nextHandler; + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + $fn = $this->nextHandler; + + if (empty($options['allow_redirects'])) { + return $fn($request, $options); + } + + if ($options['allow_redirects'] === true) { + $options['allow_redirects'] = self::$defaultSettings; + } elseif (!\is_array($options['allow_redirects'])) { + throw new \InvalidArgumentException('allow_redirects must be true, false, or array'); + } else { + // Merge the default settings with the provided settings + $options['allow_redirects'] += self::$defaultSettings; + } + + if (empty($options['allow_redirects']['max'])) { + return $fn($request, $options); + } + + return $fn($request, $options) + ->then(function (ResponseInterface $response) use ($request, $options) { + return $this->checkRedirect($request, $options, $response); + }); + } + + /** + * @return ResponseInterface|PromiseInterface + */ + public function checkRedirect(RequestInterface $request, array $options, ResponseInterface $response) + { + if (\strpos((string) $response->getStatusCode(), '3') !== 0 + || !$response->hasHeader('Location') + ) { + return $response; + } + + $this->guardMax($request, $response, $options); + $nextRequest = $this->modifyRequest($request, $options, $response); + + // If authorization is handled by curl, unset it if URI is cross-origin. + if (Psr7\UriComparator::isCrossOrigin($request->getUri(), $nextRequest->getUri()) && defined('\CURLOPT_HTTPAUTH')) { + unset( + $options['curl'][\CURLOPT_HTTPAUTH], + $options['curl'][\CURLOPT_USERPWD] + ); + } + + if (isset($options['allow_redirects']['on_redirect'])) { + ($options['allow_redirects']['on_redirect'])( + $request, + $response, + $nextRequest->getUri() + ); + } + + $promise = $this($nextRequest, $options); + + // Add headers to be able to track history of redirects. + if (!empty($options['allow_redirects']['track_redirects'])) { + return $this->withTracking( + $promise, + (string) $nextRequest->getUri(), + $response->getStatusCode() + ); + } + + return $promise; + } + + /** + * Enable tracking on promise. + */ + private function withTracking(PromiseInterface $promise, string $uri, int $statusCode): PromiseInterface + { + return $promise->then( + static function (ResponseInterface $response) use ($uri, $statusCode) { + // Note that we are pushing to the front of the list as this + // would be an earlier response than what is currently present + // in the history header. + $historyHeader = $response->getHeader(self::HISTORY_HEADER); + $statusHeader = $response->getHeader(self::STATUS_HISTORY_HEADER); + \array_unshift($historyHeader, $uri); + \array_unshift($statusHeader, (string) $statusCode); + + return $response->withHeader(self::HISTORY_HEADER, $historyHeader) + ->withHeader(self::STATUS_HISTORY_HEADER, $statusHeader); + } + ); + } + + /** + * Check for too many redirects. + * + * @throws TooManyRedirectsException Too many redirects. + */ + private function guardMax(RequestInterface $request, ResponseInterface $response, array &$options): void + { + $current = $options['__redirect_count'] + ?? 0; + $options['__redirect_count'] = $current + 1; + $max = $options['allow_redirects']['max']; + + if ($options['__redirect_count'] > $max) { + throw new TooManyRedirectsException("Will not follow more than {$max} redirects", $request, $response); + } + } + + public function modifyRequest(RequestInterface $request, array $options, ResponseInterface $response): RequestInterface + { + // Request modifications to apply. + $modify = []; + $protocols = $options['allow_redirects']['protocols']; + + // Use a GET request if this is an entity enclosing request and we are + // not forcing RFC compliance, but rather emulating what all browsers + // would do. + $statusCode = $response->getStatusCode(); + if ($statusCode == 303 || + ($statusCode <= 302 && !$options['allow_redirects']['strict']) + ) { + $safeMethods = ['GET', 'HEAD', 'OPTIONS']; + $requestMethod = $request->getMethod(); + + $modify['method'] = in_array($requestMethod, $safeMethods) ? $requestMethod : 'GET'; + $modify['body'] = ''; + } + + $uri = self::redirectUri($request, $response, $protocols); + if (isset($options['idn_conversion']) && ($options['idn_conversion'] !== false)) { + $idnOptions = ($options['idn_conversion'] === true) ? \IDNA_DEFAULT : $options['idn_conversion']; + $uri = Utils::idnUriConvert($uri, $idnOptions); + } + + $modify['uri'] = $uri; + Psr7\Message::rewindBody($request); + + // Add the Referer header if it is told to do so and only + // add the header if we are not redirecting from https to http. + if ($options['allow_redirects']['referer'] + && $modify['uri']->getScheme() === $request->getUri()->getScheme() + ) { + $uri = $request->getUri()->withUserInfo(''); + $modify['set_headers']['Referer'] = (string) $uri; + } else { + $modify['remove_headers'][] = 'Referer'; + } + + // Remove Authorization and Cookie headers if URI is cross-origin. + if (Psr7\UriComparator::isCrossOrigin($request->getUri(), $modify['uri'])) { + $modify['remove_headers'][] = 'Authorization'; + $modify['remove_headers'][] = 'Cookie'; + } + + return Psr7\Utils::modifyRequest($request, $modify); + } + + /** + * Set the appropriate URL on the request based on the location header. + */ + private static function redirectUri( + RequestInterface $request, + ResponseInterface $response, + array $protocols + ): UriInterface { + $location = Psr7\UriResolver::resolve( + $request->getUri(), + new Psr7\Uri($response->getHeaderLine('Location')) + ); + + // Ensure that the redirect URI is allowed based on the protocols. + if (!\in_array($location->getScheme(), $protocols)) { + throw new BadResponseException(\sprintf('Redirect URI, %s, does not use one of the allowed redirect protocols: %s', $location, \implode(', ', $protocols)), $request, $response); + } + + return $location; + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/RequestOptions.php b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/RequestOptions.php new file mode 100644 index 000000000..20b31bc20 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/RequestOptions.php @@ -0,0 +1,264 @@ +decider = $decider; + $this->nextHandler = $nextHandler; + $this->delay = $delay ?: __CLASS__ . '::exponentialDelay'; + } + + /** + * Default exponential backoff delay function. + * + * @return int milliseconds. + */ + public static function exponentialDelay(int $retries): int + { + return (int) \pow(2, $retries - 1) * 1000; + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + if (!isset($options['retries'])) { + $options['retries'] = 0; + } + + $fn = $this->nextHandler; + return $fn($request, $options) + ->then( + $this->onFulfilled($request, $options), + $this->onRejected($request, $options) + ); + } + + /** + * Execute fulfilled closure + */ + private function onFulfilled(RequestInterface $request, array $options): callable + { + return function ($value) use ($request, $options) { + if (!($this->decider)( + $options['retries'], + $request, + $value, + null + )) { + return $value; + } + return $this->doRetry($request, $options, $value); + }; + } + + /** + * Execute rejected closure + */ + private function onRejected(RequestInterface $req, array $options): callable + { + return function ($reason) use ($req, $options) { + if (!($this->decider)( + $options['retries'], + $req, + null, + $reason + )) { + return P\Create::rejectionFor($reason); + } + return $this->doRetry($req, $options); + }; + } + + private function doRetry(RequestInterface $request, array $options, ResponseInterface $response = null): PromiseInterface + { + $options['delay'] = ($this->delay)(++$options['retries'], $response, $request); + + return $this($request, $options); + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/TransferStats.php b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/TransferStats.php new file mode 100644 index 000000000..93fa334c8 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/TransferStats.php @@ -0,0 +1,133 @@ +request = $request; + $this->response = $response; + $this->transferTime = $transferTime; + $this->handlerErrorData = $handlerErrorData; + $this->handlerStats = $handlerStats; + } + + public function getRequest(): RequestInterface + { + return $this->request; + } + + /** + * Returns the response that was received (if any). + */ + public function getResponse(): ?ResponseInterface + { + return $this->response; + } + + /** + * Returns true if a response was received. + */ + public function hasResponse(): bool + { + return $this->response !== null; + } + + /** + * Gets handler specific error data. + * + * This might be an exception, a integer representing an error code, or + * anything else. Relying on this value assumes that you know what handler + * you are using. + * + * @return mixed + */ + public function getHandlerErrorData() + { + return $this->handlerErrorData; + } + + /** + * Get the effective URI the request was sent to. + */ + public function getEffectiveUri(): UriInterface + { + return $this->request->getUri(); + } + + /** + * Get the estimated time the request was being transferred by the handler. + * + * @return float|null Time in seconds. + */ + public function getTransferTime(): ?float + { + return $this->transferTime; + } + + /** + * Gets an array of all of the handler specific transfer data. + */ + public function getHandlerStats(): array + { + return $this->handlerStats; + } + + /** + * Get a specific handler statistic from the handler by name. + * + * @param string $stat Handler specific transfer stat to retrieve. + * + * @return mixed|null + */ + public function getHandlerStat(string $stat) + { + return $this->handlerStats[$stat] ?? null; + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Utils.php b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Utils.php new file mode 100644 index 000000000..e355f3212 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/Utils.php @@ -0,0 +1,385 @@ +getHost()) { + $asciiHost = self::idnToAsci($uri->getHost(), $options, $info); + if ($asciiHost === false) { + $errorBitSet = $info['errors'] ?? 0; + + $errorConstants = array_filter(array_keys(get_defined_constants()), static function (string $name): bool { + return substr($name, 0, 11) === 'IDNA_ERROR_'; + }); + + $errors = []; + foreach ($errorConstants as $errorConstant) { + if ($errorBitSet & constant($errorConstant)) { + $errors[] = $errorConstant; + } + } + + $errorMessage = 'IDN conversion failed'; + if ($errors) { + $errorMessage .= ' (errors: ' . implode(', ', $errors) . ')'; + } + + throw new InvalidArgumentException($errorMessage); + } + if ($uri->getHost() !== $asciiHost) { + // Replace URI only if the ASCII version is different + $uri = $uri->withHost($asciiHost); + } + } + + return $uri; + } + + /** + * @internal + */ + public static function getenv(string $name): ?string + { + if (isset($_SERVER[$name])) { + return (string) $_SERVER[$name]; + } + + if (\PHP_SAPI === 'cli' && ($value = \getenv($name)) !== false && $value !== null) { + return (string) $value; + } + + return null; + } + + /** + * @return string|false + */ + private static function idnToAsci(string $domain, int $options, ?array &$info = []) + { + if (\function_exists('idn_to_ascii') && \defined('INTL_IDNA_VARIANT_UTS46')) { + return \idn_to_ascii($domain, $options, \INTL_IDNA_VARIANT_UTS46, $info); + } + + throw new \Error('ext-idn or symfony/polyfill-intl-idn not loaded or too old'); + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/functions.php b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/functions.php new file mode 100644 index 000000000..a70d2cbf3 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/guzzle/src/functions.php @@ -0,0 +1,167 @@ + +Copyright (c) 2015 Graham Campbell +Copyright (c) 2017 Tobias Schultze +Copyright (c) 2020 Tobias Nyholm + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/data/web/inc/lib/vendor/guzzlehttp/promises/README.md b/data/web/inc/lib/vendor/guzzlehttp/promises/README.md new file mode 100644 index 000000000..1ea667ab9 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/promises/README.md @@ -0,0 +1,546 @@ +# Guzzle Promises + +[Promises/A+](https://promisesaplus.com/) implementation that handles promise +chaining and resolution iteratively, allowing for "infinite" promise chaining +while keeping the stack size constant. Read [this blog post](https://blog.domenic.me/youre-missing-the-point-of-promises/) +for a general introduction to promises. + +- [Features](#features) +- [Quick start](#quick-start) +- [Synchronous wait](#synchronous-wait) +- [Cancellation](#cancellation) +- [API](#api) + - [Promise](#promise) + - [FulfilledPromise](#fulfilledpromise) + - [RejectedPromise](#rejectedpromise) +- [Promise interop](#promise-interop) +- [Implementation notes](#implementation-notes) + + +## Features + +- [Promises/A+](https://promisesaplus.com/) implementation. +- Promise resolution and chaining is handled iteratively, allowing for + "infinite" promise chaining. +- Promises have a synchronous `wait` method. +- Promises can be cancelled. +- Works with any object that has a `then` function. +- C# style async/await coroutine promises using + `GuzzleHttp\Promise\Coroutine::of()`. + + +## Quick Start + +A *promise* represents the eventual result of an asynchronous operation. The +primary way of interacting with a promise is through its `then` method, which +registers callbacks to receive either a promise's eventual value or the reason +why the promise cannot be fulfilled. + +### Callbacks + +Callbacks are registered with the `then` method by providing an optional +`$onFulfilled` followed by an optional `$onRejected` function. + + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise->then( + // $onFulfilled + function ($value) { + echo 'The promise was fulfilled.'; + }, + // $onRejected + function ($reason) { + echo 'The promise was rejected.'; + } +); +``` + +*Resolving* a promise means that you either fulfill a promise with a *value* or +reject a promise with a *reason*. Resolving a promise triggers callbacks +registered with the promise's `then` method. These callbacks are triggered +only once and in the order in which they were added. + +### Resolving a Promise + +Promises are fulfilled using the `resolve($value)` method. Resolving a promise +with any value other than a `GuzzleHttp\Promise\RejectedPromise` will trigger +all of the onFulfilled callbacks (resolving a promise with a rejected promise +will reject the promise and trigger the `$onRejected` callbacks). + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise + ->then(function ($value) { + // Return a value and don't break the chain + return "Hello, " . $value; + }) + // This then is executed after the first then and receives the value + // returned from the first then. + ->then(function ($value) { + echo $value; + }); + +// Resolving the promise triggers the $onFulfilled callbacks and outputs +// "Hello, reader." +$promise->resolve('reader.'); +``` + +### Promise Forwarding + +Promises can be chained one after the other. Each then in the chain is a new +promise. The return value of a promise is what's forwarded to the next +promise in the chain. Returning a promise in a `then` callback will cause the +subsequent promises in the chain to only be fulfilled when the returned promise +has been fulfilled. The next promise in the chain will be invoked with the +resolved value of the promise. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$nextPromise = new Promise(); + +$promise + ->then(function ($value) use ($nextPromise) { + echo $value; + return $nextPromise; + }) + ->then(function ($value) { + echo $value; + }); + +// Triggers the first callback and outputs "A" +$promise->resolve('A'); +// Triggers the second callback and outputs "B" +$nextPromise->resolve('B'); +``` + +### Promise Rejection + +When a promise is rejected, the `$onRejected` callbacks are invoked with the +rejection reason. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise->then(null, function ($reason) { + echo $reason; +}); + +$promise->reject('Error!'); +// Outputs "Error!" +``` + +### Rejection Forwarding + +If an exception is thrown in an `$onRejected` callback, subsequent +`$onRejected` callbacks are invoked with the thrown exception as the reason. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise->then(null, function ($reason) { + throw new Exception($reason); +})->then(null, function ($reason) { + assert($reason->getMessage() === 'Error!'); +}); + +$promise->reject('Error!'); +``` + +You can also forward a rejection down the promise chain by returning a +`GuzzleHttp\Promise\RejectedPromise` in either an `$onFulfilled` or +`$onRejected` callback. + +```php +use GuzzleHttp\Promise\Promise; +use GuzzleHttp\Promise\RejectedPromise; + +$promise = new Promise(); +$promise->then(null, function ($reason) { + return new RejectedPromise($reason); +})->then(null, function ($reason) { + assert($reason === 'Error!'); +}); + +$promise->reject('Error!'); +``` + +If an exception is not thrown in a `$onRejected` callback and the callback +does not return a rejected promise, downstream `$onFulfilled` callbacks are +invoked using the value returned from the `$onRejected` callback. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise + ->then(null, function ($reason) { + return "It's ok"; + }) + ->then(function ($value) { + assert($value === "It's ok"); + }); + +$promise->reject('Error!'); +``` + + +## Synchronous Wait + +You can synchronously force promises to complete using a promise's `wait` +method. When creating a promise, you can provide a wait function that is used +to synchronously force a promise to complete. When a wait function is invoked +it is expected to deliver a value to the promise or reject the promise. If the +wait function does not deliver a value, then an exception is thrown. The wait +function provided to a promise constructor is invoked when the `wait` function +of the promise is called. + +```php +$promise = new Promise(function () use (&$promise) { + $promise->resolve('foo'); +}); + +// Calling wait will return the value of the promise. +echo $promise->wait(); // outputs "foo" +``` + +If an exception is encountered while invoking the wait function of a promise, +the promise is rejected with the exception and the exception is thrown. + +```php +$promise = new Promise(function () use (&$promise) { + throw new Exception('foo'); +}); + +$promise->wait(); // throws the exception. +``` + +Calling `wait` on a promise that has been fulfilled will not trigger the wait +function. It will simply return the previously resolved value. + +```php +$promise = new Promise(function () { die('this is not called!'); }); +$promise->resolve('foo'); +echo $promise->wait(); // outputs "foo" +``` + +Calling `wait` on a promise that has been rejected will throw an exception. If +the rejection reason is an instance of `\Exception` the reason is thrown. +Otherwise, a `GuzzleHttp\Promise\RejectionException` is thrown and the reason +can be obtained by calling the `getReason` method of the exception. + +```php +$promise = new Promise(); +$promise->reject('foo'); +$promise->wait(); +``` + +> PHP Fatal error: Uncaught exception 'GuzzleHttp\Promise\RejectionException' with message 'The promise was rejected with value: foo' + +### Unwrapping a Promise + +When synchronously waiting on a promise, you are joining the state of the +promise into the current state of execution (i.e., return the value of the +promise if it was fulfilled or throw an exception if it was rejected). This is +called "unwrapping" the promise. Waiting on a promise will by default unwrap +the promise state. + +You can force a promise to resolve and *not* unwrap the state of the promise +by passing `false` to the first argument of the `wait` function: + +```php +$promise = new Promise(); +$promise->reject('foo'); +// This will not throw an exception. It simply ensures the promise has +// been resolved. +$promise->wait(false); +``` + +When unwrapping a promise, the resolved value of the promise will be waited +upon until the unwrapped value is not a promise. This means that if you resolve +promise A with a promise B and unwrap promise A, the value returned by the +wait function will be the value delivered to promise B. + +**Note**: when you do not unwrap the promise, no value is returned. + + +## Cancellation + +You can cancel a promise that has not yet been fulfilled using the `cancel()` +method of a promise. When creating a promise you can provide an optional +cancel function that when invoked cancels the action of computing a resolution +of the promise. + + +## API + +### Promise + +When creating a promise object, you can provide an optional `$waitFn` and +`$cancelFn`. `$waitFn` is a function that is invoked with no arguments and is +expected to resolve the promise. `$cancelFn` is a function with no arguments +that is expected to cancel the computation of a promise. It is invoked when the +`cancel()` method of a promise is called. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise( + function () use (&$promise) { + $promise->resolve('waited'); + }, + function () { + // do something that will cancel the promise computation (e.g., close + // a socket, cancel a database query, etc...) + } +); + +assert('waited' === $promise->wait()); +``` + +A promise has the following methods: + +- `then(callable $onFulfilled, callable $onRejected) : PromiseInterface` + + Appends fulfillment and rejection handlers to the promise, and returns a new promise resolving to the return value of the called handler. + +- `otherwise(callable $onRejected) : PromiseInterface` + + Appends a rejection handler callback to the promise, and returns a new promise resolving to the return value of the callback if it is called, or to its original fulfillment value if the promise is instead fulfilled. + +- `wait($unwrap = true) : mixed` + + Synchronously waits on the promise to complete. + + `$unwrap` controls whether or not the value of the promise is returned for a + fulfilled promise or if an exception is thrown if the promise is rejected. + This is set to `true` by default. + +- `cancel()` + + Attempts to cancel the promise if possible. The promise being cancelled and + the parent most ancestor that has not yet been resolved will also be + cancelled. Any promises waiting on the cancelled promise to resolve will also + be cancelled. + +- `getState() : string` + + Returns the state of the promise. One of `pending`, `fulfilled`, or + `rejected`. + +- `resolve($value)` + + Fulfills the promise with the given `$value`. + +- `reject($reason)` + + Rejects the promise with the given `$reason`. + + +### FulfilledPromise + +A fulfilled promise can be created to represent a promise that has been +fulfilled. + +```php +use GuzzleHttp\Promise\FulfilledPromise; + +$promise = new FulfilledPromise('value'); + +// Fulfilled callbacks are immediately invoked. +$promise->then(function ($value) { + echo $value; +}); +``` + + +### RejectedPromise + +A rejected promise can be created to represent a promise that has been +rejected. + +```php +use GuzzleHttp\Promise\RejectedPromise; + +$promise = new RejectedPromise('Error'); + +// Rejected callbacks are immediately invoked. +$promise->then(null, function ($reason) { + echo $reason; +}); +``` + + +## Promise Interoperability + +This library works with foreign promises that have a `then` method. This means +you can use Guzzle promises with [React promises](https://github.com/reactphp/promise) +for example. When a foreign promise is returned inside of a then method +callback, promise resolution will occur recursively. + +```php +// Create a React promise +$deferred = new React\Promise\Deferred(); +$reactPromise = $deferred->promise(); + +// Create a Guzzle promise that is fulfilled with a React promise. +$guzzlePromise = new GuzzleHttp\Promise\Promise(); +$guzzlePromise->then(function ($value) use ($reactPromise) { + // Do something something with the value... + // Return the React promise + return $reactPromise; +}); +``` + +Please note that wait and cancel chaining is no longer possible when forwarding +a foreign promise. You will need to wrap a third-party promise with a Guzzle +promise in order to utilize wait and cancel functions with foreign promises. + + +### Event Loop Integration + +In order to keep the stack size constant, Guzzle promises are resolved +asynchronously using a task queue. When waiting on promises synchronously, the +task queue will be automatically run to ensure that the blocking promise and +any forwarded promises are resolved. When using promises asynchronously in an +event loop, you will need to run the task queue on each tick of the loop. If +you do not run the task queue, then promises will not be resolved. + +You can run the task queue using the `run()` method of the global task queue +instance. + +```php +// Get the global task queue +$queue = GuzzleHttp\Promise\Utils::queue(); +$queue->run(); +``` + +For example, you could use Guzzle promises with React using a periodic timer: + +```php +$loop = React\EventLoop\Factory::create(); +$loop->addPeriodicTimer(0, [$queue, 'run']); +``` + +*TODO*: Perhaps adding a `futureTick()` on each tick would be faster? + + +## Implementation Notes + +### Promise Resolution and Chaining is Handled Iteratively + +By shuffling pending handlers from one owner to another, promises are +resolved iteratively, allowing for "infinite" then chaining. + +```php +then(function ($v) { + // The stack size remains constant (a good thing) + echo xdebug_get_stack_depth() . ', '; + return $v + 1; + }); +} + +$parent->resolve(0); +var_dump($p->wait()); // int(1000) + +``` + +When a promise is fulfilled or rejected with a non-promise value, the promise +then takes ownership of the handlers of each child promise and delivers values +down the chain without using recursion. + +When a promise is resolved with another promise, the original promise transfers +all of its pending handlers to the new promise. When the new promise is +eventually resolved, all of the pending handlers are delivered the forwarded +value. + +### A Promise is the Deferred + +Some promise libraries implement promises using a deferred object to represent +a computation and a promise object to represent the delivery of the result of +the computation. This is a nice separation of computation and delivery because +consumers of the promise cannot modify the value that will be eventually +delivered. + +One side effect of being able to implement promise resolution and chaining +iteratively is that you need to be able for one promise to reach into the state +of another promise to shuffle around ownership of handlers. In order to achieve +this without making the handlers of a promise publicly mutable, a promise is +also the deferred value, allowing promises of the same parent class to reach +into and modify the private properties of promises of the same type. While this +does allow consumers of the value to modify the resolution or rejection of the +deferred, it is a small price to pay for keeping the stack size constant. + +```php +$promise = new Promise(); +$promise->then(function ($value) { echo $value; }); +// The promise is the deferred value, so you can deliver a value to it. +$promise->resolve('foo'); +// prints "foo" +``` + + +## Upgrading from Function API + +A static API was first introduced in 1.4.0, in order to mitigate problems with +functions conflicting between global and local copies of the package. The +function API will be removed in 2.0.0. A migration table has been provided here +for your convenience: + +| Original Function | Replacement Method | +|----------------|----------------| +| `queue` | `Utils::queue` | +| `task` | `Utils::task` | +| `promise_for` | `Create::promiseFor` | +| `rejection_for` | `Create::rejectionFor` | +| `exception_for` | `Create::exceptionFor` | +| `iter_for` | `Create::iterFor` | +| `inspect` | `Utils::inspect` | +| `inspect_all` | `Utils::inspectAll` | +| `unwrap` | `Utils::unwrap` | +| `all` | `Utils::all` | +| `some` | `Utils::some` | +| `any` | `Utils::any` | +| `settle` | `Utils::settle` | +| `each` | `Each::of` | +| `each_limit` | `Each::ofLimit` | +| `each_limit_all` | `Each::ofLimitAll` | +| `!is_fulfilled` | `Is::pending` | +| `is_fulfilled` | `Is::fulfilled` | +| `is_rejected` | `Is::rejected` | +| `is_settled` | `Is::settled` | +| `coroutine` | `Coroutine::of` | + + +## Security + +If you discover a security vulnerability within this package, please send an email to security@tidelift.com. All security vulnerabilities will be promptly addressed. Please do not disclose security-related issues publicly until a fix has been announced. Please see [Security Policy](https://github.com/guzzle/promises/security/policy) for more information. + + +## License + +Guzzle is made available under the MIT License (MIT). Please see [License File](LICENSE) for more information. + + +## For Enterprise + +Available as part of the Tidelift Subscription + +The maintainers of Guzzle and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-promises?utm_source=packagist-guzzlehttp-promises&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/data/web/inc/lib/vendor/guzzlehttp/promises/composer.json b/data/web/inc/lib/vendor/guzzlehttp/promises/composer.json new file mode 100644 index 000000000..c959fb32b --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/promises/composer.json @@ -0,0 +1,58 @@ +{ + "name": "guzzlehttp/promises", + "description": "Guzzle promises library", + "keywords": ["promise"], + "license": "MIT", + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "require": { + "php": ">=5.5" + }, + "require-dev": { + "symfony/phpunit-bridge": "^4.4 || ^5.1" + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + }, + "files": ["src/functions_include.php"] + }, + "autoload-dev": { + "psr-4": { + "GuzzleHttp\\Promise\\Tests\\": "tests/" + } + }, + "scripts": { + "test": "vendor/bin/simple-phpunit", + "test-ci": "vendor/bin/simple-phpunit --coverage-text" + }, + "extra": { + "branch-alias": { + "dev-master": "1.5-dev" + } + }, + "config": { + "preferred-install": "dist", + "sort-packages": true + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/promises/src/AggregateException.php b/data/web/inc/lib/vendor/guzzlehttp/promises/src/AggregateException.php new file mode 100644 index 000000000..d2b5712b9 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/promises/src/AggregateException.php @@ -0,0 +1,17 @@ +then(function ($v) { echo $v; }); + * + * @param callable $generatorFn Generator function to wrap into a promise. + * + * @return Promise + * + * @link https://github.com/petkaantonov/bluebird/blob/master/API.md#generators inspiration + */ +final class Coroutine implements PromiseInterface +{ + /** + * @var PromiseInterface|null + */ + private $currentPromise; + + /** + * @var Generator + */ + private $generator; + + /** + * @var Promise + */ + private $result; + + public function __construct(callable $generatorFn) + { + $this->generator = $generatorFn(); + $this->result = new Promise(function () { + while (isset($this->currentPromise)) { + $this->currentPromise->wait(); + } + }); + try { + $this->nextCoroutine($this->generator->current()); + } catch (\Exception $exception) { + $this->result->reject($exception); + } catch (Throwable $throwable) { + $this->result->reject($throwable); + } + } + + /** + * Create a new coroutine. + * + * @return self + */ + public static function of(callable $generatorFn) + { + return new self($generatorFn); + } + + public function then( + callable $onFulfilled = null, + callable $onRejected = null + ) { + return $this->result->then($onFulfilled, $onRejected); + } + + public function otherwise(callable $onRejected) + { + return $this->result->otherwise($onRejected); + } + + public function wait($unwrap = true) + { + return $this->result->wait($unwrap); + } + + public function getState() + { + return $this->result->getState(); + } + + public function resolve($value) + { + $this->result->resolve($value); + } + + public function reject($reason) + { + $this->result->reject($reason); + } + + public function cancel() + { + $this->currentPromise->cancel(); + $this->result->cancel(); + } + + private function nextCoroutine($yielded) + { + $this->currentPromise = Create::promiseFor($yielded) + ->then([$this, '_handleSuccess'], [$this, '_handleFailure']); + } + + /** + * @internal + */ + public function _handleSuccess($value) + { + unset($this->currentPromise); + try { + $next = $this->generator->send($value); + if ($this->generator->valid()) { + $this->nextCoroutine($next); + } else { + $this->result->resolve($value); + } + } catch (Exception $exception) { + $this->result->reject($exception); + } catch (Throwable $throwable) { + $this->result->reject($throwable); + } + } + + /** + * @internal + */ + public function _handleFailure($reason) + { + unset($this->currentPromise); + try { + $nextYield = $this->generator->throw(Create::exceptionFor($reason)); + // The throw was caught, so keep iterating on the coroutine + $this->nextCoroutine($nextYield); + } catch (Exception $exception) { + $this->result->reject($exception); + } catch (Throwable $throwable) { + $this->result->reject($throwable); + } + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/promises/src/Create.php b/data/web/inc/lib/vendor/guzzlehttp/promises/src/Create.php new file mode 100644 index 000000000..8d038e9c1 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/promises/src/Create.php @@ -0,0 +1,84 @@ +then([$promise, 'resolve'], [$promise, 'reject']); + return $promise; + } + + return new FulfilledPromise($value); + } + + /** + * Creates a rejected promise for a reason if the reason is not a promise. + * If the provided reason is a promise, then it is returned as-is. + * + * @param mixed $reason Promise or reason. + * + * @return PromiseInterface + */ + public static function rejectionFor($reason) + { + if ($reason instanceof PromiseInterface) { + return $reason; + } + + return new RejectedPromise($reason); + } + + /** + * Create an exception for a rejected promise value. + * + * @param mixed $reason + * + * @return \Exception|\Throwable + */ + public static function exceptionFor($reason) + { + if ($reason instanceof \Exception || $reason instanceof \Throwable) { + return $reason; + } + + return new RejectionException($reason); + } + + /** + * Returns an iterator for the given value. + * + * @param mixed $value + * + * @return \Iterator + */ + public static function iterFor($value) + { + if ($value instanceof \Iterator) { + return $value; + } + + if (is_array($value)) { + return new \ArrayIterator($value); + } + + return new \ArrayIterator([$value]); + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/promises/src/Each.php b/data/web/inc/lib/vendor/guzzlehttp/promises/src/Each.php new file mode 100644 index 000000000..1dda35499 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/promises/src/Each.php @@ -0,0 +1,90 @@ + $onFulfilled, + 'rejected' => $onRejected + ]))->promise(); + } + + /** + * Like of, but only allows a certain number of outstanding promises at any + * given time. + * + * $concurrency may be an integer or a function that accepts the number of + * pending promises and returns a numeric concurrency limit value to allow + * for dynamic a concurrency size. + * + * @param mixed $iterable + * @param int|callable $concurrency + * @param callable $onFulfilled + * @param callable $onRejected + * + * @return PromiseInterface + */ + public static function ofLimit( + $iterable, + $concurrency, + callable $onFulfilled = null, + callable $onRejected = null + ) { + return (new EachPromise($iterable, [ + 'fulfilled' => $onFulfilled, + 'rejected' => $onRejected, + 'concurrency' => $concurrency + ]))->promise(); + } + + /** + * Like limit, but ensures that no promise in the given $iterable argument + * is rejected. If any promise is rejected, then the aggregate promise is + * rejected with the encountered rejection. + * + * @param mixed $iterable + * @param int|callable $concurrency + * @param callable $onFulfilled + * + * @return PromiseInterface + */ + public static function ofLimitAll( + $iterable, + $concurrency, + callable $onFulfilled = null + ) { + return each_limit( + $iterable, + $concurrency, + $onFulfilled, + function ($reason, $idx, PromiseInterface $aggregate) { + $aggregate->reject($reason); + } + ); + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/promises/src/EachPromise.php b/data/web/inc/lib/vendor/guzzlehttp/promises/src/EachPromise.php new file mode 100644 index 000000000..280d79950 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/promises/src/EachPromise.php @@ -0,0 +1,247 @@ +iterable = Create::iterFor($iterable); + + if (isset($config['concurrency'])) { + $this->concurrency = $config['concurrency']; + } + + if (isset($config['fulfilled'])) { + $this->onFulfilled = $config['fulfilled']; + } + + if (isset($config['rejected'])) { + $this->onRejected = $config['rejected']; + } + } + + /** @psalm-suppress InvalidNullableReturnType */ + public function promise() + { + if ($this->aggregate) { + return $this->aggregate; + } + + try { + $this->createPromise(); + /** @psalm-assert Promise $this->aggregate */ + $this->iterable->rewind(); + $this->refillPending(); + } catch (\Throwable $e) { + $this->aggregate->reject($e); + } catch (\Exception $e) { + $this->aggregate->reject($e); + } + + /** + * @psalm-suppress NullableReturnStatement + * @phpstan-ignore-next-line + */ + return $this->aggregate; + } + + private function createPromise() + { + $this->mutex = false; + $this->aggregate = new Promise(function () { + if ($this->checkIfFinished()) { + return; + } + reset($this->pending); + // Consume a potentially fluctuating list of promises while + // ensuring that indexes are maintained (precluding array_shift). + while ($promise = current($this->pending)) { + next($this->pending); + $promise->wait(); + if (Is::settled($this->aggregate)) { + return; + } + } + }); + + // Clear the references when the promise is resolved. + $clearFn = function () { + $this->iterable = $this->concurrency = $this->pending = null; + $this->onFulfilled = $this->onRejected = null; + $this->nextPendingIndex = 0; + }; + + $this->aggregate->then($clearFn, $clearFn); + } + + private function refillPending() + { + if (!$this->concurrency) { + // Add all pending promises. + while ($this->addPending() && $this->advanceIterator()); + return; + } + + // Add only up to N pending promises. + $concurrency = is_callable($this->concurrency) + ? call_user_func($this->concurrency, count($this->pending)) + : $this->concurrency; + $concurrency = max($concurrency - count($this->pending), 0); + // Concurrency may be set to 0 to disallow new promises. + if (!$concurrency) { + return; + } + // Add the first pending promise. + $this->addPending(); + // Note this is special handling for concurrency=1 so that we do + // not advance the iterator after adding the first promise. This + // helps work around issues with generators that might not have the + // next value to yield until promise callbacks are called. + while (--$concurrency + && $this->advanceIterator() + && $this->addPending()); + } + + private function addPending() + { + if (!$this->iterable || !$this->iterable->valid()) { + return false; + } + + $promise = Create::promiseFor($this->iterable->current()); + $key = $this->iterable->key(); + + // Iterable keys may not be unique, so we use a counter to + // guarantee uniqueness + $idx = $this->nextPendingIndex++; + + $this->pending[$idx] = $promise->then( + function ($value) use ($idx, $key) { + if ($this->onFulfilled) { + call_user_func( + $this->onFulfilled, + $value, + $key, + $this->aggregate + ); + } + $this->step($idx); + }, + function ($reason) use ($idx, $key) { + if ($this->onRejected) { + call_user_func( + $this->onRejected, + $reason, + $key, + $this->aggregate + ); + } + $this->step($idx); + } + ); + + return true; + } + + private function advanceIterator() + { + // Place a lock on the iterator so that we ensure to not recurse, + // preventing fatal generator errors. + if ($this->mutex) { + return false; + } + + $this->mutex = true; + + try { + $this->iterable->next(); + $this->mutex = false; + return true; + } catch (\Throwable $e) { + $this->aggregate->reject($e); + $this->mutex = false; + return false; + } catch (\Exception $e) { + $this->aggregate->reject($e); + $this->mutex = false; + return false; + } + } + + private function step($idx) + { + // If the promise was already resolved, then ignore this step. + if (Is::settled($this->aggregate)) { + return; + } + + unset($this->pending[$idx]); + + // Only refill pending promises if we are not locked, preventing the + // EachPromise to recursively invoke the provided iterator, which + // cause a fatal error: "Cannot resume an already running generator" + if ($this->advanceIterator() && !$this->checkIfFinished()) { + // Add more pending promises if possible. + $this->refillPending(); + } + } + + private function checkIfFinished() + { + if (!$this->pending && !$this->iterable->valid()) { + // Resolve the promise if there's nothing left to do. + $this->aggregate->resolve(null); + return true; + } + + return false; + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/promises/src/FulfilledPromise.php b/data/web/inc/lib/vendor/guzzlehttp/promises/src/FulfilledPromise.php new file mode 100644 index 000000000..98f72a62a --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/promises/src/FulfilledPromise.php @@ -0,0 +1,84 @@ +value = $value; + } + + public function then( + callable $onFulfilled = null, + callable $onRejected = null + ) { + // Return itself if there is no onFulfilled function. + if (!$onFulfilled) { + return $this; + } + + $queue = Utils::queue(); + $p = new Promise([$queue, 'run']); + $value = $this->value; + $queue->add(static function () use ($p, $value, $onFulfilled) { + if (Is::pending($p)) { + try { + $p->resolve($onFulfilled($value)); + } catch (\Throwable $e) { + $p->reject($e); + } catch (\Exception $e) { + $p->reject($e); + } + } + }); + + return $p; + } + + public function otherwise(callable $onRejected) + { + return $this->then(null, $onRejected); + } + + public function wait($unwrap = true, $defaultDelivery = null) + { + return $unwrap ? $this->value : null; + } + + public function getState() + { + return self::FULFILLED; + } + + public function resolve($value) + { + if ($value !== $this->value) { + throw new \LogicException("Cannot resolve a fulfilled promise"); + } + } + + public function reject($reason) + { + throw new \LogicException("Cannot reject a fulfilled promise"); + } + + public function cancel() + { + // pass + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/promises/src/Is.php b/data/web/inc/lib/vendor/guzzlehttp/promises/src/Is.php new file mode 100644 index 000000000..c3ed8d014 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/promises/src/Is.php @@ -0,0 +1,46 @@ +getState() === PromiseInterface::PENDING; + } + + /** + * Returns true if a promise is fulfilled or rejected. + * + * @return bool + */ + public static function settled(PromiseInterface $promise) + { + return $promise->getState() !== PromiseInterface::PENDING; + } + + /** + * Returns true if a promise is fulfilled. + * + * @return bool + */ + public static function fulfilled(PromiseInterface $promise) + { + return $promise->getState() === PromiseInterface::FULFILLED; + } + + /** + * Returns true if a promise is rejected. + * + * @return bool + */ + public static function rejected(PromiseInterface $promise) + { + return $promise->getState() === PromiseInterface::REJECTED; + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/promises/src/Promise.php b/data/web/inc/lib/vendor/guzzlehttp/promises/src/Promise.php new file mode 100644 index 000000000..75939057b --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/promises/src/Promise.php @@ -0,0 +1,278 @@ +waitFn = $waitFn; + $this->cancelFn = $cancelFn; + } + + public function then( + callable $onFulfilled = null, + callable $onRejected = null + ) { + if ($this->state === self::PENDING) { + $p = new Promise(null, [$this, 'cancel']); + $this->handlers[] = [$p, $onFulfilled, $onRejected]; + $p->waitList = $this->waitList; + $p->waitList[] = $this; + return $p; + } + + // Return a fulfilled promise and immediately invoke any callbacks. + if ($this->state === self::FULFILLED) { + $promise = Create::promiseFor($this->result); + return $onFulfilled ? $promise->then($onFulfilled) : $promise; + } + + // It's either cancelled or rejected, so return a rejected promise + // and immediately invoke any callbacks. + $rejection = Create::rejectionFor($this->result); + return $onRejected ? $rejection->then(null, $onRejected) : $rejection; + } + + public function otherwise(callable $onRejected) + { + return $this->then(null, $onRejected); + } + + public function wait($unwrap = true) + { + $this->waitIfPending(); + + if ($this->result instanceof PromiseInterface) { + return $this->result->wait($unwrap); + } + if ($unwrap) { + if ($this->state === self::FULFILLED) { + return $this->result; + } + // It's rejected so "unwrap" and throw an exception. + throw Create::exceptionFor($this->result); + } + } + + public function getState() + { + return $this->state; + } + + public function cancel() + { + if ($this->state !== self::PENDING) { + return; + } + + $this->waitFn = $this->waitList = null; + + if ($this->cancelFn) { + $fn = $this->cancelFn; + $this->cancelFn = null; + try { + $fn(); + } catch (\Throwable $e) { + $this->reject($e); + } catch (\Exception $e) { + $this->reject($e); + } + } + + // Reject the promise only if it wasn't rejected in a then callback. + /** @psalm-suppress RedundantCondition */ + if ($this->state === self::PENDING) { + $this->reject(new CancellationException('Promise has been cancelled')); + } + } + + public function resolve($value) + { + $this->settle(self::FULFILLED, $value); + } + + public function reject($reason) + { + $this->settle(self::REJECTED, $reason); + } + + private function settle($state, $value) + { + if ($this->state !== self::PENDING) { + // Ignore calls with the same resolution. + if ($state === $this->state && $value === $this->result) { + return; + } + throw $this->state === $state + ? new \LogicException("The promise is already {$state}.") + : new \LogicException("Cannot change a {$this->state} promise to {$state}"); + } + + if ($value === $this) { + throw new \LogicException('Cannot fulfill or reject a promise with itself'); + } + + // Clear out the state of the promise but stash the handlers. + $this->state = $state; + $this->result = $value; + $handlers = $this->handlers; + $this->handlers = null; + $this->waitList = $this->waitFn = null; + $this->cancelFn = null; + + if (!$handlers) { + return; + } + + // If the value was not a settled promise or a thenable, then resolve + // it in the task queue using the correct ID. + if (!is_object($value) || !method_exists($value, 'then')) { + $id = $state === self::FULFILLED ? 1 : 2; + // It's a success, so resolve the handlers in the queue. + Utils::queue()->add(static function () use ($id, $value, $handlers) { + foreach ($handlers as $handler) { + self::callHandler($id, $value, $handler); + } + }); + } elseif ($value instanceof Promise && Is::pending($value)) { + // We can just merge our handlers onto the next promise. + $value->handlers = array_merge($value->handlers, $handlers); + } else { + // Resolve the handlers when the forwarded promise is resolved. + $value->then( + static function ($value) use ($handlers) { + foreach ($handlers as $handler) { + self::callHandler(1, $value, $handler); + } + }, + static function ($reason) use ($handlers) { + foreach ($handlers as $handler) { + self::callHandler(2, $reason, $handler); + } + } + ); + } + } + + /** + * Call a stack of handlers using a specific callback index and value. + * + * @param int $index 1 (resolve) or 2 (reject). + * @param mixed $value Value to pass to the callback. + * @param array $handler Array of handler data (promise and callbacks). + */ + private static function callHandler($index, $value, array $handler) + { + /** @var PromiseInterface $promise */ + $promise = $handler[0]; + + // The promise may have been cancelled or resolved before placing + // this thunk in the queue. + if (Is::settled($promise)) { + return; + } + + try { + if (isset($handler[$index])) { + /* + * If $f throws an exception, then $handler will be in the exception + * stack trace. Since $handler contains a reference to the callable + * itself we get a circular reference. We clear the $handler + * here to avoid that memory leak. + */ + $f = $handler[$index]; + unset($handler); + $promise->resolve($f($value)); + } elseif ($index === 1) { + // Forward resolution values as-is. + $promise->resolve($value); + } else { + // Forward rejections down the chain. + $promise->reject($value); + } + } catch (\Throwable $reason) { + $promise->reject($reason); + } catch (\Exception $reason) { + $promise->reject($reason); + } + } + + private function waitIfPending() + { + if ($this->state !== self::PENDING) { + return; + } elseif ($this->waitFn) { + $this->invokeWaitFn(); + } elseif ($this->waitList) { + $this->invokeWaitList(); + } else { + // If there's no wait function, then reject the promise. + $this->reject('Cannot wait on a promise that has ' + . 'no internal wait function. You must provide a wait ' + . 'function when constructing the promise to be able to ' + . 'wait on a promise.'); + } + + Utils::queue()->run(); + + /** @psalm-suppress RedundantCondition */ + if ($this->state === self::PENDING) { + $this->reject('Invoking the wait callback did not resolve the promise'); + } + } + + private function invokeWaitFn() + { + try { + $wfn = $this->waitFn; + $this->waitFn = null; + $wfn(true); + } catch (\Exception $reason) { + if ($this->state === self::PENDING) { + // The promise has not been resolved yet, so reject the promise + // with the exception. + $this->reject($reason); + } else { + // The promise was already resolved, so there's a problem in + // the application. + throw $reason; + } + } + } + + private function invokeWaitList() + { + $waitList = $this->waitList; + $this->waitList = null; + + foreach ($waitList as $result) { + do { + $result->waitIfPending(); + $result = $result->result; + } while ($result instanceof Promise); + + if ($result instanceof PromiseInterface) { + $result->wait(false); + } + } + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/promises/src/PromiseInterface.php b/data/web/inc/lib/vendor/guzzlehttp/promises/src/PromiseInterface.php new file mode 100644 index 000000000..e59833143 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/promises/src/PromiseInterface.php @@ -0,0 +1,97 @@ +reason = $reason; + } + + public function then( + callable $onFulfilled = null, + callable $onRejected = null + ) { + // If there's no onRejected callback then just return self. + if (!$onRejected) { + return $this; + } + + $queue = Utils::queue(); + $reason = $this->reason; + $p = new Promise([$queue, 'run']); + $queue->add(static function () use ($p, $reason, $onRejected) { + if (Is::pending($p)) { + try { + // Return a resolved promise if onRejected does not throw. + $p->resolve($onRejected($reason)); + } catch (\Throwable $e) { + // onRejected threw, so return a rejected promise. + $p->reject($e); + } catch (\Exception $e) { + // onRejected threw, so return a rejected promise. + $p->reject($e); + } + } + }); + + return $p; + } + + public function otherwise(callable $onRejected) + { + return $this->then(null, $onRejected); + } + + public function wait($unwrap = true, $defaultDelivery = null) + { + if ($unwrap) { + throw Create::exceptionFor($this->reason); + } + + return null; + } + + public function getState() + { + return self::REJECTED; + } + + public function resolve($value) + { + throw new \LogicException("Cannot resolve a rejected promise"); + } + + public function reject($reason) + { + if ($reason !== $this->reason) { + throw new \LogicException("Cannot reject a rejected promise"); + } + } + + public function cancel() + { + // pass + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/promises/src/RejectionException.php b/data/web/inc/lib/vendor/guzzlehttp/promises/src/RejectionException.php new file mode 100644 index 000000000..e2f137707 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/promises/src/RejectionException.php @@ -0,0 +1,48 @@ +reason = $reason; + + $message = 'The promise was rejected'; + + if ($description) { + $message .= ' with reason: ' . $description; + } elseif (is_string($reason) + || (is_object($reason) && method_exists($reason, '__toString')) + ) { + $message .= ' with reason: ' . $this->reason; + } elseif ($reason instanceof \JsonSerializable) { + $message .= ' with reason: ' + . json_encode($this->reason, JSON_PRETTY_PRINT); + } + + parent::__construct($message); + } + + /** + * Returns the rejection reason. + * + * @return mixed + */ + public function getReason() + { + return $this->reason; + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/promises/src/TaskQueue.php b/data/web/inc/lib/vendor/guzzlehttp/promises/src/TaskQueue.php new file mode 100644 index 000000000..f0fba2c59 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/promises/src/TaskQueue.php @@ -0,0 +1,67 @@ +run(); + */ +class TaskQueue implements TaskQueueInterface +{ + private $enableShutdown = true; + private $queue = []; + + public function __construct($withShutdown = true) + { + if ($withShutdown) { + register_shutdown_function(function () { + if ($this->enableShutdown) { + // Only run the tasks if an E_ERROR didn't occur. + $err = error_get_last(); + if (!$err || ($err['type'] ^ E_ERROR)) { + $this->run(); + } + } + }); + } + } + + public function isEmpty() + { + return !$this->queue; + } + + public function add(callable $task) + { + $this->queue[] = $task; + } + + public function run() + { + while ($task = array_shift($this->queue)) { + /** @var callable $task */ + $task(); + } + } + + /** + * The task queue will be run and exhausted by default when the process + * exits IFF the exit is not the result of a PHP E_ERROR error. + * + * You can disable running the automatic shutdown of the queue by calling + * this function. If you disable the task queue shutdown process, then you + * MUST either run the task queue (as a result of running your event loop + * or manually using the run() method) or wait on each outstanding promise. + * + * Note: This shutdown will occur before any destructors are triggered. + */ + public function disableShutdown() + { + $this->enableShutdown = false; + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/promises/src/TaskQueueInterface.php b/data/web/inc/lib/vendor/guzzlehttp/promises/src/TaskQueueInterface.php new file mode 100644 index 000000000..723d4d54e --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/promises/src/TaskQueueInterface.php @@ -0,0 +1,24 @@ + + * while ($eventLoop->isRunning()) { + * GuzzleHttp\Promise\Utils::queue()->run(); + * } + * + * + * @param TaskQueueInterface $assign Optionally specify a new queue instance. + * + * @return TaskQueueInterface + */ + public static function queue(TaskQueueInterface $assign = null) + { + static $queue; + + if ($assign) { + $queue = $assign; + } elseif (!$queue) { + $queue = new TaskQueue(); + } + + return $queue; + } + + /** + * Adds a function to run in the task queue when it is next `run()` and + * returns a promise that is fulfilled or rejected with the result. + * + * @param callable $task Task function to run. + * + * @return PromiseInterface + */ + public static function task(callable $task) + { + $queue = self::queue(); + $promise = new Promise([$queue, 'run']); + $queue->add(function () use ($task, $promise) { + try { + if (Is::pending($promise)) { + $promise->resolve($task()); + } + } catch (\Throwable $e) { + $promise->reject($e); + } catch (\Exception $e) { + $promise->reject($e); + } + }); + + return $promise; + } + + /** + * Synchronously waits on a promise to resolve and returns an inspection + * state array. + * + * Returns a state associative array containing a "state" key mapping to a + * valid promise state. If the state of the promise is "fulfilled", the + * array will contain a "value" key mapping to the fulfilled value of the + * promise. If the promise is rejected, the array will contain a "reason" + * key mapping to the rejection reason of the promise. + * + * @param PromiseInterface $promise Promise or value. + * + * @return array + */ + public static function inspect(PromiseInterface $promise) + { + try { + return [ + 'state' => PromiseInterface::FULFILLED, + 'value' => $promise->wait() + ]; + } catch (RejectionException $e) { + return ['state' => PromiseInterface::REJECTED, 'reason' => $e->getReason()]; + } catch (\Throwable $e) { + return ['state' => PromiseInterface::REJECTED, 'reason' => $e]; + } catch (\Exception $e) { + return ['state' => PromiseInterface::REJECTED, 'reason' => $e]; + } + } + + /** + * Waits on all of the provided promises, but does not unwrap rejected + * promises as thrown exception. + * + * Returns an array of inspection state arrays. + * + * @see inspect for the inspection state array format. + * + * @param PromiseInterface[] $promises Traversable of promises to wait upon. + * + * @return array + */ + public static function inspectAll($promises) + { + $results = []; + foreach ($promises as $key => $promise) { + $results[$key] = inspect($promise); + } + + return $results; + } + + /** + * Waits on all of the provided promises and returns the fulfilled values. + * + * Returns an array that contains the value of each promise (in the same + * order the promises were provided). An exception is thrown if any of the + * promises are rejected. + * + * @param iterable $promises Iterable of PromiseInterface objects to wait on. + * + * @return array + * + * @throws \Exception on error + * @throws \Throwable on error in PHP >=7 + */ + public static function unwrap($promises) + { + $results = []; + foreach ($promises as $key => $promise) { + $results[$key] = $promise->wait(); + } + + return $results; + } + + /** + * Given an array of promises, return a promise that is fulfilled when all + * the items in the array are fulfilled. + * + * The promise's fulfillment value is an array with fulfillment values at + * respective positions to the original array. If any promise in the array + * rejects, the returned promise is rejected with the rejection reason. + * + * @param mixed $promises Promises or values. + * @param bool $recursive If true, resolves new promises that might have been added to the stack during its own resolution. + * + * @return PromiseInterface + */ + public static function all($promises, $recursive = false) + { + $results = []; + $promise = Each::of( + $promises, + function ($value, $idx) use (&$results) { + $results[$idx] = $value; + }, + function ($reason, $idx, Promise $aggregate) { + $aggregate->reject($reason); + } + )->then(function () use (&$results) { + ksort($results); + return $results; + }); + + if (true === $recursive) { + $promise = $promise->then(function ($results) use ($recursive, &$promises) { + foreach ($promises as $promise) { + if (Is::pending($promise)) { + return self::all($promises, $recursive); + } + } + return $results; + }); + } + + return $promise; + } + + /** + * Initiate a competitive race between multiple promises or values (values + * will become immediately fulfilled promises). + * + * When count amount of promises have been fulfilled, the returned promise + * is fulfilled with an array that contains the fulfillment values of the + * winners in order of resolution. + * + * This promise is rejected with a {@see AggregateException} if the number + * of fulfilled promises is less than the desired $count. + * + * @param int $count Total number of promises. + * @param mixed $promises Promises or values. + * + * @return PromiseInterface + */ + public static function some($count, $promises) + { + $results = []; + $rejections = []; + + return Each::of( + $promises, + function ($value, $idx, PromiseInterface $p) use (&$results, $count) { + if (Is::settled($p)) { + return; + } + $results[$idx] = $value; + if (count($results) >= $count) { + $p->resolve(null); + } + }, + function ($reason) use (&$rejections) { + $rejections[] = $reason; + } + )->then( + function () use (&$results, &$rejections, $count) { + if (count($results) !== $count) { + throw new AggregateException( + 'Not enough promises to fulfill count', + $rejections + ); + } + ksort($results); + return array_values($results); + } + ); + } + + /** + * Like some(), with 1 as count. However, if the promise fulfills, the + * fulfillment value is not an array of 1 but the value directly. + * + * @param mixed $promises Promises or values. + * + * @return PromiseInterface + */ + public static function any($promises) + { + return self::some(1, $promises)->then(function ($values) { + return $values[0]; + }); + } + + /** + * Returns a promise that is fulfilled when all of the provided promises have + * been fulfilled or rejected. + * + * The returned promise is fulfilled with an array of inspection state arrays. + * + * @see inspect for the inspection state array format. + * + * @param mixed $promises Promises or values. + * + * @return PromiseInterface + */ + public static function settle($promises) + { + $results = []; + + return Each::of( + $promises, + function ($value, $idx) use (&$results) { + $results[$idx] = ['state' => PromiseInterface::FULFILLED, 'value' => $value]; + }, + function ($reason, $idx) use (&$results) { + $results[$idx] = ['state' => PromiseInterface::REJECTED, 'reason' => $reason]; + } + )->then(function () use (&$results) { + ksort($results); + return $results; + }); + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/promises/src/functions.php b/data/web/inc/lib/vendor/guzzlehttp/promises/src/functions.php new file mode 100644 index 000000000..c03d39d02 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/promises/src/functions.php @@ -0,0 +1,363 @@ + + * while ($eventLoop->isRunning()) { + * GuzzleHttp\Promise\queue()->run(); + * } + * + * + * @param TaskQueueInterface $assign Optionally specify a new queue instance. + * + * @return TaskQueueInterface + * + * @deprecated queue will be removed in guzzlehttp/promises:2.0. Use Utils::queue instead. + */ +function queue(TaskQueueInterface $assign = null) +{ + return Utils::queue($assign); +} + +/** + * Adds a function to run in the task queue when it is next `run()` and returns + * a promise that is fulfilled or rejected with the result. + * + * @param callable $task Task function to run. + * + * @return PromiseInterface + * + * @deprecated task will be removed in guzzlehttp/promises:2.0. Use Utils::task instead. + */ +function task(callable $task) +{ + return Utils::task($task); +} + +/** + * Creates a promise for a value if the value is not a promise. + * + * @param mixed $value Promise or value. + * + * @return PromiseInterface + * + * @deprecated promise_for will be removed in guzzlehttp/promises:2.0. Use Create::promiseFor instead. + */ +function promise_for($value) +{ + return Create::promiseFor($value); +} + +/** + * Creates a rejected promise for a reason if the reason is not a promise. If + * the provided reason is a promise, then it is returned as-is. + * + * @param mixed $reason Promise or reason. + * + * @return PromiseInterface + * + * @deprecated rejection_for will be removed in guzzlehttp/promises:2.0. Use Create::rejectionFor instead. + */ +function rejection_for($reason) +{ + return Create::rejectionFor($reason); +} + +/** + * Create an exception for a rejected promise value. + * + * @param mixed $reason + * + * @return \Exception|\Throwable + * + * @deprecated exception_for will be removed in guzzlehttp/promises:2.0. Use Create::exceptionFor instead. + */ +function exception_for($reason) +{ + return Create::exceptionFor($reason); +} + +/** + * Returns an iterator for the given value. + * + * @param mixed $value + * + * @return \Iterator + * + * @deprecated iter_for will be removed in guzzlehttp/promises:2.0. Use Create::iterFor instead. + */ +function iter_for($value) +{ + return Create::iterFor($value); +} + +/** + * Synchronously waits on a promise to resolve and returns an inspection state + * array. + * + * Returns a state associative array containing a "state" key mapping to a + * valid promise state. If the state of the promise is "fulfilled", the array + * will contain a "value" key mapping to the fulfilled value of the promise. If + * the promise is rejected, the array will contain a "reason" key mapping to + * the rejection reason of the promise. + * + * @param PromiseInterface $promise Promise or value. + * + * @return array + * + * @deprecated inspect will be removed in guzzlehttp/promises:2.0. Use Utils::inspect instead. + */ +function inspect(PromiseInterface $promise) +{ + return Utils::inspect($promise); +} + +/** + * Waits on all of the provided promises, but does not unwrap rejected promises + * as thrown exception. + * + * Returns an array of inspection state arrays. + * + * @see inspect for the inspection state array format. + * + * @param PromiseInterface[] $promises Traversable of promises to wait upon. + * + * @return array + * + * @deprecated inspect will be removed in guzzlehttp/promises:2.0. Use Utils::inspectAll instead. + */ +function inspect_all($promises) +{ + return Utils::inspectAll($promises); +} + +/** + * Waits on all of the provided promises and returns the fulfilled values. + * + * Returns an array that contains the value of each promise (in the same order + * the promises were provided). An exception is thrown if any of the promises + * are rejected. + * + * @param iterable $promises Iterable of PromiseInterface objects to wait on. + * + * @return array + * + * @throws \Exception on error + * @throws \Throwable on error in PHP >=7 + * + * @deprecated unwrap will be removed in guzzlehttp/promises:2.0. Use Utils::unwrap instead. + */ +function unwrap($promises) +{ + return Utils::unwrap($promises); +} + +/** + * Given an array of promises, return a promise that is fulfilled when all the + * items in the array are fulfilled. + * + * The promise's fulfillment value is an array with fulfillment values at + * respective positions to the original array. If any promise in the array + * rejects, the returned promise is rejected with the rejection reason. + * + * @param mixed $promises Promises or values. + * @param bool $recursive If true, resolves new promises that might have been added to the stack during its own resolution. + * + * @return PromiseInterface + * + * @deprecated all will be removed in guzzlehttp/promises:2.0. Use Utils::all instead. + */ +function all($promises, $recursive = false) +{ + return Utils::all($promises, $recursive); +} + +/** + * Initiate a competitive race between multiple promises or values (values will + * become immediately fulfilled promises). + * + * When count amount of promises have been fulfilled, the returned promise is + * fulfilled with an array that contains the fulfillment values of the winners + * in order of resolution. + * + * This promise is rejected with a {@see AggregateException} if the number of + * fulfilled promises is less than the desired $count. + * + * @param int $count Total number of promises. + * @param mixed $promises Promises or values. + * + * @return PromiseInterface + * + * @deprecated some will be removed in guzzlehttp/promises:2.0. Use Utils::some instead. + */ +function some($count, $promises) +{ + return Utils::some($count, $promises); +} + +/** + * Like some(), with 1 as count. However, if the promise fulfills, the + * fulfillment value is not an array of 1 but the value directly. + * + * @param mixed $promises Promises or values. + * + * @return PromiseInterface + * + * @deprecated any will be removed in guzzlehttp/promises:2.0. Use Utils::any instead. + */ +function any($promises) +{ + return Utils::any($promises); +} + +/** + * Returns a promise that is fulfilled when all of the provided promises have + * been fulfilled or rejected. + * + * The returned promise is fulfilled with an array of inspection state arrays. + * + * @see inspect for the inspection state array format. + * + * @param mixed $promises Promises or values. + * + * @return PromiseInterface + * + * @deprecated settle will be removed in guzzlehttp/promises:2.0. Use Utils::settle instead. + */ +function settle($promises) +{ + return Utils::settle($promises); +} + +/** + * Given an iterator that yields promises or values, returns a promise that is + * fulfilled with a null value when the iterator has been consumed or the + * aggregate promise has been fulfilled or rejected. + * + * $onFulfilled is a function that accepts the fulfilled value, iterator index, + * and the aggregate promise. The callback can invoke any necessary side + * effects and choose to resolve or reject the aggregate if needed. + * + * $onRejected is a function that accepts the rejection reason, iterator index, + * and the aggregate promise. The callback can invoke any necessary side + * effects and choose to resolve or reject the aggregate if needed. + * + * @param mixed $iterable Iterator or array to iterate over. + * @param callable $onFulfilled + * @param callable $onRejected + * + * @return PromiseInterface + * + * @deprecated each will be removed in guzzlehttp/promises:2.0. Use Each::of instead. + */ +function each( + $iterable, + callable $onFulfilled = null, + callable $onRejected = null +) { + return Each::of($iterable, $onFulfilled, $onRejected); +} + +/** + * Like each, but only allows a certain number of outstanding promises at any + * given time. + * + * $concurrency may be an integer or a function that accepts the number of + * pending promises and returns a numeric concurrency limit value to allow for + * dynamic a concurrency size. + * + * @param mixed $iterable + * @param int|callable $concurrency + * @param callable $onFulfilled + * @param callable $onRejected + * + * @return PromiseInterface + * + * @deprecated each_limit will be removed in guzzlehttp/promises:2.0. Use Each::ofLimit instead. + */ +function each_limit( + $iterable, + $concurrency, + callable $onFulfilled = null, + callable $onRejected = null +) { + return Each::ofLimit($iterable, $concurrency, $onFulfilled, $onRejected); +} + +/** + * Like each_limit, but ensures that no promise in the given $iterable argument + * is rejected. If any promise is rejected, then the aggregate promise is + * rejected with the encountered rejection. + * + * @param mixed $iterable + * @param int|callable $concurrency + * @param callable $onFulfilled + * + * @return PromiseInterface + * + * @deprecated each_limit_all will be removed in guzzlehttp/promises:2.0. Use Each::ofLimitAll instead. + */ +function each_limit_all( + $iterable, + $concurrency, + callable $onFulfilled = null +) { + return Each::ofLimitAll($iterable, $concurrency, $onFulfilled); +} + +/** + * Returns true if a promise is fulfilled. + * + * @return bool + * + * @deprecated is_fulfilled will be removed in guzzlehttp/promises:2.0. Use Is::fulfilled instead. + */ +function is_fulfilled(PromiseInterface $promise) +{ + return Is::fulfilled($promise); +} + +/** + * Returns true if a promise is rejected. + * + * @return bool + * + * @deprecated is_rejected will be removed in guzzlehttp/promises:2.0. Use Is::rejected instead. + */ +function is_rejected(PromiseInterface $promise) +{ + return Is::rejected($promise); +} + +/** + * Returns true if a promise is fulfilled or rejected. + * + * @return bool + * + * @deprecated is_settled will be removed in guzzlehttp/promises:2.0. Use Is::settled instead. + */ +function is_settled(PromiseInterface $promise) +{ + return Is::settled($promise); +} + +/** + * Create a new coroutine. + * + * @see Coroutine + * + * @return PromiseInterface + * + * @deprecated coroutine will be removed in guzzlehttp/promises:2.0. Use Coroutine::of instead. + */ +function coroutine(callable $generatorFn) +{ + return Coroutine::of($generatorFn); +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/promises/src/functions_include.php b/data/web/inc/lib/vendor/guzzlehttp/promises/src/functions_include.php new file mode 100644 index 000000000..34cd1710a --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/promises/src/functions_include.php @@ -0,0 +1,6 @@ +withPath('foo')->withHost('example.com')` will throw an exception + because the path of a URI with an authority must start with a slash "/" or be empty + - `(new Uri())->withScheme('http')` will return `'http://localhost'` + +### Deprecated + +- `Uri::resolve` in favor of `UriResolver::resolve` +- `Uri::removeDotSegments` in favor of `UriResolver::removeDotSegments` + +### Fixed + +- `Stream::read` when length parameter <= 0. +- `copy_to_stream` reads bytes in chunks instead of `maxLen` into memory. +- `ServerRequest::getUriFromGlobals` when `Host` header contains port. +- Compatibility of URIs with `file` scheme and empty host. + + +## [1.3.1] - 2016-06-25 + +### Fixed + +- `Uri::__toString` for network path references, e.g. `//example.org`. +- Missing lowercase normalization for host. +- Handling of URI components in case they are `'0'` in a lot of places, + e.g. as a user info password. +- `Uri::withAddedHeader` to correctly merge headers with different case. +- Trimming of header values in `Uri::withAddedHeader`. Header values may + be surrounded by whitespace which should be ignored according to RFC 7230 + Section 3.2.4. This does not apply to header names. +- `Uri::withAddedHeader` with an array of header values. +- `Uri::resolve` when base path has no slash and handling of fragment. +- Handling of encoding in `Uri::with(out)QueryValue` so one can pass the + key/value both in encoded as well as decoded form to those methods. This is + consistent with withPath, withQuery etc. +- `ServerRequest::withoutAttribute` when attribute value is null. + + +## [1.3.0] - 2016-04-13 + +### Added + +- Remaining interfaces needed for full PSR7 compatibility + (ServerRequestInterface, UploadedFileInterface, etc.). +- Support for stream_for from scalars. + +### Changed + +- Can now extend Uri. + +### Fixed +- A bug in validating request methods by making it more permissive. + + +## [1.2.3] - 2016-02-18 + +### Fixed + +- Support in `GuzzleHttp\Psr7\CachingStream` for seeking forward on remote + streams, which can sometimes return fewer bytes than requested with `fread`. +- Handling of gzipped responses with FNAME headers. + + +## [1.2.2] - 2016-01-22 + +### Added + +- Support for URIs without any authority. +- Support for HTTP 451 'Unavailable For Legal Reasons.' +- Support for using '0' as a filename. +- Support for including non-standard ports in Host headers. + + +## [1.2.1] - 2015-11-02 + +### Changes + +- Now supporting negative offsets when seeking to SEEK_END. + + +## [1.2.0] - 2015-08-15 + +### Changed + +- Body as `"0"` is now properly added to a response. +- Now allowing forward seeking in CachingStream. +- Now properly parsing HTTP requests that contain proxy targets in + `parse_request`. +- functions.php is now conditionally required. +- user-info is no longer dropped when resolving URIs. + + +## [1.1.0] - 2015-06-24 + +### Changed + +- URIs can now be relative. +- `multipart/form-data` headers are now overridden case-insensitively. +- URI paths no longer encode the following characters because they are allowed + in URIs: "(", ")", "*", "!", "'" +- A port is no longer added to a URI when the scheme is missing and no port is + present. + + +## 1.0.0 - 2015-05-19 + +Initial release. + +Currently unsupported: + +- `Psr\Http\Message\ServerRequestInterface` +- `Psr\Http\Message\UploadedFileInterface` + + + +[1.6.0]: https://github.com/guzzle/psr7/compare/1.5.2...1.6.0 +[1.5.2]: https://github.com/guzzle/psr7/compare/1.5.1...1.5.2 +[1.5.1]: https://github.com/guzzle/psr7/compare/1.5.0...1.5.1 +[1.5.0]: https://github.com/guzzle/psr7/compare/1.4.2...1.5.0 +[1.4.2]: https://github.com/guzzle/psr7/compare/1.4.1...1.4.2 +[1.4.1]: https://github.com/guzzle/psr7/compare/1.4.0...1.4.1 +[1.4.0]: https://github.com/guzzle/psr7/compare/1.3.1...1.4.0 +[1.3.1]: https://github.com/guzzle/psr7/compare/1.3.0...1.3.1 +[1.3.0]: https://github.com/guzzle/psr7/compare/1.2.3...1.3.0 +[1.2.3]: https://github.com/guzzle/psr7/compare/1.2.2...1.2.3 +[1.2.2]: https://github.com/guzzle/psr7/compare/1.2.1...1.2.2 +[1.2.1]: https://github.com/guzzle/psr7/compare/1.2.0...1.2.1 +[1.2.0]: https://github.com/guzzle/psr7/compare/1.1.0...1.2.0 +[1.1.0]: https://github.com/guzzle/psr7/compare/1.0.0...1.1.0 diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/LICENSE b/data/web/inc/lib/vendor/guzzlehttp/psr7/LICENSE new file mode 100644 index 000000000..51c7ec81c --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/LICENSE @@ -0,0 +1,26 @@ +The MIT License (MIT) + +Copyright (c) 2015 Michael Dowling +Copyright (c) 2015 Márk Sági-Kazár +Copyright (c) 2015 Graham Campbell +Copyright (c) 2016 Tobias Schultze +Copyright (c) 2016 George Mponos +Copyright (c) 2018 Tobias Nyholm + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/README.md b/data/web/inc/lib/vendor/guzzlehttp/psr7/README.md new file mode 100644 index 000000000..9566a7d47 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/README.md @@ -0,0 +1,880 @@ +# PSR-7 Message Implementation + +This repository contains a full [PSR-7](https://www.php-fig.org/psr/psr-7/) +message implementation, several stream decorators, and some helpful +functionality like query string parsing. + +![CI](https://github.com/guzzle/psr7/workflows/CI/badge.svg) +![Static analysis](https://github.com/guzzle/psr7/workflows/Static%20analysis/badge.svg) + + +# Installation + +```shell +composer require guzzlehttp/psr7 +``` + +# Stream implementation + +This package comes with a number of stream implementations and stream +decorators. + + +## AppendStream + +`GuzzleHttp\Psr7\AppendStream` + +Reads from multiple streams, one after the other. + +```php +use GuzzleHttp\Psr7; + +$a = Psr7\Utils::streamFor('abc, '); +$b = Psr7\Utils::streamFor('123.'); +$composed = new Psr7\AppendStream([$a, $b]); + +$composed->addStream(Psr7\Utils::streamFor(' Above all listen to me')); + +echo $composed; // abc, 123. Above all listen to me. +``` + + +## BufferStream + +`GuzzleHttp\Psr7\BufferStream` + +Provides a buffer stream that can be written to fill a buffer, and read +from to remove bytes from the buffer. + +This stream returns a "hwm" metadata value that tells upstream consumers +what the configured high water mark of the stream is, or the maximum +preferred size of the buffer. + +```php +use GuzzleHttp\Psr7; + +// When more than 1024 bytes are in the buffer, it will begin returning +// false to writes. This is an indication that writers should slow down. +$buffer = new Psr7\BufferStream(1024); +``` + + +## CachingStream + +The CachingStream is used to allow seeking over previously read bytes on +non-seekable streams. This can be useful when transferring a non-seekable +entity body fails due to needing to rewind the stream (for example, resulting +from a redirect). Data that is read from the remote stream will be buffered in +a PHP temp stream so that previously read bytes are cached first in memory, +then on disk. + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\Utils::streamFor(fopen('http://www.google.com', 'r')); +$stream = new Psr7\CachingStream($original); + +$stream->read(1024); +echo $stream->tell(); +// 1024 + +$stream->seek(0); +echo $stream->tell(); +// 0 +``` + + +## DroppingStream + +`GuzzleHttp\Psr7\DroppingStream` + +Stream decorator that begins dropping data once the size of the underlying +stream becomes too full. + +```php +use GuzzleHttp\Psr7; + +// Create an empty stream +$stream = Psr7\Utils::streamFor(); + +// Start dropping data when the stream has more than 10 bytes +$dropping = new Psr7\DroppingStream($stream, 10); + +$dropping->write('01234567890123456789'); +echo $stream; // 0123456789 +``` + + +## FnStream + +`GuzzleHttp\Psr7\FnStream` + +Compose stream implementations based on a hash of functions. + +Allows for easy testing and extension of a provided stream without needing +to create a concrete class for a simple extension point. + +```php + +use GuzzleHttp\Psr7; + +$stream = Psr7\Utils::streamFor('hi'); +$fnStream = Psr7\FnStream::decorate($stream, [ + 'rewind' => function () use ($stream) { + echo 'About to rewind - '; + $stream->rewind(); + echo 'rewound!'; + } +]); + +$fnStream->rewind(); +// Outputs: About to rewind - rewound! +``` + + +## InflateStream + +`GuzzleHttp\Psr7\InflateStream` + +Uses PHP's zlib.inflate filter to inflate zlib (HTTP deflate, RFC1950) or gzipped (RFC1952) content. + +This stream decorator converts the provided stream to a PHP stream resource, +then appends the zlib.inflate filter. The stream is then converted back +to a Guzzle stream resource to be used as a Guzzle stream. + + +## LazyOpenStream + +`GuzzleHttp\Psr7\LazyOpenStream` + +Lazily reads or writes to a file that is opened only after an IO operation +take place on the stream. + +```php +use GuzzleHttp\Psr7; + +$stream = new Psr7\LazyOpenStream('/path/to/file', 'r'); +// The file has not yet been opened... + +echo $stream->read(10); +// The file is opened and read from only when needed. +``` + + +## LimitStream + +`GuzzleHttp\Psr7\LimitStream` + +LimitStream can be used to read a subset or slice of an existing stream object. +This can be useful for breaking a large file into smaller pieces to be sent in +chunks (e.g. Amazon S3's multipart upload API). + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\Utils::streamFor(fopen('/tmp/test.txt', 'r+')); +echo $original->getSize(); +// >>> 1048576 + +// Limit the size of the body to 1024 bytes and start reading from byte 2048 +$stream = new Psr7\LimitStream($original, 1024, 2048); +echo $stream->getSize(); +// >>> 1024 +echo $stream->tell(); +// >>> 0 +``` + + +## MultipartStream + +`GuzzleHttp\Psr7\MultipartStream` + +Stream that when read returns bytes for a streaming multipart or +multipart/form-data stream. + + +## NoSeekStream + +`GuzzleHttp\Psr7\NoSeekStream` + +NoSeekStream wraps a stream and does not allow seeking. + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\Utils::streamFor('foo'); +$noSeek = new Psr7\NoSeekStream($original); + +echo $noSeek->read(3); +// foo +var_export($noSeek->isSeekable()); +// false +$noSeek->seek(0); +var_export($noSeek->read(3)); +// NULL +``` + + +## PumpStream + +`GuzzleHttp\Psr7\PumpStream` + +Provides a read only stream that pumps data from a PHP callable. + +When invoking the provided callable, the PumpStream will pass the amount of +data requested to read to the callable. The callable can choose to ignore +this value and return fewer or more bytes than requested. Any extra data +returned by the provided callable is buffered internally until drained using +the read() function of the PumpStream. The provided callable MUST return +false when there is no more data to read. + + +## Implementing stream decorators + +Creating a stream decorator is very easy thanks to the +`GuzzleHttp\Psr7\StreamDecoratorTrait`. This trait provides methods that +implement `Psr\Http\Message\StreamInterface` by proxying to an underlying +stream. Just `use` the `StreamDecoratorTrait` and implement your custom +methods. + +For example, let's say we wanted to call a specific function each time the last +byte is read from a stream. This could be implemented by overriding the +`read()` method. + +```php +use Psr\Http\Message\StreamInterface; +use GuzzleHttp\Psr7\StreamDecoratorTrait; + +class EofCallbackStream implements StreamInterface +{ + use StreamDecoratorTrait; + + private $callback; + + private $stream; + + public function __construct(StreamInterface $stream, callable $cb) + { + $this->stream = $stream; + $this->callback = $cb; + } + + public function read($length) + { + $result = $this->stream->read($length); + + // Invoke the callback when EOF is hit. + if ($this->eof()) { + call_user_func($this->callback); + } + + return $result; + } +} +``` + +This decorator could be added to any existing stream and used like so: + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\Utils::streamFor('foo'); + +$eofStream = new EofCallbackStream($original, function () { + echo 'EOF!'; +}); + +$eofStream->read(2); +$eofStream->read(1); +// echoes "EOF!" +$eofStream->seek(0); +$eofStream->read(3); +// echoes "EOF!" +``` + + +## PHP StreamWrapper + +You can use the `GuzzleHttp\Psr7\StreamWrapper` class if you need to use a +PSR-7 stream as a PHP stream resource. + +Use the `GuzzleHttp\Psr7\StreamWrapper::getResource()` method to create a PHP +stream from a PSR-7 stream. + +```php +use GuzzleHttp\Psr7\StreamWrapper; + +$stream = GuzzleHttp\Psr7\Utils::streamFor('hello!'); +$resource = StreamWrapper::getResource($stream); +echo fread($resource, 6); // outputs hello! +``` + + +# Static API + +There are various static methods available under the `GuzzleHttp\Psr7` namespace. + + +## `GuzzleHttp\Psr7\Message::toString` + +`public static function toString(MessageInterface $message): string` + +Returns the string representation of an HTTP message. + +```php +$request = new GuzzleHttp\Psr7\Request('GET', 'http://example.com'); +echo GuzzleHttp\Psr7\Message::toString($request); +``` + + +## `GuzzleHttp\Psr7\Message::bodySummary` + +`public static function bodySummary(MessageInterface $message, int $truncateAt = 120): string|null` + +Get a short summary of the message body. + +Will return `null` if the response is not printable. + + +## `GuzzleHttp\Psr7\Message::rewindBody` + +`public static function rewindBody(MessageInterface $message): void` + +Attempts to rewind a message body and throws an exception on failure. + +The body of the message will only be rewound if a call to `tell()` +returns a value other than `0`. + + +## `GuzzleHttp\Psr7\Message::parseMessage` + +`public static function parseMessage(string $message): array` + +Parses an HTTP message into an associative array. + +The array contains the "start-line" key containing the start line of +the message, "headers" key containing an associative array of header +array values, and a "body" key containing the body of the message. + + +## `GuzzleHttp\Psr7\Message::parseRequestUri` + +`public static function parseRequestUri(string $path, array $headers): string` + +Constructs a URI for an HTTP request message. + + +## `GuzzleHttp\Psr7\Message::parseRequest` + +`public static function parseRequest(string $message): Request` + +Parses a request message string into a request object. + + +## `GuzzleHttp\Psr7\Message::parseResponse` + +`public static function parseResponse(string $message): Response` + +Parses a response message string into a response object. + + +## `GuzzleHttp\Psr7\Header::parse` + +`public static function parse(string|array $header): array` + +Parse an array of header values containing ";" separated data into an +array of associative arrays representing the header key value pair data +of the header. When a parameter does not contain a value, but just +contains a key, this function will inject a key with a '' string value. + + +## `GuzzleHttp\Psr7\Header::splitList` + +`public static function splitList(string|string[] $header): string[]` + +Splits a HTTP header defined to contain a comma-separated list into +each individual value: + +``` +$knownEtags = Header::splitList($request->getHeader('if-none-match')); +``` + +Example headers include `accept`, `cache-control` and `if-none-match`. + + +## `GuzzleHttp\Psr7\Header::normalize` (deprecated) + +`public static function normalize(string|array $header): array` + +`Header::normalize()` is deprecated in favor of [`Header::splitList()`](README.md#guzzlehttppsr7headersplitlist) +which performs the same operation with a cleaned up API and improved +documentation. + +Converts an array of header values that may contain comma separated +headers into an array of headers with no comma separated values. + + +## `GuzzleHttp\Psr7\Query::parse` + +`public static function parse(string $str, int|bool $urlEncoding = true): array` + +Parse a query string into an associative array. + +If multiple values are found for the same key, the value of that key +value pair will become an array. This function does not parse nested +PHP style arrays into an associative array (e.g., `foo[a]=1&foo[b]=2` +will be parsed into `['foo[a]' => '1', 'foo[b]' => '2'])`. + + +## `GuzzleHttp\Psr7\Query::build` + +`public static function build(array $params, int|false $encoding = PHP_QUERY_RFC3986): string` + +Build a query string from an array of key value pairs. + +This function can use the return value of `parse()` to build a query +string. This function does not modify the provided keys when an array is +encountered (like `http_build_query()` would). + + +## `GuzzleHttp\Psr7\Utils::caselessRemove` + +`public static function caselessRemove(iterable $keys, $keys, array $data): array` + +Remove the items given by the keys, case insensitively from the data. + + +## `GuzzleHttp\Psr7\Utils::copyToStream` + +`public static function copyToStream(StreamInterface $source, StreamInterface $dest, int $maxLen = -1): void` + +Copy the contents of a stream into another stream until the given number +of bytes have been read. + + +## `GuzzleHttp\Psr7\Utils::copyToString` + +`public static function copyToString(StreamInterface $stream, int $maxLen = -1): string` + +Copy the contents of a stream into a string until the given number of +bytes have been read. + + +## `GuzzleHttp\Psr7\Utils::hash` + +`public static function hash(StreamInterface $stream, string $algo, bool $rawOutput = false): string` + +Calculate a hash of a stream. + +This method reads the entire stream to calculate a rolling hash, based on +PHP's `hash_init` functions. + + +## `GuzzleHttp\Psr7\Utils::modifyRequest` + +`public static function modifyRequest(RequestInterface $request, array $changes): RequestInterface` + +Clone and modify a request with the given changes. + +This method is useful for reducing the number of clones needed to mutate +a message. + +- method: (string) Changes the HTTP method. +- set_headers: (array) Sets the given headers. +- remove_headers: (array) Remove the given headers. +- body: (mixed) Sets the given body. +- uri: (UriInterface) Set the URI. +- query: (string) Set the query string value of the URI. +- version: (string) Set the protocol version. + + +## `GuzzleHttp\Psr7\Utils::readLine` + +`public static function readLine(StreamInterface $stream, int $maxLength = null): string` + +Read a line from the stream up to the maximum allowed buffer length. + + +## `GuzzleHttp\Psr7\Utils::streamFor` + +`public static function streamFor(resource|string|null|int|float|bool|StreamInterface|callable|\Iterator $resource = '', array $options = []): StreamInterface` + +Create a new stream based on the input type. + +Options is an associative array that can contain the following keys: + +- metadata: Array of custom metadata. +- size: Size of the stream. + +This method accepts the following `$resource` types: + +- `Psr\Http\Message\StreamInterface`: Returns the value as-is. +- `string`: Creates a stream object that uses the given string as the contents. +- `resource`: Creates a stream object that wraps the given PHP stream resource. +- `Iterator`: If the provided value implements `Iterator`, then a read-only + stream object will be created that wraps the given iterable. Each time the + stream is read from, data from the iterator will fill a buffer and will be + continuously called until the buffer is equal to the requested read size. + Subsequent read calls will first read from the buffer and then call `next` + on the underlying iterator until it is exhausted. +- `object` with `__toString()`: If the object has the `__toString()` method, + the object will be cast to a string and then a stream will be returned that + uses the string value. +- `NULL`: When `null` is passed, an empty stream object is returned. +- `callable` When a callable is passed, a read-only stream object will be + created that invokes the given callable. The callable is invoked with the + number of suggested bytes to read. The callable can return any number of + bytes, but MUST return `false` when there is no more data to return. The + stream object that wraps the callable will invoke the callable until the + number of requested bytes are available. Any additional bytes will be + buffered and used in subsequent reads. + +```php +$stream = GuzzleHttp\Psr7\Utils::streamFor('foo'); +$stream = GuzzleHttp\Psr7\Utils::streamFor(fopen('/path/to/file', 'r')); + +$generator = function ($bytes) { + for ($i = 0; $i < $bytes; $i++) { + yield ' '; + } +} + +$stream = GuzzleHttp\Psr7\Utils::streamFor($generator(100)); +``` + + +## `GuzzleHttp\Psr7\Utils::tryFopen` + +`public static function tryFopen(string $filename, string $mode): resource` + +Safely opens a PHP stream resource using a filename. + +When fopen fails, PHP normally raises a warning. This function adds an +error handler that checks for errors and throws an exception instead. + + +## `GuzzleHttp\Psr7\Utils::tryGetContents` + +`public static function tryGetContents(resource $stream): string` + +Safely gets the contents of a given stream. + +When stream_get_contents fails, PHP normally raises a warning. This +function adds an error handler that checks for errors and throws an +exception instead. + + +## `GuzzleHttp\Psr7\Utils::uriFor` + +`public static function uriFor(string|UriInterface $uri): UriInterface` + +Returns a UriInterface for the given value. + +This function accepts a string or UriInterface and returns a +UriInterface for the given value. If the value is already a +UriInterface, it is returned as-is. + + +## `GuzzleHttp\Psr7\MimeType::fromFilename` + +`public static function fromFilename(string $filename): string|null` + +Determines the mimetype of a file by looking at its extension. + + +## `GuzzleHttp\Psr7\MimeType::fromExtension` + +`public static function fromExtension(string $extension): string|null` + +Maps a file extensions to a mimetype. + + +## Upgrading from Function API + +The static API was first introduced in 1.7.0, in order to mitigate problems with functions conflicting between global and local copies of the package. The function API was removed in 2.0.0. A migration table has been provided here for your convenience: + +| Original Function | Replacement Method | +|----------------|----------------| +| `str` | `Message::toString` | +| `uri_for` | `Utils::uriFor` | +| `stream_for` | `Utils::streamFor` | +| `parse_header` | `Header::parse` | +| `normalize_header` | `Header::normalize` | +| `modify_request` | `Utils::modifyRequest` | +| `rewind_body` | `Message::rewindBody` | +| `try_fopen` | `Utils::tryFopen` | +| `copy_to_string` | `Utils::copyToString` | +| `copy_to_stream` | `Utils::copyToStream` | +| `hash` | `Utils::hash` | +| `readline` | `Utils::readLine` | +| `parse_request` | `Message::parseRequest` | +| `parse_response` | `Message::parseResponse` | +| `parse_query` | `Query::parse` | +| `build_query` | `Query::build` | +| `mimetype_from_filename` | `MimeType::fromFilename` | +| `mimetype_from_extension` | `MimeType::fromExtension` | +| `_parse_message` | `Message::parseMessage` | +| `_parse_request_uri` | `Message::parseRequestUri` | +| `get_message_body_summary` | `Message::bodySummary` | +| `_caseless_remove` | `Utils::caselessRemove` | + + +# Additional URI Methods + +Aside from the standard `Psr\Http\Message\UriInterface` implementation in form of the `GuzzleHttp\Psr7\Uri` class, +this library also provides additional functionality when working with URIs as static methods. + +## URI Types + +An instance of `Psr\Http\Message\UriInterface` can either be an absolute URI or a relative reference. +An absolute URI has a scheme. A relative reference is used to express a URI relative to another URI, +the base URI. Relative references can be divided into several forms according to +[RFC 3986 Section 4.2](https://tools.ietf.org/html/rfc3986#section-4.2): + +- network-path references, e.g. `//example.com/path` +- absolute-path references, e.g. `/path` +- relative-path references, e.g. `subpath` + +The following methods can be used to identify the type of the URI. + +### `GuzzleHttp\Psr7\Uri::isAbsolute` + +`public static function isAbsolute(UriInterface $uri): bool` + +Whether the URI is absolute, i.e. it has a scheme. + +### `GuzzleHttp\Psr7\Uri::isNetworkPathReference` + +`public static function isNetworkPathReference(UriInterface $uri): bool` + +Whether the URI is a network-path reference. A relative reference that begins with two slash characters is +termed an network-path reference. + +### `GuzzleHttp\Psr7\Uri::isAbsolutePathReference` + +`public static function isAbsolutePathReference(UriInterface $uri): bool` + +Whether the URI is a absolute-path reference. A relative reference that begins with a single slash character is +termed an absolute-path reference. + +### `GuzzleHttp\Psr7\Uri::isRelativePathReference` + +`public static function isRelativePathReference(UriInterface $uri): bool` + +Whether the URI is a relative-path reference. A relative reference that does not begin with a slash character is +termed a relative-path reference. + +### `GuzzleHttp\Psr7\Uri::isSameDocumentReference` + +`public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null): bool` + +Whether the URI is a same-document reference. A same-document reference refers to a URI that is, aside from its +fragment component, identical to the base URI. When no base URI is given, only an empty URI reference +(apart from its fragment) is considered a same-document reference. + +## URI Components + +Additional methods to work with URI components. + +### `GuzzleHttp\Psr7\Uri::isDefaultPort` + +`public static function isDefaultPort(UriInterface $uri): bool` + +Whether the URI has the default port of the current scheme. `Psr\Http\Message\UriInterface::getPort` may return null +or the standard port. This method can be used independently of the implementation. + +### `GuzzleHttp\Psr7\Uri::composeComponents` + +`public static function composeComponents($scheme, $authority, $path, $query, $fragment): string` + +Composes a URI reference string from its various components according to +[RFC 3986 Section 5.3](https://tools.ietf.org/html/rfc3986#section-5.3). Usually this method does not need to be called +manually but instead is used indirectly via `Psr\Http\Message\UriInterface::__toString`. + +### `GuzzleHttp\Psr7\Uri::fromParts` + +`public static function fromParts(array $parts): UriInterface` + +Creates a URI from a hash of [`parse_url`](https://www.php.net/manual/en/function.parse-url.php) components. + + +### `GuzzleHttp\Psr7\Uri::withQueryValue` + +`public static function withQueryValue(UriInterface $uri, $key, $value): UriInterface` + +Creates a new URI with a specific query string value. Any existing query string values that exactly match the +provided key are removed and replaced with the given key value pair. A value of null will set the query string +key without a value, e.g. "key" instead of "key=value". + +### `GuzzleHttp\Psr7\Uri::withQueryValues` + +`public static function withQueryValues(UriInterface $uri, array $keyValueArray): UriInterface` + +Creates a new URI with multiple query string values. It has the same behavior as `withQueryValue()` but for an +associative array of key => value. + +### `GuzzleHttp\Psr7\Uri::withoutQueryValue` + +`public static function withoutQueryValue(UriInterface $uri, $key): UriInterface` + +Creates a new URI with a specific query string value removed. Any existing query string values that exactly match the +provided key are removed. + +## Cross-Origin Detection + +`GuzzleHttp\Psr7\UriComparator` provides methods to determine if a modified URL should be considered cross-origin. + +### `GuzzleHttp\Psr7\UriComparator::isCrossOrigin` + +`public static function isCrossOrigin(UriInterface $original, UriInterface $modified): bool` + +Determines if a modified URL should be considered cross-origin with respect to an original URL. + +## Reference Resolution + +`GuzzleHttp\Psr7\UriResolver` provides methods to resolve a URI reference in the context of a base URI according +to [RFC 3986 Section 5](https://tools.ietf.org/html/rfc3986#section-5). This is for example also what web browsers +do when resolving a link in a website based on the current request URI. + +### `GuzzleHttp\Psr7\UriResolver::resolve` + +`public static function resolve(UriInterface $base, UriInterface $rel): UriInterface` + +Converts the relative URI into a new URI that is resolved against the base URI. + +### `GuzzleHttp\Psr7\UriResolver::removeDotSegments` + +`public static function removeDotSegments(string $path): string` + +Removes dot segments from a path and returns the new path according to +[RFC 3986 Section 5.2.4](https://tools.ietf.org/html/rfc3986#section-5.2.4). + +### `GuzzleHttp\Psr7\UriResolver::relativize` + +`public static function relativize(UriInterface $base, UriInterface $target): UriInterface` + +Returns the target URI as a relative reference from the base URI. This method is the counterpart to resolve(): + +```php +(string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target)) +``` + +One use-case is to use the current request URI as base URI and then generate relative links in your documents +to reduce the document size or offer self-contained downloadable document archives. + +```php +$base = new Uri('http://example.com/a/b/'); +echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c')); // prints 'c'. +echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y')); // prints '../x/y'. +echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'. +echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // prints '//example.org/a/b/'. +``` + +## Normalization and Comparison + +`GuzzleHttp\Psr7\UriNormalizer` provides methods to normalize and compare URIs according to +[RFC 3986 Section 6](https://tools.ietf.org/html/rfc3986#section-6). + +### `GuzzleHttp\Psr7\UriNormalizer::normalize` + +`public static function normalize(UriInterface $uri, $flags = self::PRESERVING_NORMALIZATIONS): UriInterface` + +Returns a normalized URI. The scheme and host component are already normalized to lowercase per PSR-7 UriInterface. +This methods adds additional normalizations that can be configured with the `$flags` parameter which is a bitmask +of normalizations to apply. The following normalizations are available: + +- `UriNormalizer::PRESERVING_NORMALIZATIONS` + + Default normalizations which only include the ones that preserve semantics. + +- `UriNormalizer::CAPITALIZE_PERCENT_ENCODING` + + All letters within a percent-encoding triplet (e.g., "%3A") are case-insensitive, and should be capitalized. + + Example: `http://example.org/a%c2%b1b` → `http://example.org/a%C2%B1b` + +- `UriNormalizer::DECODE_UNRESERVED_CHARACTERS` + + Decodes percent-encoded octets of unreserved characters. For consistency, percent-encoded octets in the ranges of + ALPHA (%41–%5A and %61–%7A), DIGIT (%30–%39), hyphen (%2D), period (%2E), underscore (%5F), or tilde (%7E) should + not be created by URI producers and, when found in a URI, should be decoded to their corresponding unreserved + characters by URI normalizers. + + Example: `http://example.org/%7Eusern%61me/` → `http://example.org/~username/` + +- `UriNormalizer::CONVERT_EMPTY_PATH` + + Converts the empty path to "/" for http and https URIs. + + Example: `http://example.org` → `http://example.org/` + +- `UriNormalizer::REMOVE_DEFAULT_HOST` + + Removes the default host of the given URI scheme from the URI. Only the "file" scheme defines the default host + "localhost". All of `file:/myfile`, `file:///myfile`, and `file://localhost/myfile` are equivalent according to + RFC 3986. + + Example: `file://localhost/myfile` → `file:///myfile` + +- `UriNormalizer::REMOVE_DEFAULT_PORT` + + Removes the default port of the given URI scheme from the URI. + + Example: `http://example.org:80/` → `http://example.org/` + +- `UriNormalizer::REMOVE_DOT_SEGMENTS` + + Removes unnecessary dot-segments. Dot-segments in relative-path references are not removed as it would + change the semantics of the URI reference. + + Example: `http://example.org/../a/b/../c/./d.html` → `http://example.org/a/c/d.html` + +- `UriNormalizer::REMOVE_DUPLICATE_SLASHES` + + Paths which include two or more adjacent slashes are converted to one. Webservers usually ignore duplicate slashes + and treat those URIs equivalent. But in theory those URIs do not need to be equivalent. So this normalization + may change the semantics. Encoded slashes (%2F) are not removed. + + Example: `http://example.org//foo///bar.html` → `http://example.org/foo/bar.html` + +- `UriNormalizer::SORT_QUERY_PARAMETERS` + + Sort query parameters with their values in alphabetical order. However, the order of parameters in a URI may be + significant (this is not defined by the standard). So this normalization is not safe and may change the semantics + of the URI. + + Example: `?lang=en&article=fred` → `?article=fred&lang=en` + +### `GuzzleHttp\Psr7\UriNormalizer::isEquivalent` + +`public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, $normalizations = self::PRESERVING_NORMALIZATIONS): bool` + +Whether two URIs can be considered equivalent. Both URIs are normalized automatically before comparison with the given +`$normalizations` bitmask. The method also accepts relative URI references and returns true when they are equivalent. +This of course assumes they will be resolved against the same base URI. If this is not the case, determination of +equivalence or difference of relative references does not mean anything. + + +## Version Guidance + +| Version | Status | PHP Version | +|---------|----------------|------------------| +| 1.x | Security fixes | >=5.4,<8.1 | +| 2.x | Latest | ^7.2.5 \|\| ^8.0 | + + +## Security + +If you discover a security vulnerability within this package, please send an email to security@tidelift.com. All security vulnerabilities will be promptly addressed. Please do not disclose security-related issues publicly until a fix has been announced. Please see [Security Policy](https://github.com/guzzle/psr7/security/policy) for more information. + + +## License + +Guzzle is made available under the MIT License (MIT). Please see [License File](LICENSE) for more information. + + +## For Enterprise + +Available as part of the Tidelift Subscription + +The maintainers of Guzzle and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-psr7?utm_source=packagist-guzzlehttp-psr7&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/composer.json b/data/web/inc/lib/vendor/guzzlehttp/psr7/composer.json new file mode 100644 index 000000000..c0e7236c3 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/composer.json @@ -0,0 +1,93 @@ +{ + "name": "guzzlehttp/psr7", + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": [ + "request", + "response", + "message", + "stream", + "http", + "uri", + "url", + "psr-7" + ], + "license": "MIT", + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://sagikazarmark.hu" + } + ], + "require": { + "php": "^7.2.5 || ^8.0", + "psr/http-factory": "^1.0", + "psr/http-message": "^1.0", + "ralouphie/getallheaders": "^3.0" + }, + "provide": { + "psr/http-factory-implementation": "1.0", + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.1", + "http-interop/http-factory-tests": "^0.9", + "phpunit/phpunit": "^8.5.29 || ^9.5.23" + }, + "suggest": { + "laminas/laminas-httphandlerrunner": "Emit PSR-7 responses" + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "GuzzleHttp\\Tests\\Psr7\\": "tests/" + } + }, + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "config": { + "allow-plugins": { + "bamarni/composer-bin-plugin": true + }, + "preferred-install": "dist", + "sort-packages": true + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/AppendStream.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/AppendStream.php new file mode 100644 index 000000000..cbcfaee65 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/AppendStream.php @@ -0,0 +1,248 @@ +addStream($stream); + } + } + + public function __toString(): string + { + try { + $this->rewind(); + return $this->getContents(); + } catch (\Throwable $e) { + if (\PHP_VERSION_ID >= 70400) { + throw $e; + } + trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR); + return ''; + } + } + + /** + * Add a stream to the AppendStream + * + * @param StreamInterface $stream Stream to append. Must be readable. + * + * @throws \InvalidArgumentException if the stream is not readable + */ + public function addStream(StreamInterface $stream): void + { + if (!$stream->isReadable()) { + throw new \InvalidArgumentException('Each stream must be readable'); + } + + // The stream is only seekable if all streams are seekable + if (!$stream->isSeekable()) { + $this->seekable = false; + } + + $this->streams[] = $stream; + } + + public function getContents(): string + { + return Utils::copyToString($this); + } + + /** + * Closes each attached stream. + */ + public function close(): void + { + $this->pos = $this->current = 0; + $this->seekable = true; + + foreach ($this->streams as $stream) { + $stream->close(); + } + + $this->streams = []; + } + + /** + * Detaches each attached stream. + * + * Returns null as it's not clear which underlying stream resource to return. + */ + public function detach() + { + $this->pos = $this->current = 0; + $this->seekable = true; + + foreach ($this->streams as $stream) { + $stream->detach(); + } + + $this->streams = []; + + return null; + } + + public function tell(): int + { + return $this->pos; + } + + /** + * Tries to calculate the size by adding the size of each stream. + * + * If any of the streams do not return a valid number, then the size of the + * append stream cannot be determined and null is returned. + */ + public function getSize(): ?int + { + $size = 0; + + foreach ($this->streams as $stream) { + $s = $stream->getSize(); + if ($s === null) { + return null; + } + $size += $s; + } + + return $size; + } + + public function eof(): bool + { + return !$this->streams || + ($this->current >= count($this->streams) - 1 && + $this->streams[$this->current]->eof()); + } + + public function rewind(): void + { + $this->seek(0); + } + + /** + * Attempts to seek to the given position. Only supports SEEK_SET. + */ + public function seek($offset, $whence = SEEK_SET): void + { + if (!$this->seekable) { + throw new \RuntimeException('This AppendStream is not seekable'); + } elseif ($whence !== SEEK_SET) { + throw new \RuntimeException('The AppendStream can only seek with SEEK_SET'); + } + + $this->pos = $this->current = 0; + + // Rewind each stream + foreach ($this->streams as $i => $stream) { + try { + $stream->rewind(); + } catch (\Exception $e) { + throw new \RuntimeException('Unable to seek stream ' + . $i . ' of the AppendStream', 0, $e); + } + } + + // Seek to the actual position by reading from each stream + while ($this->pos < $offset && !$this->eof()) { + $result = $this->read(min(8096, $offset - $this->pos)); + if ($result === '') { + break; + } + } + } + + /** + * Reads from all of the appended streams until the length is met or EOF. + */ + public function read($length): string + { + $buffer = ''; + $total = count($this->streams) - 1; + $remaining = $length; + $progressToNext = false; + + while ($remaining > 0) { + // Progress to the next stream if needed. + if ($progressToNext || $this->streams[$this->current]->eof()) { + $progressToNext = false; + if ($this->current === $total) { + break; + } + $this->current++; + } + + $result = $this->streams[$this->current]->read($remaining); + + if ($result === '') { + $progressToNext = true; + continue; + } + + $buffer .= $result; + $remaining = $length - strlen($buffer); + } + + $this->pos += strlen($buffer); + + return $buffer; + } + + public function isReadable(): bool + { + return true; + } + + public function isWritable(): bool + { + return false; + } + + public function isSeekable(): bool + { + return $this->seekable; + } + + public function write($string): int + { + throw new \RuntimeException('Cannot write to an AppendStream'); + } + + /** + * {@inheritdoc} + * + * @return mixed + */ + public function getMetadata($key = null) + { + return $key ? null : []; + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/BufferStream.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/BufferStream.php new file mode 100644 index 000000000..21be8c0a9 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/BufferStream.php @@ -0,0 +1,149 @@ +hwm = $hwm; + } + + public function __toString(): string + { + return $this->getContents(); + } + + public function getContents(): string + { + $buffer = $this->buffer; + $this->buffer = ''; + + return $buffer; + } + + public function close(): void + { + $this->buffer = ''; + } + + public function detach() + { + $this->close(); + + return null; + } + + public function getSize(): ?int + { + return strlen($this->buffer); + } + + public function isReadable(): bool + { + return true; + } + + public function isWritable(): bool + { + return true; + } + + public function isSeekable(): bool + { + return false; + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET): void + { + throw new \RuntimeException('Cannot seek a BufferStream'); + } + + public function eof(): bool + { + return strlen($this->buffer) === 0; + } + + public function tell(): int + { + throw new \RuntimeException('Cannot determine the position of a BufferStream'); + } + + /** + * Reads data from the buffer. + */ + public function read($length): string + { + $currentLength = strlen($this->buffer); + + if ($length >= $currentLength) { + // No need to slice the buffer because we don't have enough data. + $result = $this->buffer; + $this->buffer = ''; + } else { + // Slice up the result to provide a subset of the buffer. + $result = substr($this->buffer, 0, $length); + $this->buffer = substr($this->buffer, $length); + } + + return $result; + } + + /** + * Writes data to the buffer. + */ + public function write($string): int + { + $this->buffer .= $string; + + if (strlen($this->buffer) >= $this->hwm) { + return 0; + } + + return strlen($string); + } + + /** + * {@inheritdoc} + * + * @return mixed + */ + public function getMetadata($key = null) + { + if ($key === 'hwm') { + return $this->hwm; + } + + return $key ? null : []; + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/CachingStream.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/CachingStream.php new file mode 100644 index 000000000..f34722cff --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/CachingStream.php @@ -0,0 +1,153 @@ +remoteStream = $stream; + $this->stream = $target ?: new Stream(Utils::tryFopen('php://temp', 'r+')); + } + + public function getSize(): ?int + { + $remoteSize = $this->remoteStream->getSize(); + + if (null === $remoteSize) { + return null; + } + + return max($this->stream->getSize(), $remoteSize); + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET): void + { + if ($whence === SEEK_SET) { + $byte = $offset; + } elseif ($whence === SEEK_CUR) { + $byte = $offset + $this->tell(); + } elseif ($whence === SEEK_END) { + $size = $this->remoteStream->getSize(); + if ($size === null) { + $size = $this->cacheEntireStream(); + } + $byte = $size + $offset; + } else { + throw new \InvalidArgumentException('Invalid whence'); + } + + $diff = $byte - $this->stream->getSize(); + + if ($diff > 0) { + // Read the remoteStream until we have read in at least the amount + // of bytes requested, or we reach the end of the file. + while ($diff > 0 && !$this->remoteStream->eof()) { + $this->read($diff); + $diff = $byte - $this->stream->getSize(); + } + } else { + // We can just do a normal seek since we've already seen this byte. + $this->stream->seek($byte); + } + } + + public function read($length): string + { + // Perform a regular read on any previously read data from the buffer + $data = $this->stream->read($length); + $remaining = $length - strlen($data); + + // More data was requested so read from the remote stream + if ($remaining) { + // If data was written to the buffer in a position that would have + // been filled from the remote stream, then we must skip bytes on + // the remote stream to emulate overwriting bytes from that + // position. This mimics the behavior of other PHP stream wrappers. + $remoteData = $this->remoteStream->read( + $remaining + $this->skipReadBytes + ); + + if ($this->skipReadBytes) { + $len = strlen($remoteData); + $remoteData = substr($remoteData, $this->skipReadBytes); + $this->skipReadBytes = max(0, $this->skipReadBytes - $len); + } + + $data .= $remoteData; + $this->stream->write($remoteData); + } + + return $data; + } + + public function write($string): int + { + // When appending to the end of the currently read stream, you'll want + // to skip bytes from being read from the remote stream to emulate + // other stream wrappers. Basically replacing bytes of data of a fixed + // length. + $overflow = (strlen($string) + $this->tell()) - $this->remoteStream->tell(); + if ($overflow > 0) { + $this->skipReadBytes += $overflow; + } + + return $this->stream->write($string); + } + + public function eof(): bool + { + return $this->stream->eof() && $this->remoteStream->eof(); + } + + /** + * Close both the remote stream and buffer stream + */ + public function close(): void + { + $this->remoteStream->close(); + $this->stream->close(); + } + + private function cacheEntireStream(): int + { + $target = new FnStream(['write' => 'strlen']); + Utils::copyToStream($this, $target); + + return $this->tell(); + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/DroppingStream.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/DroppingStream.php new file mode 100644 index 000000000..6e3d209d0 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/DroppingStream.php @@ -0,0 +1,49 @@ +stream = $stream; + $this->maxLength = $maxLength; + } + + public function write($string): int + { + $diff = $this->maxLength - $this->stream->getSize(); + + // Begin returning 0 when the underlying stream is too large. + if ($diff <= 0) { + return 0; + } + + // Write the stream or a subset of the stream if needed. + if (strlen($string) < $diff) { + return $this->stream->write($string); + } + + return $this->stream->write(substr($string, 0, $diff)); + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Exception/MalformedUriException.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Exception/MalformedUriException.php new file mode 100644 index 000000000..3a084779a --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Exception/MalformedUriException.php @@ -0,0 +1,14 @@ + */ + private $methods; + + /** + * @param array $methods Hash of method name to a callable. + */ + public function __construct(array $methods) + { + $this->methods = $methods; + + // Create the functions on the class + foreach ($methods as $name => $fn) { + $this->{'_fn_' . $name} = $fn; + } + } + + /** + * Lazily determine which methods are not implemented. + * + * @throws \BadMethodCallException + */ + public function __get(string $name): void + { + throw new \BadMethodCallException(str_replace('_fn_', '', $name) + . '() is not implemented in the FnStream'); + } + + /** + * The close method is called on the underlying stream only if possible. + */ + public function __destruct() + { + if (isset($this->_fn_close)) { + call_user_func($this->_fn_close); + } + } + + /** + * An unserialize would allow the __destruct to run when the unserialized value goes out of scope. + * + * @throws \LogicException + */ + public function __wakeup(): void + { + throw new \LogicException('FnStream should never be unserialized'); + } + + /** + * Adds custom functionality to an underlying stream by intercepting + * specific method calls. + * + * @param StreamInterface $stream Stream to decorate + * @param array $methods Hash of method name to a closure + * + * @return FnStream + */ + public static function decorate(StreamInterface $stream, array $methods) + { + // If any of the required methods were not provided, then simply + // proxy to the decorated stream. + foreach (array_diff(self::SLOTS, array_keys($methods)) as $diff) { + /** @var callable $callable */ + $callable = [$stream, $diff]; + $methods[$diff] = $callable; + } + + return new self($methods); + } + + public function __toString(): string + { + try { + return call_user_func($this->_fn___toString); + } catch (\Throwable $e) { + if (\PHP_VERSION_ID >= 70400) { + throw $e; + } + trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR); + return ''; + } + } + + public function close(): void + { + call_user_func($this->_fn_close); + } + + public function detach() + { + return call_user_func($this->_fn_detach); + } + + public function getSize(): ?int + { + return call_user_func($this->_fn_getSize); + } + + public function tell(): int + { + return call_user_func($this->_fn_tell); + } + + public function eof(): bool + { + return call_user_func($this->_fn_eof); + } + + public function isSeekable(): bool + { + return call_user_func($this->_fn_isSeekable); + } + + public function rewind(): void + { + call_user_func($this->_fn_rewind); + } + + public function seek($offset, $whence = SEEK_SET): void + { + call_user_func($this->_fn_seek, $offset, $whence); + } + + public function isWritable(): bool + { + return call_user_func($this->_fn_isWritable); + } + + public function write($string): int + { + return call_user_func($this->_fn_write, $string); + } + + public function isReadable(): bool + { + return call_user_func($this->_fn_isReadable); + } + + public function read($length): string + { + return call_user_func($this->_fn_read, $length); + } + + public function getContents(): string + { + return call_user_func($this->_fn_getContents); + } + + /** + * {@inheritdoc} + * + * @return mixed + */ + public function getMetadata($key = null) + { + return call_user_func($this->_fn_getMetadata, $key); + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Header.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Header.php new file mode 100644 index 000000000..4d7005b22 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Header.php @@ -0,0 +1,134 @@ +]+>|[^=]+/', $kvp, $matches)) { + $m = $matches[0]; + if (isset($m[1])) { + $part[trim($m[0], $trimmed)] = trim($m[1], $trimmed); + } else { + $part[] = trim($m[0], $trimmed); + } + } + } + if ($part) { + $params[] = $part; + } + } + } + + return $params; + } + + /** + * Converts an array of header values that may contain comma separated + * headers into an array of headers with no comma separated values. + * + * @param string|array $header Header to normalize. + * + * @deprecated Use self::splitList() instead. + */ + public static function normalize($header): array + { + $result = []; + foreach ((array) $header as $value) { + foreach (self::splitList($value) as $parsed) { + $result[] = $parsed; + } + } + + return $result; + } + + /** + * Splits a HTTP header defined to contain a comma-separated list into + * each individual value. Empty values will be removed. + * + * Example headers include 'accept', 'cache-control' and 'if-none-match'. + * + * This method must not be used to parse headers that are not defined as + * a list, such as 'user-agent' or 'set-cookie'. + * + * @param string|string[] $values Header value as returned by MessageInterface::getHeader() + * + * @return string[] + */ + public static function splitList($values): array + { + if (!\is_array($values)) { + $values = [$values]; + } + + $result = []; + foreach ($values as $value) { + if (!\is_string($value)) { + throw new \TypeError('$header must either be a string or an array containing strings.'); + } + + $v = ''; + $isQuoted = false; + $isEscaped = false; + for ($i = 0, $max = \strlen($value); $i < $max; $i++) { + if ($isEscaped) { + $v .= $value[$i]; + $isEscaped = false; + + continue; + } + + if (!$isQuoted && $value[$i] === ',') { + $v = \trim($v); + if ($v !== '') { + $result[] = $v; + } + + $v = ''; + continue; + } + + if ($isQuoted && $value[$i] === '\\') { + $isEscaped = true; + $v .= $value[$i]; + + continue; + } + if ($value[$i] === '"') { + $isQuoted = !$isQuoted; + $v .= $value[$i]; + + continue; + } + + $v .= $value[$i]; + } + + $v = \trim($v); + if ($v !== '') { + $result[] = $v; + } + } + + return $result; + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/HttpFactory.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/HttpFactory.php new file mode 100644 index 000000000..30be222fc --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/HttpFactory.php @@ -0,0 +1,100 @@ +getSize(); + } + + return new UploadedFile($stream, $size, $error, $clientFilename, $clientMediaType); + } + + public function createStream(string $content = ''): StreamInterface + { + return Utils::streamFor($content); + } + + public function createStreamFromFile(string $file, string $mode = 'r'): StreamInterface + { + try { + $resource = Utils::tryFopen($file, $mode); + } catch (\RuntimeException $e) { + if ('' === $mode || false === \in_array($mode[0], ['r', 'w', 'a', 'x', 'c'], true)) { + throw new \InvalidArgumentException(sprintf('Invalid file opening mode "%s"', $mode), 0, $e); + } + + throw $e; + } + + return Utils::streamFor($resource); + } + + public function createStreamFromResource($resource): StreamInterface + { + return Utils::streamFor($resource); + } + + public function createServerRequest(string $method, $uri, array $serverParams = []): ServerRequestInterface + { + if (empty($method)) { + if (!empty($serverParams['REQUEST_METHOD'])) { + $method = $serverParams['REQUEST_METHOD']; + } else { + throw new \InvalidArgumentException('Cannot determine HTTP method'); + } + } + + return new ServerRequest($method, $uri, [], null, '1.1', $serverParams); + } + + public function createResponse(int $code = 200, string $reasonPhrase = ''): ResponseInterface + { + return new Response($code, [], null, '1.1', $reasonPhrase); + } + + public function createRequest(string $method, $uri): RequestInterface + { + return new Request($method, $uri); + } + + public function createUri(string $uri = ''): UriInterface + { + return new Uri($uri); + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/InflateStream.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/InflateStream.php new file mode 100644 index 000000000..8e00f1c32 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/InflateStream.php @@ -0,0 +1,37 @@ + 15 + 32]); + $this->stream = $stream->isSeekable() ? new Stream($resource) : new NoSeekStream(new Stream($resource)); + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/LazyOpenStream.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/LazyOpenStream.php new file mode 100644 index 000000000..f6c84904e --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/LazyOpenStream.php @@ -0,0 +1,49 @@ +filename = $filename; + $this->mode = $mode; + + // unsetting the property forces the first access to go through + // __get(). + unset($this->stream); + } + + /** + * Creates the underlying stream lazily when required. + */ + protected function createStream(): StreamInterface + { + return Utils::streamFor(Utils::tryFopen($this->filename, $this->mode)); + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/LimitStream.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/LimitStream.php new file mode 100644 index 000000000..fb2232557 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/LimitStream.php @@ -0,0 +1,157 @@ +stream = $stream; + $this->setLimit($limit); + $this->setOffset($offset); + } + + public function eof(): bool + { + // Always return true if the underlying stream is EOF + if ($this->stream->eof()) { + return true; + } + + // No limit and the underlying stream is not at EOF + if ($this->limit === -1) { + return false; + } + + return $this->stream->tell() >= $this->offset + $this->limit; + } + + /** + * Returns the size of the limited subset of data + */ + public function getSize(): ?int + { + if (null === ($length = $this->stream->getSize())) { + return null; + } elseif ($this->limit === -1) { + return $length - $this->offset; + } else { + return min($this->limit, $length - $this->offset); + } + } + + /** + * Allow for a bounded seek on the read limited stream + */ + public function seek($offset, $whence = SEEK_SET): void + { + if ($whence !== SEEK_SET || $offset < 0) { + throw new \RuntimeException(sprintf( + 'Cannot seek to offset %s with whence %s', + $offset, + $whence + )); + } + + $offset += $this->offset; + + if ($this->limit !== -1) { + if ($offset > $this->offset + $this->limit) { + $offset = $this->offset + $this->limit; + } + } + + $this->stream->seek($offset); + } + + /** + * Give a relative tell() + */ + public function tell(): int + { + return $this->stream->tell() - $this->offset; + } + + /** + * Set the offset to start limiting from + * + * @param int $offset Offset to seek to and begin byte limiting from + * + * @throws \RuntimeException if the stream cannot be seeked. + */ + public function setOffset(int $offset): void + { + $current = $this->stream->tell(); + + if ($current !== $offset) { + // If the stream cannot seek to the offset position, then read to it + if ($this->stream->isSeekable()) { + $this->stream->seek($offset); + } elseif ($current > $offset) { + throw new \RuntimeException("Could not seek to stream offset $offset"); + } else { + $this->stream->read($offset - $current); + } + } + + $this->offset = $offset; + } + + /** + * Set the limit of bytes that the decorator allows to be read from the + * stream. + * + * @param int $limit Number of bytes to allow to be read from the stream. + * Use -1 for no limit. + */ + public function setLimit(int $limit): void + { + $this->limit = $limit; + } + + public function read($length): string + { + if ($this->limit === -1) { + return $this->stream->read($length); + } + + // Check if the current position is less than the total allowed + // bytes + original offset + $remaining = ($this->offset + $this->limit) - $this->stream->tell(); + if ($remaining > 0) { + // Only return the amount of requested data, ensuring that the byte + // limit is not exceeded + return $this->stream->read(min($remaining, $length)); + } + + return ''; + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Message.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Message.php new file mode 100644 index 000000000..c1e15f826 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Message.php @@ -0,0 +1,246 @@ +getMethod() . ' ' + . $message->getRequestTarget()) + . ' HTTP/' . $message->getProtocolVersion(); + if (!$message->hasHeader('host')) { + $msg .= "\r\nHost: " . $message->getUri()->getHost(); + } + } elseif ($message instanceof ResponseInterface) { + $msg = 'HTTP/' . $message->getProtocolVersion() . ' ' + . $message->getStatusCode() . ' ' + . $message->getReasonPhrase(); + } else { + throw new \InvalidArgumentException('Unknown message type'); + } + + foreach ($message->getHeaders() as $name => $values) { + if (strtolower($name) === 'set-cookie') { + foreach ($values as $value) { + $msg .= "\r\n{$name}: " . $value; + } + } else { + $msg .= "\r\n{$name}: " . implode(', ', $values); + } + } + + return "{$msg}\r\n\r\n" . $message->getBody(); + } + + /** + * Get a short summary of the message body. + * + * Will return `null` if the response is not printable. + * + * @param MessageInterface $message The message to get the body summary + * @param int $truncateAt The maximum allowed size of the summary + */ + public static function bodySummary(MessageInterface $message, int $truncateAt = 120): ?string + { + $body = $message->getBody(); + + if (!$body->isSeekable() || !$body->isReadable()) { + return null; + } + + $size = $body->getSize(); + + if ($size === 0) { + return null; + } + + $body->rewind(); + $summary = $body->read($truncateAt); + $body->rewind(); + + if ($size > $truncateAt) { + $summary .= ' (truncated...)'; + } + + // Matches any printable character, including unicode characters: + // letters, marks, numbers, punctuation, spacing, and separators. + if (preg_match('/[^\pL\pM\pN\pP\pS\pZ\n\r\t]/u', $summary) !== 0) { + return null; + } + + return $summary; + } + + /** + * Attempts to rewind a message body and throws an exception on failure. + * + * The body of the message will only be rewound if a call to `tell()` + * returns a value other than `0`. + * + * @param MessageInterface $message Message to rewind + * + * @throws \RuntimeException + */ + public static function rewindBody(MessageInterface $message): void + { + $body = $message->getBody(); + + if ($body->tell()) { + $body->rewind(); + } + } + + /** + * Parses an HTTP message into an associative array. + * + * The array contains the "start-line" key containing the start line of + * the message, "headers" key containing an associative array of header + * array values, and a "body" key containing the body of the message. + * + * @param string $message HTTP request or response to parse. + */ + public static function parseMessage(string $message): array + { + if (!$message) { + throw new \InvalidArgumentException('Invalid message'); + } + + $message = ltrim($message, "\r\n"); + + $messageParts = preg_split("/\r?\n\r?\n/", $message, 2); + + if ($messageParts === false || count($messageParts) !== 2) { + throw new \InvalidArgumentException('Invalid message: Missing header delimiter'); + } + + [$rawHeaders, $body] = $messageParts; + $rawHeaders .= "\r\n"; // Put back the delimiter we split previously + $headerParts = preg_split("/\r?\n/", $rawHeaders, 2); + + if ($headerParts === false || count($headerParts) !== 2) { + throw new \InvalidArgumentException('Invalid message: Missing status line'); + } + + [$startLine, $rawHeaders] = $headerParts; + + if (preg_match("/(?:^HTTP\/|^[A-Z]+ \S+ HTTP\/)(\d+(?:\.\d+)?)/i", $startLine, $matches) && $matches[1] === '1.0') { + // Header folding is deprecated for HTTP/1.1, but allowed in HTTP/1.0 + $rawHeaders = preg_replace(Rfc7230::HEADER_FOLD_REGEX, ' ', $rawHeaders); + } + + /** @var array[] $headerLines */ + $count = preg_match_all(Rfc7230::HEADER_REGEX, $rawHeaders, $headerLines, PREG_SET_ORDER); + + // If these aren't the same, then one line didn't match and there's an invalid header. + if ($count !== substr_count($rawHeaders, "\n")) { + // Folding is deprecated, see https://tools.ietf.org/html/rfc7230#section-3.2.4 + if (preg_match(Rfc7230::HEADER_FOLD_REGEX, $rawHeaders)) { + throw new \InvalidArgumentException('Invalid header syntax: Obsolete line folding'); + } + + throw new \InvalidArgumentException('Invalid header syntax'); + } + + $headers = []; + + foreach ($headerLines as $headerLine) { + $headers[$headerLine[1]][] = $headerLine[2]; + } + + return [ + 'start-line' => $startLine, + 'headers' => $headers, + 'body' => $body, + ]; + } + + /** + * Constructs a URI for an HTTP request message. + * + * @param string $path Path from the start-line + * @param array $headers Array of headers (each value an array). + */ + public static function parseRequestUri(string $path, array $headers): string + { + $hostKey = array_filter(array_keys($headers), function ($k) { + // Numeric array keys are converted to int by PHP. + $k = (string) $k; + + return strtolower($k) === 'host'; + }); + + // If no host is found, then a full URI cannot be constructed. + if (!$hostKey) { + return $path; + } + + $host = $headers[reset($hostKey)][0]; + $scheme = substr($host, -4) === ':443' ? 'https' : 'http'; + + return $scheme . '://' . $host . '/' . ltrim($path, '/'); + } + + /** + * Parses a request message string into a request object. + * + * @param string $message Request message string. + */ + public static function parseRequest(string $message): RequestInterface + { + $data = self::parseMessage($message); + $matches = []; + if (!preg_match('/^[\S]+\s+([a-zA-Z]+:\/\/|\/).*/', $data['start-line'], $matches)) { + throw new \InvalidArgumentException('Invalid request string'); + } + $parts = explode(' ', $data['start-line'], 3); + $version = isset($parts[2]) ? explode('/', $parts[2])[1] : '1.1'; + + $request = new Request( + $parts[0], + $matches[1] === '/' ? self::parseRequestUri($parts[1], $data['headers']) : $parts[1], + $data['headers'], + $data['body'], + $version + ); + + return $matches[1] === '/' ? $request : $request->withRequestTarget($parts[1]); + } + + /** + * Parses a response message string into a response object. + * + * @param string $message Response message string. + */ + public static function parseResponse(string $message): ResponseInterface + { + $data = self::parseMessage($message); + // According to https://tools.ietf.org/html/rfc7230#section-3.1.2 the space + // between status-code and reason-phrase is required. But browsers accept + // responses without space and reason as well. + if (!preg_match('/^HTTP\/.* [0-9]{3}( .*|$)/', $data['start-line'])) { + throw new \InvalidArgumentException('Invalid response string: ' . $data['start-line']); + } + $parts = explode(' ', $data['start-line'], 3); + + return new Response( + (int) $parts[1], + $data['headers'], + $data['body'], + explode('/', $parts[0])[1], + $parts[2] ?? null + ); + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/MessageTrait.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/MessageTrait.php new file mode 100644 index 000000000..464bdfaa4 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/MessageTrait.php @@ -0,0 +1,263 @@ + Map of all registered headers, as original name => array of values */ + private $headers = []; + + /** @var array Map of lowercase header name => original name at registration */ + private $headerNames = []; + + /** @var string */ + private $protocol = '1.1'; + + /** @var StreamInterface|null */ + private $stream; + + public function getProtocolVersion(): string + { + return $this->protocol; + } + + public function withProtocolVersion($version): MessageInterface + { + if ($this->protocol === $version) { + return $this; + } + + $new = clone $this; + $new->protocol = $version; + return $new; + } + + public function getHeaders(): array + { + return $this->headers; + } + + public function hasHeader($header): bool + { + return isset($this->headerNames[strtolower($header)]); + } + + public function getHeader($header): array + { + $header = strtolower($header); + + if (!isset($this->headerNames[$header])) { + return []; + } + + $header = $this->headerNames[$header]; + + return $this->headers[$header]; + } + + public function getHeaderLine($header): string + { + return implode(', ', $this->getHeader($header)); + } + + public function withHeader($header, $value): MessageInterface + { + $this->assertHeader($header); + $value = $this->normalizeHeaderValue($value); + $normalized = strtolower($header); + + $new = clone $this; + if (isset($new->headerNames[$normalized])) { + unset($new->headers[$new->headerNames[$normalized]]); + } + $new->headerNames[$normalized] = $header; + $new->headers[$header] = $value; + + return $new; + } + + public function withAddedHeader($header, $value): MessageInterface + { + $this->assertHeader($header); + $value = $this->normalizeHeaderValue($value); + $normalized = strtolower($header); + + $new = clone $this; + if (isset($new->headerNames[$normalized])) { + $header = $this->headerNames[$normalized]; + $new->headers[$header] = array_merge($this->headers[$header], $value); + } else { + $new->headerNames[$normalized] = $header; + $new->headers[$header] = $value; + } + + return $new; + } + + public function withoutHeader($header): MessageInterface + { + $normalized = strtolower($header); + + if (!isset($this->headerNames[$normalized])) { + return $this; + } + + $header = $this->headerNames[$normalized]; + + $new = clone $this; + unset($new->headers[$header], $new->headerNames[$normalized]); + + return $new; + } + + public function getBody(): StreamInterface + { + if (!$this->stream) { + $this->stream = Utils::streamFor(''); + } + + return $this->stream; + } + + public function withBody(StreamInterface $body): MessageInterface + { + if ($body === $this->stream) { + return $this; + } + + $new = clone $this; + $new->stream = $body; + return $new; + } + + /** + * @param array $headers + */ + private function setHeaders(array $headers): void + { + $this->headerNames = $this->headers = []; + foreach ($headers as $header => $value) { + // Numeric array keys are converted to int by PHP. + $header = (string) $header; + + $this->assertHeader($header); + $value = $this->normalizeHeaderValue($value); + $normalized = strtolower($header); + if (isset($this->headerNames[$normalized])) { + $header = $this->headerNames[$normalized]; + $this->headers[$header] = array_merge($this->headers[$header], $value); + } else { + $this->headerNames[$normalized] = $header; + $this->headers[$header] = $value; + } + } + } + + /** + * @param mixed $value + * + * @return string[] + */ + private function normalizeHeaderValue($value): array + { + if (!is_array($value)) { + return $this->trimAndValidateHeaderValues([$value]); + } + + if (count($value) === 0) { + throw new \InvalidArgumentException('Header value can not be an empty array.'); + } + + return $this->trimAndValidateHeaderValues($value); + } + + /** + * Trims whitespace from the header values. + * + * Spaces and tabs ought to be excluded by parsers when extracting the field value from a header field. + * + * header-field = field-name ":" OWS field-value OWS + * OWS = *( SP / HTAB ) + * + * @param mixed[] $values Header values + * + * @return string[] Trimmed header values + * + * @see https://tools.ietf.org/html/rfc7230#section-3.2.4 + */ + private function trimAndValidateHeaderValues(array $values): array + { + return array_map(function ($value) { + if (!is_scalar($value) && null !== $value) { + throw new \InvalidArgumentException(sprintf( + 'Header value must be scalar or null but %s provided.', + is_object($value) ? get_class($value) : gettype($value) + )); + } + + $trimmed = trim((string) $value, " \t"); + $this->assertValue($trimmed); + + return $trimmed; + }, array_values($values)); + } + + /** + * @see https://tools.ietf.org/html/rfc7230#section-3.2 + * + * @param mixed $header + */ + private function assertHeader($header): void + { + if (!is_string($header)) { + throw new \InvalidArgumentException(sprintf( + 'Header name must be a string but %s provided.', + is_object($header) ? get_class($header) : gettype($header) + )); + } + + if (! preg_match('/^[a-zA-Z0-9\'`#$%&*+.^_|~!-]+$/D', $header)) { + throw new \InvalidArgumentException( + sprintf('"%s" is not valid header name.', $header) + ); + } + } + + /** + * @see https://tools.ietf.org/html/rfc7230#section-3.2 + * + * field-value = *( field-content / obs-fold ) + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + * VCHAR = %x21-7E + * obs-text = %x80-FF + * obs-fold = CRLF 1*( SP / HTAB ) + */ + private function assertValue(string $value): void + { + // The regular expression intentionally does not support the obs-fold production, because as + // per RFC 7230#3.2.4: + // + // A sender MUST NOT generate a message that includes + // line folding (i.e., that has any field-value that contains a match to + // the obs-fold rule) unless the message is intended for packaging + // within the message/http media type. + // + // Clients must not send a request with line folding and a server sending folded headers is + // likely very rare. Line folding is a fairly obscure feature of HTTP/1.1 and thus not accepting + // folding is not likely to break any legitimate use case. + if (! preg_match('/^[\x20\x09\x21-\x7E\x80-\xFF]*$/D', $value)) { + throw new \InvalidArgumentException( + sprintf('"%s" is not valid header value.', $value) + ); + } + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/MimeType.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/MimeType.php new file mode 100644 index 000000000..0debbd18c --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/MimeType.php @@ -0,0 +1,1237 @@ + 'application/vnd.1000minds.decision-model+xml', + '3dml' => 'text/vnd.in3d.3dml', + '3ds' => 'image/x-3ds', + '3g2' => 'video/3gpp2', + '3gp' => 'video/3gp', + '3gpp' => 'video/3gpp', + '3mf' => 'model/3mf', + '7z' => 'application/x-7z-compressed', + '7zip' => 'application/x-7z-compressed', + '123' => 'application/vnd.lotus-1-2-3', + 'aab' => 'application/x-authorware-bin', + 'aac' => 'audio/x-acc', + 'aam' => 'application/x-authorware-map', + 'aas' => 'application/x-authorware-seg', + 'abw' => 'application/x-abiword', + 'ac' => 'application/vnd.nokia.n-gage.ac+xml', + 'ac3' => 'audio/ac3', + 'acc' => 'application/vnd.americandynamics.acc', + 'ace' => 'application/x-ace-compressed', + 'acu' => 'application/vnd.acucobol', + 'acutc' => 'application/vnd.acucorp', + 'adp' => 'audio/adpcm', + 'aep' => 'application/vnd.audiograph', + 'afm' => 'application/x-font-type1', + 'afp' => 'application/vnd.ibm.modcap', + 'age' => 'application/vnd.age', + 'ahead' => 'application/vnd.ahead.space', + 'ai' => 'application/pdf', + 'aif' => 'audio/x-aiff', + 'aifc' => 'audio/x-aiff', + 'aiff' => 'audio/x-aiff', + 'air' => 'application/vnd.adobe.air-application-installer-package+zip', + 'ait' => 'application/vnd.dvb.ait', + 'ami' => 'application/vnd.amiga.ami', + 'amr' => 'audio/amr', + 'apk' => 'application/vnd.android.package-archive', + 'apng' => 'image/apng', + 'appcache' => 'text/cache-manifest', + 'application' => 'application/x-ms-application', + 'apr' => 'application/vnd.lotus-approach', + 'arc' => 'application/x-freearc', + 'arj' => 'application/x-arj', + 'asc' => 'application/pgp-signature', + 'asf' => 'video/x-ms-asf', + 'asm' => 'text/x-asm', + 'aso' => 'application/vnd.accpac.simply.aso', + 'asx' => 'video/x-ms-asf', + 'atc' => 'application/vnd.acucorp', + 'atom' => 'application/atom+xml', + 'atomcat' => 'application/atomcat+xml', + 'atomdeleted' => 'application/atomdeleted+xml', + 'atomsvc' => 'application/atomsvc+xml', + 'atx' => 'application/vnd.antix.game-component', + 'au' => 'audio/x-au', + 'avci' => 'image/avci', + 'avcs' => 'image/avcs', + 'avi' => 'video/x-msvideo', + 'avif' => 'image/avif', + 'aw' => 'application/applixware', + 'azf' => 'application/vnd.airzip.filesecure.azf', + 'azs' => 'application/vnd.airzip.filesecure.azs', + 'azv' => 'image/vnd.airzip.accelerator.azv', + 'azw' => 'application/vnd.amazon.ebook', + 'b16' => 'image/vnd.pco.b16', + 'bat' => 'application/x-msdownload', + 'bcpio' => 'application/x-bcpio', + 'bdf' => 'application/x-font-bdf', + 'bdm' => 'application/vnd.syncml.dm+wbxml', + 'bdoc' => 'application/x-bdoc', + 'bed' => 'application/vnd.realvnc.bed', + 'bh2' => 'application/vnd.fujitsu.oasysprs', + 'bin' => 'application/octet-stream', + 'blb' => 'application/x-blorb', + 'blorb' => 'application/x-blorb', + 'bmi' => 'application/vnd.bmi', + 'bmml' => 'application/vnd.balsamiq.bmml+xml', + 'bmp' => 'image/bmp', + 'book' => 'application/vnd.framemaker', + 'box' => 'application/vnd.previewsystems.box', + 'boz' => 'application/x-bzip2', + 'bpk' => 'application/octet-stream', + 'bpmn' => 'application/octet-stream', + 'bsp' => 'model/vnd.valve.source.compiled-map', + 'btif' => 'image/prs.btif', + 'buffer' => 'application/octet-stream', + 'bz' => 'application/x-bzip', + 'bz2' => 'application/x-bzip2', + 'c' => 'text/x-c', + 'c4d' => 'application/vnd.clonk.c4group', + 'c4f' => 'application/vnd.clonk.c4group', + 'c4g' => 'application/vnd.clonk.c4group', + 'c4p' => 'application/vnd.clonk.c4group', + 'c4u' => 'application/vnd.clonk.c4group', + 'c11amc' => 'application/vnd.cluetrust.cartomobile-config', + 'c11amz' => 'application/vnd.cluetrust.cartomobile-config-pkg', + 'cab' => 'application/vnd.ms-cab-compressed', + 'caf' => 'audio/x-caf', + 'cap' => 'application/vnd.tcpdump.pcap', + 'car' => 'application/vnd.curl.car', + 'cat' => 'application/vnd.ms-pki.seccat', + 'cb7' => 'application/x-cbr', + 'cba' => 'application/x-cbr', + 'cbr' => 'application/x-cbr', + 'cbt' => 'application/x-cbr', + 'cbz' => 'application/x-cbr', + 'cc' => 'text/x-c', + 'cco' => 'application/x-cocoa', + 'cct' => 'application/x-director', + 'ccxml' => 'application/ccxml+xml', + 'cdbcmsg' => 'application/vnd.contact.cmsg', + 'cdf' => 'application/x-netcdf', + 'cdfx' => 'application/cdfx+xml', + 'cdkey' => 'application/vnd.mediastation.cdkey', + 'cdmia' => 'application/cdmi-capability', + 'cdmic' => 'application/cdmi-container', + 'cdmid' => 'application/cdmi-domain', + 'cdmio' => 'application/cdmi-object', + 'cdmiq' => 'application/cdmi-queue', + 'cdr' => 'application/cdr', + 'cdx' => 'chemical/x-cdx', + 'cdxml' => 'application/vnd.chemdraw+xml', + 'cdy' => 'application/vnd.cinderella', + 'cer' => 'application/pkix-cert', + 'cfs' => 'application/x-cfs-compressed', + 'cgm' => 'image/cgm', + 'chat' => 'application/x-chat', + 'chm' => 'application/vnd.ms-htmlhelp', + 'chrt' => 'application/vnd.kde.kchart', + 'cif' => 'chemical/x-cif', + 'cii' => 'application/vnd.anser-web-certificate-issue-initiation', + 'cil' => 'application/vnd.ms-artgalry', + 'cjs' => 'application/node', + 'cla' => 'application/vnd.claymore', + 'class' => 'application/octet-stream', + 'clkk' => 'application/vnd.crick.clicker.keyboard', + 'clkp' => 'application/vnd.crick.clicker.palette', + 'clkt' => 'application/vnd.crick.clicker.template', + 'clkw' => 'application/vnd.crick.clicker.wordbank', + 'clkx' => 'application/vnd.crick.clicker', + 'clp' => 'application/x-msclip', + 'cmc' => 'application/vnd.cosmocaller', + 'cmdf' => 'chemical/x-cmdf', + 'cml' => 'chemical/x-cml', + 'cmp' => 'application/vnd.yellowriver-custom-menu', + 'cmx' => 'image/x-cmx', + 'cod' => 'application/vnd.rim.cod', + 'coffee' => 'text/coffeescript', + 'com' => 'application/x-msdownload', + 'conf' => 'text/plain', + 'cpio' => 'application/x-cpio', + 'cpl' => 'application/cpl+xml', + 'cpp' => 'text/x-c', + 'cpt' => 'application/mac-compactpro', + 'crd' => 'application/x-mscardfile', + 'crl' => 'application/pkix-crl', + 'crt' => 'application/x-x509-ca-cert', + 'crx' => 'application/x-chrome-extension', + 'cryptonote' => 'application/vnd.rig.cryptonote', + 'csh' => 'application/x-csh', + 'csl' => 'application/vnd.citationstyles.style+xml', + 'csml' => 'chemical/x-csml', + 'csp' => 'application/vnd.commonspace', + 'csr' => 'application/octet-stream', + 'css' => 'text/css', + 'cst' => 'application/x-director', + 'csv' => 'text/csv', + 'cu' => 'application/cu-seeme', + 'curl' => 'text/vnd.curl', + 'cww' => 'application/prs.cww', + 'cxt' => 'application/x-director', + 'cxx' => 'text/x-c', + 'dae' => 'model/vnd.collada+xml', + 'daf' => 'application/vnd.mobius.daf', + 'dart' => 'application/vnd.dart', + 'dataless' => 'application/vnd.fdsn.seed', + 'davmount' => 'application/davmount+xml', + 'dbf' => 'application/vnd.dbf', + 'dbk' => 'application/docbook+xml', + 'dcr' => 'application/x-director', + 'dcurl' => 'text/vnd.curl.dcurl', + 'dd2' => 'application/vnd.oma.dd2+xml', + 'ddd' => 'application/vnd.fujixerox.ddd', + 'ddf' => 'application/vnd.syncml.dmddf+xml', + 'dds' => 'image/vnd.ms-dds', + 'deb' => 'application/x-debian-package', + 'def' => 'text/plain', + 'deploy' => 'application/octet-stream', + 'der' => 'application/x-x509-ca-cert', + 'dfac' => 'application/vnd.dreamfactory', + 'dgc' => 'application/x-dgc-compressed', + 'dic' => 'text/x-c', + 'dir' => 'application/x-director', + 'dis' => 'application/vnd.mobius.dis', + 'disposition-notification' => 'message/disposition-notification', + 'dist' => 'application/octet-stream', + 'distz' => 'application/octet-stream', + 'djv' => 'image/vnd.djvu', + 'djvu' => 'image/vnd.djvu', + 'dll' => 'application/octet-stream', + 'dmg' => 'application/x-apple-diskimage', + 'dmn' => 'application/octet-stream', + 'dmp' => 'application/vnd.tcpdump.pcap', + 'dms' => 'application/octet-stream', + 'dna' => 'application/vnd.dna', + 'doc' => 'application/msword', + 'docm' => 'application/vnd.ms-word.template.macroEnabled.12', + 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'dot' => 'application/msword', + 'dotm' => 'application/vnd.ms-word.template.macroEnabled.12', + 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', + 'dp' => 'application/vnd.osgi.dp', + 'dpg' => 'application/vnd.dpgraph', + 'dra' => 'audio/vnd.dra', + 'drle' => 'image/dicom-rle', + 'dsc' => 'text/prs.lines.tag', + 'dssc' => 'application/dssc+der', + 'dtb' => 'application/x-dtbook+xml', + 'dtd' => 'application/xml-dtd', + 'dts' => 'audio/vnd.dts', + 'dtshd' => 'audio/vnd.dts.hd', + 'dump' => 'application/octet-stream', + 'dvb' => 'video/vnd.dvb.file', + 'dvi' => 'application/x-dvi', + 'dwd' => 'application/atsc-dwd+xml', + 'dwf' => 'model/vnd.dwf', + 'dwg' => 'image/vnd.dwg', + 'dxf' => 'image/vnd.dxf', + 'dxp' => 'application/vnd.spotfire.dxp', + 'dxr' => 'application/x-director', + 'ear' => 'application/java-archive', + 'ecelp4800' => 'audio/vnd.nuera.ecelp4800', + 'ecelp7470' => 'audio/vnd.nuera.ecelp7470', + 'ecelp9600' => 'audio/vnd.nuera.ecelp9600', + 'ecma' => 'application/ecmascript', + 'edm' => 'application/vnd.novadigm.edm', + 'edx' => 'application/vnd.novadigm.edx', + 'efif' => 'application/vnd.picsel', + 'ei6' => 'application/vnd.pg.osasli', + 'elc' => 'application/octet-stream', + 'emf' => 'image/emf', + 'eml' => 'message/rfc822', + 'emma' => 'application/emma+xml', + 'emotionml' => 'application/emotionml+xml', + 'emz' => 'application/x-msmetafile', + 'eol' => 'audio/vnd.digital-winds', + 'eot' => 'application/vnd.ms-fontobject', + 'eps' => 'application/postscript', + 'epub' => 'application/epub+zip', + 'es' => 'application/ecmascript', + 'es3' => 'application/vnd.eszigno3+xml', + 'esa' => 'application/vnd.osgi.subsystem', + 'esf' => 'application/vnd.epson.esf', + 'et3' => 'application/vnd.eszigno3+xml', + 'etx' => 'text/x-setext', + 'eva' => 'application/x-eva', + 'evy' => 'application/x-envoy', + 'exe' => 'application/octet-stream', + 'exi' => 'application/exi', + 'exp' => 'application/express', + 'exr' => 'image/aces', + 'ext' => 'application/vnd.novadigm.ext', + 'ez' => 'application/andrew-inset', + 'ez2' => 'application/vnd.ezpix-album', + 'ez3' => 'application/vnd.ezpix-package', + 'f' => 'text/x-fortran', + 'f4v' => 'video/mp4', + 'f77' => 'text/x-fortran', + 'f90' => 'text/x-fortran', + 'fbs' => 'image/vnd.fastbidsheet', + 'fcdt' => 'application/vnd.adobe.formscentral.fcdt', + 'fcs' => 'application/vnd.isac.fcs', + 'fdf' => 'application/vnd.fdf', + 'fdt' => 'application/fdt+xml', + 'fe_launch' => 'application/vnd.denovo.fcselayout-link', + 'fg5' => 'application/vnd.fujitsu.oasysgp', + 'fgd' => 'application/x-director', + 'fh' => 'image/x-freehand', + 'fh4' => 'image/x-freehand', + 'fh5' => 'image/x-freehand', + 'fh7' => 'image/x-freehand', + 'fhc' => 'image/x-freehand', + 'fig' => 'application/x-xfig', + 'fits' => 'image/fits', + 'flac' => 'audio/x-flac', + 'fli' => 'video/x-fli', + 'flo' => 'application/vnd.micrografx.flo', + 'flv' => 'video/x-flv', + 'flw' => 'application/vnd.kde.kivio', + 'flx' => 'text/vnd.fmi.flexstor', + 'fly' => 'text/vnd.fly', + 'fm' => 'application/vnd.framemaker', + 'fnc' => 'application/vnd.frogans.fnc', + 'fo' => 'application/vnd.software602.filler.form+xml', + 'for' => 'text/x-fortran', + 'fpx' => 'image/vnd.fpx', + 'frame' => 'application/vnd.framemaker', + 'fsc' => 'application/vnd.fsc.weblaunch', + 'fst' => 'image/vnd.fst', + 'ftc' => 'application/vnd.fluxtime.clip', + 'fti' => 'application/vnd.anser-web-funds-transfer-initiation', + 'fvt' => 'video/vnd.fvt', + 'fxp' => 'application/vnd.adobe.fxp', + 'fxpl' => 'application/vnd.adobe.fxp', + 'fzs' => 'application/vnd.fuzzysheet', + 'g2w' => 'application/vnd.geoplan', + 'g3' => 'image/g3fax', + 'g3w' => 'application/vnd.geospace', + 'gac' => 'application/vnd.groove-account', + 'gam' => 'application/x-tads', + 'gbr' => 'application/rpki-ghostbusters', + 'gca' => 'application/x-gca-compressed', + 'gdl' => 'model/vnd.gdl', + 'gdoc' => 'application/vnd.google-apps.document', + 'ged' => 'text/vnd.familysearch.gedcom', + 'geo' => 'application/vnd.dynageo', + 'geojson' => 'application/geo+json', + 'gex' => 'application/vnd.geometry-explorer', + 'ggb' => 'application/vnd.geogebra.file', + 'ggt' => 'application/vnd.geogebra.tool', + 'ghf' => 'application/vnd.groove-help', + 'gif' => 'image/gif', + 'gim' => 'application/vnd.groove-identity-message', + 'glb' => 'model/gltf-binary', + 'gltf' => 'model/gltf+json', + 'gml' => 'application/gml+xml', + 'gmx' => 'application/vnd.gmx', + 'gnumeric' => 'application/x-gnumeric', + 'gpg' => 'application/gpg-keys', + 'gph' => 'application/vnd.flographit', + 'gpx' => 'application/gpx+xml', + 'gqf' => 'application/vnd.grafeq', + 'gqs' => 'application/vnd.grafeq', + 'gram' => 'application/srgs', + 'gramps' => 'application/x-gramps-xml', + 'gre' => 'application/vnd.geometry-explorer', + 'grv' => 'application/vnd.groove-injector', + 'grxml' => 'application/srgs+xml', + 'gsf' => 'application/x-font-ghostscript', + 'gsheet' => 'application/vnd.google-apps.spreadsheet', + 'gslides' => 'application/vnd.google-apps.presentation', + 'gtar' => 'application/x-gtar', + 'gtm' => 'application/vnd.groove-tool-message', + 'gtw' => 'model/vnd.gtw', + 'gv' => 'text/vnd.graphviz', + 'gxf' => 'application/gxf', + 'gxt' => 'application/vnd.geonext', + 'gz' => 'application/gzip', + 'gzip' => 'application/gzip', + 'h' => 'text/x-c', + 'h261' => 'video/h261', + 'h263' => 'video/h263', + 'h264' => 'video/h264', + 'hal' => 'application/vnd.hal+xml', + 'hbci' => 'application/vnd.hbci', + 'hbs' => 'text/x-handlebars-template', + 'hdd' => 'application/x-virtualbox-hdd', + 'hdf' => 'application/x-hdf', + 'heic' => 'image/heic', + 'heics' => 'image/heic-sequence', + 'heif' => 'image/heif', + 'heifs' => 'image/heif-sequence', + 'hej2' => 'image/hej2k', + 'held' => 'application/atsc-held+xml', + 'hh' => 'text/x-c', + 'hjson' => 'application/hjson', + 'hlp' => 'application/winhlp', + 'hpgl' => 'application/vnd.hp-hpgl', + 'hpid' => 'application/vnd.hp-hpid', + 'hps' => 'application/vnd.hp-hps', + 'hqx' => 'application/mac-binhex40', + 'hsj2' => 'image/hsj2', + 'htc' => 'text/x-component', + 'htke' => 'application/vnd.kenameaapp', + 'htm' => 'text/html', + 'html' => 'text/html', + 'hvd' => 'application/vnd.yamaha.hv-dic', + 'hvp' => 'application/vnd.yamaha.hv-voice', + 'hvs' => 'application/vnd.yamaha.hv-script', + 'i2g' => 'application/vnd.intergeo', + 'icc' => 'application/vnd.iccprofile', + 'ice' => 'x-conference/x-cooltalk', + 'icm' => 'application/vnd.iccprofile', + 'ico' => 'image/x-icon', + 'ics' => 'text/calendar', + 'ief' => 'image/ief', + 'ifb' => 'text/calendar', + 'ifm' => 'application/vnd.shana.informed.formdata', + 'iges' => 'model/iges', + 'igl' => 'application/vnd.igloader', + 'igm' => 'application/vnd.insors.igm', + 'igs' => 'model/iges', + 'igx' => 'application/vnd.micrografx.igx', + 'iif' => 'application/vnd.shana.informed.interchange', + 'img' => 'application/octet-stream', + 'imp' => 'application/vnd.accpac.simply.imp', + 'ims' => 'application/vnd.ms-ims', + 'in' => 'text/plain', + 'ini' => 'text/plain', + 'ink' => 'application/inkml+xml', + 'inkml' => 'application/inkml+xml', + 'install' => 'application/x-install-instructions', + 'iota' => 'application/vnd.astraea-software.iota', + 'ipfix' => 'application/ipfix', + 'ipk' => 'application/vnd.shana.informed.package', + 'irm' => 'application/vnd.ibm.rights-management', + 'irp' => 'application/vnd.irepository.package+xml', + 'iso' => 'application/x-iso9660-image', + 'itp' => 'application/vnd.shana.informed.formtemplate', + 'its' => 'application/its+xml', + 'ivp' => 'application/vnd.immervision-ivp', + 'ivu' => 'application/vnd.immervision-ivu', + 'jad' => 'text/vnd.sun.j2me.app-descriptor', + 'jade' => 'text/jade', + 'jam' => 'application/vnd.jam', + 'jar' => 'application/java-archive', + 'jardiff' => 'application/x-java-archive-diff', + 'java' => 'text/x-java-source', + 'jhc' => 'image/jphc', + 'jisp' => 'application/vnd.jisp', + 'jls' => 'image/jls', + 'jlt' => 'application/vnd.hp-jlyt', + 'jng' => 'image/x-jng', + 'jnlp' => 'application/x-java-jnlp-file', + 'joda' => 'application/vnd.joost.joda-archive', + 'jp2' => 'image/jp2', + 'jpe' => 'image/jpeg', + 'jpeg' => 'image/jpeg', + 'jpf' => 'image/jpx', + 'jpg' => 'image/jpeg', + 'jpg2' => 'image/jp2', + 'jpgm' => 'video/jpm', + 'jpgv' => 'video/jpeg', + 'jph' => 'image/jph', + 'jpm' => 'video/jpm', + 'jpx' => 'image/jpx', + 'js' => 'application/javascript', + 'json' => 'application/json', + 'json5' => 'application/json5', + 'jsonld' => 'application/ld+json', + 'jsonml' => 'application/jsonml+json', + 'jsx' => 'text/jsx', + 'jxr' => 'image/jxr', + 'jxra' => 'image/jxra', + 'jxrs' => 'image/jxrs', + 'jxs' => 'image/jxs', + 'jxsc' => 'image/jxsc', + 'jxsi' => 'image/jxsi', + 'jxss' => 'image/jxss', + 'kar' => 'audio/midi', + 'karbon' => 'application/vnd.kde.karbon', + 'kdb' => 'application/octet-stream', + 'kdbx' => 'application/x-keepass2', + 'key' => 'application/x-iwork-keynote-sffkey', + 'kfo' => 'application/vnd.kde.kformula', + 'kia' => 'application/vnd.kidspiration', + 'kml' => 'application/vnd.google-earth.kml+xml', + 'kmz' => 'application/vnd.google-earth.kmz', + 'kne' => 'application/vnd.kinar', + 'knp' => 'application/vnd.kinar', + 'kon' => 'application/vnd.kde.kontour', + 'kpr' => 'application/vnd.kde.kpresenter', + 'kpt' => 'application/vnd.kde.kpresenter', + 'kpxx' => 'application/vnd.ds-keypoint', + 'ksp' => 'application/vnd.kde.kspread', + 'ktr' => 'application/vnd.kahootz', + 'ktx' => 'image/ktx', + 'ktx2' => 'image/ktx2', + 'ktz' => 'application/vnd.kahootz', + 'kwd' => 'application/vnd.kde.kword', + 'kwt' => 'application/vnd.kde.kword', + 'lasxml' => 'application/vnd.las.las+xml', + 'latex' => 'application/x-latex', + 'lbd' => 'application/vnd.llamagraphics.life-balance.desktop', + 'lbe' => 'application/vnd.llamagraphics.life-balance.exchange+xml', + 'les' => 'application/vnd.hhe.lesson-player', + 'less' => 'text/less', + 'lgr' => 'application/lgr+xml', + 'lha' => 'application/octet-stream', + 'link66' => 'application/vnd.route66.link66+xml', + 'list' => 'text/plain', + 'list3820' => 'application/vnd.ibm.modcap', + 'listafp' => 'application/vnd.ibm.modcap', + 'litcoffee' => 'text/coffeescript', + 'lnk' => 'application/x-ms-shortcut', + 'log' => 'text/plain', + 'lostxml' => 'application/lost+xml', + 'lrf' => 'application/octet-stream', + 'lrm' => 'application/vnd.ms-lrm', + 'ltf' => 'application/vnd.frogans.ltf', + 'lua' => 'text/x-lua', + 'luac' => 'application/x-lua-bytecode', + 'lvp' => 'audio/vnd.lucent.voice', + 'lwp' => 'application/vnd.lotus-wordpro', + 'lzh' => 'application/octet-stream', + 'm1v' => 'video/mpeg', + 'm2a' => 'audio/mpeg', + 'm2v' => 'video/mpeg', + 'm3a' => 'audio/mpeg', + 'm3u' => 'text/plain', + 'm3u8' => 'application/vnd.apple.mpegurl', + 'm4a' => 'audio/x-m4a', + 'm4p' => 'application/mp4', + 'm4s' => 'video/iso.segment', + 'm4u' => 'application/vnd.mpegurl', + 'm4v' => 'video/x-m4v', + 'm13' => 'application/x-msmediaview', + 'm14' => 'application/x-msmediaview', + 'm21' => 'application/mp21', + 'ma' => 'application/mathematica', + 'mads' => 'application/mads+xml', + 'maei' => 'application/mmt-aei+xml', + 'mag' => 'application/vnd.ecowin.chart', + 'maker' => 'application/vnd.framemaker', + 'man' => 'text/troff', + 'manifest' => 'text/cache-manifest', + 'map' => 'application/json', + 'mar' => 'application/octet-stream', + 'markdown' => 'text/markdown', + 'mathml' => 'application/mathml+xml', + 'mb' => 'application/mathematica', + 'mbk' => 'application/vnd.mobius.mbk', + 'mbox' => 'application/mbox', + 'mc1' => 'application/vnd.medcalcdata', + 'mcd' => 'application/vnd.mcd', + 'mcurl' => 'text/vnd.curl.mcurl', + 'md' => 'text/markdown', + 'mdb' => 'application/x-msaccess', + 'mdi' => 'image/vnd.ms-modi', + 'mdx' => 'text/mdx', + 'me' => 'text/troff', + 'mesh' => 'model/mesh', + 'meta4' => 'application/metalink4+xml', + 'metalink' => 'application/metalink+xml', + 'mets' => 'application/mets+xml', + 'mfm' => 'application/vnd.mfmp', + 'mft' => 'application/rpki-manifest', + 'mgp' => 'application/vnd.osgeo.mapguide.package', + 'mgz' => 'application/vnd.proteus.magazine', + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'mie' => 'application/x-mie', + 'mif' => 'application/vnd.mif', + 'mime' => 'message/rfc822', + 'mj2' => 'video/mj2', + 'mjp2' => 'video/mj2', + 'mjs' => 'application/javascript', + 'mk3d' => 'video/x-matroska', + 'mka' => 'audio/x-matroska', + 'mkd' => 'text/x-markdown', + 'mks' => 'video/x-matroska', + 'mkv' => 'video/x-matroska', + 'mlp' => 'application/vnd.dolby.mlp', + 'mmd' => 'application/vnd.chipnuts.karaoke-mmd', + 'mmf' => 'application/vnd.smaf', + 'mml' => 'text/mathml', + 'mmr' => 'image/vnd.fujixerox.edmics-mmr', + 'mng' => 'video/x-mng', + 'mny' => 'application/x-msmoney', + 'mobi' => 'application/x-mobipocket-ebook', + 'mods' => 'application/mods+xml', + 'mov' => 'video/quicktime', + 'movie' => 'video/x-sgi-movie', + 'mp2' => 'audio/mpeg', + 'mp2a' => 'audio/mpeg', + 'mp3' => 'audio/mpeg', + 'mp4' => 'video/mp4', + 'mp4a' => 'audio/mp4', + 'mp4s' => 'application/mp4', + 'mp4v' => 'video/mp4', + 'mp21' => 'application/mp21', + 'mpc' => 'application/vnd.mophun.certificate', + 'mpd' => 'application/dash+xml', + 'mpe' => 'video/mpeg', + 'mpeg' => 'video/mpeg', + 'mpf' => 'application/media-policy-dataset+xml', + 'mpg' => 'video/mpeg', + 'mpg4' => 'video/mp4', + 'mpga' => 'audio/mpeg', + 'mpkg' => 'application/vnd.apple.installer+xml', + 'mpm' => 'application/vnd.blueice.multipass', + 'mpn' => 'application/vnd.mophun.application', + 'mpp' => 'application/vnd.ms-project', + 'mpt' => 'application/vnd.ms-project', + 'mpy' => 'application/vnd.ibm.minipay', + 'mqy' => 'application/vnd.mobius.mqy', + 'mrc' => 'application/marc', + 'mrcx' => 'application/marcxml+xml', + 'ms' => 'text/troff', + 'mscml' => 'application/mediaservercontrol+xml', + 'mseed' => 'application/vnd.fdsn.mseed', + 'mseq' => 'application/vnd.mseq', + 'msf' => 'application/vnd.epson.msf', + 'msg' => 'application/vnd.ms-outlook', + 'msh' => 'model/mesh', + 'msi' => 'application/x-msdownload', + 'msl' => 'application/vnd.mobius.msl', + 'msm' => 'application/octet-stream', + 'msp' => 'application/octet-stream', + 'msty' => 'application/vnd.muvee.style', + 'mtl' => 'model/mtl', + 'mts' => 'model/vnd.mts', + 'mus' => 'application/vnd.musician', + 'musd' => 'application/mmt-usd+xml', + 'musicxml' => 'application/vnd.recordare.musicxml+xml', + 'mvb' => 'application/x-msmediaview', + 'mvt' => 'application/vnd.mapbox-vector-tile', + 'mwf' => 'application/vnd.mfer', + 'mxf' => 'application/mxf', + 'mxl' => 'application/vnd.recordare.musicxml', + 'mxmf' => 'audio/mobile-xmf', + 'mxml' => 'application/xv+xml', + 'mxs' => 'application/vnd.triscape.mxs', + 'mxu' => 'video/vnd.mpegurl', + 'n-gage' => 'application/vnd.nokia.n-gage.symbian.install', + 'n3' => 'text/n3', + 'nb' => 'application/mathematica', + 'nbp' => 'application/vnd.wolfram.player', + 'nc' => 'application/x-netcdf', + 'ncx' => 'application/x-dtbncx+xml', + 'nfo' => 'text/x-nfo', + 'ngdat' => 'application/vnd.nokia.n-gage.data', + 'nitf' => 'application/vnd.nitf', + 'nlu' => 'application/vnd.neurolanguage.nlu', + 'nml' => 'application/vnd.enliven', + 'nnd' => 'application/vnd.noblenet-directory', + 'nns' => 'application/vnd.noblenet-sealer', + 'nnw' => 'application/vnd.noblenet-web', + 'npx' => 'image/vnd.net-fpx', + 'nq' => 'application/n-quads', + 'nsc' => 'application/x-conference', + 'nsf' => 'application/vnd.lotus-notes', + 'nt' => 'application/n-triples', + 'ntf' => 'application/vnd.nitf', + 'numbers' => 'application/x-iwork-numbers-sffnumbers', + 'nzb' => 'application/x-nzb', + 'oa2' => 'application/vnd.fujitsu.oasys2', + 'oa3' => 'application/vnd.fujitsu.oasys3', + 'oas' => 'application/vnd.fujitsu.oasys', + 'obd' => 'application/x-msbinder', + 'obgx' => 'application/vnd.openblox.game+xml', + 'obj' => 'model/obj', + 'oda' => 'application/oda', + 'odb' => 'application/vnd.oasis.opendocument.database', + 'odc' => 'application/vnd.oasis.opendocument.chart', + 'odf' => 'application/vnd.oasis.opendocument.formula', + 'odft' => 'application/vnd.oasis.opendocument.formula-template', + 'odg' => 'application/vnd.oasis.opendocument.graphics', + 'odi' => 'application/vnd.oasis.opendocument.image', + 'odm' => 'application/vnd.oasis.opendocument.text-master', + 'odp' => 'application/vnd.oasis.opendocument.presentation', + 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', + 'odt' => 'application/vnd.oasis.opendocument.text', + 'oga' => 'audio/ogg', + 'ogex' => 'model/vnd.opengex', + 'ogg' => 'audio/ogg', + 'ogv' => 'video/ogg', + 'ogx' => 'application/ogg', + 'omdoc' => 'application/omdoc+xml', + 'onepkg' => 'application/onenote', + 'onetmp' => 'application/onenote', + 'onetoc' => 'application/onenote', + 'onetoc2' => 'application/onenote', + 'opf' => 'application/oebps-package+xml', + 'opml' => 'text/x-opml', + 'oprc' => 'application/vnd.palm', + 'opus' => 'audio/ogg', + 'org' => 'text/x-org', + 'osf' => 'application/vnd.yamaha.openscoreformat', + 'osfpvg' => 'application/vnd.yamaha.openscoreformat.osfpvg+xml', + 'osm' => 'application/vnd.openstreetmap.data+xml', + 'otc' => 'application/vnd.oasis.opendocument.chart-template', + 'otf' => 'font/otf', + 'otg' => 'application/vnd.oasis.opendocument.graphics-template', + 'oth' => 'application/vnd.oasis.opendocument.text-web', + 'oti' => 'application/vnd.oasis.opendocument.image-template', + 'otp' => 'application/vnd.oasis.opendocument.presentation-template', + 'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template', + 'ott' => 'application/vnd.oasis.opendocument.text-template', + 'ova' => 'application/x-virtualbox-ova', + 'ovf' => 'application/x-virtualbox-ovf', + 'owl' => 'application/rdf+xml', + 'oxps' => 'application/oxps', + 'oxt' => 'application/vnd.openofficeorg.extension', + 'p' => 'text/x-pascal', + 'p7a' => 'application/x-pkcs7-signature', + 'p7b' => 'application/x-pkcs7-certificates', + 'p7c' => 'application/pkcs7-mime', + 'p7m' => 'application/pkcs7-mime', + 'p7r' => 'application/x-pkcs7-certreqresp', + 'p7s' => 'application/pkcs7-signature', + 'p8' => 'application/pkcs8', + 'p10' => 'application/x-pkcs10', + 'p12' => 'application/x-pkcs12', + 'pac' => 'application/x-ns-proxy-autoconfig', + 'pages' => 'application/x-iwork-pages-sffpages', + 'pas' => 'text/x-pascal', + 'paw' => 'application/vnd.pawaafile', + 'pbd' => 'application/vnd.powerbuilder6', + 'pbm' => 'image/x-portable-bitmap', + 'pcap' => 'application/vnd.tcpdump.pcap', + 'pcf' => 'application/x-font-pcf', + 'pcl' => 'application/vnd.hp-pcl', + 'pclxl' => 'application/vnd.hp-pclxl', + 'pct' => 'image/x-pict', + 'pcurl' => 'application/vnd.curl.pcurl', + 'pcx' => 'image/x-pcx', + 'pdb' => 'application/x-pilot', + 'pde' => 'text/x-processing', + 'pdf' => 'application/pdf', + 'pem' => 'application/x-x509-user-cert', + 'pfa' => 'application/x-font-type1', + 'pfb' => 'application/x-font-type1', + 'pfm' => 'application/x-font-type1', + 'pfr' => 'application/font-tdpfr', + 'pfx' => 'application/x-pkcs12', + 'pgm' => 'image/x-portable-graymap', + 'pgn' => 'application/x-chess-pgn', + 'pgp' => 'application/pgp', + 'phar' => 'application/octet-stream', + 'php' => 'application/x-httpd-php', + 'php3' => 'application/x-httpd-php', + 'php4' => 'application/x-httpd-php', + 'phps' => 'application/x-httpd-php-source', + 'phtml' => 'application/x-httpd-php', + 'pic' => 'image/x-pict', + 'pkg' => 'application/octet-stream', + 'pki' => 'application/pkixcmp', + 'pkipath' => 'application/pkix-pkipath', + 'pkpass' => 'application/vnd.apple.pkpass', + 'pl' => 'application/x-perl', + 'plb' => 'application/vnd.3gpp.pic-bw-large', + 'plc' => 'application/vnd.mobius.plc', + 'plf' => 'application/vnd.pocketlearn', + 'pls' => 'application/pls+xml', + 'pm' => 'application/x-perl', + 'pml' => 'application/vnd.ctc-posml', + 'png' => 'image/png', + 'pnm' => 'image/x-portable-anymap', + 'portpkg' => 'application/vnd.macports.portpkg', + 'pot' => 'application/vnd.ms-powerpoint', + 'potm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12', + 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', + 'ppa' => 'application/vnd.ms-powerpoint', + 'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12', + 'ppd' => 'application/vnd.cups-ppd', + 'ppm' => 'image/x-portable-pixmap', + 'pps' => 'application/vnd.ms-powerpoint', + 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', + 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', + 'ppt' => 'application/powerpoint', + 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12', + 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'pqa' => 'application/vnd.palm', + 'prc' => 'model/prc', + 'pre' => 'application/vnd.lotus-freelance', + 'prf' => 'application/pics-rules', + 'provx' => 'application/provenance+xml', + 'ps' => 'application/postscript', + 'psb' => 'application/vnd.3gpp.pic-bw-small', + 'psd' => 'application/x-photoshop', + 'psf' => 'application/x-font-linux-psf', + 'pskcxml' => 'application/pskc+xml', + 'pti' => 'image/prs.pti', + 'ptid' => 'application/vnd.pvi.ptid1', + 'pub' => 'application/x-mspublisher', + 'pvb' => 'application/vnd.3gpp.pic-bw-var', + 'pwn' => 'application/vnd.3m.post-it-notes', + 'pya' => 'audio/vnd.ms-playready.media.pya', + 'pyv' => 'video/vnd.ms-playready.media.pyv', + 'qam' => 'application/vnd.epson.quickanime', + 'qbo' => 'application/vnd.intu.qbo', + 'qfx' => 'application/vnd.intu.qfx', + 'qps' => 'application/vnd.publishare-delta-tree', + 'qt' => 'video/quicktime', + 'qwd' => 'application/vnd.quark.quarkxpress', + 'qwt' => 'application/vnd.quark.quarkxpress', + 'qxb' => 'application/vnd.quark.quarkxpress', + 'qxd' => 'application/vnd.quark.quarkxpress', + 'qxl' => 'application/vnd.quark.quarkxpress', + 'qxt' => 'application/vnd.quark.quarkxpress', + 'ra' => 'audio/x-realaudio', + 'ram' => 'audio/x-pn-realaudio', + 'raml' => 'application/raml+yaml', + 'rapd' => 'application/route-apd+xml', + 'rar' => 'application/x-rar', + 'ras' => 'image/x-cmu-raster', + 'rcprofile' => 'application/vnd.ipunplugged.rcprofile', + 'rdf' => 'application/rdf+xml', + 'rdz' => 'application/vnd.data-vision.rdz', + 'relo' => 'application/p2p-overlay+xml', + 'rep' => 'application/vnd.businessobjects', + 'res' => 'application/x-dtbresource+xml', + 'rgb' => 'image/x-rgb', + 'rif' => 'application/reginfo+xml', + 'rip' => 'audio/vnd.rip', + 'ris' => 'application/x-research-info-systems', + 'rl' => 'application/resource-lists+xml', + 'rlc' => 'image/vnd.fujixerox.edmics-rlc', + 'rld' => 'application/resource-lists-diff+xml', + 'rm' => 'audio/x-pn-realaudio', + 'rmi' => 'audio/midi', + 'rmp' => 'audio/x-pn-realaudio-plugin', + 'rms' => 'application/vnd.jcp.javame.midlet-rms', + 'rmvb' => 'application/vnd.rn-realmedia-vbr', + 'rnc' => 'application/relax-ng-compact-syntax', + 'rng' => 'application/xml', + 'roa' => 'application/rpki-roa', + 'roff' => 'text/troff', + 'rp9' => 'application/vnd.cloanto.rp9', + 'rpm' => 'audio/x-pn-realaudio-plugin', + 'rpss' => 'application/vnd.nokia.radio-presets', + 'rpst' => 'application/vnd.nokia.radio-preset', + 'rq' => 'application/sparql-query', + 'rs' => 'application/rls-services+xml', + 'rsa' => 'application/x-pkcs7', + 'rsat' => 'application/atsc-rsat+xml', + 'rsd' => 'application/rsd+xml', + 'rsheet' => 'application/urc-ressheet+xml', + 'rss' => 'application/rss+xml', + 'rtf' => 'text/rtf', + 'rtx' => 'text/richtext', + 'run' => 'application/x-makeself', + 'rusd' => 'application/route-usd+xml', + 'rv' => 'video/vnd.rn-realvideo', + 's' => 'text/x-asm', + 's3m' => 'audio/s3m', + 'saf' => 'application/vnd.yamaha.smaf-audio', + 'sass' => 'text/x-sass', + 'sbml' => 'application/sbml+xml', + 'sc' => 'application/vnd.ibm.secure-container', + 'scd' => 'application/x-msschedule', + 'scm' => 'application/vnd.lotus-screencam', + 'scq' => 'application/scvp-cv-request', + 'scs' => 'application/scvp-cv-response', + 'scss' => 'text/x-scss', + 'scurl' => 'text/vnd.curl.scurl', + 'sda' => 'application/vnd.stardivision.draw', + 'sdc' => 'application/vnd.stardivision.calc', + 'sdd' => 'application/vnd.stardivision.impress', + 'sdkd' => 'application/vnd.solent.sdkm+xml', + 'sdkm' => 'application/vnd.solent.sdkm+xml', + 'sdp' => 'application/sdp', + 'sdw' => 'application/vnd.stardivision.writer', + 'sea' => 'application/octet-stream', + 'see' => 'application/vnd.seemail', + 'seed' => 'application/vnd.fdsn.seed', + 'sema' => 'application/vnd.sema', + 'semd' => 'application/vnd.semd', + 'semf' => 'application/vnd.semf', + 'senmlx' => 'application/senml+xml', + 'sensmlx' => 'application/sensml+xml', + 'ser' => 'application/java-serialized-object', + 'setpay' => 'application/set-payment-initiation', + 'setreg' => 'application/set-registration-initiation', + 'sfd-hdstx' => 'application/vnd.hydrostatix.sof-data', + 'sfs' => 'application/vnd.spotfire.sfs', + 'sfv' => 'text/x-sfv', + 'sgi' => 'image/sgi', + 'sgl' => 'application/vnd.stardivision.writer-global', + 'sgm' => 'text/sgml', + 'sgml' => 'text/sgml', + 'sh' => 'application/x-sh', + 'shar' => 'application/x-shar', + 'shex' => 'text/shex', + 'shf' => 'application/shf+xml', + 'shtml' => 'text/html', + 'sid' => 'image/x-mrsid-image', + 'sieve' => 'application/sieve', + 'sig' => 'application/pgp-signature', + 'sil' => 'audio/silk', + 'silo' => 'model/mesh', + 'sis' => 'application/vnd.symbian.install', + 'sisx' => 'application/vnd.symbian.install', + 'sit' => 'application/x-stuffit', + 'sitx' => 'application/x-stuffitx', + 'siv' => 'application/sieve', + 'skd' => 'application/vnd.koan', + 'skm' => 'application/vnd.koan', + 'skp' => 'application/vnd.koan', + 'skt' => 'application/vnd.koan', + 'sldm' => 'application/vnd.ms-powerpoint.slide.macroenabled.12', + 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', + 'slim' => 'text/slim', + 'slm' => 'text/slim', + 'sls' => 'application/route-s-tsid+xml', + 'slt' => 'application/vnd.epson.salt', + 'sm' => 'application/vnd.stepmania.stepchart', + 'smf' => 'application/vnd.stardivision.math', + 'smi' => 'application/smil', + 'smil' => 'application/smil', + 'smv' => 'video/x-smv', + 'smzip' => 'application/vnd.stepmania.package', + 'snd' => 'audio/basic', + 'snf' => 'application/x-font-snf', + 'so' => 'application/octet-stream', + 'spc' => 'application/x-pkcs7-certificates', + 'spdx' => 'text/spdx', + 'spf' => 'application/vnd.yamaha.smaf-phrase', + 'spl' => 'application/x-futuresplash', + 'spot' => 'text/vnd.in3d.spot', + 'spp' => 'application/scvp-vp-response', + 'spq' => 'application/scvp-vp-request', + 'spx' => 'audio/ogg', + 'sql' => 'application/x-sql', + 'src' => 'application/x-wais-source', + 'srt' => 'application/x-subrip', + 'sru' => 'application/sru+xml', + 'srx' => 'application/sparql-results+xml', + 'ssdl' => 'application/ssdl+xml', + 'sse' => 'application/vnd.kodak-descriptor', + 'ssf' => 'application/vnd.epson.ssf', + 'ssml' => 'application/ssml+xml', + 'sst' => 'application/octet-stream', + 'st' => 'application/vnd.sailingtracker.track', + 'stc' => 'application/vnd.sun.xml.calc.template', + 'std' => 'application/vnd.sun.xml.draw.template', + 'stf' => 'application/vnd.wt.stf', + 'sti' => 'application/vnd.sun.xml.impress.template', + 'stk' => 'application/hyperstudio', + 'stl' => 'model/stl', + 'stpx' => 'model/step+xml', + 'stpxz' => 'model/step-xml+zip', + 'stpz' => 'model/step+zip', + 'str' => 'application/vnd.pg.format', + 'stw' => 'application/vnd.sun.xml.writer.template', + 'styl' => 'text/stylus', + 'stylus' => 'text/stylus', + 'sub' => 'text/vnd.dvb.subtitle', + 'sus' => 'application/vnd.sus-calendar', + 'susp' => 'application/vnd.sus-calendar', + 'sv4cpio' => 'application/x-sv4cpio', + 'sv4crc' => 'application/x-sv4crc', + 'svc' => 'application/vnd.dvb.service', + 'svd' => 'application/vnd.svd', + 'svg' => 'image/svg+xml', + 'svgz' => 'image/svg+xml', + 'swa' => 'application/x-director', + 'swf' => 'application/x-shockwave-flash', + 'swi' => 'application/vnd.aristanetworks.swi', + 'swidtag' => 'application/swid+xml', + 'sxc' => 'application/vnd.sun.xml.calc', + 'sxd' => 'application/vnd.sun.xml.draw', + 'sxg' => 'application/vnd.sun.xml.writer.global', + 'sxi' => 'application/vnd.sun.xml.impress', + 'sxm' => 'application/vnd.sun.xml.math', + 'sxw' => 'application/vnd.sun.xml.writer', + 't' => 'text/troff', + 't3' => 'application/x-t3vm-image', + 't38' => 'image/t38', + 'taglet' => 'application/vnd.mynfc', + 'tao' => 'application/vnd.tao.intent-module-archive', + 'tap' => 'image/vnd.tencent.tap', + 'tar' => 'application/x-tar', + 'tcap' => 'application/vnd.3gpp2.tcap', + 'tcl' => 'application/x-tcl', + 'td' => 'application/urc-targetdesc+xml', + 'teacher' => 'application/vnd.smart.teacher', + 'tei' => 'application/tei+xml', + 'teicorpus' => 'application/tei+xml', + 'tex' => 'application/x-tex', + 'texi' => 'application/x-texinfo', + 'texinfo' => 'application/x-texinfo', + 'text' => 'text/plain', + 'tfi' => 'application/thraud+xml', + 'tfm' => 'application/x-tex-tfm', + 'tfx' => 'image/tiff-fx', + 'tga' => 'image/x-tga', + 'tgz' => 'application/x-tar', + 'thmx' => 'application/vnd.ms-officetheme', + 'tif' => 'image/tiff', + 'tiff' => 'image/tiff', + 'tk' => 'application/x-tcl', + 'tmo' => 'application/vnd.tmobile-livetv', + 'toml' => 'application/toml', + 'torrent' => 'application/x-bittorrent', + 'tpl' => 'application/vnd.groove-tool-template', + 'tpt' => 'application/vnd.trid.tpt', + 'tr' => 'text/troff', + 'tra' => 'application/vnd.trueapp', + 'trig' => 'application/trig', + 'trm' => 'application/x-msterminal', + 'ts' => 'video/mp2t', + 'tsd' => 'application/timestamped-data', + 'tsv' => 'text/tab-separated-values', + 'ttc' => 'font/collection', + 'ttf' => 'font/ttf', + 'ttl' => 'text/turtle', + 'ttml' => 'application/ttml+xml', + 'twd' => 'application/vnd.simtech-mindmapper', + 'twds' => 'application/vnd.simtech-mindmapper', + 'txd' => 'application/vnd.genomatix.tuxedo', + 'txf' => 'application/vnd.mobius.txf', + 'txt' => 'text/plain', + 'u3d' => 'model/u3d', + 'u8dsn' => 'message/global-delivery-status', + 'u8hdr' => 'message/global-headers', + 'u8mdn' => 'message/global-disposition-notification', + 'u8msg' => 'message/global', + 'u32' => 'application/x-authorware-bin', + 'ubj' => 'application/ubjson', + 'udeb' => 'application/x-debian-package', + 'ufd' => 'application/vnd.ufdl', + 'ufdl' => 'application/vnd.ufdl', + 'ulx' => 'application/x-glulx', + 'umj' => 'application/vnd.umajin', + 'unityweb' => 'application/vnd.unity', + 'uoml' => 'application/vnd.uoml+xml', + 'uri' => 'text/uri-list', + 'uris' => 'text/uri-list', + 'urls' => 'text/uri-list', + 'usdz' => 'model/vnd.usdz+zip', + 'ustar' => 'application/x-ustar', + 'utz' => 'application/vnd.uiq.theme', + 'uu' => 'text/x-uuencode', + 'uva' => 'audio/vnd.dece.audio', + 'uvd' => 'application/vnd.dece.data', + 'uvf' => 'application/vnd.dece.data', + 'uvg' => 'image/vnd.dece.graphic', + 'uvh' => 'video/vnd.dece.hd', + 'uvi' => 'image/vnd.dece.graphic', + 'uvm' => 'video/vnd.dece.mobile', + 'uvp' => 'video/vnd.dece.pd', + 'uvs' => 'video/vnd.dece.sd', + 'uvt' => 'application/vnd.dece.ttml+xml', + 'uvu' => 'video/vnd.uvvu.mp4', + 'uvv' => 'video/vnd.dece.video', + 'uvva' => 'audio/vnd.dece.audio', + 'uvvd' => 'application/vnd.dece.data', + 'uvvf' => 'application/vnd.dece.data', + 'uvvg' => 'image/vnd.dece.graphic', + 'uvvh' => 'video/vnd.dece.hd', + 'uvvi' => 'image/vnd.dece.graphic', + 'uvvm' => 'video/vnd.dece.mobile', + 'uvvp' => 'video/vnd.dece.pd', + 'uvvs' => 'video/vnd.dece.sd', + 'uvvt' => 'application/vnd.dece.ttml+xml', + 'uvvu' => 'video/vnd.uvvu.mp4', + 'uvvv' => 'video/vnd.dece.video', + 'uvvx' => 'application/vnd.dece.unspecified', + 'uvvz' => 'application/vnd.dece.zip', + 'uvx' => 'application/vnd.dece.unspecified', + 'uvz' => 'application/vnd.dece.zip', + 'vbox' => 'application/x-virtualbox-vbox', + 'vbox-extpack' => 'application/x-virtualbox-vbox-extpack', + 'vcard' => 'text/vcard', + 'vcd' => 'application/x-cdlink', + 'vcf' => 'text/x-vcard', + 'vcg' => 'application/vnd.groove-vcard', + 'vcs' => 'text/x-vcalendar', + 'vcx' => 'application/vnd.vcx', + 'vdi' => 'application/x-virtualbox-vdi', + 'vds' => 'model/vnd.sap.vds', + 'vhd' => 'application/x-virtualbox-vhd', + 'vis' => 'application/vnd.visionary', + 'viv' => 'video/vnd.vivo', + 'vlc' => 'application/videolan', + 'vmdk' => 'application/x-virtualbox-vmdk', + 'vob' => 'video/x-ms-vob', + 'vor' => 'application/vnd.stardivision.writer', + 'vox' => 'application/x-authorware-bin', + 'vrml' => 'model/vrml', + 'vsd' => 'application/vnd.visio', + 'vsf' => 'application/vnd.vsf', + 'vss' => 'application/vnd.visio', + 'vst' => 'application/vnd.visio', + 'vsw' => 'application/vnd.visio', + 'vtf' => 'image/vnd.valve.source.texture', + 'vtt' => 'text/vtt', + 'vtu' => 'model/vnd.vtu', + 'vxml' => 'application/voicexml+xml', + 'w3d' => 'application/x-director', + 'wad' => 'application/x-doom', + 'wadl' => 'application/vnd.sun.wadl+xml', + 'war' => 'application/java-archive', + 'wasm' => 'application/wasm', + 'wav' => 'audio/x-wav', + 'wax' => 'audio/x-ms-wax', + 'wbmp' => 'image/vnd.wap.wbmp', + 'wbs' => 'application/vnd.criticaltools.wbs+xml', + 'wbxml' => 'application/wbxml', + 'wcm' => 'application/vnd.ms-works', + 'wdb' => 'application/vnd.ms-works', + 'wdp' => 'image/vnd.ms-photo', + 'weba' => 'audio/webm', + 'webapp' => 'application/x-web-app-manifest+json', + 'webm' => 'video/webm', + 'webmanifest' => 'application/manifest+json', + 'webp' => 'image/webp', + 'wg' => 'application/vnd.pmi.widget', + 'wgt' => 'application/widget', + 'wif' => 'application/watcherinfo+xml', + 'wks' => 'application/vnd.ms-works', + 'wm' => 'video/x-ms-wm', + 'wma' => 'audio/x-ms-wma', + 'wmd' => 'application/x-ms-wmd', + 'wmf' => 'image/wmf', + 'wml' => 'text/vnd.wap.wml', + 'wmlc' => 'application/wmlc', + 'wmls' => 'text/vnd.wap.wmlscript', + 'wmlsc' => 'application/vnd.wap.wmlscriptc', + 'wmv' => 'video/x-ms-wmv', + 'wmx' => 'video/x-ms-wmx', + 'wmz' => 'application/x-msmetafile', + 'woff' => 'font/woff', + 'woff2' => 'font/woff2', + 'word' => 'application/msword', + 'wpd' => 'application/vnd.wordperfect', + 'wpl' => 'application/vnd.ms-wpl', + 'wps' => 'application/vnd.ms-works', + 'wqd' => 'application/vnd.wqd', + 'wri' => 'application/x-mswrite', + 'wrl' => 'model/vrml', + 'wsc' => 'message/vnd.wfa.wsc', + 'wsdl' => 'application/wsdl+xml', + 'wspolicy' => 'application/wspolicy+xml', + 'wtb' => 'application/vnd.webturbo', + 'wvx' => 'video/x-ms-wvx', + 'x3d' => 'model/x3d+xml', + 'x3db' => 'model/x3d+fastinfoset', + 'x3dbz' => 'model/x3d+binary', + 'x3dv' => 'model/x3d-vrml', + 'x3dvz' => 'model/x3d+vrml', + 'x3dz' => 'model/x3d+xml', + 'x32' => 'application/x-authorware-bin', + 'x_b' => 'model/vnd.parasolid.transmit.binary', + 'x_t' => 'model/vnd.parasolid.transmit.text', + 'xaml' => 'application/xaml+xml', + 'xap' => 'application/x-silverlight-app', + 'xar' => 'application/vnd.xara', + 'xav' => 'application/xcap-att+xml', + 'xbap' => 'application/x-ms-xbap', + 'xbd' => 'application/vnd.fujixerox.docuworks.binder', + 'xbm' => 'image/x-xbitmap', + 'xca' => 'application/xcap-caps+xml', + 'xcs' => 'application/calendar+xml', + 'xdf' => 'application/xcap-diff+xml', + 'xdm' => 'application/vnd.syncml.dm+xml', + 'xdp' => 'application/vnd.adobe.xdp+xml', + 'xdssc' => 'application/dssc+xml', + 'xdw' => 'application/vnd.fujixerox.docuworks', + 'xel' => 'application/xcap-el+xml', + 'xenc' => 'application/xenc+xml', + 'xer' => 'application/patch-ops-error+xml', + 'xfdf' => 'application/vnd.adobe.xfdf', + 'xfdl' => 'application/vnd.xfdl', + 'xht' => 'application/xhtml+xml', + 'xhtml' => 'application/xhtml+xml', + 'xhvml' => 'application/xv+xml', + 'xif' => 'image/vnd.xiff', + 'xl' => 'application/excel', + 'xla' => 'application/vnd.ms-excel', + 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12', + 'xlc' => 'application/vnd.ms-excel', + 'xlf' => 'application/xliff+xml', + 'xlm' => 'application/vnd.ms-excel', + 'xls' => 'application/vnd.ms-excel', + 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12', + 'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12', + 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'xlt' => 'application/vnd.ms-excel', + 'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12', + 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', + 'xlw' => 'application/vnd.ms-excel', + 'xm' => 'audio/xm', + 'xml' => 'application/xml', + 'xns' => 'application/xcap-ns+xml', + 'xo' => 'application/vnd.olpc-sugar', + 'xop' => 'application/xop+xml', + 'xpi' => 'application/x-xpinstall', + 'xpl' => 'application/xproc+xml', + 'xpm' => 'image/x-xpixmap', + 'xpr' => 'application/vnd.is-xpr', + 'xps' => 'application/vnd.ms-xpsdocument', + 'xpw' => 'application/vnd.intercon.formnet', + 'xpx' => 'application/vnd.intercon.formnet', + 'xsd' => 'application/xml', + 'xsl' => 'application/xml', + 'xslt' => 'application/xslt+xml', + 'xsm' => 'application/vnd.syncml+xml', + 'xspf' => 'application/xspf+xml', + 'xul' => 'application/vnd.mozilla.xul+xml', + 'xvm' => 'application/xv+xml', + 'xvml' => 'application/xv+xml', + 'xwd' => 'image/x-xwindowdump', + 'xyz' => 'chemical/x-xyz', + 'xz' => 'application/x-xz', + 'yaml' => 'text/yaml', + 'yang' => 'application/yang', + 'yin' => 'application/yin+xml', + 'yml' => 'text/yaml', + 'ymp' => 'text/x-suse-ymp', + 'z' => 'application/x-compress', + 'z1' => 'application/x-zmachine', + 'z2' => 'application/x-zmachine', + 'z3' => 'application/x-zmachine', + 'z4' => 'application/x-zmachine', + 'z5' => 'application/x-zmachine', + 'z6' => 'application/x-zmachine', + 'z7' => 'application/x-zmachine', + 'z8' => 'application/x-zmachine', + 'zaz' => 'application/vnd.zzazz.deck+xml', + 'zip' => 'application/zip', + 'zir' => 'application/vnd.zul', + 'zirz' => 'application/vnd.zul', + 'zmm' => 'application/vnd.handheld-entertainment+xml', + 'zsh' => 'text/x-scriptzsh', + ]; + + /** + * Determines the mimetype of a file by looking at its extension. + * + * @link https://raw.githubusercontent.com/jshttp/mime-db/master/db.json + */ + public static function fromFilename(string $filename): ?string + { + return self::fromExtension(pathinfo($filename, PATHINFO_EXTENSION)); + } + + /** + * Maps a file extensions to a mimetype. + * + * @link https://raw.githubusercontent.com/jshttp/mime-db/master/db.json + */ + public static function fromExtension(string $extension): ?string + { + return self::MIME_TYPES[strtolower($extension)] ?? null; + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/MultipartStream.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/MultipartStream.php new file mode 100644 index 000000000..3e12b74d1 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/MultipartStream.php @@ -0,0 +1,159 @@ +boundary = $boundary ?: bin2hex(random_bytes(20)); + $this->stream = $this->createStream($elements); + } + + public function getBoundary(): string + { + return $this->boundary; + } + + public function isWritable(): bool + { + return false; + } + + /** + * Get the headers needed before transferring the content of a POST file + * + * @param array $headers + */ + private function getHeaders(array $headers): string + { + $str = ''; + foreach ($headers as $key => $value) { + $str .= "{$key}: {$value}\r\n"; + } + + return "--{$this->boundary}\r\n" . trim($str) . "\r\n\r\n"; + } + + /** + * Create the aggregate stream that will be used to upload the POST data + */ + protected function createStream(array $elements = []): StreamInterface + { + $stream = new AppendStream(); + + foreach ($elements as $element) { + if (!is_array($element)) { + throw new \UnexpectedValueException("An array is expected"); + } + $this->addElement($stream, $element); + } + + // Add the trailing boundary with CRLF + $stream->addStream(Utils::streamFor("--{$this->boundary}--\r\n")); + + return $stream; + } + + private function addElement(AppendStream $stream, array $element): void + { + foreach (['contents', 'name'] as $key) { + if (!array_key_exists($key, $element)) { + throw new \InvalidArgumentException("A '{$key}' key is required"); + } + } + + $element['contents'] = Utils::streamFor($element['contents']); + + if (empty($element['filename'])) { + $uri = $element['contents']->getMetadata('uri'); + if ($uri && \is_string($uri) && \substr($uri, 0, 6) !== 'php://' && \substr($uri, 0, 7) !== 'data://') { + $element['filename'] = $uri; + } + } + + [$body, $headers] = $this->createElement( + $element['name'], + $element['contents'], + $element['filename'] ?? null, + $element['headers'] ?? [] + ); + + $stream->addStream(Utils::streamFor($this->getHeaders($headers))); + $stream->addStream($body); + $stream->addStream(Utils::streamFor("\r\n")); + } + + private function createElement(string $name, StreamInterface $stream, ?string $filename, array $headers): array + { + // Set a default content-disposition header if one was no provided + $disposition = $this->getHeader($headers, 'content-disposition'); + if (!$disposition) { + $headers['Content-Disposition'] = ($filename === '0' || $filename) + ? sprintf( + 'form-data; name="%s"; filename="%s"', + $name, + basename($filename) + ) + : "form-data; name=\"{$name}\""; + } + + // Set a default content-length header if one was no provided + $length = $this->getHeader($headers, 'content-length'); + if (!$length) { + if ($length = $stream->getSize()) { + $headers['Content-Length'] = (string) $length; + } + } + + // Set a default Content-Type if one was not supplied + $type = $this->getHeader($headers, 'content-type'); + if (!$type && ($filename === '0' || $filename)) { + if ($type = MimeType::fromFilename($filename)) { + $headers['Content-Type'] = $type; + } + } + + return [$stream, $headers]; + } + + private function getHeader(array $headers, string $key) + { + $lowercaseHeader = strtolower($key); + foreach ($headers as $k => $v) { + if (strtolower($k) === $lowercaseHeader) { + return $v; + } + } + + return null; + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/NoSeekStream.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/NoSeekStream.php new file mode 100644 index 000000000..161a224f0 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/NoSeekStream.php @@ -0,0 +1,28 @@ +source = $source; + $this->size = $options['size'] ?? null; + $this->metadata = $options['metadata'] ?? []; + $this->buffer = new BufferStream(); + } + + public function __toString(): string + { + try { + return Utils::copyToString($this); + } catch (\Throwable $e) { + if (\PHP_VERSION_ID >= 70400) { + throw $e; + } + trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR); + return ''; + } + } + + public function close(): void + { + $this->detach(); + } + + public function detach() + { + $this->tellPos = 0; + $this->source = null; + + return null; + } + + public function getSize(): ?int + { + return $this->size; + } + + public function tell(): int + { + return $this->tellPos; + } + + public function eof(): bool + { + return $this->source === null; + } + + public function isSeekable(): bool + { + return false; + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET): void + { + throw new \RuntimeException('Cannot seek a PumpStream'); + } + + public function isWritable(): bool + { + return false; + } + + public function write($string): int + { + throw new \RuntimeException('Cannot write to a PumpStream'); + } + + public function isReadable(): bool + { + return true; + } + + public function read($length): string + { + $data = $this->buffer->read($length); + $readLen = strlen($data); + $this->tellPos += $readLen; + $remaining = $length - $readLen; + + if ($remaining) { + $this->pump($remaining); + $data .= $this->buffer->read($remaining); + $this->tellPos += strlen($data) - $readLen; + } + + return $data; + } + + public function getContents(): string + { + $result = ''; + while (!$this->eof()) { + $result .= $this->read(1000000); + } + + return $result; + } + + /** + * {@inheritdoc} + * + * @return mixed + */ + public function getMetadata($key = null) + { + if (!$key) { + return $this->metadata; + } + + return $this->metadata[$key] ?? null; + } + + private function pump(int $length): void + { + if ($this->source) { + do { + $data = call_user_func($this->source, $length); + if ($data === false || $data === null) { + $this->source = null; + return; + } + $this->buffer->write($data); + $length -= strlen($data); + } while ($length > 0); + } + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Query.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Query.php new file mode 100644 index 000000000..2faab3a88 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Query.php @@ -0,0 +1,113 @@ + '1', 'foo[b]' => '2'])`. + * + * @param string $str Query string to parse + * @param int|bool $urlEncoding How the query string is encoded + */ + public static function parse(string $str, $urlEncoding = true): array + { + $result = []; + + if ($str === '') { + return $result; + } + + if ($urlEncoding === true) { + $decoder = function ($value) { + return rawurldecode(str_replace('+', ' ', (string) $value)); + }; + } elseif ($urlEncoding === PHP_QUERY_RFC3986) { + $decoder = 'rawurldecode'; + } elseif ($urlEncoding === PHP_QUERY_RFC1738) { + $decoder = 'urldecode'; + } else { + $decoder = function ($str) { + return $str; + }; + } + + foreach (explode('&', $str) as $kvp) { + $parts = explode('=', $kvp, 2); + $key = $decoder($parts[0]); + $value = isset($parts[1]) ? $decoder($parts[1]) : null; + if (!array_key_exists($key, $result)) { + $result[$key] = $value; + } else { + if (!is_array($result[$key])) { + $result[$key] = [$result[$key]]; + } + $result[$key][] = $value; + } + } + + return $result; + } + + /** + * Build a query string from an array of key value pairs. + * + * This function can use the return value of `parse()` to build a query + * string. This function does not modify the provided keys when an array is + * encountered (like `http_build_query()` would). + * + * @param array $params Query string parameters. + * @param int|false $encoding Set to false to not encode, PHP_QUERY_RFC3986 + * to encode using RFC3986, or PHP_QUERY_RFC1738 + * to encode using RFC1738. + */ + public static function build(array $params, $encoding = PHP_QUERY_RFC3986): string + { + if (!$params) { + return ''; + } + + if ($encoding === false) { + $encoder = function (string $str): string { + return $str; + }; + } elseif ($encoding === PHP_QUERY_RFC3986) { + $encoder = 'rawurlencode'; + } elseif ($encoding === PHP_QUERY_RFC1738) { + $encoder = 'urlencode'; + } else { + throw new \InvalidArgumentException('Invalid type'); + } + + $qs = ''; + foreach ($params as $k => $v) { + $k = $encoder((string) $k); + if (!is_array($v)) { + $qs .= $k; + $v = is_bool($v) ? (int) $v : $v; + if ($v !== null) { + $qs .= '=' . $encoder((string) $v); + } + $qs .= '&'; + } else { + foreach ($v as $vv) { + $qs .= $k; + $vv = is_bool($vv) ? (int) $vv : $vv; + if ($vv !== null) { + $qs .= '=' . $encoder((string) $vv); + } + $qs .= '&'; + } + } + } + + return $qs ? (string) substr($qs, 0, -1) : ''; + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Request.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Request.php new file mode 100644 index 000000000..b17af66a2 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Request.php @@ -0,0 +1,157 @@ + $headers Request headers + * @param string|resource|StreamInterface|null $body Request body + * @param string $version Protocol version + */ + public function __construct( + string $method, + $uri, + array $headers = [], + $body = null, + string $version = '1.1' + ) { + $this->assertMethod($method); + if (!($uri instanceof UriInterface)) { + $uri = new Uri($uri); + } + + $this->method = strtoupper($method); + $this->uri = $uri; + $this->setHeaders($headers); + $this->protocol = $version; + + if (!isset($this->headerNames['host'])) { + $this->updateHostFromUri(); + } + + if ($body !== '' && $body !== null) { + $this->stream = Utils::streamFor($body); + } + } + + public function getRequestTarget(): string + { + if ($this->requestTarget !== null) { + return $this->requestTarget; + } + + $target = $this->uri->getPath(); + if ($target === '') { + $target = '/'; + } + if ($this->uri->getQuery() != '') { + $target .= '?' . $this->uri->getQuery(); + } + + return $target; + } + + public function withRequestTarget($requestTarget): RequestInterface + { + if (preg_match('#\s#', $requestTarget)) { + throw new InvalidArgumentException( + 'Invalid request target provided; cannot contain whitespace' + ); + } + + $new = clone $this; + $new->requestTarget = $requestTarget; + return $new; + } + + public function getMethod(): string + { + return $this->method; + } + + public function withMethod($method): RequestInterface + { + $this->assertMethod($method); + $new = clone $this; + $new->method = strtoupper($method); + return $new; + } + + public function getUri(): UriInterface + { + return $this->uri; + } + + public function withUri(UriInterface $uri, $preserveHost = false): RequestInterface + { + if ($uri === $this->uri) { + return $this; + } + + $new = clone $this; + $new->uri = $uri; + + if (!$preserveHost || !isset($this->headerNames['host'])) { + $new->updateHostFromUri(); + } + + return $new; + } + + private function updateHostFromUri(): void + { + $host = $this->uri->getHost(); + + if ($host == '') { + return; + } + + if (($port = $this->uri->getPort()) !== null) { + $host .= ':' . $port; + } + + if (isset($this->headerNames['host'])) { + $header = $this->headerNames['host']; + } else { + $header = 'Host'; + $this->headerNames['host'] = 'Host'; + } + // Ensure Host is the first header. + // See: http://tools.ietf.org/html/rfc7230#section-5.4 + $this->headers = [$header => [$host]] + $this->headers; + } + + /** + * @param mixed $method + */ + private function assertMethod($method): void + { + if (!is_string($method) || $method === '') { + throw new InvalidArgumentException('Method must be a non-empty string.'); + } + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Response.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Response.php new file mode 100644 index 000000000..4c6ee6f03 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Response.php @@ -0,0 +1,160 @@ + 'Continue', + 101 => 'Switching Protocols', + 102 => 'Processing', + 200 => 'OK', + 201 => 'Created', + 202 => 'Accepted', + 203 => 'Non-Authoritative Information', + 204 => 'No Content', + 205 => 'Reset Content', + 206 => 'Partial Content', + 207 => 'Multi-status', + 208 => 'Already Reported', + 300 => 'Multiple Choices', + 301 => 'Moved Permanently', + 302 => 'Found', + 303 => 'See Other', + 304 => 'Not Modified', + 305 => 'Use Proxy', + 306 => 'Switch Proxy', + 307 => 'Temporary Redirect', + 308 => 'Permanent Redirect', + 400 => 'Bad Request', + 401 => 'Unauthorized', + 402 => 'Payment Required', + 403 => 'Forbidden', + 404 => 'Not Found', + 405 => 'Method Not Allowed', + 406 => 'Not Acceptable', + 407 => 'Proxy Authentication Required', + 408 => 'Request Time-out', + 409 => 'Conflict', + 410 => 'Gone', + 411 => 'Length Required', + 412 => 'Precondition Failed', + 413 => 'Request Entity Too Large', + 414 => 'Request-URI Too Large', + 415 => 'Unsupported Media Type', + 416 => 'Requested range not satisfiable', + 417 => 'Expectation Failed', + 418 => 'I\'m a teapot', + 422 => 'Unprocessable Entity', + 423 => 'Locked', + 424 => 'Failed Dependency', + 425 => 'Unordered Collection', + 426 => 'Upgrade Required', + 428 => 'Precondition Required', + 429 => 'Too Many Requests', + 431 => 'Request Header Fields Too Large', + 451 => 'Unavailable For Legal Reasons', + 500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + 504 => 'Gateway Time-out', + 505 => 'HTTP Version not supported', + 506 => 'Variant Also Negotiates', + 507 => 'Insufficient Storage', + 508 => 'Loop Detected', + 510 => 'Not Extended', + 511 => 'Network Authentication Required', + ]; + + /** @var string */ + private $reasonPhrase; + + /** @var int */ + private $statusCode; + + /** + * @param int $status Status code + * @param array $headers Response headers + * @param string|resource|StreamInterface|null $body Response body + * @param string $version Protocol version + * @param string|null $reason Reason phrase (when empty a default will be used based on the status code) + */ + public function __construct( + int $status = 200, + array $headers = [], + $body = null, + string $version = '1.1', + string $reason = null + ) { + $this->assertStatusCodeRange($status); + + $this->statusCode = $status; + + if ($body !== '' && $body !== null) { + $this->stream = Utils::streamFor($body); + } + + $this->setHeaders($headers); + if ($reason == '' && isset(self::PHRASES[$this->statusCode])) { + $this->reasonPhrase = self::PHRASES[$this->statusCode]; + } else { + $this->reasonPhrase = (string) $reason; + } + + $this->protocol = $version; + } + + public function getStatusCode(): int + { + return $this->statusCode; + } + + public function getReasonPhrase(): string + { + return $this->reasonPhrase; + } + + public function withStatus($code, $reasonPhrase = ''): ResponseInterface + { + $this->assertStatusCodeIsInteger($code); + $code = (int) $code; + $this->assertStatusCodeRange($code); + + $new = clone $this; + $new->statusCode = $code; + if ($reasonPhrase == '' && isset(self::PHRASES[$new->statusCode])) { + $reasonPhrase = self::PHRASES[$new->statusCode]; + } + $new->reasonPhrase = (string) $reasonPhrase; + return $new; + } + + /** + * @param mixed $statusCode + */ + private function assertStatusCodeIsInteger($statusCode): void + { + if (filter_var($statusCode, FILTER_VALIDATE_INT) === false) { + throw new \InvalidArgumentException('Status code must be an integer value.'); + } + } + + private function assertStatusCodeRange(int $statusCode): void + { + if ($statusCode < 100 || $statusCode >= 600) { + throw new \InvalidArgumentException('Status code must be an integer value between 1xx and 5xx.'); + } + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Rfc7230.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Rfc7230.php new file mode 100644 index 000000000..30224018d --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Rfc7230.php @@ -0,0 +1,23 @@ +@,;:\\\"/[\]?={}\x01-\x20\x7F]++):[ \t]*+((?:[ \t]*+[\x21-\x7E\x80-\xFF]++)*+)[ \t]*+\r?\n)m"; + public const HEADER_FOLD_REGEX = "(\r?\n[ \t]++)"; +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/ServerRequest.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/ServerRequest.php new file mode 100644 index 000000000..b2aa382da --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/ServerRequest.php @@ -0,0 +1,344 @@ + $headers Request headers + * @param string|resource|StreamInterface|null $body Request body + * @param string $version Protocol version + * @param array $serverParams Typically the $_SERVER superglobal + */ + public function __construct( + string $method, + $uri, + array $headers = [], + $body = null, + string $version = '1.1', + array $serverParams = [] + ) { + $this->serverParams = $serverParams; + + parent::__construct($method, $uri, $headers, $body, $version); + } + + /** + * Return an UploadedFile instance array. + * + * @param array $files An array which respect $_FILES structure + * + * @throws InvalidArgumentException for unrecognized values + */ + public static function normalizeFiles(array $files): array + { + $normalized = []; + + foreach ($files as $key => $value) { + if ($value instanceof UploadedFileInterface) { + $normalized[$key] = $value; + } elseif (is_array($value) && isset($value['tmp_name'])) { + $normalized[$key] = self::createUploadedFileFromSpec($value); + } elseif (is_array($value)) { + $normalized[$key] = self::normalizeFiles($value); + continue; + } else { + throw new InvalidArgumentException('Invalid value in files specification'); + } + } + + return $normalized; + } + + /** + * Create and return an UploadedFile instance from a $_FILES specification. + * + * If the specification represents an array of values, this method will + * delegate to normalizeNestedFileSpec() and return that return value. + * + * @param array $value $_FILES struct + * + * @return UploadedFileInterface|UploadedFileInterface[] + */ + private static function createUploadedFileFromSpec(array $value) + { + if (is_array($value['tmp_name'])) { + return self::normalizeNestedFileSpec($value); + } + + return new UploadedFile( + $value['tmp_name'], + (int) $value['size'], + (int) $value['error'], + $value['name'], + $value['type'] + ); + } + + /** + * Normalize an array of file specifications. + * + * Loops through all nested files and returns a normalized array of + * UploadedFileInterface instances. + * + * @return UploadedFileInterface[] + */ + private static function normalizeNestedFileSpec(array $files = []): array + { + $normalizedFiles = []; + + foreach (array_keys($files['tmp_name']) as $key) { + $spec = [ + 'tmp_name' => $files['tmp_name'][$key], + 'size' => $files['size'][$key] ?? null, + 'error' => $files['error'][$key] ?? null, + 'name' => $files['name'][$key] ?? null, + 'type' => $files['type'][$key] ?? null, + ]; + $normalizedFiles[$key] = self::createUploadedFileFromSpec($spec); + } + + return $normalizedFiles; + } + + /** + * Return a ServerRequest populated with superglobals: + * $_GET + * $_POST + * $_COOKIE + * $_FILES + * $_SERVER + */ + public static function fromGlobals(): ServerRequestInterface + { + $method = $_SERVER['REQUEST_METHOD'] ?? 'GET'; + $headers = getallheaders(); + $uri = self::getUriFromGlobals(); + $body = new CachingStream(new LazyOpenStream('php://input', 'r+')); + $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? str_replace('HTTP/', '', $_SERVER['SERVER_PROTOCOL']) : '1.1'; + + $serverRequest = new ServerRequest($method, $uri, $headers, $body, $protocol, $_SERVER); + + return $serverRequest + ->withCookieParams($_COOKIE) + ->withQueryParams($_GET) + ->withParsedBody($_POST) + ->withUploadedFiles(self::normalizeFiles($_FILES)); + } + + private static function extractHostAndPortFromAuthority(string $authority): array + { + $uri = 'http://' . $authority; + $parts = parse_url($uri); + if (false === $parts) { + return [null, null]; + } + + $host = $parts['host'] ?? null; + $port = $parts['port'] ?? null; + + return [$host, $port]; + } + + /** + * Get a Uri populated with values from $_SERVER. + */ + public static function getUriFromGlobals(): UriInterface + { + $uri = new Uri(''); + + $uri = $uri->withScheme(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http'); + + $hasPort = false; + if (isset($_SERVER['HTTP_HOST'])) { + [$host, $port] = self::extractHostAndPortFromAuthority($_SERVER['HTTP_HOST']); + if ($host !== null) { + $uri = $uri->withHost($host); + } + + if ($port !== null) { + $hasPort = true; + $uri = $uri->withPort($port); + } + } elseif (isset($_SERVER['SERVER_NAME'])) { + $uri = $uri->withHost($_SERVER['SERVER_NAME']); + } elseif (isset($_SERVER['SERVER_ADDR'])) { + $uri = $uri->withHost($_SERVER['SERVER_ADDR']); + } + + if (!$hasPort && isset($_SERVER['SERVER_PORT'])) { + $uri = $uri->withPort($_SERVER['SERVER_PORT']); + } + + $hasQuery = false; + if (isset($_SERVER['REQUEST_URI'])) { + $requestUriParts = explode('?', $_SERVER['REQUEST_URI'], 2); + $uri = $uri->withPath($requestUriParts[0]); + if (isset($requestUriParts[1])) { + $hasQuery = true; + $uri = $uri->withQuery($requestUriParts[1]); + } + } + + if (!$hasQuery && isset($_SERVER['QUERY_STRING'])) { + $uri = $uri->withQuery($_SERVER['QUERY_STRING']); + } + + return $uri; + } + + public function getServerParams(): array + { + return $this->serverParams; + } + + public function getUploadedFiles(): array + { + return $this->uploadedFiles; + } + + public function withUploadedFiles(array $uploadedFiles): ServerRequestInterface + { + $new = clone $this; + $new->uploadedFiles = $uploadedFiles; + + return $new; + } + + public function getCookieParams(): array + { + return $this->cookieParams; + } + + public function withCookieParams(array $cookies): ServerRequestInterface + { + $new = clone $this; + $new->cookieParams = $cookies; + + return $new; + } + + public function getQueryParams(): array + { + return $this->queryParams; + } + + public function withQueryParams(array $query): ServerRequestInterface + { + $new = clone $this; + $new->queryParams = $query; + + return $new; + } + + /** + * {@inheritdoc} + * + * @return array|object|null + */ + public function getParsedBody() + { + return $this->parsedBody; + } + + public function withParsedBody($data): ServerRequestInterface + { + $new = clone $this; + $new->parsedBody = $data; + + return $new; + } + + public function getAttributes(): array + { + return $this->attributes; + } + + /** + * {@inheritdoc} + * + * @return mixed + */ + public function getAttribute($attribute, $default = null) + { + if (false === array_key_exists($attribute, $this->attributes)) { + return $default; + } + + return $this->attributes[$attribute]; + } + + public function withAttribute($attribute, $value): ServerRequestInterface + { + $new = clone $this; + $new->attributes[$attribute] = $value; + + return $new; + } + + public function withoutAttribute($attribute): ServerRequestInterface + { + if (false === array_key_exists($attribute, $this->attributes)) { + return $this; + } + + $new = clone $this; + unset($new->attributes[$attribute]); + + return $new; + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Stream.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Stream.php new file mode 100644 index 000000000..ecd31861e --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Stream.php @@ -0,0 +1,282 @@ +size = $options['size']; + } + + $this->customMetadata = $options['metadata'] ?? []; + $this->stream = $stream; + $meta = stream_get_meta_data($this->stream); + $this->seekable = $meta['seekable']; + $this->readable = (bool)preg_match(self::READABLE_MODES, $meta['mode']); + $this->writable = (bool)preg_match(self::WRITABLE_MODES, $meta['mode']); + $this->uri = $this->getMetadata('uri'); + } + + /** + * Closes the stream when the destructed + */ + public function __destruct() + { + $this->close(); + } + + public function __toString(): string + { + try { + if ($this->isSeekable()) { + $this->seek(0); + } + return $this->getContents(); + } catch (\Throwable $e) { + if (\PHP_VERSION_ID >= 70400) { + throw $e; + } + trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR); + return ''; + } + } + + public function getContents(): string + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + + if (!$this->readable) { + throw new \RuntimeException('Cannot read from non-readable stream'); + } + + return Utils::tryGetContents($this->stream); + } + + public function close(): void + { + if (isset($this->stream)) { + if (is_resource($this->stream)) { + fclose($this->stream); + } + $this->detach(); + } + } + + public function detach() + { + if (!isset($this->stream)) { + return null; + } + + $result = $this->stream; + unset($this->stream); + $this->size = $this->uri = null; + $this->readable = $this->writable = $this->seekable = false; + + return $result; + } + + public function getSize(): ?int + { + if ($this->size !== null) { + return $this->size; + } + + if (!isset($this->stream)) { + return null; + } + + // Clear the stat cache if the stream has a URI + if ($this->uri) { + clearstatcache(true, $this->uri); + } + + $stats = fstat($this->stream); + if (is_array($stats) && isset($stats['size'])) { + $this->size = $stats['size']; + return $this->size; + } + + return null; + } + + public function isReadable(): bool + { + return $this->readable; + } + + public function isWritable(): bool + { + return $this->writable; + } + + public function isSeekable(): bool + { + return $this->seekable; + } + + public function eof(): bool + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + + return feof($this->stream); + } + + public function tell(): int + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + + $result = ftell($this->stream); + + if ($result === false) { + throw new \RuntimeException('Unable to determine stream position'); + } + + return $result; + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET): void + { + $whence = (int) $whence; + + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + if (!$this->seekable) { + throw new \RuntimeException('Stream is not seekable'); + } + if (fseek($this->stream, $offset, $whence) === -1) { + throw new \RuntimeException('Unable to seek to stream position ' + . $offset . ' with whence ' . var_export($whence, true)); + } + } + + public function read($length): string + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + if (!$this->readable) { + throw new \RuntimeException('Cannot read from non-readable stream'); + } + if ($length < 0) { + throw new \RuntimeException('Length parameter cannot be negative'); + } + + if (0 === $length) { + return ''; + } + + try { + $string = fread($this->stream, $length); + } catch (\Exception $e) { + throw new \RuntimeException('Unable to read from stream', 0, $e); + } + + if (false === $string) { + throw new \RuntimeException('Unable to read from stream'); + } + + return $string; + } + + public function write($string): int + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + if (!$this->writable) { + throw new \RuntimeException('Cannot write to a non-writable stream'); + } + + // We can't know the size after writing anything + $this->size = null; + $result = fwrite($this->stream, $string); + + if ($result === false) { + throw new \RuntimeException('Unable to write to stream'); + } + + return $result; + } + + /** + * {@inheritdoc} + * + * @return mixed + */ + public function getMetadata($key = null) + { + if (!isset($this->stream)) { + return $key ? null : []; + } elseif (!$key) { + return $this->customMetadata + stream_get_meta_data($this->stream); + } elseif (isset($this->customMetadata[$key])) { + return $this->customMetadata[$key]; + } + + $meta = stream_get_meta_data($this->stream); + + return $meta[$key] ?? null; + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php new file mode 100644 index 000000000..56d4104d4 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php @@ -0,0 +1,155 @@ +stream = $stream; + } + + /** + * Magic method used to create a new stream if streams are not added in + * the constructor of a decorator (e.g., LazyOpenStream). + * + * @return StreamInterface + */ + public function __get(string $name) + { + if ($name === 'stream') { + $this->stream = $this->createStream(); + return $this->stream; + } + + throw new \UnexpectedValueException("$name not found on class"); + } + + public function __toString(): string + { + try { + if ($this->isSeekable()) { + $this->seek(0); + } + return $this->getContents(); + } catch (\Throwable $e) { + if (\PHP_VERSION_ID >= 70400) { + throw $e; + } + trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR); + return ''; + } + } + + public function getContents(): string + { + return Utils::copyToString($this); + } + + /** + * Allow decorators to implement custom methods + * + * @return mixed + */ + public function __call(string $method, array $args) + { + /** @var callable $callable */ + $callable = [$this->stream, $method]; + $result = call_user_func_array($callable, $args); + + // Always return the wrapped object if the result is a return $this + return $result === $this->stream ? $this : $result; + } + + public function close(): void + { + $this->stream->close(); + } + + /** + * {@inheritdoc} + * + * @return mixed + */ + public function getMetadata($key = null) + { + return $this->stream->getMetadata($key); + } + + public function detach() + { + return $this->stream->detach(); + } + + public function getSize(): ?int + { + return $this->stream->getSize(); + } + + public function eof(): bool + { + return $this->stream->eof(); + } + + public function tell(): int + { + return $this->stream->tell(); + } + + public function isReadable(): bool + { + return $this->stream->isReadable(); + } + + public function isWritable(): bool + { + return $this->stream->isWritable(); + } + + public function isSeekable(): bool + { + return $this->stream->isSeekable(); + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET): void + { + $this->stream->seek($offset, $whence); + } + + public function read($length): string + { + return $this->stream->read($length); + } + + public function write($string): int + { + return $this->stream->write($string); + } + + /** + * Implement in subclasses to dynamically create streams when requested. + * + * @throws \BadMethodCallException + */ + protected function createStream(): StreamInterface + { + throw new \BadMethodCallException('Not implemented'); + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/StreamWrapper.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/StreamWrapper.php new file mode 100644 index 000000000..2a9346403 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/StreamWrapper.php @@ -0,0 +1,175 @@ +isReadable()) { + $mode = $stream->isWritable() ? 'r+' : 'r'; + } elseif ($stream->isWritable()) { + $mode = 'w'; + } else { + throw new \InvalidArgumentException('The stream must be readable, ' + . 'writable, or both.'); + } + + return fopen('guzzle://stream', $mode, false, self::createStreamContext($stream)); + } + + /** + * Creates a stream context that can be used to open a stream as a php stream resource. + * + * @return resource + */ + public static function createStreamContext(StreamInterface $stream) + { + return stream_context_create([ + 'guzzle' => ['stream' => $stream] + ]); + } + + /** + * Registers the stream wrapper if needed + */ + public static function register(): void + { + if (!in_array('guzzle', stream_get_wrappers())) { + stream_wrapper_register('guzzle', __CLASS__); + } + } + + public function stream_open(string $path, string $mode, int $options, string &$opened_path = null): bool + { + $options = stream_context_get_options($this->context); + + if (!isset($options['guzzle']['stream'])) { + return false; + } + + $this->mode = $mode; + $this->stream = $options['guzzle']['stream']; + + return true; + } + + public function stream_read(int $count): string + { + return $this->stream->read($count); + } + + public function stream_write(string $data): int + { + return $this->stream->write($data); + } + + public function stream_tell(): int + { + return $this->stream->tell(); + } + + public function stream_eof(): bool + { + return $this->stream->eof(); + } + + public function stream_seek(int $offset, int $whence): bool + { + $this->stream->seek($offset, $whence); + + return true; + } + + /** + * @return resource|false + */ + public function stream_cast(int $cast_as) + { + $stream = clone($this->stream); + $resource = $stream->detach(); + + return $resource ?? false; + } + + /** + * @return array + */ + public function stream_stat(): array + { + static $modeMap = [ + 'r' => 33060, + 'rb' => 33060, + 'r+' => 33206, + 'w' => 33188, + 'wb' => 33188 + ]; + + return [ + 'dev' => 0, + 'ino' => 0, + 'mode' => $modeMap[$this->mode], + 'nlink' => 0, + 'uid' => 0, + 'gid' => 0, + 'rdev' => 0, + 'size' => $this->stream->getSize() ?: 0, + 'atime' => 0, + 'mtime' => 0, + 'ctime' => 0, + 'blksize' => 0, + 'blocks' => 0 + ]; + } + + /** + * @return array + */ + public function url_stat(string $path, int $flags): array + { + return [ + 'dev' => 0, + 'ino' => 0, + 'mode' => 0, + 'nlink' => 0, + 'uid' => 0, + 'gid' => 0, + 'rdev' => 0, + 'size' => 0, + 'atime' => 0, + 'mtime' => 0, + 'ctime' => 0, + 'blksize' => 0, + 'blocks' => 0 + ]; + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/UploadedFile.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/UploadedFile.php new file mode 100644 index 000000000..b1521bcf8 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/UploadedFile.php @@ -0,0 +1,211 @@ +setError($errorStatus); + $this->size = $size; + $this->clientFilename = $clientFilename; + $this->clientMediaType = $clientMediaType; + + if ($this->isOk()) { + $this->setStreamOrFile($streamOrFile); + } + } + + /** + * Depending on the value set file or stream variable + * + * @param StreamInterface|string|resource $streamOrFile + * + * @throws InvalidArgumentException + */ + private function setStreamOrFile($streamOrFile): void + { + if (is_string($streamOrFile)) { + $this->file = $streamOrFile; + } elseif (is_resource($streamOrFile)) { + $this->stream = new Stream($streamOrFile); + } elseif ($streamOrFile instanceof StreamInterface) { + $this->stream = $streamOrFile; + } else { + throw new InvalidArgumentException( + 'Invalid stream or file provided for UploadedFile' + ); + } + } + + /** + * @throws InvalidArgumentException + */ + private function setError(int $error): void + { + if (false === in_array($error, UploadedFile::ERRORS, true)) { + throw new InvalidArgumentException( + 'Invalid error status for UploadedFile' + ); + } + + $this->error = $error; + } + + private function isStringNotEmpty($param): bool + { + return is_string($param) && false === empty($param); + } + + /** + * Return true if there is no upload error + */ + private function isOk(): bool + { + return $this->error === UPLOAD_ERR_OK; + } + + public function isMoved(): bool + { + return $this->moved; + } + + /** + * @throws RuntimeException if is moved or not ok + */ + private function validateActive(): void + { + if (false === $this->isOk()) { + throw new RuntimeException('Cannot retrieve stream due to upload error'); + } + + if ($this->isMoved()) { + throw new RuntimeException('Cannot retrieve stream after it has already been moved'); + } + } + + public function getStream(): StreamInterface + { + $this->validateActive(); + + if ($this->stream instanceof StreamInterface) { + return $this->stream; + } + + /** @var string $file */ + $file = $this->file; + + return new LazyOpenStream($file, 'r+'); + } + + public function moveTo($targetPath): void + { + $this->validateActive(); + + if (false === $this->isStringNotEmpty($targetPath)) { + throw new InvalidArgumentException( + 'Invalid path provided for move operation; must be a non-empty string' + ); + } + + if ($this->file) { + $this->moved = PHP_SAPI === 'cli' + ? rename($this->file, $targetPath) + : move_uploaded_file($this->file, $targetPath); + } else { + Utils::copyToStream( + $this->getStream(), + new LazyOpenStream($targetPath, 'w') + ); + + $this->moved = true; + } + + if (false === $this->moved) { + throw new RuntimeException( + sprintf('Uploaded file could not be moved to %s', $targetPath) + ); + } + } + + public function getSize(): ?int + { + return $this->size; + } + + public function getError(): int + { + return $this->error; + } + + public function getClientFilename(): ?string + { + return $this->clientFilename; + } + + public function getClientMediaType(): ?string + { + return $this->clientMediaType; + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Uri.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Uri.php new file mode 100644 index 000000000..09e878d3d --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Uri.php @@ -0,0 +1,740 @@ + 80, + 'https' => 443, + 'ftp' => 21, + 'gopher' => 70, + 'nntp' => 119, + 'news' => 119, + 'telnet' => 23, + 'tn3270' => 23, + 'imap' => 143, + 'pop' => 110, + 'ldap' => 389, + ]; + + /** + * Unreserved characters for use in a regex. + * + * @link https://tools.ietf.org/html/rfc3986#section-2.3 + */ + private const CHAR_UNRESERVED = 'a-zA-Z0-9_\-\.~'; + + /** + * Sub-delims for use in a regex. + * + * @link https://tools.ietf.org/html/rfc3986#section-2.2 + */ + private const CHAR_SUB_DELIMS = '!\$&\'\(\)\*\+,;='; + private const QUERY_SEPARATORS_REPLACEMENT = ['=' => '%3D', '&' => '%26']; + + /** @var string Uri scheme. */ + private $scheme = ''; + + /** @var string Uri user info. */ + private $userInfo = ''; + + /** @var string Uri host. */ + private $host = ''; + + /** @var int|null Uri port. */ + private $port; + + /** @var string Uri path. */ + private $path = ''; + + /** @var string Uri query string. */ + private $query = ''; + + /** @var string Uri fragment. */ + private $fragment = ''; + + /** @var string|null String representation */ + private $composedComponents; + + public function __construct(string $uri = '') + { + if ($uri !== '') { + $parts = self::parse($uri); + if ($parts === false) { + throw new MalformedUriException("Unable to parse URI: $uri"); + } + $this->applyParts($parts); + } + } + /** + * UTF-8 aware \parse_url() replacement. + * + * The internal function produces broken output for non ASCII domain names + * (IDN) when used with locales other than "C". + * + * On the other hand, cURL understands IDN correctly only when UTF-8 locale + * is configured ("C.UTF-8", "en_US.UTF-8", etc.). + * + * @see https://bugs.php.net/bug.php?id=52923 + * @see https://www.php.net/manual/en/function.parse-url.php#114817 + * @see https://curl.haxx.se/libcurl/c/CURLOPT_URL.html#ENCODING + * + * @return array|false + */ + private static function parse(string $url) + { + // If IPv6 + $prefix = ''; + if (preg_match('%^(.*://\[[0-9:a-f]+\])(.*?)$%', $url, $matches)) { + /** @var array{0:string, 1:string, 2:string} $matches */ + $prefix = $matches[1]; + $url = $matches[2]; + } + + /** @var string */ + $encodedUrl = preg_replace_callback( + '%[^:/@?&=#]+%usD', + static function ($matches) { + return urlencode($matches[0]); + }, + $url + ); + + $result = parse_url($prefix . $encodedUrl); + + if ($result === false) { + return false; + } + + return array_map('urldecode', $result); + } + + public function __toString(): string + { + if ($this->composedComponents === null) { + $this->composedComponents = self::composeComponents( + $this->scheme, + $this->getAuthority(), + $this->path, + $this->query, + $this->fragment + ); + } + + return $this->composedComponents; + } + + /** + * Composes a URI reference string from its various components. + * + * Usually this method does not need to be called manually but instead is used indirectly via + * `Psr\Http\Message\UriInterface::__toString`. + * + * PSR-7 UriInterface treats an empty component the same as a missing component as + * getQuery(), getFragment() etc. always return a string. This explains the slight + * difference to RFC 3986 Section 5.3. + * + * Another adjustment is that the authority separator is added even when the authority is missing/empty + * for the "file" scheme. This is because PHP stream functions like `file_get_contents` only work with + * `file:///myfile` but not with `file:/myfile` although they are equivalent according to RFC 3986. But + * `file:///` is the more common syntax for the file scheme anyway (Chrome for example redirects to + * that format). + * + * @link https://tools.ietf.org/html/rfc3986#section-5.3 + */ + public static function composeComponents(?string $scheme, ?string $authority, string $path, ?string $query, ?string $fragment): string + { + $uri = ''; + + // weak type checks to also accept null until we can add scalar type hints + if ($scheme != '') { + $uri .= $scheme . ':'; + } + + if ($authority != '' || $scheme === 'file') { + $uri .= '//' . $authority; + } + + if ($authority != '' && $path != '' && $path[0] != '/') { + $path = '/' . $path; + } + + $uri .= $path; + + if ($query != '') { + $uri .= '?' . $query; + } + + if ($fragment != '') { + $uri .= '#' . $fragment; + } + + return $uri; + } + + /** + * Whether the URI has the default port of the current scheme. + * + * `Psr\Http\Message\UriInterface::getPort` may return null or the standard port. This method can be used + * independently of the implementation. + */ + public static function isDefaultPort(UriInterface $uri): bool + { + return $uri->getPort() === null + || (isset(self::DEFAULT_PORTS[$uri->getScheme()]) && $uri->getPort() === self::DEFAULT_PORTS[$uri->getScheme()]); + } + + /** + * Whether the URI is absolute, i.e. it has a scheme. + * + * An instance of UriInterface can either be an absolute URI or a relative reference. This method returns true + * if it is the former. An absolute URI has a scheme. A relative reference is used to express a URI relative + * to another URI, the base URI. Relative references can be divided into several forms: + * - network-path references, e.g. '//example.com/path' + * - absolute-path references, e.g. '/path' + * - relative-path references, e.g. 'subpath' + * + * @see Uri::isNetworkPathReference + * @see Uri::isAbsolutePathReference + * @see Uri::isRelativePathReference + * @link https://tools.ietf.org/html/rfc3986#section-4 + */ + public static function isAbsolute(UriInterface $uri): bool + { + return $uri->getScheme() !== ''; + } + + /** + * Whether the URI is a network-path reference. + * + * A relative reference that begins with two slash characters is termed an network-path reference. + * + * @link https://tools.ietf.org/html/rfc3986#section-4.2 + */ + public static function isNetworkPathReference(UriInterface $uri): bool + { + return $uri->getScheme() === '' && $uri->getAuthority() !== ''; + } + + /** + * Whether the URI is a absolute-path reference. + * + * A relative reference that begins with a single slash character is termed an absolute-path reference. + * + * @link https://tools.ietf.org/html/rfc3986#section-4.2 + */ + public static function isAbsolutePathReference(UriInterface $uri): bool + { + return $uri->getScheme() === '' + && $uri->getAuthority() === '' + && isset($uri->getPath()[0]) + && $uri->getPath()[0] === '/'; + } + + /** + * Whether the URI is a relative-path reference. + * + * A relative reference that does not begin with a slash character is termed a relative-path reference. + * + * @link https://tools.ietf.org/html/rfc3986#section-4.2 + */ + public static function isRelativePathReference(UriInterface $uri): bool + { + return $uri->getScheme() === '' + && $uri->getAuthority() === '' + && (!isset($uri->getPath()[0]) || $uri->getPath()[0] !== '/'); + } + + /** + * Whether the URI is a same-document reference. + * + * A same-document reference refers to a URI that is, aside from its fragment + * component, identical to the base URI. When no base URI is given, only an empty + * URI reference (apart from its fragment) is considered a same-document reference. + * + * @param UriInterface $uri The URI to check + * @param UriInterface|null $base An optional base URI to compare against + * + * @link https://tools.ietf.org/html/rfc3986#section-4.4 + */ + public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null): bool + { + if ($base !== null) { + $uri = UriResolver::resolve($base, $uri); + + return ($uri->getScheme() === $base->getScheme()) + && ($uri->getAuthority() === $base->getAuthority()) + && ($uri->getPath() === $base->getPath()) + && ($uri->getQuery() === $base->getQuery()); + } + + return $uri->getScheme() === '' && $uri->getAuthority() === '' && $uri->getPath() === '' && $uri->getQuery() === ''; + } + + /** + * Creates a new URI with a specific query string value removed. + * + * Any existing query string values that exactly match the provided key are + * removed. + * + * @param UriInterface $uri URI to use as a base. + * @param string $key Query string key to remove. + */ + public static function withoutQueryValue(UriInterface $uri, string $key): UriInterface + { + $result = self::getFilteredQueryString($uri, [$key]); + + return $uri->withQuery(implode('&', $result)); + } + + /** + * Creates a new URI with a specific query string value. + * + * Any existing query string values that exactly match the provided key are + * removed and replaced with the given key value pair. + * + * A value of null will set the query string key without a value, e.g. "key" + * instead of "key=value". + * + * @param UriInterface $uri URI to use as a base. + * @param string $key Key to set. + * @param string|null $value Value to set + */ + public static function withQueryValue(UriInterface $uri, string $key, ?string $value): UriInterface + { + $result = self::getFilteredQueryString($uri, [$key]); + + $result[] = self::generateQueryString($key, $value); + + return $uri->withQuery(implode('&', $result)); + } + + /** + * Creates a new URI with multiple specific query string values. + * + * It has the same behavior as withQueryValue() but for an associative array of key => value. + * + * @param UriInterface $uri URI to use as a base. + * @param array $keyValueArray Associative array of key and values + */ + public static function withQueryValues(UriInterface $uri, array $keyValueArray): UriInterface + { + $result = self::getFilteredQueryString($uri, array_keys($keyValueArray)); + + foreach ($keyValueArray as $key => $value) { + $result[] = self::generateQueryString((string) $key, $value !== null ? (string) $value : null); + } + + return $uri->withQuery(implode('&', $result)); + } + + /** + * Creates a URI from a hash of `parse_url` components. + * + * @link http://php.net/manual/en/function.parse-url.php + * + * @throws MalformedUriException If the components do not form a valid URI. + */ + public static function fromParts(array $parts): UriInterface + { + $uri = new self(); + $uri->applyParts($parts); + $uri->validateState(); + + return $uri; + } + + public function getScheme(): string + { + return $this->scheme; + } + + public function getAuthority(): string + { + $authority = $this->host; + if ($this->userInfo !== '') { + $authority = $this->userInfo . '@' . $authority; + } + + if ($this->port !== null) { + $authority .= ':' . $this->port; + } + + return $authority; + } + + public function getUserInfo(): string + { + return $this->userInfo; + } + + public function getHost(): string + { + return $this->host; + } + + public function getPort(): ?int + { + return $this->port; + } + + public function getPath(): string + { + return $this->path; + } + + public function getQuery(): string + { + return $this->query; + } + + public function getFragment(): string + { + return $this->fragment; + } + + public function withScheme($scheme): UriInterface + { + $scheme = $this->filterScheme($scheme); + + if ($this->scheme === $scheme) { + return $this; + } + + $new = clone $this; + $new->scheme = $scheme; + $new->composedComponents = null; + $new->removeDefaultPort(); + $new->validateState(); + + return $new; + } + + public function withUserInfo($user, $password = null): UriInterface + { + $info = $this->filterUserInfoComponent($user); + if ($password !== null) { + $info .= ':' . $this->filterUserInfoComponent($password); + } + + if ($this->userInfo === $info) { + return $this; + } + + $new = clone $this; + $new->userInfo = $info; + $new->composedComponents = null; + $new->validateState(); + + return $new; + } + + public function withHost($host): UriInterface + { + $host = $this->filterHost($host); + + if ($this->host === $host) { + return $this; + } + + $new = clone $this; + $new->host = $host; + $new->composedComponents = null; + $new->validateState(); + + return $new; + } + + public function withPort($port): UriInterface + { + $port = $this->filterPort($port); + + if ($this->port === $port) { + return $this; + } + + $new = clone $this; + $new->port = $port; + $new->composedComponents = null; + $new->removeDefaultPort(); + $new->validateState(); + + return $new; + } + + public function withPath($path): UriInterface + { + $path = $this->filterPath($path); + + if ($this->path === $path) { + return $this; + } + + $new = clone $this; + $new->path = $path; + $new->composedComponents = null; + $new->validateState(); + + return $new; + } + + public function withQuery($query): UriInterface + { + $query = $this->filterQueryAndFragment($query); + + if ($this->query === $query) { + return $this; + } + + $new = clone $this; + $new->query = $query; + $new->composedComponents = null; + + return $new; + } + + public function withFragment($fragment): UriInterface + { + $fragment = $this->filterQueryAndFragment($fragment); + + if ($this->fragment === $fragment) { + return $this; + } + + $new = clone $this; + $new->fragment = $fragment; + $new->composedComponents = null; + + return $new; + } + + public function jsonSerialize(): string + { + return $this->__toString(); + } + + /** + * Apply parse_url parts to a URI. + * + * @param array $parts Array of parse_url parts to apply. + */ + private function applyParts(array $parts): void + { + $this->scheme = isset($parts['scheme']) + ? $this->filterScheme($parts['scheme']) + : ''; + $this->userInfo = isset($parts['user']) + ? $this->filterUserInfoComponent($parts['user']) + : ''; + $this->host = isset($parts['host']) + ? $this->filterHost($parts['host']) + : ''; + $this->port = isset($parts['port']) + ? $this->filterPort($parts['port']) + : null; + $this->path = isset($parts['path']) + ? $this->filterPath($parts['path']) + : ''; + $this->query = isset($parts['query']) + ? $this->filterQueryAndFragment($parts['query']) + : ''; + $this->fragment = isset($parts['fragment']) + ? $this->filterQueryAndFragment($parts['fragment']) + : ''; + if (isset($parts['pass'])) { + $this->userInfo .= ':' . $this->filterUserInfoComponent($parts['pass']); + } + + $this->removeDefaultPort(); + } + + /** + * @param mixed $scheme + * + * @throws \InvalidArgumentException If the scheme is invalid. + */ + private function filterScheme($scheme): string + { + if (!is_string($scheme)) { + throw new \InvalidArgumentException('Scheme must be a string'); + } + + return \strtr($scheme, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); + } + + /** + * @param mixed $component + * + * @throws \InvalidArgumentException If the user info is invalid. + */ + private function filterUserInfoComponent($component): string + { + if (!is_string($component)) { + throw new \InvalidArgumentException('User info must be a string'); + } + + return preg_replace_callback( + '/(?:[^%' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . ']+|%(?![A-Fa-f0-9]{2}))/', + [$this, 'rawurlencodeMatchZero'], + $component + ); + } + + /** + * @param mixed $host + * + * @throws \InvalidArgumentException If the host is invalid. + */ + private function filterHost($host): string + { + if (!is_string($host)) { + throw new \InvalidArgumentException('Host must be a string'); + } + + return \strtr($host, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); + } + + /** + * @param mixed $port + * + * @throws \InvalidArgumentException If the port is invalid. + */ + private function filterPort($port): ?int + { + if ($port === null) { + return null; + } + + $port = (int) $port; + if (0 > $port || 0xffff < $port) { + throw new \InvalidArgumentException( + sprintf('Invalid port: %d. Must be between 0 and 65535', $port) + ); + } + + return $port; + } + + /** + * @param string[] $keys + * + * @return string[] + */ + private static function getFilteredQueryString(UriInterface $uri, array $keys): array + { + $current = $uri->getQuery(); + + if ($current === '') { + return []; + } + + $decodedKeys = array_map('rawurldecode', $keys); + + return array_filter(explode('&', $current), function ($part) use ($decodedKeys) { + return !in_array(rawurldecode(explode('=', $part)[0]), $decodedKeys, true); + }); + } + + private static function generateQueryString(string $key, ?string $value): string + { + // Query string separators ("=", "&") within the key or value need to be encoded + // (while preventing double-encoding) before setting the query string. All other + // chars that need percent-encoding will be encoded by withQuery(). + $queryString = strtr($key, self::QUERY_SEPARATORS_REPLACEMENT); + + if ($value !== null) { + $queryString .= '=' . strtr($value, self::QUERY_SEPARATORS_REPLACEMENT); + } + + return $queryString; + } + + private function removeDefaultPort(): void + { + if ($this->port !== null && self::isDefaultPort($this)) { + $this->port = null; + } + } + + /** + * Filters the path of a URI + * + * @param mixed $path + * + * @throws \InvalidArgumentException If the path is invalid. + */ + private function filterPath($path): string + { + if (!is_string($path)) { + throw new \InvalidArgumentException('Path must be a string'); + } + + return preg_replace_callback( + '/(?:[^' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . '%:@\/]++|%(?![A-Fa-f0-9]{2}))/', + [$this, 'rawurlencodeMatchZero'], + $path + ); + } + + /** + * Filters the query string or fragment of a URI. + * + * @param mixed $str + * + * @throws \InvalidArgumentException If the query or fragment is invalid. + */ + private function filterQueryAndFragment($str): string + { + if (!is_string($str)) { + throw new \InvalidArgumentException('Query and fragment must be a string'); + } + + return preg_replace_callback( + '/(?:[^' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . '%:@\/\?]++|%(?![A-Fa-f0-9]{2}))/', + [$this, 'rawurlencodeMatchZero'], + $str + ); + } + + private function rawurlencodeMatchZero(array $match): string + { + return rawurlencode($match[0]); + } + + private function validateState(): void + { + if ($this->host === '' && ($this->scheme === 'http' || $this->scheme === 'https')) { + $this->host = self::HTTP_DEFAULT_HOST; + } + + if ($this->getAuthority() === '') { + if (0 === strpos($this->path, '//')) { + throw new MalformedUriException('The path of a URI without an authority must not start with two slashes "//"'); + } + if ($this->scheme === '' && false !== strpos(explode('/', $this->path, 2)[0], ':')) { + throw new MalformedUriException('A relative URI must not have a path beginning with a segment containing a colon'); + } + } + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/UriComparator.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/UriComparator.php new file mode 100644 index 000000000..70c582aa0 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/UriComparator.php @@ -0,0 +1,52 @@ +getHost(), $modified->getHost()) !== 0) { + return true; + } + + if ($original->getScheme() !== $modified->getScheme()) { + return true; + } + + if (self::computePort($original) !== self::computePort($modified)) { + return true; + } + + return false; + } + + private static function computePort(UriInterface $uri): int + { + $port = $uri->getPort(); + + if (null !== $port) { + return $port; + } + + return 'https' === $uri->getScheme() ? 443 : 80; + } + + private function __construct() + { + // cannot be instantiated + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/UriNormalizer.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/UriNormalizer.php new file mode 100644 index 000000000..e12971edd --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/UriNormalizer.php @@ -0,0 +1,220 @@ +getPath() === '' && + ($uri->getScheme() === 'http' || $uri->getScheme() === 'https') + ) { + $uri = $uri->withPath('/'); + } + + if ($flags & self::REMOVE_DEFAULT_HOST && $uri->getScheme() === 'file' && $uri->getHost() === 'localhost') { + $uri = $uri->withHost(''); + } + + if ($flags & self::REMOVE_DEFAULT_PORT && $uri->getPort() !== null && Uri::isDefaultPort($uri)) { + $uri = $uri->withPort(null); + } + + if ($flags & self::REMOVE_DOT_SEGMENTS && !Uri::isRelativePathReference($uri)) { + $uri = $uri->withPath(UriResolver::removeDotSegments($uri->getPath())); + } + + if ($flags & self::REMOVE_DUPLICATE_SLASHES) { + $uri = $uri->withPath(preg_replace('#//++#', '/', $uri->getPath())); + } + + if ($flags & self::SORT_QUERY_PARAMETERS && $uri->getQuery() !== '') { + $queryKeyValues = explode('&', $uri->getQuery()); + sort($queryKeyValues); + $uri = $uri->withQuery(implode('&', $queryKeyValues)); + } + + return $uri; + } + + /** + * Whether two URIs can be considered equivalent. + * + * Both URIs are normalized automatically before comparison with the given $normalizations bitmask. The method also + * accepts relative URI references and returns true when they are equivalent. This of course assumes they will be + * resolved against the same base URI. If this is not the case, determination of equivalence or difference of + * relative references does not mean anything. + * + * @param UriInterface $uri1 An URI to compare + * @param UriInterface $uri2 An URI to compare + * @param int $normalizations A bitmask of normalizations to apply, see constants + * + * @link https://tools.ietf.org/html/rfc3986#section-6.1 + */ + public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, int $normalizations = self::PRESERVING_NORMALIZATIONS): bool + { + return (string) self::normalize($uri1, $normalizations) === (string) self::normalize($uri2, $normalizations); + } + + private static function capitalizePercentEncoding(UriInterface $uri): UriInterface + { + $regex = '/(?:%[A-Fa-f0-9]{2})++/'; + + $callback = function (array $match) { + return strtoupper($match[0]); + }; + + return + $uri->withPath( + preg_replace_callback($regex, $callback, $uri->getPath()) + )->withQuery( + preg_replace_callback($regex, $callback, $uri->getQuery()) + ); + } + + private static function decodeUnreservedCharacters(UriInterface $uri): UriInterface + { + $regex = '/%(?:2D|2E|5F|7E|3[0-9]|[46][1-9A-F]|[57][0-9A])/i'; + + $callback = function (array $match) { + return rawurldecode($match[0]); + }; + + return + $uri->withPath( + preg_replace_callback($regex, $callback, $uri->getPath()) + )->withQuery( + preg_replace_callback($regex, $callback, $uri->getQuery()) + ); + } + + private function __construct() + { + // cannot be instantiated + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/UriResolver.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/UriResolver.php new file mode 100644 index 000000000..426e5c9ad --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/UriResolver.php @@ -0,0 +1,211 @@ +getScheme() != '') { + return $rel->withPath(self::removeDotSegments($rel->getPath())); + } + + if ($rel->getAuthority() != '') { + $targetAuthority = $rel->getAuthority(); + $targetPath = self::removeDotSegments($rel->getPath()); + $targetQuery = $rel->getQuery(); + } else { + $targetAuthority = $base->getAuthority(); + if ($rel->getPath() === '') { + $targetPath = $base->getPath(); + $targetQuery = $rel->getQuery() != '' ? $rel->getQuery() : $base->getQuery(); + } else { + if ($rel->getPath()[0] === '/') { + $targetPath = $rel->getPath(); + } else { + if ($targetAuthority != '' && $base->getPath() === '') { + $targetPath = '/' . $rel->getPath(); + } else { + $lastSlashPos = strrpos($base->getPath(), '/'); + if ($lastSlashPos === false) { + $targetPath = $rel->getPath(); + } else { + $targetPath = substr($base->getPath(), 0, $lastSlashPos + 1) . $rel->getPath(); + } + } + } + $targetPath = self::removeDotSegments($targetPath); + $targetQuery = $rel->getQuery(); + } + } + + return new Uri(Uri::composeComponents( + $base->getScheme(), + $targetAuthority, + $targetPath, + $targetQuery, + $rel->getFragment() + )); + } + + /** + * Returns the target URI as a relative reference from the base URI. + * + * This method is the counterpart to resolve(): + * + * (string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target)) + * + * One use-case is to use the current request URI as base URI and then generate relative links in your documents + * to reduce the document size or offer self-contained downloadable document archives. + * + * $base = new Uri('http://example.com/a/b/'); + * echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c')); // prints 'c'. + * echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y')); // prints '../x/y'. + * echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'. + * echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // prints '//example.org/a/b/'. + * + * This method also accepts a target that is already relative and will try to relativize it further. Only a + * relative-path reference will be returned as-is. + * + * echo UriResolver::relativize($base, new Uri('/a/b/c')); // prints 'c' as well + */ + public static function relativize(UriInterface $base, UriInterface $target): UriInterface + { + if ($target->getScheme() !== '' && + ($base->getScheme() !== $target->getScheme() || $target->getAuthority() === '' && $base->getAuthority() !== '') + ) { + return $target; + } + + if (Uri::isRelativePathReference($target)) { + // As the target is already highly relative we return it as-is. It would be possible to resolve + // the target with `$target = self::resolve($base, $target);` and then try make it more relative + // by removing a duplicate query. But let's not do that automatically. + return $target; + } + + if ($target->getAuthority() !== '' && $base->getAuthority() !== $target->getAuthority()) { + return $target->withScheme(''); + } + + // We must remove the path before removing the authority because if the path starts with two slashes, the URI + // would turn invalid. And we also cannot set a relative path before removing the authority, as that is also + // invalid. + $emptyPathUri = $target->withScheme('')->withPath('')->withUserInfo('')->withPort(null)->withHost(''); + + if ($base->getPath() !== $target->getPath()) { + return $emptyPathUri->withPath(self::getRelativePath($base, $target)); + } + + if ($base->getQuery() === $target->getQuery()) { + // Only the target fragment is left. And it must be returned even if base and target fragment are the same. + return $emptyPathUri->withQuery(''); + } + + // If the base URI has a query but the target has none, we cannot return an empty path reference as it would + // inherit the base query component when resolving. + if ($target->getQuery() === '') { + $segments = explode('/', $target->getPath()); + /** @var string $lastSegment */ + $lastSegment = end($segments); + + return $emptyPathUri->withPath($lastSegment === '' ? './' : $lastSegment); + } + + return $emptyPathUri; + } + + private static function getRelativePath(UriInterface $base, UriInterface $target): string + { + $sourceSegments = explode('/', $base->getPath()); + $targetSegments = explode('/', $target->getPath()); + array_pop($sourceSegments); + $targetLastSegment = array_pop($targetSegments); + foreach ($sourceSegments as $i => $segment) { + if (isset($targetSegments[$i]) && $segment === $targetSegments[$i]) { + unset($sourceSegments[$i], $targetSegments[$i]); + } else { + break; + } + } + $targetSegments[] = $targetLastSegment; + $relativePath = str_repeat('../', count($sourceSegments)) . implode('/', $targetSegments); + + // A reference to am empty last segment or an empty first sub-segment must be prefixed with "./". + // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used + // as the first segment of a relative-path reference, as it would be mistaken for a scheme name. + if ('' === $relativePath || false !== strpos(explode('/', $relativePath, 2)[0], ':')) { + $relativePath = "./$relativePath"; + } elseif ('/' === $relativePath[0]) { + if ($base->getAuthority() != '' && $base->getPath() === '') { + // In this case an extra slash is added by resolve() automatically. So we must not add one here. + $relativePath = ".$relativePath"; + } else { + $relativePath = "./$relativePath"; + } + } + + return $relativePath; + } + + private function __construct() + { + // cannot be instantiated + } +} diff --git a/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Utils.php b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Utils.php new file mode 100644 index 000000000..3a4cf3946 --- /dev/null +++ b/data/web/inc/lib/vendor/guzzlehttp/psr7/src/Utils.php @@ -0,0 +1,459 @@ + $v) { + if (!is_string($k) || !in_array(strtolower($k), $keys)) { + $result[$k] = $v; + } + } + + return $result; + } + + /** + * Copy the contents of a stream into another stream until the given number + * of bytes have been read. + * + * @param StreamInterface $source Stream to read from + * @param StreamInterface $dest Stream to write to + * @param int $maxLen Maximum number of bytes to read. Pass -1 + * to read the entire stream. + * + * @throws \RuntimeException on error. + */ + public static function copyToStream(StreamInterface $source, StreamInterface $dest, int $maxLen = -1): void + { + $bufferSize = 8192; + + if ($maxLen === -1) { + while (!$source->eof()) { + if (!$dest->write($source->read($bufferSize))) { + break; + } + } + } else { + $remaining = $maxLen; + while ($remaining > 0 && !$source->eof()) { + $buf = $source->read(min($bufferSize, $remaining)); + $len = strlen($buf); + if (!$len) { + break; + } + $remaining -= $len; + $dest->write($buf); + } + } + } + + /** + * Copy the contents of a stream into a string until the given number of + * bytes have been read. + * + * @param StreamInterface $stream Stream to read + * @param int $maxLen Maximum number of bytes to read. Pass -1 + * to read the entire stream. + * + * @throws \RuntimeException on error. + */ + public static function copyToString(StreamInterface $stream, int $maxLen = -1): string + { + $buffer = ''; + + if ($maxLen === -1) { + while (!$stream->eof()) { + $buf = $stream->read(1048576); + if ($buf === '') { + break; + } + $buffer .= $buf; + } + return $buffer; + } + + $len = 0; + while (!$stream->eof() && $len < $maxLen) { + $buf = $stream->read($maxLen - $len); + if ($buf === '') { + break; + } + $buffer .= $buf; + $len = strlen($buffer); + } + + return $buffer; + } + + /** + * Calculate a hash of a stream. + * + * This method reads the entire stream to calculate a rolling hash, based + * on PHP's `hash_init` functions. + * + * @param StreamInterface $stream Stream to calculate the hash for + * @param string $algo Hash algorithm (e.g. md5, crc32, etc) + * @param bool $rawOutput Whether or not to use raw output + * + * @throws \RuntimeException on error. + */ + public static function hash(StreamInterface $stream, string $algo, bool $rawOutput = false): string + { + $pos = $stream->tell(); + + if ($pos > 0) { + $stream->rewind(); + } + + $ctx = hash_init($algo); + while (!$stream->eof()) { + hash_update($ctx, $stream->read(1048576)); + } + + $out = hash_final($ctx, $rawOutput); + $stream->seek($pos); + + return $out; + } + + /** + * Clone and modify a request with the given changes. + * + * This method is useful for reducing the number of clones needed to mutate + * a message. + * + * The changes can be one of: + * - method: (string) Changes the HTTP method. + * - set_headers: (array) Sets the given headers. + * - remove_headers: (array) Remove the given headers. + * - body: (mixed) Sets the given body. + * - uri: (UriInterface) Set the URI. + * - query: (string) Set the query string value of the URI. + * - version: (string) Set the protocol version. + * + * @param RequestInterface $request Request to clone and modify. + * @param array $changes Changes to apply. + */ + public static function modifyRequest(RequestInterface $request, array $changes): RequestInterface + { + if (!$changes) { + return $request; + } + + $headers = $request->getHeaders(); + + if (!isset($changes['uri'])) { + $uri = $request->getUri(); + } else { + // Remove the host header if one is on the URI + if ($host = $changes['uri']->getHost()) { + $changes['set_headers']['Host'] = $host; + + if ($port = $changes['uri']->getPort()) { + $standardPorts = ['http' => 80, 'https' => 443]; + $scheme = $changes['uri']->getScheme(); + if (isset($standardPorts[$scheme]) && $port != $standardPorts[$scheme]) { + $changes['set_headers']['Host'] .= ':' . $port; + } + } + } + $uri = $changes['uri']; + } + + if (!empty($changes['remove_headers'])) { + $headers = self::caselessRemove($changes['remove_headers'], $headers); + } + + if (!empty($changes['set_headers'])) { + $headers = self::caselessRemove(array_keys($changes['set_headers']), $headers); + $headers = $changes['set_headers'] + $headers; + } + + if (isset($changes['query'])) { + $uri = $uri->withQuery($changes['query']); + } + + if ($request instanceof ServerRequestInterface) { + $new = (new ServerRequest( + $changes['method'] ?? $request->getMethod(), + $uri, + $headers, + $changes['body'] ?? $request->getBody(), + $changes['version'] ?? $request->getProtocolVersion(), + $request->getServerParams() + )) + ->withParsedBody($request->getParsedBody()) + ->withQueryParams($request->getQueryParams()) + ->withCookieParams($request->getCookieParams()) + ->withUploadedFiles($request->getUploadedFiles()); + + foreach ($request->getAttributes() as $key => $value) { + $new = $new->withAttribute($key, $value); + } + + return $new; + } + + return new Request( + $changes['method'] ?? $request->getMethod(), + $uri, + $headers, + $changes['body'] ?? $request->getBody(), + $changes['version'] ?? $request->getProtocolVersion() + ); + } + + /** + * Read a line from the stream up to the maximum allowed buffer length. + * + * @param StreamInterface $stream Stream to read from + * @param int|null $maxLength Maximum buffer length + */ + public static function readLine(StreamInterface $stream, ?int $maxLength = null): string + { + $buffer = ''; + $size = 0; + + while (!$stream->eof()) { + if ('' === ($byte = $stream->read(1))) { + return $buffer; + } + $buffer .= $byte; + // Break when a new line is found or the max length - 1 is reached + if ($byte === "\n" || ++$size === $maxLength - 1) { + break; + } + } + + return $buffer; + } + + /** + * Create a new stream based on the input type. + * + * Options is an associative array that can contain the following keys: + * - metadata: Array of custom metadata. + * - size: Size of the stream. + * + * This method accepts the following `$resource` types: + * - `Psr\Http\Message\StreamInterface`: Returns the value as-is. + * - `string`: Creates a stream object that uses the given string as the contents. + * - `resource`: Creates a stream object that wraps the given PHP stream resource. + * - `Iterator`: If the provided value implements `Iterator`, then a read-only + * stream object will be created that wraps the given iterable. Each time the + * stream is read from, data from the iterator will fill a buffer and will be + * continuously called until the buffer is equal to the requested read size. + * Subsequent read calls will first read from the buffer and then call `next` + * on the underlying iterator until it is exhausted. + * - `object` with `__toString()`: If the object has the `__toString()` method, + * the object will be cast to a string and then a stream will be returned that + * uses the string value. + * - `NULL`: When `null` is passed, an empty stream object is returned. + * - `callable` When a callable is passed, a read-only stream object will be + * created that invokes the given callable. The callable is invoked with the + * number of suggested bytes to read. The callable can return any number of + * bytes, but MUST return `false` when there is no more data to return. The + * stream object that wraps the callable will invoke the callable until the + * number of requested bytes are available. Any additional bytes will be + * buffered and used in subsequent reads. + * + * @param resource|string|int|float|bool|StreamInterface|callable|\Iterator|null $resource Entity body data + * @param array{size?: int, metadata?: array} $options Additional options + * + * @throws \InvalidArgumentException if the $resource arg is not valid. + */ + public static function streamFor($resource = '', array $options = []): StreamInterface + { + if (is_scalar($resource)) { + $stream = self::tryFopen('php://temp', 'r+'); + if ($resource !== '') { + fwrite($stream, (string) $resource); + fseek($stream, 0); + } + return new Stream($stream, $options); + } + + switch (gettype($resource)) { + case 'resource': + /* + * The 'php://input' is a special stream with quirks and inconsistencies. + * We avoid using that stream by reading it into php://temp + */ + + /** @var resource $resource */ + if ((\stream_get_meta_data($resource)['uri'] ?? '') === 'php://input') { + $stream = self::tryFopen('php://temp', 'w+'); + stream_copy_to_stream($resource, $stream); + fseek($stream, 0); + $resource = $stream; + } + return new Stream($resource, $options); + case 'object': + /** @var object $resource */ + if ($resource instanceof StreamInterface) { + return $resource; + } elseif ($resource instanceof \Iterator) { + return new PumpStream(function () use ($resource) { + if (!$resource->valid()) { + return false; + } + $result = $resource->current(); + $resource->next(); + return $result; + }, $options); + } elseif (method_exists($resource, '__toString')) { + return self::streamFor((string) $resource, $options); + } + break; + case 'NULL': + return new Stream(self::tryFopen('php://temp', 'r+'), $options); + } + + if (is_callable($resource)) { + return new PumpStream($resource, $options); + } + + throw new \InvalidArgumentException('Invalid resource type: ' . gettype($resource)); + } + + /** + * Safely opens a PHP stream resource using a filename. + * + * When fopen fails, PHP normally raises a warning. This function adds an + * error handler that checks for errors and throws an exception instead. + * + * @param string $filename File to open + * @param string $mode Mode used to open the file + * + * @return resource + * + * @throws \RuntimeException if the file cannot be opened + */ + public static function tryFopen(string $filename, string $mode) + { + $ex = null; + set_error_handler(static function (int $errno, string $errstr) use ($filename, $mode, &$ex): bool { + $ex = new \RuntimeException(sprintf( + 'Unable to open "%s" using mode "%s": %s', + $filename, + $mode, + $errstr + )); + + return true; + }); + + try { + /** @var resource $handle */ + $handle = fopen($filename, $mode); + } catch (\Throwable $e) { + $ex = new \RuntimeException(sprintf( + 'Unable to open "%s" using mode "%s": %s', + $filename, + $mode, + $e->getMessage() + ), 0, $e); + } + + restore_error_handler(); + + if ($ex) { + /** @var $ex \RuntimeException */ + throw $ex; + } + + return $handle; + } + + /** + * Safely gets the contents of a given stream. + * + * When stream_get_contents fails, PHP normally raises a warning. This + * function adds an error handler that checks for errors and throws an + * exception instead. + * + * @param resource $stream + * + * @throws \RuntimeException if the stream cannot be read + */ + public static function tryGetContents($stream): string + { + $ex = null; + set_error_handler(static function (int $errno, string $errstr) use (&$ex): bool { + $ex = new \RuntimeException(sprintf( + 'Unable to read stream contents: %s', + $errstr + )); + + return true; + }); + + try { + /** @var string|false $contents */ + $contents = stream_get_contents($stream); + + if ($contents === false) { + $ex = new \RuntimeException('Unable to read stream contents'); + } + } catch (\Throwable $e) { + $ex = new \RuntimeException(sprintf( + 'Unable to read stream contents: %s', + $e->getMessage() + ), 0, $e); + } + + restore_error_handler(); + + if ($ex) { + /** @var $ex \RuntimeException */ + throw $ex; + } + + return $contents; + } + + /** + * Returns a UriInterface for the given value. + * + * This function accepts a string or UriInterface and returns a + * UriInterface for the given value. If the value is already a + * UriInterface, it is returned as-is. + * + * @param string|UriInterface $uri + * + * @throws \InvalidArgumentException + */ + public static function uriFor($uri): UriInterface + { + if ($uri instanceof UriInterface) { + return $uri; + } + + if (is_string($uri)) { + return new Uri($uri); + } + + throw new \InvalidArgumentException('URI must be a string or UriInterface'); + } +} diff --git a/data/web/inc/lib/vendor/illuminate/contracts/Auth/Access/Gate.php b/data/web/inc/lib/vendor/illuminate/contracts/Auth/Access/Gate.php index b88ab1796..eb605d827 100644 --- a/data/web/inc/lib/vendor/illuminate/contracts/Auth/Access/Gate.php +++ b/data/web/inc/lib/vendor/illuminate/contracts/Auth/Access/Gate.php @@ -57,18 +57,18 @@ interface Gate public function after(callable $callback); /** - * Determine if the given ability should be granted for the current user. + * Determine if all of the given abilities should be granted for the current user. * - * @param string $ability + * @param iterable|string $ability * @param array|mixed $arguments * @return bool */ public function allows($ability, $arguments = []); /** - * Determine if the given ability should be denied for the current user. + * Determine if any of the given abilities should be denied for the current user. * - * @param string $ability + * @param iterable|string $ability * @param array|mixed $arguments * @return bool */ diff --git a/data/web/inc/lib/vendor/illuminate/contracts/Broadcasting/ShouldBeUnique.php b/data/web/inc/lib/vendor/illuminate/contracts/Broadcasting/ShouldBeUnique.php new file mode 100644 index 000000000..c72b7a800 --- /dev/null +++ b/data/web/inc/lib/vendor/illuminate/contracts/Broadcasting/ShouldBeUnique.php @@ -0,0 +1,8 @@ +|CastsAttributes|CastsInboundAttributes */ public static function castUsing(array $arguments); } diff --git a/data/web/inc/lib/vendor/illuminate/contracts/Database/Eloquent/CastsAttributes.php b/data/web/inc/lib/vendor/illuminate/contracts/Database/Eloquent/CastsAttributes.php index 808d005f5..89cec66a7 100644 --- a/data/web/inc/lib/vendor/illuminate/contracts/Database/Eloquent/CastsAttributes.php +++ b/data/web/inc/lib/vendor/illuminate/contracts/Database/Eloquent/CastsAttributes.php @@ -2,6 +2,12 @@ namespace Illuminate\Contracts\Database\Eloquent; +use Illuminate\Database\Eloquent\Model; + +/** + * @template TGet + * @template TSet + */ interface CastsAttributes { /** @@ -10,19 +16,19 @@ interface CastsAttributes * @param \Illuminate\Database\Eloquent\Model $model * @param string $key * @param mixed $value - * @param array $attributes - * @return mixed + * @param array $attributes + * @return TGet|null */ - public function get($model, string $key, $value, array $attributes); + public function get(Model $model, string $key, mixed $value, array $attributes); /** * Transform the attribute to its underlying model values. * * @param \Illuminate\Database\Eloquent\Model $model * @param string $key - * @param mixed $value - * @param array $attributes + * @param TSet|null $value + * @param array $attributes * @return mixed */ - public function set($model, string $key, $value, array $attributes); + public function set(Model $model, string $key, mixed $value, array $attributes); } diff --git a/data/web/inc/lib/vendor/illuminate/contracts/Database/Eloquent/CastsInboundAttributes.php b/data/web/inc/lib/vendor/illuminate/contracts/Database/Eloquent/CastsInboundAttributes.php index 4c7801b58..6a3e2ef18 100644 --- a/data/web/inc/lib/vendor/illuminate/contracts/Database/Eloquent/CastsInboundAttributes.php +++ b/data/web/inc/lib/vendor/illuminate/contracts/Database/Eloquent/CastsInboundAttributes.php @@ -2,6 +2,8 @@ namespace Illuminate\Contracts\Database\Eloquent; +use Illuminate\Database\Eloquent\Model; + interface CastsInboundAttributes { /** @@ -13,5 +15,5 @@ interface CastsInboundAttributes * @param array $attributes * @return mixed */ - public function set($model, string $key, $value, array $attributes); + public function set(Model $model, string $key, mixed $value, array $attributes); } diff --git a/data/web/inc/lib/vendor/illuminate/contracts/Database/Eloquent/SerializesCastableAttributes.php b/data/web/inc/lib/vendor/illuminate/contracts/Database/Eloquent/SerializesCastableAttributes.php index a89f91010..a2ecf16f5 100644 --- a/data/web/inc/lib/vendor/illuminate/contracts/Database/Eloquent/SerializesCastableAttributes.php +++ b/data/web/inc/lib/vendor/illuminate/contracts/Database/Eloquent/SerializesCastableAttributes.php @@ -2,6 +2,8 @@ namespace Illuminate\Contracts\Database\Eloquent; +use Illuminate\Database\Eloquent\Model; + interface SerializesCastableAttributes { /** @@ -13,5 +15,5 @@ interface SerializesCastableAttributes * @param array $attributes * @return mixed */ - public function serialize($model, string $key, $value, array $attributes); + public function serialize(Model $model, string $key, mixed $value, array $attributes); } diff --git a/data/web/inc/lib/vendor/illuminate/contracts/Database/ModelIdentifier.php b/data/web/inc/lib/vendor/illuminate/contracts/Database/ModelIdentifier.php index 9893d280e..aacd18c07 100644 --- a/data/web/inc/lib/vendor/illuminate/contracts/Database/ModelIdentifier.php +++ b/data/web/inc/lib/vendor/illuminate/contracts/Database/ModelIdentifier.php @@ -34,6 +34,13 @@ class ModelIdentifier */ public $connection; + /** + * The class name of the model collection. + * + * @var string|null + */ + public $collectionClass; + /** * Create a new model identifier. * @@ -50,4 +57,17 @@ class ModelIdentifier $this->relations = $relations; $this->connection = $connection; } + + /** + * Specify the collection class that should be used when serializing / restoring collections. + * + * @param string|null $collectionClass + * @return $this + */ + public function useCollectionClass(?string $collectionClass) + { + $this->collectionClass = $collectionClass; + + return $this; + } } diff --git a/data/web/inc/lib/vendor/illuminate/contracts/Database/Query/ConditionExpression.php b/data/web/inc/lib/vendor/illuminate/contracts/Database/Query/ConditionExpression.php new file mode 100644 index 000000000..b2e97a6e8 --- /dev/null +++ b/data/web/inc/lib/vendor/illuminate/contracts/Database/Query/ConditionExpression.php @@ -0,0 +1,7 @@ + + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/data/web/inc/lib/vendor/league/oauth2-client/README.md b/data/web/inc/lib/vendor/league/oauth2-client/README.md new file mode 100644 index 000000000..cbb449d48 --- /dev/null +++ b/data/web/inc/lib/vendor/league/oauth2-client/README.md @@ -0,0 +1,58 @@ +# OAuth 2.0 Client + +This package provides a base for integrating with [OAuth 2.0](http://oauth.net/2/) service providers. + +[![Gitter Chat](https://img.shields.io/badge/gitter-join_chat-brightgreen.svg?style=flat-square)](https://gitter.im/thephpleague/oauth2-client) +[![Source Code](https://img.shields.io/badge/source-thephpleague/oauth2--client-blue.svg?style=flat-square)](https://github.com/thephpleague/oauth2-client) +[![Latest Version](https://img.shields.io/github/release/thephpleague/oauth2-client.svg?style=flat-square)](https://github.com/thephpleague/oauth2-client/releases) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](https://github.com/thephpleague/oauth2-client/blob/master/LICENSE) +[![Build Status](https://img.shields.io/github/actions/workflow/status/thephpleague/oauth2-client/continuous-integration.yml?label=CI&logo=github&style=flat-square)](https://github.com/thephpleague/oauth2-client/actions?query=workflow%3ACI) +[![Codecov Code Coverage](https://img.shields.io/codecov/c/gh/thephpleague/oauth2-client?label=codecov&logo=codecov&style=flat-square)](https://codecov.io/gh/thephpleague/oauth2-client) +[![Total Downloads](https://img.shields.io/packagist/dt/league/oauth2-client.svg?style=flat-square)](https://packagist.org/packages/league/oauth2-client) + +--- + +The OAuth 2.0 login flow, seen commonly around the web in the form of "Connect with Facebook/Google/etc." buttons, is a common integration added to web applications, but it can be tricky and tedious to do right. To help, we've created the `league/oauth2-client` package, which provides a base for integrating with various OAuth 2.0 providers, without overburdening your application with the concerns of [RFC 6749](http://tools.ietf.org/html/rfc6749). + +This OAuth 2.0 client library will work with any OAuth 2.0 provider that conforms to the OAuth 2.0 Authorization Framework. Out-of-the-box, we provide a `GenericProvider` class to connect to any service provider that uses [Bearer tokens](http://tools.ietf.org/html/rfc6750). See our [basic usage guide](https://oauth2-client.thephpleague.com/usage/) for examples using `GenericProvider`. + +Many service providers provide additional functionality above and beyond the OAuth 2.0 specification. For this reason, you may extend and wrap this library to support additional behavior. There are already many [official](https://oauth2-client.thephpleague.com/providers/league/) and [third-party](https://oauth2-client.thephpleague.com/providers/thirdparty/) provider clients available (e.g., Facebook, GitHub, Google, Instagram, LinkedIn, etc.). If your provider isn't in the list, feel free to add it. + +This package is compliant with [PSR-1][], [PSR-2][], [PSR-4][], and [PSR-7][]. If you notice compliance oversights, please send a patch via pull request. If you're interested in contributing to this library, please take a look at our [contributing guidelines](https://github.com/thephpleague/oauth2-client/blob/master/CONTRIBUTING.md). + +## Requirements + +We support the following versions of PHP: + +* PHP 8.1 +* PHP 8.0 +* PHP 7.4 +* PHP 7.3 +* PHP 7.2 +* PHP 7.1 +* PHP 7.0 +* PHP 5.6 + +## Provider Clients + +We provide a list of [official PHP League provider clients](https://oauth2-client.thephpleague.com/providers/league/), as well as [third-party provider clients](https://oauth2-client.thephpleague.com/providers/thirdparty/). + +To build your own provider client, please refer to "[Implementing a Provider Client](https://oauth2-client.thephpleague.com/providers/implementing/)." + +## Usage + +For usage and code examples, check out our [basic usage guide](https://oauth2-client.thephpleague.com/usage/). + +## Contributing + +Please see [our contributing guidelines](https://github.com/thephpleague/oauth2-client/blob/master/CONTRIBUTING.md) for details. + +## License + +The MIT License (MIT). Please see [LICENSE](https://github.com/thephpleague/oauth2-client/blob/master/LICENSE) for more information. + + +[PSR-1]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md +[PSR-2]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md +[PSR-4]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md +[PSR-7]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-7-http-message.md diff --git a/data/web/inc/lib/vendor/league/oauth2-client/composer.json b/data/web/inc/lib/vendor/league/oauth2-client/composer.json new file mode 100644 index 000000000..59201f48f --- /dev/null +++ b/data/web/inc/lib/vendor/league/oauth2-client/composer.json @@ -0,0 +1,58 @@ +{ + "name": "league/oauth2-client", + "description": "OAuth 2.0 Client Library", + "license": "MIT", + "config": { + "sort-packages": true + }, + "require": { + "php": "^5.6 || ^7.0 || ^8.0", + "guzzlehttp/guzzle": "^6.0 || ^7.0", + "paragonie/random_compat": "^1 || ^2 || ^9.99" + }, + "require-dev": { + "mockery/mockery": "^1.3.5", + "php-parallel-lint/php-parallel-lint": "^1.3.1", + "phpunit/phpunit": "^5.7 || ^6.0 || ^9.5", + "squizlabs/php_codesniffer": "^2.3 || ^3.0" + }, + "keywords": [ + "oauth", + "oauth2", + "authorization", + "authentication", + "idp", + "identity", + "sso", + "single sign on" + ], + "authors": [ + { + "name": "Alex Bilbie", + "email": "hello@alexbilbie.com", + "homepage": "http://www.alexbilbie.com", + "role": "Developer" + }, + { + "name": "Woody Gilk", + "homepage": "https://github.com/shadowhand", + "role": "Contributor" + } + + ], + "autoload": { + "psr-4": { + "League\\OAuth2\\Client\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "League\\OAuth2\\Client\\Test\\": "test/src/" + } + }, + "extra": { + "branch-alias": { + "dev-2.x": "2.0.x-dev" + } + } +} diff --git a/data/web/inc/lib/vendor/league/oauth2-client/src/Grant/AbstractGrant.php b/data/web/inc/lib/vendor/league/oauth2-client/src/Grant/AbstractGrant.php new file mode 100644 index 000000000..2c0244ba3 --- /dev/null +++ b/data/web/inc/lib/vendor/league/oauth2-client/src/Grant/AbstractGrant.php @@ -0,0 +1,80 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Grant; + +use League\OAuth2\Client\Tool\RequiredParameterTrait; + +/** + * Represents a type of authorization grant. + * + * An authorization grant is a credential representing the resource + * owner's authorization (to access its protected resources) used by the + * client to obtain an access token. OAuth 2.0 defines four + * grant types -- authorization code, implicit, resource owner password + * credentials, and client credentials -- as well as an extensibility + * mechanism for defining additional types. + * + * @link http://tools.ietf.org/html/rfc6749#section-1.3 Authorization Grant (RFC 6749, §1.3) + */ +abstract class AbstractGrant +{ + use RequiredParameterTrait; + + /** + * Returns the name of this grant, eg. 'grant_name', which is used as the + * grant type when encoding URL query parameters. + * + * @return string + */ + abstract protected function getName(); + + /** + * Returns a list of all required request parameters. + * + * @return array + */ + abstract protected function getRequiredRequestParameters(); + + /** + * Returns this grant's name as its string representation. This allows for + * string interpolation when building URL query parameters. + * + * @return string + */ + public function __toString() + { + return $this->getName(); + } + + /** + * Prepares an access token request's parameters by checking that all + * required parameters are set, then merging with any given defaults. + * + * @param array $defaults + * @param array $options + * @return array + */ + public function prepareRequestParameters(array $defaults, array $options) + { + $defaults['grant_type'] = $this->getName(); + + $required = $this->getRequiredRequestParameters(); + $provided = array_merge($defaults, $options); + + $this->checkRequiredParameters($required, $provided); + + return $provided; + } +} diff --git a/data/web/inc/lib/vendor/league/oauth2-client/src/Grant/AuthorizationCode.php b/data/web/inc/lib/vendor/league/oauth2-client/src/Grant/AuthorizationCode.php new file mode 100644 index 000000000..c49460c02 --- /dev/null +++ b/data/web/inc/lib/vendor/league/oauth2-client/src/Grant/AuthorizationCode.php @@ -0,0 +1,41 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Grant; + +/** + * Represents an authorization code grant. + * + * @link http://tools.ietf.org/html/rfc6749#section-1.3.1 Authorization Code (RFC 6749, §1.3.1) + */ +class AuthorizationCode extends AbstractGrant +{ + /** + * @inheritdoc + */ + protected function getName() + { + return 'authorization_code'; + } + + /** + * @inheritdoc + */ + protected function getRequiredRequestParameters() + { + return [ + 'code', + ]; + } +} diff --git a/data/web/inc/lib/vendor/league/oauth2-client/src/Grant/ClientCredentials.php b/data/web/inc/lib/vendor/league/oauth2-client/src/Grant/ClientCredentials.php new file mode 100644 index 000000000..dc78c4fda --- /dev/null +++ b/data/web/inc/lib/vendor/league/oauth2-client/src/Grant/ClientCredentials.php @@ -0,0 +1,39 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Grant; + +/** + * Represents a client credentials grant. + * + * @link http://tools.ietf.org/html/rfc6749#section-1.3.4 Client Credentials (RFC 6749, §1.3.4) + */ +class ClientCredentials extends AbstractGrant +{ + /** + * @inheritdoc + */ + protected function getName() + { + return 'client_credentials'; + } + + /** + * @inheritdoc + */ + protected function getRequiredRequestParameters() + { + return []; + } +} diff --git a/data/web/inc/lib/vendor/league/oauth2-client/src/Grant/Exception/InvalidGrantException.php b/data/web/inc/lib/vendor/league/oauth2-client/src/Grant/Exception/InvalidGrantException.php new file mode 100644 index 000000000..c3c4e677b --- /dev/null +++ b/data/web/inc/lib/vendor/league/oauth2-client/src/Grant/Exception/InvalidGrantException.php @@ -0,0 +1,26 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Grant\Exception; + +use InvalidArgumentException; + +/** + * Exception thrown if the grant does not extend from AbstractGrant. + * + * @see League\OAuth2\Client\Grant\AbstractGrant + */ +class InvalidGrantException extends InvalidArgumentException +{ +} diff --git a/data/web/inc/lib/vendor/league/oauth2-client/src/Grant/GrantFactory.php b/data/web/inc/lib/vendor/league/oauth2-client/src/Grant/GrantFactory.php new file mode 100644 index 000000000..71990e83d --- /dev/null +++ b/data/web/inc/lib/vendor/league/oauth2-client/src/Grant/GrantFactory.php @@ -0,0 +1,104 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Grant; + +use League\OAuth2\Client\Grant\Exception\InvalidGrantException; + +/** + * Represents a factory used when retrieving an authorization grant type. + */ +class GrantFactory +{ + /** + * @var array + */ + protected $registry = []; + + /** + * Defines a grant singleton in the registry. + * + * @param string $name + * @param AbstractGrant $grant + * @return self + */ + public function setGrant($name, AbstractGrant $grant) + { + $this->registry[$name] = $grant; + + return $this; + } + + /** + * Returns a grant singleton by name. + * + * If the grant has not be registered, a default grant will be loaded. + * + * @param string $name + * @return AbstractGrant + */ + public function getGrant($name) + { + if (empty($this->registry[$name])) { + $this->registerDefaultGrant($name); + } + + return $this->registry[$name]; + } + + /** + * Registers a default grant singleton by name. + * + * @param string $name + * @return self + */ + protected function registerDefaultGrant($name) + { + // PascalCase the grant. E.g: 'authorization_code' becomes 'AuthorizationCode' + $class = str_replace(' ', '', ucwords(str_replace(['-', '_'], ' ', $name))); + $class = 'League\\OAuth2\\Client\\Grant\\' . $class; + + $this->checkGrant($class); + + return $this->setGrant($name, new $class); + } + + /** + * Determines if a variable is a valid grant. + * + * @param mixed $class + * @return boolean + */ + public function isGrant($class) + { + return is_subclass_of($class, AbstractGrant::class); + } + + /** + * Checks if a variable is a valid grant. + * + * @throws InvalidGrantException + * @param mixed $class + * @return void + */ + public function checkGrant($class) + { + if (!$this->isGrant($class)) { + throw new InvalidGrantException(sprintf( + 'Grant "%s" must extend AbstractGrant', + is_object($class) ? get_class($class) : $class + )); + } + } +} diff --git a/data/web/inc/lib/vendor/league/oauth2-client/src/Grant/Password.php b/data/web/inc/lib/vendor/league/oauth2-client/src/Grant/Password.php new file mode 100644 index 000000000..6543b2ebd --- /dev/null +++ b/data/web/inc/lib/vendor/league/oauth2-client/src/Grant/Password.php @@ -0,0 +1,42 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Grant; + +/** + * Represents a resource owner password credentials grant. + * + * @link http://tools.ietf.org/html/rfc6749#section-1.3.3 Resource Owner Password Credentials (RFC 6749, §1.3.3) + */ +class Password extends AbstractGrant +{ + /** + * @inheritdoc + */ + protected function getName() + { + return 'password'; + } + + /** + * @inheritdoc + */ + protected function getRequiredRequestParameters() + { + return [ + 'username', + 'password', + ]; + } +} diff --git a/data/web/inc/lib/vendor/league/oauth2-client/src/Grant/RefreshToken.php b/data/web/inc/lib/vendor/league/oauth2-client/src/Grant/RefreshToken.php new file mode 100644 index 000000000..819218230 --- /dev/null +++ b/data/web/inc/lib/vendor/league/oauth2-client/src/Grant/RefreshToken.php @@ -0,0 +1,41 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Grant; + +/** + * Represents a refresh token grant. + * + * @link http://tools.ietf.org/html/rfc6749#section-6 Refreshing an Access Token (RFC 6749, §6) + */ +class RefreshToken extends AbstractGrant +{ + /** + * @inheritdoc + */ + protected function getName() + { + return 'refresh_token'; + } + + /** + * @inheritdoc + */ + protected function getRequiredRequestParameters() + { + return [ + 'refresh_token', + ]; + } +} diff --git a/data/web/inc/lib/vendor/league/oauth2-client/src/OptionProvider/HttpBasicAuthOptionProvider.php b/data/web/inc/lib/vendor/league/oauth2-client/src/OptionProvider/HttpBasicAuthOptionProvider.php new file mode 100644 index 000000000..3da406568 --- /dev/null +++ b/data/web/inc/lib/vendor/league/oauth2-client/src/OptionProvider/HttpBasicAuthOptionProvider.php @@ -0,0 +1,42 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\OptionProvider; + +use InvalidArgumentException; + +/** + * Add http basic auth into access token request options + * @link https://tools.ietf.org/html/rfc6749#section-2.3.1 + */ +class HttpBasicAuthOptionProvider extends PostAuthOptionProvider +{ + /** + * @inheritdoc + */ + public function getAccessTokenOptions($method, array $params) + { + if (empty($params['client_id']) || empty($params['client_secret'])) { + throw new InvalidArgumentException('clientId and clientSecret are required for http basic auth'); + } + + $encodedCredentials = base64_encode(sprintf('%s:%s', $params['client_id'], $params['client_secret'])); + unset($params['client_id'], $params['client_secret']); + + $options = parent::getAccessTokenOptions($method, $params); + $options['headers']['Authorization'] = 'Basic ' . $encodedCredentials; + + return $options; + } +} diff --git a/data/web/inc/lib/vendor/league/oauth2-client/src/OptionProvider/OptionProviderInterface.php b/data/web/inc/lib/vendor/league/oauth2-client/src/OptionProvider/OptionProviderInterface.php new file mode 100644 index 000000000..1126d25aa --- /dev/null +++ b/data/web/inc/lib/vendor/league/oauth2-client/src/OptionProvider/OptionProviderInterface.php @@ -0,0 +1,30 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\OptionProvider; + +/** + * Interface for access token options provider + */ +interface OptionProviderInterface +{ + /** + * Builds request options used for requesting an access token. + * + * @param string $method + * @param array $params + * @return array + */ + public function getAccessTokenOptions($method, array $params); +} diff --git a/data/web/inc/lib/vendor/league/oauth2-client/src/OptionProvider/PostAuthOptionProvider.php b/data/web/inc/lib/vendor/league/oauth2-client/src/OptionProvider/PostAuthOptionProvider.php new file mode 100644 index 000000000..12d920ecf --- /dev/null +++ b/data/web/inc/lib/vendor/league/oauth2-client/src/OptionProvider/PostAuthOptionProvider.php @@ -0,0 +1,51 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\OptionProvider; + +use League\OAuth2\Client\Provider\AbstractProvider; +use League\OAuth2\Client\Tool\QueryBuilderTrait; + +/** + * Provide options for access token + */ +class PostAuthOptionProvider implements OptionProviderInterface +{ + use QueryBuilderTrait; + + /** + * @inheritdoc + */ + public function getAccessTokenOptions($method, array $params) + { + $options = ['headers' => ['content-type' => 'application/x-www-form-urlencoded']]; + + if ($method === AbstractProvider::METHOD_POST) { + $options['body'] = $this->getAccessTokenBody($params); + } + + return $options; + } + + /** + * Returns the request body for requesting an access token. + * + * @param array $params + * @return string + */ + protected function getAccessTokenBody(array $params) + { + return $this->buildQueryString($params); + } +} diff --git a/data/web/inc/lib/vendor/league/oauth2-client/src/Provider/AbstractProvider.php b/data/web/inc/lib/vendor/league/oauth2-client/src/Provider/AbstractProvider.php new file mode 100644 index 000000000..293a54d6e --- /dev/null +++ b/data/web/inc/lib/vendor/league/oauth2-client/src/Provider/AbstractProvider.php @@ -0,0 +1,941 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Provider; + +use GuzzleHttp\Client as HttpClient; +use GuzzleHttp\ClientInterface as HttpClientInterface; +use GuzzleHttp\Exception\BadResponseException; +use InvalidArgumentException; +use League\OAuth2\Client\Grant\AbstractGrant; +use League\OAuth2\Client\Grant\GrantFactory; +use League\OAuth2\Client\OptionProvider\OptionProviderInterface; +use League\OAuth2\Client\OptionProvider\PostAuthOptionProvider; +use League\OAuth2\Client\Provider\Exception\IdentityProviderException; +use League\OAuth2\Client\Token\AccessToken; +use League\OAuth2\Client\Token\AccessTokenInterface; +use League\OAuth2\Client\Tool\ArrayAccessorTrait; +use League\OAuth2\Client\Tool\GuardedPropertyTrait; +use League\OAuth2\Client\Tool\QueryBuilderTrait; +use League\OAuth2\Client\Tool\RequestFactory; +use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; +use UnexpectedValueException; + +/** + * Represents a service provider (authorization server). + * + * @link http://tools.ietf.org/html/rfc6749#section-1.1 Roles (RFC 6749, §1.1) + */ +abstract class AbstractProvider +{ + use ArrayAccessorTrait; + use GuardedPropertyTrait; + use QueryBuilderTrait; + + /** + * @var string|null Key used in a token response to identify the resource owner. + */ + const ACCESS_TOKEN_RESOURCE_OWNER_ID = null; + + /** + * @var string HTTP method used to fetch access tokens. + */ + const METHOD_GET = 'GET'; + + /** + * @var string HTTP method used to fetch access tokens. + */ + const METHOD_POST = 'POST'; + + /** + * @var string PKCE method used to fetch authorization token. + * The PKCE code challenge will be hashed with sha256 (recommended). + */ + const PKCE_METHOD_S256 = 'S256'; + + /** + * @var string PKCE method used to fetch authorization token. + * The PKCE code challenge will be sent as plain text, this is NOT recommended. + * Only use `plain` if no other option is possible. + */ + const PKCE_METHOD_PLAIN = 'plain'; + + /** + * @var string + */ + protected $clientId; + + /** + * @var string + */ + protected $clientSecret; + + /** + * @var string + */ + protected $redirectUri; + + /** + * @var string + */ + protected $state; + + /** + * @var string|null + */ + protected $pkceCode = null; + + /** + * @var GrantFactory + */ + protected $grantFactory; + + /** + * @var RequestFactory + */ + protected $requestFactory; + + /** + * @var HttpClientInterface + */ + protected $httpClient; + + /** + * @var OptionProviderInterface + */ + protected $optionProvider; + + /** + * Constructs an OAuth 2.0 service provider. + * + * @param array $options An array of options to set on this provider. + * Options include `clientId`, `clientSecret`, `redirectUri`, and `state`. + * Individual providers may introduce more options, as needed. + * @param array $collaborators An array of collaborators that may be used to + * override this provider's default behavior. Collaborators include + * `grantFactory`, `requestFactory`, and `httpClient`. + * Individual providers may introduce more collaborators, as needed. + */ + public function __construct(array $options = [], array $collaborators = []) + { + // We'll let the GuardedPropertyTrait handle mass assignment of incoming + // options, skipping any blacklisted properties defined in the provider + $this->fillProperties($options); + + if (empty($collaborators['grantFactory'])) { + $collaborators['grantFactory'] = new GrantFactory(); + } + $this->setGrantFactory($collaborators['grantFactory']); + + if (empty($collaborators['requestFactory'])) { + $collaborators['requestFactory'] = new RequestFactory(); + } + $this->setRequestFactory($collaborators['requestFactory']); + + if (empty($collaborators['httpClient'])) { + $client_options = $this->getAllowedClientOptions($options); + + $collaborators['httpClient'] = new HttpClient( + array_intersect_key($options, array_flip($client_options)) + ); + } + $this->setHttpClient($collaborators['httpClient']); + + if (empty($collaborators['optionProvider'])) { + $collaborators['optionProvider'] = new PostAuthOptionProvider(); + } + $this->setOptionProvider($collaborators['optionProvider']); + } + + /** + * Returns the list of options that can be passed to the HttpClient + * + * @param array $options An array of options to set on this provider. + * Options include `clientId`, `clientSecret`, `redirectUri`, and `state`. + * Individual providers may introduce more options, as needed. + * @return array The options to pass to the HttpClient constructor + */ + protected function getAllowedClientOptions(array $options) + { + $client_options = ['timeout', 'proxy']; + + // Only allow turning off ssl verification if it's for a proxy + if (!empty($options['proxy'])) { + $client_options[] = 'verify'; + } + + return $client_options; + } + + /** + * Sets the grant factory instance. + * + * @param GrantFactory $factory + * @return self + */ + public function setGrantFactory(GrantFactory $factory) + { + $this->grantFactory = $factory; + + return $this; + } + + /** + * Returns the current grant factory instance. + * + * @return GrantFactory + */ + public function getGrantFactory() + { + return $this->grantFactory; + } + + /** + * Sets the request factory instance. + * + * @param RequestFactory $factory + * @return self + */ + public function setRequestFactory(RequestFactory $factory) + { + $this->requestFactory = $factory; + + return $this; + } + + /** + * Returns the request factory instance. + * + * @return RequestFactory + */ + public function getRequestFactory() + { + return $this->requestFactory; + } + + /** + * Sets the HTTP client instance. + * + * @param HttpClientInterface $client + * @return self + */ + public function setHttpClient(HttpClientInterface $client) + { + $this->httpClient = $client; + + return $this; + } + + /** + * Returns the HTTP client instance. + * + * @return HttpClientInterface + */ + public function getHttpClient() + { + return $this->httpClient; + } + + /** + * Sets the option provider instance. + * + * @param OptionProviderInterface $provider + * @return self + */ + public function setOptionProvider(OptionProviderInterface $provider) + { + $this->optionProvider = $provider; + + return $this; + } + + /** + * Returns the option provider instance. + * + * @return OptionProviderInterface + */ + public function getOptionProvider() + { + return $this->optionProvider; + } + + /** + * Returns the current value of the state parameter. + * + * This can be accessed by the redirect handler during authorization. + * + * @return string + */ + public function getState() + { + return $this->state; + } + + /** + * Set the value of the pkceCode parameter. + * + * When using PKCE this should be set before requesting an access token. + * + * @param string $pkceCode + * @return self + */ + public function setPkceCode($pkceCode) + { + $this->pkceCode = $pkceCode; + return $this; + } + + /** + * Returns the current value of the pkceCode parameter. + * + * This can be accessed by the redirect handler during authorization. + * + * @return string|null + */ + public function getPkceCode() + { + return $this->pkceCode; + } + + /** + * Returns the base URL for authorizing a client. + * + * Eg. https://oauth.service.com/authorize + * + * @return string + */ + abstract public function getBaseAuthorizationUrl(); + + /** + * Returns the base URL for requesting an access token. + * + * Eg. https://oauth.service.com/token + * + * @param array $params + * @return string + */ + abstract public function getBaseAccessTokenUrl(array $params); + + /** + * Returns the URL for requesting the resource owner's details. + * + * @param AccessToken $token + * @return string + */ + abstract public function getResourceOwnerDetailsUrl(AccessToken $token); + + /** + * Returns a new random string to use as the state parameter in an + * authorization flow. + * + * @param int $length Length of the random string to be generated. + * @return string + */ + protected function getRandomState($length = 32) + { + // Converting bytes to hex will always double length. Hence, we can reduce + // the amount of bytes by half to produce the correct length. + return bin2hex(random_bytes($length / 2)); + } + + /** + * Returns a new random string to use as PKCE code_verifier and + * hashed as code_challenge parameters in an authorization flow. + * Must be between 43 and 128 characters long. + * + * @param int $length Length of the random string to be generated. + * @return string + */ + protected function getRandomPkceCode($length = 64) + { + return substr( + strtr( + base64_encode(random_bytes($length)), + '+/', + '-_' + ), + 0, + $length + ); + } + + /** + * Returns the default scopes used by this provider. + * + * This should only be the scopes that are required to request the details + * of the resource owner, rather than all the available scopes. + * + * @return array + */ + abstract protected function getDefaultScopes(); + + /** + * Returns the string that should be used to separate scopes when building + * the URL for requesting an access token. + * + * @return string Scope separator, defaults to ',' + */ + protected function getScopeSeparator() + { + return ','; + } + + /** + * @return string|null + */ + protected function getPkceMethod() + { + return null; + } + + /** + * Returns authorization parameters based on provided options. + * + * @param array $options + * @return array Authorization parameters + */ + protected function getAuthorizationParameters(array $options) + { + if (empty($options['state'])) { + $options['state'] = $this->getRandomState(); + } + + if (empty($options['scope'])) { + $options['scope'] = $this->getDefaultScopes(); + } + + $options += [ + 'response_type' => 'code', + 'approval_prompt' => 'auto' + ]; + + if (is_array($options['scope'])) { + $separator = $this->getScopeSeparator(); + $options['scope'] = implode($separator, $options['scope']); + } + + // Store the state as it may need to be accessed later on. + $this->state = $options['state']; + + $pkceMethod = $this->getPkceMethod(); + if (!empty($pkceMethod)) { + $this->pkceCode = $this->getRandomPkceCode(); + if ($pkceMethod === static::PKCE_METHOD_S256) { + $options['code_challenge'] = trim( + strtr( + base64_encode(hash('sha256', $this->pkceCode, true)), + '+/', + '-_' + ), + '=' + ); + } elseif ($pkceMethod === static::PKCE_METHOD_PLAIN) { + $options['code_challenge'] = $this->pkceCode; + } else { + throw new InvalidArgumentException('Unknown PKCE method "' . $pkceMethod . '".'); + } + $options['code_challenge_method'] = $pkceMethod; + } + + // Business code layer might set a different redirect_uri parameter + // depending on the context, leave it as-is + if (!isset($options['redirect_uri'])) { + $options['redirect_uri'] = $this->redirectUri; + } + + $options['client_id'] = $this->clientId; + + return $options; + } + + /** + * Builds the authorization URL's query string. + * + * @param array $params Query parameters + * @return string Query string + */ + protected function getAuthorizationQuery(array $params) + { + return $this->buildQueryString($params); + } + + /** + * Builds the authorization URL. + * + * @param array $options + * @return string Authorization URL + */ + public function getAuthorizationUrl(array $options = []) + { + $base = $this->getBaseAuthorizationUrl(); + $params = $this->getAuthorizationParameters($options); + $query = $this->getAuthorizationQuery($params); + + return $this->appendQuery($base, $query); + } + + /** + * Redirects the client for authorization. + * + * @param array $options + * @param callable|null $redirectHandler + * @return mixed + */ + public function authorize( + array $options = [], + callable $redirectHandler = null + ) { + $url = $this->getAuthorizationUrl($options); + if ($redirectHandler) { + return $redirectHandler($url, $this); + } + + // @codeCoverageIgnoreStart + header('Location: ' . $url); + exit; + // @codeCoverageIgnoreEnd + } + + /** + * Appends a query string to a URL. + * + * @param string $url The URL to append the query to + * @param string $query The HTTP query string + * @return string The resulting URL + */ + protected function appendQuery($url, $query) + { + $query = trim($query, '?&'); + + if ($query) { + $glue = strstr($url, '?') === false ? '?' : '&'; + return $url . $glue . $query; + } + + return $url; + } + + /** + * Returns the method to use when requesting an access token. + * + * @return string HTTP method + */ + protected function getAccessTokenMethod() + { + return self::METHOD_POST; + } + + /** + * Returns the key used in the access token response to identify the resource owner. + * + * @return string|null Resource owner identifier key + */ + protected function getAccessTokenResourceOwnerId() + { + return static::ACCESS_TOKEN_RESOURCE_OWNER_ID; + } + + /** + * Builds the access token URL's query string. + * + * @param array $params Query parameters + * @return string Query string + */ + protected function getAccessTokenQuery(array $params) + { + return $this->buildQueryString($params); + } + + /** + * Checks that a provided grant is valid, or attempts to produce one if the + * provided grant is a string. + * + * @param AbstractGrant|string $grant + * @return AbstractGrant + */ + protected function verifyGrant($grant) + { + if (is_string($grant)) { + return $this->grantFactory->getGrant($grant); + } + + $this->grantFactory->checkGrant($grant); + return $grant; + } + + /** + * Returns the full URL to use when requesting an access token. + * + * @param array $params Query parameters + * @return string + */ + protected function getAccessTokenUrl(array $params) + { + $url = $this->getBaseAccessTokenUrl($params); + + if ($this->getAccessTokenMethod() === self::METHOD_GET) { + $query = $this->getAccessTokenQuery($params); + return $this->appendQuery($url, $query); + } + + return $url; + } + + /** + * Returns a prepared request for requesting an access token. + * + * @param array $params Query string parameters + * @return RequestInterface + */ + protected function getAccessTokenRequest(array $params) + { + $method = $this->getAccessTokenMethod(); + $url = $this->getAccessTokenUrl($params); + $options = $this->optionProvider->getAccessTokenOptions($this->getAccessTokenMethod(), $params); + + return $this->getRequest($method, $url, $options); + } + + /** + * Requests an access token using a specified grant and option set. + * + * @param mixed $grant + * @param array $options + * @throws IdentityProviderException + * @return AccessTokenInterface + */ + public function getAccessToken($grant, array $options = []) + { + $grant = $this->verifyGrant($grant); + + $params = [ + 'client_id' => $this->clientId, + 'client_secret' => $this->clientSecret, + 'redirect_uri' => $this->redirectUri, + ]; + + if (!empty($this->pkceCode)) { + $params['code_verifier'] = $this->pkceCode; + } + + $params = $grant->prepareRequestParameters($params, $options); + $request = $this->getAccessTokenRequest($params); + $response = $this->getParsedResponse($request); + if (false === is_array($response)) { + throw new UnexpectedValueException( + 'Invalid response received from Authorization Server. Expected JSON.' + ); + } + $prepared = $this->prepareAccessTokenResponse($response); + $token = $this->createAccessToken($prepared, $grant); + + return $token; + } + + /** + * Returns a PSR-7 request instance that is not authenticated. + * + * @param string $method + * @param string $url + * @param array $options + * @return RequestInterface + */ + public function getRequest($method, $url, array $options = []) + { + return $this->createRequest($method, $url, null, $options); + } + + /** + * Returns an authenticated PSR-7 request instance. + * + * @param string $method + * @param string $url + * @param AccessTokenInterface|string|null $token + * @param array $options Any of "headers", "body", and "protocolVersion". + * @return RequestInterface + */ + public function getAuthenticatedRequest($method, $url, $token, array $options = []) + { + return $this->createRequest($method, $url, $token, $options); + } + + /** + * Creates a PSR-7 request instance. + * + * @param string $method + * @param string $url + * @param AccessTokenInterface|string|null $token + * @param array $options + * @return RequestInterface + */ + protected function createRequest($method, $url, $token, array $options) + { + $defaults = [ + 'headers' => $this->getHeaders($token), + ]; + + $options = array_merge_recursive($defaults, $options); + $factory = $this->getRequestFactory(); + + return $factory->getRequestWithOptions($method, $url, $options); + } + + /** + * Sends a request instance and returns a response instance. + * + * WARNING: This method does not attempt to catch exceptions caused by HTTP + * errors! It is recommended to wrap this method in a try/catch block. + * + * @param RequestInterface $request + * @return ResponseInterface + */ + public function getResponse(RequestInterface $request) + { + return $this->getHttpClient()->send($request); + } + + /** + * Sends a request and returns the parsed response. + * + * @param RequestInterface $request + * @throws IdentityProviderException + * @return mixed + */ + public function getParsedResponse(RequestInterface $request) + { + try { + $response = $this->getResponse($request); + } catch (BadResponseException $e) { + $response = $e->getResponse(); + } + + $parsed = $this->parseResponse($response); + + $this->checkResponse($response, $parsed); + + return $parsed; + } + + /** + * Attempts to parse a JSON response. + * + * @param string $content JSON content from response body + * @return array Parsed JSON data + * @throws UnexpectedValueException if the content could not be parsed + */ + protected function parseJson($content) + { + $content = json_decode($content, true); + + if (json_last_error() !== JSON_ERROR_NONE) { + throw new UnexpectedValueException(sprintf( + "Failed to parse JSON response: %s", + json_last_error_msg() + )); + } + + return $content; + } + + /** + * Returns the content type header of a response. + * + * @param ResponseInterface $response + * @return string Semi-colon separated join of content-type headers. + */ + protected function getContentType(ResponseInterface $response) + { + return join(';', (array) $response->getHeader('content-type')); + } + + /** + * Parses the response according to its content-type header. + * + * @throws UnexpectedValueException + * @param ResponseInterface $response + * @return array + */ + protected function parseResponse(ResponseInterface $response) + { + $content = (string) $response->getBody(); + $type = $this->getContentType($response); + + if (strpos($type, 'urlencoded') !== false) { + parse_str($content, $parsed); + return $parsed; + } + + // Attempt to parse the string as JSON regardless of content type, + // since some providers use non-standard content types. Only throw an + // exception if the JSON could not be parsed when it was expected to. + try { + return $this->parseJson($content); + } catch (UnexpectedValueException $e) { + if (strpos($type, 'json') !== false) { + throw $e; + } + + if ($response->getStatusCode() == 500) { + throw new UnexpectedValueException( + 'An OAuth server error was encountered that did not contain a JSON body', + 0, + $e + ); + } + + return $content; + } + } + + /** + * Checks a provider response for errors. + * + * @throws IdentityProviderException + * @param ResponseInterface $response + * @param array|string $data Parsed response data + * @return void + */ + abstract protected function checkResponse(ResponseInterface $response, $data); + + /** + * Prepares an parsed access token response for a grant. + * + * Custom mapping of expiration, etc should be done here. Always call the + * parent method when overloading this method. + * + * @param mixed $result + * @return array + */ + protected function prepareAccessTokenResponse(array $result) + { + if ($this->getAccessTokenResourceOwnerId() !== null) { + $result['resource_owner_id'] = $this->getValueByKey( + $result, + $this->getAccessTokenResourceOwnerId() + ); + } + return $result; + } + + /** + * Creates an access token from a response. + * + * The grant that was used to fetch the response can be used to provide + * additional context. + * + * @param array $response + * @param AbstractGrant $grant + * @return AccessTokenInterface + */ + protected function createAccessToken(array $response, AbstractGrant $grant) + { + return new AccessToken($response); + } + + /** + * Generates a resource owner object from a successful resource owner + * details request. + * + * @param array $response + * @param AccessToken $token + * @return ResourceOwnerInterface + */ + abstract protected function createResourceOwner(array $response, AccessToken $token); + + /** + * Requests and returns the resource owner of given access token. + * + * @param AccessToken $token + * @return ResourceOwnerInterface + */ + public function getResourceOwner(AccessToken $token) + { + $response = $this->fetchResourceOwnerDetails($token); + + return $this->createResourceOwner($response, $token); + } + + /** + * Requests resource owner details. + * + * @param AccessToken $token + * @return mixed + */ + protected function fetchResourceOwnerDetails(AccessToken $token) + { + $url = $this->getResourceOwnerDetailsUrl($token); + + $request = $this->getAuthenticatedRequest(self::METHOD_GET, $url, $token); + + $response = $this->getParsedResponse($request); + + if (false === is_array($response)) { + throw new UnexpectedValueException( + 'Invalid response received from Authorization Server. Expected JSON.' + ); + } + + return $response; + } + + /** + * Returns the default headers used by this provider. + * + * Typically this is used to set 'Accept' or 'Content-Type' headers. + * + * @return array + */ + protected function getDefaultHeaders() + { + return []; + } + + /** + * Returns the authorization headers used by this provider. + * + * Typically this is "Bearer" or "MAC". For more information see: + * http://tools.ietf.org/html/rfc6749#section-7.1 + * + * No default is provided, providers must overload this method to activate + * authorization headers. + * + * @param mixed|null $token Either a string or an access token instance + * @return array + */ + protected function getAuthorizationHeaders($token = null) + { + return []; + } + + /** + * Returns all headers used by this provider for a request. + * + * The request will be authenticated if an access token is provided. + * + * @param mixed|null $token object or string + * @return array + */ + public function getHeaders($token = null) + { + if ($token) { + return array_merge( + $this->getDefaultHeaders(), + $this->getAuthorizationHeaders($token) + ); + } + + return $this->getDefaultHeaders(); + } +} diff --git a/data/web/inc/lib/vendor/league/oauth2-client/src/Provider/Exception/IdentityProviderException.php b/data/web/inc/lib/vendor/league/oauth2-client/src/Provider/Exception/IdentityProviderException.php new file mode 100644 index 000000000..55cb438fb --- /dev/null +++ b/data/web/inc/lib/vendor/league/oauth2-client/src/Provider/Exception/IdentityProviderException.php @@ -0,0 +1,48 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Provider\Exception; + +/** + * Exception thrown if the provider response contains errors. + */ +class IdentityProviderException extends \Exception +{ + /** + * @var mixed + */ + protected $response; + + /** + * @param string $message + * @param int $code + * @param mixed $response The response body + */ + public function __construct($message, $code, $response) + { + $this->response = $response; + + parent::__construct($message, $code); + } + + /** + * Returns the exception's response body. + * + * @return mixed + */ + public function getResponseBody() + { + return $this->response; + } +} diff --git a/data/web/inc/lib/vendor/league/oauth2-client/src/Provider/GenericProvider.php b/data/web/inc/lib/vendor/league/oauth2-client/src/Provider/GenericProvider.php new file mode 100644 index 000000000..0fc95f250 --- /dev/null +++ b/data/web/inc/lib/vendor/league/oauth2-client/src/Provider/GenericProvider.php @@ -0,0 +1,247 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Provider; + +use InvalidArgumentException; +use League\OAuth2\Client\Provider\Exception\IdentityProviderException; +use League\OAuth2\Client\Token\AccessToken; +use League\OAuth2\Client\Tool\BearerAuthorizationTrait; +use Psr\Http\Message\ResponseInterface; + +/** + * Represents a generic service provider that may be used to interact with any + * OAuth 2.0 service provider, using Bearer token authentication. + */ +class GenericProvider extends AbstractProvider +{ + use BearerAuthorizationTrait; + + /** + * @var string + */ + private $urlAuthorize; + + /** + * @var string + */ + private $urlAccessToken; + + /** + * @var string + */ + private $urlResourceOwnerDetails; + + /** + * @var string + */ + private $accessTokenMethod; + + /** + * @var string + */ + private $accessTokenResourceOwnerId; + + /** + * @var array|null + */ + private $scopes = null; + + /** + * @var string + */ + private $scopeSeparator; + + /** + * @var string + */ + private $responseError = 'error'; + + /** + * @var string + */ + private $responseCode; + + /** + * @var string + */ + private $responseResourceOwnerId = 'id'; + + /** + * @var string|null + */ + private $pkceMethod = null; + + /** + * @param array $options + * @param array $collaborators + */ + public function __construct(array $options = [], array $collaborators = []) + { + $this->assertRequiredOptions($options); + + $possible = $this->getConfigurableOptions(); + $configured = array_intersect_key($options, array_flip($possible)); + + foreach ($configured as $key => $value) { + $this->$key = $value; + } + + // Remove all options that are only used locally + $options = array_diff_key($options, $configured); + + parent::__construct($options, $collaborators); + } + + /** + * Returns all options that can be configured. + * + * @return array + */ + protected function getConfigurableOptions() + { + return array_merge($this->getRequiredOptions(), [ + 'accessTokenMethod', + 'accessTokenResourceOwnerId', + 'scopeSeparator', + 'responseError', + 'responseCode', + 'responseResourceOwnerId', + 'scopes', + 'pkceMethod', + ]); + } + + /** + * Returns all options that are required. + * + * @return array + */ + protected function getRequiredOptions() + { + return [ + 'urlAuthorize', + 'urlAccessToken', + 'urlResourceOwnerDetails', + ]; + } + + /** + * Verifies that all required options have been passed. + * + * @param array $options + * @return void + * @throws InvalidArgumentException + */ + private function assertRequiredOptions(array $options) + { + $missing = array_diff_key(array_flip($this->getRequiredOptions()), $options); + + if (!empty($missing)) { + throw new InvalidArgumentException( + 'Required options not defined: ' . implode(', ', array_keys($missing)) + ); + } + } + + /** + * @inheritdoc + */ + public function getBaseAuthorizationUrl() + { + return $this->urlAuthorize; + } + + /** + * @inheritdoc + */ + public function getBaseAccessTokenUrl(array $params) + { + return $this->urlAccessToken; + } + + /** + * @inheritdoc + */ + public function getResourceOwnerDetailsUrl(AccessToken $token) + { + return $this->urlResourceOwnerDetails; + } + + /** + * @inheritdoc + */ + public function getDefaultScopes() + { + return $this->scopes; + } + + /** + * @inheritdoc + */ + protected function getAccessTokenMethod() + { + return $this->accessTokenMethod ?: parent::getAccessTokenMethod(); + } + + /** + * @inheritdoc + */ + protected function getAccessTokenResourceOwnerId() + { + return $this->accessTokenResourceOwnerId ?: parent::getAccessTokenResourceOwnerId(); + } + + /** + * @inheritdoc + */ + protected function getScopeSeparator() + { + return $this->scopeSeparator ?: parent::getScopeSeparator(); + } + + /** + * @inheritdoc + */ + protected function getPkceMethod() + { + return $this->pkceMethod ?: parent::getPkceMethod(); + } + + /** + * @inheritdoc + */ + protected function checkResponse(ResponseInterface $response, $data) + { + if (!empty($data[$this->responseError])) { + $error = $data[$this->responseError]; + if (!is_string($error)) { + $error = var_export($error, true); + } + $code = $this->responseCode && !empty($data[$this->responseCode])? $data[$this->responseCode] : 0; + if (!is_int($code)) { + $code = intval($code); + } + throw new IdentityProviderException($error, $code, $data); + } + } + + /** + * @inheritdoc + */ + protected function createResourceOwner(array $response, AccessToken $token) + { + return new GenericResourceOwner($response, $this->responseResourceOwnerId); + } +} diff --git a/data/web/inc/lib/vendor/league/oauth2-client/src/Provider/GenericResourceOwner.php b/data/web/inc/lib/vendor/league/oauth2-client/src/Provider/GenericResourceOwner.php new file mode 100644 index 000000000..f87661485 --- /dev/null +++ b/data/web/inc/lib/vendor/league/oauth2-client/src/Provider/GenericResourceOwner.php @@ -0,0 +1,61 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Provider; + +/** + * Represents a generic resource owner for use with the GenericProvider. + */ +class GenericResourceOwner implements ResourceOwnerInterface +{ + /** + * @var array + */ + protected $response; + + /** + * @var string + */ + protected $resourceOwnerId; + + /** + * @param array $response + * @param string $resourceOwnerId + */ + public function __construct(array $response, $resourceOwnerId) + { + $this->response = $response; + $this->resourceOwnerId = $resourceOwnerId; + } + + /** + * Returns the identifier of the authorized resource owner. + * + * @return mixed + */ + public function getId() + { + return $this->response[$this->resourceOwnerId]; + } + + /** + * Returns the raw resource owner response. + * + * @return array + */ + public function toArray() + { + return $this->response; + } +} diff --git a/data/web/inc/lib/vendor/league/oauth2-client/src/Provider/ResourceOwnerInterface.php b/data/web/inc/lib/vendor/league/oauth2-client/src/Provider/ResourceOwnerInterface.php new file mode 100644 index 000000000..828442425 --- /dev/null +++ b/data/web/inc/lib/vendor/league/oauth2-client/src/Provider/ResourceOwnerInterface.php @@ -0,0 +1,36 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Provider; + +/** + * Classes implementing `ResourceOwnerInterface` may be used to represent + * the resource owner authenticated with a service provider. + */ +interface ResourceOwnerInterface +{ + /** + * Returns the identifier of the authorized resource owner. + * + * @return mixed + */ + public function getId(); + + /** + * Return all of the owner details available as an array. + * + * @return array + */ + public function toArray(); +} diff --git a/data/web/inc/lib/vendor/league/oauth2-client/src/Token/AccessToken.php b/data/web/inc/lib/vendor/league/oauth2-client/src/Token/AccessToken.php new file mode 100644 index 000000000..81533c307 --- /dev/null +++ b/data/web/inc/lib/vendor/league/oauth2-client/src/Token/AccessToken.php @@ -0,0 +1,243 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Token; + +use InvalidArgumentException; +use RuntimeException; + +/** + * Represents an access token. + * + * @link http://tools.ietf.org/html/rfc6749#section-1.4 Access Token (RFC 6749, §1.4) + */ +class AccessToken implements AccessTokenInterface, ResourceOwnerAccessTokenInterface +{ + /** + * @var string + */ + protected $accessToken; + + /** + * @var int + */ + protected $expires; + + /** + * @var string + */ + protected $refreshToken; + + /** + * @var string + */ + protected $resourceOwnerId; + + /** + * @var array + */ + protected $values = []; + + /** + * @var int + */ + private static $timeNow; + + /** + * Set the time now. This should only be used for testing purposes. + * + * @param int $timeNow the time in seconds since epoch + * @return void + */ + public static function setTimeNow($timeNow) + { + self::$timeNow = $timeNow; + } + + /** + * Reset the time now if it was set for test purposes. + * + * @return void + */ + public static function resetTimeNow() + { + self::$timeNow = null; + } + + /** + * @return int + */ + public function getTimeNow() + { + return self::$timeNow ? self::$timeNow : time(); + } + + /** + * Constructs an access token. + * + * @param array $options An array of options returned by the service provider + * in the access token request. The `access_token` option is required. + * @throws InvalidArgumentException if `access_token` is not provided in `$options`. + */ + public function __construct(array $options = []) + { + if (empty($options['access_token'])) { + throw new InvalidArgumentException('Required option not passed: "access_token"'); + } + + $this->accessToken = $options['access_token']; + + if (!empty($options['resource_owner_id'])) { + $this->resourceOwnerId = $options['resource_owner_id']; + } + + if (!empty($options['refresh_token'])) { + $this->refreshToken = $options['refresh_token']; + } + + // We need to know when the token expires. Show preference to + // 'expires_in' since it is defined in RFC6749 Section 5.1. + // Defer to 'expires' if it is provided instead. + if (isset($options['expires_in'])) { + if (!is_numeric($options['expires_in'])) { + throw new \InvalidArgumentException('expires_in value must be an integer'); + } + + $this->expires = $options['expires_in'] != 0 ? $this->getTimeNow() + $options['expires_in'] : 0; + } elseif (!empty($options['expires'])) { + // Some providers supply the seconds until expiration rather than + // the exact timestamp. Take a best guess at which we received. + $expires = $options['expires']; + + if (!$this->isExpirationTimestamp($expires)) { + $expires += $this->getTimeNow(); + } + + $this->expires = $expires; + } + + // Capture any additional values that might exist in the token but are + // not part of the standard response. Vendors will sometimes pass + // additional user data this way. + $this->values = array_diff_key($options, array_flip([ + 'access_token', + 'resource_owner_id', + 'refresh_token', + 'expires_in', + 'expires', + ])); + } + + /** + * Check if a value is an expiration timestamp or second value. + * + * @param integer $value + * @return bool + */ + protected function isExpirationTimestamp($value) + { + // If the given value is larger than the original OAuth 2 draft date, + // assume that it is meant to be a (possible expired) timestamp. + $oauth2InceptionDate = 1349067600; // 2012-10-01 + return ($value > $oauth2InceptionDate); + } + + /** + * @inheritdoc + */ + public function getToken() + { + return $this->accessToken; + } + + /** + * @inheritdoc + */ + public function getRefreshToken() + { + return $this->refreshToken; + } + + /** + * @inheritdoc + */ + public function getExpires() + { + return $this->expires; + } + + /** + * @inheritdoc + */ + public function getResourceOwnerId() + { + return $this->resourceOwnerId; + } + + /** + * @inheritdoc + */ + public function hasExpired() + { + $expires = $this->getExpires(); + + if (empty($expires)) { + throw new RuntimeException('"expires" is not set on the token'); + } + + return $expires < time(); + } + + /** + * @inheritdoc + */ + public function getValues() + { + return $this->values; + } + + /** + * @inheritdoc + */ + public function __toString() + { + return (string) $this->getToken(); + } + + /** + * @inheritdoc + */ + public function jsonSerialize() + { + $parameters = $this->values; + + if ($this->accessToken) { + $parameters['access_token'] = $this->accessToken; + } + + if ($this->refreshToken) { + $parameters['refresh_token'] = $this->refreshToken; + } + + if ($this->expires) { + $parameters['expires'] = $this->expires; + } + + if ($this->resourceOwnerId) { + $parameters['resource_owner_id'] = $this->resourceOwnerId; + } + + return $parameters; + } +} diff --git a/data/web/inc/lib/vendor/league/oauth2-client/src/Token/AccessTokenInterface.php b/data/web/inc/lib/vendor/league/oauth2-client/src/Token/AccessTokenInterface.php new file mode 100644 index 000000000..5fd219ffc --- /dev/null +++ b/data/web/inc/lib/vendor/league/oauth2-client/src/Token/AccessTokenInterface.php @@ -0,0 +1,74 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Token; + +use JsonSerializable; +use ReturnTypeWillChange; +use RuntimeException; + +interface AccessTokenInterface extends JsonSerializable +{ + /** + * Returns the access token string of this instance. + * + * @return string + */ + public function getToken(); + + /** + * Returns the refresh token, if defined. + * + * @return string|null + */ + public function getRefreshToken(); + + /** + * Returns the expiration timestamp in seconds, if defined. + * + * @return integer|null + */ + public function getExpires(); + + /** + * Checks if this token has expired. + * + * @return boolean true if the token has expired, false otherwise. + * @throws RuntimeException if 'expires' is not set on the token. + */ + public function hasExpired(); + + /** + * Returns additional vendor values stored in the token. + * + * @return array + */ + public function getValues(); + + /** + * Returns a string representation of the access token + * + * @return string + */ + public function __toString(); + + /** + * Returns an array of parameters to serialize when this is serialized with + * json_encode(). + * + * @return array + */ + #[ReturnTypeWillChange] + public function jsonSerialize(); +} diff --git a/data/web/inc/lib/vendor/league/oauth2-client/src/Token/ResourceOwnerAccessTokenInterface.php b/data/web/inc/lib/vendor/league/oauth2-client/src/Token/ResourceOwnerAccessTokenInterface.php new file mode 100644 index 000000000..51e4ce413 --- /dev/null +++ b/data/web/inc/lib/vendor/league/oauth2-client/src/Token/ResourceOwnerAccessTokenInterface.php @@ -0,0 +1,25 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Token; + +interface ResourceOwnerAccessTokenInterface extends AccessTokenInterface +{ + /** + * Returns the resource owner identifier, if defined. + * + * @return string|null + */ + public function getResourceOwnerId(); +} diff --git a/data/web/inc/lib/vendor/league/oauth2-client/src/Tool/ArrayAccessorTrait.php b/data/web/inc/lib/vendor/league/oauth2-client/src/Tool/ArrayAccessorTrait.php new file mode 100644 index 000000000..a18198cf3 --- /dev/null +++ b/data/web/inc/lib/vendor/league/oauth2-client/src/Tool/ArrayAccessorTrait.php @@ -0,0 +1,52 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Tool; + +/** + * Provides generic array navigation tools. + */ +trait ArrayAccessorTrait +{ + /** + * Returns a value by key using dot notation. + * + * @param array $data + * @param string $key + * @param mixed|null $default + * @return mixed + */ + private function getValueByKey(array $data, $key, $default = null) + { + if (!is_string($key) || empty($key) || !count($data)) { + return $default; + } + + if (strpos($key, '.') !== false) { + $keys = explode('.', $key); + + foreach ($keys as $innerKey) { + if (!is_array($data) || !array_key_exists($innerKey, $data)) { + return $default; + } + + $data = $data[$innerKey]; + } + + return $data; + } + + return array_key_exists($key, $data) ? $data[$key] : $default; + } +} diff --git a/data/web/inc/lib/vendor/league/oauth2-client/src/Tool/BearerAuthorizationTrait.php b/data/web/inc/lib/vendor/league/oauth2-client/src/Tool/BearerAuthorizationTrait.php new file mode 100644 index 000000000..081c7c861 --- /dev/null +++ b/data/web/inc/lib/vendor/league/oauth2-client/src/Tool/BearerAuthorizationTrait.php @@ -0,0 +1,36 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Tool; + +use League\OAuth2\Client\Token\AccessTokenInterface; + +/** + * Enables `Bearer` header authorization for providers. + * + * @link http://tools.ietf.org/html/rfc6750 Bearer Token Usage (RFC 6750) + */ +trait BearerAuthorizationTrait +{ + /** + * Returns authorization headers for the 'bearer' grant. + * + * @param AccessTokenInterface|string|null $token Either a string or an access token instance + * @return array + */ + protected function getAuthorizationHeaders($token = null) + { + return ['Authorization' => 'Bearer ' . $token]; + } +} diff --git a/data/web/inc/lib/vendor/league/oauth2-client/src/Tool/GuardedPropertyTrait.php b/data/web/inc/lib/vendor/league/oauth2-client/src/Tool/GuardedPropertyTrait.php new file mode 100644 index 000000000..02c9ba5fb --- /dev/null +++ b/data/web/inc/lib/vendor/league/oauth2-client/src/Tool/GuardedPropertyTrait.php @@ -0,0 +1,70 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Tool; + +/** + * Provides support for blacklisting explicit properties from the + * mass assignment behavior. + */ +trait GuardedPropertyTrait +{ + /** + * The properties that aren't mass assignable. + * + * @var array + */ + protected $guarded = []; + + /** + * Attempts to mass assign the given options to explicitly defined properties, + * skipping over any properties that are defined in the guarded array. + * + * @param array $options + * @return mixed + */ + protected function fillProperties(array $options = []) + { + if (isset($options['guarded'])) { + unset($options['guarded']); + } + + foreach ($options as $option => $value) { + if (property_exists($this, $option) && !$this->isGuarded($option)) { + $this->{$option} = $value; + } + } + } + + /** + * Returns current guarded properties. + * + * @return array + */ + public function getGuarded() + { + return $this->guarded; + } + + /** + * Determines if the given property is guarded. + * + * @param string $property + * @return bool + */ + public function isGuarded($property) + { + return in_array($property, $this->getGuarded()); + } +} diff --git a/data/web/inc/lib/vendor/league/oauth2-client/src/Tool/MacAuthorizationTrait.php b/data/web/inc/lib/vendor/league/oauth2-client/src/Tool/MacAuthorizationTrait.php new file mode 100644 index 000000000..f8dcd77c5 --- /dev/null +++ b/data/web/inc/lib/vendor/league/oauth2-client/src/Tool/MacAuthorizationTrait.php @@ -0,0 +1,83 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Tool; + +use League\OAuth2\Client\Token\AccessToken; +use League\OAuth2\Client\Token\AccessTokenInterface; + +/** + * Enables `MAC` header authorization for providers. + * + * @link http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-05 Message Authentication Code (MAC) Tokens + */ +trait MacAuthorizationTrait +{ + /** + * Returns the id of this token for MAC generation. + * + * @param AccessToken $token + * @return string + */ + abstract protected function getTokenId(AccessToken $token); + + /** + * Returns the MAC signature for the current request. + * + * @param string $id + * @param integer $ts + * @param string $nonce + * @return string + */ + abstract protected function getMacSignature($id, $ts, $nonce); + + /** + * Returns a new random string to use as the state parameter in an + * authorization flow. + * + * @param int $length Length of the random string to be generated. + * @return string + */ + abstract protected function getRandomState($length = 32); + + /** + * Returns the authorization headers for the 'mac' grant. + * + * @param AccessTokenInterface|string|null $token Either a string or an access token instance + * @return array + * @codeCoverageIgnore + * + * @todo This is currently untested and provided only as an example. If you + * complete the implementation, please create a pull request for + * https://github.com/thephpleague/oauth2-client + */ + protected function getAuthorizationHeaders($token = null) + { + if ($token === null) { + return []; + } + + $ts = time(); + $id = $this->getTokenId($token); + $nonce = $this->getRandomState(16); + $mac = $this->getMacSignature($id, $ts, $nonce); + + $parts = []; + foreach (compact('id', 'ts', 'nonce', 'mac') as $key => $value) { + $parts[] = sprintf('%s="%s"', $key, $value); + } + + return ['Authorization' => 'MAC ' . implode(', ', $parts)]; + } +} diff --git a/data/web/inc/lib/vendor/league/oauth2-client/src/Tool/ProviderRedirectTrait.php b/data/web/inc/lib/vendor/league/oauth2-client/src/Tool/ProviderRedirectTrait.php new file mode 100644 index 000000000..f81b511f9 --- /dev/null +++ b/data/web/inc/lib/vendor/league/oauth2-client/src/Tool/ProviderRedirectTrait.php @@ -0,0 +1,122 @@ +redirectLimit) { + $attempts++; + $response = $this->getHttpClient()->send($request, [ + 'allow_redirects' => false + ]); + + if ($this->isRedirect($response)) { + $redirectUrl = new Uri($response->getHeader('Location')[0]); + $request = $request->withUri($redirectUrl); + } else { + break; + } + } + + return $response; + } + + /** + * Returns the HTTP client instance. + * + * @return GuzzleHttp\ClientInterface + */ + abstract public function getHttpClient(); + + /** + * Retrieves current redirect limit. + * + * @return integer + */ + public function getRedirectLimit() + { + return $this->redirectLimit; + } + + /** + * Determines if a given response is a redirect. + * + * @param ResponseInterface $response + * + * @return boolean + */ + protected function isRedirect(ResponseInterface $response) + { + $statusCode = $response->getStatusCode(); + + return $statusCode > 300 && $statusCode < 400 && $response->hasHeader('Location'); + } + + /** + * Sends a request instance and returns a response instance. + * + * WARNING: This method does not attempt to catch exceptions caused by HTTP + * errors! It is recommended to wrap this method in a try/catch block. + * + * @param RequestInterface $request + * @return ResponseInterface + */ + public function getResponse(RequestInterface $request) + { + try { + $response = $this->followRequestRedirects($request); + } catch (BadResponseException $e) { + $response = $e->getResponse(); + } + + return $response; + } + + /** + * Updates the redirect limit. + * + * @param integer $limit + * @return League\OAuth2\Client\Provider\AbstractProvider + * @throws InvalidArgumentException + */ + public function setRedirectLimit($limit) + { + if (!is_int($limit)) { + throw new InvalidArgumentException('redirectLimit must be an integer.'); + } + + if ($limit < 1) { + throw new InvalidArgumentException('redirectLimit must be greater than or equal to one.'); + } + + $this->redirectLimit = $limit; + + return $this; + } +} diff --git a/data/web/inc/lib/vendor/league/oauth2-client/src/Tool/QueryBuilderTrait.php b/data/web/inc/lib/vendor/league/oauth2-client/src/Tool/QueryBuilderTrait.php new file mode 100644 index 000000000..bdda3e79e --- /dev/null +++ b/data/web/inc/lib/vendor/league/oauth2-client/src/Tool/QueryBuilderTrait.php @@ -0,0 +1,33 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Tool; + +/** + * Provides a standard way to generate query strings. + */ +trait QueryBuilderTrait +{ + /** + * Build a query string from an array. + * + * @param array $params + * + * @return string + */ + protected function buildQueryString(array $params) + { + return http_build_query($params, '', '&', \PHP_QUERY_RFC3986); + } +} diff --git a/data/web/inc/lib/vendor/league/oauth2-client/src/Tool/RequestFactory.php b/data/web/inc/lib/vendor/league/oauth2-client/src/Tool/RequestFactory.php new file mode 100644 index 000000000..1af434297 --- /dev/null +++ b/data/web/inc/lib/vendor/league/oauth2-client/src/Tool/RequestFactory.php @@ -0,0 +1,87 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Tool; + +use GuzzleHttp\Psr7\Request; + +/** + * Used to produce PSR-7 Request instances. + * + * @link https://github.com/guzzle/guzzle/pull/1101 + */ +class RequestFactory +{ + /** + * Creates a PSR-7 Request instance. + * + * @param null|string $method HTTP method for the request. + * @param null|string $uri URI for the request. + * @param array $headers Headers for the message. + * @param string|resource|StreamInterface $body Message body. + * @param string $version HTTP protocol version. + * + * @return Request + */ + public function getRequest( + $method, + $uri, + array $headers = [], + $body = null, + $version = '1.1' + ) { + return new Request($method, $uri, $headers, $body, $version); + } + + /** + * Parses simplified options. + * + * @param array $options Simplified options. + * + * @return array Extended options for use with getRequest. + */ + protected function parseOptions(array $options) + { + // Should match default values for getRequest + $defaults = [ + 'headers' => [], + 'body' => null, + 'version' => '1.1', + ]; + + return array_merge($defaults, $options); + } + + /** + * Creates a request using a simplified array of options. + * + * @param null|string $method + * @param null|string $uri + * @param array $options + * + * @return Request + */ + public function getRequestWithOptions($method, $uri, array $options = []) + { + $options = $this->parseOptions($options); + + return $this->getRequest( + $method, + $uri, + $options['headers'], + $options['body'], + $options['version'] + ); + } +} diff --git a/data/web/inc/lib/vendor/league/oauth2-client/src/Tool/RequiredParameterTrait.php b/data/web/inc/lib/vendor/league/oauth2-client/src/Tool/RequiredParameterTrait.php new file mode 100644 index 000000000..47da97717 --- /dev/null +++ b/data/web/inc/lib/vendor/league/oauth2-client/src/Tool/RequiredParameterTrait.php @@ -0,0 +1,56 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Tool; + +use BadMethodCallException; + +/** + * Provides functionality to check for required parameters. + */ +trait RequiredParameterTrait +{ + /** + * Checks for a required parameter in a hash. + * + * @throws BadMethodCallException + * @param string $name + * @param array $params + * @return void + */ + private function checkRequiredParameter($name, array $params) + { + if (!isset($params[$name])) { + throw new BadMethodCallException(sprintf( + 'Required parameter not passed: "%s"', + $name + )); + } + } + + /** + * Checks for multiple required parameters in a hash. + * + * @throws InvalidArgumentException + * @param array $names + * @param array $params + * @return void + */ + private function checkRequiredParameters(array $names, array $params) + { + foreach ($names as $name) { + $this->checkRequiredParameter($name, $params); + } + } +} diff --git a/data/web/inc/lib/vendor/nesbot/carbon/.phpstorm.meta.php b/data/web/inc/lib/vendor/nesbot/carbon/.phpstorm.meta.php new file mode 100644 index 000000000..bd7c7e0e7 --- /dev/null +++ b/data/web/inc/lib/vendor/nesbot/carbon/.phpstorm.meta.php @@ -0,0 +1,10 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\MessageFormatter; + +use Symfony\Component\Translation\Formatter\MessageFormatterInterface; + +if (!class_exists(LazyMessageFormatter::class, false)) { + abstract class LazyMessageFormatter implements MessageFormatterInterface + { + public function format(string $message, string $locale, array $parameters = []): string + { + return $this->formatter->format( + $message, + $this->transformLocale($locale), + $parameters + ); + } + } +} diff --git a/data/web/inc/lib/vendor/nesbot/carbon/lazy/Carbon/MessageFormatter/MessageFormatterMapperWeakType.php b/data/web/inc/lib/vendor/nesbot/carbon/lazy/Carbon/MessageFormatter/MessageFormatterMapperWeakType.php new file mode 100644 index 000000000..cbd890d5b --- /dev/null +++ b/data/web/inc/lib/vendor/nesbot/carbon/lazy/Carbon/MessageFormatter/MessageFormatterMapperWeakType.php @@ -0,0 +1,36 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\MessageFormatter; + +use Symfony\Component\Translation\Formatter\ChoiceMessageFormatterInterface; +use Symfony\Component\Translation\Formatter\MessageFormatterInterface; + +if (!class_exists(LazyMessageFormatter::class, false)) { + abstract class LazyMessageFormatter implements MessageFormatterInterface, ChoiceMessageFormatterInterface + { + abstract protected function transformLocale(?string $locale): ?string; + + public function format($message, $locale, array $parameters = []) + { + return $this->formatter->format( + $message, + $this->transformLocale($locale), + $parameters + ); + } + + public function choiceFormat($message, $number, $locale, array $parameters = []) + { + return $this->formatter->choiceFormat($message, $number, $locale, $parameters); + } + } +} diff --git a/data/web/inc/lib/vendor/nesbot/carbon/lazy/Carbon/PHPStan/AbstractMacroBuiltin.php b/data/web/inc/lib/vendor/nesbot/carbon/lazy/Carbon/PHPStan/AbstractMacroBuiltin.php new file mode 100644 index 000000000..ba7cf6320 --- /dev/null +++ b/data/web/inc/lib/vendor/nesbot/carbon/lazy/Carbon/PHPStan/AbstractMacroBuiltin.php @@ -0,0 +1,36 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\PHPStan; + +use PHPStan\BetterReflection\Reflection; +use ReflectionMethod; + +if (!class_exists(AbstractReflectionMacro::class, false)) { + abstract class AbstractReflectionMacro extends AbstractMacro + { + /** + * {@inheritdoc} + */ + public function getReflection(): ?ReflectionMethod + { + if ($this->reflectionFunction instanceof Reflection\ReflectionMethod) { + return new Reflection\Adapter\ReflectionMethod($this->reflectionFunction); + } + + return $this->reflectionFunction instanceof ReflectionMethod + ? $this->reflectionFunction + : null; + } + } +} diff --git a/data/web/inc/lib/vendor/nesbot/carbon/lazy/Carbon/PHPStan/AbstractMacroStatic.php b/data/web/inc/lib/vendor/nesbot/carbon/lazy/Carbon/PHPStan/AbstractMacroStatic.php new file mode 100644 index 000000000..bd4c8e804 --- /dev/null +++ b/data/web/inc/lib/vendor/nesbot/carbon/lazy/Carbon/PHPStan/AbstractMacroStatic.php @@ -0,0 +1,45 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\PHPStan; + +use PHPStan\BetterReflection\Reflection; +use ReflectionMethod; + +if (!class_exists(AbstractReflectionMacro::class, false)) { + abstract class AbstractReflectionMacro extends AbstractMacro + { + /** + * {@inheritdoc} + */ + public function getReflection(): ?Reflection\Adapter\ReflectionMethod + { + if ($this->reflectionFunction instanceof Reflection\Adapter\ReflectionMethod) { + return $this->reflectionFunction; + } + + if ($this->reflectionFunction instanceof Reflection\ReflectionMethod) { + return new Reflection\Adapter\ReflectionMethod($this->reflectionFunction); + } + + return $this->reflectionFunction instanceof ReflectionMethod + ? new Reflection\Adapter\ReflectionMethod( + Reflection\ReflectionMethod::createFromName( + $this->reflectionFunction->getDeclaringClass()->getName(), + $this->reflectionFunction->getName() + ) + ) + : null; + } + } +} diff --git a/data/web/inc/lib/vendor/nesbot/carbon/lazy/Carbon/PHPStan/MacroStrongType.php b/data/web/inc/lib/vendor/nesbot/carbon/lazy/Carbon/PHPStan/MacroStrongType.php index eacd9c1ea..f615b3a64 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/lazy/Carbon/PHPStan/MacroStrongType.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/lazy/Carbon/PHPStan/MacroStrongType.php @@ -14,14 +14,16 @@ declare(strict_types=1); namespace Carbon\PHPStan; if (!class_exists(LazyMacro::class, false)) { - abstract class LazyMacro extends AbstractMacro + abstract class LazyMacro extends AbstractReflectionMacro { /** * {@inheritdoc} */ public function getFileName(): ?string { - return $this->reflectionFunction->getFileName(); + $file = $this->reflectionFunction->getFileName(); + + return (($file ? realpath($file) : null) ?: $file) ?: null; } /** diff --git a/data/web/inc/lib/vendor/nesbot/carbon/lazy/Carbon/PHPStan/MacroWeakType.php b/data/web/inc/lib/vendor/nesbot/carbon/lazy/Carbon/PHPStan/MacroWeakType.php index 3e9fcf4f7..bf64c1dd9 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/lazy/Carbon/PHPStan/MacroWeakType.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/lazy/Carbon/PHPStan/MacroWeakType.php @@ -14,7 +14,7 @@ declare(strict_types=1); namespace Carbon\PHPStan; if (!class_exists(LazyMacro::class, false)) { - abstract class LazyMacro extends AbstractMacro + abstract class LazyMacro extends AbstractReflectionMacro { /** * {@inheritdoc} @@ -23,7 +23,9 @@ if (!class_exists(LazyMacro::class, false)) { */ public function getFileName() { - return $this->reflectionFunction->getFileName(); + $file = $this->reflectionFunction->getFileName(); + + return (($file ? realpath($file) : null) ?: $file) ?: null; } /** diff --git a/data/web/inc/lib/vendor/nesbot/carbon/readme.md b/data/web/inc/lib/vendor/nesbot/carbon/readme.md index 5d827219e..3f4117706 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/readme.md +++ b/data/web/inc/lib/vendor/nesbot/carbon/readme.md @@ -2,7 +2,7 @@ [![Latest Stable Version](https://img.shields.io/packagist/v/nesbot/carbon.svg?style=flat-square)](https://packagist.org/packages/nesbot/carbon) [![Total Downloads](https://img.shields.io/packagist/dt/nesbot/carbon.svg?style=flat-square)](https://packagist.org/packages/nesbot/carbon) -[![GitHub Actions](https://img.shields.io/endpoint.svg?url=https%3A%2F%2Factions-badge.atrox.dev%2Fbriannesbitt%2FCarbon%2Fbadge&style=flat-square&label=Build&logo=none)](https://actions-badge.atrox.dev/briannesbitt/Carbon/goto) +[![GitHub Actions](https://img.shields.io/endpoint.svg?url=https%3A%2F%2Factions-badge.atrox.dev%2Fbriannesbitt%2FCarbon%2Fbadge&style=flat-square&label=Build&logo=none)](https://github.com/briannesbitt/Carbon/actions) [![codecov.io](https://img.shields.io/codecov/c/github/briannesbitt/Carbon.svg?style=flat-square)](https://codecov.io/github/briannesbitt/Carbon?branch=master) [![Tidelift](https://tidelift.com/badges/github/briannesbitt/Carbon)](https://tidelift.com/subscription/pkg/packagist-nesbot-carbon?utm_source=packagist-nesbot-carbon&utm_medium=referral&utm_campaign=readme) @@ -119,21 +119,52 @@ This project exists thanks to all the people who contribute. Support this project by becoming a sponsor. Your logo will show up here with a link to your website. - - - - - - - + +Онлайн казино +CasinoHex Canada +Probukmacher +Игровые автоматы +Casino-portugal.pt +Slots City +inkedin +Онлайн казино України +OnlineCasinosSpelen +Best non Gamstop sites in the UK +Real Money Pokies +Non GamStop Bookies UK +Онлайн Казино Украины +SSSTwitter +Non-GamStop Bets UK +Chudovo +UK Casino Gap +NZ Casino Deps +NonStopCasino.org +Migliori Siti Non AAMS +UK NonGamStopCasinos +SnapTik +IG Downloader +Proxidize +Blastup +AzuraCast +Triplebyte +GitHub Sponsors +Salesforce + -[[Become a sponsor](https://opencollective.com/Carbon#sponsor)] +[[Become a sponsor via OpenCollective](https://opencollective.com/Carbon#sponsor)] + + + + + + +[[Become a sponsor via GitHub](https://github.com/sponsors/kylekatarnls)] ### Backers Thank you to all our backers! 🙏 - + [[Become a backer](https://opencollective.com/Carbon#backer)] diff --git a/data/web/inc/lib/vendor/nesbot/carbon/sponsors.php b/data/web/inc/lib/vendor/nesbot/carbon/sponsors.php new file mode 100644 index 000000000..67b217161 --- /dev/null +++ b/data/web/inc/lib/vendor/nesbot/carbon/sponsors.php @@ -0,0 +1,129 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Carbon\CarbonImmutable; + +require_once __DIR__.'/vendor/autoload.php'; + +function getMaxHistoryMonthsByAmount($amount): int +{ + if ($amount >= 50) { + return 6; + } + + if ($amount >= 20) { + return 4; + } + + return 2; +} + +function getHtmlAttribute($rawValue): string +{ + return str_replace( + ['​', "\r"], + '', + trim(htmlspecialchars((string) $rawValue), "  \n\r\t\v\0"), + ); +} + +function getOpenCollectiveSponsors(): string +{ + $customSponsorImages = [ + // For consistency and equity among sponsors, as of now, we kindly ask our sponsors + // to provide an image having a width/height ratio between 1/1 and 2/1. + // By default, we'll show the member picture from OpenCollective, and will resize it if bigger + // int(OpenCollective.MemberId) => ImageURL + ]; + + $members = json_decode(file_get_contents('https://opencollective.com/carbon/members/all.json'), true); + + $list = array_filter($members, static function ($member): bool { + return ($member['lastTransactionAmount'] > 3 || $member['isActive']) && + $member['role'] === 'BACKER' && + $member['type'] !== 'USER' && + ( + $member['totalAmountDonated'] > 100 || + $member['lastTransactionAt'] > CarbonImmutable::now() + ->subMonthsNoOverflow(getMaxHistoryMonthsByAmount($member['lastTransactionAmount'])) + ->format('Y-m-d h:i') || + $member['isActive'] && $member['lastTransactionAmount'] >= 30 + ); + }); + + $list = array_map(static function (array $member): array { + $createdAt = CarbonImmutable::parse($member['createdAt']); + $lastTransactionAt = CarbonImmutable::parse($member['lastTransactionAt']); + + if ($createdAt->format('d H:i:s.u') > $lastTransactionAt->format('d H:i:s.u')) { + $createdAt = $createdAt + ->setDay($lastTransactionAt->day) + ->modify($lastTransactionAt->format('H:i:s.u')); + } + + $monthlyContribution = (float) ($member['totalAmountDonated'] / ceil($createdAt->floatDiffInMonths())); + + if ( + $lastTransactionAt->isAfter('last month') && + $member['lastTransactionAmount'] > $monthlyContribution + ) { + $monthlyContribution = (float) $member['lastTransactionAmount']; + } + + $yearlyContribution = (float) ($member['totalAmountDonated'] / max(1, $createdAt->floatDiffInYears())); + $status = null; + + if ($monthlyContribution > 29) { + $status = 'sponsor'; + } elseif ($monthlyContribution > 4.5 || $yearlyContribution > 29) { + $status = 'backer'; + } elseif ($member['totalAmountDonated'] > 0) { + $status = 'helper'; + } + + return array_merge($member, [ + 'star' => ($monthlyContribution > 98 || $yearlyContribution > 500), + 'status' => $status, + 'monthlyContribution' => $monthlyContribution, + 'yearlyContribution' => $yearlyContribution, + ]); + }, $list); + + usort($list, static function (array $a, array $b): int { + return ($b['monthlyContribution'] <=> $a['monthlyContribution']) + ?: ($b['totalAmountDonated'] <=> $a['totalAmountDonated']); + }); + + return implode('', array_map(static function (array $member) use ($customSponsorImages): string { + $href = htmlspecialchars($member['website'] ?? $member['profile']); + $src = $customSponsorImages[$member['MemberId'] ?? ''] ?? $member['image'] ?? (strtr($member['profile'], ['https://opencollective.com/' => 'https://images.opencollective.com/']).'/avatar/256.png'); + [$x, $y] = @getimagesize($src) ?: [0, 0]; + $validImage = ($x && $y); + $src = $validImage ? htmlspecialchars($src) : 'https://opencollective.com/static/images/default-guest-logo.svg'; + $height = $member['status'] === 'sponsor' ? 64 : 42; + $width = min($height * 2, $validImage ? round($x * $height / $y) : $height); + $href .= (strpos($href, '?') === false ? '?' : '&').'utm_source=opencollective&utm_medium=github&utm_campaign=Carbon'; + $title = getHtmlAttribute(($member['description'] ?? null) ?: $member['name']); + $alt = getHtmlAttribute($member['name']); + + return "\n".''. + ''.$alt.''. + ''; + }, $list))."\n"; +} + +file_put_contents('readme.md', preg_replace_callback( + '/()[\s\S]+()/', + static function (array $match): string { + return $match[1].getOpenCollectiveSponsors().$match[2]; + }, + file_get_contents('readme.md') +)); diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/AbstractTranslator.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/AbstractTranslator.php index 48441e7c2..8b8fe089e 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/AbstractTranslator.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/AbstractTranslator.php @@ -11,6 +11,7 @@ namespace Carbon; +use Carbon\MessageFormatter\MessageFormatterMapper; use Closure; use ReflectionException; use ReflectionFunction; @@ -51,7 +52,7 @@ abstract class AbstractTranslator extends Translation\Translator /** * List of locales aliases. * - * @var string[] + * @var array */ protected $aliases = [ 'me' => 'sr_Latn_ME', @@ -83,7 +84,7 @@ abstract class AbstractTranslator extends Translation\Translator $this->initializing = true; $this->directories = [__DIR__.'/Lang']; $this->addLoader('array', new ArrayLoader()); - parent::__construct($locale, $formatter, $cacheDir, $debug); + parent::__construct($locale, new MessageFormatterMapper($formatter), $cacheDir, $debug); $this->initializing = false; } @@ -220,8 +221,8 @@ abstract class AbstractTranslator extends Translation\Translator $catalogue = $this->getCatalogue($locale); $format = $this instanceof TranslatorStrongTypeInterface - ? $this->getFromCatalogue($catalogue, (string) $id, $domain) // @codeCoverageIgnore - : $this->getCatalogue($locale)->get((string) $id, $domain); + ? $this->getFromCatalogue($catalogue, (string) $id, $domain) + : $this->getCatalogue($locale)->get((string) $id, $domain); // @codeCoverageIgnore if ($format instanceof Closure) { // @codeCoverageIgnoreStart @@ -250,11 +251,7 @@ abstract class AbstractTranslator extends Translation\Translator */ protected function loadMessagesFromFile($locale) { - if (isset($this->messages[$locale])) { - return true; - } - - return $this->resetMessages($locale); + return isset($this->messages[$locale]) || $this->resetMessages($locale); } /** @@ -311,7 +308,7 @@ abstract class AbstractTranslator extends Translation\Translator */ public function setLocale($locale) { - $locale = preg_replace_callback('/[-_]([a-z]{2,}|[0-9]{2,})/', function ($matches) { + $locale = preg_replace_callback('/[-_]([a-z]{2,}|\d{2,})/', function ($matches) { // _2-letters or YUE is a region, _3+-letters is a variant $upper = strtoupper($matches[1]); @@ -359,13 +356,13 @@ abstract class AbstractTranslator extends Translation\Translator parent::setLocale($macroLocale); } - if ($this->loadMessagesFromFile($locale) || $this->initializing) { - parent::setLocale($locale); - - return true; + if (!$this->loadMessagesFromFile($locale) && !$this->initializing) { + return false; } - return false; + parent::setLocale($locale); + + return true; } /** diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Carbon.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Carbon.php index e327590e2..e32569ae3 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Carbon.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Carbon.php @@ -33,477 +33,477 @@ use DateTimeZone; * @property int $second * @property int $micro * @property int $microsecond - * @property int|float|string $timestamp seconds since the Unix Epoch - * @property string $englishDayOfWeek the day of week in English - * @property string $shortEnglishDayOfWeek the abbreviated day of week in English - * @property string $englishMonth the month in English - * @property string $shortEnglishMonth the abbreviated month in English + * @property int|float|string $timestamp seconds since the Unix Epoch + * @property string $englishDayOfWeek the day of week in English + * @property string $shortEnglishDayOfWeek the abbreviated day of week in English + * @property string $englishMonth the month in English + * @property string $shortEnglishMonth the abbreviated month in English * @property int $milliseconds * @property int $millisecond * @property int $milli - * @property int $week 1 through 53 - * @property int $isoWeek 1 through 53 - * @property int $weekYear year according to week format - * @property int $isoWeekYear year according to ISO week format - * @property int $dayOfYear 1 through 366 - * @property int $age does a diffInYears() with default parameters - * @property int $offset the timezone offset in seconds from UTC - * @property int $offsetMinutes the timezone offset in minutes from UTC - * @property int $offsetHours the timezone offset in hours from UTC - * @property CarbonTimeZone $timezone the current timezone - * @property CarbonTimeZone $tz alias of $timezone - * @property-read int $dayOfWeek 0 (for Sunday) through 6 (for Saturday) - * @property-read int $dayOfWeekIso 1 (for Monday) through 7 (for Sunday) - * @property-read int $weekOfYear ISO-8601 week number of year, weeks starting on Monday - * @property-read int $daysInMonth number of days in the given month - * @property-read string $latinMeridiem "am"/"pm" (Ante meridiem or Post meridiem latin lowercase mark) - * @property-read string $latinUpperMeridiem "AM"/"PM" (Ante meridiem or Post meridiem latin uppercase mark) - * @property-read string $timezoneAbbreviatedName the current timezone abbreviated name - * @property-read string $tzAbbrName alias of $timezoneAbbreviatedName - * @property-read string $dayName long name of weekday translated according to Carbon locale, in english if no translation available for current language - * @property-read string $shortDayName short name of weekday translated according to Carbon locale, in english if no translation available for current language - * @property-read string $minDayName very short name of weekday translated according to Carbon locale, in english if no translation available for current language - * @property-read string $monthName long name of month translated according to Carbon locale, in english if no translation available for current language - * @property-read string $shortMonthName short name of month translated according to Carbon locale, in english if no translation available for current language - * @property-read string $meridiem lowercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language - * @property-read string $upperMeridiem uppercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language - * @property-read int $noZeroHour current hour from 1 to 24 - * @property-read int $weeksInYear 51 through 53 - * @property-read int $isoWeeksInYear 51 through 53 - * @property-read int $weekOfMonth 1 through 5 - * @property-read int $weekNumberInMonth 1 through 5 - * @property-read int $firstWeekDay 0 through 6 - * @property-read int $lastWeekDay 0 through 6 - * @property-read int $daysInYear 365 or 366 - * @property-read int $quarter the quarter of this instance, 1 - 4 - * @property-read int $decade the decade of this instance - * @property-read int $century the century of this instance - * @property-read int $millennium the millennium of this instance - * @property-read bool $dst daylight savings time indicator, true if DST, false otherwise - * @property-read bool $local checks if the timezone is local, true if local, false otherwise - * @property-read bool $utc checks if the timezone is UTC, true if UTC, false otherwise - * @property-read string $timezoneName the current timezone name - * @property-read string $tzName alias of $timezoneName - * @property-read string $locale locale of the current instance + * @property int $week 1 through 53 + * @property int $isoWeek 1 through 53 + * @property int $weekYear year according to week format + * @property int $isoWeekYear year according to ISO week format + * @property int $dayOfYear 1 through 366 + * @property int $age does a diffInYears() with default parameters + * @property int $offset the timezone offset in seconds from UTC + * @property int $offsetMinutes the timezone offset in minutes from UTC + * @property int $offsetHours the timezone offset in hours from UTC + * @property CarbonTimeZone $timezone the current timezone + * @property CarbonTimeZone $tz alias of $timezone + * @property-read int $dayOfWeek 0 (for Sunday) through 6 (for Saturday) + * @property-read int $dayOfWeekIso 1 (for Monday) through 7 (for Sunday) + * @property-read int $weekOfYear ISO-8601 week number of year, weeks starting on Monday + * @property-read int $daysInMonth number of days in the given month + * @property-read string $latinMeridiem "am"/"pm" (Ante meridiem or Post meridiem latin lowercase mark) + * @property-read string $latinUpperMeridiem "AM"/"PM" (Ante meridiem or Post meridiem latin uppercase mark) + * @property-read string $timezoneAbbreviatedName the current timezone abbreviated name + * @property-read string $tzAbbrName alias of $timezoneAbbreviatedName + * @property-read string $dayName long name of weekday translated according to Carbon locale, in english if no translation available for current language + * @property-read string $shortDayName short name of weekday translated according to Carbon locale, in english if no translation available for current language + * @property-read string $minDayName very short name of weekday translated according to Carbon locale, in english if no translation available for current language + * @property-read string $monthName long name of month translated according to Carbon locale, in english if no translation available for current language + * @property-read string $shortMonthName short name of month translated according to Carbon locale, in english if no translation available for current language + * @property-read string $meridiem lowercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language + * @property-read string $upperMeridiem uppercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language + * @property-read int $noZeroHour current hour from 1 to 24 + * @property-read int $weeksInYear 51 through 53 + * @property-read int $isoWeeksInYear 51 through 53 + * @property-read int $weekOfMonth 1 through 5 + * @property-read int $weekNumberInMonth 1 through 5 + * @property-read int $firstWeekDay 0 through 6 + * @property-read int $lastWeekDay 0 through 6 + * @property-read int $daysInYear 365 or 366 + * @property-read int $quarter the quarter of this instance, 1 - 4 + * @property-read int $decade the decade of this instance + * @property-read int $century the century of this instance + * @property-read int $millennium the millennium of this instance + * @property-read bool $dst daylight savings time indicator, true if DST, false otherwise + * @property-read bool $local checks if the timezone is local, true if local, false otherwise + * @property-read bool $utc checks if the timezone is UTC, true if UTC, false otherwise + * @property-read string $timezoneName the current timezone name + * @property-read string $tzName alias of $timezoneName + * @property-read string $locale locale of the current instance * - * @method bool isUtc() Check if the current instance has UTC timezone. (Both isUtc and isUTC cases are valid.) - * @method bool isLocal() Check if the current instance has non-UTC timezone. - * @method bool isValid() Check if the current instance is a valid date. - * @method bool isDST() Check if the current instance is in a daylight saving time. - * @method bool isSunday() Checks if the instance day is sunday. - * @method bool isMonday() Checks if the instance day is monday. - * @method bool isTuesday() Checks if the instance day is tuesday. - * @method bool isWednesday() Checks if the instance day is wednesday. - * @method bool isThursday() Checks if the instance day is thursday. - * @method bool isFriday() Checks if the instance day is friday. - * @method bool isSaturday() Checks if the instance day is saturday. - * @method bool isSameYear(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same year as the instance. If null passed, compare to now (with the same timezone). - * @method bool isCurrentYear() Checks if the instance is in the same year as the current moment. - * @method bool isNextYear() Checks if the instance is in the same year as the current moment next year. - * @method bool isLastYear() Checks if the instance is in the same year as the current moment last year. - * @method bool isSameWeek(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same week as the instance. If null passed, compare to now (with the same timezone). - * @method bool isCurrentWeek() Checks if the instance is in the same week as the current moment. - * @method bool isNextWeek() Checks if the instance is in the same week as the current moment next week. - * @method bool isLastWeek() Checks if the instance is in the same week as the current moment last week. - * @method bool isSameDay(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same day as the instance. If null passed, compare to now (with the same timezone). - * @method bool isCurrentDay() Checks if the instance is in the same day as the current moment. - * @method bool isNextDay() Checks if the instance is in the same day as the current moment next day. - * @method bool isLastDay() Checks if the instance is in the same day as the current moment last day. - * @method bool isSameHour(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same hour as the instance. If null passed, compare to now (with the same timezone). - * @method bool isCurrentHour() Checks if the instance is in the same hour as the current moment. - * @method bool isNextHour() Checks if the instance is in the same hour as the current moment next hour. - * @method bool isLastHour() Checks if the instance is in the same hour as the current moment last hour. - * @method bool isSameMinute(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same minute as the instance. If null passed, compare to now (with the same timezone). - * @method bool isCurrentMinute() Checks if the instance is in the same minute as the current moment. - * @method bool isNextMinute() Checks if the instance is in the same minute as the current moment next minute. - * @method bool isLastMinute() Checks if the instance is in the same minute as the current moment last minute. - * @method bool isSameSecond(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same second as the instance. If null passed, compare to now (with the same timezone). - * @method bool isCurrentSecond() Checks if the instance is in the same second as the current moment. - * @method bool isNextSecond() Checks if the instance is in the same second as the current moment next second. - * @method bool isLastSecond() Checks if the instance is in the same second as the current moment last second. - * @method bool isSameMicro(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same microsecond as the instance. If null passed, compare to now (with the same timezone). - * @method bool isCurrentMicro() Checks if the instance is in the same microsecond as the current moment. - * @method bool isNextMicro() Checks if the instance is in the same microsecond as the current moment next microsecond. - * @method bool isLastMicro() Checks if the instance is in the same microsecond as the current moment last microsecond. - * @method bool isSameMicrosecond(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same microsecond as the instance. If null passed, compare to now (with the same timezone). - * @method bool isCurrentMicrosecond() Checks if the instance is in the same microsecond as the current moment. - * @method bool isNextMicrosecond() Checks if the instance is in the same microsecond as the current moment next microsecond. - * @method bool isLastMicrosecond() Checks if the instance is in the same microsecond as the current moment last microsecond. - * @method bool isCurrentMonth() Checks if the instance is in the same month as the current moment. - * @method bool isNextMonth() Checks if the instance is in the same month as the current moment next month. - * @method bool isLastMonth() Checks if the instance is in the same month as the current moment last month. - * @method bool isCurrentQuarter() Checks if the instance is in the same quarter as the current moment. - * @method bool isNextQuarter() Checks if the instance is in the same quarter as the current moment next quarter. - * @method bool isLastQuarter() Checks if the instance is in the same quarter as the current moment last quarter. - * @method bool isSameDecade(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same decade as the instance. If null passed, compare to now (with the same timezone). - * @method bool isCurrentDecade() Checks if the instance is in the same decade as the current moment. - * @method bool isNextDecade() Checks if the instance is in the same decade as the current moment next decade. - * @method bool isLastDecade() Checks if the instance is in the same decade as the current moment last decade. - * @method bool isSameCentury(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same century as the instance. If null passed, compare to now (with the same timezone). - * @method bool isCurrentCentury() Checks if the instance is in the same century as the current moment. - * @method bool isNextCentury() Checks if the instance is in the same century as the current moment next century. - * @method bool isLastCentury() Checks if the instance is in the same century as the current moment last century. - * @method bool isSameMillennium(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same millennium as the instance. If null passed, compare to now (with the same timezone). - * @method bool isCurrentMillennium() Checks if the instance is in the same millennium as the current moment. - * @method bool isNextMillennium() Checks if the instance is in the same millennium as the current moment next millennium. - * @method bool isLastMillennium() Checks if the instance is in the same millennium as the current moment last millennium. - * @method $this years(int $value) Set current instance year to the given value. - * @method $this year(int $value) Set current instance year to the given value. - * @method $this setYears(int $value) Set current instance year to the given value. - * @method $this setYear(int $value) Set current instance year to the given value. - * @method $this months(int $value) Set current instance month to the given value. - * @method $this month(int $value) Set current instance month to the given value. - * @method $this setMonths(int $value) Set current instance month to the given value. - * @method $this setMonth(int $value) Set current instance month to the given value. - * @method $this days(int $value) Set current instance day to the given value. - * @method $this day(int $value) Set current instance day to the given value. - * @method $this setDays(int $value) Set current instance day to the given value. - * @method $this setDay(int $value) Set current instance day to the given value. - * @method $this hours(int $value) Set current instance hour to the given value. - * @method $this hour(int $value) Set current instance hour to the given value. - * @method $this setHours(int $value) Set current instance hour to the given value. - * @method $this setHour(int $value) Set current instance hour to the given value. - * @method $this minutes(int $value) Set current instance minute to the given value. - * @method $this minute(int $value) Set current instance minute to the given value. - * @method $this setMinutes(int $value) Set current instance minute to the given value. - * @method $this setMinute(int $value) Set current instance minute to the given value. - * @method $this seconds(int $value) Set current instance second to the given value. - * @method $this second(int $value) Set current instance second to the given value. - * @method $this setSeconds(int $value) Set current instance second to the given value. - * @method $this setSecond(int $value) Set current instance second to the given value. - * @method $this millis(int $value) Set current instance millisecond to the given value. - * @method $this milli(int $value) Set current instance millisecond to the given value. - * @method $this setMillis(int $value) Set current instance millisecond to the given value. - * @method $this setMilli(int $value) Set current instance millisecond to the given value. - * @method $this milliseconds(int $value) Set current instance millisecond to the given value. - * @method $this millisecond(int $value) Set current instance millisecond to the given value. - * @method $this setMilliseconds(int $value) Set current instance millisecond to the given value. - * @method $this setMillisecond(int $value) Set current instance millisecond to the given value. - * @method $this micros(int $value) Set current instance microsecond to the given value. - * @method $this micro(int $value) Set current instance microsecond to the given value. - * @method $this setMicros(int $value) Set current instance microsecond to the given value. - * @method $this setMicro(int $value) Set current instance microsecond to the given value. - * @method $this microseconds(int $value) Set current instance microsecond to the given value. - * @method $this microsecond(int $value) Set current instance microsecond to the given value. - * @method $this setMicroseconds(int $value) Set current instance microsecond to the given value. - * @method $this setMicrosecond(int $value) Set current instance microsecond to the given value. - * @method $this addYears(int $value = 1) Add years (the $value count passed in) to the instance (using date interval). - * @method $this addYear() Add one year to the instance (using date interval). - * @method $this subYears(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval). - * @method $this subYear() Sub one year to the instance (using date interval). - * @method $this addYearsWithOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. - * @method $this addYearWithOverflow() Add one year to the instance (using date interval) with overflow explicitly allowed. - * @method $this subYearsWithOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. - * @method $this subYearWithOverflow() Sub one year to the instance (using date interval) with overflow explicitly allowed. - * @method $this addYearsWithoutOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addYearWithoutOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subYearsWithoutOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subYearWithoutOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addYearsWithNoOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addYearWithNoOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subYearsWithNoOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subYearWithNoOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addYearsNoOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addYearNoOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subYearsNoOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subYearNoOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addMonths(int $value = 1) Add months (the $value count passed in) to the instance (using date interval). - * @method $this addMonth() Add one month to the instance (using date interval). - * @method $this subMonths(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval). - * @method $this subMonth() Sub one month to the instance (using date interval). - * @method $this addMonthsWithOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. - * @method $this addMonthWithOverflow() Add one month to the instance (using date interval) with overflow explicitly allowed. - * @method $this subMonthsWithOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. - * @method $this subMonthWithOverflow() Sub one month to the instance (using date interval) with overflow explicitly allowed. - * @method $this addMonthsWithoutOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addMonthWithoutOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subMonthsWithoutOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subMonthWithoutOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addMonthsWithNoOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addMonthWithNoOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subMonthsWithNoOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subMonthWithNoOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addMonthsNoOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addMonthNoOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subMonthsNoOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subMonthNoOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addDays(int $value = 1) Add days (the $value count passed in) to the instance (using date interval). - * @method $this addDay() Add one day to the instance (using date interval). - * @method $this subDays(int $value = 1) Sub days (the $value count passed in) to the instance (using date interval). - * @method $this subDay() Sub one day to the instance (using date interval). - * @method $this addHours(int $value = 1) Add hours (the $value count passed in) to the instance (using date interval). - * @method $this addHour() Add one hour to the instance (using date interval). - * @method $this subHours(int $value = 1) Sub hours (the $value count passed in) to the instance (using date interval). - * @method $this subHour() Sub one hour to the instance (using date interval). - * @method $this addMinutes(int $value = 1) Add minutes (the $value count passed in) to the instance (using date interval). - * @method $this addMinute() Add one minute to the instance (using date interval). - * @method $this subMinutes(int $value = 1) Sub minutes (the $value count passed in) to the instance (using date interval). - * @method $this subMinute() Sub one minute to the instance (using date interval). - * @method $this addSeconds(int $value = 1) Add seconds (the $value count passed in) to the instance (using date interval). - * @method $this addSecond() Add one second to the instance (using date interval). - * @method $this subSeconds(int $value = 1) Sub seconds (the $value count passed in) to the instance (using date interval). - * @method $this subSecond() Sub one second to the instance (using date interval). - * @method $this addMillis(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using date interval). - * @method $this addMilli() Add one millisecond to the instance (using date interval). - * @method $this subMillis(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using date interval). - * @method $this subMilli() Sub one millisecond to the instance (using date interval). - * @method $this addMilliseconds(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using date interval). - * @method $this addMillisecond() Add one millisecond to the instance (using date interval). - * @method $this subMilliseconds(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using date interval). - * @method $this subMillisecond() Sub one millisecond to the instance (using date interval). - * @method $this addMicros(int $value = 1) Add microseconds (the $value count passed in) to the instance (using date interval). - * @method $this addMicro() Add one microsecond to the instance (using date interval). - * @method $this subMicros(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using date interval). - * @method $this subMicro() Sub one microsecond to the instance (using date interval). - * @method $this addMicroseconds(int $value = 1) Add microseconds (the $value count passed in) to the instance (using date interval). - * @method $this addMicrosecond() Add one microsecond to the instance (using date interval). - * @method $this subMicroseconds(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using date interval). - * @method $this subMicrosecond() Sub one microsecond to the instance (using date interval). - * @method $this addMillennia(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval). - * @method $this addMillennium() Add one millennium to the instance (using date interval). - * @method $this subMillennia(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval). - * @method $this subMillennium() Sub one millennium to the instance (using date interval). - * @method $this addMillenniaWithOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. - * @method $this addMillenniumWithOverflow() Add one millennium to the instance (using date interval) with overflow explicitly allowed. - * @method $this subMillenniaWithOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. - * @method $this subMillenniumWithOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly allowed. - * @method $this addMillenniaWithoutOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addMillenniumWithoutOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subMillenniaWithoutOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subMillenniumWithoutOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addMillenniaWithNoOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addMillenniumWithNoOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subMillenniaWithNoOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subMillenniumWithNoOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addMillenniaNoOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addMillenniumNoOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subMillenniaNoOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subMillenniumNoOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addCenturies(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval). - * @method $this addCentury() Add one century to the instance (using date interval). - * @method $this subCenturies(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval). - * @method $this subCentury() Sub one century to the instance (using date interval). - * @method $this addCenturiesWithOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. - * @method $this addCenturyWithOverflow() Add one century to the instance (using date interval) with overflow explicitly allowed. - * @method $this subCenturiesWithOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. - * @method $this subCenturyWithOverflow() Sub one century to the instance (using date interval) with overflow explicitly allowed. - * @method $this addCenturiesWithoutOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addCenturyWithoutOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subCenturiesWithoutOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subCenturyWithoutOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addCenturiesWithNoOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addCenturyWithNoOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subCenturiesWithNoOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subCenturyWithNoOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addCenturiesNoOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addCenturyNoOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subCenturiesNoOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subCenturyNoOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addDecades(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval). - * @method $this addDecade() Add one decade to the instance (using date interval). - * @method $this subDecades(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval). - * @method $this subDecade() Sub one decade to the instance (using date interval). - * @method $this addDecadesWithOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. - * @method $this addDecadeWithOverflow() Add one decade to the instance (using date interval) with overflow explicitly allowed. - * @method $this subDecadesWithOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. - * @method $this subDecadeWithOverflow() Sub one decade to the instance (using date interval) with overflow explicitly allowed. - * @method $this addDecadesWithoutOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addDecadeWithoutOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subDecadesWithoutOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subDecadeWithoutOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addDecadesWithNoOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addDecadeWithNoOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subDecadesWithNoOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subDecadeWithNoOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addDecadesNoOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addDecadeNoOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subDecadesNoOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subDecadeNoOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addQuarters(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval). - * @method $this addQuarter() Add one quarter to the instance (using date interval). - * @method $this subQuarters(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval). - * @method $this subQuarter() Sub one quarter to the instance (using date interval). - * @method $this addQuartersWithOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. - * @method $this addQuarterWithOverflow() Add one quarter to the instance (using date interval) with overflow explicitly allowed. - * @method $this subQuartersWithOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. - * @method $this subQuarterWithOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly allowed. - * @method $this addQuartersWithoutOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addQuarterWithoutOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subQuartersWithoutOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subQuarterWithoutOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addQuartersWithNoOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addQuarterWithNoOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subQuartersWithNoOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subQuarterWithNoOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addQuartersNoOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addQuarterNoOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subQuartersNoOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method $this subQuarterNoOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. - * @method $this addWeeks(int $value = 1) Add weeks (the $value count passed in) to the instance (using date interval). - * @method $this addWeek() Add one week to the instance (using date interval). - * @method $this subWeeks(int $value = 1) Sub weeks (the $value count passed in) to the instance (using date interval). - * @method $this subWeek() Sub one week to the instance (using date interval). - * @method $this addWeekdays(int $value = 1) Add weekdays (the $value count passed in) to the instance (using date interval). - * @method $this addWeekday() Add one weekday to the instance (using date interval). - * @method $this subWeekdays(int $value = 1) Sub weekdays (the $value count passed in) to the instance (using date interval). - * @method $this subWeekday() Sub one weekday to the instance (using date interval). - * @method $this addRealMicros(int $value = 1) Add microseconds (the $value count passed in) to the instance (using timestamp). - * @method $this addRealMicro() Add one microsecond to the instance (using timestamp). - * @method $this subRealMicros(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using timestamp). - * @method $this subRealMicro() Sub one microsecond to the instance (using timestamp). - * @method CarbonPeriod microsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each microsecond or every X microseconds if a factor is given. - * @method $this addRealMicroseconds(int $value = 1) Add microseconds (the $value count passed in) to the instance (using timestamp). - * @method $this addRealMicrosecond() Add one microsecond to the instance (using timestamp). - * @method $this subRealMicroseconds(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using timestamp). - * @method $this subRealMicrosecond() Sub one microsecond to the instance (using timestamp). - * @method CarbonPeriod microsecondsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each microsecond or every X microseconds if a factor is given. - * @method $this addRealMillis(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using timestamp). - * @method $this addRealMilli() Add one millisecond to the instance (using timestamp). - * @method $this subRealMillis(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using timestamp). - * @method $this subRealMilli() Sub one millisecond to the instance (using timestamp). - * @method CarbonPeriod millisUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millisecond or every X milliseconds if a factor is given. - * @method $this addRealMilliseconds(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using timestamp). - * @method $this addRealMillisecond() Add one millisecond to the instance (using timestamp). - * @method $this subRealMilliseconds(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using timestamp). - * @method $this subRealMillisecond() Sub one millisecond to the instance (using timestamp). - * @method CarbonPeriod millisecondsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millisecond or every X milliseconds if a factor is given. - * @method $this addRealSeconds(int $value = 1) Add seconds (the $value count passed in) to the instance (using timestamp). - * @method $this addRealSecond() Add one second to the instance (using timestamp). - * @method $this subRealSeconds(int $value = 1) Sub seconds (the $value count passed in) to the instance (using timestamp). - * @method $this subRealSecond() Sub one second to the instance (using timestamp). - * @method CarbonPeriod secondsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each second or every X seconds if a factor is given. - * @method $this addRealMinutes(int $value = 1) Add minutes (the $value count passed in) to the instance (using timestamp). - * @method $this addRealMinute() Add one minute to the instance (using timestamp). - * @method $this subRealMinutes(int $value = 1) Sub minutes (the $value count passed in) to the instance (using timestamp). - * @method $this subRealMinute() Sub one minute to the instance (using timestamp). - * @method CarbonPeriod minutesUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each minute or every X minutes if a factor is given. - * @method $this addRealHours(int $value = 1) Add hours (the $value count passed in) to the instance (using timestamp). - * @method $this addRealHour() Add one hour to the instance (using timestamp). - * @method $this subRealHours(int $value = 1) Sub hours (the $value count passed in) to the instance (using timestamp). - * @method $this subRealHour() Sub one hour to the instance (using timestamp). - * @method CarbonPeriod hoursUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each hour or every X hours if a factor is given. - * @method $this addRealDays(int $value = 1) Add days (the $value count passed in) to the instance (using timestamp). - * @method $this addRealDay() Add one day to the instance (using timestamp). - * @method $this subRealDays(int $value = 1) Sub days (the $value count passed in) to the instance (using timestamp). - * @method $this subRealDay() Sub one day to the instance (using timestamp). - * @method CarbonPeriod daysUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each day or every X days if a factor is given. - * @method $this addRealWeeks(int $value = 1) Add weeks (the $value count passed in) to the instance (using timestamp). - * @method $this addRealWeek() Add one week to the instance (using timestamp). - * @method $this subRealWeeks(int $value = 1) Sub weeks (the $value count passed in) to the instance (using timestamp). - * @method $this subRealWeek() Sub one week to the instance (using timestamp). - * @method CarbonPeriod weeksUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each week or every X weeks if a factor is given. - * @method $this addRealMonths(int $value = 1) Add months (the $value count passed in) to the instance (using timestamp). - * @method $this addRealMonth() Add one month to the instance (using timestamp). - * @method $this subRealMonths(int $value = 1) Sub months (the $value count passed in) to the instance (using timestamp). - * @method $this subRealMonth() Sub one month to the instance (using timestamp). - * @method CarbonPeriod monthsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each month or every X months if a factor is given. - * @method $this addRealQuarters(int $value = 1) Add quarters (the $value count passed in) to the instance (using timestamp). - * @method $this addRealQuarter() Add one quarter to the instance (using timestamp). - * @method $this subRealQuarters(int $value = 1) Sub quarters (the $value count passed in) to the instance (using timestamp). - * @method $this subRealQuarter() Sub one quarter to the instance (using timestamp). - * @method CarbonPeriod quartersUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each quarter or every X quarters if a factor is given. - * @method $this addRealYears(int $value = 1) Add years (the $value count passed in) to the instance (using timestamp). - * @method $this addRealYear() Add one year to the instance (using timestamp). - * @method $this subRealYears(int $value = 1) Sub years (the $value count passed in) to the instance (using timestamp). - * @method $this subRealYear() Sub one year to the instance (using timestamp). - * @method CarbonPeriod yearsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each year or every X years if a factor is given. - * @method $this addRealDecades(int $value = 1) Add decades (the $value count passed in) to the instance (using timestamp). - * @method $this addRealDecade() Add one decade to the instance (using timestamp). - * @method $this subRealDecades(int $value = 1) Sub decades (the $value count passed in) to the instance (using timestamp). - * @method $this subRealDecade() Sub one decade to the instance (using timestamp). - * @method CarbonPeriod decadesUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each decade or every X decades if a factor is given. - * @method $this addRealCenturies(int $value = 1) Add centuries (the $value count passed in) to the instance (using timestamp). - * @method $this addRealCentury() Add one century to the instance (using timestamp). - * @method $this subRealCenturies(int $value = 1) Sub centuries (the $value count passed in) to the instance (using timestamp). - * @method $this subRealCentury() Sub one century to the instance (using timestamp). - * @method CarbonPeriod centuriesUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each century or every X centuries if a factor is given. - * @method $this addRealMillennia(int $value = 1) Add millennia (the $value count passed in) to the instance (using timestamp). - * @method $this addRealMillennium() Add one millennium to the instance (using timestamp). - * @method $this subRealMillennia(int $value = 1) Sub millennia (the $value count passed in) to the instance (using timestamp). - * @method $this subRealMillennium() Sub one millennium to the instance (using timestamp). - * @method CarbonPeriod millenniaUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millennium or every X millennia if a factor is given. - * @method $this roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. - * @method $this roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. - * @method $this floorYear(float $precision = 1) Truncate the current instance year with given precision. - * @method $this floorYears(float $precision = 1) Truncate the current instance year with given precision. - * @method $this ceilYear(float $precision = 1) Ceil the current instance year with given precision. - * @method $this ceilYears(float $precision = 1) Ceil the current instance year with given precision. - * @method $this roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. - * @method $this roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. - * @method $this floorMonth(float $precision = 1) Truncate the current instance month with given precision. - * @method $this floorMonths(float $precision = 1) Truncate the current instance month with given precision. - * @method $this ceilMonth(float $precision = 1) Ceil the current instance month with given precision. - * @method $this ceilMonths(float $precision = 1) Ceil the current instance month with given precision. - * @method $this roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. - * @method $this roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. - * @method $this floorDay(float $precision = 1) Truncate the current instance day with given precision. - * @method $this floorDays(float $precision = 1) Truncate the current instance day with given precision. - * @method $this ceilDay(float $precision = 1) Ceil the current instance day with given precision. - * @method $this ceilDays(float $precision = 1) Ceil the current instance day with given precision. - * @method $this roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. - * @method $this roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. - * @method $this floorHour(float $precision = 1) Truncate the current instance hour with given precision. - * @method $this floorHours(float $precision = 1) Truncate the current instance hour with given precision. - * @method $this ceilHour(float $precision = 1) Ceil the current instance hour with given precision. - * @method $this ceilHours(float $precision = 1) Ceil the current instance hour with given precision. - * @method $this roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. - * @method $this roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. - * @method $this floorMinute(float $precision = 1) Truncate the current instance minute with given precision. - * @method $this floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. - * @method $this ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. - * @method $this ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. - * @method $this roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. - * @method $this roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. - * @method $this floorSecond(float $precision = 1) Truncate the current instance second with given precision. - * @method $this floorSeconds(float $precision = 1) Truncate the current instance second with given precision. - * @method $this ceilSecond(float $precision = 1) Ceil the current instance second with given precision. - * @method $this ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. - * @method $this roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. - * @method $this roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. - * @method $this floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. - * @method $this floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. - * @method $this ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. - * @method $this ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. - * @method $this roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. - * @method $this roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. - * @method $this floorCentury(float $precision = 1) Truncate the current instance century with given precision. - * @method $this floorCenturies(float $precision = 1) Truncate the current instance century with given precision. - * @method $this ceilCentury(float $precision = 1) Ceil the current instance century with given precision. - * @method $this ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. - * @method $this roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. - * @method $this roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. - * @method $this floorDecade(float $precision = 1) Truncate the current instance decade with given precision. - * @method $this floorDecades(float $precision = 1) Truncate the current instance decade with given precision. - * @method $this ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. - * @method $this ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. - * @method $this roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. - * @method $this roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. - * @method $this floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. - * @method $this floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. - * @method $this ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. - * @method $this ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. - * @method $this roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. - * @method $this roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. - * @method $this floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. - * @method $this floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. - * @method $this ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. - * @method $this ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. - * @method $this roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. - * @method $this roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. - * @method $this floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. - * @method $this floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. - * @method $this ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. - * @method $this ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. - * @method string shortAbsoluteDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'Absolute' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) - * @method string longAbsoluteDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'Absolute' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) - * @method string shortRelativeDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'Relative' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) - * @method string longRelativeDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'Relative' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) - * @method string shortRelativeToNowDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'RelativeToNow' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) - * @method string longRelativeToNowDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'RelativeToNow' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) - * @method string shortRelativeToOtherDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'RelativeToOther' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) - * @method string longRelativeToOtherDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'RelativeToOther' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) - * @method static Carbon|false createFromFormat(string $format, string $time, string|DateTimeZone $timezone = null) Parse a string into a new Carbon object according to the specified format. - * @method static Carbon __set_state(array $array) https://php.net/manual/en/datetime.set-state.php + * @method bool isUtc() Check if the current instance has UTC timezone. (Both isUtc and isUTC cases are valid.) + * @method bool isLocal() Check if the current instance has non-UTC timezone. + * @method bool isValid() Check if the current instance is a valid date. + * @method bool isDST() Check if the current instance is in a daylight saving time. + * @method bool isSunday() Checks if the instance day is sunday. + * @method bool isMonday() Checks if the instance day is monday. + * @method bool isTuesday() Checks if the instance day is tuesday. + * @method bool isWednesday() Checks if the instance day is wednesday. + * @method bool isThursday() Checks if the instance day is thursday. + * @method bool isFriday() Checks if the instance day is friday. + * @method bool isSaturday() Checks if the instance day is saturday. + * @method bool isSameYear(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same year as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentYear() Checks if the instance is in the same year as the current moment. + * @method bool isNextYear() Checks if the instance is in the same year as the current moment next year. + * @method bool isLastYear() Checks if the instance is in the same year as the current moment last year. + * @method bool isSameWeek(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same week as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentWeek() Checks if the instance is in the same week as the current moment. + * @method bool isNextWeek() Checks if the instance is in the same week as the current moment next week. + * @method bool isLastWeek() Checks if the instance is in the same week as the current moment last week. + * @method bool isSameDay(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same day as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentDay() Checks if the instance is in the same day as the current moment. + * @method bool isNextDay() Checks if the instance is in the same day as the current moment next day. + * @method bool isLastDay() Checks if the instance is in the same day as the current moment last day. + * @method bool isSameHour(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same hour as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentHour() Checks if the instance is in the same hour as the current moment. + * @method bool isNextHour() Checks if the instance is in the same hour as the current moment next hour. + * @method bool isLastHour() Checks if the instance is in the same hour as the current moment last hour. + * @method bool isSameMinute(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same minute as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentMinute() Checks if the instance is in the same minute as the current moment. + * @method bool isNextMinute() Checks if the instance is in the same minute as the current moment next minute. + * @method bool isLastMinute() Checks if the instance is in the same minute as the current moment last minute. + * @method bool isSameSecond(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same second as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentSecond() Checks if the instance is in the same second as the current moment. + * @method bool isNextSecond() Checks if the instance is in the same second as the current moment next second. + * @method bool isLastSecond() Checks if the instance is in the same second as the current moment last second. + * @method bool isSameMicro(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same microsecond as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentMicro() Checks if the instance is in the same microsecond as the current moment. + * @method bool isNextMicro() Checks if the instance is in the same microsecond as the current moment next microsecond. + * @method bool isLastMicro() Checks if the instance is in the same microsecond as the current moment last microsecond. + * @method bool isSameMicrosecond(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same microsecond as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentMicrosecond() Checks if the instance is in the same microsecond as the current moment. + * @method bool isNextMicrosecond() Checks if the instance is in the same microsecond as the current moment next microsecond. + * @method bool isLastMicrosecond() Checks if the instance is in the same microsecond as the current moment last microsecond. + * @method bool isCurrentMonth() Checks if the instance is in the same month as the current moment. + * @method bool isNextMonth() Checks if the instance is in the same month as the current moment next month. + * @method bool isLastMonth() Checks if the instance is in the same month as the current moment last month. + * @method bool isCurrentQuarter() Checks if the instance is in the same quarter as the current moment. + * @method bool isNextQuarter() Checks if the instance is in the same quarter as the current moment next quarter. + * @method bool isLastQuarter() Checks if the instance is in the same quarter as the current moment last quarter. + * @method bool isSameDecade(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same decade as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentDecade() Checks if the instance is in the same decade as the current moment. + * @method bool isNextDecade() Checks if the instance is in the same decade as the current moment next decade. + * @method bool isLastDecade() Checks if the instance is in the same decade as the current moment last decade. + * @method bool isSameCentury(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same century as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentCentury() Checks if the instance is in the same century as the current moment. + * @method bool isNextCentury() Checks if the instance is in the same century as the current moment next century. + * @method bool isLastCentury() Checks if the instance is in the same century as the current moment last century. + * @method bool isSameMillennium(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same millennium as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentMillennium() Checks if the instance is in the same millennium as the current moment. + * @method bool isNextMillennium() Checks if the instance is in the same millennium as the current moment next millennium. + * @method bool isLastMillennium() Checks if the instance is in the same millennium as the current moment last millennium. + * @method $this years(int $value) Set current instance year to the given value. + * @method $this year(int $value) Set current instance year to the given value. + * @method $this setYears(int $value) Set current instance year to the given value. + * @method $this setYear(int $value) Set current instance year to the given value. + * @method $this months(int $value) Set current instance month to the given value. + * @method $this month(int $value) Set current instance month to the given value. + * @method $this setMonths(int $value) Set current instance month to the given value. + * @method $this setMonth(int $value) Set current instance month to the given value. + * @method $this days(int $value) Set current instance day to the given value. + * @method $this day(int $value) Set current instance day to the given value. + * @method $this setDays(int $value) Set current instance day to the given value. + * @method $this setDay(int $value) Set current instance day to the given value. + * @method $this hours(int $value) Set current instance hour to the given value. + * @method $this hour(int $value) Set current instance hour to the given value. + * @method $this setHours(int $value) Set current instance hour to the given value. + * @method $this setHour(int $value) Set current instance hour to the given value. + * @method $this minutes(int $value) Set current instance minute to the given value. + * @method $this minute(int $value) Set current instance minute to the given value. + * @method $this setMinutes(int $value) Set current instance minute to the given value. + * @method $this setMinute(int $value) Set current instance minute to the given value. + * @method $this seconds(int $value) Set current instance second to the given value. + * @method $this second(int $value) Set current instance second to the given value. + * @method $this setSeconds(int $value) Set current instance second to the given value. + * @method $this setSecond(int $value) Set current instance second to the given value. + * @method $this millis(int $value) Set current instance millisecond to the given value. + * @method $this milli(int $value) Set current instance millisecond to the given value. + * @method $this setMillis(int $value) Set current instance millisecond to the given value. + * @method $this setMilli(int $value) Set current instance millisecond to the given value. + * @method $this milliseconds(int $value) Set current instance millisecond to the given value. + * @method $this millisecond(int $value) Set current instance millisecond to the given value. + * @method $this setMilliseconds(int $value) Set current instance millisecond to the given value. + * @method $this setMillisecond(int $value) Set current instance millisecond to the given value. + * @method $this micros(int $value) Set current instance microsecond to the given value. + * @method $this micro(int $value) Set current instance microsecond to the given value. + * @method $this setMicros(int $value) Set current instance microsecond to the given value. + * @method $this setMicro(int $value) Set current instance microsecond to the given value. + * @method $this microseconds(int $value) Set current instance microsecond to the given value. + * @method $this microsecond(int $value) Set current instance microsecond to the given value. + * @method $this setMicroseconds(int $value) Set current instance microsecond to the given value. + * @method $this setMicrosecond(int $value) Set current instance microsecond to the given value. + * @method $this addYears(int $value = 1) Add years (the $value count passed in) to the instance (using date interval). + * @method $this addYear() Add one year to the instance (using date interval). + * @method $this subYears(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval). + * @method $this subYear() Sub one year to the instance (using date interval). + * @method $this addYearsWithOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method $this addYearWithOverflow() Add one year to the instance (using date interval) with overflow explicitly allowed. + * @method $this subYearsWithOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method $this subYearWithOverflow() Sub one year to the instance (using date interval) with overflow explicitly allowed. + * @method $this addYearsWithoutOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addYearWithoutOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subYearsWithoutOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subYearWithoutOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addYearsWithNoOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addYearWithNoOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subYearsWithNoOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subYearWithNoOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addYearsNoOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addYearNoOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subYearsNoOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subYearNoOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addMonths(int $value = 1) Add months (the $value count passed in) to the instance (using date interval). + * @method $this addMonth() Add one month to the instance (using date interval). + * @method $this subMonths(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval). + * @method $this subMonth() Sub one month to the instance (using date interval). + * @method $this addMonthsWithOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method $this addMonthWithOverflow() Add one month to the instance (using date interval) with overflow explicitly allowed. + * @method $this subMonthsWithOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method $this subMonthWithOverflow() Sub one month to the instance (using date interval) with overflow explicitly allowed. + * @method $this addMonthsWithoutOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addMonthWithoutOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subMonthsWithoutOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subMonthWithoutOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addMonthsWithNoOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addMonthWithNoOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subMonthsWithNoOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subMonthWithNoOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addMonthsNoOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addMonthNoOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subMonthsNoOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subMonthNoOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addDays(int $value = 1) Add days (the $value count passed in) to the instance (using date interval). + * @method $this addDay() Add one day to the instance (using date interval). + * @method $this subDays(int $value = 1) Sub days (the $value count passed in) to the instance (using date interval). + * @method $this subDay() Sub one day to the instance (using date interval). + * @method $this addHours(int $value = 1) Add hours (the $value count passed in) to the instance (using date interval). + * @method $this addHour() Add one hour to the instance (using date interval). + * @method $this subHours(int $value = 1) Sub hours (the $value count passed in) to the instance (using date interval). + * @method $this subHour() Sub one hour to the instance (using date interval). + * @method $this addMinutes(int $value = 1) Add minutes (the $value count passed in) to the instance (using date interval). + * @method $this addMinute() Add one minute to the instance (using date interval). + * @method $this subMinutes(int $value = 1) Sub minutes (the $value count passed in) to the instance (using date interval). + * @method $this subMinute() Sub one minute to the instance (using date interval). + * @method $this addSeconds(int $value = 1) Add seconds (the $value count passed in) to the instance (using date interval). + * @method $this addSecond() Add one second to the instance (using date interval). + * @method $this subSeconds(int $value = 1) Sub seconds (the $value count passed in) to the instance (using date interval). + * @method $this subSecond() Sub one second to the instance (using date interval). + * @method $this addMillis(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using date interval). + * @method $this addMilli() Add one millisecond to the instance (using date interval). + * @method $this subMillis(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using date interval). + * @method $this subMilli() Sub one millisecond to the instance (using date interval). + * @method $this addMilliseconds(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using date interval). + * @method $this addMillisecond() Add one millisecond to the instance (using date interval). + * @method $this subMilliseconds(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using date interval). + * @method $this subMillisecond() Sub one millisecond to the instance (using date interval). + * @method $this addMicros(int $value = 1) Add microseconds (the $value count passed in) to the instance (using date interval). + * @method $this addMicro() Add one microsecond to the instance (using date interval). + * @method $this subMicros(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using date interval). + * @method $this subMicro() Sub one microsecond to the instance (using date interval). + * @method $this addMicroseconds(int $value = 1) Add microseconds (the $value count passed in) to the instance (using date interval). + * @method $this addMicrosecond() Add one microsecond to the instance (using date interval). + * @method $this subMicroseconds(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using date interval). + * @method $this subMicrosecond() Sub one microsecond to the instance (using date interval). + * @method $this addMillennia(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval). + * @method $this addMillennium() Add one millennium to the instance (using date interval). + * @method $this subMillennia(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval). + * @method $this subMillennium() Sub one millennium to the instance (using date interval). + * @method $this addMillenniaWithOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method $this addMillenniumWithOverflow() Add one millennium to the instance (using date interval) with overflow explicitly allowed. + * @method $this subMillenniaWithOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method $this subMillenniumWithOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly allowed. + * @method $this addMillenniaWithoutOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addMillenniumWithoutOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subMillenniaWithoutOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subMillenniumWithoutOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addMillenniaWithNoOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addMillenniumWithNoOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subMillenniaWithNoOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subMillenniumWithNoOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addMillenniaNoOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addMillenniumNoOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subMillenniaNoOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subMillenniumNoOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addCenturies(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval). + * @method $this addCentury() Add one century to the instance (using date interval). + * @method $this subCenturies(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval). + * @method $this subCentury() Sub one century to the instance (using date interval). + * @method $this addCenturiesWithOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method $this addCenturyWithOverflow() Add one century to the instance (using date interval) with overflow explicitly allowed. + * @method $this subCenturiesWithOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method $this subCenturyWithOverflow() Sub one century to the instance (using date interval) with overflow explicitly allowed. + * @method $this addCenturiesWithoutOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addCenturyWithoutOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subCenturiesWithoutOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subCenturyWithoutOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addCenturiesWithNoOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addCenturyWithNoOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subCenturiesWithNoOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subCenturyWithNoOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addCenturiesNoOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addCenturyNoOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subCenturiesNoOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subCenturyNoOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addDecades(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval). + * @method $this addDecade() Add one decade to the instance (using date interval). + * @method $this subDecades(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval). + * @method $this subDecade() Sub one decade to the instance (using date interval). + * @method $this addDecadesWithOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method $this addDecadeWithOverflow() Add one decade to the instance (using date interval) with overflow explicitly allowed. + * @method $this subDecadesWithOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method $this subDecadeWithOverflow() Sub one decade to the instance (using date interval) with overflow explicitly allowed. + * @method $this addDecadesWithoutOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addDecadeWithoutOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subDecadesWithoutOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subDecadeWithoutOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addDecadesWithNoOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addDecadeWithNoOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subDecadesWithNoOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subDecadeWithNoOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addDecadesNoOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addDecadeNoOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subDecadesNoOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subDecadeNoOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addQuarters(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval). + * @method $this addQuarter() Add one quarter to the instance (using date interval). + * @method $this subQuarters(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval). + * @method $this subQuarter() Sub one quarter to the instance (using date interval). + * @method $this addQuartersWithOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method $this addQuarterWithOverflow() Add one quarter to the instance (using date interval) with overflow explicitly allowed. + * @method $this subQuartersWithOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method $this subQuarterWithOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly allowed. + * @method $this addQuartersWithoutOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addQuarterWithoutOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subQuartersWithoutOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subQuarterWithoutOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addQuartersWithNoOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addQuarterWithNoOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subQuartersWithNoOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subQuarterWithNoOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addQuartersNoOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addQuarterNoOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subQuartersNoOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method $this subQuarterNoOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method $this addWeeks(int $value = 1) Add weeks (the $value count passed in) to the instance (using date interval). + * @method $this addWeek() Add one week to the instance (using date interval). + * @method $this subWeeks(int $value = 1) Sub weeks (the $value count passed in) to the instance (using date interval). + * @method $this subWeek() Sub one week to the instance (using date interval). + * @method $this addWeekdays(int $value = 1) Add weekdays (the $value count passed in) to the instance (using date interval). + * @method $this addWeekday() Add one weekday to the instance (using date interval). + * @method $this subWeekdays(int $value = 1) Sub weekdays (the $value count passed in) to the instance (using date interval). + * @method $this subWeekday() Sub one weekday to the instance (using date interval). + * @method $this addRealMicros(int $value = 1) Add microseconds (the $value count passed in) to the instance (using timestamp). + * @method $this addRealMicro() Add one microsecond to the instance (using timestamp). + * @method $this subRealMicros(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using timestamp). + * @method $this subRealMicro() Sub one microsecond to the instance (using timestamp). + * @method CarbonPeriod microsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each microsecond or every X microseconds if a factor is given. + * @method $this addRealMicroseconds(int $value = 1) Add microseconds (the $value count passed in) to the instance (using timestamp). + * @method $this addRealMicrosecond() Add one microsecond to the instance (using timestamp). + * @method $this subRealMicroseconds(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using timestamp). + * @method $this subRealMicrosecond() Sub one microsecond to the instance (using timestamp). + * @method CarbonPeriod microsecondsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each microsecond or every X microseconds if a factor is given. + * @method $this addRealMillis(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using timestamp). + * @method $this addRealMilli() Add one millisecond to the instance (using timestamp). + * @method $this subRealMillis(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using timestamp). + * @method $this subRealMilli() Sub one millisecond to the instance (using timestamp). + * @method CarbonPeriod millisUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millisecond or every X milliseconds if a factor is given. + * @method $this addRealMilliseconds(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using timestamp). + * @method $this addRealMillisecond() Add one millisecond to the instance (using timestamp). + * @method $this subRealMilliseconds(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using timestamp). + * @method $this subRealMillisecond() Sub one millisecond to the instance (using timestamp). + * @method CarbonPeriod millisecondsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millisecond or every X milliseconds if a factor is given. + * @method $this addRealSeconds(int $value = 1) Add seconds (the $value count passed in) to the instance (using timestamp). + * @method $this addRealSecond() Add one second to the instance (using timestamp). + * @method $this subRealSeconds(int $value = 1) Sub seconds (the $value count passed in) to the instance (using timestamp). + * @method $this subRealSecond() Sub one second to the instance (using timestamp). + * @method CarbonPeriod secondsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each second or every X seconds if a factor is given. + * @method $this addRealMinutes(int $value = 1) Add minutes (the $value count passed in) to the instance (using timestamp). + * @method $this addRealMinute() Add one minute to the instance (using timestamp). + * @method $this subRealMinutes(int $value = 1) Sub minutes (the $value count passed in) to the instance (using timestamp). + * @method $this subRealMinute() Sub one minute to the instance (using timestamp). + * @method CarbonPeriod minutesUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each minute or every X minutes if a factor is given. + * @method $this addRealHours(int $value = 1) Add hours (the $value count passed in) to the instance (using timestamp). + * @method $this addRealHour() Add one hour to the instance (using timestamp). + * @method $this subRealHours(int $value = 1) Sub hours (the $value count passed in) to the instance (using timestamp). + * @method $this subRealHour() Sub one hour to the instance (using timestamp). + * @method CarbonPeriod hoursUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each hour or every X hours if a factor is given. + * @method $this addRealDays(int $value = 1) Add days (the $value count passed in) to the instance (using timestamp). + * @method $this addRealDay() Add one day to the instance (using timestamp). + * @method $this subRealDays(int $value = 1) Sub days (the $value count passed in) to the instance (using timestamp). + * @method $this subRealDay() Sub one day to the instance (using timestamp). + * @method CarbonPeriod daysUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each day or every X days if a factor is given. + * @method $this addRealWeeks(int $value = 1) Add weeks (the $value count passed in) to the instance (using timestamp). + * @method $this addRealWeek() Add one week to the instance (using timestamp). + * @method $this subRealWeeks(int $value = 1) Sub weeks (the $value count passed in) to the instance (using timestamp). + * @method $this subRealWeek() Sub one week to the instance (using timestamp). + * @method CarbonPeriod weeksUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each week or every X weeks if a factor is given. + * @method $this addRealMonths(int $value = 1) Add months (the $value count passed in) to the instance (using timestamp). + * @method $this addRealMonth() Add one month to the instance (using timestamp). + * @method $this subRealMonths(int $value = 1) Sub months (the $value count passed in) to the instance (using timestamp). + * @method $this subRealMonth() Sub one month to the instance (using timestamp). + * @method CarbonPeriod monthsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each month or every X months if a factor is given. + * @method $this addRealQuarters(int $value = 1) Add quarters (the $value count passed in) to the instance (using timestamp). + * @method $this addRealQuarter() Add one quarter to the instance (using timestamp). + * @method $this subRealQuarters(int $value = 1) Sub quarters (the $value count passed in) to the instance (using timestamp). + * @method $this subRealQuarter() Sub one quarter to the instance (using timestamp). + * @method CarbonPeriod quartersUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each quarter or every X quarters if a factor is given. + * @method $this addRealYears(int $value = 1) Add years (the $value count passed in) to the instance (using timestamp). + * @method $this addRealYear() Add one year to the instance (using timestamp). + * @method $this subRealYears(int $value = 1) Sub years (the $value count passed in) to the instance (using timestamp). + * @method $this subRealYear() Sub one year to the instance (using timestamp). + * @method CarbonPeriod yearsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each year or every X years if a factor is given. + * @method $this addRealDecades(int $value = 1) Add decades (the $value count passed in) to the instance (using timestamp). + * @method $this addRealDecade() Add one decade to the instance (using timestamp). + * @method $this subRealDecades(int $value = 1) Sub decades (the $value count passed in) to the instance (using timestamp). + * @method $this subRealDecade() Sub one decade to the instance (using timestamp). + * @method CarbonPeriod decadesUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each decade or every X decades if a factor is given. + * @method $this addRealCenturies(int $value = 1) Add centuries (the $value count passed in) to the instance (using timestamp). + * @method $this addRealCentury() Add one century to the instance (using timestamp). + * @method $this subRealCenturies(int $value = 1) Sub centuries (the $value count passed in) to the instance (using timestamp). + * @method $this subRealCentury() Sub one century to the instance (using timestamp). + * @method CarbonPeriod centuriesUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each century or every X centuries if a factor is given. + * @method $this addRealMillennia(int $value = 1) Add millennia (the $value count passed in) to the instance (using timestamp). + * @method $this addRealMillennium() Add one millennium to the instance (using timestamp). + * @method $this subRealMillennia(int $value = 1) Sub millennia (the $value count passed in) to the instance (using timestamp). + * @method $this subRealMillennium() Sub one millennium to the instance (using timestamp). + * @method CarbonPeriod millenniaUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millennium or every X millennia if a factor is given. + * @method $this roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. + * @method $this roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. + * @method $this floorYear(float $precision = 1) Truncate the current instance year with given precision. + * @method $this floorYears(float $precision = 1) Truncate the current instance year with given precision. + * @method $this ceilYear(float $precision = 1) Ceil the current instance year with given precision. + * @method $this ceilYears(float $precision = 1) Ceil the current instance year with given precision. + * @method $this roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. + * @method $this roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. + * @method $this floorMonth(float $precision = 1) Truncate the current instance month with given precision. + * @method $this floorMonths(float $precision = 1) Truncate the current instance month with given precision. + * @method $this ceilMonth(float $precision = 1) Ceil the current instance month with given precision. + * @method $this ceilMonths(float $precision = 1) Ceil the current instance month with given precision. + * @method $this roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. + * @method $this roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. + * @method $this floorDay(float $precision = 1) Truncate the current instance day with given precision. + * @method $this floorDays(float $precision = 1) Truncate the current instance day with given precision. + * @method $this ceilDay(float $precision = 1) Ceil the current instance day with given precision. + * @method $this ceilDays(float $precision = 1) Ceil the current instance day with given precision. + * @method $this roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. + * @method $this roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. + * @method $this floorHour(float $precision = 1) Truncate the current instance hour with given precision. + * @method $this floorHours(float $precision = 1) Truncate the current instance hour with given precision. + * @method $this ceilHour(float $precision = 1) Ceil the current instance hour with given precision. + * @method $this ceilHours(float $precision = 1) Ceil the current instance hour with given precision. + * @method $this roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. + * @method $this roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. + * @method $this floorMinute(float $precision = 1) Truncate the current instance minute with given precision. + * @method $this floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. + * @method $this ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. + * @method $this ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. + * @method $this roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. + * @method $this roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. + * @method $this floorSecond(float $precision = 1) Truncate the current instance second with given precision. + * @method $this floorSeconds(float $precision = 1) Truncate the current instance second with given precision. + * @method $this ceilSecond(float $precision = 1) Ceil the current instance second with given precision. + * @method $this ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. + * @method $this roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. + * @method $this roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. + * @method $this floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. + * @method $this floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. + * @method $this ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. + * @method $this ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. + * @method $this roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. + * @method $this roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. + * @method $this floorCentury(float $precision = 1) Truncate the current instance century with given precision. + * @method $this floorCenturies(float $precision = 1) Truncate the current instance century with given precision. + * @method $this ceilCentury(float $precision = 1) Ceil the current instance century with given precision. + * @method $this ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. + * @method $this roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. + * @method $this roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. + * @method $this floorDecade(float $precision = 1) Truncate the current instance decade with given precision. + * @method $this floorDecades(float $precision = 1) Truncate the current instance decade with given precision. + * @method $this ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. + * @method $this ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. + * @method $this roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. + * @method $this roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. + * @method $this floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. + * @method $this floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. + * @method $this ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. + * @method $this ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. + * @method $this roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. + * @method $this roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. + * @method $this floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. + * @method $this floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. + * @method $this ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. + * @method $this ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. + * @method $this roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. + * @method $this roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. + * @method $this floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. + * @method $this floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. + * @method $this ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. + * @method $this ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. + * @method string shortAbsoluteDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'Absolute' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string longAbsoluteDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'Absolute' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string shortRelativeDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'Relative' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string longRelativeDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'Relative' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string shortRelativeToNowDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'RelativeToNow' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string longRelativeToNowDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'RelativeToNow' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string shortRelativeToOtherDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'RelativeToOther' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string longRelativeToOtherDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'RelativeToOther' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method static static|false createFromFormat(string $format, string $time, DateTimeZone|string|false|null $timezone = null) Parse a string into a new Carbon object according to the specified format. + * @method static static __set_state(array $array) https://php.net/manual/en/datetime.set-state.php * * */ diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/CarbonImmutable.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/CarbonImmutable.php index 6d1194ee7..4c9c1cfef 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/CarbonImmutable.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/CarbonImmutable.php @@ -24,486 +24,486 @@ use DateTimeZone; * * * - * @property int $year - * @property int $yearIso - * @property int $month - * @property int $day - * @property int $hour - * @property int $minute - * @property int $second - * @property int $micro - * @property int $microsecond - * @property int|float|string $timestamp seconds since the Unix Epoch - * @property string $englishDayOfWeek the day of week in English - * @property string $shortEnglishDayOfWeek the abbreviated day of week in English - * @property string $englishMonth the month in English - * @property string $shortEnglishMonth the abbreviated month in English - * @property int $milliseconds - * @property int $millisecond - * @property int $milli - * @property int $week 1 through 53 - * @property int $isoWeek 1 through 53 - * @property int $weekYear year according to week format - * @property int $isoWeekYear year according to ISO week format - * @property int $dayOfYear 1 through 366 - * @property int $age does a diffInYears() with default parameters - * @property int $offset the timezone offset in seconds from UTC - * @property int $offsetMinutes the timezone offset in minutes from UTC - * @property int $offsetHours the timezone offset in hours from UTC - * @property CarbonTimeZone $timezone the current timezone - * @property CarbonTimeZone $tz alias of $timezone - * @property-read int $dayOfWeek 0 (for Sunday) through 6 (for Saturday) - * @property-read int $dayOfWeekIso 1 (for Monday) through 7 (for Sunday) - * @property-read int $weekOfYear ISO-8601 week number of year, weeks starting on Monday - * @property-read int $daysInMonth number of days in the given month - * @property-read string $latinMeridiem "am"/"pm" (Ante meridiem or Post meridiem latin lowercase mark) - * @property-read string $latinUpperMeridiem "AM"/"PM" (Ante meridiem or Post meridiem latin uppercase mark) - * @property-read string $timezoneAbbreviatedName the current timezone abbreviated name - * @property-read string $tzAbbrName alias of $timezoneAbbreviatedName - * @property-read string $dayName long name of weekday translated according to Carbon locale, in english if no translation available for current language - * @property-read string $shortDayName short name of weekday translated according to Carbon locale, in english if no translation available for current language - * @property-read string $minDayName very short name of weekday translated according to Carbon locale, in english if no translation available for current language - * @property-read string $monthName long name of month translated according to Carbon locale, in english if no translation available for current language - * @property-read string $shortMonthName short name of month translated according to Carbon locale, in english if no translation available for current language - * @property-read string $meridiem lowercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language - * @property-read string $upperMeridiem uppercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language - * @property-read int $noZeroHour current hour from 1 to 24 - * @property-read int $weeksInYear 51 through 53 - * @property-read int $isoWeeksInYear 51 through 53 - * @property-read int $weekOfMonth 1 through 5 - * @property-read int $weekNumberInMonth 1 through 5 - * @property-read int $firstWeekDay 0 through 6 - * @property-read int $lastWeekDay 0 through 6 - * @property-read int $daysInYear 365 or 366 - * @property-read int $quarter the quarter of this instance, 1 - 4 - * @property-read int $decade the decade of this instance - * @property-read int $century the century of this instance - * @property-read int $millennium the millennium of this instance - * @property-read bool $dst daylight savings time indicator, true if DST, false otherwise - * @property-read bool $local checks if the timezone is local, true if local, false otherwise - * @property-read bool $utc checks if the timezone is UTC, true if UTC, false otherwise - * @property-read string $timezoneName the current timezone name - * @property-read string $tzName alias of $timezoneName - * @property-read string $locale locale of the current instance + * @property int $year + * @property int $yearIso + * @property int $month + * @property int $day + * @property int $hour + * @property int $minute + * @property int $second + * @property int $micro + * @property int $microsecond + * @property int|float|string $timestamp seconds since the Unix Epoch + * @property string $englishDayOfWeek the day of week in English + * @property string $shortEnglishDayOfWeek the abbreviated day of week in English + * @property string $englishMonth the month in English + * @property string $shortEnglishMonth the abbreviated month in English + * @property int $milliseconds + * @property int $millisecond + * @property int $milli + * @property int $week 1 through 53 + * @property int $isoWeek 1 through 53 + * @property int $weekYear year according to week format + * @property int $isoWeekYear year according to ISO week format + * @property int $dayOfYear 1 through 366 + * @property int $age does a diffInYears() with default parameters + * @property int $offset the timezone offset in seconds from UTC + * @property int $offsetMinutes the timezone offset in minutes from UTC + * @property int $offsetHours the timezone offset in hours from UTC + * @property CarbonTimeZone $timezone the current timezone + * @property CarbonTimeZone $tz alias of $timezone + * @property-read int $dayOfWeek 0 (for Sunday) through 6 (for Saturday) + * @property-read int $dayOfWeekIso 1 (for Monday) through 7 (for Sunday) + * @property-read int $weekOfYear ISO-8601 week number of year, weeks starting on Monday + * @property-read int $daysInMonth number of days in the given month + * @property-read string $latinMeridiem "am"/"pm" (Ante meridiem or Post meridiem latin lowercase mark) + * @property-read string $latinUpperMeridiem "AM"/"PM" (Ante meridiem or Post meridiem latin uppercase mark) + * @property-read string $timezoneAbbreviatedName the current timezone abbreviated name + * @property-read string $tzAbbrName alias of $timezoneAbbreviatedName + * @property-read string $dayName long name of weekday translated according to Carbon locale, in english if no translation available for current language + * @property-read string $shortDayName short name of weekday translated according to Carbon locale, in english if no translation available for current language + * @property-read string $minDayName very short name of weekday translated according to Carbon locale, in english if no translation available for current language + * @property-read string $monthName long name of month translated according to Carbon locale, in english if no translation available for current language + * @property-read string $shortMonthName short name of month translated according to Carbon locale, in english if no translation available for current language + * @property-read string $meridiem lowercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language + * @property-read string $upperMeridiem uppercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language + * @property-read int $noZeroHour current hour from 1 to 24 + * @property-read int $weeksInYear 51 through 53 + * @property-read int $isoWeeksInYear 51 through 53 + * @property-read int $weekOfMonth 1 through 5 + * @property-read int $weekNumberInMonth 1 through 5 + * @property-read int $firstWeekDay 0 through 6 + * @property-read int $lastWeekDay 0 through 6 + * @property-read int $daysInYear 365 or 366 + * @property-read int $quarter the quarter of this instance, 1 - 4 + * @property-read int $decade the decade of this instance + * @property-read int $century the century of this instance + * @property-read int $millennium the millennium of this instance + * @property-read bool $dst daylight savings time indicator, true if DST, false otherwise + * @property-read bool $local checks if the timezone is local, true if local, false otherwise + * @property-read bool $utc checks if the timezone is UTC, true if UTC, false otherwise + * @property-read string $timezoneName the current timezone name + * @property-read string $tzName alias of $timezoneName + * @property-read string $locale locale of the current instance * - * @method bool isUtc() Check if the current instance has UTC timezone. (Both isUtc and isUTC cases are valid.) - * @method bool isLocal() Check if the current instance has non-UTC timezone. - * @method bool isValid() Check if the current instance is a valid date. - * @method bool isDST() Check if the current instance is in a daylight saving time. - * @method bool isSunday() Checks if the instance day is sunday. - * @method bool isMonday() Checks if the instance day is monday. - * @method bool isTuesday() Checks if the instance day is tuesday. - * @method bool isWednesday() Checks if the instance day is wednesday. - * @method bool isThursday() Checks if the instance day is thursday. - * @method bool isFriday() Checks if the instance day is friday. - * @method bool isSaturday() Checks if the instance day is saturday. - * @method bool isSameYear(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same year as the instance. If null passed, compare to now (with the same timezone). - * @method bool isCurrentYear() Checks if the instance is in the same year as the current moment. - * @method bool isNextYear() Checks if the instance is in the same year as the current moment next year. - * @method bool isLastYear() Checks if the instance is in the same year as the current moment last year. - * @method bool isSameWeek(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same week as the instance. If null passed, compare to now (with the same timezone). - * @method bool isCurrentWeek() Checks if the instance is in the same week as the current moment. - * @method bool isNextWeek() Checks if the instance is in the same week as the current moment next week. - * @method bool isLastWeek() Checks if the instance is in the same week as the current moment last week. - * @method bool isSameDay(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same day as the instance. If null passed, compare to now (with the same timezone). - * @method bool isCurrentDay() Checks if the instance is in the same day as the current moment. - * @method bool isNextDay() Checks if the instance is in the same day as the current moment next day. - * @method bool isLastDay() Checks if the instance is in the same day as the current moment last day. - * @method bool isSameHour(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same hour as the instance. If null passed, compare to now (with the same timezone). - * @method bool isCurrentHour() Checks if the instance is in the same hour as the current moment. - * @method bool isNextHour() Checks if the instance is in the same hour as the current moment next hour. - * @method bool isLastHour() Checks if the instance is in the same hour as the current moment last hour. - * @method bool isSameMinute(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same minute as the instance. If null passed, compare to now (with the same timezone). - * @method bool isCurrentMinute() Checks if the instance is in the same minute as the current moment. - * @method bool isNextMinute() Checks if the instance is in the same minute as the current moment next minute. - * @method bool isLastMinute() Checks if the instance is in the same minute as the current moment last minute. - * @method bool isSameSecond(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same second as the instance. If null passed, compare to now (with the same timezone). - * @method bool isCurrentSecond() Checks if the instance is in the same second as the current moment. - * @method bool isNextSecond() Checks if the instance is in the same second as the current moment next second. - * @method bool isLastSecond() Checks if the instance is in the same second as the current moment last second. - * @method bool isSameMicro(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same microsecond as the instance. If null passed, compare to now (with the same timezone). - * @method bool isCurrentMicro() Checks if the instance is in the same microsecond as the current moment. - * @method bool isNextMicro() Checks if the instance is in the same microsecond as the current moment next microsecond. - * @method bool isLastMicro() Checks if the instance is in the same microsecond as the current moment last microsecond. - * @method bool isSameMicrosecond(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same microsecond as the instance. If null passed, compare to now (with the same timezone). - * @method bool isCurrentMicrosecond() Checks if the instance is in the same microsecond as the current moment. - * @method bool isNextMicrosecond() Checks if the instance is in the same microsecond as the current moment next microsecond. - * @method bool isLastMicrosecond() Checks if the instance is in the same microsecond as the current moment last microsecond. - * @method bool isCurrentMonth() Checks if the instance is in the same month as the current moment. - * @method bool isNextMonth() Checks if the instance is in the same month as the current moment next month. - * @method bool isLastMonth() Checks if the instance is in the same month as the current moment last month. - * @method bool isCurrentQuarter() Checks if the instance is in the same quarter as the current moment. - * @method bool isNextQuarter() Checks if the instance is in the same quarter as the current moment next quarter. - * @method bool isLastQuarter() Checks if the instance is in the same quarter as the current moment last quarter. - * @method bool isSameDecade(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same decade as the instance. If null passed, compare to now (with the same timezone). - * @method bool isCurrentDecade() Checks if the instance is in the same decade as the current moment. - * @method bool isNextDecade() Checks if the instance is in the same decade as the current moment next decade. - * @method bool isLastDecade() Checks if the instance is in the same decade as the current moment last decade. - * @method bool isSameCentury(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same century as the instance. If null passed, compare to now (with the same timezone). - * @method bool isCurrentCentury() Checks if the instance is in the same century as the current moment. - * @method bool isNextCentury() Checks if the instance is in the same century as the current moment next century. - * @method bool isLastCentury() Checks if the instance is in the same century as the current moment last century. - * @method bool isSameMillennium(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same millennium as the instance. If null passed, compare to now (with the same timezone). - * @method bool isCurrentMillennium() Checks if the instance is in the same millennium as the current moment. - * @method bool isNextMillennium() Checks if the instance is in the same millennium as the current moment next millennium. - * @method bool isLastMillennium() Checks if the instance is in the same millennium as the current moment last millennium. - * @method CarbonImmutable years(int $value) Set current instance year to the given value. - * @method CarbonImmutable year(int $value) Set current instance year to the given value. - * @method CarbonImmutable setYears(int $value) Set current instance year to the given value. - * @method CarbonImmutable setYear(int $value) Set current instance year to the given value. - * @method CarbonImmutable months(int $value) Set current instance month to the given value. - * @method CarbonImmutable month(int $value) Set current instance month to the given value. - * @method CarbonImmutable setMonths(int $value) Set current instance month to the given value. - * @method CarbonImmutable setMonth(int $value) Set current instance month to the given value. - * @method CarbonImmutable days(int $value) Set current instance day to the given value. - * @method CarbonImmutable day(int $value) Set current instance day to the given value. - * @method CarbonImmutable setDays(int $value) Set current instance day to the given value. - * @method CarbonImmutable setDay(int $value) Set current instance day to the given value. - * @method CarbonImmutable hours(int $value) Set current instance hour to the given value. - * @method CarbonImmutable hour(int $value) Set current instance hour to the given value. - * @method CarbonImmutable setHours(int $value) Set current instance hour to the given value. - * @method CarbonImmutable setHour(int $value) Set current instance hour to the given value. - * @method CarbonImmutable minutes(int $value) Set current instance minute to the given value. - * @method CarbonImmutable minute(int $value) Set current instance minute to the given value. - * @method CarbonImmutable setMinutes(int $value) Set current instance minute to the given value. - * @method CarbonImmutable setMinute(int $value) Set current instance minute to the given value. - * @method CarbonImmutable seconds(int $value) Set current instance second to the given value. - * @method CarbonImmutable second(int $value) Set current instance second to the given value. - * @method CarbonImmutable setSeconds(int $value) Set current instance second to the given value. - * @method CarbonImmutable setSecond(int $value) Set current instance second to the given value. - * @method CarbonImmutable millis(int $value) Set current instance millisecond to the given value. - * @method CarbonImmutable milli(int $value) Set current instance millisecond to the given value. - * @method CarbonImmutable setMillis(int $value) Set current instance millisecond to the given value. - * @method CarbonImmutable setMilli(int $value) Set current instance millisecond to the given value. - * @method CarbonImmutable milliseconds(int $value) Set current instance millisecond to the given value. - * @method CarbonImmutable millisecond(int $value) Set current instance millisecond to the given value. - * @method CarbonImmutable setMilliseconds(int $value) Set current instance millisecond to the given value. - * @method CarbonImmutable setMillisecond(int $value) Set current instance millisecond to the given value. - * @method CarbonImmutable micros(int $value) Set current instance microsecond to the given value. - * @method CarbonImmutable micro(int $value) Set current instance microsecond to the given value. - * @method CarbonImmutable setMicros(int $value) Set current instance microsecond to the given value. - * @method CarbonImmutable setMicro(int $value) Set current instance microsecond to the given value. - * @method CarbonImmutable microseconds(int $value) Set current instance microsecond to the given value. - * @method CarbonImmutable microsecond(int $value) Set current instance microsecond to the given value. - * @method CarbonImmutable setMicroseconds(int $value) Set current instance microsecond to the given value. - * @method CarbonImmutable setMicrosecond(int $value) Set current instance microsecond to the given value. - * @method CarbonImmutable addYears(int $value = 1) Add years (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable addYear() Add one year to the instance (using date interval). - * @method CarbonImmutable subYears(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable subYear() Sub one year to the instance (using date interval). - * @method CarbonImmutable addYearsWithOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. - * @method CarbonImmutable addYearWithOverflow() Add one year to the instance (using date interval) with overflow explicitly allowed. - * @method CarbonImmutable subYearsWithOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. - * @method CarbonImmutable subYearWithOverflow() Sub one year to the instance (using date interval) with overflow explicitly allowed. - * @method CarbonImmutable addYearsWithoutOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addYearWithoutOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subYearsWithoutOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subYearWithoutOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addYearsWithNoOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addYearWithNoOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subYearsWithNoOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subYearWithNoOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addYearsNoOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addYearNoOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subYearsNoOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subYearNoOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addMonths(int $value = 1) Add months (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable addMonth() Add one month to the instance (using date interval). - * @method CarbonImmutable subMonths(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable subMonth() Sub one month to the instance (using date interval). - * @method CarbonImmutable addMonthsWithOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. - * @method CarbonImmutable addMonthWithOverflow() Add one month to the instance (using date interval) with overflow explicitly allowed. - * @method CarbonImmutable subMonthsWithOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. - * @method CarbonImmutable subMonthWithOverflow() Sub one month to the instance (using date interval) with overflow explicitly allowed. - * @method CarbonImmutable addMonthsWithoutOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addMonthWithoutOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subMonthsWithoutOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subMonthWithoutOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addMonthsWithNoOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addMonthWithNoOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subMonthsWithNoOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subMonthWithNoOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addMonthsNoOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addMonthNoOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subMonthsNoOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subMonthNoOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addDays(int $value = 1) Add days (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable addDay() Add one day to the instance (using date interval). - * @method CarbonImmutable subDays(int $value = 1) Sub days (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable subDay() Sub one day to the instance (using date interval). - * @method CarbonImmutable addHours(int $value = 1) Add hours (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable addHour() Add one hour to the instance (using date interval). - * @method CarbonImmutable subHours(int $value = 1) Sub hours (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable subHour() Sub one hour to the instance (using date interval). - * @method CarbonImmutable addMinutes(int $value = 1) Add minutes (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable addMinute() Add one minute to the instance (using date interval). - * @method CarbonImmutable subMinutes(int $value = 1) Sub minutes (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable subMinute() Sub one minute to the instance (using date interval). - * @method CarbonImmutable addSeconds(int $value = 1) Add seconds (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable addSecond() Add one second to the instance (using date interval). - * @method CarbonImmutable subSeconds(int $value = 1) Sub seconds (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable subSecond() Sub one second to the instance (using date interval). - * @method CarbonImmutable addMillis(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable addMilli() Add one millisecond to the instance (using date interval). - * @method CarbonImmutable subMillis(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable subMilli() Sub one millisecond to the instance (using date interval). - * @method CarbonImmutable addMilliseconds(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable addMillisecond() Add one millisecond to the instance (using date interval). - * @method CarbonImmutable subMilliseconds(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable subMillisecond() Sub one millisecond to the instance (using date interval). - * @method CarbonImmutable addMicros(int $value = 1) Add microseconds (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable addMicro() Add one microsecond to the instance (using date interval). - * @method CarbonImmutable subMicros(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable subMicro() Sub one microsecond to the instance (using date interval). - * @method CarbonImmutable addMicroseconds(int $value = 1) Add microseconds (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable addMicrosecond() Add one microsecond to the instance (using date interval). - * @method CarbonImmutable subMicroseconds(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable subMicrosecond() Sub one microsecond to the instance (using date interval). - * @method CarbonImmutable addMillennia(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable addMillennium() Add one millennium to the instance (using date interval). - * @method CarbonImmutable subMillennia(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable subMillennium() Sub one millennium to the instance (using date interval). - * @method CarbonImmutable addMillenniaWithOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. - * @method CarbonImmutable addMillenniumWithOverflow() Add one millennium to the instance (using date interval) with overflow explicitly allowed. - * @method CarbonImmutable subMillenniaWithOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. - * @method CarbonImmutable subMillenniumWithOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly allowed. - * @method CarbonImmutable addMillenniaWithoutOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addMillenniumWithoutOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subMillenniaWithoutOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subMillenniumWithoutOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addMillenniaWithNoOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addMillenniumWithNoOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subMillenniaWithNoOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subMillenniumWithNoOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addMillenniaNoOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addMillenniumNoOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subMillenniaNoOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subMillenniumNoOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addCenturies(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable addCentury() Add one century to the instance (using date interval). - * @method CarbonImmutable subCenturies(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable subCentury() Sub one century to the instance (using date interval). - * @method CarbonImmutable addCenturiesWithOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. - * @method CarbonImmutable addCenturyWithOverflow() Add one century to the instance (using date interval) with overflow explicitly allowed. - * @method CarbonImmutable subCenturiesWithOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. - * @method CarbonImmutable subCenturyWithOverflow() Sub one century to the instance (using date interval) with overflow explicitly allowed. - * @method CarbonImmutable addCenturiesWithoutOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addCenturyWithoutOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subCenturiesWithoutOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subCenturyWithoutOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addCenturiesWithNoOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addCenturyWithNoOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subCenturiesWithNoOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subCenturyWithNoOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addCenturiesNoOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addCenturyNoOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subCenturiesNoOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subCenturyNoOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addDecades(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable addDecade() Add one decade to the instance (using date interval). - * @method CarbonImmutable subDecades(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable subDecade() Sub one decade to the instance (using date interval). - * @method CarbonImmutable addDecadesWithOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. - * @method CarbonImmutable addDecadeWithOverflow() Add one decade to the instance (using date interval) with overflow explicitly allowed. - * @method CarbonImmutable subDecadesWithOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. - * @method CarbonImmutable subDecadeWithOverflow() Sub one decade to the instance (using date interval) with overflow explicitly allowed. - * @method CarbonImmutable addDecadesWithoutOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addDecadeWithoutOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subDecadesWithoutOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subDecadeWithoutOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addDecadesWithNoOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addDecadeWithNoOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subDecadesWithNoOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subDecadeWithNoOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addDecadesNoOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addDecadeNoOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subDecadesNoOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subDecadeNoOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addQuarters(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable addQuarter() Add one quarter to the instance (using date interval). - * @method CarbonImmutable subQuarters(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable subQuarter() Sub one quarter to the instance (using date interval). - * @method CarbonImmutable addQuartersWithOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. - * @method CarbonImmutable addQuarterWithOverflow() Add one quarter to the instance (using date interval) with overflow explicitly allowed. - * @method CarbonImmutable subQuartersWithOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. - * @method CarbonImmutable subQuarterWithOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly allowed. - * @method CarbonImmutable addQuartersWithoutOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addQuarterWithoutOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subQuartersWithoutOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subQuarterWithoutOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addQuartersWithNoOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addQuarterWithNoOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subQuartersWithNoOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subQuarterWithNoOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addQuartersNoOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addQuarterNoOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subQuartersNoOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable subQuarterNoOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. - * @method CarbonImmutable addWeeks(int $value = 1) Add weeks (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable addWeek() Add one week to the instance (using date interval). - * @method CarbonImmutable subWeeks(int $value = 1) Sub weeks (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable subWeek() Sub one week to the instance (using date interval). - * @method CarbonImmutable addWeekdays(int $value = 1) Add weekdays (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable addWeekday() Add one weekday to the instance (using date interval). - * @method CarbonImmutable subWeekdays(int $value = 1) Sub weekdays (the $value count passed in) to the instance (using date interval). - * @method CarbonImmutable subWeekday() Sub one weekday to the instance (using date interval). - * @method CarbonImmutable addRealMicros(int $value = 1) Add microseconds (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable addRealMicro() Add one microsecond to the instance (using timestamp). - * @method CarbonImmutable subRealMicros(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable subRealMicro() Sub one microsecond to the instance (using timestamp). - * @method CarbonPeriod microsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each microsecond or every X microseconds if a factor is given. - * @method CarbonImmutable addRealMicroseconds(int $value = 1) Add microseconds (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable addRealMicrosecond() Add one microsecond to the instance (using timestamp). - * @method CarbonImmutable subRealMicroseconds(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable subRealMicrosecond() Sub one microsecond to the instance (using timestamp). - * @method CarbonPeriod microsecondsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each microsecond or every X microseconds if a factor is given. - * @method CarbonImmutable addRealMillis(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable addRealMilli() Add one millisecond to the instance (using timestamp). - * @method CarbonImmutable subRealMillis(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable subRealMilli() Sub one millisecond to the instance (using timestamp). - * @method CarbonPeriod millisUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millisecond or every X milliseconds if a factor is given. - * @method CarbonImmutable addRealMilliseconds(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable addRealMillisecond() Add one millisecond to the instance (using timestamp). - * @method CarbonImmutable subRealMilliseconds(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable subRealMillisecond() Sub one millisecond to the instance (using timestamp). - * @method CarbonPeriod millisecondsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millisecond or every X milliseconds if a factor is given. - * @method CarbonImmutable addRealSeconds(int $value = 1) Add seconds (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable addRealSecond() Add one second to the instance (using timestamp). - * @method CarbonImmutable subRealSeconds(int $value = 1) Sub seconds (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable subRealSecond() Sub one second to the instance (using timestamp). - * @method CarbonPeriod secondsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each second or every X seconds if a factor is given. - * @method CarbonImmutable addRealMinutes(int $value = 1) Add minutes (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable addRealMinute() Add one minute to the instance (using timestamp). - * @method CarbonImmutable subRealMinutes(int $value = 1) Sub minutes (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable subRealMinute() Sub one minute to the instance (using timestamp). - * @method CarbonPeriod minutesUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each minute or every X minutes if a factor is given. - * @method CarbonImmutable addRealHours(int $value = 1) Add hours (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable addRealHour() Add one hour to the instance (using timestamp). - * @method CarbonImmutable subRealHours(int $value = 1) Sub hours (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable subRealHour() Sub one hour to the instance (using timestamp). - * @method CarbonPeriod hoursUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each hour or every X hours if a factor is given. - * @method CarbonImmutable addRealDays(int $value = 1) Add days (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable addRealDay() Add one day to the instance (using timestamp). - * @method CarbonImmutable subRealDays(int $value = 1) Sub days (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable subRealDay() Sub one day to the instance (using timestamp). - * @method CarbonPeriod daysUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each day or every X days if a factor is given. - * @method CarbonImmutable addRealWeeks(int $value = 1) Add weeks (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable addRealWeek() Add one week to the instance (using timestamp). - * @method CarbonImmutable subRealWeeks(int $value = 1) Sub weeks (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable subRealWeek() Sub one week to the instance (using timestamp). - * @method CarbonPeriod weeksUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each week or every X weeks if a factor is given. - * @method CarbonImmutable addRealMonths(int $value = 1) Add months (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable addRealMonth() Add one month to the instance (using timestamp). - * @method CarbonImmutable subRealMonths(int $value = 1) Sub months (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable subRealMonth() Sub one month to the instance (using timestamp). - * @method CarbonPeriod monthsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each month or every X months if a factor is given. - * @method CarbonImmutable addRealQuarters(int $value = 1) Add quarters (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable addRealQuarter() Add one quarter to the instance (using timestamp). - * @method CarbonImmutable subRealQuarters(int $value = 1) Sub quarters (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable subRealQuarter() Sub one quarter to the instance (using timestamp). - * @method CarbonPeriod quartersUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each quarter or every X quarters if a factor is given. - * @method CarbonImmutable addRealYears(int $value = 1) Add years (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable addRealYear() Add one year to the instance (using timestamp). - * @method CarbonImmutable subRealYears(int $value = 1) Sub years (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable subRealYear() Sub one year to the instance (using timestamp). - * @method CarbonPeriod yearsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each year or every X years if a factor is given. - * @method CarbonImmutable addRealDecades(int $value = 1) Add decades (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable addRealDecade() Add one decade to the instance (using timestamp). - * @method CarbonImmutable subRealDecades(int $value = 1) Sub decades (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable subRealDecade() Sub one decade to the instance (using timestamp). - * @method CarbonPeriod decadesUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each decade or every X decades if a factor is given. - * @method CarbonImmutable addRealCenturies(int $value = 1) Add centuries (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable addRealCentury() Add one century to the instance (using timestamp). - * @method CarbonImmutable subRealCenturies(int $value = 1) Sub centuries (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable subRealCentury() Sub one century to the instance (using timestamp). - * @method CarbonPeriod centuriesUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each century or every X centuries if a factor is given. - * @method CarbonImmutable addRealMillennia(int $value = 1) Add millennia (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable addRealMillennium() Add one millennium to the instance (using timestamp). - * @method CarbonImmutable subRealMillennia(int $value = 1) Sub millennia (the $value count passed in) to the instance (using timestamp). - * @method CarbonImmutable subRealMillennium() Sub one millennium to the instance (using timestamp). - * @method CarbonPeriod millenniaUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millennium or every X millennia if a factor is given. - * @method CarbonImmutable roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. - * @method CarbonImmutable roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. - * @method CarbonImmutable floorYear(float $precision = 1) Truncate the current instance year with given precision. - * @method CarbonImmutable floorYears(float $precision = 1) Truncate the current instance year with given precision. - * @method CarbonImmutable ceilYear(float $precision = 1) Ceil the current instance year with given precision. - * @method CarbonImmutable ceilYears(float $precision = 1) Ceil the current instance year with given precision. - * @method CarbonImmutable roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. - * @method CarbonImmutable roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. - * @method CarbonImmutable floorMonth(float $precision = 1) Truncate the current instance month with given precision. - * @method CarbonImmutable floorMonths(float $precision = 1) Truncate the current instance month with given precision. - * @method CarbonImmutable ceilMonth(float $precision = 1) Ceil the current instance month with given precision. - * @method CarbonImmutable ceilMonths(float $precision = 1) Ceil the current instance month with given precision. - * @method CarbonImmutable roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. - * @method CarbonImmutable roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. - * @method CarbonImmutable floorDay(float $precision = 1) Truncate the current instance day with given precision. - * @method CarbonImmutable floorDays(float $precision = 1) Truncate the current instance day with given precision. - * @method CarbonImmutable ceilDay(float $precision = 1) Ceil the current instance day with given precision. - * @method CarbonImmutable ceilDays(float $precision = 1) Ceil the current instance day with given precision. - * @method CarbonImmutable roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. - * @method CarbonImmutable roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. - * @method CarbonImmutable floorHour(float $precision = 1) Truncate the current instance hour with given precision. - * @method CarbonImmutable floorHours(float $precision = 1) Truncate the current instance hour with given precision. - * @method CarbonImmutable ceilHour(float $precision = 1) Ceil the current instance hour with given precision. - * @method CarbonImmutable ceilHours(float $precision = 1) Ceil the current instance hour with given precision. - * @method CarbonImmutable roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. - * @method CarbonImmutable roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. - * @method CarbonImmutable floorMinute(float $precision = 1) Truncate the current instance minute with given precision. - * @method CarbonImmutable floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. - * @method CarbonImmutable ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. - * @method CarbonImmutable ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. - * @method CarbonImmutable roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. - * @method CarbonImmutable roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. - * @method CarbonImmutable floorSecond(float $precision = 1) Truncate the current instance second with given precision. - * @method CarbonImmutable floorSeconds(float $precision = 1) Truncate the current instance second with given precision. - * @method CarbonImmutable ceilSecond(float $precision = 1) Ceil the current instance second with given precision. - * @method CarbonImmutable ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. - * @method CarbonImmutable roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. - * @method CarbonImmutable roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. - * @method CarbonImmutable floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. - * @method CarbonImmutable floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. - * @method CarbonImmutable ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. - * @method CarbonImmutable ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. - * @method CarbonImmutable roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. - * @method CarbonImmutable roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. - * @method CarbonImmutable floorCentury(float $precision = 1) Truncate the current instance century with given precision. - * @method CarbonImmutable floorCenturies(float $precision = 1) Truncate the current instance century with given precision. - * @method CarbonImmutable ceilCentury(float $precision = 1) Ceil the current instance century with given precision. - * @method CarbonImmutable ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. - * @method CarbonImmutable roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. - * @method CarbonImmutable roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. - * @method CarbonImmutable floorDecade(float $precision = 1) Truncate the current instance decade with given precision. - * @method CarbonImmutable floorDecades(float $precision = 1) Truncate the current instance decade with given precision. - * @method CarbonImmutable ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. - * @method CarbonImmutable ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. - * @method CarbonImmutable roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. - * @method CarbonImmutable roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. - * @method CarbonImmutable floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. - * @method CarbonImmutable floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. - * @method CarbonImmutable ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. - * @method CarbonImmutable ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. - * @method CarbonImmutable roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. - * @method CarbonImmutable roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. - * @method CarbonImmutable floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. - * @method CarbonImmutable floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. - * @method CarbonImmutable ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. - * @method CarbonImmutable ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. - * @method CarbonImmutable roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. - * @method CarbonImmutable roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. - * @method CarbonImmutable floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. - * @method CarbonImmutable floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. - * @method CarbonImmutable ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. - * @method CarbonImmutable ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. - * @method string shortAbsoluteDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'Absolute' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) - * @method string longAbsoluteDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'Absolute' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) - * @method string shortRelativeDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'Relative' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) - * @method string longRelativeDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'Relative' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) - * @method string shortRelativeToNowDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'RelativeToNow' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) - * @method string longRelativeToNowDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'RelativeToNow' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) - * @method string shortRelativeToOtherDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'RelativeToOther' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) - * @method string longRelativeToOtherDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'RelativeToOther' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) - * @method static CarbonImmutable|false createFromFormat(string $format, string $time, string|DateTimeZone $timezone = null) Parse a string into a new CarbonImmutable object according to the specified format. - * @method static CarbonImmutable __set_state(array $array) https://php.net/manual/en/datetime.set-state.php + * @method bool isUtc() Check if the current instance has UTC timezone. (Both isUtc and isUTC cases are valid.) + * @method bool isLocal() Check if the current instance has non-UTC timezone. + * @method bool isValid() Check if the current instance is a valid date. + * @method bool isDST() Check if the current instance is in a daylight saving time. + * @method bool isSunday() Checks if the instance day is sunday. + * @method bool isMonday() Checks if the instance day is monday. + * @method bool isTuesday() Checks if the instance day is tuesday. + * @method bool isWednesday() Checks if the instance day is wednesday. + * @method bool isThursday() Checks if the instance day is thursday. + * @method bool isFriday() Checks if the instance day is friday. + * @method bool isSaturday() Checks if the instance day is saturday. + * @method bool isSameYear(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same year as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentYear() Checks if the instance is in the same year as the current moment. + * @method bool isNextYear() Checks if the instance is in the same year as the current moment next year. + * @method bool isLastYear() Checks if the instance is in the same year as the current moment last year. + * @method bool isSameWeek(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same week as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentWeek() Checks if the instance is in the same week as the current moment. + * @method bool isNextWeek() Checks if the instance is in the same week as the current moment next week. + * @method bool isLastWeek() Checks if the instance is in the same week as the current moment last week. + * @method bool isSameDay(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same day as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentDay() Checks if the instance is in the same day as the current moment. + * @method bool isNextDay() Checks if the instance is in the same day as the current moment next day. + * @method bool isLastDay() Checks if the instance is in the same day as the current moment last day. + * @method bool isSameHour(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same hour as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentHour() Checks if the instance is in the same hour as the current moment. + * @method bool isNextHour() Checks if the instance is in the same hour as the current moment next hour. + * @method bool isLastHour() Checks if the instance is in the same hour as the current moment last hour. + * @method bool isSameMinute(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same minute as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentMinute() Checks if the instance is in the same minute as the current moment. + * @method bool isNextMinute() Checks if the instance is in the same minute as the current moment next minute. + * @method bool isLastMinute() Checks if the instance is in the same minute as the current moment last minute. + * @method bool isSameSecond(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same second as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentSecond() Checks if the instance is in the same second as the current moment. + * @method bool isNextSecond() Checks if the instance is in the same second as the current moment next second. + * @method bool isLastSecond() Checks if the instance is in the same second as the current moment last second. + * @method bool isSameMicro(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same microsecond as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentMicro() Checks if the instance is in the same microsecond as the current moment. + * @method bool isNextMicro() Checks if the instance is in the same microsecond as the current moment next microsecond. + * @method bool isLastMicro() Checks if the instance is in the same microsecond as the current moment last microsecond. + * @method bool isSameMicrosecond(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same microsecond as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentMicrosecond() Checks if the instance is in the same microsecond as the current moment. + * @method bool isNextMicrosecond() Checks if the instance is in the same microsecond as the current moment next microsecond. + * @method bool isLastMicrosecond() Checks if the instance is in the same microsecond as the current moment last microsecond. + * @method bool isCurrentMonth() Checks if the instance is in the same month as the current moment. + * @method bool isNextMonth() Checks if the instance is in the same month as the current moment next month. + * @method bool isLastMonth() Checks if the instance is in the same month as the current moment last month. + * @method bool isCurrentQuarter() Checks if the instance is in the same quarter as the current moment. + * @method bool isNextQuarter() Checks if the instance is in the same quarter as the current moment next quarter. + * @method bool isLastQuarter() Checks if the instance is in the same quarter as the current moment last quarter. + * @method bool isSameDecade(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same decade as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentDecade() Checks if the instance is in the same decade as the current moment. + * @method bool isNextDecade() Checks if the instance is in the same decade as the current moment next decade. + * @method bool isLastDecade() Checks if the instance is in the same decade as the current moment last decade. + * @method bool isSameCentury(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same century as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentCentury() Checks if the instance is in the same century as the current moment. + * @method bool isNextCentury() Checks if the instance is in the same century as the current moment next century. + * @method bool isLastCentury() Checks if the instance is in the same century as the current moment last century. + * @method bool isSameMillennium(Carbon|DateTimeInterface|string|null $date = null) Checks if the given date is in the same millennium as the instance. If null passed, compare to now (with the same timezone). + * @method bool isCurrentMillennium() Checks if the instance is in the same millennium as the current moment. + * @method bool isNextMillennium() Checks if the instance is in the same millennium as the current moment next millennium. + * @method bool isLastMillennium() Checks if the instance is in the same millennium as the current moment last millennium. + * @method CarbonImmutable years(int $value) Set current instance year to the given value. + * @method CarbonImmutable year(int $value) Set current instance year to the given value. + * @method CarbonImmutable setYears(int $value) Set current instance year to the given value. + * @method CarbonImmutable setYear(int $value) Set current instance year to the given value. + * @method CarbonImmutable months(int $value) Set current instance month to the given value. + * @method CarbonImmutable month(int $value) Set current instance month to the given value. + * @method CarbonImmutable setMonths(int $value) Set current instance month to the given value. + * @method CarbonImmutable setMonth(int $value) Set current instance month to the given value. + * @method CarbonImmutable days(int $value) Set current instance day to the given value. + * @method CarbonImmutable day(int $value) Set current instance day to the given value. + * @method CarbonImmutable setDays(int $value) Set current instance day to the given value. + * @method CarbonImmutable setDay(int $value) Set current instance day to the given value. + * @method CarbonImmutable hours(int $value) Set current instance hour to the given value. + * @method CarbonImmutable hour(int $value) Set current instance hour to the given value. + * @method CarbonImmutable setHours(int $value) Set current instance hour to the given value. + * @method CarbonImmutable setHour(int $value) Set current instance hour to the given value. + * @method CarbonImmutable minutes(int $value) Set current instance minute to the given value. + * @method CarbonImmutable minute(int $value) Set current instance minute to the given value. + * @method CarbonImmutable setMinutes(int $value) Set current instance minute to the given value. + * @method CarbonImmutable setMinute(int $value) Set current instance minute to the given value. + * @method CarbonImmutable seconds(int $value) Set current instance second to the given value. + * @method CarbonImmutable second(int $value) Set current instance second to the given value. + * @method CarbonImmutable setSeconds(int $value) Set current instance second to the given value. + * @method CarbonImmutable setSecond(int $value) Set current instance second to the given value. + * @method CarbonImmutable millis(int $value) Set current instance millisecond to the given value. + * @method CarbonImmutable milli(int $value) Set current instance millisecond to the given value. + * @method CarbonImmutable setMillis(int $value) Set current instance millisecond to the given value. + * @method CarbonImmutable setMilli(int $value) Set current instance millisecond to the given value. + * @method CarbonImmutable milliseconds(int $value) Set current instance millisecond to the given value. + * @method CarbonImmutable millisecond(int $value) Set current instance millisecond to the given value. + * @method CarbonImmutable setMilliseconds(int $value) Set current instance millisecond to the given value. + * @method CarbonImmutable setMillisecond(int $value) Set current instance millisecond to the given value. + * @method CarbonImmutable micros(int $value) Set current instance microsecond to the given value. + * @method CarbonImmutable micro(int $value) Set current instance microsecond to the given value. + * @method CarbonImmutable setMicros(int $value) Set current instance microsecond to the given value. + * @method CarbonImmutable setMicro(int $value) Set current instance microsecond to the given value. + * @method CarbonImmutable microseconds(int $value) Set current instance microsecond to the given value. + * @method CarbonImmutable microsecond(int $value) Set current instance microsecond to the given value. + * @method CarbonImmutable setMicroseconds(int $value) Set current instance microsecond to the given value. + * @method CarbonImmutable setMicrosecond(int $value) Set current instance microsecond to the given value. + * @method CarbonImmutable addYears(int $value = 1) Add years (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addYear() Add one year to the instance (using date interval). + * @method CarbonImmutable subYears(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subYear() Sub one year to the instance (using date interval). + * @method CarbonImmutable addYearsWithOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable addYearWithOverflow() Add one year to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable subYearsWithOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable subYearWithOverflow() Sub one year to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable addYearsWithoutOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addYearWithoutOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subYearsWithoutOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subYearWithoutOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addYearsWithNoOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addYearWithNoOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subYearsWithNoOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subYearWithNoOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addYearsNoOverflow(int $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addYearNoOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subYearsNoOverflow(int $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subYearNoOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addMonths(int $value = 1) Add months (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addMonth() Add one month to the instance (using date interval). + * @method CarbonImmutable subMonths(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subMonth() Sub one month to the instance (using date interval). + * @method CarbonImmutable addMonthsWithOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable addMonthWithOverflow() Add one month to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable subMonthsWithOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable subMonthWithOverflow() Sub one month to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable addMonthsWithoutOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addMonthWithoutOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subMonthsWithoutOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subMonthWithoutOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addMonthsWithNoOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addMonthWithNoOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subMonthsWithNoOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subMonthWithNoOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addMonthsNoOverflow(int $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addMonthNoOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subMonthsNoOverflow(int $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subMonthNoOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addDays(int $value = 1) Add days (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addDay() Add one day to the instance (using date interval). + * @method CarbonImmutable subDays(int $value = 1) Sub days (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subDay() Sub one day to the instance (using date interval). + * @method CarbonImmutable addHours(int $value = 1) Add hours (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addHour() Add one hour to the instance (using date interval). + * @method CarbonImmutable subHours(int $value = 1) Sub hours (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subHour() Sub one hour to the instance (using date interval). + * @method CarbonImmutable addMinutes(int $value = 1) Add minutes (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addMinute() Add one minute to the instance (using date interval). + * @method CarbonImmutable subMinutes(int $value = 1) Sub minutes (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subMinute() Sub one minute to the instance (using date interval). + * @method CarbonImmutable addSeconds(int $value = 1) Add seconds (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addSecond() Add one second to the instance (using date interval). + * @method CarbonImmutable subSeconds(int $value = 1) Sub seconds (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subSecond() Sub one second to the instance (using date interval). + * @method CarbonImmutable addMillis(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addMilli() Add one millisecond to the instance (using date interval). + * @method CarbonImmutable subMillis(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subMilli() Sub one millisecond to the instance (using date interval). + * @method CarbonImmutable addMilliseconds(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addMillisecond() Add one millisecond to the instance (using date interval). + * @method CarbonImmutable subMilliseconds(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subMillisecond() Sub one millisecond to the instance (using date interval). + * @method CarbonImmutable addMicros(int $value = 1) Add microseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addMicro() Add one microsecond to the instance (using date interval). + * @method CarbonImmutable subMicros(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subMicro() Sub one microsecond to the instance (using date interval). + * @method CarbonImmutable addMicroseconds(int $value = 1) Add microseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addMicrosecond() Add one microsecond to the instance (using date interval). + * @method CarbonImmutable subMicroseconds(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subMicrosecond() Sub one microsecond to the instance (using date interval). + * @method CarbonImmutable addMillennia(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addMillennium() Add one millennium to the instance (using date interval). + * @method CarbonImmutable subMillennia(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subMillennium() Sub one millennium to the instance (using date interval). + * @method CarbonImmutable addMillenniaWithOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable addMillenniumWithOverflow() Add one millennium to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable subMillenniaWithOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable subMillenniumWithOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable addMillenniaWithoutOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addMillenniumWithoutOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subMillenniaWithoutOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subMillenniumWithoutOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addMillenniaWithNoOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addMillenniumWithNoOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subMillenniaWithNoOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subMillenniumWithNoOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addMillenniaNoOverflow(int $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addMillenniumNoOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subMillenniaNoOverflow(int $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subMillenniumNoOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addCenturies(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addCentury() Add one century to the instance (using date interval). + * @method CarbonImmutable subCenturies(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subCentury() Sub one century to the instance (using date interval). + * @method CarbonImmutable addCenturiesWithOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable addCenturyWithOverflow() Add one century to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable subCenturiesWithOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable subCenturyWithOverflow() Sub one century to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable addCenturiesWithoutOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addCenturyWithoutOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subCenturiesWithoutOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subCenturyWithoutOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addCenturiesWithNoOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addCenturyWithNoOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subCenturiesWithNoOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subCenturyWithNoOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addCenturiesNoOverflow(int $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addCenturyNoOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subCenturiesNoOverflow(int $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subCenturyNoOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addDecades(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addDecade() Add one decade to the instance (using date interval). + * @method CarbonImmutable subDecades(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subDecade() Sub one decade to the instance (using date interval). + * @method CarbonImmutable addDecadesWithOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable addDecadeWithOverflow() Add one decade to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable subDecadesWithOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable subDecadeWithOverflow() Sub one decade to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable addDecadesWithoutOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addDecadeWithoutOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subDecadesWithoutOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subDecadeWithoutOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addDecadesWithNoOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addDecadeWithNoOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subDecadesWithNoOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subDecadeWithNoOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addDecadesNoOverflow(int $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addDecadeNoOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subDecadesNoOverflow(int $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subDecadeNoOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addQuarters(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addQuarter() Add one quarter to the instance (using date interval). + * @method CarbonImmutable subQuarters(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subQuarter() Sub one quarter to the instance (using date interval). + * @method CarbonImmutable addQuartersWithOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable addQuarterWithOverflow() Add one quarter to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable subQuartersWithOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable subQuarterWithOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly allowed. + * @method CarbonImmutable addQuartersWithoutOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addQuarterWithoutOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subQuartersWithoutOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subQuarterWithoutOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addQuartersWithNoOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addQuarterWithNoOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subQuartersWithNoOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subQuarterWithNoOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addQuartersNoOverflow(int $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addQuarterNoOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subQuartersNoOverflow(int $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable subQuarterNoOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. + * @method CarbonImmutable addWeeks(int $value = 1) Add weeks (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addWeek() Add one week to the instance (using date interval). + * @method CarbonImmutable subWeeks(int $value = 1) Sub weeks (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subWeek() Sub one week to the instance (using date interval). + * @method CarbonImmutable addWeekdays(int $value = 1) Add weekdays (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable addWeekday() Add one weekday to the instance (using date interval). + * @method CarbonImmutable subWeekdays(int $value = 1) Sub weekdays (the $value count passed in) to the instance (using date interval). + * @method CarbonImmutable subWeekday() Sub one weekday to the instance (using date interval). + * @method CarbonImmutable addRealMicros(int $value = 1) Add microseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealMicro() Add one microsecond to the instance (using timestamp). + * @method CarbonImmutable subRealMicros(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealMicro() Sub one microsecond to the instance (using timestamp). + * @method CarbonPeriod microsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each microsecond or every X microseconds if a factor is given. + * @method CarbonImmutable addRealMicroseconds(int $value = 1) Add microseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealMicrosecond() Add one microsecond to the instance (using timestamp). + * @method CarbonImmutable subRealMicroseconds(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealMicrosecond() Sub one microsecond to the instance (using timestamp). + * @method CarbonPeriod microsecondsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each microsecond or every X microseconds if a factor is given. + * @method CarbonImmutable addRealMillis(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealMilli() Add one millisecond to the instance (using timestamp). + * @method CarbonImmutable subRealMillis(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealMilli() Sub one millisecond to the instance (using timestamp). + * @method CarbonPeriod millisUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millisecond or every X milliseconds if a factor is given. + * @method CarbonImmutable addRealMilliseconds(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealMillisecond() Add one millisecond to the instance (using timestamp). + * @method CarbonImmutable subRealMilliseconds(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealMillisecond() Sub one millisecond to the instance (using timestamp). + * @method CarbonPeriod millisecondsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millisecond or every X milliseconds if a factor is given. + * @method CarbonImmutable addRealSeconds(int $value = 1) Add seconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealSecond() Add one second to the instance (using timestamp). + * @method CarbonImmutable subRealSeconds(int $value = 1) Sub seconds (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealSecond() Sub one second to the instance (using timestamp). + * @method CarbonPeriod secondsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each second or every X seconds if a factor is given. + * @method CarbonImmutable addRealMinutes(int $value = 1) Add minutes (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealMinute() Add one minute to the instance (using timestamp). + * @method CarbonImmutable subRealMinutes(int $value = 1) Sub minutes (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealMinute() Sub one minute to the instance (using timestamp). + * @method CarbonPeriod minutesUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each minute or every X minutes if a factor is given. + * @method CarbonImmutable addRealHours(int $value = 1) Add hours (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealHour() Add one hour to the instance (using timestamp). + * @method CarbonImmutable subRealHours(int $value = 1) Sub hours (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealHour() Sub one hour to the instance (using timestamp). + * @method CarbonPeriod hoursUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each hour or every X hours if a factor is given. + * @method CarbonImmutable addRealDays(int $value = 1) Add days (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealDay() Add one day to the instance (using timestamp). + * @method CarbonImmutable subRealDays(int $value = 1) Sub days (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealDay() Sub one day to the instance (using timestamp). + * @method CarbonPeriod daysUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each day or every X days if a factor is given. + * @method CarbonImmutable addRealWeeks(int $value = 1) Add weeks (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealWeek() Add one week to the instance (using timestamp). + * @method CarbonImmutable subRealWeeks(int $value = 1) Sub weeks (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealWeek() Sub one week to the instance (using timestamp). + * @method CarbonPeriod weeksUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each week or every X weeks if a factor is given. + * @method CarbonImmutable addRealMonths(int $value = 1) Add months (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealMonth() Add one month to the instance (using timestamp). + * @method CarbonImmutable subRealMonths(int $value = 1) Sub months (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealMonth() Sub one month to the instance (using timestamp). + * @method CarbonPeriod monthsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each month or every X months if a factor is given. + * @method CarbonImmutable addRealQuarters(int $value = 1) Add quarters (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealQuarter() Add one quarter to the instance (using timestamp). + * @method CarbonImmutable subRealQuarters(int $value = 1) Sub quarters (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealQuarter() Sub one quarter to the instance (using timestamp). + * @method CarbonPeriod quartersUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each quarter or every X quarters if a factor is given. + * @method CarbonImmutable addRealYears(int $value = 1) Add years (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealYear() Add one year to the instance (using timestamp). + * @method CarbonImmutable subRealYears(int $value = 1) Sub years (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealYear() Sub one year to the instance (using timestamp). + * @method CarbonPeriod yearsUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each year or every X years if a factor is given. + * @method CarbonImmutable addRealDecades(int $value = 1) Add decades (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealDecade() Add one decade to the instance (using timestamp). + * @method CarbonImmutable subRealDecades(int $value = 1) Sub decades (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealDecade() Sub one decade to the instance (using timestamp). + * @method CarbonPeriod decadesUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each decade or every X decades if a factor is given. + * @method CarbonImmutable addRealCenturies(int $value = 1) Add centuries (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealCentury() Add one century to the instance (using timestamp). + * @method CarbonImmutable subRealCenturies(int $value = 1) Sub centuries (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealCentury() Sub one century to the instance (using timestamp). + * @method CarbonPeriod centuriesUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each century or every X centuries if a factor is given. + * @method CarbonImmutable addRealMillennia(int $value = 1) Add millennia (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable addRealMillennium() Add one millennium to the instance (using timestamp). + * @method CarbonImmutable subRealMillennia(int $value = 1) Sub millennia (the $value count passed in) to the instance (using timestamp). + * @method CarbonImmutable subRealMillennium() Sub one millennium to the instance (using timestamp). + * @method CarbonPeriod millenniaUntil($endDate = null, int $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millennium or every X millennia if a factor is given. + * @method CarbonImmutable roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. + * @method CarbonImmutable roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. + * @method CarbonImmutable floorYear(float $precision = 1) Truncate the current instance year with given precision. + * @method CarbonImmutable floorYears(float $precision = 1) Truncate the current instance year with given precision. + * @method CarbonImmutable ceilYear(float $precision = 1) Ceil the current instance year with given precision. + * @method CarbonImmutable ceilYears(float $precision = 1) Ceil the current instance year with given precision. + * @method CarbonImmutable roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. + * @method CarbonImmutable roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. + * @method CarbonImmutable floorMonth(float $precision = 1) Truncate the current instance month with given precision. + * @method CarbonImmutable floorMonths(float $precision = 1) Truncate the current instance month with given precision. + * @method CarbonImmutable ceilMonth(float $precision = 1) Ceil the current instance month with given precision. + * @method CarbonImmutable ceilMonths(float $precision = 1) Ceil the current instance month with given precision. + * @method CarbonImmutable roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. + * @method CarbonImmutable roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. + * @method CarbonImmutable floorDay(float $precision = 1) Truncate the current instance day with given precision. + * @method CarbonImmutable floorDays(float $precision = 1) Truncate the current instance day with given precision. + * @method CarbonImmutable ceilDay(float $precision = 1) Ceil the current instance day with given precision. + * @method CarbonImmutable ceilDays(float $precision = 1) Ceil the current instance day with given precision. + * @method CarbonImmutable roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. + * @method CarbonImmutable roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. + * @method CarbonImmutable floorHour(float $precision = 1) Truncate the current instance hour with given precision. + * @method CarbonImmutable floorHours(float $precision = 1) Truncate the current instance hour with given precision. + * @method CarbonImmutable ceilHour(float $precision = 1) Ceil the current instance hour with given precision. + * @method CarbonImmutable ceilHours(float $precision = 1) Ceil the current instance hour with given precision. + * @method CarbonImmutable roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. + * @method CarbonImmutable roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. + * @method CarbonImmutable floorMinute(float $precision = 1) Truncate the current instance minute with given precision. + * @method CarbonImmutable floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. + * @method CarbonImmutable ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. + * @method CarbonImmutable ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. + * @method CarbonImmutable roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. + * @method CarbonImmutable roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. + * @method CarbonImmutable floorSecond(float $precision = 1) Truncate the current instance second with given precision. + * @method CarbonImmutable floorSeconds(float $precision = 1) Truncate the current instance second with given precision. + * @method CarbonImmutable ceilSecond(float $precision = 1) Ceil the current instance second with given precision. + * @method CarbonImmutable ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. + * @method CarbonImmutable roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. + * @method CarbonImmutable roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. + * @method CarbonImmutable floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. + * @method CarbonImmutable floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. + * @method CarbonImmutable ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. + * @method CarbonImmutable ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. + * @method CarbonImmutable roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. + * @method CarbonImmutable roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. + * @method CarbonImmutable floorCentury(float $precision = 1) Truncate the current instance century with given precision. + * @method CarbonImmutable floorCenturies(float $precision = 1) Truncate the current instance century with given precision. + * @method CarbonImmutable ceilCentury(float $precision = 1) Ceil the current instance century with given precision. + * @method CarbonImmutable ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. + * @method CarbonImmutable roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. + * @method CarbonImmutable roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. + * @method CarbonImmutable floorDecade(float $precision = 1) Truncate the current instance decade with given precision. + * @method CarbonImmutable floorDecades(float $precision = 1) Truncate the current instance decade with given precision. + * @method CarbonImmutable ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. + * @method CarbonImmutable ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. + * @method CarbonImmutable roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. + * @method CarbonImmutable roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. + * @method CarbonImmutable floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. + * @method CarbonImmutable floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. + * @method CarbonImmutable ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. + * @method CarbonImmutable ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. + * @method CarbonImmutable roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. + * @method CarbonImmutable roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. + * @method CarbonImmutable floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. + * @method CarbonImmutable floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. + * @method CarbonImmutable ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. + * @method CarbonImmutable ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. + * @method CarbonImmutable roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. + * @method CarbonImmutable roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. + * @method CarbonImmutable floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. + * @method CarbonImmutable floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. + * @method CarbonImmutable ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. + * @method CarbonImmutable ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. + * @method string shortAbsoluteDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'Absolute' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string longAbsoluteDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'Absolute' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string shortRelativeDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'Relative' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string longRelativeDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'Relative' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string shortRelativeToNowDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'RelativeToNow' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string longRelativeToNowDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'RelativeToNow' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string shortRelativeToOtherDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'RelativeToOther' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method string longRelativeToOtherDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'RelativeToOther' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) + * @method static static|false createFromFormat(string $format, string $time, DateTimeZone|string|false|null $timezone = null) Parse a string into a new CarbonImmutable object according to the specified format. + * @method static static __set_state(array $array) https://php.net/manual/en/datetime.set-state.php * * */ diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/CarbonInterface.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/CarbonInterface.php index 15e2061c7..b90e29817 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/CarbonInterface.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/CarbonInterface.php @@ -586,6 +586,7 @@ interface CarbonInterface extends DateTimeInterface, JsonSerializable public const YEARS_PER_DECADE = 10; public const MONTHS_PER_YEAR = 12; public const MONTHS_PER_QUARTER = 3; + public const QUARTERS_PER_YEAR = 4; public const WEEKS_PER_YEAR = 52; public const WEEKS_PER_MONTH = 4; public const DAYS_PER_YEAR = 365; @@ -726,6 +727,8 @@ interface CarbonInterface extends DateTimeInterface, JsonSerializable /** * Returns the list of properties to dump on serialize() called on. * + * Only used by PHP < 7.4. + * * @return array */ public function __sleep(); @@ -735,7 +738,7 @@ interface CarbonInterface extends DateTimeInterface, JsonSerializable * * @example * ``` - * echo Carbon::now(); // Carbon instances can be casted to string + * echo Carbon::now(); // Carbon instances can be cast to string * ``` * * @return string @@ -987,7 +990,7 @@ interface CarbonInterface extends DateTimeInterface, JsonSerializable * * @param string $modifier * - * @return static + * @return static|false */ public function change($modifier); @@ -1038,13 +1041,13 @@ interface CarbonInterface extends DateTimeInterface, JsonSerializable * If $hour is not null then the default values for $minute and $second * will be 0. * - * @param int|null $year - * @param int|null $month - * @param int|null $day - * @param int|null $hour - * @param int|null $minute - * @param int|null $second - * @param DateTimeZone|string|null $tz + * @param DateTimeInterface|int|null $year + * @param int|null $month + * @param int|null $day + * @param int|null $hour + * @param int|null $minute + * @param int|null $second + * @param DateTimeZone|string|null $tz * * @throws InvalidFormatException * @@ -1276,7 +1279,7 @@ interface CarbonInterface extends DateTimeInterface, JsonSerializable * * @return CarbonInterval */ - public function diffAsCarbonInterval($date = null, $absolute = true); + public function diffAsCarbonInterval($date = null, $absolute = true, array $skip = []); /** * Get the difference by the given interval using a filter closure. @@ -2116,6 +2119,18 @@ interface CarbonInterface extends DateTimeInterface, JsonSerializable */ public static function getDays(); + /** + * Return the number of days since the start of the week (using the current locale or the first parameter + * if explicitly given). + * + * @param int|null $weekStartsAt optional start allow you to specify the day of week to use to start the week, + * if not provided, start of week is inferred from the locale + * (Sunday for en_US, Monday for de_DE, etc.) + * + * @return int + */ + public function getDaysFromStartOfWeek(?int $weekStartsAt = null): int; + /** * Get the fallback locale. * @@ -2738,12 +2753,35 @@ interface CarbonInterface extends DateTimeInterface, JsonSerializable public function isLeapYear(); /** - * Determines if the instance is a long year + * Determines if the instance is a long year (using ISO 8601 year). * * @example * ``` - * Carbon::parse('2015-01-01')->isLongYear(); // true - * Carbon::parse('2016-01-01')->isLongYear(); // false + * Carbon::parse('2015-01-01')->isLongIsoYear(); // true + * Carbon::parse('2016-01-01')->isLongIsoYear(); // true + * Carbon::parse('2016-01-03')->isLongIsoYear(); // false + * Carbon::parse('2019-12-29')->isLongIsoYear(); // false + * Carbon::parse('2019-12-30')->isLongIsoYear(); // true + * ``` + * + * @see https://en.wikipedia.org/wiki/ISO_8601#Week_dates + * + * @return bool + */ + public function isLongIsoYear(); + + /** + * Determines if the instance is a long year (using calendar year). + * + * ⚠️ This method completely ignores month and day to use the numeric year number, + * it's not correct if the exact date matters. For instance as `2019-12-30` is already + * in the first week of the 2020 year, if you want to know from this date if ISO week + * year 2020 is a long year, use `isLongIsoYear` instead. + * + * @example + * ``` + * Carbon::create(2015)->isLongYear(); // true + * Carbon::create(2016)->isLongYear(); // false * ``` * * @see https://en.wikipedia.org/wiki/ISO_8601#Week_dates @@ -3382,7 +3420,7 @@ interface CarbonInterface extends DateTimeInterface, JsonSerializable * * @param string|int|null $modifier * - * @return static + * @return static|false */ public function next($modifier = null); @@ -3528,7 +3566,7 @@ interface CarbonInterface extends DateTimeInterface, JsonSerializable * * @param string|int|null $modifier * - * @return static + * @return static|false */ public function previous($modifier = null); @@ -3773,6 +3811,19 @@ interface CarbonInterface extends DateTimeInterface, JsonSerializable */ public function setDateTimeFrom($date = null); + /** + * Set the day (keeping the current time) to the start of the week + the number of days passed as the first + * parameter. First day of week is driven by the locale unless explicitly set with the second parameter. + * + * @param int $numberOfDays number of days to add after the start of the current week + * @param int|null $weekStartsAt optional start allow you to specify the day of week to use to start the week, + * if not provided, start of week is inferred from the locale + * (Sunday for en_US, Monday for de_DE, etc.) + * + * @return static + */ + public function setDaysFromStartOfWeek(int $numberOfDays, ?int $weekStartsAt = null); + /** * Set the fallback locale. * @@ -3860,7 +3911,7 @@ interface CarbonInterface extends DateTimeInterface, JsonSerializable * * /!\ Use this method for unit tests only. * - * @param Closure|static|string|false|null $testNow real or mock Carbon instance + * @param DateTimeInterface|Closure|static|string|false|null $testNow real or mock Carbon instance */ public static function setTestNow($testNow = null); @@ -3881,7 +3932,7 @@ interface CarbonInterface extends DateTimeInterface, JsonSerializable * * /!\ Use this method for unit tests only. * - * @param Closure|static|string|false|null $testNow real or mock Carbon instance + * @param DateTimeInterface|Closure|static|string|false|null $testNow real or mock Carbon instance */ public static function setTestNowAndTimezone($testNow = null, $tz = null); @@ -3942,11 +3993,11 @@ interface CarbonInterface extends DateTimeInterface, JsonSerializable /** * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. - * You should rather let Carbon object being casted to string with DEFAULT_TO_STRING_FORMAT, and - * use other method or custom format passed to format() method if you need to dump an other string + * You should rather let Carbon object being cast to string with DEFAULT_TO_STRING_FORMAT, and + * use other method or custom format passed to format() method if you need to dump another string * format. * - * Set the default format used when type juggling a Carbon instance to a string + * Set the default format used when type juggling a Carbon instance to a string. * * @param string|Closure|null $format * @@ -4537,6 +4588,18 @@ interface CarbonInterface extends DateTimeInterface, JsonSerializable */ public function toFormattedDateString(); + /** + * Format the instance with the day, and a readable date + * + * @example + * ``` + * echo Carbon::now()->toFormattedDayDateString(); + * ``` + * + * @return string + */ + public function toFormattedDayDateString(): string; + /** * Return the ISO-8601 string (ex: 1977-04-22T06:00:00Z, if $keepOffset truthy, offset will be kept: * 1977-04-22T01:00:00-05:00). @@ -5057,12 +5120,14 @@ interface CarbonInterface extends DateTimeInterface, JsonSerializable * * /!\ Use this method for unit tests only. * - * @param Closure|static|string|false|null $testNow real or mock Carbon instance - * @param Closure|null $callback + * @template T * - * @return mixed + * @param DateTimeInterface|Closure|static|string|false|null $testNow real or mock Carbon instance + * @param Closure(): T $callback + * + * @return T */ - public static function withTestNow($testNow = null, $callback = null); + public static function withTestNow($testNow, $callback); /** * Create a Carbon instance for yesterday. diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/CarbonInterval.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/CarbonInterval.php index d465beac7..8437c545e 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/CarbonInterval.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/CarbonInterval.php @@ -15,6 +15,7 @@ use Carbon\Exceptions\BadFluentConstructorException; use Carbon\Exceptions\BadFluentSetterException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidIntervalException; +use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\ParseErrorException; use Carbon\Exceptions\UnitNotConfiguredException; use Carbon\Exceptions\UnknownGetterException; @@ -22,15 +23,20 @@ use Carbon\Exceptions\UnknownSetterException; use Carbon\Exceptions\UnknownUnitException; use Carbon\Traits\IntervalRounding; use Carbon\Traits\IntervalStep; +use Carbon\Traits\MagicParameter; use Carbon\Traits\Mixin; use Carbon\Traits\Options; +use Carbon\Traits\ToStringFormat; use Closure; use DateInterval; +use DateMalformedIntervalStringException; use DateTimeInterface; use DateTimeZone; use Exception; +use InvalidArgumentException; use ReflectionException; use ReturnTypeWillChange; +use RuntimeException; use Throwable; /** @@ -46,7 +52,7 @@ use Throwable; * @property int $minutes Total minutes of the current interval. * @property int $seconds Total seconds of the current interval. * @property int $microseconds Total microseconds of the current interval. - * @property int $milliseconds Total microseconds of the current interval. + * @property int $milliseconds Total milliseconds of the current interval. * @property int $microExcludeMilli Remaining microseconds without the milliseconds. * @property int $dayzExcludeWeeks Total days remaining in the final week of the current instance (days % 7). * @property int $daysExcludeWeeks alias of dayzExcludeWeeks @@ -184,10 +190,12 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface { use IntervalRounding; use IntervalStep; + use MagicParameter; use Mixin { Mixin::mixin as baseMixin; } use Options; + use ToStringFormat; /** * Interval spec period designators @@ -241,6 +249,11 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface */ private static $flipCascadeFactors; + /** + * @var bool + */ + private static $floatSettersEnabled = false; + /** * The registered macros. * @@ -294,7 +307,12 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface */ public static function getCascadeFactors() { - return static::$cascadeFactors ?: [ + return static::$cascadeFactors ?: static::getDefaultCascadeFactors(); + } + + protected static function getDefaultCascadeFactors(): array + { + return [ 'milliseconds' => [Carbon::MICROSECONDS_PER_MILLISECOND, 'microseconds'], 'seconds' => [Carbon::MILLISECONDS_PER_SECOND, 'milliseconds'], 'minutes' => [Carbon::SECONDS_PER_MINUTE, 'seconds'], @@ -337,6 +355,19 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface static::$cascadeFactors = $cascadeFactors; } + /** + * This option allow you to opt-in for the Carbon 3 behavior where float + * values will no longer be cast to integer (so truncated). + * + * ⚠️ This settings will be applied globally, which mean your whole application + * code including the third-party dependencies that also may use Carbon will + * adopt the new behavior. + */ + public static function enableFloatSetters(bool $floatSettersEnabled = true): void + { + self::$floatSettersEnabled = $floatSettersEnabled; + } + /////////////////////////////////////////////////////////////////// //////////////////////////// CONSTRUCTORS ///////////////////////// /////////////////////////////////////////////////////////////////// @@ -344,14 +375,14 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface /** * Create a new CarbonInterval instance. * - * @param int|null $years - * @param int|null $months - * @param int|null $weeks - * @param int|null $days - * @param int|null $hours - * @param int|null $minutes - * @param int|null $seconds - * @param int|null $microseconds + * @param Closure|DateInterval|string|int|null $years + * @param int|float|null $months + * @param int|float|null $weeks + * @param int|float|null $days + * @param int|float|null $hours + * @param int|float|null $minutes + * @param int|float|null $seconds + * @param int|float|null $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. */ @@ -371,8 +402,9 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface } $spec = $years; + $isStringSpec = (\is_string($spec) && !preg_match('/^[\d.]/', $spec)); - if (!\is_string($spec) || (float) $years || preg_match('/^[0-9.]/', $years)) { + if (!$isStringSpec || (float) $years) { $spec = static::PERIOD_PREFIX; $spec .= $years > 0 ? $years.static::PERIOD_YEARS : ''; @@ -397,7 +429,74 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface } } - parent::__construct($spec); + try { + parent::__construct($spec); + } catch (Throwable $exception) { + try { + parent::__construct('PT0S'); + + if ($isStringSpec) { + if (!preg_match('/^P + (?:(?[+-]?\d*(?:\.\d+)?)Y)? + (?:(?[+-]?\d*(?:\.\d+)?)M)? + (?:(?[+-]?\d*(?:\.\d+)?)W)? + (?:(?[+-]?\d*(?:\.\d+)?)D)? + (?:T + (?:(?[+-]?\d*(?:\.\d+)?)H)? + (?:(?[+-]?\d*(?:\.\d+)?)M)? + (?:(?[+-]?\d*(?:\.\d+)?)S)? + )? + $/x', $spec, $match)) { + throw new InvalidArgumentException("Invalid duration: $spec"); + } + + $years = (float) ($match['year'] ?? 0); + $this->assertSafeForInteger('year', $years); + $months = (float) ($match['month'] ?? 0); + $this->assertSafeForInteger('month', $months); + $weeks = (float) ($match['week'] ?? 0); + $this->assertSafeForInteger('week', $weeks); + $days = (float) ($match['day'] ?? 0); + $this->assertSafeForInteger('day', $days); + $hours = (float) ($match['hour'] ?? 0); + $this->assertSafeForInteger('hour', $hours); + $minutes = (float) ($match['minute'] ?? 0); + $this->assertSafeForInteger('minute', $minutes); + $seconds = (float) ($match['second'] ?? 0); + $this->assertSafeForInteger('second', $seconds); + } + + $totalDays = (($weeks * static::getDaysPerWeek()) + $days); + $this->assertSafeForInteger('days total (including weeks)', $totalDays); + + $this->y = (int) $years; + $this->m = (int) $months; + $this->d = (int) $totalDays; + $this->h = (int) $hours; + $this->i = (int) $minutes; + $this->s = (int) $seconds; + + if ( + ((float) $this->y) !== $years || + ((float) $this->m) !== $months || + ((float) $this->d) !== $totalDays || + ((float) $this->h) !== $hours || + ((float) $this->i) !== $minutes || + ((float) $this->s) !== $seconds + ) { + $this->add(static::fromString( + ($years - $this->y).' years '. + ($months - $this->m).' months '. + ($totalDays - $this->d).' days '. + ($hours - $this->h).' hours '. + ($minutes - $this->i).' minutes '. + ($seconds - $this->s).' seconds ' + )); + } + } catch (Throwable $secondException) { + throw $secondException instanceof OutOfRangeException ? $secondException : $exception; + } + } if ($microseconds !== null) { $this->f = $microseconds / Carbon::MICROSECONDS_PER_SECOND; @@ -410,7 +509,7 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface * @param string $source * @param string $target * - * @return int|null + * @return int|float|null */ public static function getFactor($source, $target) { @@ -438,7 +537,7 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface * @param string $source * @param string $target * - * @return int|null + * @return int|float|null */ public static function getFactorWithDefault($source, $target) { @@ -465,7 +564,7 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface /** * Returns current config for days per week. * - * @return int + * @return int|float */ public static function getDaysPerWeek() { @@ -475,7 +574,7 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface /** * Returns current config for hours per day. * - * @return int + * @return int|float */ public static function getHoursPerDay() { @@ -485,7 +584,7 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface /** * Returns current config for minutes per hour. * - * @return int + * @return int|float */ public static function getMinutesPerHour() { @@ -495,7 +594,7 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface /** * Returns current config for seconds per minute. * - * @return int + * @return int|float */ public static function getSecondsPerMinute() { @@ -505,7 +604,7 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface /** * Returns current config for microseconds per second. * - * @return int + * @return int|float */ public static function getMillisecondsPerSecond() { @@ -515,7 +614,7 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface /** * Returns current config for microseconds per second. * - * @return int + * @return int|float */ public static function getMicrosecondsPerMillisecond() { @@ -673,6 +772,23 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface } } + /** + * Evaluate the PHP generated by var_export() and recreate the exported CarbonInterval instance. + * + * @param array $dump data as exported by var_export() + * + * @return static + */ + #[ReturnTypeWillChange] + public static function __set_state($dump) + { + /** @noinspection PhpVoidFunctionResultUsedInspection */ + /** @var DateInterval $dateInterval */ + $dateInterval = parent::__set_state($dump); + + return static::instance($dateInterval); + } + /** * Return the current context from inside a macro callee or a new one if static. * @@ -767,6 +883,8 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface case 'year': case 'years': case 'y': + case 'yr': + case 'yrs': $years += $intValue; break; @@ -780,6 +898,7 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface case 'month': case 'months': case 'mo': + case 'mos': $months += $intValue; break; @@ -882,7 +1001,7 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface return static::fromString(Carbon::translateTimeString($interval, $locale ?: static::getLocale(), 'en')); } - private static function castIntervalToClass(DateInterval $interval, string $className) + private static function castIntervalToClass(DateInterval $interval, string $className, array $skip = []) { $mainClass = DateInterval::class; @@ -891,7 +1010,7 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface } $microseconds = $interval->f; - $instance = new $className(static::getDateIntervalSpec($interval)); + $instance = new $className(static::getDateIntervalSpec($interval, false, $skip)); if ($microseconds) { $instance->f = $microseconds; @@ -940,12 +1059,19 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface * set the $days field. * * @param DateInterval $interval + * @param bool $skipCopy set to true to return the passed object + * (without copying it) if it's already of the + * current class * * @return static */ - public static function instance(DateInterval $interval) + public static function instance(DateInterval $interval, array $skip = [], bool $skipCopy = false) { - return self::castIntervalToClass($interval, static::class); + if ($skipCopy && $interval instanceof static) { + return $interval; + } + + return self::castIntervalToClass($interval, static::class, $skip); } /** @@ -956,17 +1082,20 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface * * @param mixed|int|DateInterval|string|Closure|null $interval interval or number of the given $unit * @param string|null $unit if specified, $interval must be an integer + * @param bool $skipCopy set to true to return the passed object + * (without copying it) if it's already of the + * current class * * @return static|null */ - public static function make($interval, $unit = null) + public static function make($interval, $unit = null, bool $skipCopy = false) { if ($unit) { $interval = "$interval ".Carbon::pluralUnit($unit); } if ($interval instanceof DateInterval) { - return static::instance($interval); + return static::instance($interval, [], $skipCopy); } if ($interval instanceof Closure) { @@ -984,7 +1113,7 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface { $interval = preg_replace('/\s+/', ' ', trim($interval)); - if (preg_match('/^P[T0-9]/', $interval)) { + if (preg_match('/^P[T\d]/', $interval)) { return new static($interval); } @@ -992,8 +1121,14 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface return static::fromString($interval); } - /** @var static $interval */ - $interval = static::createFromDateString($interval); + // @codeCoverageIgnoreStart + try { + /** @var static $interval */ + $interval = static::createFromDateString($interval); + } catch (DateMalformedIntervalStringException $e) { + return null; + } + // @codeCoverageIgnoreEnd return !$interval || $interval->isEmpty() ? null : $interval; } @@ -1081,11 +1216,11 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface return (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND) % Carbon::MICROSECONDS_PER_MILLISECOND; case 'weeks': - return (int) ($this->d / static::getDaysPerWeek()); + return (int) ($this->d / (int) static::getDaysPerWeek()); case 'daysExcludeWeeks': case 'dayzExcludeWeeks': - return $this->d % static::getDaysPerWeek(); + return $this->d % (int) static::getDaysPerWeek(); case 'locale': return $this->getTranslatorLocale(); @@ -1126,43 +1261,63 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface foreach ($properties as $key => $value) { switch (Carbon::singularUnit(rtrim($key, 'z'))) { case 'year': + $this->checkIntegerValue($key, $value); $this->y = $value; + $this->handleDecimalPart('year', $value, $this->y); break; case 'month': + $this->checkIntegerValue($key, $value); $this->m = $value; + $this->handleDecimalPart('month', $value, $this->m); break; case 'week': - $this->d = $value * static::getDaysPerWeek(); + $this->checkIntegerValue($key, $value); + $days = $value * (int) static::getDaysPerWeek(); + $this->assertSafeForInteger('days total (including weeks)', $days); + $this->d = $days; + $this->handleDecimalPart('day', $days, $this->d); break; case 'day': + $this->checkIntegerValue($key, $value); $this->d = $value; + $this->handleDecimalPart('day', $value, $this->d); break; case 'daysexcludeweek': case 'dayzexcludeweek': - $this->d = $this->weeks * static::getDaysPerWeek() + $value; + $this->checkIntegerValue($key, $value); + $days = $this->weeks * (int) static::getDaysPerWeek() + $value; + $this->assertSafeForInteger('days total (including weeks)', $days); + $this->d = $days; + $this->handleDecimalPart('day', $days, $this->d); break; case 'hour': + $this->checkIntegerValue($key, $value); $this->h = $value; + $this->handleDecimalPart('hour', $value, $this->h); break; case 'minute': + $this->checkIntegerValue($key, $value); $this->i = $value; + $this->handleDecimalPart('minute', $value, $this->i); break; case 'second': + $this->checkIntegerValue($key, $value); $this->s = $value; + $this->handleDecimalPart('second', $value, $this->s); break; @@ -1355,11 +1510,15 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface } if (preg_match('/^(?add|sub)(?[A-Z].*)$/', $method, $match)) { - return $this->{$match['method']}($parameters[0], $match['unit']); + $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($match['unit']), 0); + + return $this->{$match['method']}($value, $match['unit']); } + $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($method), 1); + try { - $this->set($method, \count($parameters) === 0 ? 1 : $parameters[0]); + $this->set($method, $value); } catch (UnknownSetterException $exception) { if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new BadFluentSetterException($method, 0, $exception); @@ -1410,9 +1569,9 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface $minimumUnit = 's'; $skip = []; extract($this->getForHumansInitialVariables($syntax, $short)); - $skip = array_filter((array) $skip, static function ($value) { + $skip = array_map('strtolower', array_filter((array) $skip, static function ($value) { return \is_string($value) && $value !== ''; - }); + })); if ($syntax === null) { $syntax = CarbonInterface::DIFF_ABSOLUTE; @@ -1435,11 +1594,9 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface ]; } - if ($altNumbers) { - if ($altNumbers !== true) { - $language = new Language($this->locale); - $altNumbers = \in_array($language->getCode(), (array) $altNumbers); - } + if ($altNumbers && $altNumbers !== true) { + $language = new Language($this->locale); + $altNumbers = \in_array($language->getCode(), (array) $altNumbers, true); } if (\is_array($join)) { @@ -1620,18 +1777,23 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface $unit = $short ? 's' : 'second'; $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); + $declensionMode = null; /** @var \Symfony\Component\Translation\Translator $translator */ $translator = $this->getLocalTranslator(); - $handleDeclensions = function ($unit, $count) use ($interpolations, $transId, $translator, $altNumbers, $absolute) { + $handleDeclensions = function ($unit, $count, $index = 0, $parts = 1) use ($interpolations, $transId, $translator, $altNumbers, $absolute, &$declensionMode) { if (!$absolute) { - // Some languages have special pluralization for past and future tense. - $key = $unit.'_'.$transId; - $result = $this->translate($key, $interpolations, $count, $translator, $altNumbers); + $declensionMode = $declensionMode ?? $this->translate($transId.'_mode'); - if ($result !== $key) { - return $result; + if ($this->needsDeclension($declensionMode, $index, $parts)) { + // Some languages have special pluralization for past and future tense. + $key = $unit.'_'.$transId; + $result = $this->translate($key, $interpolations, $count, $translator, $altNumbers); + + if ($result !== $key) { + return $result; + } } } @@ -1696,17 +1858,17 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface } } - $transChoice = function ($short, $unitData) use ($absolute, $handleDeclensions, $translator, $aUnit, $altNumbers, $interpolations) { + $transChoice = function ($short, $unitData, $index, $parts) use ($absolute, $handleDeclensions, $translator, $aUnit, $altNumbers, $interpolations) { $count = $unitData['value']; if ($short) { - $result = $handleDeclensions($unitData['unitShort'], $count); + $result = $handleDeclensions($unitData['unitShort'], $count, $index, $parts); if ($result !== null) { return $result; } } elseif ($aUnit) { - $result = $handleDeclensions('a_'.$unitData['unit'], $count); + $result = $handleDeclensions('a_'.$unitData['unit'], $count, $index, $parts); if ($result !== null) { return $result; @@ -1714,7 +1876,7 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface } if (!$absolute) { - return $handleDeclensions($unitData['unit'], $count); + return $handleDeclensions($unitData['unit'], $count, $index, $parts); } return $this->translate($unitData['unit'], $interpolations, $count, $translator, $altNumbers); @@ -1726,7 +1888,7 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface if ($diffIntervalData['value'] > 0) { $unit = $short ? $diffIntervalData['unitShort'] : $diffIntervalData['unit']; $count = $diffIntervalData['value']; - $interval[] = $transChoice($short, $diffIntervalData); + $interval[] = [$short, $diffIntervalData]; } elseif ($options & CarbonInterface::SEQUENTIAL_PARTS_ONLY && \count($interval) > 0) { break; } @@ -1737,13 +1899,19 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface } // break the loop after we have reached the minimum unit - if (\in_array($minimumUnit, [$diffIntervalData['unit'], $diffIntervalData['unitShort']])) { + if (\in_array($minimumUnit, [$diffIntervalData['unit'], $diffIntervalData['unitShort']], true)) { $fallbackUnit = [$diffIntervalData['unit'], $diffIntervalData['unitShort']]; break; } } + $actualParts = \count($interval); + + foreach ($interval as $index => &$item) { + $item = $transChoice($item[0], $item[1], $index, $actualParts); + } + if (\count($interval) === 0) { if ($relativeToNow && $options & CarbonInterface::JUST_NOW) { $key = 'diff_now'; @@ -1812,17 +1980,17 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface */ public function __toString() { - $format = $this->localToStringFormat; + $format = $this->localToStringFormat ?? static::$toStringFormat; - if ($format) { - if ($format instanceof Closure) { - return $format($this); - } - - return $this->format($format); + if (!$format) { + return $this->forHumans(); } - return $this->forHumans(); + if ($format instanceof Closure) { + return $format($this); + } + + return $this->format($format); } /** @@ -1863,7 +2031,7 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface /** * Invert the interval. * - * @param bool|int $inverted if a parameter is passed, the passed value casted as 1 or 0 is used + * @param bool|int $inverted if a parameter is passed, the passed value cast as 1 or 0 is used * as the new value of the ->invert property. * * @return $this @@ -2141,7 +2309,7 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface * * @return string */ - public static function getDateIntervalSpec(DateInterval $interval) + public static function getDateIntervalSpec(DateInterval $interval, bool $microseconds = false, array $skip = []) { $date = array_filter([ static::PERIOD_YEARS => abs($interval->y), @@ -2149,10 +2317,25 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface static::PERIOD_DAYS => abs($interval->d), ]); + if ( + $interval->days >= CarbonInterface::DAYS_PER_WEEK * CarbonInterface::WEEKS_PER_MONTH && + (!isset($date[static::PERIOD_YEARS]) || \count(array_intersect(['y', 'year', 'years'], $skip))) && + (!isset($date[static::PERIOD_MONTHS]) || \count(array_intersect(['m', 'month', 'months'], $skip))) + ) { + $date = [ + static::PERIOD_DAYS => abs($interval->days), + ]; + } + + $seconds = abs($interval->s); + if ($microseconds && $interval->f > 0) { + $seconds = sprintf('%d.%06d', $seconds, abs($interval->f) * 1000000); + } + $time = array_filter([ static::PERIOD_HOURS => abs($interval->h), static::PERIOD_MINUTES => abs($interval->i), - static::PERIOD_SECONDS => abs($interval->s), + static::PERIOD_SECONDS => $seconds, ]); $specString = static::PERIOD_PREFIX; @@ -2176,9 +2359,9 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface * * @return string */ - public function spec() + public function spec(bool $microseconds = false) { - return static::getDateIntervalSpec($this); + return static::getDateIntervalSpec($this, $microseconds); } /** @@ -2229,9 +2412,11 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface $originalData = $this->toArray(); $originalData['milliseconds'] = (int) ($originalData['microseconds'] / static::getMicrosecondsPerMillisecond()); $originalData['microseconds'] = $originalData['microseconds'] % static::getMicrosecondsPerMillisecond(); - $originalData['daysExcludeWeeks'] = $originalData['days']; + $originalData['weeks'] = (int) ($this->d / static::getDaysPerWeek()); + $originalData['daysExcludeWeeks'] = fmod($this->d, static::getDaysPerWeek()); unset($originalData['days']); $newData = $originalData; + $previous = []; foreach (self::getFlipCascadeFactors() as $source => [$target, $factor]) { foreach (['source', 'target'] as $key) { @@ -2241,9 +2426,29 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface } $value = $newData[$source]; - $modulo = ($factor + ($value % $factor)) % $factor; + $modulo = fmod($factor + fmod($value, $factor), $factor); $newData[$source] = $modulo; $newData[$target] += ($value - $modulo) / $factor; + + $decimalPart = fmod($newData[$source], 1); + + if ($decimalPart !== 0.0) { + $unit = $source; + + foreach ($previous as [$subUnit, $subFactor]) { + $newData[$unit] -= $decimalPart; + $newData[$subUnit] += $decimalPart * $subFactor; + $decimalPart = fmod($newData[$subUnit], 1); + + if ($decimalPart === 0.0) { + break; + } + + $unit = $subUnit; + } + } + + array_unshift($previous, [$source, $factor]); } $positive = null; @@ -2324,13 +2529,13 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface $cumulativeFactor = 0; $unitFound = false; $factors = self::getFlipCascadeFactors(); - $daysPerWeek = static::getDaysPerWeek(); + $daysPerWeek = (int) static::getDaysPerWeek(); $values = [ 'years' => $this->years, 'months' => $this->months, 'weeks' => (int) ($this->d / $daysPerWeek), - 'dayz' => $this->d % $daysPerWeek, + 'dayz' => fmod($this->d, $daysPerWeek), 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, @@ -2391,10 +2596,11 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface } if ($unit === 'weeks') { - return $result / $daysPerWeek; + $result /= $daysPerWeek; } - return $result; + // Cast as int numbers with no decimal part + return fmod($result, 1) === 0.0 ? (int) $result : $result; } /** @@ -2662,6 +2868,15 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface */ public function roundUnit($unit, $precision = 1, $function = 'round') { + if (static::getCascadeFactors() !== static::getDefaultCascadeFactors()) { + $value = $function($this->total($unit) / $precision) * $precision; + $inverted = $value < 0; + + return $this->copyProperties(self::fromString( + number_format(abs($value), 12, '.', '').' '.$unit + )->invert($inverted)->cascade()); + } + $base = CarbonImmutable::parse('2000-01-01 00:00:00', 'UTC') ->roundUnit($unit, $precision, $function); $next = $base->add($this); @@ -2752,4 +2967,88 @@ class CarbonInterval extends DateInterval implements CarbonConverterInterface { return $this->round($precision, 'ceil'); } + + private function needsDeclension(string $mode, int $index, int $parts): bool + { + switch ($mode) { + case 'last': + return $index === $parts - 1; + default: + return true; + } + } + + private function checkIntegerValue(string $name, $value) + { + if (\is_int($value)) { + return; + } + + $this->assertSafeForInteger($name, $value); + + if (\is_float($value) && (((float) (int) $value) === $value)) { + return; + } + + if (!self::$floatSettersEnabled) { + $type = \gettype($value); + @trigger_error( + "Since 2.70.0, it's deprecated to pass $type value for $name.\n". + "It's truncated when stored as an integer interval unit.\n". + "From 3.0.0, decimal part will no longer be truncated and will be cascaded to smaller units.\n". + "- To maintain the current behavior, use explicit cast: $name((int) \$value)\n". + "- To adopt the new behavior globally, call CarbonInterval::enableFloatSetters()\n", + \E_USER_DEPRECATED + ); + } + } + + /** + * Throw an exception if precision loss when storing the given value as an integer would be >= 1.0. + */ + private function assertSafeForInteger(string $name, $value) + { + if ($value && !\is_int($value) && ($value >= 0x7fffffffffffffff || $value <= -0x7fffffffffffffff)) { + throw new OutOfRangeException($name, -0x7fffffffffffffff, 0x7fffffffffffffff, $value); + } + } + + private function handleDecimalPart(string $unit, $value, $integerValue) + { + if (self::$floatSettersEnabled) { + $floatValue = (float) $value; + $base = (float) $integerValue; + + if ($floatValue === $base) { + return; + } + + $units = [ + 'y' => 'year', + 'm' => 'month', + 'd' => 'day', + 'h' => 'hour', + 'i' => 'minute', + 's' => 'second', + ]; + $upper = true; + + foreach ($units as $property => $name) { + if ($name === $unit) { + $upper = false; + + continue; + } + + if (!$upper && $this->$property !== 0) { + throw new RuntimeException( + "You cannot set $unit to a float value as $name would be overridden, ". + 'set it first to 0 explicitly if you really want to erase its value' + ); + } + } + + $this->add($unit, $floatValue - $base); + } + } } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/CarbonPeriod.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/CarbonPeriod.php index 0e81e7573..d12a98697 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/CarbonPeriod.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/CarbonPeriod.php @@ -11,6 +11,7 @@ namespace Carbon; +use Carbon\Exceptions\EndLessPeriodException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\InvalidPeriodDateException; @@ -23,11 +24,13 @@ use Carbon\Exceptions\UnreachableException; use Carbon\Traits\IntervalRounding; use Carbon\Traits\Mixin; use Carbon\Traits\Options; +use Carbon\Traits\ToStringFormat; use Closure; use Countable; use DateInterval; use DatePeriod; use DateTime; +use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use InvalidArgumentException; @@ -48,43 +51,47 @@ use RuntimeException; * @property-read CarbonInterface $end Period end date. * @property-read CarbonInterval $interval Underlying date interval instance. Always present, one day by default. * - * @method static CarbonPeriod start($date, $inclusive = null) Create instance specifying start date or modify the start date if called on an instance. - * @method static CarbonPeriod since($date, $inclusive = null) Alias for start(). - * @method static CarbonPeriod sinceNow($inclusive = null) Create instance with start date set to now or set the start date to now if called on an instance. - * @method static CarbonPeriod end($date = null, $inclusive = null) Create instance specifying end date or modify the end date if called on an instance. - * @method static CarbonPeriod until($date = null, $inclusive = null) Alias for end(). - * @method static CarbonPeriod untilNow($inclusive = null) Create instance with end date set to now or set the end date to now if called on an instance. - * @method static CarbonPeriod dates($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. - * @method static CarbonPeriod between($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. - * @method static CarbonPeriod recurrences($recurrences = null) Create instance with maximum number of recurrences or modify the number of recurrences if called on an instance. - * @method static CarbonPeriod times($recurrences = null) Alias for recurrences(). - * @method static CarbonPeriod options($options = null) Create instance with options or modify the options if called on an instance. - * @method static CarbonPeriod toggle($options, $state = null) Create instance with options toggled on or off, or toggle options if called on an instance. - * @method static CarbonPeriod filter($callback, $name = null) Create instance with filter added to the stack or append a filter if called on an instance. - * @method static CarbonPeriod push($callback, $name = null) Alias for filter(). - * @method static CarbonPeriod prepend($callback, $name = null) Create instance with filter prepended to the stack or prepend a filter if called on an instance. - * @method static CarbonPeriod filters(array $filters = []) Create instance with filters stack or replace the whole filters stack if called on an instance. - * @method static CarbonPeriod interval($interval) Create instance with given date interval or modify the interval if called on an instance. - * @method static CarbonPeriod each($interval) Create instance with given date interval or modify the interval if called on an instance. - * @method static CarbonPeriod every($interval) Create instance with given date interval or modify the interval if called on an instance. - * @method static CarbonPeriod step($interval) Create instance with given date interval or modify the interval if called on an instance. - * @method static CarbonPeriod stepBy($interval) Create instance with given date interval or modify the interval if called on an instance. - * @method static CarbonPeriod invert() Create instance with inverted date interval or invert the interval if called on an instance. - * @method static CarbonPeriod years($years = 1) Create instance specifying a number of years for date interval or replace the interval by the given a number of years if called on an instance. - * @method static CarbonPeriod year($years = 1) Alias for years(). - * @method static CarbonPeriod months($months = 1) Create instance specifying a number of months for date interval or replace the interval by the given a number of months if called on an instance. - * @method static CarbonPeriod month($months = 1) Alias for months(). - * @method static CarbonPeriod weeks($weeks = 1) Create instance specifying a number of weeks for date interval or replace the interval by the given a number of weeks if called on an instance. - * @method static CarbonPeriod week($weeks = 1) Alias for weeks(). - * @method static CarbonPeriod days($days = 1) Create instance specifying a number of days for date interval or replace the interval by the given a number of days if called on an instance. - * @method static CarbonPeriod dayz($days = 1) Alias for days(). - * @method static CarbonPeriod day($days = 1) Alias for days(). - * @method static CarbonPeriod hours($hours = 1) Create instance specifying a number of hours for date interval or replace the interval by the given a number of hours if called on an instance. - * @method static CarbonPeriod hour($hours = 1) Alias for hours(). - * @method static CarbonPeriod minutes($minutes = 1) Create instance specifying a number of minutes for date interval or replace the interval by the given a number of minutes if called on an instance. - * @method static CarbonPeriod minute($minutes = 1) Alias for minutes(). - * @method static CarbonPeriod seconds($seconds = 1) Create instance specifying a number of seconds for date interval or replace the interval by the given a number of seconds if called on an instance. - * @method static CarbonPeriod second($seconds = 1) Alias for seconds(). + * @method static static start($date, $inclusive = null) Create instance specifying start date or modify the start date if called on an instance. + * @method static static since($date, $inclusive = null) Alias for start(). + * @method static static sinceNow($inclusive = null) Create instance with start date set to now or set the start date to now if called on an instance. + * @method static static end($date = null, $inclusive = null) Create instance specifying end date or modify the end date if called on an instance. + * @method static static until($date = null, $inclusive = null) Alias for end(). + * @method static static untilNow($inclusive = null) Create instance with end date set to now or set the end date to now if called on an instance. + * @method static static dates($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. + * @method static static between($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. + * @method static static recurrences($recurrences = null) Create instance with maximum number of recurrences or modify the number of recurrences if called on an instance. + * @method static static times($recurrences = null) Alias for recurrences(). + * @method static static options($options = null) Create instance with options or modify the options if called on an instance. + * @method static static toggle($options, $state = null) Create instance with options toggled on or off, or toggle options if called on an instance. + * @method static static filter($callback, $name = null) Create instance with filter added to the stack or append a filter if called on an instance. + * @method static static push($callback, $name = null) Alias for filter(). + * @method static static prepend($callback, $name = null) Create instance with filter prepended to the stack or prepend a filter if called on an instance. + * @method static static filters(array $filters = []) Create instance with filters stack or replace the whole filters stack if called on an instance. + * @method static static interval($interval) Create instance with given date interval or modify the interval if called on an instance. + * @method static static each($interval) Create instance with given date interval or modify the interval if called on an instance. + * @method static static every($interval) Create instance with given date interval or modify the interval if called on an instance. + * @method static static step($interval) Create instance with given date interval or modify the interval if called on an instance. + * @method static static stepBy($interval) Create instance with given date interval or modify the interval if called on an instance. + * @method static static invert() Create instance with inverted date interval or invert the interval if called on an instance. + * @method static static years($years = 1) Create instance specifying a number of years for date interval or replace the interval by the given a number of years if called on an instance. + * @method static static year($years = 1) Alias for years(). + * @method static static months($months = 1) Create instance specifying a number of months for date interval or replace the interval by the given a number of months if called on an instance. + * @method static static month($months = 1) Alias for months(). + * @method static static weeks($weeks = 1) Create instance specifying a number of weeks for date interval or replace the interval by the given a number of weeks if called on an instance. + * @method static static week($weeks = 1) Alias for weeks(). + * @method static static days($days = 1) Create instance specifying a number of days for date interval or replace the interval by the given a number of days if called on an instance. + * @method static static dayz($days = 1) Alias for days(). + * @method static static day($days = 1) Alias for days(). + * @method static static hours($hours = 1) Create instance specifying a number of hours for date interval or replace the interval by the given a number of hours if called on an instance. + * @method static static hour($hours = 1) Alias for hours(). + * @method static static minutes($minutes = 1) Create instance specifying a number of minutes for date interval or replace the interval by the given a number of minutes if called on an instance. + * @method static static minute($minutes = 1) Alias for minutes(). + * @method static static seconds($seconds = 1) Create instance specifying a number of seconds for date interval or replace the interval by the given a number of seconds if called on an instance. + * @method static static second($seconds = 1) Alias for seconds(). + * @method static static milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds for date interval or replace the interval by the given a number of milliseconds if called on an instance. + * @method static static millisecond($milliseconds = 1) Alias for milliseconds(). + * @method static static microseconds($microseconds = 1) Create instance specifying a number of microseconds for date interval or replace the interval by the given a number of microseconds if called on an instance. + * @method static static microsecond($microseconds = 1) Alias for microseconds(). * @method $this roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(float $precision = 1) Truncate the current instance year with given precision. @@ -173,6 +180,7 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable Mixin::mixin as baseMixin; } use Options; + use ToStringFormat; /** * Built-in filter for limit by recurrences. @@ -230,6 +238,13 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable */ public const END_MAX_ATTEMPTS = 10000; + /** + * Default date class of iteration items. + * + * @var string + */ + protected const DEFAULT_DATE_CLASS = Carbon::class; + /** * The registered macros. * @@ -251,6 +266,13 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable */ protected $dateInterval; + /** + * True once __construct is finished. + * + * @var bool + */ + protected $constructed = false; + /** * Whether current date interval was set by default. * @@ -377,7 +399,7 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable ); } - $class = \get_called_class(); + $class = static::class; $type = \gettype($period); throw new NotAPeriodException( @@ -482,15 +504,16 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable $interval = null; $start = null; $end = null; + $dateClass = static::DEFAULT_DATE_CLASS; foreach (explode('/', $iso) as $key => $part) { - if ($key === 0 && preg_match('/^R([0-9]*|INF)$/', $part, $match)) { + if ($key === 0 && preg_match('/^R(\d*|INF)$/', $part, $match)) { $parsed = \strlen($match[1]) ? (($match[1] !== 'INF') ? (int) $match[1] : INF) : null; } elseif ($interval === null && $parsed = CarbonInterval::make($part)) { $interval = $part; - } elseif ($start === null && $parsed = Carbon::make($part)) { + } elseif ($start === null && $parsed = $dateClass::make($part)) { $start = $part; - } elseif ($end === null && $parsed = Carbon::make(static::addMissingParts($start ?? '', $part))) { + } elseif ($end === null && $parsed = $dateClass::make(static::addMissingParts($start ?? '', $part))) { $end = $part; } else { throw new InvalidPeriodParameterException("Invalid ISO 8601 specification: $iso."); @@ -503,7 +526,7 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable } /** - * Add missing parts of the target date from the soure date. + * Add missing parts of the target date from the source date. * * @param string $source * @param string $target @@ -512,7 +535,7 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable */ protected static function addMissingParts($source, $target) { - $pattern = '/'.preg_replace('/[0-9]+/', '[0-9]+', preg_quote($target, '/')).'$/'; + $pattern = '/'.preg_replace('/\d+/', '[0-9]+', preg_quote($target, '/')).'$/'; $result = preg_replace($pattern, $target, $source, 1, $count); @@ -621,6 +644,10 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable */ public function __construct(...$arguments) { + if (is_a($this->dateClass, DateTimeImmutable::class, true)) { + $this->options = static::IMMUTABLE; + } + // Parse and assign arguments one by one. First argument may be an ISO 8601 spec, // which will be first parsed into parts and then processed the same way. @@ -648,6 +675,8 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable } } + $optionsSet = false; + foreach ($arguments as $argument) { $parsedDate = null; @@ -655,10 +684,10 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable $this->setTimezone($argument); } elseif ($this->dateInterval === null && ( - \is_string($argument) && preg_match( - '/^(-?\d(\d(?![\/-])|[^\d\/-]([\/-])?)*|P[T0-9].*|(?:\h*\d+(?:\.\d+)?\h*[a-z]+)+)$/i', + (\is_string($argument) && preg_match( + '/^(-?\d(\d(?![\/-])|[^\d\/-]([\/-])?)*|P[T\d].*|(?:\h*\d+(?:\.\d+)?\h*[a-z]+)+)$/i', $argument - ) || + )) || $argument instanceof DateInterval || $argument instanceof Closure ) && @@ -671,15 +700,17 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable $this->setEndDate($parsedDate); } elseif ($this->recurrences === null && $this->endDate === null && is_numeric($argument)) { $this->setRecurrences($argument); - } elseif ($this->options === null && (\is_int($argument) || $argument === null)) { - $this->setOptions($argument); + } elseif (!$optionsSet && (\is_int($argument) || $argument === null)) { + $optionsSet = true; + $this->setOptions(((int) $this->options) | ((int) $argument)); } else { throw new InvalidPeriodParameterException('Invalid constructor parameters.'); } } if ($this->startDate === null) { - $this->setStartDate(Carbon::now()); + $dateClass = $this->dateClass; + $this->setStartDate($dateClass::now()); } if ($this->dateInterval === null) { @@ -691,6 +722,8 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable if ($this->options === null) { $this->setOptions(0); } + + $this->constructed = true; } /** @@ -703,6 +736,17 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable return clone $this; } + /** + * Prepare the instance to be set (self if mutable to be mutated, + * copy if immutable to generate a new instance). + * + * @return static + */ + protected function copyIfImmutable() + { + return $this; + } + /** * Get the getter for a property allowing both `DatePeriod` snakeCase and camelCase names. * @@ -794,7 +838,7 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable * * @param string $dateClass * - * @return $this + * @return static */ public function setDateClass(string $dateClass) { @@ -802,15 +846,16 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable throw new NotACarbonClassException($dateClass); } - $this->dateClass = $dateClass; + $self = $this->copyIfImmutable(); + $self->dateClass = $dateClass; if (is_a($dateClass, Carbon::class, true)) { - $this->toggleOptions(static::IMMUTABLE, false); + $self->options = $self->options & ~static::IMMUTABLE; } elseif (is_a($dateClass, CarbonImmutable::class, true)) { - $this->toggleOptions(static::IMMUTABLE, true); + $self->options = $self->options | static::IMMUTABLE; } - return $this; + return $self; } /** @@ -830,7 +875,7 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable * * @throws InvalidIntervalException * - * @return $this + * @return static */ public function setDateInterval($interval) { @@ -842,25 +887,24 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable throw new InvalidIntervalException('Empty interval is not accepted.'); } - $this->dateInterval = $interval; + $self = $this->copyIfImmutable(); + $self->dateInterval = $interval; - $this->isDefaultInterval = false; + $self->isDefaultInterval = false; - $this->handleChangedParameters(); + $self->handleChangedParameters(); - return $this; + return $self; } /** * Invert the period date interval. * - * @return $this + * @return static */ public function invertDateInterval() { - $interval = $this->dateInterval->invert(); - - return $this->setDateInterval($interval); + return $this->setDateInterval($this->dateInterval->invert()); } /** @@ -869,14 +913,11 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable * @param DateTime|DateTimeInterface|string $start * @param DateTime|DateTimeInterface|string|null $end * - * @return $this + * @return static */ public function setDates($start, $end) { - $this->setStartDate($start); - $this->setEndDate($end); - - return $this; + return $this->setStartDate($start)->setEndDate($end); } /** @@ -886,7 +927,7 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable * * @throws InvalidArgumentException * - * @return $this + * @return static */ public function setOptions($options) { @@ -894,11 +935,12 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable throw new InvalidPeriodParameterException('Invalid options.'); } - $this->options = $options ?: 0; + $self = $this->copyIfImmutable(); + $self->options = $options ?: 0; - $this->handleChangedParameters(); + $self->handleChangedParameters(); - return $this; + return $self; } /** @@ -919,7 +961,7 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable * * @throws \InvalidArgumentException * - * @return $this + * @return static */ public function toggleOptions($options, $state = null) { @@ -939,7 +981,7 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable * * @param bool $state * - * @return $this + * @return static */ public function excludeStartDate($state = true) { @@ -951,7 +993,7 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable * * @param bool $state * - * @return $this + * @return static */ public function excludeEndDate($state = true) { @@ -1095,17 +1137,18 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable * @param callable $callback * @param string $name * - * @return $this + * @return static */ public function addFilter($callback, $name = null) { - $tuple = $this->createFilterTuple(\func_get_args()); + $self = $this->copyIfImmutable(); + $tuple = $self->createFilterTuple(\func_get_args()); - $this->filters[] = $tuple; + $self->filters[] = $tuple; - $this->handleChangedParameters(); + $self->handleChangedParameters(); - return $this; + return $self; } /** @@ -1116,17 +1159,18 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable * @param callable $callback * @param string $name * - * @return $this + * @return static */ public function prependFilter($callback, $name = null) { - $tuple = $this->createFilterTuple(\func_get_args()); + $self = $this->copyIfImmutable(); + $tuple = $self->createFilterTuple(\func_get_args()); - array_unshift($this->filters, $tuple); + array_unshift($self->filters, $tuple); - $this->handleChangedParameters(); + $self->handleChangedParameters(); - return $this; + return $self; } /** @@ -1134,24 +1178,25 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable * * @param callable|string $filter * - * @return $this + * @return static */ public function removeFilter($filter) { + $self = $this->copyIfImmutable(); $key = \is_callable($filter) ? 0 : 1; - $this->filters = array_values(array_filter( + $self->filters = array_values(array_filter( $this->filters, function ($tuple) use ($key, $filter) { return $tuple[$key] !== $filter; } )); - $this->updateInternalState(); + $self->updateInternalState(); - $this->handleChangedParameters(); + $self->handleChangedParameters(); - return $this; + return $self; } /** @@ -1189,39 +1234,41 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable * * @param array $filters * - * @return $this + * @return static */ public function setFilters(array $filters) { - $this->filters = $filters; + $self = $this->copyIfImmutable(); + $self->filters = $filters; - $this->updateInternalState(); + $self->updateInternalState(); - $this->handleChangedParameters(); + $self->handleChangedParameters(); - return $this; + return $self; } /** * Reset filters stack. * - * @return $this + * @return static */ public function resetFilters() { - $this->filters = []; + $self = $this->copyIfImmutable(); + $self->filters = []; - if ($this->endDate !== null) { - $this->filters[] = [static::END_DATE_FILTER, null]; + if ($self->endDate !== null) { + $self->filters[] = [static::END_DATE_FILTER, null]; } - if ($this->recurrences !== null) { - $this->filters[] = [static::RECURRENCES_FILTER, null]; + if ($self->recurrences !== null) { + $self->filters[] = [static::RECURRENCES_FILTER, null]; } - $this->handleChangedParameters(); + $self->handleChangedParameters(); - return $this; + return $self; } /** @@ -1231,11 +1278,11 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable * * @throws InvalidArgumentException * - * @return $this + * @return static */ public function setRecurrences($recurrences) { - if (!is_numeric($recurrences) && $recurrences !== null || $recurrences < 0) { + if ((!is_numeric($recurrences) && $recurrences !== null) || $recurrences < 0) { throw new InvalidPeriodParameterException('Invalid number of recurrences.'); } @@ -1243,15 +1290,17 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable return $this->removeFilter(static::RECURRENCES_FILTER); } - $this->recurrences = $recurrences === INF ? INF : (int) $recurrences; + /** @var self $self */ + $self = $this->copyIfImmutable(); + $self->recurrences = $recurrences === INF ? INF : (int) $recurrences; - if (!$this->hasFilter(static::RECURRENCES_FILTER)) { - return $this->addFilter(static::RECURRENCES_FILTER); + if (!$self->hasFilter(static::RECURRENCES_FILTER)) { + return $self->addFilter(static::RECURRENCES_FILTER); } - $this->handleChangedParameters(); + $self->handleChangedParameters(); - return $this; + return $self; } /** @@ -1262,21 +1311,22 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable * * @throws InvalidPeriodDateException * - * @return $this + * @return static */ public function setStartDate($date, $inclusive = null) { - if (!$date = ([$this->dateClass, 'make'])($date)) { + if (!$this->isInfiniteDate($date) && !($date = ([$this->dateClass, 'make'])($date))) { throw new InvalidPeriodDateException('Invalid start date.'); } - $this->startDate = $date; + $self = $this->copyIfImmutable(); + $self->startDate = $date; if ($inclusive !== null) { - $this->toggleOptions(static::EXCLUDE_START_DATE, !$inclusive); + $self = $self->toggleOptions(static::EXCLUDE_START_DATE, !$inclusive); } - return $this; + return $self; } /** @@ -1287,11 +1337,11 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable * * @throws \InvalidArgumentException * - * @return $this + * @return static */ public function setEndDate($date, $inclusive = null) { - if ($date !== null && !$date = ([$this->dateClass, 'make'])($date)) { + if ($date !== null && !$this->isInfiniteDate($date) && !$date = ([$this->dateClass, 'make'])($date)) { throw new InvalidPeriodDateException('Invalid end date.'); } @@ -1299,19 +1349,20 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable return $this->removeFilter(static::END_DATE_FILTER); } - $this->endDate = $date; + $self = $this->copyIfImmutable(); + $self->endDate = $date; if ($inclusive !== null) { - $this->toggleOptions(static::EXCLUDE_END_DATE, !$inclusive); + $self = $self->toggleOptions(static::EXCLUDE_END_DATE, !$inclusive); } - if (!$this->hasFilter(static::END_DATE_FILTER)) { - return $this->addFilter(static::END_DATE_FILTER); + if (!$self->hasFilter(static::END_DATE_FILTER)) { + return $self->addFilter(static::END_DATE_FILTER); } - $this->handleChangedParameters(); + $self->handleChangedParameters(); - return $this; + return $self; } /** @@ -1457,13 +1508,21 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable */ public function toString() { + $format = $this->localToStringFormat ?? static::$toStringFormat; + + if ($format instanceof Closure) { + return $format($this); + } + $translator = ([$this->dateClass, 'getTranslator'])(); $parts = []; - $format = !$this->startDate->isStartOfDay() || $this->endDate && !$this->endDate->isStartOfDay() - ? 'Y-m-d H:i:s' - : 'Y-m-d'; + $format = $format ?? ( + !$this->startDate->isStartOfDay() || ($this->endDate && !$this->endDate->isStartOfDay()) + ? 'Y-m-d H:i:s' + : 'Y-m-d' + ); if ($this->recurrences !== null) { $parts[] = $this->translate('period_recurrences', [], $this->recurrences, $translator); @@ -1506,9 +1565,9 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable if (!method_exists($className, 'instance')) { if (is_a($className, DatePeriod::class, true)) { return new $className( - $this->getStartDate(), + $this->rawDate($this->getStartDate()), $this->getDateInterval(), - $this->getEndDate() ? $this->getIncludedEndDate() : $this->getRecurrences(), + $this->getEndDate() ? $this->rawDate($this->getIncludedEndDate()) : $this->getRecurrences(), $this->isStartExcluded() ? DatePeriod::EXCLUDE_START_DATE : 0 ); } @@ -1534,6 +1593,39 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable return $this->cast(DatePeriod::class); } + /** + * Return `true` if the period has no custom filter and is guaranteed to be endless. + * + * Note that we can't check if a period is endless as soon as it has custom filters + * because filters can emit `CarbonPeriod::END_ITERATION` to stop the iteration in + * a way we can't predict without actually iterating the period. + */ + public function isUnfilteredAndEndLess(): bool + { + foreach ($this->filters as $filter) { + switch ($filter) { + case [static::RECURRENCES_FILTER, null]: + if ($this->recurrences !== null && is_finite($this->recurrences)) { + return false; + } + + break; + + case [static::END_DATE_FILTER, null]: + if ($this->endDate !== null && !$this->endDate->isEndOfTime()) { + return false; + } + + break; + + default: + return false; + } + } + + return true; + } + /** * Convert the date period into an array without changing current iteration state. * @@ -1541,6 +1633,10 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable */ public function toArray() { + if ($this->isUnfilteredAndEndLess()) { + throw new EndLessPeriodException("Endless period can't be converted to array nor counted."); + } + $state = [ $this->key, $this->current ? $this->current->avoidMutation() : null, @@ -1572,6 +1668,16 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable */ public function first() { + if ($this->isUnfilteredAndEndLess()) { + foreach ($this as $date) { + $this->rewind(); + + return $date; + } + + return null; + } + return ($this->toArray() ?: [])[0] ?? null; } @@ -1626,54 +1732,80 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable return $roundedValue; } - $first = \count($parameters) >= 1 ? $parameters[0] : null; - $second = \count($parameters) >= 2 ? $parameters[1] : null; - switch ($method) { case 'start': case 'since': - return $this->setStartDate($first, $second); + self::setDefaultParameters($parameters, [ + [0, 'date', null], + ]); + + return $this->setStartDate(...$parameters); case 'sinceNow': - return $this->setStartDate(new Carbon(), $first); + return $this->setStartDate(new Carbon(), ...$parameters); case 'end': case 'until': - return $this->setEndDate($first, $second); + self::setDefaultParameters($parameters, [ + [0, 'date', null], + ]); + + return $this->setEndDate(...$parameters); case 'untilNow': - return $this->setEndDate(new Carbon(), $first); + return $this->setEndDate(new Carbon(), ...$parameters); case 'dates': case 'between': - return $this->setDates($first, $second); + self::setDefaultParameters($parameters, [ + [0, 'start', null], + [1, 'end', null], + ]); + + return $this->setDates(...$parameters); case 'recurrences': case 'times': - return $this->setRecurrences($first); + self::setDefaultParameters($parameters, [ + [0, 'recurrences', null], + ]); + + return $this->setRecurrences(...$parameters); case 'options': - return $this->setOptions($first); + self::setDefaultParameters($parameters, [ + [0, 'options', null], + ]); + + return $this->setOptions(...$parameters); case 'toggle': - return $this->toggleOptions($first, $second); + self::setDefaultParameters($parameters, [ + [0, 'options', null], + ]); + + return $this->toggleOptions(...$parameters); case 'filter': case 'push': - return $this->addFilter($first, $second); + return $this->addFilter(...$parameters); case 'prepend': - return $this->prependFilter($first, $second); + return $this->prependFilter(...$parameters); case 'filters': - return $this->setFilters($first ?: []); + self::setDefaultParameters($parameters, [ + [0, 'filters', []], + ]); + + return $this->setFilters(...$parameters); case 'interval': case 'each': case 'every': case 'step': case 'stepBy': - return $this->setDateInterval($first); + return $this->setDateInterval(...$parameters); case 'invert': return $this->invertDateInterval(); @@ -1693,15 +1825,19 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable case 'minute': case 'seconds': case 'second': + case 'milliseconds': + case 'millisecond': + case 'microseconds': + case 'microsecond': return $this->setDateInterval(( // Override default P1D when instantiating via fluent setters. [$this->isDefaultInterval ? new CarbonInterval('PT0S') : $this->dateInterval, $method] - )( - \count($parameters) === 0 ? 1 : $first - )); + )(...$parameters)); } - if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { + $dateClass = $this->dateClass; + + if ($this->localStrictModeEnabled ?? $dateClass::isStrictModeEnabled()) { throw new UnknownMethodException($method); } @@ -1717,18 +1853,19 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable */ public function setTimezone($timezone) { - $this->tzName = $timezone; - $this->timezone = $timezone; + $self = $this->copyIfImmutable(); + $self->tzName = $timezone; + $self->timezone = $timezone; - if ($this->startDate) { - $this->setStartDate($this->startDate->setTimezone($timezone)); + if ($self->startDate) { + $self = $self->setStartDate($self->startDate->setTimezone($timezone)); } - if ($this->endDate) { - $this->setEndDate($this->endDate->setTimezone($timezone)); + if ($self->endDate) { + $self = $self->setEndDate($self->endDate->setTimezone($timezone)); } - return $this; + return $self; } /** @@ -1740,18 +1877,19 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable */ public function shiftTimezone($timezone) { - $this->tzName = $timezone; - $this->timezone = $timezone; + $self = $this->copyIfImmutable(); + $self->tzName = $timezone; + $self->timezone = $timezone; - if ($this->startDate) { - $this->setStartDate($this->startDate->shiftTimezone($timezone)); + if ($self->startDate) { + $self = $self->setStartDate($self->startDate->shiftTimezone($timezone)); } - if ($this->endDate) { - $this->setEndDate($this->endDate->shiftTimezone($timezone)); + if ($self->endDate) { + $self = $self->setEndDate($self->endDate->shiftTimezone($timezone)); } - return $this; + return $self; } /** @@ -1896,7 +2034,7 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable /** * Determines if the instance is equal to another. - * Warning: if options differ, instances wil never be equal. + * Warning: if options differ, instances will never be equal. * * @param mixed $period * @@ -1911,7 +2049,7 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable /** * Determines if the instance is equal to another. - * Warning: if options differ, instances wil never be equal. + * Warning: if options differ, instances will never be equal. * * @param mixed $period * @@ -1934,7 +2072,7 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable /** * Determines if the instance is not equal to another. - * Warning: if options differ, instances wil never be equal. + * Warning: if options differ, instances will never be equal. * * @param mixed $period * @@ -1949,7 +2087,7 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable /** * Determines if the instance is not equal to another. - * Warning: if options differ, instances wil never be equal. + * Warning: if options differ, instances will never be equal. * * @param mixed $period * @@ -2130,19 +2268,18 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable * @param float|int|string|\DateInterval|null $precision * @param string $function * - * @return $this + * @return static */ public function roundUnit($unit, $precision = 1, $function = 'round') { - $this->setStartDate($this->getStartDate()->roundUnit($unit, $precision, $function)); + $self = $this->copyIfImmutable(); + $self = $self->setStartDate($self->getStartDate()->roundUnit($unit, $precision, $function)); - if ($this->endDate) { - $this->setEndDate($this->getEndDate()->roundUnit($unit, $precision, $function)); + if ($self->endDate) { + $self = $self->setEndDate($self->getEndDate()->roundUnit($unit, $precision, $function)); } - $this->setDateInterval($this->getDateInterval()->roundUnit($unit, $precision, $function)); - - return $this; + return $self->setDateInterval($self->getDateInterval()->roundUnit($unit, $precision, $function)); } /** @@ -2151,7 +2288,7 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable * @param string $unit * @param float|int|string|\DateInterval|null $precision * - * @return $this + * @return static */ public function floorUnit($unit, $precision = 1) { @@ -2164,7 +2301,7 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable * @param string $unit * @param float|int|string|\DateInterval|null $precision * - * @return $this + * @return static */ public function ceilUnit($unit, $precision = 1) { @@ -2177,7 +2314,7 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable * @param float|int|string|\DateInterval|null $precision * @param string $function * - * @return $this + * @return static */ public function round($precision = null, $function = 'round') { @@ -2192,7 +2329,7 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable * * @param float|int|string|\DateInterval|null $precision * - * @return $this + * @return static */ public function floor($precision = null) { @@ -2204,7 +2341,7 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable * * @param float|int|string|\DateInterval|null $precision * - * @return $this + * @return static */ public function ceil($precision = null) { @@ -2393,9 +2530,9 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable protected function handleChangedParameters() { if (($this->getOptions() & static::IMMUTABLE) && $this->dateClass === Carbon::class) { - $this->setDateClass(CarbonImmutable::class); + $this->dateClass = CarbonImmutable::class; } elseif (!($this->getOptions() & static::IMMUTABLE) && $this->dateClass === CarbonImmutable::class) { - $this->setDateClass(Carbon::class); + $this->dateClass = Carbon::class; } $this->validationResult = null; @@ -2555,14 +2692,51 @@ class CarbonPeriod implements Iterator, Countable, JsonSerializable if (\is_string($value)) { $value = trim($value); - if (!preg_match('/^P[0-9T]/', $value) && - !preg_match('/^R[0-9]/', $value) && - preg_match('/[a-z0-9]/i', $value) + if (!preg_match('/^P[\dT]/', $value) && + !preg_match('/^R\d/', $value) && + preg_match('/[a-z\d]/i', $value) ) { - return Carbon::parse($value, $this->tzName); + $dateClass = $this->dateClass; + + return $dateClass::parse($value, $this->tzName); } } return null; } + + private function isInfiniteDate($date): bool + { + return $date instanceof CarbonInterface && ($date->isEndOfTime() || $date->isStartOfTime()); + } + + private function rawDate($date): ?DateTimeInterface + { + if ($date === false || $date === null) { + return null; + } + + if ($date instanceof CarbonInterface) { + return $date->isMutable() + ? $date->toDateTime() + : $date->toDateTimeImmutable(); + } + + if (\in_array(\get_class($date), [DateTime::class, DateTimeImmutable::class], true)) { + return $date; + } + + $class = $date instanceof DateTime ? DateTime::class : DateTimeImmutable::class; + + return new $class($date->format('Y-m-d H:i:s.u'), $date->getTimezone()); + } + + private static function setDefaultParameters(array &$parameters, array $defaults): void + { + foreach ($defaults as [$index, $name, $value]) { + if (!\array_key_exists($index, $parameters) && !\array_key_exists($name, $parameters)) { + $parameters[$index] = $value; + } + } + } } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/CarbonPeriodImmutable.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/CarbonPeriodImmutable.php new file mode 100644 index 000000000..f0d0ee281 --- /dev/null +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/CarbonPeriodImmutable.php @@ -0,0 +1,40 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon; + +class CarbonPeriodImmutable extends CarbonPeriod +{ + /** + * Default date class of iteration items. + * + * @var string + */ + protected const DEFAULT_DATE_CLASS = CarbonImmutable::class; + + /** + * Date class of iteration items. + * + * @var string + */ + protected $dateClass = CarbonImmutable::class; + + /** + * Prepare the instance to be set (self if mutable to be mutated, + * copy if immutable to generate a new instance). + * + * @return static + */ + protected function copyIfImmutable() + { + return $this->constructed ? clone $this : $this; + } +} diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/CarbonTimeZone.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/CarbonTimeZone.php index b4d16ba97..c81899f1e 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/CarbonTimeZone.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/CarbonTimeZone.php @@ -30,7 +30,7 @@ class CarbonTimeZone extends DateTimeZone throw new InvalidTimeZoneException('Absolute timezone offset cannot be greater than 100.'); } - return ($timezone >= 0 ? '+' : '').$timezone.':00'; + return ($timezone >= 0 ? '+' : '').ltrim($timezone, '+').':00'; } protected static function getDateTimeZoneNameFromMixed($timezone) @@ -101,15 +101,15 @@ class CarbonTimeZone extends DateTimeZone $tz = static::getDateTimeZoneFromName($object); } - if ($tz === false) { - if (Carbon::isStrictModeEnabled()) { - throw new InvalidTimeZoneException('Unknown or bad timezone ('.($objectDump ?: $object).')'); - } - - return false; + if ($tz !== false) { + return new static($tz->getName()); } - return new static($tz->getName()); + if (Carbon::isStrictModeEnabled()) { + throw new InvalidTimeZoneException('Unknown or bad timezone ('.($objectDump ?: $object).')'); + } + + return false; } /** @@ -231,15 +231,15 @@ class CarbonTimeZone extends DateTimeZone { $tz = $this->toRegionName($date); - if ($tz === false) { - if (Carbon::isStrictModeEnabled()) { - throw new InvalidTimeZoneException('Unknown timezone for offset '.$this->getOffset($date ?: Carbon::now($this)).' seconds.'); - } - - return false; + if ($tz !== false) { + return new static($tz); } - return new static($tz); + if (Carbon::isStrictModeEnabled()) { + throw new InvalidTimeZoneException('Unknown timezone for offset '.$this->getOffset($date ?: Carbon::now($this)).' seconds.'); + } + + return false; } /** @@ -252,6 +252,18 @@ class CarbonTimeZone extends DateTimeZone return $this->getName(); } + /** + * Return the type number: + * + * Type 1; A UTC offset, such as -0300 + * Type 2; A timezone abbreviation, such as GMT + * Type 3: A timezone identifier, such as Europe/London + */ + public function getType(): int + { + return preg_match('/"timezone_type";i:(\d)/', serialize($this), $match) ? (int) $match[1] : 3; + } + /** * Create a CarbonTimeZone from mixed input. * diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Doctrine/CarbonDoctrineType.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Doctrine/CarbonDoctrineType.php deleted file mode 100644 index ccc457fcd..000000000 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Doctrine/CarbonDoctrineType.php +++ /dev/null @@ -1,23 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Carbon\Doctrine; - -use Doctrine\DBAL\Platforms\AbstractPlatform; - -interface CarbonDoctrineType -{ - public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform); - - public function convertToPHPValue($value, AbstractPlatform $platform); - - public function convertToDatabaseValue($value, AbstractPlatform $platform); -} diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Doctrine/CarbonImmutableType.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Doctrine/CarbonImmutableType.php deleted file mode 100644 index bf476a77e..000000000 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Doctrine/CarbonImmutableType.php +++ /dev/null @@ -1,37 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Carbon\Doctrine; - -use Doctrine\DBAL\Platforms\AbstractPlatform; - -class CarbonImmutableType extends DateTimeImmutableType implements CarbonDoctrineType -{ - /** - * {@inheritdoc} - * - * @return string - */ - public function getName() - { - return 'carbon_immutable'; - } - - /** - * {@inheritdoc} - * - * @return bool - */ - public function requiresSQLCommentHint(AbstractPlatform $platform) - { - return true; - } -} diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Doctrine/CarbonType.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Doctrine/CarbonType.php deleted file mode 100644 index 9289d84d3..000000000 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Doctrine/CarbonType.php +++ /dev/null @@ -1,37 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Carbon\Doctrine; - -use Doctrine\DBAL\Platforms\AbstractPlatform; - -class CarbonType extends DateTimeType implements CarbonDoctrineType -{ - /** - * {@inheritdoc} - * - * @return string - */ - public function getName() - { - return 'carbon'; - } - - /** - * {@inheritdoc} - * - * @return bool - */ - public function requiresSQLCommentHint(AbstractPlatform $platform) - { - return true; - } -} diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Doctrine/DateTimeType.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Doctrine/DateTimeType.php deleted file mode 100644 index 29b0bb955..000000000 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Doctrine/DateTimeType.php +++ /dev/null @@ -1,16 +0,0 @@ - */ - use CarbonTypeConverter; -} diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/BadComparisonUnitException.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/BadComparisonUnitException.php index b3a087190..3ca8837d1 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/BadComparisonUnitException.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/BadComparisonUnitException.php @@ -11,19 +11,38 @@ namespace Carbon\Exceptions; -use Exception; +use Throwable; class BadComparisonUnitException extends UnitException { + /** + * The unit. + * + * @var string + */ + protected $unit; + /** * Constructor. * * @param string $unit * @param int $code - * @param Exception|null $previous + * @param Throwable|null $previous */ - public function __construct($unit, $code = 0, Exception $previous = null) + public function __construct($unit, $code = 0, Throwable $previous = null) { + $this->unit = $unit; + parent::__construct("Bad comparison unit: '$unit'", $code, $previous); } + + /** + * Get the unit. + * + * @return string + */ + public function getUnit(): string + { + return $this->unit; + } } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/BadFluentConstructorException.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/BadFluentConstructorException.php index d5cd5564c..2e222e54e 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/BadFluentConstructorException.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/BadFluentConstructorException.php @@ -12,19 +12,38 @@ namespace Carbon\Exceptions; use BadMethodCallException as BaseBadMethodCallException; -use Exception; +use Throwable; class BadFluentConstructorException extends BaseBadMethodCallException implements BadMethodCallException { + /** + * The method. + * + * @var string + */ + protected $method; + /** * Constructor. * * @param string $method * @param int $code - * @param Exception|null $previous + * @param Throwable|null $previous */ - public function __construct($method, $code = 0, Exception $previous = null) + public function __construct($method, $code = 0, Throwable $previous = null) { + $this->method = $method; + parent::__construct(sprintf("Unknown fluent constructor '%s'.", $method), $code, $previous); } + + /** + * Get the method. + * + * @return string + */ + public function getMethod(): string + { + return $this->method; + } } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/BadFluentSetterException.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/BadFluentSetterException.php index 1d7ec542a..4ceaa2ef0 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/BadFluentSetterException.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/BadFluentSetterException.php @@ -12,19 +12,38 @@ namespace Carbon\Exceptions; use BadMethodCallException as BaseBadMethodCallException; -use Exception; +use Throwable; class BadFluentSetterException extends BaseBadMethodCallException implements BadMethodCallException { + /** + * The setter. + * + * @var string + */ + protected $setter; + /** * Constructor. * - * @param string $method + * @param string $setter * @param int $code - * @param Exception|null $previous + * @param Throwable|null $previous */ - public function __construct($method, $code = 0, Exception $previous = null) + public function __construct($setter, $code = 0, Throwable $previous = null) { - parent::__construct(sprintf("Unknown fluent setter '%s'", $method), $code, $previous); + $this->setter = $setter; + + parent::__construct(sprintf("Unknown fluent setter '%s'", $setter), $code, $previous); + } + + /** + * Get the setter. + * + * @return string + */ + public function getSetter(): string + { + return $this->setter; } } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/BadMethodCallException.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/BadMethodCallException.php index 73c2dd86f..108206d3e 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/BadMethodCallException.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/BadMethodCallException.php @@ -13,4 +13,5 @@ namespace Carbon\Exceptions; interface BadMethodCallException extends Exception { + // } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/EndLessPeriodException.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/EndLessPeriodException.php new file mode 100644 index 000000000..e10492693 --- /dev/null +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/EndLessPeriodException.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Exceptions; + +use RuntimeException as BaseRuntimeException; + +final class EndLessPeriodException extends BaseRuntimeException implements RuntimeException +{ + // +} diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/Exception.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/Exception.php index 3bbbd77d5..8ad747e75 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/Exception.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/Exception.php @@ -13,4 +13,5 @@ namespace Carbon\Exceptions; interface Exception { + // } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/ImmutableException.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/ImmutableException.php index a48d4f936..db334c6c9 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/ImmutableException.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/ImmutableException.php @@ -11,20 +11,38 @@ namespace Carbon\Exceptions; -use Exception; use RuntimeException as BaseRuntimeException; +use Throwable; class ImmutableException extends BaseRuntimeException implements RuntimeException { + /** + * The value. + * + * @var string + */ + protected $value; + /** * Constructor. * * @param string $value the immutable type/value * @param int $code - * @param Exception|null $previous + * @param Throwable|null $previous */ - public function __construct($value, $code = 0, Exception $previous = null) + public function __construct($value, $code = 0, Throwable $previous = null) { + $this->value = $value; parent::__construct("$value is immutable.", $code, $previous); } + + /** + * Get the value. + * + * @return string + */ + public function getValue(): string + { + return $this->value; + } } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidArgumentException.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidArgumentException.php index 9739f4d18..5b013cd50 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidArgumentException.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidArgumentException.php @@ -13,4 +13,5 @@ namespace Carbon\Exceptions; interface InvalidArgumentException extends Exception { + // } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidCastException.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidCastException.php index d2f370199..a421401f6 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidCastException.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidCastException.php @@ -11,20 +11,9 @@ namespace Carbon\Exceptions; -use Exception; use InvalidArgumentException as BaseInvalidArgumentException; class InvalidCastException extends BaseInvalidArgumentException implements InvalidArgumentException { - /** - * Constructor. - * - * @param string $message - * @param int $code - * @param Exception|null $previous - */ - public function __construct($message, $code = 0, Exception $previous = null) - { - parent::__construct($message, $code, $previous); - } + // } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidDateException.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidDateException.php index 99bb91c05..c9ecb6b06 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidDateException.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidDateException.php @@ -11,8 +11,8 @@ namespace Carbon\Exceptions; -use Exception; use InvalidArgumentException as BaseInvalidArgumentException; +use Throwable; class InvalidDateException extends BaseInvalidArgumentException implements InvalidArgumentException { @@ -36,9 +36,9 @@ class InvalidDateException extends BaseInvalidArgumentException implements Inval * @param string $field * @param mixed $value * @param int $code - * @param Exception|null $previous + * @param Throwable|null $previous */ - public function __construct($field, $value, $code = 0, Exception $previous = null) + public function __construct($field, $value, $code = 0, Throwable $previous = null) { $this->field = $field; $this->value = $value; diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidFormatException.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidFormatException.php index 3341b49d0..92d55fe35 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidFormatException.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidFormatException.php @@ -11,20 +11,9 @@ namespace Carbon\Exceptions; -use Exception; use InvalidArgumentException as BaseInvalidArgumentException; class InvalidFormatException extends BaseInvalidArgumentException implements InvalidArgumentException { - /** - * Constructor. - * - * @param string $message - * @param int $code - * @param Exception|null $previous - */ - public function __construct($message, $code = 0, Exception $previous = null) - { - parent::__construct($message, $code, $previous); - } + // } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidIntervalException.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidIntervalException.php index 5f9f142ee..69cf4128a 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidIntervalException.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidIntervalException.php @@ -11,20 +11,9 @@ namespace Carbon\Exceptions; -use Exception; use InvalidArgumentException as BaseInvalidArgumentException; class InvalidIntervalException extends BaseInvalidArgumentException implements InvalidArgumentException { - /** - * Constructor. - * - * @param string $message - * @param int $code - * @param Exception|null $previous - */ - public function __construct($message, $code = 0, Exception $previous = null) - { - parent::__construct($message, $code, $previous); - } + // } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidPeriodDateException.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidPeriodDateException.php index a37e3f5ec..9bd84a96d 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidPeriodDateException.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidPeriodDateException.php @@ -11,20 +11,9 @@ namespace Carbon\Exceptions; -use Exception; use InvalidArgumentException as BaseInvalidArgumentException; class InvalidPeriodDateException extends BaseInvalidArgumentException implements InvalidArgumentException { - /** - * Constructor. - * - * @param string $message - * @param int $code - * @param Exception|null $previous - */ - public function __construct($message, $code = 0, Exception $previous = null) - { - parent::__construct($message, $code, $previous); - } + // } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidPeriodParameterException.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidPeriodParameterException.php index ede47712b..cf2c90240 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidPeriodParameterException.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidPeriodParameterException.php @@ -11,20 +11,9 @@ namespace Carbon\Exceptions; -use Exception; use InvalidArgumentException as BaseInvalidArgumentException; class InvalidPeriodParameterException extends BaseInvalidArgumentException implements InvalidArgumentException { - /** - * Constructor. - * - * @param string $message - * @param int $code - * @param Exception|null $previous - */ - public function __construct($message, $code = 0, Exception $previous = null) - { - parent::__construct($message, $code, $previous); - } + // } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidTimeZoneException.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidTimeZoneException.php index 892e16e81..f72595583 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidTimeZoneException.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidTimeZoneException.php @@ -11,20 +11,9 @@ namespace Carbon\Exceptions; -use Exception; use InvalidArgumentException as BaseInvalidArgumentException; class InvalidTimeZoneException extends BaseInvalidArgumentException implements InvalidArgumentException { - /** - * Constructor. - * - * @param string $message - * @param int $code - * @param Exception|null $previous - */ - public function __construct($message, $code = 0, Exception $previous = null) - { - parent::__construct($message, $code, $previous); - } + // } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidTypeException.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidTypeException.php index 3fbe3fc47..2c8ec9ba0 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidTypeException.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/InvalidTypeException.php @@ -11,20 +11,9 @@ namespace Carbon\Exceptions; -use Exception; use InvalidArgumentException as BaseInvalidArgumentException; class InvalidTypeException extends BaseInvalidArgumentException implements InvalidArgumentException { - /** - * Constructor. - * - * @param string $message - * @param int $code - * @param Exception|null $previous - */ - public function __construct($message, $code = 0, Exception $previous = null) - { - parent::__construct($message, $code, $previous); - } + // } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/NotACarbonClassException.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/NotACarbonClassException.php index 2b4c48e32..7a87632c4 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/NotACarbonClassException.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/NotACarbonClassException.php @@ -12,24 +12,39 @@ namespace Carbon\Exceptions; use Carbon\CarbonInterface; -use Exception; use InvalidArgumentException as BaseInvalidArgumentException; +use Throwable; class NotACarbonClassException extends BaseInvalidArgumentException implements InvalidArgumentException { + /** + * The className. + * + * @var string + */ + protected $className; + /** * Constructor. * * @param string $className * @param int $code - * @param Exception|null $previous + * @param Throwable|null $previous */ - public function __construct($className, $code = 0, Exception $previous = null) + public function __construct($className, $code = 0, Throwable $previous = null) { - parent::__construct(sprintf( - 'Given class does not implement %s: %s', - CarbonInterface::class, - $className - ), $code, $previous); + $this->className = $className; + + parent::__construct(sprintf('Given class does not implement %s: %s', CarbonInterface::class, $className), $code, $previous); + } + + /** + * Get the className. + * + * @return string + */ + public function getClassName(): string + { + return $this->className; } } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/NotAPeriodException.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/NotAPeriodException.php index 41bb62902..4edd7a484 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/NotAPeriodException.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/NotAPeriodException.php @@ -11,20 +11,9 @@ namespace Carbon\Exceptions; -use Exception; use InvalidArgumentException as BaseInvalidArgumentException; class NotAPeriodException extends BaseInvalidArgumentException implements InvalidArgumentException { - /** - * Constructor. - * - * @param string $message - * @param int $code - * @param Exception|null $previous - */ - public function __construct($message, $code = 0, Exception $previous = null) - { - parent::__construct($message, $code, $previous); - } + // } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/NotLocaleAwareException.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/NotLocaleAwareException.php index adbc36cd5..f2c546843 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/NotLocaleAwareException.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/NotLocaleAwareException.php @@ -11,8 +11,8 @@ namespace Carbon\Exceptions; -use Exception; use InvalidArgumentException as BaseInvalidArgumentException; +use Throwable; class NotLocaleAwareException extends BaseInvalidArgumentException implements InvalidArgumentException { @@ -21,9 +21,9 @@ class NotLocaleAwareException extends BaseInvalidArgumentException implements In * * @param mixed $object * @param int $code - * @param Exception|null $previous + * @param Throwable|null $previous */ - public function __construct($object, $code = 0, Exception $previous = null) + public function __construct($object, $code = 0, Throwable $previous = null) { $dump = \is_object($object) ? \get_class($object) : \gettype($object); diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/OutOfRangeException.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/OutOfRangeException.php index 54822d954..2c586d0b7 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/OutOfRangeException.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/OutOfRangeException.php @@ -11,8 +11,8 @@ namespace Carbon\Exceptions; -use Exception; use InvalidArgumentException as BaseInvalidArgumentException; +use Throwable; // This will extends OutOfRangeException instead of InvalidArgumentException since 3.0.0 // use OutOfRangeException as BaseOutOfRangeException; @@ -55,9 +55,9 @@ class OutOfRangeException extends BaseInvalidArgumentException implements Invali * @param mixed $max * @param mixed $value * @param int $code - * @param Exception|null $previous + * @param Throwable|null $previous */ - public function __construct($unit, $min, $max, $value, $code = 0, Exception $previous = null) + public function __construct($unit, $min, $max, $value, $code = 0, Throwable $previous = null) { $this->unit = $unit; $this->min = $min; diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/ParseErrorException.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/ParseErrorException.php index 0314c5d88..5416fd149 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/ParseErrorException.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/ParseErrorException.php @@ -11,23 +11,78 @@ namespace Carbon\Exceptions; -use Exception; use InvalidArgumentException as BaseInvalidArgumentException; +use Throwable; class ParseErrorException extends BaseInvalidArgumentException implements InvalidArgumentException { + /** + * The expected. + * + * @var string + */ + protected $expected; + + /** + * The actual. + * + * @var string + */ + protected $actual; + + /** + * The help message. + * + * @var string + */ + protected $help; + /** * Constructor. * * @param string $expected * @param string $actual * @param int $code - * @param Exception|null $previous + * @param Throwable|null $previous */ - public function __construct($expected, $actual, $help = '', $code = 0, Exception $previous = null) + public function __construct($expected, $actual, $help = '', $code = 0, Throwable $previous = null) { + $this->expected = $expected; + $this->actual = $actual; + $this->help = $help; + $actual = $actual === '' ? 'data is missing' : "get '$actual'"; parent::__construct(trim("Format expected $expected but $actual\n$help"), $code, $previous); } + + /** + * Get the expected. + * + * @return string + */ + public function getExpected(): string + { + return $this->expected; + } + + /** + * Get the actual. + * + * @return string + */ + public function getActual(): string + { + return $this->actual; + } + + /** + * Get the help message. + * + * @return string + */ + public function getHelp(): string + { + return $this->help; + } } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/RuntimeException.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/RuntimeException.php index 24bf5a68b..ad196f79d 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/RuntimeException.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/RuntimeException.php @@ -13,4 +13,5 @@ namespace Carbon\Exceptions; interface RuntimeException extends Exception { + // } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/UnitException.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/UnitException.php index 8bd8653e1..ee99953b4 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/UnitException.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/UnitException.php @@ -11,20 +11,9 @@ namespace Carbon\Exceptions; -use Exception; use InvalidArgumentException as BaseInvalidArgumentException; class UnitException extends BaseInvalidArgumentException implements InvalidArgumentException { - /** - * Constructor. - * - * @param string $message - * @param int $code - * @param Exception|null $previous - */ - public function __construct($message, $code = 0, Exception $previous = null) - { - parent::__construct($message, $code, $previous); - } + // } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/UnitNotConfiguredException.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/UnitNotConfiguredException.php index 39ee12c5b..0e7230563 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/UnitNotConfiguredException.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/UnitNotConfiguredException.php @@ -11,19 +11,38 @@ namespace Carbon\Exceptions; -use Exception; +use Throwable; class UnitNotConfiguredException extends UnitException { + /** + * The unit. + * + * @var string + */ + protected $unit; + /** * Constructor. * * @param string $unit * @param int $code - * @param Exception|null $previous + * @param Throwable|null $previous */ - public function __construct($unit, $code = 0, Exception $previous = null) + public function __construct($unit, $code = 0, Throwable $previous = null) { + $this->unit = $unit; + parent::__construct("Unit $unit have no configuration to get total from other units.", $code, $previous); } + + /** + * Get the unit. + * + * @return string + */ + public function getUnit(): string + { + return $this->unit; + } } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/UnknownGetterException.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/UnknownGetterException.php index 6c8c01b6c..5c504975a 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/UnknownGetterException.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/UnknownGetterException.php @@ -11,20 +11,39 @@ namespace Carbon\Exceptions; -use Exception; use InvalidArgumentException as BaseInvalidArgumentException; +use Throwable; class UnknownGetterException extends BaseInvalidArgumentException implements InvalidArgumentException { + /** + * The getter. + * + * @var string + */ + protected $getter; + /** * Constructor. * - * @param string $name getter name + * @param string $getter getter name * @param int $code - * @param Exception|null $previous + * @param Throwable|null $previous */ - public function __construct($name, $code = 0, Exception $previous = null) + public function __construct($getter, $code = 0, Throwable $previous = null) { - parent::__construct("Unknown getter '$name'", $code, $previous); + $this->getter = $getter; + + parent::__construct("Unknown getter '$getter'", $code, $previous); + } + + /** + * Get the getter. + * + * @return string + */ + public function getGetter(): string + { + return $this->getter; } } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/UnknownMethodException.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/UnknownMethodException.php index 901db986a..75273a706 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/UnknownMethodException.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/UnknownMethodException.php @@ -12,19 +12,38 @@ namespace Carbon\Exceptions; use BadMethodCallException as BaseBadMethodCallException; -use Exception; +use Throwable; class UnknownMethodException extends BaseBadMethodCallException implements BadMethodCallException { + /** + * The method. + * + * @var string + */ + protected $method; + /** * Constructor. * * @param string $method * @param int $code - * @param Exception|null $previous + * @param Throwable|null $previous */ - public function __construct($method, $code = 0, Exception $previous = null) + public function __construct($method, $code = 0, Throwable $previous = null) { + $this->method = $method; + parent::__construct("Method $method does not exist.", $code, $previous); } + + /** + * Get the method. + * + * @return string + */ + public function getMethod(): string + { + return $this->method; + } } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/UnknownSetterException.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/UnknownSetterException.php index c9e9c9ff2..a795f5d72 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/UnknownSetterException.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/UnknownSetterException.php @@ -11,20 +11,39 @@ namespace Carbon\Exceptions; -use Exception; use InvalidArgumentException as BaseInvalidArgumentException; +use Throwable; class UnknownSetterException extends BaseInvalidArgumentException implements BadMethodCallException { + /** + * The setter. + * + * @var string + */ + protected $setter; + /** * Constructor. * - * @param string $name setter name + * @param string $setter setter name * @param int $code - * @param Exception|null $previous + * @param Throwable|null $previous */ - public function __construct($name, $code = 0, Exception $previous = null) + public function __construct($setter, $code = 0, Throwable $previous = null) { - parent::__construct("Unknown setter '$name'", $code, $previous); + $this->setter = $setter; + + parent::__construct("Unknown setter '$setter'", $code, $previous); + } + + /** + * Get the setter. + * + * @return string + */ + public function getSetter(): string + { + return $this->setter; } } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/UnknownUnitException.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/UnknownUnitException.php index d965c82ae..ecd7f7a59 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/UnknownUnitException.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/UnknownUnitException.php @@ -11,19 +11,38 @@ namespace Carbon\Exceptions; -use Exception; +use Throwable; class UnknownUnitException extends UnitException { + /** + * The unit. + * + * @var string + */ + protected $unit; + /** * Constructor. * * @param string $unit * @param int $code - * @param Exception|null $previous + * @param Throwable|null $previous */ - public function __construct($unit, $code = 0, Exception $previous = null) + public function __construct($unit, $code = 0, Throwable $previous = null) { + $this->unit = $unit; + parent::__construct("Unknown unit '$unit'.", $code, $previous); } + + /** + * Get the unit. + * + * @return string + */ + public function getUnit(): string + { + return $this->unit; + } } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/UnreachableException.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/UnreachableException.php index 6f8b39f5f..1654ab11b 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/UnreachableException.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Exceptions/UnreachableException.php @@ -11,20 +11,9 @@ namespace Carbon\Exceptions; -use Exception; use RuntimeException as BaseRuntimeException; class UnreachableException extends BaseRuntimeException implements RuntimeException { - /** - * Constructor. - * - * @param string $message - * @param int $code - * @param Exception|null $previous - */ - public function __construct($message, $code = 0, Exception $previous = null) - { - parent::__construct($message, $code, $previous); - } + // } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Factory.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Factory.php index f8c72890c..d497535f7 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Factory.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Factory.php @@ -177,10 +177,10 @@ use ReflectionMethod; * parameter of null. * /!\ Use this method for unit tests only. * @method void setToStringFormat($format) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. - * You should rather let Carbon object being casted to string with DEFAULT_TO_STRING_FORMAT, and - * use other method or custom format passed to format() method if you need to dump an other string + * You should rather let Carbon object being cast to string with DEFAULT_TO_STRING_FORMAT, and + * use other method or custom format passed to format() method if you need to dump another string * format. - * Set the default format used when type juggling a Carbon instance to a string + * Set the default format used when type juggling a Carbon instance to a string. * @method void setTranslator(TranslatorInterface $translator) Set the default translator instance to use. * @method Carbon setUtf8($utf8) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. * You should rather use UTF-8 language packages on every machine. @@ -231,7 +231,7 @@ use ReflectionMethod; * You should rather use the ->settings() method. * Or you can use method variants: addYearsWithOverflow/addYearsNoOverflow, same variants * are available for quarters, years, decade, centuries, millennia (singular and plural forms). - * @method mixed withTestNow($testNow = null, $callback = null) Temporarily sets a static date to be used within the callback. + * @method mixed withTestNow($testNow, $callback) Temporarily sets a static date to be used within the callback. * Using setTestNow to set the date, executing the callback, then * clearing the test instance. * /!\ Use this method for unit tests only. diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/FactoryImmutable.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/FactoryImmutable.php index 596ee8064..d88a1cf67 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/FactoryImmutable.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/FactoryImmutable.php @@ -12,6 +12,9 @@ namespace Carbon; use Closure; +use DateTimeImmutable; +use DateTimeZone; +use Psr\Clock\ClockInterface; /** * A factory to generate CarbonImmutable instances with common settings. @@ -111,7 +114,6 @@ use Closure; * @method CarbonImmutable maxValue() Create a Carbon instance for the greatest supported date. * @method CarbonImmutable minValue() Create a Carbon instance for the lowest supported date. * @method void mixin($mixin) Mix another object into the class. - * @method CarbonImmutable now($tz = null) Get a Carbon instance for the current date and time. * @method CarbonImmutable parse($time = null, $tz = null) Create a carbon instance from a string. * This is an alias for the constructor that allows better fluent syntax * as it allows you to do Carbon::parse('Monday next week')->fn() rather @@ -175,10 +177,10 @@ use Closure; * parameter of null. * /!\ Use this method for unit tests only. * @method void setToStringFormat($format) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. - * You should rather let Carbon object being casted to string with DEFAULT_TO_STRING_FORMAT, and - * use other method or custom format passed to format() method if you need to dump an other string + * You should rather let Carbon object being cast to string with DEFAULT_TO_STRING_FORMAT, and + * use other method or custom format passed to format() method if you need to dump another string * format. - * Set the default format used when type juggling a Carbon instance to a string + * Set the default format used when type juggling a Carbon instance to a string. * @method void setTranslator(TranslatorInterface $translator) Set the default translator instance to use. * @method CarbonImmutable setUtf8($utf8) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. * You should rather use UTF-8 language packages on every machine. @@ -229,7 +231,7 @@ use Closure; * You should rather use the ->settings() method. * Or you can use method variants: addYearsWithOverflow/addYearsNoOverflow, same variants * are available for quarters, years, decade, centuries, millennia (singular and plural forms). - * @method mixed withTestNow($testNow = null, $callback = null) Temporarily sets a static date to be used within the callback. + * @method mixed withTestNow($testNow, $callback) Temporarily sets a static date to be used within the callback. * Using setTestNow to set the date, executing the callback, then * clearing the test instance. * /!\ Use this method for unit tests only. @@ -237,7 +239,21 @@ use Closure; * * */ -class FactoryImmutable extends Factory +class FactoryImmutable extends Factory implements ClockInterface { protected $className = CarbonImmutable::class; + + /** + * Get a Carbon instance for the current date and time. + * + * @param DateTimeZone|string|int|null $tz + * + * @return CarbonImmutable + */ + public function now($tz = null): DateTimeImmutable + { + $className = $this->className; + + return new $className(null, $tz); + } } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_AE.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_AE.php index 75fe47f6d..35a22b1d2 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_AE.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_AE.php @@ -12,6 +12,7 @@ /* * Authors: * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + * - Abdullah-Alhariri */ return array_replace_recursive(require __DIR__.'/ar.php', [ 'formats' => [ @@ -24,4 +25,5 @@ return array_replace_recursive(require __DIR__.'/ar.php', [ 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], 'first_day_of_week' => 6, 'day_of_first_week_of_year' => 1, + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], ]); diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_BH.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_BH.php index 362009e29..35180965a 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_BH.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_BH.php @@ -12,6 +12,7 @@ /* * Authors: * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + * - Abdullah-Alhariri */ return array_replace_recursive(require __DIR__.'/ar.php', [ 'formats' => [ @@ -24,4 +25,5 @@ return array_replace_recursive(require __DIR__.'/ar.php', [ 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], 'first_day_of_week' => 6, 'day_of_first_week_of_year' => 1, + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], ]); diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_EG.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_EG.php index 362009e29..35180965a 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_EG.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_EG.php @@ -12,6 +12,7 @@ /* * Authors: * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + * - Abdullah-Alhariri */ return array_replace_recursive(require __DIR__.'/ar.php', [ 'formats' => [ @@ -24,4 +25,5 @@ return array_replace_recursive(require __DIR__.'/ar.php', [ 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], 'first_day_of_week' => 6, 'day_of_first_week_of_year' => 1, + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], ]); diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_IQ.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_IQ.php index 0ac09958e..2d4200845 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_IQ.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_IQ.php @@ -12,6 +12,7 @@ /* * Authors: * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + * - Abdullah-Alhariri */ return array_replace_recursive(require __DIR__.'/ar.php', [ 'formats' => [ @@ -24,4 +25,5 @@ return array_replace_recursive(require __DIR__.'/ar.php', [ 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], 'first_day_of_week' => 6, 'day_of_first_week_of_year' => 1, + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], ]); diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_JO.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_JO.php index 0ac09958e..2d4200845 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_JO.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_JO.php @@ -12,6 +12,7 @@ /* * Authors: * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + * - Abdullah-Alhariri */ return array_replace_recursive(require __DIR__.'/ar.php', [ 'formats' => [ @@ -24,4 +25,5 @@ return array_replace_recursive(require __DIR__.'/ar.php', [ 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], 'first_day_of_week' => 6, 'day_of_first_week_of_year' => 1, + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], ]); diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_KW.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_KW.php index e6f0531d4..b3fb1cfec 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_KW.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_KW.php @@ -16,6 +16,7 @@ * - JD Isaacks * - Atef Ben Ali (atefBB) * - Mohamed Sabil (mohamedsabil83) + * - Abdullah-Alhariri */ $months = [ 'يناير', @@ -90,4 +91,5 @@ return [ ], 'meridiem' => ['ص', 'م'], 'weekend' => [5, 6], + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], ]; diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_LB.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_LB.php index 55bb10c33..2792745c6 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_LB.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_LB.php @@ -12,6 +12,7 @@ /* * Authors: * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + * - Abdullah-Alhariri */ return array_replace_recursive(require __DIR__.'/ar.php', [ 'formats' => [ @@ -24,4 +25,5 @@ return array_replace_recursive(require __DIR__.'/ar.php', [ 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], 'first_day_of_week' => 1, 'day_of_first_week_of_year' => 1, + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], ]); diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_OM.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_OM.php index 362009e29..35180965a 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_OM.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_OM.php @@ -12,6 +12,7 @@ /* * Authors: * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + * - Abdullah-Alhariri */ return array_replace_recursive(require __DIR__.'/ar.php', [ 'formats' => [ @@ -24,4 +25,5 @@ return array_replace_recursive(require __DIR__.'/ar.php', [ 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], 'first_day_of_week' => 6, 'day_of_first_week_of_year' => 1, + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], ]); diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_PS.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_PS.php index e790b99e6..503c60d2e 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_PS.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_PS.php @@ -9,5 +9,10 @@ * file that was distributed with this source code. */ +/* + * Authors: + * - Abdullah-Alhariri + */ return array_replace_recursive(require __DIR__.'/ar.php', [ + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], ]); diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_QA.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_QA.php index 362009e29..35180965a 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_QA.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_QA.php @@ -12,6 +12,7 @@ /* * Authors: * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + * - Abdullah-Alhariri */ return array_replace_recursive(require __DIR__.'/ar.php', [ 'formats' => [ @@ -24,4 +25,5 @@ return array_replace_recursive(require __DIR__.'/ar.php', [ 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], 'first_day_of_week' => 6, 'day_of_first_week_of_year' => 1, + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], ]); diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_SA.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_SA.php index 10aaa2ede..550b0c73a 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_SA.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_SA.php @@ -15,6 +15,7 @@ * - JD Isaacks * - Atef Ben Ali (atefBB) * - Mohamed Sabil (mohamedsabil83) + * - Abdullah-Alhariri */ $months = [ 'يناير', @@ -89,4 +90,5 @@ return [ ], 'meridiem' => ['ص', 'م'], 'weekend' => [5, 6], + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], ]; diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_SD.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_SD.php index 362009e29..35180965a 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_SD.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_SD.php @@ -12,6 +12,7 @@ /* * Authors: * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + * - Abdullah-Alhariri */ return array_replace_recursive(require __DIR__.'/ar.php', [ 'formats' => [ @@ -24,4 +25,5 @@ return array_replace_recursive(require __DIR__.'/ar.php', [ 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], 'first_day_of_week' => 6, 'day_of_first_week_of_year' => 1, + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], ]); diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_SY.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_SY.php index 0ac09958e..2d4200845 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_SY.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_SY.php @@ -12,6 +12,7 @@ /* * Authors: * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + * - Abdullah-Alhariri */ return array_replace_recursive(require __DIR__.'/ar.php', [ 'formats' => [ @@ -24,4 +25,5 @@ return array_replace_recursive(require __DIR__.'/ar.php', [ 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], 'first_day_of_week' => 6, 'day_of_first_week_of_year' => 1, + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], ]); diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_YE.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_YE.php index 5dc29388e..169fe88a9 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_YE.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ar_YE.php @@ -12,6 +12,7 @@ /* * Authors: * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org + * - Abdullah-Alhariri */ return array_replace_recursive(require __DIR__.'/ar.php', [ 'formats' => [ @@ -23,4 +24,5 @@ return array_replace_recursive(require __DIR__.'/ar.php', [ 'weekdays_short' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], 'day_of_first_week_of_year' => 1, + 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], ]); diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/be.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/be.php index 51b4d0cc1..ee736365a 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/be.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/be.php @@ -9,13 +9,12 @@ * file that was distributed with this source code. */ -// @codeCoverageIgnoreStart - use Carbon\CarbonInterface; use Symfony\Component\Translation\PluralizationRules; -if (class_exists('Symfony\\Component\\Translation\\PluralizationRules')) { - PluralizationRules::set(function ($number) { +// @codeCoverageIgnoreStart +if (class_exists(PluralizationRules::class)) { + PluralizationRules::set(static function ($number) { return (($number % 10 == 1) && ($number % 100 != 11)) ? 0 : ((($number % 10 >= 2) && ($number % 10 <= 4) && (($number % 100 < 10) || ($number % 100 >= 20))) ? 1 : 2); }, 'be'); } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ca_ES_Valencia.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ca_ES_Valencia.php index 861acd2a0..1c16421ad 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ca_ES_Valencia.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ca_ES_Valencia.php @@ -9,5 +9,15 @@ * file that was distributed with this source code. */ +use Symfony\Component\Translation\PluralizationRules; + +// @codeCoverageIgnoreStart +if (class_exists(PluralizationRules::class)) { + PluralizationRules::set(static function ($number) { + return PluralizationRules::get($number, 'ca'); + }, 'ca_ES_Valencia'); +} +// @codeCoverageIgnoreEnd + return array_replace_recursive(require __DIR__.'/ca.php', [ ]); diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ckb.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ckb.php new file mode 100644 index 000000000..acf4dc280 --- /dev/null +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ckb.php @@ -0,0 +1,89 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Authors: + * - Swara Mohammed + */ +$months = [ + 'ڕێبەندان', + 'ڕەشەمە', + 'نەورۆز', + 'گوڵان', + 'جۆزەردان', + 'پوشپەڕ', + 'گەلاوێژ', + 'خەرمانان', + 'ڕەزبەر', + 'گەڵاڕێزان', + 'سەرماوەرز', + 'بەفرانبار', +]; + +return [ + 'year' => implode('|', ['{0}:count ساڵێک', '{1}ساڵێک', '{2}دوو ساڵ', ']2,11[:count ساڵ', ']10,Inf[:count ساڵ']), + 'a_year' => implode('|', ['{0}:count ساڵێک', '{1}ساڵێک', '{2}دوو ساڵ', ']2,11[:count ساڵ', ']10,Inf[:count ساڵ']), + 'month' => implode('|', ['{0}:count مانگێک', '{1}مانگێک', '{2}دوو مانگ', ']2,11[:count مانگ', ']10,Inf[:count مانگ']), + 'a_month' => implode('|', ['{0}:count مانگێک', '{1}مانگێک', '{2}دوو مانگ', ']2,11[:count مانگ', ']10,Inf[:count مانگ']), + 'week' => implode('|', ['{0}:count هەفتەیەک', '{1}هەفتەیەک', '{2}دوو هەفتە', ']2,11[:count هەفتە', ']10,Inf[:count هەفتە']), + 'a_week' => implode('|', ['{0}:count هەفتەیەک', '{1}هەفتەیەک', '{2}دوو هەفتە', ']2,11[:count هەفتە', ']10,Inf[:count هەفتە']), + 'day' => implode('|', ['{0}:count ڕۆژێک', '{1}ڕۆژێک', '{2}دوو ڕۆژ', ']2,11[:count ڕۆژ', ']10,Inf[:count ڕۆژ']), + 'a_day' => implode('|', ['{0}:count ڕۆژێک', '{1}ڕۆژێک', '{2}دوو ڕۆژ', ']2,11[:count ڕۆژ', ']10,Inf[:count ڕۆژ']), + 'hour' => implode('|', ['{0}:count کاتژمێرێک', '{1}کاتژمێرێک', '{2}دوو کاتژمێر', ']2,11[:count کاتژمێر', ']10,Inf[:count کاتژمێر']), + 'a_hour' => implode('|', ['{0}:count کاتژمێرێک', '{1}کاتژمێرێک', '{2}دوو کاتژمێر', ']2,11[:count کاتژمێر', ']10,Inf[:count کاتژمێر']), + 'minute' => implode('|', ['{0}:count خولەکێک', '{1}خولەکێک', '{2}دوو خولەک', ']2,11[:count خولەک', ']10,Inf[:count خولەک']), + 'a_minute' => implode('|', ['{0}:count خولەکێک', '{1}خولەکێک', '{2}دوو خولەک', ']2,11[:count خولەک', ']10,Inf[:count خولەک']), + 'second' => implode('|', ['{0}:count چرکەیەک', '{1}چرکەیەک', '{2}دوو چرکە', ']2,11[:count چرکە', ']10,Inf[:count چرکە']), + 'a_second' => implode('|', ['{0}:count چرکەیەک', '{1}چرکەیەک', '{2}دوو چرکە', ']2,11[:count چرکە', ']10,Inf[:count چرکە']), + 'ago' => 'پێش :time', + 'from_now' => ':time لە ئێستاوە', + 'after' => 'دوای :time', + 'before' => 'پێش :time', + 'diff_now' => 'ئێستا', + 'diff_today' => 'ئەمڕۆ', + 'diff_today_regexp' => 'ڕۆژ(?:\\s+لە)?(?:\\s+کاتژمێر)?', + 'diff_yesterday' => 'دوێنێ', + 'diff_yesterday_regexp' => 'دوێنێ(?:\\s+لە)?(?:\\s+کاتژمێر)?', + 'diff_tomorrow' => 'سبەینێ', + 'diff_tomorrow_regexp' => 'سبەینێ(?:\\s+لە)?(?:\\s+کاتژمێر)?', + 'diff_before_yesterday' => 'پێش دوێنێ', + 'diff_after_tomorrow' => 'دوای سبەینێ', + 'period_recurrences' => implode('|', ['{0}جار', '{1}جار', '{2}:count دووجار', ']2,11[:count جار', ']10,Inf[:count جار']), + 'period_interval' => 'هەموو :interval', + 'period_start_date' => 'لە :date', + 'period_end_date' => 'بۆ :date', + 'months' => $months, + 'months_short' => $months, + 'weekdays' => ['یەکشەممە', 'دووشەممە', 'سێشەممە', 'چوارشەممە', 'پێنجشەممە', 'هەینی', 'شەممە'], + 'weekdays_short' => ['یەکشەممە', 'دووشەممە', 'سێشەممە', 'چوارشەممە', 'پێنجشەممە', 'هەینی', 'شەممە'], + 'weekdays_min' => ['یەکشەممە', 'دووشەممە', 'سێشەممە', 'چوارشەممە', 'پێنجشەممە', 'هەینی', 'شەممە'], + 'list' => ['، ', ' و '], + 'first_day_of_week' => 6, + 'day_of_first_week_of_year' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'D/M/YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], + 'calendar' => [ + 'sameDay' => '[ئەمڕۆ لە کاتژمێر] LT', + 'nextDay' => '[سبەینێ لە کاتژمێر] LT', + 'nextWeek' => 'dddd [لە کاتژمێر] LT', + 'lastDay' => '[دوێنێ لە کاتژمێر] LT', + 'lastWeek' => 'dddd [لە کاتژمێر] LT', + 'sameElse' => 'L', + ], + 'meridiem' => ['پ.ن', 'د.ن'], + 'weekend' => [5, 6], +]; diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/cs.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/cs.php index 8cff9a019..c01e3ccc8 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/cs.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/cs.php @@ -101,7 +101,8 @@ return [ 'after' => $za, 'first_day_of_week' => 1, 'day_of_first_week_of_year' => 4, - 'months' => ['leden', 'únor', 'březen', 'duben', 'květen', 'červen', 'červenec', 'srpen', 'září', 'říjen', 'listopad', 'prosinec'], + 'months' => ['ledna', 'února', 'března', 'dubna', 'května', 'června', 'července', 'srpna', 'září', 'října', 'listopadu', 'prosince'], + 'months_standalone' => ['leden', 'únor', 'březen', 'duben', 'květen', 'červen', 'červenec', 'srpen', 'září', 'říjen', 'listopad', 'prosinec'], 'months_short' => ['led', 'úno', 'bře', 'dub', 'kvě', 'čvn', 'čvc', 'srp', 'zář', 'říj', 'lis', 'pro'], 'weekdays' => ['neděle', 'pondělí', 'úterý', 'středa', 'čtvrtek', 'pátek', 'sobota'], 'weekdays_short' => ['ned', 'pon', 'úte', 'stř', 'čtv', 'pát', 'sob'], diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/cy.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/cy.php index ab7c45a4f..119274f01 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/cy.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/cy.php @@ -60,7 +60,7 @@ return [ 'ordinal' => function ($number) { return $number.( $number > 20 - ? (\in_array($number, [40, 50, 60, 80, 100]) ? 'fed' : 'ain') + ? (\in_array((int) $number, [40, 50, 60, 80, 100], true) ? 'fed' : 'ain') : ([ '', 'af', 'il', 'ydd', 'ydd', 'ed', 'ed', 'ed', 'fed', 'fed', 'fed', // 1af to 10fed 'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'fed', // 11eg to 20fed diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/da.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/da.php index 4e6640a67..322f91d5b 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/da.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/da.php @@ -18,6 +18,7 @@ * - Jens Herlevsen * - Ulrik McArdle (mcardle) * - Frederik Sauer (FrittenKeeZ) + * - Janus Bahs Jacquet (kokoshneta) */ return [ 'year' => ':count år|:count år', @@ -41,7 +42,7 @@ return [ 'second' => ':count sekund|:count sekunder', 'a_second' => 'få sekunder|:count sekunder', 's' => ':count s.', - 'ago' => ':time siden', + 'ago' => 'for :time siden', 'from_now' => 'om :time', 'after' => ':time efter', 'before' => ':time før', @@ -70,9 +71,9 @@ return [ ], 'ordinal' => ':number.', 'months' => ['januar', 'februar', 'marts', 'april', 'maj', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'december'], - 'months_short' => ['jan', 'feb', 'mar', 'apr', 'maj', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec'], + 'months_short' => ['jan.', 'feb.', 'mar.', 'apr.', 'maj.', 'jun.', 'jul.', 'aug.', 'sep.', 'okt.', 'nov.', 'dec.'], 'weekdays' => ['søndag', 'mandag', 'tirsdag', 'onsdag', 'torsdag', 'fredag', 'lørdag'], - 'weekdays_short' => ['søn', 'man', 'tir', 'ons', 'tor', 'fre', 'lør'], + 'weekdays_short' => ['søn.', 'man.', 'tir.', 'ons.', 'tor.', 'fre.', 'lør.'], 'weekdays_min' => ['sø', 'ma', 'ti', 'on', 'to', 'fr', 'lø'], 'first_day_of_week' => 1, 'day_of_first_week_of_year' => 4, diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/de.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/de.php index ff00c9745..3b70750e4 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/de.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/de.php @@ -105,4 +105,13 @@ return [ 'first_day_of_week' => 1, 'day_of_first_week_of_year' => 4, 'list' => [', ', ' und '], + 'ordinal_words' => [ + 'of' => 'im', + 'first' => 'erster', + 'second' => 'zweiter', + 'third' => 'dritter', + 'fourth' => 'vierten', + 'fifth' => 'fünfter', + 'last' => 'letzten', + ], ]; diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/en.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/en.php index a8633fef0..f81f617e3 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/en.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/en.php @@ -72,7 +72,7 @@ return [ $lastDigit = $number % 10; return $number.( - (~~($number % 100 / 10) === 1) ? 'th' : ( + ((int) ($number % 100 / 10) === 1) ? 'th' : ( ($lastDigit === 1) ? 'st' : ( ($lastDigit === 2) ? 'nd' : ( ($lastDigit === 3) ? 'rd' : 'th' diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/en_CH.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/en_CH.php index e2dd81db5..10d9cd8f1 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/en_CH.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/en_CH.php @@ -11,4 +11,12 @@ return array_replace_recursive(require __DIR__.'/en.php', [ 'first_day_of_week' => 1, + 'formats' => [ + 'LT' => 'HH:mm', + 'LTS' => 'HH:mm:ss', + 'L' => 'DD.MM.YYYY', + 'LL' => 'D MMMM YYYY', + 'LLL' => 'D MMMM YYYY HH:mm', + 'LLLL' => 'dddd D MMMM YYYY HH:mm', + ], ]); diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/es.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/es.php index f77ec39c6..1c4fcfd0b 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/es.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/es.php @@ -26,6 +26,7 @@ * - quinterocesar * - Daniel Commesse Liévanos (danielcommesse) * - Pete Scopes (pdscopes) + * - gam04 */ use Carbon\CarbonInterface; @@ -108,4 +109,13 @@ return [ 'day_of_first_week_of_year' => 4, 'list' => [', ', ' y '], 'meridiem' => ['a. m.', 'p. m.'], + 'ordinal_words' => [ + 'of' => 'de', + 'first' => 'primer', + 'second' => 'segundo', + 'third' => 'tercer', + 'fourth' => 'cuarto', + 'fifth' => 'quinto', + 'last' => 'último', + ], ]; diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/fi.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/fi.php index 2003e1eab..edf2d6d35 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/fi.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/fi.php @@ -74,8 +74,10 @@ return [ 'LTS' => 'HH.mm:ss', 'L' => 'D.M.YYYY', 'LL' => 'dddd D. MMMM[ta] YYYY', + 'll' => 'ddd D. MMM YYYY', 'LLL' => 'D.MM. HH.mm', 'LLLL' => 'D. MMMM[ta] YYYY HH.mm', + 'llll' => 'D. MMM YY HH.mm', ], 'weekdays' => ['sunnuntai', 'maanantai', 'tiistai', 'keskiviikko', 'torstai', 'perjantai', 'lauantai'], 'weekdays_short' => ['su', 'ma', 'ti', 'ke', 'to', 'pe', 'la'], diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/fr.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/fr.php index 73fe5e41b..f4c7247b4 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/fr.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/fr.php @@ -90,7 +90,7 @@ return [ 'weekdays_min' => ['di', 'lu', 'ma', 'me', 'je', 've', 'sa'], 'ordinal' => function ($number, $period) { switch ($period) { - // In french, only the first has be ordinal, other number remains cardinal + // In French, only the first has to be ordinal, other number remains cardinal // @link https://fr.wikihow.com/%C3%A9crire-la-date-en-fran%C3%A7ais case 'D': return $number.($number === 1 ? 'er' : ''); @@ -111,4 +111,13 @@ return [ 'first_day_of_week' => 1, 'day_of_first_week_of_year' => 4, 'list' => [', ', ' et '], + 'ordinal_words' => [ + 'of' => 'de', + 'first' => 'premier', + 'second' => 'deuxième', + 'third' => 'troisième', + 'fourth' => 'quatrième', + 'fifth' => 'cinquième', + 'last' => 'dernier', + ], ]; diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/hu.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/hu.php index b2d2ac113..b7583eecd 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/hu.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/hu.php @@ -82,7 +82,7 @@ return [ 'second_before' => ':count másodperccel', 's_before' => ':count másodperccel', 'months' => ['január', 'február', 'március', 'április', 'május', 'június', 'július', 'augusztus', 'szeptember', 'október', 'november', 'december'], - 'months_short' => ['jan.', 'feb.', 'márc.', 'ápr.', 'máj.', 'jún.', 'júl.', 'aug.', 'szept.', 'okt.', 'nov.', 'dec.'], + 'months_short' => ['jan.', 'febr.', 'márc.', 'ápr.', 'máj.', 'jún.', 'júl.', 'aug.', 'szept.', 'okt.', 'nov.', 'dec.'], 'weekdays' => ['vasárnap', 'hétfő', 'kedd', 'szerda', 'csütörtök', 'péntek', 'szombat'], 'weekdays_short' => ['vas', 'hét', 'kedd', 'sze', 'csüt', 'pén', 'szo'], 'weekdays_min' => ['v', 'h', 'k', 'sze', 'cs', 'p', 'sz'], diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/it.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/it.php index 605bcbb5a..49875d7ef 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/it.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/it.php @@ -55,7 +55,7 @@ return [ 'µs' => ':countµs', 'ago' => ':time fa', 'from_now' => function ($time) { - return (preg_match('/^[0-9].+$/', $time) ? 'tra' : 'in')." $time"; + return (preg_match('/^\d.+$/', $time) ? 'tra' : 'in')." $time"; }, 'after' => ':time dopo', 'before' => ':time prima', @@ -103,4 +103,13 @@ return [ 'first_day_of_week' => 1, 'day_of_first_week_of_year' => 4, 'list' => [', ', ' e '], + 'ordinal_words' => [ + 'of' => 'di', + 'first' => 'primo', + 'second' => 'secondo', + 'third' => 'terzo', + 'fourth' => 'quarto', + 'fifth' => 'quinto', + 'last' => 'ultimo', + ], ]; diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ku.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ku.php index b001e3015..189960c8a 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ku.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ku.php @@ -11,31 +11,29 @@ /* * Authors: - * - Halwest Manguri - * - Kardo Qadir + * - Unicode, Inc. */ -$months = ['کانونی دووەم', 'شوبات', 'ئازار', 'نیسان', 'ئایار', '‌حوزەیران', 'تەمموز', 'ئاب', 'ئەیلول', 'تشرینی یەکەم', 'تشرینی دووەم', 'کانونی یەکەم']; - -$weekdays = ['دوو شەممە', 'سێ شەممە', 'چوار شەممە', 'پێنج شەممە', 'هەینی', 'شەممە', 'یەک شەممە']; return [ - 'ago' => 'پێش :time', - 'from_now' => ':time لە ئێستاوە', - 'after' => 'دوای :time', - 'before' => 'پێش :time', - 'year' => '{0}ساڵ|{1}ساڵێک|{2}٢ ساڵ|[3,10]:count ساڵ|[11,Inf]:count ساڵ', - 'month' => '{0}مانگ|{1}مانگێک|{2}٢ مانگ|[3,10]:count مانگ|[11,Inf]:count مانگ', - 'week' => '{0}هەفتە|{1}هەفتەیەک|{2}٢ هەفتە|[3,10]:count هەفتە|[11,Inf]:count هەفتە', - 'day' => '{0}ڕۆژ|{1}ڕۆژێک|{2}٢ ڕۆژ|[3,10]:count ڕۆژ|[11,Inf]:count ڕۆژ', - 'hour' => '{0}کاتژمێر|{1}کاتژمێرێک|{2}٢ کاتژمێر|[3,10]:count کاتژمێر|[11,Inf]:count کاتژمێر', - 'minute' => '{0}خولەک|{1}خولەکێک|{2}٢ خولەک|[3,10]:count خولەک|[11,Inf]:count خولەک', - 'second' => '{0}چرکە|{1}چرکەیەک|{2}٢ چرکە|[3,10]:count چرکە|[11,Inf]:count چرکە', - 'months' => $months, - 'months_standalone' => $months, - 'months_short' => $months, - 'weekdays' => $weekdays, - 'weekdays_short' => $weekdays, - 'weekdays_min' => $weekdays, + 'ago' => 'berî :time', + 'from_now' => 'di :time de', + 'after' => ':time piştî', + 'before' => ':time berê', + 'year' => ':count sal', + 'year_ago' => ':count salê|:count salan', + 'year_from_now' => 'salekê|:count salan', + 'month' => ':count meh', + 'week' => ':count hefte', + 'day' => ':count roj', + 'hour' => ':count saet', + 'minute' => ':count deqîqe', + 'second' => ':count saniye', + 'months' => ['rêbendanê', 'reşemiyê', 'adarê', 'avrêlê', 'gulanê', 'pûşperê', 'tîrmehê', 'gelawêjê', 'rezberê', 'kewçêrê', 'sermawezê', 'berfanbarê'], + 'months_standalone' => ['rêbendan', 'reşemî', 'adar', 'avrêl', 'gulan', 'pûşper', 'tîrmeh', 'gelawêj', 'rezber', 'kewçêr', 'sermawez', 'berfanbar'], + 'months_short' => ['rêb', 'reş', 'ada', 'avr', 'gul', 'pûş', 'tîr', 'gel', 'rez', 'kew', 'ser', 'ber'], + 'weekdays' => ['yekşem', 'duşem', 'sêşem', 'çarşem', 'pêncşem', 'în', 'şemî'], + 'weekdays_short' => ['yş', 'dş', 'sş', 'çş', 'pş', 'în', 'ş'], + 'weekdays_min' => ['Y', 'D', 'S', 'Ç', 'P', 'Î', 'Ş'], 'list' => [', ', ' û '], 'first_day_of_week' => 6, 'day_of_first_week_of_year' => 1, diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/lv.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/lv.php index 693eceb5a..d5cba7ca0 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/lv.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/lv.php @@ -176,7 +176,8 @@ return [ 'weekdays' => $daysOfWeek, 'weekdays_short' => ['Sv.', 'P.', 'O.', 'T.', 'C.', 'Pk.', 'S.'], 'weekdays_min' => ['Sv.', 'P.', 'O.', 'T.', 'C.', 'Pk.', 'S.'], - 'months' => ['janvārī', 'februārī', 'martā', 'aprīlī', 'maijā', 'jūnijā', 'jūlijā', 'augustā', 'septembrī', 'oktobrī', 'novembrī', 'decembrī'], + 'months' => ['janvāris', 'februāris', 'marts', 'aprīlis', 'maijs', 'jūnijs', 'jūlijs', 'augusts', 'septembris', 'oktobris', 'novembris', 'decembris'], + 'months_standalone' => ['janvārī', 'februārī', 'martā', 'aprīlī', 'maijā', 'jūnijā', 'jūlijā', 'augustā', 'septembrī', 'oktobrī', 'novembrī', 'decembrī'], 'months_short' => ['janv.', 'febr.', 'martā', 'apr.', 'maijā', 'jūn.', 'jūl.', 'aug.', 'sept.', 'okt.', 'nov.', 'dec.'], 'meridiem' => ['priekšpusdiena', 'pēcpusdiena'], ]; diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/mn.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/mn.php index 717d199bc..38c6434d3 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/mn.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/mn.php @@ -26,6 +26,7 @@ * - Nicolás Hock Isaza * - Ochirkhuyag * - Batmandakh + * - lucifer-crybaby */ return [ 'year' => ':count жил', @@ -43,38 +44,55 @@ return [ 'second' => ':count секунд', 's' => ':countс', - 'ago' => ':timeн өмнө', - 'year_ago' => ':count жилий', - 'month_ago' => ':count сары', - 'day_ago' => ':count хоногий', - 'hour_ago' => ':count цагий', - 'minute_ago' => ':count минуты', - 'second_ago' => ':count секунды', + 'ago_mode' => 'last', + 'ago' => ':time өмнө', + 'year_ago' => ':count жилийн', + 'y_ago' => ':count жилийн', + 'month_ago' => ':count сарын', + 'm_ago' => ':count сарын', + 'day_ago' => ':count хоногийн', + 'd_ago' => ':count хоногийн', + 'week_ago' => ':count долоо хоногийн', + 'w_ago' => ':count долоо хоногийн', + 'hour_ago' => ':count цагийн', + 'minute_ago' => ':count минутын', + 'second_ago' => ':count секундын', + 'from_now_mode' => 'last', 'from_now' => 'одоогоос :time', 'year_from_now' => ':count жилийн дараа', + 'y_from_now' => ':count жилийн дараа', 'month_from_now' => ':count сарын дараа', + 'm_from_now' => ':count сарын дараа', 'day_from_now' => ':count хоногийн дараа', + 'd_from_now' => ':count хоногийн дараа', 'hour_from_now' => ':count цагийн дараа', 'minute_from_now' => ':count минутын дараа', 'second_from_now' => ':count секундын дараа', - // Does it required to make translation for before, after as follows? hmm, I think we've made it with ago and from now keywords already. Anyway, I've included it just in case of undesired action... - 'after' => ':timeн дараа', - 'year_after' => ':count жилий', - 'month_after' => ':count сары', - 'day_after' => ':count хоногий', - 'hour_after' => ':count цагий', - 'minute_after' => ':count минуты', - 'second_after' => ':count секунды', + 'after_mode' => 'last', + 'after' => ':time дараа', + 'year_after' => ':count жилийн', + 'y_after' => ':count жилийн', + 'month_after' => ':count сарын', + 'm_after' => ':count сарын', + 'day_after' => ':count хоногийн', + 'd_after' => ':count хоногийн', + 'hour_after' => ':count цагийн', + 'minute_after' => ':count минутын', + 'second_after' => ':count секундын', - 'before' => ':timeн өмнө', - 'year_before' => ':count жилий', - 'month_before' => ':count сары', - 'day_before' => ':count хоногий', - 'hour_before' => ':count цагий', - 'minute_before' => ':count минуты', - 'second_before' => ':count секунды', + 'before_mode' => 'last', + 'before' => ':time өмнө', + 'year_before' => ':count жилийн', + 'y_before' => ':count жилийн', + 'month_before' => ':count сарын', + 'm_before' => ':count сарын', + 'day_before' => ':count хоногийн', + 'd_before' => ':count хоногийн', + 'hour_before' => ':count цагийн', + 'minute_before' => ':count минутын', + 'second_before' => ':count секундын', 'list' => ', ', 'diff_now' => 'одоо', diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ms.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ms.php index 36934eeb1..c9e80854f 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ms.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ms.php @@ -48,7 +48,7 @@ return [ 'ago' => ':time yang lepas', 'from_now' => ':time dari sekarang', 'after' => ':time kemudian', - 'before' => ':time lepas', + 'before' => ':time sebelum', 'diff_now' => 'sekarang', 'diff_today' => 'Hari', 'diff_today_regexp' => 'Hari(?:\\s+ini)?(?:\\s+pukul)?', diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/oc.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/oc.php index 89693e674..c9411d69d 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/oc.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/oc.php @@ -17,7 +17,7 @@ use Symfony\Component\Translation\PluralizationRules; if (class_exists('Symfony\\Component\\Translation\\PluralizationRules')) { - PluralizationRules::set(function ($number) { + PluralizationRules::set(static function ($number) { return $number == 1 ? 0 : 1; }, 'oc'); } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/pl.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/pl.php index f0196c0d6..b72053549 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/pl.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/pl.php @@ -62,7 +62,7 @@ return [ }, 'after' => ':time po', 'before' => ':time przed', - 'diff_now' => 'przed chwilą', + 'diff_now' => 'teraz', 'diff_today' => 'Dziś', 'diff_today_regexp' => 'Dziś(?:\\s+o)?', 'diff_yesterday' => 'wczoraj', diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/pt.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/pt.php index 0af894994..bb6359b14 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/pt.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/pt.php @@ -104,4 +104,13 @@ return [ 'first_day_of_week' => 1, 'day_of_first_week_of_year' => 4, 'list' => [', ', ' e '], + 'ordinal_words' => [ + 'of' => 'de', + 'first' => 'primeira', + 'second' => 'segunda', + 'third' => 'terceira', + 'fourth' => 'quarta', + 'fifth' => 'quinta', + 'last' => 'última', + ], ]; diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sh.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sh.php index e4aa5a1c7..e03b50675 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sh.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sh.php @@ -13,7 +13,7 @@ use Symfony\Component\Translation\PluralizationRules; if (class_exists('Symfony\\Component\\Translation\\PluralizationRules')) { - PluralizationRules::set(function ($number) { + PluralizationRules::set(static function ($number) { return (($number % 10 == 1) && ($number % 100 != 11)) ? 0 : ((($number % 10 >= 2) && ($number % 10 <= 4) && (($number % 100 < 10) || ($number % 100 >= 20))) ? 1 : 2); }, 'sh'); } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sk.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sk.php index fd0f6b3e9..f9702e960 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sk.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sk.php @@ -31,33 +31,89 @@ * - jofi * - Jakub ADAMEC * - Marek Adamický + * - AlterwebStudio */ + +use Carbon\CarbonInterface; + +$fromNow = function ($time) { + return 'o '.strtr($time, [ + 'hodina' => 'hodinu', + 'minúta' => 'minútu', + 'sekunda' => 'sekundu', + ]); +}; + +$ago = function ($time) { + $replacements = [ + '/\bhodina\b/' => 'hodinou', + '/\bminúta\b/' => 'minútou', + '/\bsekunda\b/' => 'sekundou', + '/\bdeň\b/u' => 'dňom', + '/\btýždeň\b/u' => 'týždňom', + '/\bmesiac\b/' => 'mesiacom', + '/\brok\b/' => 'rokom', + ]; + + $replacementsPlural = [ + '/\bhodiny\b/' => 'hodinami', + '/\bminúty\b/' => 'minútami', + '/\bsekundy\b/' => 'sekundami', + '/\bdni\b/' => 'dňami', + '/\btýždne\b/' => 'týždňami', + '/\bmesiace\b/' => 'mesiacmi', + '/\broky\b/' => 'rokmi', + ]; + + foreach ($replacements + $replacementsPlural as $pattern => $replacement) { + $time = preg_replace($pattern, $replacement, $time); + } + + return "pred $time"; +}; + return [ - 'year' => 'rok|:count roky|:count rokov', + 'year' => ':count rok|:count roky|:count rokov', + 'a_year' => 'rok|:count roky|:count rokov', 'y' => ':count r', - 'month' => 'mesiac|:count mesiace|:count mesiacov', + 'month' => ':count mesiac|:count mesiace|:count mesiacov', + 'a_month' => 'mesiac|:count mesiace|:count mesiacov', 'm' => ':count m', - 'week' => 'týždeň|:count týždne|:count týždňov', + 'week' => ':count týždeň|:count týždne|:count týždňov', + 'a_week' => 'týždeň|:count týždne|:count týždňov', 'w' => ':count t', - 'day' => 'deň|:count dni|:count dní', + 'day' => ':count deň|:count dni|:count dní', + 'a_day' => 'deň|:count dni|:count dní', 'd' => ':count d', - 'hour' => 'hodinu|:count hodiny|:count hodín', + 'hour' => ':count hodina|:count hodiny|:count hodín', + 'a_hour' => 'hodina|:count hodiny|:count hodín', 'h' => ':count h', - 'minute' => 'minútu|:count minúty|:count minút', + 'minute' => ':count minúta|:count minúty|:count minút', + 'a_minute' => 'minúta|:count minúty|:count minút', 'min' => ':count min', - 'second' => 'sekundu|:count sekundy|:count sekúnd', + 'second' => ':count sekunda|:count sekundy|:count sekúnd', + 'a_second' => 'sekunda|:count sekundy|:count sekúnd', 's' => ':count s', - 'ago' => 'pred :time', - 'from_now' => 'za :time', - 'after' => 'o :time neskôr', - 'before' => ':time predtým', - 'year_ago' => 'rokom|:count rokmi|:count rokmi', - 'month_ago' => 'mesiacom|:count mesiacmi|:count mesiacmi', - 'week_ago' => 'týždňom|:count týždňami|:count týždňami', - 'day_ago' => 'dňom|:count dňami|:count dňami', - 'hour_ago' => 'hodinou|:count hodinami|:count hodinami', - 'minute_ago' => 'minútou|:count minútami|:count minútami', - 'second_ago' => 'sekundou|:count sekundami|:count sekundami', + 'millisecond' => ':count milisekunda|:count milisekundy|:count milisekúnd', + 'a_millisecond' => 'milisekunda|:count milisekundy|:count milisekúnd', + 'ms' => ':count ms', + 'microsecond' => ':count mikrosekunda|:count mikrosekundy|:count mikrosekúnd', + 'a_microsecond' => 'mikrosekunda|:count mikrosekundy|:count mikrosekúnd', + 'µs' => ':count µs', + + 'ago' => $ago, + 'from_now' => $fromNow, + 'before' => ':time pred', + 'after' => ':time po', + + 'hour_after' => ':count hodinu|:count hodiny|:count hodín', + 'minute_after' => ':count minútu|:count minúty|:count minút', + 'second_after' => ':count sekundu|:count sekundy|:count sekúnd', + + 'hour_before' => ':count hodinu|:count hodiny|:count hodín', + 'minute_before' => ':count minútu|:count minúty|:count minút', + 'second_before' => ':count sekundu|:count sekundy|:count sekúnd', + 'first_day_of_week' => 1, 'day_of_first_week_of_year' => 4, 'list' => [', ', ' a '], @@ -72,8 +128,26 @@ return [ 'LLL' => 'D. M. HH:mm', 'LLLL' => 'dddd D. MMMM YYYY HH:mm', ], + 'calendar' => [ + 'sameDay' => '[dnes o] LT', + 'nextDay' => '[zajtra o] LT', + 'lastDay' => '[včera o] LT', + 'nextWeek' => 'dddd [o] LT', + 'lastWeek' => static function (CarbonInterface $date) { + switch ($date->dayOfWeek) { + case 1: + case 2: + case 4: + case 5: + return '[minulý] dddd [o] LT'; //pondelok/utorok/štvrtok/piatok + default: + return '[minulá] dddd [o] LT'; + } + }, + 'sameElse' => 'L', + ], 'weekdays' => ['nedeľa', 'pondelok', 'utorok', 'streda', 'štvrtok', 'piatok', 'sobota'], - 'weekdays_short' => ['ne', 'po', 'ut', 'st', 'št', 'pi', 'so'], + 'weekdays_short' => ['ned', 'pon', 'uto', 'str', 'štv', 'pia', 'sob'], 'weekdays_min' => ['ne', 'po', 'ut', 'st', 'št', 'pi', 'so'], 'months' => ['január', 'február', 'marec', 'apríl', 'máj', 'jún', 'júl', 'august', 'september', 'október', 'november', 'december'], 'months_short' => ['jan', 'feb', 'mar', 'apr', 'máj', 'jún', 'júl', 'aug', 'sep', 'okt', 'nov', 'dec'], diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sl.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sl.php index 2e197212b..1f1d1b338 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sl.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sl.php @@ -49,9 +49,9 @@ return [ 'a_second' => '{1}nekaj sekund|:count sekunda|:count sekundi|:count sekunde|:count sekund', 's' => ':count s', - 'year_ago' => ':count letom|:count leti|:count leti|:count leti', - 'y_ago' => ':count letom|:count leti|:count leti|:count leti', - 'month_ago' => ':count mesecem|:count meseci|:count meseci|:count meseci', + 'year_ago' => ':count letom|:count letoma|:count leti|:count leti', + 'y_ago' => ':count letom|:count letoma|:count leti|:count leti', + 'month_ago' => ':count mesecem|:count mesecema|:count meseci|:count meseci', 'week_ago' => ':count tednom|:count tednoma|:count tedni|:count tedni', 'day_ago' => ':count dnem|:count dnevoma|:count dnevi|:count dnevi', 'd_ago' => ':count dnem|:count dnevoma|:count dnevi|:count dnevi', diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sr_Cyrl.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sr_Cyrl.php index c09df19cf..8becbc576 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sr_Cyrl.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sr_Cyrl.php @@ -24,28 +24,28 @@ use Carbon\CarbonInterface; return [ - 'year' => '{2,3,4,22,23,24,32,33,34,42,43,44,52,53,54}:count године|[0,Inf[:count година', + 'year' => ':count година|:count године|:count година', 'y' => ':count г.', - 'month' => '{1}:count месец|{2,3,4}:count месеца|[0,Inf[:count месеци', + 'month' => ':count месец|:count месеца|:count месеци', 'm' => ':count м.', - 'week' => '{1}:count недеља|{2,3,4}:count недеље|[0,Inf[:count недеља', + 'week' => ':count недеља|:count недеље|:count недеља', 'w' => ':count нед.', - 'day' => '{1,21,31}:count дан|[0,Inf[:count дана', + 'day' => ':count дан|:count дана|:count дана', 'd' => ':count д.', - 'hour' => '{1,21}:count сат|{2,3,4,22,23,24}:count сата|[0,Inf[:count сати', + 'hour' => ':count сат|:count сата|:count сати', 'h' => ':count ч.', - 'minute' => '{1,21,31,41,51}:count минут|[0,Inf[:count минута', + 'minute' => ':count минут|:count минута|:count минута', 'min' => ':count мин.', - 'second' => '{1,21,31,41,51}:count секунд|{2,3,4,22,23,24,32,33,34,42,43,44,52,53,54}:count секунде|[0,Inf[:count секунди', + 'second' => ':count секунд|:count секунде|:count секунди', 's' => ':count сек.', 'ago' => 'пре :time', 'from_now' => 'за :time', 'after' => ':time након', 'before' => ':time пре', - 'year_from_now' => '{1,21,31,41,51}:count годину|{2,3,4,22,23,24,32,33,34,42,43,44,52,53,54}:count године|[0,Inf[:count година', - 'year_ago' => '{1,21,31,41,51}:count годину|{2,3,4,22,23,24,32,33,34,42,43,44,52,53,54}:count године|[0,Inf[:count година', - 'week_from_now' => '{1}:count недељу|{2,3,4}:count недеље|[0,Inf[:count недеља', - 'week_ago' => '{1}:count недељу|{2,3,4}:count недеље|[0,Inf[:count недеља', + 'year_from_now' => ':count годину|:count године|:count година', + 'year_ago' => ':count годину|:count године|:count година', + 'week_from_now' => ':count недељу|:count недеље|:count недеља', + 'week_ago' => ':count недељу|:count недеље|:count недеља', 'diff_now' => 'управо сада', 'diff_today' => 'данас', 'diff_today_regexp' => 'данас(?:\\s+у)?', diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sr_Cyrl_BA.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sr_Cyrl_BA.php index 0fb63d769..4b29a45c7 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sr_Cyrl_BA.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sr_Cyrl_BA.php @@ -9,6 +9,16 @@ * file that was distributed with this source code. */ +use Symfony\Component\Translation\PluralizationRules; + +// @codeCoverageIgnoreStart +if (class_exists(PluralizationRules::class)) { + PluralizationRules::set(static function ($number) { + return PluralizationRules::get($number, 'sr'); + }, 'sr_Cyrl_BA'); +} +// @codeCoverageIgnoreEnd + return array_replace_recursive(require __DIR__.'/sr_Cyrl.php', [ 'formats' => [ 'LT' => 'HH:mm', diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sr_Cyrl_ME.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sr_Cyrl_ME.php index d13229abc..28d22fd2c 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sr_Cyrl_ME.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sr_Cyrl_ME.php @@ -16,32 +16,41 @@ */ use Carbon\CarbonInterface; +use Symfony\Component\Translation\PluralizationRules; + +// @codeCoverageIgnoreStart +if (class_exists(PluralizationRules::class)) { + PluralizationRules::set(static function ($number) { + return PluralizationRules::get($number, 'sr'); + }, 'sr_Cyrl_ME'); +} +// @codeCoverageIgnoreEnd return [ - 'year' => '{2,3,4,22,23,24,32,33,34,42,43,44,52,53,54}:count године|[0,Inf[:count година', + 'year' => ':count година|:count године|:count година', 'y' => ':count г.', - 'month' => '{1}:count мјесец|{2,3,4}:count мјесеца|[0,Inf[:count мјесеци', + 'month' => ':count мјесец|:count мјесеца|:count мјесеци', 'm' => ':count мј.', - 'week' => '{1}:count недјеља|{2,3,4}:count недјеље|[0,Inf[:count недјеља', + 'week' => ':count недјеља|:count недјеље|:count недјеља', 'w' => ':count нед.', - 'day' => '{1,21,31}:count дан|[0,Inf[:count дана', + 'day' => ':count дан|:count дана|:count дана', 'd' => ':count д.', - 'hour' => '{1,21}:count сат|{2,3,4,22,23,24}:count сата|[0,Inf[:count сати', + 'hour' => ':count сат|:count сата|:count сати', 'h' => ':count ч.', - 'minute' => '{1,21,31,41,51}:count минут|[0,Inf[:count минута', + 'minute' => ':count минут|:count минута|:count минута', 'min' => ':count мин.', - 'second' => '{1,21,31,41,51}:count секунд|{2,3,4,22,23,24,32,33,34,42,43,44,52,53,54}:count секунде|[0,Inf[:count секунди', + 'second' => ':count секунд|:count секунде|:count секунди', 's' => ':count сек.', 'ago' => 'прије :time', 'from_now' => 'за :time', 'after' => ':time након', 'before' => ':time прије', - 'year_from_now' => '{1,21,31,41,51}:count годину|{2,3,4,22,23,24,32,33,34,42,43,44,52,53,54}:count године|[0,Inf[:count година', - 'year_ago' => '{1,21,31,41,51}:count годину|{2,3,4,22,23,24,32,33,34,42,43,44,52,53,54}:count године|[0,Inf[:count година', + 'year_from_now' => ':count годину|:count године|:count година', + 'year_ago' => ':count годину|:count године|:count година', - 'week_from_now' => '{1}:count недјељу|{2,3,4}:count недјеље|[0,Inf[:count недјеља', - 'week_ago' => '{1}:count недјељу|{2,3,4}:count недјеље|[0,Inf[:count недјеља', + 'week_from_now' => ':count недјељу|:count недјеље|:count недјеља', + 'week_ago' => ':count недјељу|:count недјеље|:count недјеља', 'diff_now' => 'управо сада', 'diff_today' => 'данас', diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sr_Cyrl_XK.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sr_Cyrl_XK.php index 492baf0cb..d6e29b86b 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sr_Cyrl_XK.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sr_Cyrl_XK.php @@ -9,6 +9,16 @@ * file that was distributed with this source code. */ +use Symfony\Component\Translation\PluralizationRules; + +// @codeCoverageIgnoreStart +if (class_exists(PluralizationRules::class)) { + PluralizationRules::set(static function ($number) { + return PluralizationRules::get($number, 'sr'); + }, 'sr_Cyrl_XK'); +} +// @codeCoverageIgnoreEnd + return array_replace_recursive(require __DIR__.'/sr_Cyrl_BA.php', [ 'weekdays' => ['недеља', 'понедељак', 'уторак', 'среда', 'четвртак', 'петак', 'субота'], ]); diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sr_Latn_BA.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sr_Latn_BA.php index 897c674a5..95b2770db 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sr_Latn_BA.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sr_Latn_BA.php @@ -9,6 +9,16 @@ * file that was distributed with this source code. */ +use Symfony\Component\Translation\PluralizationRules; + +// @codeCoverageIgnoreStart +if (class_exists(PluralizationRules::class)) { + PluralizationRules::set(static function ($number) { + return PluralizationRules::get($number, 'sr'); + }, 'sr_Latn_BA'); +} +// @codeCoverageIgnoreEnd + return array_replace_recursive(require __DIR__.'/sr_Latn.php', [ 'formats' => [ 'LT' => 'HH:mm', diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sr_Latn_ME.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sr_Latn_ME.php index e2133ef1a..5b8f2d062 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sr_Latn_ME.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sr_Latn_ME.php @@ -16,6 +16,15 @@ */ use Carbon\CarbonInterface; +use Symfony\Component\Translation\PluralizationRules; + +// @codeCoverageIgnoreStart +if (class_exists(PluralizationRules::class)) { + PluralizationRules::set(static function ($number) { + return PluralizationRules::get($number, 'sr'); + }, 'sr_Latn_ME'); +} +// @codeCoverageIgnoreEnd return array_replace_recursive(require __DIR__.'/sr.php', [ 'month' => ':count mjesec|:count mjeseca|:count mjeseci', @@ -27,6 +36,7 @@ return array_replace_recursive(require __DIR__.'/sr.php', [ 'before' => ':time prije', 'week_from_now' => ':count nedjelju|:count nedjelje|:count nedjelja', 'week_ago' => ':count nedjelju|:count nedjelje|:count nedjelja', + 'second_ago' => ':count sekund|:count sekunde|:count sekundi', 'diff_tomorrow' => 'sjutra', 'calendar' => [ 'nextDay' => '[sjutra u] LT', diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sr_Latn_XK.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sr_Latn_XK.php index d0b9d10bb..5278e2e5a 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sr_Latn_XK.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sr_Latn_XK.php @@ -9,6 +9,16 @@ * file that was distributed with this source code. */ +use Symfony\Component\Translation\PluralizationRules; + +// @codeCoverageIgnoreStart +if (class_exists(PluralizationRules::class)) { + PluralizationRules::set(static function ($number) { + return PluralizationRules::get($number, 'sr'); + }, 'sr_Latn_XK'); +} +// @codeCoverageIgnoreEnd + return array_replace_recursive(require __DIR__.'/sr_Latn_BA.php', [ 'weekdays' => ['nedelja', 'ponedeljak', 'utorak', 'sreda', 'četvrtak', 'petak', 'subota'], ]); diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ss.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ss.php index cd4b91901..1c52c9bf6 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ss.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/ss.php @@ -50,7 +50,7 @@ return [ $lastDigit = $number % 10; return $number.( - (~~($number % 100 / 10) === 1) ? 'e' : ( + ((int) ($number % 100 / 10) === 1) ? 'e' : ( ($lastDigit === 1 || $lastDigit === 2) ? 'a' : 'e' ) ); diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sv.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sv.php index ca33e1c45..1706c7191 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sv.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sv.php @@ -70,7 +70,7 @@ return [ $lastDigit = $number % 10; return $number.( - (~~($number % 100 / 10) === 1) ? 'e' : ( + ((int) ($number % 100 / 10) === 1) ? 'e' : ( ($lastDigit === 1 || $lastDigit === 2) ? 'a' : 'e' ) ); diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/uk.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/uk.php index b267b0002..4217d16ed 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/uk.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/uk.php @@ -55,7 +55,7 @@ $processHoursFunction = function (CarbonInterface $date, string $format) { */ return [ 'year' => ':count рік|:count роки|:count років', - 'y' => ':countр', + 'y' => ':countр|:countрр|:countрр', 'a_year' => '{1}рік|:count рік|:count роки|:count років', 'month' => ':count місяць|:count місяці|:count місяців', 'm' => ':countм', @@ -193,6 +193,7 @@ return [ 'genitive' => ['неділі', 'понеділка', 'вівторка', 'середи', 'четверга', 'п’ятниці', 'суботи'], ]; + $format = $format ?? ''; $nounCase = preg_match('/(\[(В|в|У|у)\])\s+dddd/u', $format) ? 'accusative' : ( diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Laravel/ServiceProvider.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Laravel/ServiceProvider.php index 8be0569e8..84e241e3e 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Laravel/ServiceProvider.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Laravel/ServiceProvider.php @@ -24,6 +24,22 @@ use Throwable; class ServiceProvider extends \Illuminate\Support\ServiceProvider { + /** @var callable|null */ + protected $appGetter = null; + + /** @var callable|null */ + protected $localeGetter = null; + + public function setAppGetter(?callable $appGetter): void + { + $this->appGetter = $appGetter; + } + + public function setLocaleGetter(?callable $localeGetter): void + { + $this->localeGetter = $localeGetter; + } + public function boot() { $this->updateLocale(); @@ -44,8 +60,12 @@ class ServiceProvider extends \Illuminate\Support\ServiceProvider public function updateLocale() { - $app = $this->app && method_exists($this->app, 'getLocale') ? $this->app : app('translator'); - $locale = $app->getLocale(); + $locale = $this->getLocale(); + + if ($locale === null) { + return; + } + Carbon::setLocale($locale); CarbonImmutable::setLocale($locale); CarbonPeriod::setLocale($locale); @@ -70,6 +90,34 @@ class ServiceProvider extends \Illuminate\Support\ServiceProvider // Needed for Laravel < 5.3 compatibility } + protected function getLocale() + { + if ($this->localeGetter) { + return ($this->localeGetter)(); + } + + $app = $this->getApp(); + $app = $app && method_exists($app, 'getLocale') + ? $app + : $this->getGlobalApp('translator'); + + return $app ? $app->getLocale() : null; + } + + protected function getApp() + { + if ($this->appGetter) { + return ($this->appGetter)(); + } + + return $this->app ?? $this->getGlobalApp(); + } + + protected function getGlobalApp(...$args) + { + return \function_exists('app') ? \app(...$args) : null; + } + protected function isEventDispatcher($instance) { return $instance instanceof EventDispatcher diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/MessageFormatter/MessageFormatterMapper.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/MessageFormatter/MessageFormatterMapper.php new file mode 100644 index 000000000..c05480876 --- /dev/null +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/MessageFormatter/MessageFormatterMapper.php @@ -0,0 +1,44 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\MessageFormatter; + +use ReflectionMethod; +use Symfony\Component\Translation\Formatter\MessageFormatter; +use Symfony\Component\Translation\Formatter\MessageFormatterInterface; + +// @codeCoverageIgnoreStart +$transMethod = new ReflectionMethod(MessageFormatterInterface::class, 'format'); + +require $transMethod->getParameters()[0]->hasType() + ? __DIR__.'/../../../lazy/Carbon/MessageFormatter/MessageFormatterMapperStrongType.php' + : __DIR__.'/../../../lazy/Carbon/MessageFormatter/MessageFormatterMapperWeakType.php'; +// @codeCoverageIgnoreEnd + +final class MessageFormatterMapper extends LazyMessageFormatter +{ + /** + * Wrapped formatter. + * + * @var MessageFormatterInterface + */ + protected $formatter; + + public function __construct(?MessageFormatterInterface $formatter = null) + { + $this->formatter = $formatter ?? new MessageFormatter(); + } + + protected function transformLocale(?string $locale): ?string + { + return $locale ? preg_replace('/[_@][A-Za-z][a-z]{2,}/', '', $locale) : $locale; + } +} diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/PHPStan/AbstractMacro.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/PHPStan/AbstractMacro.php index fc6fd2a79..fde67b36a 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/PHPStan/AbstractMacro.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/PHPStan/AbstractMacro.php @@ -14,6 +14,12 @@ declare(strict_types=1); namespace Carbon\PHPStan; use Closure; +use InvalidArgumentException; +use PHPStan\BetterReflection\Reflection\Adapter\ReflectionParameter as AdapterReflectionParameter; +use PHPStan\BetterReflection\Reflection\Adapter\ReflectionType as AdapterReflectionType; +use PHPStan\BetterReflection\Reflection\ReflectionClass as BetterReflectionClass; +use PHPStan\BetterReflection\Reflection\ReflectionFunction as BetterReflectionFunction; +use PHPStan\BetterReflection\Reflection\ReflectionParameter as BetterReflectionParameter; use PHPStan\Reflection\Php\BuiltinMethodReflection; use PHPStan\TrinaryLogic; use ReflectionClass; @@ -64,24 +70,34 @@ abstract class AbstractMacro implements BuiltinMethodReflection /** * Macro constructor. * - * @param string $className - * @phpstan-param class-string $className - * - * @param string $methodName - * @param callable $macro + * @param class-string $className + * @param string $methodName + * @param callable $macro */ public function __construct(string $className, string $methodName, $macro) { $this->className = $className; $this->methodName = $methodName; - $this->reflectionFunction = \is_array($macro) + $rawReflectionFunction = \is_array($macro) ? new ReflectionMethod($macro[0], $macro[1]) : new ReflectionFunction($macro); - $this->parameters = $this->reflectionFunction->getParameters(); + $this->reflectionFunction = self::hasModernParser() + ? $this->getReflectionFunction($macro) + : $rawReflectionFunction; // @codeCoverageIgnore + $this->parameters = array_map( + function ($parameter) { + if ($parameter instanceof BetterReflectionParameter) { + return new AdapterReflectionParameter($parameter); + } - if ($this->reflectionFunction->isClosure()) { + return $parameter; // @codeCoverageIgnore + }, + $this->reflectionFunction->getParameters() + ); + + if ($rawReflectionFunction->isClosure()) { try { - $closure = $this->reflectionFunction->getClosure(); + $closure = $rawReflectionFunction->getClosure(); $boundClosure = Closure::bind($closure, new stdClass()); $this->static = (!$boundClosure || (new ReflectionFunction($boundClosure))->getClosureThis() === null); } catch (Throwable $e) { @@ -90,6 +106,31 @@ abstract class AbstractMacro implements BuiltinMethodReflection } } + private function getReflectionFunction($spec) + { + if (\is_array($spec) && \count($spec) === 2 && \is_string($spec[1])) { + \assert($spec[1] !== ''); + + if (\is_object($spec[0])) { + return BetterReflectionClass::createFromInstance($spec[0]) + ->getMethod($spec[1]); + } + + return BetterReflectionClass::createFromName($spec[0]) + ->getMethod($spec[1]); + } + + if (\is_string($spec)) { + return BetterReflectionFunction::createFromName($spec); + } + + if ($spec instanceof Closure) { + return BetterReflectionFunction::createFromClosure($spec); + } + + throw new InvalidArgumentException('Could not create reflection from the spec given'); // @codeCoverageIgnore + } + /** * {@inheritdoc} */ @@ -175,7 +216,13 @@ abstract class AbstractMacro implements BuiltinMethodReflection */ public function getReturnType(): ?ReflectionType { - return $this->reflectionFunction->getReturnType(); + $type = $this->reflectionFunction->getReturnType(); + + if ($type instanceof ReflectionType) { + return $type; // @codeCoverageIgnore + } + + return self::adaptType($type); } /** @@ -205,18 +252,35 @@ abstract class AbstractMacro implements BuiltinMethodReflection return $this; } - /** - * {@inheritdoc} - */ - public function getReflection(): ?ReflectionMethod - { - return $this->reflectionFunction instanceof ReflectionMethod - ? $this->reflectionFunction - : null; - } - public function getTentativeReturnType(): ?ReflectionType { return null; } + + public function returnsByReference(): TrinaryLogic + { + return TrinaryLogic::createNo(); + } + + private static function adaptType($type) + { + $method = method_exists(AdapterReflectionType::class, 'fromTypeOrNull') + ? 'fromTypeOrNull' + : 'fromReturnTypeOrNull'; // @codeCoverageIgnore + + return AdapterReflectionType::$method($type); + } + + private static function hasModernParser(): bool + { + static $modernParser = null; + + if ($modernParser !== null) { + return $modernParser; + } + + $modernParser = method_exists(AdapterReflectionType::class, 'fromTypeOrNull'); + + return $modernParser; + } } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/PHPStan/Macro.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/PHPStan/Macro.php index 839258736..de3e51f6a 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/PHPStan/Macro.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/PHPStan/Macro.php @@ -13,9 +13,16 @@ declare(strict_types=1); namespace Carbon\PHPStan; +use PHPStan\BetterReflection\Reflection\Adapter; use PHPStan\Reflection\Php\BuiltinMethodReflection; use ReflectionMethod; +$method = new ReflectionMethod(BuiltinMethodReflection::class, 'getReflection'); + +require $method->hasReturnType() && $method->getReturnType()->getName() === Adapter\ReflectionMethod::class + ? __DIR__.'/../../../lazy/Carbon/PHPStan/AbstractMacroStatic.php' + : __DIR__.'/../../../lazy/Carbon/PHPStan/AbstractMacroBuiltin.php'; + $method = new ReflectionMethod(BuiltinMethodReflection::class, 'getFileName'); require $method->hasReturnType() diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/PHPStan/MacroExtension.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/PHPStan/MacroExtension.php index 8e2524c09..2cd6fce54 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/PHPStan/MacroExtension.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/PHPStan/MacroExtension.php @@ -11,10 +11,12 @@ namespace Carbon\PHPStan; +use PHPStan\Reflection\Assertions; use PHPStan\Reflection\ClassReflection; use PHPStan\Reflection\MethodReflection; use PHPStan\Reflection\MethodsClassReflectionExtension; use PHPStan\Reflection\Php\PhpMethodReflectionFactory; +use PHPStan\Reflection\ReflectionProvider; use PHPStan\Type\TypehintHelper; /** @@ -38,10 +40,13 @@ final class MacroExtension implements MethodsClassReflectionExtension * Extension constructor. * * @param PhpMethodReflectionFactory $methodReflectionFactory + * @param ReflectionProvider $reflectionProvider */ - public function __construct(PhpMethodReflectionFactory $methodReflectionFactory) - { - $this->scanner = new MacroScanner(); + public function __construct( + PhpMethodReflectionFactory $methodReflectionFactory, + ReflectionProvider $reflectionProvider + ) { + $this->scanner = new MacroScanner($reflectionProvider); $this->methodReflectionFactory = $methodReflectionFactory; } @@ -59,6 +64,7 @@ final class MacroExtension implements MethodsClassReflectionExtension public function getMethod(ClassReflection $classReflection, string $methodName): MethodReflection { $builtinMacro = $this->scanner->getMethod($classReflection->getName(), $methodName); + $supportAssertions = class_exists(Assertions::class); return $this->methodReflectionFactory->create( $classReflection, @@ -72,7 +78,11 @@ final class MacroExtension implements MethodsClassReflectionExtension $builtinMacro->isDeprecated()->yes(), $builtinMacro->isInternal(), $builtinMacro->isFinal(), - $builtinMacro->getDocComment() + $supportAssertions ? null : $builtinMacro->getDocComment(), + $supportAssertions ? Assertions::createEmpty() : null, + null, + $builtinMacro->getDocComment(), + [] ); } } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/PHPStan/MacroScanner.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/PHPStan/MacroScanner.php index d169939d8..eb8957d4d 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/PHPStan/MacroScanner.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/PHPStan/MacroScanner.php @@ -12,35 +12,55 @@ namespace Carbon\PHPStan; use Carbon\CarbonInterface; +use PHPStan\Reflection\ReflectionProvider; use ReflectionClass; use ReflectionException; final class MacroScanner { + /** + * @var \PHPStan\Reflection\ReflectionProvider + */ + private $reflectionProvider; + + /** + * MacroScanner constructor. + * + * @param \PHPStan\Reflection\ReflectionProvider $reflectionProvider + */ + public function __construct(ReflectionProvider $reflectionProvider) + { + $this->reflectionProvider = $reflectionProvider; + } + /** * Return true if the given pair class-method is a Carbon macro. * - * @param string $className - * @phpstan-param class-string $className - * - * @param string $methodName + * @param class-string $className + * @param string $methodName * * @return bool */ public function hasMethod(string $className, string $methodName): bool { - return is_a($className, CarbonInterface::class, true) && - \is_callable([$className, 'hasMacro']) && + $classReflection = $this->reflectionProvider->getClass($className); + + if ( + $classReflection->getName() !== CarbonInterface::class && + !$classReflection->isSubclassOf(CarbonInterface::class) + ) { + return false; + } + + return \is_callable([$className, 'hasMacro']) && $className::hasMacro($methodName); } /** * Return the Macro for a given pair class-method. * - * @param string $className - * @phpstan-param class-string $className - * - * @param string $methodName + * @param class-string $className + * @param string $methodName * * @throws ReflectionException * diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Comparison.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Comparison.php index a23e6ed0c..f6261d882 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Comparison.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Comparison.php @@ -75,6 +75,9 @@ trait Comparison */ public function equalTo($date): bool { + $this->discourageNull($date); + $this->discourageBoolean($date); + return $this == $this->resolveCarbon($date); } @@ -155,6 +158,9 @@ trait Comparison */ public function greaterThan($date): bool { + $this->discourageNull($date); + $this->discourageBoolean($date); + return $this > $this->resolveCarbon($date); } @@ -216,7 +222,10 @@ trait Comparison */ public function greaterThanOrEqualTo($date): bool { - return $this >= $date; + $this->discourageNull($date); + $this->discourageBoolean($date); + + return $this >= $this->resolveCarbon($date); } /** @@ -256,6 +265,9 @@ trait Comparison */ public function lessThan($date): bool { + $this->discourageNull($date); + $this->discourageBoolean($date); + return $this < $this->resolveCarbon($date); } @@ -317,7 +329,10 @@ trait Comparison */ public function lessThanOrEqualTo($date): bool { - return $this <= $date; + $this->discourageNull($date); + $this->discourageBoolean($date); + + return $this <= $this->resolveCarbon($date); } /** @@ -351,10 +366,10 @@ trait Comparison } if ($equal) { - return $this->greaterThanOrEqualTo($date1) && $this->lessThanOrEqualTo($date2); + return $this >= $date1 && $this <= $date2; } - return $this->greaterThan($date1) && $this->lessThan($date2); + return $this > $date1 && $this < $date2; } /** @@ -448,7 +463,7 @@ trait Comparison */ public function isWeekend() { - return \in_array($this->dayOfWeek, static::$weekendDays); + return \in_array($this->dayOfWeek, static::$weekendDays, true); } /** @@ -548,12 +563,17 @@ trait Comparison } /** - * Determines if the instance is a long year + * Determines if the instance is a long year (using calendar year). + * + * ⚠️ This method completely ignores month and day to use the numeric year number, + * it's not correct if the exact date matters. For instance as `2019-12-30` is already + * in the first week of the 2020 year, if you want to know from this date if ISO week + * year 2020 is a long year, use `isLongIsoYear` instead. * * @example * ``` - * Carbon::parse('2015-01-01')->isLongYear(); // true - * Carbon::parse('2016-01-01')->isLongYear(); // false + * Carbon::create(2015)->isLongYear(); // true + * Carbon::create(2016)->isLongYear(); // false * ``` * * @see https://en.wikipedia.org/wiki/ISO_8601#Week_dates @@ -565,6 +585,27 @@ trait Comparison return static::create($this->year, 12, 28, 0, 0, 0, $this->tz)->weekOfYear === 53; } + /** + * Determines if the instance is a long year (using ISO 8601 year). + * + * @example + * ``` + * Carbon::parse('2015-01-01')->isLongIsoYear(); // true + * Carbon::parse('2016-01-01')->isLongIsoYear(); // true + * Carbon::parse('2016-01-03')->isLongIsoYear(); // false + * Carbon::parse('2019-12-29')->isLongIsoYear(); // false + * Carbon::parse('2019-12-30')->isLongIsoYear(); // true + * ``` + * + * @see https://en.wikipedia.org/wiki/ISO_8601#Week_dates + * + * @return bool + */ + public function isLongIsoYear() + { + return static::create($this->isoWeekYear, 12, 28, 0, 0, 0, $this->tz)->weekOfYear === 53; + } + /** * Compares the formatted values of the two dates. * @@ -621,19 +662,19 @@ trait Comparison 'microsecond' => 'Y-m-d H:i:s.u', ]; - if (!isset($units[$unit])) { - if (isset($this->$unit)) { - return $this->resolveCarbon($date)->$unit === $this->$unit; - } - - if ($this->localStrictModeEnabled ?? static::isStrictModeEnabled()) { - throw new BadComparisonUnitException($unit); - } - - return false; + if (isset($units[$unit])) { + return $this->isSameAs($units[$unit], $date); } - return $this->isSameAs($units[$unit], $date); + if (isset($this->$unit)) { + return $this->resolveCarbon($date)->$unit === $this->$unit; + } + + if ($this->localStrictModeEnabled ?? static::isStrictModeEnabled()) { + throw new BadComparisonUnitException($unit); + } + + return false; } /** @@ -981,12 +1022,12 @@ trait Comparison return $current->startOfMinute()->eq($other); } - if (preg_match('/\d(h|am|pm)$/', $tester)) { + if (preg_match('/\d(?:h|am|pm)$/', $tester)) { return $current->startOfHour()->eq($other); } if (preg_match( - '/^(january|february|march|april|may|june|july|august|september|october|november|december)\s+\d+$/i', + '/^(?:january|february|march|april|may|june|july|august|september|october|november|december)(?:\s+\d+)?$/i', $tester )) { return $current->startOfMonth()->eq($other->startOfMonth()); @@ -1067,4 +1108,18 @@ trait Comparison { return $this->endOfTime ?? false; } + + private function discourageNull($value): void + { + if ($value === null) { + @trigger_error("Since 2.61.0, it's deprecated to compare a date to null, meaning of such comparison is ambiguous and will no longer be possible in 3.0.0, you should explicitly pass 'now' or make an other check to eliminate null values.", \E_USER_DEPRECATED); + } + } + + private function discourageBoolean($value): void + { + if (\is_bool($value)) { + @trigger_error("Since 2.61.0, it's deprecated to compare a date to true or false, meaning of such comparison is ambiguous and will no longer be possible in 3.0.0, you should explicitly pass 'now' or make an other check to eliminate boolean values.", \E_USER_DEPRECATED); + } + } } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Converter.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Converter.php index 8fe008a5c..fff8a600a 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Converter.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Converter.php @@ -16,6 +16,7 @@ use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Carbon\CarbonInterval; use Carbon\CarbonPeriod; +use Carbon\CarbonPeriodImmutable; use Carbon\Exceptions\UnitException; use Closure; use DateTime; @@ -34,39 +35,7 @@ use ReturnTypeWillChange; */ trait Converter { - /** - * Format to use for __toString method when type juggling occurs. - * - * @var string|Closure|null - */ - protected static $toStringFormat; - - /** - * Reset the format used to the default when type juggling a Carbon instance to a string - * - * @return void - */ - public static function resetToStringFormat() - { - static::setToStringFormat(null); - } - - /** - * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. - * You should rather let Carbon object being casted to string with DEFAULT_TO_STRING_FORMAT, and - * use other method or custom format passed to format() method if you need to dump an other string - * format. - * - * Set the default format used when type juggling a Carbon instance to a string - * - * @param string|Closure|null $format - * - * @return void - */ - public static function setToStringFormat($format) - { - static::$toStringFormat = $format; - } + use ToStringFormat; /** * Returns the formatted date string on success or FALSE on failure. @@ -110,7 +79,7 @@ trait Converter * * @example * ``` - * echo Carbon::now(); // Carbon instances can be casted to string + * echo Carbon::now(); // Carbon instances can be cast to string * ``` * * @return string @@ -158,6 +127,21 @@ trait Converter return $this->rawFormat('M j, Y'); } + /** + * Format the instance with the day, and a readable date + * + * @example + * ``` + * echo Carbon::now()->toFormattedDayDateString(); + * ``` + * + * @return string + */ + public function toFormattedDayDateString(): string + { + return $this->rawFormat('D, M j, Y'); + } + /** * Format the instance as time * @@ -622,16 +606,18 @@ trait Converter $interval = CarbonInterval::make("$interval ".static::pluralUnit($unit)); } - $period = (new CarbonPeriod())->setDateClass(static::class)->setStartDate($this); + $period = ($this->isMutable() ? new CarbonPeriod() : new CarbonPeriodImmutable()) + ->setDateClass(static::class) + ->setStartDate($this); if ($interval) { - $period->setDateInterval($interval); + $period = $period->setDateInterval($interval); } - if (\is_int($end) || \is_string($end) && ctype_digit($end)) { - $period->setRecurrences($end); + if (\is_int($end) || (\is_string($end) && ctype_digit($end))) { + $period = $period->setRecurrences($end); } elseif ($end) { - $period->setEndDate($end); + $period = $period->setEndDate($end); } return $period; diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Creator.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Creator.php index f2adee5fd..0d611ea22 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Creator.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Creator.php @@ -19,6 +19,8 @@ use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Translator; use Closure; +use DateMalformedStringException; +use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Exception; @@ -79,8 +81,8 @@ trait Creator // Work-around for PHP bug https://bugs.php.net/bug.php?id=67127 if (!str_contains((string) .1, '.')) { - $locale = setlocale(LC_NUMERIC, '0'); - setlocale(LC_NUMERIC, 'C'); + $locale = setlocale(LC_NUMERIC, '0'); // @codeCoverageIgnore + setlocale(LC_NUMERIC, 'C'); // @codeCoverageIgnore } try { @@ -92,7 +94,7 @@ trait Creator $this->constructedObjectId = spl_object_hash($this); if (isset($locale)) { - setlocale(LC_NUMERIC, $locale); + setlocale(LC_NUMERIC, $locale); // @codeCoverageIgnore } self::setLastErrors(parent::getLastErrors()); @@ -112,7 +114,7 @@ trait Creator $safeTz = static::safeCreateDateTimeZone($tz); if ($safeTz) { - return $date->setTimezone($safeTz); + return ($date instanceof DateTimeImmutable ? $date : clone $date)->setTimezone($safeTz); } return $date; @@ -148,7 +150,7 @@ trait Creator $instance = new static($date->format('Y-m-d H:i:s.u'), $date->getTimezone()); - if ($date instanceof CarbonInterface || $date instanceof Options) { + if ($date instanceof CarbonInterface) { $settings = $date->getSettings(); if (!$date->hasLocalTranslator()) { @@ -184,7 +186,13 @@ trait Creator try { return new static($time, $tz); } catch (Exception $exception) { - $date = @static::now($tz)->change($time); + // @codeCoverageIgnoreStart + try { + $date = @static::now($tz)->change($time); + } catch (DateMalformedStringException $ignoredException) { + $date = null; + } + // @codeCoverageIgnoreEnd if (!$date) { throw new InvalidFormatException("Could not parse '$time': ".$exception->getMessage(), 0, $exception); @@ -354,13 +362,13 @@ trait Creator * If $hour is not null then the default values for $minute and $second * will be 0. * - * @param int|null $year - * @param int|null $month - * @param int|null $day - * @param int|null $hour - * @param int|null $minute - * @param int|null $second - * @param DateTimeZone|string|null $tz + * @param DateTimeInterface|int|null $year + * @param int|null $month + * @param int|null $day + * @param int|null $hour + * @param int|null $minute + * @param int|null $second + * @param DateTimeZone|string|null $tz * * @throws InvalidFormatException * @@ -368,7 +376,7 @@ trait Creator */ public static function create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $tz = null) { - if (\is_string($year) && !is_numeric($year) || $year instanceof DateTimeInterface) { + if ((\is_string($year) && !is_numeric($year)) || $year instanceof DateTimeInterface) { return static::parse($year, $tz ?: (\is_string($month) || $month instanceof DateTimeZone ? $month : null)); } @@ -634,6 +642,10 @@ trait Creator $time = preg_replace('/^(.*)(am|pm|AM|PM)(.*)$/U', '$1$3 $2', $time); } + if ($tz === false) { + $tz = null; + } + // First attempt to create an instance, so that error messages are based on the unmodified format. $date = self::createFromFormatAndTimezone($format, $time, $tz); $lastErrors = parent::getLastErrors(); @@ -651,12 +663,14 @@ trait Creator $tz = clone $mock->getTimezone(); } - // Set microseconds to zero to match behavior of DateTime::createFromFormat() - // See https://bugs.php.net/bug.php?id=74332 - $mock = $mock->copy()->microsecond(0); + $mock = $mock->copy(); // Prepend mock datetime only if the format does not contain non escaped unix epoch reset flag. if (!preg_match("/{$nonEscaped}[!|]/", $format)) { + if (preg_match('/[HhGgisvuB]/', $format)) { + $mock = $mock->setTime(0, 0); + } + $format = static::MOCK_DATETIME_FORMAT.' '.$format; $time = ($mock instanceof self ? $mock->rawFormat(static::MOCK_DATETIME_FORMAT) : $mock->format(static::MOCK_DATETIME_FORMAT)).' '.$time; } @@ -862,6 +876,19 @@ trait Creator */ public static function createFromLocaleFormat($format, $locale, $time, $tz = null) { + $format = preg_replace_callback( + '/(?:\\\\[a-zA-Z]|[bfkqCEJKQRV]){2,}/', + static function (array $match) use ($locale): string { + $word = str_replace('\\', '', $match[0]); + $translatedWord = static::translateTimeString($word, $locale, 'en'); + + return $word === $translatedWord + ? $match[0] + : preg_replace('/[a-zA-Z]/', '\\\\$0', $translatedWord); + }, + $format + ); + return static::rawCreateFromFormat($format, static::translateTimeString($time, $locale, 'en'), $tz); } @@ -907,9 +934,9 @@ trait Creator if (\is_string($var)) { $var = trim($var); - if (!preg_match('/^P[0-9T]/', $var) && - !preg_match('/^R[0-9]/', $var) && - preg_match('/[a-z0-9]/i', $var) + if (!preg_match('/^P[\dT]/', $var) && + !preg_match('/^R\d/', $var) && + preg_match('/[a-z\d]/i', $var) ) { $date = static::parse($var); } @@ -921,13 +948,20 @@ trait Creator /** * Set last errors. * - * @param array $lastErrors + * @param array|bool $lastErrors * * @return void */ - private static function setLastErrors(array $lastErrors) + private static function setLastErrors($lastErrors) { - static::$lastErrors = $lastErrors; + if (\is_array($lastErrors) || $lastErrors === false) { + static::$lastErrors = \is_array($lastErrors) ? $lastErrors : [ + 'warning_count' => 0, + 'warnings' => [], + 'error_count' => 0, + 'errors' => [], + ]; + } } /** diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Date.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Date.php index 8c8af6fb0..8ae5c1781 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Date.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Date.php @@ -532,6 +532,7 @@ trait Date use Creator; use Difference; use Macro; + use MagicParameter; use Modifiers; use Mutability; use ObjectInitialisation; @@ -641,9 +642,11 @@ trait Date /** * List of minimum and maximums for each unit. * + * @param int $daysInMonth + * * @return array */ - protected static function getRangesByUnit() + protected static function getRangesByUnit(int $daysInMonth = 31): array { return [ // @call roundUnit @@ -651,7 +654,7 @@ trait Date // @call roundUnit 'month' => [1, static::MONTHS_PER_YEAR], // @call roundUnit - 'day' => [1, 31], + 'day' => [1, $daysInMonth], // @call roundUnit 'hour' => [0, static::HOURS_PER_DAY - 1], // @call roundUnit @@ -940,7 +943,7 @@ trait Date case $name === 'millisecond': // @property int case $name === 'milli': - return (int) floor($this->rawFormat('u') / 1000); + return (int) floor(((int) $this->rawFormat('u')) / 1000); // @property int 1 through 53 case $name === 'week': @@ -1250,7 +1253,7 @@ trait Date protected function getTranslatedFormByRegExp($baseKey, $keySuffix, $context, $subKey, $defaultValue) { $key = $baseKey.$keySuffix; - $standaloneKey = "${key}_standalone"; + $standaloneKey = "{$key}_standalone"; $baseTranslation = $this->getTranslationMessage($key); if ($baseTranslation instanceof Closure) { @@ -1259,7 +1262,7 @@ trait Date if ( $this->getTranslationMessage("$standaloneKey.$subKey") && - (!$context || ($regExp = $this->getTranslationMessage("${baseKey}_regexp")) && !preg_match($regExp, $context)) + (!$context || (($regExp = $this->getTranslationMessage("{$baseKey}_regexp")) && !preg_match($regExp, $context))) ) { $key = $standaloneKey; } @@ -1354,9 +1357,14 @@ trait Date */ public function weekday($value = null) { - $dayOfWeek = ($this->dayOfWeek + 7 - (int) ($this->getTranslationMessage('first_day_of_week') ?? 0)) % 7; + if ($value === null) { + return $this->dayOfWeek; + } - return $value === null ? $dayOfWeek : $this->addDays($value - $dayOfWeek); + $firstDay = (int) ($this->getTranslationMessage('first_day_of_week') ?? 0); + $dayOfWeek = ($this->dayOfWeek + 7 - $firstDay) % 7; + + return $this->addDays((($value + 7 - $firstDay) % 7) - $dayOfWeek); } /** @@ -1373,6 +1381,39 @@ trait Date return $value === null ? $dayOfWeekIso : $this->addDays($value - $dayOfWeekIso); } + /** + * Return the number of days since the start of the week (using the current locale or the first parameter + * if explicitly given). + * + * @param int|null $weekStartsAt optional start allow you to specify the day of week to use to start the week, + * if not provided, start of week is inferred from the locale + * (Sunday for en_US, Monday for de_DE, etc.) + * + * @return int + */ + public function getDaysFromStartOfWeek(int $weekStartsAt = null): int + { + $firstDay = (int) ($weekStartsAt ?? $this->getTranslationMessage('first_day_of_week') ?? 0); + + return ($this->dayOfWeek + 7 - $firstDay) % 7; + } + + /** + * Set the day (keeping the current time) to the start of the week + the number of days passed as the first + * parameter. First day of week is driven by the locale unless explicitly set with the second parameter. + * + * @param int $numberOfDays number of days to add after the start of the current week + * @param int|null $weekStartsAt optional start allow you to specify the day of week to use to start the week, + * if not provided, start of week is inferred from the locale + * (Sunday for en_US, Monday for de_DE, etc.) + * + * @return static + */ + public function setDaysFromStartOfWeek(int $numberOfDays, int $weekStartsAt = null) + { + return $this->addDays($numberOfDays - $this->getDaysFromStartOfWeek($weekStartsAt)); + } + /** * Set any unit to a new value without overflowing current other unit given. * @@ -1848,9 +1889,18 @@ trait Date $format = preg_replace('#(?toDateTimeString())); + $time = strtotime($this->toDateTimeString()); + $formatted = ($this->localStrictModeEnabled ?? static::isStrictModeEnabled()) + ? strftime($format, $time) + : @strftime($format, $time); - return static::$utf8 ? utf8_encode($formatted) : $formatted; + return static::$utf8 + ? ( + \function_exists('mb_convert_encoding') + ? mb_convert_encoding($formatted, 'UTF-8', mb_list_encodings()) + : utf8_encode($formatted) + ) + : $formatted; } /** @@ -1869,6 +1919,10 @@ trait Date 'LL' => $this->getTranslationMessage('formats.LL', $locale, 'MMMM D, YYYY'), 'LLL' => $this->getTranslationMessage('formats.LLL', $locale, 'MMMM D, YYYY h:mm A'), 'LLLL' => $this->getTranslationMessage('formats.LLLL', $locale, 'dddd, MMMM D, YYYY h:mm A'), + 'l' => $this->getTranslationMessage('formats.l', $locale), + 'll' => $this->getTranslationMessage('formats.ll', $locale), + 'lll' => $this->getTranslationMessage('formats.lll', $locale), + 'llll' => $this->getTranslationMessage('formats.llll', $locale), ]; } @@ -2152,7 +2206,7 @@ trait Date $input = mb_substr($format, $i); - if (preg_match('/^(LTS|LT|[Ll]{1,4})/', $input, $match)) { + if (preg_match('/^(LTS|LT|l{1,4}|L{1,4})/', $input, $match)) { if ($formats === null) { $formats = $this->getIsoFormats(); } @@ -2256,6 +2310,7 @@ trait Date 'c' => true, 'r' => true, 'U' => true, + 'T' => true, ]; } @@ -2359,7 +2414,7 @@ trait Date $symbol = $second < 0 ? '-' : '+'; $minute = abs($second) / static::SECONDS_PER_MINUTE; $hour = str_pad((string) floor($minute / static::MINUTES_PER_HOUR), 2, '0', STR_PAD_LEFT); - $minute = str_pad((string) ($minute % static::MINUTES_PER_HOUR), 2, '0', STR_PAD_LEFT); + $minute = str_pad((string) (((int) $minute) % static::MINUTES_PER_HOUR), 2, '0', STR_PAD_LEFT); return "$symbol$hour$separator$minute"; } @@ -2479,7 +2534,7 @@ trait Date return 'millennia'; } - return "${unit}s"; + return "{$unit}s"; } protected function executeCallable($macro, ...$parameters) @@ -2566,7 +2621,7 @@ trait Date if (str_starts_with($unit, 'is')) { $word = substr($unit, 2); - if (\in_array($word, static::$days)) { + if (\in_array($word, static::$days, true)) { return $this->isDayOfWeek($word); } @@ -2594,7 +2649,7 @@ trait Date $unit = strtolower(substr($unit, 3)); } - if (\in_array($unit, static::$units)) { + if (\in_array($unit, static::$units, true)) { return $this->setUnit($unit, ...$parameters); } @@ -2604,7 +2659,7 @@ trait Date if (str_starts_with($unit, 'Real')) { $unit = static::singularUnit(substr($unit, 4)); - return $this->{"${action}RealUnit"}($unit, ...$parameters); + return $this->{"{$action}RealUnit"}($unit, ...$parameters); } if (preg_match('/^(Month|Quarter|Year|Decade|Century|Centurie|Millennium|Millennia)s?(No|With|Without|WithNo)Overflow$/', $unit, $match)) { @@ -2616,7 +2671,7 @@ trait Date } if (static::isModifiableUnit($unit)) { - return $this->{"${action}Unit"}($unit, $parameters[0] ?? 1, $overflow); + return $this->{"{$action}Unit"}($unit, $this->getMagicParameter($parameters, 0, 'value', 1), $overflow); } $sixFirstLetters = substr($unit, 0, 6); @@ -2655,7 +2710,11 @@ trait Date try { $unit = static::singularUnit(substr($method, 0, -5)); - return $this->range($parameters[0] ?? $this, $parameters[1] ?? 1, $unit); + return $this->range( + $this->getMagicParameter($parameters, 0, 'endDate', $this), + $this->getMagicParameter($parameters, 1, 'factor', 1), + $unit + ); } catch (InvalidArgumentException $exception) { // Try macros } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Difference.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Difference.php index cce1d2c3f..ab5b65d23 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Difference.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Difference.php @@ -83,9 +83,9 @@ trait Difference * * @return CarbonInterval */ - protected static function fixDiffInterval(DateInterval $diff, $absolute) + protected static function fixDiffInterval(DateInterval $diff, $absolute, array $skip = []) { - $diff = CarbonInterval::instance($diff); + $diff = CarbonInterval::instance($diff, $skip); // Work-around for https://bugs.php.net/bug.php?id=77145 // @codeCoverageIgnoreStart @@ -148,9 +148,9 @@ trait Difference * * @return CarbonInterval */ - public function diffAsCarbonInterval($date = null, $absolute = true) + public function diffAsCarbonInterval($date = null, $absolute = true, array $skip = []) { - return static::fixDiffInterval($this->diff($this->resolveCarbon($date), $absolute), $absolute); + return static::fixDiffInterval($this->diff($this->resolveCarbon($date), $absolute), $absolute, $skip); } /** @@ -189,9 +189,21 @@ trait Difference */ public function diffInMonths($date = null, $absolute = true) { - $date = $this->resolveCarbon($date); + $date = $this->resolveCarbon($date)->avoidMutation()->tz($this->tz); - return $this->diffInYears($date, $absolute) * static::MONTHS_PER_YEAR + (int) $this->diff($date, $absolute)->format('%r%m'); + [$yearStart, $monthStart, $dayStart] = explode('-', $this->format('Y-m-dHisu')); + [$yearEnd, $monthEnd, $dayEnd] = explode('-', $date->format('Y-m-dHisu')); + + $diff = (((int) $yearEnd) - ((int) $yearStart)) * static::MONTHS_PER_YEAR + + ((int) $monthEnd) - ((int) $monthStart); + + if ($diff > 0) { + $diff -= ($dayStart > $dayEnd ? 1 : 0); + } elseif ($diff < 0) { + $diff += ($dayStart < $dayEnd ? 1 : 0); + } + + return $absolute ? abs($diff) : $diff; } /** @@ -286,9 +298,9 @@ trait Difference */ public function diffInWeekdays($date = null, $absolute = true) { - return $this->diffInDaysFiltered(function (CarbonInterface $date) { + return $this->diffInDaysFiltered(static function (CarbonInterface $date) { return $date->isWeekday(); - }, $date, $absolute); + }, $this->resolveCarbon($date)->avoidMutation()->modify($this->format('H:i:s.u')), $absolute); } /** @@ -301,9 +313,9 @@ trait Difference */ public function diffInWeekendDays($date = null, $absolute = true) { - return $this->diffInDaysFiltered(function (CarbonInterface $date) { + return $this->diffInDaysFiltered(static function (CarbonInterface $date) { return $date->isWeekend(); - }, $date, $absolute); + }, $this->resolveCarbon($date)->avoidMutation()->modify($this->format('H:i:s.u')), $absolute); } /** @@ -472,7 +484,7 @@ trait Difference */ public function floatDiffInSeconds($date = null, $absolute = true) { - return $this->diffInMicroseconds($date, $absolute) / static::MICROSECONDS_PER_SECOND; + return (float) ($this->diffInMicroseconds($date, $absolute) / static::MICROSECONDS_PER_SECOND); } /** @@ -830,8 +842,9 @@ trait Difference $intSyntax = $intSyntax === static::DIFF_RELATIVE_AUTO && $other === null ? static::DIFF_RELATIVE_TO_NOW : $intSyntax; $parts = min(7, max(1, (int) $parts)); + $skip = \is_array($syntax) ? ($syntax['skip'] ?? []) : []; - return $this->diffAsCarbonInterval($other, false) + return $this->diffAsCarbonInterval($other, false, (array) $skip) ->setLocalTranslator($this->getLocalTranslator()) ->forHumans($syntax, (bool) $short, $parts, $options ?? $this->localHumanDiffOptions ?? static::getHumanDiffOptions()); } @@ -1161,7 +1174,7 @@ trait Difference version_compare(PHP_VERSION, '8.1.0-dev', '<') && abs($interval->d - $daysDiff) === 1 ) { - $daysDiff = abs($interval->d); + $daysDiff = abs($interval->d); // @codeCoverageIgnore } return $daysDiff * $sign; diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/IntervalRounding.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/IntervalRounding.php index 4cd66b676..f069c280d 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/IntervalRounding.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/IntervalRounding.php @@ -40,7 +40,7 @@ trait IntervalRounding $unit = 'second'; if ($precision instanceof DateInterval) { - $precision = (string) CarbonInterval::instance($precision); + $precision = (string) CarbonInterval::instance($precision, [], true); } if (\is_string($precision) && preg_match('/^\s*(?\d+)?\s*(?\w+)(?\W.*)?$/', $precision, $match)) { diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Localization.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Localization.php index ddd2b4e98..46aff113e 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Localization.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Localization.php @@ -23,12 +23,16 @@ use Symfony\Component\Translation\TranslatorInterface; use Symfony\Contracts\Translation\LocaleAwareInterface; use Symfony\Contracts\Translation\TranslatorInterface as ContractsTranslatorInterface; -if (!interface_exists('Symfony\\Component\\Translation\\TranslatorInterface')) { +// @codeCoverageIgnoreStart +if (interface_exists('Symfony\\Contracts\\Translation\\TranslatorInterface') && + !interface_exists('Symfony\\Component\\Translation\\TranslatorInterface') +) { class_alias( 'Symfony\\Contracts\\Translation\\TranslatorInterface', 'Symfony\\Component\\Translation\\TranslatorInterface' ); } +// @codeCoverageIgnoreEnd /** * Trait Localization. @@ -355,6 +359,13 @@ trait Localization $weekdays = $messages['weekdays'] ?? []; $meridiem = $messages['meridiem'] ?? ['AM', 'PM']; + if (isset($messages['ordinal_words'])) { + $timeString = self::replaceOrdinalWords( + $timeString, + $key === 'from' ? array_flip($messages['ordinal_words']) : $messages['ordinal_words'] + ); + } + if ($key === 'from') { foreach (['months', 'weekdays'] as $variable) { $list = $messages[$variable.'_standalone'] ?? null; @@ -454,7 +465,7 @@ trait Localization } } - $this->setLocalTranslator($translator); + $this->localTranslator = $translator; } return $this; @@ -555,17 +566,13 @@ trait Localization public static function localeHasShortUnits($locale) { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { - return $newLocale && - ( - ($y = static::translateWith($translator, 'y')) !== 'y' && - $y !== static::translateWith($translator, 'year') - ) || ( - ($y = static::translateWith($translator, 'd')) !== 'd' && + return ($newLocale && (($y = static::translateWith($translator, 'y')) !== 'y' && $y !== static::translateWith($translator, 'year'))) || ( + ($y = static::translateWith($translator, 'd')) !== 'd' && $y !== static::translateWith($translator, 'day') - ) || ( - ($y = static::translateWith($translator, 'h')) !== 'h' && + ) || ( + ($y = static::translateWith($translator, 'h')) !== 'h' && $y !== static::translateWith($translator, 'hour') - ); + ); }); } @@ -734,7 +741,7 @@ trait Localization } if ($translator && !($translator instanceof LocaleAwareInterface || method_exists($translator, 'getLocale'))) { - throw new NotLocaleAwareException($translator); + throw new NotLocaleAwareException($translator); // @codeCoverageIgnore } return $translator; @@ -823,4 +830,11 @@ trait Localization return $list; } + + private static function replaceOrdinalWords(string $timeString, array $ordinalWords): string + { + return preg_replace_callback('/(? + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Traits; + +/** + * Trait MagicParameter. + * + * Allows to retrieve parameter in magic calls by index or name. + */ +trait MagicParameter +{ + private function getMagicParameter(array $parameters, int $index, string $key, $default) + { + if (\array_key_exists($index, $parameters)) { + return $parameters[$index]; + } + + if (\array_key_exists($key, $parameters)) { + return $parameters[$key]; + } + + return $default; + } +} diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Mixin.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Mixin.php index 88b251df4..582245456 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Mixin.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Mixin.php @@ -11,6 +11,9 @@ namespace Carbon\Traits; +use Carbon\CarbonInterface; +use Carbon\CarbonInterval; +use Carbon\CarbonPeriod; use Closure; use Generator; use ReflectionClass; @@ -99,12 +102,13 @@ trait Mixin { $context = eval(self::getAnonymousClassCodeForTrait($trait)); $className = \get_class($context); + $baseClass = static::class; foreach (self::getMixableMethods($context) as $name) { $closureBase = Closure::fromCallable([$context, $name]); - static::macro($name, function () use ($closureBase, $className) { - /** @phpstan-ignore-next-line */ + static::macro($name, function (...$parameters) use ($closureBase, $className, $baseClass) { + $downContext = isset($this) ? ($this) : new $baseClass(); $context = isset($this) ? $this->cast($className) : new $className(); try { @@ -117,7 +121,48 @@ trait Mixin // in case of errors not converted into exceptions $closure = $closure ?: $closureBase; - return $closure(...\func_get_args()); + $result = $closure(...$parameters); + + if (!($result instanceof $className)) { + return $result; + } + + if ($downContext instanceof CarbonInterface && $result instanceof CarbonInterface) { + if ($context !== $result) { + $downContext = $downContext->copy(); + } + + return $downContext + ->setTimezone($result->getTimezone()) + ->modify($result->format('Y-m-d H:i:s.u')) + ->settings($result->getSettings()); + } + + if ($downContext instanceof CarbonInterval && $result instanceof CarbonInterval) { + if ($context !== $result) { + $downContext = $downContext->copy(); + } + + $downContext->copyProperties($result); + self::copyStep($downContext, $result); + self::copyNegativeUnits($downContext, $result); + + return $downContext->settings($result->getSettings()); + } + + if ($downContext instanceof CarbonPeriod && $result instanceof CarbonPeriod) { + if ($context !== $result) { + $downContext = $downContext->copy(); + } + + return $downContext + ->setDates($result->getStartDate(), $result->getEndDate()) + ->setRecurrences($result->getRecurrences()) + ->setOptions($result->getOptions()) + ->settings($result->getSettings()); + } + + return $result; }); } } @@ -151,22 +196,12 @@ trait Mixin protected static function bindMacroContext($context, callable $callable) { static::$macroContextStack[] = $context; - $exception = null; - $result = null; try { - $result = $callable(); - } catch (Throwable $throwable) { - $exception = $throwable; + return $callable(); + } finally { + array_pop(static::$macroContextStack); } - - array_pop(static::$macroContextStack); - - if ($exception) { - throw $exception; - } - - return $result; } /** diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Modifiers.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Modifiers.php index 164dbbd10..39343d8fa 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Modifiers.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Modifiers.php @@ -75,7 +75,7 @@ trait Modifiers * * @param string|int|null $modifier * - * @return static + * @return static|false */ public function next($modifier = null) { @@ -157,7 +157,7 @@ trait Modifiers * * @param string|int|null $modifier * - * @return static + * @return static|false */ public function previous($modifier = null) { @@ -451,7 +451,7 @@ trait Modifiers * * @param string $modifier * - * @return static + * @return static|false */ public function change($modifier) { diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Options.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Options.php index 0ddee8dd6..48f973977 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Options.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Options.php @@ -22,7 +22,7 @@ use Throwable; * * Depends on the following methods: * - * @method \Carbon\Carbon|\Carbon\CarbonImmutable shiftTimezone($timezone) Set the timezone + * @method static shiftTimezone($timezone) Set the timezone */ trait Options { @@ -422,7 +422,7 @@ trait Options foreach ($map as $property => $key) { $value = $this->$property ?? null; - if ($value !== null) { + if ($value !== null && ($key !== 'locale' || $value !== 'en' || $this->localTranslator)) { $settings[$key] = $value; } } @@ -437,11 +437,11 @@ trait Options */ public function __debugInfo() { - $infos = array_filter(get_object_vars($this), function ($var) { + $infos = array_filter(get_object_vars($this), static function ($var) { return $var; }); - foreach (['dumpProperties', 'constructedObjectId'] as $property) { + foreach (['dumpProperties', 'constructedObjectId', 'constructed'] as $property) { if (isset($infos[$property])) { unset($infos[$property]); } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Rounding.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Rounding.php index 33062397f..85ff5a711 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Rounding.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Rounding.php @@ -52,12 +52,11 @@ trait Rounding 'millisecond' => [1000, 'microsecond'], ]; $normalizedUnit = static::singularUnit($unit); - $ranges = array_merge(static::getRangesByUnit(), [ + $ranges = array_merge(static::getRangesByUnit($this->daysInMonth), [ // @call roundUnit 'microsecond' => [0, 999999], ]); $factor = 1; - $initialMonth = $this->month; if ($normalizedUnit === 'week') { $normalizedUnit = 'day'; @@ -77,12 +76,15 @@ trait Rounding $found = false; $fraction = 0; $arguments = null; + $initialValue = null; $factor = $this->year < 0 ? -1 : 1; $changes = []; + $minimumInc = null; foreach ($ranges as $unit => [$minimum, $maximum]) { if ($normalizedUnit === $unit) { $arguments = [$this->$unit, $minimum]; + $initialValue = $this->$unit; $fraction = $precision - floor($precision); $found = true; @@ -93,7 +95,23 @@ trait Rounding $delta = $maximum + 1 - $minimum; $factor /= $delta; $fraction *= $delta; - $arguments[0] += $this->$unit * $factor; + $inc = ($this->$unit - $minimum) * $factor; + + if ($inc !== 0.0) { + $minimumInc = $minimumInc ?? ($arguments[0] / pow(2, 52)); + + // If value is still the same when adding a non-zero increment/decrement, + // it means precision got lost in the addition + if (abs($inc) < $minimumInc) { + $inc = $minimumInc * ($inc < 0 ? -1 : 1); + } + + // If greater than $precision, assume precision loss caused an overflow + if ($function !== 'floor' || abs($arguments[0] + $inc - $initialValue) >= $precision) { + $arguments[0] += $inc; + } + } + $changes[$unit] = round( $minimum + ($fraction ? $fraction * $function(($this->$unit - $minimum) / $fraction) : 0) ); @@ -111,16 +129,13 @@ trait Rounding $normalizedValue = floor($function(($value - $minimum) / $precision) * $precision + $minimum); /** @var CarbonInterface $result */ - $result = $this->$normalizedUnit($normalizedValue); + $result = $this; foreach ($changes as $unit => $value) { $result = $result->$unit($value); } - return $normalizedUnit === 'month' && $precision <= 1 && abs($result->month - $initialMonth) === 2 - // Re-run the change in case an overflow occurred - ? $result->$normalizedUnit($normalizedValue) - : $result; + return $result->$normalizedUnit($normalizedValue); } /** diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Serialization.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Serialization.php index eebc69bd0..c1d5c5e13 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Serialization.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Serialization.php @@ -120,6 +120,8 @@ trait Serialization /** * Returns the list of properties to dump on serialize() called on. * + * Only used by PHP < 7.4. + * * @return array */ public function __sleep() @@ -134,22 +136,70 @@ trait Serialization return $properties; } + /** + * Returns the values to dump on serialize() called on. + * + * Only used by PHP >= 7.4. + * + * @return array + */ + public function __serialize(): array + { + // @codeCoverageIgnoreStart + if (isset($this->timezone_type, $this->timezone, $this->date)) { + return [ + 'date' => $this->date ?? null, + 'timezone_type' => $this->timezone_type, + 'timezone' => $this->timezone ?? null, + ]; + } + // @codeCoverageIgnoreEnd + + $timezone = $this->getTimezone(); + $export = [ + 'date' => $this->format('Y-m-d H:i:s.u'), + 'timezone_type' => $timezone->getType(), + 'timezone' => $timezone->getName(), + ]; + + // @codeCoverageIgnoreStart + if (\extension_loaded('msgpack') && isset($this->constructedObjectId)) { + $export['dumpDateProperties'] = [ + 'date' => $this->format('Y-m-d H:i:s.u'), + 'timezone' => serialize($this->timezone ?? null), + ]; + } + // @codeCoverageIgnoreEnd + + if ($this->localTranslator ?? null) { + $export['dumpLocale'] = $this->locale ?? null; + } + + return $export; + } + /** * Set locale if specified on unserialize() called. * + * Only used by PHP < 7.4. + * * @return void */ #[ReturnTypeWillChange] public function __wakeup() { - if (get_parent_class() && method_exists(parent::class, '__wakeup')) { + if (parent::class && method_exists(parent::class, '__wakeup')) { // @codeCoverageIgnoreStart try { parent::__wakeup(); } catch (Throwable $exception) { - // FatalError occurs when calling msgpack_unpack() in PHP 7.4 or later. - ['date' => $date, 'timezone' => $timezone] = $this->dumpDateProperties; - parent::__construct($date, unserialize($timezone)); + try { + // FatalError occurs when calling msgpack_unpack() in PHP 7.4 or later. + ['date' => $date, 'timezone' => $timezone] = $this->dumpDateProperties; + parent::__construct($date, unserialize($timezone)); + } catch (Throwable $ignoredException) { + throw $exception; + } } // @codeCoverageIgnoreEnd } @@ -164,6 +214,38 @@ trait Serialization $this->cleanupDumpProperties(); } + /** + * Set locale if specified on unserialize() called. + * + * Only used by PHP >= 7.4. + * + * @return void + */ + public function __unserialize(array $data): void + { + // @codeCoverageIgnoreStart + try { + $this->__construct($data['date'] ?? null, $data['timezone'] ?? null); + } catch (Throwable $exception) { + if (!isset($data['dumpDateProperties']['date'], $data['dumpDateProperties']['timezone'])) { + throw $exception; + } + + try { + // FatalError occurs when calling msgpack_unpack() in PHP 7.4 or later. + ['date' => $date, 'timezone' => $timezone] = $data['dumpDateProperties']; + $this->__construct($date, unserialize($timezone)); + } catch (Throwable $ignoredException) { + throw $exception; + } + } + // @codeCoverageIgnoreEnd + + if (isset($data['dumpLocale'])) { + $this->locale($data['dumpLocale']); + } + } + /** * Prepare the object for JSON serialization. * @@ -207,11 +289,15 @@ trait Serialization */ public function cleanupDumpProperties() { - foreach ($this->dumpProperties as $property) { - if (isset($this->$property)) { - unset($this->$property); + // @codeCoverageIgnoreStart + if (PHP_VERSION < 8.2) { + foreach ($this->dumpProperties as $property) { + if (isset($this->$property)) { + unset($this->$property); + } } } + // @codeCoverageIgnoreEnd return $this; } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Test.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Test.php index c86faa74c..f23c72e8f 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Test.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Test.php @@ -28,7 +28,7 @@ trait Test /** * A test Carbon instance to be returned when now instances are created. * - * @var static + * @var Closure|static|null */ protected static $testNow; @@ -59,15 +59,13 @@ trait Test * * /!\ Use this method for unit tests only. * - * @param Closure|static|string|false|null $testNow real or mock Carbon instance + * @param DateTimeInterface|Closure|static|string|false|null $testNow real or mock Carbon instance */ public static function setTestNow($testNow = null) { - if ($testNow === false) { - $testNow = null; - } - - static::$testNow = \is_string($testNow) ? static::parse($testNow) : $testNow; + static::$testNow = $testNow instanceof self || $testNow instanceof Closure + ? $testNow + : static::make($testNow); } /** @@ -87,7 +85,7 @@ trait Test * * /!\ Use this method for unit tests only. * - * @param Closure|static|string|false|null $testNow real or mock Carbon instance + * @param DateTimeInterface|Closure|static|string|false|null $testNow real or mock Carbon instance */ public static function setTestNowAndTimezone($testNow = null, $tz = null) { @@ -121,16 +119,22 @@ trait Test * * /!\ Use this method for unit tests only. * - * @param Closure|static|string|false|null $testNow real or mock Carbon instance - * @param Closure|null $callback + * @template T * - * @return mixed + * @param DateTimeInterface|Closure|static|string|false|null $testNow real or mock Carbon instance + * @param Closure(): T $callback + * + * @return T */ - public static function withTestNow($testNow = null, $callback = null) + public static function withTestNow($testNow, $callback) { static::setTestNow($testNow); - $result = $callback(); - static::setTestNow(); + + try { + $result = $callback(); + } finally { + static::setTestNow(); + } return $result; } diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Timestamp.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Timestamp.php index 2cb5c48d7..88a465c93 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Timestamp.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Timestamp.php @@ -63,7 +63,7 @@ trait Timestamp public static function createFromTimestampMsUTC($timestamp) { [$milliseconds, $microseconds] = self::getIntegerAndDecimalParts($timestamp, 3); - $sign = $milliseconds < 0 || $milliseconds === 0.0 && $microseconds < 0 ? -1 : 1; + $sign = $milliseconds < 0 || ($milliseconds === 0.0 && $microseconds < 0) ? -1 : 1; $milliseconds = abs($milliseconds); $microseconds = $sign * abs($microseconds) + static::MICROSECONDS_PER_MILLISECOND * ($milliseconds % static::MILLISECONDS_PER_SECOND); $seconds = $sign * floor($milliseconds / static::MILLISECONDS_PER_SECOND); @@ -125,7 +125,7 @@ trait Timestamp */ public function getPreciseTimestamp($precision = 6) { - return round($this->rawFormat('Uu') / pow(10, 6 - $precision)); + return round(((float) $this->rawFormat('Uu')) / pow(10, 6 - $precision)); } /** @@ -182,7 +182,7 @@ trait Timestamp $integer = 0; $decimal = 0; - foreach (preg_split('`[^0-9.]+`', $numbers) as $chunk) { + foreach (preg_split('`[^\d.]+`', $numbers) as $chunk) { [$integerPart, $decimalPart] = explode('.', "$chunk."); $integer += (int) $integerPart; diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/ToStringFormat.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/ToStringFormat.php new file mode 100644 index 000000000..a81164f99 --- /dev/null +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/ToStringFormat.php @@ -0,0 +1,56 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Carbon\Traits; + +use Closure; + +/** + * Trait ToStringFormat. + * + * Handle global format customization for string cast of the object. + */ +trait ToStringFormat +{ + /** + * Format to use for __toString method when type juggling occurs. + * + * @var string|Closure|null + */ + protected static $toStringFormat; + + /** + * Reset the format used to the default when type juggling a Carbon instance to a string + * + * @return void + */ + public static function resetToStringFormat() + { + static::setToStringFormat(null); + } + + /** + * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. + * You should rather let Carbon object being cast to string with DEFAULT_TO_STRING_FORMAT, and + * use other method or custom format passed to format() method if you need to dump another string + * format. + * + * Set the default format used when type juggling a Carbon instance to a string. + * + * @param string|Closure|null $format + * + * @return void + */ + public static function setToStringFormat($format) + { + static::$toStringFormat = $format; + } +} diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Units.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Units.php index 2902a8b10..5be14ec7e 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Units.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Traits/Units.php @@ -17,6 +17,7 @@ use Carbon\CarbonInterval; use Carbon\Exceptions\UnitException; use Closure; use DateInterval; +use DateMalformedStringException; use ReturnTypeWillChange; /** @@ -60,8 +61,6 @@ trait Units case 'millisecond': return $this->addRealUnit('microsecond', $value * static::MICROSECONDS_PER_MILLISECOND); - break; - // @call addRealUnit case 'second': break; @@ -167,7 +166,7 @@ trait Units 'weekday', ]; - return \in_array($unit, $modifiableUnits) || \in_array($unit, static::$units); + return \in_array($unit, $modifiableUnits, true) || \in_array($unit, static::$units, true); } /** @@ -199,7 +198,7 @@ trait Units public function add($unit, $value = 1, $overflow = null) { if (\is_string($unit) && \func_num_args() === 1) { - $unit = CarbonInterval::make($unit); + $unit = CarbonInterval::make($unit, [], true); } if ($unit instanceof CarbonConverterInterface) { @@ -232,6 +231,8 @@ trait Units */ public function addUnit($unit, $value = 1, $overflow = null) { + $originalArgs = \func_get_args(); + $date = $this; if (!is_numeric($value) || !(float) $value) { @@ -264,7 +265,7 @@ trait Units /** @var static $date */ $date = $date->addDays($sign); - while (\in_array($date->dayOfWeek, $weekendDays)) { + while (\in_array($date->dayOfWeek, $weekendDays, true)) { $date = $date->addDays($sign); } } @@ -274,14 +275,14 @@ trait Units } $timeString = $date->toTimeString(); - } elseif ($canOverflow = \in_array($unit, [ + } elseif ($canOverflow = (\in_array($unit, [ 'month', 'year', ]) && ($overflow === false || ( $overflow === null && ($ucUnit = ucfirst($unit).'s') && !($this->{'local'.$ucUnit.'Overflow'} ?? static::{'shouldOverflow'.$ucUnit}()) - ))) { + )))) { $day = $date->day; } @@ -304,16 +305,21 @@ trait Units $unit = 'second'; $value = $second; } - $date = $date->modify("$value $unit"); - if (isset($timeString)) { - $date = $date->setTimeFromTimeString($timeString); - } elseif (isset($canOverflow, $day) && $canOverflow && $day !== $date->day) { - $date = $date->modify('last day of previous month'); + try { + $date = $date->modify("$value $unit"); + + if (isset($timeString)) { + $date = $date->setTimeFromTimeString($timeString); + } elseif (isset($canOverflow, $day) && $canOverflow && $day !== $date->day) { + $date = $date->modify('last day of previous month'); + } + } catch (DateMalformedStringException $ignoredException) { // @codeCoverageIgnore + $date = null; // @codeCoverageIgnore } if (!$date) { - throw new UnitException('Unable to add unit '.var_export(\func_get_args(), true)); + throw new UnitException('Unable to add unit '.var_export($originalArgs, true)); } return $date; @@ -362,7 +368,7 @@ trait Units public function sub($unit, $value = 1, $overflow = null) { if (\is_string($unit) && \func_num_args() === 1) { - $unit = CarbonInterval::make($unit); + $unit = CarbonInterval::make($unit, [], true); } if ($unit instanceof CarbonConverterInterface) { @@ -398,7 +404,7 @@ trait Units public function subtract($unit, $value = 1, $overflow = null) { if (\is_string($unit) && \func_num_args() === 1) { - $unit = CarbonInterval::make($unit); + $unit = CarbonInterval::make($unit, [], true); } return $this->sub($unit, $value, $overflow); diff --git a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/TranslatorImmutable.php b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/TranslatorImmutable.php index ad36c6704..ce6b2f90a 100644 --- a/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/TranslatorImmutable.php +++ b/data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/TranslatorImmutable.php @@ -66,7 +66,7 @@ class TranslatorImmutable extends Translator /** * @codeCoverageIgnore */ - public function setConfigCacheFactory(ConfigCacheFactoryInterface $configCacheFactory) + public function setConfigCacheFactory(ConfigCacheFactoryInterface $configCacheFactory): void { $this->disallowMutation(__METHOD__); diff --git a/data/web/inc/lib/vendor/psr/clock/CHANGELOG.md b/data/web/inc/lib/vendor/psr/clock/CHANGELOG.md new file mode 100644 index 000000000..3cd6b9b75 --- /dev/null +++ b/data/web/inc/lib/vendor/psr/clock/CHANGELOG.md @@ -0,0 +1,11 @@ +# Changelog + +All notable changes to this project will be documented in this file, in reverse chronological order by release. + +## 1.0.0 + +First stable release after PSR-20 acceptance + +## 0.1.0 + +First release diff --git a/data/web/inc/lib/vendor/psr/clock/LICENSE b/data/web/inc/lib/vendor/psr/clock/LICENSE new file mode 100644 index 000000000..be6834212 --- /dev/null +++ b/data/web/inc/lib/vendor/psr/clock/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2017 PHP Framework Interoperability Group + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/data/web/inc/lib/vendor/psr/clock/README.md b/data/web/inc/lib/vendor/psr/clock/README.md new file mode 100644 index 000000000..6ca877eeb --- /dev/null +++ b/data/web/inc/lib/vendor/psr/clock/README.md @@ -0,0 +1,61 @@ +# PSR Clock + +This repository holds the interface for [PSR-20][psr-url]. + +Note that this is not a clock of its own. It is merely an interface that +describes a clock. See the specification for more details. + +## Installation + +```bash +composer require psr/clock +``` + +## Usage + +If you need a clock, you can use the interface like this: + +```php +clock = $clock; + } + + public function doSomething() + { + /** @var DateTimeImmutable $currentDateAndTime */ + $currentDateAndTime = $this->clock->now(); + // do something useful with that information + } +} +``` + +You can then pick one of the [implementations][implementation-url] of the interface to get a clock. + +If you want to implement the interface, you can require this package and +implement `Psr\Clock\ClockInterface` in your code. + +Don't forget to add `psr/clock-implementation` to your `composer.json`s `provides`-section like this: + +```json +{ + "provides": { + "psr/clock-implementation": "1.0" + } +} +``` + +And please read the [specification text][specification-url] for details on the interface. + +[psr-url]: https://www.php-fig.org/psr/psr-20 +[package-url]: https://packagist.org/packages/psr/clock +[implementation-url]: https://packagist.org/providers/psr/clock-implementation +[specification-url]: https://github.com/php-fig/fig-standards/blob/master/proposed/clock.md diff --git a/data/web/inc/lib/vendor/psr/clock/composer.json b/data/web/inc/lib/vendor/psr/clock/composer.json new file mode 100644 index 000000000..77992eda7 --- /dev/null +++ b/data/web/inc/lib/vendor/psr/clock/composer.json @@ -0,0 +1,21 @@ +{ + "name": "psr/clock", + "description": "Common interface for reading the clock.", + "keywords": ["psr", "psr-20", "time", "clock", "now"], + "homepage": "https://github.com/php-fig/clock", + "license": "MIT", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "require": { + "php": "^7.0 || ^8.0" + }, + "autoload": { + "psr-4": { + "Psr\\Clock\\": "src/" + } + } +} diff --git a/data/web/inc/lib/vendor/psr/clock/src/ClockInterface.php b/data/web/inc/lib/vendor/psr/clock/src/ClockInterface.php new file mode 100644 index 000000000..7b6d8d8aa --- /dev/null +++ b/data/web/inc/lib/vendor/psr/clock/src/ClockInterface.php @@ -0,0 +1,13 @@ +=7.0.0", + "psr/http-message": "^1.0" + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/data/web/inc/lib/vendor/psr/http-factory/src/RequestFactoryInterface.php b/data/web/inc/lib/vendor/psr/http-factory/src/RequestFactoryInterface.php new file mode 100644 index 000000000..cb39a08bf --- /dev/null +++ b/data/web/inc/lib/vendor/psr/http-factory/src/RequestFactoryInterface.php @@ -0,0 +1,18 @@ +=5.3.0" + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/data/web/inc/lib/vendor/psr/http-message/src/MessageInterface.php b/data/web/inc/lib/vendor/psr/http-message/src/MessageInterface.php new file mode 100644 index 000000000..dd46e5ec8 --- /dev/null +++ b/data/web/inc/lib/vendor/psr/http-message/src/MessageInterface.php @@ -0,0 +1,187 @@ +getHeaders() as $name => $values) { + * echo $name . ": " . implode(", ", $values); + * } + * + * // Emit headers iteratively: + * foreach ($message->getHeaders() as $name => $values) { + * foreach ($values as $value) { + * header(sprintf('%s: %s', $name, $value), false); + * } + * } + * + * While header names are not case-sensitive, getHeaders() will preserve the + * exact case in which headers were originally specified. + * + * @return string[][] Returns an associative array of the message's headers. Each + * key MUST be a header name, and each value MUST be an array of strings + * for that header. + */ + public function getHeaders(); + + /** + * Checks if a header exists by the given case-insensitive name. + * + * @param string $name Case-insensitive header field name. + * @return bool Returns true if any header names match the given header + * name using a case-insensitive string comparison. Returns false if + * no matching header name is found in the message. + */ + public function hasHeader($name); + + /** + * Retrieves a message header value by the given case-insensitive name. + * + * This method returns an array of all the header values of the given + * case-insensitive header name. + * + * If the header does not appear in the message, this method MUST return an + * empty array. + * + * @param string $name Case-insensitive header field name. + * @return string[] An array of string values as provided for the given + * header. If the header does not appear in the message, this method MUST + * return an empty array. + */ + public function getHeader($name); + + /** + * Retrieves a comma-separated string of the values for a single header. + * + * This method returns all of the header values of the given + * case-insensitive header name as a string concatenated together using + * a comma. + * + * NOTE: Not all header values may be appropriately represented using + * comma concatenation. For such headers, use getHeader() instead + * and supply your own delimiter when concatenating. + * + * If the header does not appear in the message, this method MUST return + * an empty string. + * + * @param string $name Case-insensitive header field name. + * @return string A string of values as provided for the given header + * concatenated together using a comma. If the header does not appear in + * the message, this method MUST return an empty string. + */ + public function getHeaderLine($name); + + /** + * Return an instance with the provided value replacing the specified header. + * + * While header names are case-insensitive, the casing of the header will + * be preserved by this function, and returned from getHeaders(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * new and/or updated header and value. + * + * @param string $name Case-insensitive header field name. + * @param string|string[] $value Header value(s). + * @return static + * @throws \InvalidArgumentException for invalid header names or values. + */ + public function withHeader($name, $value); + + /** + * Return an instance with the specified header appended with the given value. + * + * Existing values for the specified header will be maintained. The new + * value(s) will be appended to the existing list. If the header did not + * exist previously, it will be added. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * new header and/or value. + * + * @param string $name Case-insensitive header field name to add. + * @param string|string[] $value Header value(s). + * @return static + * @throws \InvalidArgumentException for invalid header names or values. + */ + public function withAddedHeader($name, $value); + + /** + * Return an instance without the specified header. + * + * Header resolution MUST be done without case-sensitivity. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that removes + * the named header. + * + * @param string $name Case-insensitive header field name to remove. + * @return static + */ + public function withoutHeader($name); + + /** + * Gets the body of the message. + * + * @return StreamInterface Returns the body as a stream. + */ + public function getBody(); + + /** + * Return an instance with the specified message body. + * + * The body MUST be a StreamInterface object. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return a new instance that has the + * new body stream. + * + * @param StreamInterface $body Body. + * @return static + * @throws \InvalidArgumentException When the body is not valid. + */ + public function withBody(StreamInterface $body); +} diff --git a/data/web/inc/lib/vendor/psr/http-message/src/RequestInterface.php b/data/web/inc/lib/vendor/psr/http-message/src/RequestInterface.php new file mode 100644 index 000000000..a96d4fd63 --- /dev/null +++ b/data/web/inc/lib/vendor/psr/http-message/src/RequestInterface.php @@ -0,0 +1,129 @@ +getQuery()` + * or from the `QUERY_STRING` server param. + * + * @return array + */ + public function getQueryParams(); + + /** + * Return an instance with the specified query string arguments. + * + * These values SHOULD remain immutable over the course of the incoming + * request. They MAY be injected during instantiation, such as from PHP's + * $_GET superglobal, or MAY be derived from some other value such as the + * URI. In cases where the arguments are parsed from the URI, the data + * MUST be compatible with what PHP's parse_str() would return for + * purposes of how duplicate query parameters are handled, and how nested + * sets are handled. + * + * Setting query string arguments MUST NOT change the URI stored by the + * request, nor the values in the server params. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated query string arguments. + * + * @param array $query Array of query string arguments, typically from + * $_GET. + * @return static + */ + public function withQueryParams(array $query); + + /** + * Retrieve normalized file upload data. + * + * This method returns upload metadata in a normalized tree, with each leaf + * an instance of Psr\Http\Message\UploadedFileInterface. + * + * These values MAY be prepared from $_FILES or the message body during + * instantiation, or MAY be injected via withUploadedFiles(). + * + * @return array An array tree of UploadedFileInterface instances; an empty + * array MUST be returned if no data is present. + */ + public function getUploadedFiles(); + + /** + * Create a new instance with the specified uploaded files. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated body parameters. + * + * @param array $uploadedFiles An array tree of UploadedFileInterface instances. + * @return static + * @throws \InvalidArgumentException if an invalid structure is provided. + */ + public function withUploadedFiles(array $uploadedFiles); + + /** + * Retrieve any parameters provided in the request body. + * + * If the request Content-Type is either application/x-www-form-urlencoded + * or multipart/form-data, and the request method is POST, this method MUST + * return the contents of $_POST. + * + * Otherwise, this method may return any results of deserializing + * the request body content; as parsing returns structured content, the + * potential types MUST be arrays or objects only. A null value indicates + * the absence of body content. + * + * @return null|array|object The deserialized body parameters, if any. + * These will typically be an array or object. + */ + public function getParsedBody(); + + /** + * Return an instance with the specified body parameters. + * + * These MAY be injected during instantiation. + * + * If the request Content-Type is either application/x-www-form-urlencoded + * or multipart/form-data, and the request method is POST, use this method + * ONLY to inject the contents of $_POST. + * + * The data IS NOT REQUIRED to come from $_POST, but MUST be the results of + * deserializing the request body content. Deserialization/parsing returns + * structured data, and, as such, this method ONLY accepts arrays or objects, + * or a null value if nothing was available to parse. + * + * As an example, if content negotiation determines that the request data + * is a JSON payload, this method could be used to create a request + * instance with the deserialized parameters. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated body parameters. + * + * @param null|array|object $data The deserialized body data. This will + * typically be in an array or object. + * @return static + * @throws \InvalidArgumentException if an unsupported argument type is + * provided. + */ + public function withParsedBody($data); + + /** + * Retrieve attributes derived from the request. + * + * The request "attributes" may be used to allow injection of any + * parameters derived from the request: e.g., the results of path + * match operations; the results of decrypting cookies; the results of + * deserializing non-form-encoded message bodies; etc. Attributes + * will be application and request specific, and CAN be mutable. + * + * @return array Attributes derived from the request. + */ + public function getAttributes(); + + /** + * Retrieve a single derived request attribute. + * + * Retrieves a single derived request attribute as described in + * getAttributes(). If the attribute has not been previously set, returns + * the default value as provided. + * + * This method obviates the need for a hasAttribute() method, as it allows + * specifying a default value to return if the attribute is not found. + * + * @see getAttributes() + * @param string $name The attribute name. + * @param mixed $default Default value to return if the attribute does not exist. + * @return mixed + */ + public function getAttribute($name, $default = null); + + /** + * Return an instance with the specified derived request attribute. + * + * This method allows setting a single derived request attribute as + * described in getAttributes(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated attribute. + * + * @see getAttributes() + * @param string $name The attribute name. + * @param mixed $value The value of the attribute. + * @return static + */ + public function withAttribute($name, $value); + + /** + * Return an instance that removes the specified derived request attribute. + * + * This method allows removing a single derived request attribute as + * described in getAttributes(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that removes + * the attribute. + * + * @see getAttributes() + * @param string $name The attribute name. + * @return static + */ + public function withoutAttribute($name); +} diff --git a/data/web/inc/lib/vendor/psr/http-message/src/StreamInterface.php b/data/web/inc/lib/vendor/psr/http-message/src/StreamInterface.php new file mode 100644 index 000000000..f68f39126 --- /dev/null +++ b/data/web/inc/lib/vendor/psr/http-message/src/StreamInterface.php @@ -0,0 +1,158 @@ + + * [user-info@]host[:port] + * + * + * If the port component is not set or is the standard port for the current + * scheme, it SHOULD NOT be included. + * + * @see https://tools.ietf.org/html/rfc3986#section-3.2 + * @return string The URI authority, in "[user-info@]host[:port]" format. + */ + public function getAuthority(); + + /** + * Retrieve the user information component of the URI. + * + * If no user information is present, this method MUST return an empty + * string. + * + * If a user is present in the URI, this will return that value; + * additionally, if the password is also present, it will be appended to the + * user value, with a colon (":") separating the values. + * + * The trailing "@" character is not part of the user information and MUST + * NOT be added. + * + * @return string The URI user information, in "username[:password]" format. + */ + public function getUserInfo(); + + /** + * Retrieve the host component of the URI. + * + * If no host is present, this method MUST return an empty string. + * + * The value returned MUST be normalized to lowercase, per RFC 3986 + * Section 3.2.2. + * + * @see http://tools.ietf.org/html/rfc3986#section-3.2.2 + * @return string The URI host. + */ + public function getHost(); + + /** + * Retrieve the port component of the URI. + * + * If a port is present, and it is non-standard for the current scheme, + * this method MUST return it as an integer. If the port is the standard port + * used with the current scheme, this method SHOULD return null. + * + * If no port is present, and no scheme is present, this method MUST return + * a null value. + * + * If no port is present, but a scheme is present, this method MAY return + * the standard port for that scheme, but SHOULD return null. + * + * @return null|int The URI port. + */ + public function getPort(); + + /** + * Retrieve the path component of the URI. + * + * The path can either be empty or absolute (starting with a slash) or + * rootless (not starting with a slash). Implementations MUST support all + * three syntaxes. + * + * Normally, the empty path "" and absolute path "/" are considered equal as + * defined in RFC 7230 Section 2.7.3. But this method MUST NOT automatically + * do this normalization because in contexts with a trimmed base path, e.g. + * the front controller, this difference becomes significant. It's the task + * of the user to handle both "" and "/". + * + * The value returned MUST be percent-encoded, but MUST NOT double-encode + * any characters. To determine what characters to encode, please refer to + * RFC 3986, Sections 2 and 3.3. + * + * As an example, if the value should include a slash ("/") not intended as + * delimiter between path segments, that value MUST be passed in encoded + * form (e.g., "%2F") to the instance. + * + * @see https://tools.ietf.org/html/rfc3986#section-2 + * @see https://tools.ietf.org/html/rfc3986#section-3.3 + * @return string The URI path. + */ + public function getPath(); + + /** + * Retrieve the query string of the URI. + * + * If no query string is present, this method MUST return an empty string. + * + * The leading "?" character is not part of the query and MUST NOT be + * added. + * + * The value returned MUST be percent-encoded, but MUST NOT double-encode + * any characters. To determine what characters to encode, please refer to + * RFC 3986, Sections 2 and 3.4. + * + * As an example, if a value in a key/value pair of the query string should + * include an ampersand ("&") not intended as a delimiter between values, + * that value MUST be passed in encoded form (e.g., "%26") to the instance. + * + * @see https://tools.ietf.org/html/rfc3986#section-2 + * @see https://tools.ietf.org/html/rfc3986#section-3.4 + * @return string The URI query string. + */ + public function getQuery(); + + /** + * Retrieve the fragment component of the URI. + * + * If no fragment is present, this method MUST return an empty string. + * + * The leading "#" character is not part of the fragment and MUST NOT be + * added. + * + * The value returned MUST be percent-encoded, but MUST NOT double-encode + * any characters. To determine what characters to encode, please refer to + * RFC 3986, Sections 2 and 3.5. + * + * @see https://tools.ietf.org/html/rfc3986#section-2 + * @see https://tools.ietf.org/html/rfc3986#section-3.5 + * @return string The URI fragment. + */ + public function getFragment(); + + /** + * Return an instance with the specified scheme. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified scheme. + * + * Implementations MUST support the schemes "http" and "https" case + * insensitively, and MAY accommodate other schemes if required. + * + * An empty scheme is equivalent to removing the scheme. + * + * @param string $scheme The scheme to use with the new instance. + * @return static A new instance with the specified scheme. + * @throws \InvalidArgumentException for invalid or unsupported schemes. + */ + public function withScheme($scheme); + + /** + * Return an instance with the specified user information. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified user information. + * + * Password is optional, but the user information MUST include the + * user; an empty string for the user is equivalent to removing user + * information. + * + * @param string $user The user name to use for authority. + * @param null|string $password The password associated with $user. + * @return static A new instance with the specified user information. + */ + public function withUserInfo($user, $password = null); + + /** + * Return an instance with the specified host. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified host. + * + * An empty host value is equivalent to removing the host. + * + * @param string $host The hostname to use with the new instance. + * @return static A new instance with the specified host. + * @throws \InvalidArgumentException for invalid hostnames. + */ + public function withHost($host); + + /** + * Return an instance with the specified port. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified port. + * + * Implementations MUST raise an exception for ports outside the + * established TCP and UDP port ranges. + * + * A null value provided for the port is equivalent to removing the port + * information. + * + * @param null|int $port The port to use with the new instance; a null value + * removes the port information. + * @return static A new instance with the specified port. + * @throws \InvalidArgumentException for invalid ports. + */ + public function withPort($port); + + /** + * Return an instance with the specified path. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified path. + * + * The path can either be empty or absolute (starting with a slash) or + * rootless (not starting with a slash). Implementations MUST support all + * three syntaxes. + * + * If the path is intended to be domain-relative rather than path relative then + * it must begin with a slash ("/"). Paths not starting with a slash ("/") + * are assumed to be relative to some base path known to the application or + * consumer. + * + * Users can provide both encoded and decoded path characters. + * Implementations ensure the correct encoding as outlined in getPath(). + * + * @param string $path The path to use with the new instance. + * @return static A new instance with the specified path. + * @throws \InvalidArgumentException for invalid paths. + */ + public function withPath($path); + + /** + * Return an instance with the specified query string. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified query string. + * + * Users can provide both encoded and decoded query characters. + * Implementations ensure the correct encoding as outlined in getQuery(). + * + * An empty query string value is equivalent to removing the query string. + * + * @param string $query The query string to use with the new instance. + * @return static A new instance with the specified query string. + * @throws \InvalidArgumentException for invalid query strings. + */ + public function withQuery($query); + + /** + * Return an instance with the specified URI fragment. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified URI fragment. + * + * Users can provide both encoded and decoded fragment characters. + * Implementations ensure the correct encoding as outlined in getFragment(). + * + * An empty fragment value is equivalent to removing the fragment. + * + * @param string $fragment The fragment to use with the new instance. + * @return static A new instance with the specified fragment. + */ + public function withFragment($fragment); + + /** + * Return the string representation as a URI reference. + * + * Depending on which components of the URI are present, the resulting + * string is either a full URI or relative reference according to RFC 3986, + * Section 4.1. The method concatenates the various components of the URI, + * using the appropriate delimiters: + * + * - If a scheme is present, it MUST be suffixed by ":". + * - If an authority is present, it MUST be prefixed by "//". + * - The path can be concatenated without delimiters. But there are two + * cases where the path has to be adjusted to make the URI reference + * valid as PHP does not allow to throw an exception in __toString(): + * - If the path is rootless and an authority is present, the path MUST + * be prefixed by "/". + * - If the path is starting with more than one "/" and no authority is + * present, the starting slashes MUST be reduced to one. + * - If a query is present, it MUST be prefixed by "?". + * - If a fragment is present, it MUST be prefixed by "#". + * + * @see http://tools.ietf.org/html/rfc3986#section-4.1 + * @return string + */ + public function __toString(); +} diff --git a/data/web/inc/lib/vendor/ralouphie/getallheaders/LICENSE b/data/web/inc/lib/vendor/ralouphie/getallheaders/LICENSE new file mode 100644 index 000000000..be5540c2a --- /dev/null +++ b/data/web/inc/lib/vendor/ralouphie/getallheaders/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Ralph Khattar + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/data/web/inc/lib/vendor/ralouphie/getallheaders/README.md b/data/web/inc/lib/vendor/ralouphie/getallheaders/README.md new file mode 100644 index 000000000..9430d76bb --- /dev/null +++ b/data/web/inc/lib/vendor/ralouphie/getallheaders/README.md @@ -0,0 +1,27 @@ +getallheaders +============= + +PHP `getallheaders()` polyfill. Compatible with PHP >= 5.3. + +[![Build Status](https://travis-ci.org/ralouphie/getallheaders.svg?branch=master)](https://travis-ci.org/ralouphie/getallheaders) +[![Coverage Status](https://coveralls.io/repos/ralouphie/getallheaders/badge.png?branch=master)](https://coveralls.io/r/ralouphie/getallheaders?branch=master) +[![Latest Stable Version](https://poser.pugx.org/ralouphie/getallheaders/v/stable.png)](https://packagist.org/packages/ralouphie/getallheaders) +[![Latest Unstable Version](https://poser.pugx.org/ralouphie/getallheaders/v/unstable.png)](https://packagist.org/packages/ralouphie/getallheaders) +[![License](https://poser.pugx.org/ralouphie/getallheaders/license.png)](https://packagist.org/packages/ralouphie/getallheaders) + + +This is a simple polyfill for [`getallheaders()`](http://www.php.net/manual/en/function.getallheaders.php). + +## Install + +For PHP version **`>= 5.6`**: + +``` +composer require ralouphie/getallheaders +``` + +For PHP version **`< 5.6`**: + +``` +composer require ralouphie/getallheaders "^2" +``` diff --git a/data/web/inc/lib/vendor/ralouphie/getallheaders/composer.json b/data/web/inc/lib/vendor/ralouphie/getallheaders/composer.json new file mode 100644 index 000000000..de8ce62e4 --- /dev/null +++ b/data/web/inc/lib/vendor/ralouphie/getallheaders/composer.json @@ -0,0 +1,26 @@ +{ + "name": "ralouphie/getallheaders", + "description": "A polyfill for getallheaders.", + "license": "MIT", + "authors": [ + { + "name": "Ralph Khattar", + "email": "ralph.khattar@gmail.com" + } + ], + "require": { + "php": ">=5.6" + }, + "require-dev": { + "phpunit/phpunit": "^5 || ^6.5", + "php-coveralls/php-coveralls": "^2.1" + }, + "autoload": { + "files": ["src/getallheaders.php"] + }, + "autoload-dev": { + "psr-4": { + "getallheaders\\Tests\\": "tests/" + } + } +} diff --git a/data/web/inc/lib/vendor/ralouphie/getallheaders/src/getallheaders.php b/data/web/inc/lib/vendor/ralouphie/getallheaders/src/getallheaders.php new file mode 100644 index 000000000..c7285a5ba --- /dev/null +++ b/data/web/inc/lib/vendor/ralouphie/getallheaders/src/getallheaders.php @@ -0,0 +1,46 @@ + 'Content-Type', + 'CONTENT_LENGTH' => 'Content-Length', + 'CONTENT_MD5' => 'Content-Md5', + ); + + foreach ($_SERVER as $key => $value) { + if (substr($key, 0, 5) === 'HTTP_') { + $key = substr($key, 5); + if (!isset($copy_server[$key]) || !isset($_SERVER[$key])) { + $key = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', $key)))); + $headers[$key] = $value; + } + } elseif (isset($copy_server[$key])) { + $headers[$copy_server[$key]] = $value; + } + } + + if (!isset($headers['Authorization'])) { + if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) { + $headers['Authorization'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION']; + } elseif (isset($_SERVER['PHP_AUTH_USER'])) { + $basic_pass = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : ''; + $headers['Authorization'] = 'Basic ' . base64_encode($_SERVER['PHP_AUTH_USER'] . ':' . $basic_pass); + } elseif (isset($_SERVER['PHP_AUTH_DIGEST'])) { + $headers['Authorization'] = $_SERVER['PHP_AUTH_DIGEST']; + } + } + + return $headers; + } + +} diff --git a/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/.gitignore b/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/.gitignore new file mode 100644 index 000000000..e8c7cb69e --- /dev/null +++ b/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/.gitignore @@ -0,0 +1,4 @@ +/build +/vendor +composer.phar +composer.lock \ No newline at end of file diff --git a/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/.scrutinizer.yml b/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/.scrutinizer.yml new file mode 100644 index 000000000..1f831e850 --- /dev/null +++ b/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/.scrutinizer.yml @@ -0,0 +1,35 @@ +filter: + excluded_paths: [test/*] +checks: + php: + code_rating: true + remove_extra_empty_lines: true + remove_php_closing_tag: true + remove_trailing_whitespace: true + fix_use_statements: + remove_unused: true + preserve_multiple: false + preserve_blanklines: true + order_alphabetically: true + fix_php_opening_tag: true + fix_linefeed: true + fix_line_ending: true + fix_identation_4spaces: true + fix_doc_comments: true +tools: + external_code_coverage: + timeout: 600 + runs: 2 + php_analyzer: true + php_code_coverage: false + php_code_sniffer: + config: + standard: PSR2 + filter: + paths: ['src'] + php_loc: + enabled: true + excluded_dirs: [examples, vendor, test] + php_cpd: + enabled: true + excluded_dirs: [examples, vendor, test] diff --git a/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/.travis.yml b/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/.travis.yml new file mode 100644 index 000000000..c5f3825a3 --- /dev/null +++ b/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/.travis.yml @@ -0,0 +1,29 @@ +language: php + +sudo: false + +php: + - 7.2 + - 7.3 + - 7.4 + - 8.0 + - 8.1 + - 8.2 + +matrix: + include: + - php: 5.6 + env: 'COMPOSER_FLAGS="--prefer-stable --prefer-lowest"' + +before_script: + - travis_retry composer self-update + - travis_retry composer install --no-interaction --prefer-source --dev + - travis_retry phpenv rehash + +script: + - ./vendor/bin/phpcs --standard=psr2 src/ + - ./vendor/bin/phpunit --coverage-text --coverage-clover=coverage.clover + +after_script: + - wget https://scrutinizer-ci.com/ocular.phar + - php ocular.phar code-coverage:upload --format=php-clover coverage.clover diff --git a/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/CHANGELOG.md b/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/CHANGELOG.md new file mode 100644 index 000000000..e1990de3b --- /dev/null +++ b/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/CHANGELOG.md @@ -0,0 +1,74 @@ +# Changelog +All Notable changes to `oauth2-keycloak` will be documented in this file + +## 2.1.0 - 2018-03-12 + +### Added +- Introduce `getLogoutUrl` method on provider to build and return and authorized logout url - thanks @FlxPeters + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing + +## 2.0.0 - 2017-01-25 + +### Added +- PHP 7.1 Support + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- PHP 5.5 Support + +### Security +- Nothing + +## 1.0.0 - 2017-01-25 + +Bump for base package parity + +## 0.2.0 - 2016-12-07 + +### Added +- JSON Web Token decryption support + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing + +## 0.1.0 - 2015-08-31 + +### Added +- Initial release! + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing diff --git a/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/CONTRIBUTING.md b/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/CONTRIBUTING.md new file mode 100644 index 000000000..e1e078197 --- /dev/null +++ b/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/CONTRIBUTING.md @@ -0,0 +1,42 @@ +# Contributing + +Contributions are **welcome** and will be fully **credited**. + +We accept contributions via Pull Requests on [Github](https://github.com/stevenmaguire/oauth2-keycloak). + + +## Pull Requests + +- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer). + +- **Add tests!** - Your patch won't be accepted if it doesn't have tests. + +- **Document any change in behaviour** - Make sure the README and any other relevant documentation are kept up-to-date. + +- **Consider our release cycle** - We try to follow SemVer. Randomly breaking public APIs is not an option. + +- **Create topic branches** - Don't ask us to pull from your master branch. + +- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. + +- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please squash them before submitting. + +- **Ensure tests pass!** - Please run the tests (see below) before submitting your pull request, and make sure they pass. We won't accept a patch until all tests pass. + +- **Ensure no coding standards violations** - Please run PHP Code Sniffer using the PSR-2 standard (see below) before submitting your pull request. A violation will cause the build to fail, so please make sure there are no violations. We can't accept a patch if the build fails. + + +## Running Tests + +``` bash +$ ./vendor/bin/phpunit +``` + + +## Running PHP Code Sniffer + +``` bash +$ ./vendor/bin/phpcs src --standard=psr2 -sp +``` + +**Happy coding**! diff --git a/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/LICENSE b/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/LICENSE new file mode 100644 index 000000000..51455e2dd --- /dev/null +++ b/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Steven Maguire + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/README.md b/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/README.md new file mode 100644 index 000000000..d0b1acaf3 --- /dev/null +++ b/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/README.md @@ -0,0 +1,176 @@ +# Keycloak Provider for OAuth 2.0 Client +[![Latest Version](https://img.shields.io/github/release/stevenmaguire/oauth2-keycloak.svg?style=flat-square)](https://github.com/stevenmaguire/oauth2-keycloak/releases) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md) +[![Build Status](https://img.shields.io/travis/stevenmaguire/oauth2-keycloak/master.svg?style=flat-square)](https://travis-ci.org/stevenmaguire/oauth2-keycloak) +[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/stevenmaguire/oauth2-keycloak.svg?style=flat-square)](https://scrutinizer-ci.com/g/stevenmaguire/oauth2-keycloak/code-structure) +[![Quality Score](https://img.shields.io/scrutinizer/g/stevenmaguire/oauth2-keycloak.svg?style=flat-square)](https://scrutinizer-ci.com/g/stevenmaguire/oauth2-keycloak) +[![Total Downloads](https://img.shields.io/packagist/dt/stevenmaguire/oauth2-keycloak.svg?style=flat-square)](https://packagist.org/packages/stevenmaguire/oauth2-keycloak) + +This package provides Keycloak OAuth 2.0 support for the PHP League's [OAuth 2.0 Client](https://github.com/thephpleague/oauth2-client). + +## Installation + +To install, use composer: + +``` +composer require stevenmaguire/oauth2-keycloak +``` + +## Usage + +Usage is the same as The League's OAuth client, using `\Stevenmaguire\OAuth2\Client\Provider\Keycloak` as the provider. + +Use `authServerUrl` to specify the Keycloak server URL. You can lookup the correct value from the Keycloak client installer JSON under `auth-server-url`, eg. `http://localhost:8080/auth`. + +Use `realm` to specify the Keycloak realm name. You can lookup the correct value from the Keycloak client installer JSON under `resource`, eg. `master`. + +### Authorization Code Flow + +```php +$provider = new Stevenmaguire\OAuth2\Client\Provider\Keycloak([ + 'authServerUrl' => '{keycloak-server-url}', + 'realm' => '{keycloak-realm}', + 'clientId' => '{keycloak-client-id}', + 'clientSecret' => '{keycloak-client-secret}', + 'redirectUri' => 'https://example.com/callback-url', + 'encryptionAlgorithm' => 'RS256', // optional + 'encryptionKeyPath' => '../key.pem' // optional + 'encryptionKey' => 'contents_of_key_or_certificate' // optional + 'version' => '20.0.1', // optional +]); + +if (!isset($_GET['code'])) { + + // If we don't have an authorization code then get one + $authUrl = $provider->getAuthorizationUrl(); + $_SESSION['oauth2state'] = $provider->getState(); + header('Location: '.$authUrl); + exit; + +// Check given state against previously stored one to mitigate CSRF attack +} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { + + unset($_SESSION['oauth2state']); + exit('Invalid state, make sure HTTP sessions are enabled.'); + +} else { + + // Try to get an access token (using the authorization coe grant) + try { + $token = $provider->getAccessToken('authorization_code', [ + 'code' => $_GET['code'] + ]); + } catch (Exception $e) { + exit('Failed to get access token: '.$e->getMessage()); + } + + // Optional: Now you have a token you can look up a users profile data + try { + + // We got an access token, let's now get the user's details + $user = $provider->getResourceOwner($token); + + // Use these details to create a new profile + printf('Hello %s!', $user->getName()); + + } catch (Exception $e) { + exit('Failed to get resource owner: '.$e->getMessage()); + } + + // Use this to interact with an API on the users behalf + echo $token->getToken(); +} +``` + +### Refreshing a Token + +```php +$provider = new Stevenmaguire\OAuth2\Client\Provider\Keycloak([ + 'authServerUrl' => '{keycloak-server-url}', + 'realm' => '{keycloak-realm}', + 'clientId' => '{keycloak-client-id}', + 'clientSecret' => '{keycloak-client-secret}', + 'redirectUri' => 'https://example.com/callback-url', +]); + +$token = $provider->getAccessToken('refresh_token', ['refresh_token' => $token->getRefreshToken()]); +``` + +### Handling encryption + +If you've configured your Keycloak instance to use encryption, there are some advanced options available to you. + +#### Configure the provider to use the same encryption algorithm + +```php +$provider = new Stevenmaguire\OAuth2\Client\Provider\Keycloak([ + // ... + 'encryptionAlgorithm' => 'RS256', +]); +``` + +or + +```php +$provider->setEncryptionAlgorithm('RS256'); +``` + +#### Configure the provider to use the expected decryption public key or certificate + +##### By key value + +```php +$key = "-----BEGIN PUBLIC KEY-----\n....\n-----END PUBLIC KEY-----"; +// or +// $key = "-----BEGIN CERTIFICATE-----\n....\n-----END CERTIFICATE-----"; + +$provider = new Stevenmaguire\OAuth2\Client\Provider\Keycloak([ + // ... + 'encryptionKey' => $key, +]); +``` + +or + +```php +$provider->setEncryptionKey($key); +``` + +##### By key path + +```php +$keyPath = '../key.pem'; + +$provider = new Stevenmaguire\OAuth2\Client\Provider\Keycloak([ + // ... + 'encryptionKeyPath' => $keyPath, +]); +``` + +or + +```php +$provider->setEncryptionKeyPath($keyPath); +``` + +## Testing + +``` bash +$ ./vendor/bin/phpunit +``` + +## Contributing + +Please see [CONTRIBUTING](https://github.com/stevenmaguire/oauth2-keycloak/blob/master/CONTRIBUTING.md) for details. + + +## Credits + +- [Steven Maguire](https://github.com/stevenmaguire) +- [Martin Stefan](https://github.com/mstefan21) +- [All Contributors](https://github.com/stevenmaguire/oauth2-keycloak/contributors) + + +## License + +The MIT License (MIT). Please see [License File](https://github.com/stevenmaguire/oauth2-keycloak/blob/master/LICENSE) for more information. diff --git a/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/composer.json b/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/composer.json new file mode 100644 index 000000000..b6a54477e --- /dev/null +++ b/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/composer.json @@ -0,0 +1,51 @@ +{ + "name": "stevenmaguire/oauth2-keycloak", + "description": "Keycloak OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "license": "MIT", + "authors": [ + { + "name": "Steven Maguire", + "email": "stevenmaguire@gmail.com", + "homepage": "https://github.com/stevenmaguire" + } + ], + "keywords": [ + "oauth", + "oauth2", + "client", + "authorization", + "authorisation", + "keycloak" + ], + "require": { + "php": "~7.2 || ~8.0", + "league/oauth2-client": "^2.0", + "firebase/php-jwt": "^4.0 || ^5.0 || ^6.0" + }, + "require-dev": { + "phpunit/phpunit": "~9.6.4", + "mockery/mockery": "~1.5.0", + "squizlabs/php_codesniffer": "~3.7.0" + }, + "autoload": { + "psr-4": { + "Stevenmaguire\\OAuth2\\Client\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Stevenmaguire\\OAuth2\\Client\\Test\\": "test/src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "scripts": { + "test": [ + "@putenv XDEBUG_MODE=coverage", + "phpunit --colors=always" + ] + } +} \ No newline at end of file diff --git a/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/examples/index.php b/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/examples/index.php new file mode 100644 index 000000000..398333f15 --- /dev/null +++ b/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/examples/index.php @@ -0,0 +1,53 @@ + '', + 'realm' => '', + 'clientId' => '', + 'clientSecret' => '', + 'redirectUri' => '', + 'encryptionAlgorithm' => null, + 'encryptionKey' => null, + 'encryptionKeyPath' => null +]); + +if (!isset($_GET['code'])) { + // If we don't have an authorization code then get one + $authUrl = $provider->getAuthorizationUrl(); + $_SESSION['oauth2state'] = $provider->getState(); + header('Location: '.$authUrl); + exit; + +// Check given state against previously stored one to mitigate CSRF attack +} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { + unset($_SESSION['oauth2state']); + exit('Invalid state, make sure HTTP sessions are enabled.'); +} else { + // Try to get an access token (using the authorization coe grant) + try { + $token = $provider->getAccessToken('authorization_code', [ + 'code' => $_GET['code'] + ]); + } catch (Exception $e) { + exit('Failed to get access token: '.$e->getMessage()); + } + + // Optional: Now you have a token you can look up a users profile data + try { + + // We got an access token, let's now get the user's details + $user = $provider->getResourceOwner($token); + // Use these details to create a new profile + printf('Hello %s!\n
', $user->getName()); + + } catch (Exception $e) { + exit('Failed to get resource owner: '.$e->getMessage()); + } + + // Use this to interact with an API on the users behalf + echo $token->getToken(); +} diff --git a/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/phpunit.xml.dist b/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/phpunit.xml.dist new file mode 100644 index 000000000..b915f933b --- /dev/null +++ b/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/phpunit.xml.dist @@ -0,0 +1,33 @@ + + + + + src + + + vendor + src/autoload.php + + + + + + + + + ./test/ + + + diff --git a/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/src/Provider/Exception/EncryptionConfigurationException.php b/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/src/Provider/Exception/EncryptionConfigurationException.php new file mode 100644 index 000000000..546d2de83 --- /dev/null +++ b/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/src/Provider/Exception/EncryptionConfigurationException.php @@ -0,0 +1,22 @@ +setEncryptionKeyPath($options['encryptionKeyPath']); + unset($options['encryptionKeyPath']); + } + + if (isset($options['version'])) { + $this->setVersion($options['version']); + } + + parent::__construct($options, $collaborators); + } + + /** + * Attempts to decrypt the given response. + * + * @param string|array|null $response + * + * @return string|array|null + */ + public function decryptResponse($response) + { + if (!is_string($response)) { + return $response; + } + + if ($this->usesEncryption()) { + return json_decode( + json_encode( + JWT::decode( + $response, + $this->encryptionKey, + array($this->encryptionAlgorithm) + ) + ), + true + ); + } + + throw EncryptionConfigurationException::undeterminedEncryption(); + } + + /** + * Get authorization url to begin OAuth flow + * + * @return string + */ + public function getBaseAuthorizationUrl() + { + return $this->getBaseUrlWithRealm().'/protocol/openid-connect/auth'; + } + + /** + * Get access token url to retrieve token + * + * @param array $params + * + * @return string + */ + public function getBaseAccessTokenUrl(array $params) + { + return $this->getBaseUrlWithRealm().'/protocol/openid-connect/token'; + } + + /** + * Get provider url to fetch user details + * + * @param AccessToken $token + * + * @return string + */ + public function getResourceOwnerDetailsUrl(AccessToken $token) + { + return $this->getBaseUrlWithRealm().'/protocol/openid-connect/userinfo'; + } + + /** + * Builds the logout URL. + * + * @param array $options + * @return string Authorization URL + */ + public function getLogoutUrl(array $options = []) + { + $base = $this->getBaseLogoutUrl(); + $params = $this->getAuthorizationParameters($options); + + // Starting with keycloak 18.0.0, the parameter redirect_uri is no longer supported on logout. + // As of this version the parameter is called post_logout_redirect_uri. In addition to this + // a parameter id_token_hint has to be provided. + if ($this->validateGteVersion('18.0.0')) { + if (isset($options['access_token']) === true) { + $accessToken = $options['access_token']; + + $params['id_token_hint'] = $accessToken->getValues()['id_token']; + $params['post_logout_redirect_uri'] = $params['redirect_uri']; + } + + unset($params['redirect_uri']); + } + + $query = $this->getAuthorizationQuery($params); + return $this->appendQuery($base, $query); + } + + /** + * Get logout url to logout of session token + * + * @return string + */ + private function getBaseLogoutUrl() + { + return $this->getBaseUrlWithRealm() . '/protocol/openid-connect/logout'; + } + + /** + * Creates base url from provider configuration. + * + * @return string + */ + protected function getBaseUrlWithRealm() + { + return $this->authServerUrl.'/realms/'.$this->realm; + } + + /** + * Get the default scopes used by this provider. + * + * This should not be a complete list of all scopes, but the minimum + * required for the provider user interface! + * + * @return string[] + */ + protected function getDefaultScopes() + { + $scopes = [ + 'profile', + 'email' + ]; + if ($this->validateGteVersion('20.0.0')) { + $scopes[] = 'openid'; + } + return $scopes; + } + + /** + * Returns the string that should be used to separate scopes when building + * the URL for requesting an access token. + * + * @return string Scope separator, defaults to ',' + */ + protected function getScopeSeparator() + { + return ' '; + } + + + /** + * Check a provider response for errors. + * + * @throws IdentityProviderException + * @param ResponseInterface $response + * @param string $data Parsed response data + * @return void + */ + protected function checkResponse(ResponseInterface $response, $data) + { + if (!empty($data['error'])) { + $error = $data['error']; + if (isset($data['error_description'])) { + $error.=': '.$data['error_description']; + } + throw new IdentityProviderException($error, 0, $data); + } + } + + /** + * Generate a user object from a successful user details request. + * + * @param array $response + * @param AccessToken $token + * @return KeycloakResourceOwner + */ + protected function createResourceOwner(array $response, AccessToken $token) + { + return new KeycloakResourceOwner($response); + } + + /** + * Requests and returns the resource owner of given access token. + * + * @param AccessToken $token + * @return KeycloakResourceOwner + * @throws EncryptionConfigurationException + */ + public function getResourceOwner(AccessToken $token) + { + $response = $this->fetchResourceOwnerDetails($token); + + // We are always getting an array. We have to check if it is + // the array we created + if (array_key_exists('jwt', $response)) { + $response = $response['jwt']; + } + + $response = $this->decryptResponse($response); + + return $this->createResourceOwner($response, $token); + } + + /** + * Updates expected encryption algorithm of Keycloak instance. + * + * @param string $encryptionAlgorithm + * + * @return Keycloak + */ + public function setEncryptionAlgorithm($encryptionAlgorithm) + { + $this->encryptionAlgorithm = $encryptionAlgorithm; + + return $this; + } + + /** + * Updates expected encryption key of Keycloak instance. + * + * @param string $encryptionKey + * + * @return Keycloak + */ + public function setEncryptionKey($encryptionKey) + { + $this->encryptionKey = $encryptionKey; + + return $this; + } + + /** + * Updates expected encryption key of Keycloak instance to content of given + * file path. + * + * @param string $encryptionKeyPath + * + * @return Keycloak + */ + public function setEncryptionKeyPath($encryptionKeyPath) + { + try { + $this->encryptionKey = file_get_contents($encryptionKeyPath); + } catch (Exception $e) { + // Not sure how to handle this yet. + } + + return $this; + } + + /** + * Updates the keycloak version. + * + * @param string $version + * + * @return Keycloak + */ + public function setVersion($version) + { + $this->version = $version; + + return $this; + } + + /** + * Checks if provider is configured to use encryption. + * + * @return bool + */ + public function usesEncryption() + { + return (bool) $this->encryptionAlgorithm && $this->encryptionKey; + } + + /** + * Parses the response according to its content-type header. + * + * @throws UnexpectedValueException + * @param ResponseInterface $response + * @return array + */ + protected function parseResponse(ResponseInterface $response) + { + // We have a problem with keycloak when the userinfo responses + // with a jwt token + // Because it just return a jwt as string with the header + // application/jwt + // This can't be parsed to a array + // Dont know why this function only allow an array as return value... + $content = (string) $response->getBody(); + $type = $this->getContentType($response); + + if (strpos($type, 'jwt') !== false) { + // Here we make the temporary array + return ['jwt' => $content]; + } + + return parent::parseResponse($response); + } + + /** + * Validate if version is greater or equal + * + * @param string $version + * @return bool + */ + private function validateGteVersion($version) + { + return (isset($this->version) && version_compare($this->version, $version, '>=')); + } +} diff --git a/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/src/Provider/KeycloakResourceOwner.php b/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/src/Provider/KeycloakResourceOwner.php new file mode 100644 index 000000000..7587af783 --- /dev/null +++ b/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/src/Provider/KeycloakResourceOwner.php @@ -0,0 +1,65 @@ +response = $response; + } + + /** + * Get resource owner id + * + * @return string|null + */ + public function getId() + { + return \array_key_exists('sub', $this->response) ? $this->response['sub'] : null; + } + + /** + * Get resource owner email + * + * @return string|null + */ + public function getEmail() + { + return \array_key_exists('email', $this->response) ? $this->response['email'] : null; + } + + /** + * Get resource owner name + * + * @return string|null + */ + public function getName() + { + return \array_key_exists('name', $this->response) ? $this->response['name'] : null; + } + + /** + * Return all of the owner details available as an array. + * + * @return array + */ + public function toArray() + { + return $this->response; + } +} diff --git a/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/test/src/Provider/KeycloakTest.php b/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/test/src/Provider/KeycloakTest.php new file mode 100644 index 000000000..a5c1da14f --- /dev/null +++ b/data/web/inc/lib/vendor/stevenmaguire/oauth2-keycloak/test/src/Provider/KeycloakTest.php @@ -0,0 +1,342 @@ +provider = new Keycloak([ + 'authServerUrl' => 'http://mock.url/auth', + 'realm' => 'mock_realm', + 'clientId' => 'mock_client_id', + 'clientSecret' => 'mock_secret', + 'redirectUri' => 'none', + ]); + } + + public function tearDown(): void + { + m::close(); + parent::tearDown(); + } + + public function testAuthorizationUrl() + { + $url = $this->provider->getAuthorizationUrl(); + $uri = parse_url($url); + parse_str($uri['query'], $query); + + $this->assertArrayHasKey('client_id', $query); + $this->assertArrayHasKey('redirect_uri', $query); + $this->assertArrayHasKey('state', $query); + $this->assertArrayHasKey('scope', $query); + $this->assertArrayHasKey('response_type', $query); + $this->assertArrayHasKey('approval_prompt', $query); + $this->assertNotNull($this->provider->getState()); + } + + public function testEncryptionAlgorithm() + { + $algorithm = uniqid(); + $provider = new Keycloak([ + 'encryptionAlgorithm' => $algorithm, + ]); + + $this->assertEquals($algorithm, $provider->encryptionAlgorithm); + + $algorithm = uniqid(); + $provider->setEncryptionAlgorithm($algorithm); + + $this->assertEquals($algorithm, $provider->encryptionAlgorithm); + } + + public function testEncryptionKey() + { + $key = uniqid(); + $provider = new Keycloak([ + 'encryptionKey' => $key, + ]); + + $this->assertEquals($key, $provider->encryptionKey); + + $key = uniqid(); + $provider->setEncryptionKey($key); + + $this->assertEquals($key, $provider->encryptionKey); + } + + public function testEncryptionKeyPath() + { + global $mockFileGetContents; + $path = uniqid(); + $key = uniqid(); + $mockFileGetContents = $key; + + $provider = new Keycloak([ + 'encryptionKeyPath' => $path, + ]); + + $this->assertEquals($key, $provider->encryptionKey); + + $path = uniqid(); + $key = uniqid(); + $mockFileGetContents = $key; + + $provider->setEncryptionKeyPath($path); + + $this->assertEquals($key, $provider->encryptionKey); + } + + public function testEncryptionKeyPathFails() + { + $this->markTestIncomplete('Need to assess the test to see what is required to be checked.'); + + global $mockFileGetContents; + $path = uniqid(); + $key = uniqid(); + $mockFileGetContents = new \Exception(); + + $provider = new Keycloak([ + 'encryptionKeyPath' => $path, + ]); + + $provider->setEncryptionKeyPath($path); + } + + public function testScopes() + { + $scopeSeparator = ' '; + $options = ['scope' => [uniqid(), uniqid()]]; + $query = ['scope' => implode($scopeSeparator, $options['scope'])]; + $url = $this->provider->getAuthorizationUrl($options); + $encodedScope = $this->buildQueryString($query); + $this->assertStringContainsString($encodedScope, $url); + } + + public function testGetAuthorizationUrl() + { + $url = $this->provider->getAuthorizationUrl(); + $uri = parse_url($url); + + $this->assertEquals('/auth/realms/mock_realm/protocol/openid-connect/auth', $uri['path']); + } + + public function testGetLogoutUrl() + { + $url = $this->provider->getLogoutUrl(); + $uri = parse_url($url); + + $this->assertEquals('/auth/realms/mock_realm/protocol/openid-connect/logout', $uri['path']); + } + + public function testGetBaseAccessTokenUrl() + { + $params = []; + + $url = $this->provider->getBaseAccessTokenUrl($params); + $uri = parse_url($url); + + $this->assertEquals('/auth/realms/mock_realm/protocol/openid-connect/token', $uri['path']); + } + + public function testGetAccessToken() + { + $response = m::mock('Psr\Http\Message\ResponseInterface'); + $response->shouldReceive('getBody') + ->andReturn('{"access_token":"mock_access_token", "scope":"email", "token_type":"bearer"}'); + $response->shouldReceive('getHeader') + ->andReturn(['content-type' => 'json']); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(1) + ->andReturn($response); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + + $this->assertEquals('mock_access_token', $token->getToken()); + $this->assertNull($token->getExpires()); + $this->assertNull($token->getRefreshToken()); + $this->assertNull($token->getResourceOwnerId()); + } + + public function testUserData() + { + $userId = rand(1000, 9999); + $name = uniqid(); + $nickname = uniqid(); + $email = uniqid(); + + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody') + ->andReturn( + 'access_token=mock_access_token&expires=3600&refresh_token=mock_refresh_token&otherKey={1234}' + ); + $postResponse->shouldReceive('getHeader') + ->andReturn(['content-type' => 'application/x-www-form-urlencoded']); + + $userResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $userResponse->shouldReceive('getBody') + ->andReturn('{"sub": '.$userId.', "name": "'.$name.'", "email": "'.$email.'"}'); + $userResponse->shouldReceive('getHeader') + ->andReturn(['content-type' => 'json']); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(2) + ->andReturn($postResponse, $userResponse); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + $user = $this->provider->getResourceOwner($token); + + $this->assertEquals($userId, $user->getId()); + $this->assertEquals($userId, $user->toArray()['sub']); + $this->assertEquals($name, $user->getName()); + $this->assertEquals($name, $user->toArray()['name']); + $this->assertEquals($email, $user->getEmail()); + $this->assertEquals($email, $user->toArray()['email']); + } + + public function testUserDataWithEncryption() + { + $userId = rand(1000, 9999); + $name = uniqid(); + $nickname = uniqid(); + $email = uniqid(); + $jwt = uniqid(); + $algorithm = uniqid(); + $key = uniqid(); + + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody') + ->andReturn( + 'access_token=mock_access_token&expires=3600&refresh_token=mock_refresh_token&otherKey={1234}' + ); + $postResponse->shouldReceive('getHeader') + ->andReturn(['content-type' => 'application/x-www-form-urlencoded']); + $postResponse->shouldReceive('getStatusCode') + ->andReturn(200); + + $userResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $userResponse->shouldReceive('getBody') + ->andReturn($jwt); + $userResponse->shouldReceive('getHeader') + ->andReturn(['content-type' => 'application/jwt']); + $userResponse->shouldReceive('getStatusCode') + ->andReturn(200); + + $decoder = \Mockery::mock('overload:Firebase\JWT\JWT'); + $decoder->shouldReceive('decode') + ->with($jwt, $key, [$algorithm]) + ->andReturn([ + 'sub' => $userId, + 'email' => $email, + 'name' => $name, + ]); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(2) + ->andReturn($postResponse, $userResponse); + $this->provider->setHttpClient($client); + + $token = $this->provider->setEncryptionAlgorithm($algorithm) + ->setEncryptionKey($key) + ->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + $user = $this->provider->getResourceOwner($token); + + $this->assertEquals($userId, $user->getId()); + $this->assertEquals($userId, $user->toArray()['sub']); + $this->assertEquals($name, $user->getName()); + $this->assertEquals($name, $user->toArray()['name']); + $this->assertEquals($email, $user->getEmail()); + $this->assertEquals($email, $user->toArray()['email']); + } + + public function testUserDataFailsWhenEncryptionEncounteredAndNotConfigured() + { + $this->expectException(EncryptionConfigurationException::class); + + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody') + ->andReturn( + 'access_token=mock_access_token&expires=3600&refresh_token=mock_refresh_token&otherKey={1234}' + ); + $postResponse->shouldReceive('getHeader') + ->andReturn(['content-type' => 'application/x-www-form-urlencoded']); + $postResponse->shouldReceive('getStatusCode') + ->andReturn(200); + + $userResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $userResponse->shouldReceive('getBody') + ->andReturn(uniqid()); + $userResponse->shouldReceive('getHeader') + ->andReturn(['content-type' => 'application/jwt']); + $userResponse->shouldReceive('getStatusCode') + ->andReturn(200); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(2) + ->andReturn($postResponse, $userResponse); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + $user = $this->provider->getResourceOwner($token); + } + + public function testErrorResponse() + { + $this->expectException(IdentityProviderException::class); + + $response = m::mock('Psr\Http\Message\ResponseInterface'); + $response->shouldReceive('getBody') + ->andReturn('{"error": "invalid_grant", "error_description": "Code not found"}'); + $response->shouldReceive('getHeader') + ->andReturn(['content-type' => 'json']); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(1) + ->andReturn($response); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + } + } +} diff --git a/data/web/inc/lib/vendor/symfony/polyfill-mbstring/LICENSE b/data/web/inc/lib/vendor/symfony/polyfill-mbstring/LICENSE index 4cd8bdd30..6e3afce69 100644 --- a/data/web/inc/lib/vendor/symfony/polyfill-mbstring/LICENSE +++ b/data/web/inc/lib/vendor/symfony/polyfill-mbstring/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2015-2019 Fabien Potencier +Copyright (c) 2015-present Fabien Potencier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/data/web/inc/lib/vendor/symfony/polyfill-mbstring/Mbstring.php b/data/web/inc/lib/vendor/symfony/polyfill-mbstring/Mbstring.php index b65c54a6b..2e0b96940 100644 --- a/data/web/inc/lib/vendor/symfony/polyfill-mbstring/Mbstring.php +++ b/data/web/inc/lib/vendor/symfony/polyfill-mbstring/Mbstring.php @@ -69,7 +69,7 @@ final class Mbstring { public const MB_CASE_FOLD = \PHP_INT_MAX; - private const CASE_FOLD = [ + private const SIMPLE_CASE_FOLD = [ ['µ', 'ſ', "\xCD\x85", 'ς', "\xCF\x90", "\xCF\x91", "\xCF\x95", "\xCF\x96", "\xCF\xB0", "\xCF\xB1", "\xCF\xB5", "\xE1\xBA\x9B", "\xE1\xBE\xBE"], ['μ', 's', 'ι', 'σ', 'β', 'θ', 'φ', 'π', 'κ', 'ρ', 'ε', "\xE1\xB9\xA1", 'ι'], ]; @@ -80,7 +80,7 @@ final class Mbstring public static function mb_convert_encoding($s, $toEncoding, $fromEncoding = null) { - if (\is_array($fromEncoding) || ($fromEncoding !== null && false !== strpos($fromEncoding, ','))) { + if (\is_array($fromEncoding) || (null !== $fromEncoding && false !== strpos($fromEncoding, ','))) { $fromEncoding = self::mb_detect_encoding($s, $fromEncoding); } else { $fromEncoding = self::getEncoding($fromEncoding); @@ -102,7 +102,7 @@ final class Mbstring $fromEncoding = 'Windows-1252'; } if ('UTF-8' !== $fromEncoding) { - $s = \iconv($fromEncoding, 'UTF-8//IGNORE', $s); + $s = iconv($fromEncoding, 'UTF-8//IGNORE', $s); } return preg_replace_callback('/[\x80-\xFF]+/', [__CLASS__, 'html_encoding_callback'], $s); @@ -113,7 +113,7 @@ final class Mbstring $fromEncoding = 'UTF-8'; } - return \iconv($fromEncoding, $toEncoding.'//IGNORE', $s); + return iconv($fromEncoding, $toEncoding.'//IGNORE', $s); } public static function mb_convert_variables($toEncoding, $fromEncoding, &...$vars) @@ -130,7 +130,7 @@ final class Mbstring public static function mb_decode_mimeheader($s) { - return \iconv_mime_decode($s, 2, self::$internalEncoding); + return iconv_mime_decode($s, 2, self::$internalEncoding); } public static function mb_encode_mimeheader($s, $charset = null, $transferEncoding = null, $linefeed = null, $indent = null) @@ -140,7 +140,7 @@ final class Mbstring public static function mb_decode_numericentity($s, $convmap, $encoding = null) { - if (null !== $s && !is_scalar($s) && !(\is_object($s) && method_exists($s, '__toString'))) { + if (null !== $s && !\is_scalar($s) && !(\is_object($s) && method_exists($s, '__toString'))) { trigger_error('mb_decode_numericentity() expects parameter 1 to be string, '.\gettype($s).' given', \E_USER_WARNING); return null; @@ -150,7 +150,7 @@ final class Mbstring return false; } - if (null !== $encoding && !is_scalar($encoding)) { + if (null !== $encoding && !\is_scalar($encoding)) { trigger_error('mb_decode_numericentity() expects parameter 3 to be string, '.\gettype($s).' given', \E_USER_WARNING); return ''; // Instead of null (cf. mb_encode_numericentity). @@ -166,10 +166,10 @@ final class Mbstring if ('UTF-8' === $encoding) { $encoding = null; if (!preg_match('//u', $s)) { - $s = @\iconv('UTF-8', 'UTF-8//IGNORE', $s); + $s = @iconv('UTF-8', 'UTF-8//IGNORE', $s); } } else { - $s = \iconv($encoding, 'UTF-8//IGNORE', $s); + $s = iconv($encoding, 'UTF-8//IGNORE', $s); } $cnt = floor(\count($convmap) / 4) * 4; @@ -195,12 +195,12 @@ final class Mbstring return $s; } - return \iconv('UTF-8', $encoding.'//IGNORE', $s); + return iconv('UTF-8', $encoding.'//IGNORE', $s); } public static function mb_encode_numericentity($s, $convmap, $encoding = null, $is_hex = false) { - if (null !== $s && !is_scalar($s) && !(\is_object($s) && method_exists($s, '__toString'))) { + if (null !== $s && !\is_scalar($s) && !(\is_object($s) && method_exists($s, '__toString'))) { trigger_error('mb_encode_numericentity() expects parameter 1 to be string, '.\gettype($s).' given', \E_USER_WARNING); return null; @@ -210,13 +210,13 @@ final class Mbstring return false; } - if (null !== $encoding && !is_scalar($encoding)) { + if (null !== $encoding && !\is_scalar($encoding)) { trigger_error('mb_encode_numericentity() expects parameter 3 to be string, '.\gettype($s).' given', \E_USER_WARNING); return null; // Instead of '' (cf. mb_decode_numericentity). } - if (null !== $is_hex && !is_scalar($is_hex)) { + if (null !== $is_hex && !\is_scalar($is_hex)) { trigger_error('mb_encode_numericentity() expects parameter 4 to be boolean, '.\gettype($s).' given', \E_USER_WARNING); return null; @@ -232,10 +232,10 @@ final class Mbstring if ('UTF-8' === $encoding) { $encoding = null; if (!preg_match('//u', $s)) { - $s = @\iconv('UTF-8', 'UTF-8//IGNORE', $s); + $s = @iconv('UTF-8', 'UTF-8//IGNORE', $s); } } else { - $s = \iconv($encoding, 'UTF-8//IGNORE', $s); + $s = iconv($encoding, 'UTF-8//IGNORE', $s); } static $ulenMask = ["\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4]; @@ -265,7 +265,7 @@ final class Mbstring return $result; } - return \iconv('UTF-8', $encoding.'//IGNORE', $result); + return iconv('UTF-8', $encoding.'//IGNORE', $result); } public static function mb_convert_case($s, $mode, $encoding = null) @@ -280,10 +280,10 @@ final class Mbstring if ('UTF-8' === $encoding) { $encoding = null; if (!preg_match('//u', $s)) { - $s = @\iconv('UTF-8', 'UTF-8//IGNORE', $s); + $s = @iconv('UTF-8', 'UTF-8//IGNORE', $s); } } else { - $s = \iconv($encoding, 'UTF-8//IGNORE', $s); + $s = iconv($encoding, 'UTF-8//IGNORE', $s); } if (\MB_CASE_TITLE == $mode) { @@ -301,7 +301,11 @@ final class Mbstring $map = $upper; } else { if (self::MB_CASE_FOLD === $mode) { - $s = str_replace(self::CASE_FOLD[0], self::CASE_FOLD[1], $s); + static $caseFolding = null; + if (null === $caseFolding) { + $caseFolding = self::getData('caseFolding'); + } + $s = strtr($s, $caseFolding); } static $lower = null; @@ -343,7 +347,7 @@ final class Mbstring return $s; } - return \iconv('UTF-8', $encoding.'//IGNORE', $s); + return iconv('UTF-8', $encoding.'//IGNORE', $s); } public static function mb_internal_encoding($encoding = null) @@ -354,7 +358,7 @@ final class Mbstring $normalizedEncoding = self::getEncoding($encoding); - if ('UTF-8' === $normalizedEncoding || false !== @\iconv($normalizedEncoding, $normalizedEncoding, ' ')) { + if ('UTF-8' === $normalizedEncoding || false !== @iconv($normalizedEncoding, $normalizedEncoding, ' ')) { self::$internalEncoding = $normalizedEncoding; return true; @@ -406,6 +410,12 @@ final class Mbstring public static function mb_check_encoding($var = null, $encoding = null) { + if (PHP_VERSION_ID < 70200 && \is_array($var)) { + trigger_error('mb_check_encoding() expects parameter 1 to be string, array given', \E_USER_WARNING); + + return null; + } + if (null === $encoding) { if (null === $var) { return false; @@ -413,7 +423,21 @@ final class Mbstring $encoding = self::$internalEncoding; } - return self::mb_detect_encoding($var, [$encoding]) || false !== @\iconv($encoding, $encoding, $var); + if (!\is_array($var)) { + return self::mb_detect_encoding($var, [$encoding]) || false !== @iconv($encoding, $encoding, $var); + } + + foreach ($var as $key => $value) { + if (!self::mb_check_encoding($key, $encoding)) { + return false; + } + if (!self::mb_check_encoding($value, $encoding)) { + return false; + } + } + + return true; + } public static function mb_detect_encoding($str, $encodingList = null, $strict = false) @@ -488,7 +512,7 @@ final class Mbstring return \strlen($s); } - return @\iconv_strlen($s, $encoding); + return @iconv_strlen($s, $encoding); } public static function mb_strpos($haystack, $needle, $offset = 0, $encoding = null) @@ -509,7 +533,7 @@ final class Mbstring return 0; } - return \iconv_strpos($haystack, $needle, $offset, $encoding); + return iconv_strpos($haystack, $needle, $offset, $encoding); } public static function mb_strrpos($haystack, $needle, $offset = 0, $encoding = null) @@ -533,7 +557,7 @@ final class Mbstring } $pos = '' !== $needle || 80000 > \PHP_VERSION_ID - ? \iconv_strrpos($haystack, $needle, $encoding) + ? iconv_strrpos($haystack, $needle, $encoding) : self::mb_strlen($haystack, $encoding); return false !== $pos ? $offset + $pos : false; @@ -541,7 +565,7 @@ final class Mbstring public static function mb_str_split($string, $split_length = 1, $encoding = null) { - if (null !== $string && !is_scalar($string) && !(\is_object($string) && method_exists($string, '__toString'))) { + if (null !== $string && !\is_scalar($string) && !(\is_object($string) && method_exists($string, '__toString'))) { trigger_error('mb_str_split() expects parameter 1 to be string, '.\gettype($string).' given', \E_USER_WARNING); return null; @@ -550,6 +574,7 @@ final class Mbstring if (1 > $split_length = (int) $split_length) { if (80000 > \PHP_VERSION_ID) { trigger_error('The length of each segment must be greater than zero', \E_USER_WARNING); + return false; } @@ -568,7 +593,7 @@ final class Mbstring } $rx .= '.{'.$split_length.'})/us'; - return preg_split($rx, $string, null, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY); + return preg_split($rx, $string, -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY); } $result = []; @@ -617,7 +642,7 @@ final class Mbstring } if ($start < 0) { - $start = \iconv_strlen($s, $encoding) + $start; + $start = iconv_strlen($s, $encoding) + $start; if ($start < 0) { $start = 0; } @@ -626,19 +651,21 @@ final class Mbstring if (null === $length) { $length = 2147483647; } elseif ($length < 0) { - $length = \iconv_strlen($s, $encoding) + $length - $start; + $length = iconv_strlen($s, $encoding) + $length - $start; if ($length < 0) { return ''; } } - return (string) \iconv_substr($s, $start, $length, $encoding); + return (string) iconv_substr($s, $start, $length, $encoding); } public static function mb_stripos($haystack, $needle, $offset = 0, $encoding = null) { - $haystack = self::mb_convert_case($haystack, self::MB_CASE_FOLD, $encoding); - $needle = self::mb_convert_case($needle, self::MB_CASE_FOLD, $encoding); + [$haystack, $needle] = str_replace(self::SIMPLE_CASE_FOLD[0], self::SIMPLE_CASE_FOLD[1], [ + self::mb_convert_case($haystack, \MB_CASE_LOWER, $encoding), + self::mb_convert_case($needle, \MB_CASE_LOWER, $encoding), + ]); return self::mb_strpos($haystack, $needle, $offset, $encoding); } @@ -657,7 +684,7 @@ final class Mbstring $pos = strrpos($haystack, $needle); } else { $needle = self::mb_substr($needle, 0, 1, $encoding); - $pos = \iconv_strrpos($haystack, $needle, $encoding); + $pos = iconv_strrpos($haystack, $needle, $encoding); } return self::getSubpart($pos, $part, $haystack, $encoding); @@ -673,8 +700,11 @@ final class Mbstring public static function mb_strripos($haystack, $needle, $offset = 0, $encoding = null) { - $haystack = self::mb_convert_case($haystack, self::MB_CASE_FOLD, $encoding); - $needle = self::mb_convert_case($needle, self::MB_CASE_FOLD, $encoding); + $haystack = self::mb_convert_case($haystack, \MB_CASE_LOWER, $encoding); + $needle = self::mb_convert_case($needle, \MB_CASE_LOWER, $encoding); + + $haystack = str_replace(self::SIMPLE_CASE_FOLD[0], self::SIMPLE_CASE_FOLD[1], $haystack); + $needle = str_replace(self::SIMPLE_CASE_FOLD[0], self::SIMPLE_CASE_FOLD[1], $needle); return self::mb_strrpos($haystack, $needle, $offset, $encoding); } @@ -736,12 +766,12 @@ final class Mbstring $encoding = self::getEncoding($encoding); if ('UTF-8' !== $encoding) { - $s = \iconv($encoding, 'UTF-8//IGNORE', $s); + $s = iconv($encoding, 'UTF-8//IGNORE', $s); } $s = preg_replace('/[\x{1100}-\x{115F}\x{2329}\x{232A}\x{2E80}-\x{303E}\x{3040}-\x{A4CF}\x{AC00}-\x{D7A3}\x{F900}-\x{FAFF}\x{FE10}-\x{FE19}\x{FE30}-\x{FE6F}\x{FF00}-\x{FF60}\x{FFE0}-\x{FFE6}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}]/u', '', $s, -1, $wide); - return ($wide << 1) + \iconv_strlen($s, 'UTF-8'); + return ($wide << 1) + iconv_strlen($s, 'UTF-8'); } public static function mb_substr_count($haystack, $needle, $encoding = null) @@ -797,6 +827,50 @@ final class Mbstring return $code; } + public static function mb_str_pad(string $string, int $length, string $pad_string = ' ', int $pad_type = \STR_PAD_RIGHT, string $encoding = null): string + { + if (!\in_array($pad_type, [\STR_PAD_RIGHT, \STR_PAD_LEFT, \STR_PAD_BOTH], true)) { + throw new \ValueError('mb_str_pad(): Argument #4 ($pad_type) must be STR_PAD_LEFT, STR_PAD_RIGHT, or STR_PAD_BOTH'); + } + + if (null === $encoding) { + $encoding = self::mb_internal_encoding(); + } + + try { + $validEncoding = @self::mb_check_encoding('', $encoding); + } catch (\ValueError $e) { + throw new \ValueError(sprintf('mb_str_pad(): Argument #5 ($encoding) must be a valid encoding, "%s" given', $encoding)); + } + + // BC for PHP 7.3 and lower + if (!$validEncoding) { + throw new \ValueError(sprintf('mb_str_pad(): Argument #5 ($encoding) must be a valid encoding, "%s" given', $encoding)); + } + + if (self::mb_strlen($pad_string, $encoding) <= 0) { + throw new \ValueError('mb_str_pad(): Argument #3 ($pad_string) must be a non-empty string'); + } + + $paddingRequired = $length - self::mb_strlen($string, $encoding); + + if ($paddingRequired < 1) { + return $string; + } + + switch ($pad_type) { + case \STR_PAD_LEFT: + return self::mb_substr(str_repeat($pad_string, $paddingRequired), 0, $paddingRequired, $encoding).$string; + case \STR_PAD_RIGHT: + return $string.self::mb_substr(str_repeat($pad_string, $paddingRequired), 0, $paddingRequired, $encoding); + default: + $leftPaddingLength = floor($paddingRequired / 2); + $rightPaddingLength = $paddingRequired - $leftPaddingLength; + + return self::mb_substr(str_repeat($pad_string, $leftPaddingLength), 0, $leftPaddingLength, $encoding).$string.self::mb_substr(str_repeat($pad_string, $rightPaddingLength), 0, $rightPaddingLength, $encoding); + } + } + private static function getSubpart($pos, $part, $haystack, $encoding) { if (false === $pos) { diff --git a/data/web/inc/lib/vendor/symfony/polyfill-mbstring/README.md b/data/web/inc/lib/vendor/symfony/polyfill-mbstring/README.md index 4efb599d8..478b40da2 100644 --- a/data/web/inc/lib/vendor/symfony/polyfill-mbstring/README.md +++ b/data/web/inc/lib/vendor/symfony/polyfill-mbstring/README.md @@ -5,7 +5,7 @@ This component provides a partial, native PHP implementation for the [Mbstring](https://php.net/mbstring) extension. More information can be found in the -[main Polyfill README](https://github.com/symfony/polyfill/blob/master/README.md). +[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md). License ======= diff --git a/data/web/inc/lib/vendor/symfony/polyfill-mbstring/Resources/unidata/caseFolding.php b/data/web/inc/lib/vendor/symfony/polyfill-mbstring/Resources/unidata/caseFolding.php new file mode 100644 index 000000000..512bba0bf --- /dev/null +++ b/data/web/inc/lib/vendor/symfony/polyfill-mbstring/Resources/unidata/caseFolding.php @@ -0,0 +1,119 @@ + 'i̇', + 'µ' => 'μ', + 'ſ' => 's', + 'ͅ' => 'ι', + 'ς' => 'σ', + 'ϐ' => 'β', + 'ϑ' => 'θ', + 'ϕ' => 'φ', + 'ϖ' => 'π', + 'ϰ' => 'κ', + 'ϱ' => 'ρ', + 'ϵ' => 'ε', + 'ẛ' => 'ṡ', + 'ι' => 'ι', + 'ß' => 'ss', + 'ʼn' => 'ʼn', + 'ǰ' => 'ǰ', + 'ΐ' => 'ΐ', + 'ΰ' => 'ΰ', + 'և' => 'եւ', + 'ẖ' => 'ẖ', + 'ẗ' => 'ẗ', + 'ẘ' => 'ẘ', + 'ẙ' => 'ẙ', + 'ẚ' => 'aʾ', + 'ẞ' => 'ss', + 'ὐ' => 'ὐ', + 'ὒ' => 'ὒ', + 'ὔ' => 'ὔ', + 'ὖ' => 'ὖ', + 'ᾀ' => 'ἀι', + 'ᾁ' => 'ἁι', + 'ᾂ' => 'ἂι', + 'ᾃ' => 'ἃι', + 'ᾄ' => 'ἄι', + 'ᾅ' => 'ἅι', + 'ᾆ' => 'ἆι', + 'ᾇ' => 'ἇι', + 'ᾈ' => 'ἀι', + 'ᾉ' => 'ἁι', + 'ᾊ' => 'ἂι', + 'ᾋ' => 'ἃι', + 'ᾌ' => 'ἄι', + 'ᾍ' => 'ἅι', + 'ᾎ' => 'ἆι', + 'ᾏ' => 'ἇι', + 'ᾐ' => 'ἠι', + 'ᾑ' => 'ἡι', + 'ᾒ' => 'ἢι', + 'ᾓ' => 'ἣι', + 'ᾔ' => 'ἤι', + 'ᾕ' => 'ἥι', + 'ᾖ' => 'ἦι', + 'ᾗ' => 'ἧι', + 'ᾘ' => 'ἠι', + 'ᾙ' => 'ἡι', + 'ᾚ' => 'ἢι', + 'ᾛ' => 'ἣι', + 'ᾜ' => 'ἤι', + 'ᾝ' => 'ἥι', + 'ᾞ' => 'ἦι', + 'ᾟ' => 'ἧι', + 'ᾠ' => 'ὠι', + 'ᾡ' => 'ὡι', + 'ᾢ' => 'ὢι', + 'ᾣ' => 'ὣι', + 'ᾤ' => 'ὤι', + 'ᾥ' => 'ὥι', + 'ᾦ' => 'ὦι', + 'ᾧ' => 'ὧι', + 'ᾨ' => 'ὠι', + 'ᾩ' => 'ὡι', + 'ᾪ' => 'ὢι', + 'ᾫ' => 'ὣι', + 'ᾬ' => 'ὤι', + 'ᾭ' => 'ὥι', + 'ᾮ' => 'ὦι', + 'ᾯ' => 'ὧι', + 'ᾲ' => 'ὰι', + 'ᾳ' => 'αι', + 'ᾴ' => 'άι', + 'ᾶ' => 'ᾶ', + 'ᾷ' => 'ᾶι', + 'ᾼ' => 'αι', + 'ῂ' => 'ὴι', + 'ῃ' => 'ηι', + 'ῄ' => 'ήι', + 'ῆ' => 'ῆ', + 'ῇ' => 'ῆι', + 'ῌ' => 'ηι', + 'ῒ' => 'ῒ', + 'ῖ' => 'ῖ', + 'ῗ' => 'ῗ', + 'ῢ' => 'ῢ', + 'ῤ' => 'ῤ', + 'ῦ' => 'ῦ', + 'ῧ' => 'ῧ', + 'ῲ' => 'ὼι', + 'ῳ' => 'ωι', + 'ῴ' => 'ώι', + 'ῶ' => 'ῶ', + 'ῷ' => 'ῶι', + 'ῼ' => 'ωι', + 'ff' => 'ff', + 'fi' => 'fi', + 'fl' => 'fl', + 'ffi' => 'ffi', + 'ffl' => 'ffl', + 'ſt' => 'st', + 'st' => 'st', + 'ﬓ' => 'մն', + 'ﬔ' => 'մե', + 'ﬕ' => 'մի', + 'ﬖ' => 'վն', + 'ﬗ' => 'մխ', +]; diff --git a/data/web/inc/lib/vendor/symfony/polyfill-mbstring/bootstrap.php b/data/web/inc/lib/vendor/symfony/polyfill-mbstring/bootstrap.php index 1fedd1f7c..ecf1a0352 100644 --- a/data/web/inc/lib/vendor/symfony/polyfill-mbstring/bootstrap.php +++ b/data/web/inc/lib/vendor/symfony/polyfill-mbstring/bootstrap.php @@ -132,6 +132,10 @@ if (!function_exists('mb_str_split')) { function mb_str_split($string, $length = 1, $encoding = null) { return p\Mbstring::mb_str_split($string, $length, $encoding); } } +if (!function_exists('mb_str_pad')) { + function mb_str_pad(string $string, int $length, string $pad_string = ' ', int $pad_type = STR_PAD_RIGHT, ?string $encoding = null): string { return p\Mbstring::mb_str_pad($string, $length, $pad_string, $pad_type, $encoding); } +} + if (extension_loaded('mbstring')) { return; } diff --git a/data/web/inc/lib/vendor/symfony/polyfill-mbstring/bootstrap80.php b/data/web/inc/lib/vendor/symfony/polyfill-mbstring/bootstrap80.php index 82f5ac4d0..2f9fb5b42 100644 --- a/data/web/inc/lib/vendor/symfony/polyfill-mbstring/bootstrap80.php +++ b/data/web/inc/lib/vendor/symfony/polyfill-mbstring/bootstrap80.php @@ -128,6 +128,10 @@ if (!function_exists('mb_str_split')) { function mb_str_split(?string $string, ?int $length = 1, ?string $encoding = null): array { return p\Mbstring::mb_str_split((string) $string, (int) $length, $encoding); } } +if (!function_exists('mb_str_pad')) { + function mb_str_pad(string $string, int $length, string $pad_string = ' ', int $pad_type = STR_PAD_RIGHT, ?string $encoding = null): string { return p\Mbstring::mb_str_pad($string, $length, $pad_string, $pad_type, $encoding); } +} + if (extension_loaded('mbstring')) { return; } diff --git a/data/web/inc/lib/vendor/symfony/polyfill-mbstring/composer.json b/data/web/inc/lib/vendor/symfony/polyfill-mbstring/composer.json index 1fa21ca16..bd99d4b9d 100644 --- a/data/web/inc/lib/vendor/symfony/polyfill-mbstring/composer.json +++ b/data/web/inc/lib/vendor/symfony/polyfill-mbstring/composer.json @@ -30,9 +30,6 @@ }, "minimum-stability": "dev", "extra": { - "branch-alias": { - "dev-main": "1.23-dev" - }, "thanks": { "name": "symfony/polyfill", "url": "https://github.com/symfony/polyfill" diff --git a/data/web/inc/lib/vendor/symfony/polyfill-php80/LICENSE b/data/web/inc/lib/vendor/symfony/polyfill-php80/LICENSE index 5593b1d84..0ed3a2465 100644 --- a/data/web/inc/lib/vendor/symfony/polyfill-php80/LICENSE +++ b/data/web/inc/lib/vendor/symfony/polyfill-php80/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2020 Fabien Potencier +Copyright (c) 2020-present Fabien Potencier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/data/web/inc/lib/vendor/symfony/polyfill-php80/Php80.php b/data/web/inc/lib/vendor/symfony/polyfill-php80/Php80.php index 5fef51184..362dd1a95 100644 --- a/data/web/inc/lib/vendor/symfony/polyfill-php80/Php80.php +++ b/data/web/inc/lib/vendor/symfony/polyfill-php80/Php80.php @@ -100,6 +100,16 @@ final class Php80 public static function str_ends_with(string $haystack, string $needle): bool { - return '' === $needle || ('' !== $haystack && 0 === substr_compare($haystack, $needle, -\strlen($needle))); + if ('' === $needle || $needle === $haystack) { + return true; + } + + if ('' === $haystack) { + return false; + } + + $needleLength = \strlen($needle); + + return $needleLength <= \strlen($haystack) && 0 === substr_compare($haystack, $needle, -$needleLength); } } diff --git a/data/web/inc/lib/vendor/symfony/polyfill-php80/PhpToken.php b/data/web/inc/lib/vendor/symfony/polyfill-php80/PhpToken.php new file mode 100644 index 000000000..fe6e69105 --- /dev/null +++ b/data/web/inc/lib/vendor/symfony/polyfill-php80/PhpToken.php @@ -0,0 +1,103 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Php80; + +/** + * @author Fedonyuk Anton + * + * @internal + */ +class PhpToken implements \Stringable +{ + /** + * @var int + */ + public $id; + + /** + * @var string + */ + public $text; + + /** + * @var int + */ + public $line; + + /** + * @var int + */ + public $pos; + + public function __construct(int $id, string $text, int $line = -1, int $position = -1) + { + $this->id = $id; + $this->text = $text; + $this->line = $line; + $this->pos = $position; + } + + public function getTokenName(): ?string + { + if ('UNKNOWN' === $name = token_name($this->id)) { + $name = \strlen($this->text) > 1 || \ord($this->text) < 32 ? null : $this->text; + } + + return $name; + } + + /** + * @param int|string|array $kind + */ + public function is($kind): bool + { + foreach ((array) $kind as $value) { + if (\in_array($value, [$this->id, $this->text], true)) { + return true; + } + } + + return false; + } + + public function isIgnorable(): bool + { + return \in_array($this->id, [\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT, \T_OPEN_TAG], true); + } + + public function __toString(): string + { + return (string) $this->text; + } + + /** + * @return static[] + */ + public static function tokenize(string $code, int $flags = 0): array + { + $line = 1; + $position = 0; + $tokens = token_get_all($code, $flags); + foreach ($tokens as $index => $token) { + if (\is_string($token)) { + $id = \ord($token); + $text = $token; + } else { + [$id, $text, $line] = $token; + } + $tokens[$index] = new static($id, $text, $line, $position); + $position += \strlen($text); + } + + return $tokens; + } +} diff --git a/data/web/inc/lib/vendor/symfony/polyfill-php80/README.md b/data/web/inc/lib/vendor/symfony/polyfill-php80/README.md index 10b8ee49a..3816c559d 100644 --- a/data/web/inc/lib/vendor/symfony/polyfill-php80/README.md +++ b/data/web/inc/lib/vendor/symfony/polyfill-php80/README.md @@ -3,12 +3,13 @@ Symfony Polyfill / Php80 This component provides features added to PHP 8.0 core: -- `Stringable` interface +- [`Stringable`](https://php.net/stringable) interface - [`fdiv`](https://php.net/fdiv) -- `ValueError` class -- `UnhandledMatchError` class +- [`ValueError`](https://php.net/valueerror) class +- [`UnhandledMatchError`](https://php.net/unhandledmatcherror) class - `FILTER_VALIDATE_BOOL` constant - [`get_debug_type`](https://php.net/get_debug_type) +- [`PhpToken`](https://php.net/phptoken) class - [`preg_last_error_msg`](https://php.net/preg_last_error_msg) - [`str_contains`](https://php.net/str_contains) - [`str_starts_with`](https://php.net/str_starts_with) diff --git a/data/web/inc/lib/vendor/symfony/polyfill-php80/Resources/stubs/Attribute.php b/data/web/inc/lib/vendor/symfony/polyfill-php80/Resources/stubs/Attribute.php index 7ea6d2772..2b955423f 100644 --- a/data/web/inc/lib/vendor/symfony/polyfill-php80/Resources/stubs/Attribute.php +++ b/data/web/inc/lib/vendor/symfony/polyfill-php80/Resources/stubs/Attribute.php @@ -1,5 +1,14 @@ + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + #[Attribute(Attribute::TARGET_CLASS)] final class Attribute { diff --git a/data/web/inc/lib/vendor/symfony/polyfill-php80/Resources/stubs/PhpToken.php b/data/web/inc/lib/vendor/symfony/polyfill-php80/Resources/stubs/PhpToken.php new file mode 100644 index 000000000..bd1212f6e --- /dev/null +++ b/data/web/inc/lib/vendor/symfony/polyfill-php80/Resources/stubs/PhpToken.php @@ -0,0 +1,16 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (\PHP_VERSION_ID < 80000 && extension_loaded('tokenizer')) { + class PhpToken extends Symfony\Polyfill\Php80\PhpToken + { + } +} diff --git a/data/web/inc/lib/vendor/symfony/polyfill-php80/Resources/stubs/Stringable.php b/data/web/inc/lib/vendor/symfony/polyfill-php80/Resources/stubs/Stringable.php index 77e037cb5..7c62d7508 100644 --- a/data/web/inc/lib/vendor/symfony/polyfill-php80/Resources/stubs/Stringable.php +++ b/data/web/inc/lib/vendor/symfony/polyfill-php80/Resources/stubs/Stringable.php @@ -1,5 +1,14 @@ + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + if (\PHP_VERSION_ID < 80000) { interface Stringable { diff --git a/data/web/inc/lib/vendor/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php b/data/web/inc/lib/vendor/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php index 37937cbfa..01c6c6c8a 100644 --- a/data/web/inc/lib/vendor/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php +++ b/data/web/inc/lib/vendor/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php @@ -1,5 +1,14 @@ + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + if (\PHP_VERSION_ID < 80000) { class UnhandledMatchError extends Error { diff --git a/data/web/inc/lib/vendor/symfony/polyfill-php80/Resources/stubs/ValueError.php b/data/web/inc/lib/vendor/symfony/polyfill-php80/Resources/stubs/ValueError.php index a3a9b88b0..783dbc28c 100644 --- a/data/web/inc/lib/vendor/symfony/polyfill-php80/Resources/stubs/ValueError.php +++ b/data/web/inc/lib/vendor/symfony/polyfill-php80/Resources/stubs/ValueError.php @@ -1,5 +1,14 @@ + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + if (\PHP_VERSION_ID < 80000) { class ValueError extends Error { diff --git a/data/web/inc/lib/vendor/symfony/polyfill-php80/composer.json b/data/web/inc/lib/vendor/symfony/polyfill-php80/composer.json index 5fe679db3..46ccde203 100644 --- a/data/web/inc/lib/vendor/symfony/polyfill-php80/composer.json +++ b/data/web/inc/lib/vendor/symfony/polyfill-php80/composer.json @@ -29,9 +29,6 @@ }, "minimum-stability": "dev", "extra": { - "branch-alias": { - "dev-main": "1.23-dev" - }, "thanks": { "name": "symfony/polyfill", "url": "https://github.com/symfony/polyfill" diff --git a/data/web/inc/lib/vendor/symfony/translation-contracts/LICENSE b/data/web/inc/lib/vendor/symfony/translation-contracts/LICENSE index 235841453..7536caeae 100644 --- a/data/web/inc/lib/vendor/symfony/translation-contracts/LICENSE +++ b/data/web/inc/lib/vendor/symfony/translation-contracts/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2018-2021 Fabien Potencier +Copyright (c) 2018-present Fabien Potencier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/data/web/inc/lib/vendor/symfony/translation-contracts/LocaleAwareInterface.php b/data/web/inc/lib/vendor/symfony/translation-contracts/LocaleAwareInterface.php index 6923b977e..db40ba13e 100644 --- a/data/web/inc/lib/vendor/symfony/translation-contracts/LocaleAwareInterface.php +++ b/data/web/inc/lib/vendor/symfony/translation-contracts/LocaleAwareInterface.php @@ -16,6 +16,8 @@ interface LocaleAwareInterface /** * Sets the current locale. * + * @return void + * * @throws \InvalidArgumentException If the locale contains invalid characters */ public function setLocale(string $locale); diff --git a/data/web/inc/lib/vendor/symfony/translation-contracts/README.md b/data/web/inc/lib/vendor/symfony/translation-contracts/README.md index 42e5c5175..b211d5849 100644 --- a/data/web/inc/lib/vendor/symfony/translation-contracts/README.md +++ b/data/web/inc/lib/vendor/symfony/translation-contracts/README.md @@ -3,7 +3,7 @@ Symfony Translation Contracts A set of abstractions extracted out of the Symfony components. -Can be used to build on semantics that the Symfony components proved useful - and +Can be used to build on semantics that the Symfony components proved useful and that already have battle tested implementations. See https://github.com/symfony/contracts/blob/main/README.md for more information. diff --git a/data/web/inc/lib/vendor/symfony/translation-contracts/Test/TranslatorTest.php b/data/web/inc/lib/vendor/symfony/translation-contracts/Test/TranslatorTest.php index c2c30a917..756228af5 100644 --- a/data/web/inc/lib/vendor/symfony/translation-contracts/Test/TranslatorTest.php +++ b/data/web/inc/lib/vendor/symfony/translation-contracts/Test/TranslatorTest.php @@ -30,7 +30,7 @@ use Symfony\Contracts\Translation\TranslatorTrait; */ class TranslatorTest extends TestCase { - private $defaultLocale; + private string $defaultLocale; protected function setUp(): void { @@ -114,7 +114,7 @@ class TranslatorTest extends TestCase $this->assertEquals('en', $translator->getLocale()); } - public function getTransTests() + public static function getTransTests() { return [ ['Symfony is great!', 'Symfony is great!', []], @@ -122,7 +122,7 @@ class TranslatorTest extends TestCase ]; } - public function getTransChoiceTests() + public static function getTransChoiceTests() { return [ ['There are no apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0], @@ -137,7 +137,7 @@ class TranslatorTest extends TestCase } /** - * @dataProvider getInternal + * @dataProvider getInterval */ public function testInterval($expected, $number, $interval) { @@ -146,7 +146,7 @@ class TranslatorTest extends TestCase $this->assertEquals($expected, $translator->trans($interval.' foo|[1,Inf[ bar', ['%count%' => $number])); } - public function getInternal() + public static function getInterval() { return [ ['foo', 3, '{1,2, 3 ,4}'], @@ -183,13 +183,14 @@ class TranslatorTest extends TestCase */ public function testThrowExceptionIfMatchingMessageCannotBeFound($id, $number) { - $this->expectException(\InvalidArgumentException::class); $translator = $this->getTranslator(); + $this->expectException(\InvalidArgumentException::class); + $translator->trans($id, ['%count%' => $number]); } - public function getNonMatchingMessages() + public static function getNonMatchingMessages() { return [ ['{0} There are no apples|{1} There is one apple', 2], @@ -199,7 +200,7 @@ class TranslatorTest extends TestCase ]; } - public function getChooseTests() + public static function getChooseTests() { return [ ['There are no apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0], @@ -255,13 +256,13 @@ class TranslatorTest extends TestCase new-line in it. Selector = 0.|{1}This is a text with a new-line in it. Selector = 1.|[1,Inf]This is a text with a new-line in it. Selector > 1.', 5], - // with double-quotes and id split accros lines + // with double-quotes and id split across lines ['This is a text with a new-line in it. Selector = 1.', '{0}This is a text with a new-line in it. Selector = 0.|{1}This is a text with a new-line in it. Selector = 1.|[1,Inf]This is a text with a new-line in it. Selector > 1.', 1], - // with single-quotes and id split accros lines + // with single-quotes and id split across lines ['This is a text with a new-line in it. Selector > 1.', '{0}This is a text with a new-line in it. Selector = 0.|{1}This is a text with a @@ -269,9 +270,9 @@ class TranslatorTest extends TestCase new-line in it. Selector > 1.', 5], // with single-quotes and \n in text ['This is a text with a\nnew-line in it. Selector = 0.', '{0}This is a text with a\nnew-line in it. Selector = 0.|{1}This is a text with a\nnew-line in it. Selector = 1.|[1,Inf]This is a text with a\nnew-line in it. Selector > 1.', 0], - // with double-quotes and id split accros lines + // with double-quotes and id split across lines ["This is a text with a\nnew-line in it. Selector = 1.", "{0}This is a text with a\nnew-line in it. Selector = 0.|{1}This is a text with a\nnew-line in it. Selector = 1.|[1,Inf]This is a text with a\nnew-line in it. Selector > 1.", 1], - // esacape pipe + // escape pipe ['This is a text with | in it. Selector = 0.', '{0}This is a text with || in it. Selector = 0.|{1}This is a text with || in it. Selector = 1.', 0], // Empty plural set (2 plural forms) from a .PO file ['', '|', 1], @@ -315,7 +316,7 @@ class TranslatorTest extends TestCase * * As it is impossible to have this ever complete we should try as hard as possible to have it almost complete. */ - public function successLangcodes(): array + public static function successLangcodes(): array { return [ ['1', ['ay', 'bo', 'cgg', 'dz', 'id', 'ja', 'jbo', 'ka', 'kk', 'km', 'ko', 'ky']], @@ -334,7 +335,7 @@ class TranslatorTest extends TestCase * * @return array with nplural together with langcodes */ - public function failingLangcodes(): array + public static function failingLangcodes(): array { return [ ['1', ['fa']], @@ -356,7 +357,7 @@ class TranslatorTest extends TestCase foreach ($matrix as $langCode => $data) { $indexes = array_flip($data); if ($expectSuccess) { - $this->assertEquals($nplural, \count($indexes), "Langcode '$langCode' has '$nplural' plural forms."); + $this->assertCount($nplural, $indexes, "Langcode '$langCode' has '$nplural' plural forms."); } else { $this->assertNotEquals((int) $nplural, \count($indexes), "Langcode '$langCode' has '$nplural' plural forms."); } diff --git a/data/web/inc/lib/vendor/symfony/translation-contracts/TranslatorTrait.php b/data/web/inc/lib/vendor/symfony/translation-contracts/TranslatorTrait.php index 9c264bd29..e3b0adff0 100644 --- a/data/web/inc/lib/vendor/symfony/translation-contracts/TranslatorTrait.php +++ b/data/web/inc/lib/vendor/symfony/translation-contracts/TranslatorTrait.php @@ -23,24 +23,18 @@ trait TranslatorTrait private ?string $locale = null; /** - * {@inheritdoc} + * @return void */ public function setLocale(string $locale) { $this->locale = $locale; } - /** - * {@inheritdoc} - */ public function getLocale(): string { return $this->locale ?: (class_exists(\Locale::class) ? \Locale::getDefault() : 'en'); } - /** - * {@inheritdoc} - */ public function trans(?string $id, array $parameters = [], string $domain = null, string $locale = null): string { if (null === $id || '' === $id) { @@ -140,121 +134,92 @@ EOF; { $number = abs($number); - switch ('pt_BR' !== $locale && 'en_US_POSIX' !== $locale && \strlen($locale) > 3 ? substr($locale, 0, strrpos($locale, '_')) : $locale) { - case 'af': - case 'bn': - case 'bg': - case 'ca': - case 'da': - case 'de': - case 'el': - case 'en': - case 'en_US_POSIX': - case 'eo': - case 'es': - case 'et': - case 'eu': - case 'fa': - case 'fi': - case 'fo': - case 'fur': - case 'fy': - case 'gl': - case 'gu': - case 'ha': - case 'he': - case 'hu': - case 'is': - case 'it': - case 'ku': - case 'lb': - case 'ml': - case 'mn': - case 'mr': - case 'nah': - case 'nb': - case 'ne': - case 'nl': - case 'nn': - case 'no': - case 'oc': - case 'om': - case 'or': - case 'pa': - case 'pap': - case 'ps': - case 'pt': - case 'so': - case 'sq': - case 'sv': - case 'sw': - case 'ta': - case 'te': - case 'tk': - case 'ur': - case 'zu': - return (1 == $number) ? 0 : 1; - - case 'am': - case 'bh': - case 'fil': - case 'fr': - case 'gun': - case 'hi': - case 'hy': - case 'ln': - case 'mg': - case 'nso': - case 'pt_BR': - case 'ti': - case 'wa': - return ($number < 2) ? 0 : 1; - - case 'be': - case 'bs': - case 'hr': - case 'ru': - case 'sh': - case 'sr': - case 'uk': - return ((1 == $number % 10) && (11 != $number % 100)) ? 0 : ((($number % 10 >= 2) && ($number % 10 <= 4) && (($number % 100 < 10) || ($number % 100 >= 20))) ? 1 : 2); - - case 'cs': - case 'sk': - return (1 == $number) ? 0 : ((($number >= 2) && ($number <= 4)) ? 1 : 2); - - case 'ga': - return (1 == $number) ? 0 : ((2 == $number) ? 1 : 2); - - case 'lt': - return ((1 == $number % 10) && (11 != $number % 100)) ? 0 : ((($number % 10 >= 2) && (($number % 100 < 10) || ($number % 100 >= 20))) ? 1 : 2); - - case 'sl': - return (1 == $number % 100) ? 0 : ((2 == $number % 100) ? 1 : (((3 == $number % 100) || (4 == $number % 100)) ? 2 : 3)); - - case 'mk': - return (1 == $number % 10) ? 0 : 1; - - case 'mt': - return (1 == $number) ? 0 : (((0 == $number) || (($number % 100 > 1) && ($number % 100 < 11))) ? 1 : ((($number % 100 > 10) && ($number % 100 < 20)) ? 2 : 3)); - - case 'lv': - return (0 == $number) ? 0 : (((1 == $number % 10) && (11 != $number % 100)) ? 1 : 2); - - case 'pl': - return (1 == $number) ? 0 : ((($number % 10 >= 2) && ($number % 10 <= 4) && (($number % 100 < 12) || ($number % 100 > 14))) ? 1 : 2); - - case 'cy': - return (1 == $number) ? 0 : ((2 == $number) ? 1 : (((8 == $number) || (11 == $number)) ? 2 : 3)); - - case 'ro': - return (1 == $number) ? 0 : (((0 == $number) || (($number % 100 > 0) && ($number % 100 < 20))) ? 1 : 2); - - case 'ar': - return (0 == $number) ? 0 : ((1 == $number) ? 1 : ((2 == $number) ? 2 : ((($number % 100 >= 3) && ($number % 100 <= 10)) ? 3 : ((($number % 100 >= 11) && ($number % 100 <= 99)) ? 4 : 5)))); - - default: - return 0; - } + return match ('pt_BR' !== $locale && 'en_US_POSIX' !== $locale && \strlen($locale) > 3 ? substr($locale, 0, strrpos($locale, '_')) : $locale) { + 'af', + 'bn', + 'bg', + 'ca', + 'da', + 'de', + 'el', + 'en', + 'en_US_POSIX', + 'eo', + 'es', + 'et', + 'eu', + 'fa', + 'fi', + 'fo', + 'fur', + 'fy', + 'gl', + 'gu', + 'ha', + 'he', + 'hu', + 'is', + 'it', + 'ku', + 'lb', + 'ml', + 'mn', + 'mr', + 'nah', + 'nb', + 'ne', + 'nl', + 'nn', + 'no', + 'oc', + 'om', + 'or', + 'pa', + 'pap', + 'ps', + 'pt', + 'so', + 'sq', + 'sv', + 'sw', + 'ta', + 'te', + 'tk', + 'ur', + 'zu' => (1 == $number) ? 0 : 1, + 'am', + 'bh', + 'fil', + 'fr', + 'gun', + 'hi', + 'hy', + 'ln', + 'mg', + 'nso', + 'pt_BR', + 'ti', + 'wa' => ($number < 2) ? 0 : 1, + 'be', + 'bs', + 'hr', + 'ru', + 'sh', + 'sr', + 'uk' => ((1 == $number % 10) && (11 != $number % 100)) ? 0 : ((($number % 10 >= 2) && ($number % 10 <= 4) && (($number % 100 < 10) || ($number % 100 >= 20))) ? 1 : 2), + 'cs', + 'sk' => (1 == $number) ? 0 : ((($number >= 2) && ($number <= 4)) ? 1 : 2), + 'ga' => (1 == $number) ? 0 : ((2 == $number) ? 1 : 2), + 'lt' => ((1 == $number % 10) && (11 != $number % 100)) ? 0 : ((($number % 10 >= 2) && (($number % 100 < 10) || ($number % 100 >= 20))) ? 1 : 2), + 'sl' => (1 == $number % 100) ? 0 : ((2 == $number % 100) ? 1 : (((3 == $number % 100) || (4 == $number % 100)) ? 2 : 3)), + 'mk' => (1 == $number % 10) ? 0 : 1, + 'mt' => (1 == $number) ? 0 : (((0 == $number) || (($number % 100 > 1) && ($number % 100 < 11))) ? 1 : ((($number % 100 > 10) && ($number % 100 < 20)) ? 2 : 3)), + 'lv' => (0 == $number) ? 0 : (((1 == $number % 10) && (11 != $number % 100)) ? 1 : 2), + 'pl' => (1 == $number) ? 0 : ((($number % 10 >= 2) && ($number % 10 <= 4) && (($number % 100 < 12) || ($number % 100 > 14))) ? 1 : 2), + 'cy' => (1 == $number) ? 0 : ((2 == $number) ? 1 : (((8 == $number) || (11 == $number)) ? 2 : 3)), + 'ro' => (1 == $number) ? 0 : (((0 == $number) || (($number % 100 > 0) && ($number % 100 < 20))) ? 1 : 2), + 'ar' => (0 == $number) ? 0 : ((1 == $number) ? 1 : ((2 == $number) ? 2 : ((($number % 100 >= 3) && ($number % 100 <= 10)) ? 3 : ((($number % 100 >= 11) && ($number % 100 <= 99)) ? 4 : 5)))), + default => 0, + }; } } diff --git a/data/web/inc/lib/vendor/symfony/translation-contracts/composer.json b/data/web/inc/lib/vendor/symfony/translation-contracts/composer.json index 875242f6d..213b5cda8 100644 --- a/data/web/inc/lib/vendor/symfony/translation-contracts/composer.json +++ b/data/web/inc/lib/vendor/symfony/translation-contracts/composer.json @@ -16,18 +16,18 @@ } ], "require": { - "php": ">=8.0.2" - }, - "suggest": { - "symfony/translation-implementation": "" + "php": ">=8.1" }, "autoload": { - "psr-4": { "Symfony\\Contracts\\Translation\\": "" } + "psr-4": { "Symfony\\Contracts\\Translation\\": "" }, + "exclude-from-classmap": [ + "/Test/" + ] }, "minimum-stability": "dev", "extra": { "branch-alias": { - "dev-main": "3.0-dev" + "dev-main": "3.4-dev" }, "thanks": { "name": "symfony/contracts", diff --git a/data/web/inc/lib/vendor/symfony/translation/CHANGELOG.md b/data/web/inc/lib/vendor/symfony/translation/CHANGELOG.md index 160b5e694..5f9098c07 100644 --- a/data/web/inc/lib/vendor/symfony/translation/CHANGELOG.md +++ b/data/web/inc/lib/vendor/symfony/translation/CHANGELOG.md @@ -1,6 +1,35 @@ CHANGELOG ========= +6.4 +--- + + * Give current locale to `LocaleSwitcher::runWithLocale()`'s callback + * Add `--as-tree` option to `translation:pull` command to write YAML messages as a tree-like structure + * [BC BREAK] Add argument `$buildDir` to `DataCollectorTranslator::warmUp()` + * Add `DataCollectorTranslatorPass` and `LoggingTranslatorPass` (moved from `FrameworkBundle`) + * Add `PhraseTranslationProvider` + +6.2.7 +----- + + * [BC BREAK] The following data providers for `ProviderFactoryTestCase` are now static: + `supportsProvider()`, `createProvider()`, `unsupportedSchemeProvider()`and `incompleteDsnProvider()` + * [BC BREAK] `ProviderTestCase::toStringProvider()` is now static + +6.2 +--- + + * Deprecate `PhpStringTokenParser` + * Deprecate `PhpExtractor` in favor of `PhpAstExtractor` + * Add `PhpAstExtractor` (requires [nikic/php-parser](https://github.com/nikic/php-parser) to be installed) + +6.1 +--- + + * Parameters implementing `TranslatableInterface` are processed + * Add the file extension to the `XliffFileDumper` constructor + 5.4 --- diff --git a/data/web/inc/lib/vendor/symfony/translation/Catalogue/AbstractOperation.php b/data/web/inc/lib/vendor/symfony/translation/Catalogue/AbstractOperation.php index 43a52fab2..7dff58ff4 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Catalogue/AbstractOperation.php +++ b/data/web/inc/lib/vendor/symfony/translation/Catalogue/AbstractOperation.php @@ -34,11 +34,6 @@ abstract class AbstractOperation implements OperationInterface protected $target; protected $result; - /** - * @var array|null The domains affected by this operation - */ - private $domains; - /** * This array stores 'all', 'new' and 'obsolete' messages for all valid domains. * @@ -62,6 +57,8 @@ abstract class AbstractOperation implements OperationInterface */ protected $messages; + private array $domains; + /** * @throws LogicException */ @@ -77,12 +74,9 @@ abstract class AbstractOperation implements OperationInterface $this->messages = []; } - /** - * {@inheritdoc} - */ public function getDomains(): array { - if (null === $this->domains) { + if (!isset($this->domains)) { $domains = []; foreach ([$this->source, $this->target] as $catalogue) { foreach ($catalogue->getDomains() as $domain) { @@ -100,9 +94,6 @@ abstract class AbstractOperation implements OperationInterface return $this->domains; } - /** - * {@inheritdoc} - */ public function getMessages(string $domain): array { if (!\in_array($domain, $this->getDomains())) { @@ -116,9 +107,6 @@ abstract class AbstractOperation implements OperationInterface return $this->messages[$domain][self::ALL_BATCH]; } - /** - * {@inheritdoc} - */ public function getNewMessages(string $domain): array { if (!\in_array($domain, $this->getDomains())) { @@ -132,9 +120,6 @@ abstract class AbstractOperation implements OperationInterface return $this->messages[$domain][self::NEW_BATCH]; } - /** - * {@inheritdoc} - */ public function getObsoleteMessages(string $domain): array { if (!\in_array($domain, $this->getDomains())) { @@ -148,9 +133,6 @@ abstract class AbstractOperation implements OperationInterface return $this->messages[$domain][self::OBSOLETE_BATCH]; } - /** - * {@inheritdoc} - */ public function getResult(): MessageCatalogueInterface { foreach ($this->getDomains() as $domain) { @@ -174,12 +156,12 @@ abstract class AbstractOperation implements OperationInterface foreach ($this->getDomains() as $domain) { $intlDomain = $domain.MessageCatalogueInterface::INTL_DOMAIN_SUFFIX; - switch ($batch) { - case self::OBSOLETE_BATCH: $messages = $this->getObsoleteMessages($domain); break; - case self::NEW_BATCH: $messages = $this->getNewMessages($domain); break; - case self::ALL_BATCH: $messages = $this->getMessages($domain); break; - default: throw new \InvalidArgumentException(sprintf('$batch argument must be one of ["%s", "%s", "%s"].', self::ALL_BATCH, self::NEW_BATCH, self::OBSOLETE_BATCH)); - } + $messages = match ($batch) { + self::OBSOLETE_BATCH => $this->getObsoleteMessages($domain), + self::NEW_BATCH => $this->getNewMessages($domain), + self::ALL_BATCH => $this->getMessages($domain), + default => throw new \InvalidArgumentException(sprintf('$batch argument must be one of ["%s", "%s", "%s"].', self::ALL_BATCH, self::NEW_BATCH, self::OBSOLETE_BATCH)), + }; if (!$messages || (!$this->source->all($intlDomain) && $this->source->all($domain))) { continue; @@ -198,6 +180,8 @@ abstract class AbstractOperation implements OperationInterface * stores the results. * * @param string $domain The domain which the operation will be performed for + * + * @return void */ abstract protected function processDomain(string $domain); } diff --git a/data/web/inc/lib/vendor/symfony/translation/Catalogue/MergeOperation.php b/data/web/inc/lib/vendor/symfony/translation/Catalogue/MergeOperation.php index 87db2fb03..1b777a843 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Catalogue/MergeOperation.php +++ b/data/web/inc/lib/vendor/symfony/translation/Catalogue/MergeOperation.php @@ -25,7 +25,7 @@ use Symfony\Component\Translation\MessageCatalogueInterface; class MergeOperation extends AbstractOperation { /** - * {@inheritdoc} + * @return void */ protected function processDomain(string $domain) { @@ -36,6 +36,18 @@ class MergeOperation extends AbstractOperation ]; $intlDomain = $domain.MessageCatalogueInterface::INTL_DOMAIN_SUFFIX; + foreach ($this->target->getCatalogueMetadata('', $domain) ?? [] as $key => $value) { + if (null === $this->result->getCatalogueMetadata($key, $domain)) { + $this->result->setCatalogueMetadata($key, $value, $domain); + } + } + + foreach ($this->target->getCatalogueMetadata('', $intlDomain) ?? [] as $key => $value) { + if (null === $this->result->getCatalogueMetadata($key, $intlDomain)) { + $this->result->setCatalogueMetadata($key, $value, $intlDomain); + } + } + foreach ($this->source->all($domain) as $id => $message) { $this->messages[$domain]['all'][$id] = $message; $d = $this->source->defines($id, $intlDomain) ? $intlDomain : $domain; diff --git a/data/web/inc/lib/vendor/symfony/translation/Catalogue/TargetOperation.php b/data/web/inc/lib/vendor/symfony/translation/Catalogue/TargetOperation.php index 682b5752f..2c0ec722e 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Catalogue/TargetOperation.php +++ b/data/web/inc/lib/vendor/symfony/translation/Catalogue/TargetOperation.php @@ -26,7 +26,7 @@ use Symfony\Component\Translation\MessageCatalogueInterface; class TargetOperation extends AbstractOperation { /** - * {@inheritdoc} + * @return void */ protected function processDomain(string $domain) { @@ -37,6 +37,18 @@ class TargetOperation extends AbstractOperation ]; $intlDomain = $domain.MessageCatalogueInterface::INTL_DOMAIN_SUFFIX; + foreach ($this->target->getCatalogueMetadata('', $domain) ?? [] as $key => $value) { + if (null === $this->result->getCatalogueMetadata($key, $domain)) { + $this->result->setCatalogueMetadata($key, $value, $domain); + } + } + + foreach ($this->target->getCatalogueMetadata('', $intlDomain) ?? [] as $key => $value) { + if (null === $this->result->getCatalogueMetadata($key, $intlDomain)) { + $this->result->setCatalogueMetadata($key, $value, $intlDomain); + } + } + // For 'all' messages, the code can't be simplified as ``$this->messages[$domain]['all'] = $target->all($domain);``, // because doing so will drop messages like {x: x ∈ source ∧ x ∉ target.all ∧ x ∈ target.fallback} // diff --git a/data/web/inc/lib/vendor/symfony/translation/CatalogueMetadataAwareInterface.php b/data/web/inc/lib/vendor/symfony/translation/CatalogueMetadataAwareInterface.php new file mode 100644 index 000000000..c845959f1 --- /dev/null +++ b/data/web/inc/lib/vendor/symfony/translation/CatalogueMetadataAwareInterface.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation; + +/** + * This interface is used to get, set, and delete metadata about the Catalogue. + * + * @author Hugo Alliaume + */ +interface CatalogueMetadataAwareInterface +{ + /** + * Gets catalogue metadata for the given domain and key. + * + * Passing an empty domain will return an array with all catalogue metadata indexed by + * domain and then by key. Passing an empty key will return an array with all + * catalogue metadata for the given domain. + * + * @return mixed The value that was set or an array with the domains/keys or null + */ + public function getCatalogueMetadata(string $key = '', string $domain = 'messages'): mixed; + + /** + * Adds catalogue metadata to a message domain. + * + * @return void + */ + public function setCatalogueMetadata(string $key, mixed $value, string $domain = 'messages'); + + /** + * Deletes catalogue metadata for the given key and domain. + * + * Passing an empty domain will delete all catalogue metadata. Passing an empty key will + * delete all metadata for the given domain. + * + * @return void + */ + public function deleteCatalogueMetadata(string $key = '', string $domain = 'messages'); +} diff --git a/data/web/inc/lib/vendor/symfony/translation/Command/TranslationPullCommand.php b/data/web/inc/lib/vendor/symfony/translation/Command/TranslationPullCommand.php index 42513a8a8..5d9c092c3 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Command/TranslationPullCommand.php +++ b/data/web/inc/lib/vendor/symfony/translation/Command/TranslationPullCommand.php @@ -34,9 +34,9 @@ final class TranslationPullCommand extends Command { use TranslationTrait; - private $providerCollection; - private $writer; - private $reader; + private TranslationProviderCollection $providerCollection; + private TranslationWriterInterface $writer; + private TranslationReaderInterface $reader; private string $defaultLocale; private array $transPaths; private array $enabledLocales; @@ -64,9 +64,8 @@ final class TranslationPullCommand extends Command if ($input->mustSuggestOptionValuesFor('domains')) { $provider = $this->providerCollection->get($input->getArgument('provider')); - if ($provider && method_exists($provider, 'getDomains')) { - $domains = $provider->getDomains(); - $suggestions->suggestValues($domains); + if (method_exists($provider, 'getDomains')) { + $suggestions->suggestValues($provider->getDomains()); } return; @@ -83,10 +82,7 @@ final class TranslationPullCommand extends Command } } - /** - * {@inheritdoc} - */ - protected function configure() + protected function configure(): void { $keys = $this->providerCollection->keys(); $defaultProvider = 1 === \count($keys) ? $keys[0] : null; @@ -99,6 +95,7 @@ final class TranslationPullCommand extends Command new InputOption('domains', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'Specify the domains to pull.'), new InputOption('locales', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'Specify the locales to pull.'), new InputOption('format', null, InputOption::VALUE_OPTIONAL, 'Override the default output format.', 'xlf12'), + new InputOption('as-tree', null, InputOption::VALUE_OPTIONAL, 'Write messages as a tree-like structure. Needs --format=yaml. The given value defines the level where to switch to inline YAML'), ]) ->setHelp(<<<'EOF' The %command.name% command pulls translations from the given provider. Only @@ -120,9 +117,6 @@ EOF ; } - /** - * {@inheritdoc} - */ protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); @@ -133,6 +127,7 @@ EOF $locales = $input->getOption('locales') ?: $this->enabledLocales; $domains = $input->getOption('domains'); $format = $input->getOption('format'); + $asTree = (int) $input->getOption('as-tree'); $xliffVersion = '1.2'; if ($intlIcu && !$force) { @@ -141,7 +136,7 @@ EOF switch ($format) { case 'xlf20': $xliffVersion = '2.0'; - // no break + // no break case 'xlf12': $format = 'xlf'; } @@ -149,6 +144,8 @@ EOF 'path' => end($this->transPaths), 'xliff_version' => $xliffVersion, 'default_locale' => $this->defaultLocale, + 'as_tree' => (bool) $asTree, + 'inline' => $asTree, ]; if (!$domains) { @@ -159,7 +156,7 @@ EOF if ($force) { foreach ($providerTranslations->getCatalogues() as $catalogue) { - $operation = new TargetOperation((new MessageCatalogue($catalogue->getLocale())), $catalogue); + $operation = new TargetOperation(new MessageCatalogue($catalogue->getLocale()), $catalogue); if ($intlIcu) { $operation->moveMessagesToIntlDomainsIfPossible(); } diff --git a/data/web/inc/lib/vendor/symfony/translation/Command/TranslationPushCommand.php b/data/web/inc/lib/vendor/symfony/translation/Command/TranslationPushCommand.php index dba21643d..1d04adbc9 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Command/TranslationPushCommand.php +++ b/data/web/inc/lib/vendor/symfony/translation/Command/TranslationPushCommand.php @@ -21,6 +21,7 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; +use Symfony\Component\Translation\Provider\FilteringProvider; use Symfony\Component\Translation\Provider\TranslationProviderCollection; use Symfony\Component\Translation\Reader\TranslationReaderInterface; use Symfony\Component\Translation\TranslatorBag; @@ -33,8 +34,8 @@ final class TranslationPushCommand extends Command { use TranslationTrait; - private $providers; - private $reader; + private TranslationProviderCollection $providers; + private TranslationReaderInterface $reader; private array $transPaths; private array $enabledLocales; @@ -72,10 +73,7 @@ final class TranslationPushCommand extends Command } } - /** - * {@inheritdoc} - */ - protected function configure() + protected function configure(): void { $keys = $this->providers->keys(); $defaultProvider = 1 === \count($keys) ? $keys[0] : null; @@ -112,15 +110,12 @@ EOF ; } - /** - * {@inheritdoc} - */ protected function execute(InputInterface $input, OutputInterface $output): int { $provider = $this->providers->get($input->getArgument('provider')); if (!$this->enabledLocales) { - throw new InvalidArgumentException(sprintf('You must define "framework.translator.enabled_locales" or "framework.translator.providers.%s.locales" config key in order to work with translation providers.', parse_url($provider, \PHP_URL_SCHEME))); + throw new InvalidArgumentException(sprintf('You must define "framework.enabled_locales" or "framework.translator.providers.%s.locales" config key in order to work with translation providers.', parse_url($provider, \PHP_URL_SCHEME))); } $io = new SymfonyStyle($input, $output); @@ -129,6 +124,12 @@ EOF $force = $input->getOption('force'); $deleteMissing = $input->getOption('delete-missing'); + if (!$domains && $provider instanceof FilteringProvider) { + $domains = $provider->getDomains(); + } + + // Reading local translations must be done after retrieving the domains from the provider + // in order to manage only translations from configured domains $localTranslations = $this->readLocalTranslations($locales, $domains, $this->transPaths); if (!$domains) { diff --git a/data/web/inc/lib/vendor/symfony/translation/Command/XliffLintCommand.php b/data/web/inc/lib/vendor/symfony/translation/Command/XliffLintCommand.php index f062fb79f..ba946389e 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Command/XliffLintCommand.php +++ b/data/web/inc/lib/vendor/symfony/translation/Command/XliffLintCommand.php @@ -41,23 +41,23 @@ class XliffLintCommand extends Command private ?\Closure $isReadableProvider; private bool $requireStrictFileNames; - public function __construct(string $name = null, callable $directoryIteratorProvider = null, callable $isReadableProvider = null, bool $requireStrictFileNames = true) + public function __construct(?string $name = null, ?callable $directoryIteratorProvider = null, ?callable $isReadableProvider = null, bool $requireStrictFileNames = true) { parent::__construct($name); - $this->directoryIteratorProvider = null === $directoryIteratorProvider || $directoryIteratorProvider instanceof \Closure ? $directoryIteratorProvider : \Closure::fromCallable($directoryIteratorProvider); - $this->isReadableProvider = null === $isReadableProvider || $isReadableProvider instanceof \Closure ? $isReadableProvider : \Closure::fromCallable($isReadableProvider); + $this->directoryIteratorProvider = null === $directoryIteratorProvider ? null : $directoryIteratorProvider(...); + $this->isReadableProvider = null === $isReadableProvider ? null : $isReadableProvider(...); $this->requireStrictFileNames = $requireStrictFileNames; } /** - * {@inheritdoc} + * @return void */ protected function configure() { $this ->addArgument('filename', InputArgument::IS_ARRAY, 'A file, a directory or "-" for reading from STDIN') - ->addOption('format', null, InputOption::VALUE_REQUIRED, 'The output format') + ->addOption('format', null, InputOption::VALUE_REQUIRED, sprintf('The output format ("%s")', implode('", "', $this->getAvailableFormatOptions()))) ->setHelp(<<%command.name% command lints an XLIFF file and outputs to STDOUT the first encountered syntax error. @@ -109,7 +109,7 @@ EOF return $this->display($io, $filesInfo); } - private function validate(string $content, string $file = null): array + private function validate(string $content, ?string $file = null): array { $errors = []; @@ -154,21 +154,17 @@ EOF return ['file' => $file, 'valid' => 0 === \count($errors), 'messages' => $errors]; } - private function display(SymfonyStyle $io, array $files) + private function display(SymfonyStyle $io, array $files): int { - switch ($this->format) { - case 'txt': - return $this->displayTxt($io, $files); - case 'json': - return $this->displayJson($io, $files); - case 'github': - return $this->displayTxt($io, $files, true); - default: - throw new InvalidArgumentException(sprintf('The format "%s" is not supported.', $this->format)); - } + return match ($this->format) { + 'txt' => $this->displayTxt($io, $files), + 'json' => $this->displayJson($io, $files), + 'github' => $this->displayTxt($io, $files, true), + default => throw new InvalidArgumentException(sprintf('Supported formats are "%s".', implode('", "', $this->getAvailableFormatOptions()))), + }; } - private function displayTxt(SymfonyStyle $io, array $filesInfo, bool $errorAsGithubAnnotations = false) + private function displayTxt(SymfonyStyle $io, array $filesInfo, bool $errorAsGithubAnnotations = false): int { $countFiles = \count($filesInfo); $erroredFiles = 0; @@ -184,9 +180,7 @@ EOF // general document errors have a '-1' line number $line = -1 === $error['line'] ? null : $error['line']; - if ($githubReporter) { - $githubReporter->error($error['message'], $info['file'], $line, null !== $line ? $error['column'] : null); - } + $githubReporter?->error($error['message'], $info['file'], $line, null !== $line ? $error['column'] : null); return null === $line ? $error['message'] : sprintf('Line %d, Column %d: %s', $line, $error['column'], $error['message']); }, $info['messages'])); @@ -202,7 +196,7 @@ EOF return min($erroredFiles, 1); } - private function displayJson(SymfonyStyle $io, array $filesInfo) + private function displayJson(SymfonyStyle $io, array $filesInfo): int { $errors = 0; @@ -218,7 +212,10 @@ EOF return min($errors, 1); } - private function getFiles(string $fileOrDirectory) + /** + * @return iterable<\SplFileInfo> + */ + private function getFiles(string $fileOrDirectory): iterable { if (is_file($fileOrDirectory)) { yield new \SplFileInfo($fileOrDirectory); @@ -235,14 +232,15 @@ EOF } } - private function getDirectoryIterator(string $directory) + /** + * @return iterable<\SplFileInfo> + */ + private function getDirectoryIterator(string $directory): iterable { - $default = function ($directory) { - return new \RecursiveIteratorIterator( - new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS), - \RecursiveIteratorIterator::LEAVES_ONLY - ); - }; + $default = fn ($directory) => new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS), + \RecursiveIteratorIterator::LEAVES_ONLY + ); if (null !== $this->directoryIteratorProvider) { return ($this->directoryIteratorProvider)($directory, $default); @@ -251,11 +249,9 @@ EOF return $default($directory); } - private function isReadable(string $fileOrDirectory) + private function isReadable(string $fileOrDirectory): bool { - $default = function ($fileOrDirectory) { - return is_readable($fileOrDirectory); - }; + $default = fn ($fileOrDirectory) => is_readable($fileOrDirectory); if (null !== $this->isReadableProvider) { return ($this->isReadableProvider)($fileOrDirectory, $default); @@ -278,7 +274,12 @@ EOF public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void { if ($input->mustSuggestOptionValuesFor('format')) { - $suggestions->suggestValues(['txt', 'json', 'github']); + $suggestions->suggestValues($this->getAvailableFormatOptions()); } } + + private function getAvailableFormatOptions(): array + { + return ['txt', 'json', 'github']; + } } diff --git a/data/web/inc/lib/vendor/symfony/translation/DataCollector/TranslationDataCollector.php b/data/web/inc/lib/vendor/symfony/translation/DataCollector/TranslationDataCollector.php index 0f7901d52..d4f49cc66 100644 --- a/data/web/inc/lib/vendor/symfony/translation/DataCollector/TranslationDataCollector.php +++ b/data/web/inc/lib/vendor/symfony/translation/DataCollector/TranslationDataCollector.php @@ -25,17 +25,14 @@ use Symfony\Component\VarDumper\Cloner\Data; */ class TranslationDataCollector extends DataCollector implements LateDataCollectorInterface { - private $translator; + private DataCollectorTranslator $translator; public function __construct(DataCollectorTranslator $translator) { $this->translator = $translator; } - /** - * {@inheritdoc} - */ - public function lateCollect() + public function lateCollect(): void { $messages = $this->sanitizeCollectedMessages($this->translator->getCollectedMessages()); @@ -45,19 +42,13 @@ class TranslationDataCollector extends DataCollector implements LateDataCollecto $this->data = $this->cloneVar($this->data); } - /** - * {@inheritdoc} - */ - public function collect(Request $request, Response $response, \Throwable $exception = null) + public function collect(Request $request, Response $response, ?\Throwable $exception = null): void { $this->data['locale'] = $this->translator->getLocale(); $this->data['fallback_locales'] = $this->translator->getFallbackLocales(); } - /** - * {@inheritdoc} - */ - public function reset() + public function reset(): void { $this->data = []; } @@ -82,7 +73,7 @@ class TranslationDataCollector extends DataCollector implements LateDataCollecto return $this->data[DataCollectorTranslator::MESSAGE_DEFINED] ?? 0; } - public function getLocale() + public function getLocale(): ?string { return !empty($this->data['locale']) ? $this->data['locale'] : null; } @@ -90,20 +81,17 @@ class TranslationDataCollector extends DataCollector implements LateDataCollecto /** * @internal */ - public function getFallbackLocales() + public function getFallbackLocales(): Data|array { return (isset($this->data['fallback_locales']) && \count($this->data['fallback_locales']) > 0) ? $this->data['fallback_locales'] : []; } - /** - * {@inheritdoc} - */ public function getName(): string { return 'translation'; } - private function sanitizeCollectedMessages(array $messages) + private function sanitizeCollectedMessages(array $messages): array { $result = []; foreach ($messages as $key => $message) { @@ -128,7 +116,7 @@ class TranslationDataCollector extends DataCollector implements LateDataCollecto return $result; } - private function computeCount(array $messages) + private function computeCount(array $messages): array { $count = [ DataCollectorTranslator::MESSAGE_DEFINED => 0, @@ -143,7 +131,7 @@ class TranslationDataCollector extends DataCollector implements LateDataCollecto return $count; } - private function sanitizeString(string $string, int $length = 80) + private function sanitizeString(string $string, int $length = 80): string { $string = trim(preg_replace('/\s+/', ' ', $string)); diff --git a/data/web/inc/lib/vendor/symfony/translation/DataCollectorTranslator.php b/data/web/inc/lib/vendor/symfony/translation/DataCollectorTranslator.php index 2a08b0960..a2832ee8e 100644 --- a/data/web/inc/lib/vendor/symfony/translation/DataCollectorTranslator.php +++ b/data/web/inc/lib/vendor/symfony/translation/DataCollectorTranslator.php @@ -25,7 +25,7 @@ class DataCollectorTranslator implements TranslatorInterface, TranslatorBagInter public const MESSAGE_MISSING = 1; public const MESSAGE_EQUALS_FALLBACK = 2; - private $translator; + private TranslatorInterface $translator; private array $messages = []; /** @@ -40,10 +40,7 @@ class DataCollectorTranslator implements TranslatorInterface, TranslatorBagInter $this->translator = $translator; } - /** - * {@inheritdoc} - */ - public function trans(?string $id, array $parameters = [], string $domain = null, string $locale = null): string + public function trans(?string $id, array $parameters = [], ?string $domain = null, ?string $locale = null): string { $trans = $this->translator->trans($id = (string) $id, $parameters, $domain, $locale); $this->collectMessage($locale, $domain, $id, $trans, $parameters); @@ -52,46 +49,32 @@ class DataCollectorTranslator implements TranslatorInterface, TranslatorBagInter } /** - * {@inheritdoc} + * @return void */ public function setLocale(string $locale) { $this->translator->setLocale($locale); } - /** - * {@inheritdoc} - */ public function getLocale(): string { return $this->translator->getLocale(); } - /** - * {@inheritdoc} - */ - public function getCatalogue(string $locale = null): MessageCatalogueInterface + public function getCatalogue(?string $locale = null): MessageCatalogueInterface { return $this->translator->getCatalogue($locale); } - /** - * {@inheritdoc} - */ public function getCatalogues(): array { return $this->translator->getCatalogues(); } - /** - * {@inheritdoc} - * - * @return string[] - */ - public function warmUp(string $cacheDir): array + public function warmUp(string $cacheDir, ?string $buildDir = null): array { if ($this->translator instanceof WarmableInterface) { - return (array) $this->translator->warmUp($cacheDir); + return (array) $this->translator->warmUp($cacheDir, $buildDir); } return []; @@ -110,7 +93,7 @@ class DataCollectorTranslator implements TranslatorInterface, TranslatorBagInter } /** - * Passes through all unknown calls onto the translator object. + * @return mixed */ public function __call(string $method, array $args) { @@ -122,11 +105,9 @@ class DataCollectorTranslator implements TranslatorInterface, TranslatorBagInter return $this->messages; } - private function collectMessage(?string $locale, ?string $domain, string $id, string $translation, ?array $parameters = []) + private function collectMessage(?string $locale, ?string $domain, string $id, string $translation, ?array $parameters = []): void { - if (null === $domain) { - $domain = 'messages'; - } + $domain ??= 'messages'; $catalogue = $this->translator->getCatalogue($locale); $locale = $catalogue->getLocale(); diff --git a/data/web/inc/lib/vendor/symfony/translation/DependencyInjection/DataCollectorTranslatorPass.php b/data/web/inc/lib/vendor/symfony/translation/DependencyInjection/DataCollectorTranslatorPass.php new file mode 100644 index 000000000..cdf63be4b --- /dev/null +++ b/data/web/inc/lib/vendor/symfony/translation/DependencyInjection/DataCollectorTranslatorPass.php @@ -0,0 +1,36 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\DependencyInjection; + +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\Translation\TranslatorBagInterface; + +/** + * @author Christian Flothmann + */ +class DataCollectorTranslatorPass implements CompilerPassInterface +{ + public function process(ContainerBuilder $container): void + { + if (!$container->has('translator')) { + return; + } + + $translatorClass = $container->getParameterBag()->resolveValue($container->findDefinition('translator')->getClass()); + + if (!is_subclass_of($translatorClass, TranslatorBagInterface::class)) { + $container->removeDefinition('translator.data_collector'); + $container->removeDefinition('data_collector.translation'); + } + } +} diff --git a/data/web/inc/lib/vendor/symfony/translation/DependencyInjection/LoggingTranslatorPass.php b/data/web/inc/lib/vendor/symfony/translation/DependencyInjection/LoggingTranslatorPass.php new file mode 100644 index 000000000..c21552f97 --- /dev/null +++ b/data/web/inc/lib/vendor/symfony/translation/DependencyInjection/LoggingTranslatorPass.php @@ -0,0 +1,59 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\DependencyInjection; + +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; +use Symfony\Component\Translation\TranslatorBagInterface; +use Symfony\Contracts\Translation\TranslatorInterface; + +/** + * @author Abdellatif Ait boudad + */ +class LoggingTranslatorPass implements CompilerPassInterface +{ + public function process(ContainerBuilder $container): void + { + if (!$container->hasAlias('logger') || !$container->hasAlias('translator')) { + return; + } + + if (!$container->hasParameter('translator.logging') || !$container->getParameter('translator.logging')) { + return; + } + + $translatorAlias = $container->getAlias('translator'); + $definition = $container->getDefinition((string) $translatorAlias); + $class = $container->getParameterBag()->resolveValue($definition->getClass()); + + if (!$r = $container->getReflectionClass($class)) { + throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $translatorAlias)); + } + + if (!$r->isSubclassOf(TranslatorInterface::class) || !$r->isSubclassOf(TranslatorBagInterface::class)) { + return; + } + + $container->getDefinition('translator.logging')->setDecoratedService('translator'); + $warmer = $container->getDefinition('translation.warmer'); + $subscriberAttributes = $warmer->getTag('container.service_subscriber'); + $warmer->clearTag('container.service_subscriber'); + + foreach ($subscriberAttributes as $k => $v) { + if ((!isset($v['id']) || 'translator' !== $v['id']) && (!isset($v['key']) || 'translator' !== $v['key'])) { + $warmer->addTag('container.service_subscriber', $v); + } + } + $warmer->addTag('container.service_subscriber', ['key' => 'translator', 'id' => 'translator.logging.inner']); + } +} diff --git a/data/web/inc/lib/vendor/symfony/translation/DependencyInjection/TranslationDumperPass.php b/data/web/inc/lib/vendor/symfony/translation/DependencyInjection/TranslationDumperPass.php index 4020a0788..2ece6ac7b 100644 --- a/data/web/inc/lib/vendor/symfony/translation/DependencyInjection/TranslationDumperPass.php +++ b/data/web/inc/lib/vendor/symfony/translation/DependencyInjection/TranslationDumperPass.php @@ -20,6 +20,9 @@ use Symfony\Component\DependencyInjection\Reference; */ class TranslationDumperPass implements CompilerPassInterface { + /** + * @return void + */ public function process(ContainerBuilder $container) { if (!$container->hasDefinition('translation.writer')) { diff --git a/data/web/inc/lib/vendor/symfony/translation/DependencyInjection/TranslationExtractorPass.php b/data/web/inc/lib/vendor/symfony/translation/DependencyInjection/TranslationExtractorPass.php index ee7c47ae4..1baf9341e 100644 --- a/data/web/inc/lib/vendor/symfony/translation/DependencyInjection/TranslationExtractorPass.php +++ b/data/web/inc/lib/vendor/symfony/translation/DependencyInjection/TranslationExtractorPass.php @@ -21,6 +21,9 @@ use Symfony\Component\DependencyInjection\Reference; */ class TranslationExtractorPass implements CompilerPassInterface { + /** + * @return void + */ public function process(ContainerBuilder $container) { if (!$container->hasDefinition('translation.extractor')) { diff --git a/data/web/inc/lib/vendor/symfony/translation/DependencyInjection/TranslatorPass.php b/data/web/inc/lib/vendor/symfony/translation/DependencyInjection/TranslatorPass.php index be79cdaf0..dd6ea3c83 100644 --- a/data/web/inc/lib/vendor/symfony/translation/DependencyInjection/TranslatorPass.php +++ b/data/web/inc/lib/vendor/symfony/translation/DependencyInjection/TranslatorPass.php @@ -18,6 +18,9 @@ use Symfony\Component\DependencyInjection\Reference; class TranslatorPass implements CompilerPassInterface { + /** + * @return void + */ public function process(ContainerBuilder $container) { if (!$container->hasDefinition('translator.default')) { @@ -49,6 +52,23 @@ class TranslatorPass implements CompilerPassInterface ->replaceArgument(3, $loaders) ; + if ($container->hasDefinition('validator') && $container->hasDefinition('translation.extractor.visitor.constraint')) { + $constraintVisitorDefinition = $container->getDefinition('translation.extractor.visitor.constraint'); + $constraintClassNames = []; + + foreach ($container->getDefinitions() as $definition) { + if (!$definition->hasTag('validator.constraint_validator')) { + continue; + } + // Resolve constraint validator FQCN even if defined as %foo.validator.class% parameter + $className = $container->getParameterBag()->resolveValue($definition->getClass()); + // Extraction of the constraint class name from the Constraint Validator FQCN + $constraintClassNames[] = str_replace('Validator', '', substr(strrchr($className, '\\'), 1)); + } + + $constraintVisitorDefinition->setArgument(0, $constraintClassNames); + } + if (!$container->hasParameter('twig.default_path')) { return; } diff --git a/data/web/inc/lib/vendor/symfony/translation/DependencyInjection/TranslatorPathsPass.php b/data/web/inc/lib/vendor/symfony/translation/DependencyInjection/TranslatorPathsPass.php index b85c06621..1756e3c8c 100644 --- a/data/web/inc/lib/vendor/symfony/translation/DependencyInjection/TranslatorPathsPass.php +++ b/data/web/inc/lib/vendor/symfony/translation/DependencyInjection/TranslatorPathsPass.php @@ -16,12 +16,15 @@ use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ServiceLocator; +use Symfony\Component\HttpKernel\Controller\ArgumentResolver\TraceableValueResolver; /** * @author Yonel Ceruto */ class TranslatorPathsPass extends AbstractRecursivePass { + protected bool $skipScalars = true; + private int $level = 0; /** @@ -39,6 +42,9 @@ class TranslatorPathsPass extends AbstractRecursivePass */ private array $controllers = []; + /** + * @return void + */ public function process(ContainerBuilder $container) { if (!$container->hasDefinition('translator')) { @@ -120,28 +126,20 @@ class TranslatorPathsPass extends AbstractRecursivePass private function findControllerArguments(ContainerBuilder $container): array { - if ($container->hasDefinition('argument_resolver.service')) { - $argument = $container->getDefinition('argument_resolver.service')->getArgument(0); - if ($argument instanceof Reference) { - $argument = $container->getDefinition($argument); - } + if (!$container->has('argument_resolver.service')) { + return []; + } + $resolverDef = $container->findDefinition('argument_resolver.service'); - return $argument->getArgument(0); + if (TraceableValueResolver::class === $resolverDef->getClass()) { + $resolverDef = $container->getDefinition($resolverDef->getArgument(0)); } - if ($container->hasDefinition('debug.'.'argument_resolver.service')) { - $argument = $container->getDefinition('debug.'.'argument_resolver.service')->getArgument(0); - if ($argument instanceof Reference) { - $argument = $container->getDefinition($argument); - } - $argument = $argument->getArgument(0); - if ($argument instanceof Reference) { - $argument = $container->getDefinition($argument); - } - - return $argument->getArgument(0); + $argument = $resolverDef->getArgument(0); + if ($argument instanceof Reference) { + $argument = $container->getDefinition($argument); } - return []; + return $argument->getArgument(0); } } diff --git a/data/web/inc/lib/vendor/symfony/translation/Dumper/CsvFileDumper.php b/data/web/inc/lib/vendor/symfony/translation/Dumper/CsvFileDumper.php index 0bd3f5e0f..8f5475259 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Dumper/CsvFileDumper.php +++ b/data/web/inc/lib/vendor/symfony/translation/Dumper/CsvFileDumper.php @@ -23,9 +23,6 @@ class CsvFileDumper extends FileDumper private string $delimiter = ';'; private string $enclosure = '"'; - /** - * {@inheritdoc} - */ public function formatCatalogue(MessageCatalogue $messages, string $domain, array $options = []): string { $handle = fopen('php://memory', 'r+'); @@ -43,6 +40,8 @@ class CsvFileDumper extends FileDumper /** * Sets the delimiter and escape character for CSV. + * + * @return void */ public function setCsvControl(string $delimiter = ';', string $enclosure = '"') { @@ -50,9 +49,6 @@ class CsvFileDumper extends FileDumper $this->enclosure = $enclosure; } - /** - * {@inheritdoc} - */ protected function getExtension(): string { return 'csv'; diff --git a/data/web/inc/lib/vendor/symfony/translation/Dumper/DumperInterface.php b/data/web/inc/lib/vendor/symfony/translation/Dumper/DumperInterface.php index 7cdaef515..6bf42931e 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Dumper/DumperInterface.php +++ b/data/web/inc/lib/vendor/symfony/translation/Dumper/DumperInterface.php @@ -25,6 +25,8 @@ interface DumperInterface * Dumps the message catalogue. * * @param array $options Options that are used by the dumper + * + * @return void */ public function dump(MessageCatalogue $messages, array $options = []); } diff --git a/data/web/inc/lib/vendor/symfony/translation/Dumper/FileDumper.php b/data/web/inc/lib/vendor/symfony/translation/Dumper/FileDumper.php index 6bad4ff32..e30d4770e 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Dumper/FileDumper.php +++ b/data/web/inc/lib/vendor/symfony/translation/Dumper/FileDumper.php @@ -35,7 +35,7 @@ abstract class FileDumper implements DumperInterface /** * Sets the template for the relative paths to files. * - * @param string $relativePathTemplate A template for the relative paths to files + * @return void */ public function setRelativePathTemplate(string $relativePathTemplate) { @@ -43,7 +43,7 @@ abstract class FileDumper implements DumperInterface } /** - * {@inheritdoc} + * @return void */ public function dump(MessageCatalogue $messages, array $options = []) { diff --git a/data/web/inc/lib/vendor/symfony/translation/Dumper/IcuResFileDumper.php b/data/web/inc/lib/vendor/symfony/translation/Dumper/IcuResFileDumper.php index b62ea1536..72c1ec089 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Dumper/IcuResFileDumper.php +++ b/data/web/inc/lib/vendor/symfony/translation/Dumper/IcuResFileDumper.php @@ -20,14 +20,8 @@ use Symfony\Component\Translation\MessageCatalogue; */ class IcuResFileDumper extends FileDumper { - /** - * {@inheritdoc} - */ protected $relativePathTemplate = '%domain%/%locale%.%extension%'; - /** - * {@inheritdoc} - */ public function formatCatalogue(MessageCatalogue $messages, string $domain, array $options = []): string { $data = $indexes = $resources = ''; @@ -47,7 +41,7 @@ class IcuResFileDumper extends FileDumper $data .= pack('V', \strlen($target)) .mb_convert_encoding($target."\0", 'UTF-16LE', 'UTF-8') .$this->writePadding($data) - ; + ; } $resOffset = $this->getPosition($data); @@ -56,7 +50,7 @@ class IcuResFileDumper extends FileDumper .$indexes .$this->writePadding($data) .$resources - ; + ; $bundleTop = $this->getPosition($data); @@ -89,14 +83,11 @@ class IcuResFileDumper extends FileDumper return $padding ? str_repeat("\xAA", 4 - $padding) : null; } - private function getPosition(string $data) + private function getPosition(string $data): float|int { return (\strlen($data) + 28) / 4; } - /** - * {@inheritdoc} - */ protected function getExtension(): string { return 'res'; diff --git a/data/web/inc/lib/vendor/symfony/translation/Dumper/IniFileDumper.php b/data/web/inc/lib/vendor/symfony/translation/Dumper/IniFileDumper.php index 75032be14..6cbdef606 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Dumper/IniFileDumper.php +++ b/data/web/inc/lib/vendor/symfony/translation/Dumper/IniFileDumper.php @@ -20,9 +20,6 @@ use Symfony\Component\Translation\MessageCatalogue; */ class IniFileDumper extends FileDumper { - /** - * {@inheritdoc} - */ public function formatCatalogue(MessageCatalogue $messages, string $domain, array $options = []): string { $output = ''; @@ -35,9 +32,6 @@ class IniFileDumper extends FileDumper return $output; } - /** - * {@inheritdoc} - */ protected function getExtension(): string { return 'ini'; diff --git a/data/web/inc/lib/vendor/symfony/translation/Dumper/JsonFileDumper.php b/data/web/inc/lib/vendor/symfony/translation/Dumper/JsonFileDumper.php index 11027303a..e5035397f 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Dumper/JsonFileDumper.php +++ b/data/web/inc/lib/vendor/symfony/translation/Dumper/JsonFileDumper.php @@ -20,9 +20,6 @@ use Symfony\Component\Translation\MessageCatalogue; */ class JsonFileDumper extends FileDumper { - /** - * {@inheritdoc} - */ public function formatCatalogue(MessageCatalogue $messages, string $domain, array $options = []): string { $flags = $options['json_encoding'] ?? \JSON_PRETTY_PRINT; @@ -30,9 +27,6 @@ class JsonFileDumper extends FileDumper return json_encode($messages->all($domain), $flags); } - /** - * {@inheritdoc} - */ protected function getExtension(): string { return 'json'; diff --git a/data/web/inc/lib/vendor/symfony/translation/Dumper/MoFileDumper.php b/data/web/inc/lib/vendor/symfony/translation/Dumper/MoFileDumper.php index 08c8f8997..9ded5f4ef 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Dumper/MoFileDumper.php +++ b/data/web/inc/lib/vendor/symfony/translation/Dumper/MoFileDumper.php @@ -21,9 +21,6 @@ use Symfony\Component\Translation\MessageCatalogue; */ class MoFileDumper extends FileDumper { - /** - * {@inheritdoc} - */ public function formatCatalogue(MessageCatalogue $messages, string $domain, array $options = []): string { $sources = $targets = $sourceOffsets = $targetOffsets = ''; @@ -57,19 +54,16 @@ class MoFileDumper extends FileDumper .$this->writeLong($offset[2] + $sourcesStart + $sourcesSize); } - $output = implode('', array_map([$this, 'writeLong'], $header)) + $output = implode('', array_map($this->writeLong(...), $header)) .$sourceOffsets .$targetOffsets .$sources .$targets - ; + ; return $output; } - /** - * {@inheritdoc} - */ protected function getExtension(): string { return 'mo'; diff --git a/data/web/inc/lib/vendor/symfony/translation/Dumper/PhpFileDumper.php b/data/web/inc/lib/vendor/symfony/translation/Dumper/PhpFileDumper.php index 565d89375..51e90665d 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Dumper/PhpFileDumper.php +++ b/data/web/inc/lib/vendor/symfony/translation/Dumper/PhpFileDumper.php @@ -20,17 +20,11 @@ use Symfony\Component\Translation\MessageCatalogue; */ class PhpFileDumper extends FileDumper { - /** - * {@inheritdoc} - */ public function formatCatalogue(MessageCatalogue $messages, string $domain, array $options = []): string { return "all($domain), true).";\n"; } - /** - * {@inheritdoc} - */ protected function getExtension(): string { return 'php'; diff --git a/data/web/inc/lib/vendor/symfony/translation/Dumper/PoFileDumper.php b/data/web/inc/lib/vendor/symfony/translation/Dumper/PoFileDumper.php index 313e50458..a2d0deb78 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Dumper/PoFileDumper.php +++ b/data/web/inc/lib/vendor/symfony/translation/Dumper/PoFileDumper.php @@ -20,9 +20,6 @@ use Symfony\Component\Translation\MessageCatalogue; */ class PoFileDumper extends FileDumper { - /** - * {@inheritdoc} - */ public function formatCatalogue(MessageCatalogue $messages, string $domain, array $options = []): string { $output = 'msgid ""'."\n"; @@ -68,7 +65,7 @@ class PoFileDumper extends FileDumper return $output; } - private function getStandardRules(string $id) + private function getStandardRules(string $id): array { // Partly copied from TranslatorTrait::trans. $parts = []; @@ -111,9 +108,6 @@ EOF; return $standardRules; } - /** - * {@inheritdoc} - */ protected function getExtension(): string { return 'po'; diff --git a/data/web/inc/lib/vendor/symfony/translation/Dumper/QtFileDumper.php b/data/web/inc/lib/vendor/symfony/translation/Dumper/QtFileDumper.php index 819409fc0..0373e9c10 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Dumper/QtFileDumper.php +++ b/data/web/inc/lib/vendor/symfony/translation/Dumper/QtFileDumper.php @@ -20,9 +20,6 @@ use Symfony\Component\Translation\MessageCatalogue; */ class QtFileDumper extends FileDumper { - /** - * {@inheritdoc} - */ public function formatCatalogue(MessageCatalogue $messages, string $domain, array $options = []): string { $dom = new \DOMDocument('1.0', 'utf-8'); @@ -51,9 +48,6 @@ class QtFileDumper extends FileDumper return $dom->saveXML(); } - /** - * {@inheritdoc} - */ protected function getExtension(): string { return 'ts'; diff --git a/data/web/inc/lib/vendor/symfony/translation/Dumper/XliffFileDumper.php b/data/web/inc/lib/vendor/symfony/translation/Dumper/XliffFileDumper.php index b8a109a41..d0f016b23 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Dumper/XliffFileDumper.php +++ b/data/web/inc/lib/vendor/symfony/translation/Dumper/XliffFileDumper.php @@ -21,9 +21,11 @@ use Symfony\Component\Translation\MessageCatalogue; */ class XliffFileDumper extends FileDumper { - /** - * {@inheritdoc} - */ + public function __construct( + private string $extension = 'xlf', + ) { + } + public function formatCatalogue(MessageCatalogue $messages, string $domain, array $options = []): string { $xliffVersion = '1.2'; @@ -47,15 +49,12 @@ class XliffFileDumper extends FileDumper throw new InvalidArgumentException(sprintf('No support implemented for dumping XLIFF version "%s".', $xliffVersion)); } - /** - * {@inheritdoc} - */ protected function getExtension(): string { - return 'xlf'; + return $this->extension; } - private function dumpXliff1(string $defaultLocale, MessageCatalogue $messages, ?string $domain, array $options = []) + private function dumpXliff1(string $defaultLocale, MessageCatalogue $messages, ?string $domain, array $options = []): string { $toolInfo = ['tool-id' => 'symfony', 'tool-name' => 'Symfony']; if (\array_key_exists('tool_info', $options)) { @@ -81,6 +80,15 @@ class XliffFileDumper extends FileDumper $xliffTool->setAttribute($id, $value); } + if ($catalogueMetadata = $messages->getCatalogueMetadata('', $domain) ?? []) { + $xliffPropGroup = $xliffHead->appendChild($dom->createElement('prop-group')); + foreach ($catalogueMetadata as $key => $value) { + $xliffProp = $xliffPropGroup->appendChild($dom->createElement('prop')); + $xliffProp->setAttribute('prop-type', $key); + $xliffProp->appendChild($dom->createTextNode($value)); + } + } + $xliffBody = $xliffFile->appendChild($dom->createElement('body')); foreach ($messages->all($domain) as $source => $target) { $translation = $dom->createElement('trans-unit'); @@ -129,7 +137,7 @@ class XliffFileDumper extends FileDumper return $dom->saveXML(); } - private function dumpXliff2(string $defaultLocale, MessageCatalogue $messages, ?string $domain) + private function dumpXliff2(string $defaultLocale, MessageCatalogue $messages, ?string $domain): string { $dom = new \DOMDocument('1.0', 'utf-8'); $dom->formatOutput = true; @@ -147,6 +155,16 @@ class XliffFileDumper extends FileDumper $xliffFile->setAttribute('id', $domain.'.'.$messages->getLocale()); } + if ($catalogueMetadata = $messages->getCatalogueMetadata('', $domain) ?? []) { + $xliff->setAttribute('xmlns:m', 'urn:oasis:names:tc:xliff:metadata:2.0'); + $xliffMetadata = $xliffFile->appendChild($dom->createElement('m:metadata')); + foreach ($catalogueMetadata as $key => $value) { + $xliffMeta = $xliffMetadata->appendChild($dom->createElement('prop')); + $xliffMeta->setAttribute('type', $key); + $xliffMeta->appendChild($dom->createTextNode($value)); + } + } + foreach ($messages->all($domain) as $source => $target) { $translation = $dom->createElement('unit'); $translation->setAttribute('id', strtr(substr(base64_encode(hash('sha256', $source, true)), 0, 7), '/+', '._')); @@ -196,7 +214,7 @@ class XliffFileDumper extends FileDumper return $dom->saveXML(); } - private function hasMetadataArrayInfo(string $key, array $metadata = null): bool + private function hasMetadataArrayInfo(string $key, ?array $metadata = null): bool { return is_iterable($metadata[$key] ?? null); } diff --git a/data/web/inc/lib/vendor/symfony/translation/Dumper/YamlFileDumper.php b/data/web/inc/lib/vendor/symfony/translation/Dumper/YamlFileDumper.php index d0cfbefaa..d2670331e 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Dumper/YamlFileDumper.php +++ b/data/web/inc/lib/vendor/symfony/translation/Dumper/YamlFileDumper.php @@ -30,9 +30,6 @@ class YamlFileDumper extends FileDumper $this->extension = $extension; } - /** - * {@inheritdoc} - */ public function formatCatalogue(MessageCatalogue $messages, string $domain, array $options = []): string { if (!class_exists(Yaml::class)) { @@ -52,9 +49,6 @@ class YamlFileDumper extends FileDumper return Yaml::dump($data); } - /** - * {@inheritdoc} - */ protected function getExtension(): string { return $this->extension; diff --git a/data/web/inc/lib/vendor/symfony/translation/Exception/IncompleteDsnException.php b/data/web/inc/lib/vendor/symfony/translation/Exception/IncompleteDsnException.php index cb0ce027e..b304bde01 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Exception/IncompleteDsnException.php +++ b/data/web/inc/lib/vendor/symfony/translation/Exception/IncompleteDsnException.php @@ -13,7 +13,7 @@ namespace Symfony\Component\Translation\Exception; class IncompleteDsnException extends InvalidArgumentException { - public function __construct(string $message, string $dsn = null, \Throwable $previous = null) + public function __construct(string $message, ?string $dsn = null, ?\Throwable $previous = null) { if ($dsn) { $message = sprintf('Invalid "%s" provider DSN: ', $dsn).$message; diff --git a/data/web/inc/lib/vendor/symfony/translation/Exception/MissingRequiredOptionException.php b/data/web/inc/lib/vendor/symfony/translation/Exception/MissingRequiredOptionException.php index 2b5f80806..46152e254 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Exception/MissingRequiredOptionException.php +++ b/data/web/inc/lib/vendor/symfony/translation/Exception/MissingRequiredOptionException.php @@ -16,7 +16,7 @@ namespace Symfony\Component\Translation\Exception; */ class MissingRequiredOptionException extends IncompleteDsnException { - public function __construct(string $option, string $dsn = null, \Throwable $previous = null) + public function __construct(string $option, ?string $dsn = null, ?\Throwable $previous = null) { $message = sprintf('The option "%s" is required but missing.', $option); diff --git a/data/web/inc/lib/vendor/symfony/translation/Exception/ProviderException.php b/data/web/inc/lib/vendor/symfony/translation/Exception/ProviderException.php index 331ff7586..f2981f58b 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Exception/ProviderException.php +++ b/data/web/inc/lib/vendor/symfony/translation/Exception/ProviderException.php @@ -18,10 +18,10 @@ use Symfony\Contracts\HttpClient\ResponseInterface; */ class ProviderException extends RuntimeException implements ProviderExceptionInterface { - private $response; + private ResponseInterface $response; private string $debug; - public function __construct(string $message, ResponseInterface $response, int $code = 0, \Exception $previous = null) + public function __construct(string $message, ResponseInterface $response, int $code = 0, ?\Exception $previous = null) { $this->response = $response; $this->debug = $response->getInfo('debug') ?? ''; diff --git a/data/web/inc/lib/vendor/symfony/translation/Exception/UnsupportedSchemeException.php b/data/web/inc/lib/vendor/symfony/translation/Exception/UnsupportedSchemeException.php index 7fbaa8f04..8d3295184 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Exception/UnsupportedSchemeException.php +++ b/data/web/inc/lib/vendor/symfony/translation/Exception/UnsupportedSchemeException.php @@ -29,9 +29,13 @@ class UnsupportedSchemeException extends LogicException 'class' => Bridge\Lokalise\LokaliseProviderFactory::class, 'package' => 'symfony/lokalise-translation-provider', ], + 'phrase' => [ + 'class' => Bridge\Phrase\PhraseProviderFactory::class, + 'package' => 'symfony/phrase-translation-provider', + ], ]; - public function __construct(Dsn $dsn, string $name = null, array $supported = []) + public function __construct(Dsn $dsn, ?string $name = null, array $supported = []) { $provider = $dsn->getScheme(); if (false !== $pos = strpos($provider, '+')) { @@ -39,7 +43,7 @@ class UnsupportedSchemeException extends LogicException } $package = self::SCHEME_TO_PACKAGE_MAP[$provider] ?? null; if ($package && !class_exists($package['class'])) { - parent::__construct(sprintf('Unable to synchronize translations via "%s" as the provider is not installed; try running "composer require %s".', $provider, $package['package'])); + parent::__construct(sprintf('Unable to synchronize translations via "%s" as the provider is not installed. Try running "composer require %s".', $provider, $package['package'])); return; } diff --git a/data/web/inc/lib/vendor/symfony/translation/Extractor/ChainExtractor.php b/data/web/inc/lib/vendor/symfony/translation/Extractor/ChainExtractor.php index e58e82f05..d36f7f385 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Extractor/ChainExtractor.php +++ b/data/web/inc/lib/vendor/symfony/translation/Extractor/ChainExtractor.php @@ -29,6 +29,8 @@ class ChainExtractor implements ExtractorInterface /** * Adds a loader to the translation extractor. + * + * @return void */ public function addExtractor(string $format, ExtractorInterface $extractor) { @@ -36,7 +38,7 @@ class ChainExtractor implements ExtractorInterface } /** - * {@inheritdoc} + * @return void */ public function setPrefix(string $prefix) { @@ -46,7 +48,7 @@ class ChainExtractor implements ExtractorInterface } /** - * {@inheritdoc} + * @return void */ public function extract(string|iterable $directory, MessageCatalogue $catalogue) { diff --git a/data/web/inc/lib/vendor/symfony/translation/Extractor/ExtractorInterface.php b/data/web/inc/lib/vendor/symfony/translation/Extractor/ExtractorInterface.php index b76a7f20b..642130af7 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Extractor/ExtractorInterface.php +++ b/data/web/inc/lib/vendor/symfony/translation/Extractor/ExtractorInterface.php @@ -25,11 +25,15 @@ interface ExtractorInterface * Extracts translation messages from files, a file or a directory to the catalogue. * * @param string|iterable $resource Files, a file or a directory + * + * @return void */ public function extract(string|iterable $resource, MessageCatalogue $catalogue); /** * Sets the prefix that should be used for new found messages. + * + * @return void */ public function setPrefix(string $prefix); } diff --git a/data/web/inc/lib/vendor/symfony/translation/Extractor/PhpAstExtractor.php b/data/web/inc/lib/vendor/symfony/translation/Extractor/PhpAstExtractor.php new file mode 100644 index 000000000..06fc77de3 --- /dev/null +++ b/data/web/inc/lib/vendor/symfony/translation/Extractor/PhpAstExtractor.php @@ -0,0 +1,85 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Extractor; + +use PhpParser\NodeTraverser; +use PhpParser\NodeVisitor; +use PhpParser\Parser; +use PhpParser\ParserFactory; +use Symfony\Component\Finder\Finder; +use Symfony\Component\Translation\Extractor\Visitor\AbstractVisitor; +use Symfony\Component\Translation\MessageCatalogue; + +/** + * PhpAstExtractor extracts translation messages from a PHP AST. + * + * @author Mathieu Santostefano + */ +final class PhpAstExtractor extends AbstractFileExtractor implements ExtractorInterface +{ + private Parser $parser; + + public function __construct( + /** + * @param iterable $visitors + */ + private readonly iterable $visitors, + private string $prefix = '', + ) { + if (!class_exists(ParserFactory::class)) { + throw new \LogicException(sprintf('You cannot use "%s" as the "nikic/php-parser" package is not installed. Try running "composer require nikic/php-parser".', static::class)); + } + + $this->parser = (new ParserFactory())->createForHostVersion(); + } + + public function extract(iterable|string $resource, MessageCatalogue $catalogue): void + { + foreach ($this->extractFiles($resource) as $file) { + $traverser = new NodeTraverser(); + + // This is needed to resolve namespaces in class methods/constants. + $nameResolver = new NodeVisitor\NameResolver(); + $traverser->addVisitor($nameResolver); + + /** @var AbstractVisitor&NodeVisitor $visitor */ + foreach ($this->visitors as $visitor) { + $visitor->initialize($catalogue, $file, $this->prefix); + $traverser->addVisitor($visitor); + } + + $nodes = $this->parser->parse(file_get_contents($file)); + $traverser->traverse($nodes); + } + } + + public function setPrefix(string $prefix): void + { + $this->prefix = $prefix; + } + + protected function canBeExtracted(string $file): bool + { + return 'php' === pathinfo($file, \PATHINFO_EXTENSION) + && $this->isFile($file) + && preg_match('/\bt\(|->trans\(|TranslatableMessage|Symfony\\\\Component\\\\Validator\\\\Constraints/i', file_get_contents($file)); + } + + protected function extractFromDirectory(array|string $resource): iterable|Finder + { + if (!class_exists(Finder::class)) { + throw new \LogicException(sprintf('You cannot use "%s" as the "symfony/finder" package is not installed. Try running "composer require symfony/finder".', static::class)); + } + + return (new Finder())->files()->name('*.php')->in($resource); + } +} diff --git a/data/web/inc/lib/vendor/symfony/translation/Extractor/PhpExtractor.php b/data/web/inc/lib/vendor/symfony/translation/Extractor/PhpExtractor.php index 1b86cc591..7ff27f7c8 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Extractor/PhpExtractor.php +++ b/data/web/inc/lib/vendor/symfony/translation/Extractor/PhpExtractor.php @@ -11,6 +11,8 @@ namespace Symfony\Component\Translation\Extractor; +trigger_deprecation('symfony/translation', '6.2', '"%s" is deprecated, use "%s" instead.', PhpExtractor::class, PhpAstExtractor::class); + use Symfony\Component\Finder\Finder; use Symfony\Component\Translation\MessageCatalogue; @@ -18,6 +20,8 @@ use Symfony\Component\Translation\MessageCatalogue; * PhpExtractor extracts translation messages from a PHP template. * * @author Michel Salib + * + * @deprecated since Symfony 6.2, use the PhpAstExtractor instead */ class PhpExtractor extends AbstractFileExtractor implements ExtractorInterface { @@ -129,7 +133,7 @@ class PhpExtractor extends AbstractFileExtractor implements ExtractorInterface ]; /** - * {@inheritdoc} + * @return void */ public function extract(string|iterable $resource, MessageCatalogue $catalog) { @@ -142,7 +146,7 @@ class PhpExtractor extends AbstractFileExtractor implements ExtractorInterface } /** - * {@inheritdoc} + * @return void */ public function setPrefix(string $prefix) { @@ -164,7 +168,7 @@ class PhpExtractor extends AbstractFileExtractor implements ExtractorInterface /** * Seeks to a non-whitespace token. */ - private function seekToNextRelevantToken(\Iterator $tokenIterator) + private function seekToNextRelevantToken(\Iterator $tokenIterator): void { for (; $tokenIterator->valid(); $tokenIterator->next()) { $t = $tokenIterator->current(); @@ -174,7 +178,7 @@ class PhpExtractor extends AbstractFileExtractor implements ExtractorInterface } } - private function skipMethodArgument(\Iterator $tokenIterator) + private function skipMethodArgument(\Iterator $tokenIterator): void { $openBraces = 0; @@ -199,7 +203,7 @@ class PhpExtractor extends AbstractFileExtractor implements ExtractorInterface * Extracts the message from the iterator while the tokens * match allowed message tokens. */ - private function getValue(\Iterator $tokenIterator) + private function getValue(\Iterator $tokenIterator): string { $message = ''; $docToken = ''; @@ -257,6 +261,8 @@ class PhpExtractor extends AbstractFileExtractor implements ExtractorInterface /** * Extracts trans message from PHP tokens. + * + * @return void */ protected function parseTokens(array $tokens, MessageCatalogue $catalog, string $filename) { @@ -314,9 +320,6 @@ class PhpExtractor extends AbstractFileExtractor implements ExtractorInterface return $this->isFile($file) && 'php' === pathinfo($file, \PATHINFO_EXTENSION); } - /** - * {@inheritdoc} - */ protected function extractFromDirectory(string|array $directory): iterable { if (!class_exists(Finder::class)) { diff --git a/data/web/inc/lib/vendor/symfony/translation/Extractor/PhpStringTokenParser.php b/data/web/inc/lib/vendor/symfony/translation/Extractor/PhpStringTokenParser.php index 7fbd37c68..2dfc1e387 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Extractor/PhpStringTokenParser.php +++ b/data/web/inc/lib/vendor/symfony/translation/Extractor/PhpStringTokenParser.php @@ -11,6 +11,8 @@ namespace Symfony\Component\Translation\Extractor; +trigger_deprecation('symfony/translation', '6.2', '"%s" is deprecated.', PhpStringTokenParser::class); + /* * The following is derived from code at http://github.com/nikic/PHP-Parser * @@ -47,6 +49,9 @@ namespace Symfony\Component\Translation\Extractor; * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +/** + * @deprecated since Symfony 6.2 + */ class PhpStringTokenParser { protected static $replacements = [ @@ -89,7 +94,7 @@ class PhpStringTokenParser * @param string $str String without quotes * @param string|null $quote Quote type */ - public static function parseEscapeSequences(string $str, string $quote = null): string + public static function parseEscapeSequences(string $str, ?string $quote = null): string { if (null !== $quote) { $str = str_replace('\\'.$quote, $quote, $str); diff --git a/data/web/inc/lib/vendor/symfony/translation/Extractor/Visitor/AbstractVisitor.php b/data/web/inc/lib/vendor/symfony/translation/Extractor/Visitor/AbstractVisitor.php new file mode 100644 index 000000000..c33689616 --- /dev/null +++ b/data/web/inc/lib/vendor/symfony/translation/Extractor/Visitor/AbstractVisitor.php @@ -0,0 +1,135 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Extractor\Visitor; + +use PhpParser\Node; +use Symfony\Component\Translation\MessageCatalogue; + +/** + * @author Mathieu Santostefano + */ +abstract class AbstractVisitor +{ + private MessageCatalogue $catalogue; + private \SplFileInfo $file; + private string $messagePrefix; + + public function initialize(MessageCatalogue $catalogue, \SplFileInfo $file, string $messagePrefix): void + { + $this->catalogue = $catalogue; + $this->file = $file; + $this->messagePrefix = $messagePrefix; + } + + protected function addMessageToCatalogue(string $message, ?string $domain, int $line): void + { + $domain ??= 'messages'; + $this->catalogue->set($message, $this->messagePrefix.$message, $domain); + $metadata = $this->catalogue->getMetadata($message, $domain) ?? []; + $normalizedFilename = preg_replace('{[\\\\/]+}', '/', $this->file); + $metadata['sources'][] = $normalizedFilename.':'.$line; + $this->catalogue->setMetadata($message, $metadata, $domain); + } + + protected function getStringArguments(Node\Expr\CallLike|Node\Attribute|Node\Expr\New_ $node, int|string $index, bool $indexIsRegex = false): array + { + if (\is_string($index)) { + return $this->getStringNamedArguments($node, $index, $indexIsRegex); + } + + $args = $node instanceof Node\Expr\CallLike ? $node->getRawArgs() : $node->args; + + if (!($arg = $args[$index] ?? null) instanceof Node\Arg) { + return []; + } + + return (array) $this->getStringValue($arg->value); + } + + protected function hasNodeNamedArguments(Node\Expr\CallLike|Node\Attribute|Node\Expr\New_ $node): bool + { + $args = $node instanceof Node\Expr\CallLike ? $node->getRawArgs() : $node->args; + + foreach ($args as $arg) { + if ($arg instanceof Node\Arg && null !== $arg->name) { + return true; + } + } + + return false; + } + + protected function nodeFirstNamedArgumentIndex(Node\Expr\CallLike|Node\Attribute|Node\Expr\New_ $node): int + { + $args = $node instanceof Node\Expr\CallLike ? $node->getRawArgs() : $node->args; + + foreach ($args as $i => $arg) { + if ($arg instanceof Node\Arg && null !== $arg->name) { + return $i; + } + } + + return \PHP_INT_MAX; + } + + private function getStringNamedArguments(Node\Expr\CallLike|Node\Attribute $node, ?string $argumentName = null, bool $isArgumentNamePattern = false): array + { + $args = $node instanceof Node\Expr\CallLike ? $node->getArgs() : $node->args; + $argumentValues = []; + + foreach ($args as $arg) { + if (!$isArgumentNamePattern && $arg->name?->toString() === $argumentName) { + $argumentValues[] = $this->getStringValue($arg->value); + } elseif ($isArgumentNamePattern && preg_match($argumentName, $arg->name?->toString() ?? '') > 0) { + $argumentValues[] = $this->getStringValue($arg->value); + } + } + + return array_filter($argumentValues); + } + + private function getStringValue(Node $node): ?string + { + if ($node instanceof Node\Scalar\String_) { + return $node->value; + } + + if ($node instanceof Node\Expr\BinaryOp\Concat) { + if (null === $left = $this->getStringValue($node->left)) { + return null; + } + + if (null === $right = $this->getStringValue($node->right)) { + return null; + } + + return $left.$right; + } + + if ($node instanceof Node\Expr\Assign && $node->expr instanceof Node\Scalar\String_) { + return $node->expr->value; + } + + if ($node instanceof Node\Expr\ClassConstFetch) { + try { + $reflection = new \ReflectionClass($node->class->toString()); + $constant = $reflection->getReflectionConstant($node->name->toString()); + if (false !== $constant && \is_string($constant->getValue())) { + return $constant->getValue(); + } + } catch (\ReflectionException) { + } + } + + return null; + } +} diff --git a/data/web/inc/lib/vendor/symfony/translation/Extractor/Visitor/ConstraintVisitor.php b/data/web/inc/lib/vendor/symfony/translation/Extractor/Visitor/ConstraintVisitor.php new file mode 100644 index 000000000..00fb9eedc --- /dev/null +++ b/data/web/inc/lib/vendor/symfony/translation/Extractor/Visitor/ConstraintVisitor.php @@ -0,0 +1,112 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Extractor\Visitor; + +use PhpParser\Node; +use PhpParser\NodeVisitor; + +/** + * @author Mathieu Santostefano + * + * Code mostly comes from https://github.com/php-translation/extractor/blob/master/src/Visitor/Php/Symfony/Constraint.php + */ +final class ConstraintVisitor extends AbstractVisitor implements NodeVisitor +{ + public function __construct( + private readonly array $constraintClassNames = [] + ) { + } + + public function beforeTraverse(array $nodes): ?Node + { + return null; + } + + public function enterNode(Node $node): ?Node + { + return null; + } + + public function leaveNode(Node $node): ?Node + { + if (!$node instanceof Node\Expr\New_ && !$node instanceof Node\Attribute) { + return null; + } + + $className = $node instanceof Node\Attribute ? $node->name : $node->class; + if (!$className instanceof Node\Name) { + return null; + } + + $parts = $className->getParts(); + $isConstraintClass = false; + + foreach ($parts as $part) { + if (\in_array($part, $this->constraintClassNames, true)) { + $isConstraintClass = true; + + break; + } + } + + if (!$isConstraintClass) { + return null; + } + + $arg = $node->args[0] ?? null; + if (!$arg instanceof Node\Arg) { + return null; + } + + if ($this->hasNodeNamedArguments($node)) { + $messages = $this->getStringArguments($node, '/message/i', true); + } else { + if (!$arg->value instanceof Node\Expr\Array_) { + // There is no way to guess which argument is a message to be translated. + return null; + } + + $messages = []; + $options = $arg->value; + + /** @var Node\Expr\ArrayItem $item */ + foreach ($options->items as $item) { + if (!$item->key instanceof Node\Scalar\String_) { + continue; + } + + if (false === stripos($item->key->value ?? '', 'message')) { + continue; + } + + if (!$item->value instanceof Node\Scalar\String_) { + continue; + } + + $messages[] = $item->value->value; + + break; + } + } + + foreach ($messages as $message) { + $this->addMessageToCatalogue($message, 'validators', $node->getStartLine()); + } + + return null; + } + + public function afterTraverse(array $nodes): ?Node + { + return null; + } +} diff --git a/data/web/inc/lib/vendor/symfony/translation/Extractor/Visitor/TransMethodVisitor.php b/data/web/inc/lib/vendor/symfony/translation/Extractor/Visitor/TransMethodVisitor.php new file mode 100644 index 000000000..53a6981a2 --- /dev/null +++ b/data/web/inc/lib/vendor/symfony/translation/Extractor/Visitor/TransMethodVisitor.php @@ -0,0 +1,65 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Extractor\Visitor; + +use PhpParser\Node; +use PhpParser\NodeVisitor; + +/** + * @author Mathieu Santostefano + */ +final class TransMethodVisitor extends AbstractVisitor implements NodeVisitor +{ + public function beforeTraverse(array $nodes): ?Node + { + return null; + } + + public function enterNode(Node $node): ?Node + { + return null; + } + + public function leaveNode(Node $node): ?Node + { + if (!$node instanceof Node\Expr\MethodCall && !$node instanceof Node\Expr\FuncCall) { + return null; + } + + if (!\is_string($node->name) && !$node->name instanceof Node\Identifier && !$node->name instanceof Node\Name) { + return null; + } + + $name = (string) $node->name; + + if ('trans' === $name || 't' === $name) { + $firstNamedArgumentIndex = $this->nodeFirstNamedArgumentIndex($node); + + if (!$messages = $this->getStringArguments($node, 0 < $firstNamedArgumentIndex ? 0 : 'message')) { + return null; + } + + $domain = $this->getStringArguments($node, 2 < $firstNamedArgumentIndex ? 2 : 'domain')[0] ?? null; + + foreach ($messages as $message) { + $this->addMessageToCatalogue($message, $domain, $node->getStartLine()); + } + } + + return null; + } + + public function afterTraverse(array $nodes): ?Node + { + return null; + } +} diff --git a/data/web/inc/lib/vendor/symfony/translation/Extractor/Visitor/TranslatableMessageVisitor.php b/data/web/inc/lib/vendor/symfony/translation/Extractor/Visitor/TranslatableMessageVisitor.php new file mode 100644 index 000000000..6bd8bb022 --- /dev/null +++ b/data/web/inc/lib/vendor/symfony/translation/Extractor/Visitor/TranslatableMessageVisitor.php @@ -0,0 +1,65 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation\Extractor\Visitor; + +use PhpParser\Node; +use PhpParser\NodeVisitor; + +/** + * @author Mathieu Santostefano + */ +final class TranslatableMessageVisitor extends AbstractVisitor implements NodeVisitor +{ + public function beforeTraverse(array $nodes): ?Node + { + return null; + } + + public function enterNode(Node $node): ?Node + { + return null; + } + + public function leaveNode(Node $node): ?Node + { + if (!$node instanceof Node\Expr\New_) { + return null; + } + + if (!($className = $node->class) instanceof Node\Name) { + return null; + } + + if (!\in_array('TranslatableMessage', $className->getParts(), true)) { + return null; + } + + $firstNamedArgumentIndex = $this->nodeFirstNamedArgumentIndex($node); + + if (!$messages = $this->getStringArguments($node, 0 < $firstNamedArgumentIndex ? 0 : 'message')) { + return null; + } + + $domain = $this->getStringArguments($node, 2 < $firstNamedArgumentIndex ? 2 : 'domain')[0] ?? null; + + foreach ($messages as $message) { + $this->addMessageToCatalogue($message, $domain, $node->getStartLine()); + } + + return null; + } + + public function afterTraverse(array $nodes): ?Node + { + return null; + } +} diff --git a/data/web/inc/lib/vendor/symfony/translation/Formatter/IntlFormatter.php b/data/web/inc/lib/vendor/symfony/translation/Formatter/IntlFormatter.php index f7f1c36a2..e62de253f 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Formatter/IntlFormatter.php +++ b/data/web/inc/lib/vendor/symfony/translation/Formatter/IntlFormatter.php @@ -20,12 +20,9 @@ use Symfony\Component\Translation\Exception\LogicException; */ class IntlFormatter implements IntlFormatterInterface { - private $hasMessageFormatter; - private $cache = []; + private bool $hasMessageFormatter; + private array $cache = []; - /** - * {@inheritdoc} - */ public function formatIntl(string $message, string $locale, array $parameters = []): string { // MessageFormatter constructor throws an exception if the message is empty @@ -34,7 +31,7 @@ class IntlFormatter implements IntlFormatterInterface } if (!$formatter = $this->cache[$locale][$message] ?? null) { - if (!($this->hasMessageFormatter ?? $this->hasMessageFormatter = class_exists(\MessageFormatter::class))) { + if (!$this->hasMessageFormatter ??= class_exists(\MessageFormatter::class)) { throw new LogicException('Cannot parse message translation: please install the "intl" PHP extension or the "symfony/polyfill-intl-messageformatter" package.'); } try { diff --git a/data/web/inc/lib/vendor/symfony/translation/Formatter/MessageFormatter.php b/data/web/inc/lib/vendor/symfony/translation/Formatter/MessageFormatter.php index 68821b1d0..d5255bdcb 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Formatter/MessageFormatter.php +++ b/data/web/inc/lib/vendor/symfony/translation/Formatter/MessageFormatter.php @@ -22,33 +22,23 @@ class_exists(IntlFormatter::class); */ class MessageFormatter implements MessageFormatterInterface, IntlFormatterInterface { - private $translator; - private $intlFormatter; + private TranslatorInterface $translator; + private IntlFormatterInterface $intlFormatter; /** * @param TranslatorInterface|null $translator An identity translator to use as selector for pluralization */ - public function __construct(TranslatorInterface $translator = null, IntlFormatterInterface $intlFormatter = null) + public function __construct(?TranslatorInterface $translator = null, ?IntlFormatterInterface $intlFormatter = null) { $this->translator = $translator ?? new IdentityTranslator(); $this->intlFormatter = $intlFormatter ?? new IntlFormatter(); } - /** - * {@inheritdoc} - */ public function format(string $message, string $locale, array $parameters = []): string { - if ($this->translator instanceof TranslatorInterface) { - return $this->translator->trans($message, $parameters, null, $locale); - } - - return strtr($message, $parameters); + return $this->translator->trans($message, $parameters, null, $locale); } - /** - * {@inheritdoc} - */ public function formatIntl(string $message, string $locale, array $parameters = []): string { return $this->intlFormatter->formatIntl($message, $locale, $parameters); diff --git a/data/web/inc/lib/vendor/symfony/translation/LICENSE b/data/web/inc/lib/vendor/symfony/translation/LICENSE index 88bf75bb4..0138f8f07 100644 --- a/data/web/inc/lib/vendor/symfony/translation/LICENSE +++ b/data/web/inc/lib/vendor/symfony/translation/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2004-2022 Fabien Potencier +Copyright (c) 2004-present Fabien Potencier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/data/web/inc/lib/vendor/symfony/translation/Loader/ArrayLoader.php b/data/web/inc/lib/vendor/symfony/translation/Loader/ArrayLoader.php index 35de9ef54..e63a7d05b 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Loader/ArrayLoader.php +++ b/data/web/inc/lib/vendor/symfony/translation/Loader/ArrayLoader.php @@ -20,9 +20,6 @@ use Symfony\Component\Translation\MessageCatalogue; */ class ArrayLoader implements LoaderInterface { - /** - * {@inheritdoc} - */ public function load(mixed $resource, string $locale, string $domain = 'messages'): MessageCatalogue { $resource = $this->flatten($resource); @@ -46,9 +43,11 @@ class ArrayLoader implements LoaderInterface foreach ($messages as $key => $value) { if (\is_array($value)) { foreach ($this->flatten($value) as $k => $v) { - $result[$key.'.'.$k] = $v; + if (null !== $v) { + $result[$key.'.'.$k] = $v; + } } - } else { + } elseif (null !== $value) { $result[$key] = $value; } } diff --git a/data/web/inc/lib/vendor/symfony/translation/Loader/CsvFileLoader.php b/data/web/inc/lib/vendor/symfony/translation/Loader/CsvFileLoader.php index 76b00b151..7f2f96be6 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Loader/CsvFileLoader.php +++ b/data/web/inc/lib/vendor/symfony/translation/Loader/CsvFileLoader.php @@ -24,9 +24,6 @@ class CsvFileLoader extends FileLoader private string $enclosure = '"'; private string $escape = '\\'; - /** - * {@inheritdoc} - */ protected function loadResource(string $resource): array { $messages = []; @@ -45,7 +42,7 @@ class CsvFileLoader extends FileLoader continue; } - if ('#' !== substr($data[0], 0, 1) && isset($data[1]) && 2 === \count($data)) { + if (!str_starts_with($data[0], '#') && isset($data[1]) && 2 === \count($data)) { $messages[$data[0]] = $data[1]; } } @@ -55,6 +52,8 @@ class CsvFileLoader extends FileLoader /** * Sets the delimiter, enclosure, and escape character for CSV. + * + * @return void */ public function setCsvControl(string $delimiter = ';', string $enclosure = '"', string $escape = '\\') { diff --git a/data/web/inc/lib/vendor/symfony/translation/Loader/FileLoader.php b/data/web/inc/lib/vendor/symfony/translation/Loader/FileLoader.php index e170d7617..877c3bbc7 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Loader/FileLoader.php +++ b/data/web/inc/lib/vendor/symfony/translation/Loader/FileLoader.php @@ -21,9 +21,6 @@ use Symfony\Component\Translation\MessageCatalogue; */ abstract class FileLoader extends ArrayLoader { - /** - * {@inheritdoc} - */ public function load(mixed $resource, string $locale, string $domain = 'messages'): MessageCatalogue { if (!stream_is_local($resource)) { @@ -37,9 +34,7 @@ abstract class FileLoader extends ArrayLoader $messages = $this->loadResource($resource); // empty resource - if (null === $messages) { - $messages = []; - } + $messages ??= []; // not an array if (!\is_array($messages)) { diff --git a/data/web/inc/lib/vendor/symfony/translation/Loader/IcuDatFileLoader.php b/data/web/inc/lib/vendor/symfony/translation/Loader/IcuDatFileLoader.php index c3ca5fd08..76e4e7f02 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Loader/IcuDatFileLoader.php +++ b/data/web/inc/lib/vendor/symfony/translation/Loader/IcuDatFileLoader.php @@ -23,9 +23,6 @@ use Symfony\Component\Translation\MessageCatalogue; */ class IcuDatFileLoader extends IcuResFileLoader { - /** - * {@inheritdoc} - */ public function load(mixed $resource, string $locale, string $domain = 'messages'): MessageCatalogue { if (!stream_is_local($resource.'.dat')) { @@ -38,7 +35,7 @@ class IcuDatFileLoader extends IcuResFileLoader try { $rb = new \ResourceBundle($locale, $resource); - } catch (\Exception $e) { + } catch (\Exception) { $rb = null; } diff --git a/data/web/inc/lib/vendor/symfony/translation/Loader/IcuResFileLoader.php b/data/web/inc/lib/vendor/symfony/translation/Loader/IcuResFileLoader.php index 54c48f813..949dd9792 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Loader/IcuResFileLoader.php +++ b/data/web/inc/lib/vendor/symfony/translation/Loader/IcuResFileLoader.php @@ -23,9 +23,6 @@ use Symfony\Component\Translation\MessageCatalogue; */ class IcuResFileLoader implements LoaderInterface { - /** - * {@inheritdoc} - */ public function load(mixed $resource, string $locale, string $domain = 'messages'): MessageCatalogue { if (!stream_is_local($resource)) { @@ -38,7 +35,7 @@ class IcuResFileLoader implements LoaderInterface try { $rb = new \ResourceBundle($locale, $resource); - } catch (\Exception $e) { + } catch (\Exception) { $rb = null; } @@ -71,9 +68,9 @@ class IcuResFileLoader implements LoaderInterface * * @param \ResourceBundle $rb The ResourceBundle that will be flattened * @param array $messages Used internally for recursive calls - * @param string $path Current path being parsed, used internally for recursive calls + * @param string|null $path Current path being parsed, used internally for recursive calls */ - protected function flatten(\ResourceBundle $rb, array &$messages = [], string $path = null): array + protected function flatten(\ResourceBundle $rb, array &$messages = [], ?string $path = null): array { foreach ($rb as $key => $value) { $nodePath = $path ? $path.'.'.$key : $key; diff --git a/data/web/inc/lib/vendor/symfony/translation/Loader/IniFileLoader.php b/data/web/inc/lib/vendor/symfony/translation/Loader/IniFileLoader.php index 04e294d11..3126896c8 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Loader/IniFileLoader.php +++ b/data/web/inc/lib/vendor/symfony/translation/Loader/IniFileLoader.php @@ -18,9 +18,6 @@ namespace Symfony\Component\Translation\Loader; */ class IniFileLoader extends FileLoader { - /** - * {@inheritdoc} - */ protected function loadResource(string $resource): array { return parse_ini_file($resource, true); diff --git a/data/web/inc/lib/vendor/symfony/translation/Loader/JsonFileLoader.php b/data/web/inc/lib/vendor/symfony/translation/Loader/JsonFileLoader.php index 67a8d58ed..385553ef6 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Loader/JsonFileLoader.php +++ b/data/web/inc/lib/vendor/symfony/translation/Loader/JsonFileLoader.php @@ -20,9 +20,6 @@ use Symfony\Component\Translation\Exception\InvalidResourceException; */ class JsonFileLoader extends FileLoader { - /** - * {@inheritdoc} - */ protected function loadResource(string $resource): array { $messages = []; @@ -42,19 +39,13 @@ class JsonFileLoader extends FileLoader */ private function getJSONErrorMessage(int $errorCode): string { - switch ($errorCode) { - case \JSON_ERROR_DEPTH: - return 'Maximum stack depth exceeded'; - case \JSON_ERROR_STATE_MISMATCH: - return 'Underflow or the modes mismatch'; - case \JSON_ERROR_CTRL_CHAR: - return 'Unexpected control character found'; - case \JSON_ERROR_SYNTAX: - return 'Syntax error, malformed JSON'; - case \JSON_ERROR_UTF8: - return 'Malformed UTF-8 characters, possibly incorrectly encoded'; - default: - return 'Unknown error'; - } + return match ($errorCode) { + \JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', + \JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch', + \JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', + \JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON', + \JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded', + default => 'Unknown error', + }; } } diff --git a/data/web/inc/lib/vendor/symfony/translation/Loader/MoFileLoader.php b/data/web/inc/lib/vendor/symfony/translation/Loader/MoFileLoader.php index b0c891387..8427c393e 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Loader/MoFileLoader.php +++ b/data/web/inc/lib/vendor/symfony/translation/Loader/MoFileLoader.php @@ -38,8 +38,6 @@ class MoFileLoader extends FileLoader /** * Parses machine object (MO) format, independent of the machine's endian it * was created on. Both 32bit and 64bit systems are supported. - * - * {@inheritdoc} */ protected function loadResource(string $resource): array { diff --git a/data/web/inc/lib/vendor/symfony/translation/Loader/PhpFileLoader.php b/data/web/inc/lib/vendor/symfony/translation/Loader/PhpFileLoader.php index 6bc2a05f1..541b6c832 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Loader/PhpFileLoader.php +++ b/data/web/inc/lib/vendor/symfony/translation/Loader/PhpFileLoader.php @@ -20,12 +20,9 @@ class PhpFileLoader extends FileLoader { private static ?array $cache = []; - /** - * {@inheritdoc} - */ protected function loadResource(string $resource): array { - if ([] === self::$cache && \function_exists('opcache_invalidate') && filter_var(ini_get('opcache.enable'), \FILTER_VALIDATE_BOOLEAN) && (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) || filter_var(ini_get('opcache.enable_cli'), \FILTER_VALIDATE_BOOLEAN))) { + if ([] === self::$cache && \function_exists('opcache_invalidate') && filter_var(\ini_get('opcache.enable'), \FILTER_VALIDATE_BOOL) && (!\in_array(\PHP_SAPI, ['cli', 'phpdbg', 'embed'], true) || filter_var(\ini_get('opcache.enable_cli'), \FILTER_VALIDATE_BOOL))) { self::$cache = null; } @@ -33,10 +30,6 @@ class PhpFileLoader extends FileLoader return require $resource; } - if (isset(self::$cache[$resource])) { - return self::$cache[$resource]; - } - - return self::$cache[$resource] = require $resource; + return self::$cache[$resource] ??= require $resource; } } diff --git a/data/web/inc/lib/vendor/symfony/translation/Loader/PoFileLoader.php b/data/web/inc/lib/vendor/symfony/translation/Loader/PoFileLoader.php index 6df161487..620d97339 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Loader/PoFileLoader.php +++ b/data/web/inc/lib/vendor/symfony/translation/Loader/PoFileLoader.php @@ -57,8 +57,6 @@ class PoFileLoader extends FileLoader * - Message IDs are allowed to have other encodings as just US-ASCII. * * Items with an empty id are ignored. - * - * {@inheritdoc} */ protected function loadResource(string $resource): array { @@ -83,15 +81,15 @@ class PoFileLoader extends FileLoader } $item = $defaults; $flags = []; - } elseif ('#,' === substr($line, 0, 2)) { + } elseif (str_starts_with($line, '#,')) { $flags = array_map('trim', explode(',', substr($line, 2))); - } elseif ('msgid "' === substr($line, 0, 7)) { + } elseif (str_starts_with($line, 'msgid "')) { // We start a new msg so save previous // TODO: this fails when comments or contexts are added $this->addMessage($messages, $item); $item = $defaults; $item['ids']['singular'] = substr($line, 7, -1); - } elseif ('msgstr "' === substr($line, 0, 8)) { + } elseif (str_starts_with($line, 'msgstr "')) { $item['translated'] = substr($line, 8, -1); } elseif ('"' === $line[0]) { $continues = isset($item['translated']) ? 'translated' : 'ids'; @@ -102,9 +100,9 @@ class PoFileLoader extends FileLoader } else { $item[$continues] .= substr($line, 1, -1); } - } elseif ('msgid_plural "' === substr($line, 0, 14)) { + } elseif (str_starts_with($line, 'msgid_plural "')) { $item['ids']['plural'] = substr($line, 14, -1); - } elseif ('msgstr[' === substr($line, 0, 7)) { + } elseif (str_starts_with($line, 'msgstr[')) { $size = strpos($line, ']'); $item['translated'][(int) substr($line, 7, 1)] = substr($line, $size + 3, -1); } @@ -124,7 +122,7 @@ class PoFileLoader extends FileLoader * A .po file could contain by error missing plural indexes. We need to * fix these before saving them. */ - private function addMessage(array &$messages, array $item) + private function addMessage(array &$messages, array $item): void { if (!empty($item['ids']['singular'])) { $id = stripcslashes($item['ids']['singular']); diff --git a/data/web/inc/lib/vendor/symfony/translation/Loader/QtFileLoader.php b/data/web/inc/lib/vendor/symfony/translation/Loader/QtFileLoader.php index 6d5582d66..235f85ee9 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Loader/QtFileLoader.php +++ b/data/web/inc/lib/vendor/symfony/translation/Loader/QtFileLoader.php @@ -25,9 +25,6 @@ use Symfony\Component\Translation\MessageCatalogue; */ class QtFileLoader implements LoaderInterface { - /** - * {@inheritdoc} - */ public function load(mixed $resource, string $locale, string $domain = 'messages'): MessageCatalogue { if (!class_exists(XmlUtils::class)) { @@ -67,7 +64,6 @@ class QtFileLoader implements LoaderInterface $domain ); } - $translation = $translation->nextSibling; } if (class_exists(FileResource::class)) { diff --git a/data/web/inc/lib/vendor/symfony/translation/Loader/XliffFileLoader.php b/data/web/inc/lib/vendor/symfony/translation/Loader/XliffFileLoader.php index 670e19979..31b3251ba 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Loader/XliffFileLoader.php +++ b/data/web/inc/lib/vendor/symfony/translation/Loader/XliffFileLoader.php @@ -28,9 +28,6 @@ use Symfony\Component\Translation\Util\XliffUtils; */ class XliffFileLoader implements LoaderInterface { - /** - * {@inheritdoc} - */ public function load(mixed $resource, string $locale, string $domain = 'messages'): MessageCatalogue { if (!class_exists(XmlUtils::class)) { @@ -75,7 +72,7 @@ class XliffFileLoader implements LoaderInterface return $catalogue; } - private function extract(\DOMDocument $dom, MessageCatalogue $catalogue, string $domain) + private function extract(\DOMDocument $dom, MessageCatalogue $catalogue, string $domain): void { $xliffVersion = XliffUtils::getVersionNumber($dom); @@ -91,7 +88,7 @@ class XliffFileLoader implements LoaderInterface /** * Extract messages and metadata from DOMDocument into a MessageCatalogue. */ - private function extractXliff1(\DOMDocument $dom, MessageCatalogue $catalogue, string $domain) + private function extractXliff1(\DOMDocument $dom, MessageCatalogue $catalogue, string $domain): void { $xml = simplexml_import_dom($dom); $encoding = $dom->encoding ? strtoupper($dom->encoding) : null; @@ -104,6 +101,10 @@ class XliffFileLoader implements LoaderInterface $file->registerXPathNamespace('xliff', $namespace); + foreach ($file->xpath('.//xliff:prop') as $prop) { + $catalogue->setCatalogueMetadata($prop->attributes()['prop-type'], (string) $prop, $domain); + } + foreach ($file->xpath('.//xliff:trans-unit') as $translation) { $attributes = $translation->attributes(); @@ -111,6 +112,10 @@ class XliffFileLoader implements LoaderInterface continue; } + if (isset($translation->target) && 'needs-translation' === (string) $translation->target->attributes()['state']) { + continue; + } + $source = isset($attributes['resname']) && $attributes['resname'] ? $attributes['resname'] : $translation->source; // If the xlf file has another encoding specified, try to convert it because // simple_xml will always return utf-8 encoded values @@ -144,7 +149,7 @@ class XliffFileLoader implements LoaderInterface } } - private function extractXliff2(\DOMDocument $dom, MessageCatalogue $catalogue, string $domain) + private function extractXliff2(\DOMDocument $dom, MessageCatalogue $catalogue, string $domain): void { $xml = simplexml_import_dom($dom); $encoding = $dom->encoding ? strtoupper($dom->encoding) : null; @@ -190,7 +195,7 @@ class XliffFileLoader implements LoaderInterface /** * Convert a UTF8 string to the specified encoding. */ - private function utf8ToCharset(string $content, string $encoding = null): string + private function utf8ToCharset(string $content, ?string $encoding = null): string { if ('UTF-8' !== $encoding && !empty($encoding)) { return mb_convert_encoding($content, $encoding, 'UTF-8'); @@ -199,7 +204,7 @@ class XliffFileLoader implements LoaderInterface return $content; } - private function parseNotesMetadata(\SimpleXMLElement $noteElement = null, string $encoding = null): array + private function parseNotesMetadata(?\SimpleXMLElement $noteElement = null, ?string $encoding = null): array { $notes = []; @@ -227,6 +232,6 @@ class XliffFileLoader implements LoaderInterface private function isXmlString(string $resource): bool { - return 0 === strpos($resource, 'yamlParser) { + if (!isset($this->yamlParser)) { if (!class_exists(\Symfony\Component\Yaml\Parser::class)) { throw new LogicException('Loading translations from the YAML format requires the Symfony Yaml component.'); } diff --git a/data/web/inc/lib/vendor/symfony/translation/LocaleSwitcher.php b/data/web/inc/lib/vendor/symfony/translation/LocaleSwitcher.php new file mode 100644 index 000000000..c07809c58 --- /dev/null +++ b/data/web/inc/lib/vendor/symfony/translation/LocaleSwitcher.php @@ -0,0 +1,78 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Translation; + +use Symfony\Component\Routing\RequestContext; +use Symfony\Contracts\Translation\LocaleAwareInterface; + +/** + * @author Kevin Bond + */ +class LocaleSwitcher implements LocaleAwareInterface +{ + private string $defaultLocale; + + /** + * @param LocaleAwareInterface[] $localeAwareServices + */ + public function __construct( + private string $locale, + private iterable $localeAwareServices, + private ?RequestContext $requestContext = null, + ) { + $this->defaultLocale = $locale; + } + + public function setLocale(string $locale): void + { + if (class_exists(\Locale::class)) { + \Locale::setDefault($locale); + } + $this->locale = $locale; + $this->requestContext?->setParameter('_locale', $locale); + + foreach ($this->localeAwareServices as $service) { + $service->setLocale($locale); + } + } + + public function getLocale(): string + { + return $this->locale; + } + + /** + * Switch to a new locale, execute a callback, then switch back to the original. + * + * @template T + * + * @param callable(string $locale):T $callback + * + * @return T + */ + public function runWithLocale(string $locale, callable $callback): mixed + { + $original = $this->getLocale(); + $this->setLocale($locale); + + try { + return $callback($locale); + } finally { + $this->setLocale($original); + } + } + + public function reset(): void + { + $this->setLocale($this->defaultLocale); + } +} diff --git a/data/web/inc/lib/vendor/symfony/translation/LoggingTranslator.php b/data/web/inc/lib/vendor/symfony/translation/LoggingTranslator.php index 8c8441cdf..4a560bd6a 100644 --- a/data/web/inc/lib/vendor/symfony/translation/LoggingTranslator.php +++ b/data/web/inc/lib/vendor/symfony/translation/LoggingTranslator.php @@ -21,8 +21,8 @@ use Symfony\Contracts\Translation\TranslatorInterface; */ class LoggingTranslator implements TranslatorInterface, TranslatorBagInterface, LocaleAwareInterface { - private $translator; - private $logger; + private TranslatorInterface $translator; + private LoggerInterface $logger; /** * @param TranslatorInterface&TranslatorBagInterface&LocaleAwareInterface $translator The translator must implement TranslatorBagInterface @@ -37,10 +37,7 @@ class LoggingTranslator implements TranslatorInterface, TranslatorBagInterface, $this->logger = $logger; } - /** - * {@inheritdoc} - */ - public function trans(?string $id, array $parameters = [], string $domain = null, string $locale = null): string + public function trans(?string $id, array $parameters = [], ?string $domain = null, ?string $locale = null): string { $trans = $this->translator->trans($id = (string) $id, $parameters, $domain, $locale); $this->log($id, $domain, $locale); @@ -49,7 +46,7 @@ class LoggingTranslator implements TranslatorInterface, TranslatorBagInterface, } /** - * {@inheritdoc} + * @return void */ public function setLocale(string $locale) { @@ -62,25 +59,16 @@ class LoggingTranslator implements TranslatorInterface, TranslatorBagInterface, $this->logger->debug(sprintf('The locale of the translator has changed from "%s" to "%s".', $prev, $locale)); } - /** - * {@inheritdoc} - */ public function getLocale(): string { return $this->translator->getLocale(); } - /** - * {@inheritdoc} - */ - public function getCatalogue(string $locale = null): MessageCatalogueInterface + public function getCatalogue(?string $locale = null): MessageCatalogueInterface { return $this->translator->getCatalogue($locale); } - /** - * {@inheritdoc} - */ public function getCatalogues(): array { return $this->translator->getCatalogues(); @@ -99,7 +87,7 @@ class LoggingTranslator implements TranslatorInterface, TranslatorBagInterface, } /** - * Passes through all unknown calls onto the translator object. + * @return mixed */ public function __call(string $method, array $args) { @@ -109,11 +97,9 @@ class LoggingTranslator implements TranslatorInterface, TranslatorBagInterface, /** * Logs for missing translations. */ - private function log(string $id, ?string $domain, ?string $locale) + private function log(string $id, ?string $domain, ?string $locale): void { - if (null === $domain) { - $domain = 'messages'; - } + $domain ??= 'messages'; $catalogue = $this->translator->getCatalogue($locale); if ($catalogue->defines($id, $domain)) { diff --git a/data/web/inc/lib/vendor/symfony/translation/MessageCatalogue.php b/data/web/inc/lib/vendor/symfony/translation/MessageCatalogue.php index 7aa27efda..d56f04393 100644 --- a/data/web/inc/lib/vendor/symfony/translation/MessageCatalogue.php +++ b/data/web/inc/lib/vendor/symfony/translation/MessageCatalogue.php @@ -17,13 +17,14 @@ use Symfony\Component\Translation\Exception\LogicException; /** * @author Fabien Potencier */ -class MessageCatalogue implements MessageCatalogueInterface, MetadataAwareInterface +class MessageCatalogue implements MessageCatalogueInterface, MetadataAwareInterface, CatalogueMetadataAwareInterface { private array $messages = []; private array $metadata = []; + private array $catalogueMetadata = []; private array $resources = []; private string $locale; - private $fallbackCatalogue = null; + private ?MessageCatalogueInterface $fallbackCatalogue = null; private ?self $parent = null; /** @@ -35,17 +36,11 @@ class MessageCatalogue implements MessageCatalogueInterface, MetadataAwareInterf $this->messages = $messages; } - /** - * {@inheritdoc} - */ public function getLocale(): string { return $this->locale; } - /** - * {@inheritdoc} - */ public function getDomains(): array { $domains = []; @@ -60,10 +55,7 @@ class MessageCatalogue implements MessageCatalogueInterface, MetadataAwareInterf return array_values($domains); } - /** - * {@inheritdoc} - */ - public function all(string $domain = null): array + public function all(?string $domain = null): array { if (null !== $domain) { // skip messages merge if intl-icu requested explicitly @@ -89,16 +81,13 @@ class MessageCatalogue implements MessageCatalogueInterface, MetadataAwareInterf } /** - * {@inheritdoc} + * @return void */ public function set(string $id, string $translation, string $domain = 'messages') { $this->add([$id => $translation], $domain); } - /** - * {@inheritdoc} - */ public function has(string $id, string $domain = 'messages'): bool { if (isset($this->messages[$domain][$id]) || isset($this->messages[$domain.self::INTL_DOMAIN_SUFFIX][$id])) { @@ -112,17 +101,11 @@ class MessageCatalogue implements MessageCatalogueInterface, MetadataAwareInterf return false; } - /** - * {@inheritdoc} - */ public function defines(string $id, string $domain = 'messages'): bool { return isset($this->messages[$domain][$id]) || isset($this->messages[$domain.self::INTL_DOMAIN_SUFFIX][$id]); } - /** - * {@inheritdoc} - */ public function get(string $id, string $domain = 'messages'): string { if (isset($this->messages[$domain.self::INTL_DOMAIN_SUFFIX][$id])) { @@ -141,7 +124,7 @@ class MessageCatalogue implements MessageCatalogueInterface, MetadataAwareInterf } /** - * {@inheritdoc} + * @return void */ public function replace(array $messages, string $domain = 'messages') { @@ -151,28 +134,23 @@ class MessageCatalogue implements MessageCatalogueInterface, MetadataAwareInterf } /** - * {@inheritdoc} + * @return void */ public function add(array $messages, string $domain = 'messages') { - if (!isset($this->messages[$domain])) { - $this->messages[$domain] = []; - } - $intlDomain = $domain; - if (!str_ends_with($domain, self::INTL_DOMAIN_SUFFIX)) { - $intlDomain .= self::INTL_DOMAIN_SUFFIX; - } + $altDomain = str_ends_with($domain, self::INTL_DOMAIN_SUFFIX) ? substr($domain, 0, -\strlen(self::INTL_DOMAIN_SUFFIX)) : $domain.self::INTL_DOMAIN_SUFFIX; foreach ($messages as $id => $message) { - if (isset($this->messages[$intlDomain]) && \array_key_exists($id, $this->messages[$intlDomain])) { - $this->messages[$intlDomain][$id] = $message; - } else { - $this->messages[$domain][$id] = $message; - } + unset($this->messages[$altDomain][$id]); + $this->messages[$domain][$id] = $message; + } + + if ([] === ($this->messages[$altDomain] ?? null)) { + unset($this->messages[$altDomain]); } } /** - * {@inheritdoc} + * @return void */ public function addCatalogue(MessageCatalogueInterface $catalogue) { @@ -196,10 +174,15 @@ class MessageCatalogue implements MessageCatalogueInterface, MetadataAwareInterf $metadata = $catalogue->getMetadata('', ''); $this->addMetadata($metadata); } + + if ($catalogue instanceof CatalogueMetadataAwareInterface) { + $catalogueMetadata = $catalogue->getCatalogueMetadata('', ''); + $this->addCatalogueMetadata($catalogueMetadata); + } } /** - * {@inheritdoc} + * @return void */ public function addFallbackCatalogue(MessageCatalogueInterface $catalogue) { @@ -230,33 +213,24 @@ class MessageCatalogue implements MessageCatalogueInterface, MetadataAwareInterf } } - /** - * {@inheritdoc} - */ public function getFallbackCatalogue(): ?MessageCatalogueInterface { return $this->fallbackCatalogue; } - /** - * {@inheritdoc} - */ public function getResources(): array { return array_values($this->resources); } /** - * {@inheritdoc} + * @return void */ public function addResource(ResourceInterface $resource) { $this->resources[$resource->__toString()] = $resource; } - /** - * {@inheritdoc} - */ public function getMetadata(string $key = '', string $domain = 'messages'): mixed { if ('' == $domain) { @@ -277,7 +251,7 @@ class MessageCatalogue implements MessageCatalogueInterface, MetadataAwareInterf } /** - * {@inheritdoc} + * @return void */ public function setMetadata(string $key, mixed $value, string $domain = 'messages') { @@ -285,7 +259,7 @@ class MessageCatalogue implements MessageCatalogueInterface, MetadataAwareInterf } /** - * {@inheritdoc} + * @return void */ public function deleteMetadata(string $key = '', string $domain = 'messages') { @@ -298,12 +272,53 @@ class MessageCatalogue implements MessageCatalogueInterface, MetadataAwareInterf } } + public function getCatalogueMetadata(string $key = '', string $domain = 'messages'): mixed + { + if (!$domain) { + return $this->catalogueMetadata; + } + + if (isset($this->catalogueMetadata[$domain])) { + if (!$key) { + return $this->catalogueMetadata[$domain]; + } + + if (isset($this->catalogueMetadata[$domain][$key])) { + return $this->catalogueMetadata[$domain][$key]; + } + } + + return null; + } + + /** + * @return void + */ + public function setCatalogueMetadata(string $key, mixed $value, string $domain = 'messages') + { + $this->catalogueMetadata[$domain][$key] = $value; + } + + /** + * @return void + */ + public function deleteCatalogueMetadata(string $key = '', string $domain = 'messages') + { + if (!$domain) { + $this->catalogueMetadata = []; + } elseif (!$key) { + unset($this->catalogueMetadata[$domain]); + } else { + unset($this->catalogueMetadata[$domain][$key]); + } + } + /** * Adds current values with the new values. * * @param array $values Values to add */ - private function addMetadata(array $values) + private function addMetadata(array $values): void { foreach ($values as $domain => $keys) { foreach ($keys as $key => $value) { @@ -311,4 +326,13 @@ class MessageCatalogue implements MessageCatalogueInterface, MetadataAwareInterf } } } + + private function addCatalogueMetadata(array $values): void + { + foreach ($values as $domain => $keys) { + foreach ($keys as $key => $value) { + $this->setCatalogueMetadata($key, $value, $domain); + } + } + } } diff --git a/data/web/inc/lib/vendor/symfony/translation/MessageCatalogueInterface.php b/data/web/inc/lib/vendor/symfony/translation/MessageCatalogueInterface.php index 75e3a2fa7..fd0d26d7e 100644 --- a/data/web/inc/lib/vendor/symfony/translation/MessageCatalogueInterface.php +++ b/data/web/inc/lib/vendor/symfony/translation/MessageCatalogueInterface.php @@ -36,10 +36,8 @@ interface MessageCatalogueInterface * Gets the messages within a given domain. * * If $domain is null, it returns all messages. - * - * @param string $domain The domain name */ - public function all(string $domain = null): array; + public function all(?string $domain = null): array; /** * Sets a message translation. @@ -47,6 +45,8 @@ interface MessageCatalogueInterface * @param string $id The message id * @param string $translation The messages translation * @param string $domain The domain name + * + * @return void */ public function set(string $id, string $translation, string $domain = 'messages'); @@ -79,6 +79,8 @@ interface MessageCatalogueInterface * * @param array $messages An array of translations * @param string $domain The domain name + * + * @return void */ public function replace(array $messages, string $domain = 'messages'); @@ -87,6 +89,8 @@ interface MessageCatalogueInterface * * @param array $messages An array of translations * @param string $domain The domain name + * + * @return void */ public function add(array $messages, string $domain = 'messages'); @@ -94,6 +98,8 @@ interface MessageCatalogueInterface * Merges translations from the given Catalogue into the current one. * * The two catalogues must have the same locale. + * + * @return void */ public function addCatalogue(self $catalogue); @@ -102,6 +108,8 @@ interface MessageCatalogueInterface * only when the translation does not exist. * * This is used to provide default translations when they do not exist for the current locale. + * + * @return void */ public function addFallbackCatalogue(self $catalogue); @@ -119,6 +127,8 @@ interface MessageCatalogueInterface /** * Adds a resource for this collection. + * + * @return void */ public function addResource(ResourceInterface $resource); } diff --git a/data/web/inc/lib/vendor/symfony/translation/MetadataAwareInterface.php b/data/web/inc/lib/vendor/symfony/translation/MetadataAwareInterface.php index 2eaaceb36..39e5326c3 100644 --- a/data/web/inc/lib/vendor/symfony/translation/MetadataAwareInterface.php +++ b/data/web/inc/lib/vendor/symfony/translation/MetadataAwareInterface.php @@ -12,7 +12,7 @@ namespace Symfony\Component\Translation; /** - * MetadataAwareInterface. + * This interface is used to get, set, and delete metadata about the translation messages. * * @author Fabien Potencier */ @@ -31,6 +31,8 @@ interface MetadataAwareInterface /** * Adds metadata to a message domain. + * + * @return void */ public function setMetadata(string $key, mixed $value, string $domain = 'messages'); @@ -39,6 +41,8 @@ interface MetadataAwareInterface * * Passing an empty domain will delete all metadata. Passing an empty key will * delete all metadata for the given domain. + * + * @return void */ public function deleteMetadata(string $key = '', string $domain = 'messages'); } diff --git a/data/web/inc/lib/vendor/symfony/translation/Provider/AbstractProviderFactory.php b/data/web/inc/lib/vendor/symfony/translation/Provider/AbstractProviderFactory.php index 17442fde8..f0c11d85d 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Provider/AbstractProviderFactory.php +++ b/data/web/inc/lib/vendor/symfony/translation/Provider/AbstractProviderFactory.php @@ -27,19 +27,11 @@ abstract class AbstractProviderFactory implements ProviderFactoryInterface protected function getUser(Dsn $dsn): string { - if (null === $user = $dsn->getUser()) { - throw new IncompleteDsnException('User is not set.', $dsn->getOriginalDsn()); - } - - return $user; + return $dsn->getUser() ?? throw new IncompleteDsnException('User is not set.', $dsn->getScheme().'://'.$dsn->getHost()); } protected function getPassword(Dsn $dsn): string { - if (null === $password = $dsn->getPassword()) { - throw new IncompleteDsnException('Password is not set.', $dsn->getOriginalDsn()); - } - - return $password; + return $dsn->getPassword() ?? throw new IncompleteDsnException('Password is not set.', $dsn->getOriginalDsn()); } } diff --git a/data/web/inc/lib/vendor/symfony/translation/Provider/Dsn.php b/data/web/inc/lib/vendor/symfony/translation/Provider/Dsn.php index 0f74d17fb..1d90e27f9 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Provider/Dsn.php +++ b/data/web/inc/lib/vendor/symfony/translation/Provider/Dsn.php @@ -29,29 +29,29 @@ final class Dsn private array $options = []; private string $originalDsn; - public function __construct(string $dsn) + public function __construct(#[\SensitiveParameter] string $dsn) { $this->originalDsn = $dsn; - if (false === $parsedDsn = parse_url($dsn)) { - throw new InvalidArgumentException(sprintf('The "%s" translation provider DSN is invalid.', $dsn)); + if (false === $params = parse_url($dsn)) { + throw new InvalidArgumentException('The translation provider DSN is invalid.'); } - if (!isset($parsedDsn['scheme'])) { - throw new InvalidArgumentException(sprintf('The "%s" translation provider DSN must contain a scheme.', $dsn)); + if (!isset($params['scheme'])) { + throw new InvalidArgumentException('The translation provider DSN must contain a scheme.'); } - $this->scheme = $parsedDsn['scheme']; + $this->scheme = $params['scheme']; - if (!isset($parsedDsn['host'])) { - throw new InvalidArgumentException(sprintf('The "%s" translation provider DSN must contain a host (use "default" by default).', $dsn)); + if (!isset($params['host'])) { + throw new InvalidArgumentException('The translation provider DSN must contain a host (use "default" by default).'); } - $this->host = $parsedDsn['host']; + $this->host = $params['host']; - $this->user = '' !== ($parsedDsn['user'] ?? '') ? urldecode($parsedDsn['user']) : null; - $this->password = '' !== ($parsedDsn['pass'] ?? '') ? urldecode($parsedDsn['pass']) : null; - $this->port = $parsedDsn['port'] ?? null; - $this->path = $parsedDsn['path'] ?? null; - parse_str($parsedDsn['query'] ?? '', $this->options); + $this->user = '' !== ($params['user'] ?? '') ? rawurldecode($params['user']) : null; + $this->password = '' !== ($params['pass'] ?? '') ? rawurldecode($params['pass']) : null; + $this->port = $params['port'] ?? null; + $this->path = $params['path'] ?? null; + parse_str($params['query'] ?? '', $this->options); } public function getScheme(): string @@ -74,17 +74,17 @@ final class Dsn return $this->password; } - public function getPort(int $default = null): ?int + public function getPort(?int $default = null): ?int { return $this->port ?? $default; } - public function getOption(string $key, mixed $default = null) + public function getOption(string $key, mixed $default = null): mixed { return $this->options[$key] ?? $default; } - public function getRequiredOption(string $key) + public function getRequiredOption(string $key): mixed { if (!\array_key_exists($key, $this->options) || '' === trim($this->options[$key])) { throw new MissingRequiredOptionException($key); diff --git a/data/web/inc/lib/vendor/symfony/translation/Provider/FilteringProvider.php b/data/web/inc/lib/vendor/symfony/translation/Provider/FilteringProvider.php index a43fedc71..d4465b9fd 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Provider/FilteringProvider.php +++ b/data/web/inc/lib/vendor/symfony/translation/Provider/FilteringProvider.php @@ -21,7 +21,7 @@ use Symfony\Component\Translation\TranslatorBagInterface; */ class FilteringProvider implements ProviderInterface { - private $provider; + private ProviderInterface $provider; private array $locales; private array $domains; @@ -37,9 +37,6 @@ class FilteringProvider implements ProviderInterface return (string) $this->provider; } - /** - * {@inheritdoc} - */ public function write(TranslatorBagInterface $translatorBag): void { $this->provider->write($translatorBag); diff --git a/data/web/inc/lib/vendor/symfony/translation/Provider/ProviderInterface.php b/data/web/inc/lib/vendor/symfony/translation/Provider/ProviderInterface.php index a32193f29..0e47083b6 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Provider/ProviderInterface.php +++ b/data/web/inc/lib/vendor/symfony/translation/Provider/ProviderInterface.php @@ -14,10 +14,8 @@ namespace Symfony\Component\Translation\Provider; use Symfony\Component\Translation\TranslatorBag; use Symfony\Component\Translation\TranslatorBagInterface; -interface ProviderInterface +interface ProviderInterface extends \Stringable { - public function __toString(): string; - /** * Translations available in the TranslatorBag only must be created. * Translations available in both the TranslatorBag and on the provider diff --git a/data/web/inc/lib/vendor/symfony/translation/Provider/TranslationProviderCollection.php b/data/web/inc/lib/vendor/symfony/translation/Provider/TranslationProviderCollection.php index 61ac641cd..b917415ba 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Provider/TranslationProviderCollection.php +++ b/data/web/inc/lib/vendor/symfony/translation/Provider/TranslationProviderCollection.php @@ -21,7 +21,7 @@ final class TranslationProviderCollection /** * @var array */ - private $providers; + private array $providers; /** * @param array $providers diff --git a/data/web/inc/lib/vendor/symfony/translation/PseudoLocalizationTranslator.php b/data/web/inc/lib/vendor/symfony/translation/PseudoLocalizationTranslator.php index 1d10e0ccb..f26909f5e 100644 --- a/data/web/inc/lib/vendor/symfony/translation/PseudoLocalizationTranslator.php +++ b/data/web/inc/lib/vendor/symfony/translation/PseudoLocalizationTranslator.php @@ -20,7 +20,7 @@ final class PseudoLocalizationTranslator implements TranslatorInterface { private const EXPANSION_CHARACTER = '~'; - private $translator; + private TranslatorInterface $translator; private bool $accents; private float $expansionFactor; private bool $brackets; @@ -83,10 +83,7 @@ final class PseudoLocalizationTranslator implements TranslatorInterface $this->localizableHTMLAttributes = $options['localizable_html_attributes'] ?? []; } - /** - * {@inheritdoc} - */ - public function trans(string $id, array $parameters = [], string $domain = null, string $locale = null): string + public function trans(string $id, array $parameters = [], ?string $domain = null, ?string $locale = null): string { $trans = ''; $visibleText = ''; @@ -123,7 +120,7 @@ final class PseudoLocalizationTranslator implements TranslatorInterface return [[true, true, $originalTrans]]; } - $html = mb_convert_encoding($originalTrans, 'HTML-ENTITIES', mb_detect_encoding($originalTrans, null, true) ?: 'UTF-8'); + $html = mb_encode_numericentity($originalTrans, [0x80, 0x10FFFF, 0, 0x1FFFFF], mb_detect_encoding($originalTrans, null, true) ?: 'UTF-8'); $useInternalErrors = libxml_use_internal_errors(true); @@ -283,7 +280,7 @@ final class PseudoLocalizationTranslator implements TranslatorInterface } $visibleLength = $this->strlen($visibleText); - $missingLength = (int) (ceil($visibleLength * $this->expansionFactor)) - $visibleLength; + $missingLength = (int) ceil($visibleLength * $this->expansionFactor) - $visibleLength; if ($this->brackets) { $missingLength -= 2; } diff --git a/data/web/inc/lib/vendor/symfony/translation/README.md b/data/web/inc/lib/vendor/symfony/translation/README.md index adda9a5b2..32e4017b7 100644 --- a/data/web/inc/lib/vendor/symfony/translation/README.md +++ b/data/web/inc/lib/vendor/symfony/translation/README.md @@ -26,12 +26,7 @@ echo $translator->trans('Hello World!'); // outputs « Bonjour ! » Sponsor ------- -The Translation component for Symfony 5.4/6.0 is [backed][1] by: - - * [Crowdin][2], a cloud-based localization management software helping teams to go global and stay agile. - * [Lokalise][3], a continuous localization and translation management platform that integrates into your development workflow so you can ship localized products, faster. - -Help Symfony by [sponsoring][4] its development! +Help Symfony by [sponsoring][1] its development! Resources --------- @@ -42,7 +37,4 @@ Resources [send Pull Requests](https://github.com/symfony/symfony/pulls) in the [main Symfony repository](https://github.com/symfony/symfony) -[1]: https://symfony.com/backers -[2]: https://crowdin.com -[3]: https://lokalise.com -[4]: https://symfony.com/sponsor +[1]: https://symfony.com/sponsor diff --git a/data/web/inc/lib/vendor/symfony/translation/Reader/TranslationReader.php b/data/web/inc/lib/vendor/symfony/translation/Reader/TranslationReader.php index bbc687e13..01408d4dc 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Reader/TranslationReader.php +++ b/data/web/inc/lib/vendor/symfony/translation/Reader/TranslationReader.php @@ -33,6 +33,8 @@ class TranslationReader implements TranslationReaderInterface * Adds a loader to the translation extractor. * * @param string $format The format of the loader + * + * @return void */ public function addLoader(string $format, LoaderInterface $loader) { @@ -40,7 +42,7 @@ class TranslationReader implements TranslationReaderInterface } /** - * {@inheritdoc} + * @return void */ public function read(string $directory, MessageCatalogue $catalogue) { diff --git a/data/web/inc/lib/vendor/symfony/translation/Reader/TranslationReaderInterface.php b/data/web/inc/lib/vendor/symfony/translation/Reader/TranslationReaderInterface.php index bc37204f9..ea74dc23f 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Reader/TranslationReaderInterface.php +++ b/data/web/inc/lib/vendor/symfony/translation/Reader/TranslationReaderInterface.php @@ -22,6 +22,8 @@ interface TranslationReaderInterface { /** * Reads translation messages from a directory to the catalogue. + * + * @return void */ public function read(string $directory, MessageCatalogue $catalogue); } diff --git a/data/web/inc/lib/vendor/symfony/translation/Resources/bin/translation-status.php b/data/web/inc/lib/vendor/symfony/translation/Resources/bin/translation-status.php index a76916427..8064190d8 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Resources/bin/translation-status.php +++ b/data/web/inc/lib/vendor/symfony/translation/Resources/bin/translation-status.php @@ -9,6 +9,10 @@ * file that was distributed with this source code. */ +if ('cli' !== \PHP_SAPI) { + throw new Exception('This script must be run from the command line.'); +} + $usageInstructions = << count($translation['missingKeys']), array_values($translationStatus))); + $totalTranslationMismatches += array_sum(array_map(fn ($translation) => count($translation['mismatches']), array_values($translationStatus))); printTranslationStatus($originalFilePath, $translationStatus, $config['verbose_output'], $config['include_completed_languages']); } exit($totalTranslationMismatches > 0 ? 1 : 0); -function findTranslationFiles($originalFilePath, $localeToAnalyze) +function findTranslationFiles($originalFilePath, $localeToAnalyze): array { $translations = []; @@ -118,7 +118,7 @@ function findTranslationFiles($originalFilePath, $localeToAnalyze) return $translations; } -function calculateTranslationStatus($originalFilePath, $translationFilePaths) +function calculateTranslationStatus($originalFilePath, $translationFilePaths): array { $translationStatus = []; $allTranslationKeys = extractTranslationKeys($originalFilePath); @@ -159,7 +159,7 @@ function extractLocaleFromFilePath($filePath) return $parts[count($parts) - 2]; } -function extractTranslationKeys($filePath) +function extractTranslationKeys($filePath): array { $translationKeys = []; $contents = new \SimpleXMLElement(file_get_contents($filePath)); diff --git a/data/web/inc/lib/vendor/symfony/translation/Resources/data/parents.json b/data/web/inc/lib/vendor/symfony/translation/Resources/data/parents.json index 288f16300..24d4d119e 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Resources/data/parents.json +++ b/data/web/inc/lib/vendor/symfony/translation/Resources/data/parents.json @@ -35,6 +35,7 @@ "en_GM": "en_001", "en_GY": "en_001", "en_HK": "en_001", + "en_ID": "en_001", "en_IE": "en_001", "en_IL": "en_001", "en_IM": "en_001", @@ -54,6 +55,7 @@ "en_MS": "en_001", "en_MT": "en_001", "en_MU": "en_001", + "en_MV": "en_001", "en_MW": "en_001", "en_MY": "en_001", "en_NA": "en_001", @@ -116,6 +118,8 @@ "es_UY": "es_419", "es_VE": "es_419", "ff_Adlm": "root", + "hi_Latn": "en_IN", + "ks_Deva": "root", "nb": "no", "nn": "no", "pa_Arab": "root", diff --git a/data/web/inc/lib/vendor/symfony/translation/Resources/functions.php b/data/web/inc/lib/vendor/symfony/translation/Resources/functions.php index 901d2f87e..0d2a037a2 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Resources/functions.php +++ b/data/web/inc/lib/vendor/symfony/translation/Resources/functions.php @@ -15,7 +15,7 @@ if (!\function_exists(t::class)) { /** * @author Nate Wiebe */ - function t(string $message, array $parameters = [], string $domain = null): TranslatableMessage + function t(string $message, array $parameters = [], ?string $domain = null): TranslatableMessage { return new TranslatableMessage($message, $parameters, $domain); } diff --git a/data/web/inc/lib/vendor/symfony/translation/Resources/schemas/xliff-core-1.2-strict.xsd b/data/web/inc/lib/vendor/symfony/translation/Resources/schemas/xliff-core-1.2-transitional.xsd similarity index 96% rename from data/web/inc/lib/vendor/symfony/translation/Resources/schemas/xliff-core-1.2-strict.xsd rename to data/web/inc/lib/vendor/symfony/translation/Resources/schemas/xliff-core-1.2-transitional.xsd index dface628c..1f38de72f 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Resources/schemas/xliff-core-1.2-strict.xsd +++ b/data/web/inc/lib/vendor/symfony/translation/Resources/schemas/xliff-core-1.2-transitional.xsd @@ -1,5 +1,4 @@ - - + - + @@ -1672,14 +1672,16 @@ Jan-10-2006 + + - + @@ -1739,10 +1741,11 @@ Jan-10-2006 + - + @@ -1791,6 +1794,7 @@ Jan-10-2006 + @@ -1838,16 +1842,34 @@ Jan-10-2006 + + + + + + + + + + + + + + + + + + - + - + @@ -1865,8 +1887,9 @@ Jan-10-2006 + - + @@ -1877,6 +1900,7 @@ Jan-10-2006 + @@ -1901,7 +1925,7 @@ Jan-10-2006 - + @@ -1913,10 +1937,11 @@ Jan-10-2006 + - + @@ -1924,6 +1949,7 @@ Jan-10-2006 + @@ -1947,7 +1973,7 @@ Jan-10-2006 - + @@ -1962,7 +1988,8 @@ Jan-10-2006 - + + @@ -1985,7 +2012,8 @@ Jan-10-2006 - + + @@ -2011,6 +2039,8 @@ Jan-10-2006 + + @@ -2018,7 +2048,7 @@ Jan-10-2006 - + @@ -2042,18 +2072,21 @@ Jan-10-2006 - + + - + + + @@ -2070,7 +2103,7 @@ Jan-10-2006 - + @@ -2089,20 +2122,22 @@ Jan-10-2006 + - + + - + @@ -2111,7 +2146,8 @@ Jan-10-2006 - + + @@ -2121,12 +2157,13 @@ Jan-10-2006 + - + @@ -2217,7 +2254,8 @@ Jan-10-2006 - + + diff --git a/data/web/inc/lib/vendor/symfony/translation/Test/ProviderFactoryTestCase.php b/data/web/inc/lib/vendor/symfony/translation/Test/ProviderFactoryTestCase.php index d6510e0dd..95ffcb1e5 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Test/ProviderFactoryTestCase.php +++ b/data/web/inc/lib/vendor/symfony/translation/Test/ProviderFactoryTestCase.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Translation\Test; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; use Symfony\Component\HttpClient\MockHttpClient; @@ -20,39 +21,39 @@ use Symfony\Component\Translation\Exception\UnsupportedSchemeException; use Symfony\Component\Translation\Loader\LoaderInterface; use Symfony\Component\Translation\Provider\Dsn; use Symfony\Component\Translation\Provider\ProviderFactoryInterface; +use Symfony\Component\Translation\TranslatorBagInterface; use Symfony\Contracts\HttpClient\HttpClientInterface; /** * A test case to ease testing a translation provider factory. * * @author Mathieu Santostefano - * - * @internal */ abstract class ProviderFactoryTestCase extends TestCase { - protected $client; - protected $logger; + protected HttpClientInterface $client; + protected LoggerInterface|MockObject $logger; protected string $defaultLocale; - protected $loader; - protected $xliffFileDumper; + protected LoaderInterface|MockObject $loader; + protected XliffFileDumper|MockObject $xliffFileDumper; + protected TranslatorBagInterface|MockObject $translatorBag; abstract public function createFactory(): ProviderFactoryInterface; /** * @return iterable */ - abstract public function supportsProvider(): iterable; + abstract public static function supportsProvider(): iterable; /** - * @return iterable + * @return iterable */ - abstract public function createProvider(): iterable; + abstract public static function createProvider(): iterable; /** * @return iterable */ - public function unsupportedSchemeProvider(): iterable + public static function unsupportedSchemeProvider(): iterable { return []; } @@ -60,7 +61,7 @@ abstract class ProviderFactoryTestCase extends TestCase /** * @return iterable */ - public function incompleteDsnProvider(): iterable + public static function incompleteDsnProvider(): iterable { return []; } @@ -89,7 +90,7 @@ abstract class ProviderFactoryTestCase extends TestCase /** * @dataProvider unsupportedSchemeProvider */ - public function testUnsupportedSchemeException(string $dsn, string $message = null) + public function testUnsupportedSchemeException(string $dsn, ?string $message = null) { $factory = $this->createFactory(); @@ -106,7 +107,7 @@ abstract class ProviderFactoryTestCase extends TestCase /** * @dataProvider incompleteDsnProvider */ - public function testIncompleteDsnException(string $dsn, string $message = null) + public function testIncompleteDsnException(string $dsn, ?string $message = null) { $factory = $this->createFactory(); @@ -144,4 +145,9 @@ abstract class ProviderFactoryTestCase extends TestCase { return $this->xliffFileDumper ??= $this->createMock(XliffFileDumper::class); } + + protected function getTranslatorBag(): TranslatorBagInterface + { + return $this->translatorBag ??= $this->createMock(TranslatorBagInterface::class); + } } diff --git a/data/web/inc/lib/vendor/symfony/translation/Test/ProviderTestCase.php b/data/web/inc/lib/vendor/symfony/translation/Test/ProviderTestCase.php index 5ae26829b..a8fa0b8bb 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Test/ProviderTestCase.php +++ b/data/web/inc/lib/vendor/symfony/translation/Test/ProviderTestCase.php @@ -11,35 +11,36 @@ namespace Symfony\Component\Translation\Test; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; use Symfony\Component\HttpClient\MockHttpClient; use Symfony\Component\Translation\Dumper\XliffFileDumper; use Symfony\Component\Translation\Loader\LoaderInterface; use Symfony\Component\Translation\Provider\ProviderInterface; +use Symfony\Component\Translation\TranslatorBagInterface; use Symfony\Contracts\HttpClient\HttpClientInterface; /** * A test case to ease testing a translation provider. * * @author Mathieu Santostefano - * - * @internal */ abstract class ProviderTestCase extends TestCase { - protected $client; - protected $logger; + protected HttpClientInterface $client; + protected LoggerInterface|MockObject $logger; protected string $defaultLocale; - protected $loader; - protected $xliffFileDumper; + protected LoaderInterface|MockObject $loader; + protected XliffFileDumper|MockObject $xliffFileDumper; + protected TranslatorBagInterface|MockObject $translatorBag; - abstract public function createProvider(HttpClientInterface $client, LoaderInterface $loader, LoggerInterface $logger, string $defaultLocale, string $endpoint): ProviderInterface; + abstract public static function createProvider(HttpClientInterface $client, LoaderInterface $loader, LoggerInterface $logger, string $defaultLocale, string $endpoint): ProviderInterface; /** - * @return iterable + * @return iterable */ - abstract public function toStringProvider(): iterable; + abstract public static function toStringProvider(): iterable; /** * @dataProvider toStringProvider @@ -73,4 +74,9 @@ abstract class ProviderTestCase extends TestCase { return $this->xliffFileDumper ??= $this->createMock(XliffFileDumper::class); } + + protected function getTranslatorBag(): TranslatorBagInterface + { + return $this->translatorBag ??= $this->createMock(TranslatorBagInterface::class); + } } diff --git a/data/web/inc/lib/vendor/symfony/translation/TranslatableMessage.php b/data/web/inc/lib/vendor/symfony/translation/TranslatableMessage.php index b1a3b6b13..c591e68c2 100644 --- a/data/web/inc/lib/vendor/symfony/translation/TranslatableMessage.php +++ b/data/web/inc/lib/vendor/symfony/translation/TranslatableMessage.php @@ -23,7 +23,7 @@ class TranslatableMessage implements TranslatableInterface private array $parameters; private ?string $domain; - public function __construct(string $message, array $parameters = [], string $domain = null) + public function __construct(string $message, array $parameters = [], ?string $domain = null) { $this->message = $message; $this->parameters = $parameters; @@ -50,12 +50,10 @@ class TranslatableMessage implements TranslatableInterface return $this->domain; } - public function trans(TranslatorInterface $translator, string $locale = null): string + public function trans(TranslatorInterface $translator, ?string $locale = null): string { return $translator->trans($this->getMessage(), array_map( - static function ($parameter) use ($translator, $locale) { - return $parameter instanceof TranslatableInterface ? $parameter->trans($translator, $locale) : $parameter; - }, + static fn ($parameter) => $parameter instanceof TranslatableInterface ? $parameter->trans($translator, $locale) : $parameter, $this->getParameters() ), $this->getDomain(), $locale); } diff --git a/data/web/inc/lib/vendor/symfony/translation/Translator.php b/data/web/inc/lib/vendor/symfony/translation/Translator.php index 05e84d0cc..1973d079f 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Translator.php +++ b/data/web/inc/lib/vendor/symfony/translation/Translator.php @@ -22,6 +22,7 @@ use Symfony\Component\Translation\Formatter\MessageFormatter; use Symfony\Component\Translation\Formatter\MessageFormatterInterface; use Symfony\Component\Translation\Loader\LoaderInterface; use Symfony\Contracts\Translation\LocaleAwareInterface; +use Symfony\Contracts\Translation\TranslatableInterface; use Symfony\Contracts\Translation\TranslatorInterface; // Help opcache.preload discover always-needed symbols @@ -51,7 +52,7 @@ class Translator implements TranslatorInterface, TranslatorBagInterface, LocaleA private array $resources = []; - private $formatter; + private MessageFormatterInterface $formatter; private ?string $cacheDir; @@ -59,7 +60,7 @@ class Translator implements TranslatorInterface, TranslatorBagInterface, LocaleA private array $cacheVary; - private $configCacheFactory; + private ?ConfigCacheFactoryInterface $configCacheFactory; private array $parentLocales; @@ -68,21 +69,20 @@ class Translator implements TranslatorInterface, TranslatorBagInterface, LocaleA /** * @throws InvalidArgumentException If a locale contains invalid characters */ - public function __construct(string $locale, MessageFormatterInterface $formatter = null, string $cacheDir = null, bool $debug = false, array $cacheVary = []) + public function __construct(string $locale, ?MessageFormatterInterface $formatter = null, ?string $cacheDir = null, bool $debug = false, array $cacheVary = []) { $this->setLocale($locale); - if (null === $formatter) { - $formatter = new MessageFormatter(); - } - - $this->formatter = $formatter; + $this->formatter = $formatter ??= new MessageFormatter(); $this->cacheDir = $cacheDir; $this->debug = $debug; $this->cacheVary = $cacheVary; $this->hasIntlFormatter = $formatter instanceof IntlFormatterInterface; } + /** + * @return void + */ public function setConfigCacheFactory(ConfigCacheFactoryInterface $configCacheFactory) { $this->configCacheFactory = $configCacheFactory; @@ -92,6 +92,8 @@ class Translator implements TranslatorInterface, TranslatorBagInterface, LocaleA * Adds a Loader. * * @param string $format The name of the loader (@see addResource()) + * + * @return void */ public function addLoader(string $format, LoaderInterface $loader) { @@ -104,13 +106,13 @@ class Translator implements TranslatorInterface, TranslatorBagInterface, LocaleA * @param string $format The name of the loader (@see addLoader()) * @param mixed $resource The resource name * + * @return void + * * @throws InvalidArgumentException If the locale contains invalid characters */ - public function addResource(string $format, mixed $resource, string $locale, string $domain = null) + public function addResource(string $format, mixed $resource, string $locale, ?string $domain = null) { - if (null === $domain) { - $domain = 'messages'; - } + $domain ??= 'messages'; $this->assertValidLocale($locale); $locale ?: $locale = class_exists(\Locale::class) ? \Locale::getDefault() : 'en'; @@ -125,7 +127,7 @@ class Translator implements TranslatorInterface, TranslatorBagInterface, LocaleA } /** - * {@inheritdoc} + * @return void */ public function setLocale(string $locale) { @@ -133,9 +135,6 @@ class Translator implements TranslatorInterface, TranslatorBagInterface, LocaleA $this->locale = $locale; } - /** - * {@inheritdoc} - */ public function getLocale(): string { return $this->locale ?: (class_exists(\Locale::class) ? \Locale::getDefault() : 'en'); @@ -146,6 +145,8 @@ class Translator implements TranslatorInterface, TranslatorBagInterface, LocaleA * * @param string[] $locales * + * @return void + * * @throws InvalidArgumentException If a locale contains invalid characters */ public function setFallbackLocales(array $locales) @@ -170,18 +171,13 @@ class Translator implements TranslatorInterface, TranslatorBagInterface, LocaleA return $this->fallbackLocales; } - /** - * {@inheritdoc} - */ - public function trans(?string $id, array $parameters = [], string $domain = null, string $locale = null): string + public function trans(?string $id, array $parameters = [], ?string $domain = null, ?string $locale = null): string { if (null === $id || '' === $id) { return ''; } - if (null === $domain) { - $domain = 'messages'; - } + $domain ??= 'messages'; $catalogue = $this->getCatalogue($locale); $locale = $catalogue->getLocale(); @@ -194,6 +190,8 @@ class Translator implements TranslatorInterface, TranslatorBagInterface, LocaleA } } + $parameters = array_map(fn ($parameter) => $parameter instanceof TranslatableInterface ? $parameter->trans($this, $locale) : $parameter, $parameters); + $len = \strlen(MessageCatalogue::INTL_DOMAIN_SUFFIX); if ($this->hasIntlFormatter && ($catalogue->defines($id, $domain.MessageCatalogue::INTL_DOMAIN_SUFFIX) @@ -205,10 +203,7 @@ class Translator implements TranslatorInterface, TranslatorBagInterface, LocaleA return $this->formatter->format($catalogue->get($id, $domain), $locale, $parameters); } - /** - * {@inheritdoc} - */ - public function getCatalogue(string $locale = null): MessageCatalogueInterface + public function getCatalogue(?string $locale = null): MessageCatalogueInterface { if (!$locale) { $locale = $this->getLocale(); @@ -223,9 +218,6 @@ class Translator implements TranslatorInterface, TranslatorBagInterface, LocaleA return $this->catalogues[$locale]; } - /** - * {@inheritdoc} - */ public function getCatalogues(): array { return array_values($this->catalogues); @@ -241,6 +233,9 @@ class Translator implements TranslatorInterface, TranslatorBagInterface, LocaleA return $this->loaders; } + /** + * @return void + */ protected function loadCatalogue(string $locale) { if (null === $this->cacheDir) { @@ -250,6 +245,9 @@ class Translator implements TranslatorInterface, TranslatorBagInterface, LocaleA } } + /** + * @return void + */ protected function initializeCatalogue(string $locale) { $this->assertValidLocale($locale); @@ -386,6 +384,9 @@ EOF } } + /** + * @return array + */ protected function computeFallbackLocales(string $locale) { $this->parentLocales ??= json_decode(file_get_contents(__DIR__.'/Resources/data/parents.json'), true); @@ -430,6 +431,8 @@ EOF /** * Asserts that the locale is valid, throws an Exception if not. * + * @return void + * * @throws InvalidArgumentException If the locale contains invalid characters */ protected function assertValidLocale(string $locale) diff --git a/data/web/inc/lib/vendor/symfony/translation/TranslatorBag.php b/data/web/inc/lib/vendor/symfony/translation/TranslatorBag.php index ffd109f17..3b47aecee 100644 --- a/data/web/inc/lib/vendor/symfony/translation/TranslatorBag.php +++ b/data/web/inc/lib/vendor/symfony/translation/TranslatorBag.php @@ -35,10 +35,7 @@ final class TranslatorBag implements TranslatorBagInterface } } - /** - * {@inheritdoc} - */ - public function getCatalogue(string $locale = null): MessageCatalogueInterface + public function getCatalogue(?string $locale = null): MessageCatalogueInterface { if (null === $locale || !isset($this->catalogues[$locale])) { $this->catalogues[$locale] = new MessageCatalogue($locale); @@ -47,9 +44,6 @@ final class TranslatorBag implements TranslatorBagInterface return $this->catalogues[$locale]; } - /** - * {@inheritdoc} - */ public function getCatalogues(): array { return array_values($this->catalogues); @@ -70,7 +64,7 @@ final class TranslatorBag implements TranslatorBagInterface $operation->moveMessagesToIntlDomainsIfPossible(AbstractOperation::NEW_BATCH); $newCatalogue = new MessageCatalogue($locale); - foreach ($operation->getDomains() as $domain) { + foreach ($catalogue->getDomains() as $domain) { $newCatalogue->add($operation->getNewMessages($domain), $domain); } @@ -94,7 +88,10 @@ final class TranslatorBag implements TranslatorBagInterface $obsoleteCatalogue = new MessageCatalogue($locale); foreach ($operation->getDomains() as $domain) { - $obsoleteCatalogue->add($operation->getObsoleteMessages($domain), $domain); + $obsoleteCatalogue->add( + array_diff($operation->getMessages($domain), $operation->getNewMessages($domain)), + $domain + ); } $diff->addCatalogue($obsoleteCatalogue); diff --git a/data/web/inc/lib/vendor/symfony/translation/TranslatorBagInterface.php b/data/web/inc/lib/vendor/symfony/translation/TranslatorBagInterface.php index a787acf12..365d1f13b 100644 --- a/data/web/inc/lib/vendor/symfony/translation/TranslatorBagInterface.php +++ b/data/web/inc/lib/vendor/symfony/translation/TranslatorBagInterface.php @@ -25,7 +25,7 @@ interface TranslatorBagInterface * * @throws InvalidArgumentException If the locale contains invalid characters */ - public function getCatalogue(string $locale = null): MessageCatalogueInterface; + public function getCatalogue(?string $locale = null): MessageCatalogueInterface; /** * Returns all catalogues of the instance. diff --git a/data/web/inc/lib/vendor/symfony/translation/Util/ArrayConverter.php b/data/web/inc/lib/vendor/symfony/translation/Util/ArrayConverter.php index 60b8be6e0..64e15b485 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Util/ArrayConverter.php +++ b/data/web/inc/lib/vendor/symfony/translation/Util/ArrayConverter.php @@ -36,7 +36,7 @@ class ArrayConverter $tree = []; foreach ($messages as $id => $value) { - $referenceToElement = &self::getElementByPath($tree, explode('.', $id)); + $referenceToElement = &self::getElementByPath($tree, self::getKeyParts($id)); $referenceToElement = $value; @@ -46,7 +46,7 @@ class ArrayConverter return $tree; } - private static function &getElementByPath(array &$tree, array $parts) + private static function &getElementByPath(array &$tree, array $parts): mixed { $elem = &$tree; $parentOfElem = null; @@ -63,6 +63,7 @@ class ArrayConverter $elem = &$elem[implode('.', \array_slice($parts, $i))]; break; } + $parentOfElem = &$elem; $elem = &$elem[$part]; } @@ -82,7 +83,7 @@ class ArrayConverter return $elem; } - private static function cancelExpand(array &$tree, string $prefix, array $node) + private static function cancelExpand(array &$tree, string $prefix, array $node): void { $prefix .= '.'; @@ -94,4 +95,48 @@ class ArrayConverter } } } + + /** + * @return string[] + */ + private static function getKeyParts(string $key): array + { + $parts = explode('.', $key); + $partsCount = \count($parts); + + $result = []; + $buffer = ''; + + foreach ($parts as $index => $part) { + if (0 === $index && '' === $part) { + $buffer = '.'; + + continue; + } + + if ($index === $partsCount - 1 && '' === $part) { + $buffer .= '.'; + $result[] = $buffer; + + continue; + } + + if (isset($parts[$index + 1]) && '' === $parts[$index + 1]) { + $buffer .= $part; + + continue; + } + + if ($buffer) { + $result[] = $buffer.$part; + $buffer = ''; + + continue; + } + + $result[] = $part; + } + + return $result; + } } diff --git a/data/web/inc/lib/vendor/symfony/translation/Util/XliffUtils.php b/data/web/inc/lib/vendor/symfony/translation/Util/XliffUtils.php index 85ecc8504..335c34beb 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Util/XliffUtils.php +++ b/data/web/inc/lib/vendor/symfony/translation/Util/XliffUtils.php @@ -129,7 +129,7 @@ class XliffUtils private static function getSchema(string $xliffVersion): string { if ('1.2' === $xliffVersion) { - $schemaSource = file_get_contents(__DIR__.'/../Resources/schemas/xliff-core-1.2-strict.xsd'); + $schemaSource = file_get_contents(__DIR__.'/../Resources/schemas/xliff-core-1.2-transitional.xsd'); $xmlUri = 'http://www.w3.org/2001/xml.xsd'; } elseif ('2.0' === $xliffVersion) { $schemaSource = file_get_contents(__DIR__.'/../Resources/schemas/xliff-core-2.0.xsd'); diff --git a/data/web/inc/lib/vendor/symfony/translation/Writer/TranslationWriter.php b/data/web/inc/lib/vendor/symfony/translation/Writer/TranslationWriter.php index 5dd3a5c40..61e03cb0e 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Writer/TranslationWriter.php +++ b/data/web/inc/lib/vendor/symfony/translation/Writer/TranslationWriter.php @@ -30,6 +30,8 @@ class TranslationWriter implements TranslationWriterInterface /** * Adds a dumper to the writer. + * + * @return void */ public function addDumper(string $format, DumperInterface $dumper) { @@ -50,6 +52,8 @@ class TranslationWriter implements TranslationWriterInterface * @param string $format The format to use to dump the messages * @param array $options Options that are passed to the dumper * + * @return void + * * @throws InvalidArgumentException */ public function write(MessageCatalogue $catalogue, string $format, array $options = []) diff --git a/data/web/inc/lib/vendor/symfony/translation/Writer/TranslationWriterInterface.php b/data/web/inc/lib/vendor/symfony/translation/Writer/TranslationWriterInterface.php index 43213097e..5ebb9794a 100644 --- a/data/web/inc/lib/vendor/symfony/translation/Writer/TranslationWriterInterface.php +++ b/data/web/inc/lib/vendor/symfony/translation/Writer/TranslationWriterInterface.php @@ -27,6 +27,8 @@ interface TranslationWriterInterface * @param string $format The format to use to dump the messages * @param array $options Options that are passed to the dumper * + * @return void + * * @throws InvalidArgumentException */ public function write(MessageCatalogue $catalogue, string $format, array $options = []); diff --git a/data/web/inc/lib/vendor/symfony/translation/composer.json b/data/web/inc/lib/vendor/symfony/translation/composer.json index abe8b972c..af6f7a3df 100644 --- a/data/web/inc/lib/vendor/symfony/translation/composer.json +++ b/data/web/inc/lib/vendor/symfony/translation/composer.json @@ -16,27 +16,32 @@ } ], "require": { - "php": ">=8.0.2", + "php": ">=8.1", + "symfony/deprecation-contracts": "^2.5|^3", "symfony/polyfill-mbstring": "~1.0", - "symfony/translation-contracts": "^2.3|^3.0" + "symfony/translation-contracts": "^2.5|^3.0" }, "require-dev": { - "symfony/config": "^5.4|^6.0", - "symfony/console": "^5.4|^6.0", - "symfony/dependency-injection": "^5.4|^6.0", - "symfony/http-client-contracts": "^1.1|^2.0|^3.0", - "symfony/http-kernel": "^5.4|^6.0", - "symfony/intl": "^5.4|^6.0", + "nikic/php-parser": "^4.18|^5.0", + "symfony/config": "^5.4|^6.0|^7.0", + "symfony/console": "^5.4|^6.0|^7.0", + "symfony/dependency-injection": "^5.4|^6.0|^7.0", + "symfony/http-client-contracts": "^2.5|^3.0", + "symfony/http-kernel": "^5.4|^6.0|^7.0", + "symfony/intl": "^5.4|^6.0|^7.0", "symfony/polyfill-intl-icu": "^1.21", - "symfony/service-contracts": "^1.1.2|^2|^3", - "symfony/yaml": "^5.4|^6.0", - "symfony/finder": "^5.4|^6.0", + "symfony/routing": "^5.4|^6.0|^7.0", + "symfony/service-contracts": "^2.5|^3", + "symfony/yaml": "^5.4|^6.0|^7.0", + "symfony/finder": "^5.4|^6.0|^7.0", "psr/log": "^1|^2|^3" }, "conflict": { "symfony/config": "<5.4", "symfony/dependency-injection": "<5.4", + "symfony/http-client-contracts": "<2.5", "symfony/http-kernel": "<5.4", + "symfony/service-contracts": "<2.5", "symfony/twig-bundle": "<5.4", "symfony/yaml": "<5.4", "symfony/console": "<5.4" @@ -44,11 +49,6 @@ "provide": { "symfony/translation-implementation": "2.3|3.0" }, - "suggest": { - "symfony/config": "", - "symfony/yaml": "", - "psr/log-implementation": "To use logging capability in translator" - }, "autoload": { "files": [ "Resources/functions.php" ], "psr-4": { "Symfony\\Component\\Translation\\": "" }, diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/CHANGELOG.md b/data/web/inc/lib/vendor/symfony/var-dumper/CHANGELOG.md index f58ed3170..7481cff1a 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/CHANGELOG.md +++ b/data/web/inc/lib/vendor/symfony/var-dumper/CHANGELOG.md @@ -1,6 +1,25 @@ CHANGELOG ========= +6.4 +--- + + * Dump uninitialized properties + +6.3 +--- + + * Add caster for `WeakMap` + * Add support of named arguments to `dd()` and `dump()` to display the argument name + * Add support for `Relay\Relay` + * Add display of invisible characters + +6.2 +--- + + * Add support for `FFI\CData` and `FFI\CType` + * Deprecate calling `VarDumper::setHandler()` without arguments + 5.4 --- diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/AmqpCaster.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/AmqpCaster.php index dc3b62198..22026f46a 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/AmqpCaster.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/AmqpCaster.php @@ -46,6 +46,9 @@ class AmqpCaster \AMQP_EX_TYPE_HEADERS => 'AMQP_EX_TYPE_HEADERS', ]; + /** + * @return array + */ public static function castConnection(\AMQPConnection $c, array $a, Stub $stub, bool $isNested) { $prefix = Caster::PREFIX_VIRTUAL; @@ -79,6 +82,9 @@ class AmqpCaster return $a; } + /** + * @return array + */ public static function castChannel(\AMQPChannel $c, array $a, Stub $stub, bool $isNested) { $prefix = Caster::PREFIX_VIRTUAL; @@ -102,6 +108,9 @@ class AmqpCaster return $a; } + /** + * @return array + */ public static function castQueue(\AMQPQueue $c, array $a, Stub $stub, bool $isNested) { $prefix = Caster::PREFIX_VIRTUAL; @@ -125,6 +134,9 @@ class AmqpCaster return $a; } + /** + * @return array + */ public static function castExchange(\AMQPExchange $c, array $a, Stub $stub, bool $isNested) { $prefix = Caster::PREFIX_VIRTUAL; @@ -153,6 +165,9 @@ class AmqpCaster return $a; } + /** + * @return array + */ public static function castEnvelope(\AMQPEnvelope $c, array $a, Stub $stub, bool $isNested, int $filter = 0) { $prefix = Caster::PREFIX_VIRTUAL; diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ArgsStub.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ArgsStub.php index a89a71b1f..9dc24c1b1 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ArgsStub.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ArgsStub.php @@ -28,7 +28,7 @@ class ArgsStub extends EnumStub $values = []; foreach ($args as $k => $v) { - $values[$k] = !is_scalar($v) && !$v instanceof Stub ? new CutStub($v) : $v; + $values[$k] = !\is_scalar($v) && !$v instanceof Stub ? new CutStub($v) : $v; } if (null === $params) { parent::__construct($values, false); @@ -57,7 +57,7 @@ class ArgsStub extends EnumStub try { $r = null !== $class ? new \ReflectionMethod($class, $function) : new \ReflectionFunction($function); - } catch (\ReflectionException $e) { + } catch (\ReflectionException) { return [null, null]; } diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/Caster.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/Caster.php index 53f4461d0..d9577e7ae 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/Caster.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/Caster.php @@ -32,22 +32,27 @@ class Caster public const EXCLUDE_EMPTY = 128; public const EXCLUDE_NOT_IMPORTANT = 256; public const EXCLUDE_STRICT = 512; + public const EXCLUDE_UNINITIALIZED = 1024; public const PREFIX_VIRTUAL = "\0~\0"; public const PREFIX_DYNAMIC = "\0+\0"; public const PREFIX_PROTECTED = "\0*\0"; + // usage: sprintf(Caster::PATTERN_PRIVATE, $class, $property) + public const PATTERN_PRIVATE = "\0%s\0%s"; + + private static array $classProperties = []; /** * Casts objects to arrays and adds the dynamic property prefix. * * @param bool $hasDebugInfo Whether the __debugInfo method exists on $obj or not */ - public static function castObject(object $obj, string $class, bool $hasDebugInfo = false, string $debugClass = null): array + public static function castObject(object $obj, string $class, bool $hasDebugInfo = false, ?string $debugClass = null): array { if ($hasDebugInfo) { try { $debugInfo = $obj->__debugInfo(); - } catch (\Exception $e) { + } catch (\Throwable) { // ignore failing __debugInfo() $hasDebugInfo = false; } @@ -59,20 +64,17 @@ class Caster return $a; } + $classProperties = self::$classProperties[$class] ??= self::getClassProperties(new \ReflectionClass($class)); + $a = array_replace($classProperties, $a); + if ($a) { - static $publicProperties = []; - $debugClass = $debugClass ?? get_debug_type($obj); + $debugClass ??= get_debug_type($obj); $i = 0; $prefixedKeys = []; foreach ($a as $k => $v) { if ("\0" !== ($k[0] ?? '')) { - if (!isset($publicProperties[$class])) { - foreach ((new \ReflectionClass($class))->getProperties(\ReflectionProperty::IS_PUBLIC) as $prop) { - $publicProperties[$class][$prop->name] = true; - } - } - if (!isset($publicProperties[$class][$k])) { + if (!isset($classProperties[$k])) { $prefixedKeys[$i] = self::PREFIX_DYNAMIC.$k; } } elseif ($debugClass !== $class && 1 === strpos($k, $class)) { @@ -115,7 +117,7 @@ class Caster * @param array $a The array containing the properties to filter * @param int $filter A bit field of Caster::EXCLUDE_* constants specifying which properties to filter out * @param string[] $listedProperties List of properties to exclude when Caster::EXCLUDE_VERBOSE is set, and to preserve when Caster::EXCLUDE_NOT_IMPORTANT is set - * @param int &$count Set to the number of removed properties + * @param int|null &$count Set to the number of removed properties */ public static function filter(array $a, int $filter, array $listedProperties = [], ?int &$count = 0): array { @@ -129,6 +131,8 @@ class Caster $type |= self::EXCLUDE_EMPTY & $filter; } elseif (false === $v || '' === $v || '0' === $v || 0 === $v || 0.0 === $v || [] === $v) { $type |= self::EXCLUDE_EMPTY & $filter; + } elseif ($v instanceof UninitializedStub) { + $type |= self::EXCLUDE_UNINITIALIZED & $filter; } if ((self::EXCLUDE_NOT_IMPORTANT & $filter) && !\in_array($k, $listedProperties, true)) { $type |= self::EXCLUDE_NOT_IMPORTANT; @@ -167,4 +171,28 @@ class Caster return $a; } + + private static function getClassProperties(\ReflectionClass $class): array + { + $classProperties = []; + $className = $class->name; + + if ($parent = $class->getParentClass()) { + $classProperties += self::$classProperties[$parent->name] ??= self::getClassProperties($parent); + } + + foreach ($class->getProperties() as $p) { + if ($p->isStatic()) { + continue; + } + + $classProperties[match (true) { + $p->isPublic() => $p->name, + $p->isProtected() => self::PREFIX_PROTECTED.$p->name, + default => "\0".$className."\0".$p->name, + }] = new UninitializedStub($p); + } + + return $classProperties; + } } diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ClassStub.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ClassStub.php index 1ac6d0ac3..914728663 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ClassStub.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ClassStub.php @@ -24,7 +24,7 @@ class ClassStub extends ConstStub * @param string $identifier A PHP identifier, e.g. a class, method, interface, etc. name * @param callable $callable The callable targeted by the identifier when it is ambiguous or not a real PHP identifier */ - public function __construct(string $identifier, callable|array|string $callable = null) + public function __construct(string $identifier, callable|array|string|null $callable = null) { $this->value = $identifier; @@ -50,15 +50,13 @@ class ClassStub extends ConstStub if (\is_array($r)) { try { $r = new \ReflectionMethod($r[0], $r[1]); - } catch (\ReflectionException $e) { + } catch (\ReflectionException) { $r = new \ReflectionClass($r[0]); } } if (str_contains($identifier, "@anonymous\0")) { - $this->value = $identifier = preg_replace_callback('/[a-zA-Z_\x7f-\xff][\\\\a-zA-Z0-9_\x7f-\xff]*+@anonymous\x00.*?\.php(?:0x?|:[0-9]++\$)[0-9a-fA-F]++/', function ($m) { - return class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' : $m[0]; - }, $identifier); + $this->value = $identifier = preg_replace_callback('/[a-zA-Z_\x7f-\xff][\\\\a-zA-Z0-9_\x7f-\xff]*+@anonymous\x00.*?\.php(?:0x?|:[0-9]++\$)[0-9a-fA-F]++/', fn ($m) => class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' : $m[0], $identifier); } if (null !== $callable && $r instanceof \ReflectionFunctionAbstract) { @@ -71,7 +69,7 @@ class ClassStub extends ConstStub $this->value .= $s; } } - } catch (\ReflectionException $e) { + } catch (\ReflectionException) { return; } finally { if (0 < $i = strrpos($this->value, '\\')) { @@ -87,6 +85,9 @@ class ClassStub extends ConstStub } } + /** + * @return mixed + */ public static function wrapCallable(mixed $callable) { if (\is_object($callable) || !\is_callable($callable)) { diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ConstStub.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ConstStub.php index d7d1812bd..587c6c398 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ConstStub.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ConstStub.php @@ -20,7 +20,7 @@ use Symfony\Component\VarDumper\Cloner\Stub; */ class ConstStub extends Stub { - public function __construct(string $name, string|int|float $value = null) + public function __construct(string $name, string|int|float|null $value = null) { $this->class = $name; $this->value = 1 < \func_num_args() ? $value : $name; diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/CutStub.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/CutStub.php index b5a96a02c..772399ef6 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/CutStub.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/CutStub.php @@ -27,7 +27,7 @@ class CutStub extends Stub switch (\gettype($value)) { case 'object': $this->type = self::TYPE_OBJECT; - $this->class = \get_class($value); + $this->class = $value::class; if ($value instanceof \Closure) { ReflectionCaster::castClosure($value, [], $this, true, Caster::EXCLUDE_VERBOSE); diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/DOMCaster.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/DOMCaster.php index 4dd16e0ee..d2d3fc129 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/DOMCaster.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/DOMCaster.php @@ -63,6 +63,9 @@ class DOMCaster \XML_NAMESPACE_DECL_NODE => 'XML_NAMESPACE_DECL_NODE', ]; + /** + * @return array + */ public static function castException(\DOMException $e, array $a, Stub $stub, bool $isNested) { $k = Caster::PREFIX_PROTECTED.'code'; @@ -73,6 +76,9 @@ class DOMCaster return $a; } + /** + * @return array + */ public static function castLength($dom, array $a, Stub $stub, bool $isNested) { $a += [ @@ -82,6 +88,9 @@ class DOMCaster return $a; } + /** + * @return array + */ public static function castImplementation(\DOMImplementation $dom, array $a, Stub $stub, bool $isNested) { $a += [ @@ -92,6 +101,9 @@ class DOMCaster return $a; } + /** + * @return array + */ public static function castNode(\DOMNode $dom, array $a, Stub $stub, bool $isNested) { $a += [ @@ -116,6 +128,9 @@ class DOMCaster return $a; } + /** + * @return array + */ public static function castNameSpaceNode(\DOMNameSpaceNode $dom, array $a, Stub $stub, bool $isNested) { $a += [ @@ -132,6 +147,9 @@ class DOMCaster return $a; } + /** + * @return array + */ public static function castDocument(\DOMDocument $dom, array $a, Stub $stub, bool $isNested, int $filter = 0) { $a += [ @@ -166,6 +184,9 @@ class DOMCaster return $a; } + /** + * @return array + */ public static function castCharacterData(\DOMCharacterData $dom, array $a, Stub $stub, bool $isNested) { $a += [ @@ -176,6 +197,9 @@ class DOMCaster return $a; } + /** + * @return array + */ public static function castAttr(\DOMAttr $dom, array $a, Stub $stub, bool $isNested) { $a += [ @@ -189,6 +213,9 @@ class DOMCaster return $a; } + /** + * @return array + */ public static function castElement(\DOMElement $dom, array $a, Stub $stub, bool $isNested) { $a += [ @@ -199,6 +226,9 @@ class DOMCaster return $a; } + /** + * @return array + */ public static function castText(\DOMText $dom, array $a, Stub $stub, bool $isNested) { $a += [ @@ -208,43 +238,9 @@ class DOMCaster return $a; } - public static function castTypeinfo(\DOMTypeinfo $dom, array $a, Stub $stub, bool $isNested) - { - $a += [ - 'typeName' => $dom->typeName, - 'typeNamespace' => $dom->typeNamespace, - ]; - - return $a; - } - - public static function castDomError(\DOMDomError $dom, array $a, Stub $stub, bool $isNested) - { - $a += [ - 'severity' => $dom->severity, - 'message' => $dom->message, - 'type' => $dom->type, - 'relatedException' => $dom->relatedException, - 'related_data' => $dom->related_data, - 'location' => $dom->location, - ]; - - return $a; - } - - public static function castLocator(\DOMLocator $dom, array $a, Stub $stub, bool $isNested) - { - $a += [ - 'lineNumber' => $dom->lineNumber, - 'columnNumber' => $dom->columnNumber, - 'offset' => $dom->offset, - 'relatedNode' => $dom->relatedNode, - 'uri' => $dom->uri ? new LinkStub($dom->uri, $dom->lineNumber) : $dom->uri, - ]; - - return $a; - } - + /** + * @return array + */ public static function castDocumentType(\DOMDocumentType $dom, array $a, Stub $stub, bool $isNested) { $a += [ @@ -259,6 +255,9 @@ class DOMCaster return $a; } + /** + * @return array + */ public static function castNotation(\DOMNotation $dom, array $a, Stub $stub, bool $isNested) { $a += [ @@ -269,6 +268,9 @@ class DOMCaster return $a; } + /** + * @return array + */ public static function castEntity(\DOMEntity $dom, array $a, Stub $stub, bool $isNested) { $a += [ @@ -283,6 +285,9 @@ class DOMCaster return $a; } + /** + * @return array + */ public static function castProcessingInstruction(\DOMProcessingInstruction $dom, array $a, Stub $stub, bool $isNested) { $a += [ @@ -293,6 +298,9 @@ class DOMCaster return $a; } + /** + * @return array + */ public static function castXPath(\DOMXPath $dom, array $a, Stub $stub, bool $isNested) { $a += [ diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/DateCaster.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/DateCaster.php index 99f53849b..a0cbddb76 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/DateCaster.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/DateCaster.php @@ -24,11 +24,14 @@ class DateCaster { private const PERIOD_LIMIT = 3; + /** + * @return array + */ public static function castDateTime(\DateTimeInterface $d, array $a, Stub $stub, bool $isNested, int $filter) { $prefix = Caster::PREFIX_VIRTUAL; - $location = $d->getTimezone()->getLocation(); - $fromNow = (new \DateTime())->diff($d); + $location = $d->getTimezone() ? $d->getTimezone()->getLocation() : null; + $fromNow = (new \DateTimeImmutable())->diff($d); $title = $d->format('l, F j, Y') ."\n".self::formatInterval($fromNow).' from now' @@ -47,6 +50,9 @@ class DateCaster return $a; } + /** + * @return array + */ public static function castInterval(\DateInterval $interval, array $a, Stub $stub, bool $isNested, int $filter) { $now = new \DateTimeImmutable('@0', new \DateTimeZone('UTC')); @@ -76,10 +82,13 @@ class DateCaster return $i->format(rtrim($format)); } + /** + * @return array + */ public static function castTimeZone(\DateTimeZone $timeZone, array $a, Stub $stub, bool $isNested, int $filter) { $location = $timeZone->getLocation(); - $formatted = (new \DateTime('now', $timeZone))->format($location ? 'e (P)' : 'P'); + $formatted = (new \DateTimeImmutable('now', $timeZone))->format($location ? 'e (P)' : 'P'); $title = $location && \extension_loaded('intl') ? \Locale::getDisplayRegion('-'.$location['country_code']) : ''; $z = [Caster::PREFIX_VIRTUAL.'timezone' => new ConstStub($formatted, $title)]; @@ -87,6 +96,9 @@ class DateCaster return $filter & Caster::EXCLUDE_VERBOSE ? $z : $z + $a; } + /** + * @return array + */ public static function castPeriod(\DatePeriod $p, array $a, Stub $stub, bool $isNested, int $filter) { $dates = []; @@ -103,11 +115,11 @@ class DateCaster } $period = sprintf( - 'every %s, from %s (%s) %s', + 'every %s, from %s%s %s', self::formatInterval($p->getDateInterval()), + $p->include_start_date ? '[' : ']', self::formatDateTime($p->getStartDate()), - $p->include_start_date ? 'included' : 'excluded', - ($end = $p->getEndDate()) ? 'to '.self::formatDateTime($end) : 'recurring '.$p->recurrences.' time/s' + ($end = $p->getEndDate()) ? 'to '.self::formatDateTime($end).(\PHP_VERSION_ID >= 80200 && $p->include_end_date ? ']' : '[') : 'recurring '.$p->recurrences.' time/s' ); $p = [Caster::PREFIX_VIRTUAL.'period' => new ConstStub($period, implode("\n", $dates))]; diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/DoctrineCaster.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/DoctrineCaster.php index 129b2cb47..3120c3d91 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/DoctrineCaster.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/DoctrineCaster.php @@ -25,6 +25,9 @@ use Symfony\Component\VarDumper\Cloner\Stub; */ class DoctrineCaster { + /** + * @return array + */ public static function castCommonProxy(CommonProxy $proxy, array $a, Stub $stub, bool $isNested) { foreach (['__cloner__', '__initializer__'] as $k) { @@ -37,6 +40,9 @@ class DoctrineCaster return $a; } + /** + * @return array + */ public static function castOrmProxy(OrmProxy $proxy, array $a, Stub $stub, bool $isNested) { foreach (['_entityPersister', '_identifier'] as $k) { @@ -49,6 +55,9 @@ class DoctrineCaster return $a; } + /** + * @return array + */ public static function castPersistentCollection(PersistentCollection $coll, array $a, Stub $stub, bool $isNested) { foreach (['snapshot', 'association', 'typeClass'] as $k) { diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/DsPairStub.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/DsPairStub.php index 22112af9c..afa2727b1 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/DsPairStub.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/DsPairStub.php @@ -18,7 +18,7 @@ use Symfony\Component\VarDumper\Cloner\Stub; */ class DsPairStub extends Stub { - public function __construct(string|int $key, mixed $value) + public function __construct(mixed $key, mixed $value) { $this->value = [ Caster::PREFIX_VIRTUAL.'key' => $key, diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ExceptionCaster.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ExceptionCaster.php index 8e517e079..02efb1b02 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ExceptionCaster.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ExceptionCaster.php @@ -11,6 +11,7 @@ namespace Symfony\Component\VarDumper\Caster; +use Symfony\Component\ErrorHandler\Exception\FlattenException; use Symfony\Component\ErrorHandler\Exception\SilencedErrorContext; use Symfony\Component\VarDumper\Cloner\Stub; use Symfony\Component\VarDumper\Exception\ThrowingCasterException; @@ -46,16 +47,25 @@ class ExceptionCaster private static array $framesCache = []; + /** + * @return array + */ public static function castError(\Error $e, array $a, Stub $stub, bool $isNested, int $filter = 0) { return self::filterExceptionArray($stub->class, $a, "\0Error\0", $filter); } + /** + * @return array + */ public static function castException(\Exception $e, array $a, Stub $stub, bool $isNested, int $filter = 0) { return self::filterExceptionArray($stub->class, $a, "\0Exception\0", $filter); } + /** + * @return array + */ public static function castErrorException(\ErrorException $e, array $a, Stub $stub, bool $isNested) { if (isset($a[$s = Caster::PREFIX_PROTECTED.'severity'], self::$errorTypes[$a[$s]])) { @@ -65,6 +75,9 @@ class ExceptionCaster return $a; } + /** + * @return array + */ public static function castThrowingCasterException(ThrowingCasterException $e, array $a, Stub $stub, bool $isNested) { $trace = Caster::PREFIX_VIRTUAL.'trace'; @@ -83,6 +96,9 @@ class ExceptionCaster return $a; } + /** + * @return array + */ public static function castSilencedErrorContext(SilencedErrorContext $e, array $a, Stub $stub, bool $isNested) { $sPrefix = "\0".SilencedErrorContext::class."\0"; @@ -110,6 +126,9 @@ class ExceptionCaster return $a; } + /** + * @return array + */ public static function castTraceStub(TraceStub $trace, array $a, Stub $stub, bool $isNested) { if (!$isNested) { @@ -184,6 +203,9 @@ class ExceptionCaster return $a; } + /** + * @return array + */ public static function castFrameStub(FrameStub $frame, array $a, Stub $stub, bool $isNested) { if (!$isNested) { @@ -267,6 +289,19 @@ class ExceptionCaster return $a; } + /** + * @return array + */ + public static function castFlattenException(FlattenException $e, array $a, Stub $stub, bool $isNested) + { + if ($isNested) { + $k = sprintf(Caster::PATTERN_PRIVATE, FlattenException::class, 'traceAsString'); + $a[$k] = new CutStub($a[$k]); + } + + return $a; + } + private static function filterExceptionArray(string $xClass, array $a, string $xPrefix, int $filter): array { if (isset($a[$xPrefix.'trace'])) { @@ -285,12 +320,10 @@ class ExceptionCaster if (empty($a[$xPrefix.'previous'])) { unset($a[$xPrefix.'previous']); } - unset($a[$xPrefix.'string'], $a[Caster::PREFIX_DYNAMIC.'xdebug_message'], $a[Caster::PREFIX_DYNAMIC.'__destructorException']); + unset($a[$xPrefix.'string'], $a[Caster::PREFIX_DYNAMIC.'xdebug_message']); if (isset($a[Caster::PREFIX_PROTECTED.'message']) && str_contains($a[Caster::PREFIX_PROTECTED.'message'], "@anonymous\0")) { - $a[Caster::PREFIX_PROTECTED.'message'] = preg_replace_callback('/[a-zA-Z_\x7f-\xff][\\\\a-zA-Z0-9_\x7f-\xff]*+@anonymous\x00.*?\.php(?:0x?|:[0-9]++\$)[0-9a-fA-F]++/', function ($m) { - return class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' : $m[0]; - }, $a[Caster::PREFIX_PROTECTED.'message']); + $a[Caster::PREFIX_PROTECTED.'message'] = preg_replace_callback('/[a-zA-Z_\x7f-\xff][\\\\a-zA-Z0-9_\x7f-\xff]*+@anonymous\x00.*?\.php(?:0x?|:[0-9]++\$)[0-9a-fA-F]++/', fn ($m) => class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' : $m[0], $a[Caster::PREFIX_PROTECTED.'message']); } if (isset($a[Caster::PREFIX_PROTECTED.'file'], $a[Caster::PREFIX_PROTECTED.'line'])) { @@ -337,7 +370,7 @@ class ExceptionCaster $stub->attr['file'] = $f; $stub->attr['line'] = $caller->getStartLine(); } - } catch (\ReflectionException $e) { + } catch (\ReflectionException) { // ignore fake class/function } @@ -352,9 +385,7 @@ class ExceptionCaster $pad = null; for ($i = $srcContext << 1; $i >= 0; --$i) { if (isset($src[$i][$ltrim]) && "\r" !== ($c = $src[$i][$ltrim]) && "\n" !== $c) { - if (null === $pad) { - $pad = $c; - } + $pad ??= $c; if ((' ' !== $c && "\t" !== $c) || $pad !== $c) { break; } diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/FFICaster.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/FFICaster.php new file mode 100644 index 000000000..f1984eef3 --- /dev/null +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/FFICaster.php @@ -0,0 +1,161 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Caster; + +use FFI\CData; +use FFI\CType; +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * Casts FFI extension classes to array representation. + * + * @author Nesmeyanov Kirill + */ +final class FFICaster +{ + /** + * In case of "char*" contains a string, the length of which depends on + * some other parameter, then during the generation of the string it is + * possible to go beyond the allowable memory area. + * + * This restriction serves to ensure that processing does not take + * up the entire allowable PHP memory limit. + */ + private const MAX_STRING_LENGTH = 255; + + public static function castCTypeOrCData(CData|CType $data, array $args, Stub $stub): array + { + if ($data instanceof CType) { + $type = $data; + $data = null; + } else { + $type = \FFI::typeof($data); + } + + $stub->class = sprintf('%s<%s> size %d align %d', ($data ?? $type)::class, $type->getName(), $type->getSize(), $type->getAlignment()); + + return match ($type->getKind()) { + CType::TYPE_FLOAT, + CType::TYPE_DOUBLE, + \defined('\FFI\CType::TYPE_LONGDOUBLE') ? CType::TYPE_LONGDOUBLE : -1, + CType::TYPE_UINT8, + CType::TYPE_SINT8, + CType::TYPE_UINT16, + CType::TYPE_SINT16, + CType::TYPE_UINT32, + CType::TYPE_SINT32, + CType::TYPE_UINT64, + CType::TYPE_SINT64, + CType::TYPE_BOOL, + CType::TYPE_CHAR, + CType::TYPE_ENUM => null !== $data ? [Caster::PREFIX_VIRTUAL.'cdata' => $data->cdata] : [], + CType::TYPE_POINTER => self::castFFIPointer($stub, $type, $data), + CType::TYPE_STRUCT => self::castFFIStructLike($type, $data), + CType::TYPE_FUNC => self::castFFIFunction($stub, $type), + default => $args, + }; + } + + private static function castFFIFunction(Stub $stub, CType $type): array + { + $arguments = []; + + for ($i = 0, $count = $type->getFuncParameterCount(); $i < $count; ++$i) { + $param = $type->getFuncParameterType($i); + + $arguments[] = $param->getName(); + } + + $abi = match ($type->getFuncABI()) { + CType::ABI_DEFAULT, + CType::ABI_CDECL => '[cdecl]', + CType::ABI_FASTCALL => '[fastcall]', + CType::ABI_THISCALL => '[thiscall]', + CType::ABI_STDCALL => '[stdcall]', + CType::ABI_PASCAL => '[pascal]', + CType::ABI_REGISTER => '[register]', + CType::ABI_MS => '[ms]', + CType::ABI_SYSV => '[sysv]', + CType::ABI_VECTORCALL => '[vectorcall]', + default => '[unknown abi]' + }; + + $returnType = $type->getFuncReturnType(); + + $stub->class = $abi.' callable('.implode(', ', $arguments).'): ' + .$returnType->getName(); + + return [Caster::PREFIX_VIRTUAL.'returnType' => $returnType]; + } + + private static function castFFIPointer(Stub $stub, CType $type, ?CData $data = null): array + { + $ptr = $type->getPointerType(); + + if (null === $data) { + return [Caster::PREFIX_VIRTUAL.'0' => $ptr]; + } + + return match ($ptr->getKind()) { + CType::TYPE_CHAR => [Caster::PREFIX_VIRTUAL.'cdata' => self::castFFIStringValue($data)], + CType::TYPE_FUNC => self::castFFIFunction($stub, $ptr), + default => [Caster::PREFIX_VIRTUAL.'cdata' => $data[0]], + }; + } + + private static function castFFIStringValue(CData $data): string|CutStub + { + $result = []; + + for ($i = 0; $i < self::MAX_STRING_LENGTH; ++$i) { + $result[$i] = $data[$i]; + + if ("\0" === $result[$i]) { + return implode('', $result); + } + } + + $string = implode('', $result); + $stub = new CutStub($string); + $stub->cut = -1; + $stub->value = $string; + + return $stub; + } + + private static function castFFIStructLike(CType $type, ?CData $data = null): array + { + $isUnion = ($type->getAttributes() & CType::ATTR_UNION) === CType::ATTR_UNION; + + $result = []; + + foreach ($type->getStructFieldNames() as $name) { + $field = $type->getStructFieldType($name); + + // Retrieving the value of a field from a union containing + // a pointer is not a safe operation, because may contain + // incorrect data. + $isUnsafe = $isUnion && CType::TYPE_POINTER === $field->getKind(); + + if ($isUnsafe) { + $result[Caster::PREFIX_VIRTUAL.$name.'?'] = $field; + } elseif (null === $data) { + $result[Caster::PREFIX_VIRTUAL.$name] = $field; + } else { + $fieldName = $data->{$name} instanceof CData ? '' : $field->getName().' '; + $result[Caster::PREFIX_VIRTUAL.$fieldName.$name] = $data->{$name}; + } + } + + return $result; + } +} diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/FiberCaster.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/FiberCaster.php index c74a9e59c..b797dbd63 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/FiberCaster.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/FiberCaster.php @@ -20,6 +20,9 @@ use Symfony\Component\VarDumper\Cloner\Stub; */ final class FiberCaster { + /** + * @return array + */ public static function castFiber(\Fiber $fiber, array $a, Stub $stub, bool $isNested, int $filter = 0) { $prefix = Caster::PREFIX_VIRTUAL; diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/IntlCaster.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/IntlCaster.php index 23b9d5da3..a4590f4b5 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/IntlCaster.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/IntlCaster.php @@ -21,6 +21,9 @@ use Symfony\Component\VarDumper\Cloner\Stub; */ class IntlCaster { + /** + * @return array + */ public static function castMessageFormatter(\MessageFormatter $c, array $a, Stub $stub, bool $isNested) { $a += [ @@ -31,6 +34,9 @@ class IntlCaster return self::castError($c, $a); } + /** + * @return array + */ public static function castNumberFormatter(\NumberFormatter $c, array $a, Stub $stub, bool $isNested, int $filter = 0) { $a += [ @@ -102,12 +108,15 @@ class IntlCaster 'SIGNIFICANT_DIGIT_SYMBOL' => $c->getSymbol(\NumberFormatter::SIGNIFICANT_DIGIT_SYMBOL), 'MONETARY_GROUPING_SEPARATOR_SYMBOL' => $c->getSymbol(\NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL), ] - ), + ), ]; return self::castError($c, $a); } + /** + * @return array + */ public static function castIntlTimeZone(\IntlTimeZone $c, array $a, Stub $stub, bool $isNested) { $a += [ @@ -125,6 +134,9 @@ class IntlCaster return self::castError($c, $a); } + /** + * @return array + */ public static function castIntlCalendar(\IntlCalendar $c, array $a, Stub $stub, bool $isNested, int $filter = 0) { $a += [ @@ -142,6 +154,9 @@ class IntlCaster return self::castError($c, $a); } + /** + * @return array + */ public static function castIntlDateFormatter(\IntlDateFormatter $c, array $a, Stub $stub, bool $isNested, int $filter = 0) { $a += [ diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/LinkStub.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/LinkStub.php index 36e0d3cb9..4930436df 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/LinkStub.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/LinkStub.php @@ -23,14 +23,11 @@ class LinkStub extends ConstStub private static array $vendorRoots; private static array $composerRoots = []; - public function __construct(string $label, int $line = 0, string $href = null) + public function __construct(string $label, int $line = 0, ?string $href = null) { $this->value = $label; - if (null === $href) { - $href = $label; - } - if (!\is_string($href)) { + if (!\is_string($href ??= $label)) { return; } if (str_starts_with($href, 'file://')) { @@ -63,7 +60,7 @@ class LinkStub extends ConstStub } } - private function getComposerRoot(string $file, bool &$inVendor) + private function getComposerRoot(string $file, bool &$inVendor): string|false { if (!isset(self::$vendorRoots)) { self::$vendorRoots = []; diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/MemcachedCaster.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/MemcachedCaster.php index d6baa2514..2f161e8cb 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/MemcachedCaster.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/MemcachedCaster.php @@ -23,6 +23,9 @@ class MemcachedCaster private static array $optionConstants; private static array $defaultOptions; + /** + * @return array + */ public static function castMemcached(\Memcached $c, array $a, Stub $stub, bool $isNested) { $a += [ @@ -37,8 +40,8 @@ class MemcachedCaster private static function getNonDefaultOptions(\Memcached $c): array { - self::$defaultOptions = self::$defaultOptions ?? self::discoverDefaultOptions(); - self::$optionConstants = self::$optionConstants ?? self::getOptionConstants(); + self::$defaultOptions ??= self::discoverDefaultOptions(); + self::$optionConstants ??= self::getOptionConstants(); $nonDefaultOptions = []; foreach (self::$optionConstants as $constantKey => $value) { @@ -56,7 +59,7 @@ class MemcachedCaster $defaultMemcached->addServer('127.0.0.1', 11211); $defaultOptions = []; - self::$optionConstants = self::$optionConstants ?? self::getOptionConstants(); + self::$optionConstants ??= self::getOptionConstants(); foreach (self::$optionConstants as $constantKey => $value) { $defaultOptions[$constantKey] = $defaultMemcached->getOption($value); diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/PdoCaster.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/PdoCaster.php index 140473b53..d68eae216 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/PdoCaster.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/PdoCaster.php @@ -59,6 +59,9 @@ class PdoCaster ], ]; + /** + * @return array + */ public static function castPdo(\PDO $c, array $a, Stub $stub, bool $isNested) { $attr = []; @@ -76,7 +79,7 @@ class PdoCaster if ($v && isset($v[$attr[$k]])) { $attr[$k] = new ConstStub($v[$attr[$k]], $attr[$k]); } - } catch (\Exception $e) { + } catch (\Exception) { } } if (isset($attr[$k = 'STATEMENT_CLASS'][1])) { @@ -108,6 +111,9 @@ class PdoCaster return $a; } + /** + * @return array + */ public static function castPdoStatement(\PDOStatement $c, array $a, Stub $stub, bool $isNested) { $prefix = Caster::PREFIX_VIRTUAL; diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/PgSqlCaster.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/PgSqlCaster.php index d8e5b5253..0d8b3d919 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/PgSqlCaster.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/PgSqlCaster.php @@ -69,6 +69,9 @@ class PgSqlCaster 'function' => \PGSQL_DIAG_SOURCE_FUNCTION, ]; + /** + * @return array + */ public static function castLargeObject($lo, array $a, Stub $stub, bool $isNested) { $a['seek position'] = pg_lo_tell($lo); @@ -76,6 +79,9 @@ class PgSqlCaster return $a; } + /** + * @return array + */ public static function castLink($link, array $a, Stub $stub, bool $isNested) { $a['status'] = pg_connection_status($link); @@ -108,6 +114,9 @@ class PgSqlCaster return $a; } + /** + * @return array + */ public static function castResult($result, array $a, Stub $stub, bool $isNested) { $a['num rows'] = pg_num_rows($result); diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ProxyManagerCaster.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ProxyManagerCaster.php index e7120191f..eb6c88db6 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ProxyManagerCaster.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ProxyManagerCaster.php @@ -21,6 +21,9 @@ use Symfony\Component\VarDumper\Cloner\Stub; */ class ProxyManagerCaster { + /** + * @return array + */ public static function castProxy(ProxyInterface $c, array $a, Stub $stub, bool $isNested) { if ($parent = get_parent_class($c)) { diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/RdKafkaCaster.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/RdKafkaCaster.php index 805336395..fcaa1b768 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/RdKafkaCaster.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/RdKafkaCaster.php @@ -31,13 +31,16 @@ use Symfony\Component\VarDumper\Cloner\Stub; */ class RdKafkaCaster { + /** + * @return array + */ public static function castKafkaConsumer(KafkaConsumer $c, array $a, Stub $stub, bool $isNested) { $prefix = Caster::PREFIX_VIRTUAL; try { $assignment = $c->getAssignment(); - } catch (RdKafkaException $e) { + } catch (RdKafkaException) { $assignment = []; } @@ -51,6 +54,9 @@ class RdKafkaCaster return $a; } + /** + * @return array + */ public static function castTopic(Topic $c, array $a, Stub $stub, bool $isNested) { $prefix = Caster::PREFIX_VIRTUAL; @@ -62,6 +68,9 @@ class RdKafkaCaster return $a; } + /** + * @return array + */ public static function castTopicPartition(TopicPartition $c, array $a) { $prefix = Caster::PREFIX_VIRTUAL; @@ -75,6 +84,9 @@ class RdKafkaCaster return $a; } + /** + * @return array + */ public static function castMessage(Message $c, array $a, Stub $stub, bool $isNested) { $prefix = Caster::PREFIX_VIRTUAL; @@ -86,6 +98,9 @@ class RdKafkaCaster return $a; } + /** + * @return array + */ public static function castConf(Conf $c, array $a, Stub $stub, bool $isNested) { $prefix = Caster::PREFIX_VIRTUAL; @@ -97,6 +112,9 @@ class RdKafkaCaster return $a; } + /** + * @return array + */ public static function castTopicConf(TopicConf $c, array $a, Stub $stub, bool $isNested) { $prefix = Caster::PREFIX_VIRTUAL; @@ -108,6 +126,9 @@ class RdKafkaCaster return $a; } + /** + * @return array + */ public static function castRdKafka(\RdKafka $c, array $a, Stub $stub, bool $isNested) { $prefix = Caster::PREFIX_VIRTUAL; @@ -121,6 +142,9 @@ class RdKafkaCaster return $a; } + /** + * @return array + */ public static function castCollectionMetadata(CollectionMetadata $c, array $a, Stub $stub, bool $isNested) { $a += iterator_to_array($c); @@ -128,6 +152,9 @@ class RdKafkaCaster return $a; } + /** + * @return array + */ public static function castTopicMetadata(TopicMetadata $c, array $a, Stub $stub, bool $isNested) { $prefix = Caster::PREFIX_VIRTUAL; @@ -140,6 +167,9 @@ class RdKafkaCaster return $a; } + /** + * @return array + */ public static function castPartitionMetadata(PartitionMetadata $c, array $a, Stub $stub, bool $isNested) { $prefix = Caster::PREFIX_VIRTUAL; @@ -153,6 +183,9 @@ class RdKafkaCaster return $a; } + /** + * @return array + */ public static function castBrokerMetadata(BrokerMetadata $c, array $a, Stub $stub, bool $isNested) { $prefix = Caster::PREFIX_VIRTUAL; @@ -166,13 +199,16 @@ class RdKafkaCaster return $a; } + /** + * @return array + */ private static function extractMetadata(KafkaConsumer|\RdKafka $c) { $prefix = Caster::PREFIX_VIRTUAL; try { $m = $c->getMetadata(true, null, 500); - } catch (RdKafkaException $e) { + } catch (RdKafkaException) { return []; } diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/RedisCaster.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/RedisCaster.php index eac25a12a..6ff046754 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/RedisCaster.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/RedisCaster.php @@ -11,6 +11,7 @@ namespace Symfony\Component\VarDumper\Caster; +use Relay\Relay; use Symfony\Component\VarDumper\Cloner\Stub; /** @@ -23,15 +24,15 @@ use Symfony\Component\VarDumper\Cloner\Stub; class RedisCaster { private const SERIALIZERS = [ - \Redis::SERIALIZER_NONE => 'NONE', - \Redis::SERIALIZER_PHP => 'PHP', + 0 => 'NONE', // Redis::SERIALIZER_NONE + 1 => 'PHP', // Redis::SERIALIZER_PHP 2 => 'IGBINARY', // Optional Redis::SERIALIZER_IGBINARY ]; private const MODES = [ - \Redis::ATOMIC => 'ATOMIC', - \Redis::MULTI => 'MULTI', - \Redis::PIPELINE => 'PIPELINE', + 0 => 'ATOMIC', // Redis::ATOMIC + 1 => 'MULTI', // Redis::MULTI + 2 => 'PIPELINE', // Redis::PIPELINE ]; private const COMPRESSION_MODES = [ @@ -46,7 +47,10 @@ class RedisCaster \RedisCluster::FAILOVER_DISTRIBUTE_SLAVES => 'DISTRIBUTE_SLAVES', ]; - public static function castRedis(\Redis $c, array $a, Stub $stub, bool $isNested) + /** + * @return array + */ + public static function castRedis(\Redis|Relay $c, array $a, Stub $stub, bool $isNested) { $prefix = Caster::PREFIX_VIRTUAL; @@ -72,6 +76,9 @@ class RedisCaster ]; } + /** + * @return array + */ public static function castRedisArray(\RedisArray $c, array $a, Stub $stub, bool $isNested) { $prefix = Caster::PREFIX_VIRTUAL; @@ -84,6 +91,9 @@ class RedisCaster ]; } + /** + * @return array + */ public static function castRedisCluster(\RedisCluster $c, array $a, Stub $stub, bool $isNested) { $prefix = Caster::PREFIX_VIRTUAL; @@ -102,9 +112,9 @@ class RedisCaster return $a; } - private static function getRedisOptions(\Redis|\RedisArray|\RedisCluster $redis, array $options = []): EnumStub + private static function getRedisOptions(\Redis|Relay|\RedisArray|\RedisCluster $redis, array $options = []): EnumStub { - $serializer = $redis->getOption(\Redis::OPT_SERIALIZER); + $serializer = $redis->getOption(\defined('Redis::OPT_SERIALIZER') ? \Redis::OPT_SERIALIZER : 1); if (\is_array($serializer)) { foreach ($serializer as &$v) { if (isset(self::SERIALIZERS[$v])) { @@ -136,11 +146,11 @@ class RedisCaster } $options += [ - 'TCP_KEEPALIVE' => \defined('Redis::OPT_TCP_KEEPALIVE') ? $redis->getOption(\Redis::OPT_TCP_KEEPALIVE) : 0, - 'READ_TIMEOUT' => $redis->getOption(\Redis::OPT_READ_TIMEOUT), + 'TCP_KEEPALIVE' => \defined('Redis::OPT_TCP_KEEPALIVE') ? $redis->getOption(\Redis::OPT_TCP_KEEPALIVE) : Relay::OPT_TCP_KEEPALIVE, + 'READ_TIMEOUT' => $redis->getOption(\defined('Redis::OPT_READ_TIMEOUT') ? \Redis::OPT_READ_TIMEOUT : Relay::OPT_READ_TIMEOUT), 'COMPRESSION' => $compression, 'SERIALIZER' => $serializer, - 'PREFIX' => $redis->getOption(\Redis::OPT_PREFIX), + 'PREFIX' => $redis->getOption(\defined('Redis::OPT_PREFIX') ? \Redis::OPT_PREFIX : Relay::OPT_PREFIX), 'SCAN' => $retry, ]; diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ReflectionCaster.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ReflectionCaster.php index 86d439f2b..4adb9bc9f 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ReflectionCaster.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ReflectionCaster.php @@ -35,6 +35,9 @@ class ReflectionCaster 'isVariadic' => 'isVariadic', ]; + /** + * @return array + */ public static function castClosure(\Closure $c, array $a, Stub $stub, bool $isNested, int $filter = 0) { $prefix = Caster::PREFIX_VIRTUAL; @@ -71,6 +74,9 @@ class ReflectionCaster return $a; } + /** + * @return array + */ public static function unsetClosureFileInfo(\Closure $c, array $a) { unset($a[Caster::PREFIX_VIRTUAL.'file'], $a[Caster::PREFIX_VIRTUAL.'line']); @@ -78,12 +84,12 @@ class ReflectionCaster return $a; } - public static function castGenerator(\Generator $c, array $a, Stub $stub, bool $isNested) + public static function castGenerator(\Generator $c, array $a, Stub $stub, bool $isNested): array { // Cannot create ReflectionGenerator based on a terminated Generator try { $reflectionGenerator = new \ReflectionGenerator($c); - } catch (\Exception $e) { + } catch (\Exception) { $a[Caster::PREFIX_VIRTUAL.'closed'] = true; return $a; @@ -92,6 +98,9 @@ class ReflectionCaster return self::castReflectionGenerator($reflectionGenerator, $a, $stub, $isNested); } + /** + * @return array + */ public static function castType(\ReflectionType $c, array $a, Stub $stub, bool $isNested) { $prefix = Caster::PREFIX_VIRTUAL; @@ -114,6 +123,9 @@ class ReflectionCaster return $a; } + /** + * @return array + */ public static function castAttribute(\ReflectionAttribute $c, array $a, Stub $stub, bool $isNested) { self::addMap($a, $c, [ @@ -124,6 +136,9 @@ class ReflectionCaster return $a; } + /** + * @return array + */ public static function castReflectionGenerator(\ReflectionGenerator $c, array $a, Stub $stub, bool $isNested) { $prefix = Caster::PREFIX_VIRTUAL; @@ -144,7 +159,7 @@ class ReflectionCaster array_unshift($trace, [ 'function' => 'yield', 'file' => $function->getExecutingFile(), - 'line' => $function->getExecutingLine() - (int) (\PHP_VERSION_ID < 80100), + 'line' => $function->getExecutingLine(), ]); $trace[] = $frame; $a[$prefix.'trace'] = new TraceStub($trace, false, 0, -1, -1); @@ -159,6 +174,9 @@ class ReflectionCaster return $a; } + /** + * @return array + */ public static function castClass(\ReflectionClass $c, array $a, Stub $stub, bool $isNested, int $filter = 0) { $prefix = Caster::PREFIX_VIRTUAL; @@ -190,6 +208,9 @@ class ReflectionCaster return $a; } + /** + * @return array + */ public static function castFunctionAbstract(\ReflectionFunctionAbstract $c, array $a, Stub $stub, bool $isNested, int $filter = 0) { $prefix = Caster::PREFIX_VIRTUAL; @@ -197,7 +218,7 @@ class ReflectionCaster self::addMap($a, $c, [ 'returnsReference' => 'returnsReference', 'returnType' => 'getReturnType', - 'class' => 'getClosureScopeClass', + 'class' => \PHP_VERSION_ID >= 80111 ? 'getClosureCalledClass' : 'getClosureScopeClass', 'this' => 'getClosureThis', ]); @@ -248,6 +269,9 @@ class ReflectionCaster return $a; } + /** + * @return array + */ public static function castClassConstant(\ReflectionClassConstant $c, array $a, Stub $stub, bool $isNested) { $a[Caster::PREFIX_VIRTUAL.'modifiers'] = implode(' ', \Reflection::getModifierNames($c->getModifiers())); @@ -258,6 +282,9 @@ class ReflectionCaster return $a; } + /** + * @return array + */ public static function castMethod(\ReflectionMethod $c, array $a, Stub $stub, bool $isNested) { $a[Caster::PREFIX_VIRTUAL.'modifiers'] = implode(' ', \Reflection::getModifierNames($c->getModifiers())); @@ -265,6 +292,9 @@ class ReflectionCaster return $a; } + /** + * @return array + */ public static function castParameter(\ReflectionParameter $c, array $a, Stub $stub, bool $isNested) { $prefix = Caster::PREFIX_VIRTUAL; @@ -292,19 +322,22 @@ class ReflectionCaster if ($c->isOptional()) { try { $a[$prefix.'default'] = $v = $c->getDefaultValue(); - if ($c->isDefaultValueConstant()) { + if ($c->isDefaultValueConstant() && !\is_object($v)) { $a[$prefix.'default'] = new ConstStub($c->getDefaultValueConstantName(), $v); } if (null === $v) { unset($a[$prefix.'allowsNull']); } - } catch (\ReflectionException $e) { + } catch (\ReflectionException) { } } return $a; } + /** + * @return array + */ public static function castProperty(\ReflectionProperty $c, array $a, Stub $stub, bool $isNested) { $a[Caster::PREFIX_VIRTUAL.'modifiers'] = implode(' ', \Reflection::getModifierNames($c->getModifiers())); @@ -315,6 +348,9 @@ class ReflectionCaster return $a; } + /** + * @return array + */ public static function castReference(\ReflectionReference $c, array $a, Stub $stub, bool $isNested) { $a[Caster::PREFIX_VIRTUAL.'id'] = $c->getId(); @@ -322,6 +358,9 @@ class ReflectionCaster return $a; } + /** + * @return array + */ public static function castExtension(\ReflectionExtension $c, array $a, Stub $stub, bool $isNested) { self::addMap($a, $c, [ @@ -338,6 +377,9 @@ class ReflectionCaster return $a; } + /** + * @return array + */ public static function castZendExtension(\ReflectionZendExtension $c, array $a, Stub $stub, bool $isNested) { self::addMap($a, $c, [ @@ -350,6 +392,9 @@ class ReflectionCaster return $a; } + /** + * @return string + */ public static function getSignature(array $a) { $prefix = Caster::PREFIX_VIRTUAL; @@ -402,7 +447,7 @@ class ReflectionCaster return $signature; } - private static function addExtra(array &$a, \Reflector $c) + private static function addExtra(array &$a, \Reflector $c): void { $x = isset($a[Caster::PREFIX_VIRTUAL.'extra']) ? $a[Caster::PREFIX_VIRTUAL.'extra']->value : []; @@ -418,7 +463,7 @@ class ReflectionCaster } } - private static function addMap(array &$a, object $c, array $map, string $prefix = Caster::PREFIX_VIRTUAL) + private static function addMap(array &$a, object $c, array $map, string $prefix = Caster::PREFIX_VIRTUAL): void { foreach ($map as $k => $m) { if ('isDisabled' === $k) { diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ResourceCaster.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ResourceCaster.php index 4e597f86d..f3bbf3be4 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ResourceCaster.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ResourceCaster.php @@ -27,6 +27,9 @@ class ResourceCaster return curl_getinfo($h); } + /** + * @return array + */ public static function castDba($dba, array $a, Stub $stub, bool $isNested) { $list = dba_list(); @@ -35,12 +38,15 @@ class ResourceCaster return $a; } + /** + * @return array + */ public static function castProcess($process, array $a, Stub $stub, bool $isNested) { return proc_get_status($process); } - public static function castStream($stream, array $a, Stub $stub, bool $isNested) + public static function castStream($stream, array $a, Stub $stub, bool $isNested): array { $a = stream_get_meta_data($stream) + static::castStreamContext($stream, $a, $stub, $isNested); if ($a['uri'] ?? false) { @@ -50,11 +56,17 @@ class ResourceCaster return $a; } + /** + * @return array + */ public static function castStreamContext($stream, array $a, Stub $stub, bool $isNested) { return @stream_context_get_params($stream) ?: $a; } + /** + * @return array + */ public static function castGd($gd, array $a, Stub $stub, bool $isNested) { $a['size'] = imagesx($gd).'x'.imagesy($gd); @@ -63,15 +75,9 @@ class ResourceCaster return $a; } - public static function castMysqlLink($h, array $a, Stub $stub, bool $isNested) - { - $a['host'] = mysql_get_host_info($h); - $a['protocol'] = mysql_get_proto_info($h); - $a['server'] = mysql_get_server_info($h); - - return $a; - } - + /** + * @return array + */ public static function castOpensslX509($h, array $a, Stub $stub, bool $isNested) { $stub->cut = -1; @@ -86,7 +92,7 @@ class ResourceCaster $a += [ 'subject' => new EnumStub(array_intersect_key($info['subject'], ['organizationName' => true, 'commonName' => true])), 'issuer' => new EnumStub(array_intersect_key($info['issuer'], ['organizationName' => true, 'commonName' => true])), - 'expiry' => new ConstStub(date(\DateTime::ISO8601, $info['validTo_time_t']), $info['validTo_time_t']), + 'expiry' => new ConstStub(date(\DateTimeInterface::ISO8601, $info['validTo_time_t']), $info['validTo_time_t']), 'fingerprint' => new EnumStub([ 'md5' => new ConstStub(wordwrap(strtoupper(openssl_x509_fingerprint($h, 'md5')), 2, ':', true)), 'sha1' => new ConstStub(wordwrap(strtoupper(openssl_x509_fingerprint($h, 'sha1')), 2, ':', true)), diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ScalarStub.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ScalarStub.php new file mode 100644 index 000000000..3bb1935b8 --- /dev/null +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/ScalarStub.php @@ -0,0 +1,27 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Caster; + +use Symfony\Component\VarDumper\Cloner\Stub; + +/** + * Represents any arbitrary value. + * + * @author Alexandre Daubois + */ +class ScalarStub extends Stub +{ + public function __construct(mixed $value) + { + $this->value = $value; + } +} diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/SplCaster.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/SplCaster.php index a51cace1d..814d824d1 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/SplCaster.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/SplCaster.php @@ -29,16 +29,25 @@ class SplCaster \SplFileObject::READ_CSV => 'READ_CSV', ]; + /** + * @return array + */ public static function castArrayObject(\ArrayObject $c, array $a, Stub $stub, bool $isNested) { return self::castSplArray($c, $a, $stub, $isNested); } + /** + * @return array + */ public static function castArrayIterator(\ArrayIterator $c, array $a, Stub $stub, bool $isNested) { return self::castSplArray($c, $a, $stub, $isNested); } + /** + * @return array + */ public static function castHeap(\Iterator $c, array $a, Stub $stub, bool $isNested) { $a += [ @@ -48,6 +57,9 @@ class SplCaster return $a; } + /** + * @return array + */ public static function castDoublyLinkedList(\SplDoublyLinkedList $c, array $a, Stub $stub, bool $isNested) { $prefix = Caster::PREFIX_VIRTUAL; @@ -63,6 +75,9 @@ class SplCaster return $a; } + /** + * @return array + */ public static function castFileInfo(\SplFileInfo $c, array $a, Stub $stub, bool $isNested) { static $map = [ @@ -117,7 +132,7 @@ class SplCaster foreach ($map as $key => $accessor) { try { $a[$prefix.$key] = $c->$accessor(); - } catch (\Exception $e) { + } catch (\Exception) { } } @@ -139,6 +154,9 @@ class SplCaster return $a; } + /** + * @return array + */ public static function castFileObject(\SplFileObject $c, array $a, Stub $stub, bool $isNested) { static $map = [ @@ -155,7 +173,7 @@ class SplCaster foreach ($map as $key => $accessor) { try { $a[$prefix.$key] = $c->$accessor(); - } catch (\Exception $e) { + } catch (\Exception) { } } @@ -176,6 +194,9 @@ class SplCaster return $a; } + /** + * @return array + */ public static function castObjectStorage(\SplObjectStorage $c, array $a, Stub $stub, bool $isNested) { $storage = []; @@ -184,10 +205,10 @@ class SplCaster $clone = clone $c; foreach ($clone as $obj) { - $storage[] = [ + $storage[] = new EnumStub([ 'object' => $obj, 'info' => $clone->getInfo(), - ]; + ]); } $a += [ @@ -197,6 +218,9 @@ class SplCaster return $a; } + /** + * @return array + */ public static function castOuterIterator(\OuterIterator $c, array $a, Stub $stub, bool $isNested) { $a[Caster::PREFIX_VIRTUAL.'innerIterator'] = $c->getInnerIterator(); @@ -204,6 +228,9 @@ class SplCaster return $a; } + /** + * @return array + */ public static function castWeakReference(\WeakReference $c, array $a, Stub $stub, bool $isNested) { $a[Caster::PREFIX_VIRTUAL.'object'] = $c->get(); @@ -211,6 +238,27 @@ class SplCaster return $a; } + /** + * @return array + */ + public static function castWeakMap(\WeakMap $c, array $a, Stub $stub, bool $isNested) + { + $map = []; + + foreach (clone $c as $obj => $data) { + $map[] = new EnumStub([ + 'object' => $obj, + 'data' => $data, + ]); + } + + $a += [ + Caster::PREFIX_VIRTUAL.'map' => $map, + ]; + + return $a; + } + private static function castSplArray(\ArrayObject|\ArrayIterator $c, array $a, Stub $stub, bool $isNested): array { $prefix = Caster::PREFIX_VIRTUAL; @@ -218,10 +266,14 @@ class SplCaster if (!($flags & \ArrayObject::STD_PROP_LIST)) { $c->setFlags(\ArrayObject::STD_PROP_LIST); - $a = Caster::castObject($c, \get_class($c), method_exists($c, '__debugInfo'), $stub->class); + $a = Caster::castObject($c, $c::class, method_exists($c, '__debugInfo'), $stub->class); $c->setFlags($flags); } + + unset($a["\0ArrayObject\0storage"], $a["\0ArrayIterator\0storage"]); + $a += [ + $prefix.'storage' => $c->getArrayCopy(), $prefix.'flag::STD_PROP_LIST' => (bool) ($flags & \ArrayObject::STD_PROP_LIST), $prefix.'flag::ARRAY_AS_PROPS' => (bool) ($flags & \ArrayObject::ARRAY_AS_PROPS), ]; diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/StubCaster.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/StubCaster.php index 32ead7c27..4b93ff76f 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/StubCaster.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/StubCaster.php @@ -22,6 +22,9 @@ use Symfony\Component\VarDumper\Cloner\Stub; */ class StubCaster { + /** + * @return array + */ public static function castStub(Stub $c, array $a, Stub $stub, bool $isNested) { if ($isNested) { @@ -43,11 +46,17 @@ class StubCaster return $a; } + /** + * @return array + */ public static function castCutArray(CutArrayStub $c, array $a, Stub $stub, bool $isNested) { return $isNested ? $c->preservedSubset : $a; } + /** + * @return array + */ public static function cutInternals($obj, array $a, Stub $stub, bool $isNested) { if ($isNested) { @@ -59,6 +68,9 @@ class StubCaster return $a; } + /** + * @return array + */ public static function castEnum(EnumStub $c, array $a, Stub $stub, bool $isNested) { if ($isNested) { @@ -81,4 +93,15 @@ class StubCaster return $a; } + + /** + * @return array + */ + public static function castScalar(ScalarStub $scalarStub, array $a, Stub $stub) + { + $stub->type = Stub::TYPE_SCALAR; + $stub->attr['value'] = $scalarStub->value; + + return $a; + } } diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/SymfonyCaster.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/SymfonyCaster.php index 08428b927..ebc00f90e 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/SymfonyCaster.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/SymfonyCaster.php @@ -15,6 +15,7 @@ use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Uid\Ulid; use Symfony\Component\Uid\Uuid; use Symfony\Component\VarDumper\Cloner\Stub; +use Symfony\Component\VarExporter\Internal\LazyObjectState; /** * @final @@ -30,6 +31,9 @@ class SymfonyCaster 'format' => 'getRequestFormat', ]; + /** + * @return array + */ public static function castRequest(Request $request, array $a, Stub $stub, bool $isNested) { $clone = null; @@ -37,9 +41,7 @@ class SymfonyCaster foreach (self::REQUEST_GETTERS as $prop => $getter) { $key = Caster::PREFIX_PROTECTED.$prop; if (\array_key_exists($key, $a) && null === $a[$key]) { - if (null === $clone) { - $clone = clone $request; - } + $clone ??= clone $request; $a[Caster::PREFIX_VIRTUAL.$prop] = $clone->{$getter}(); } } @@ -47,9 +49,12 @@ class SymfonyCaster return $a; } + /** + * @return array + */ public static function castHttpClient($client, array $a, Stub $stub, bool $isNested) { - $multiKey = sprintf("\0%s\0multi", \get_class($client)); + $multiKey = sprintf("\0%s\0multi", $client::class); if (isset($a[$multiKey])) { $a[$multiKey] = new CutStub($a[$multiKey]); } @@ -57,6 +62,9 @@ class SymfonyCaster return $a; } + /** + * @return array + */ public static function castHttpClientResponse($response, array $a, Stub $stub, bool $isNested) { $stub->cut += \count($a); @@ -69,6 +77,37 @@ class SymfonyCaster return $a; } + /** + * @return array + */ + public static function castLazyObjectState($state, array $a, Stub $stub, bool $isNested) + { + if (!$isNested) { + return $a; + } + + $stub->cut += \count($a) - 1; + + $instance = $a['realInstance'] ?? null; + + $a = ['status' => new ConstStub(match ($a['status']) { + LazyObjectState::STATUS_INITIALIZED_FULL => 'INITIALIZED_FULL', + LazyObjectState::STATUS_INITIALIZED_PARTIAL => 'INITIALIZED_PARTIAL', + LazyObjectState::STATUS_UNINITIALIZED_FULL => 'UNINITIALIZED_FULL', + LazyObjectState::STATUS_UNINITIALIZED_PARTIAL => 'UNINITIALIZED_PARTIAL', + }, $a['status'])]; + + if ($instance) { + $a['realInstance'] = $instance; + --$stub->cut; + } + + return $a; + } + + /** + * @return array + */ public static function castUuid(Uuid $uuid, array $a, Stub $stub, bool $isNested) { $a[Caster::PREFIX_VIRTUAL.'toBase58'] = $uuid->toBase58(); @@ -82,6 +121,9 @@ class SymfonyCaster return $a; } + /** + * @return array + */ public static function castUlid(Ulid $ulid, array $a, Stub $stub, bool $isNested) { $a[Caster::PREFIX_VIRTUAL.'toBase58'] = $ulid->toBase58(); diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/TraceStub.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/TraceStub.php index 5eea1c876..d215d8db0 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/TraceStub.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/TraceStub.php @@ -25,7 +25,7 @@ class TraceStub extends Stub public $sliceLength; public $numberingOffset; - public function __construct(array $trace, bool $keepArgs = true, int $sliceOffset = 0, int $sliceLength = null, int $numberingOffset = 0) + public function __construct(array $trace, bool $keepArgs = true, int $sliceOffset = 0, ?int $sliceLength = null, int $numberingOffset = 0) { $this->value = $trace; $this->keepArgs = $keepArgs; diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/UninitializedStub.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/UninitializedStub.php new file mode 100644 index 000000000..a9bdd9b81 --- /dev/null +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/UninitializedStub.php @@ -0,0 +1,25 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\VarDumper\Caster; + +/** + * Represents an uninitialized property. + * + * @author Nicolas Grekas + */ +class UninitializedStub extends ConstStub +{ + public function __construct(\ReflectionProperty $property) + { + parent::__construct('?'.($property->hasType() ? ' '.$property->getType() : ''), 'Uninitialized property'); + } +} diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/XmlReaderCaster.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/XmlReaderCaster.php index 721513c5d..1cfcf4dd8 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/XmlReaderCaster.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/XmlReaderCaster.php @@ -1,4 +1,5 @@ 'XML_DECLARATION', ]; + /** + * @return array + */ public static function castXmlReader(\XMLReader $reader, array $a, Stub $stub, bool $isNested) { try { @@ -51,7 +55,7 @@ class XmlReaderCaster 'VALIDATE' => @$reader->getParserProperty(\XMLReader::VALIDATE), 'SUBST_ENTITIES' => @$reader->getParserProperty(\XMLReader::SUBST_ENTITIES), ]; - } catch (\Error $e) { + } catch (\Error) { $properties = [ 'LOADDTD' => false, 'DEFAULTATTRS' => false, @@ -81,6 +85,7 @@ class XmlReaderCaster $info[$props]->cut = $count; } + $a = Caster::filter($a, Caster::EXCLUDE_UNINITIALIZED, [], $count); $info = Caster::filter($info, Caster::EXCLUDE_EMPTY, [], $count); // +2 because hasValue and hasAttributes are always filtered $stub->cut += $count + 2; diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/XmlResourceCaster.php b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/XmlResourceCaster.php index ba55fcedd..0cf42584a 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Caster/XmlResourceCaster.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Caster/XmlResourceCaster.php @@ -47,6 +47,9 @@ class XmlResourceCaster \XML_ERROR_EXTERNAL_ENTITY_HANDLING => 'XML_ERROR_EXTERNAL_ENTITY_HANDLING', ]; + /** + * @return array + */ public static function castXml($h, array $a, Stub $stub, bool $isNested) { $a['current_byte_index'] = xml_get_current_byte_index($h); diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Cloner/AbstractCloner.php b/data/web/inc/lib/vendor/symfony/var-dumper/Cloner/AbstractCloner.php index b835c0336..fc330bae2 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Cloner/AbstractCloner.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Cloner/AbstractCloner.php @@ -28,6 +28,7 @@ abstract class AbstractCloner implements ClonerInterface 'Symfony\Component\VarDumper\Caster\CutArrayStub' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'castCutArray'], 'Symfony\Component\VarDumper\Caster\ConstStub' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'castStub'], 'Symfony\Component\VarDumper\Caster\EnumStub' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'castEnum'], + 'Symfony\Component\VarDumper\Caster\ScalarStub' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'castScalar'], 'Fiber' => ['Symfony\Component\VarDumper\Caster\FiberCaster', 'castFiber'], @@ -66,9 +67,6 @@ abstract class AbstractCloner implements ClonerInterface 'DOMAttr' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castAttr'], 'DOMElement' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castElement'], 'DOMText' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castText'], - 'DOMTypeinfo' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castTypeinfo'], - 'DOMDomError' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castDomError'], - 'DOMLocator' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castLocator'], 'DOMDocumentType' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castDocumentType'], 'DOMNotation' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castNotation'], 'DOMEntity' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castEntity'], @@ -92,10 +90,12 @@ abstract class AbstractCloner implements ClonerInterface 'Symfony\Component\HttpFoundation\Request' => ['Symfony\Component\VarDumper\Caster\SymfonyCaster', 'castRequest'], 'Symfony\Component\Uid\Ulid' => ['Symfony\Component\VarDumper\Caster\SymfonyCaster', 'castUlid'], 'Symfony\Component\Uid\Uuid' => ['Symfony\Component\VarDumper\Caster\SymfonyCaster', 'castUuid'], + 'Symfony\Component\VarExporter\Internal\LazyObjectState' => ['Symfony\Component\VarDumper\Caster\SymfonyCaster', 'castLazyObjectState'], 'Symfony\Component\VarDumper\Exception\ThrowingCasterException' => ['Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castThrowingCasterException'], 'Symfony\Component\VarDumper\Caster\TraceStub' => ['Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castTraceStub'], 'Symfony\Component\VarDumper\Caster\FrameStub' => ['Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castFrameStub'], 'Symfony\Component\VarDumper\Cloner\AbstractCloner' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'], + 'Symfony\Component\ErrorHandler\Exception\FlattenException' => ['Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castFlattenException'], 'Symfony\Component\ErrorHandler\Exception\SilencedErrorContext' => ['Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castSilencedErrorContext'], 'Imagine\Image\ImageInterface' => ['Symfony\Component\VarDumper\Caster\ImagineCaster', 'castImage'], @@ -127,9 +127,11 @@ abstract class AbstractCloner implements ClonerInterface 'SplObjectStorage' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castObjectStorage'], 'SplPriorityQueue' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castHeap'], 'OuterIterator' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castOuterIterator'], + 'WeakMap' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castWeakMap'], 'WeakReference' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castWeakReference'], 'Redis' => ['Symfony\Component\VarDumper\Caster\RedisCaster', 'castRedis'], + 'Relay\Relay' => ['Symfony\Component\VarDumper\Caster\RedisCaster', 'castRedis'], 'RedisArray' => ['Symfony\Component\VarDumper\Caster\RedisCaster', 'castRedisArray'], 'RedisCluster' => ['Symfony\Component\VarDumper\Caster\RedisCaster', 'castRedisCluster'], @@ -163,7 +165,6 @@ abstract class AbstractCloner implements ClonerInterface 'GdImage' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castGd'], ':gd' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castGd'], - ':mysql link' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castMysqlLink'], ':pgsql large object' => ['Symfony\Component\VarDumper\Caster\PgSqlCaster', 'castLargeObject'], ':pgsql link' => ['Symfony\Component\VarDumper\Caster\PgSqlCaster', 'castLink'], ':pgsql link persistent' => ['Symfony\Component\VarDumper\Caster\PgSqlCaster', 'castLink'], @@ -191,6 +192,9 @@ abstract class AbstractCloner implements ClonerInterface 'RdKafka\Topic' => ['Symfony\Component\VarDumper\Caster\RdKafkaCaster', 'castTopic'], 'RdKafka\TopicPartition' => ['Symfony\Component\VarDumper\Caster\RdKafkaCaster', 'castTopicPartition'], 'RdKafka\TopicConf' => ['Symfony\Component\VarDumper\Caster\RdKafkaCaster', 'castTopicConf'], + + 'FFI\CData' => ['Symfony\Component\VarDumper\Caster\FFICaster', 'castCTypeOrCData'], + 'FFI\CType' => ['Symfony\Component\VarDumper\Caster\FFICaster', 'castCTypeOrCData'], ]; protected $maxItems = 2500; @@ -215,12 +219,9 @@ abstract class AbstractCloner implements ClonerInterface * * @see addCasters */ - public function __construct(array $casters = null) + public function __construct(?array $casters = null) { - if (null === $casters) { - $casters = static::$defaultCasters; - } - $this->addCasters($casters); + $this->addCasters($casters ?? static::$defaultCasters); } /** @@ -232,6 +233,8 @@ abstract class AbstractCloner implements ClonerInterface * see e.g. static::$defaultCasters. * * @param callable[] $casters A map of casters + * + * @return void */ public function addCasters(array $casters) { @@ -242,6 +245,8 @@ abstract class AbstractCloner implements ClonerInterface /** * Sets the maximum number of items to clone past the minimum depth in nested structures. + * + * @return void */ public function setMaxItems(int $maxItems) { @@ -250,6 +255,8 @@ abstract class AbstractCloner implements ClonerInterface /** * Sets the maximum cloned length for strings. + * + * @return void */ public function setMaxString(int $maxString) { @@ -259,6 +266,8 @@ abstract class AbstractCloner implements ClonerInterface /** * Sets the minimum tree depth where we are guaranteed to clone all the items. After this * depth is reached, only setMaxItems items will be cloned. + * + * @return void */ public function setMinDepth(int $minDepth) { diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Cloner/Data.php b/data/web/inc/lib/vendor/symfony/var-dumper/Cloner/Data.php index 6ecb883e8..16f51b0c7 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Cloner/Data.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Cloner/Data.php @@ -17,7 +17,7 @@ use Symfony\Component\VarDumper\Dumper\ContextProvider\SourceContextProvider; /** * @author Nicolas Grekas */ -class Data implements \ArrayAccess, \Countable, \IteratorAggregate +class Data implements \ArrayAccess, \Countable, \IteratorAggregate, \Stringable { private array $data; private int $position = 0; @@ -121,6 +121,9 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate yield from $value; } + /** + * @return mixed + */ public function __get(string $key) { if (null !== $data = $this->seek($key)) { @@ -211,6 +214,11 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate return $data; } + public function getContext(): array + { + return $this->context; + } + /** * Seeks to a specific key in nested data structures. */ @@ -257,21 +265,21 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate /** * Dumps data with a DumperInterface dumper. + * + * @return void */ public function dump(DumperInterface $dumper) { $refs = [0]; $cursor = new Cursor(); + $cursor->hashType = -1; + $cursor->attr = $this->context[SourceContextProvider::class] ?? []; + $label = $this->context['label'] ?? ''; - if ($cursor->attr = $this->context[SourceContextProvider::class] ?? []) { - $cursor->attr['if_links'] = true; - $cursor->hashType = -1; - $dumper->dumpScalar($cursor, 'default', '^'); - $cursor->attr = ['if_links' => true]; - $dumper->dumpScalar($cursor, 'default', ' '); - $cursor->hashType = 0; + if ($cursor->attr || '' !== $label) { + $dumper->dumpScalar($cursor, 'label', $label); } - + $cursor->hashType = 0; $this->dumpItem($dumper, $cursor, $refs, $this->data[$this->position][$this->key]); } @@ -280,7 +288,7 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate * * @param mixed $item A Stub object or the original value being dumped */ - private function dumpItem(DumperInterface $dumper, Cursor $cursor, array &$refs, mixed $item) + private function dumpItem(DumperInterface $dumper, Cursor $cursor, array &$refs, mixed $item): void { $cursor->refIndex = 0; $cursor->softRefTo = $cursor->softRefHandle = $cursor->softRefCount = 0; @@ -362,6 +370,10 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate $dumper->leaveHash($cursor, $item->type, $item->class, $withChildren, $cut); break; + case Stub::TYPE_SCALAR: + $dumper->dumpScalar($cursor, 'default', $item->attr['value']); + break; + default: throw new \RuntimeException(sprintf('Unexpected Stub type: "%s".', $item->type)); } @@ -402,7 +414,7 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate return $hashCut; } - private function getStub(mixed $item) + private function getStub(mixed $item): mixed { if (!$item || !\is_array($item)) { return $item; diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Cloner/DumperInterface.php b/data/web/inc/lib/vendor/symfony/var-dumper/Cloner/DumperInterface.php index 61d02d240..4c5b315b6 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Cloner/DumperInterface.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Cloner/DumperInterface.php @@ -20,6 +20,8 @@ interface DumperInterface { /** * Dumps a scalar value. + * + * @return void */ public function dumpScalar(Cursor $cursor, string $type, string|int|float|bool|null $value); @@ -29,6 +31,8 @@ interface DumperInterface * @param string $str The string being dumped * @param bool $bin Whether $str is UTF-8 or binary encoded * @param int $cut The number of characters $str has been cut by + * + * @return void */ public function dumpString(Cursor $cursor, string $str, bool $bin, int $cut); @@ -38,6 +42,8 @@ interface DumperInterface * @param int $type A Cursor::HASH_* const for the type of hash * @param string|int|null $class The object class, resource type or array count * @param bool $hasChild When the dump of the hash has child item + * + * @return void */ public function enterHash(Cursor $cursor, int $type, string|int|null $class, bool $hasChild); @@ -48,6 +54,8 @@ interface DumperInterface * @param string|int|null $class The object class, resource type or array count * @param bool $hasChild When the dump of the hash has child item * @param int $cut The number of items the hash has been cut by + * + * @return void */ public function leaveHash(Cursor $cursor, int $type, string|int|null $class, bool $hasChild, int $cut); } diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Cloner/Stub.php b/data/web/inc/lib/vendor/symfony/var-dumper/Cloner/Stub.php index 1c5b88712..0c2a4b9d0 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Cloner/Stub.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Cloner/Stub.php @@ -23,6 +23,7 @@ class Stub public const TYPE_ARRAY = 3; public const TYPE_OBJECT = 4; public const TYPE_RESOURCE = 5; + public const TYPE_SCALAR = 6; public const STRING_BINARY = 1; public const STRING_UTF8 = 2; diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Cloner/VarCloner.php b/data/web/inc/lib/vendor/symfony/var-dumper/Cloner/VarCloner.php index 9afcc348a..e168d0d3b 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Cloner/VarCloner.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Cloner/VarCloner.php @@ -16,12 +16,8 @@ namespace Symfony\Component\VarDumper\Cloner; */ class VarCloner extends AbstractCloner { - private static string $gid; private static array $arrayCache = []; - /** - * {@inheritdoc} - */ protected function doClone(mixed $var): array { $len = 1; // Length of $queue @@ -44,7 +40,6 @@ class VarCloner extends AbstractCloner $stub = null; // Stub capturing the main properties of an original item value // or null if the original value is used directly - $gid = self::$gid ??= md5(random_bytes(6)); // Unique string used to detect the special $GLOBALS variable $arrayStub = new Stub(); $arrayStub->type = Stub::TYPE_ARRAY; $fromObjCast = false; @@ -121,53 +116,15 @@ class VarCloner extends AbstractCloner } $stub = $arrayStub; - if (\PHP_VERSION_ID >= 80100) { - $stub->class = array_is_list($v) ? Stub::ARRAY_INDEXED : Stub::ARRAY_ASSOC; - $a = $v; - break; - } - - $stub->class = Stub::ARRAY_INDEXED; - - $j = -1; - foreach ($v as $gk => $gv) { - if ($gk !== ++$j) { - $stub->class = Stub::ARRAY_ASSOC; - $a = $v; - $a[$gid] = true; - break; - } - } - - // Copies of $GLOBALS have very strange behavior, - // let's detect them with some black magic - if (isset($v[$gid])) { - unset($v[$gid]); - $a = []; - foreach ($v as $gk => &$gv) { - if ($v === $gv && !isset($hardRefs[\ReflectionReference::fromArrayElement($v, $gk)->getId()])) { - unset($v); - $v = new Stub(); - $v->value = [$v->cut = \count($gv), Stub::TYPE_ARRAY => 0]; - $v->handle = -1; - $gv = &$a[$gk]; - $hardRefs[\ReflectionReference::fromArrayElement($a, $gk)->getId()] = &$gv; - $gv = $v; - } - - $a[$gk] = &$gv; - } - unset($gv); - } else { - $a = $v; - } + $stub->class = array_is_list($v) ? Stub::ARRAY_INDEXED : Stub::ARRAY_ASSOC; + $a = $v; break; case \is_object($v): if (empty($objRefs[$h = spl_object_id($v)])) { $stub = new Stub(); $stub->type = Stub::TYPE_OBJECT; - $stub->class = \get_class($v); + $stub->class = $v::class; $stub->value = $v; $stub->handle = $h; $a = $this->castObject($stub, 0 < $i); diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Command/Descriptor/CliDescriptor.php b/data/web/inc/lib/vendor/symfony/var-dumper/Command/Descriptor/CliDescriptor.php index e3d5f1d11..4450fe986 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Command/Descriptor/CliDescriptor.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Command/Descriptor/CliDescriptor.php @@ -26,7 +26,7 @@ use Symfony\Component\VarDumper\Dumper\CliDumper; */ class CliDescriptor implements DumpDescriptorInterface { - private $dumper; + private CliDumper $dumper; private mixed $lastIdentifier = null; public function __construct(CliDumper $dumper) diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Command/Descriptor/HtmlDescriptor.php b/data/web/inc/lib/vendor/symfony/var-dumper/Command/Descriptor/HtmlDescriptor.php index 1c0d80a05..98f150a5e 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Command/Descriptor/HtmlDescriptor.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Command/Descriptor/HtmlDescriptor.php @@ -24,7 +24,7 @@ use Symfony\Component\VarDumper\Dumper\HtmlDumper; */ class HtmlDescriptor implements DumpDescriptorInterface { - private $dumper; + private HtmlDumper $dumper; private bool $initialized = false; public function __construct(HtmlDumper $dumper) diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Command/ServerDumpCommand.php b/data/web/inc/lib/vendor/symfony/var-dumper/Command/ServerDumpCommand.php index 13dd475b5..b64a884b9 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Command/ServerDumpCommand.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Command/ServerDumpCommand.php @@ -38,7 +38,7 @@ use Symfony\Component\VarDumper\Server\DumpServer; #[AsCommand(name: 'server:dump', description: 'Start a dump server that collects and displays dumps in a single place')] class ServerDumpCommand extends Command { - private $server; + private DumpServer $server; /** @var DumpDescriptorInterface[] */ private array $descriptors; @@ -54,7 +54,7 @@ class ServerDumpCommand extends Command parent::__construct(); } - protected function configure() + protected function configure(): void { $this ->addOption('format', null, InputOption::VALUE_REQUIRED, sprintf('The output format (%s)', implode(', ', $this->getAvailableFormats())), 'cli') diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Dumper/AbstractDumper.php b/data/web/inc/lib/vendor/symfony/var-dumper/Dumper/AbstractDumper.php index 6ac380836..53165ba64 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Dumper/AbstractDumper.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Dumper/AbstractDumper.php @@ -26,12 +26,15 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface public const DUMP_COMMA_SEPARATOR = 4; public const DUMP_TRAILING_COMMA = 8; + /** @var callable|resource|string|null */ public static $defaultOutput = 'php://output'; protected $line = ''; + /** @var callable|null */ protected $lineDumper; + /** @var resource|null */ protected $outputStream; - protected $decimalPoint; // This is locale dependent + protected $decimalPoint = '.'; protected $indentPad = ' '; protected $flags; @@ -42,12 +45,10 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface * @param string|null $charset The default character encoding to use for non-UTF8 strings * @param int $flags A bit field of static::DUMP_* constants to fine tune dumps representation */ - public function __construct($output = null, string $charset = null, int $flags = 0) + public function __construct($output = null, ?string $charset = null, int $flags = 0) { $this->flags = $flags; - $this->setCharset($charset ?: ini_get('php.output_encoding') ?: ini_get('default_charset') ?: 'UTF-8'); - $this->decimalPoint = localeconv(); - $this->decimalPoint = $this->decimalPoint['decimal_point']; + $this->setCharset($charset ?: \ini_get('php.output_encoding') ?: \ini_get('default_charset') ?: 'UTF-8'); $this->setOutput($output ?: static::$defaultOutput); if (!$output && \is_string(static::$defaultOutput)) { static::$defaultOutput = $this->outputStream; @@ -57,9 +58,9 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface /** * Sets the output destination of the dumps. * - * @param callable|resource|string $output A line dumper callable, an opened stream or an output path + * @param callable|resource|string|null $output A line dumper callable, an opened stream or an output path * - * @return callable|resource|string The previous output destination + * @return callable|resource|string|null The previous output destination */ public function setOutput($output) { @@ -73,7 +74,7 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface $output = fopen($output, 'w'); } $this->outputStream = $output; - $this->lineDumper = [$this, 'echoLine']; + $this->lineDumper = $this->echoLine(...); } return $prev; @@ -120,9 +121,6 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface */ public function dump(Data $data, $output = null): ?string { - $this->decimalPoint = localeconv(); - $this->decimalPoint = $this->decimalPoint['decimal_point']; - if ($locale = $this->flags & (self::DUMP_COMMA_SEPARATOR | self::DUMP_TRAILING_COMMA) ? setlocale(\LC_NUMERIC, 0) : null) { setlocale(\LC_NUMERIC, 'C'); } @@ -160,6 +158,8 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface * * @param int $depth The recursive depth in the dumped structure for the line being dumped, * or -1 to signal the end-of-dump to the line dumper callable + * + * @return void */ protected function dumpLine(int $depth) { @@ -169,6 +169,8 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface /** * Generic line dumper callback. + * + * @return void */ protected function echoLine(string $line, int $depth, string $indentPad) { diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Dumper/CliDumper.php b/data/web/inc/lib/vendor/symfony/var-dumper/Dumper/CliDumper.php index f6e290ca4..af9637072 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Dumper/CliDumper.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Dumper/CliDumper.php @@ -22,6 +22,7 @@ use Symfony\Component\VarDumper\Cloner\Stub; class CliDumper extends AbstractDumper { public static $defaultColors; + /** @var callable|resource|string|null */ public static $defaultOutput = 'php://stdout'; protected $colors; @@ -51,6 +52,7 @@ class CliDumper extends AbstractDumper "\r" => '\r', "\033" => '\e', ]; + protected static $unicodeCharsRx = "/[\u{00A0}\u{00AD}\u{034F}\u{061C}\u{115F}\u{1160}\u{17B4}\u{17B5}\u{180E}\u{2000}-\u{200F}\u{202F}\u{205F}\u{2060}-\u{2064}\u{206A}-\u{206F}\u{3000}\u{2800}\u{3164}\u{FEFF}\u{FFA0}\u{1D159}\u{1D173}-\u{1D17A}]/u"; protected $collapseNextHash = false; protected $expandNextHash = false; @@ -61,10 +63,7 @@ class CliDumper extends AbstractDumper private bool $handlesHrefGracefully; - /** - * {@inheritdoc} - */ - public function __construct($output = null, string $charset = null, int $flags = 0) + public function __construct($output = null, ?string $charset = null, int $flags = 0) { parent::__construct($output, $charset, $flags); @@ -83,11 +82,13 @@ class CliDumper extends AbstractDumper ]); } - $this->displayOptions['fileLinkFormat'] = ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format') ?: 'file://%f#L%l'; + $this->displayOptions['fileLinkFormat'] = \ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format') ?: 'file://%f#L%l'; } /** * Enables/disables colored output. + * + * @return void */ public function setColors(bool $colors) { @@ -96,6 +97,8 @@ class CliDumper extends AbstractDumper /** * Sets the maximum number of characters per line for dumped strings. + * + * @return void */ public function setMaxStringWidth(int $maxStringWidth) { @@ -106,6 +109,8 @@ class CliDumper extends AbstractDumper * Configures styles. * * @param array $styles A map of style names to style definitions + * + * @return void */ public function setStyles(array $styles) { @@ -116,6 +121,8 @@ class CliDumper extends AbstractDumper * Configures display options. * * @param array $displayOptions A map of display options to customize the behavior + * + * @return void */ public function setDisplayOptions(array $displayOptions) { @@ -123,11 +130,12 @@ class CliDumper extends AbstractDumper } /** - * {@inheritdoc} + * @return void */ public function dumpScalar(Cursor $cursor, string $type, string|int|float|bool|null $value) { $this->dumpKey($cursor); + $this->collapseNextHash = $this->expandNextHash = false; $style = 'const'; $attr = $cursor->attr; @@ -137,6 +145,11 @@ class CliDumper extends AbstractDumper $style = 'default'; break; + case 'label': + $this->styles += ['label' => $this->styles['default']]; + $style = 'label'; + break; + case 'integer': $style = 'num'; @@ -153,17 +166,12 @@ class CliDumper extends AbstractDumper $style = 'float'; } - switch (true) { - case \INF === $value: $value = 'INF'; break; - case -\INF === $value: $value = '-INF'; break; - case is_nan($value): $value = 'NAN'; break; - default: - $value = (string) $value; - if (!str_contains($value, $this->decimalPoint)) { - $value .= $this->decimalPoint.'0'; - } - break; - } + $value = match (true) { + \INF === $value => 'INF', + -\INF === $value => '-INF', + is_nan($value) => 'NAN', + default => !str_contains($value = (string) $value, $this->decimalPoint) ? $value .= $this->decimalPoint.'0' : $value, + }; break; case 'NULL': @@ -186,11 +194,12 @@ class CliDumper extends AbstractDumper } /** - * {@inheritdoc} + * @return void */ public function dumpString(Cursor $cursor, string $str, bool $bin, int $cut) { $this->dumpKey($cursor); + $this->collapseNextHash = $this->expandNextHash = false; $attr = $cursor->attr; if ($bin) { @@ -198,13 +207,16 @@ class CliDumper extends AbstractDumper } if ('' === $str) { $this->line .= '""'; + if ($cut) { + $this->line .= '…'.$cut; + } $this->endValue($cursor); } else { $attr += [ 'length' => 0 <= $cut ? mb_strlen($str, 'UTF-8') + $cut : 0, 'binary' => $bin, ]; - $str = $bin && false !== strpos($str, "\0") ? [$str] : explode("\n", $str); + $str = $bin && str_contains($str, "\0") ? [$str] : explode("\n", $str); if (isset($str[1]) && !isset($str[2]) && !isset($str[1][0])) { unset($str[1]); $str[0] .= "\n"; @@ -274,15 +286,14 @@ class CliDumper extends AbstractDumper } /** - * {@inheritdoc} + * @return void */ public function enterHash(Cursor $cursor, int $type, string|int|null $class, bool $hasChild) { - if (null === $this->colors) { - $this->colors = $this->supportsColors(); - } + $this->colors ??= $this->supportsColors(); $this->dumpKey($cursor); + $this->expandNextHash = false; $attr = $cursor->attr; if ($this->collapseNextHash) { @@ -315,7 +326,7 @@ class CliDumper extends AbstractDumper } /** - * {@inheritdoc} + * @return void */ public function leaveHash(Cursor $cursor, int $type, string|int|null $class, bool $hasChild, int $cut) { @@ -332,6 +343,8 @@ class CliDumper extends AbstractDumper * * @param bool $hasChild When the dump of the hash has child item * @param int $cut The number of items the hash has been cut by + * + * @return void */ protected function dumpEllipsis(Cursor $cursor, bool $hasChild, int $cut) { @@ -348,6 +361,8 @@ class CliDumper extends AbstractDumper /** * Dumps a key in a hash structure. + * + * @return void */ protected function dumpKey(Cursor $cursor) { @@ -437,12 +452,11 @@ class CliDumper extends AbstractDumper */ protected function style(string $style, string $value, array $attr = []): string { - if (null === $this->colors) { - $this->colors = $this->supportsColors(); - } + $this->colors ??= $this->supportsColors(); $this->handlesHrefGracefully ??= 'JetBrains-JediTerm' !== getenv('TERMINAL_EMULATOR') - && (!getenv('KONSOLE_VERSION') || (int) getenv('KONSOLE_VERSION') > 201100); + && (!getenv('KONSOLE_VERSION') || (int) getenv('KONSOLE_VERSION') > 201100) + && !isset($_SERVER['IDEA_INITIAL_DIRECTORY']); if (isset($attr['ellipsis'], $attr['ellipsis-type'])) { $prefix = substr($value, 0, -$attr['ellipsis']); @@ -474,7 +488,15 @@ class CliDumper extends AbstractDumper return $s.$endCchr; }, $value, -1, $cchrCount); - if ($this->colors) { + if (!($attr['binary'] ?? false)) { + $value = preg_replace_callback(static::$unicodeCharsRx, function ($c) use (&$cchrCount, $startCchr, $endCchr) { + ++$cchrCount; + + return $startCchr.'\u{'.strtoupper(dechex(mb_ord($c[0]))).'}'.$endCchr; + }, $value); + } + + if ($this->colors && '' !== $value) { if ($cchrCount && "\033" === $value[0]) { $value = substr($value, \strlen($startCchr)); } else { @@ -497,10 +519,15 @@ class CliDumper extends AbstractDumper } } if (isset($attr['href'])) { + if ('label' === $style) { + $value .= '^'; + } $value = "\033]8;;{$attr['href']}\033\\{$value}\033]8;;\033\\"; } - } elseif ($attr['if_links'] ?? false) { - return ''; + } + + if ('label' === $style && '' !== $value) { + $value .= ' '; } return $value; @@ -511,7 +538,7 @@ class CliDumper extends AbstractDumper if ($this->outputStream !== static::$defaultOutput) { return $this->hasColorSupport($this->outputStream); } - if (null !== static::$defaultColors) { + if (isset(static::$defaultColors)) { return static::$defaultColors; } if (isset($_SERVER['argv'][1])) { @@ -546,16 +573,23 @@ class CliDumper extends AbstractDumper } /** - * {@inheritdoc} + * @return void */ protected function dumpLine(int $depth, bool $endOfValue = false) { + if (null === $this->colors) { + $this->colors = $this->supportsColors(); + } + if ($this->colors) { $this->line = sprintf("\033[%sm%s\033[m", $this->styles['default'], $this->line); } parent::dumpLine($depth); } + /** + * @return void + */ protected function endValue(Cursor $cursor) { if (-1 === $cursor->hashType) { @@ -632,7 +666,7 @@ class CliDumper extends AbstractDumper return $result; } - private function getSourceLink(string $file, int $line) + private function getSourceLink(string $file, int $line): string|false { if ($fmt = $this->displayOptions['fileLinkFormat']) { return \is_string($fmt) ? strtr($fmt, ['%f' => $file, '%l' => $line]) : ($fmt->format($file, $line) ?: 'file://'.$file.'#L'.$line); diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Dumper/ContextProvider/RequestContextProvider.php b/data/web/inc/lib/vendor/symfony/var-dumper/Dumper/ContextProvider/RequestContextProvider.php index 3684a4753..69dff067b 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Dumper/ContextProvider/RequestContextProvider.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Dumper/ContextProvider/RequestContextProvider.php @@ -22,8 +22,8 @@ use Symfony\Component\VarDumper\Cloner\VarCloner; */ final class RequestContextProvider implements ContextProviderInterface { - private $requestStack; - private $cloner; + private RequestStack $requestStack; + private VarCloner $cloner; public function __construct(RequestStack $requestStack) { diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Dumper/ContextProvider/SourceContextProvider.php b/data/web/inc/lib/vendor/symfony/var-dumper/Dumper/ContextProvider/SourceContextProvider.php index 8ef6e360e..cadddfac4 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Dumper/ContextProvider/SourceContextProvider.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Dumper/ContextProvider/SourceContextProvider.php @@ -11,7 +11,8 @@ namespace Symfony\Component\VarDumper\Dumper\ContextProvider; -use Symfony\Component\HttpKernel\Debug\FileLinkFormatter; +use Symfony\Component\ErrorHandler\ErrorRenderer\FileLinkFormatter; +use Symfony\Component\HttpKernel\Debug\FileLinkFormatter as LegacyFileLinkFormatter; use Symfony\Component\VarDumper\Cloner\VarCloner; use Symfony\Component\VarDumper\Dumper\HtmlDumper; use Symfony\Component\VarDumper\VarDumper; @@ -28,9 +29,9 @@ final class SourceContextProvider implements ContextProviderInterface private int $limit; private ?string $charset; private ?string $projectDir; - private $fileLinkFormatter; + private FileLinkFormatter|LegacyFileLinkFormatter|null $fileLinkFormatter; - public function __construct(string $charset = null, string $projectDir = null, FileLinkFormatter $fileLinkFormatter = null, int $limit = 9) + public function __construct(?string $charset = null, ?string $projectDir = null, FileLinkFormatter|LegacyFileLinkFormatter|null $fileLinkFormatter = null, int $limit = 9) { $this->charset = $charset; $this->projectDir = $projectDir; @@ -44,7 +45,7 @@ final class SourceContextProvider implements ContextProviderInterface $file = $trace[1]['file']; $line = $trace[1]['line']; - $name = false; + $name = '-' === $file || 'Standard input code' === $file ? 'Standard input code' : false; $fileExcerpt = false; for ($i = 2; $i < $this->limit; ++$i) { diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Dumper/ContextualizedDumper.php b/data/web/inc/lib/vendor/symfony/var-dumper/Dumper/ContextualizedDumper.php index 18ab56ebd..84cfb4259 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Dumper/ContextualizedDumper.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Dumper/ContextualizedDumper.php @@ -19,7 +19,7 @@ use Symfony\Component\VarDumper\Dumper\ContextProvider\ContextProviderInterface; */ class ContextualizedDumper implements DataDumperInterface { - private $wrappedDumper; + private DataDumperInterface $wrappedDumper; private array $contextProviders; /** @@ -31,13 +31,16 @@ class ContextualizedDumper implements DataDumperInterface $this->contextProviders = $contextProviders; } + /** + * @return string|null + */ public function dump(Data $data) { - $context = []; + $context = $data->getContext(); foreach ($this->contextProviders as $contextProvider) { - $context[\get_class($contextProvider)] = $contextProvider->getContext(); + $context[$contextProvider::class] = $contextProvider->getContext(); } - $this->wrappedDumper->dump($data->withContext($context)); + return $this->wrappedDumper->dump($data->withContext($context)); } } diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Dumper/DataDumperInterface.php b/data/web/inc/lib/vendor/symfony/var-dumper/Dumper/DataDumperInterface.php index b173bccf3..df05b6af5 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Dumper/DataDumperInterface.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Dumper/DataDumperInterface.php @@ -20,5 +20,8 @@ use Symfony\Component\VarDumper\Cloner\Data; */ interface DataDumperInterface { + /** + * @return string|null + */ public function dump(Data $data); } diff --git a/data/web/inc/lib/vendor/symfony/var-dumper/Dumper/HtmlDumper.php b/data/web/inc/lib/vendor/symfony/var-dumper/Dumper/HtmlDumper.php index 40e97a534..ea09e6819 100644 --- a/data/web/inc/lib/vendor/symfony/var-dumper/Dumper/HtmlDumper.php +++ b/data/web/inc/lib/vendor/symfony/var-dumper/Dumper/HtmlDumper.php @@ -21,6 +21,7 @@ use Symfony\Component\VarDumper\Cloner\Data; */ class HtmlDumper extends CliDumper { + /** @var callable|resource|string|null */ public static $defaultOutput = 'php://output'; protected static $themes = [ @@ -74,19 +75,16 @@ class HtmlDumper extends CliDumper ]; private array $extraDisplayOptions = []; - /** - * {@inheritdoc} - */ - public function __construct($output = null, string $charset = null, int $flags = 0) + public function __construct($output = null, ?string $charset = null, int $flags = 0) { AbstractDumper::__construct($output, $charset, $flags); $this->dumpId = 'sf-dump-'.mt_rand(); - $this->displayOptions['fileLinkFormat'] = ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format'); + $this->displayOptions['fileLinkFormat'] = \ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format'); $this->styles = static::$themes['dark'] ?? self::$themes['dark']; } /** - * {@inheritdoc} + * @return void */ public function setStyles(array $styles) { @@ -94,6 +92,9 @@ class HtmlDumper extends CliDumper $this->styles = $styles + $this->styles; } + /** + * @return void + */ public function setTheme(string $themeName) { if (!isset(static::$themes[$themeName])) { @@ -107,6 +108,8 @@ class HtmlDumper extends CliDumper * Configures display options. * * @param array $displayOptions A map of display options to customize the behavior + * + * @return void */ public function setDisplayOptions(array $displayOptions) { @@ -116,6 +119,8 @@ class HtmlDumper extends CliDumper /** * Sets an HTML header that will be dumped once in the output stream. + * + * @return void */ public function setDumpHeader(?string $header) { @@ -124,6 +129,8 @@ class HtmlDumper extends CliDumper /** * Sets an HTML prefix and suffix that will encapse every single dump. + * + * @return void */ public function setDumpBoundaries(string $prefix, string $suffix) { @@ -131,9 +138,6 @@ class HtmlDumper extends CliDumper $this->dumpSuffix = $suffix; } - /** - * {@inheritdoc} - */ public function dump(Data $data, $output = null, array $extraDisplayOptions = []): ?string { $this->extraDisplayOptions = $extraDisplayOptions; @@ -145,6 +149,8 @@ class HtmlDumper extends CliDumper /** * Dumps the HTML header. + * + * @return string */ protected function getDumpHeader() { @@ -158,19 +164,15 @@ class HtmlDumper extends CliDumper