diff --git a/.docker/dev/nginx/ssl.sh b/.docker/dev/nginx/ssl.sh old mode 100644 new mode 100755 diff --git a/.docker/release/Dockerfile b/.docker/release/Dockerfile index f1ba85139..0e6473191 100644 --- a/.docker/release/Dockerfile +++ b/.docker/release/Dockerfile @@ -1,48 +1,192 @@ +# syntax=docker/dockerfile:1 + +FROM alpine:3.24.3 AS builder +RUN apk add --no-cache php85 php85-json php-phar php-zip +RUN apk add --no-cache npm +RUN npm install -g gulp yarn +WORKDIR /source +COPY package.json yarn.lock ./ +RUN yarn install +COPY . . +# Patch release.php with hotfix from: https://github.com/xgbstar1/snappymail-docker/blob/main/Dockerfile, so that release.php doesn't fail with error +RUN sed -i 's_^if.*rename.*snappymail.v.0.0.0.*$_if (!!system("mv snappymail/v/0.0.0 snappymail/v/{$package->version}")) {_' cli/release.php || true +RUN php release.php +RUN set -eux; \ + VERSION=$( ls build/dist/releases/webmail ); \ + ls -al build/dist/releases/webmail/$VERSION/snappymail-$VERSION.tar.gz; \ + mkdir -p /snappymail; \ + tar -zxvf build/dist/releases/webmail/$VERSION/snappymail-$VERSION.tar.gz -C /snappymail; \ + find /snappymail -type d -exec chmod 550 {} \; ; \ + find /snappymail -type f -exec chmod 440 {} \; ; \ + find /snappymail/data -type d -exec chmod 750 {} \; ; \ + # Remove unneeded files + rm -v /snappymail/README.md /snappymail/_include.php + # Inspired by the original Rainloop dockerfile from youtous on GitLab -FROM php:7.4-fpm-buster +FROM php:8.5-fpm-alpine AS final -ARG FILES_ZIP -LABEL org.label-schema.description="SnappyMail webmail client image using nginx, php-fpm based on Debian Buster" - -ENV UID=991 GID=991 UPLOAD_MAX_SIZE=25M LOG_TO_STDERR=true MEMORY_LIMIT=128M SECURE_COOKIES=true -ENV fpm.pool.clear_env=false +LABEL org.label-schema.description="SnappyMail webmail client image using nginx, php-fpm on Alpine" # Install dependencies such as nginx -RUN mkdir -p /usr/share/man/man1/ /usr/share/man/man3/ /usr/share/man/man7/ && \ - apt-get update -q --fix-missing && \ - apt-get -y upgrade && \ - apt-get install --no-install-recommends -y \ - apt-transport-https gnupg openssl wget curl ca-certificates nginx supervisor sudo \ - unzip libzip-dev libxml2-dev libldb-dev libldap2-dev \ - sqlite3 libsqlite3-dev libsqlite3-0 libpq-dev postgresql-client mariadb-client logrotate \ - zip mlocate libpcre3-dev libicu-dev \ - build-essential chrpath libssl-dev \ - libxft-dev libfreetype6 libfreetype6-dev \ - libpng-dev libjpeg62-turbo-dev \ - libfontconfig1 libfontconfig1-dev \ - && \ - rm -rf /var/lib/apt/lists/* +RUN apk add --no-cache ca-certificates nginx supervisor bash # Install PHP extensions -RUN php -m && \ - docker-php-ext-configure ldap --with-libdir=lib/x86_64-linux-gnu/ && \ - docker-php-ext-configure intl && \ - docker-php-ext-configure gd --with-freetype --with-jpeg && \ - docker-php-ext-install ldap opcache pdo_mysql pdo_pgsql zip intl gd && \ - php -m +# apcu +RUN set -eux; \ + apk add --no-cache --virtual .build-dependencies $PHPIZE_DEPS; \ + pecl install apcu; \ + docker-php-ext-enable apcu; \ + docker-php-source delete; \ + apk del .build-dependencies; + +# gd +RUN set -eux; \ + apk add --no-cache freetype libjpeg-turbo libpng; \ + apk add --no-cache --virtual .deps freetype-dev libjpeg-turbo-dev libpng-dev; \ + docker-php-ext-configure gd --with-freetype --with-jpeg; \ + docker-php-ext-install gd; \ + apk del .deps + +# gmagick +# RUN set -eux; \ +# apk add --no-cache graphicsmagick libgomp; \ +# apk add --no-cache --virtual .deps graphicsmagick-dev libtool; \ +# apk add --no-cache --virtual .build-dependencies $PHPIZE_DEPS; \ +# pecl install gmagick-2.0.6RC1; \ +# docker-php-ext-enable gmagick; \ +# docker-php-source delete; \ +# apk del .build-dependencies; \ +# apk del .deps + +# gnupg +RUN set -eux; \ + apk add --no-cache gnupg gpgme; \ + apk add --no-cache --virtual .deps gpgme-dev; \ + apk add --no-cache --virtual .build-dependencies $PHPIZE_DEPS; \ + pecl install gnupg; \ + docker-php-ext-enable gnupg; \ + docker-php-source delete; \ + apk del .build-dependencies; \ + apk del .deps + +# imagick +RUN set -eux; \ + apk add --no-cache imagemagick libgomp; \ + apk add --no-cache --virtual .deps imagemagick-dev; \ + apk add --no-cache --virtual .build-dependencies $PHPIZE_DEPS; \ + echo | pecl install imagick; \ + docker-php-ext-enable imagick; \ + docker-php-source delete; \ + apk del .build-dependencies; \ + apk del .deps + +# intl +RUN set -eux; \ + apk add --no-cache icu-libs; \ + apk add --no-cache --virtual .deps icu-dev; \ + docker-php-ext-configure intl; \ + docker-php-ext-install intl; \ + apk del .deps + +# ldap +RUN set -eux; \ + apk add --no-cache libldap; \ + apk add --no-cache --virtual .deps openldap-dev; \ + docker-php-ext-configure ldap; \ + docker-php-ext-install ldap; \ + apk del .deps + +# mysql +RUN docker-php-ext-install pdo_mysql + +# postgres +RUN set -eux; \ + apk add --no-cache postgresql-libs; \ + apk add --no-cache --virtual .deps postgresql-dev; \ + docker-php-ext-install pdo_pgsql; \ + apk del .deps + +# redis +RUN set -eux; \ + apk add --no-cache liblzf zstd-libs; \ + apk add --no-cache --virtual .deps zstd-dev; \ + apk add --no-cache --virtual .build-dependencies $PHPIZE_DEPS; \ + pecl install igbinary; \ + docker-php-ext-enable igbinary; \ + pecl install --configureoptions 'enable-redis-igbinary="yes" enable-redis-lzf="yes" enable-redis-zstd="yes"' redis; \ + docker-php-ext-enable redis; \ + docker-php-source delete; \ + apk del .build-dependencies; \ + apk del .deps + +# sqlite +RUN set -eux; \ + apk add --no-cache sqlite-libs; \ + apk add --no-cache --virtual .deps sqlite-dev; \ + docker-php-ext-install pdo_sqlite; \ + apk del .deps + +# tidy +RUN set -eux; \ + apk add --no-cache tidyhtml; \ + apk add --no-cache --virtual .deps tidyhtml-dev; \ + docker-php-ext-install tidy; \ + apk del .deps + +# uuid +RUN set -eux; \ + apk add --no-cache libuuid; \ + apk add --no-cache --virtual .deps util-linux-dev; \ + apk add --no-cache --virtual .build-dependencies $PHPIZE_DEPS; \ + pecl install uuid; \ + docker-php-ext-enable uuid; \ + docker-php-source delete; \ + apk del .build-dependencies; \ + apk del .deps + +# xxtea - Manually install php8 compatible version from https://github.com/xxtea/xxtea-pecl master branch +RUN set -eux; \ + apk add --no-cache --virtual .build-dependencies $PHPIZE_DEPS; \ + wget -q https://github.com/xxtea/xxtea-pecl/tarball/3f5888a29045e12301254151737c5dab4523a1c1 -O xxtea.tar; \ + echo '9cbfd9c27255767deb26ddedf69e738d401d88ac9762d82c8510f9768842ca18 xxtea.tar' | sha256sum -c -; \ + tar -C /usr/src -xvf xxtea.tar; \ + cd /usr/src/xxtea-xxtea-pecl-3f5888a; \ + phpize; \ + ./configure --with-php-config=/usr/local/bin/php-config --enable-xxtea=yes; \ + make install; \ + docker-php-ext-enable xxtea; \ + cd -; \ + rm -fv xxtea.tar; \ + rm -rfv /usr/src/xxtea*; \ + apk del .build-dependencies; + +# zip +RUN set -eux; \ + apk add --no-cache libzip; \ + apk add --no-cache --virtual .deps libzip-dev; \ + docker-php-ext-install zip; \ + apk del .deps # Install snappymail -WORKDIR /tmp -COPY ${FILES_ZIP} . -RUN mkdir /snappymail && \ - unzip -q ${FILES_ZIP} -d /snappymail && \ - find /snappymail -type d -exec chmod 755 {} \; && \ - find /snappymail -type f -exec chmod 644 {} \; && \ - rm -rf ${FILES_ZIP} +# The 'www-data' user/group in alpine is 82:82. The 'nginx' user/group in alpine is 101:101, and is part of www-data group +COPY --chown=www-data:www-data --from=builder /snappymail /snappymail +# Use a custom snappymail data folder +RUN mv -v /snappymail/data /var/lib/snappymail; +# Setup configs +COPY --chown=root:root .docker/release/files / +RUN set -eux; \ + chown www-data:www-data /snappymail/include.php; \ + chmod 440 /snappymail/include.php; \ + chmod +x /entrypoint.sh; \ + # Disable the built-in php-fpm configs, since we're using our own config + mv -v /usr/local/etc/php-fpm.d/docker.conf /usr/local/etc/php-fpm.d/docker.conf.disabled; \ + mv -v /usr/local/etc/php-fpm.d/www.conf /usr/local/etc/php-fpm.d/www.conf.disabled; \ + mv -v /usr/local/etc/php-fpm.d/zz-docker.conf /usr/local/etc/php-fpm.d/zz-docker.conf.disabled; -# Install other content -COPY files / -RUN chmod +x /entrypoint.sh && chmod +x /logrotate-loop.sh -VOLUME /snappymail/data +USER root +WORKDIR /snappymail +VOLUME /var/lib/snappymail EXPOSE 8888 +EXPOSE 9000 +ENTRYPOINT [] CMD ["/entrypoint.sh"] diff --git a/.docker/release/files/entrypoint.sh b/.docker/release/files/entrypoint.sh old mode 100644 new mode 100755 index eed82bf5b..c0ed7df0c --- a/.docker/release/files/entrypoint.sh +++ b/.docker/release/files/entrypoint.sh @@ -1,23 +1,26 @@ #!/bin/sh +set -eu -# Create not root user -groupadd --gid "$GID" php-cli -f -adduser --uid "$UID" --disabled-password --gid "$GID" --shell /bin/bash --home /home/php-cli php-cli --force --gecos "" +DEBUG=${DEBUG:-} +if [ "$DEBUG" = 'true' ]; then + set -x +fi +UPLOAD_MAX_SIZE=${UPLOAD_MAX_SIZE:-25M} +MEMORY_LIMIT=${MEMORY_LIMIT:-128M} +SECURE_COOKIES=${SECURE_COOKIES:-true} +# Disable listening on ipv6 for ipv4-only environments, or nginx will fail to start +if ! ip a | grep 'inet6 ' > /dev/null; then + echo "[INFO] ipv6 is disabled. Configuring nginx to not listen on ipv6" + sed -i '/listen \[::\]:/d' /etc/nginx/nginx.conf +fi # Set attachment size limit sed -i "s//$UPLOAD_MAX_SIZE/g" /usr/local/etc/php-fpm.d/php-fpm.conf /etc/nginx/nginx.conf sed -i "s//$MEMORY_LIMIT/g" /usr/local/etc/php-fpm.d/php-fpm.conf -# Set log output to STDERR if wanted (LOG_TO_STDERR=true) -if [ "$LOG_TO_STDERR" = true ]; then - echo "[INFO] Logging to stderr activated" - sed -i "s/.*error_log.*$/error_log \/dev\/stderr warn;/" /etc/nginx/nginx.conf - sed -i "s/.*error_log.*$/php_admin_value[error_log] = \/dev\/stderr/" /usr/local/etc/php-fpm.d/php-fpm.conf -fi - # Secure cookies -if [ "${SECURE_COOKIES}" = true ]; then +if [ "${SECURE_COOKIES}" = 'true' ]; then echo "[INFO] Secure cookies activated" { echo 'session.cookie_httponly = On'; @@ -26,43 +29,58 @@ if [ "${SECURE_COOKIES}" = true ]; then } > /usr/local/etc/php/conf.d/cookies.ini; fi -# Copy snappymail default config if absent -SNAPPYMAIL_CONFIG_FILE=/snappymail/data/_data_/_default_/configs/application.ini +echo "[INFO] Snappymail version: $( ls /snappymail/snappymail/v )" + +# Set permissions on snappymail data +echo "[INFO] Setting permissions on /var/lib/snappymail" +chown -R www-data:www-data /var/lib/snappymail/ +chmod 550 /var/lib/snappymail/ +find /var/lib/snappymail/ -type d -exec chmod 750 {} \; + +# Create snappymail default config if absent +SNAPPYMAIL_CONFIG_FILE=/var/lib/snappymail/_data_/_default_/configs/application.ini if [ ! -f "$SNAPPYMAIL_CONFIG_FILE" ]; then - echo "[INFO] Creating default Snappymail configuration" - mkdir -p $(dirname $SNAPPYMAIL_CONFIG_FILE) - cp /usr/local/include/application.ini $SNAPPYMAIL_CONFIG_FILE + echo "[INFO] Creating default Snappymail configuration: $SNAPPYMAIL_CONFIG_FILE" + # Run snappymail and exit. This populates the snappymail data directory and generates the config file + # On error, print php exception and exit + EXITCODE= + su - www-data -s /bin/sh -c 'php /snappymail/index.php' > /tmp/out || EXITCODE=$? + if [ -n "$EXITCODE" ]; then + cat /tmp/out + exit "$EXITCODE" + fi fi +echo "[INFO] Overriding values in snappymail configuration: $SNAPPYMAIL_CONFIG_FILE" # Enable output of snappymail logs -if [ "${LOG_TO_STDERR}" = true ]; then - sed -z 's/\; Enable logging\nenable = Off/\; Enable logging\nenable = On/' -i $SNAPPYMAIL_CONFIG_FILE - sed 's/^filename = .*/filename = "errors.log"/' -i $SNAPPYMAIL_CONFIG_FILE - sed 's/^write_on_error_only = .*/write_on_error_only = Off/' -i $SNAPPYMAIL_CONFIG_FILE - sed 's/^write_on_php_error_only = .*/write_on_php_error_only = On/' -i $SNAPPYMAIL_CONFIG_FILE -else - sed -z 's/\; Enable logging\nenable = On/\; Enable logging\nenable = Off/' -i $SNAPPYMAIL_CONFIG_FILE -fi +sed '/^\; Enable logging/{ +N +s/enable = Off/enable = On/ +}' -i $SNAPPYMAIL_CONFIG_FILE +# Redirect snappymail logs to stderr /stdout +sed 's/^filename = .*/filename = "stderr"/' -i $SNAPPYMAIL_CONFIG_FILE +sed 's/^write_on_error_only = .*/write_on_error_only = Off/' -i $SNAPPYMAIL_CONFIG_FILE +sed 's/^write_on_php_error_only = .*/write_on_php_error_only = On/' -i $SNAPPYMAIL_CONFIG_FILE # Always enable snappymail Auth logging sed 's/^auth_logging = .*/auth_logging = On/' -i $SNAPPYMAIL_CONFIG_FILE sed 's/^auth_logging_filename = .*/auth_logging_filename = "auth.log"/' -i $SNAPPYMAIL_CONFIG_FILE sed 's/^auth_logging_format = .*/auth_logging_format = "[{date:Y-m-d H:i:s}] Auth failed: ip={request:ip} user={imap:login} host={imap:host} port={imap:port}"/' -i $SNAPPYMAIL_CONFIG_FILE -# Redirect snappymail logs to stderr /stdout -mkdir -p /snappymail/data/_data_/_default_/logs/ -# empty logs -cp /dev/null /snappymail/data/_data_/_default_/logs/errors.log -cp /dev/null /snappymail/data/_data_/_default_/logs/auth.log -chown -R php-cli:php-cli /snappymail/data/ +sed 's/^auth_syslog = .*/auth_syslog = Off/' -i $SNAPPYMAIL_CONFIG_FILE -# Fix permissions -chown -R $UID:$GID /snappymail/data /var/log /var/lib/nginx -chmod o+w /dev/stdout -chmod o+w /dev/stderr +( + while ! nc -vz -w 1 127.0.0.1 8888 > /dev/null 2>&1; do echo "[INFO] Checking whether nginx is alive"; sleep 1; done + while ! nc -vz -w 1 127.0.0.1 9000 > /dev/null 2>&1; do echo "[INFO] Checking whether php-fpm is alive"; sleep 1; done + # Create snappymail admin password if absent + SNAPPYMAIL_ADMIN_PASSWORD_FILE=/var/lib/snappymail/_data_/_default_/admin_password.txt + if [ ! -f "$SNAPPYMAIL_ADMIN_PASSWORD_FILE" ]; then + echo "[INFO] Creating Snappymail admin password file: $SNAPPYMAIL_ADMIN_PASSWORD_FILE" + wget -T 1 -qO- 'http://127.0.0.1:8888/?/AdminAppData/0/12345/' > /dev/null + echo "[INFO] Snappymail Admin Panel ready at http://localhost:8888/?admin. Login using password in $SNAPPYMAIL_ADMIN_PASSWORD_FILE" + fi - -# Touch supervisord PID file in order to fix permissions -touch /run/supervisord.pid -chown php-cli:php-cli /run/supervisord.pid + wget -T 1 -qO- 'http://127.0.0.1:8888/' > /dev/null + echo "[INFO] Snappymail ready at http://localhost:8888/" +) & # RUN ! -exec sudo -u php-cli -g php-cli /usr/bin/supervisord -c '/supervisor.conf' --pidfile '/run/supervisord.pid' +exec /usr/bin/supervisord -c /supervisor.conf --pidfile /run/supervisord.pid diff --git a/.docker/release/files/etc/logrotate.d/snappymail b/.docker/release/files/etc/logrotate.d/snappymail deleted file mode 100644 index 701631d98..000000000 --- a/.docker/release/files/etc/logrotate.d/snappymail +++ /dev/null @@ -1,5 +0,0 @@ -/snappymail/data/_data_/_default_/logs/* { - size 10M - rotate 0 - missingok -} \ No newline at end of file diff --git a/.docker/release/files/etc/nginx/nginx.conf b/.docker/release/files/etc/nginx/nginx.conf index 1bb643f23..aff3829cf 100644 --- a/.docker/release/files/etc/nginx/nginx.conf +++ b/.docker/release/files/etc/nginx/nginx.conf @@ -11,7 +11,7 @@ http { default_type application/octet-stream; access_log off; - error_log /tmp/ngx_error.log error; + error_log /dev/stderr error; sendfile on; keepalive_timeout 15; @@ -52,6 +52,8 @@ http { server { listen 8888; + listen [::]:8888; + #listen [::]:8888 ipv6only=off; root /snappymail; index index.php; charset utf-8; @@ -95,7 +97,7 @@ http { fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param HTTP_PROXY ""; fastcgi_index index.php; - fastcgi_pass unix:/tmp/php-fpm.sock; + fastcgi_pass 127.0.0.1:9000; fastcgi_intercept_errors on; fastcgi_request_buffering off; fastcgi_param REMOTE_ADDR $http_x_real_ip; diff --git a/.docker/release/files/logrotate-loop.sh b/.docker/release/files/logrotate-loop.sh deleted file mode 100644 index ba1d42469..000000000 --- a/.docker/release/files/logrotate-loop.sh +++ /dev/null @@ -1,113 +0,0 @@ -#!/bin/bash -# ---------------------------------------------------------------------- -# Simple script to invoke logrotate at regular intervals -# ---------------------------------------------------------------------- - -# from https://github.com/misho-kr/docker-appliances/blob/master/nginx-nodejs/logrotate-loop.sh - -LOGROTATE_BIN="logrotate" - -STATE="$HOME/logrotate.state" -CONF="/etc/logrotate.d/snappymail" - -export LOGROTATE_BIN STATE CONF - -RUN_INTERVAL="3600" # every hour - -# helper functions for logging -export FMT="%a %b %d %Y %H:%M:%S GMT%z (%Z)" - -function log_date() { - echo "$(date +"$FMT"): $*" -} - -# ---------------------------------------------------------------------- -# Main loop of the logrotate service: -# -# while True: -# sleep N seconds -# run logrotate -# -# ---------------------------------------------------------------------- - -function logrotate_loop() { - - trap on_terminate TERM INT - - local interval="${1}" - - log_date "====================================================" - log_date - log_date "logrotate service starting (pid=$$)" - log_date "logrotate process will run every ${interval} seconds" - - while true; do - - current_time=$(date "+%s") - next_run_time=$(( current_time + interval )) - - while (( current_time < next_run_time )) - do - logrotate_sleep $(( next_run_time - current_time )) - current_time=$(date "+%s") - done - - logrotate_run - done -} - -# helper function to execute logrotate and pass it the right parameters -function logrotate_run() { - - log_date "logrotate will run now" - ${LOGROTATE_BIN} -s ${STATE} ${CONF} -} - -# ---------------------------------------------------------------------- -# Procedure to idle the execution for a number of seconds -# -# There are two requirements: -# -# - export the PID of the sleep command so that it can be terminated -# in case the logrotate service is being shutdown -# - keep this (bash) process responsive to SIGTERM while in sleep -# mode (normally the signal will be masked and will not be delivered -# until the subprocess completes) -# ---------------------------------------------------------------------- - -proc_sleep_pid="" - -function logrotate_sleep() { - - local sleep_interval=${1} - - log_date "logrotate will sleep for ${sleep_interval} seconds" - - ( exec -a "logrotate: sleep" sleep ${sleep_interval} )& - - proc_sleep_pid=$! - wait ${proc_sleep_pid} -} - -# ---------------------------------------------------------------------- -# Signal handler for logrotate service to make sure the process exits: -# -# - properly by terminating the sleep process that is used to idle -# the service -# - gracefully by writing a message in the log -# ---------------------------------------------------------------------- - -function on_terminate() { - - log_date "logrotate will terminate" - log_date - - kill -TERM ${proc_sleep_pid} - exit 0 -} - -# ---------------------------------------------------------------------- -# main -# ---------------------------------------------------------------------- - -logrotate_loop ${1:-RUN_INTERVAL} diff --git a/.docker/release/files/snappymail/include.php b/.docker/release/files/snappymail/include.php new file mode 100644 index 000000000..53ba30722 --- /dev/null +++ b/.docker/release/files/snappymail/include.php @@ -0,0 +1,3 @@ + diff --git a/.docker/release/files/supervisor.conf b/.docker/release/files/supervisor.conf index da6c6aefe..13a12a290 100644 --- a/.docker/release/files/supervisor.conf +++ b/.docker/release/files/supervisor.conf @@ -1,10 +1,13 @@ [supervisord] nodaemon=true +user=root +logfile=/dev/null +logfile_maxbytes=0 [program:nginx] command=nginx -c /etc/nginx/nginx.conf -g 'daemon off;' process_name=%(program_name)s_%(process_num)02d -user=php-cli +user=root numprocs=1 autostart=true autorestart=false @@ -17,7 +20,7 @@ stderr_logfile_maxbytes=0 [program:php-fpm] command=php-fpm -F process_name=%(program_name)s_%(process_num)02d -user=php-cli +user=root numprocs=1 autostart=true autorestart=false @@ -27,34 +30,11 @@ stdout_logfile_maxbytes=0 stderr_logfile=/dev/stderr stderr_logfile_maxbytes=0 -; reads snappymail logs -[program:snappymail-auth] -command=tail -f /snappymail/data/_data_/_default_/logs/auth.log -stdout_logfile=/dev/stdout -stdout_logfile_maxbytes=0 -stderr_logfile=/dev/stderr -stderr_logfile_maxbytes=0 - -[program:snappymail-errors] -command=tail -f /snappymail/data/_data_/_default_/logs/errors.log -# everything is an error -stdout_logfile=/dev/stderr -stdout_logfile_maxbytes=0 -redirect_stderr=true - -[program:logrotate] -command=/logrotate-loop.sh -autorestart=true -stdout_logfile=/dev/stdout -stdout_logfile_maxbytes=0 -stderr_logfile=/dev/stderr -stderr_logfile_maxbytes=0 - [eventlistener:subprocess-stopped] command=php /listener.php process_name=%(program_name)s_%(process_num)02d -user=php-cli +user=root numprocs=1 events=PROCESS_STATE_EXITED,PROCESS_STATE_STOPPED,PROCESS_STATE_FATAL autostart=true -autorestart=unexpected \ No newline at end of file +autorestart=unexpected diff --git a/.docker/release/files/usr/local/etc/php-fpm.d/php-fpm.conf b/.docker/release/files/usr/local/etc/php-fpm.d/php-fpm.conf index 456fdb798..fbee3d4e0 100644 --- a/.docker/release/files/usr/local/etc/php-fpm.d/php-fpm.conf +++ b/.docker/release/files/usr/local/etc/php-fpm.d/php-fpm.conf @@ -1,15 +1,21 @@ [global] daemonize = no +error_log = /dev/stderr +log_buffering = no [default] -listen = /tmp/php-fpm.sock +listen = 9000 +user = www-data +listen.owner = www-data +listen.group = www-data pm = ondemand pm.max_children = 30 pm.process_idle_timeout = 10s pm.max_requests = 500 catch_workers_output = yes +decorate_workers_output = no chdir = / -php_admin_value[error_log] = /tmp/php_error.log +pm.status_path = /status php_admin_value[log_errors] = On php_admin_value[expose_php] = Off php_admin_value[display_errors] = Off diff --git a/.docker/release/files/usr/local/include/application.ini b/.docker/release/files/usr/local/include/application.ini deleted file mode 100644 index da48c375e..000000000 --- a/.docker/release/files/usr/local/include/application.ini +++ /dev/null @@ -1,305 +0,0 @@ -; SnappyMail configuration file -; Please don't add custom parameters here, those will be overwritten - -[webmail] -; Text displayed as page title -title = "SnappyMail Webmail" - -; Text displayed on startup -loading_description = "SnappyMail" -favicon_url = "" - -; Theme used by default -theme = "Default" - -; Allow theme selection on settings screen -allow_themes = On -allow_user_background = Off - -; Language used by default -language = "en" - -; Admin Panel interface language -language_admin = "en" - -; Allow language selection on settings screen -allow_languages_on_settings = On -allow_additional_accounts = On -allow_additional_identities = On - -; Number of messages displayed on page by default -messages_per_page = 20 - -; Mark message read after N seconds -message_read_delay = 5 - -; File size limit (MB) for file upload on compose screen -; 0 for unlimited. -attachment_size_limit = 2 - -[interface] -show_attachment_thumbnail = On -new_move_to_folder_button = On - -[contacts] -; Enable contacts -enable = Off -allow_sync = Off -sync_interval = 20 -type = "sqlite" -pdo_dsn = "host=127.0.0.1;port=3306;dbname=snappymail" -pdo_user = "root" -pdo_password = "" -suggestions_limit = 30 - -[security] -; Enable CSRF protection (http://en.wikipedia.org/wiki/Cross-site_request_forgery) -csrf_protection = On -custom_server_signature = "SnappyMail" -x_frame_options_header = "DENY" -x_xss_protection_header = "1; mode=block" -openpgp = Off - -; Login and password for web admin panel -admin_login = "admin" -admin_password = "" -admin_totp = "" - -; Access settings -allow_admin_panel = On -hide_x_mailer_header = On -admin_panel_host = "" -admin_panel_key = "admin" -content_security_policy = "" -csp_report = Off -encrypt_cipher = "aes-256-cbc-hmac-sha1" - -[ssl] -; Require verification of SSL certificate used. -verify_certificate = Off - -; Allow self-signed certificates. Requires verify_certificate. -allow_self_signed = On - -; Location of Certificate Authority file on local filesystem (/etc/ssl/certs/ca-certificates.crt) -cafile = "" - -; capath must be a correctly hashed certificate directory. (/etc/ssl/certs/) -capath = "" - -; Location of client certificate file (pem format with private key) on local filesystem -client_cert = "" - -[capa] -contacts = On -quota = On -search = On -search_adv = On -dangerous_actions = On -message_actions = On -attachments_actions = On - -[login] -default_domain = "" - -; Allow language selection on webmail login screen -allow_languages_on_login = On -determine_user_language = On -determine_user_domain = Off -hide_submit_button = On -login_lowercase = On - -; This option allows webmail to remember the logged in user -; once they closed the browser window. -; -; Values: -; "DefaultOff" - can be used, disabled by default; -; "DefaultOn" - can be used, enabled by default; -; "Unused" - cannot be used -sign_me_auto = "DefaultOff" - -[plugins] -; Enable plugin support -enable = Off - -; List of enabled plugins -enabled_list = "" - -[defaults] -; Editor mode used by default (Plain, Html, HtmlForced or PlainForced) -view_editor_type = "Html" - -; layout: 0 - no preview, 1 - side preview, 2 - bottom preview -view_layout = 1 -view_use_checkboxes = On -autologout = 30 -view_html = On -show_images = Off -contacts_autosave = On -mail_use_threads = Off -allow_draft_autosave = On -mail_reply_same_folder = Off - -[logs] -; Enable logging -enable = Off - -; Log messages of set RFC 5424 section 6.2.1 Severity level and higher (0 = highest, 7 = lowest). -; 0 = Emergency -; 1 = Alert -; 2 = Critical -; 3 = Error -; 4 = Warning -; 5 = Notice -; 6 = Informational -; 7 = Debug -level = 4 - -; Logs entire request only if error occured (php requred) -write_on_error_only = Off - -; Logs entire request only if php error occured -write_on_php_error_only = Off - -; Logs entire request only if request timeout (in seconds) occured. -write_on_timeout_only = 0 - -; Required for development purposes only. -; Disabling this option is not recommended. -hide_passwords = On -time_zone = "UTC" -session_filter = "" - -; Log filename. -; For security reasons, some characters are removed from filename. -; Allows for pattern-based folder creation (see examples below). -; -; Patterns: -; {date:Y-m-d} - Replaced by pattern-based date -; Detailed info: http://www.php.net/manual/en/function.date.php -; {user:email} - Replaced by user's email address -; If user is not logged in, value is set to "unknown" -; {user:login} - Replaced by user's login (the user part of an email) -; If user is not logged in, value is set to "unknown" -; {user:domain} - Replaced by user's domain name (the domain part of an email) -; If user is not logged in, value is set to "unknown" -; {user:uid} - Replaced by user's UID regardless of account currently used -; -; {user:ip} -; {request:ip} - Replaced by user's IP address -; -; Others: -; {imap:login} {imap:host} {imap:port} -; {smtp:login} {smtp:host} {smtp:port} -; -; Examples: -; filename = "log-{date:Y-m-d}.txt" -; filename = "{date:Y-m-d}/{user:domain}/{user:email}_{user:uid}.log" -; filename = "{user:email}-{date:Y-m-d}.txt" -; filename = "syslog" -filename = "log-{date:Y-m-d}.txt" - -; Enable auth logging in a separate file (for fail2ban) -auth_logging = Off -auth_logging_filename = "fail2ban/auth-{date:Y-m-d}.txt" -auth_logging_format = "[{date:Y-m-d H:i:s}] Auth failed: ip={request:ip} user={imap:login} host={imap:host} port={imap:port}" - -; Enable auth logging to syslog for fail2ban -auth_syslog = On - -[debug] -; Special option required for development purposes -enable = Off - -[cache] -; The section controls caching of the entire application. -; -; Enables caching in the system -enable = On - -; Additional caching key. If changed, cache is purged -index = "v1" - -; Can be: files, APCU, memcache, redis (beta) -fast_cache_driver = "files" - -; Additional caching key. If changed, fast cache is purged -fast_cache_index = "v1" - -; Browser-level cache. If enabled, caching is maintainted without using files -http = On - -; Browser-level cache time (seconds, Expires header) -http_expires = 3600 - -; Caching message UIDs when searching and sorting (threading) -server_uids = On - -[labs] -allow_prefetch = Off -cache_system_data = On -date_from_headers = On -autocreate_system_folders = Off -allow_message_append = Off -login_fault_delay = 1 -log_ajax_response_write_limit = 300 -allow_html_editor_biti_buttons = Off -allow_ctrl_enter_on_compose = On -try_to_detect_hidden_images = Off -use_app_debug_js = Off -use_mobile_version_for_tablets = Off -use_app_debug_css = Off -use_imap_sort = On -use_imap_force_selection = Off -use_imap_thread = On -use_imap_move = Off -use_imap_expunge_all_on_delete = Off -imap_forwarded_flag = "$Forwarded" -imap_read_receipt_flag = "$ReadReceipt" -imap_body_text_limit = 555000 -imap_message_list_fast_simple_search = On -imap_message_list_count_limit_trigger = 0 -imap_message_list_date_filter = 0 -imap_message_list_permanent_filter = "" -imap_message_all_headers = Off -imap_large_thread_limit = 50 -imap_folder_list_limit = 200 -imap_show_login_alert = On -imap_use_list_status = On -imap_timeout = 300 -smtp_show_server_errors = Off -smtp_timeout = 60 -sieve_auth_plain_initial = On -sieve_allow_fileinto_inbox = Off -sieve_timeout = 10 -sasl_allow_plain = On -sasl_allow_scram_sha = Off -sasl_allow_cram_md5 = Off -mail_func_clear_headers = On -mail_func_additional_parameters = Off -favicon_status = On -folders_spec_limit = 50 -curl_proxy = "" -curl_proxy_auth = "" -in_iframe = Off -force_https = Off -http_client_ip_check_proxy = Off -fast_cache_memcache_host = "127.0.0.1" -fast_cache_memcache_port = 11211 -fast_cache_redis_host = "127.0.0.1" -fast_cache_redis_port = 6379 -use_local_proxy_for_external_images = On -detect_image_exif_orientation = On -cookie_default_path = "" -cookie_default_secure = Off -check_new_messages = On -replace_env_in_configuration = "" -strict_html_parser = Off -boundary_prefix = "" -kolab_enabled = Off -dev_email = "" -dev_password = "" - -[version] -current = "2.15.0" -saved = "Fri, 04 Mar 2022 08:55:26 +0000" diff --git a/.docker/release/test/build_and_test.sh b/.docker/release/test/build_and_test.sh new file mode 100755 index 000000000..f332ad2c2 --- /dev/null +++ b/.docker/release/test/build_and_test.sh @@ -0,0 +1,7 @@ +#!/bin/sh +# This script uses docker buildx to build a docker image, and loads it into the docker daemon. Then it executes ./test.sh to test the docker image +# It is useful for testing release builds in development +set -eu +IMAGE=snappymail/snappymail:test +DOCKER_BUILDX=1 docker build -t "$IMAGE" -f .docker/release/Dockerfile . +.docker/release/test/test.sh "$IMAGE" diff --git a/.docker/release/test/config.yaml b/.docker/release/test/config.yaml new file mode 100644 index 000000000..47cf00ea9 --- /dev/null +++ b/.docker/release/test/config.yaml @@ -0,0 +1,29 @@ +# See: https://github.com/GoogleContainerTools/container-structure-test +# See: https://github.com/GoogleContainerTools/container-structure-test/issues/78 +schemaVersion: 2.0.0 +commandTests: + - name: Integration test + command: /bin/sh + args: + - -c + - | + set -eux + DEBUG=true /entrypoint.sh > /tmp/test 2>&1 & + sleep 5 + cat /tmp/test + pidof supervisord + pidof nginx + pidof php-fpm + ls -al /var/lib/snappymail/_data_/_default_/configs/application.ini + ls -al /var/lib/snappymail/_data_/_default_/admin_password.txt + nc -vz 127.0.0.1 8888 + nc -vz 127.0.0.1 9000 + wget -S -T 3 -O /dev/null http://127.0.0.1:8888 + kill `pidof supervisord` +metadataTest: + exposedPorts: ["8888", "9000"] + volumes: ["/var/lib/snappymail"] + entrypoint: [] + cmd: ["/entrypoint.sh"] + workdir: /snappymail + user: root diff --git a/.docker/release/test/test.sh b/.docker/release/test/test.sh new file mode 100755 index 000000000..1981cb358 --- /dev/null +++ b/.docker/release/test/test.sh @@ -0,0 +1,10 @@ +#!/bin/sh +# This script tests a given docker image using https://github.com/GoogleContainerTools/container-structure-test +set -eu +SCRIPT_DIR=$( cd "$(dirname "$0")" && pwd ) +IMAGE=${1:-} +echo "Testing image: $IMAGE" +docker run --rm -i \ + -v /var/run/docker.sock:/var/run/docker.sock:ro \ + -v "$SCRIPT_DIR/config.yaml:/config.yaml:ro" \ + gcr.io/gcp-runtimes/container-structure-test:latest test --image "$IMAGE" --config config.yaml diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000..16ef81459 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,2 @@ +/.git +/node_modules diff --git a/.eslintrc.js b/.eslintrc.js index 80846798b..e22cb986d 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -3,7 +3,7 @@ module.exports = { // extends: ['eslint:recommended', 'plugin:prettier/recommended'], extends: ['eslint:recommended'], parserOptions: { - ecmaVersion: 6, + ecmaVersion: 11, sourceType: 'module' }, env: { @@ -27,8 +27,6 @@ module.exports = { 'SquireUI': "readonly", // node_modules/knockout but dev/External/ko.js is used 'ko': "readonly", - // dev/External/ifvisible.js - 'ifvisible': "readonly", // vendors/routes/ 'hasher': "readonly", 'Crossroads': "readonly", @@ -37,10 +35,17 @@ module.exports = { // vendors/bootstrap/bootstrap.native.js 'BSN': "readonly", // Mailvelope - 'mailvelope': "readonly" + 'mailvelope': "readonly", + // Punycode + 'IDN': "readonly", + // Turndown + 'TurndownService': "readonly", + // Marked + 'marked': "readonly" }, // http://eslint.org/docs/rules/ rules: { + 'no-cond-assign': 0, // plugins 'no-mixed-spaces-and-tabs': 'off', 'max-len': [ diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index fc1bece3e..b37d3418e 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1,2 +1,2 @@ -community_bridge: SnappyMail +github: the-djmaze custom: ["https://www.paypal.me/thedjmaze", "https://snappymail.eu"] diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 98e5ea01f..998692964 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -23,13 +23,16 @@ A clear and concise description of what you expected to happen. **Screenshots** If applicable, add screenshots to help explain your problem. -**Desktop (please complete the following information):** - - Browser [e.g. chromium 89, firefox 86, safari 14] - - SnappyMail Version [e.g. 2.3.4] +**Please complete the following information:** +- Browser: [e.g. chromium 100, firefox 100, safari 14, mobile] +- IMAP daemon: [e.g. courier, dovecot] +- PHP version: +- SnappyMail Version: +- Mode: [e.g. standalone, nextcloud, cyberpanel, docker] -**Mobile (please complete the following information):** - - Browser [e.g. stock browser, chrome 87, firefox 86, safari 14] - - SnappyMail Version [e.g. 2.3.4] +**Debug/logging information** +[Read here how to log](https://github.com/the-djmaze/snappymail/wiki/FAQ#how-do-i-enable-logging) +- [ ] I've placed them here (few lines) or as attachments (many lines) **Additional context** Add any other context about the problem here. diff --git a/.github/workflows/docker-pr.yml b/.github/workflows/docker-pr.yml new file mode 100644 index 000000000..af069cdf6 --- /dev/null +++ b/.github/workflows/docker-pr.yml @@ -0,0 +1,93 @@ +name: docker-pr + +on: + pull_request: + branches: + - master + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + + # This step generates the docker tags + - name: Docker meta + id: meta + uses: docker/metadata-action@v4 + env: + # This env var ensures {{sha}} is a real commit SHA for type=ref,event=pr + DOCKER_METADATA_PR_HEAD_SHA: 'true' + with: + images: | + djmaze/snappymail + ghcr.io/${{ github.repository }} + # type=ref,event=pr generates tag(s) on PRs only. E.g. 'pr-123', 'pr-123-abc0123' + tags: | + type=ref,event=pr + type=ref,suffix=-{{sha}},event=pr + # The rest of the org.opencontainers.image.xxx labels are dynamically generated + labels: | + org.opencontainers.image.description=SnappyMail + org.opencontainers.image.licenses=AGPLv3 + + # See: https://github.com/docker/build-push-action/blob/v2.6.1/docs/advanced/cache.md#github-cache + - name: Set up QEMU + uses: docker/setup-qemu-action@v2 + + - name: Set up Docker Buildx + id: buildx + uses: docker/setup-buildx-action@v2 + + - name: Cache Docker layers + uses: actions/cache@v3 + with: + path: /tmp/.buildx-cache + key: ${{ runner.os }}-buildx-${{ github.sha }} + restore-keys: | + ${{ runner.os }}-buildx- + + # See: https://github.com/docker/buildx/issues/59 + - name: Build + id: build + uses: docker/build-push-action@v3 + with: + context: '.' + file: ./.docker/release/Dockerfile + platforms: linux/amd64 + push: false + load: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=local,src=/tmp/.buildx-cache + cache-to: type=local,dest=/tmp/.buildx-cache-new,mode=max + + - name: Docker images + run: | + docker images + + - name: Test + run: | + TAG=$( echo "${{ steps.meta.outputs.tags }}" | head -n1 ) + .docker/release/test/test.sh "$TAG" + + - name: Build all archs + uses: docker/build-push-action@v3 + with: + context: '.' + file: ./.docker/release/Dockerfile + platforms: linux/386,linux/amd64,linux/arm64 + push: false + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=local,src=/tmp/.buildx-cache + cache-to: type=local,dest=/tmp/.buildx-cache-new,mode=max + + # Temp fix + # https://github.com/docker/build-push-action/issues/252 + # https://github.com/moby/buildkit/issues/1896 + - name: Move cache + run: | + rm -rf /tmp/.buildx-cache + mv /tmp/.buildx-cache-new /tmp/.buildx-cache diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml new file mode 100644 index 000000000..b957e2fc8 --- /dev/null +++ b/.github/workflows/docker.yml @@ -0,0 +1,117 @@ +name: docker + +on: + push: + tags: + - 'v2.*' + +# This is needed to push to GitHub Container Registry. See https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry +permissions: + contents: read + packages: write + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + + # This step generates the docker tags + - name: Docker meta + id: meta + uses: docker/metadata-action@v4 + env: + # This env var ensures {{sha}} is a real commit SHA for type=ref,event=pr + DOCKER_METADATA_PR_HEAD_SHA: 'true' + with: + images: | + djmaze/snappymail + ghcr.io/${{ github.repository }} + # type=ref,event=branch generates tag(s) on branch only. E.g. 'master', 'master-abc0123' + # type=ref,event=tag generates tag(s) on tags only. E.g. 'v0.0.0', 'v0.0.0-abc0123', and 'latest' + tags: | + type=ref,event=branch + type=ref,event=tag + # The rest of the org.opencontainers.image.xxx labels are dynamically generated + labels: | + org.opencontainers.image.description=SnappyMail + org.opencontainers.image.licenses=AGPLv3 + + # See: https://github.com/docker/build-push-action/blob/v2.6.1/docs/advanced/cache.md#github-cache + - name: Set up QEMU + uses: docker/setup-qemu-action@v2 + + - name: Set up Docker Buildx + id: buildx + uses: docker/setup-buildx-action@v2 + + - name: Cache Docker layers + uses: actions/cache@v3 + with: + path: /tmp/.buildx-cache + key: ${{ runner.os }}-buildx-${{ github.sha }} + restore-keys: | + ${{ runner.os }}-buildx- + + - name: Login to Docker Hub registry + if: startsWith(github.ref, 'refs/tags/') # Login only on tags + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Login to GitHub Container Registry + if: startsWith(github.ref, 'refs/tags/') # Login only on tags + uses: docker/login-action@v2 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + # See: https://github.com/docker/buildx/issues/59 + - name: Build + id: build + uses: docker/build-push-action@v3 + with: + context: '.' + file: ./.docker/release/Dockerfile + platforms: linux/amd64 + push: false + load: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=local,src=/tmp/.buildx-cache + cache-to: type=local,dest=/tmp/.buildx-cache-new,mode=max + + - name: Docker images + run: | + docker images + + - name: Test + run: | + TAG=$( echo "${{ steps.meta.outputs.tags }}" | head -n1 ) + .docker/release/test/test.sh "$TAG" + + - name: Build and push + id: build-and-push + uses: docker/build-push-action@v3 + with: + context: '.' + file: ./.docker/release/Dockerfile + # TODO: Add more arches? + # platforms: linux/386,linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64,linux/s390x + platforms: linux/386,linux/amd64,linux/arm64 + push: ${{ startsWith(github.ref, 'refs/tags/') }} # Push only on tags + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=local,src=/tmp/.buildx-cache + cache-to: type=local,dest=/tmp/.buildx-cache-new,mode=max + + # Temp fix + # https://github.com/docker/build-push-action/issues/252 + # https://github.com/moby/buildkit/issues/1896 + - name: Move cache + run: | + rm -rf /tmp/.buildx-cache + mv /tmp/.buildx-cache-new /tmp/.buildx-cache diff --git a/.gitignore b/.gitignore index ae906552b..5f49d65d5 100644 --- a/.gitignore +++ b/.gitignore @@ -12,10 +12,12 @@ /.docker/dev/mail/config /.docker/dev/nginx/ssl/* !/.docker/dev/nginx/ssl/.gitempty +/.docker/release/snappymail-*.zip /dist /data /MULTIPLY /include.php +/issues .idea/ .env /test @@ -23,6 +25,8 @@ /vendors/knockout/spec /vendors/openpgp-5 !/vendors/openpgp-5/dist +/vendors/squire2 +!/vendors/squire2/dist /vendors/vanillaqr.js/ /integrations/nextcloud/rainloop /integrations/owncloud/rainloop diff --git a/.gitmodules b/.gitmodules index cfb771834..ccf1009a6 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,7 @@ [submodule "vendors/openpgp-5"] path = vendors/openpgp-5 url = git@github.com:the-djmaze/openpgpjs.git +[submodule "vendors/squire2"] + path = vendors/squire2 + url = git@github.com:the-djmaze/Squire.git + branch = snappymail diff --git a/.htaccess b/.htaccess index 0e6142e36..71041371a 100644 --- a/.htaccess +++ b/.htaccess @@ -1,7 +1,15 @@ + + AcceptPathInfo On + + RewriteEngine On # Redirect cPanel RewriteRule cpsess.* https://%{HTTP_HOST}/ [L,R=301] + + RewriteCond %{REQUEST_FILENAME} !-f + RewriteCond %{REQUEST_FILENAME} !-d + RewriteRule ^(.+)$ index.php/$1 [L,QSA] @@ -23,10 +31,9 @@ # Header set Cache-Control "public, max-age=31536000" # Header set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self' data:; style-src 'self' 'unsafe-inline'" # Header set Referrer-Policy "no-referrer" - Header set Strict-Transport-Security "max-age=31536000" +# Header set Strict-Transport-Security "max-age=31536000" Header set imagetoolbar "no" # Header set X-Content-Type-Options "nosniff" -# Header set X-Frame-Options "DENY" # Header set X-XSS-Protection "1; mode=block" Header set Service-Worker-Allowed "/" diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 000000000..d31a1b771 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,2422 @@ +## 2.38.2 – 2024-10-09 +### Fixed +- error '$index is not defined' in Settings > Accounts + [#1797](https://github.com/the-djmaze/snappymail/issues/1797) + + +## 2.38.1 – 2024-10-08 + +### Added +- Admin - Extensions search filter +- Options to unset current font family and size + [#1726](https://github.com/the-djmaze/snappymail/issues/1726) +- Option to allow insecure cryptkey + [#1746](https://github.com/the-djmaze/snappymail/issues/1746) +- Save vCard FN property + [#1761](https://github.com/the-djmaze/snappymail/issues/1761) +- Docker Nginx should listen on IPv6 addresses in addition to IPv4 + [#1770](https://github.com/the-djmaze/snappymail/issues/1770) +- Full-screen Message View on Double-Click + [#1787](https://github.com/the-djmaze/snappymail/issues/1787) + +### Changed +- Use the custom Squire as submodule vendors/squire2 +- Disallow noembed and noframes HTML elements +- Keep 1 space between HTML elements in compressed templates +- Squire: sanitizeToDOMFragment now uses cleanHTML() +- Squire: improved handling of BR elements + [#1389](https://github.com/the-djmaze/snappymail/issues/1389) +- Nextcloud border-radius by @gnilebein + [#1790](https://github.com/the-djmaze/snappymail/pull/1790) +- Compose window sentFolder handling for + [#1793](https://github.com/the-djmaze/snappymail/pull/1793) +- Update Portuguese by @ner00 +- Update Polish by @tinola +- Update French by @hguilbert +- Update Portuguese (Brazil) by @mstolf + +### Fixed +- Composer dialog scroll got broken in v2.28 +- Composer dialog "from" triangle button wrong position due to font changes +- Admin - Config `search` should be ko.observable() not ko.observableArray() +- Squire: paste images + [#1389](https://github.com/the-djmaze/snappymail/issues/1389) +- Domain whitelist failures on login + [#1706](https://github.com/the-djmaze/snappymail/issues/1706) +- Sieve parse errors +- Sieve support `index` was not optional for + [#1709](https://github.com/the-djmaze/snappymail/issues/1709) +- Pagination problem for large mailbox after 2.36.1 + [#1716](https://github.com/the-djmaze/snappymail/issues/1716) +- Undefined constant "LOG_ERROR" + [#1754](https://github.com/the-djmaze/snappymail/issues/1754) +- Search Filter Capital "B" not working + [#1780](https://github.com/the-djmaze/snappymail/issues/1780) +- PHP 8.4: Implicitly nullable parameter declarations deprecated + + +## 2.38.0 – 2024-09-16 + +### Added +- Remove `tel:` links when converting HTML to plain + [#1724](https://github.com/the-djmaze/snappymail/issues/1724) +- Convert HTML to Markdown instead of plain, by using [Turndown](https://github.com/mixmark-io/turndown) + [#1604](https://github.com/the-djmaze/snappymail/issues/1604) +- Check HTMLInputElement.validity() for + [#1733](https://github.com/the-djmaze/snappymail/issues/1733) + +### Changed +- Use a modified [Squire 2.3.2](https://github.com/the-djmaze/Squire/commits/snappymail/) +- cleanHtml use allowedTags instead of disallowedTags and improved CSS handling +- Update Portuguese by @ner00 + +### Fixed +- mXSS exploit found by SonarSource + [CVE-2024-45800](https://github.com/the-djmaze/snappymail/security/advisories/GHSA-2rq7-79vp-ffxm) +- Call to a member function Email() on null + [#1706](https://github.com/the-djmaze/snappymail/issues/1706) +- IMAP capabilities via IMAP Proxy + [#1725](https://github.com/the-djmaze/snappymail/issues/1725) +- Messages on page setting is not validated against 999 max + [#1733](https://github.com/the-djmaze/snappymail/issues/1733) + + +## 2.37.3 – 2024-08-27 + +### Added +- Mark images with width=1 as tracking pixel +- Show warning in Admin -> About when PHP runs in 32bit +- Edit ACL rules + [#157](https://github.com/the-djmaze/snappymail/issues/157) +- Show GnuPG version for + [#1560](https://github.com/the-djmaze/snappymail/issues/1560) +- Make sure only scalar values are allowed in $_ENV for + [#1560](https://github.com/the-djmaze/snappymail/issues/1560) +- Change minimum new mail check interval + [#1678](https://github.com/the-djmaze/snappymail/issues/1678) +- Sieve editor does not support "index" extension + [#1709](https://github.com/the-djmaze/snappymail/issues/1709) + +### Changed +- Improved domain autoconfig interaction +- MS autodiscover priorities DNS over subdomain +- Simplify sieve scripts list + [#1675](https://github.com/the-djmaze/snappymail/issues/1675) +- Handling of (token) errors due to + [#1706](https://github.com/the-djmaze/snappymail/issues/1706) +- Sabre/Xml to v4.0.5 +- Update Chinese by @Artoria2e5 +- Update French by @hguilbert + +### Fixed +- Thread sorting visible after disabling the imap capability + [#1574](https://github.com/the-djmaze/snappymail/issues/1574) +- Creating new message impossible as long as a draft exists? + [#1710](https://github.com/the-djmaze/snappymail/issues/1710) +- InvalidToken error at login + [#1706](https://github.com/the-djmaze/snappymail/issues/1706) + +### Nextcloud +- Force Nextcloud personal language by default + [#1428](https://github.com/the-djmaze/snappymail/issues/1428) + + +## 2.37.2 – 2024-08-13 + +### Added +- Validate Fetch JSON response + +### Fixed +- PATH_INFO bug due to Office365 OAuth login +- Prevent logout loop on error + +### Nextcloud +- Failed loading due to Office365 OAuth2 attempt + [#1703](https://github.com/the-djmaze/snappymail/issues/1703) + + +## 2.37.1 – 2024-08-12 + +### Fixed +- Gulp v5 broke the fonts + +### Nextcloud +- Support v30 + + +## 2.37.0 – 2024-08-12 + +### Added +- JavaScript event `rl-vm-visible` +- Detailed error message on account switch failure for + [#1594](https://github.com/the-djmaze/snappymail/issues/1594) +- Workarounds for Microsoft OAuth2 (currently requires Apache AcceptPathInfo) + [#1645](https://github.com/the-djmaze/snappymail/issues/1645) +- Support "mark for deletion" + [#1657](https://github.com/the-djmaze/snappymail/issues/1657) by @smsoft-ru +- Invoke "Update Identity" pop up right after login (when not initialized) + [#1689](https://github.com/the-djmaze/snappymail/issues/1689) +- Keyboard shortcut for "Swap default (background) color" + [#1690](https://github.com/the-djmaze/snappymail/issues/1690) + +### Changed +- Updated gulp to v5 +- Replaced vulnerable gulp-header with gulp-append-prepend +- Removed abandoned vulnerable rollup-plugin-html +- Align save button in admin security settings +- Made registerProtocolHandler('mailto') optional by activating at Settings -> General +- Improved InvalidToken handling for + [#1653](https://github.com/the-djmaze/snappymail/issues/1653) +- Cleanup localizations +- Update French by @hguilbert +- Update German by @tkasch +- Update Polish by @tinola +- Update Portuguese by @ner00 + +### Fixed +- prevent multiple afterShow() and afterHide() due to `transitionend` on multiple CSS properties +- Attempt to read property "smimeSigned" on null +- Refreshing mail list doesn't update current message + [#1654](https://github.com/the-djmaze/snappymail/issues/1654) +- Deletion of CACHE folder causing error + [#1660](https://github.com/the-djmaze/snappymail/issues/1660) +- Multiple line breaks are not displayed + [#1666](https://github.com/the-djmaze/snappymail/issues/1666) +- RainLoop\Exceptions\ClientException::__construct(): Argument #2 ($oPrevious) must be of type ?Throwable, string given + [#1686](https://github.com/the-djmaze/snappymail/issues/1686) +- SpamAssassin Division by zero + [#1694](https://github.com/the-djmaze/snappymail/issues/1694) +- Failed to parse RFC 2822 date '6 Jul 2024 16:42:09 +0200' + [#1694](https://github.com/the-djmaze/snappymail/issues/1694) +- Fix capabilities when THREAD is disabled + [#1698](https://github.com/the-djmaze/snappymail/pull/1698) by @akhil1508 + +### Nextcloud +- Failed loading due to incorrect `app_path` +- Bugfix language detection +- Allow multi-account in nc with oauth login + [#1699](https://github.com/the-djmaze/snappymail/pull/1699) by @akhil1508 + + +## 2.36.4 – 2024-06-25 + +### Added +- Customize private key passphrase expiration interval + [#1545](https://github.com/the-djmaze/snappymail/discussions/1545) +- AdvancedSearch support for filtering mails before a given date + [#1606](https://github.com/the-djmaze/snappymail/pull/1606) by @codiflow +- Control valid spam and virus headers + [#1607](https://github.com/the-djmaze/snappymail/issues/1607) +- Remember S/MIME private Key without function + [#1611](https://github.com/the-djmaze/snappymail/issues/1611) +- Resize compose dialog +- Magnetic theme + [#1637](https://github.com/the-djmaze/snappymail/pull/1637) by @TheCuteFoxxy + +### Changed +- Improved signing messages by allowing to choose between the options +- Improved language detection code +- More detailed Decrypt errors +- Update French by @hguilbert +- Update Polish by @tinola +- Update Portuguese by @ner00 +- Update Spanish by @huloza + +### Fixed +- Default language error +- Undefined $sEmail in DoAdminDomainMatch +- Handling Autocrypt header failed on `=` + [#1608](https://github.com/the-djmaze/snappymail/issues/1608) +- Blank lines are inserted when editing draft + [#1609](https://github.com/the-djmaze/snappymail/issues/1609) +- Workaround Cyrus MAILBOXID bug (disable OBJECTID capability by default due to impact) + [#1640](https://github.com/the-djmaze/snappymail/issues/1640) +- Workaround HTML with multiple body elements or MIME with multiple text/html + [#1641](https://github.com/the-djmaze/snappymail/issues/1641) + +### Nextcloud +- OIDC stay logged in + [#1620](https://github.com/the-djmaze/snappymail/pull/1620) by @avinash-0007 + + +## 2.36.3 – 2024-05-27 + +### Changed +- UserAuth prevent plugin errors (like the Nextcloud plugin did) + +### Fixed +- Undefined variable $aTokenData + [#1567](https://github.com/the-djmaze/snappymail/issues/1567) + + +## 2.36.2 – 2024-05-26 + +### Added +- "copy to" action in menu's for + [#1559](https://github.com/the-djmaze/snappymail/issues/1559) +- Log signal info for + [#1569](https://github.com/the-djmaze/snappymail/issues/1569) +- OpenPGP.js automatically import backup keys from server + +### Changed +- Improved "remember me" cookie handling +- Update Basque by @Thadah +- Update Portuguese by @ner00 + +### Fixed +- "Account already exists" + [#1561](https://github.com/the-djmaze/snappymail/issues/1561) +- Properly escape path separator in tar.php file list regex + [#1562](https://github.com/the-djmaze/snappymail/pull/1562) by @sevmonster +- Prevent mkdir() error + [#1565](https://github.com/the-djmaze/snappymail/issues/1565) +- SCRAM Exception when trying to log in to SMTP + [#1575](https://github.com/the-djmaze/snappymail/issues/1575) +- Error when redirected back to instance after Gmail OAuth + [#1580](https://github.com/the-djmaze/snappymail/issues/1580) +- Uncaught TypeError: hasPublicKeyForEmails(...).then is not a function + [#1589](https://github.com/the-djmaze/snappymail/issues/1589) +- Undefined variable $sFilename +- GPG/PGP exec() return false handling + +### Nextcloud +- OIDC login active again + [#1572](https://github.com/the-djmaze/snappymail/pull/1572) by @avinash-0007 + + +## 2.36.1 – 2024-04-23 + +### Added +- Autoconfig detect through DNS SRV (RFC 6186 & 8314) and disable MX +- Have I Been Pwned class to check breached passwords and email addresses +- Handle RFC 5987 in Content-Disposition header +- Ignore text/x-amp-html +- Show SMTP error to user + [#1521](https://github.com/the-djmaze/snappymail/issues/1521) +- OAuth2 for login using gmail (and others) + +### Changed +- logMask all AUTHENTICATE requests +- ErrorTip use white-space: pre +- Simplify LoginProcess handling +- ES2020 everywhere (require Safari 13.1) +- Modified Squire to be more in line with v2.2.8 +- CSS set min-width for .attachmentParent and .flagParent to line them up +- cPanel use extension login-cpanel instead of login-remote +- Improved login credentials handling +- Speedup Knockout a bit and removed `with($context)` scope +- Update Belarusian by @spoooyders +- Update Chinese by @mayswind +- Update French by @hguilbert +- Update Polish by @tinola +- Update Portuguese by @ner00 + +### Fixed +- Content encoding and type detection in JavaScript could fail due to case-sensitivity. +- Extensions set logger failed +- GnuPG check open_basedir and if shell_exec is disabled + [#1385](https://github.com/the-djmaze/snappymail/issues/1385) + [#1496](https://github.com/the-djmaze/snappymail/issues/1496) + [#1555](https://github.com/the-djmaze/snappymail/issues/1555) +- Hide pagination when search result has no messages +- Prevent mbstring error before setup.php +- Prevent MessagesPerPage Infinity + [#1540](https://github.com/the-djmaze/snappymail/issues/1540) +- Reseal CryptKey failed + [#1543](https://github.com/the-djmaze/snappymail/issues/1543) + +### Nextcloud +- Add an occ command to set up the login settings + [#1552](https://github.com/the-djmaze/snappymail/issues/1552) + + +## 2.36.0 – 2024-03-18 + +### Added +- Allow setting the supported THREAD algorithm +- Icon to system folders +- Remove remembered password after 15 minutes of inactivity + [#1142](https://github.com/the-djmaze/snappymail/issues/1142) +- Swap background and text color for unreadable text on dark background + [#1486](https://github.com/the-djmaze/snappymail/issues/1486) +- Generate TOTP code at ?Admin -> Security + [#1501](https://github.com/the-djmaze/snappymail/issues/1501) +- Button to change S/MIME private key passphrase + [#1505](https://github.com/the-djmaze/snappymail/issues/1505) +- Belarusian + [#1512](https://github.com/the-djmaze/snappymail/pull/1512) by @spoooyders +- Log some domain idn_to_ascii issues + [#1513](https://github.com/the-djmaze/snappymail/issues/1513) + +### Changed +- On folder/mailbox rename, also rename all children instead of reloading all +- Seal MainAccount CryptKey and on error ask old login passphrase to reseal key. +- Moved cache drivers outside core into extensions +- Sieve always allow fileinto INBOX + [#1510](https://github.com/the-djmaze/snappymail/issues/1510) +- Moved application.ini `sieve_auth_plain_initial` to per domain config +- Languages use rfc5646, by using the shortest ISO 639 code by default +- Update French by @hguilbert +- Update Portuguese by @ner00 + +### Fixed +- On folder/mailbox rename, the old fullName must be removed from cache +- On folder/mailbox rename, the checkable option was not renamed +- Sort accounts drag & drop +- S/MIME encrypted and opaque signed not visible + [#1450](https://github.com/the-djmaze/snappymail/issues/1450) +- Wrong last UID of thread + [#1507](https://github.com/the-djmaze/snappymail/issues/1507) +- Creation of dynamic property SnappyMail\DAV\Client::$HTTP + [#1509](https://github.com/the-djmaze/snappymail/issues/1509) +- "Download as ZIP" fails for messages + [#1514](https://github.com/the-djmaze/snappymail/issues/1514) +- SMTP "Authentication failed" when IMAP uses `shortLogin` and SMTP not + [#1517](https://github.com/the-djmaze/snappymail/issues/1517) + + +## 2.35.4 – 2024-03-16 + +### Added +- \SnappyMail\IDN::toAscii() + +### Changed +- OpenPGP.js to v5.11.1 +- punycode.js lowercase domain names +- application.ini `login_lowercase` removed and now configurable per domain JSON `lowerLogin` +- Update Portuguese by @ner00 + +### Fixed +- Raise JS TypeEroor "toLowerCase" after update + [#1491](https://github.com/the-djmaze/snappymail/issues/1491) +- Call to undefined function shell_exec + [#1496](https://github.com/the-djmaze/snappymail/issues/1496) +- Download attachments as ZIP doesn't work for PGP encrypted mail + [#1499](https://github.com/the-djmaze/snappymail/issues/1499) +- Importing or downloading a PGP public key attachment from a PGP encrypted message doesn't work + [#1500](https://github.com/the-djmaze/snappymail/issues/1500) +- VCard PHP Notice: Undefined index: ENCODING + +### Nextcloud +- Changed stored password handling +- Can't login from nextcloud with 2.35.3 bug Nextcloud + [#1490](https://github.com/the-djmaze/snappymail/issues/1490) + + +## 2.35.3 – 2024-03-12 + +### Added +- GnuPG can be disabled +- Missing strings for localization inside identity popup (Cryptography > S/MIME) + [#1458](https://github.com/the-djmaze/snappymail/issues/1458) +- Automatically verify PGP and S/MIME signed messages +- TNEFDecoder for + [#1012](https://github.com/the-djmaze/snappymail/discussions/1012) +- RTF to HTML converter for + [#1012](https://github.com/the-djmaze/snappymail/discussions/1012) +- Polyfill for PHP ctype + [#1250](https://github.com/the-djmaze/snappymail/issues/1250) + +### Changed +- `new Error()` to `Error()` +- Reduce KnockoutJS footprint by removing unused code +- CSS reposition rainloopErrorTip location +- Improved error handling on PGP and S/MIME decrypt +- Improved OpenPGP.js import keys +- Use Identity S/MIME key and certificate from server instead of POST +- application.ini `[webmail]language_admin` to `[admin_panel]language` +- application.ini `[security]admin_panel_host` to `[admin_panel]host` +- application.ini `[security]admin_panel_key` to `[admin_panel]key` +- Drop deprecated Domain::SetConfig() +- Internationalized domain names are now handled as punycode +- Cacher->Get() can now return NULL +- Update French by @hguilbert +- Update Polish by @tinola +- Update Portuguese by @ner00 + +### Fixed +- Handling of Internationalized Domain Names in several areas +- Decrypt error message +- Stalwart ManageSieve Error 352 when getting Filters + [#1455](https://github.com/the-djmaze/snappymail/issues/1455) +- Nextcloud V25+ theme slightly broken + [#1463](https://github.com/the-djmaze/snappymail/issues/1463) +- PGP decryption fails with "Not armored text" + [#1462](https://github.com/the-djmaze/snappymail/issues/1462) +- AUTH_BASIC falling through as AUTH_BEARER; change AUTH_BEARER to a different value + [#1461](https://github.com/the-djmaze/snappymail/issues/1461) +- SetPassword expects \SnappyMail\SensitiveString +- Crash on importing corrupt OpenPGP keys +- Crash on old browsers instead of showing error +- Ignore popups on logoutReload() + [#1467](https://github.com/the-djmaze/snappymail/issues/1467) +- Custom SASLMechanisms fail in IMAP when the connection is secure + [#1484](https://github.com/the-djmaze/snappymail/pull/1484) by @botsarenthuman + + +## 2.35.2 – 2024-02-27 + +### Added +- GnuPG error handling +- Missing strings for localization inside identity popup (Cryptography > S/MIME) + [#1458](https://github.com/the-djmaze/snappymail/issues/1458) + +### Changed +- Update Portuguese by @ner00 + +### Fixed +- Drop support for gnupg PECL extension as it fails with "no passphrase" issues +- Error 352 when getting Filters + [#1455](https://github.com/the-djmaze/snappymail/issues/1455) + +### Nextcloud +- SetPassword(): Argument #1 must be of type SensitiveString, string given + [#1456](https://github.com/the-djmaze/snappymail/issues/1456) + + +## 2.35.1 – 2024-02-26 + +### Added +- Search functionality in Admin -> Config +- Cache S/MIME passphrases when "remember" is checked +- Import S/MIME certificate popup +- pre-verify S/MIME opaque signed messages so we have a body to view +- Sort PGP keys and S/MIME certificates on email address +- Optionally use existing private key to generate S/MIME certificate + +### Changed +- Better handling to detect which PGP or S/MIME sign/encrypt to use +- Improved StorageType handling +- Cleanup and improved Capa handling +- OPEN_PGP should be OPENPGP as it is one word +- Use get_debug_type() instead of gettype() +- Require OpenSSL due to S/MIME +- AbstractProvider::IsActive() is now an abstract method and must be defined in child class +- Make better use of SnappyMail\SensitiveString +- Update Polish translation by @tinola + +### Fixed +- Verify S/MIME signatures got broken allong the way while implementing this +- Generate S/MIME self-signed certificate failed to keep existing private key +- MIME parser RegExp didn't escape boundary which caused issues +- TypeError: b64Encode(...).match(...) is null on saving compose draft +- Fix timestampToString() for future dates + + +## 2.35.0 – 2024-02-20 + +### Added +- S/MIME support + [#259](https://github.com/the-djmaze/snappymail/issues/259) + +### Changed +- Disable IMAP METADATA by default (hardly used) +- Update Polish translation by @tinola +- Rename CSS .openpgp-control to .crypto-control +- Renamed some methods in PHP + +### Fixed +- When moving a folder/mailbox check for parent delimiter +- Mask `passphrase` in the logs for PHP < 8.2 +- Added some missing translations +- Sign messages using PGP +- Check for CONDSTORE or QRESYNC to get the HIGHESTMODSEQ +- Unable to login on certain IMAP server since 2.34.2 + [#1438](https://github.com/the-djmaze/snappymail/issues/1438) + +### Nextcloud +- Save as .eml + [#1425](https://github.com/the-djmaze/snappymail/issues/1425) + + +## 2.34.2 – 2024-02-14 + +### Fixed +- Message was sent but not saved to sent items folder + [#1432](https://github.com/the-djmaze/snappymail/issues/1432) +- Login with scram failed + [#1433](https://github.com/the-djmaze/snappymail/issues/1433) + + +## 2.34.1 – 2024-02-13 + +### Added +- Autocrypt support + [#342](https://github.com/the-djmaze/snappymail/issues/342) +- Load the mailboxes/folders of all namespaces (other users, global, shared, etc.) +- Load keys from server into OpenPGP.js + [#973](https://github.com/the-djmaze/snappymail/issues/973) +- Import PGP Keys from remote key servers +- Sort Inbox Folders with Unread Messages First + [#1427](https://github.com/the-djmaze/snappymail/issues/1427) +- Define JMAP FolderModel.myRights +- Identity Management: add identity display name + [#1405](https://github.com/the-djmaze/snappymail/issues/1405) +- Identity Management: add per-identity "sent" folder + [#1404](https://github.com/the-djmaze/snappymail/issues/1404) +- Some support for JSON-LD / Structured Email + [#1422](https://github.com/the-djmaze/snappymail/issues/1422) +- Domain Autoconfig and Microsoft's autodiscover (and also as extension/plugin) +- View MMS messages that are received via email + [#1294](https://github.com/the-djmaze/snappymail/issues/1294) +- Draft code for S/MIME + [#259](https://github.com/the-djmaze/snappymail/issues/259) + +### Changed +- Many OpenPGP improvements + [#89](https://github.com/the-djmaze/snappymail/issues/89) +- Allow CSP connect-src CORS for keys.openpgp.org to directly fetch PGP keys +- Improved handling of visible folders +- KnockoutJS Replace some ko.exportSymbol('*') in favour of ko['*'] +- KnockoutJS use Symbol for isObservableArray() +- Simplify generating folderListVisible +- Drop the bSearchSecretWords param from logger +- Transparent background for text + [#1412](https://github.com/the-djmaze/snappymail/issues/1412) +- Enable OpenPGP.js by default at install +- Added folder edit popup for improved IMAP ACL Support + [#157](https://github.com/the-djmaze/snappymail/issues/157) +- Process all IMAP namespaces +- Update Polish by @tinola +- Update Portuguese by @ner00 + +### Fixed +- Make time_zone a select list due to PEBKAC +- Workaround Outlook generated double spacing + [#1415](https://github.com/the-djmaze/snappymail/issues/1415) +- HTML Parser is not picking up the full Unsubscribe URL in the attached text file + [#1225](https://github.com/the-djmaze/snappymail/issues/1225) +- Contacts - it auto "Select All", after entry delete + [#1411](https://github.com/the-djmaze/snappymail/issues/1411) +- Message header parsing issue + [#1403](https://github.com/the-djmaze/snappymail/issues/1403) +- apple-touch-icon should not be transparent + [#1408](https://github.com/the-djmaze/snappymail/issues/1408) +- Creation of dynamic property is deprecated + [#1409](https://github.com/the-djmaze/snappymail/issues/1409) +- Ask/send readReceipt was broken +- OpenPGP public key can not be removed anymore after importing private key of subkey + [#1384](https://github.com/the-djmaze/snappymail/issues/1384) +- KnockoutJS failed to output text '0' +- JavaScript friendlySize() failed on 0 +- Workaround Dovecot `PREAUTH [CAPABILITY (null)]` issue +- Workaround disabled ACL could cause "Disconnected: Too many invalid IMAP commands" + +### Nextcloud +- Save multiple as .eml + [#1425](https://github.com/the-djmaze/snappymail/issues/1425) +- Disabled support for Nextcloud OpenID Connect + [#1420](https://github.com/the-djmaze/snappymail/issues/1420) + + +## 2.33.0 – 2024-01-22 + +### Added +- Feature to use the SQLite AddressBook per login account instead of global (on by default). +- Return all fetched messages headers in JSON. + +### Changed +- Docker hub use Alpine linux 3.18.5 and PHP 8.2 +- Some InvalidArgumentException to the better suited ValueError +- Removed some unused KnockoutJS code +- KnockoutJS drop unused rateLimit method +- Cleanup some data-bind="" +- Drop the disabled KnockoutJS twoWayBindings +- Drop support for KnockoutJS _ko_property_writers and for two-way binding they must be observables +- Login form use method="POST" to prevent uri exposure when javascript fails +- Merge code to generate MIME PGP parts and MIME Plain parts +- SMTP sendRequestWithCheck for future support of RFC's +- Cleanup mime header handling + +### Fixed +- Sorting not supported since 2.32.0 + [#1373](https://github.com/the-djmaze/snappymail/issues/1373) +- FILE_ON_SAVING_ERROR is not defined + [#1379](https://github.com/the-djmaze/snappymail/issues/1379) +- Saving EML files with same subject result in only saving latest email + [#1381](https://github.com/the-djmaze/snappymail/issues/1381) +- Some Sieve parser issues +- Handling of RainLoop Sieve script +- Sieve rfc5429 RejectCommand and ErejectCommand +- KnockoutJS title:value was removed, use attr:{title:value} +- dataBaseUpgrade() always runs on sqlite and pgsql +- Message was sent but not saved to sent items folder + [#1397](https://github.com/the-djmaze/snappymail/issues/1397) +- DKIM `pass` detection sometimes failed + + +## 2.32.0 – 2023-12-26 + +### Added +- Run full GetUids() in background when message_list_limit is set +- MessageListThreadsMap as background task when message_list_limit is set +- Properly set CACHEDIR.TAG +- Sending group email to all contact addresses + [#1286](https://github.com/the-djmaze/snappymail/pull/1286) by @rezaei92 + +### Changed +- Default IMAP message_list_limit to 10000 +- DoMessageCopy() return toFolder hash/etag +- Improved Squire WYSIWYG +- Sort real attachments and inline attachments for + [#1360](https://github.com/the-djmaze/snappymail/issues/1360) +- Nextcloud Theme fixes and improvements + [#1363](https://github.com/the-djmaze/snappymail/pull/1363) by @hampoelz +- Improve display of attachments + [#1361](https://github.com/the-djmaze/snappymail/issues/1361) +- Rename messageVisibility to messageVisible +- All CSS font-size to % instead of px +- Flip source code view of .eml attachments + [#1332](https://github.com/the-djmaze/snappymail/issues/1332) + +### Fixed +- Folders array_filter(): Argument 1 must be of type array, null given +- At upgrade set `static` and `themes` folder to 0755 +- Preview tooltip shows "null" when PREVIEW capability is disabled + +### Nextcloud +- Improved language handling + [#1362](https://github.com/the-djmaze/snappymail/pull/1362) by @avinash-0007 +- FilterLanguage had wrong parameter order +- Use NextcloudV25+ theme by default + + +## 2.31.0 – 2023-12-08 + +### Added +- PHP Hook `filter.language` to allow remote language selection + +### Changed +- Cleaner language detection +- Get Squire in sync with v2.2.5 and some bugfixes +- Update French by @Cwpute +- Squire: drop support for iPod + +### Fixed +- Call to undefined method FolderMyRights() + [#1344](https://github.com/the-djmaze/snappymail/issues/1344) +- NO Mailbox does not exist, or must be subscribed to") + [#1354](https://github.com/the-djmaze/snappymail/issues/1354) +- Flag indicators are added to wrong message + [#1347](https://github.com/the-djmaze/snappymail/pull/1347) by @SergeyMosin +- Squire: issue when using the enter key in a reply window + [#1296](https://github.com/the-djmaze/snappymail/issues/1296) +- Squire: crash on cut/delete range + +### Nextcloud +- Use language as defined in Nextcloud settings + [#1293](https://github.com/the-djmaze/snappymail/issues/1293) +- Plugin Call to undefined method RainLoop\Model\MainAccount::ImapConnectAndLoginHelper() +- SnappyMail failed due to Nextcloud Symfony polyfill + + +## 2.30.0 – 2023-12-04 + +### Added +- SnappyMail\SensitiveString class to secure passwords +- Allow to disable all IMAP features through Admin -> Domain +- Setting to open mails in a tab or new window + [#951](https://github.com/the-djmaze/snappymail/issues/951) +- Fully support IMAP PREVIEW + [#1338](https://github.com/the-djmaze/snappymail/issues/1338) +- Disable "Mark message as read after", offer manual toggle + [#1289](https://github.com/the-djmaze/snappymail/issues/1289) +- A "Move to" button inside message view as an icon/button and in the drop down menu. + [#1295](https://github.com/the-djmaze/snappymail/issues/1295) +- Support for IMAP WITHIN +- Support \noinferiors to disallow creating subfolders +- A test due to Failed loading libs.min.js + [#358](https://github.com/the-djmaze/snappymail/issues/358), + [#862](https://github.com/the-djmaze/snappymail/issues/862), + [#890](https://github.com/the-djmaze/snappymail/issues/890), + [#895](https://github.com/the-djmaze/snappymail/issues/895), + [#1238](https://github.com/the-djmaze/snappymail/issues/1238), + [#1320](https://github.com/the-djmaze/snappymail/issues/1320) + +### Changed +- Split PHP 8 polyfills from include.php +- Disable snappymail/v/0.0.0/static/.htaccess for now as many servers have issues with it +- Merged all Domain `disable_*` settings into `disabled_capabilities:[]` +- Prioritize LIST-EXTENDED over LSUB (LSUB deprecated in IMAP4rev2) +- Removed unused ImapClient::IsSupported() +- Removed obsolete `$_ENV['SNAPPYMAIL_NEXTCLOUD']` +- Removed unused Plugin->replaceTemplate() +- Removed openDropdownTrigger + +### Fixed +- Move to button does not work + [#1328](https://github.com/the-djmaze/snappymail/issues/1328) +- Mark passwords as sensitive information + [#1343](https://github.com/the-djmaze/snappymail/issues/1343) +- Account sSmtpPassword wrong value +- SCRAM sign-in failed + [#1245](https://github.com/the-djmaze/snappymail/issues/1245) +- Squire generates to many `

` + [#1339](https://github.com/the-djmaze/snappymail/issues/1339) +- Creation of dynamic property SnappyMail\Stream\ZipEntry::$compression is deprecated +- `json.after-*` hooks didn't send $aResponse as recursive array +- Sieve: Move to folder with trailing space does not work + [#1329](https://github.com/the-djmaze/snappymail/issues/1329) +- Squire: cantFocusEmptyTextNodes var is always undefined + [#1337](https://github.com/the-djmaze/snappymail/issues/1337) +- Squire: Remove redundant after replacing styles +- Squire: Handle empty nodes in moveRangeBoundariesDownTree +- Theme "Nextcloud V25+" can't be translated + [#1331](https://github.com/the-djmaze/snappymail/issues/1331) + + +## 2.29.4 – 2023-11-21 + +### Fixed +- Contacts not work + [#1319](https://github.com/the-djmaze/snappymail/issues/1319) + + +## 2.29.3 – 2023-11-21 + +### Added +- Docker Hub image + [#965](https://github.com/the-djmaze/snappymail/pull/965) by @leojonathanoh + +### Changed +- Sabre/VObject 4.5.4 and Sabre/Xml 4.0.4 + [#1311](https://github.com/the-djmaze/snappymail/issues/1311) + +### Fixed +- '#/mailbox/folder/mUID/search' uri/route handling + [#1301](https://github.com/the-djmaze/snappymail/pull/1301) by @SergeyMosin +- "Remember me" doesn't work when browser is closed + [#1313](https://github.com/the-djmaze/snappymail/issues/1313) +- Blank email displayed when "Prefer HTML to plain text" is unchecked and the message is html only + [#1302](https://github.com/the-djmaze/snappymail/issues/1302) +- Parent folder of Sub folder not useable. + [#1008](https://github.com/the-djmaze/snappymail/issues/1008) +- Large detailed header don't display body + [#1284](https://github.com/the-djmaze/snappymail/issues/1284) + +### Nextcloud +- Improvements for Install / update issues #929 + [#929](https://github.com/the-djmaze/snappymail/issues/929) +- Should use language as defined in cloud settings #1293 + [#1293](https://github.com/the-djmaze/snappymail/issues/1293) + + +## 2.29.2 – 2023-11-14 + +### Added +- Show size of folders in folders list #1303 + [#1303](https://github.com/the-djmaze/snappymail/issues/1303) + +### Fixed +- Configuration failed when using special chars in MySQL password #1308 + [#1308](https://github.com/the-djmaze/snappymail/issues/1308) +- With email open, "delete" doesn't delete #1274 + [#1274](https://github.com/the-djmaze/snappymail/issues/1274) +- Fix threading view in Thunderbird (others?) + [#1304](https://github.com/the-djmaze/snappymail/pull/1304) by @tkasch + + +## 2.29.1 – 2023-10-02 + +### Fixed +- Some small messages list bugs + + +## 2.29.0 – 2023-10-02 + +### Added +- Modern UI / Nextcloud Theme + [#629](https://github.com/the-djmaze/snappymail/pull/629) by @hampoelz +- "Add/Edit signature" label to PopupsIdentity.html + [#1248](https://github.com/the-djmaze/snappymail/pull/1248) by @SergeyMosin +- use calendar icon in message list for messages with '.ics' or 'text/calendar' attachments by @SergeyMosin + [#1248](https://github.com/the-djmaze/snappymail/pull/1248) +- Show unseen message count when the message list is threaded + [#1248](https://github.com/the-djmaze/snappymail/pull/1248) by @SergeyMosin +- in mobile mode hide folders(left) panel when a folder is clicked + [#1248](https://github.com/the-djmaze/snappymail/pull/1248) by @SergeyMosin +- spellcheck the subject when 'allowSpellcheck' setting is true + [#1248](https://github.com/the-djmaze/snappymail/pull/1248) by @SergeyMosin +- 'collapse_blockquotes', 'allow_spellcheck' and 'mail_list_grouped' to admin settings ('defaults' section) + [#1248](https://github.com/the-djmaze/snappymail/pull/1248) by @SergeyMosin +- Browser support for autocompleting TOTP code + [#1251](https://github.com/the-djmaze/snappymail/issues/1251) + +### Changed +- URL strip tracking for + [#1225](https://github.com/the-djmaze/snappymail/issues/1225) +- Color picker use color blind palette "Tableau 10" by Maureen Stone by default + [#1199](https://github.com/the-djmaze/snappymail/issues/1199) +- Draft code to improve mobile breakpoints + [#1150](https://github.com/the-djmaze/snappymail/issues/1150) +- address input: space character can trigger '_parseValue' if the email address looks complete + [#1248](https://github.com/the-djmaze/snappymail/pull/1248) by @SergeyMosin +- if applicable set '\\answered' or '$forwarded' flag after a message is sent so the proper icon is shown in the message list view + [#1248](https://github.com/the-djmaze/snappymail/pull/1248) by @SergeyMosin + +### Fixed +- CHARSET is not valid in UTF8 mode + [#1230](https://github.com/the-djmaze/snappymail/issues/1230) +- Spam score is always "acceptable" + [#1228](https://github.com/the-djmaze/snappymail/issues/1228) +- Undefined constant PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT + [#1205](https://github.com/the-djmaze/snappymail/issues/1205) +- Fetch controller.abort(reason) handling + [#1220](https://github.com/the-djmaze/snappymail/issues/1220) +- "Request failed" on message move + [#1220](https://github.com/the-djmaze/snappymail/issues/1220) +- Unwrapped text nodes attached to squire._root + [#1234](https://github.com/the-djmaze/snappymail/pull/1234) by @SergeyMosin +- Extra wrapper div is added in Squire every time a Draft is open (or closed) after save. + [#1208](https://github.com/the-djmaze/snappymail/issues/1208) +- foreach() argument must be of type array|object + [#1237](https://github.com/the-djmaze/snappymail/issues/1237) +- `` tag 'style' is lost in replies + [#1248](https://github.com/the-djmaze/snappymail/pull/1248) by @SergeyMosin +- unseen indicator is not shown in thread view when 'listGrouped' settings is false + [#1248](https://github.com/the-djmaze/snappymail/pull/1248) by @SergeyMosin +- TOTP plugin is dependent on ctype + [#1250](https://github.com/the-djmaze/snappymail/issues/1250) + +### Nextcloud +- iFrame mode: click on unified search result opens inner iFrame + [#1248](https://github.com/the-djmaze/snappymail/pull/1248) by @SergeyMosin +- set 'smremember' cookie if 'sign_me_auto' is set to 'DefaultOn' when using 'snappymail-autologin*', otherwise nextcloud users need to re-login when the browser is re-opened + [#1248](https://github.com/the-djmaze/snappymail/pull/1248) by @SergeyMosin +- Improve UX of "Put in Calendar" option in plugin + [#1259](https://github.com/the-djmaze/snappymail/pull/1259) by @theronakpatel + + +## 2.28.4 – 2023-07-10 + +### Added +- application.ini msg_default_action + [#1204](https://github.com/the-djmaze/snappymail/pull/1204) by @SergeyMosin +- application.ini view_show_next_message + [#1204](https://github.com/the-djmaze/snappymail/pull/1204) by @SergeyMosin +- application.ini view_images + [#1204](https://github.com/the-djmaze/snappymail/pull/1204) by @SergeyMosin +- nextcloud add ability to include custom php file in InstallStep migration + [#1197](https://github.com/the-djmaze/snappymail/pull/1197) by @SergeyMosin +- Support plugin for Squire editor + [#1192](https://github.com/the-djmaze/snappymail/issues/1192) + +### Changed +- only show 'Add "domain.tld" as an application for mailto links?' message after login (firefox shows the message on every reload otherwise). + [#1204](https://github.com/the-djmaze/snappymail/issues/1204) +- Convert getPdoAccessData() : array to a RainLoop\Pdo\Settings object instance +- New bidi buttons to Squire editor + [#1200](https://github.com/the-djmaze/snappymail/pull/1200) by @rezaei92 + +### Fixed +- Undefined constant PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT + [#1205](https://github.com/the-djmaze/snappymail/issues/1205) +- 'reloadTime' function result is passed into 'setInterval' instead of the function + [#1204](https://github.com/the-djmaze/snappymail/pull/1204) by @SergeyMosin +- UNKNOWN-CTE Invalid data in MIME part + [#1186](https://github.com/the-djmaze/snappymail/issues/1186) + + +## 2.28.3 – 2023-06-22 + +### Added +- Attachments in "new window" view + [#1166](https://github.com/the-djmaze/snappymail/issues/1166) + +### Changed +- Update Portuguese by @ner00 +- Update French by @hguilbert + +### Fixed +- Some emails with inline CSS break the UI + [#1187](https://github.com/the-djmaze/snappymail/issues/1187) +- Remote.get() Promise broken by previous change + [#1185](https://github.com/the-djmaze/snappymail/issues/1185) +- Class "MailSo\Base\Exceptions\InvalidArgumentException" not found + [#1182](https://github.com/the-djmaze/snappymail/issues/1182) +- First account not showed in the right list (dropbox) + [#1180](https://github.com/the-djmaze/snappymail/issues/1180) + + +## 2.28.2 – 2023-06-19 + +### Added +- Detailed error for "Cannot access the repository at the moment" + [#1164](https://github.com/the-djmaze/snappymail/issues/1164) +- Bidi in Squire editor + [#1158](https://github.com/the-djmaze/snappymail/issues/1158) +- Translate Squire UI +- Nextcloud 27 compatibility by @LarsBel +- JWT class for handling JSON Web Tokens + +### Changed +- Update German by @cm-schl +- Update French by @hguilbert +- Update Polish by @tinola +- Merge handling of local Account Settings. Found while investigating + [#1170](https://github.com/the-djmaze/snappymail/issues/1170) +- Image max-width now 100% instead of 90vw + +### Fixed +- Cannot modify header information + [#929](https://github.com/the-djmaze/snappymail/issues/929) (comment) +- Admin Panel broken when admin_panel_host is set + [#1169](https://github.com/the-djmaze/snappymail/issues/1169) +- Invalid CSP report-uri +- Prevent MessageList multiple request at the same time + [#1071](https://github.com/the-djmaze/snappymail/issues/1071) +- Error in Addressbook Sync + [#1179](https://github.com/the-djmaze/snappymail/issues/1179) +- base64_decode() second parameter must be true + + +## 2.28.1 – 2023-06-05 + +### Changed +- Optical issue with input fields for mail and folder search + [#1149](https://github.com/the-djmaze/snappymail/issues/1149) +- Update Chinese translation + [#1157](https://github.com/the-djmaze/snappymail/pull/1157) by @mayswind +- Update Polish translation + [#1156](https://github.com/the-djmaze/snappymail/pull/1156) by @tinola + +### Fixed +- Undefined SIG constants + [#1147](https://github.com/the-djmaze/snappymail/issues/1147) + + +## 2.28.0 – 2023-05-30 + +### Added +- Threaded view make number orange when unread sub-messages + [#1028](https://github.com/the-djmaze/snappymail/issues/1028) +- Handle PHP pctnl messages +- addEventListener('rl-view-model') missing for Settings + [#1013](https://github.com/the-djmaze/snappymail/issues/1013) +- CSS `--btn-border-radius` + +### Changed +- Improved RTL languages support + [#1056](https://github.com/the-djmaze/snappymail/issues/1056) +- Composer text/attachments as tabs + [#1119](https://github.com/the-djmaze/snappymail/issues/1119) +- Filter dialog doesn't refer to folder names consistently + [#1111](https://github.com/the-djmaze/snappymail/issues/1111) +- TLS connection for MYSQL contact db + [#1078](https://github.com/the-djmaze/snappymail/issues/1078) +- Allow empty message body when there are attachments + [#1052](https://github.com/the-djmaze/snappymail/issues/1052) +- PHP inherit logger as Trait +- Update Portuguese + [#1124](https://github.com/the-djmaze/snappymail/pull/1124) by @ner00 +- Update Traditional Chinese (Taiwan) + [#1107](https://github.com/the-djmaze/snappymail/pull/1107) by @chiyi4488 +- Update Russian + [#1108](https://github.com/the-djmaze/snappymail/pull/1108) by @konkere +- Update Italian + [#1094](https://github.com/the-djmaze/snappymail/pull/1094) by @cm-schl +- Update French + [#1102](https://github.com/the-djmaze/snappymail/pull/1102) by @hguilbert +- Update German + [#1087](https://github.com/the-djmaze/snappymail/pull/1087) by @cm-schl + +### Fixed +- Show messagelist timeout/abort error for + [#1071](https://github.com/the-djmaze/snappymail/issues/1071) +- DesktopNotifications setting not saved + [#1137](https://github.com/the-djmaze/snappymail/issues/1137) +- PHP Deprecation warning for $_openPipes + [#1141](https://github.com/the-djmaze/snappymail/issues/1141) +- Images size wrong + [#1134](https://github.com/the-djmaze/snappymail/issues/1134) +- Unable to preview body of encrypted mail in mailvelope reply-to + [#1130](https://github.com/the-djmaze/snappymail/issues/1130) +- Replace ` diff --git a/plugins/haveibeenpwned/hibp.js b/plugins/haveibeenpwned/hibp.js new file mode 100644 index 000000000..98c8c5d06 --- /dev/null +++ b/plugins/haveibeenpwned/hibp.js @@ -0,0 +1,25 @@ +(doc => { + + addEventListener('rl-view-model.create', event => { + if ('SettingsSecurity' === event.detail.viewModelTemplateID) { + const template = doc.getElementById('SettingsSecurity'), + details = doc.createElement('details'), + summary = doc.createElement('summary'), + button = doc.createElement('button'); + summary.textContent = "Have i been pwned?" + button.dataset.bind = "click:HibpCheck"; + button.textContent = "Check"; + details.append(summary, button); + template.content.append(details); + + event.detail.HibpCheck = () => { + // JsonHibpCheck + rl.pluginRemoteRequest((iError, oData) => { + console.dir({iError, oData}); + }, 'HibpCheck'); + + }; + } + }); + +})(document); diff --git a/plugins/haveibeenpwned/index.php b/plugins/haveibeenpwned/index.php new file mode 100644 index 000000000..7e22f707d --- /dev/null +++ b/plugins/haveibeenpwned/index.php @@ -0,0 +1,57 @@ +UseLangs(true); + $this->addJs('hibp.js'); + $this->addJsonHook('HibpCheck'); + } + + public function HibpCheck() + { +// $oAccount = $this->Manager()->Actions()->GetAccount(); + $oAccount = $this->Manager()->Actions()->getAccountFromToken(); +// $oAccount = \RainLoop\Api::Actions()->getAccountFromToken(); + + $api_key = \trim($this->Config()->Get('plugin', 'hibp-api-key', '')); + $breaches = $api_key ? Hibp::account($api_key, $oAccount->Email()) : null; + + $pwned = Hibp::password(new SensitiveString($oAccount->ImapPass())); + + return $this->jsonResponse(__FUNCTION__, array( + 'pwned' => $pwned, + 'breaches' => $breaches + )); + } + + public function configMapping() : array + { + return [ + \RainLoop\Plugins\Property::NewInstance("hibp-api-key") + ->SetLabel('API key') + ->SetDescription('https://haveibeenpwned.com/API/Key') + ->SetType(\RainLoop\Enumerations\PluginPropertyType::STRING) + ]; + } +} diff --git a/plugins/ics-viewer/LICENSE b/plugins/ics-viewer/LICENSE new file mode 100644 index 000000000..9e5e56cdd --- /dev/null +++ b/plugins/ics-viewer/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2022 SnappyMail + +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/plugins/ics-viewer/ical.js b/plugins/ics-viewer/ical.js new file mode 100644 index 000000000..97ec65305 --- /dev/null +++ b/plugins/ics-viewer/ical.js @@ -0,0 +1,9526 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * Portions Copyright (C) Philipp Kewisch */ + +ICAL = (() => { + +/** + * Represents the BINARY value type, which contains extra methods for encoding and decoding. + * + * @memberof ICAL + */ +class Binary { + /** + * Creates a binary value from the given string. + * + * @param {String} aString The binary value string + * @return {Binary} The binary value instance + */ + static fromString(aString) { + return new Binary(aString); + } + + /** + * Creates a new ICAL.Binary instance + * + * @param {String} aValue The binary data for this value + */ + constructor(aValue) { + this.value = aValue; + } + + /** + * The type name, to be used in the jCal object. + * @default "binary" + * @constant + */ + icaltype = "binary"; + + /** + * Base64 decode the current value + * + * @return {String} The base64-decoded value + */ + decodeValue() { + return this._b64_decode(this.value); + } + + /** + * Encodes the passed parameter with base64 and sets the internal + * value to the result. + * + * @param {String} aValue The raw binary value to encode + */ + setEncodedValue(aValue) { + this.value = this._b64_encode(aValue); + } + + _b64_encode(data) { + // http://kevin.vanzonneveld.net + // + original by: Tyler Akins (http://rumkin.com) + // + improved by: Bayron Guevara + // + improved by: Thunder.m + // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) + // + bugfixed by: Pellentesque Malesuada + // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) + // + improved by: Rafał Kukawski (http://kukawski.pl) + // * example 1: base64_encode('Kevin van Zonneveld'); + // * returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA==' + // mozilla has this native + // - but breaks in 2.0.0.12! + //if (typeof this.window['atob'] == 'function') { + // return atob(data); + //} + let b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + + "abcdefghijklmnopqrstuvwxyz0123456789+/="; + let o1, o2, o3, h1, h2, h3, h4, bits, i = 0, + ac = 0, + enc = "", + tmp_arr = []; + + if (!data) { + return data; + } + + do { // pack three octets into four hexets + o1 = data.charCodeAt(i++); + o2 = data.charCodeAt(i++); + o3 = data.charCodeAt(i++); + + bits = o1 << 16 | o2 << 8 | o3; + + h1 = bits >> 18 & 0x3f; + h2 = bits >> 12 & 0x3f; + h3 = bits >> 6 & 0x3f; + h4 = bits & 0x3f; + + // use hexets to index into b64, and append result to encoded string + tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4); + } while (i < data.length); + + enc = tmp_arr.join(''); + + let r = data.length % 3; + + return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3); + + } + + _b64_decode(data) { + // http://kevin.vanzonneveld.net + // + original by: Tyler Akins (http://rumkin.com) + // + improved by: Thunder.m + // + input by: Aman Gupta + // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) + // + bugfixed by: Onno Marsman + // + bugfixed by: Pellentesque Malesuada + // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) + // + input by: Brett Zamir (http://brett-zamir.me) + // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) + // * example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA=='); + // * returns 1: 'Kevin van Zonneveld' + // mozilla has this native + // - but breaks in 2.0.0.12! + //if (typeof this.window['btoa'] == 'function') { + // return btoa(data); + //} + let b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + + "abcdefghijklmnopqrstuvwxyz0123456789+/="; + let o1, o2, o3, h1, h2, h3, h4, bits, i = 0, + ac = 0, + dec = "", + tmp_arr = []; + + if (!data) { + return data; + } + + data += ''; + + do { // unpack four hexets into three octets using index points in b64 + h1 = b64.indexOf(data.charAt(i++)); + h2 = b64.indexOf(data.charAt(i++)); + h3 = b64.indexOf(data.charAt(i++)); + h4 = b64.indexOf(data.charAt(i++)); + + bits = h1 << 18 | h2 << 12 | h3 << 6 | h4; + + o1 = bits >> 16 & 0xff; + o2 = bits >> 8 & 0xff; + o3 = bits & 0xff; + + if (h3 == 64) { + tmp_arr[ac++] = String.fromCharCode(o1); + } else if (h4 == 64) { + tmp_arr[ac++] = String.fromCharCode(o1, o2); + } else { + tmp_arr[ac++] = String.fromCharCode(o1, o2, o3); + } + } while (i < data.length); + + dec = tmp_arr.join(''); + + return dec; + } + + /** + * The string representation of this value + * @return {String} + */ + toString() { + return this.value; + } +} + +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * Portions Copyright (C) Philipp Kewisch */ + +const DURATION_LETTERS = /([PDWHMTS]{1,1})/; +const DATA_PROPS_TO_COPY = ["weeks", "days", "hours", "minutes", "seconds", "isNegative"]; + +/** + * This class represents the "duration" value type, with various calculation + * and manipulation methods. + * + * @memberof ICAL + */ +class Duration { + /** + * Returns a new ICAL.Duration instance from the passed seconds value. + * + * @param {Number} aSeconds The seconds to create the instance from + * @return {Duration} The newly created duration instance + */ + static fromSeconds(aSeconds) { + return (new Duration()).fromSeconds(aSeconds); + } + + /** + * Checks if the given string is an iCalendar duration value. + * + * @param {String} value The raw ical value + * @return {Boolean} True, if the given value is of the + * duration ical type + */ + static isValueString(string) { + return (string[0] === 'P' || string[1] === 'P'); + } + + /** + * Creates a new {@link ICAL.Duration} instance from the passed string. + * + * @param {String} aStr The string to parse + * @return {Duration} The created duration instance + */ + static fromString(aStr) { + let pos = 0; + let dict = Object.create(null); + let chunks = 0; + + while ((pos = aStr.search(DURATION_LETTERS)) !== -1) { + let type = aStr[pos]; + let numeric = aStr.slice(0, Math.max(0, pos)); + aStr = aStr.slice(pos + 1); + + chunks += parseDurationChunk(type, numeric, dict); + } + + if (chunks < 2) { + // There must be at least a chunk with "P" and some unit chunk + throw new Error( + 'invalid duration value: Not enough duration components in "' + aStr + '"' + ); + } + + return new Duration(dict); + } + + /** + * Creates a new ICAL.Duration instance from the given data object. + * + * @param {Object} aData An object with members of the duration + * @param {Number=} aData.weeks Duration in weeks + * @param {Number=} aData.days Duration in days + * @param {Number=} aData.hours Duration in hours + * @param {Number=} aData.minutes Duration in minutes + * @param {Number=} aData.seconds Duration in seconds + * @param {Boolean=} aData.isNegative If true, the duration is negative + * @return {Duration} The createad duration instance + */ + static fromData(aData) { + return new Duration(aData); + } + + /** + * Creates a new ICAL.Duration instance. + * + * @param {Object} data An object with members of the duration + * @param {Number=} data.weeks Duration in weeks + * @param {Number=} data.days Duration in days + * @param {Number=} data.hours Duration in hours + * @param {Number=} data.minutes Duration in minutes + * @param {Number=} data.seconds Duration in seconds + * @param {Boolean=} data.isNegative If true, the duration is negative + */ + constructor(data) { + this.wrappedJSObject = this; + this.fromData(data); + } + + /** + * The weeks in this duration + * @type {Number} + * @default 0 + */ + weeks = 0; + + /** + * The days in this duration + * @type {Number} + * @default 0 + */ + days = 0; + + /** + * The days in this duration + * @type {Number} + * @default 0 + */ + hours = 0; + + /** + * The minutes in this duration + * @type {Number} + * @default 0 + */ + minutes = 0; + + /** + * The seconds in this duration + * @type {Number} + * @default 0 + */ + seconds = 0; + + /** + * The seconds in this duration + * @type {Boolean} + * @default false + */ + isNegative = false; + + /** + * The class identifier. + * @constant + * @type {String} + * @default "icalduration" + */ + icalclass = "icalduration"; + + /** + * The type name, to be used in the jCal object. + * @constant + * @type {String} + * @default "duration" + */ + icaltype = "duration"; + + /** + * Returns a clone of the duration object. + * + * @return {Duration} The cloned object + */ + clone() { + return Duration.fromData(this); + } + + /** + * The duration value expressed as a number of seconds. + * + * @return {Number} The duration value in seconds + */ + toSeconds() { + let seconds = this.seconds + 60 * this.minutes + 3600 * this.hours + + 86400 * this.days + 7 * 86400 * this.weeks; + return (this.isNegative ? -seconds : seconds); + } + + /** + * Reads the passed seconds value into this duration object. Afterwards, + * members like {@link ICAL.Duration#days days} and {@link ICAL.Duration#weeks weeks} will be set up + * accordingly. + * + * @param {Number} aSeconds The duration value in seconds + * @return {Duration} Returns this instance + */ + fromSeconds(aSeconds) { + let secs = Math.abs(aSeconds); + + this.isNegative = (aSeconds < 0); + this.days = trunc(secs / 86400); + + // If we have a flat number of weeks, use them. + if (this.days % 7 == 0) { + this.weeks = this.days / 7; + this.days = 0; + } else { + this.weeks = 0; + } + + secs -= (this.days + 7 * this.weeks) * 86400; + + this.hours = trunc(secs / 3600); + secs -= this.hours * 3600; + + this.minutes = trunc(secs / 60); + secs -= this.minutes * 60; + + this.seconds = secs; + return this; + } + + /** + * Sets up the current instance using members from the passed data object. + * + * @param {Object} aData An object with members of the duration + * @param {Number=} aData.weeks Duration in weeks + * @param {Number=} aData.days Duration in days + * @param {Number=} aData.hours Duration in hours + * @param {Number=} aData.minutes Duration in minutes + * @param {Number=} aData.seconds Duration in seconds + * @param {Boolean=} aData.isNegative If true, the duration is negative + */ + fromData(aData) { + for (let prop of DATA_PROPS_TO_COPY) { + if (aData && prop in aData) { + this[prop] = aData[prop]; + } else { + this[prop] = 0; + } + } + } + + /** + * Resets the duration instance to the default values, i.e. PT0S + */ + reset() { + this.isNegative = false; + this.weeks = 0; + this.days = 0; + this.hours = 0; + this.minutes = 0; + this.seconds = 0; + } + + /** + * Compares the duration instance with another one. + * + * @param {Duration} aOther The instance to compare with + * @return {Number} -1, 0 or 1 for less/equal/greater + */ + compare(aOther) { + let thisSeconds = this.toSeconds(); + let otherSeconds = aOther.toSeconds(); + return (thisSeconds > otherSeconds) - (thisSeconds < otherSeconds); + } + + /** + * Normalizes the duration instance. For example, a duration with a value + * of 61 seconds will be normalized to 1 minute and 1 second. + */ + normalize() { + this.fromSeconds(this.toSeconds()); + } + + /** + * The string representation of this duration. + * @return {String} + */ + toString() { + if (this.toSeconds() == 0) { + return "PT0S"; + } else { + let str = ""; + if (this.isNegative) str += "-"; + str += "P"; + if (this.weeks) str += this.weeks + "W"; + if (this.days) str += this.days + "D"; + + if (this.hours || this.minutes || this.seconds) { + str += "T"; + if (this.hours) str += this.hours + "H"; + if (this.minutes) str += this.minutes + "M"; + if (this.seconds) str += this.seconds + "S"; + } + return str; + } + } + + /** + * The iCalendar string representation of this duration. + * @return {String} + */ + toICALString() { + return this.toString(); + } +} + +/** + * Internal helper function to handle a chunk of a duration. + * + * @private + * @param {String} letter type of duration chunk + * @param {String} number numeric value or -/+ + * @param {Object} dict target to assign values to + */ +function parseDurationChunk(letter, number, object) { + let type; + switch (letter) { + case 'P': + if (number && number === '-') { + object.isNegative = true; + } else { + object.isNegative = false; + } + // period + break; + case 'D': + type = 'days'; + break; + case 'W': + type = 'weeks'; + break; + case 'H': + type = 'hours'; + break; + case 'M': + type = 'minutes'; + break; + case 'S': + type = 'seconds'; + break; + default: + // Not a valid chunk + return 0; + } + + if (type) { + if (!number && number !== 0) { + throw new Error( + 'invalid duration value: Missing number before "' + letter + '"' + ); + } + let num = parseInt(number, 10); + if (isStrictlyNaN(num)) { + throw new Error( + 'invalid duration value: Invalid number "' + number + '" before "' + letter + '"' + ); + } + object[type] = num; + } + + return 1; +} + +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * Portions Copyright (C) Philipp Kewisch */ + +/** + * This lets typescript resolve our custom types in the + * generated d.ts files (jsdoc typedefs are converted to typescript types). + * Ignore prevents the typedefs from being documented more than once. + * + * @ignore + * @typedef {import("./types.js").weekDay} weekDay + * Imports the 'weekDay' type from the "types.js" module + */ + +/** + * @classdesc + * iCalendar Time representation (similar to JS Date object). Fully + * independent of system (OS) timezone / time. Unlike JS Date, the month + * January is 1, not zero. + * + * @example + * var time = new ICAL.Time({ + * year: 2012, + * month: 10, + * day: 11 + * minute: 0, + * second: 0, + * isDate: false + * }); + * + * + * @memberof ICAL +*/ +class Time { + static _dowCache = {}; + static _wnCache = {}; + + /** + * Returns the days in the given month + * + * @param {Number} month The month to check + * @param {Number} year The year to check + * @return {Number} The number of days in the month + */ + static daysInMonth(month, year) { + let _daysInMonth = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + let days = 30; + + if (month < 1 || month > 12) return days; + + days = _daysInMonth[month]; + + if (month == 2) { + days += Time.isLeapYear(year); + } + + return days; + } + + /** + * Checks if the year is a leap year + * + * @param {Number} year The year to check + * @return {Boolean} True, if the year is a leap year + */ + static isLeapYear(year) { + if (year <= 1752) { + return ((year % 4) == 0); + } else { + return (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)); + } + } + + /** + * Create a new ICAL.Time from the day of year and year. The date is returned + * in floating timezone. + * + * @param {Number} aDayOfYear The day of year + * @param {Number} aYear The year to create the instance in + * @return {Time} The created instance with the calculated date + */ + static fromDayOfYear(aDayOfYear, aYear) { + let year = aYear; + let doy = aDayOfYear; + let tt = new Time(); + tt.auto_normalize = false; + let is_leap = (Time.isLeapYear(year) ? 1 : 0); + + if (doy < 1) { + year--; + is_leap = (Time.isLeapYear(year) ? 1 : 0); + doy += Time.daysInYearPassedMonth[is_leap][12]; + return Time.fromDayOfYear(doy, year); + } else if (doy > Time.daysInYearPassedMonth[is_leap][12]) { + is_leap = (Time.isLeapYear(year) ? 1 : 0); + doy -= Time.daysInYearPassedMonth[is_leap][12]; + year++; + return Time.fromDayOfYear(doy, year); + } + + tt.year = year; + tt.isDate = true; + + for (let month = 11; month >= 0; month--) { + if (doy > Time.daysInYearPassedMonth[is_leap][month]) { + tt.month = month + 1; + tt.day = doy - Time.daysInYearPassedMonth[is_leap][month]; + break; + } + } + + tt.auto_normalize = true; + return tt; + } + + /** + * Returns a new ICAL.Time instance from a date string, e.g 2015-01-02. + * + * @deprecated Use {@link ICAL.Time.fromDateString} instead + * @param {String} str The string to create from + * @return {Time} The date/time instance + */ + static fromStringv2(str) { + return new Time({ + year: parseInt(str.slice(0, 4), 10), + month: parseInt(str.slice(5, 7), 10), + day: parseInt(str.slice(8, 10), 10), + isDate: true + }); + } + + /** + * Returns a new ICAL.Time instance from a date string, e.g 2015-01-02. + * + * @param {String} aValue The string to create from + * @return {Time} The date/time instance + */ + static fromDateString(aValue) { + // Dates should have no timezone. + // Google likes to sometimes specify Z on dates + // we specifically ignore that to avoid issues. + + // YYYY-MM-DD + // 2012-10-10 + return new Time({ + year: strictParseInt(aValue.slice(0, 4)), + month: strictParseInt(aValue.slice(5, 7)), + day: strictParseInt(aValue.slice(8, 10)), + isDate: true + }); + } + + /** + * Returns a new ICAL.Time instance from a date-time string, e.g + * 2015-01-02T03:04:05. If a property is specified, the timezone is set up + * from the property's TZID parameter. + * + * @param {String} aValue The string to create from + * @param {Property=} prop The property the date belongs to + * @return {Time} The date/time instance + */ + static fromDateTimeString(aValue, prop) { + if (aValue.length < 19) { + throw new Error( + 'invalid date-time value: "' + aValue + '"' + ); + } + + let zone; + let zoneId; + + if (aValue[19] && aValue[19] === 'Z') { + zone = Timezone.utcTimezone; + } else if (prop) { + zoneId = prop.getParameter('tzid'); + + if (prop.parent) { + if (prop.parent.name === 'standard' || prop.parent.name === 'daylight') { + // Per RFC 5545 3.8.2.4 and 3.8.2.2, start/end date-times within + // these components MUST be specified in local time. + zone = Timezone.localTimezone; + } else if (zoneId) { + // If the desired time zone is defined within the component tree, + // fetch its definition and prefer that. + zone = prop.parent.getTimeZoneByID(zoneId); + } + } + } + + const timeData = { + year: strictParseInt(aValue.slice(0, 4)), + month: strictParseInt(aValue.slice(5, 7)), + day: strictParseInt(aValue.slice(8, 10)), + hour: strictParseInt(aValue.slice(11, 13)), + minute: strictParseInt(aValue.slice(14, 16)), + second: strictParseInt(aValue.slice(17, 19)), + }; + + // Although RFC 5545 requires that all TZIDs used within a file have a + // corresponding time zone definition, we may not be parsing the full file + // or we may be dealing with a non-compliant file; in either case, we can + // check our own time zone service for the TZID in a last-ditch effort. + if (zoneId && !zone) { + timeData.timezone = zoneId; + } + + // 2012-10-10T10:10:10(Z)? + return new Time(timeData, zone); + } + + /** + * Returns a new ICAL.Time instance from a date or date-time string, + * + * @param {String} aValue The string to create from + * @param {Property=} prop The property the date belongs to + * @return {Time} The date/time instance + */ + static fromString(aValue, aProperty) { + if (aValue.length > 10) { + return Time.fromDateTimeString(aValue, aProperty); + } else { + return Time.fromDateString(aValue); + } + } + + /** + * Creates a new ICAL.Time instance from the given Javascript Date. + * + * @param {?Date} aDate The Javascript Date to read, or null to reset + * @param {Boolean} [useUTC=false] If true, the UTC values of the date will be used + */ + static fromJSDate(aDate, useUTC) { + let tt = new Time(); + return tt.fromJSDate(aDate, useUTC); + } + + /** + * Creates a new ICAL.Time instance from the the passed data object. + * + * @param {Object} aData Time initialization + * @param {Number=} aData.year The year for this date + * @param {Number=} aData.month The month for this date + * @param {Number=} aData.day The day for this date + * @param {Number=} aData.hour The hour for this date + * @param {Number=} aData.minute The minute for this date + * @param {Number=} aData.second The second for this date + * @param {Boolean=} aData.isDate If true, the instance represents a date + * (as opposed to a date-time) + * @param {Timezone=} aZone Timezone this position occurs in + */ + static fromData = function fromData(aData, aZone) { + let t = new Time(); + return t.fromData(aData, aZone); + }; + + /** + * Creates a new ICAL.Time instance from the current moment. + * The instance is “floating” - has no timezone relation. + * To create an instance considering the time zone, call + * ICAL.Time.fromJSDate(new Date(), true) + * @return {Time} + */ + static now() { + return Time.fromJSDate(new Date(), false); + } + + /** + * Returns the date on which ISO week number 1 starts. + * + * @see Time#weekNumber + * @param {Number} aYear The year to search in + * @param {weekDay=} aWeekStart The week start weekday, used for calculation. + * @return {Time} The date on which week number 1 starts + */ + static weekOneStarts(aYear, aWeekStart) { + let t = Time.fromData({ + year: aYear, + month: 1, + day: 1, + isDate: true + }); + + let dow = t.dayOfWeek(); + let wkst = aWeekStart || Time.DEFAULT_WEEK_START; + if (dow > Time.THURSDAY) { + t.day += 7; + } + if (wkst > Time.THURSDAY) { + t.day -= 7; + } + + t.day -= dow - wkst; + + return t; + } + + /** + * Get the dominical letter for the given year. Letters range from A - G for + * common years, and AG to GF for leap years. + * + * @param {Number} yr The year to retrieve the letter for + * @return {String} The dominical letter. + */ + static getDominicalLetter(yr) { + let LTRS = "GFEDCBA"; + let dom = (yr + (yr / 4 | 0) + (yr / 400 | 0) - (yr / 100 | 0) - 1) % 7; + let isLeap = Time.isLeapYear(yr); + if (isLeap) { + return LTRS[(dom + 6) % 7] + LTRS[dom]; + } else { + return LTRS[dom]; + } + } + + static #epochTime = null; + /** + * January 1st, 1970 as an ICAL.Time. + * @type {Time} + * @constant + * @instance + */ + static get epochTime() { + if (!this.#epochTime) { + this.#epochTime = Time.fromData({ + year: 1970, + month: 1, + day: 1, + hour: 0, + minute: 0, + second: 0, + isDate: false, + timezone: "Z" + }); + } + return this.#epochTime; + } + + static _cmp_attr(a, b, attr) { + if (a[attr] > b[attr]) return 1; + if (a[attr] < b[attr]) return -1; + return 0; + } + + /** + * The days that have passed in the year after a given month. The array has + * two members, one being an array of passed days for non-leap years, the + * other analog for leap years. + * @example + * var isLeapYear = ICAL.Time.isLeapYear(year); + * var passedDays = ICAL.Time.daysInYearPassedMonth[isLeapYear][month]; + * @type {Array.>} + */ + static daysInYearPassedMonth = [ + [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365], + [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366] + ]; + + static SUNDAY = 1; + static MONDAY = 2; + static TUESDAY = 3; + static WEDNESDAY = 4; + static THURSDAY = 5; + static FRIDAY = 6; + static SATURDAY = 7; + + /** + * The default weekday for the WKST part. + * @constant + * @default ICAL.Time.MONDAY + */ + static DEFAULT_WEEK_START = 2; // MONDAY + + /** + * Creates a new ICAL.Time instance. + * + * @param {Object} data Time initialization + * @param {Number=} data.year The year for this date + * @param {Number=} data.month The month for this date + * @param {Number=} data.day The day for this date + * @param {Number=} data.hour The hour for this date + * @param {Number=} data.minute The minute for this date + * @param {Number=} data.second The second for this date + * @param {Boolean=} data.isDate If true, the instance represents a date (as + * opposed to a date-time) + * @param {Timezone} zone timezone this position occurs in + */ + constructor(data, zone) { + this.wrappedJSObject = this; + let time = this._time = Object.create(null); + + /* time defaults */ + time.year = 0; + time.month = 1; + time.day = 1; + time.hour = 0; + time.minute = 0; + time.second = 0; + time.isDate = false; + + this.fromData(data, zone); + } + + /** + * The class identifier. + * @constant + * @type {String} + * @default "icaltime" + */ + icalclass = "icaltime"; + _cachedUnixTime = null; + + /** + * The type name, to be used in the jCal object. This value may change and + * is strictly defined by the {@link ICAL.Time#isDate isDate} member. + * @type {String} + * @default "date-time" + */ + get icaltype() { + return this.isDate ? 'date' : 'date-time'; + } + + /** + * The timezone for this time. + * @type {Timezone} + */ + zone = null; + + /** + * Internal uses to indicate that a change has been made and the next read + * operation must attempt to normalize the value (for example changing the + * day to 33). + * + * @type {Boolean} + * @private + */ + _pendingNormalization = false; + + /** + * Returns a clone of the time object. + * + * @return {Time} The cloned object + */ + clone() { + return new Time(this._time, this.zone); + } + + /** + * Reset the time instance to epoch time + */ + reset() { + this.fromData(Time.epochTime); + this.zone = Timezone.utcTimezone; + } + + /** + * Reset the time instance to the given date/time values. + * + * @param {Number} year The year to set + * @param {Number} month The month to set + * @param {Number} day The day to set + * @param {Number} hour The hour to set + * @param {Number} minute The minute to set + * @param {Number} second The second to set + * @param {Timezone} timezone The timezone to set + */ + resetTo(year, month, day, hour, minute, second, timezone) { + this.fromData({ + year: year, + month: month, + day: day, + hour: hour, + minute: minute, + second: second, + zone: timezone + }); + } + + /** + * Set up the current instance from the Javascript date value. + * + * @param {?Date} aDate The Javascript Date to read, or null to reset + * @param {Boolean} [useUTC=false] If true, the UTC values of the date will be used + */ + fromJSDate(aDate, useUTC) { + if (!aDate) { + this.reset(); + } else { + if (useUTC) { + this.zone = Timezone.utcTimezone; + this.year = aDate.getUTCFullYear(); + this.month = aDate.getUTCMonth() + 1; + this.day = aDate.getUTCDate(); + this.hour = aDate.getUTCHours(); + this.minute = aDate.getUTCMinutes(); + this.second = aDate.getUTCSeconds(); + } else { + this.zone = Timezone.localTimezone; + this.year = aDate.getFullYear(); + this.month = aDate.getMonth() + 1; + this.day = aDate.getDate(); + this.hour = aDate.getHours(); + this.minute = aDate.getMinutes(); + this.second = aDate.getSeconds(); + } + } + this._cachedUnixTime = null; + return this; + } + + /** + * Sets up the current instance using members from the passed data object. + * + * @param {Object} aData Time initialization + * @param {Number=} aData.year The year for this date + * @param {Number=} aData.month The month for this date + * @param {Number=} aData.day The day for this date + * @param {Number=} aData.hour The hour for this date + * @param {Number=} aData.minute The minute for this date + * @param {Number=} aData.second The second for this date + * @param {Boolean=} aData.isDate If true, the instance represents a date + * (as opposed to a date-time) + * @param {Timezone=} aZone Timezone this position occurs in + */ + fromData(aData, aZone) { + if (aData) { + for (let [key, value] of Object.entries(aData)) { + // ical type cannot be set + if (key === 'icaltype') continue; + this[key] = value; + } + } + + if (aZone) { + this.zone = aZone; + } + + if (aData && !("isDate" in aData)) { + this.isDate = !("hour" in aData); + } else if (aData && ("isDate" in aData)) { + this.isDate = aData.isDate; + } + + if (aData && "timezone" in aData) { + let zone = TimezoneService.get( + aData.timezone + ); + + this.zone = zone || Timezone.localTimezone; + } + + if (aData && "zone" in aData) { + this.zone = aData.zone; + } + + if (!this.zone) { + this.zone = Timezone.localTimezone; + } + + this._cachedUnixTime = null; + return this; + } + + /** + * Calculate the day of week. + * @param {weekDay=} aWeekStart + * The week start weekday, defaults to SUNDAY + * @return {weekDay} + */ + dayOfWeek(aWeekStart) { + let firstDow = aWeekStart || Time.SUNDAY; + let dowCacheKey = (this.year << 12) + (this.month << 8) + (this.day << 3) + firstDow; + if (dowCacheKey in Time._dowCache) { + return Time._dowCache[dowCacheKey]; + } + + // Using Zeller's algorithm + let q = this.day; + let m = this.month + (this.month < 3 ? 12 : 0); + let Y = this.year - (this.month < 3 ? 1 : 0); + + let h = (q + Y + trunc(((m + 1) * 26) / 10) + trunc(Y / 4)); + { // eslint-disable-line no-constant-condition + h += trunc(Y / 100) * 6 + trunc(Y / 400); + } + + // Normalize to 1 = wkst + h = ((h + 7 - firstDow) % 7) + 1; + Time._dowCache[dowCacheKey] = h; + return h; + } + + /** + * Calculate the day of year. + * @return {Number} + */ + dayOfYear() { + let is_leap = (Time.isLeapYear(this.year) ? 1 : 0); + let diypm = Time.daysInYearPassedMonth; + return diypm[is_leap][this.month - 1] + this.day; + } + + /** + * Returns a copy of the current date/time, rewound to the start of the + * week. The resulting ICAL.Time instance is of icaltype date, even if this + * is a date-time. + * + * @param {weekDay=} aWeekStart + * The week start weekday, defaults to SUNDAY + * @return {Time} The start of the week (cloned) + */ + startOfWeek(aWeekStart) { + let firstDow = aWeekStart || Time.SUNDAY; + let result = this.clone(); + result.day -= ((this.dayOfWeek() + 7 - firstDow) % 7); + result.isDate = true; + result.hour = 0; + result.minute = 0; + result.second = 0; + return result; + } + + /** + * Returns a copy of the current date/time, shifted to the end of the week. + * The resulting ICAL.Time instance is of icaltype date, even if this is a + * date-time. + * + * @param {weekDay=} aWeekStart + * The week start weekday, defaults to SUNDAY + * @return {Time} The end of the week (cloned) + */ + endOfWeek(aWeekStart) { + let firstDow = aWeekStart || Time.SUNDAY; + let result = this.clone(); + result.day += (7 - this.dayOfWeek() + firstDow - Time.SUNDAY) % 7; + result.isDate = true; + result.hour = 0; + result.minute = 0; + result.second = 0; + return result; + } + + /** + * Returns a copy of the current date/time, rewound to the start of the + * month. The resulting ICAL.Time instance is of icaltype date, even if + * this is a date-time. + * + * @return {Time} The start of the month (cloned) + */ + startOfMonth() { + let result = this.clone(); + result.day = 1; + result.isDate = true; + result.hour = 0; + result.minute = 0; + result.second = 0; + return result; + } + + /** + * Returns a copy of the current date/time, shifted to the end of the + * month. The resulting ICAL.Time instance is of icaltype date, even if + * this is a date-time. + * + * @return {Time} The end of the month (cloned) + */ + endOfMonth() { + let result = this.clone(); + result.day = Time.daysInMonth(result.month, result.year); + result.isDate = true; + result.hour = 0; + result.minute = 0; + result.second = 0; + return result; + } + + /** + * Returns a copy of the current date/time, rewound to the start of the + * year. The resulting ICAL.Time instance is of icaltype date, even if + * this is a date-time. + * + * @return {Time} The start of the year (cloned) + */ + startOfYear() { + let result = this.clone(); + result.day = 1; + result.month = 1; + result.isDate = true; + result.hour = 0; + result.minute = 0; + result.second = 0; + return result; + } + + /** + * Returns a copy of the current date/time, shifted to the end of the + * year. The resulting ICAL.Time instance is of icaltype date, even if + * this is a date-time. + * + * @return {Time} The end of the year (cloned) + */ + endOfYear() { + let result = this.clone(); + result.day = 31; + result.month = 12; + result.isDate = true; + result.hour = 0; + result.minute = 0; + result.second = 0; + return result; + } + + /** + * First calculates the start of the week, then returns the day of year for + * this date. If the day falls into the previous year, the day is zero or negative. + * + * @param {weekDay=} aFirstDayOfWeek + * The week start weekday, defaults to SUNDAY + * @return {Number} The calculated day of year + */ + startDoyWeek(aFirstDayOfWeek) { + let firstDow = aFirstDayOfWeek || Time.SUNDAY; + let delta = this.dayOfWeek() - firstDow; + if (delta < 0) delta += 7; + return this.dayOfYear() - delta; + } + + /** + * Get the dominical letter for the current year. Letters range from A - G + * for common years, and AG to GF for leap years. + * + * @param {Number} yr The year to retrieve the letter for + * @return {String} The dominical letter. + */ + getDominicalLetter() { + return Time.getDominicalLetter(this.year); + } + + /** + * Finds the nthWeekDay relative to the current month (not day). The + * returned value is a day relative the month that this month belongs to so + * 1 would indicate the first of the month and 40 would indicate a day in + * the following month. + * + * @param {Number} aDayOfWeek Day of the week see the day name constants + * @param {Number} aPos Nth occurrence of a given week day values + * of 1 and 0 both indicate the first weekday of that type. aPos may + * be either positive or negative + * + * @return {Number} numeric value indicating a day relative + * to the current month of this time object + */ + nthWeekDay(aDayOfWeek, aPos) { + let daysInMonth = Time.daysInMonth(this.month, this.year); + let weekday; + let pos = aPos; + + let start = 0; + + let otherDay = this.clone(); + + if (pos >= 0) { + otherDay.day = 1; + + // because 0 means no position has been given + // 1 and 0 indicate the same day. + if (pos != 0) { + // remove the extra numeric value + pos--; + } + + // set current start offset to current day. + start = otherDay.day; + + // find the current day of week + let startDow = otherDay.dayOfWeek(); + + // calculate the difference between current + // day of the week and desired day of the week + let offset = aDayOfWeek - startDow; + + + // if the offset goes into the past + // week we add 7 so it goes into the next + // week. We only want to go forward in time here. + if (offset < 0) + // this is really important otherwise we would + // end up with dates from in the past. + offset += 7; + + // add offset to start so start is the same + // day of the week as the desired day of week. + start += offset; + + // because we are going to add (and multiply) + // the numeric value of the day we subtract it + // from the start position so not to add it twice. + start -= aDayOfWeek; + + // set week day + weekday = aDayOfWeek; + } else { + + // then we set it to the last day in the current month + otherDay.day = daysInMonth; + + // find the ends weekday + let endDow = otherDay.dayOfWeek(); + + pos++; + + weekday = (endDow - aDayOfWeek); + + if (weekday < 0) { + weekday += 7; + } + + weekday = daysInMonth - weekday; + } + + weekday += pos * 7; + + return start + weekday; + } + + /** + * Checks if current time is the nth weekday, relative to the current + * month. Will always return false when rule resolves outside of current + * month. + * + * @param {weekDay} aDayOfWeek Day of week to check + * @param {Number} aPos Relative position + * @return {Boolean} True, if it is the nth weekday + */ + isNthWeekDay(aDayOfWeek, aPos) { + let dow = this.dayOfWeek(); + + if (aPos === 0 && dow === aDayOfWeek) { + return true; + } + + // get pos + let day = this.nthWeekDay(aDayOfWeek, aPos); + + if (day === this.day) { + return true; + } + + return false; + } + + /** + * Calculates the ISO 8601 week number. The first week of a year is the + * week that contains the first Thursday. The year can have 53 weeks, if + * January 1st is a Friday. + * + * Note there are regions where the first week of the year is the one that + * starts on January 1st, which may offset the week number. Also, if a + * different week start is specified, this will also affect the week + * number. + * + * @see Time.weekOneStarts + * @param {weekDay} aWeekStart The weekday the week starts with + * @return {Number} The ISO week number + */ + weekNumber(aWeekStart) { + let wnCacheKey = (this.year << 12) + (this.month << 8) + (this.day << 3) + aWeekStart; + if (wnCacheKey in Time._wnCache) { + return Time._wnCache[wnCacheKey]; + } + // This function courtesty of Julian Bucknall, published under the MIT license + // http://www.boyet.com/articles/publishedarticles/calculatingtheisoweeknumb.html + // plus some fixes to be able to use different week starts. + let week1; + + let dt = this.clone(); + dt.isDate = true; + let isoyear = this.year; + + if (dt.month == 12 && dt.day > 25) { + week1 = Time.weekOneStarts(isoyear + 1, aWeekStart); + if (dt.compare(week1) < 0) { + week1 = Time.weekOneStarts(isoyear, aWeekStart); + } else { + isoyear++; + } + } else { + week1 = Time.weekOneStarts(isoyear, aWeekStart); + if (dt.compare(week1) < 0) { + week1 = Time.weekOneStarts(--isoyear, aWeekStart); + } + } + + let daysBetween = (dt.subtractDate(week1).toSeconds() / 86400); + let answer = trunc(daysBetween / 7) + 1; + Time._wnCache[wnCacheKey] = answer; + return answer; + } + + /** + * Adds the duration to the current time. The instance is modified in + * place. + * + * @param {Duration} aDuration The duration to add + */ + addDuration(aDuration) { + let mult = (aDuration.isNegative ? -1 : 1); + + // because of the duration optimizations it is much + // more efficient to grab all the values up front + // then set them directly (which will avoid a normalization call). + // So we don't actually normalize until we need it. + let second = this.second; + let minute = this.minute; + let hour = this.hour; + let day = this.day; + + second += mult * aDuration.seconds; + minute += mult * aDuration.minutes; + hour += mult * aDuration.hours; + day += mult * aDuration.days; + day += mult * 7 * aDuration.weeks; + + this.second = second; + this.minute = minute; + this.hour = hour; + this.day = day; + + this._cachedUnixTime = null; + } + + /** + * Subtract the date details (_excluding_ timezone). Useful for finding + * the relative difference between two time objects excluding their + * timezone differences. + * + * @param {Time} aDate The date to subtract + * @return {Duration} The difference as a duration + */ + subtractDate(aDate) { + let unixTime = this.toUnixTime() + this.utcOffset(); + let other = aDate.toUnixTime() + aDate.utcOffset(); + return Duration.fromSeconds(unixTime - other); + } + + /** + * Subtract the date details, taking timezones into account. + * + * @param {Time} aDate The date to subtract + * @return {Duration} The difference in duration + */ + subtractDateTz(aDate) { + let unixTime = this.toUnixTime(); + let other = aDate.toUnixTime(); + return Duration.fromSeconds(unixTime - other); + } + + /** + * Compares the ICAL.Time instance with another one. + * + * @param {Duration} aOther The instance to compare with + * @return {Number} -1, 0 or 1 for less/equal/greater + */ + compare(other) { + let a = this.toUnixTime(); + let b = other.toUnixTime(); + + if (a > b) return 1; + if (b > a) return -1; + return 0; + } + + /** + * Compares only the date part of this instance with another one. + * + * @param {Duration} other The instance to compare with + * @param {Timezone} tz The timezone to compare in + * @return {Number} -1, 0 or 1 for less/equal/greater + */ + compareDateOnlyTz(other, tz) { + let a = this.convertToZone(tz); + let b = other.convertToZone(tz); + let rc = 0; + + if ((rc = Time._cmp_attr(a, b, "year")) != 0) return rc; + if ((rc = Time._cmp_attr(a, b, "month")) != 0) return rc; + if ((rc = Time._cmp_attr(a, b, "day")) != 0) return rc; + + return rc; + } + + /** + * Convert the instance into another timezone. The returned ICAL.Time + * instance is always a copy. + * + * @param {Timezone} zone The zone to convert to + * @return {Time} The copy, converted to the zone + */ + convertToZone(zone) { + let copy = this.clone(); + let zone_equals = (this.zone.tzid == zone.tzid); + + if (!this.isDate && !zone_equals) { + Timezone.convert_time(copy, this.zone, zone); + } + + copy.zone = zone; + return copy; + } + + /** + * Calculates the UTC offset of the current date/time in the timezone it is + * in. + * + * @return {Number} UTC offset in seconds + */ + utcOffset() { + if (this.zone == Timezone.localTimezone || + this.zone == Timezone.utcTimezone) { + return 0; + } else { + return this.zone.utcOffset(this); + } + } + + /** + * Returns an RFC 5545 compliant ical representation of this object. + * + * @return {String} ical date/date-time + */ + toICALString() { + let string = this.toString(); + + if (string.length > 10) { + return design$1.icalendar.value['date-time'].toICAL(string); + } else { + return design$1.icalendar.value.date.toICAL(string); + } + } + + /** + * The string representation of this date/time, in jCal form + * (including : and - separators). + * @return {String} + */ + toString() { + let result = this.year + '-' + + pad2(this.month) + '-' + + pad2(this.day); + + if (!this.isDate) { + result += 'T' + pad2(this.hour) + ':' + + pad2(this.minute) + ':' + + pad2(this.second); + + if (this.zone === Timezone.utcTimezone) { + result += 'Z'; + } + } + + return result; + } + + /** + * Converts the current instance to a Javascript date + * @return {Date} + */ + toJSDate() { + if (this.zone == Timezone.localTimezone) { + if (this.isDate) { + return new Date(this.year, this.month - 1, this.day); + } else { + return new Date(this.year, this.month - 1, this.day, + this.hour, this.minute, this.second, 0); + } + } else { + return new Date(this.toUnixTime() * 1000); + } + } + + _normalize() { + if (this._time.isDate) { + this._time.hour = 0; + this._time.minute = 0; + this._time.second = 0; + } + this.adjust(0, 0, 0, 0); + + return this; + } + + /** + * Adjust the date/time by the given offset + * + * @param {Number} aExtraDays The extra amount of days + * @param {Number} aExtraHours The extra amount of hours + * @param {Number} aExtraMinutes The extra amount of minutes + * @param {Number} aExtraSeconds The extra amount of seconds + * @param {Number=} aTime The time to adjust, defaults to the + * current instance. + */ + adjust(aExtraDays, aExtraHours, aExtraMinutes, aExtraSeconds, aTime) { + + let minutesOverflow, hoursOverflow, + daysOverflow = 0, yearsOverflow = 0; + + let second, minute, hour, day; + let daysInMonth; + + let time = aTime || this._time; + + if (!time.isDate) { + second = time.second + aExtraSeconds; + time.second = second % 60; + minutesOverflow = trunc(second / 60); + if (time.second < 0) { + time.second += 60; + minutesOverflow--; + } + + minute = time.minute + aExtraMinutes + minutesOverflow; + time.minute = minute % 60; + hoursOverflow = trunc(minute / 60); + if (time.minute < 0) { + time.minute += 60; + hoursOverflow--; + } + + hour = time.hour + aExtraHours + hoursOverflow; + + time.hour = hour % 24; + daysOverflow = trunc(hour / 24); + if (time.hour < 0) { + time.hour += 24; + daysOverflow--; + } + } + + + // Adjust month and year first, because we need to know what month the day + // is in before adjusting it. + if (time.month > 12) { + yearsOverflow = trunc((time.month - 1) / 12); + } else if (time.month < 1) { + yearsOverflow = trunc(time.month / 12) - 1; + } + + time.year += yearsOverflow; + time.month -= 12 * yearsOverflow; + + // Now take care of the days (and adjust month if needed) + day = time.day + aExtraDays + daysOverflow; + + if (day > 0) { + for (;;) { + daysInMonth = Time.daysInMonth(time.month, time.year); + if (day <= daysInMonth) { + break; + } + + time.month++; + if (time.month > 12) { + time.year++; + time.month = 1; + } + + day -= daysInMonth; + } + } else { + while (day <= 0) { + if (time.month == 1) { + time.year--; + time.month = 12; + } else { + time.month--; + } + + day += Time.daysInMonth(time.month, time.year); + } + } + + time.day = day; + + this._cachedUnixTime = null; + return this; + } + + /** + * Sets up the current instance from unix time, the number of seconds since + * January 1st, 1970. + * + * @param {Number} seconds The seconds to set up with + */ + fromUnixTime(seconds) { + this.zone = Timezone.utcTimezone; + // We could use `fromJSDate` here, but this is about twice as fast. + // We could also clone `epochTime` and use `adjust` for a more + // ical.js-centric approach, but this is about 100 times as fast. + let date = new Date(seconds * 1000); + this.year = date.getUTCFullYear(); + this.month = date.getUTCMonth() + 1; + this.day = date.getUTCDate(); + if (this._time.isDate) { + this.hour = 0; + this.minute = 0; + this.second = 0; + } else { + this.hour = date.getUTCHours(); + this.minute = date.getUTCMinutes(); + this.second = date.getUTCSeconds(); + } + + this._cachedUnixTime = null; + } + + /** + * Converts the current instance to seconds since January 1st 1970. + * + * @return {Number} Seconds since 1970 + */ + toUnixTime() { + if (this._cachedUnixTime !== null) { + return this._cachedUnixTime; + } + let offset = this.utcOffset(); + + // we use the offset trick to ensure + // that we are getting the actual UTC time + let ms = Date.UTC( + this.year, + this.month - 1, + this.day, + this.hour, + this.minute, + this.second - offset + ); + + // seconds + this._cachedUnixTime = ms / 1000; + return this._cachedUnixTime; + } + + /** + * Converts time to into Object which can be serialized then re-created + * using the constructor. + * + * @example + * // toJSON will automatically be called + * var json = JSON.stringify(mytime); + * + * var deserialized = JSON.parse(json); + * + * var time = new ICAL.Time(deserialized); + * + * @return {Object} + */ + toJSON() { + let copy = [ + 'year', + 'month', + 'day', + 'hour', + 'minute', + 'second', + 'isDate' + ]; + + let result = Object.create(null); + + let i = 0; + let len = copy.length; + let prop; + + for (; i < len; i++) { + prop = copy[i]; + result[prop] = this[prop]; + } + + if (this.zone) { + result.timezone = this.zone.tzid; + } + + return result; + } +} + +(function setupNormalizeAttributes() { + // This needs to run before any instances are created! + function defineAttr(attr) { + Object.defineProperty(Time.prototype, attr, { + get: function getTimeAttr() { + if (this._pendingNormalization) { + this._normalize(); + this._pendingNormalization = false; + } + + return this._time[attr]; + }, + set: function setTimeAttr(val) { + // Check if isDate will be set and if was not set to normalize date. + // This avoids losing days when seconds, minutes and hours are zeroed + // what normalize will do when time is a date. + if (attr === "isDate" && val && !this._time.isDate) { + this.adjust(0, 0, 0, 0); + } + this._cachedUnixTime = null; + this._pendingNormalization = true; + this._time[attr] = val; + } + }); + + } + + defineAttr("year"); + defineAttr("month"); + defineAttr("day"); + defineAttr("hour"); + defineAttr("minute"); + defineAttr("second"); + defineAttr("isDate"); +})(); + +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * Portions Copyright (C) Philipp Kewisch */ + +/** + * This lets typescript resolve our custom types in the + * generated d.ts files (jsdoc typedefs are converted to typescript types). + * Ignore prevents the typedefs from being documented more than once. + * + * @ignore + * @typedef {import("./types.js").parserState} parserState + * Imports the 'parserState' type from the "types.js" module + * @typedef {import("./types.js").designSet} designSet + * Imports the 'designSet' type from the "types.js" module + */ + +const CHAR = /[^ \t]/; +const VALUE_DELIMITER = ':'; +const PARAM_DELIMITER = ';'; +const PARAM_NAME_DELIMITER = '='; +const DEFAULT_VALUE_TYPE$1 = 'unknown'; +const DEFAULT_PARAM_TYPE = 'text'; +const RFC6868_REPLACE_MAP$1 = { "^'": '"', "^n": "\n", "^^": "^" }; + +/** + * Parses iCalendar or vCard data into a raw jCal object. Consult + * documentation on the {@tutorial layers|layers of parsing} for more + * details. + * + * @function ICAL.parse + * @memberof ICAL + * @variation function + * @todo Fix the API to be more clear on the return type + * @param {String} input The string data to parse + * @return {Object|Object[]} A single jCal object, or an array thereof + */ +function parse(input) { + let state = {}; + let root = state.component = []; + + state.stack = [root]; + + parse._eachLine(input, function(err, line) { + parse._handleContentLine(line, state); + }); + + + // when there are still items on the stack + // throw a fatal error, a component was not closed + // correctly in that case. + if (state.stack.length > 1) { + throw new ParserError( + 'invalid ical body. component began but did not end' + ); + } + + state = null; + + return (root.length == 1 ? root[0] : root); +} + +/** + * Parse an iCalendar property value into the jCal for a single property + * + * @function ICAL.parse.property + * @param {String} str + * The iCalendar property string to parse + * @param {designSet=} designSet + * The design data to use for this property + * @return {Object} + * The jCal Object containing the property + */ +parse.property = function(str, designSet) { + let state = { + component: [[], []], + designSet: designSet || design$1.defaultSet + }; + parse._handleContentLine(str, state); + return state.component[1][0]; +}; + +/** + * Convenience method to parse a component. You can use ICAL.parse() directly + * instead. + * + * @function ICAL.parse.component + * @see ICAL.parse(function) + * @param {String} str The iCalendar component string to parse + * @return {Object} The jCal Object containing the component + */ +parse.component = function(str) { + return parse(str); +}; + + +/** + * An error that occurred during parsing. + * + * @param {String} message The error message + * @memberof ICAL.parse + * @extends {Error} + */ +class ParserError extends Error { + name = this.constructor.name; +} + +// classes & constants +parse.ParserError = ParserError; + + +/** + * Handles a single line of iCalendar/vCard, updating the state. + * + * @private + * @function ICAL.parse._handleContentLine + * @param {String} line The content line to process + * @param {parserState} state The current state of the line parsing + */ +parse._handleContentLine = function(line, state) { + // break up the parts of the line + let valuePos = line.indexOf(VALUE_DELIMITER); + let paramPos = line.indexOf(PARAM_DELIMITER); + + let lastParamIndex; + let lastValuePos; + + // name of property or begin/end + let name; + let value; + // params is only overridden if paramPos !== -1. + // we can't do params = params || {} later on + // because it sacrifices ops. + let params = {}; + + /** + * Different property cases + * + * + * 1. RRULE:FREQ=foo + * // FREQ= is not a param but the value + * + * 2. ATTENDEE;ROLE=REQ-PARTICIPANT; + * // ROLE= is a param because : has not happened yet + */ + // when the parameter delimiter is after the + // value delimiter then it is not a parameter. + + if ((paramPos !== -1 && valuePos !== -1)) { + // when the parameter delimiter is after the + // value delimiter then it is not a parameter. + if (paramPos > valuePos) { + paramPos = -1; + } + } + + let parsedParams; + if (paramPos !== -1) { + name = line.slice(0, Math.max(0, paramPos)).toLowerCase(); + parsedParams = parse._parseParameters(line.slice(Math.max(0, paramPos)), 0, state.designSet); + if (parsedParams[2] == -1) { + throw new ParserError("Invalid parameters in '" + line + "'"); + } + params = parsedParams[0]; + lastParamIndex = parsedParams[1].length + parsedParams[2] + paramPos; + if ((lastValuePos = + line.slice(Math.max(0, lastParamIndex)).indexOf(VALUE_DELIMITER)) !== -1) { + value = line.slice(Math.max(0, lastParamIndex + lastValuePos + 1)); + } else { + throw new ParserError("Missing parameter value in '" + line + "'"); + } + } else if (valuePos !== -1) { + // without parmeters (BEGIN:VCAENDAR, CLASS:PUBLIC) + name = line.slice(0, Math.max(0, valuePos)).toLowerCase(); + value = line.slice(Math.max(0, valuePos + 1)); + + if (name === 'begin') { + let newComponent = [value.toLowerCase(), [], []]; + if (state.stack.length === 1) { + state.component.push(newComponent); + } else { + state.component[2].push(newComponent); + } + state.stack.push(state.component); + state.component = newComponent; + if (!state.designSet) { + state.designSet = design$1.getDesignSet(state.component[0]); + } + return; + } else if (name === 'end') { + state.component = state.stack.pop(); + return; + } + // If it is not begin/end, then this is a property with an empty value, + // which should be considered valid. + } else { + /** + * Invalid line. + * The rational to throw an error is we will + * never be certain that the rest of the file + * is sane and it is unlikely that we can serialize + * the result correctly either. + */ + throw new ParserError( + 'invalid line (no token ";" or ":") "' + line + '"' + ); + } + + let valueType; + let multiValue = false; + let structuredValue = false; + let propertyDetails; + let splitName; + let ungroupedName; + + // fetch the ungrouped part of the name + if (state.designSet.propertyGroups && name.indexOf('.') !== -1) { + splitName = name.split('.'); + params.group = splitName[0]; + ungroupedName = splitName[1]; + } else { + ungroupedName = name; + } + + if (ungroupedName in state.designSet.property) { + propertyDetails = state.designSet.property[ungroupedName]; + + if ('multiValue' in propertyDetails) { + multiValue = propertyDetails.multiValue; + } + + if ('structuredValue' in propertyDetails) { + structuredValue = propertyDetails.structuredValue; + } + + if (value && 'detectType' in propertyDetails) { + valueType = propertyDetails.detectType(value); + } + } + + // attempt to determine value + if (!valueType) { + if (!('value' in params)) { + if (propertyDetails) { + valueType = propertyDetails.defaultType; + } else { + valueType = DEFAULT_VALUE_TYPE$1; + } + } else { + // possible to avoid this? + valueType = params.value.toLowerCase(); + } + } + + delete params.value; + + /** + * Note on `var result` juggling: + * + * I observed that building the array in pieces has adverse + * effects on performance, so where possible we inline the creation. + * It is a little ugly but resulted in ~2000 additional ops/sec. + */ + + let result; + if (multiValue && structuredValue) { + value = parse._parseMultiValue(value, structuredValue, valueType, [], multiValue, state.designSet, structuredValue); + result = [ungroupedName, params, valueType, value]; + } else if (multiValue) { + result = [ungroupedName, params, valueType]; + parse._parseMultiValue(value, multiValue, valueType, result, null, state.designSet, false); + } else if (structuredValue) { + value = parse._parseMultiValue(value, structuredValue, valueType, [], null, state.designSet, structuredValue); + result = [ungroupedName, params, valueType, value]; + } else { + value = parse._parseValue(value, valueType, state.designSet, false); + result = [ungroupedName, params, valueType, value]; + } + // rfc6350 requires that in vCard 4.0 the first component is the VERSION + // component with as value 4.0, note that 3.0 does not have this requirement. + if (state.component[0] === 'vcard' && state.component[1].length === 0 && + !(name === 'version' && value === '4.0')) { + state.designSet = design$1.getDesignSet("vcard3"); + } + state.component[1].push(result); +}; + +/** + * Parse a value from the raw value into the jCard/jCal value. + * + * @private + * @function ICAL.parse._parseValue + * @param {String} value Original value + * @param {String} type Type of value + * @param {Object} designSet The design data to use for this value + * @return {Object} varies on type + */ +parse._parseValue = function(value, type, designSet, structuredValue) { + if (type in designSet.value && 'fromICAL' in designSet.value[type]) { + return designSet.value[type].fromICAL(value, structuredValue); + } + return value; +}; + +/** + * Parse parameters from a string to object. + * + * @function ICAL.parse._parseParameters + * @private + * @param {String} line A single unfolded line + * @param {Number} start Position to start looking for properties + * @param {Object} designSet The design data to use for this property + * @return {Object} key/value pairs + */ +parse._parseParameters = function(line, start, designSet) { + let lastParam = start; + let pos = 0; + let delim = PARAM_NAME_DELIMITER; + let result = {}; + let name, lcname; + let value, valuePos = -1; + let type, multiValue, mvdelim; + + // find the next '=' sign + // use lastParam and pos to find name + // check if " is used if so get value from "->" + // then increment pos to find next ; + + while ((pos !== false) && + (pos = line.indexOf(delim, pos + 1)) !== -1) { + + name = line.slice(lastParam + 1, pos); + if (name.length == 0) { + throw new ParserError("Empty parameter name in '" + line + "'"); + } + lcname = name.toLowerCase(); + mvdelim = false; + multiValue = false; + + if (lcname in designSet.param && designSet.param[lcname].valueType) { + type = designSet.param[lcname].valueType; + } else { + type = DEFAULT_PARAM_TYPE; + } + + if (lcname in designSet.param) { + multiValue = designSet.param[lcname].multiValue; + if (designSet.param[lcname].multiValueSeparateDQuote) { + mvdelim = parse._rfc6868Escape('"' + multiValue + '"'); + } + } + + let nextChar = line[pos + 1]; + if (nextChar === '"') { + valuePos = pos + 2; + pos = line.indexOf('"', valuePos); + if (multiValue && pos != -1) { + let extendedValue = true; + while (extendedValue) { + if (line[pos + 1] == multiValue && line[pos + 2] == '"') { + pos = line.indexOf('"', pos + 3); + } else { + extendedValue = false; + } + } + } + if (pos === -1) { + throw new ParserError( + 'invalid line (no matching double quote) "' + line + '"' + ); + } + value = line.slice(valuePos, pos); + lastParam = line.indexOf(PARAM_DELIMITER, pos); + let propValuePos = line.indexOf(VALUE_DELIMITER, pos); + // if either no next parameter or delimeter in property value, let's stop here + if (lastParam === -1 || (propValuePos !== -1 && lastParam > propValuePos)) { + pos = false; + } + } else { + valuePos = pos + 1; + + // move to next ";" + let nextPos = line.indexOf(PARAM_DELIMITER, valuePos); + let propValuePos = line.indexOf(VALUE_DELIMITER, valuePos); + if (propValuePos !== -1 && nextPos > propValuePos) { + // this is a delimiter in the property value, let's stop here + nextPos = propValuePos; + pos = false; + } else if (nextPos === -1) { + // no ";" + if (propValuePos === -1) { + nextPos = line.length; + } else { + nextPos = propValuePos; + } + pos = false; + } else { + lastParam = nextPos; + pos = nextPos; + } + + value = line.slice(valuePos, nextPos); + } + + const length_before = value.length; + value = parse._rfc6868Escape(value); + valuePos += length_before - value.length; + if (multiValue) { + let delimiter = mvdelim || multiValue; + value = parse._parseMultiValue(value, delimiter, type, [], null, designSet); + } else { + value = parse._parseValue(value, type, designSet); + } + + if (multiValue && (lcname in result)) { + if (Array.isArray(result[lcname])) { + result[lcname].push(value); + } else { + result[lcname] = [ + result[lcname], + value + ]; + } + } else { + result[lcname] = value; + } + } + return [result, value, valuePos]; +}; + +/** + * Internal helper for rfc6868. Exposing this on ICAL.parse so that + * hackers can disable the rfc6868 parsing if the really need to. + * + * @function ICAL.parse._rfc6868Escape + * @param {String} val The value to escape + * @return {String} The escaped value + */ +parse._rfc6868Escape = function(val) { + return val.replace(/\^['n^]/g, function(x) { + return RFC6868_REPLACE_MAP$1[x]; + }); +}; + +/** + * Parse a multi value string. This function is used either for parsing + * actual multi-value property's values, or for handling parameter values. It + * can be used for both multi-value properties and structured value properties. + * + * @private + * @function ICAL.parse._parseMultiValue + * @param {String} buffer The buffer containing the full value + * @param {String} delim The multi-value delimiter + * @param {String} type The value type to be parsed + * @param {Array.} result The array to append results to, varies on value type + * @param {String} innerMulti The inner delimiter to split each value with + * @param {designSet} designSet The design data for this value + * @return {?|Array.} Either an array of results, or the first result + */ +parse._parseMultiValue = function(buffer, delim, type, result, innerMulti, designSet, structuredValue) { + let pos = 0; + let lastPos = 0; + let value; + if (delim.length === 0) { + return buffer; + } + + // split each piece + while ((pos = unescapedIndexOf(buffer, delim, lastPos)) !== -1) { + value = buffer.slice(lastPos, pos); + if (innerMulti) { + value = parse._parseMultiValue(value, innerMulti, type, [], null, designSet, structuredValue); + } else { + value = parse._parseValue(value, type, designSet, structuredValue); + } + result.push(value); + lastPos = pos + delim.length; + } + + // on the last piece take the rest of string + value = buffer.slice(lastPos); + if (innerMulti) { + value = parse._parseMultiValue(value, innerMulti, type, [], null, designSet, structuredValue); + } else { + value = parse._parseValue(value, type, designSet, structuredValue); + } + result.push(value); + + return result.length == 1 ? result[0] : result; +}; + +/** + * Process a complete buffer of iCalendar/vCard data line by line, correctly + * unfolding content. Each line will be processed with the given callback + * + * @private + * @function ICAL.parse._eachLine + * @param {String} buffer The buffer to process + * @param {function(?String, String)} callback The callback for each line + */ +parse._eachLine = function(buffer, callback) { + let len = buffer.length; + let lastPos = buffer.search(CHAR); + let pos = lastPos; + let line; + let firstChar; + + let newlineOffset; + + do { + pos = buffer.indexOf('\n', lastPos) + 1; + + if (pos > 1 && buffer[pos - 2] === '\r') { + newlineOffset = 2; + } else { + newlineOffset = 1; + } + + if (pos === 0) { + pos = len; + newlineOffset = 0; + } + + firstChar = buffer[lastPos]; + + if (firstChar === ' ' || firstChar === '\t') { + // add to line + line += buffer.slice(lastPos + 1, pos - newlineOffset); + } else { + if (line) + callback(null, line); + // push line + line = buffer.slice(lastPos, pos - newlineOffset); + } + + lastPos = pos; + } while (pos !== len); + + // extra ending line + line = line.trim(); + + if (line.length) + callback(null, line); +}; + +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * Portions Copyright (C) Philipp Kewisch */ + +const OPTIONS = ["tzid", "location", "tznames", "latitude", "longitude"]; + +/** + * Timezone representation. + * + * @example + * var vcalendar; + * var timezoneComp = vcalendar.getFirstSubcomponent('vtimezone'); + * var tzid = timezoneComp.getFirstPropertyValue('tzid'); + * + * var timezone = new ICAL.Timezone({ + * component: timezoneComp, + * tzid + * }); + * + * @memberof ICAL + */ +class Timezone { + static _compare_change_fn(a, b) { + if (a.year < b.year) return -1; + else if (a.year > b.year) return 1; + + if (a.month < b.month) return -1; + else if (a.month > b.month) return 1; + + if (a.day < b.day) return -1; + else if (a.day > b.day) return 1; + + if (a.hour < b.hour) return -1; + else if (a.hour > b.hour) return 1; + + if (a.minute < b.minute) return -1; + else if (a.minute > b.minute) return 1; + + if (a.second < b.second) return -1; + else if (a.second > b.second) return 1; + + return 0; + } + + /** + * Convert the date/time from one zone to the next. + * + * @param {Time} tt The time to convert + * @param {Timezone} from_zone The source zone to convert from + * @param {Timezone} to_zone The target zone to convert to + * @return {Time} The converted date/time object + */ + static convert_time(tt, from_zone, to_zone) { + if (tt.isDate || + from_zone.tzid == to_zone.tzid || + from_zone == Timezone.localTimezone || + to_zone == Timezone.localTimezone) { + tt.zone = to_zone; + return tt; + } + + let utcOffset = from_zone.utcOffset(tt); + tt.adjust(0, 0, 0, - utcOffset); + + utcOffset = to_zone.utcOffset(tt); + tt.adjust(0, 0, 0, utcOffset); + + return null; + } + + /** + * Creates a new ICAL.Timezone instance from the passed data object. + * + * @param {Component|Object} aData options for class + * @param {String|Component} aData.component + * If aData is a simple object, then this member can be set to either a + * string containing the component data, or an already parsed + * ICAL.Component + * @param {String} aData.tzid The timezone identifier + * @param {String} aData.location The timezone locationw + * @param {String} aData.tznames An alternative string representation of the + * timezone + * @param {Number} aData.latitude The latitude of the timezone + * @param {Number} aData.longitude The longitude of the timezone + */ + static fromData(aData) { + let tt = new Timezone(); + return tt.fromData(aData); + } + + /** + * The instance describing the UTC timezone + * @type {Timezone} + * @constant + * @instance + */ + static #utcTimezone = null; + static get utcTimezone() { + if (!this.#utcTimezone) { + this.#utcTimezone = Timezone.fromData({ + tzid: "UTC" + }); + } + return this.#utcTimezone; + } + + /** + * The instance describing the local timezone + * @type {Timezone} + * @constant + * @instance + */ + static #localTimezone = null; + static get localTimezone() { + if (!this.#localTimezone) { + this.#localTimezone = Timezone.fromData({ + tzid: "floating" + }); + } + return this.#localTimezone; + } + + /** + * Adjust a timezone change object. + * @private + * @param {Object} change The timezone change object + * @param {Number} days The extra amount of days + * @param {Number} hours The extra amount of hours + * @param {Number} minutes The extra amount of minutes + * @param {Number} seconds The extra amount of seconds + */ + static adjust_change(change, days, hours, minutes, seconds) { + return Time.prototype.adjust.call( + change, + days, + hours, + minutes, + seconds, + change + ); + } + + static _minimumExpansionYear = -1; + static EXTRA_COVERAGE = 5; + + /** + * Creates a new ICAL.Timezone instance, by passing in a tzid and component. + * + * @param {Component|Object} data options for class + * @param {String|Component} data.component + * If data is a simple object, then this member can be set to either a + * string containing the component data, or an already parsed + * ICAL.Component + * @param {String} data.tzid The timezone identifier + * @param {String} data.location The timezone locationw + * @param {String} data.tznames An alternative string representation of the + * timezone + * @param {Number} data.latitude The latitude of the timezone + * @param {Number} data.longitude The longitude of the timezone + */ + constructor(data) { + this.wrappedJSObject = this; + this.fromData(data); + } + + + /** + * Timezone identifier + * @type {String} + */ + tzid = ""; + + /** + * Timezone location + * @type {String} + */ + location = ""; + + /** + * Alternative timezone name, for the string representation + * @type {String} + */ + tznames = ""; + + /** + * The primary latitude for the timezone. + * @type {Number} + */ + latitude = 0.0; + + /** + * The primary longitude for the timezone. + * @type {Number} + */ + longitude = 0.0; + + /** + * The vtimezone component for this timezone. + * @type {Component} + */ + component = null; + + /** + * The year this timezone has been expanded to. All timezone transition + * dates until this year are known and can be used for calculation + * + * @private + * @type {Number} + */ + expandedUntilYear = 0; + + /** + * The class identifier. + * @constant + * @type {String} + * @default "icaltimezone" + */ + icalclass = "icaltimezone"; + + /** + * Sets up the current instance using members from the passed data object. + * + * @param {Component|Object} aData options for class + * @param {String|Component} aData.component + * If aData is a simple object, then this member can be set to either a + * string containing the component data, or an already parsed + * ICAL.Component + * @param {String} aData.tzid The timezone identifier + * @param {String} aData.location The timezone locationw + * @param {String} aData.tznames An alternative string representation of the + * timezone + * @param {Number} aData.latitude The latitude of the timezone + * @param {Number} aData.longitude The longitude of the timezone + */ + fromData(aData) { + this.expandedUntilYear = 0; + this.changes = []; + + if (aData instanceof Component) { + // Either a component is passed directly + this.component = aData; + } else { + // Otherwise the component may be in the data object + if (aData && "component" in aData) { + if (typeof aData.component == "string") { + // If a string was passed, parse it as a component + let jCal = parse(aData.component); + this.component = new Component(jCal); + } else if (aData.component instanceof Component) { + // If it was a component already, then just set it + this.component = aData.component; + } else { + // Otherwise just null out the component + this.component = null; + } + } + + // Copy remaining passed properties + for (let prop of OPTIONS) { + if (aData && prop in aData) { + this[prop] = aData[prop]; + } + } + } + + // If we have a component but no TZID, attempt to get it from the + // component's properties. + if (this.component instanceof Component && !this.tzid) { + this.tzid = this.component.getFirstPropertyValue('tzid'); + } + + return this; + } + + /** + * Finds the utcOffset the given time would occur in this timezone. + * + * @param {Time} tt The time to check for + * @return {Number} utc offset in seconds + */ + utcOffset(tt) { + if (this == Timezone.utcTimezone || this == Timezone.localTimezone) { + return 0; + } + + this._ensureCoverage(tt.year); + + if (!this.changes.length) { + return 0; + } + + let tt_change = { + year: tt.year, + month: tt.month, + day: tt.day, + hour: tt.hour, + minute: tt.minute, + second: tt.second + }; + + let change_num = this._findNearbyChange(tt_change); + let change_num_to_use = -1; + let step = 1; + + // TODO: replace with bin search? + for (;;) { + let change = clone(this.changes[change_num], true); + if (change.utcOffset < change.prevUtcOffset) { + Timezone.adjust_change(change, 0, 0, 0, change.utcOffset); + } else { + Timezone.adjust_change(change, 0, 0, 0, + change.prevUtcOffset); + } + + let cmp = Timezone._compare_change_fn(tt_change, change); + + if (cmp >= 0) { + change_num_to_use = change_num; + } else { + step = -1; + } + + if (step == -1 && change_num_to_use != -1) { + break; + } + + change_num += step; + + if (change_num < 0) { + return 0; + } + + if (change_num >= this.changes.length) { + break; + } + } + + let zone_change = this.changes[change_num_to_use]; + let utcOffset_change = zone_change.utcOffset - zone_change.prevUtcOffset; + + if (utcOffset_change < 0 && change_num_to_use > 0) { + let tmp_change = clone(zone_change, true); + Timezone.adjust_change(tmp_change, 0, 0, 0, tmp_change.prevUtcOffset); + + if (Timezone._compare_change_fn(tt_change, tmp_change) < 0) { + let prev_zone_change = this.changes[change_num_to_use - 1]; + + let want_daylight = false; // TODO + + if (zone_change.is_daylight != want_daylight && + prev_zone_change.is_daylight == want_daylight) { + zone_change = prev_zone_change; + } + } + } + + // TODO return is_daylight? + return zone_change.utcOffset; + } + + _findNearbyChange(change) { + // find the closest match + let idx = binsearchInsert( + this.changes, + change, + Timezone._compare_change_fn + ); + + if (idx >= this.changes.length) { + return this.changes.length - 1; + } + + return idx; + } + + _ensureCoverage(aYear) { + if (Timezone._minimumExpansionYear == -1) { + let today = Time.now(); + Timezone._minimumExpansionYear = today.year; + } + + let changesEndYear = aYear; + if (changesEndYear < Timezone._minimumExpansionYear) { + changesEndYear = Timezone._minimumExpansionYear; + } + + changesEndYear += Timezone.EXTRA_COVERAGE; + + if (!this.changes.length || this.expandedUntilYear < aYear) { + let subcomps = this.component.getAllSubcomponents(); + let compLen = subcomps.length; + let compIdx = 0; + + for (; compIdx < compLen; compIdx++) { + this._expandComponent( + subcomps[compIdx], changesEndYear, this.changes + ); + } + + this.changes.sort(Timezone._compare_change_fn); + this.expandedUntilYear = changesEndYear; + } + } + + _expandComponent(aComponent, aYear, changes) { + if (!aComponent.hasProperty("dtstart") || + !aComponent.hasProperty("tzoffsetto") || + !aComponent.hasProperty("tzoffsetfrom")) { + return null; + } + + let dtstart = aComponent.getFirstProperty("dtstart").getFirstValue(); + let change; + + function convert_tzoffset(offset) { + return offset.factor * (offset.hours * 3600 + offset.minutes * 60); + } + + function init_changes() { + let changebase = {}; + changebase.is_daylight = (aComponent.name == "daylight"); + changebase.utcOffset = convert_tzoffset( + aComponent.getFirstProperty("tzoffsetto").getFirstValue() + ); + + changebase.prevUtcOffset = convert_tzoffset( + aComponent.getFirstProperty("tzoffsetfrom").getFirstValue() + ); + + return changebase; + } + + if (!aComponent.hasProperty("rrule") && !aComponent.hasProperty("rdate")) { + change = init_changes(); + change.year = dtstart.year; + change.month = dtstart.month; + change.day = dtstart.day; + change.hour = dtstart.hour; + change.minute = dtstart.minute; + change.second = dtstart.second; + + Timezone.adjust_change(change, 0, 0, 0, -change.prevUtcOffset); + changes.push(change); + } else { + let props = aComponent.getAllProperties("rdate"); + for (let rdate of props) { + let time = rdate.getFirstValue(); + change = init_changes(); + + change.year = time.year; + change.month = time.month; + change.day = time.day; + + if (time.isDate) { + change.hour = dtstart.hour; + change.minute = dtstart.minute; + change.second = dtstart.second; + + if (dtstart.zone != Timezone.utcTimezone) { + Timezone.adjust_change(change, 0, 0, 0, -change.prevUtcOffset); + } + } else { + change.hour = time.hour; + change.minute = time.minute; + change.second = time.second; + + if (time.zone != Timezone.utcTimezone) { + Timezone.adjust_change(change, 0, 0, 0, -change.prevUtcOffset); + } + } + + changes.push(change); + } + + let rrule = aComponent.getFirstProperty("rrule"); + + if (rrule) { + rrule = rrule.getFirstValue(); + change = init_changes(); + + if (rrule.until && rrule.until.zone == Timezone.utcTimezone) { + rrule.until.adjust(0, 0, 0, change.prevUtcOffset); + rrule.until.zone = Timezone.localTimezone; + } + + let iterator = rrule.iterator(dtstart); + + let occ; + while ((occ = iterator.next())) { + change = init_changes(); + if (occ.year > aYear || !occ) { + break; + } + + change.year = occ.year; + change.month = occ.month; + change.day = occ.day; + change.hour = occ.hour; + change.minute = occ.minute; + change.second = occ.second; + change.isDate = occ.isDate; + + Timezone.adjust_change(change, 0, 0, 0, -change.prevUtcOffset); + changes.push(change); + } + } + } + + return changes; + } + + /** + * The string representation of this timezone. + * @return {String} + */ + toString() { + return (this.tznames ? this.tznames : this.tzid); + } +} + +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * Portions Copyright (C) Philipp Kewisch */ + +let zones = null; + +/** + * @classdesc + * Singleton class to contain timezones. Right now it is all manual registry in + * the future we may use this class to download timezone information or handle + * loading pre-expanded timezones. + * + * @exports module:ICAL.TimezoneService + * @memberof ICAL + */ +const TimezoneService = { + get count() { + if (zones === null) { + return 0; + } + + return Object.keys(zones).length; + }, + + reset: function() { + zones = Object.create(null); + let utc = Timezone.utcTimezone; + + zones.Z = utc; + zones.UTC = utc; + zones.GMT = utc; + }, + _hard_reset: function() { + zones = null; + }, + + /** + * Checks if timezone id has been registered. + * + * @param {String} tzid Timezone identifier (e.g. America/Los_Angeles) + * @return {Boolean} False, when not present + */ + has: function(tzid) { + if (zones === null) { + return false; + } + + return !!zones[tzid]; + }, + + /** + * Returns a timezone by its tzid if present. + * + * @param {String} tzid Timezone identifier (e.g. America/Los_Angeles) + * @return {Timezone | undefined} The timezone, or undefined if not found + */ + get: function(tzid) { + if (zones === null) { + this.reset(); + } + + return zones[tzid]; + }, + + /** + * Registers a timezone object or component. + * + * @param {Component|Timezone} timezone + * The initialized zone or vtimezone. + * + * @param {String=} name + * The name of the timezone. Defaults to the component's TZID if not + * passed. + */ + register: function(timezone, name) { + if (zones === null) { + this.reset(); + } + + // This avoids a breaking change by the change of argument order + // TODO remove in v3 + if (typeof timezone === "string" && name instanceof Timezone) { + [timezone, name] = [name, timezone]; + } + + if (!name) { + if (timezone instanceof Timezone) { + name = timezone.tzid; + } else { + if (timezone.name === 'vtimezone') { + timezone = new Timezone(timezone); + name = timezone.tzid; + } + } + } + + if (!name) { + throw new TypeError("Neither a timezone nor a name was passed"); + } + + if (timezone instanceof Timezone) { + zones[name] = timezone; + } else { + throw new TypeError('timezone must be ICAL.Timezone or ICAL.Component'); + } + }, + + /** + * Removes a timezone by its tzid from the list. + * + * @param {String} tzid Timezone identifier (e.g. America/Los_Angeles) + * @return {?Timezone} The removed timezone, or null if not registered + */ + remove: function(tzid) { + if (zones === null) { + return null; + } + + return (delete zones[tzid]); + } +}; + +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * Portions Copyright (C) Philipp Kewisch */ + +/** + * Helper functions used in various places within ical.js + * @module ICAL.helpers + */ + +/** + * Compiles a list of all referenced TZIDs in all subcomponents and + * removes any extra VTIMEZONE subcomponents. In addition, if any TZIDs + * are referenced by a component, but a VTIMEZONE does not exist, + * an attempt will be made to generate a VTIMEZONE using ICAL.TimezoneService. + * + * @param {Component} vcal The top-level VCALENDAR component. + * @return {Component} The ICAL.Component that was passed in. + */ +function updateTimezones(vcal) { + let allsubs, properties, vtimezones, reqTzid, i; + + if (!vcal || vcal.name !== "vcalendar") { + //not a top-level vcalendar component + return vcal; + } + + //Store vtimezone subcomponents in an object reference by tzid. + //Store properties from everything else in another array + allsubs = vcal.getAllSubcomponents(); + properties = []; + vtimezones = {}; + for (i = 0; i < allsubs.length; i++) { + if (allsubs[i].name === "vtimezone") { + let tzid = allsubs[i].getFirstProperty("tzid").getFirstValue(); + vtimezones[tzid] = allsubs[i]; + } else { + properties = properties.concat(allsubs[i].getAllProperties()); + } + } + + //create an object with one entry for each required tz + reqTzid = {}; + for (i = 0; i < properties.length; i++) { + let tzid = properties[i].getParameter("tzid"); + if (tzid) { + reqTzid[tzid] = true; + } + } + + //delete any vtimezones that are not on the reqTzid list. + for (let [tzid, comp] of Object.entries(vtimezones)) { + if (!reqTzid[tzid]) { + vcal.removeSubcomponent(comp); + } + } + + //create any missing, but registered timezones + for (let tzid of Object.keys(reqTzid)) { + if (!vtimezones[tzid] && TimezoneService.has(tzid)) { + vcal.addSubcomponent(TimezoneService.get(tzid).component); + } + } + + return vcal; +} + +/** + * Checks if the given type is of the number type and also NaN. + * + * @param {Number} number The number to check + * @return {Boolean} True, if the number is strictly NaN + */ +function isStrictlyNaN(number) { + return typeof(number) === 'number' && isNaN(number); +} + +/** + * Parses a string value that is expected to be an integer, when the valid is + * not an integer throws a decoration error. + * + * @param {String} string Raw string input + * @return {Number} Parsed integer + */ +function strictParseInt(string) { + let result = parseInt(string, 10); + + if (isStrictlyNaN(result)) { + throw new Error( + 'Could not extract integer from "' + string + '"' + ); + } + + return result; +} + +/** + * Creates or returns a class instance of a given type with the initialization + * data if the data is not already an instance of the given type. + * + * @example + * var time = new ICAL.Time(...); + * var result = ICAL.helpers.formatClassType(time, ICAL.Time); + * + * (result instanceof ICAL.Time) + * // => true + * + * result = ICAL.helpers.formatClassType({}, ICAL.Time); + * (result isntanceof ICAL.Time) + * // => true + * + * + * @param {Object} data object initialization data + * @param {Object} type object type (like ICAL.Time) + * @return {?} An instance of the found type. + */ +function formatClassType(data, type) { + if (typeof(data) === 'undefined') { + return undefined; + } + + if (data instanceof type) { + return data; + } + return new type(data); +} + +/** + * Identical to indexOf but will only match values when they are not preceded + * by a backslash character. + * + * @param {String} buffer String to search + * @param {String} search Value to look for + * @param {Number} pos Start position + * @return {Number} The position, or -1 if not found + */ +function unescapedIndexOf(buffer, search, pos) { + while ((pos = buffer.indexOf(search, pos)) !== -1) { + if (pos > 0 && buffer[pos - 1] === '\\') { + pos += 1; + } else { + return pos; + } + } + return -1; +} + +/** + * Find the index for insertion using binary search. + * + * @param {Array} list The list to search + * @param {?} seekVal The value to insert + * @param {function(?,?)} cmpfunc The comparison func, that can + * compare two seekVals + * @return {Number} The insert position + */ +function binsearchInsert(list, seekVal, cmpfunc) { + if (!list.length) + return 0; + + let low = 0, high = list.length - 1, + mid, cmpval; + + while (low <= high) { + mid = low + Math.floor((high - low) / 2); + cmpval = cmpfunc(seekVal, list[mid]); + + if (cmpval < 0) + high = mid - 1; + else if (cmpval > 0) + low = mid + 1; + else + break; + } + + if (cmpval < 0) + return mid; // insertion is displacing, so use mid outright. + else if (cmpval > 0) + return mid + 1; + else + return mid; +} + +/** + * Clone the passed object or primitive. By default a shallow clone will be + * executed. + * + * @param {*} aSrc The thing to clone + * @param {Boolean=} aDeep If true, a deep clone will be performed + * @return {*} The copy of the thing + */ +function clone(aSrc, aDeep) { + if (!aSrc || typeof aSrc != "object") { + return aSrc; + } else if (aSrc instanceof Date) { + return new Date(aSrc.getTime()); + } else if ("clone" in aSrc) { + return aSrc.clone(); + } else if (Array.isArray(aSrc)) { + let arr = []; + for (let i = 0; i < aSrc.length; i++) { + arr.push(aDeep ? clone(aSrc[i], true) : aSrc[i]); + } + return arr; + } else { + let obj = {}; + for (let [name, value] of Object.entries(aSrc)) { + if (aDeep) { + obj[name] = clone(value, true); + } else { + obj[name] = value; + } + } + return obj; + } +} + +/** + * Performs iCalendar line folding. A line ending character is inserted and + * the next line begins with a whitespace. + * + * @example + * SUMMARY:This line will be fold + * ed right in the middle of a word. + * + * @param {String} aLine The line to fold + * @return {String} The folded line + */ +function foldline(aLine) { + let result = ""; + let line = aLine || "", pos = 0, line_length = 0; + //pos counts position in line for the UTF-16 presentation + //line_length counts the bytes for the UTF-8 presentation + while (line.length) { + let cp = line.codePointAt(pos); + if (cp < 128) ++line_length; + else if (cp < 2048) line_length += 2;//needs 2 UTF-8 bytes + else if (cp < 65536) line_length += 3; + else line_length += 4; //cp is less than 1114112 + if (line_length < ICALmodule.foldLength + 1) + pos += cp > 65535 ? 2 : 1; + else { + result += ICALmodule.newLineChar + " " + line.slice(0, Math.max(0, pos)); + line = line.slice(Math.max(0, pos)); + pos = line_length = 0; + } + } + return result.slice(ICALmodule.newLineChar.length + 1); +} + +/** + * Pads the given string or number with zeros so it will have at least two + * characters. + * + * @param {String|Number} data The string or number to pad + * @return {String} The number padded as a string + */ +function pad2(data) { + if (typeof(data) !== 'string') { + // handle fractions. + if (typeof(data) === 'number') { + data = parseInt(data); + } + data = String(data); + } + + let len = data.length; + + switch (len) { + case 0: + return '00'; + case 1: + return '0' + data; + default: + return data; + } +} + +/** + * Truncates the given number, correctly handling negative numbers. + * + * @param {Number} number The number to truncate + * @return {Number} The truncated number + */ +function trunc(number) { + return (number < 0 ? Math.ceil(number) : Math.floor(number)); +} + +/** + * Poor-man's cross-browser object extension. Doesn't support all the + * features, but enough for our usage. Note that the target's properties are + * not overwritten with the source properties. + * + * @example + * var child = ICAL.helpers.extend(parent, { + * "bar": 123 + * }); + * + * @param {Object} source The object to extend + * @param {Object} target The object to extend with + * @return {Object} Returns the target. + */ +function extend(source, target) { + for (let key in source) { + let descr = Object.getOwnPropertyDescriptor(source, key); + if (descr && !Object.getOwnPropertyDescriptor(target, key)) { + Object.defineProperty(target, key, descr); + } + } + return target; +} + +var helpers = /*#__PURE__*/Object.freeze({ + __proto__: null, + updateTimezones: updateTimezones, + isStrictlyNaN: isStrictlyNaN, + strictParseInt: strictParseInt, + formatClassType: formatClassType, + unescapedIndexOf: unescapedIndexOf, + binsearchInsert: binsearchInsert, + clone: clone, + foldline: foldline, + pad2: pad2, + trunc: trunc, + extend: extend +}); + +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * Portions Copyright (C) Philipp Kewisch */ + +/** + * This class represents the "utc-offset" value type, with various calculation and manipulation + * methods. + * + * @memberof ICAL + */ +class UtcOffset { + /** + * Creates a new {@link ICAL.UtcOffset} instance from the passed string. + * + * @param {String} aString The string to parse + * @return {Duration} The created utc-offset instance + */ + static fromString(aString) { + // -05:00 + let options = {}; + //TODO: support seconds per rfc5545 ? + options.factor = (aString[0] === '+') ? 1 : -1; + options.hours = strictParseInt(aString.slice(1, 3)); + options.minutes = strictParseInt(aString.slice(4, 6)); + + return new UtcOffset(options); + } + + /** + * Creates a new {@link ICAL.UtcOffset} instance from the passed seconds + * value. + * + * @param {Number} aSeconds The number of seconds to convert + */ + static fromSeconds(aSeconds) { + let instance = new UtcOffset(); + instance.fromSeconds(aSeconds); + return instance; + } + + /** + * Creates a new ICAL.UtcOffset instance. + * + * @param {Object} aData An object with members of the utc offset + * @param {Number=} aData.hours The hours for the utc offset + * @param {Number=} aData.minutes The minutes in the utc offset + * @param {Number=} aData.factor The factor for the utc-offset, either -1 or 1 + */ + constructor(aData) { + this.fromData(aData); + } + + /** + * The hours in the utc-offset + * @type {Number} + */ + hours = 0; + + /** + * The minutes in the utc-offset + * @type {Number} + */ + minutes = 0; + + /** + * The sign of the utc offset, 1 for positive offset, -1 for negative + * offsets. + * @type {Number} + */ + factor = 1; + + /** + * The type name, to be used in the jCal object. + * @constant + * @type {String} + * @default "utc-offset" + */ + icaltype = "utc-offset"; + + /** + * Returns a clone of the utc offset object. + * + * @return {UtcOffset} The cloned object + */ + clone() { + return UtcOffset.fromSeconds(this.toSeconds()); + } + + /** + * Sets up the current instance using members from the passed data object. + * + * @param {Object} aData An object with members of the utc offset + * @param {Number=} aData.hours The hours for the utc offset + * @param {Number=} aData.minutes The minutes in the utc offset + * @param {Number=} aData.factor The factor for the utc-offset, either -1 or 1 + */ + fromData(aData) { + if (aData) { + for (let [key, value] of Object.entries(aData)) { + this[key] = value; + } + } + this._normalize(); + } + + /** + * Sets up the current instance from the given seconds value. The seconds + * value is truncated to the minute. Offsets are wrapped when the world + * ends, the hour after UTC+14:00 is UTC-12:00. + * + * @param {Number} aSeconds The seconds to convert into an offset + */ + fromSeconds(aSeconds) { + let secs = Math.abs(aSeconds); + + this.factor = aSeconds < 0 ? -1 : 1; + this.hours = trunc(secs / 3600); + + secs -= (this.hours * 3600); + this.minutes = trunc(secs / 60); + return this; + } + + /** + * Convert the current offset to a value in seconds + * + * @return {Number} The offset in seconds + */ + toSeconds() { + return this.factor * (60 * this.minutes + 3600 * this.hours); + } + + /** + * Compare this utc offset with another one. + * + * @param {UtcOffset} other The other offset to compare with + * @return {Number} -1, 0 or 1 for less/equal/greater + */ + compare(other) { + let a = this.toSeconds(); + let b = other.toSeconds(); + return (a > b) - (b > a); + } + + _normalize() { + // Range: 97200 seconds (with 1 hour inbetween) + let secs = this.toSeconds(); + let factor = this.factor; + while (secs < -43200) { // = UTC-12:00 + secs += 97200; + } + while (secs > 50400) { // = UTC+14:00 + secs -= 97200; + } + + this.fromSeconds(secs); + + // Avoid changing the factor when on zero seconds + if (secs == 0) { + this.factor = factor; + } + } + + /** + * The iCalendar string representation of this utc-offset. + * @return {String} + */ + toICALString() { + return design$1.icalendar.value['utc-offset'].toICAL(this.toString()); + } + + /** + * The string representation of this utc-offset. + * @return {String} + */ + toString() { + return (this.factor == 1 ? "+" : "-") + pad2(this.hours) + ':' + pad2(this.minutes); + } +} + +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * Portions Copyright (C) Philipp Kewisch */ + +/** + * Describes a vCard time, which has slight differences to the ICAL.Time. + * Properties can be null if not specified, for example for dates with + * reduced accuracy or truncation. + * + * Note that currently not all methods are correctly re-implemented for + * VCardTime. For example, comparison will have undefined results when some + * members are null. + * + * Also, normalization is not yet implemented for this class! + * + * @memberof ICAL + * @extends {ICAL.Time} + */ +class VCardTime extends Time { + /** + * Returns a new ICAL.VCardTime instance from a date and/or time string. + * + * @param {String} aValue The string to create from + * @param {String} aIcalType The type for this instance, e.g. date-and-or-time + * @return {VCardTime} The date/time instance + */ + static fromDateAndOrTimeString(aValue, aIcalType) { + function part(v, s, e) { + return v ? strictParseInt(v.slice(s, s + e)) : null; + } + let parts = aValue.split('T'); + let dt = parts[0], tmz = parts[1]; + let splitzone = tmz ? design$1.vcard.value.time._splitZone(tmz) : []; + let zone = splitzone[0], tm = splitzone[1]; + + let dtlen = dt ? dt.length : 0; + let tmlen = tm ? tm.length : 0; + + let hasDashDate = dt && dt[0] == '-' && dt[1] == '-'; + let hasDashTime = tm && tm[0] == '-'; + + let o = { + year: hasDashDate ? null : part(dt, 0, 4), + month: hasDashDate && (dtlen == 4 || dtlen == 7) ? part(dt, 2, 2) : dtlen == 7 ? part(dt, 5, 2) : dtlen == 10 ? part(dt, 5, 2) : null, + day: dtlen == 5 ? part(dt, 3, 2) : dtlen == 7 && hasDashDate ? part(dt, 5, 2) : dtlen == 10 ? part(dt, 8, 2) : null, + + hour: hasDashTime ? null : part(tm, 0, 2), + minute: hasDashTime && tmlen == 3 ? part(tm, 1, 2) : tmlen > 4 ? hasDashTime ? part(tm, 1, 2) : part(tm, 3, 2) : null, + second: tmlen == 4 ? part(tm, 2, 2) : tmlen == 6 ? part(tm, 4, 2) : tmlen == 8 ? part(tm, 6, 2) : null + }; + + if (zone == 'Z') { + zone = Timezone.utcTimezone; + } else if (zone && zone[3] == ':') { + zone = UtcOffset.fromString(zone); + } else { + zone = null; + } + + return new VCardTime(o, zone, aIcalType); + } + + + /** + * Creates a new ICAL.VCardTime instance. + * + * @param {Object} data The data for the time instance + * @param {Number=} data.year The year for this date + * @param {Number=} data.month The month for this date + * @param {Number=} data.day The day for this date + * @param {Number=} data.hour The hour for this date + * @param {Number=} data.minute The minute for this date + * @param {Number=} data.second The second for this date + * @param {Timezone|UtcOffset} zone The timezone to use + * @param {String} icaltype The type for this date/time object + */ + constructor(data, zone, icaltype) { + super(data, zone); + this.icaltype = icaltype || "date-and-or-time"; + } + + /** + * The class identifier. + * @constant + * @type {String} + * @default "vcardtime" + */ + icalclass = "vcardtime"; + + /** + * The type name, to be used in the jCal object. + * @type {String} + * @default "date-and-or-time" + */ + icaltype = "date-and-or-time"; + + /** + * Returns a clone of the vcard date/time object. + * + * @return {VCardTime} The cloned object + */ + clone() { + return new VCardTime(this._time, this.zone, this.icaltype); + } + + _normalize() { + return this; + } + + /** + * @inheritdoc + */ + utcOffset() { + if (this.zone instanceof UtcOffset) { + return this.zone.toSeconds(); + } else { + return Time.prototype.utcOffset.apply(this, arguments); + } + } + + /** + * Returns an RFC 6350 compliant representation of this object. + * + * @return {String} vcard date/time string + */ + toICALString() { + return design$1.vcard.value[this.icaltype].toICAL(this.toString()); + } + + /** + * The string representation of this date/time, in jCard form + * (including : and - separators). + * @return {String} + */ + toString() { + let y = this.year, m = this.month, d = this.day; + let h = this.hour, mm = this.minute, s = this.second; + + let hasYear = y !== null, hasMonth = m !== null, hasDay = d !== null; + let hasHour = h !== null, hasMinute = mm !== null, hasSecond = s !== null; + + let datepart = (hasYear ? pad2(y) + (hasMonth || hasDay ? '-' : '') : (hasMonth || hasDay ? '--' : '')) + + (hasMonth ? pad2(m) : '') + + (hasDay ? '-' + pad2(d) : ''); + let timepart = (hasHour ? pad2(h) : '-') + (hasHour && hasMinute ? ':' : '') + + (hasMinute ? pad2(mm) : '') + (!hasHour && !hasMinute ? '-' : '') + + (hasMinute && hasSecond ? ':' : '') + + (hasSecond ? pad2(s) : ''); + + let zone; + if (this.zone === Timezone.utcTimezone) { + zone = 'Z'; + } else if (this.zone instanceof UtcOffset) { + zone = this.zone.toString(); + } else if (this.zone === Timezone.localTimezone) { + zone = ''; + } else if (this.zone instanceof Timezone) { + let offset = UtcOffset.fromSeconds(this.zone.utcOffset(this)); + zone = offset.toString(); + } else { + zone = ''; + } + + switch (this.icaltype) { + case "time": + return timepart + zone; + case "date-and-or-time": + case "date-time": + return datepart + (timepart == '--' ? '' : 'T' + timepart + zone); + case "date": + return datepart; + } + return null; + } +} + +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * Portions Copyright (C) Philipp Kewisch */ + +/** + * This lets typescript resolve our custom types in the + * generated d.ts files (jsdoc typedefs are converted to typescript types). + * Ignore prevents the typedefs from being documented more than once. + * + * @ignore + * @typedef {import("./types.js").weekDay} weekDay + * Imports the 'weekDay' type from the "types.js" module + */ + +/** + * An iterator for a single recurrence rule. This class usually doesn't have to be instanciated + * directly, the convenience method {@link ICAL.Recur#iterator} can be used. + * + * @memberof ICAL + */ +class RecurIterator { + static _indexMap = { + "BYSECOND": 0, + "BYMINUTE": 1, + "BYHOUR": 2, + "BYDAY": 3, + "BYMONTHDAY": 4, + "BYYEARDAY": 5, + "BYWEEKNO": 6, + "BYMONTH": 7, + "BYSETPOS": 8 + }; + + static _expandMap = { + "SECONDLY": [1, 1, 1, 1, 1, 1, 1, 1], + "MINUTELY": [2, 1, 1, 1, 1, 1, 1, 1], + "HOURLY": [2, 2, 1, 1, 1, 1, 1, 1], + "DAILY": [2, 2, 2, 1, 1, 1, 1, 1], + "WEEKLY": [2, 2, 2, 2, 3, 3, 1, 1], + "MONTHLY": [2, 2, 2, 2, 2, 3, 3, 1], + "YEARLY": [2, 2, 2, 2, 2, 2, 2, 2] + }; + + static UNKNOWN = 0; + static CONTRACT = 1; + static EXPAND = 2; + static ILLEGAL = 3; + + /** + * Creates a new ICAL.RecurIterator instance. The options object may contain additional members + * when resuming iteration from a previous run. + * + * @param {Object} options The iterator options + * @param {Recur} options.rule The rule to iterate. + * @param {Time} options.dtstart The start date of the event. + * @param {Boolean=} options.initialized When true, assume that options are + * from a previously constructed iterator. Initialization will not be + * repeated. + */ + constructor(options) { + this.fromData(options); + } + + /** + * True when iteration is finished. + * @type {Boolean} + */ + completed = false; + + /** + * The rule that is being iterated + * @type {Recur} + */ + rule = null; + + /** + * The start date of the event being iterated. + * @type {Time} + */ + dtstart = null; + + /** + * The last occurrence that was returned from the + * {@link RecurIterator#next} method. + * @type {Time} + */ + last = null; + + /** + * The sequence number from the occurrence + * @type {Number} + */ + occurrence_number = 0; + + /** + * The indices used for the {@link ICAL.RecurIterator#by_data} object. + * @type {Object} + * @private + */ + by_indices = null; + + /** + * If true, the iterator has already been initialized + * @type {Boolean} + * @private + */ + initialized = false; + + /** + * The initializd by-data. + * @type {Object} + * @private + */ + by_data = null; + + /** + * The expanded yeardays + * @type {Array} + * @private + */ + days = null; + + /** + * The index in the {@link ICAL.RecurIterator#days} array. + * @type {Number} + * @private + */ + days_index = 0; + + /** + * Initialize the recurrence iterator from the passed data object. This + * method is usually not called directly, you can initialize the iterator + * through the constructor. + * + * @param {Object} options The iterator options + * @param {Recur} options.rule The rule to iterate. + * @param {Time} options.dtstart The start date of the event. + * @param {Boolean=} options.initialized When true, assume that options are + * from a previously constructed iterator. Initialization will not be + * repeated. + */ + fromData(options) { + this.rule = formatClassType(options.rule, Recur); + + if (!this.rule) { + throw new Error('iterator requires a (ICAL.Recur) rule'); + } + + this.dtstart = formatClassType(options.dtstart, Time); + + if (!this.dtstart) { + throw new Error('iterator requires a (ICAL.Time) dtstart'); + } + + if (options.by_data) { + this.by_data = options.by_data; + } else { + this.by_data = clone(this.rule.parts, true); + } + + if (options.occurrence_number) + this.occurrence_number = options.occurrence_number; + + this.days = options.days || []; + if (options.last) { + this.last = formatClassType(options.last, Time); + } + + this.by_indices = options.by_indices; + + if (!this.by_indices) { + this.by_indices = { + "BYSECOND": 0, + "BYMINUTE": 0, + "BYHOUR": 0, + "BYDAY": 0, + "BYMONTH": 0, + "BYWEEKNO": 0, + "BYMONTHDAY": 0 + }; + } + + this.initialized = options.initialized || false; + + if (!this.initialized) { + try { + this.init(); + } catch (e) { + if (e instanceof InvalidRecurrenceRuleError) { + // Init may error if there are no possible recurrence instances from + // the rule, but we don't want to bubble this error up. Instead, we + // create an empty iterator. + this.completed = true; + } else { + // Propagate other errors to consumers. + throw e; + } + } + } + } + + /** + * Initialize the iterator + * @private + */ + init() { + this.initialized = true; + this.last = this.dtstart.clone(); + let parts = this.by_data; + + if ("BYDAY" in parts) { + // libical does this earlier when the rule is loaded, but we postpone to + // now so we can preserve the original order. + this.sort_byday_rules(parts.BYDAY); + } + + // If the BYYEARDAY appares, no other date rule part may appear + if ("BYYEARDAY" in parts) { + if ("BYMONTH" in parts || "BYWEEKNO" in parts || + "BYMONTHDAY" in parts || "BYDAY" in parts) { + throw new Error("Invalid BYYEARDAY rule"); + } + } + + // BYWEEKNO and BYMONTHDAY rule parts may not both appear + if ("BYWEEKNO" in parts && "BYMONTHDAY" in parts) { + throw new Error("BYWEEKNO does not fit to BYMONTHDAY"); + } + + // For MONTHLY recurrences (FREQ=MONTHLY) neither BYYEARDAY nor + // BYWEEKNO may appear. + if (this.rule.freq == "MONTHLY" && + ("BYYEARDAY" in parts || "BYWEEKNO" in parts)) { + throw new Error("For MONTHLY recurrences neither BYYEARDAY nor BYWEEKNO may appear"); + } + + // For WEEKLY recurrences (FREQ=WEEKLY) neither BYMONTHDAY nor + // BYYEARDAY may appear. + if (this.rule.freq == "WEEKLY" && + ("BYYEARDAY" in parts || "BYMONTHDAY" in parts)) { + throw new Error("For WEEKLY recurrences neither BYMONTHDAY nor BYYEARDAY may appear"); + } + + // BYYEARDAY may only appear in YEARLY rules + if (this.rule.freq != "YEARLY" && "BYYEARDAY" in parts) { + throw new Error("BYYEARDAY may only appear in YEARLY rules"); + } + + this.last.second = this.setup_defaults("BYSECOND", "SECONDLY", this.dtstart.second); + this.last.minute = this.setup_defaults("BYMINUTE", "MINUTELY", this.dtstart.minute); + this.last.hour = this.setup_defaults("BYHOUR", "HOURLY", this.dtstart.hour); + this.last.day = this.setup_defaults("BYMONTHDAY", "DAILY", this.dtstart.day); + this.last.month = this.setup_defaults("BYMONTH", "MONTHLY", this.dtstart.month); + + if (this.rule.freq == "WEEKLY") { + if ("BYDAY" in parts) { + let [, dow] = this.ruleDayOfWeek(parts.BYDAY[0], this.rule.wkst); + let wkdy = dow - this.last.dayOfWeek(this.rule.wkst); + if ((this.last.dayOfWeek(this.rule.wkst) < dow && wkdy >= 0) || wkdy < 0) { + // Initial time is after first day of BYDAY data + this.last.day += wkdy; + } + } else { + let dayName = Recur.numericDayToIcalDay(this.dtstart.dayOfWeek()); + parts.BYDAY = [dayName]; + } + } + + if (this.rule.freq == "YEARLY") { + // Some yearly recurrence rules may be specific enough to not actually + // occur on a yearly basis, e.g. the 29th day of February or the fifth + // Monday of a given month. The standard isn't clear on the intended + // behavior in these cases, but `libical` at least will iterate until it + // finds a matching year. + // CAREFUL: Some rules may specify an occurrence that can never happen, + // e.g. the first Monday of April so long as it falls on the 15th + // through the 21st. Detecting these is non-trivial, so ensure that we + // stop iterating at some point. + const untilYear = this.rule.until ? this.rule.until.year : 20000; + while (this.last.year <= untilYear) { + this.expand_year_days(this.last.year); + if (this.days.length > 0) { + break; + } + this.increment_year(this.rule.interval); + } + + if (this.days.length == 0) { + throw new InvalidRecurrenceRuleError(); + } + + this._nextByYearDay(); + } + + if (this.rule.freq == "MONTHLY") { + if (this.has_by_data("BYDAY")) { + let tempLast = null; + let initLast = this.last.clone(); + let daysInMonth = Time.daysInMonth(this.last.month, this.last.year); + + // Check every weekday in BYDAY with relative dow and pos. + for (let bydow of this.by_data.BYDAY) { + this.last = initLast.clone(); + let [pos, dow] = this.ruleDayOfWeek(bydow); + let dayOfMonth = this.last.nthWeekDay(dow, pos); + + // If |pos| >= 6, the byday is invalid for a monthly rule. + if (pos >= 6 || pos <= -6) { + throw new Error("Malformed values in BYDAY part"); + } + + // If a Byday with pos=+/-5 is not in the current month it + // must be searched in the next months. + if (dayOfMonth > daysInMonth || dayOfMonth <= 0) { + // Skip if we have already found a "last" in this month. + if (tempLast && tempLast.month == initLast.month) { + continue; + } + while (dayOfMonth > daysInMonth || dayOfMonth <= 0) { + this.increment_month(); + daysInMonth = Time.daysInMonth(this.last.month, this.last.year); + dayOfMonth = this.last.nthWeekDay(dow, pos); + } + } + + this.last.day = dayOfMonth; + if (!tempLast || this.last.compare(tempLast) < 0) { + tempLast = this.last.clone(); + } + } + this.last = tempLast.clone(); + + //XXX: This feels like a hack, but we need to initialize + // the BYMONTHDAY case correctly and byDayAndMonthDay handles + // this case. It accepts a special flag which will avoid incrementing + // the initial value without the flag days that match the start time + // would be missed. + if (this.has_by_data('BYMONTHDAY')) { + this._byDayAndMonthDay(true); + } + + if (this.last.day > daysInMonth || this.last.day == 0) { + throw new Error("Malformed values in BYDAY part"); + } + } else if (this.has_by_data("BYMONTHDAY")) { + // Change the day value so that normalisation won't change the month. + this.last.day = 1; + + // Get a sorted list of days in the starting month that match the rule. + let normalized = this.normalizeByMonthDayRules( + this.last.year, + this.last.month, + this.rule.parts.BYMONTHDAY + ).filter(d => d >= this.last.day); + + if (normalized.length) { + // There's at least one valid day, use it. + this.last.day = normalized[0]; + this.by_data.BYMONTHDAY = normalized; + } else { + // There's no occurrence in this month, find the next valid month. + // The longest possible sequence of skipped months is February-April-June, + // so we might need to call next_month up to three times. + if (!this.next_month() && !this.next_month() && !this.next_month()) { + throw new Error("No possible occurrences"); + } + } + } + } + } + + /** + * Retrieve the next occurrence from the iterator. + * @return {Time} + */ + next(again = false) { + let before = (this.last ? this.last.clone() : null); + + if ((this.rule.count && this.occurrence_number >= this.rule.count) || + (this.rule.until && this.last.compare(this.rule.until) > 0)) { + this.completed = true; + } + + if (this.completed) { + return null; + } + + if (this.occurrence_number == 0 && this.last.compare(this.dtstart) >= 0) { + // First of all, give the instance that was initialized + this.occurrence_number++; + return this.last; + } + + let valid; + do { + valid = 1; + + switch (this.rule.freq) { + case "SECONDLY": + this.next_second(); + break; + case "MINUTELY": + this.next_minute(); + break; + case "HOURLY": + this.next_hour(); + break; + case "DAILY": + this.next_day(); + break; + case "WEEKLY": + this.next_week(); + break; + case "MONTHLY": + valid = this.next_month(); + break; + case "YEARLY": + this.next_year(); + break; + + default: + return null; + } + } while (!this.check_contracting_rules() || + this.last.compare(this.dtstart) < 0 || + !valid); + + if (this.last.compare(before) == 0) { + if (again) { + throw new Error("Same occurrence found twice, protecting you from death by recursion"); + } + this.next(true); + } + + if (this.rule.until && this.last.compare(this.rule.until) > 0) { + this.completed = true; + return null; + } else { + this.occurrence_number++; + return this.last; + } + } + + next_second() { + return this.next_generic("BYSECOND", "SECONDLY", "second", "minute"); + } + + increment_second(inc) { + return this.increment_generic(inc, "second", 60, "minute"); + } + + next_minute() { + return this.next_generic("BYMINUTE", "MINUTELY", + "minute", "hour", "next_second"); + } + + increment_minute(inc) { + return this.increment_generic(inc, "minute", 60, "hour"); + } + + next_hour() { + return this.next_generic("BYHOUR", "HOURLY", "hour", + "monthday", "next_minute"); + } + + increment_hour(inc) { + this.increment_generic(inc, "hour", 24, "monthday"); + } + + next_day() { + let this_freq = (this.rule.freq == "DAILY"); + + if (this.next_hour() == 0) { + return 0; + } + + if (this_freq) { + this.increment_monthday(this.rule.interval); + } else { + this.increment_monthday(1); + } + + return 0; + } + + next_week() { + let end_of_data = 0; + + if (this.next_weekday_by_week() == 0) { + return end_of_data; + } + + if (this.has_by_data("BYWEEKNO")) { + this.by_indices.BYWEEKNO++; + + if (this.by_indices.BYWEEKNO == this.by_data.BYWEEKNO.length) { + this.by_indices.BYWEEKNO = 0; + end_of_data = 1; + } + + // HACK should be first month of the year + this.last.month = 1; + this.last.day = 1; + + let week_no = this.by_data.BYWEEKNO[this.by_indices.BYWEEKNO]; + + this.last.day += 7 * week_no; + + if (end_of_data) { + this.increment_year(1); + } + } else { + // Jump to the next week + this.increment_monthday(7 * this.rule.interval); + } + + return end_of_data; + } + + /** + * Normalize each by day rule for a given year/month. + * Takes into account ordering and negative rules + * + * @private + * @param {Number} year Current year. + * @param {Number} month Current month. + * @param {Array} rules Array of rules. + * + * @return {Array} sorted and normalized rules. + * Negative rules will be expanded to their + * correct positive values for easier processing. + */ + normalizeByMonthDayRules(year, month, rules) { + let daysInMonth = Time.daysInMonth(month, year); + + // XXX: This is probably bad for performance to allocate + // a new array for each month we scan, if possible + // we should try to optimize this... + let newRules = []; + + let ruleIdx = 0; + let len = rules.length; + let rule; + + for (; ruleIdx < len; ruleIdx++) { + rule = parseInt(rules[ruleIdx], 10); + if (isNaN(rule)) { + throw new Error('Invalid BYMONTHDAY value'); + } + + // if this rule falls outside of given + // month discard it. + if (Math.abs(rule) > daysInMonth) { + continue; + } + + // negative case + if (rule < 0) { + // we add (not subtract it is a negative number) + // one from the rule because 1 === last day of month + rule = daysInMonth + (rule + 1); + } else if (rule === 0) { + // skip zero: it is invalid. + continue; + } + + // only add unique items... + if (newRules.indexOf(rule) === -1) { + newRules.push(rule); + } + + } + + // unique and sort + return newRules.sort(function(a, b) { return a - b; }); + } + + /** + * NOTES: + * We are given a list of dates in the month (BYMONTHDAY) (23, etc..) + * Also we are given a list of days (BYDAY) (MO, 2SU, etc..) when + * both conditions match a given date (this.last.day) iteration stops. + * + * @private + * @param {Boolean=} isInit When given true will not increment the + * current day (this.last). + */ + _byDayAndMonthDay(isInit) { + let byMonthDay; // setup in initMonth + let byDay = this.by_data.BYDAY; + + let date; + let dateIdx = 0; + let dateLen; // setup in initMonth + let dayLen = byDay.length; + + // we are not valid by default + let dataIsValid = 0; + + let daysInMonth; + let self = this; + // we need a copy of this, because a DateTime gets normalized + // automatically if the day is out of range. At some points we + // set the last day to 0 to start counting. + let lastDay = this.last.day; + + function initMonth() { + daysInMonth = Time.daysInMonth( + self.last.month, self.last.year + ); + + byMonthDay = self.normalizeByMonthDayRules( + self.last.year, + self.last.month, + self.by_data.BYMONTHDAY + ); + + dateLen = byMonthDay.length; + + // For the case of more than one occurrence in one month + // we have to be sure to start searching after the last + // found date or at the last BYMONTHDAY, unless we are + // initializing the iterator because in this case we have + // to consider the last found date too. + while (byMonthDay[dateIdx] <= lastDay && + !(isInit && byMonthDay[dateIdx] == lastDay) && + dateIdx < dateLen - 1) { + dateIdx++; + } + } + + function nextMonth() { + // since the day is incremented at the start + // of the loop below, we need to start at 0 + lastDay = 0; + self.increment_month(); + dateIdx = 0; + initMonth(); + } + + initMonth(); + + // should come after initMonth + if (isInit) { + lastDay -= 1; + } + + // Use a counter to avoid an infinite loop with malformed rules. + // Stop checking after 4 years so we consider also a leap year. + let monthsCounter = 48; + + while (!dataIsValid && monthsCounter) { + monthsCounter--; + // increment the current date. This is really + // important otherwise we may fall into the infinite + // loop trap. The initial date takes care of the case + // where the current date is the date we are looking + // for. + date = lastDay + 1; + + if (date > daysInMonth) { + nextMonth(); + continue; + } + + // find next date + let next = byMonthDay[dateIdx++]; + + // this logic is dependent on the BYMONTHDAYS + // being in order (which is done by #normalizeByMonthDayRules) + if (next >= date) { + // if the next month day is in the future jump to it. + lastDay = next; + } else { + // in this case the 'next' monthday has past + // we must move to the month. + nextMonth(); + continue; + } + + // Now we can loop through the day rules to see + // if one matches the current month date. + for (let dayIdx = 0; dayIdx < dayLen; dayIdx++) { + let parts = this.ruleDayOfWeek(byDay[dayIdx]); + let pos = parts[0]; + let dow = parts[1]; + + this.last.day = lastDay; + if (this.last.isNthWeekDay(dow, pos)) { + // when we find the valid one we can mark + // the conditions as met and break the loop. + // (Because we have this condition above + // it will also break the parent loop). + dataIsValid = 1; + break; + } + } + + // It is completely possible that the combination + // cannot be matched in the current month. + // When we reach the end of possible combinations + // in the current month we iterate to the next one. + // since dateIdx is incremented right after getting + // "next", we don't need dateLen -1 here. + if (!dataIsValid && dateIdx === dateLen) { + nextMonth(); + continue; + } + } + + if (monthsCounter <= 0) { + // Checked 4 years without finding a Byday that matches + // a Bymonthday. Maybe the rule is not correct. + throw new Error("Malformed values in BYDAY combined with BYMONTHDAY parts"); + } + + + return dataIsValid; + } + + next_month() { + let data_valid = 1; + + if (this.next_hour() == 0) { + return data_valid; + } + + if (this.has_by_data("BYDAY") && this.has_by_data("BYMONTHDAY")) { + data_valid = this._byDayAndMonthDay(); + } else if (this.has_by_data("BYDAY")) { + let daysInMonth = Time.daysInMonth(this.last.month, this.last.year); + let setpos = 0; + let setpos_total = 0; + + if (this.has_by_data("BYSETPOS")) { + let last_day = this.last.day; + for (let day = 1; day <= daysInMonth; day++) { + this.last.day = day; + if (this.is_day_in_byday(this.last)) { + setpos_total++; + if (day <= last_day) { + setpos++; + } + } + } + this.last.day = last_day; + } + + data_valid = 0; + let day; + for (day = this.last.day + 1; day <= daysInMonth; day++) { + this.last.day = day; + + if (this.is_day_in_byday(this.last)) { + if (!this.has_by_data("BYSETPOS") || + this.check_set_position(++setpos) || + this.check_set_position(setpos - setpos_total - 1)) { + + data_valid = 1; + break; + } + } + } + + if (day > daysInMonth) { + this.last.day = 1; + this.increment_month(); + + if (this.is_day_in_byday(this.last)) { + if (!this.has_by_data("BYSETPOS") || this.check_set_position(1)) { + data_valid = 1; + } + } else { + data_valid = 0; + } + } + } else if (this.has_by_data("BYMONTHDAY")) { + this.by_indices.BYMONTHDAY++; + + if (this.by_indices.BYMONTHDAY >= this.by_data.BYMONTHDAY.length) { + this.by_indices.BYMONTHDAY = 0; + this.increment_month(); + if (this.by_indices.BYMONTHDAY >= this.by_data.BYMONTHDAY.length) { + return 0; + } + } + + let daysInMonth = Time.daysInMonth(this.last.month, this.last.year); + let day = this.by_data.BYMONTHDAY[this.by_indices.BYMONTHDAY]; + + if (day < 0) { + day = daysInMonth + day + 1; + } + + if (day > daysInMonth) { + this.last.day = 1; + data_valid = this.is_day_in_byday(this.last); + } else { + this.last.day = day; + } + } else { + this.increment_month(); + let daysInMonth = Time.daysInMonth(this.last.month, this.last.year); + if (this.by_data.BYMONTHDAY[0] > daysInMonth) { + data_valid = 0; + } else { + this.last.day = this.by_data.BYMONTHDAY[0]; + } + } + + return data_valid; + } + + next_weekday_by_week() { + let end_of_data = 0; + + if (this.next_hour() == 0) { + return end_of_data; + } + + if (!this.has_by_data("BYDAY")) { + return 1; + } + + for (;;) { + let tt = new Time(); + this.by_indices.BYDAY++; + + if (this.by_indices.BYDAY == Object.keys(this.by_data.BYDAY).length) { + this.by_indices.BYDAY = 0; + end_of_data = 1; + } + + let coded_day = this.by_data.BYDAY[this.by_indices.BYDAY]; + let parts = this.ruleDayOfWeek(coded_day); + let dow = parts[1]; + + dow -= this.rule.wkst; + + if (dow < 0) { + dow += 7; + } + + tt.year = this.last.year; + tt.month = this.last.month; + tt.day = this.last.day; + + let startOfWeek = tt.startDoyWeek(this.rule.wkst); + + if (dow + startOfWeek < 1) { + // The selected date is in the previous year + if (!end_of_data) { + continue; + } + } + + let next = Time.fromDayOfYear(startOfWeek + dow, this.last.year); + + /** + * The normalization horrors below are due to + * the fact that when the year/month/day changes + * it can effect the other operations that come after. + */ + this.last.year = next.year; + this.last.month = next.month; + this.last.day = next.day; + + return end_of_data; + } + } + + next_year() { + if (this.next_hour() == 0) { + return 0; + } + + if (++this.days_index == this.days.length) { + this.days_index = 0; + do { + this.increment_year(this.rule.interval); + if (this.has_by_data("BYMONTHDAY")) { + this.by_data.BYMONTHDAY = this.normalizeByMonthDayRules( + this.last.year, + this.last.month, + this.rule.parts.BYMONTHDAY + ); + } + this.expand_year_days(this.last.year); + } while (this.days.length == 0); + } + + this._nextByYearDay(); + + return 1; + } + + _nextByYearDay() { + let doy = this.days[this.days_index]; + let year = this.last.year; + if (doy < 1) { + // Time.fromDayOfYear(doy, year) indexes relative to the + // start of the given year. That is different from the + // semantics of BYYEARDAY where negative indexes are an + // offset from the end of the given year. + doy += 1; + year += 1; + } + let next = Time.fromDayOfYear(doy, year); + this.last.day = next.day; + this.last.month = next.month; + } + + /** + * @param dow (eg: '1TU', '-1MO') + * @param {weekDay=} aWeekStart The week start weekday + * @return [pos, numericDow] (eg: [1, 3]) numericDow is relative to aWeekStart + */ + ruleDayOfWeek(dow, aWeekStart) { + let matches = dow.match(/([+-]?[0-9])?(MO|TU|WE|TH|FR|SA|SU)/); + if (matches) { + let pos = parseInt(matches[1] || 0, 10); + dow = Recur.icalDayToNumericDay(matches[2], aWeekStart); + return [pos, dow]; + } else { + return [0, 0]; + } + } + + next_generic(aRuleType, aInterval, aDateAttr, aFollowingAttr, aPreviousIncr) { + let has_by_rule = (aRuleType in this.by_data); + let this_freq = (this.rule.freq == aInterval); + let end_of_data = 0; + + if (aPreviousIncr && this[aPreviousIncr]() == 0) { + return end_of_data; + } + + if (has_by_rule) { + this.by_indices[aRuleType]++; + let dta = this.by_data[aRuleType]; + + if (this.by_indices[aRuleType] == dta.length) { + this.by_indices[aRuleType] = 0; + end_of_data = 1; + } + this.last[aDateAttr] = dta[this.by_indices[aRuleType]]; + } else if (this_freq) { + this["increment_" + aDateAttr](this.rule.interval); + } + + if (has_by_rule && end_of_data && this_freq) { + this["increment_" + aFollowingAttr](1); + } + + return end_of_data; + } + + increment_monthday(inc) { + for (let i = 0; i < inc; i++) { + let daysInMonth = Time.daysInMonth(this.last.month, this.last.year); + this.last.day++; + + if (this.last.day > daysInMonth) { + this.last.day -= daysInMonth; + this.increment_month(); + } + } + } + + increment_month() { + this.last.day = 1; + if (this.has_by_data("BYMONTH")) { + this.by_indices.BYMONTH++; + + if (this.by_indices.BYMONTH == this.by_data.BYMONTH.length) { + this.by_indices.BYMONTH = 0; + this.increment_year(1); + } + + this.last.month = this.by_data.BYMONTH[this.by_indices.BYMONTH]; + } else { + if (this.rule.freq == "MONTHLY") { + this.last.month += this.rule.interval; + } else { + this.last.month++; + } + + this.last.month--; + let years = trunc(this.last.month / 12); + this.last.month %= 12; + this.last.month++; + + if (years != 0) { + this.increment_year(years); + } + } + + if (this.has_by_data("BYMONTHDAY")) { + this.by_data.BYMONTHDAY = this.normalizeByMonthDayRules( + this.last.year, + this.last.month, + this.rule.parts.BYMONTHDAY + ); + } + } + + increment_year(inc) { + // Don't jump into the next month if this.last is Feb 29. + this.last.day = 1; + this.last.year += inc; + } + + increment_generic(inc, aDateAttr, aFactor, aNextIncrement) { + this.last[aDateAttr] += inc; + let nextunit = trunc(this.last[aDateAttr] / aFactor); + this.last[aDateAttr] %= aFactor; + if (nextunit != 0) { + this["increment_" + aNextIncrement](nextunit); + } + } + + has_by_data(aRuleType) { + return (aRuleType in this.rule.parts); + } + + expand_year_days(aYear) { + let t = new Time(); + this.days = []; + + // We need our own copy with a few keys set + let parts = {}; + let rules = ["BYDAY", "BYWEEKNO", "BYMONTHDAY", "BYMONTH", "BYYEARDAY"]; + for (let part of rules) { + if (part in this.rule.parts) { + parts[part] = this.rule.parts[part]; + } + } + + if ("BYMONTH" in parts && "BYWEEKNO" in parts) { + let valid = 1; + let validWeeks = {}; + t.year = aYear; + t.isDate = true; + + for (let monthIdx = 0; monthIdx < this.by_data.BYMONTH.length; monthIdx++) { + let month = this.by_data.BYMONTH[monthIdx]; + t.month = month; + t.day = 1; + let first_week = t.weekNumber(this.rule.wkst); + t.day = Time.daysInMonth(month, aYear); + let last_week = t.weekNumber(this.rule.wkst); + for (monthIdx = first_week; monthIdx < last_week; monthIdx++) { + validWeeks[monthIdx] = 1; + } + } + + for (let weekIdx = 0; weekIdx < this.by_data.BYWEEKNO.length && valid; weekIdx++) { + let weekno = this.by_data.BYWEEKNO[weekIdx]; + if (weekno < 52) { + valid &= validWeeks[weekIdx]; + } else { + valid = 0; + } + } + + if (valid) { + delete parts.BYMONTH; + } else { + delete parts.BYWEEKNO; + } + } + + let partCount = Object.keys(parts).length; + + if (partCount == 0) { + let t1 = this.dtstart.clone(); + t1.year = this.last.year; + this.days.push(t1.dayOfYear()); + } else if (partCount == 1 && "BYMONTH" in parts) { + for (let month of this.by_data.BYMONTH) { + let t2 = this.dtstart.clone(); + t2.year = aYear; + t2.month = month; + t2.isDate = true; + this.days.push(t2.dayOfYear()); + } + } else if (partCount == 1 && "BYMONTHDAY" in parts) { + for (let monthday of this.by_data.BYMONTHDAY) { + let t3 = this.dtstart.clone(); + if (monthday < 0) { + let daysInMonth = Time.daysInMonth(t3.month, aYear); + monthday = monthday + daysInMonth + 1; + } + t3.day = monthday; + t3.year = aYear; + t3.isDate = true; + this.days.push(t3.dayOfYear()); + } + } else if (partCount == 2 && + "BYMONTHDAY" in parts && + "BYMONTH" in parts) { + for (let month of this.by_data.BYMONTH) { + let daysInMonth = Time.daysInMonth(month, aYear); + for (let monthday of this.by_data.BYMONTHDAY) { + if (monthday < 0) { + monthday = monthday + daysInMonth + 1; + } + t.day = monthday; + t.month = month; + t.year = aYear; + t.isDate = true; + + this.days.push(t.dayOfYear()); + } + } + } else if (partCount == 1 && "BYWEEKNO" in parts) ; else if (partCount == 2 && + "BYWEEKNO" in parts && + "BYMONTHDAY" in parts) ; else if (partCount == 1 && "BYDAY" in parts) { + this.days = this.days.concat(this.expand_by_day(aYear)); + } else if (partCount == 2 && "BYDAY" in parts && "BYMONTH" in parts) { + for (let month of this.by_data.BYMONTH) { + let daysInMonth = Time.daysInMonth(month, aYear); + + t.year = aYear; + t.month = month; + t.day = 1; + t.isDate = true; + + let first_dow = t.dayOfWeek(); + let doy_offset = t.dayOfYear() - 1; + + t.day = daysInMonth; + let last_dow = t.dayOfWeek(); + + if (this.has_by_data("BYSETPOS")) { + let by_month_day = []; + for (let day = 1; day <= daysInMonth; day++) { + t.day = day; + if (this.is_day_in_byday(t)) { + by_month_day.push(day); + } + } + + for (let spIndex = 0; spIndex < by_month_day.length; spIndex++) { + if (this.check_set_position(spIndex + 1) || + this.check_set_position(spIndex - by_month_day.length)) { + this.days.push(doy_offset + by_month_day[spIndex]); + } + } + } else { + for (let coded_day of this.by_data.BYDAY) { + let bydayParts = this.ruleDayOfWeek(coded_day); + let pos = bydayParts[0]; + let dow = bydayParts[1]; + let month_day; + + let first_matching_day = ((dow + 7 - first_dow) % 7) + 1; + let last_matching_day = daysInMonth - ((last_dow + 7 - dow) % 7); + + if (pos == 0) { + for (let day = first_matching_day; day <= daysInMonth; day += 7) { + this.days.push(doy_offset + day); + } + } else if (pos > 0) { + month_day = first_matching_day + (pos - 1) * 7; + + if (month_day <= daysInMonth) { + this.days.push(doy_offset + month_day); + } + } else { + month_day = last_matching_day + (pos + 1) * 7; + + if (month_day > 0) { + this.days.push(doy_offset + month_day); + } + } + } + } + } + // Return dates in order of occurrence (1,2,3,...) instead + // of by groups of weekdays (1,8,15,...,2,9,16,...). + this.days.sort(function(a, b) { return a - b; }); // Comparator function allows to sort numbers. + } else if (partCount == 2 && "BYDAY" in parts && "BYMONTHDAY" in parts) { + let expandedDays = this.expand_by_day(aYear); + + for (let day of expandedDays) { + let tt = Time.fromDayOfYear(day, aYear); + if (this.by_data.BYMONTHDAY.indexOf(tt.day) >= 0) { + this.days.push(day); + } + } + } else if (partCount == 3 && + "BYDAY" in parts && + "BYMONTHDAY" in parts && + "BYMONTH" in parts) { + let expandedDays = this.expand_by_day(aYear); + + for (let day of expandedDays) { + let tt = Time.fromDayOfYear(day, aYear); + + if (this.by_data.BYMONTH.indexOf(tt.month) >= 0 && + this.by_data.BYMONTHDAY.indexOf(tt.day) >= 0) { + this.days.push(day); + } + } + } else if (partCount == 2 && "BYDAY" in parts && "BYWEEKNO" in parts) { + let expandedDays = this.expand_by_day(aYear); + + for (let day of expandedDays) { + let tt = Time.fromDayOfYear(day, aYear); + let weekno = tt.weekNumber(this.rule.wkst); + + if (this.by_data.BYWEEKNO.indexOf(weekno)) { + this.days.push(day); + } + } + } else if (partCount == 3 && + "BYDAY" in parts && + "BYWEEKNO" in parts && + "BYMONTHDAY" in parts) ; else if (partCount == 1 && "BYYEARDAY" in parts) { + this.days = this.days.concat(this.by_data.BYYEARDAY); + } else { + this.days = []; + } + + let daysInYear = Time.isLeapYear(aYear) ? 366 : 365; + this.days.sort((a, b) => { + if (a < 0) a += daysInYear + 1; + if (b < 0) b += daysInYear + 1; + return a - b; + }); + + return 0; + } + + expand_by_day(aYear) { + + let days_list = []; + let tmp = this.last.clone(); + + tmp.year = aYear; + tmp.month = 1; + tmp.day = 1; + tmp.isDate = true; + + let start_dow = tmp.dayOfWeek(); + + tmp.month = 12; + tmp.day = 31; + tmp.isDate = true; + + let end_dow = tmp.dayOfWeek(); + let end_year_day = tmp.dayOfYear(); + + for (let day of this.by_data.BYDAY) { + let parts = this.ruleDayOfWeek(day); + let pos = parts[0]; + let dow = parts[1]; + + if (pos == 0) { + let tmp_start_doy = ((dow + 7 - start_dow) % 7) + 1; + + for (let doy = tmp_start_doy; doy <= end_year_day; doy += 7) { + days_list.push(doy); + } + + } else if (pos > 0) { + let first; + if (dow >= start_dow) { + first = dow - start_dow + 1; + } else { + first = dow - start_dow + 8; + } + + days_list.push(first + (pos - 1) * 7); + } else { + let last; + pos = -pos; + + if (dow <= end_dow) { + last = end_year_day - end_dow + dow; + } else { + last = end_year_day - end_dow + dow - 7; + } + + days_list.push(last - (pos - 1) * 7); + } + } + return days_list; + } + + is_day_in_byday(tt) { + if (this.by_data.BYDAY) { + for (let day of this.by_data.BYDAY) { + let parts = this.ruleDayOfWeek(day); + let pos = parts[0]; + let dow = parts[1]; + let this_dow = tt.dayOfWeek(); + + if ((pos == 0 && dow == this_dow) || + (tt.nthWeekDay(dow, pos) == tt.day)) { + return 1; + } + } + } + + return 0; + } + + /** + * Checks if given value is in BYSETPOS. + * + * @private + * @param {Numeric} aPos position to check for. + * @return {Boolean} false unless BYSETPOS rules exist + * and the given value is present in rules. + */ + check_set_position(aPos) { + if (this.has_by_data('BYSETPOS')) { + let idx = this.by_data.BYSETPOS.indexOf(aPos); + // negative numbers are not false-y + return idx !== -1; + } + return false; + } + + sort_byday_rules(aRules) { + for (let i = 0; i < aRules.length; i++) { + for (let j = 0; j < i; j++) { + let one = this.ruleDayOfWeek(aRules[j], this.rule.wkst)[1]; + let two = this.ruleDayOfWeek(aRules[i], this.rule.wkst)[1]; + + if (one > two) { + let tmp = aRules[i]; + aRules[i] = aRules[j]; + aRules[j] = tmp; + } + } + } + } + + check_contract_restriction(aRuleType, v) { + let indexMapValue = RecurIterator._indexMap[aRuleType]; + let ruleMapValue = RecurIterator._expandMap[this.rule.freq][indexMapValue]; + let pass = false; + + if (aRuleType in this.by_data && + ruleMapValue == RecurIterator.CONTRACT) { + + let ruleType = this.by_data[aRuleType]; + + for (let bydata of ruleType) { + if (bydata == v) { + pass = true; + break; + } + } + } else { + // Not a contracting byrule or has no data, test passes + pass = true; + } + return pass; + } + + check_contracting_rules() { + let dow = this.last.dayOfWeek(); + let weekNo = this.last.weekNumber(this.rule.wkst); + let doy = this.last.dayOfYear(); + + return (this.check_contract_restriction("BYSECOND", this.last.second) && + this.check_contract_restriction("BYMINUTE", this.last.minute) && + this.check_contract_restriction("BYHOUR", this.last.hour) && + this.check_contract_restriction("BYDAY", Recur.numericDayToIcalDay(dow)) && + this.check_contract_restriction("BYWEEKNO", weekNo) && + this.check_contract_restriction("BYMONTHDAY", this.last.day) && + this.check_contract_restriction("BYMONTH", this.last.month) && + this.check_contract_restriction("BYYEARDAY", doy)); + } + + setup_defaults(aRuleType, req, deftime) { + let indexMapValue = RecurIterator._indexMap[aRuleType]; + let ruleMapValue = RecurIterator._expandMap[this.rule.freq][indexMapValue]; + + if (ruleMapValue != RecurIterator.CONTRACT) { + if (!(aRuleType in this.by_data)) { + this.by_data[aRuleType] = [deftime]; + } + if (this.rule.freq != req) { + return this.by_data[aRuleType][0]; + } + } + return deftime; + } + + /** + * Convert iterator into a serialize-able object. Will preserve current + * iteration sequence to ensure the seamless continuation of the recurrence + * rule. + * @return {Object} + */ + toJSON() { + let result = Object.create(null); + + result.initialized = this.initialized; + result.rule = this.rule.toJSON(); + result.dtstart = this.dtstart.toJSON(); + result.by_data = this.by_data; + result.days = this.days; + result.last = this.last.toJSON(); + result.by_indices = this.by_indices; + result.occurrence_number = this.occurrence_number; + + return result; + } +} + +/** + * An error indicating that a recurrence rule is invalid and produces no + * occurrences. + * + * @extends {Error} + * @class + */ +class InvalidRecurrenceRuleError extends Error { + constructor() { + super("Recurrence rule has no valid occurrences"); + } +} + +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * Portions Copyright (C) Philipp Kewisch */ + +/** + * This lets typescript resolve our custom types in the + * generated d.ts files (jsdoc typedefs are converted to typescript types). + * Ignore prevents the typedefs from being documented more than once. + * + * @ignore + * @typedef {import("./types.js").weekDay} weekDay + * Imports the 'weekDay' type from the "types.js" module + * @typedef {import("./types.js").frequencyValues} frequencyValues + * Imports the 'frequencyValues' type from the "types.js" module + */ + +const VALID_DAY_NAMES = /^(SU|MO|TU|WE|TH|FR|SA)$/; +const VALID_BYDAY_PART = /^([+-])?(5[0-3]|[1-4][0-9]|[1-9])?(SU|MO|TU|WE|TH|FR|SA)$/; +const DOW_MAP = { + SU: Time.SUNDAY, + MO: Time.MONDAY, + TU: Time.TUESDAY, + WE: Time.WEDNESDAY, + TH: Time.THURSDAY, + FR: Time.FRIDAY, + SA: Time.SATURDAY +}; + +const REVERSE_DOW_MAP = Object.fromEntries(Object.entries(DOW_MAP).map(entry => entry.reverse())); + +const ALLOWED_FREQ = ['SECONDLY', 'MINUTELY', 'HOURLY', + 'DAILY', 'WEEKLY', 'MONTHLY', 'YEARLY']; + +/** + * This class represents the "recur" value type, used for example by RRULE. It provides methods to + * calculate occurrences among others. + * + * @memberof ICAL + */ +class Recur { + /** + * Creates a new {@link ICAL.Recur} instance from the passed string. + * + * @param {String} string The string to parse + * @return {Recur} The created recurrence instance + */ + static fromString(string) { + let data = this._stringToData(string, false); + return new Recur(data); + } + + /** + * Creates a new {@link ICAL.Recur} instance using members from the passed + * data object. + * + * @param {Object} aData An object with members of the recurrence + * @param {frequencyValues=} aData.freq The frequency value + * @param {Number=} aData.interval The INTERVAL value + * @param {weekDay=} aData.wkst The week start value + * @param {Time=} aData.until The end of the recurrence set + * @param {Number=} aData.count The number of occurrences + * @param {Array.=} aData.bysecond The seconds for the BYSECOND part + * @param {Array.=} aData.byminute The minutes for the BYMINUTE part + * @param {Array.=} aData.byhour The hours for the BYHOUR part + * @param {Array.=} aData.byday The BYDAY values + * @param {Array.=} aData.bymonthday The days for the BYMONTHDAY part + * @param {Array.=} aData.byyearday The days for the BYYEARDAY part + * @param {Array.=} aData.byweekno The weeks for the BYWEEKNO part + * @param {Array.=} aData.bymonth The month for the BYMONTH part + * @param {Array.=} aData.bysetpos The positionals for the BYSETPOS part + */ + static fromData(aData) { + return new Recur(aData); + } + + /** + * Converts a recurrence string to a data object, suitable for the fromData + * method. + * + * @private + * @param {String} string The string to parse + * @param {Boolean} fmtIcal If true, the string is considered to be an + * iCalendar string + * @return {Recur} The recurrence instance + */ + static _stringToData(string, fmtIcal) { + let dict = Object.create(null); + + // split is slower in FF but fast enough. + // v8 however this is faster then manual split? + let values = string.split(';'); + let len = values.length; + + for (let i = 0; i < len; i++) { + let parts = values[i].split('='); + let ucname = parts[0].toUpperCase(); + let lcname = parts[0].toLowerCase(); + let name = (fmtIcal ? lcname : ucname); + let value = parts[1]; + + if (ucname in partDesign) { + let partArr = value.split(','); + let partSet = new Set(); + + for (let part of partArr) { + partSet.add(partDesign[ucname](part)); + } + partArr = [...partSet]; + + dict[name] = (partArr.length == 1 ? partArr[0] : partArr); + } else if (ucname in optionDesign) { + optionDesign[ucname](value, dict, fmtIcal); + } else { + // Don't swallow unknown values. Just set them as they are. + dict[lcname] = value; + } + } + + return dict; + } + + /** + * Convert an ical representation of a day (SU, MO, etc..) + * into a numeric value of that day. + * + * @param {String} string The iCalendar day name + * @param {weekDay=} aWeekStart + * The week start weekday, defaults to SUNDAY + * @return {Number} Numeric value of given day + */ + static icalDayToNumericDay(string, aWeekStart) { + //XXX: this is here so we can deal + // with possibly invalid string values. + let firstDow = aWeekStart || Time.SUNDAY; + return ((DOW_MAP[string] - firstDow + 7) % 7) + 1; + } + + /** + * Convert a numeric day value into its ical representation (SU, MO, etc..) + * + * @param {Number} num Numeric value of given day + * @param {weekDay=} aWeekStart + * The week start weekday, defaults to SUNDAY + * @return {String} The ICAL day value, e.g SU,MO,... + */ + static numericDayToIcalDay(num, aWeekStart) { + //XXX: this is here so we can deal with possibly invalid number values. + // Also, this allows consistent mapping between day numbers and day + // names for external users. + let firstDow = aWeekStart || Time.SUNDAY; + let dow = (num + firstDow - Time.SUNDAY); + if (dow > 7) { + dow -= 7; + } + return REVERSE_DOW_MAP[dow]; + } + + /** + * Create a new instance of the Recur class. + * + * @param {Object} data An object with members of the recurrence + * @param {frequencyValues=} data.freq The frequency value + * @param {Number=} data.interval The INTERVAL value + * @param {weekDay=} data.wkst The week start value + * @param {Time=} data.until The end of the recurrence set + * @param {Number=} data.count The number of occurrences + * @param {Array.=} data.bysecond The seconds for the BYSECOND part + * @param {Array.=} data.byminute The minutes for the BYMINUTE part + * @param {Array.=} data.byhour The hours for the BYHOUR part + * @param {Array.=} data.byday The BYDAY values + * @param {Array.=} data.bymonthday The days for the BYMONTHDAY part + * @param {Array.=} data.byyearday The days for the BYYEARDAY part + * @param {Array.=} data.byweekno The weeks for the BYWEEKNO part + * @param {Array.=} data.bymonth The month for the BYMONTH part + * @param {Array.=} data.bysetpos The positionals for the BYSETPOS part + */ + constructor(data) { + this.wrappedJSObject = this; + this.parts = {}; + + if (data && typeof(data) === 'object') { + this.fromData(data); + } + } + + /** + * An object holding the BY-parts of the recurrence rule + * @memberof ICAL.Recur + * @typedef {Object} byParts + * @property {Array.=} BYSECOND The seconds for the BYSECOND part + * @property {Array.=} BYMINUTE The minutes for the BYMINUTE part + * @property {Array.=} BYHOUR The hours for the BYHOUR part + * @property {Array.=} BYDAY The BYDAY values + * @property {Array.=} BYMONTHDAY The days for the BYMONTHDAY part + * @property {Array.=} BYYEARDAY The days for the BYYEARDAY part + * @property {Array.=} BYWEEKNO The weeks for the BYWEEKNO part + * @property {Array.=} BYMONTH The month for the BYMONTH part + * @property {Array.=} BYSETPOS The positionals for the BYSETPOS part + */ + + /** + * An object holding the BY-parts of the recurrence rule + * @type {byParts} + */ + parts = null; + + /** + * The interval value for the recurrence rule. + * @type {Number} + */ + interval = 1; + + /** + * The week start day + * + * @type {weekDay} + * @default ICAL.Time.MONDAY + */ + wkst = Time.MONDAY; + + /** + * The end of the recurrence + * @type {?Time} + */ + until = null; + + /** + * The maximum number of occurrences + * @type {?Number} + */ + count = null; + + /** + * The frequency value. + * @type {frequencyValues} + */ + freq = null; + + /** + * The class identifier. + * @constant + * @type {String} + * @default "icalrecur" + */ + icalclass = "icalrecur"; + + /** + * The type name, to be used in the jCal object. + * @constant + * @type {String} + * @default "recur" + */ + icaltype = "recur"; + + /** + * Create a new iterator for this recurrence rule. The passed start date + * must be the start date of the event, not the start of the range to + * search in. + * + * @example + * let recur = comp.getFirstPropertyValue('rrule'); + * let dtstart = comp.getFirstPropertyValue('dtstart'); + * let iter = recur.iterator(dtstart); + * for (let next = iter.next(); next; next = iter.next()) { + * if (next.compare(rangeStart) < 0) { + * continue; + * } + * console.log(next.toString()); + * } + * + * @param {Time} aStart The item's start date + * @return {RecurIterator} The recurrence iterator + */ + iterator(aStart) { + return new RecurIterator({ + rule: this, + dtstart: aStart + }); + } + + /** + * Returns a clone of the recurrence object. + * + * @return {Recur} The cloned object + */ + clone() { + return new Recur(this.toJSON()); + } + + /** + * Checks if the current rule is finite, i.e. has a count or until part. + * + * @return {Boolean} True, if the rule is finite + */ + isFinite() { + return !!(this.count || this.until); + } + + /** + * Checks if the current rule has a count part, and not limited by an until + * part. + * + * @return {Boolean} True, if the rule is by count + */ + isByCount() { + return !!(this.count && !this.until); + } + + /** + * Adds a component (part) to the recurrence rule. This is not a component + * in the sense of {@link ICAL.Component}, but a part of the recurrence + * rule, i.e. BYMONTH. + * + * @param {String} aType The name of the component part + * @param {Array|String} aValue The component value + */ + addComponent(aType, aValue) { + let ucname = aType.toUpperCase(); + if (ucname in this.parts) { + this.parts[ucname].push(aValue); + } else { + this.parts[ucname] = [aValue]; + } + } + + /** + * Sets the component value for the given by-part. + * + * @param {String} aType The component part name + * @param {Array} aValues The component values + */ + setComponent(aType, aValues) { + this.parts[aType.toUpperCase()] = aValues.slice(); + } + + /** + * Gets (a copy) of the requested component value. + * + * @param {String} aType The component part name + * @return {Array} The component part value + */ + getComponent(aType) { + let ucname = aType.toUpperCase(); + return (ucname in this.parts ? this.parts[ucname].slice() : []); + } + + /** + * Retrieves the next occurrence after the given recurrence id. See the + * guide on {@tutorial terminology} for more details. + * + * NOTE: Currently, this method iterates all occurrences from the start + * date. It should not be called in a loop for performance reasons. If you + * would like to get more than one occurrence, you can iterate the + * occurrences manually, see the example on the + * {@link ICAL.Recur#iterator iterator} method. + * + * @param {Time} aStartTime The start of the event series + * @param {Time} aRecurrenceId The date of the last occurrence + * @return {Time} The next occurrence after + */ + getNextOccurrence(aStartTime, aRecurrenceId) { + let iter = this.iterator(aStartTime); + let next; + + do { + next = iter.next(); + } while (next && next.compare(aRecurrenceId) <= 0); + + if (next && aRecurrenceId.zone) { + next.zone = aRecurrenceId.zone; + } + + return next; + } + + /** + * Sets up the current instance using members from the passed data object. + * + * @param {Object} data An object with members of the recurrence + * @param {frequencyValues=} data.freq The frequency value + * @param {Number=} data.interval The INTERVAL value + * @param {weekDay=} data.wkst The week start value + * @param {Time=} data.until The end of the recurrence set + * @param {Number=} data.count The number of occurrences + * @param {Array.=} data.bysecond The seconds for the BYSECOND part + * @param {Array.=} data.byminute The minutes for the BYMINUTE part + * @param {Array.=} data.byhour The hours for the BYHOUR part + * @param {Array.=} data.byday The BYDAY values + * @param {Array.=} data.bymonthday The days for the BYMONTHDAY part + * @param {Array.=} data.byyearday The days for the BYYEARDAY part + * @param {Array.=} data.byweekno The weeks for the BYWEEKNO part + * @param {Array.=} data.bymonth The month for the BYMONTH part + * @param {Array.=} data.bysetpos The positionals for the BYSETPOS part + */ + fromData(data) { + for (let key in data) { + let uckey = key.toUpperCase(); + + if (uckey in partDesign) { + if (Array.isArray(data[key])) { + this.parts[uckey] = data[key]; + } else { + this.parts[uckey] = [data[key]]; + } + } else { + this[key] = data[key]; + } + } + + if (this.interval && typeof this.interval != "number") { + optionDesign.INTERVAL(this.interval, this); + } + + if (this.wkst && typeof this.wkst != "number") { + this.wkst = Recur.icalDayToNumericDay(this.wkst); + } + + if (this.until && !(this.until instanceof Time)) { + this.until = Time.fromString(this.until); + } + } + + /** + * The jCal representation of this recurrence type. + * @return {Object} + */ + toJSON() { + let res = Object.create(null); + res.freq = this.freq; + + if (this.count) { + res.count = this.count; + } + + if (this.interval > 1) { + res.interval = this.interval; + } + + for (let [k, kparts] of Object.entries(this.parts)) { + if (Array.isArray(kparts) && kparts.length == 1) { + res[k.toLowerCase()] = kparts[0]; + } else { + res[k.toLowerCase()] = clone(kparts); + } + } + + if (this.until) { + res.until = this.until.toString(); + } + if ('wkst' in this && this.wkst !== Time.DEFAULT_WEEK_START) { + res.wkst = Recur.numericDayToIcalDay(this.wkst); + } + return res; + } + + /** + * The string representation of this recurrence rule. + * @return {String} + */ + toString() { + // TODO retain order + let str = "FREQ=" + this.freq; + if (this.count) { + str += ";COUNT=" + this.count; + } + if (this.interval > 1) { + str += ";INTERVAL=" + this.interval; + } + for (let [k, v] of Object.entries(this.parts)) { + str += ";" + k + "=" + v; + } + if (this.until) { + str += ';UNTIL=' + this.until.toICALString(); + } + if ('wkst' in this && this.wkst !== Time.DEFAULT_WEEK_START) { + str += ';WKST=' + Recur.numericDayToIcalDay(this.wkst); + } + return str; + } +} + +function parseNumericValue(type, min, max, value) { + let result = value; + + if (value[0] === '+') { + result = value.slice(1); + } + + result = strictParseInt(result); + + if (min !== undefined && value < min) { + throw new Error( + type + ': invalid value "' + value + '" must be > ' + min + ); + } + + if (max !== undefined && value > max) { + throw new Error( + type + ': invalid value "' + value + '" must be < ' + min + ); + } + + return result; +} + +const optionDesign = { + FREQ: function(value, dict, fmtIcal) { + // yes this is actually equal or faster then regex. + // upside here is we can enumerate the valid values. + if (ALLOWED_FREQ.indexOf(value) !== -1) { + dict.freq = value; + } else { + throw new Error( + 'invalid frequency "' + value + '" expected: "' + + ALLOWED_FREQ.join(', ') + '"' + ); + } + }, + + COUNT: function(value, dict, fmtIcal) { + dict.count = strictParseInt(value); + }, + + INTERVAL: function(value, dict, fmtIcal) { + dict.interval = strictParseInt(value); + if (dict.interval < 1) { + // 0 or negative values are not allowed, some engines seem to generate + // it though. Assume 1 instead. + dict.interval = 1; + } + }, + + UNTIL: function(value, dict, fmtIcal) { + if (value.length > 10) { + dict.until = design$1.icalendar.value['date-time'].fromICAL(value); + } else { + dict.until = design$1.icalendar.value.date.fromICAL(value); + } + if (!fmtIcal) { + dict.until = Time.fromString(dict.until); + } + }, + + WKST: function(value, dict, fmtIcal) { + if (VALID_DAY_NAMES.test(value)) { + dict.wkst = Recur.icalDayToNumericDay(value); + } else { + throw new Error('invalid WKST value "' + value + '"'); + } + } +}; + +const partDesign = { + BYSECOND: parseNumericValue.bind(undefined, 'BYSECOND', 0, 60), + BYMINUTE: parseNumericValue.bind(undefined, 'BYMINUTE', 0, 59), + BYHOUR: parseNumericValue.bind(undefined, 'BYHOUR', 0, 23), + BYDAY: function(value) { + if (VALID_BYDAY_PART.test(value)) { + return value; + } else { + throw new Error('invalid BYDAY value "' + value + '"'); + } + }, + BYMONTHDAY: parseNumericValue.bind(undefined, 'BYMONTHDAY', -31, 31), + BYYEARDAY: parseNumericValue.bind(undefined, 'BYYEARDAY', -366, 366), + BYWEEKNO: parseNumericValue.bind(undefined, 'BYWEEKNO', -53, 53), + BYMONTH: parseNumericValue.bind(undefined, 'BYMONTH', 1, 12), + BYSETPOS: parseNumericValue.bind(undefined, 'BYSETPOS', -366, 366) +}; + +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * Portions Copyright (C) Philipp Kewisch */ + +/** + * This lets typescript resolve our custom types in the + * generated d.ts files (jsdoc typedefs are converted to typescript types). + * Ignore prevents the typedefs from being documented more than once. + * @ignore + * @typedef {import("./types.js").jCalComponent} jCalComponent + * Imports the 'occurrenceDetails' type from the "types.js" module + */ + +/** + * This class represents the "period" value type, with various calculation and manipulation methods. + * + * @memberof ICAL + */ +class Period { + /** + * Creates a new {@link ICAL.Period} instance from the passed string. + * + * @param {String} str The string to parse + * @param {Property} prop The property this period will be on + * @return {Period} The created period instance + */ + static fromString(str, prop) { + let parts = str.split('/'); + + if (parts.length !== 2) { + throw new Error( + 'Invalid string value: "' + str + '" must contain a "/" char.' + ); + } + + let options = { + start: Time.fromDateTimeString(parts[0], prop) + }; + + let end = parts[1]; + + if (Duration.isValueString(end)) { + options.duration = Duration.fromString(end); + } else { + options.end = Time.fromDateTimeString(end, prop); + } + + return new Period(options); + } + + /** + * Creates a new {@link ICAL.Period} instance from the given data object. + * The passed data object cannot contain both and end date and a duration. + * + * @param {Object} aData An object with members of the period + * @param {Time=} aData.start The start of the period + * @param {Time=} aData.end The end of the period + * @param {Duration=} aData.duration The duration of the period + * @return {Period} The period instance + */ + static fromData(aData) { + return new Period(aData); + } + + /** + * Returns a new period instance from the given jCal data array. The first + * member is always the start date string, the second member is either a + * duration or end date string. + * + * @param {jCalComponent} aData The jCal data array + * @param {Property} aProp The property this jCal data is on + * @param {Boolean} aLenient If true, data value can be both date and date-time + * @return {Period} The period instance + */ + static fromJSON(aData, aProp, aLenient) { + function fromDateOrDateTimeString(aValue, dateProp) { + if (aLenient) { + return Time.fromString(aValue, dateProp); + } else { + return Time.fromDateTimeString(aValue, dateProp); + } + } + + if (Duration.isValueString(aData[1])) { + return Period.fromData({ + start: fromDateOrDateTimeString(aData[0], aProp), + duration: Duration.fromString(aData[1]) + }); + } else { + return Period.fromData({ + start: fromDateOrDateTimeString(aData[0], aProp), + end: fromDateOrDateTimeString(aData[1], aProp) + }); + } + } + + /** + * Creates a new ICAL.Period instance. The passed data object cannot contain both and end date and + * a duration. + * + * @param {Object} aData An object with members of the period + * @param {Time=} aData.start The start of the period + * @param {Time=} aData.end The end of the period + * @param {Duration=} aData.duration The duration of the period + */ + constructor(aData) { + this.wrappedJSObject = this; + + if (aData && 'start' in aData) { + if (aData.start && !(aData.start instanceof Time)) { + throw new TypeError('.start must be an instance of ICAL.Time'); + } + this.start = aData.start; + } + + if (aData && aData.end && aData.duration) { + throw new Error('cannot accept both end and duration'); + } + + if (aData && 'end' in aData) { + if (aData.end && !(aData.end instanceof Time)) { + throw new TypeError('.end must be an instance of ICAL.Time'); + } + this.end = aData.end; + } + + if (aData && 'duration' in aData) { + if (aData.duration && !(aData.duration instanceof Duration)) { + throw new TypeError('.duration must be an instance of ICAL.Duration'); + } + this.duration = aData.duration; + } + } + + + /** + * The start of the period + * @type {Time} + */ + start = null; + + /** + * The end of the period + * @type {Time} + */ + end = null; + + /** + * The duration of the period + * @type {Duration} + */ + duration = null; + + /** + * The class identifier. + * @constant + * @type {String} + * @default "icalperiod" + */ + icalclass = "icalperiod"; + + /** + * The type name, to be used in the jCal object. + * @constant + * @type {String} + * @default "period" + */ + icaltype = "period"; + + /** + * Returns a clone of the duration object. + * + * @return {Period} The cloned object + */ + clone() { + return Period.fromData({ + start: this.start ? this.start.clone() : null, + end: this.end ? this.end.clone() : null, + duration: this.duration ? this.duration.clone() : null + }); + } + + /** + * Calculates the duration of the period, either directly or by subtracting + * start from end date. + * + * @return {Duration} The calculated duration + */ + getDuration() { + if (this.duration) { + return this.duration; + } else { + return this.end.subtractDate(this.start); + } + } + + /** + * Calculates the end date of the period, either directly or by adding + * duration to start date. + * + * @return {Time} The calculated end date + */ + getEnd() { + if (this.end) { + return this.end; + } else { + let end = this.start.clone(); + end.addDuration(this.duration); + return end; + } + } + + /** + * The string representation of this period. + * @return {String} + */ + toString() { + return this.start + "/" + (this.end || this.duration); + } + + /** + * The jCal representation of this period type. + * @return {Object} + */ + toJSON() { + return [this.start.toString(), (this.end || this.duration).toString()]; + } + + /** + * The iCalendar string representation of this period. + * @return {String} + */ + toICALString() { + return this.start.toICALString() + "/" + + (this.end || this.duration).toICALString(); + } +} + +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * Portions Copyright (C) Philipp Kewisch */ + +/** + * This lets typescript resolve our custom types in the + * generated d.ts files (jsdoc typedefs are converted to typescript types). + * Ignore prevents the typedefs from being documented more than once. + * @ignore + * @typedef {import("./types.js").designSet} designSet + * Imports the 'designSet' type from the "types.js" module + */ + +/** @module ICAL.design */ + +const FROM_ICAL_NEWLINE = /\\\\|\\;|\\,|\\[Nn]/g; +const TO_ICAL_NEWLINE = /\\|;|,|\n/g; +const FROM_VCARD_NEWLINE = /\\\\|\\,|\\[Nn]/g; +const TO_VCARD_NEWLINE = /\\|,|\n/g; + +function createTextType(fromNewline, toNewline) { + let result = { + matches: /.*/, + + fromICAL: function(aValue, structuredEscape) { + return replaceNewline(aValue, fromNewline, structuredEscape); + }, + + toICAL: function(aValue, structuredEscape) { + let regEx = toNewline; + if (structuredEscape) + regEx = new RegExp(regEx.source + '|' + structuredEscape, regEx.flags); + return aValue.replace(regEx, function(str) { + switch (str) { + case "\\": + return "\\\\"; + case ";": + return "\\;"; + case ",": + return "\\,"; + case "\n": + return "\\n"; + /* c8 ignore next 2 */ + default: + return str; + } + }); + } + }; + return result; +} + +// default types used multiple times +const DEFAULT_TYPE_TEXT = { defaultType: "text" }; +const DEFAULT_TYPE_TEXT_MULTI = { defaultType: "text", multiValue: "," }; +const DEFAULT_TYPE_TEXT_STRUCTURED = { defaultType: "text", structuredValue: ";" }; +const DEFAULT_TYPE_INTEGER = { defaultType: "integer" }; +const DEFAULT_TYPE_DATETIME_DATE = { defaultType: "date-time", allowedTypes: ["date-time", "date"] }; +const DEFAULT_TYPE_DATETIME = { defaultType: "date-time" }; +const DEFAULT_TYPE_URI = { defaultType: "uri" }; +const DEFAULT_TYPE_UTCOFFSET = { defaultType: "utc-offset" }; +const DEFAULT_TYPE_RECUR = { defaultType: "recur" }; +const DEFAULT_TYPE_DATE_ANDOR_TIME = { defaultType: "date-and-or-time", allowedTypes: ["date-time", "date", "text"] }; + +function replaceNewlineReplace(string) { + switch (string) { + case "\\\\": + return "\\"; + case "\\;": + return ";"; + case "\\,": + return ","; + case "\\n": + case "\\N": + return "\n"; + /* c8 ignore next 2 */ + default: + return string; + } +} + +function replaceNewline(value, newline, structuredEscape) { + // avoid regex when possible. + if (value.indexOf('\\') === -1) { + return value; + } + if (structuredEscape) + newline = new RegExp(newline.source + '|\\\\' + structuredEscape, newline.flags); + return value.replace(newline, replaceNewlineReplace); +} + +let commonProperties = { + "categories": DEFAULT_TYPE_TEXT_MULTI, + "url": DEFAULT_TYPE_URI, + "version": DEFAULT_TYPE_TEXT, + "uid": DEFAULT_TYPE_TEXT +}; + +let commonValues = { + "boolean": { + values: ["TRUE", "FALSE"], + + fromICAL: function(aValue) { + switch (aValue) { + case 'TRUE': + return true; + case 'FALSE': + return false; + default: + //TODO: parser warning + return false; + } + }, + + toICAL: function(aValue) { + if (aValue) { + return 'TRUE'; + } + return 'FALSE'; + } + + }, + float: { + matches: /^[+-]?\d+\.\d+$/, + + fromICAL: function(aValue) { + let parsed = parseFloat(aValue); + if (isStrictlyNaN(parsed)) { + // TODO: parser warning + return 0.0; + } + return parsed; + }, + + toICAL: function(aValue) { + return String(aValue); + } + }, + integer: { + fromICAL: function(aValue) { + let parsed = parseInt(aValue); + if (isStrictlyNaN(parsed)) { + return 0; + } + return parsed; + }, + + toICAL: function(aValue) { + return String(aValue); + } + }, + "utc-offset": { + toICAL: function(aValue) { + if (aValue.length < 7) { + // no seconds + // -0500 + return aValue.slice(0, 3) + + aValue.slice(4, 6); + } else { + // seconds + // -050000 + return aValue.slice(0, 3) + + aValue.slice(4, 6) + + aValue.slice(7, 9); + } + }, + + fromICAL: function(aValue) { + if (aValue.length < 6) { + // no seconds + // -05:00 + return aValue.slice(0, 3) + ':' + + aValue.slice(3, 5); + } else { + // seconds + // -05:00:00 + return aValue.slice(0, 3) + ':' + + aValue.slice(3, 5) + ':' + + aValue.slice(5, 7); + } + }, + + decorate: function(aValue) { + return UtcOffset.fromString(aValue); + }, + + undecorate: function(aValue) { + return aValue.toString(); + } + } +}; + +let icalParams = { + // Although the syntax is DQUOTE uri DQUOTE, I don't think we should + // enforce anything aside from it being a valid content line. + // + // At least some params require - if multi values are used - DQUOTEs + // for each of its values - e.g. delegated-from="uri1","uri2" + // To indicate this, I introduced the new k/v pair + // multiValueSeparateDQuote: true + // + // "ALTREP": { ... }, + + // CN just wants a param-value + // "CN": { ... } + + "cutype": { + values: ["INDIVIDUAL", "GROUP", "RESOURCE", "ROOM", "UNKNOWN"], + allowXName: true, + allowIanaToken: true + }, + + "delegated-from": { + valueType: "cal-address", + multiValue: ",", + multiValueSeparateDQuote: true + }, + "delegated-to": { + valueType: "cal-address", + multiValue: ",", + multiValueSeparateDQuote: true + }, + // "DIR": { ... }, // See ALTREP + "encoding": { + values: ["8BIT", "BASE64"] + }, + // "FMTTYPE": { ... }, // See ALTREP + "fbtype": { + values: ["FREE", "BUSY", "BUSY-UNAVAILABLE", "BUSY-TENTATIVE"], + allowXName: true, + allowIanaToken: true + }, + // "LANGUAGE": { ... }, // See ALTREP + "member": { + valueType: "cal-address", + multiValue: ",", + multiValueSeparateDQuote: true + }, + "partstat": { + // TODO These values are actually different per-component + values: ["NEEDS-ACTION", "ACCEPTED", "DECLINED", "TENTATIVE", + "DELEGATED", "COMPLETED", "IN-PROCESS"], + allowXName: true, + allowIanaToken: true + }, + "range": { + values: ["THISANDFUTURE"] + }, + "related": { + values: ["START", "END"] + }, + "reltype": { + values: ["PARENT", "CHILD", "SIBLING"], + allowXName: true, + allowIanaToken: true + }, + "role": { + values: ["REQ-PARTICIPANT", "CHAIR", + "OPT-PARTICIPANT", "NON-PARTICIPANT"], + allowXName: true, + allowIanaToken: true + }, + "rsvp": { + values: ["TRUE", "FALSE"] + }, + "sent-by": { + valueType: "cal-address" + }, + "tzid": { + matches: /^\// + }, + "value": { + // since the value here is a 'type' lowercase is used. + values: ["binary", "boolean", "cal-address", "date", "date-time", + "duration", "float", "integer", "period", "recur", "text", + "time", "uri", "utc-offset"], + allowXName: true, + allowIanaToken: true + } +}; + +// When adding a value here, be sure to add it to the parameter types! +const icalValues = extend(commonValues, { + text: createTextType(FROM_ICAL_NEWLINE, TO_ICAL_NEWLINE), + + uri: { + // TODO + /* ... */ + }, + + "binary": { + decorate: function(aString) { + return Binary.fromString(aString); + }, + + undecorate: function(aBinary) { + return aBinary.toString(); + } + }, + "cal-address": { + // needs to be an uri + }, + "date": { + decorate: function(aValue, aProp) { + if (design.strict) { + return Time.fromDateString(aValue, aProp); + } else { + return Time.fromString(aValue, aProp); + } + }, + + /** + * undecorates a time object. + */ + undecorate: function(aValue) { + return aValue.toString(); + }, + + fromICAL: function(aValue) { + // from: 20120901 + // to: 2012-09-01 + if (!design.strict && aValue.length >= 15) { + // This is probably a date-time, e.g. 20120901T130000Z + return icalValues["date-time"].fromICAL(aValue); + } else { + return aValue.slice(0, 4) + '-' + + aValue.slice(4, 6) + '-' + + aValue.slice(6, 8); + } + }, + + toICAL: function(aValue) { + // from: 2012-09-01 + // to: 20120901 + let len = aValue.length; + + if (len == 10) { + return aValue.slice(0, 4) + + aValue.slice(5, 7) + + aValue.slice(8, 10); + } else if (len >= 19) { + return icalValues["date-time"].toICAL(aValue); + } else { + //TODO: serialize warning? + return aValue; + } + + } + }, + "date-time": { + fromICAL: function(aValue) { + // from: 20120901T130000 + // to: 2012-09-01T13:00:00 + if (!design.strict && aValue.length == 8) { + // This is probably a date, e.g. 20120901 + return icalValues.date.fromICAL(aValue); + } else { + let result = aValue.slice(0, 4) + '-' + + aValue.slice(4, 6) + '-' + + aValue.slice(6, 8) + 'T' + + aValue.slice(9, 11) + ':' + + aValue.slice(11, 13) + ':' + + aValue.slice(13, 15); + + if (aValue[15] && aValue[15] === 'Z') { + result += 'Z'; + } + + return result; + } + }, + + toICAL: function(aValue) { + // from: 2012-09-01T13:00:00 + // to: 20120901T130000 + let len = aValue.length; + + if (len == 10 && !design.strict) { + return icalValues.date.toICAL(aValue); + } else if (len >= 19) { + let result = aValue.slice(0, 4) + + aValue.slice(5, 7) + + // grab the (DDTHH) segment + aValue.slice(8, 13) + + // MM + aValue.slice(14, 16) + + // SS + aValue.slice(17, 19); + + if (aValue[19] && aValue[19] === 'Z') { + result += 'Z'; + } + return result; + } else { + // TODO: error + return aValue; + } + }, + + decorate: function(aValue, aProp) { + if (design.strict) { + return Time.fromDateTimeString(aValue, aProp); + } else { + return Time.fromString(aValue, aProp); + } + }, + + undecorate: function(aValue) { + return aValue.toString(); + } + }, + duration: { + decorate: function(aValue) { + return Duration.fromString(aValue); + }, + undecorate: function(aValue) { + return aValue.toString(); + } + }, + period: { + fromICAL: function(string) { + let parts = string.split('/'); + parts[0] = icalValues['date-time'].fromICAL(parts[0]); + + if (!Duration.isValueString(parts[1])) { + parts[1] = icalValues['date-time'].fromICAL(parts[1]); + } + + return parts; + }, + + toICAL: function(parts) { + parts = parts.slice(); + if (!design.strict && parts[0].length == 10) { + parts[0] = icalValues.date.toICAL(parts[0]); + } else { + parts[0] = icalValues['date-time'].toICAL(parts[0]); + } + + if (!Duration.isValueString(parts[1])) { + if (!design.strict && parts[1].length == 10) { + parts[1] = icalValues.date.toICAL(parts[1]); + } else { + parts[1] = icalValues['date-time'].toICAL(parts[1]); + } + } + + return parts.join("/"); + }, + + decorate: function(aValue, aProp) { + return Period.fromJSON(aValue, aProp, !design.strict); + }, + + undecorate: function(aValue) { + return aValue.toJSON(); + } + }, + recur: { + fromICAL: function(string) { + return Recur._stringToData(string, true); + }, + + toICAL: function(data) { + let str = ""; + for (let [k, val] of Object.entries(data)) { + if (k == "until") { + if (val.length > 10) { + val = icalValues['date-time'].toICAL(val); + } else { + val = icalValues.date.toICAL(val); + } + } else if (k == "wkst") { + if (typeof val === 'number') { + val = Recur.numericDayToIcalDay(val); + } + } else if (Array.isArray(val)) { + val = val.join(","); + } + str += k.toUpperCase() + "=" + val + ";"; + } + return str.slice(0, Math.max(0, str.length - 1)); + }, + + decorate: function decorate(aValue) { + return Recur.fromData(aValue); + }, + + undecorate: function(aRecur) { + return aRecur.toJSON(); + } + }, + + time: { + fromICAL: function(aValue) { + // from: MMHHSS(Z)? + // to: HH:MM:SS(Z)? + if (aValue.length < 6) { + // TODO: parser exception? + return aValue; + } + + // HH::MM::SSZ? + let result = aValue.slice(0, 2) + ':' + + aValue.slice(2, 4) + ':' + + aValue.slice(4, 6); + + if (aValue[6] === 'Z') { + result += 'Z'; + } + + return result; + }, + + toICAL: function(aValue) { + // from: HH:MM:SS(Z)? + // to: MMHHSS(Z)? + if (aValue.length < 8) { + //TODO: error + return aValue; + } + + let result = aValue.slice(0, 2) + + aValue.slice(3, 5) + + aValue.slice(6, 8); + + if (aValue[8] === 'Z') { + result += 'Z'; + } + + return result; + } + } +}); + +let icalProperties = extend(commonProperties, { + + "action": DEFAULT_TYPE_TEXT, + "attach": { defaultType: "uri" }, + "attendee": { defaultType: "cal-address" }, + "calscale": DEFAULT_TYPE_TEXT, + "class": DEFAULT_TYPE_TEXT, + "comment": DEFAULT_TYPE_TEXT, + "completed": DEFAULT_TYPE_DATETIME, + "contact": DEFAULT_TYPE_TEXT, + "created": DEFAULT_TYPE_DATETIME, + "description": DEFAULT_TYPE_TEXT, + "dtend": DEFAULT_TYPE_DATETIME_DATE, + "dtstamp": DEFAULT_TYPE_DATETIME, + "dtstart": DEFAULT_TYPE_DATETIME_DATE, + "due": DEFAULT_TYPE_DATETIME_DATE, + "duration": { defaultType: "duration" }, + "exdate": { + defaultType: "date-time", + allowedTypes: ["date-time", "date"], + multiValue: ',' + }, + "exrule": DEFAULT_TYPE_RECUR, + "freebusy": { defaultType: "period", multiValue: "," }, + "geo": { defaultType: "float", structuredValue: ";" }, + "last-modified": DEFAULT_TYPE_DATETIME, + "location": DEFAULT_TYPE_TEXT, + "method": DEFAULT_TYPE_TEXT, + "organizer": { defaultType: "cal-address" }, + "percent-complete": DEFAULT_TYPE_INTEGER, + "priority": DEFAULT_TYPE_INTEGER, + "prodid": DEFAULT_TYPE_TEXT, + "related-to": DEFAULT_TYPE_TEXT, + "repeat": DEFAULT_TYPE_INTEGER, + "rdate": { + defaultType: "date-time", + allowedTypes: ["date-time", "date", "period"], + multiValue: ',', + detectType: function(string) { + if (string.indexOf('/') !== -1) { + return 'period'; + } + return (string.indexOf('T') === -1) ? 'date' : 'date-time'; + } + }, + "recurrence-id": DEFAULT_TYPE_DATETIME_DATE, + "resources": DEFAULT_TYPE_TEXT_MULTI, + "request-status": DEFAULT_TYPE_TEXT_STRUCTURED, + "rrule": DEFAULT_TYPE_RECUR, + "sequence": DEFAULT_TYPE_INTEGER, + "status": DEFAULT_TYPE_TEXT, + "summary": DEFAULT_TYPE_TEXT, + "transp": DEFAULT_TYPE_TEXT, + "trigger": { defaultType: "duration", allowedTypes: ["duration", "date-time"] }, + "tzoffsetfrom": DEFAULT_TYPE_UTCOFFSET, + "tzoffsetto": DEFAULT_TYPE_UTCOFFSET, + "tzurl": DEFAULT_TYPE_URI, + "tzid": DEFAULT_TYPE_TEXT, + "tzname": DEFAULT_TYPE_TEXT +}); + +// When adding a value here, be sure to add it to the parameter types! +const vcardValues = extend(commonValues, { + text: createTextType(FROM_VCARD_NEWLINE, TO_VCARD_NEWLINE), + uri: createTextType(FROM_VCARD_NEWLINE, TO_VCARD_NEWLINE), + + date: { + decorate: function(aValue) { + return VCardTime.fromDateAndOrTimeString(aValue, "date"); + }, + undecorate: function(aValue) { + return aValue.toString(); + }, + fromICAL: function(aValue) { + if (aValue.length == 8) { + return icalValues.date.fromICAL(aValue); + } else if (aValue[0] == '-' && aValue.length == 6) { + return aValue.slice(0, 4) + '-' + aValue.slice(4); + } else { + return aValue; + } + }, + toICAL: function(aValue) { + if (aValue.length == 10) { + return icalValues.date.toICAL(aValue); + } else if (aValue[0] == '-' && aValue.length == 7) { + return aValue.slice(0, 4) + aValue.slice(5); + } else { + return aValue; + } + } + }, + + time: { + decorate: function(aValue) { + return VCardTime.fromDateAndOrTimeString("T" + aValue, "time"); + }, + undecorate: function(aValue) { + return aValue.toString(); + }, + fromICAL: function(aValue) { + let splitzone = vcardValues.time._splitZone(aValue, true); + let zone = splitzone[0], value = splitzone[1]; + + //console.log("SPLIT: ",splitzone); + + if (value.length == 6) { + value = value.slice(0, 2) + ':' + + value.slice(2, 4) + ':' + + value.slice(4, 6); + } else if (value.length == 4 && value[0] != '-') { + value = value.slice(0, 2) + ':' + value.slice(2, 4); + } else if (value.length == 5) { + value = value.slice(0, 3) + ':' + value.slice(3, 5); + } + + if (zone.length == 5 && (zone[0] == '-' || zone[0] == '+')) { + zone = zone.slice(0, 3) + ':' + zone.slice(3); + } + + return value + zone; + }, + + toICAL: function(aValue) { + let splitzone = vcardValues.time._splitZone(aValue); + let zone = splitzone[0], value = splitzone[1]; + + if (value.length == 8) { + value = value.slice(0, 2) + + value.slice(3, 5) + + value.slice(6, 8); + } else if (value.length == 5 && value[0] != '-') { + value = value.slice(0, 2) + value.slice(3, 5); + } else if (value.length == 6) { + value = value.slice(0, 3) + value.slice(4, 6); + } + + if (zone.length == 6 && (zone[0] == '-' || zone[0] == '+')) { + zone = zone.slice(0, 3) + zone.slice(4); + } + + return value + zone; + }, + + _splitZone: function(aValue, isFromIcal) { + let lastChar = aValue.length - 1; + let signChar = aValue.length - (isFromIcal ? 5 : 6); + let sign = aValue[signChar]; + let zone, value; + + if (aValue[lastChar] == 'Z') { + zone = aValue[lastChar]; + value = aValue.slice(0, Math.max(0, lastChar)); + } else if (aValue.length > 6 && (sign == '-' || sign == '+')) { + zone = aValue.slice(signChar); + value = aValue.slice(0, Math.max(0, signChar)); + } else { + zone = ""; + value = aValue; + } + + return [zone, value]; + } + }, + + "date-time": { + decorate: function(aValue) { + return VCardTime.fromDateAndOrTimeString(aValue, "date-time"); + }, + + undecorate: function(aValue) { + return aValue.toString(); + }, + + fromICAL: function(aValue) { + return vcardValues['date-and-or-time'].fromICAL(aValue); + }, + + toICAL: function(aValue) { + return vcardValues['date-and-or-time'].toICAL(aValue); + } + }, + + "date-and-or-time": { + decorate: function(aValue) { + return VCardTime.fromDateAndOrTimeString(aValue, "date-and-or-time"); + }, + + undecorate: function(aValue) { + return aValue.toString(); + }, + + fromICAL: function(aValue) { + let parts = aValue.split('T'); + return (parts[0] ? vcardValues.date.fromICAL(parts[0]) : '') + + (parts[1] ? 'T' + vcardValues.time.fromICAL(parts[1]) : ''); + }, + + toICAL: function(aValue) { + let parts = aValue.split('T'); + return vcardValues.date.toICAL(parts[0]) + + (parts[1] ? 'T' + vcardValues.time.toICAL(parts[1]) : ''); + + } + }, + timestamp: icalValues['date-time'], + "language-tag": { + matches: /^[a-zA-Z0-9-]+$/ // Could go with a more strict regex here + }, + "phone-number": { + fromICAL: function(aValue) { + return Array.from(aValue).filter(function(c) { + return c === '\\' ? undefined : c; + }).join(''); + }, + toICAL: function(aValue) { + return Array.from(aValue).map(function(c) { + return c === ',' || c === ";" ? '\\' + c : c; + }).join(''); + } + } +}); + +let vcardParams = { + "type": { + valueType: "text", + multiValue: "," + }, + "value": { + // since the value here is a 'type' lowercase is used. + values: ["text", "uri", "date", "time", "date-time", "date-and-or-time", + "timestamp", "boolean", "integer", "float", "utc-offset", + "language-tag"], + allowXName: true, + allowIanaToken: true + } +}; + +let vcardProperties = extend(commonProperties, { + "adr": { defaultType: "text", structuredValue: ";", multiValue: "," }, + "anniversary": DEFAULT_TYPE_DATE_ANDOR_TIME, + "bday": DEFAULT_TYPE_DATE_ANDOR_TIME, + "caladruri": DEFAULT_TYPE_URI, + "caluri": DEFAULT_TYPE_URI, + "clientpidmap": DEFAULT_TYPE_TEXT_STRUCTURED, + "email": DEFAULT_TYPE_TEXT, + "fburl": DEFAULT_TYPE_URI, + "fn": DEFAULT_TYPE_TEXT, + "gender": DEFAULT_TYPE_TEXT_STRUCTURED, + "geo": DEFAULT_TYPE_URI, + "impp": DEFAULT_TYPE_URI, + "key": DEFAULT_TYPE_URI, + "kind": DEFAULT_TYPE_TEXT, + "lang": { defaultType: "language-tag" }, + "logo": DEFAULT_TYPE_URI, + "member": DEFAULT_TYPE_URI, + "n": { defaultType: "text", structuredValue: ";", multiValue: "," }, + "nickname": DEFAULT_TYPE_TEXT_MULTI, + "note": DEFAULT_TYPE_TEXT, + "org": { defaultType: "text", structuredValue: ";" }, + "photo": DEFAULT_TYPE_URI, + "related": DEFAULT_TYPE_URI, + "rev": { defaultType: "timestamp" }, + "role": DEFAULT_TYPE_TEXT, + "sound": DEFAULT_TYPE_URI, + "source": DEFAULT_TYPE_URI, + "tel": { defaultType: "uri", allowedTypes: ["uri", "text"] }, + "title": DEFAULT_TYPE_TEXT, + "tz": { defaultType: "text", allowedTypes: ["text", "utc-offset", "uri"] }, + "xml": DEFAULT_TYPE_TEXT +}); + +let vcard3Values = extend(commonValues, { + binary: icalValues.binary, + date: vcardValues.date, + "date-time": vcardValues["date-time"], + "phone-number": vcardValues["phone-number"], + uri: icalValues.uri, + text: icalValues.text, + time: icalValues.time, + vcard: icalValues.text, + "utc-offset": { + toICAL: function(aValue) { + return aValue.slice(0, 7); + }, + + fromICAL: function(aValue) { + return aValue.slice(0, 7); + }, + + decorate: function(aValue) { + return UtcOffset.fromString(aValue); + }, + + undecorate: function(aValue) { + return aValue.toString(); + } + } +}); + +let vcard3Params = { + "type": { + valueType: "text", + multiValue: "," + }, + "value": { + // since the value here is a 'type' lowercase is used. + values: ["text", "uri", "date", "date-time", "phone-number", "time", + "boolean", "integer", "float", "utc-offset", "vcard", "binary"], + allowXName: true, + allowIanaToken: true + } +}; + +let vcard3Properties = extend(commonProperties, { + fn: DEFAULT_TYPE_TEXT, + n: { defaultType: "text", structuredValue: ";", multiValue: "," }, + nickname: DEFAULT_TYPE_TEXT_MULTI, + photo: { defaultType: "binary", allowedTypes: ["binary", "uri"] }, + bday: { + defaultType: "date-time", + allowedTypes: ["date-time", "date"], + detectType: function(string) { + return (string.indexOf('T') === -1) ? 'date' : 'date-time'; + } + }, + + adr: { defaultType: "text", structuredValue: ";", multiValue: "," }, + label: DEFAULT_TYPE_TEXT, + + tel: { defaultType: "phone-number" }, + email: DEFAULT_TYPE_TEXT, + mailer: DEFAULT_TYPE_TEXT, + + tz: { defaultType: "utc-offset", allowedTypes: ["utc-offset", "text"] }, + geo: { defaultType: "float", structuredValue: ";" }, + + title: DEFAULT_TYPE_TEXT, + role: DEFAULT_TYPE_TEXT, + logo: { defaultType: "binary", allowedTypes: ["binary", "uri"] }, + agent: { defaultType: "vcard", allowedTypes: ["vcard", "text", "uri"] }, + org: DEFAULT_TYPE_TEXT_STRUCTURED, + + note: DEFAULT_TYPE_TEXT_MULTI, + prodid: DEFAULT_TYPE_TEXT, + rev: { + defaultType: "date-time", + allowedTypes: ["date-time", "date"], + detectType: function(string) { + return (string.indexOf('T') === -1) ? 'date' : 'date-time'; + } + }, + "sort-string": DEFAULT_TYPE_TEXT, + sound: { defaultType: "binary", allowedTypes: ["binary", "uri"] }, + + class: DEFAULT_TYPE_TEXT, + key: { defaultType: "binary", allowedTypes: ["binary", "text"] } +}); + +/** + * iCalendar design set + * @type {designSet} + */ +let icalSet = { + value: icalValues, + param: icalParams, + property: icalProperties, + propertyGroups: false +}; + +/** + * vCard 4.0 design set + * @type {designSet} + */ +let vcardSet = { + value: vcardValues, + param: vcardParams, + property: vcardProperties, + propertyGroups: true +}; + +/** + * vCard 3.0 design set + * @type {designSet} + */ +let vcard3Set = { + value: vcard3Values, + param: vcard3Params, + property: vcard3Properties, + propertyGroups: true +}; + +/** + * The design data, used by the parser to determine types for properties and + * other metadata needed to produce correct jCard/jCal data. + * + * @alias ICAL.design + * @exports module:ICAL.design + */ +const design = { + /** + * Can be set to false to make the parser more lenient. + */ + strict: true, + + /** + * The default set for new properties and components if none is specified. + * @type {designSet} + */ + defaultSet: icalSet, + + /** + * The default type for unknown properties + * @type {String} + */ + defaultType: 'unknown', + + /** + * Holds the design set for known top-level components + * + * @type {Object} + * @property {designSet} vcard vCard VCARD + * @property {designSet} vevent iCalendar VEVENT + * @property {designSet} vtodo iCalendar VTODO + * @property {designSet} vjournal iCalendar VJOURNAL + * @property {designSet} valarm iCalendar VALARM + * @property {designSet} vtimezone iCalendar VTIMEZONE + * @property {designSet} daylight iCalendar DAYLIGHT + * @property {designSet} standard iCalendar STANDARD + * + * @example + * let propertyName = 'fn'; + * let componentDesign = ICAL.design.components.vcard; + * let propertyDetails = componentDesign.property[propertyName]; + * if (propertyDetails.defaultType == 'text') { + * // Yep, sure is... + * } + */ + components: { + vcard: vcardSet, + vcard3: vcard3Set, + vevent: icalSet, + vtodo: icalSet, + vjournal: icalSet, + valarm: icalSet, + vtimezone: icalSet, + daylight: icalSet, + standard: icalSet + }, + + + /** + * The design set for iCalendar (rfc5545/rfc7265) components. + * @type {designSet} + */ + icalendar: icalSet, + + /** + * The design set for vCard (rfc6350/rfc7095) components. + * @type {designSet} + */ + vcard: vcardSet, + + /** + * The design set for vCard (rfc2425/rfc2426/rfc7095) components. + * @type {designSet} + */ + vcard3: vcard3Set, + + /** + * Gets the design set for the given component name. + * + * @param {String} componentName The name of the component + * @return {designSet} The design set for the component + */ + getDesignSet: function(componentName) { + let isInDesign = componentName && componentName in design.components; + return isInDesign ? design.components[componentName] : design.defaultSet; + } +}; +var design$1 = design; + +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * Portions Copyright (C) Philipp Kewisch */ + +/** + * This lets typescript resolve our custom types in the + * generated d.ts files (jsdoc typedefs are converted to typescript types). + * Ignore prevents the typedefs from being documented more than once. + * + * @ignore + * @typedef {import("./types.js").designSet} designSet + * Imports the 'designSet' type from the "types.js" module + */ + +const LINE_ENDING = '\r\n'; +const DEFAULT_VALUE_TYPE = 'unknown'; +const RFC6868_REPLACE_MAP = { '"': "^'", "\n": "^n", "^": "^^" }; + +/** + * Convert a full jCal/jCard array into a iCalendar/vCard string. + * + * @function ICAL.stringify + * @variation function + * @param {Array} jCal The jCal/jCard document + * @return {String} The stringified iCalendar/vCard document + */ +function stringify(jCal) { + if (typeof jCal[0] == "string") { + // This is a single component + jCal = [jCal]; + } + + let i = 0; + let len = jCal.length; + let result = ''; + + for (; i < len; i++) { + result += stringify.component(jCal[i]) + LINE_ENDING; + } + + return result; +} + +/** + * Converts an jCal component array into a ICAL string. + * Recursive will resolve sub-components. + * + * Exact component/property order is not saved all + * properties will come before subcomponents. + * + * @function ICAL.stringify.component + * @param {Array} component + * jCal/jCard fragment of a component + * @param {designSet} designSet + * The design data to use for this component + * @return {String} The iCalendar/vCard string + */ +stringify.component = function(component, designSet) { + let name = component[0].toUpperCase(); + let result = 'BEGIN:' + name + LINE_ENDING; + + let props = component[1]; + let propIdx = 0; + let propLen = props.length; + + let designSetName = component[0]; + // rfc6350 requires that in vCard 4.0 the first component is the VERSION + // component with as value 4.0, note that 3.0 does not have this requirement. + if (designSetName === 'vcard' && component[1].length > 0 && + !(component[1][0][0] === "version" && component[1][0][3] === "4.0")) { + designSetName = "vcard3"; + } + designSet = designSet || design$1.getDesignSet(designSetName); + + for (; propIdx < propLen; propIdx++) { + result += stringify.property(props[propIdx], designSet) + LINE_ENDING; + } + + // Ignore subcomponents if none exist, e.g. in vCard. + let comps = component[2] || []; + let compIdx = 0; + let compLen = comps.length; + + for (; compIdx < compLen; compIdx++) { + result += stringify.component(comps[compIdx], designSet) + LINE_ENDING; + } + + result += 'END:' + name; + return result; +}; + +/** + * Converts a single jCal/jCard property to a iCalendar/vCard string. + * + * @function ICAL.stringify.property + * @param {Array} property + * jCal/jCard property array + * @param {designSet} designSet + * The design data to use for this property + * @param {Boolean} noFold + * If true, the line is not folded + * @return {String} The iCalendar/vCard string + */ +stringify.property = function(property, designSet, noFold) { + let name = property[0].toUpperCase(); + let jsName = property[0]; + let params = property[1]; + + if (!designSet) { + designSet = design$1.defaultSet; + } + + let groupName = params.group; + let line; + if (designSet.propertyGroups && groupName) { + line = groupName.toUpperCase() + "." + name; + } else { + line = name; + } + + for (let [paramName, value] of Object.entries(params)) { + if (designSet.propertyGroups && paramName == 'group') { + continue; + } + + let paramDesign = designSet.param[paramName]; + let multiValue = paramDesign && paramDesign.multiValue; + if (multiValue && Array.isArray(value)) { + value = value.map(function(val) { + val = stringify._rfc6868Unescape(val); + val = stringify.paramPropertyValue(val, paramDesign.multiValueSeparateDQuote); + return val; + }); + value = stringify.multiValue(value, multiValue, "unknown", null, designSet); + } else { + value = stringify._rfc6868Unescape(value); + value = stringify.paramPropertyValue(value); + } + + line += ';' + paramName.toUpperCase() + '=' + value; + } + + if (property.length === 3) { + // If there are no values, we must assume a blank value + return line + ':'; + } + + let valueType = property[2]; + + let propDetails; + let multiValue = false; + let structuredValue = false; + let isDefault = false; + + if (jsName in designSet.property) { + propDetails = designSet.property[jsName]; + + if ('multiValue' in propDetails) { + multiValue = propDetails.multiValue; + } + + if (('structuredValue' in propDetails) && Array.isArray(property[3])) { + structuredValue = propDetails.structuredValue; + } + + if ('defaultType' in propDetails) { + if (valueType === propDetails.defaultType) { + isDefault = true; + } + } else { + if (valueType === DEFAULT_VALUE_TYPE) { + isDefault = true; + } + } + } else { + if (valueType === DEFAULT_VALUE_TYPE) { + isDefault = true; + } + } + + // push the VALUE property if type is not the default + // for the current property. + if (!isDefault) { + // value will never contain ;/:/, so we don't escape it here. + line += ';VALUE=' + valueType.toUpperCase(); + } + + line += ':'; + + if (multiValue && structuredValue) { + line += stringify.multiValue( + property[3], structuredValue, valueType, multiValue, designSet, structuredValue + ); + } else if (multiValue) { + line += stringify.multiValue( + property.slice(3), multiValue, valueType, null, designSet, false + ); + } else if (structuredValue) { + line += stringify.multiValue( + property[3], structuredValue, valueType, null, designSet, structuredValue + ); + } else { + line += stringify.value(property[3], valueType, designSet, false); + } + + return noFold ? line : foldline(line); +}; + +/** + * Handles escaping of property values that may contain: + * + * COLON (:), SEMICOLON (;), or COMMA (,) + * + * If any of the above are present the result is wrapped + * in double quotes. + * + * @function ICAL.stringify.paramPropertyValue + * @param {String} value Raw property value + * @param {boolean} force If value should be escaped even when unnecessary + * @return {String} Given or escaped value when needed + */ +stringify.paramPropertyValue = function(value, force) { + if (!force && + (value.indexOf(',') === -1) && + (value.indexOf(':') === -1) && + (value.indexOf(';') === -1)) { + + return value; + } + + return '"' + value + '"'; +}; + +/** + * Converts an array of ical values into a single + * string based on a type and a delimiter value (like ","). + * + * @function ICAL.stringify.multiValue + * @param {Array} values List of values to convert + * @param {String} delim Used to join the values (",", ";", ":") + * @param {String} type Lowecase ical value type + * (like boolean, date-time, etc..) + * @param {?String} innerMulti If set, each value will again be processed + * Used for structured values + * @param {designSet} designSet + * The design data to use for this property + * + * @return {String} iCalendar/vCard string for value + */ +stringify.multiValue = function(values, delim, type, innerMulti, designSet, structuredValue) { + let result = ''; + let len = values.length; + let i = 0; + + for (; i < len; i++) { + if (innerMulti && Array.isArray(values[i])) { + result += stringify.multiValue(values[i], innerMulti, type, null, designSet, structuredValue); + } else { + result += stringify.value(values[i], type, designSet, structuredValue); + } + + if (i !== (len - 1)) { + result += delim; + } + } + + return result; +}; + +/** + * Processes a single ical value runs the associated "toICAL" method from the + * design value type if available to convert the value. + * + * @function ICAL.stringify.value + * @param {String|Number} value A formatted value + * @param {String} type Lowercase iCalendar/vCard value type + * (like boolean, date-time, etc..) + * @return {String} iCalendar/vCard value for single value + */ +stringify.value = function(value, type, designSet, structuredValue) { + if (type in designSet.value && 'toICAL' in designSet.value[type]) { + return designSet.value[type].toICAL(value, structuredValue); + } + return value; +}; + +/** + * Internal helper for rfc6868. Exposing this on ICAL.stringify so that + * hackers can disable the rfc6868 parsing if the really need to. + * + * @param {String} val The value to unescape + * @return {String} The escaped value + */ +stringify._rfc6868Unescape = function(val) { + return val.replace(/[\n^"]/g, function(x) { + return RFC6868_REPLACE_MAP[x]; + }); +}; + +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * Portions Copyright (C) Philipp Kewisch */ + +const NAME_INDEX$1 = 0; +const PROP_INDEX = 1; +const TYPE_INDEX = 2; +const VALUE_INDEX = 3; + +/** + * This lets typescript resolve our custom types in the + * generated d.ts files (jsdoc typedefs are converted to typescript types). + * Ignore prevents the typedefs from being documented more than once. + * @ignore + * @typedef {import("./types.js").designSet} designSet + * Imports the 'designSet' type from the "types.js" module + * @typedef {import("./types.js").Geo} Geo + * Imports the 'Geo' type from the "types.js" module + */ + +/** + * Provides a layer on top of the raw jCal object for manipulating a single property, with its + * parameters and value. + * + * @memberof ICAL + */ +class Property { + /** + * Create an {@link ICAL.Property} by parsing the passed iCalendar string. + * + * @param {String} str The iCalendar string to parse + * @param {designSet=} designSet The design data to use for this property + * @return {Property} The created iCalendar property + */ + static fromString(str, designSet) { + return new Property(parse.property(str, designSet)); + } + + /** + * Creates a new ICAL.Property instance. + * + * It is important to note that mutations done in the wrapper directly mutate the jCal object used + * to initialize. + * + * Can also be used to create new properties by passing the name of the property (as a String). + * + * @param {Array|String} jCal Raw jCal representation OR the new name of the property + * @param {Component=} parent Parent component + */ + constructor(jCal, parent) { + this._parent = parent || null; + + if (typeof(jCal) === 'string') { + // We are creating the property by name and need to detect the type + this.jCal = [jCal, {}, design$1.defaultType]; + this.jCal[TYPE_INDEX] = this.getDefaultType(); + } else { + this.jCal = jCal; + } + this._updateType(); + } + + /** + * The value type for this property + * @type {String} + */ + get type() { + return this.jCal[TYPE_INDEX]; + } + + /** + * The name of this property, in lowercase. + * @type {String} + */ + get name() { + return this.jCal[NAME_INDEX$1]; + } + + /** + * The parent component for this property. + * @type {Component} + */ + get parent() { + return this._parent; + } + + set parent(p) { + // Before setting the parent, check if the design set has changed. If it + // has, we later need to update the type if it was unknown before. + let designSetChanged = !this._parent || (p && p._designSet != this._parent._designSet); + + this._parent = p; + + if (this.type == design$1.defaultType && designSetChanged) { + this.jCal[TYPE_INDEX] = this.getDefaultType(); + this._updateType(); + } + } + + /** + * The design set for this property, e.g. icalendar vs vcard + * + * @type {designSet} + * @private + */ + get _designSet() { + return this.parent ? this.parent._designSet : design$1.defaultSet; + } + + /** + * Updates the type metadata from the current jCal type and design set. + * + * @private + */ + _updateType() { + let designSet = this._designSet; + + if (this.type in designSet.value) { + if ('decorate' in designSet.value[this.type]) { + this.isDecorated = true; + } else { + this.isDecorated = false; + } + + if (this.name in designSet.property) { + this.isMultiValue = ('multiValue' in designSet.property[this.name]); + this.isStructuredValue = ('structuredValue' in designSet.property[this.name]); + } + } + } + + /** + * Hydrate a single value. The act of hydrating means turning the raw jCal + * value into a potentially wrapped object, for example {@link ICAL.Time}. + * + * @private + * @param {Number} index The index of the value to hydrate + * @return {?Object} The decorated value. + */ + _hydrateValue(index) { + if (this._values && this._values[index]) { + return this._values[index]; + } + + // for the case where there is no value. + if (this.jCal.length <= (VALUE_INDEX + index)) { + return null; + } + + if (this.isDecorated) { + if (!this._values) { + this._values = []; + } + return (this._values[index] = this._decorate( + this.jCal[VALUE_INDEX + index] + )); + } else { + return this.jCal[VALUE_INDEX + index]; + } + } + + /** + * Decorate a single value, returning its wrapped object. This is used by + * the hydrate function to actually wrap the value. + * + * @private + * @param {?} value The value to decorate + * @return {Object} The decorated value + */ + _decorate(value) { + return this._designSet.value[this.type].decorate(value, this); + } + + /** + * Undecorate a single value, returning its raw jCal data. + * + * @private + * @param {Object} value The value to undecorate + * @return {?} The undecorated value + */ + _undecorate(value) { + return this._designSet.value[this.type].undecorate(value, this); + } + + /** + * Sets the value at the given index while also hydrating it. The passed + * value can either be a decorated or undecorated value. + * + * @private + * @param {?} value The value to set + * @param {Number} index The index to set it at + */ + _setDecoratedValue(value, index) { + if (!this._values) { + this._values = []; + } + + if (typeof(value) === 'object' && 'icaltype' in value) { + // decorated value + this.jCal[VALUE_INDEX + index] = this._undecorate(value); + this._values[index] = value; + } else { + // undecorated value + this.jCal[VALUE_INDEX + index] = value; + this._values[index] = this._decorate(value); + } + } + + /** + * Gets a parameter on the property. + * + * @param {String} name Parameter name (lowercase) + * @return {Array|String} Parameter value + */ + getParameter(name) { + if (name in this.jCal[PROP_INDEX]) { + return this.jCal[PROP_INDEX][name]; + } else { + return undefined; + } + } + + /** + * Gets first parameter on the property. + * + * @param {String} name Parameter name (lowercase) + * @return {String} Parameter value + */ + getFirstParameter(name) { + let parameters = this.getParameter(name); + + if (Array.isArray(parameters)) { + return parameters[0]; + } + + return parameters; + } + + /** + * Sets a parameter on the property. + * + * @param {String} name The parameter name + * @param {Array|String} value The parameter value + */ + setParameter(name, value) { + let lcname = name.toLowerCase(); + if (typeof value === "string" && + lcname in this._designSet.param && + 'multiValue' in this._designSet.param[lcname]) { + value = [value]; + } + this.jCal[PROP_INDEX][name] = value; + } + + /** + * Removes a parameter + * + * @param {String} name The parameter name + */ + removeParameter(name) { + delete this.jCal[PROP_INDEX][name]; + } + + /** + * Get the default type based on this property's name. + * + * @return {String} The default type for this property + */ + getDefaultType() { + let name = this.jCal[NAME_INDEX$1]; + let designSet = this._designSet; + + if (name in designSet.property) { + let details = designSet.property[name]; + if ('defaultType' in details) { + return details.defaultType; + } + } + return design$1.defaultType; + } + + /** + * Sets type of property and clears out any existing values of the current + * type. + * + * @param {String} type New iCAL type (see design.*.values) + */ + resetType(type) { + this.removeAllValues(); + this.jCal[TYPE_INDEX] = type; + this._updateType(); + } + + /** + * Finds the first property value. + * + * @return {Binary | Duration | Period | + * Recur | Time | UtcOffset | Geo | string | null} First property value + */ + getFirstValue() { + return this._hydrateValue(0); + } + + /** + * Gets all values on the property. + * + * NOTE: this creates an array during each call. + * + * @return {Array} List of values + */ + getValues() { + let len = this.jCal.length - VALUE_INDEX; + + if (len < 1) { + // it is possible for a property to have no value. + return []; + } + + let i = 0; + let result = []; + + for (; i < len; i++) { + result[i] = this._hydrateValue(i); + } + + return result; + } + + /** + * Removes all values from this property + */ + removeAllValues() { + if (this._values) { + this._values.length = 0; + } + this.jCal.length = 3; + } + + /** + * Sets the values of the property. Will overwrite the existing values. + * This can only be used for multi-value properties. + * + * @param {Array} values An array of values + */ + setValues(values) { + if (!this.isMultiValue) { + throw new Error( + this.name + ': does not not support mulitValue.\n' + + 'override isMultiValue' + ); + } + + let len = values.length; + let i = 0; + this.removeAllValues(); + + if (len > 0 && + typeof(values[0]) === 'object' && + 'icaltype' in values[0]) { + this.resetType(values[0].icaltype); + } + + if (this.isDecorated) { + for (; i < len; i++) { + this._setDecoratedValue(values[i], i); + } + } else { + for (; i < len; i++) { + this.jCal[VALUE_INDEX + i] = values[i]; + } + } + } + + /** + * Sets the current value of the property. If this is a multi-value + * property, all other values will be removed. + * + * @param {String|Object} value New property value. + */ + setValue(value) { + this.removeAllValues(); + if (typeof(value) === 'object' && 'icaltype' in value) { + this.resetType(value.icaltype); + } + + if (this.isDecorated) { + this._setDecoratedValue(value, 0); + } else { + this.jCal[VALUE_INDEX] = value; + } + } + + /** + * Returns the Object representation of this component. The returned object + * is a live jCal object and should be cloned if modified. + * @return {Object} + */ + toJSON() { + return this.jCal; + } + + /** + * The string representation of this component. + * @return {String} + */ + toICALString() { + return stringify.property( + this.jCal, this._designSet, true + ); + } +} + +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * Portions Copyright (C) Philipp Kewisch */ + +/** + * This lets typescript resolve our custom types in the + * generated d.ts files (jsdoc typedefs are converted to typescript types). + * Ignore prevents the typedefs from being documented more than once. + * @ignore + * @typedef {import("./types.js").designSet} designSet + * Imports the 'designSet' type from the "types.js" module + * @typedef {import("./types.js").Geo} Geo + * Imports the 'Geo' type from the "types.js" module + */ + +const NAME_INDEX = 0; +const PROPERTY_INDEX = 1; +const COMPONENT_INDEX = 2; + +/** + * Wraps a jCal component, adding convenience methods to add, remove and update subcomponents and + * properties. + * + * @memberof ICAL + */ +class Component { + /** + * Create an {@link ICAL.Component} by parsing the passed iCalendar string. + * + * @param {String} str The iCalendar string to parse + */ + static fromString(str) { + return new Component(parse.component(str)); + } + + /** + * Creates a new Component instance. + * + * @param {Array|String} jCal Raw jCal component data OR name of new + * component + * @param {Component=} parent Parent component to associate + */ + constructor(jCal, parent) { + if (typeof(jCal) === 'string') { + // jCal spec (name, properties, components) + jCal = [jCal, [], []]; + } + + // mostly for legacy reasons. + this.jCal = jCal; + + this.parent = parent || null; + + if (!this.parent && this.name === 'vcalendar') { + this._timezoneCache = new Map(); + } + } + + /** + * Hydrated properties are inserted into the _properties array at the same + * position as in the jCal array, so it is possible that the array contains + * undefined values for unhydrdated properties. To avoid iterating the + * array when checking if all properties have been hydrated, we save the + * count here. + * + * @type {Number} + * @private + */ + _hydratedPropertyCount = 0; + + /** + * The same count as for _hydratedPropertyCount, but for subcomponents + * + * @type {Number} + * @private + */ + _hydratedComponentCount = 0; + + /** + * A cache of hydrated time zone objects which may be used by consumers, keyed + * by time zone ID. + * + * @type {Map} + * @private + */ + _timezoneCache = null; + + /** + * @private + */ + _components = null; + + /** + * @private + */ + _properties = null; + + /** + * The name of this component + * + * @type {String} + */ + get name() { + return this.jCal[NAME_INDEX]; + } + + /** + * The design set for this component, e.g. icalendar vs vcard + * + * @type {designSet} + * @private + */ + get _designSet() { + let parentDesign = this.parent && this.parent._designSet; + return parentDesign || design$1.getDesignSet(this.name); + } + + /** + * @private + */ + _hydrateComponent(index) { + if (!this._components) { + this._components = []; + this._hydratedComponentCount = 0; + } + + if (this._components[index]) { + return this._components[index]; + } + + let comp = new Component( + this.jCal[COMPONENT_INDEX][index], + this + ); + + this._hydratedComponentCount++; + return (this._components[index] = comp); + } + + /** + * @private + */ + _hydrateProperty(index) { + if (!this._properties) { + this._properties = []; + this._hydratedPropertyCount = 0; + } + + if (this._properties[index]) { + return this._properties[index]; + } + + let prop = new Property( + this.jCal[PROPERTY_INDEX][index], + this + ); + + this._hydratedPropertyCount++; + return (this._properties[index] = prop); + } + + /** + * Finds first sub component, optionally filtered by name. + * + * @param {String=} name Optional name to filter by + * @return {?Component} The found subcomponent + */ + getFirstSubcomponent(name) { + if (name) { + let i = 0; + let comps = this.jCal[COMPONENT_INDEX]; + let len = comps.length; + + for (; i < len; i++) { + if (comps[i][NAME_INDEX] === name) { + let result = this._hydrateComponent(i); + return result; + } + } + } else { + if (this.jCal[COMPONENT_INDEX].length) { + return this._hydrateComponent(0); + } + } + + // ensure we return a value (strict mode) + return null; + } + + /** + * Finds all sub components, optionally filtering by name. + * + * @param {String=} name Optional name to filter by + * @return {Component[]} The found sub components + */ + getAllSubcomponents(name) { + let jCalLen = this.jCal[COMPONENT_INDEX].length; + let i = 0; + + if (name) { + let comps = this.jCal[COMPONENT_INDEX]; + let result = []; + + for (; i < jCalLen; i++) { + if (name === comps[i][NAME_INDEX]) { + result.push( + this._hydrateComponent(i) + ); + } + } + return result; + } else { + if (!this._components || + (this._hydratedComponentCount !== jCalLen)) { + for (; i < jCalLen; i++) { + this._hydrateComponent(i); + } + } + + return this._components || []; + } + } + + /** + * Returns true when a named property exists. + * + * @param {String} name The property name + * @return {Boolean} True, when property is found + */ + hasProperty(name) { + let props = this.jCal[PROPERTY_INDEX]; + let len = props.length; + + let i = 0; + for (; i < len; i++) { + // 0 is property name + if (props[i][NAME_INDEX] === name) { + return true; + } + } + + return false; + } + + /** + * Finds the first property, optionally with the given name. + * + * @param {String=} name Lowercase property name + * @return {?Property} The found property + */ + getFirstProperty(name) { + if (name) { + let i = 0; + let props = this.jCal[PROPERTY_INDEX]; + let len = props.length; + + for (; i < len; i++) { + if (props[i][NAME_INDEX] === name) { + let result = this._hydrateProperty(i); + return result; + } + } + } else { + if (this.jCal[PROPERTY_INDEX].length) { + return this._hydrateProperty(0); + } + } + + return null; + } + + /** + * Returns first property's value, if available. + * + * @param {String=} name Lowercase property name + * @return {Binary | Duration | Period | + * Recur | Time | UtcOffset | Geo | string | null} The found property value. + */ + getFirstPropertyValue(name) { + let prop = this.getFirstProperty(name); + if (prop) { + return prop.getFirstValue(); + } + + return null; + } + + /** + * Get all properties in the component, optionally filtered by name. + * + * @param {String=} name Lowercase property name + * @return {Property[]} List of properties + */ + getAllProperties(name) { + let jCalLen = this.jCal[PROPERTY_INDEX].length; + let i = 0; + + if (name) { + let props = this.jCal[PROPERTY_INDEX]; + let result = []; + + for (; i < jCalLen; i++) { + if (name === props[i][NAME_INDEX]) { + result.push( + this._hydrateProperty(i) + ); + } + } + return result; + } else { + if (!this._properties || + (this._hydratedPropertyCount !== jCalLen)) { + for (; i < jCalLen; i++) { + this._hydrateProperty(i); + } + } + + return this._properties || []; + } + } + + /** + * @private + */ + _removeObjectByIndex(jCalIndex, cache, index) { + cache = cache || []; + // remove cached version + if (cache[index]) { + let obj = cache[index]; + if ("parent" in obj) { + obj.parent = null; + } + } + + cache.splice(index, 1); + + // remove it from the jCal + this.jCal[jCalIndex].splice(index, 1); + } + + /** + * @private + */ + _removeObject(jCalIndex, cache, nameOrObject) { + let i = 0; + let objects = this.jCal[jCalIndex]; + let len = objects.length; + let cached = this[cache]; + + if (typeof(nameOrObject) === 'string') { + for (; i < len; i++) { + if (objects[i][NAME_INDEX] === nameOrObject) { + this._removeObjectByIndex(jCalIndex, cached, i); + return true; + } + } + } else if (cached) { + for (; i < len; i++) { + if (cached[i] && cached[i] === nameOrObject) { + this._removeObjectByIndex(jCalIndex, cached, i); + return true; + } + } + } + + return false; + } + + /** + * @private + */ + _removeAllObjects(jCalIndex, cache, name) { + let cached = this[cache]; + + // Unfortunately we have to run through all children to reset their + // parent property. + let objects = this.jCal[jCalIndex]; + let i = objects.length - 1; + + // descending search required because splice + // is used and will effect the indices. + for (; i >= 0; i--) { + if (!name || objects[i][NAME_INDEX] === name) { + this._removeObjectByIndex(jCalIndex, cached, i); + } + } + } + + /** + * Adds a single sub component. + * + * @param {Component} component The component to add + * @return {Component} The passed in component + */ + addSubcomponent(component) { + if (!this._components) { + this._components = []; + this._hydratedComponentCount = 0; + } + + if (component.parent) { + component.parent.removeSubcomponent(component); + } + + let idx = this.jCal[COMPONENT_INDEX].push(component.jCal); + this._components[idx - 1] = component; + this._hydratedComponentCount++; + component.parent = this; + return component; + } + + /** + * Removes a single component by name or the instance of a specific + * component. + * + * @param {Component|String} nameOrComp Name of component, or component + * @return {Boolean} True when comp is removed + */ + removeSubcomponent(nameOrComp) { + let removed = this._removeObject(COMPONENT_INDEX, '_components', nameOrComp); + if (removed) { + this._hydratedComponentCount--; + } + return removed; + } + + /** + * Removes all components or (if given) all components by a particular + * name. + * + * @param {String=} name Lowercase component name + */ + removeAllSubcomponents(name) { + let removed = this._removeAllObjects(COMPONENT_INDEX, '_components', name); + this._hydratedComponentCount = 0; + return removed; + } + + /** + * Adds an {@link ICAL.Property} to the component. + * + * @param {Property} property The property to add + * @return {Property} The passed in property + */ + addProperty(property) { + if (!(property instanceof Property)) { + throw new TypeError('must be instance of ICAL.Property'); + } + + if (!this._properties) { + this._properties = []; + this._hydratedPropertyCount = 0; + } + + if (property.parent) { + property.parent.removeProperty(property); + } + + let idx = this.jCal[PROPERTY_INDEX].push(property.jCal); + this._properties[idx - 1] = property; + this._hydratedPropertyCount++; + property.parent = this; + return property; + } + + /** + * Helper method to add a property with a value to the component. + * + * @param {String} name Property name to add + * @param {String|Number|Object} value Property value + * @return {Property} The created property + */ + addPropertyWithValue(name, value) { + let prop = new Property(name); + prop.setValue(value); + + this.addProperty(prop); + + return prop; + } + + /** + * Helper method that will update or create a property of the given name + * and sets its value. If multiple properties with the given name exist, + * only the first is updated. + * + * @param {String} name Property name to update + * @param {String|Number|Object} value Property value + * @return {Property} The created property + */ + updatePropertyWithValue(name, value) { + let prop = this.getFirstProperty(name); + + if (prop) { + prop.setValue(value); + } else { + prop = this.addPropertyWithValue(name, value); + } + + return prop; + } + + /** + * Removes a single property by name or the instance of the specific + * property. + * + * @param {String|Property} nameOrProp Property name or instance to remove + * @return {Boolean} True, when deleted + */ + removeProperty(nameOrProp) { + let removed = this._removeObject(PROPERTY_INDEX, '_properties', nameOrProp); + if (removed) { + this._hydratedPropertyCount--; + } + return removed; + } + + /** + * Removes all properties associated with this component, optionally + * filtered by name. + * + * @param {String=} name Lowercase property name + * @return {Boolean} True, when deleted + */ + removeAllProperties(name) { + let removed = this._removeAllObjects(PROPERTY_INDEX, '_properties', name); + this._hydratedPropertyCount = 0; + return removed; + } + + /** + * Returns the Object representation of this component. The returned object + * is a live jCal object and should be cloned if modified. + * @return {Object} + */ + toJSON() { + return this.jCal; + } + + /** + * The string representation of this component. + * @return {String} + */ + toString() { + return stringify.component( + this.jCal, this._designSet + ); + } + + /** + * Retrieve a time zone definition from the component tree, if any is present. + * If the tree contains no time zone definitions or the TZID cannot be + * matched, returns null. + * + * @param {String} tzid The ID of the time zone to retrieve + * @return {Timezone} The time zone corresponding to the ID, or null + */ + getTimeZoneByID(tzid) { + // VTIMEZONE components can only appear as a child of the VCALENDAR + // component; walk the tree if we're not the root. + if (this.parent) { + return this.parent.getTimeZoneByID(tzid); + } + + // If there is no time zone cache, we are probably parsing an incomplete + // file and will have no time zone definitions. + if (!this._timezoneCache) { + return null; + } + + if (this._timezoneCache.has(tzid)) { + return this._timezoneCache.get(tzid); + } + + // If the time zone is not already cached, hydrate it from the + // subcomponents. + const zones = this.getAllSubcomponents('vtimezone'); + for (const zone of zones) { + if (zone.getFirstProperty('tzid').getFirstValue() === tzid) { + const hydratedZone = new Timezone({ + component: zone, + tzid: tzid, + }); + + this._timezoneCache.set(tzid, hydratedZone); + + return hydratedZone; + } + } + + // Per the standard, we should always have a time zone defined in a file + // for any referenced TZID, but don't blow up if the file is invalid. + return null; + } +} + +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * Portions Copyright (C) Philipp Kewisch */ + +/** + * Primary class for expanding recurring rules. Can take multiple rrules, rdates, exdate(s) and + * iterate (in order) over each next occurrence. + * + * Once initialized this class can also be serialized saved and continue iteration from the last + * point. + * + * NOTE: it is intended that this class is to be used with {@link ICAL.Event} which handles recurrence + * exceptions. + * + * @example + * // assuming event is a parsed ical component + * var event; + * + * var expand = new ICAL.RecurExpansion({ + * component: event, + * dtstart: event.getFirstPropertyValue('dtstart') + * }); + * + * // remember there are infinite rules so it is a good idea to limit the scope of the iterations + * // then resume later on. + * + * // next is always an ICAL.Time or null + * var next; + * + * while (someCondition && (next = expand.next())) { + * // do something with next + * } + * + * // save instance for later + * var json = JSON.stringify(expand); + * + * //... + * + * // NOTE: if the component's properties have changed you will need to rebuild the class and start + * // over. This only works when the component's recurrence info is the same. + * var expand = new ICAL.RecurExpansion(JSON.parse(json)); + * + * @memberof ICAL + */ +class RecurExpansion { + /** + * Creates a new ICAL.RecurExpansion instance. + * + * The options object can be filled with the specified initial values. It can also contain + * additional members, as a result of serializing a previous expansion state, as shown in the + * example. + * + * @param {Object} options + * Recurrence expansion options + * @param {Time} options.dtstart + * Start time of the event + * @param {Component=} options.component + * Component for expansion, required if not resuming. + */ + constructor(options) { + this.ruleDates = []; + this.exDates = []; + this.fromData(options); + } + + /** + * True when iteration is fully completed. + * @type {Boolean} + */ + complete = false; + + /** + * Array of rrule iterators. + * + * @type {RecurIterator[]} + * @private + */ + ruleIterators = null; + + /** + * Array of rdate instances. + * + * @type {Time[]} + * @private + */ + ruleDates = null; + + /** + * Array of exdate instances. + * + * @type {Time[]} + * @private + */ + exDates = null; + + /** + * Current position in ruleDates array. + * @type {Number} + * @private + */ + ruleDateInc = 0; + + /** + * Current position in exDates array + * @type {Number} + * @private + */ + exDateInc = 0; + + /** + * Current negative date. + * + * @type {Time} + * @private + */ + exDate = null; + + /** + * Current additional date. + * + * @type {Time} + * @private + */ + ruleDate = null; + + /** + * Start date of recurring rules. + * + * @type {Time} + */ + dtstart = null; + + /** + * Last expanded time + * + * @type {Time} + */ + last = null; + + /** + * Initialize the recurrence expansion from the data object. The options + * object may also contain additional members, see the + * {@link ICAL.RecurExpansion constructor} for more details. + * + * @param {Object} options + * Recurrence expansion options + * @param {Time} options.dtstart + * Start time of the event + * @param {Component=} options.component + * Component for expansion, required if not resuming. + */ + fromData(options) { + let start = formatClassType(options.dtstart, Time); + + if (!start) { + throw new Error('.dtstart (ICAL.Time) must be given'); + } else { + this.dtstart = start; + } + + if (options.component) { + this._init(options.component); + } else { + this.last = formatClassType(options.last, Time) || start.clone(); + + if (!options.ruleIterators) { + throw new Error('.ruleIterators or .component must be given'); + } + + this.ruleIterators = options.ruleIterators.map(function(item) { + return formatClassType(item, RecurIterator); + }); + + this.ruleDateInc = options.ruleDateInc; + this.exDateInc = options.exDateInc; + + if (options.ruleDates) { + this.ruleDates = options.ruleDates.map(item => formatClassType(item, Time)); + this.ruleDate = this.ruleDates[this.ruleDateInc]; + } + + if (options.exDates) { + this.exDates = options.exDates.map(item => formatClassType(item, Time)); + this.exDate = this.exDates[this.exDateInc]; + } + + if (typeof(options.complete) !== 'undefined') { + this.complete = options.complete; + } + } + } + + /** + * Retrieve the next occurrence in the series. + * @return {Time} + */ + next() { + let iter; + let next; + let compare; + + let maxTries = 500; + let currentTry = 0; + + while (true) { + if (currentTry++ > maxTries) { + throw new Error( + 'max tries have occurred, rule may be impossible to fulfill.' + ); + } + + next = this.ruleDate; + iter = this._nextRecurrenceIter(this.last); + + // no more matches + // because we increment the rule day or rule + // _after_ we choose a value this should be + // the only spot where we need to worry about the + // end of events. + if (!next && !iter) { + // there are no more iterators or rdates + this.complete = true; + break; + } + + // no next rule day or recurrence rule is first. + if (!next || (iter && next.compare(iter.last) > 0)) { + // must be cloned, recur will reuse the time element. + next = iter.last.clone(); + // move to next so we can continue + iter.next(); + } + + // if the ruleDate is still next increment it. + if (this.ruleDate === next) { + this._nextRuleDay(); + } + + this.last = next; + + // check the negative rules + if (this.exDate) { + compare = this.exDate.compare(this.last); + + if (compare < 0) { + this._nextExDay(); + } + + // if the current rule is excluded skip it. + if (compare === 0) { + this._nextExDay(); + continue; + } + } + + //XXX: The spec states that after we resolve the final + // list of dates we execute exdate this seems somewhat counter + // intuitive to what I have seen most servers do so for now + // I exclude based on the original date not the one that may + // have been modified by the exception. + return this.last; + } + } + + /** + * Converts object into a serialize-able format. This format can be passed + * back into the expansion to resume iteration. + * @return {Object} + */ + toJSON() { + function toJSON(item) { + return item.toJSON(); + } + + let result = Object.create(null); + result.ruleIterators = this.ruleIterators.map(toJSON); + + if (this.ruleDates) { + result.ruleDates = this.ruleDates.map(toJSON); + } + + if (this.exDates) { + result.exDates = this.exDates.map(toJSON); + } + + result.ruleDateInc = this.ruleDateInc; + result.exDateInc = this.exDateInc; + result.last = this.last.toJSON(); + result.dtstart = this.dtstart.toJSON(); + result.complete = this.complete; + + return result; + } + + /** + * Extract all dates from the properties in the given component. The + * properties will be filtered by the property name. + * + * @private + * @param {Component} component The component to search in + * @param {String} propertyName The property name to search for + * @return {Time[]} The extracted dates. + */ + _extractDates(component, propertyName) { + let result = []; + let props = component.getAllProperties(propertyName); + + for (let i = 0, len = props.length; i < len; i++) { + for (let prop of props[i].getValues()) { + let idx = binsearchInsert( + result, + prop, + (a, b) => a.compare(b) + ); + + // ordered insert + result.splice(idx, 0, prop); + } + } + + return result; + } + + /** + * Initialize the recurrence expansion. + * + * @private + * @param {Component} component The component to initialize from. + */ + _init(component) { + this.ruleIterators = []; + + this.last = this.dtstart.clone(); + + // to provide api consistency non-recurring + // events can also use the iterator though it will + // only return a single time. + if (!component.hasProperty('rdate') && + !component.hasProperty('rrule') && + !component.hasProperty('recurrence-id')) { + this.ruleDate = this.last.clone(); + this.complete = true; + return; + } + + if (component.hasProperty('rdate')) { + this.ruleDates = this._extractDates(component, 'rdate'); + + // special hack for cases where first rdate is prior + // to the start date. We only check for the first rdate. + // This is mostly for google's crazy recurring date logic + // (contacts birthdays). + if ((this.ruleDates[0]) && + (this.ruleDates[0].compare(this.dtstart) < 0)) { + + this.ruleDateInc = 0; + this.last = this.ruleDates[0].clone(); + } else { + this.ruleDateInc = binsearchInsert( + this.ruleDates, + this.last, + (a, b) => a.compare(b) + ); + } + + this.ruleDate = this.ruleDates[this.ruleDateInc]; + } + + if (component.hasProperty('rrule')) { + let rules = component.getAllProperties('rrule'); + let i = 0; + let len = rules.length; + + let rule; + let iter; + + for (; i < len; i++) { + rule = rules[i].getFirstValue(); + iter = rule.iterator(this.dtstart); + this.ruleIterators.push(iter); + + // increment to the next occurrence so future + // calls to next return times beyond the initial iteration. + // XXX: I find this suspicious might be a bug? + iter.next(); + } + } + + if (component.hasProperty('exdate')) { + this.exDates = this._extractDates(component, 'exdate'); + // if we have a .last day we increment the index to beyond it. + this.exDateInc = binsearchInsert( + this.exDates, + this.last, + (a, b) => a.compare(b) + ); + + this.exDate = this.exDates[this.exDateInc]; + } + } + + /** + * Advance to the next exdate + * @private + */ + _nextExDay() { + this.exDate = this.exDates[++this.exDateInc]; + } + + /** + * Advance to the next rule date + * @private + */ + _nextRuleDay() { + this.ruleDate = this.ruleDates[++this.ruleDateInc]; + } + + /** + * Find and return the recurrence rule with the most recent event and + * return it. + * + * @private + * @return {?RecurIterator} Found iterator. + */ + _nextRecurrenceIter() { + let iters = this.ruleIterators; + + if (iters.length === 0) { + return null; + } + + let len = iters.length; + let iter; + let iterTime; + let iterIdx = 0; + let chosenIter; + + // loop through each iterator + for (; iterIdx < len; iterIdx++) { + iter = iters[iterIdx]; + iterTime = iter.last; + + // if iteration is complete + // then we must exclude it from + // the search and remove it. + if (iter.completed) { + len--; + if (iterIdx !== 0) { + iterIdx--; + } + iters.splice(iterIdx, 1); + continue; + } + + // find the most recent possible choice + if (!chosenIter || chosenIter.last.compare(iterTime) > 0) { + // that iterator is saved + chosenIter = iter; + } + } + + // the chosen iterator is returned but not mutated + // this iterator contains the most recent event. + return chosenIter; + } +} + +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * Portions Copyright (C) Philipp Kewisch */ + +/** + * This lets typescript resolve our custom types in the + * generated d.ts files (jsdoc typedefs are converted to typescript types). + * Ignore prevents the typedefs from being documented more than once. + * @ignore + * @typedef {import("./types.js").frequencyValues} frequencyValues + * Imports the 'frequencyValues' type from the "types.js" module + * @typedef {import("./types.js").occurrenceDetails} occurrenceDetails + * Imports the 'occurrenceDetails' type from the "types.js" module + */ + +/** + * ICAL.js is organized into multiple layers. The bottom layer is a raw jCal + * object, followed by the component/property layer. The highest level is the + * event representation, which this class is part of. See the + * {@tutorial layers} guide for more details. + * + * @memberof ICAL + */ +class Event { + /** + * Creates a new ICAL.Event instance. + * + * @param {Component=} component The ICAL.Component to base this event on + * @param {Object} [options] Options for this event + * @param {Boolean=} options.strictExceptions When true, will verify exceptions are related by + * their UUID + * @param {Array=} options.exceptions + * Exceptions to this event, either as components or events. If not + * specified exceptions will automatically be set in relation of + * component's parent + */ + constructor(component, options) { + if (!(component instanceof Component)) { + options = component; + component = null; + } + + if (component) { + this.component = component; + } else { + this.component = new Component('vevent'); + } + + this._rangeExceptionCache = Object.create(null); + this.exceptions = Object.create(null); + this.rangeExceptions = []; + + if (options && options.strictExceptions) { + this.strictExceptions = options.strictExceptions; + } + + if (options && options.exceptions) { + options.exceptions.forEach(this.relateException, this); + } else if (this.component.parent && !this.isRecurrenceException()) { + this.component.parent.getAllSubcomponents('vevent').forEach(function(event) { + if (event.hasProperty('recurrence-id')) { + this.relateException(event); + } + }, this); + } + } + + + static THISANDFUTURE = 'THISANDFUTURE'; + + /** + * List of related event exceptions. + * + * @type {Event[]} + */ + exceptions = null; + + /** + * When true, will verify exceptions are related by their UUID. + * + * @type {Boolean} + */ + strictExceptions = false; + + /** + * Relates a given event exception to this object. If the given component + * does not share the UID of this event it cannot be related and will throw + * an exception. + * + * If this component is an exception it cannot have other exceptions + * related to it. + * + * @param {Component|Event} obj Component or event + */ + relateException(obj) { + if (this.isRecurrenceException()) { + throw new Error('cannot relate exception to exceptions'); + } + + if (obj instanceof Component) { + obj = new Event(obj); + } + + if (this.strictExceptions && obj.uid !== this.uid) { + throw new Error('attempted to relate unrelated exception'); + } + + let id = obj.recurrenceId.toString(); + + // we don't sort or manage exceptions directly + // here the recurrence expander handles that. + this.exceptions[id] = obj; + + // index RANGE=THISANDFUTURE exceptions so we can + // look them up later in getOccurrenceDetails. + if (obj.modifiesFuture()) { + let item = [ + obj.recurrenceId.toUnixTime(), id + ]; + + // we keep them sorted so we can find the nearest + // value later on... + let idx = binsearchInsert( + this.rangeExceptions, + item, + compareRangeException + ); + + this.rangeExceptions.splice(idx, 0, item); + } + } + + /** + * Checks if this record is an exception and has the RANGE=THISANDFUTURE + * value. + * + * @return {Boolean} True, when exception is within range + */ + modifiesFuture() { + if (!this.component.hasProperty('recurrence-id')) { + return false; + } + + let range = this.component.getFirstProperty('recurrence-id').getParameter('range'); + return range === Event.THISANDFUTURE; + } + + /** + * Finds the range exception nearest to the given date. + * + * @param {Time} time usually an occurrence time of an event + * @return {?Event} the related event/exception or null + */ + findRangeException(time) { + if (!this.rangeExceptions.length) { + return null; + } + + let utc = time.toUnixTime(); + let idx = binsearchInsert( + this.rangeExceptions, + [utc], + compareRangeException + ); + + idx -= 1; + + // occurs before + if (idx < 0) { + return null; + } + + let rangeItem = this.rangeExceptions[idx]; + + /* c8 ignore next 4 */ + if (utc < rangeItem[0]) { + // sanity check only + return null; + } + + return rangeItem[1]; + } + + /** + * Returns the occurrence details based on its start time. If the + * occurrence has an exception will return the details for that exception. + * + * NOTE: this method is intend to be used in conjunction + * with the {@link ICAL.Event#iterator iterator} method. + * + * @param {Time} occurrence time occurrence + * @return {occurrenceDetails} Information about the occurrence + */ + getOccurrenceDetails(occurrence) { + let id = occurrence.toString(); + let utcId = occurrence.convertToZone(Timezone.utcTimezone).toString(); + let item; + let result = { + //XXX: Clone? + recurrenceId: occurrence + }; + + if (id in this.exceptions) { + item = result.item = this.exceptions[id]; + result.startDate = item.startDate; + result.endDate = item.endDate; + result.item = item; + } else if (utcId in this.exceptions) { + item = this.exceptions[utcId]; + result.startDate = item.startDate; + result.endDate = item.endDate; + result.item = item; + } else { + // range exceptions (RANGE=THISANDFUTURE) have a + // lower priority then direct exceptions but + // must be accounted for first. Their item is + // always the first exception with the range prop. + let rangeExceptionId = this.findRangeException( + occurrence + ); + let end; + + if (rangeExceptionId) { + let exception = this.exceptions[rangeExceptionId]; + + // range exception must modify standard time + // by the difference (if any) in start/end times. + result.item = exception; + + let startDiff = this._rangeExceptionCache[rangeExceptionId]; + + if (!startDiff) { + let original = exception.recurrenceId.clone(); + let newStart = exception.startDate.clone(); + + // zones must be same otherwise subtract may be incorrect. + original.zone = newStart.zone; + startDiff = newStart.subtractDate(original); + + this._rangeExceptionCache[rangeExceptionId] = startDiff; + } + + let start = occurrence.clone(); + start.zone = exception.startDate.zone; + start.addDuration(startDiff); + + end = start.clone(); + end.addDuration(exception.duration); + + result.startDate = start; + result.endDate = end; + } else { + // no range exception standard expansion + end = occurrence.clone(); + end.addDuration(this.duration); + + result.endDate = end; + result.startDate = occurrence; + result.item = this; + } + } + + return result; + } + + /** + * Builds a recur expansion instance for a specific point in time (defaults + * to startDate). + * + * @param {Time=} startTime Starting point for expansion + * @return {RecurExpansion} Expansion object + */ + iterator(startTime) { + return new RecurExpansion({ + component: this.component, + dtstart: startTime || this.startDate + }); + } + + /** + * Checks if the event is recurring + * + * @return {Boolean} True, if event is recurring + */ + isRecurring() { + let comp = this.component; + return comp.hasProperty('rrule') || comp.hasProperty('rdate'); + } + + /** + * Checks if the event describes a recurrence exception. See + * {@tutorial terminology} for details. + * + * @return {Boolean} True, if the event describes a recurrence exception + */ + isRecurrenceException() { + return this.component.hasProperty('recurrence-id'); + } + + /** + * Returns the types of recurrences this event may have. + * + * Returned as an object with the following possible keys: + * + * - YEARLY + * - MONTHLY + * - WEEKLY + * - DAILY + * - MINUTELY + * - SECONDLY + * + * @return {Object.} + * Object of recurrence flags + */ + getRecurrenceTypes() { + let rules = this.component.getAllProperties('rrule'); + let i = 0; + let len = rules.length; + let result = Object.create(null); + + for (; i < len; i++) { + let value = rules[i].getFirstValue(); + result[value.freq] = true; + } + + return result; + } + + /** + * The uid of this event + * @type {String} + */ + get uid() { + return this._firstProp('uid'); + } + + set uid(value) { + this._setProp('uid', value); + } + + /** + * The start date + * @type {Time} + */ + get startDate() { + return this._firstProp('dtstart'); + } + + set startDate(value) { + this._setTime('dtstart', value); + } + + /** + * The end date. This can be the result directly from the property, or the + * end date calculated from start date and duration. Setting the property + * will remove any duration properties. + * @type {Time} + */ + get endDate() { + let endDate = this._firstProp('dtend'); + if (!endDate) { + let duration = this._firstProp('duration'); + endDate = this.startDate.clone(); + if (duration) { + endDate.addDuration(duration); + } else if (endDate.isDate) { + endDate.day += 1; + } + } + return endDate; + } + + set endDate(value) { + if (this.component.hasProperty('duration')) { + this.component.removeProperty('duration'); + } + this._setTime('dtend', value); + } + + /** + * The duration. This can be the result directly from the property, or the + * duration calculated from start date and end date. Setting the property + * will remove any `dtend` properties. + * @type {Duration} + */ + get duration() { + let duration = this._firstProp('duration'); + if (!duration) { + return this.endDate.subtractDateTz(this.startDate); + } + return duration; + } + + set duration(value) { + if (this.component.hasProperty('dtend')) { + this.component.removeProperty('dtend'); + } + + this._setProp('duration', value); + } + + /** + * The location of the event. + * @type {String} + */ + get location() { + return this._firstProp('location'); + } + + set location(value) { + this._setProp('location', value); + } + + /** + * The attendees in the event + * @type {Property[]} + */ + get attendees() { + //XXX: This is way lame we should have a better + // data structure for this later. + return this.component.getAllProperties('attendee'); + } + + /** + * The event summary + * @type {String} + */ + get summary() { + return this._firstProp('summary'); + } + + set summary(value) { + this._setProp('summary', value); + } + + /** + * The event description. + * @type {String} + */ + get description() { + return this._firstProp('description'); + } + + set description(value) { + this._setProp('description', value); + } + + /** + * The event color from [rfc7986](https://datatracker.ietf.org/doc/html/rfc7986) + * @type {String} + */ + get color() { + return this._firstProp('color'); + } + + set color(value) { + this._setProp('color', value); + } + + /** + * The organizer value as an uri. In most cases this is a mailto: uri, but + * it can also be something else, like urn:uuid:... + * @type {String} + */ + get organizer() { + return this._firstProp('organizer'); + } + + set organizer(value) { + this._setProp('organizer', value); + } + + /** + * The sequence value for this event. Used for scheduling + * see {@tutorial terminology}. + * @type {Number} + */ + get sequence() { + return this._firstProp('sequence'); + } + + set sequence(value) { + this._setProp('sequence', value); + } + + /** + * The recurrence id for this event. See {@tutorial terminology} for details. + * @type {Time} + */ + get recurrenceId() { + return this._firstProp('recurrence-id'); + } + + set recurrenceId(value) { + this._setTime('recurrence-id', value); + } + + /** + * Set/update a time property's value. + * This will also update the TZID of the property. + * + * TODO: this method handles the case where we are switching + * from a known timezone to an implied timezone (one without TZID). + * This does _not_ handle the case of moving between a known + * (by TimezoneService) timezone to an unknown timezone... + * + * We will not add/remove/update the VTIMEZONE subcomponents + * leading to invalid ICAL data... + * @private + * @param {String} propName The property name + * @param {Time} time The time to set + */ + _setTime(propName, time) { + let prop = this.component.getFirstProperty(propName); + + if (!prop) { + prop = new Property(propName); + this.component.addProperty(prop); + } + + // utc and local don't get a tzid + if ( + time.zone === Timezone.localTimezone || + time.zone === Timezone.utcTimezone + ) { + // remove the tzid + prop.removeParameter('tzid'); + } else { + prop.setParameter('tzid', time.zone.tzid); + } + + prop.setValue(time); + } + + _setProp(name, value) { + this.component.updatePropertyWithValue(name, value); + } + + _firstProp(name) { + return this.component.getFirstPropertyValue(name); + } + + /** + * The string representation of this event. + * @return {String} + */ + toString() { + return this.component.toString(); + } +} + +function compareRangeException(a, b) { + if (a[0] > b[0]) return 1; + if (b[0] > a[0]) return -1; + return 0; +} + +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * Portions Copyright (C) Philipp Kewisch */ + +/** + * The ComponentParser is used to process a String or jCal Object, + * firing callbacks for various found components, as well as completion. + * + * @example + * var options = { + * // when false no events will be emitted for type + * parseEvent: true, + * parseTimezone: true + * }; + * + * var parser = new ICAL.ComponentParser(options); + * + * parser.onevent(eventComponent) { + * //... + * } + * + * // ontimezone, etc... + * + * parser.oncomplete = function() { + * + * }; + * + * parser.process(stringOrComponent); + * + * @memberof ICAL + */ +class ComponentParser { + /** + * Creates a new ICAL.ComponentParser instance. + * + * @param {Object=} options Component parser options + * @param {Boolean} options.parseEvent Whether events should be parsed + * @param {Boolean} options.parseTimezeone Whether timezones should be parsed + */ + constructor(options) { + if (typeof(options) === 'undefined') { + options = {}; + } + + for (let [key, value] of Object.entries(options)) { + this[key] = value; + } + } + + /** + * When true, parse events + * + * @type {Boolean} + */ + parseEvent = true; + + /** + * When true, parse timezones + * + * @type {Boolean} + */ + parseTimezone = true; + + + /* SAX like events here for reference */ + + /** + * Fired when parsing is complete + * @callback + */ + oncomplete = /* c8 ignore next */ function() {}; + + /** + * Fired if an error occurs during parsing. + * + * @callback + * @param {Error} err details of error + */ + onerror = /* c8 ignore next */ function(err) {}; + + /** + * Fired when a top level component (VTIMEZONE) is found + * + * @callback + * @param {Timezone} component Timezone object + */ + ontimezone = /* c8 ignore next */ function(component) {}; + + /** + * Fired when a top level component (VEVENT) is found. + * + * @callback + * @param {Event} component Top level component + */ + onevent = /* c8 ignore next */ function(component) {}; + + /** + * Process a string or parse ical object. This function itself will return + * nothing but will start the parsing process. + * + * Events must be registered prior to calling this method. + * + * @param {Component|String|Object} ical The component to process, + * either in its final form, as a jCal Object, or string representation + */ + process(ical) { + //TODO: this is sync now in the future we will have a incremental parser. + if (typeof(ical) === 'string') { + ical = parse(ical); + } + + if (!(ical instanceof Component)) { + ical = new Component(ical); + } + + let components = ical.getAllSubcomponents(); + let i = 0; + let len = components.length; + let component; + + for (; i < len; i++) { + component = components[i]; + + switch (component.name) { + case 'vtimezone': + if (this.parseTimezone) { + let tzid = component.getFirstPropertyValue('tzid'); + if (tzid) { + this.ontimezone(new Timezone({ + tzid: tzid, + component: component + })); + } + } + break; + case 'vevent': + if (this.parseEvent) { + this.onevent(new Event(component)); + } + break; + default: + continue; + } + } + + //XXX: ideally we should do a "nextTick" here + // so in all cases this is actually async. + this.oncomplete(); + } +} + +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * Portions Copyright (C) Philipp Kewisch */ + +/** + * The main ICAL module. Provides access to everything else. + * + * @alias ICAL + * @namespace ICAL + * @property {ICAL.design} design + * @property {ICAL.helpers} helpers + */ +var ICALmodule = { + /** + * The number of characters before iCalendar line folding should occur + * @type {Number} + * @default 75 + */ + foldLength: 75, + + debug: false, + + /** + * The character(s) to be used for a newline. The default value is provided by + * rfc5545. + * @type {String} + * @default "\r\n" + */ + newLineChar: '\r\n', + + Binary, + Component, + ComponentParser, + Duration, + Event, + Period, + Property, + Recur, + RecurExpansion, + RecurIterator, + Time, + Timezone, + TimezoneService, + UtcOffset, + VCardTime, + + parse, + stringify, + + design: design$1, + helpers +}; + +return ICALmodule; + +})(); diff --git a/plugins/ics-viewer/index.php b/plugins/ics-viewer/index.php new file mode 100644 index 000000000..4100593b2 --- /dev/null +++ b/plugins/ics-viewer/index.php @@ -0,0 +1,22 @@ +UseLangs(true); + $this->addJs('message.js'); + $this->addJs('windowsZones.js'); + // Load https://github.com/kewisch/ical.js/releases + $this->addJs('ical.js'); + } +} diff --git a/plugins/ics-viewer/message.js b/plugins/ics-viewer/message.js new file mode 100644 index 000000000..b0adc469d --- /dev/null +++ b/plugins/ics-viewer/message.js @@ -0,0 +1,143 @@ +(rl => { + const templateId = 'MailMessageView'; + + addEventListener('rl-view-model.create', e => { + if (templateId === e.detail.viewModelTemplateID) { + + const + template = document.getElementById(templateId), + view = e.detail, + attachmentsPlace = template.content.querySelector('.attachmentsPlace'), + dateRegEx = /(TZID=(?[^:]+):)?(?[0-9]{4})(?[0-9]{2})(?[0-9]{2})T(?[0-9]{2})(?[0-9]{2})(?[0-9]{2})(?Z?)/, + parseDate = str => { + let parts = dateRegEx.exec(str)?.groups, + options = {dateStyle: 'long', timeStyle: 'short'}, + date = (parts ? new Date( + parseInt(parts.year, 10), + parseInt(parts.month, 10) - 1, + parseInt(parts.day, 10), + parseInt(parts.hour, 10), + parseInt(parts.minute, 10), + parseInt(parts.second, 10) + ) : new Date(str)); + parts?.tz && (options.timeZone = windowsVTIMEZONEs[parts.tz] || parts.tz); + try { + return date.format(options); + } catch (e) { + console.error(e); + if (options.timeZone) { + options.timeZone = undefined; + return date.format(options); + } + } + }; + + attachmentsPlace.after(Element.fromHTML(` +
+ + + + + + + + + +
Organizer:
Start:
End:
Location:
Attendees:
+
`)); + + view.ICSViewer = ko.observable(null); + + view.saveICS = () => { + let VEVENT = view.VEVENT(); + if (VEVENT) { + if (rl.nextcloud && VEVENT.rawText) { + rl.nextcloud.selectCalendar() + .then(href => href && rl.nextcloud.calendarPut(href, VEVENT)); + } else { + // TODO + } + } + } + + /** + * TODO + */ + view.message.subscribe(msg => { + view.ICSViewer(null); + if (msg) { + // JSON-LD after parsing HTML + // See http://schema.org/ + msg.linkedData.subscribe(data => { + if (!view.ICSViewer()) { + data.forEach(item => { + if (item["ical:summary"]) { + let VEVENT = { + SUMMARY: item["ical:summary"], + DTSTART: parseDate(item["ical:dtstart"]), +// DTEND: parseDate(item["ical:dtend"]), +// TRANSP: item["ical:transp"], +// LOCATION: item["ical:location"], + ATTENDEE: [] + } + view.ICSViewer(VEVENT); + return; + } + }); + } + }); + // ICS attachment. + // attachments is a ko.observableArray, so it must be + // unwrapped before array methods are used on it. + // A scheduling mail does not always carry a text/calendar + // attachment either: the part is often inline inside + // multipart/alternative and repeated as application/ics. + let ics = (msg.attachments() || []).find(attachment => + 'text/calendar' == attachment.mimeType + || 'application/ics' == attachment.mimeType + || 'text/x-vcalendar' == attachment.mimeType + || /\.ics$/i.test(attachment.fileName || '')); + if (ics && ics.download) { + + // fetch it and parse the VEVENT + rl.fetch(ics.linkDownload()) + .then(response => (response.status < 400) ? response.text() : Promise.reject(new Error({ response }))) + .then(text => { + let jcalData = ICAL.parse(text) + var comp = new ICAL.Component(jcalData); + var vevent = comp.getFirstSubcomponent("vevent"); + var event = new ICAL.Event(vevent); + let VEVENT = {}; + if (event.organizer && event.organizer.startsWith("mailto:")) { + VEVENT.ORGANIZER_TXT = event.organizer.substr(7) + VEVENT.ORGANIZER_MAIL = event.organizer + } else + VEVENT.ORGANIZER_TXT = event.organizer + VEVENT.SUMMARY = event.summary; + VEVENT.DTSTART = parseDate(vevent.getFirstPropertyValue("dtstart")); + VEVENT.DTEND = parseDate(vevent.getFirstPropertyValue("dtend")); + VEVENT.LOCATION = event.location; + VEVENT.ATTENDEE = [] + for (let attendee of event.attendees) { + VEVENT.ATTENDEE.push(attendee.getFirstParameter("cn")); + } + + if (VEVENT) { + VEVENT.rawText = text; + VEVENT.isCancelled = () => VEVENT.STATUS?.includes('CANCELLED'); + VEVENT.isConfirmed = () => VEVENT.STATUS?.includes('CONFIRMED'); + VEVENT.shouldReply = () => VEVENT.METHOD?.includes('REPLY'); + console.dir({ + isCancelled: VEVENT.isCancelled(), + shouldReply: VEVENT.shouldReply() + }); + view.ICSViewer(VEVENT); + } + }); + } + } + }); + } + }); + +})(window.rl); diff --git a/plugins/ics-viewer/style.css b/plugins/ics-viewer/style.css new file mode 100644 index 000000000..b3a4e5c8c --- /dev/null +++ b/plugins/ics-viewer/style.css @@ -0,0 +1,44 @@ + +/** + * .SML-@type where @type is the value of the JSON-LD "@type": + * See http://schema.org/ + */ + +.SML-FlightReservation { +} + + .SML-Airline { + } + + .SML-Airport { + } + + .SML-Flight { + } + +.SML-FoodEstablishmentReservation { +} + + .SML-FoodEstablishment { + } + +.SML-ParcelDelivery { +} + + .SML-Order { + } + + .SML-Organization { + } + + .SML-Product { + } + + .SML-PostalAddress { + } + +.SML-Person { +} + +.SML-PromotionCard { +} diff --git a/plugins/ics-viewer/windowsZones.js b/plugins/ics-viewer/windowsZones.js new file mode 100644 index 000000000..1c2c915c3 --- /dev/null +++ b/plugins/ics-viewer/windowsZones.js @@ -0,0 +1,738 @@ +// Windows timezones (Subset from https://github.com/unicode-cldr/cldr-core/blob/master/supplemental/windowsZones.json) +const windowsVTIMEZONEs = { + "_unicodeVersion": "13.0.0", + "_cldrVersion": "37", + // Windows : [IANA...] + "Afghanistan Standard Time": [ + "Asia/Kabul" + ], + "Alaskan Standard Time": [ + "America/Anchorage"/*, + "America/Juneau", + "America/Metlakatla", + "America/Nome", + "America/Sitka", + "America/Yakutat"*/ + ], + "Aleutian Standard Time": [ + "America/Adak" + ], + "Altai Standard Time": [ + "Asia/Barnaul" + ], + "Arab Standard Time": [ + "Asia/Aden"/*, + "Asia/Bahrain", + "Asia/Kuwait", + "Asia/Qatar", + "Asia/Riyadh" + */], + "Arabian Standard Time": [ + "Asia/Dubai"/*, + "Asia/Muscat", + "Etc/GMT-4" + */], + "Arabic Standard Time": [ + "Asia/Baghdad" + ], + "Argentina Standard Time": [ + "America/Argentina/La_Rioja"/*, + "America/Argentina/Rio_Gallegos", + "America/Argentina/Salta", + "America/Argentina/San_Juan", + "America/Argentina/San_Luis", + "America/Argentina/Tucuman", + "America/Argentina/Ushuaia", + "America/Buenos_Aires", + "America/Catamarca", + "America/Cordoba", + "America/Jujuy", + "America/Mendoza" + */], + "Astrakhan Standard Time": [ + "Europe/Astrakhan"/*, + "Europe/Ulyanovsk" + */], + "Atlantic Standard Time": [ + "America/Glace_Bay"/*, + "America/Goose_Bay", + "America/Halifax", + "America/Moncton", + "America/Thule", + "Atlantic/Bermuda" + */], + "AUS Central Standard Time": [ + "Australia/Darwin" + ], + "Aus Central W. Standard Time": [ + "Australia/Eucla" + ], + "AUS Eastern Standard Time": [ + "Australia/Melbourne"/*, + "Australia/Sydney" + */], + "Azerbaijan Standard Time": [ + "Asia/Baku" + ], + "Azores Standard Time": [ + "America/Scoresbysund"/*, + "Atlantic/Azores" + */], + "Bahia Standard Time": [ + "America/Bahia" + ], + "Bangladesh Standard Time": [ + "Asia/Dhaka"/*, + "Asia/Thimphu" + */], + "Belarus Standard Time": [ + "Europe/Minsk" + ], + "Bougainville Standard Time": [ + "Pacific/Bougainville" + ], + "Canada Central Standard Time": [ + "America/Regina"/*, + "America/Swift_Current" + */], + "Cape Verde Standard Time": [ + "Atlantic/Cape_Verde"/*, + "Etc/GMT+1" + */], + "Caucasus Standard Time": [ + "Asia/Yerevan" + ], + "Cen. Australia Standard Time": [ + "Australia/Adelaide"/*, + "Australia/Broken_Hill" + */], + "Central America Standard Time": [ + "America/Belize"/*, + "America/Costa_Rica", + "America/El_Salvador", + "America/Guatemala", + "America/Managua", + "America/Tegucigalpa", + "Pacific/Galapagos", + "Etc/GMT+6" + */], + "Central Asia Standard Time": [ + "Asia/Almaty"/*, + "Asia/Bishkek", + "Asia/Qostanay", + "Asia/Urumqi", + "Indian/Chagos", + "Antarctica/Vostok", + "Etc/GMT-6" + */], + "Central Brazilian Standard Time": [ + "America/Campo_Grande"/*, + "America/Cuiaba" + */], + "Central Europe Standard Time": [ + "Europe/Belgrade"/*, + "Europe/Bratislava", + "Europe/Budapest", + "Europe/Ljubljana", + "Europe/Podgorica", + "Europe/Prague", + "Europe/Tirane" + */], + "Central European Standard Time": [ + "Europe/Sarajevo"/*, + "Europe/Skopje", + "Europe/Warsaw", + "Europe/Zagreb" + */], + "Central Pacific Standard Time": [ + "Pacific/Efate"/*, + "Pacific/Guadalcanal", + "Pacific/Noumea", + "Pacific/Ponape Pacific/Kosrae", + "Antarctica/Macquarie", + "Etc/GMT-11" + */], + "Central Standard Time": [ + "America/Chicago"/*, + "America/Indiana/Knox", + "America/Indiana/Tell_City", + "America/Matamoros", + "America/Menominee", + "America/North_Dakota/Beulah", + "America/North_Dakota/Center", + "America/North_Dakota/New_Salem", + "America/Rainy_River", + "America/Rankin_Inlet", + "America/Resolute", + "America/Winnipeg", + "CST6CDT" + */], + "Central Standard Time (Mexico)": [ + "America/Bahia_Banderas"/*, + "America/Merida", + "America/Mexico_City", + "America/Monterrey" + */], + "Chatham Islands Standard Time": [ + "Pacific/Chatham" + ], + "China Standard Time": [ + "Asia/Hong_Kong"/*, + "Asia/Macau", + "Asia/Shanghai" + */], + "Cuba Standard Time": [ + "America/Havana" + ], + "Dateline Standard Time": [ + "Etc/GMT+12" + ], + "E. Africa Standard Time": [ + "Africa/Addis_Ababa"/*, + "Africa/Asmera", + "Africa/Dar_es_Salaam", + "Africa/Djibouti", + "Africa/Juba", + "Africa/Kampala", + "Africa/Mogadishu", + "Africa/Nairobi", + "Indian/Antananarivo", + "Indian/Comoro", + "Indian/Mayotte", + "Antarctica/Syowa", + "Etc/GMT-3" + */], + "E. Australia Standard Time": [ + "Australia/Brisbane"/*, + "Australia/Lindeman" + */], + "E. Europe Standard Time": [ + "Europe/Chisinau" + ], + "E. South America Standard Time": [ + "America/Sao_Paulo" + ], + "Easter Island Standard Time": [ + "Pacific/Easter" + ], + "Eastern Standard Time": [ + "America/Detroit"/*, + "America/Indiana/Petersburg", + "America/Indiana/Vincennes", + "America/Indiana/Winamac", + "America/Iqaluit", + "America/Kentucky/Monticello", + "America/Louisville", + "America/Montreal", + "America/Nassau", + "America/New_York", + "America/Nipigon", + "America/Pangnirtung", + "America/Thunder_Bay", + "America/Toronto", + "EST5EDT" + */], + "Eastern Standard Time (Mexico)": [ + "America/Cancun" + ], + "Egypt Standard Time": [ + "Africa/Cairo" + ], + "Ekaterinburg Standard Time": [ + "Asia/Yekaterinburg" + ], + "Fiji Standard Time": [ + "Pacific/Fiji" + ], + "FLE Standard Time": [ + "Europe/Helsinki"/*, + "Europe/Kiev", + "Europe/Mariehamn", + "Europe/Riga", + "Europe/Sofia", + "Europe/Tallinn", + "Europe/Uzhgorod", + "Europe/Vilnius", + "Europe/Zaporozhye" + */], + "Georgian Standard Time": [ + "Asia/Tbilisi" + ], + "GMT Standard Time": [ + "Atlantic/Canary"/*, + "Atlantic/Faeroe", + "Atlantic/Madeira", + "Europe/Dublin", + "Europe/Guernsey", + "Europe/Isle_of_Man", + "Europe/Jersey", + "Europe/Lisbon", + "Europe/London" + */], + "Greenland Standard Time": [ + "America/Godthab" + ], + "Greenwich Standard Time": [ + "Africa/Abidjan"/*, + "Africa/Accra", + "Africa/Bamako", + "Africa/Banjul", + "Africa/Bissau", + "Africa/Conakry", + "Africa/Dakar", + "Africa/Freetown", + "Africa/Lome", + "Africa/Monrovia", + "Africa/Nouakchott", + "Africa/Ouagadougou", + "Atlantic/Reykjavik", + "Atlantic/St_Helena" + */], + "GTB Standard Time": [ + "Asia/Nicosia"/*, + "Asia/Famagusta", + "Europe/Athens", + "Europe/Bucharest" + */], + "Haiti Standard Time": [ + "America/Port-au-Prince" + ], + "Hawaiian Standard Time": [ + "Pacific/Honolulu"/*, + "Pacific/Johnston", + "Pacific/Rarotonga", + "Pacific/Tahiti", + "Etc/GMT+10" + */], + "India Standard Time": [ + "Asia/Calcutta" + ], + "Iran Standard Time": [ + "Asia/Tehran" + ], + "Israel Standard Time": [ + "Asia/Jerusalem" + ], + "Jordan Standard Time": [ + "Asia/Amman" + ], + "Kaliningrad Standard Time": [ + "Europe/Kaliningrad" + ], + "Korea Standard Time": [ + "Asia/Seoul" + ], + "Libya Standard Time": [ + "Africa/Tripoli" + ], + "Line Islands Standard Time": [ + "Pacific/Kiritimati"/*, + "Etc/GMT-14" + */], + "Lord Howe Standard Time": [ + "Australia/Lord_Howe" + ], + "Magadan Standard Time": [ + "Asia/Magadan" + ], + "Magallanes Standard Time": [ + "America/Punta_Arenas" + ], + "Marquesas Standard Time": [ + "Pacific/Marquesas" + ], + "Mauritius Standard Time": [ + "Indian/Mauritius"/*, + "Indian/Mahe", + "Indian/Reunion" + */], + "Middle East Standard Time": [ + "Asia/Beirut" + ], + "Montevideo Standard Time": [ + "America/Montevideo" + ], + "Morocco Standard Time": [ + "Africa/Casablanca"/*, + "Africa/El_Aaiun" + */], + "Mountain Standard Time": [ + "America/Boise"/*, + "America/Cambridge_Bay", + "America/Denver", + "America/Edmonton", + "America/Inuvik", + "America/Ojinaga", + "America/Yellowknife", + "MST7MDT" + */], + "Mountain Standard Time (Mexico)": [ + "America/Chihuahua"/*, + "America/Mazatlan" + */], + "Myanmar Standard Time": [ + "Asia/Rangoon"/*, + "Indian/Cocos" + */], + "N. Central Asia Standard Time": [ + "Asia/Novosibirsk" + ], + "Namibia Standard Time": [ + "Africa/Windhoek" + ], + "Nepal Standard Time": [ + "Asia/Katmandu" + ], + "New Zealand Standard Time": [ + "Pacific/Auckland"/*, + "Antarctica/McMurdo" + */], + "Newfoundland Standard Time": [ + "America/St_Johns" + ], + "Norfolk Standard Time": [ + "Pacific/Norfolk" + ], + "North Asia East Standard Time": [ + "Asia/Irkutsk" + ], + "North Asia Standard Time": [ + "Asia/Krasnoyarsk"/*, + "Asia/Novokuznetsk" + */], + "North Korea Standard Time": [ + "Asia/Pyongyang" + ], + "Omsk Standard Time": [ + "Asia/Omsk" + ], + "Pacific SA Standard Time": [ + "America/Santiago" + ], + "Pacific Standard Time": [ + "America/Los_Angeles"/*, + "America/Dawson", + "America/Vancouver", + "America/Whitehorse", + "PST8PDT" + */], + "Pacific Standard Time (Mexico)": [ + "America/Tijuana"/*, + "America/Santa_Isabel" + */], + "Pakistan Standard Time": [ + "Asia/Karachi" + ], + "Paraguay Standard Time": [ + "America/Asuncion" + ], + "Qyzylorda Standard Time": [ + "Asia/Qyzylorda" + ], + "Romance Standard Time": [ + "Europe/Paris"/*, + "Europe/Brussels", + "Europe/Copenhagen", + "Europe/Madrid", + "Africa/Ceuta" + */], + "Russia Time Zone 3": [ + "Europe/Samara" + ], + "Russia Time Zone 10": [ + "Asia/Srednekolymsk" + ], + "Russia Time Zone 11": [ + "Asia/Kamchatka"/*, + "Asia/Anadyr" + */], + "Russian Standard Time": [ + "Europe/Moscow"/*, + "Europe/Kirov", + "Europe/Simferopol" + */], + "SA Eastern Standard Time": [ + "America/Belem"/*, + "America/Cayenne", + "America/Fortaleza", + "America/Maceio", + "America/Paramaribo", + "America/Recife", + "America/Santarem", + "Atlantic/Stanley", + "Antarctica/Palmer", + "Antarctica/Rothera", + "Etc/GMT+3" + */], + "SA Pacific Standard Time": [ + "America/Bogota"/*, + "America/Cayman", + "America/Coral_Harbour", + "America/Eirunepe", + "America/Guayaquil", + "America/Jamaica", + "America/Lima", + "America/Panama", + "America/Rio_Branco", + "Etc/GMT+5" + */], + "SA Western Standard Time": [ + "America/Anguilla"/*, + "America/Antigua", + "America/Aruba", + "America/Barbados", + "America/Blanc-Sablon", + "America/Boa_Vista", + "America/Curacao", + "America/Dominica", + "America/Grenada", + "America/Guadeloupe", + "America/Guyana", + "America/Kralendijk", + "America/La_Paz", + "America/Lower_Princes", + "America/Manaus", + "America/Marigot", + "America/Martinique", + "America/Montserrat", + "America/Port_of_Spain", + "America/Porto_Velho", + "America/Puerto_Rico", + "America/Santo_Domingo", + "America/St_Barthelemy", + "America/St_Kitts", + "America/St_Lucia", + "America/St_Thomas", + "America/St_Vincent", + "America/Tortola", + "Etc/GMT+4" + */], + "Saint Pierre Standard Time": [ + "America/Miquelon" + ], + "Sakhalin Standard Time": [ + "Asia/Sakhalin" + ], + "Samoa Standard Time": [ + "Pacific/Apia" + ], + "Sao Tome Standard Time": [ + "Africa/Sao_Tome" + ], + "Saratov Standard Time": [ + "Europe/Saratov" + ], + "SE Asia Standard Time": [ + "Asia/Bangkok"/*, + "Asia/Jakarta", + "Asia/Phnom_Penh", + "Asia/Pontianak", + "Asia/Saigon", + "Asia/Vientiane", + "Indian/Christmas", + "Antarctica/Davis", + "Etc/GMT-7" + */], + "Singapore Standard Time": [ + "Asia/Singapore"/*, + "Asia/Brunei", + "Asia/Kuala_Lumpur", + "Asia/Kuching", + "Asia/Makassar", + "Asia/Manila", + "Antarctica/Casey", + "Etc/GMT-8" + */], + "South Africa Standard Time": [ + "Africa/Johannesburg"/*, + "Africa/Blantyre", + "Africa/Bujumbura", + "Africa/Gaborone", + "Africa/Harare", + "Africa/Kigali", + "Africa/Lubumbashi", + "Africa/Lusaka", + "Africa/Maputo", + "Africa/Maseru", + "Africa/Mbabane", + "Etc/GMT-2" + */], + "Sri Lanka Standard Time": [ + "Asia/Colombo" + ], + "Sudan Standard Time": [ + "Africa/Khartoum" + ], + "Syria Standard Time": [ + "Asia/Damascus" + ], + "Taipei Standard Time": [ + "Asia/Taipei" + ], + "Tasmania Standard Time": [ + "Australia/Currie"/*, + "Australia/Hobart" + */], + "Tocantins Standard Time": [ + "America/Araguaina" + ], + "Tokyo Standard Time": [ + "Asia/Tokyo"/*, + "Asia/Dili", + "Asia/Jayapura", + "Pacific/Palau", + "Etc/GMT-9" + */], + "Tomsk Standard Time": [ + "Asia/Tomsk" + ], + "Tonga Standard Time": [ + "Pacific/Tongatapu" + ], + "Transbaikal Standard Time": [ + "Asia/Chita" + ], + "Turkey Standard Time": [ + "Europe/Istanbul" + ], + "Turks And Caicos Standard Time": [ + "America/Grand_Turk" + ], + "Ulaanbaatar Standard Time": [ + "Asia/Ulaanbaatar"/*, + "Asia/Choibalsan" + */], + "US Eastern Standard Time": [ + "America/Indianapolis"/*, + "America/Indiana/Marengo", + "America/Indiana/Vevay" + */], + "US Mountain Standard Time": [ + "America/Phoenix"/*, + "America/Creston", + "America/Dawson_Creek", + "America/Fort_Nelson", + "America/Hermosillo", + "Etc/GMT+7" + */], + "UTC": [ + "Etc/GMT"/*, + "America/Danmarkshavn", + "Etc/UTC" + */], + "UTC-02": [ + "Etc/GMT+2"/*, + "America/Noronha", + "Atlantic/South_Georgia" + */], + "UTC-08": [ + "Etc/GMT+8"/*, + "Pacific/Pitcairn" + */], + "UTC-09": [ + "Etc/GMT+9"/*, + "Pacific/Gambier" + */], + "UTC-11": [ + "Etc/GMT+11"/*, + "Pacific/Midway", + "Pacific/Niue", + "Pacific/Pago_Pago" + */], + "UTC+12": [ + "Etc/GMT-12"/*, + "Pacific/Funafuti", + "Pacific/Kwajalein", + "Pacific/Majuro", + "Pacific/Nauru", + "Pacific/Tarawa", + "Pacific/Wake", + "Pacific/Wallis" + */], + "UTC+13": [ + "Etc/GMT-13"/*, + "Pacific/Enderbury", + "Pacific/Fakaofo" + */], + "Venezuela Standard Time": [ + "America/Caracas" + ], + "Vladivostok Standard Time": [ + "Asia/Vladivostok"/*, + "Asia/Ust-Nera" + */], + "Volgograd Standard Time": [ + "Europe/Volgograd" + ], + "W. Australia Standard Time": [ + "Australia/Perth" + ], + "W. Central Africa Standard Time": [ + "Africa/Algiers"/*, + "Africa/Bangui", + "Africa/Brazzaville", + "Africa/Douala", + "Africa/Kinshasa", + "Africa/Lagos", + "Africa/Libreville", + "Africa/Luanda", + "Africa/Malabo", + "Africa/Ndjamena", + "Africa/Niamey", + "Africa/Porto-Novo", + "Africa/Tunis", + "Etc/GMT-1" + */], + "W. Europe Standard Time": [ + "Europe/Amsterdam"/*, + "Europe/Andorra", + "Europe/Berlin", + "Europe/Busingen", + "Europe/Gibraltar", + "Europe/Luxembourg", + "Europe/Malta", + "Europe/Monaco", + "Europe/Oslo", + "Europe/Rome", + "Europe/San_Marino", + "Europe/Stockholm", + "Europe/Vaduz", + "Europe/Vatican", + "Europe/Vienna", + "Europe/Zurich", + "Arctic/Longyearbyen" + */], + "W. Mongolia Standard Time": [ + "Asia/Hovd" + ], + "West Asia Standard Time": [ + "Asia/Aqtau"/*, + "Asia/Aqtobe", + "Asia/Ashgabat", + "Asia/Atyrau", + "Asia/Dushanbe", + "Asia/Oral", + "Asia/Samarkand", + "Asia/Tashkent", + "Indian/Kerguelen", + "Indian/Maldives", + "Antarctica/Mawson", + "Etc/GMT-5" + */], + "West Bank Standard Time": [ + "Asia/Gaza"/*, + "Asia/Hebron" + */], + "West Pacific Standard Time": [ + "Pacific/Guam"/*, + "Pacific/Port_Moresby", + "Pacific/Saipan", + "Pacific/Truk", + "Antarctica/DumontDUrville", + "Etc/GMT-10" + */], + "Yakutsk Standard Time": [ + "Asia/Khandyga"/*, + "Asia/Yakutsk" + */], +}; diff --git a/plugins/imap-contacts-suggestions/ImapContactsSuggestions.php b/plugins/imap-contacts-suggestions/ImapContactsSuggestions.php new file mode 100644 index 000000000..9a379ff26 --- /dev/null +++ b/plugins/imap-contacts-suggestions/ImapContactsSuggestions.php @@ -0,0 +1,44 @@ + \strlen($sQuery)) { + return []; + } + + $oActions = \RainLoop\Api::Actions(); + $oMailClient = $oActions->MailClient(); + if (!$oMailClient->IsLoggined()) { + $oAccount = $oActions->getAccountFromToken(); + $oAccount->ImapConnectAndLogin($oActions->Plugins(), $oMailClient->ImapClient(), $oActions->Config()); + } + $oImapClient = $oMailClient->ImapClient(); + + $oImapClient->FolderSelect($this->sFolderName); + + $sQuery = \MailSo\Imap\SearchCriterias::escapeSearchString($oImapClient, $sQuery); + $aUids = \array_slice( + $oImapClient->MessageSearch("FROM {$sQuery}"), + 0, $iLimit + ); + + $aResult = []; + if ($aUids) { + foreach ($oImapClient->Fetch(['BODY.PEEK[HEADER.FIELDS (FROM)]'], \implode(',', $aUids), true) as $oFetchResponse) { + $oHeaders = new \MailSo\Mime\HeaderCollection($oFetchResponse->GetHeaderFieldsValue()); + $oFrom = $oHeaders->GetAsEmailCollection(\MailSo\Mime\Enumerations\Header::FROM_, true); + foreach ($oFrom as $oMail) { + $aResult[] = [$oMail->GetEmail(), $oMail->GetDisplayName()]; + } + } + } + + return $aResult; + } +} diff --git a/plugins/imap-contacts-suggestions/LICENSE b/plugins/imap-contacts-suggestions/LICENSE new file mode 100644 index 000000000..4aed64b3a --- /dev/null +++ b/plugins/imap-contacts-suggestions/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2015 RainLoop Team + +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/plugins/imap-contacts-suggestions/index.php b/plugins/imap-contacts-suggestions/index.php new file mode 100644 index 000000000..559e77770 --- /dev/null +++ b/plugins/imap-contacts-suggestions/index.php @@ -0,0 +1,39 @@ +addHook('main.fabrica', 'MainFabrica'); + } + + public function Supported() : string + { + return ''; + } + + /** + * @param mixed $mResult + */ + public function MainFabrica(string $sName, &$mResult) + { + if ('suggestions' === $sName) { + if (!\is_array($mResult)) { + $mResult = array(); + } +// $sFolder = \trim($this->Config()->Get('plugin', 'mailbox', 'INBOX')); +// if ($sFolder) { + include_once __DIR__ . '/ImapContactsSuggestions.php'; + $mResult[] = new ImapContactsSuggestions(); +// } + } + } +} diff --git a/plugins/kolab/KolabAddressBook.php b/plugins/kolab/KolabAddressBook.php new file mode 100644 index 000000000..c934af1d7 --- /dev/null +++ b/plugins/kolab/KolabAddressBook.php @@ -0,0 +1,396 @@ +ImapClient()->FolderGetMetadata($sFolderName, [\MailSo\Imap\Enumerations\MetadataKeys::KOLAB_CTYPE]); + if (!$metadata || 'contact' !== \array_shift($metadata)) { + $sFolderName = ''; +// throw new \Exception("Invalid kolab contact folder: {$sFolderName}"); + } + + $this->sFolderName = $sFolderName; + } + + protected function MailClient() : \MailSo\Mail\MailClient + { + $oActions = \RainLoop\Api::Actions(); + $oMailClient = $oActions->MailClient(); + if (!$oMailClient->IsLoggined()) { + $oActions->getAccountFromToken()->ImapConnectAndLogin($oActions->Plugins(), $oMailClient->ImapClient(), $oActions->Config()); + } + return $oMailClient; + } + + protected function ImapClient() : \MailSo\Imap\ImapClient + { + if (!$this->oImapClient) { + $this->oImapClient = $this->MailClient()->ImapClient(); + } + return $this->oImapClient; + } + + protected function SelectFolder() : bool + { + $sFolderName = $this->sFolderName; + if ($sFolderName) { + try { + $this->ImapClient()->FolderSelect($sFolderName); + return true; + } catch (\Throwable $e) { + \trigger_error("KolabAddressBook {$sFolderName} error: {$e->getMessage()}"); + } + } + return false; + } + + protected function fetchXCardFromMessage(\MailSo\Mail\Message $oMessage) : ?VCard + { + $xCard = null; + try { + foreach ($oMessage->Attachments() ?: [] as $oAttachment) { + if ('application/vcard+xml' === $oAttachment->ContentType()) { + $result = $this->MailClient()->MessageMimeStream(function ($rResource) use (&$xCard) { + if (\is_resource($rResource)) { + $xCard = \Sabre\VObject\Reader::readXML($rResource); + } + }, $this->sFolderName, $oMessage->Uid(), $oAttachment->PartID()); + break; + } + } + } catch (\Throwable $e) { + \error_log("KolabAddressBook message {$oMessage->Uid()} error: {$e->getMessage()}"); + } + return $xCard; + } + + protected function MessageAsContact(\MailSo\Mail\Message $oMessage) : Contact + { + $oContact = new Contact; + $oContact->id = $oMessage->Uid(); + $oContact->Changed = $oMessage->HeaderTimeStampInUTC(); + + // Fetch xCard attachment and populate $oContact with it + $xCard = $this->fetchXCardFromMessage($oMessage); + if ($xCard) { + $oContact->setVCard($xCard); + } + + // Reset, else it is 'urn:uuid:01234567-89AB-CDEF-0123-456789ABCDEF' + $oContact->IdContactStr = $oMessage->Subject(); + $oContact->IdContactStr = \str_replace('urn:uuid:', '', $oContact->IdContactStr); + + return $oContact; + } + + public function IsSupported() : bool + { + // Check $this->ImapClient()->hasCapability('METADATA') + return true; + } + + public function SetEmail(string $sEmail) : bool + { + return true; + } + + /** + * Sync with davClient + */ + public function Sync() : bool + { + // TODO + return false; + } + + public function Export(string $sType = 'vcf') : bool + { + $rCsv = 'csv' === $sType ? \fopen('php://output', 'w') : null; + $bCsvHeader = true; + + if (!\strlen($this->sFolderName)) { +// return false; + throw new \RainLoop\Exceptions\ClientException(\RainLoop\Notifications::CantGetMessageList); + } + + $this->ImapClient(); + + try + { + $oParams = new \MailSo\Mail\MessageListParams; + $oParams->sFolderName = $this->sFolderName; +// $oParams->iOffset = 0; + $oParams->iLimit = 999; // Is the max + $oMessageList = $this->MailClient()->MessageList($oParams); + foreach ($oMessageList as $oMessage) { + try { + if ($rCsv) { + $oContact = $this->MessageAsContact($oMessage); + \RainLoop\Providers\AddressBook\Utils::VCardToCsv($rCsv, $oContact->vCard, $bCsvHeader); + $bCsvHeader = false; + } else if ($xCard = $this->fetchXCardFromMessage($oMessage)) { + echo $xCard->serialize(); + } + } catch (\Throwable $oExc) { + $this->oLogger && $this->oLogger->WriteException($oExc); + } + } + } + catch (\Throwable $oException) + { + throw $oException; + throw new \RainLoop\Exceptions\ClientException(\RainLoop\Notifications::CantGetMessageList, $oException); + } + return true; + } + + public function ContactSave(Contact $oContact) : bool + { + if (!$this->SelectFolder()) { + return false; + } + + $id = \intval($oContact->id); + $sUID = ''; + + $oVCard = $oContact->vCard; + + $oPrevMessage = $this->MailClient()->Message($this->sFolderName, $id); + if ($oPrevMessage) { + $sUID = $oPrevMessage->Subject(); + if (!$sUID) { + $oVCard = $this->fetchXCardFromMessage($oPrevMessage); + $sUID = \str_replace('urn:uuid:', '', $oVCard->UID); + } + } else { + $id = 0; + } + + if (!$sUID || !\SnappyMail\UUID::isValid($sUID)) { + $sUID = \SnappyMail\UUID::generate(); + } + $oVCard->UID = new \Sabre\VObject\Property\Uri($oVCard, 'uid', 'urn:uuid:' . $sUID); + $oContact->IdContactStr = $sUID; + + if (!\count($oVCard->select('x-kolab-version'))) { + $oVCard->add(new \Sabre\VObject\Property\Text($oVCard, 'x-kolab-version', '3.1.0')); + } + + $oVCard->VERSION = '3.0'; +// $oVCard->PRODID = 'SnappyMail-'.APP_VERSION; + $oVCard->KIND = 'individual'; + + $oMessage = new \MailSo\Mime\Message(); + $oMessage->DoesNotAddDefaultXMailer(); + $oMessage->messageIdRequired = false; + + $sEmail = ''; + if ($oVCard && isset($oVCard->EMAIL)) { + foreach ($oVCard->EMAIL as $oProp) { + $oTypes = $oProp ? $oProp['TYPE'] : null; + $sValue = $oProp ? \trim($oProp->getValue()) : ''; + if ($sValue && (!$sEmail || ($oTypes && $oTypes->has('PREF')))) { + $sEmail = $sValue; + } + } + if ($sEmail) { + $oMessage->SetFrom(new \MailSo\Mime\Email($sEmail, (string) $oVCard->FN)); + } + } + + $oMessage->SetSubject($sUID); +// $oMessage->SetDate(\time()); + $oMessage->SetCustomHeader('X-Kolab-Type', 'application/x-vnd.kolab.contact'); + $oMessage->SetCustomHeader('X-Kolab-Mime-Version', '3.0'); + $oMessage->SetCustomHeader('User-Agent', 'SnappyMail'); + + $oPart = new \MailSo\Mime\Part; + $oPart->Headers->AddByName(\MailSo\Mime\Enumerations\Header::CONTENT_TYPE, 'text/plain; charset="us-ascii"'); + $oPart->Headers->AddByName(\MailSo\Mime\Enumerations\Header::CONTENT_TRANSFER_ENCODING, '7Bit'); + $oPart->Body = "This is a Kolab Groupware object.\r\n" + . "To view this object you will need an email client that can understand the Kolab Groupware format.\r\n" + . "For a list of such email clients please visit\r\n" + . "https://en.wikipedia.org/wiki/Kolab\r\n"; + $oMessage->SubParts->append($oPart); + + // Now the vCard + $oPart = new \MailSo\Mime\Part; + $oPart->Headers->AddByName(\MailSo\Mime\Enumerations\Header::CONTENT_TYPE, 'application/vcard+xml; name="kolab.xml"'); + $oPart->Headers->AddByName(\MailSo\Mime\Enumerations\Header::CONTENT_TRANSFER_ENCODING, 'quoted-printable'); + $oPart->Headers->AddByName(\MailSo\Mime\Enumerations\Header::CONTENT_DISPOSITION, 'attachment; filename="kolab.xml"'); + $oPart->Body = \quoted_printable_encode(\preg_replace('/\r?\n/s', "\r\n", + \str_replace('encoding="UTF-8"', 'encoding="UTF-8" standalone="no" ', \Sabre\VObject\Writer::writeXml($oVCard)) + )); + $oMessage->SubParts->append($oPart); + + // Store Message + $rMessageStream = \MailSo\Base\ResourceRegistry::CreateMemoryResource(); + $iMessageStreamSize = \MailSo\Base\Utils::MultipleStreamWriter( + $oMessage->ToStream(false), array($rMessageStream), 8192, true, true); + if (false !== $iMessageStreamSize) { + \rewind($rMessageStream); + $this->ImapClient()->MessageReplaceStream($this->sFolderName, $id, $rMessageStream, $iMessageStreamSize); + } + + return true; + } + + public function DeleteContacts(array $aContactIds) : bool + { + try { + $this->MailClient()->MessageDelete( + $this->sFolderName, + new \MailSo\Imap\SequenceSet($aContactIds) + ); +/* + // Delete remote when Mode = read + write + if (1 === $oConfig['Mode']) { + $oClient = $this->getDavClient(); + if ($oClient) { + $sPath = $oClient->__UrlPath__; + $aRemoteSyncData = $this->prepareDavSyncData($oClient, $sPath); + if ($aRemoteSyncData && isset($aRemoteSyncData[$sKey], $aRemoteSyncData[$sKey]['vcf'])) { + $this->davClientRequest($oClient, 'DELETE', $sPath.$aRemoteSyncData[$sKey]['vcf']); + } + } + } +*/ + return true; + } catch (\Throwable $e) { + } + return false; + } + + public function DeleteAllContacts(string $sEmail) : bool + { + // Called by \RainLoop\Api::ClearUserData() + // Not needed as the contacts are inside IMAP mailbox +// $this->MailClient()->FolderClear($this->sFolderName); + return false; + } + + public function GetContacts(int $iOffset = 0, int $iLimit = 20, string $sSearch = '', int &$iResultCount = 0) : array + { + if (!\strlen($this->sFolderName)) { +// return []; + throw new \RainLoop\Exceptions\ClientException(\RainLoop\Notifications::CantGetMessageList); + } + + $this->ImapClient(); + + $aResult = []; + + try + { + $oParams = new \MailSo\Mail\MessageListParams; + $oParams->sFolderName = $this->sFolderName; + $oParams->iOffset = $iOffset; + $oParams->iLimit = $iLimit; + if ($sSearch) { + $oParams->sSearch = 'from='.$sSearch; + } + $oParams->sSort = 'FROM'; + + $oMessageList = $this->MailClient()->MessageList($oParams); + foreach ($oMessageList as $oMessage) { + $aResult[] = $this->MessageAsContact($oMessage); + } + } + catch (\Throwable $oException) + { + throw $oException; + throw new \RainLoop\Exceptions\ClientException(\RainLoop\Notifications::CantGetMessageList, $oException); + } + + return $aResult; + } + + public function GetContactByEmail(string $sEmail) : ?Contact + { + // TODO + return null; + } + + public function GetContactByID($mID, bool $bIsStrID = false) : ?Contact + { + if ($bIsStrID) { + $oMessage = null; + } else { + $oMessage = $this->MailClient()->Message($this->sFolderName, $mID); + } + return $oMessage ? $this->MessageAsContact($oMessage) : null; + } + + public function GetSuggestions(string $sSearch, int $iLimit = 20) : array + { + $sSearch = \trim($sSearch); + if (2 > \strlen($sSearch) || !$this->SelectFolder()) { + return []; + } + + $sSearch = \MailSo\Imap\SearchCriterias::escapeSearchString($this->ImapClient(), $sSearch); + $aUids = \array_slice( + $this->ImapClient()->MessageSearch("FROM {$sSearch}"), + 0, $iLimit + ); + + $aResult = []; + foreach ($this->ImapClient()->Fetch(['BODY.PEEK[HEADER.FIELDS (FROM)]'], \implode(',', $aUids), true) as $oFetchResponse) { + $oHeaders = new \MailSo\Mime\HeaderCollection($oFetchResponse->GetHeaderFieldsValue()); + $oFrom = $oHeaders->GetAsEmailCollection(\MailSo\Mime\Enumerations\Header::FROM_, true); + foreach ($oFrom as $oMail) { + $aResult[] = [$oMail->GetEmail(), $oMail->GetDisplayName()]; + } + } + + return $aResult; + } + + public function IncFrec(array $aEmails, bool $bCreateAuto = true) : bool + { + if ($bCreateAuto) { + foreach ($aEmails as $sEmail => $sAddress) { + $sSearch = \MailSo\Imap\SearchCriterias::escapeSearchString($this->ImapClient(), $sEmail); + if (!$this->ImapClient()->MessageSearch("FROM {$sSearch}")) { + $oVCard = new VCard; + $oVCard->add('EMAIL', $sEmail); + $sFullName = \trim(\MailSo\Mime\Email::Parse(\trim($sAddress))->GetDisplayName()); + if ('' !== $sFullName) { + $sFirst = $sLast = ''; + if (false !== \strpos($sFullName, ' ')) { + $aNames = \explode(' ', $sFullName, 2); + $sFirst = isset($aNames[0]) ? $aNames[0] : ''; + $sLast = isset($aNames[1]) ? $aNames[1] : ''; + } else { + $sFirst = $sFullName; + } + if (\strlen($sFirst) || \strlen($sLast)) { + $oVCard->N = array($sLast, $sFirst, '', '', ''); + } + } + $oContact = new Contact(); + $oContact->setVCard($oVCard); + $this->ContactSave($oContact); + } + } + return true; + } + return false; + } + + public function Test() : string + { + // Nothing to test + return ''; + } +} diff --git a/plugins/kolab/LICENSE b/plugins/kolab/LICENSE new file mode 100644 index 000000000..4aed64b3a --- /dev/null +++ b/plugins/kolab/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2015 RainLoop Team + +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/plugins/kolab/index.php b/plugins/kolab/index.php new file mode 100644 index 000000000..e0a9063aa --- /dev/null +++ b/plugins/kolab/index.php @@ -0,0 +1,94 @@ +Set('contacts', 'enable', true); + if (\RainLoop\Api::Config()->Get('contacts', 'enable', false)) { + $this->UseLangs(true); + + $this->addHook('filter.app-data', 'FilterAppData'); + $this->addHook('main.fabrica', 'MainFabrica'); + + $this->addJs('js/settings.js'); + $this->addTemplate('templates/KolabSettings.html'); + $this->addJsonHook('KolabFolder', 'DoKolabFolder'); + } + } + + public function Supported() : string + { + return ''; + } + + private function Account() : \RainLoop\Model\Account + { + return \RainLoop\Api::Actions()->getAccountFromToken(); + } + + private function SettingsProvider() : \RainLoop\Providers\Settings + { + return \RainLoop\Api::Actions()->SettingsProvider(true); + } + + private function Settings() : \RainLoop\Settings + { + return $this->SettingsProvider()->Load($this->Account()); + } + + public function DoKolabFolder() : array + { +// \error_log(\print_r($this->Manager()->Actions()->GetActionParams(), 1)); + $sValue = $this->jsonParam('contact'); + $oSettings = $this->Settings(); + if (\is_string($sValue)) { + $oSettings->SetConf('KolabContactFolder', $sValue); + $this->SettingsProvider()->Save($this->Account(), $oSettings); + } + return $this->jsonResponse(__FUNCTION__, true); + } + + public function FilterAppData($bAdmin, &$aResult) : void + { +// if ImapClient->hasCapability('METADATA') + if (!$bAdmin && \is_array($aResult) && !empty($aResult['Auth'])) { + $aResult['Capa']['Kolab'] = true; + $aResult['KolabContactFolder'] = (string) $this->Settings()->GetConf('KolabContactFolder', ''); + } + } + + /** + * @param mixed $mResult + */ + public function MainFabrica(string $sName, &$mResult) + { +/* + if ('suggestions' === $sName) { + if (!\is_array($mResult)) { + $mResult = array(); + } +// $sFolder = \trim($this->Config()->Get('plugin', 'mailbox', '')); +// if ($sFolder) { + require_once __DIR__ . '/KolabContactsSuggestions.php'; + $mResult[] = new KolabContactsSuggestions(); +// } + } +*/ + if ('address-book' === $sName) { + $sFolderName = $this->Settings()->GetConf('KolabContactFolder', ''); + if ($sFolderName) { + require_once __DIR__ . '/KolabAddressBook.php'; + $mResult = new KolabAddressBook($sFolderName); + } + } + } +} diff --git a/plugins/kolab/js/settings.js b/plugins/kolab/js/settings.js new file mode 100644 index 000000000..1f83fb0bd --- /dev/null +++ b/plugins/kolab/js/settings.js @@ -0,0 +1,54 @@ +(rl => { + +const getFolders = type => { + const + aResult = [{ + id: '', + name: '', + }], + foldersWalk = folders => { + folders.forEach(oItem => { + if (type === oItem.kolabType()) { + aResult.push({ + id: oItem.fullName, + name: oItem.fullName + }); + } + if (oItem.subFolders.length) { + foldersWalk(oItem.subFolders()); + } + }); + }; + foldersWalk(rl.app.folderList()); + return aResult; +}; + + +class KolabSettings /* extends AbstractViewSettings */ +{ + constructor() { + this.contactFolder = ko.observable(rl.settings.get('KolabContactFolder')); +// rl.app.FolderUserStore.hasCapability('METADATA'); + this.contactFolder.subscribe(value => { + rl.pluginRemoteRequest(()=>{}, 'KolabFolder', { + contact: value + }); + }); + this.contactFoldersList = ko.computed(() => getFolders('contact'), {'pure':true}); +// this.eventFoldersList = ko.computed(() => getFolders('event'), {'pure':true}); +// this.taskFoldersList = ko.computed(() => getFolders('task'), {'pure':true}); +// this.noteFoldersList = ko.computed(() => getFolders('note'), {'pure':true}); +// this.fileFoldersList = ko.computed(() => getFolders('file'), {'pure':true}); +// this.journalFoldersList = ko.computed(() => getFolders('journal'), {'pure':true}); +// this.configFoldersList = ko.computed(() => getFolders('configuration'), {'pure':true}); + } +} + +rl.addSettingsViewModel( + KolabSettings, + 'KolabSettings', + 'Kolab', + 'kolab' +); + +})(window.rl); diff --git a/plugins/kolab/langs/ar.json b/plugins/kolab/langs/ar.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/ar.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/bg.json b/plugins/kolab/langs/bg.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/bg.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/cs.json b/plugins/kolab/langs/cs.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/cs.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/da.json b/plugins/kolab/langs/da.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/da.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/de.json b/plugins/kolab/langs/de.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/de.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/el.json b/plugins/kolab/langs/el.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/el.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/en.json b/plugins/kolab/langs/en.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/en.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/es.json b/plugins/kolab/langs/es.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/es.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/et.json b/plugins/kolab/langs/et.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/et.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/fa.json b/plugins/kolab/langs/fa.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/fa.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/fi.json b/plugins/kolab/langs/fi.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/fi.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/fr.json b/plugins/kolab/langs/fr.json new file mode 100644 index 000000000..da740ca95 --- /dev/null +++ b/plugins/kolab/langs/fr.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Dossier Contacts" + } +} diff --git a/plugins/kolab/langs/hu.json b/plugins/kolab/langs/hu.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/hu.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/id.json b/plugins/kolab/langs/id.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/id.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/is.json b/plugins/kolab/langs/is.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/is.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/it.json b/plugins/kolab/langs/it.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/it.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/ja.json b/plugins/kolab/langs/ja.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/ja.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/ko.json b/plugins/kolab/langs/ko.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/ko.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/lt.json b/plugins/kolab/langs/lt.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/lt.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/lv.json b/plugins/kolab/langs/lv.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/lv.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/nb.json b/plugins/kolab/langs/nb.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/nb.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/nl.json b/plugins/kolab/langs/nl.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/nl.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/pl.json b/plugins/kolab/langs/pl.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/pl.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/pt.json b/plugins/kolab/langs/pt.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/pt.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/ro.json b/plugins/kolab/langs/ro.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/ro.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/ru.json b/plugins/kolab/langs/ru.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/ru.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/sk.json b/plugins/kolab/langs/sk.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/sk.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/sl.json b/plugins/kolab/langs/sl.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/sl.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/sv.json b/plugins/kolab/langs/sv.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/sv.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/tr.json b/plugins/kolab/langs/tr.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/tr.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/uk.json b/plugins/kolab/langs/uk.json new file mode 100644 index 000000000..39fe71e65 --- /dev/null +++ b/plugins/kolab/langs/uk.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "Contacts Folder" + } +} diff --git a/plugins/kolab/langs/zh-TW.json b/plugins/kolab/langs/zh-TW.json new file mode 100644 index 000000000..a635a4ef5 --- /dev/null +++ b/plugins/kolab/langs/zh-TW.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "聯絡人名刺夾" + } +} diff --git a/plugins/kolab/langs/zh.json b/plugins/kolab/langs/zh.json new file mode 100644 index 000000000..25cbc5656 --- /dev/null +++ b/plugins/kolab/langs/zh.json @@ -0,0 +1,5 @@ +{ + "KOLAB": { + "CONTACTS_FOLDER": "联系人文件夹" + } +} diff --git a/plugins/kolab/templates/KolabSettings.html b/plugins/kolab/templates/KolabSettings.html new file mode 100644 index 000000000..71cd3cc93 --- /dev/null +++ b/plugins/kolab/templates/KolabSettings.html @@ -0,0 +1,12 @@ +
+
Kolab
+
+ +
+ + +
+ +
+
diff --git a/plugins/ldap-contacts-suggestions/LdapContactsSuggestions.php b/plugins/ldap-contacts-suggestions/LdapContactsSuggestions.php index 8a10443b2..aa5907753 100644 --- a/plugins/ldap-contacts-suggestions/LdapContactsSuggestions.php +++ b/plugins/ldap-contacts-suggestions/LdapContactsSuggestions.php @@ -2,60 +2,27 @@ class LdapContactsSuggestions implements \RainLoop\Providers\Suggestions\ISuggestions { - /** - * @var string - */ - private $sLdapUri = 'ldap://localhost:389'; + use \MailSo\Log\Inherit; - /** - * @var bool - */ - private $bUseStartTLS = True; + private string $sLdapUri = 'ldap://localhost:389'; - /** - * @var string - */ - private $sBindDn = null; + private bool $bUseStartTLS = true; - /** - * @var string - */ - private $sBindPassword = null; + private string $sBindDn = ''; - /** - * @var string - */ - private $sBaseDn = 'ou=People,dc=example,dc=com'; + private string $sBindPassword = ''; - /** - * @var string - */ - private $sObjectClasses = 'inetOrgPerson'; + private string $sBaseDn = 'ou=People,dc=example,dc=com'; - /** - * @var string - */ - private $sUidAttributes = 'uid'; + private string $sObjectClasses = 'inetOrgPerson'; - /** - * @var string - */ - private $sNameAttributes = 'displayName,cn,givenName,sn'; + private string $sUidAttributes = 'uid'; - /** - * @var string - */ - private $sEmailAttributes = 'mailAddress,mail,mailAlternateAddress,mailAlias'; + private string $sNameAttributes = 'displayName,cn,givenName,sn'; - /** - * @var \MailSo\Log\Logger - */ - private $oLogger = null; + private string $sEmailAttributes = 'mailAddress,mail,mailAlternateAddress,mailAlias'; - /** - * @var string - */ - private $sAllowedEmails = '*'; + private string $sAllowedEmails = '*'; /** * @param string $sLdapUri @@ -75,8 +42,7 @@ class LdapContactsSuggestions implements \RainLoop\Providers\Suggestions\ISugges { $this->sLdapUri = $sLdapUri; $this->bUseStartTLS = $bUseStartTLS; - if (0 < \strlen($sBindDn)) - { + if (\strlen($sBindDn)) { $this->sBindDn = $sBindDn; $this->sBindPassword = $sBindPassword; } @@ -90,142 +56,51 @@ class LdapContactsSuggestions implements \RainLoop\Providers\Suggestions\ISugges return $this; } - /** - * @param \RainLoop\Model\Account $oAccount - * @param string $sQuery - * @param int $iLimit = 20 - * - * @return array - */ - public function Process(RainLoop\Model\Account $oAccount, string $sQuery, int $iLimit = 20): array + public function Process(\RainLoop\Model\Account $oAccount, string $sQuery, int $iLimit = 20): array { $sQuery = \trim($sQuery); - if (2 > \strlen($sQuery)) - { - return array(); - } - else if (!$oAccount || !\RainLoop\Plugins\Helper::ValidateWildcardValues($oAccount->Email(), $this->sAllowedEmails)) + if (2 > \strlen($sQuery) + || !$oAccount + || !\RainLoop\Plugins\Helper::ValidateWildcardValues($oAccount->Email(), $this->sAllowedEmails)) { return array(); } - $aResult = $this->ldapSearch($oAccount, $sQuery); - - $aResult = \RainLoop\Utils::RemoveSuggestionDuplicates($aResult); - if ($iLimit < \count($aResult)) - { - $aResult = \array_slice($aResult, 0, $iLimit); - } - - return $aResult; - } - - /** - * @param array $aLdapItem - * @param array $aEmailAttributes - * @param array $aNameAttributes - * @param array $aUidAttributes - * - * @return array - */ - private function findNameAndEmail($aLdapItem, $aEmailAttributes, $aNameAttributes, $aUidAttributes) - { - $sEmail = $sName = $sUid = ''; - if ($aLdapItem) - { - foreach ($aEmailAttributes as $sField) - { - $sField = \strtolower($sField); - if (!empty($aLdapItem[$sField][0])) - { - $sEmail = \trim($aLdapItem[$sField][0]); - if (!empty($sEmail)) - { - break; - } - } - } - - foreach ($aNameAttributes as $sField) - { - $sField = \strtolower($sField); - if (!empty($aLdapItem[$sField][0])) - { - $sName = \trim($aLdapItem[$sField][0]); - if (!empty($sName)) - { - break; - } - } - } - - foreach ($aUidAttributes as $sField) - { - $sField = \strtolower($sField); - if (!empty($aLdapItem[$sField][0])) - { - $sUid = \trim($aLdapItem[$sField][0]); - if (!empty($sUid)) - { - break; - } - } - } - } - - return array($sEmail, $sName, $sUid); - } - - /** - * @param \RainLoop\Model\Account $oAccount - * @param string $sQuery - * - * @return array - */ - private function ldapSearch($oAccount, $sQuery) - { $sSearchEscaped = $this->escape($sQuery); $aResult = array(); $oCon = @\ldap_connect($this->sLdapUri); - if ($oCon) - { - $this->oLogger->Write('ldap_connect: connected', \MailSo\Log\Enumerations\Type::INFO, 'LDAP'); + if ($oCon) { + $this->logWrite('ldap_connect: connected', \LOG_INFO, 'LDAP'); @\ldap_set_option($oCon, LDAP_OPT_PROTOCOL_VERSION, 3); - if ($this->bUseStartTLS && !@\ldap_start_tls($oCon)) - { + if ($this->bUseStartTLS && !@\ldap_start_tls($oCon)) { $this->logLdapError($oCon, 'ldap_start_tls'); return $aResult; } - if (!@\ldap_bind($oCon, $this->sBindDn, $this->sBindPassword)) - { - if (is_null($this->sBindDn)) - { + if (!@\ldap_bind($oCon, $this->sBindDn, $this->sBindPassword)) { + if (\is_null($this->sBindDn)) { $this->logLdapError($oCon, 'ldap_bind (anonymous)'); - } - else - { + } else { $this->logLdapError($oCon, 'ldap_bind'); } - return $aResult; } - $sDomain = \MailSo\Base\Utils::GetDomainFromEmail($oAccount->Email()); + $sDomain = \MailSo\Base\Utils::getEmailAddressDomain($oAccount->Email()); $sBaseDn = \strtr($this->sBaseDn, array( '{domain}' => $sDomain, '{domain:dc}' => 'dc='.\strtr($sDomain, array('.' => ',dc=')), '{email}' => $oAccount->Email(), - '{email:user}' => \MailSo\Base\Utils::GetAccountNameFromEmail($oAccount->Email()), + '{email:user}' => \MailSo\Base\Utils::getEmailAddressLocalPart($oAccount->Email()), '{email:domain}' => $sDomain, - '{login}' => $oAccount->Login(), - '{imap:login}' => $oAccount->Login(), - '{imap:host}' => $oAccount->DomainIncHost(), - '{imap:port}' => $oAccount->DomainIncPort() + '{login}' => $oAccount->IncLogin(), + '{imap:login}' => $oAccount->IncLogin(), + '{imap:host}' => $oAccount->Domain()->ImapSettings()->host, + '{imap:port}' => $oAccount->Domain()->ImapSettings()->port )); $aObjectClasses = empty($this->sObjectClasses) ? array() : \explode(',', $this->sObjectClasses); @@ -242,11 +117,9 @@ class LdapContactsSuggestions implements \RainLoop\Providers\Suggestions\ISugges $iObjCount = 0; $sObjFilter = ''; - foreach ($aObjectClasses as $sItem) - { - if (!empty($sItem)) - { - $iObjCount++; + foreach ($aObjectClasses as $sItem) { + if (!empty($sItem)) { + ++$iObjCount; $sObjFilter .= '(objectClass='.$sItem.')'; } } @@ -254,10 +127,8 @@ class LdapContactsSuggestions implements \RainLoop\Providers\Suggestions\ISugges $aItems = array(); $sSubFilter = ''; - foreach ($aFields as $sItem) - { - if (!empty($sItem)) - { + foreach ($aFields as $sItem) { + if (!empty($sItem)) { $aItems[] = $sItem; $sSubFilter .= '('.$sItem.'=*'.$sSearchEscaped.'*)'; } @@ -268,47 +139,91 @@ class LdapContactsSuggestions implements \RainLoop\Providers\Suggestions\ISugges $sFilter .= (1 < count($aItems) ? '(|' : '').$sSubFilter.(1 < count($aItems) ? ')' : ''); $sFilter .= ')'; - $this->oLogger->Write('ldap_search: start: '.$sBaseDn.' / '.$sFilter, \MailSo\Log\Enumerations\Type::INFO, 'LDAP'); - $oS = @\ldap_search($oCon, $sBaseDn, $sFilter, $aItems, 0, 30, 30); - if ($oS) - { - $aEntries = @\ldap_get_entries($oCon, $oS); - if (is_array($aEntries)) - { - if (isset($aEntries['count'])) - { - unset($aEntries['count']); - } + // A directory rarely keeps everything worth suggesting in one branch: + // meeting rooms and other bookable resources commonly live outside + // the people branch. Searching a single subtree either misses them, + // or - if the base is widened to the domain root - drags every + // service account into the suggestion list. Base DNs are therefore + // separated by '|', which cannot appear unescaped in a DN, so an + // existing single-branch configuration keeps working unchanged. + $aBaseDns = \array_filter(\array_map('trim', \explode('|', $sBaseDn)), 'strlen'); - foreach ($aEntries as $aItem) - { - if ($aItem) - { - $sName = $sEmail = ''; - list ($sEmail, $sName) = $this->findNameAndEmail($aItem, $aEmails, $aNames, $aUIDs); - if (!empty($sEmail)) - { - $aResult[] = array($sEmail, $sName); + foreach ($aBaseDns as $sOneBaseDn) { + $this->logWrite('ldap_search: start: '.$sOneBaseDn.' / '.$sFilter, \LOG_INFO, 'LDAP'); + $oS = @\ldap_search($oCon, $sOneBaseDn, $sFilter, $aItems, 0, 30, 30); + if ($oS) { + $aEntries = @\ldap_get_entries($oCon, $oS); + if (is_array($aEntries)) { + if (isset($aEntries['count'])) { + unset($aEntries['count']); + } + + foreach ($aEntries as $aItem) { + if ($aItem) { + $sName = $sEmail = ''; + list ($sEmail, $sName) = $this->findNameAndEmail($aItem, $aEmails, $aNames, $aUIDs); + if (!empty($sEmail)) { + $aResult[] = array($sEmail, $sName); + } } } + } else { + $this->logLdapError($oCon, 'ldap_get_entries'); } - } - else - { - $this->logLdapError($oCon, 'ldap_get_entries'); + } else { + // One unreachable branch must not silence the others. + $this->logLdapError($oCon, 'ldap_search ('.$sOneBaseDn.')'); } } - else - { - $this->logLdapError($oCon, 'ldap_search'); - } - } - else - { - return $aResult; } - return $aResult; + return \array_slice($aResult, 0, $iLimit); + } + + /** + * @param array $aLdapItem + * @param array $aEmailAttributes + * @param array $aNameAttributes + * @param array $aUidAttributes + * + * @return array + */ + private function findNameAndEmail($aLdapItem, $aEmailAttributes, $aNameAttributes, $aUidAttributes) + { + $sEmail = $sName = $sUid = ''; + if ($aLdapItem) { + foreach ($aEmailAttributes as $sField) { + $sField = \strtolower($sField); + if (!empty($aLdapItem[$sField][0])) { + $sEmail = \trim($aLdapItem[$sField][0]); + if (!empty($sEmail)) { + break; + } + } + } + + foreach ($aNameAttributes as $sField) { + $sField = \strtolower($sField); + if (!empty($aLdapItem[$sField][0])) { + $sName = \trim($aLdapItem[$sField][0]); + if (!empty($sName)) { + break; + } + } + } + + foreach ($aUidAttributes as $sField) { + $sField = \strtolower($sField); + if (!empty($aLdapItem[$sField][0])) { + $sUid = \trim($aLdapItem[$sField][0]); + if (!empty($sUid)) { + break; + } + } + } + } + + return array($sEmail, $sName, $sUid); } /** @@ -321,8 +236,7 @@ class LdapContactsSuggestions implements \RainLoop\Providers\Suggestions\ISugges $aNewChars = array(); $aChars = array('\\', '*', '(', ')', \chr(0)); - foreach ($aChars as $iIndex => $sValue) - { + foreach ($aChars as $iIndex => $sValue) { $aNewChars[$iIndex] = '\\'.\str_pad(\dechex(\ord($sValue)), 2, '0'); } @@ -337,28 +251,10 @@ class LdapContactsSuggestions implements \RainLoop\Providers\Suggestions\ISugges */ public function logLdapError($oCon, $sCmd) { - if ($this->oLogger) - { + if ($this->oLogger) { $sError = $oCon ? @\ldap_error($oCon) : ''; $iErrno = $oCon ? @\ldap_errno($oCon) : 0; - - $this->oLogger->Write($sCmd.' error: '.$sError.' ('.$iErrno.')', - \MailSo\Log\Enumerations\Type::WARNING, 'LDAP'); + $this->logWrite($sCmd.' error: '.$sError.' ('.$iErrno.')', \LOG_WARNING, 'LDAP'); } } - - /** - * @param \MailSo\Log\Logger $oLogger - * - * @return \LdapContactsSuggestions - */ - public function SetLogger($oLogger) - { - if ($oLogger instanceof \MailSo\Log\Logger) - { - $this->oLogger = $oLogger; - } - - return $this; - } } diff --git a/plugins/ldap-contacts-suggestions/index.php b/plugins/ldap-contacts-suggestions/index.php index f24812f52..5ef78593c 100644 --- a/plugins/ldap-contacts-suggestions/index.php +++ b/plugins/ldap-contacts-suggestions/index.php @@ -3,9 +3,11 @@ class LdapContactsSuggestionsPlugin extends \RainLoop\Plugins\AbstractPlugin { const - NAME = 'Contacts suggestions (LDAP)', - VERSION = '2.1', - CATEGORY = 'Security', + NAME = 'Contacts suggestions (LDAP)', + VERSION = '2.15', + RELEASE = '2026-08-19', + REQUIRED = '2.35.3', + CATEGORY = 'Contacts', DESCRIPTION = 'Get contacts suggestions from LDAP.'; public function Init() : void @@ -13,9 +15,6 @@ class LdapContactsSuggestionsPlugin extends \RainLoop\Plugins\AbstractPlugin $this->addHook('main.fabrica', 'MainFabrica'); } - /** - * @return string - */ public function Supported() : string { if (!\function_exists('ldap_connect')) @@ -32,43 +31,38 @@ class LdapContactsSuggestionsPlugin extends \RainLoop\Plugins\AbstractPlugin */ public function MainFabrica($sName, &$mResult) { - switch ($sName) - { - case 'suggestions': + if ('suggestions' == $sName) { + if (!\is_array($mResult)) { + $mResult = array(); + } - if (!\is_array($mResult)) - { - $mResult = array(); - } + $sLdapUri = \trim($this->Config()->Get('plugin', 'ldap_uri', '')); + $sBaseDn = \trim($this->Config()->Get('plugin', 'base_dn', '')); + $sObjectClasses = \trim($this->Config()->Get('plugin', 'object_classes', '')); + $sEmailAttributes = \trim($this->Config()->Get('plugin', 'mail_attributes', '')); - $sLdapUri = \trim($this->Config()->Get('plugin', 'ldap_uri', '')); - $bUseStartTLS = (bool) $this->Config()->Get('plugin', 'use_start_tls', True); - $sBindDn = \trim($this->Config()->Get('plugin', 'bind_dn', '')); - $sBindPassword = \trim($this->Config()->Get('plugin', 'bind_password', '')); - $sBaseDn = \trim($this->Config()->Get('plugin', 'base_dn', '')); - $sObjectClasses = \trim($this->Config()->Get('plugin', 'object_classes', '')); - $sUidAttributes = \trim($this->Config()->Get('plugin', 'uid_attributes', '')); - $sNameAttributes = \trim($this->Config()->Get('plugin', 'name_attributes', '')); - $sEmailAttributes = \trim($this->Config()->Get('plugin', 'mail_attributes', '')); - $sAllowedEmails = \trim($this->Config()->Get('plugin', 'allowed_emails', '')); + if (\strlen($sLdapUri) && \strlen($sBaseDn) && \strlen($sObjectClasses) && \strlen($sEmailAttributes)) { + require_once __DIR__.'/LdapContactsSuggestions.php'; - if (0 < \strlen($sLdapUri) && 0 < \strlen($sBaseDn) && 0 < \strlen($sObjectClasses) && 0 < \strlen($sEmailAttributes)) - { - include_once __DIR__.'/LdapContactsSuggestions.php'; + $oProvider = new LdapContactsSuggestions(); + $oProvider->SetConfig( + $sLdapUri, + (bool) $this->Config()->Get('plugin', 'use_start_tls', true), + \trim($this->Config()->Get('plugin', 'bind_dn', '')), + \trim($this->Config()->Get('plugin', 'bind_password', '')), + $sBaseDn, + $sObjectClasses, + \trim($this->Config()->Get('plugin', 'uid_attributes', '')), + \trim($this->Config()->Get('plugin', 'name_attributes', '')), + $sEmailAttributes, + \trim($this->Config()->Get('plugin', 'allowed_emails', '')) + ); - $oProvider = new LdapContactsSuggestions(); - $oProvider->SetConfig($sLdapUri, $bUseStartTLS, $sBindDn, $sBindPassword, $sBaseDn, $sObjectClasses, $sUidAttributes, $sNameAttributes, $sEmailAttributes, $sAllowedEmails); - - $mResult[] = $oProvider; - } - - break; + $mResult[] = $oProvider; + } } } - /** - * @return array - */ protected function configMapping() : array { return array( @@ -85,9 +79,9 @@ class LdapContactsSuggestionsPlugin extends \RainLoop\Plugins\AbstractPlugin ->SetType(\RainLoop\Enumerations\PluginPropertyType::PASSWORD) ->SetDefaultValue(''), \RainLoop\Plugins\Property::NewInstance('base_dn')->SetLabel('Search base DN') - ->SetDescription('DN to use as the search base. Supported tokens: {domain}, {domain:dc}, {email}, {email:user}, {email:domain}, {login}, {imap:login}, {imap:host}, {imap:port}') + ->SetDescription('DN to use as the search base. Supported tokens: {domain}, {domain:dc}, {email}, {email:user}, {email:domain}, {login}, {imap:login}, {imap:host}, {imap:port} Several branches may be given, separated by | - useful when meeting rooms or other resources live outside the people branch.') ->SetDefaultValue('ou=People,dc=example,dc=com'), - \RainLoop\Plugins\Property::NewInstance('object_classes')->SetLabel('objectClasses to use') + \RainLoop\Plugins\Property::NewInstance('object_classes')->SetLabel('objectClasses') ->SetDescription('LDAP objectClasses to search for, comma separated list') ->SetDefaultValue('inetOrgPerson'), \RainLoop\Plugins\Property::NewInstance('uid_attributes')->SetLabel('uid attributes') diff --git a/plugins/ldap-identities/LdapConfig.php b/plugins/ldap-identities/LdapConfig.php index d737e7370..c55f88bcb 100644 --- a/plugins/ldap-identities/LdapConfig.php +++ b/plugins/ldap-identities/LdapConfig.php @@ -7,6 +7,8 @@ class LdapConfig { public const CONFIG_SERVER = "server"; public const CONFIG_PROTOCOL_VERSION = "server_version"; + public const CONFIG_STARTTLS = "starttls"; + public const CONFIG_MAIL_PREFIX = "mail_prefix"; public const CONFIG_BIND_USER = "bind_user"; public const CONFIG_BIND_PASSWORD = "bind_password"; @@ -28,6 +30,8 @@ class LdapConfig public $server; public $protocol; + public $starttls; + public $mail_prefix; public $bind_user; public $bind_password; public $user_base; @@ -48,6 +52,8 @@ class LdapConfig $ldap = new self(); $ldap->server = trim($config->Get("plugin", self::CONFIG_SERVER)); $ldap->protocol = (int)trim($config->Get("plugin", self::CONFIG_PROTOCOL_VERSION, 3)); + $ldap->starttls = (bool)trim($config->Get("plugin", self::CONFIG_STARTTLS)); + $ldap->mail_prefix = trim($config->Get("plugin", self::CONFIG_MAIL_PREFIX)); $ldap->bind_user = trim($config->Get("plugin", self::CONFIG_BIND_USER)); $ldap->bind_password = trim($config->Get("plugin", self::CONFIG_BIND_PASSWORD)); $ldap->user_base = trim($config->Get("plugin", self::CONFIG_USER_BASE)); diff --git a/plugins/ldap-identities/LdapException.php b/plugins/ldap-identities/LdapException.php index 2abaf07a8..df489e577 100644 --- a/plugins/ldap-identities/LdapException.php +++ b/plugins/ldap-identities/LdapException.php @@ -1,5 +1,5 @@ ldapAvailable = false; - $logger->Write("The LDAP extension is not available!", Type::WARNING, self::LOG_KEY); + $logger->Write("The LDAP extension is not available!", \LOG_WARNING, self::LOG_KEY); return; } @@ -70,17 +69,18 @@ class LdapIdentities implements IIdentities $this->config->user_base, $this->config->user_objectclass, $this->config->user_field_name, - $this->config->user_field_mail + $this->config->user_field_mail, + $this->config->mail_prefix ); } catch (LdapException $e) { return []; // exceptions are only thrown from the handleerror function that does logging already } if (count($userResults) < 1) { - $this->logger->Write("Could not find user $username", Type::NOTICE, self::LOG_KEY); + $this->logger->Write("Could not find user $username", \LOG_NOTICE, self::LOG_KEY); return []; } else if (count($userResults) > 1) { - $this->logger->Write("Found multiple matches for user $username", Type::WARNING, self::LOG_KEY); + $this->logger->Write("Found multiple matches for user $username", \LOG_WARNING, self::LOG_KEY); } $userResult = $userResults[0]; @@ -105,7 +105,8 @@ class LdapIdentities implements IIdentities $this->config->group_base, $this->config->group_objectclass, $this->config->group_field_name, - $this->config->group_field_mail + $this->config->group_field_mail, + $this->config->mail_prefix ); } catch (LdapException $e) { return []; // exceptions are only thrown from the handleerror function that does logging already @@ -130,11 +131,11 @@ class LdapIdentities implements IIdentities /** * @inheritDoc - * @throws \RainLoop\Exceptions\Exception + * @throws \RainLoop\Exceptions\ClientException */ public function SetIdentities(Account $account, array $identities): void { - throw new \RainLoop\Exceptions\Exception("Ldap identities provider does not support storage"); + throw new \RainLoop\Exceptions\ClientException("Ldap identities provider does not support storage"); } /** @@ -179,6 +180,15 @@ class LdapIdentities implements IIdentities return false; } + // Activate StartTLS + if ($this->config->starttls) { + $starttlsResult = ldap_start_tls($ldap); + if (!$starttlsResult) { + $this->ldapAvailable = false; + return false; + } + } + $this->ldap = $ldap; $this->ldapConnected = true; return true; @@ -219,7 +229,7 @@ class LdapIdentities implements IIdentities $errorMsg = @ldap_error($this->ldap); $message = empty($op) ? "LDAP Error: {$errorMsg} ({$errorNo})" : "LDAP Error during {$op}: {$errorMsg} ({$errorNo})"; - $this->logger->Write($message, Type::ERROR, self::LOG_KEY); + $this->logger->Write($message, \LOG_ERR, self::LOG_KEY); throw new LdapException($message, $errorNo); } @@ -233,7 +243,7 @@ class LdapIdentities implements IIdentities * @return LdapResult[] * @throws LdapException */ - private function FindLdapResults(string $searchField, string $searchValue, string $searchBase, string $objectClass, string $nameField, string $mailField): array + private function FindLdapResults(string $searchField, string $searchValue, string $searchBase, string $objectClass, string $nameField, string $mailField, string $mailPrefix): array { $this->EnsureBound(); @@ -253,6 +263,8 @@ class LdapIdentities implements IIdentities return []; } + $entries = $this->CleanupMailAddresses($entries, $mailField, $mailPrefix); + $results = []; for ($i = 0; $i < $entries["count"]; $i++) { $entry = $entries[$i]; @@ -268,6 +280,49 @@ class LdapIdentities implements IIdentities return $results; } + // Function CleanupMailAddresses(): If a prefix is given this function removes addresses without / with the wrong prefix and then the prefix itself from all remaining values. + // This is usefull for example for importing Active Directory LDAP entry "proxyAddresses" which can hold different address types with prefixes like "X400:", "smtp:" "sip:" and others. + + /** + @param array $entries + @param string $mailField + @paraam string $mailPrefix + @return array + */ + private function CleanupMailAddresses(array $entries, string $mailField, string $mailPrefix) + { + if (!empty($mailPrefix)) { + for ($i = 0; $i < $entries["count"]; $i++) { + // Remove addresses without the given prefix + $entries[$i]["$mailField"] = array_filter($entries[$i]["$mailField"], + function($prefixMail) + { + // $mailPrefix can't be used here, because it's nailed to the CleanupMailAddresses function and can't be passed to the array_filter function afaik. + // Ideas to avoid this are welcome. + if (stripos($prefixMail, $this->config->mail_prefix) === 0) { + return TRUE; + } + return FALSE; + } + ); + // Set "count" to new value + $newcount = count($entries[$i]["$mailField"]); + if (array_key_exists("count", $entries[$i]["$mailField"])) { + $newcount = $newcount - 1; + } + $entries[$i]["$mailField"]["count"] = $newcount; + + // Remove the prefix + for ($j = 0; $j < $entries[$i]["$mailField"]["count"]; $j++) { + $mailPrefixLen = mb_strlen($mailPrefix); + $entries[$i]["$mailField"][$j] = substr($entries[$i]["$mailField"][$j], $mailPrefixLen); + } + } + } + + return $entries; + } + /** * @param array $entry * @param string $attribute @@ -279,14 +334,14 @@ class LdapIdentities implements IIdentities { if (!isset($entry[$attribute])) { if ($required) - $this->logger->Write("Attribute $attribute not found on object {$entry['dn']} while required", Type::NOTICE, self::LOG_KEY); + $this->logger->Write("Attribute $attribute not found on object {$entry['dn']} while required", \LOG_NOTICE, self::LOG_KEY); return $single ? "" : []; } if ($single) { if ($entry[$attribute]["count"] > 1) - $this->logger->Write("Attribute $attribute is multivalues while only a single value is expected", Type::NOTICE, self::LOG_KEY); + $this->logger->Write("Attribute $attribute is multivalues while only a single value is expected", \LOG_NOTICE, self::LOG_KEY); return $entry[$attribute][0]; } diff --git a/plugins/ldap-identities/index.php b/plugins/ldap-identities/index.php index 2fc18ebd5..4ac3f2faf 100644 --- a/plugins/ldap-identities/index.php +++ b/plugins/ldap-identities/index.php @@ -8,11 +8,11 @@ class LdapIdentitiesPlugin extends AbstractPlugin { const NAME = 'LDAP Identities', - VERSION = '2.0', + VERSION = '2.3', AUTHOR = 'FWest98', URL = 'https://github.com/FWest98', - RELEASE = '2020-11-11', - REQUIRED = '2.1.0', + RELEASE = '2024-02-27', + REQUIRED = '2.20.0', CATEGORY = 'Accounts', DESCRIPTION = 'Adds functionality to import account identities from LDAP.'; @@ -58,6 +58,18 @@ class LdapIdentitiesPlugin extends AbstractPlugin ->SetType(PluginPropertyType::SELECTION) ->SetDefaultValue([2, 3]), + Property::NewInstance(LdapConfig::CONFIG_STARTTLS) + ->SetLabel("Use StartTLS") + ->SetType(PluginPropertyType::BOOL) + ->SetDescription("Whether or not to use TLS encrypted connection") + ->SetDefaultValue(true), + + Property::NewInstance(LdapConfig::CONFIG_MAIL_PREFIX) + ->SetLabel("Email prefix") + ->SetType(PluginPropertyType::STRING) + ->SetDescription("Only addresses with this prefix will be used as identity. The prefix is removed from the identity list.\nThis is useful for example to import identities from Exchange, which stores mail addresses in the ProxyAddresses attribut of Active Directory with \"smtp:\" as prefix. (e.g. \"smtp:john.doe@topsecret.info\")\n-> To use addresses set by Exchange use \"smtp:\" as prefix.") + ->SetDefaultValue(""), + Property::NewInstance(LdapConfig::CONFIG_BIND_USER) ->SetLabel("Bind User DN") ->SetDescription("The user to use for binding to the LDAP server. Should be a DN or RDN. Leave empty for anonymous bind") diff --git a/plugins/ldap-login-mapping/LICENSE b/plugins/ldap-login-mapping/LICENSE new file mode 100644 index 000000000..335b3845a --- /dev/null +++ b/plugins/ldap-login-mapping/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2014 RainLoop Team +Copyright (c) 2018 +Copyright (c) 2022 + +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/plugins/ldap-login-mapping/README b/plugins/ldap-login-mapping/README new file mode 100644 index 000000000..59e065d6b --- /dev/null +++ b/plugins/ldap-login-mapping/README @@ -0,0 +1 @@ +This plugins allows to authenticate using LDAP mail field, yet login field would still be used for IMAP and SMTP authentication. diff --git a/plugins/ldap-login-mapping/VERSION b/plugins/ldap-login-mapping/VERSION new file mode 100644 index 000000000..cd5ac039d --- /dev/null +++ b/plugins/ldap-login-mapping/VERSION @@ -0,0 +1 @@ +2.0 diff --git a/plugins/ldap-login-mapping/index.php b/plugins/ldap-login-mapping/index.php new file mode 100644 index 000000000..ea00ee759 --- /dev/null +++ b/plugins/ldap-login-mapping/index.php @@ -0,0 +1,254 @@ +, ZephOne', + RELEASE = '2025-01-09', + REQUIRED = '2.36.1', + CATEGORY = 'Login', + DESCRIPTION = 'This plugins allows to authenticate using LDAP mail field, yet login field would still be used for IMAP and SMTP authentication'; + /** + * @var array + */ + private $aDomains = array(); + + /** + * @var string + */ + private $sSearchDomain = ''; + + /** + * @var string + */ + private $sHostName = '127.0.0.1'; + + /** + * @var int + */ + private $iHostPort = 389; + + /** + * @var string + */ + private $sUsersDn = ''; + + /** + * @var string + */ + private $sObjectClass = 'inetOrgPerson'; + + /** + * @var string + */ + private $sLoginField = 'uid'; + + /** + * @var string + */ + private $sEmailField = 'mail'; + + /** + * @var \MailSo\Log\Logger + */ + private $oLogger = null; + + public function Init(): void + { + $this->addHook('login.credentials', 'FilterLoginСredentials'); + } + + /** + * @return string + */ + public function Supported(): string + { + if (!\function_exists('ldap_connect')) + { + return 'The LDAP PHP extension must be installed to use this plugin'; + } + + return ''; + } + + /** + * @param string $sEmail + * @param string $sImapUser + * @param string $sPassword + * @param string $sSmtpUser + * + * @throws \RainLoop\Exceptions\ClientException + */ + public function FilterLoginСredentials(string &$sEmail, string &$sImapUser, string &$sPassword, string &$sSmtpUser) + { + $this->oLogger = \RainLoop\Api::Logger(); + + $this->aDomains = explode(',', $this->Config()->Get('plugin', 'domains', '')); + $this->sSearchDomain = trim($this->Config()->Get('plugin', 'search_domain', '')); + $this->sHostName = trim($this->Config()->Get('plugin', 'hostname', '')); + $this->iHostPort = (int) $this->Config()->Get('plugin', 'port', 389); + $this->sUsersDn = trim($this->Config()->Get('plugin', 'users_dn', '')); + $this->sObjectClass = trim($this->Config()->Get('plugin', 'object_class', '')); + $this->sLoginField = trim($this->Config()->Get('plugin', 'login_field', '')); + $this->sEmailField = trim($this->Config()->Get('plugin', 'mail_field', '')); + + if (0 < \strlen($this->sObjectClass) && 0 < \strlen($this->sEmailField)) + { + $sIP = $_SERVER['REMOTE_ADDR']; + $sResult = $this->ldapSearch($sEmail); + if ( is_array($sResult) ) { + $sImapUser = $sResult['login']; + $sSmtpUser = $sResult['login']; + $sEmail = $sResult['email']; + } + syslog(LOG_WARNING, "plugins/ldap-login-mapping/index.php:FilterLoginCredentials() auth try: $sIP/$sEmail, resolved as $sImapUser/$sEmail"); + } + } + + /** + * @return array + */ + public function configMapping(): array + { + return [ + Property::NewInstance('domains') + ->SetLabel('LDAP enabled domains') + ->SetDefaultValue('example1.com,example2.com'), + + Property::NewInstance('search_domain') + ->SetLabel('Forced domain') + ->SetDescription('Force this domain email for LDAP search') + ->SetDefaultValue('example.com'), + + Property::NewInstance('hostname') + ->SetLabel('LDAP hostname') + ->SetDefaultValue('127.0.0.1'), + + Property::NewInstance('port') + ->SetLabel('LDAP port') + ->SetType(PluginPropertyType::INT) + ->SetDefaultValue(389), + + Property::NewInstance('users_dn') + ->SetLabel('Search base DN') + ->SetDescription('LDAP users search base DN. No tokens.') + ->SetDefaultValue('ou=People,dc=domain,dc=com'), + + Property::NewInstance('object_class') + ->SetLabel('objectClass value') + ->SetDefaultValue('inetOrgPerson'), + + Property::NewInstance('login_field') + ->SetLabel('Login field') + ->SetDefaultValue('uid'), + + Property::NewInstance('mail_field') + ->SetLabel('Mail field') + ->SetDefaultValue('mail'), + ]; + } + + /** + * @param string $sEmailOrLogin + * + * @return string + */ + private function ldapSearch($sEmail) + { + $bFound = FALSE; + foreach ( $this->aDomains as $sDomain ) { + $sRegex = '/^[a-z0-9._-]+@' . preg_quote(trim($sDomain)) . '$/i'; + $this->oLogger->Write('DEBUG regex ' . $sRegex, \LOG_INFO, 'LDAP'); + if ( preg_match($sRegex, $sEmail) === 1) { + $bFound = TRUE; + break; + } + } + if ( !$bFound ) { + $this->oLogger->Write( + 'preg_match: no match in "' . $sEmail . '" for /^[a-z0-9._-]+@{configured-domains}$/i', + \LOG_INFO, + 'LDAP'); + return FALSE; + } + $sLogin = \MailSo\Base\Utils::getEmailAddressLocalPart($sEmail); + + $this->oLogger->Write('ldap_connect: trying...', \LOG_INFO, 'LDAP'); + + $oCon = @\ldap_connect($this->sHostName, $this->iHostPort); + if (!$oCon) return FALSE; + + $this->oLogger->Write('ldap_connect: connected', \LOG_INFO, 'LDAP'); + + @\ldap_set_option($oCon, LDAP_OPT_PROTOCOL_VERSION, 3); + + if (!@\ldap_bind($oCon)) { + $this->logLdapError($oCon, 'ldap_bind'); + return FALSE; + } + $sSearchDn = $this->sUsersDn; + $aItems = array($this->sLoginField, $this->sEmailField); + if ( 0 < \strlen($this->sSearchDomain) ) { + $sFilter = '(&(objectclass='.$this->sObjectClass.')(|('.$this->sEmailField.'='.$sLogin.'@'.$this->sSearchDomain.')('.$this->sLoginField.'='.$sLogin.')))'; + + } else { + $sFilter = '(&(objectclass='.$this->sObjectClass.')(|('.$this->sEmailField.'='.$sEmail.')('.$this->sLoginField.'='.$sLogin.')))'; + } + $this->oLogger->Write('ldap_search: start: '.$sSearchDn.' / '.$sFilter, \LOG_INFO, 'LDAP'); + $oS = @\ldap_search($oCon, $sSearchDn, $sFilter, $aItems, 0, 30, 30); + if (!$oS) { + $this->logLdapError($oCon, 'ldap_search'); + return FALSE; + } + $aEntries = @\ldap_get_entries($oCon, $oS); + if (!is_array($aEntries)) { + $this->logLdapError($oCon, 'ldap_get_entries'); + return FALSE; + } + if (!isset($aEntries[0])) { + $this->logLdapError($oCon, 'ldap_get_entries (no result)'); + return FALSE; + } + if (!isset($aEntries[0][$this->sLoginField][0])) { + $this->logLdapError($oCon, 'ldap_get_entries (no login)'); + return FALSE; + } + if (!isset($aEntries[0][$this->sEmailField][0])) { + $this->logLdapError($oCon, 'ldap_get_entries (no mail)'); + return FALSE; + } + $sLogin = $aEntries[0][$this->sLoginField][0]; + $sEmail = $aEntries[0][$this->sEmailField][0]; + $this->oLogger->Write('ldap_search: found "' . $this->sLoginField . ': '.$sLogin . '" and "' . $this->sEmailField . ': '.$sEmail . '"'); + + return array( + 'login' => $sLogin, + 'email' => $sEmail, + ); + } + + /** + * @param mixed $oCon + * @param string $sCmd + * + * @return string + */ + private function logLdapError($oCon, $sCmd) + { + if ($this->oLogger) + { + $sError = $oCon ? @\ldap_error($oCon) : ''; + $iErrno = $oCon ? @\ldap_errno($oCon) : 0; + + $this->oLogger->Write($sCmd.' error: '.$sError.' ('.$iErrno.')', + \LOG_WARNING, 'LDAP'); + } + } + +} diff --git a/plugins/ldap-mail-accounts/LdapMailAccounts.php b/plugins/ldap-mail-accounts/LdapMailAccounts.php new file mode 100644 index 000000000..5dc0c4eb6 --- /dev/null +++ b/plugins/ldap-mail-accounts/LdapMailAccounts.php @@ -0,0 +1,532 @@ +config = $config; + $this->logger = $logger; + + // Check if LDAP is available + if (!extension_loaded('ldap') || !function_exists('ldap_connect')) { + $this->ldapAvailable = false; + $logger->Write("The LDAP extension is not available!", \LOG_WARNING, self::LOG_KEY); + return; + } + + $this->Connect(); + } + + + /** + * @inheritDoc + * + * Overwrite the MainAccount mail address by looking up the new one in the ldap directory + * + * The ldap search string has to be configured in the plugin configuration of the extension (in the SnappyMail Admin Panel) + * + * @param string &$sEmail + */ + public function overwriteEmail(&$sEmail) + { + try { + $this->EnsureBound(); + } catch (LdapMailAccountsException $e) { + return false; // exceptions are only thrown from the handle error function that does logging already + } + + // Try to get account information. IncLogin() returns the username of the user + // and removes the domainname if this was configured inside the domain config. + $username = $sEmail; + $oActions = \RainLoop\Api::Actions(); + $oDomain = $oActions->DomainProvider()->Load(\MailSo\Base\Utils::getEmailAddressDomain($sEmail), true); + if ($oDomain->ImapSettings()->shortLogin){ + $username = @ldap_escape($this->RemoveEventualDomainPart($sEmail), "", LDAP_ESCAPE_FILTER); + } + + $searchString = $this->config->search_string; + + // Replace placeholders inside the ldap search string with actual values + $searchString = str_replace("#USERNAME#", $username, $searchString); + $searchString = str_replace("#BASE_DN#", $this->config->base, $searchString); + + $this->logger->Write("ldap search string after replacement of placeholders: $searchString", \LOG_NOTICE, self::LOG_KEY); + + try { + $mailAddressResults = $this->FindLdapResults( + $this->config->field_search, + $searchString, + $this->config->base, + $this->config->objectclass, + $this->config->field_name, + $this->config->field_username, + $this->config->field_domain, + true, + $this->config->field_mail_address_main_account, + ); + } + catch (LdapMailAccountsException $e) { + return false; // exceptions are only thrown from the handle error function that does logging already + } + if (count($mailAddressResults) < 1) { + $this->logger->Write("Could not find user $username in LDAP! Overwriting of main mail address not possible.", \LOG_NOTICE, self::LOG_KEY); + return false; + } + + foreach($mailAddressResults as $mailAddressResult) + { + if($mailAddressResult->username === $username) { + //$sImapUser and $sSmtpUser are already set to be the same as $sEmail by function "resolveLoginCredentials" in /RainLoop/Actions/UserAuth.php + //that called this hook, so we just have to overwrite the mail address + $sEmail = $mailAddressResult->mailMainAccount; + } + } + } + + /** + * @inheritDoc + * + * Add additional mail accounts to the given primary account by looking up the ldap directory + * + * The ldap search string has to be configured in the plugin configuration of the extension (in the SnappyMail Admin Panel) + * + * @param MainAccount $oAccount + * @return bool true if additional accounts have been added or no additional accounts where found in ldap. false if an error occured + */ + public function AddLdapMailAccounts(MainAccount $oAccount): bool + { + try { + $this->EnsureBound(); + } catch (LdapMailAccountsException $e) { + return false; // exceptions are only thrown from the handle error function that does logging already + } + + //Basing on https://github.com/the-djmaze/snappymail/issues/616 + + $oActions = \RainLoop\Api::Actions(); + + //Check if SnappyMail is configured to allow additional accounts + if (!$oActions->GetCapa(Capa::ADDITIONAL_ACCOUNTS)) { + return $oActions->FalseResponse(__FUNCTION__); + } + + // Try to get account information. ImapUser() returns the username of the user + // and removes the domainname if this was configured inside the domain config. + $username = @ldap_escape($oAccount->ImapUser(), "", LDAP_ESCAPE_FILTER); + + $searchString = $this->config->search_string; + + // Replace placeholders inside the ldap search string with actual values + $searchString = str_replace("#USERNAME#", $username, $searchString); + $searchString = str_replace("#BASE_DN#", $this->config->base, $searchString); + + $this->logger->Write("ldap search string after replacement of placeholders: $searchString", \LOG_NOTICE, self::LOG_KEY); + + try { + $mailAddressResults = $this->FindLdapResults( + $this->config->field_search, + $searchString, + $this->config->base, + $this->config->objectclass, + $this->config->field_name, + $this->config->field_username, + $this->config->field_domain, + false, + $this->config->field_mail_address_additional_account + ); + } + catch (LdapMailAccountsException $e) { + return false; // exceptions are only thrown from the handle error function that does logging already + } + + if (count($mailAddressResults) < 1) { + $this->logger->Write("Could not find user $username", \LOG_NOTICE, self::LOG_KEY); + return false; + } + + $aAccounts = $oActions->GetAccounts($oAccount); + + //Search for accounts with suffix " (LDAP)" at the end of the name that were created by this plugin and initially remove them from the + //account array. This only removes the visibility but does not delete the config done by the user. So if a user looses access to a + //mailbox the user will not see the account anymore but the configuration can be restored when the user regains access to it + foreach($aAccounts as $key => $aAccount) + { + if (preg_match("/\s\(LDAP\)$/", $aAccount['name'])) + { + unset($aAccounts[$key]); + } + } + + //SnappyMail saves the passwords of the additional accounts by encrypting them using a cryptkey that is saved in the file .cryptkey + //When the password of the main account changes, SnappyMail asks the user for the old password to reencrypt the keys with the new userpassword. + //On a password change using ldap (or when the password has been forgotten by the user) this makes us some problems. Therefore overwrite + //the .cryptkey file in order to always accept the actual ldap password of the user. This has side effects on pgp keys! + //See https://github.com/the-djmaze/snappymail/issues/1570#issuecomment-2085528061 + if ($this->config->bool_overwrite_cryptkey) { + if (!$oActions->StorageProvider()->Put($oAccount, StorageType::ROOT, '.cryptkey', "")) { + $this->logger->Write("Could not overwrite the .cryptkey file!", \LOG_WARNING, self::LOG_KEY); + return $oActions->FalseResponse(__FUNCTION__); + } + } + + if (count($mailAddressResults) == 1) { + $this->logger->Write("Found only one match for user $username, no additional mail adresses found", \LOG_NOTICE, self::LOG_KEY); + //Write back the accounts even if no additional account was found. This ensures, that previous additional accounts are always removed + $oActions->SetAccounts($oAccount, $aAccounts); + return true; + } + + foreach($mailAddressResults as $mailAddressResult) + { + $sUsername = $mailAddressResult->username; + $sDomain = $mailAddressResult->domain; + $sName = $mailAddressResult->name; + $sEmail = $mailAddressResult->mailAdditionalAccount; + + //Check if the domain of the found mail address is in the list of configured domains + if ($oActions->DomainProvider()->Load($sDomain, true)) + { + //only execute if the found account isn't already in the list of additional accounts + //and if the found account is different from the main account. + //The check if the address is different from the one of the main account when using the Nextcloud integration needs + //to be done twice: directly on the mail address (when Nextcloud is configured to log the user in by mail address) + //or on "$sUsername@$sDomain" for the case Nextcloud logs the user in to SnappyMail by his username and a default domain. + if (!isset($aAccounts[$sEmail]) && $oAccount->Email() !== $sEmail && $oAccount->Email() !== "$sUsername@$sDomain") + { + //Try to login the user with the same password as the primary account has + //if this fails the user will see the new mail addresses but will be asked for the correct password + $sPass = new \SnappyMail\SensitiveString($oAccount->IncPassword()); + //After creating the accounts here $sUsername is used as username to login to the IMAP server (see Account.php) + //$oNewAccount = RainLoop\Model\AdditionalAccount::NewInstanceFromCredentials($oActions, $sEmail, $sUsername, $sPass); + + $oDomain = $oActions->DomainProvider()->Load($sDomain, false); + + $oNewAccount = new AdditionalAccount; + $oNewAccount->setCredentials( + $oDomain, + $sEmail, + $sUsername, + $sPass, + $sUsername + ); + + $aAccounts[$sEmail] = $oNewAccount->asTokenArray($oAccount); + } + + //Always inject/update the found mailbox names into the array (also if the mailbox already existed) + if (isset($aAccounts[$sEmail])) + { + $aAccounts[$sEmail]['name'] = $sName . " (LDAP)"; + } + } + else { + $this->logger->Write("Domain $sDomain is not part of configured domains in SnappyMail Admin Panel - mail address $sEmail will not be added.", \LOG_NOTICE, self::LOG_KEY); + } + } + + if ($aAccounts) + { + $oActions->SetAccounts($oAccount, $aAccounts); + return true; + } + + return false; + } + + /** + * Checks if a connection to the LDAP was possible + * + * @throws LdapMailAccountsException + * + * */ + private function EnsureConnected(): void + { + if ($this->ldapConnected) return; + + $res = $this->Connect(); + if (!$res) + $this->HandleLdapError("Connect"); + } + + /** + * Connect to the LDAP using the server address and protocol version defined inside the configuration of the plugin + */ + private function Connect(): bool + { + // Set up connection + $ldap = @ldap_connect($this->config->server); + if ($ldap === false) { + $this->ldapAvailable = false; + return false; + } + + // Set protocol version + $option = @ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, $this->config->protocol); + if (!$option) { + $this->ldapAvailable = false; + return false; + } + + $this->ldap = $ldap; + $this->ldapConnected = true; + return true; + } + + /** + * Ensures the plugin has been authenticated at the LDAP + * + * @throws LdapMailAccountsException + * + * */ + private function EnsureBound(): void + { + if ($this->ldapBound) return; + $this->EnsureConnected(); + + $res = $this->Bind(); + if (!$res) + $this->HandleLdapError("Bind"); + } + + /** + * Authenticates the plugin at the LDAP using the username and password defined inside the configuration of the plugin + * + * @return bool true if authentication was successful + */ + private function Bind(): bool + { + // Bind to LDAP here + $bindResult = @ldap_bind($this->ldap, $this->config->bind_user, $this->config->bind_password); + if (!$bindResult) { + $this->ldapAvailable = false; + return false; + } + + $this->ldapBound = true; + return true; + } + + /** + * Handles and logs an eventual LDAP error + * + * @param string $op + * @throws LdapMailAccountsException + */ + private function HandleLdapError(string $op = ""): void + { + // Obtain LDAP error and write logs + $errorNo = @ldap_errno($this->ldap); + $errorMsg = @ldap_error($this->ldap); + + $message = empty($op) ? "LDAP Error: {$errorMsg} ({$errorNo})" : "LDAP Error during {$op}: {$errorMsg} ({$errorNo})"; + $this->logger->Write($message, \LOG_ERR, self::LOG_KEY); + throw new LdapMailAccountsException($message, $errorNo); + } + + /** + * Looks up the LDAP for additional mail accounts + * + * The search for additional mail accounts is done by a ldap search using the defined fields inside the configuration of the plugin (SnappyMail Admin Panel) + * + * @param string $searchField + * @param string $searchString + * @param string $searchBase + * @param string $objectClass + * @param string $nameField + * @param string $usernameField + * @param string $domainField + * @param bool $overwriteMailMainAccount true if the mail address of the main account should be looked up for overwriting. false if additional mail accounts should be searched + * @param string $mailAddressField The field containing the mail address (of main account or additional mail account) + * @return LdapMailAccountResult[] + * @throws LdapMailAccountsException + */ + private function FindLdapResults( + string $searchField, + string $searchString, + string $searchBase, + string $objectClass, + string $nameField, + string $usernameField, + string $domainField, + bool $overwriteMailMainAccount, + string $mailAddressField): array + { + $this->EnsureBound(); + $nameField = strtolower($nameField); + $usernameField = strtolower($usernameField); + $domainField = strtolower($domainField); + + $filter = "(&(objectclass=$objectClass)($searchField=$searchString))"; + $this->logger->Write("Used ldap filter to search for mail account(s): $filter", \LOG_NOTICE, self::LOG_KEY); + + //Set together the attributes to search inside the LDAP + $ldapAttributes = ['dn', $usernameField, $nameField, $domainField, $mailAddressField]; + + $ldapResult = @ldap_search($this->ldap, $searchBase, $filter, $ldapAttributes); + if (!$ldapResult) { + $this->HandleLdapError("Fetch $objectClass"); + return []; + } + + $entries = @ldap_get_entries($this->ldap, $ldapResult); + if (!$entries) { + $this->HandleLdapError("Fetch $objectClass"); + return []; + } + + // Save the found ldap entries into a LdapMailAccountResult object and return them + $results = []; + for ($i = 0; $i < $entries["count"]; $i++) { + $entry = $entries[$i]; + + $result = new LdapMailAccountResult(); + $result->dn = $entry["dn"]; + $result->name = $this->LdapGetAttribute($entry, $nameField, true, true); + + $result->username = $this->LdapGetAttribute($entry, $usernameField, true, true); + $result->username = $this->RemoveEventualDomainPart($result->username); + + $result->domain = $this->LdapGetAttribute($entry, $domainField, true, true); + $result->domain = $this->RemoveEventualLocalPart($result->domain); + + if($overwriteMailMainAccount) { + $result->mailMainAccount = $this->LdapGetAttribute($entry, $mailAddressField, true, true); + } + else { + $result->mailAdditionalAccount = $this->LdapGetAttribute($entry, $mailAddressField, true, true); + } + + $results[] = $result; + } + + return $results; + } + + /** + * Removes an eventually found domain-part of an email address + * + * If the input string contains an '@' character the function returns the local-part before the '@'\ + * If no '@' character can be found the input string is returned. + * + * @param string $sInput + * @return string + */ + public static function RemoveEventualDomainPart(string $sInput) : string + { + // Copy of \MailSo\Base\Utils::getEmailAddressLocalPart to make sure that also after eventual future + // updates the input string gets returned when no '@' is found (getEmailAddressDomain already doesn't do this) + $sResult = ''; + if (\strlen($sInput)) + { + $iPos = \strrpos($sInput, '@'); + $sResult = (false === $iPos) ? $sInput : \substr($sInput, 0, $iPos); + } + + return $sResult; + } + + + /** + * Removes an eventually found local-part of an email address + * + * If the input string contains an '@' character the function returns the domain-part behind the '@'\ + * If no '@' character can be found the input string is returned. + * + * @param string $sInput + * @return string + */ + public static function RemoveEventualLocalPart(string $sInput) : string + { + $sResult = ''; + if (\strlen($sInput)) + { + $iPos = \strrpos($sInput, '@'); + $sResult = (false === $iPos) ? $sInput : \substr($sInput, $iPos + 1); + } + + return $sResult; + } + + + /** + * Gets LDAP attributes out of the input array + * + * @param array $entry Array containing the result of a ldap search + * @param string $attribute The name of the attribute to return + * @param bool $single If true the function checks if exact one value for this attribute is inside the input array. If false an array is returned. Default true. + * @param bool $required If true the attribute has to exist inside the input array. Default false. + * @return string|string[] + */ + private function LdapGetAttribute(array $entry, string $attribute, bool $single = true, bool $required = false) + { + if (!isset($entry[$attribute])) { + if ($required) + $this->logger->Write("Attribute $attribute not found on object {$entry['dn']} while required", \LOG_NOTICE, self::LOG_KEY); + + return $single ? "" : []; + } + + if ($single) { + if ($entry[$attribute]["count"] > 1) + $this->logger->Write("Attribute $attribute is multivalues while only a single value is expected", \LOG_NOTICE, self::LOG_KEY); + + return $entry[$attribute][0]; + } + + $result = $entry[$attribute]; + unset($result["count"]); + return array_values($result); + } +} + +class LdapMailAccountResult +{ + /** @var string */ + public $dn; + + /** @var string */ + public $name; + + /** @var string */ + public $username; + + /** @var string */ + public $domain; + + /** @var string */ + public $mailMainAccount; + + /** @var string */ + public $mailAdditionalAccount; +} diff --git a/plugins/ldap-mail-accounts/LdapMailAccountsConfig.php b/plugins/ldap-mail-accounts/LdapMailAccountsConfig.php new file mode 100644 index 000000000..8b674e4f2 --- /dev/null +++ b/plugins/ldap-mail-accounts/LdapMailAccountsConfig.php @@ -0,0 +1,63 @@ +server = trim($config->Get("plugin", self::CONFIG_SERVER)); + $ldap->protocol = (int)trim($config->Get("plugin", self::CONFIG_PROTOCOL_VERSION, 3)); + $ldap->bind_user = trim($config->Get("plugin", self::CONFIG_BIND_USER)); + $ldap->bind_password = trim($config->Get("plugin", self::CONFIG_BIND_PASSWORD)); + $ldap->base = trim($config->Get("plugin", self::CONFIG_BASE)); + $ldap->objectclass = trim($config->Get("plugin", self::CONFIG_OBJECTCLASS)); + $ldap->field_name = trim($config->Get("plugin", self::CONFIG_FIELD_NAME)); + $ldap->field_search = trim($config->Get("plugin", self::CONFIG_FIELD_SEARCH)); + $ldap->field_username = trim($config->Get("plugin", self::CONFIG_FIELD_USERNAME)); + $ldap->search_string = trim($config->Get("plugin", self::CONFIG_SEARCH_STRING)); + $ldap->field_domain = trim($config->Get("plugin", self::CONFIG_FIELD_MAIL_DOMAIN)); + $ldap->field_mail_address_additional_account = trim($config->Get("plugin", self::CONFIG_FIELD_MAIL_ADDRESS_ADDITIONAL_ACCOUNT)); + $ldap->bool_overwrite_mail_address_main_account = $config->Get("plugin", self::CONFIG_BOOL_OVERWRITE_MAIL_ADDRESS_MAIN_ACCOUNT); + $ldap->field_mail_address_main_account = trim($config->Get("plugin", self::CONFIG_FIELD_MAIL_ADDRESS_MAIN_ACCOUNT)); + $ldap->bool_overwrite_cryptkey = $config->Get("plugin", self::CONFIG_BOOL_OVERWRITE_CRYPTKEY); + + return $ldap; + } +} \ No newline at end of file diff --git a/plugins/ldap-mail-accounts/LdapMailAccountsException.php b/plugins/ldap-mail-accounts/LdapMailAccountsException.php new file mode 100644 index 000000000..3135cc14b --- /dev/null +++ b/plugins/ldap-mail-accounts/LdapMailAccountsException.php @@ -0,0 +1,5 @@ + menu Extensions. +- Click on the gear symbol beside the plugin to open the configration dialog. + - Insert the connection data to access your LDAP. Leave username and password empty for an anonymous login. + - The fields `Object class`, `Base DN`, `Search field` and `LDAP search string` are used to put together a ldap search filter which will return the additional mail accounts of a user:\ + `(&(objectclass=)(=))`.\ + This filter will be executed on the `Base DN` you have defined. `LDAP search string` can contain the placeholders `#USERNAME#` (will be replaced with the username the user logged in to Snappymail) and `#BASE_DN#` (will be replaced with the value you inserted into the field `Base DN` inside the plugin settings). This will allow you to create more complex search strings like `uid=#USERNAME#`. + - `Username field`, `Domain name field of additional account`, `Mail address field for additional account` and `Additional account name field` are used to define the ldap attributes to read when the ldap search was successful. For example insert `mail` into the `Username field` and the `Domain name field of additional account` to use the [local-part](https://en.wikipedia.org/wiki/Email_address#Local-part) of the mail address as username and the [domain-part](https://en.wikipedia.org/wiki/Email_address#Domain) as domain for the additional account.\ + `Username field` and `Domain name field of additional account` before use get checked by the plugin if they contain a mail address and if true only the local-part or domain-part is returned. If no `@` is found the content of the found ldap attribute is returned without modification. This can be usefull if your user should login with something different than the mail address (a username that is diffrent from the local-part of the mail address). + + Section `Overwrite mail address of main account` can be used to overwrite the username or mail address used at login with a value found in ldap. If activated, the username or mail address used at login will be looked up inside the `Username field` in ldap (for details see how a search for additional accounts is made). If the username is found, the value of the field `Mail address field for main account` will be used to overwrite the mail address of the main account. + + `Overwrite user cryptkey` can be activated to prevent SnappyMail from asking the user for his old LDAP password when this password was changed or reseted. SnappyMail saves the passwords of the additional accounts by encrypting them using a cryptkey that is saved in the file `.cryptkey`. When the password of the main account changes, SnappyMail asks the user for the old password to reencrypt the keys with the new userpassword. + On a password change using ldap (or when the password has been forgotten by the user) this makes problems and asks the user to insert the old password. Therefore activating this option overwrites the .cryptkey file on login in order to always accept the actual ldap password of the user. + **ATTENTION:** This has side effects on pgp keys because these are also secured by the cryptkey and could therefore not be accessible anymore! See https://github.com/the-djmaze/snappymail/issues/1570#issuecomment-2085528061 . This has also an impact on additional mail accounts that aren't created by this plugin because without the cryptkey saved passwords of additional mail accounts can not be decrypted anymore. + +**Important:** SnappyMail normally needs a mail address as username. This plugin handles some special circumstances (login with an ldap username, not a mail address) so that you can login to your IMAP server with the ldap username but send mails with a mail address connected to this ldap user. diff --git a/plugins/ldap-mail-accounts/index.php b/plugins/ldap-mail-accounts/index.php new file mode 100644 index 000000000..bc53ad4f4 --- /dev/null +++ b/plugins/ldap-mail-accounts/index.php @@ -0,0 +1,192 @@ +addHook("login.success", 'AddAdditionalLdapMailAccounts'); + $this->addHook('login.credentials', 'overwriteMainAccountEmail'); + } + + // Function gets called by RainLoop/Actions/UserAuth.php + /** + * Overwrite the MainAccount mail address by looking up the new one in the ldap directory + * + * @param string &$sEmail + * @param string &$sImapUser + * @param string &$sPassword + * @param string &$sSmtpUser + */ + public function overwriteMainAccountEmail(string &$sEmail, string &$sImapUser, string &$sPassword, string &$sSmtpUser) + { + $this->Manager()->Actions()->Logger()->Write("Login DATA: login: $sImapUser email: $sEmail", \LOG_WARNING, "LDAP MAIL ACCOUNTS PLUGIN"); + + // Set up config + $config = LdapMailAccountsConfig::MakeConfig($this->Config()); + + if ($config->bool_overwrite_mail_address_main_account) + { + $oldapMailAccounts = new LdapMailAccounts($config, $this->Manager()->Actions()->Logger()); + $oldapMailAccounts->overwriteEmail($sEmail); + } + + $this->Manager()->Actions()->Logger()->Write("Login DATA: login: $sImapUser email: $sEmail", \LOG_WARNING, "LDAP MAIL ACCOUNTS PLUGIN"); + } + + // Function gets called by RainLoop/Actions/User.php + /** + * Add additional mail accounts to the webinterface of the user by looking up the ldap directory + * + * @param MainAccount $oAccount + */ + public function AddAdditionalLdapMailAccounts(MainAccount $oAccount) + { + // Set up config + $config = LdapMailAccountsConfig::MakeConfig($this->Config()); + $oldapMailAccounts = new LdapMailAccounts($config, $this->Manager()->Actions()->Logger()); + $oldapMailAccounts->AddLdapMailAccounts($oAccount); + } + + /** + * Defines the content of the plugin configuration page inside the Admin Panel of SnappyMail + */ + protected function configMapping(): array + { + $groupOverwriteMainAccount = new \RainLoop\Plugins\PropertyCollection('Overwrite mail address of main account'); + $groupOverwriteMainAccount->exchangeArray([ + \RainLoop\Plugins\Property::NewInstance(LdapMailAccountsConfig::CONFIG_BOOL_OVERWRITE_MAIL_ADDRESS_MAIN_ACCOUNT)->SetLabel('Enabled') + ->SetType(\RainLoop\Enumerations\PluginPropertyType::BOOL) + ->SetDefaultValue(false), + + \RainLoop\Plugins\Property::NewInstance(LdapMailAccountsConfig::CONFIG_FIELD_MAIL_ADDRESS_MAIN_ACCOUNT) + ->SetLabel("Mail address field for main account") + ->SetType(RainLoop\Enumerations\PluginPropertyType::STRING) + ->SetDescription("The ldap field containing the mail address to use on the SnappyMail main account. + \nThe value found inside ldap will overwrite the mail address of the SnappyMail main account (the account the user logged in at SnappyMail) + \nThe mail address used at login will still be used to login to the servers.") + ->SetDefaultValue("mail"), + ]); + + $groupAdditionalSettings = new \RainLoop\Plugins\PropertyCollection('Additional settings'); + $groupAdditionalSettings->exchangeArray([ + \RainLoop\Plugins\Property::NewInstance(LdapMailAccountsConfig::CONFIG_BOOL_OVERWRITE_CRYPTKEY)->SetLabel('Overwrite user cryptkey') + ->SetType(\RainLoop\Enumerations\PluginPropertyType::BOOL) + ->SetDescription("SnappyMail saves the passwords of the additional accounts by encrypting them using a cryptkey that is saved in the file \".cryptkey\". When the password of the main account changes, SnappyMail asks the user for the old password to reencrypt the keys with the new userpassword. + \nOn a password change using ldap (or when the password has been forgotten by the user) this makes problems and asks the user to insert the old password. Therefore activating this option overwrites the .cryptkey file on login in order to always accept the actual ldap password of the user. + \nATTENTION: This has side effects on pgp keys because these are also secured by the cryptkey and could therefore not be accessible anymore! + \nSee https://github.com/the-djmaze/snappymail/issues/1570#issuecomment-2085528061") + ->SetDefaultValue(false), + ]); + + return [ + \RainLoop\Plugins\Property::NewInstance(LdapMailAccountsConfig::CONFIG_SERVER) + ->SetLabel("LDAP Server URL") + ->SetPlaceholder("ldap://server:port") + ->SetType(RainLoop\Enumerations\PluginPropertyType::STRING), + + \RainLoop\Plugins\Property::NewInstance(LdapMailAccountsConfig::CONFIG_PROTOCOL_VERSION) + ->SetLabel("LDAP Protocol Version") + ->SetType(RainLoop\Enumerations\PluginPropertyType::SELECTION) + ->SetDefaultValue([2, 3]), + + \RainLoop\Plugins\Property::NewInstance(LdapMailAccountsConfig::CONFIG_BIND_USER) + ->SetLabel("LDAP Username") + ->SetDescription("The user to use for binding to the LDAP server. Should be a DN or RDN. Leave empty for anonymous bind.") + ->SetType(RainLoop\Enumerations\PluginPropertyType::STRING), + + \RainLoop\Plugins\Property::NewInstance(LdapMailAccountsConfig::CONFIG_BIND_PASSWORD) + ->SetLabel("LDAP Password") + ->SetDescription("Leave empty for anonymous bind.") + ->SetType(RainLoop\Enumerations\PluginPropertyType::PASSWORD), + + \RainLoop\Plugins\Property::NewInstance(LdapMailAccountsConfig::CONFIG_OBJECTCLASS) + ->SetLabel("Object class") + ->SetType(RainLoop\Enumerations\PluginPropertyType::STRING) + ->SetDescription("The object class to use when searching for additional mail accounts of the logged in SnappyMail user") + ->SetDefaultValue("user"), + + \RainLoop\Plugins\Property::NewInstance(LdapMailAccountsConfig::CONFIG_BASE) + ->SetLabel("Base DN") + ->SetType(RainLoop\Enumerations\PluginPropertyType::STRING) + ->SetDescription("The base DN to search in for additional mail accounts of the logged in SnappyMail user"), + + \RainLoop\Plugins\Property::NewInstance(LdapMailAccountsConfig::CONFIG_FIELD_SEARCH) + ->SetLabel("Search field") + ->SetType(RainLoop\Enumerations\PluginPropertyType::STRING) + ->SetDescription("The name of the ldap attribute that has to contain the here defined 'LDAP search string'.") + ->SetDefaultValue("member"), + + \RainLoop\Plugins\Property::NewInstance(LdapMailAccountsConfig::CONFIG_SEARCH_STRING) + ->SetLabel("LDAP search string") + ->SetType(RainLoop\Enumerations\PluginPropertyType::STRING) + ->SetDescription("The search string used to find ldap objects of mail accounts the user has access to. + \nPossible placeholers:\n#USERNAME# - replaced with the username of the actual SnappyMail user + \n#BASE_DN# - replaced with the value inside the field 'User base DN'.") + ->SetDefaultValue("uid=#USERNAME#"), + + \RainLoop\Plugins\Property::NewInstance(LdapMailAccountsConfig::CONFIG_FIELD_USERNAME) + ->SetLabel("Username field") + ->SetType(RainLoop\Enumerations\PluginPropertyType::STRING) + ->SetDescription("Used when searching for additional accounts or when overwriting the mail address of the main account. + \nThe field containing the username of the mail account. + \nWhen looking up additional accounts: + \nIf this field contains an email address, only the local-part before the @ is used. The domain part is retrieved configuring the field below. This username gets used by SnappyMail to login to the additional mail account + \nWhen overwriting the main account mail address: + \nThe username from SnappyMail login gets used to search an LDAP entry containig a field with the same username.") + ->SetDefaultValue("uid"), + + \RainLoop\Plugins\Property::NewInstance(LdapMailAccountsConfig::CONFIG_FIELD_MAIL_DOMAIN) + ->SetLabel("Domain name field of additional account") + ->SetType(RainLoop\Enumerations\PluginPropertyType::STRING) + ->SetDescription("The field containing the domain name of the found additional mail account. + \nThis domain gets looked up by SnappyMail to choose the right connection parameters at logging in to the additional mail account. + \nIf this field contains an email address, only the domain-part after the @ is used.") + ->SetDefaultValue("mail"), + + \RainLoop\Plugins\Property::NewInstance(LdapMailAccountsConfig::CONFIG_FIELD_MAIL_ADDRESS_ADDITIONAL_ACCOUNT) + ->SetLabel("Mail address field for additional account") + ->SetType(RainLoop\Enumerations\PluginPropertyType::STRING) + ->SetDescription("The ldap field containing the mail address to use on the found additional mail account. + \nThe value found inside ldap will be used as mail address of the additional mail accounts created by this plugin. + \nIn most cases this could be the same ldap field as in \"Domain name field of additional account\"") + ->SetDefaultValue("mail"), + + \RainLoop\Plugins\Property::NewInstance(LdapMailAccountsConfig::CONFIG_FIELD_NAME) + ->SetLabel("Additional account name field") + ->SetType(RainLoop\Enumerations\PluginPropertyType::STRING) + ->SetDescription("The field containing the default sender name of the found additional mail account.") + ->SetDefaultValue("displayName"), + + $groupOverwriteMainAccount, + + $groupAdditionalSettings + ]; + } +} diff --git a/plugins/login-autoconfig/LICENSE b/plugins/login-autoconfig/LICENSE new file mode 100644 index 000000000..61aa05084 --- /dev/null +++ b/plugins/login-autoconfig/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2024 SnappyMail + +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/plugins/login-autoconfig/index.php b/plugins/login-autoconfig/index.php new file mode 100644 index 000000000..ba23a9b92 --- /dev/null +++ b/plugins/login-autoconfig/index.php @@ -0,0 +1,78 @@ +addHook('login.credentials.step-1', 'detect'); + } + + public function detect(string $sEmail) : void + { + if (\str_contains($sEmail, '@')) { + $oProvider = $this->Manager()->Actions()->DomainProvider(); + $sDomain = \MailSo\Base\Utils::getEmailAddressDomain($sEmail); + $oDomain = $oProvider->Load($sDomain, false); + if (!$oDomain) { + $result = \RainLoop\Providers\Domain\Autoconfig::discover($sEmail); + if ($result) { + $typeIMAP = ConnectionSecurityType::AUTO_DETECT; + if ('STARTTLS' === $result['incomingServer'][0]['socketType']) { + $typeIMAP = ConnectionSecurityType::STARTTLS; + } else if ('SSL' === $result['incomingServer'][0]['socketType']) { + $typeIMAP = ConnectionSecurityType::SSL; + } + $typeSMTP = ConnectionSecurityType::AUTO_DETECT; + if ('STARTTLS' === $result['outgoingServer'][0]['socketType']) { + $typeSMTP = ConnectionSecurityType::STARTTLS; + } else if ('SSL' === $result['outgoingServer'][0]['socketType']) { + $typeSMTP = ConnectionSecurityType::SSL; + } + $oDomain = \RainLoop\Model\Domain::fromArray($sDomain, [ + 'IMAP' => [ + 'host' => $result['incomingServer'][0]['hostname'], + 'port' => $result['incomingServer'][0]['port'], + 'type' => $typeIMAP, + 'shortLogin' => '%EMAILADDRESS%' !== $result['incomingServer'][0]['username'], +// 'ssl' => [] + ], + 'SMTP' => [ + 'host' => $result['outgoingServer'][0]['hostname'], + 'port' => $result['outgoingServer'][0]['port'], + 'type' => $typeSMTP, + 'shortLogin' => '%EMAILADDRESS%' !== $result['outgoingServer'][0]['username'], +// 'useAuth' => !empty($result['authentication']), + ], + 'Sieve' => [ + 'host' => $result['incomingServer'][0]['hostname'], + 'port' => $result['incomingServer'][0]['port'], + 'type' => $typeIMAP, + 'shortLogin' => '%EMAILADDRESS%' !== $result['incomingServer'][0]['username'], + 'enabled' => false + ], + 'whiteList' => '' + ]); + $oProvider->Save($oDomain); + \SnappyMail\Log::notice('Autoconfig', "Domain setup for '{$sDomain}' is created and active"); + } + } + } + } + +} diff --git a/plugins/login-cpanel/LICENSE b/plugins/login-cpanel/LICENSE new file mode 100644 index 000000000..f709b02e2 --- /dev/null +++ b/plugins/login-cpanel/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2016 RainLoop Team + +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/plugins/login-cpanel/index.php b/plugins/login-cpanel/index.php new file mode 100644 index 000000000..9bc5ebf7a --- /dev/null +++ b/plugins/login-cpanel/index.php @@ -0,0 +1,77 @@ +addPartHook('cPanelAutoLogin', 'AutoLogin'); + $this->addHook('filter.app-data', 'FilterAppData'); + $this->addHook('login.credentials', 'FilterLoginCredentials'); + } + + public function FilterAppData($bAdmin, &$aResult) + { + if (!$bAdmin && \is_array($aResult) && empty($aResult['Auth']) && isset($_ENV['REMOTE_USER'])) { + $aResult['DevEmail'] = $_ENV['REMOTE_USER']; +// $aResult['DevPassword'] = $_ENV['REMOTE_PASSWORD']; + } + } + + private static bool $login = false; + public function AutoLogin() : bool + { + $oActions = \RainLoop\Api::Actions(); + + $oException = null; + $oAccount = null; + + $sEmail = $_ENV['REMOTE_USER'] ?? ''; + $sPassword = $_ENV['REMOTE_PASSWORD'] ?? ''; + + if (\strlen($sEmail) && \strlen($sPassword)) { + try + { + static::$login = true; + $oAccount = $oActions->LoginProcess($sEmail, $sPassword); + } + catch (\Throwable $oException) + { + $oLogger = $oActions->Logger(); + $oLogger && $oLogger->WriteException($oException); + } + } + + \MailSo\Base\Http::Location('./'); + return true; + } + + public function FilterLoginCredentials(&$sEmail, &$sImapUser, &$sPassword, &$sSmtpUser) + { + // cPanel https://github.com/the-djmaze/snappymail/issues/697 +// && !empty($_ENV['CPANEL']) + if (static::$login/* && $sImapUser == $_ENV['REMOTE_USER']*/) { + if (empty($_ENV['REMOTE_TEMP_USER'])) { + $iPos = \strpos($sPassword, '[::cpses::]'); + if ($iPos) { + $_ENV['REMOTE_TEMP_USER'] = \substr($sPassword, 0, $iPos); + } + } + if (!empty($_ENV['REMOTE_TEMP_USER'])) { + $sImapUser = $_ENV['REMOTE_USER'] . '/' . $_ENV['REMOTE_TEMP_USER']; + $sSmtpUser = $_ENV['REMOTE_USER'] . '/' . $_ENV['REMOTE_TEMP_USER']; + } + } + } + +} diff --git a/plugins/login-external-sso/LICENSE b/plugins/login-external-sso/LICENSE new file mode 100644 index 000000000..f709b02e2 --- /dev/null +++ b/plugins/login-external-sso/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2016 RainLoop Team + +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/plugins/login-external-sso/index.php b/plugins/login-external-sso/index.php new file mode 100644 index 000000000..f3a215b04 --- /dev/null +++ b/plugins/login-external-sso/index.php @@ -0,0 +1,56 @@ +addPartHook('ExternalSso', 'ServiceExternalSso'); + } + + public function ServiceExternalSso() : string + { + $oActions = \RainLoop\Api::Actions(); + $oActions->Http()->ServerNoCache(); + $sKey = $this->Config()->Get('plugin', 'key', ''); + $sEmail = isset($_POST['Email']) ? $_POST['Email'] : ''; + $sPassword = isset($_POST['Password']) ? $_POST['Password'] : ''; + if ($sEmail && $sPassword && $sKey && isset($_POST['SsoKey']) && $_POST['SsoKey'] == $sKey) { + $sResult = \RainLoop\Api::CreateUserSsoHash($sEmail, $sPassword); + if (isset($_POST['Output']) && 'json' === \strtolower($_POST['Output'])) { + \header('Content-Type: application/json; charset=utf-8'); + echo \json_encode(array( + 'Action' => 'ExternalSso', + 'Result' => $sResult + )); + } else { + \header('Content-Type: text/plain'); + echo $sResult; + } + } + return true; + } + + /** + * @return array + */ + public function configMapping() : array + { + return array( + // Was application.ini external_sso_key + \RainLoop\Plugins\Property::NewInstance('key')->SetLabel('SSO key') + ->SetDefaultValue(''), + ); + } + +} diff --git a/plugins/login-external/LICENSE b/plugins/login-external/LICENSE new file mode 100644 index 000000000..f709b02e2 --- /dev/null +++ b/plugins/login-external/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2016 RainLoop Team + +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/plugins/login-external/index.php b/plugins/login-external/index.php new file mode 100644 index 000000000..9929d5b2e --- /dev/null +++ b/plugins/login-external/index.php @@ -0,0 +1,69 @@ +addPartHook('ExternalLogin', 'ServiceExternalLogin'); + } + + public function ServiceExternalLogin() : bool + { + $oActions = \RainLoop\Api::Actions(); + $oActions->Http()->ServerNoCache(); + + $oAccount = null; + $oException = null; + + $sEmail = isset($_POST['Email']) ? $_POST['Email'] : ''; + $sPassword = isset($_POST['Password']) ? $_POST['Password'] : ''; + + try + { + // Convert password to SensitiveString type + $oPassword = new \SnappyMail\SensitiveString($sPassword); + $oAccount = $oActions->LoginProcess($sEmail, $oPassword); + if (!$oAccount instanceof \RainLoop\Model\MainAccount) { + $oAccount = null; + \SnappyMail\LOG::info(\get_class($this), 'LoginProcess failed'); + } + } + catch (\Throwable $oException) + { + $oLogger = $oActions->Logger(); + $oLogger && $oLogger->WriteException($oException); + } + + if (isset($_POST['Output']) && 'json' === \strtolower($_POST['Output'])) { + \header('Content-Type: application/json; charset=utf-8'); + $aResult = array( + 'Action' => 'ExternalLogin', + 'Result' => $oAccount ? true : false, + 'ErrorCode' => 0 + ); + if (!$oAccount) { + if ($oException instanceof \RainLoop\Exceptions\ClientException) { + $aResult['ErrorCode'] = $oException->getCode(); + } else { + $aResult['ErrorCode'] = \RainLoop\Notifications::AuthError; + } + } + echo \json_encode($aResult); + } else { + \MailSo\Base\Http::Location('./'); + } + return true; + } + +} diff --git a/plugins/login-gmail/LoginOAuth2.js b/plugins/login-gmail/LoginOAuth2.js new file mode 100644 index 000000000..efee7ad60 --- /dev/null +++ b/plugins/login-gmail/LoginOAuth2.js @@ -0,0 +1,46 @@ +(rl => { + const client_id = rl.pluginSettingsGet('login-gmail', 'client_id'), + login = () => { + document.location = 'https://accounts.google.com/o/oauth2/auth?' + (new URLSearchParams({ + response_type: 'code', + client_id: client_id, + redirect_uri: document.location.href + '?LoginGMail', + scope: [ + // Primary Google Account email address + 'https://www.googleapis.com/auth/userinfo.email', + // Personal info + 'https://www.googleapis.com/auth/userinfo.profile', + // Associate personal info + 'openid', + // Access IMAP and SMTP through OAUTH + 'https://mail.google.com/' + ].join(' '), + state: 'gmail', // + rl.settings.app('token') + localStorage.getItem('smctoken') + // Force authorize screen, so we always get a refresh_token + access_type: 'offline', + prompt: 'consent' + })); + }; + + if (client_id) { + addEventListener('sm-user-login', e => { + if (event.detail.get('Email').includes('@gmail.com')) { + e.preventDefault(); + login(); + } + }); + + addEventListener('rl-view-model', e => { + if ('Login' === e.detail.viewModelTemplateID) { + const + container = e.detail.viewModelDom.querySelector('#plugin-Login-BottomControlGroup'), + btn = Element.fromHTML(''), + div = Element.fromHTML('
'); + btn.onclick = login; + div.append(btn); + container && container.append(div); + } + }); + } + +})(window.rl); diff --git a/plugins/login-gmail/index.php b/plugins/login-gmail/index.php new file mode 100644 index 000000000..a6b8d3f9d --- /dev/null +++ b/plugins/login-gmail/index.php @@ -0,0 +1,223 @@ +UseLangs(true); + $this->addJs('LoginOAuth2.js'); + $this->addHook('imap.before-login', 'clientLogin'); + $this->addHook('smtp.before-login', 'clientLogin'); + $this->addHook('sieve.before-login', 'clientLogin'); + + $this->addPartHook('LoginGMail', 'ServiceLoginGMail'); + + // Prevent Disallowed Sec-Fetch Dest: document Mode: navigate Site: cross-site User: true + $this->addHook('filter.http-paths', 'httpPaths'); + } + + public function httpPaths(array $aPaths) : void + { + if (!empty($aPaths[0]) && 'LoginGMail' === $aPaths[0]) { + $oConfig = \RainLoop\Api::Config(); + $oConfig->Set('security', 'secfetch_allow', + \trim($oConfig->Get('security', 'secfetch_allow', '') . ';site=cross-site', ';') + ); + } + } + + public function ServiceLoginGMail() : string + { + $oActions = \RainLoop\Api::Actions(); + $oHttp = $oActions->Http(); + $oHttp->ServerNoCache(); + + $uri = \preg_replace('/.LoginGMail.*$/D', '', $_SERVER['REQUEST_URI']); + + try + { + if (isset($_GET['error'])) { + throw new \RuntimeException($_GET['error']); + } + if (isset($_GET['code']) && isset($_GET['state']) && 'gmail' === $_GET['state']) { + $oGMail = $this->gmailConnector(); + } + if (empty($oGMail)) { + $oActions->Location($uri); + exit; + } + + $iExpires = \time(); + $aResponse = $oGMail->getAccessToken( + static::TOKEN_URI, + 'authorization_code', + array( + 'code' => $_GET['code'], + 'redirect_uri' => $oHttp->GetFullUrl().'?LoginGMail' + ) + ); + if (200 != $aResponse['code']) { + if (isset($aResponse['result']['error'])) { + throw new \RuntimeException( + $aResponse['code'] + . ': ' + . $aResponse['result']['error'] + . ' / ' + . $aResponse['result']['error_description'] + ); + } + throw new \RuntimeException("HTTP: {$aResponse['code']}"); + } + $aResponse = $aResponse['result']; + if (empty($aResponse['access_token'])) { + throw new \RuntimeException('access_token missing'); + } + if (empty($aResponse['refresh_token'])) { + throw new \RuntimeException('refresh_token missing'); + } + + $sAccessToken = $aResponse['access_token']; + $iExpires += $aResponse['expires_in']; + + $oGMail->setAccessToken($sAccessToken); + $aUserInfo = $oGMail->fetch('https://www.googleapis.com/oauth2/v2/userinfo'); + if (200 != $aUserInfo['code']) { + throw new \RuntimeException("HTTP: {$aResponse['code']}"); + } + $aUserInfo = $aUserInfo['result']; + if (empty($aUserInfo['id'])) { + throw new \RuntimeException('unknown id'); + } + if (empty($aUserInfo['email'])) { + throw new \RuntimeException('unknown email address'); + } + + static::$auth = [ + 'access_token' => $sAccessToken, + 'refresh_token' => $aResponse['refresh_token'], + 'expires_in' => $aResponse['expires_in'], + 'expires' => $iExpires + ]; + + $oPassword = new \SnappyMail\SensitiveString($aUserInfo['id']); + $oAccount = $oActions->LoginProcess($aUserInfo['email'], $oPassword); +// $oAccount = MainAccount::NewInstanceFromCredentials($oActions, $aUserInfo['email'], $aUserInfo['email'], $oPassword, true); + if ($oAccount) { +// $oActions->SetMainAuthAccount($oAccount); +// $oActions->SetAuthToken($oAccount); + $oActions->StorageProvider()->Put($oAccount, StorageType::SESSION, \RainLoop\Utils::GetSessionToken(), + \SnappyMail\Crypt::EncryptToJSON(static::$auth, $oAccount->CryptKey()) + ); + } + } + catch (\Exception $oException) + { + $oActions->Logger()->WriteException($oException, \LOG_ERR); + } + $oActions->Location($uri); + exit; + } + + public function configMapping() : array + { + return [ + \RainLoop\Plugins\Property::NewInstance('client_id') + ->SetLabel('Client ID') + ->SetType(\RainLoop\Enumerations\PluginPropertyType::STRING) + ->SetAllowedInJs() + ->SetDescription('https://github.com/the-djmaze/snappymail/wiki/FAQ#gmail'), + \RainLoop\Plugins\Property::NewInstance('client_secret') + ->SetLabel('Client Secret') + ->SetType(\RainLoop\Enumerations\PluginPropertyType::STRING) + ->SetEncrypted() + ]; + } + + public function clientLogin(\RainLoop\Model\Account $oAccount, \MailSo\Net\NetClient $oClient, \MailSo\Net\ConnectSettings $oSettings) : void + { + if ($oAccount instanceof MainAccount && \str_ends_with($oAccount->Email(), '@gmail.com')) { + $oActions = \RainLoop\Api::Actions(); + try { + $aData = static::$auth ?: \SnappyMail\Crypt::DecryptFromJSON( + $oActions->StorageProvider()->Get($oAccount, StorageType::SESSION, \RainLoop\Utils::GetSessionToken()), + $oAccount->CryptKey() + ); + } catch (\Throwable $oException) { +// $oActions->Logger()->WriteException($oException, \LOG_ERR); + return; + } + if (!empty($aData['expires']) && !empty($aData['access_token']) && !empty($aData['refresh_token'])) { + if (\time() >= $aData['expires']) { + $iExpires = \time(); + $oGMail = $this->gmailConnector(); + if ($oGMail) { + $aRefreshTokenResponse = $oGMail->getAccessToken( + static::TOKEN_URI, + 'refresh_token', + array('refresh_token' => $aData['refresh_token']) + ); + if (!empty($aRefreshTokenResponse['result']['access_token'])) { + $aData['access_token'] = $aRefreshTokenResponse['result']['access_token']; + $aResponse['expires'] = $iExpires + $aResponse['expires_in']; + $oActions->StorageProvider()->Put($oAccount, StorageType::SESSION, \RainLoop\Utils::GetSessionToken(), + \SnappyMail\Crypt::EncryptToJSON($aData, $oAccount->CryptKey()) + ); + } + } + } + $oSettings->passphrase = $aData['access_token']; + \array_unshift($oSettings->SASLMechanisms, 'OAUTHBEARER', 'XOAUTH2'); + } + } + } + + protected function gmailConnector() : ?\OAuth2\Client + { + $client_id = \trim($this->Config()->Get('plugin', 'client_id', '')); + $client_secret = \trim($this->Config()->getDecrypted('plugin', 'client_secret', '')); + if ($client_id && $client_secret) { + try + { + $oGMail = new \OAuth2\Client($client_id, $client_secret); + $oActions = \RainLoop\Api::Actions(); + $sProxy = $oActions->Config()->Get('labs', 'curl_proxy', ''); + if (\strlen($sProxy)) { + $oGMail->setCurlOption(CURLOPT_PROXY, $sProxy); + $sProxyAuth = $oActions->Config()->Get('labs', 'curl_proxy_auth', ''); + if (\strlen($sProxyAuth)) { + $oGMail->setCurlOption(CURLOPT_PROXYUSERPWD, $sProxyAuth); + } + } + return $oGMail; + } + catch (\Exception $oException) + { + $oActions->Logger()->WriteException($oException, \LOG_ERR); + } + } + return null; + } +} diff --git a/plugins/login-http/LICENSE b/plugins/login-http/LICENSE new file mode 100644 index 000000000..f709b02e2 --- /dev/null +++ b/plugins/login-http/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2016 RainLoop Team + +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/plugins/login-http/index.php b/plugins/login-http/index.php new file mode 100644 index 000000000..9b53c0cb5 --- /dev/null +++ b/plugins/login-http/index.php @@ -0,0 +1,39 @@ +addPartHook('ExternalHTTP', 'ServiceExternalHTTP'); + } + + public function ServiceExternalHTTP() : string + { + $oActions = \RainLoop\Api::Actions(); + $oActions->Http()->ServerNoCache(); + $sUser=$_SERVER['PHP_AUTH_USER'] ?? ''; + $sPassword=$_SERVER['PHP_AUTH_PW'] ?? ''; + try { + $oAccount = $oActions->LoginProcess($sUser, new \SnappyMail\SensitiveString($sPassword)); + if ($oAccount) { + \MailSo\Base\Http::Location('./'); + return true; + } + } catch (\Throwable $e) { + // Log l'erreur si besoin + } + \MailSo\Base\Http::Location('./?ExternalHTTP'); + return true; + } +} diff --git a/plugins/login-o365/LoginOAuth2.js b/plugins/login-o365/LoginOAuth2.js new file mode 100644 index 000000000..392c0e7b1 --- /dev/null +++ b/plugins/login-o365/LoginOAuth2.js @@ -0,0 +1,91 @@ +((rl) => { + const client_id = rl.pluginSettingsGet("login-o365", "client_id"), + allowAnyDomain = !!rl.pluginSettingsGet("login-o365", "allow_any_domain"), + isSupportedEmail = (email) => { + email = (email || "").toLowerCase(); + if (!email.includes("@")) return false; + if (allowAnyDomain) return true; + return /@(outlook\.com|hotmail\.com|live\.com)$/.test(email); + }, + startOAuth = (op, opts = {}) => { + const email = (opts.email || "").toLowerCase(); + const name = opts.name || ""; + const returnHash = opts.return || ""; + + // Server mints a signed state + correct redirect_uri and returns full authUrl. + rl.pluginRemoteRequest((iError, data) => { + const url = data?.Result?.authUrl; + if (!iError && url) { + document.location = url; + } + }, "LoginO365AuthUrl", { + op: op, + email: email, + name: name, + return: returnHash, + }); + }; + + if (client_id) { + addEventListener("sm-user-login", (e) => { + const email = (e.detail.get("Email") || "").toLowerCase(); + if (isSupportedEmail(email)) { + e.preventDefault(); + startOAuth("login", { email }); + } + }); + + addEventListener("rl-view-model", (e) => { + if ("Login" === e.detail.viewModelTemplateID) { + const + container = e.detail.viewModelDom.querySelector("#plugin-Login-BottomControlGroup"), + btn = Element.fromHTML(''), + div = Element.fromHTML('
'); + btn.onclick = () => { + // Best-effort: try to read the email field if present. + const input = e.detail.viewModelDom.querySelector('input[type="email"], input[name="Email"], input[name="email"], input'); + const email = (input?.value || "").toLowerCase(); + if (!email || isSupportedEmail(email)) { + startOAuth("login", { email }); + } + }; + div.append(btn); + container && container.append(div); + } + + // "Add account" popup (Settings → Accounts → Add account) + if ("PopupsAccount" === e.detail.viewModelTemplateID) { + // Only for the "Add account" mode, not "Edit account". + if (typeof e.detail.isNew === "function" && !e.detail.isNew()) { + return; + } + const root = e.detail.viewModelDom; + if (!root) return; + + const footer = root.querySelector("footer"); + const form = root.querySelector("#accountform"); + const addButton = root.querySelector("button.buttonAddAccount"); + if (!footer || !form || !addButton) return; + + // Avoid inserting duplicates when view model is re-rendered. + if (root.querySelector(".plugin-o365-add-account")) return; + + const btn = Element.fromHTML( + '' + ); + + btn.onclick = () => { + const email = (form.querySelector('input[name="email"]')?.value || "").trim().toLowerCase(); + const name = (form.querySelector('input[name="name"]')?.value || "").trim(); + if (!email || !isSupportedEmail(email)) { + return; + } + startOAuth("add", { email, name, return: document.location.hash || "#/settings/accounts" }); + }; + + // Put the button next to the default Add Account submit button. + footer.insertBefore(btn, addButton.nextSibling); + } + }); + } +})(window.rl); diff --git a/plugins/login-o365/index.php b/plugins/login-o365/index.php new file mode 100644 index 000000000..bb8ae7b69 --- /dev/null +++ b/plugins/login-o365/index.php @@ -0,0 +1,695 @@ + ['access_token'=>..., 'refresh_token'=>..., 'expires'=>..., 'expires_in'=>...], + * ... + * ] + */ + private static array $auth = []; + + public function Init() : void + { + $this->UseLangs(true); + $this->addJs('LoginOAuth2.js'); + $this->addHook('imap.before-login', 'clientLogin'); + $this->addHook('smtp.before-login', 'clientLogin'); + $this->addHook('sieve.before-login', 'clientLogin'); + + $this->addPartHook('LoginO365', 'ServiceLoginO365'); + // Used by JS to obtain an auth URL with signed state (for both login + add-account flows). + $this->addJsonHook('LoginO365AuthUrl', 'DoLoginO365AuthUrl'); + + // Prevent Disallowed Sec-Fetch Dest: document Mode: navigate Site: cross-site User: true + $this->addHook('filter.http-paths', 'httpPaths'); + + // Cleanup: when an additional account is removed, also remove its encrypted refresh token bundle. + $this->addHook('json.after-AccountDelete', 'afterAccountDelete'); + } + + public function httpPaths(array &$aPaths) : void + { + if (!empty($_SERVER['PATH_INFO']) && \str_ends_with($_SERVER['PATH_INFO'], 'LoginO365')) { + $aPaths = ['LoginO365']; + } + + if (!empty($aPaths[0]) && 'LoginO365' === $aPaths[0]) { + $oConfig = \RainLoop\Api::Config(); + $oConfig->Set('security', 'secfetch_allow', + \trim($oConfig->Get('security', 'secfetch_allow', '') . ';site=cross-site', ';') + ); + } + } + + public function ServiceLoginO365() : string + { + $oActions = \RainLoop\Api::Actions(); + $oHttp = $oActions->Http(); + $oHttp->ServerNoCache(); + + try + { + if (isset($_GET['error'])) { + $desc = $_GET['error_description'] ?? ''; + throw new \RuntimeException("{$_GET['error']}: {$desc}"); + } + + // Must have code + state + if (!isset($_GET['code']) || empty($_GET['state'])) { + $oActions->Location(\RainLoop\Utils::WebPath()); + exit; + } + + $oO365 = $this->o365Connector(); + if (!$oO365) { + $oActions->Location(\RainLoop\Utils::WebPath()); + exit; + } + + $iNow = \time(); + + $redirectUri = $this->redirectUri(); + + $tenant = $this->Config()->Get('plugin', 'tenant', 'common'); + + $state = (string) $_GET['state']; + $statePayload = $this->verifyAndConsumeState($state); + if (!$statePayload) { + $oActions->Location(\RainLoop\Utils::WebPath()); + exit; + } + + $aTokenWrap = $oO365->getAccessToken( + \str_replace('{{tenant}}', $tenant, static::TOKEN_URI), + 'authorization_code', + [ + 'code' => $_GET['code'], + 'redirect_uri' => $redirectUri + ] + ); + + if (!\is_array($aTokenWrap) || !isset($aTokenWrap['code'])) { + throw new \RuntimeException('Token request failed: ' . \json_encode($aTokenWrap)); + } + if (200 !== (int)$aTokenWrap['code']) { + $err = $aTokenWrap['result']['error'] ?? ''; + $desc = $aTokenWrap['result']['error_description'] ?? ''; + throw new \RuntimeException("Token HTTP {$aTokenWrap['code']}: {$err} / {$desc}"); + } + + $aToken = $aTokenWrap['result'] ?? []; + $accessToken = $aToken['access_token'] ?? ''; + $refreshToken = $aToken['refresh_token'] ?? ''; + $expiresIn = (int)($aToken['expires_in'] ?? 0); + $idToken = $aToken['id_token'] ?? ''; + + if ($accessToken === '') { + throw new \RuntimeException('access_token missing'); + } + + if ($refreshToken === '') { + throw new \RuntimeException('refresh_token missing'); + } + if ($idToken === '') { + // We rely on id_token to get email/sub without Graph. + throw new \RuntimeException('id_token missing (add openid email profile scopes)'); + } + + // Parse id_token (JWT) to get identity (sub + email) + $claims = $this->decodeJwtPayload($idToken); + if (!\is_array($claims)) { + throw new \RuntimeException('Cannot decode id_token payload'); + } + + $email = $claims['email'] ?? ($claims['preferred_username'] ?? ($claims['upn'] ?? '')); + $sub = $claims['sub'] ?? ''; + + if ($sub === '') { + throw new \RuntimeException('unknown id from id_token'); + } + if ($email === '') { + throw new \RuntimeException('unknown email address from id_token'); + } + + if (!$this->isSupportedEmail(\strtolower($email))) { + throw new \RuntimeException('Unsupported email domain for this plugin'); + } + + $tokenBundle = [ + 'access_token' => $accessToken, + 'refresh_token' => $refreshToken, + 'expires_in' => $expiresIn, + 'expires' => $iNow + $expiresIn + ]; + + $op = $statePayload['op'] ?? 'login'; + if ('add' === $op) { + $oMainAccount = $oActions->getMainAccountFromToken(false); + if (!$oMainAccount) { + throw new \RuntimeException('Add-account flow requires logged in main account'); + } + if (!empty($statePayload['main']) && $statePayload['main'] !== $oMainAccount->Email()) { + throw new \RuntimeException('Add-account state does not match current main account'); + } + + // Store token bundle encrypted with MAIN account crypt key (never store refresh_token unencrypted). + // This is later used by imap/smtp/sieve.before-login for *additional* accounts. + $this->storeAccountTokens($oMainAccount, $email, $tokenBundle); + + // Create/validate an AdditionalAccount entry exactly like SnappyMail expects in "additionalaccounts". + // We set the "password" to the OAuth subject (sub) as an opaque secret; the plugin will inject XOAUTH2. + $oPassword = new \SnappyMail\SensitiveString($sub); + $oAdditional = $oActions->LoginProcess($email, $oPassword, false); + if (!$oAdditional instanceof \RainLoop\Model\AdditionalAccount) { + throw new \RuntimeException('Failed to create additional account'); + } + + $asciiEmail = \SnappyMail\IDN::emailToAscii($oAdditional->Email()); + if ($asciiEmail === $oMainAccount->Email()) { + throw new \RuntimeException('Cannot add main account as additional'); + } + + $aAccounts = $oActions->GetAccounts($oMainAccount); + $aEntry = $oAdditional->asTokenArray($oMainAccount); + if (!empty($statePayload['name']) && \is_string($statePayload['name'])) { + $aEntry['name'] = \trim($statePayload['name']); + } else if (isset($aAccounts[$asciiEmail]['name'])) { + // Preserve previous custom label if re-adding/updating. + $aEntry['name'] = (string) $aAccounts[$asciiEmail]['name']; + } + $aAccounts[$asciiEmail] = $aEntry; + $oActions->SetAccounts($oMainAccount, $aAccounts); + + // Cache for this request (used during LoginProcess() above and any subsequent logins). + static::$auth[\strtolower($asciiEmail)] = $tokenBundle; + + $returnHash = ''; + if (!empty($statePayload['return']) && \is_string($statePayload['return']) && \str_starts_with($statePayload['return'], '#')) { + $returnHash = $statePayload['return']; + } + $oActions->Location(\RainLoop\Utils::WebPath() . $returnHash); + exit; + } + + // Default: "login" flow (preserve existing behavior) + static::$auth[\strtolower($email)] = $tokenBundle; + + // SnappyMail uses password as opaque string; plugin injects XOAUTH2 later. + $oPassword = new \SnappyMail\SensitiveString($sub); + $oAccount = $oActions->LoginProcess($email, $oPassword); + + if ($oAccount) { + $oActions->StorageProvider()->Put( + $oAccount, + StorageType::SESSION, + \RainLoop\Utils::GetSessionToken(), + \SnappyMail\Crypt::EncryptToJSON($tokenBundle, $oAccount->CryptKey()) + ); + } + } + catch (\Throwable $e) { + $oActions->Logger()->WriteException($e, \LOG_ERR); + } + + $oActions->Location(\RainLoop\Utils::WebPath()); + exit; + } + + public function configMapping() : array + { + return [ + \RainLoop\Plugins\Property::NewInstance('client_id') + ->SetLabel('Client ID') + ->SetType(\RainLoop\Enumerations\PluginPropertyType::STRING) + ->SetAllowedInJs(), + \RainLoop\Plugins\Property::NewInstance('client_secret') + ->SetLabel('Client Secret') + ->SetType(\RainLoop\Enumerations\PluginPropertyType::STRING) + ->SetEncrypted(), + \RainLoop\Plugins\Property::NewInstance('tenant') + ->SetLabel('Tenant') + ->SetType(\RainLoop\Enumerations\PluginPropertyType::SELECTION) + ->SetDefaultValue(['common','consumers','organizations']) + ->SetAllowedInJs(), + \RainLoop\Plugins\Property::NewInstance('personal') + // When true: redirect URI uses query parameter form "/?LoginO365" (Azure supports it). + // When false: redirect URI uses path form "/LoginO365" (useful behind reverse proxies). + ->SetLabel('Use "/?LoginO365" redirect URI') + ->SetType(\RainLoop\Enumerations\PluginPropertyType::BOOL) + ->SetDefaultValue(false) + ->SetAllowedInJs(), + \RainLoop\Plugins\Property::NewInstance('allow_any_domain') + ->SetLabel('Allow any domain (not only outlook.com/hotmail.com/live.com)') + ->SetType(\RainLoop\Enumerations\PluginPropertyType::BOOL) + ->SetDefaultValue(false) + ->SetAllowedInJs() + ]; + } + + public function clientLogin(\RainLoop\Model\Account $oAccount, \MailSo\Net\NetClient $oClient, \MailSo\Net\ConnectSettings $oSettings) : void + { + $email = \strtolower($oAccount->Email()); + + if (!$this->isSupportedEmail($email)) { + return; + } + + $oActions = \RainLoop\Api::Actions(); + + $aData = static::$auth[$email] ?? null; + if (!$aData) { + try { + if ($oAccount instanceof MainAccount) { + $blob = $oActions->StorageProvider()->Get( + $oAccount, + StorageType::SESSION, + \RainLoop\Utils::GetSessionToken() + ); + $aData = \SnappyMail\Crypt::DecryptFromJSON($blob, $oAccount->CryptKey()); + } else if ($oAccount instanceof \RainLoop\Model\AdditionalAccount) { + $oMain = $oActions->getMainAccountFromToken(false); + if (!$oMain) { + return; + } + $blob = $oActions->StorageProvider()->Get( + $oMain, + StorageType::CONFIG, + $this->tokenStorageKey($email) + ); + $aData = \SnappyMail\Crypt::DecryptFromJSON($blob, $oMain->CryptKey()); + } + } catch (\Throwable $e) { + return; + } + } + + if (empty($aData['access_token']) || empty($aData['refresh_token']) || empty($aData['expires'])) { + return; + } + + // Refresh if expired (or close to expiry) + if (\time() >= ((int)$aData['expires'] - 30)) { + $oO365 = $this->o365Connector(); + if ($oO365) { + $tenant = $this->Config()->Get('plugin', 'tenant', 'common'); + $aRefreshWrap = $oO365->getAccessToken( + \str_replace('{{tenant}}', $tenant, static::TOKEN_URI), + 'refresh_token', + ['refresh_token' => $aData['refresh_token']] + ); + + if (\is_array($aRefreshWrap) && isset($aRefreshWrap['code']) && 200 === (int)$aRefreshWrap['code']) { + $r = $aRefreshWrap['result'] ?? []; + if (!empty($r['access_token'])) { + $aData['access_token'] = $r['access_token']; + } + if (!empty($r['refresh_token'])) { + $aData['refresh_token'] = $r['refresh_token']; + } + $expiresIn = (int)($r['expires_in'] ?? 0); + if ($expiresIn > 0) { + $aData['expires'] = \time() + $expiresIn; + $aData['expires_in'] = $expiresIn; + } + + // Persist updated bundle (encrypted). + if ($oAccount instanceof MainAccount) { + $oActions->StorageProvider()->Put( + $oAccount, + StorageType::SESSION, + \RainLoop\Utils::GetSessionToken(), + \SnappyMail\Crypt::EncryptToJSON($aData, $oAccount->CryptKey()) + ); + } else if ($oAccount instanceof \RainLoop\Model\AdditionalAccount) { + $oMain = $oActions->getMainAccountFromToken(false); + if ($oMain) { + $oActions->StorageProvider()->Put( + $oMain, + StorageType::CONFIG, + $this->tokenStorageKey($email), + \SnappyMail\Crypt::EncryptToJSON($aData, $oMain->CryptKey()) + ); + } + } + } + } + } + + static::$auth[$email] = $aData; + + // Inject XOAUTH2/OAUTHBEARER + $oSettings->passphrase = $aData['access_token']; + \array_unshift($oSettings->SASLMechanisms, 'OAUTHBEARER', 'XOAUTH2'); + } + + /** + * Server-side cleanup hook: after a successful AccountDelete, remove stored token bundle for that email. + * This prevents leaving encrypted refresh tokens behind when an additional account is removed. + */ + public function afterAccountDelete(array &$aResponse) : void + { + if (empty($aResponse['Result'])) { + return; + } + $oActions = \RainLoop\Api::Actions(); + $oMain = $oActions->getMainAccountFromToken(false); + if (!$oMain) { + return; + } + $email = \strtolower(\SnappyMail\IDN::emailToAscii(\trim((string) $oActions->GetActionParam('emailToDelete', '')))); + if ($email && $this->isSupportedEmail($email)) { + $oActions->StorageProvider()->Clear($oMain, StorageType::CONFIG, $this->tokenStorageKey($email)); + } + } + + protected function o365Connector() : ?\OAuth2\Client + { + $client_id = \trim($this->Config()->Get('plugin', 'client_id', '')); + $client_secret = \trim($this->Config()->getDecrypted('plugin', 'client_secret', '')); + + if ($client_id && $client_secret) { + try { + $oO365 = new \OAuth2\Client($client_id, $client_secret); + + $oActions = \RainLoop\Api::Actions(); + $sProxy = $oActions->Config()->Get('labs', 'curl_proxy', ''); + if (\strlen($sProxy)) { + $oO365->setCurlOption(CURLOPT_PROXY, $sProxy); + $sProxyAuth = $oActions->Config()->Get('labs', 'curl_proxy_auth', ''); + if (\strlen($sProxyAuth)) { + $oO365->setCurlOption(CURLOPT_PROXYUSERPWD, $sProxyAuth); + } + } + + return $oO365; + } catch (\Throwable $e) { + \RainLoop\Api::Actions()->Logger()->WriteException($e, \LOG_ERR); + } + } + + return null; + } + + private function decodeJwtPayload(string $jwt) : ?array + { + $parts = \explode('.', $jwt); + if (\count($parts) < 2) { + return null; + } + $payload = $parts[1]; + $payload .= \str_repeat('=', (4 - (\strlen($payload) % 4)) % 4); + $json = \base64_decode(\strtr($payload, '-_', '+/')); + if ($json === false) { + return null; + } + $data = \json_decode($json, true); + return \is_array($data) ? $data : null; + } + + /** + * JSON action called by JS to obtain an MS authorize URL with signed state. + * This avoids exposing any signing secret to JS and keeps redirect_uri consistent with server logic. + */ + public function DoLoginO365AuthUrl() : array + { + $oActions = \RainLoop\Api::Actions(); + + $op = (string) $this->jsonParam('op', 'login'); + if (!\in_array($op, ['login', 'add'], true)) { + return $this->jsonResponse(__FUNCTION__, false); + } + + $email = \strtolower(\trim((string) $this->jsonParam('email', ''))); + $name = \trim((string) $this->jsonParam('name', '')); + $returnHash = (string) $this->jsonParam('return', ''); + + if ($returnHash && !\str_starts_with($returnHash, '#')) { + $returnHash = ''; + } + + // For add-account flow, require a logged-in main account (we must write to its additionalaccounts storage). + $oMainAccount = null; + if ('add' === $op) { + $oMainAccount = $oActions->getMainAccountFromToken(false); + if (!$oMainAccount) { + return $this->jsonResponse(__FUNCTION__, false); + } + } + + // Optional server-side guard: only permit supported consumer domains unless configured otherwise. + if ($email && !$this->isSupportedEmail($email)) { + return $this->jsonResponse(__FUNCTION__, false); + } + + $oConfig = $this->Config(); + $client_id = \trim($oConfig->Get('plugin', 'client_id', '')); + if (!$client_id) { + return $this->jsonResponse(__FUNCTION__, false); + } + + $nonce = $this->b64url(\random_bytes(16)); + // Store nonce server-side to prevent replay; consumed on callback. + $oActions->StorageProvider()->Put( + null, + StorageType::NOBODY, + $this->stateNonceKey($nonce), + (string) \time() + ); + + $payload = [ + 'v' => 1, + 'op' => $op, + 'csrf' => \RainLoop\Utils::GetCsrfToken(), + 'nonce' => $nonce, + 'ts' => \time() + ]; + if ('add' === $op && $oMainAccount) { + $payload['main'] = $oMainAccount->Email(); + if ($name) { + $payload['name'] = \substr($name, 0, 100); + } + if ($returnHash) { + $payload['return'] = \substr($returnHash, 0, 200); + } + } + + $state = $this->signState($payload); + $tenant = $oConfig->Get('plugin', 'tenant', 'common'); + $redirectUri = $this->redirectUri(); + + $params = [ + 'response_type' => 'code', + 'client_id' => $client_id, + 'redirect_uri' => $redirectUri, + 'scope' => \implode(' ', [ + 'openid', + 'offline_access', + 'email', + 'profile', + 'https://outlook.office.com/IMAP.AccessAsUser.All', + 'https://outlook.office.com/SMTP.Send', + ]), + 'state' => $state, + // Helps MS UI prefill, but does not change server-side validation. + ]; + if ($email) { + $params['login_hint'] = $email; + } + $authUrl = \str_replace('{{tenant}}', $tenant, static::AUTH_URI) + . '?' + . \http_build_query($params, '', '&', PHP_QUERY_RFC3986); + + return $this->jsonResponse(__FUNCTION__, [ + 'authUrl' => $authUrl + ]); + } + + private function isSupportedEmail(string $email) : bool + { + if ((bool)$this->Config()->Get('plugin', 'allow_any_domain', false)) { + return \str_contains($email, '@'); + } + return \str_ends_with($email, '@hotmail.com') + || \str_ends_with($email, '@outlook.com') + || \str_ends_with($email, '@live.com'); + } + + /** + * Build absolute base URL (works behind nginx reverse proxy). + */ + private function baseUrl() : string + { + $scheme = (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) + ? $_SERVER['HTTP_X_FORWARDED_PROTO'] + : ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http'); + + $host = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? ''; + if (!$host) { + throw new \RuntimeException('Cannot determine HTTP_HOST'); + } + return $scheme . '://' . $host; + } + + /** + * Redirect URI used for the Azure app registration. + * When plugin.personal=true -> "/?LoginO365" + * When plugin.personal=false -> "/LoginO365" + */ + private function redirectUri() : string + { + $base = \rtrim($this->baseUrl(), '/'); + $useQuery = (bool)$this->Config()->Get('plugin', 'personal', false); + return $useQuery ? ($base . '/?LoginO365') : ($base . '/LoginO365'); + } + + private function tokenStorageKey(string $emailLower) : string + { + // Stored under MAIN account StorageType::CONFIG (encrypted with main CryptKey). + // Email is hashed to avoid path/encoding issues across storage backends. + return 'login-o365.tokens.' . \sha1($emailLower); + } + + private function storeAccountTokens(MainAccount $oMainAccount, string $email, array $tokenBundle) : void + { + $emailLower = \strtolower(\SnappyMail\IDN::emailToAscii($email)); + \RainLoop\Api::Actions()->StorageProvider()->Put( + $oMainAccount, + StorageType::CONFIG, + $this->tokenStorageKey($emailLower), + \SnappyMail\Crypt::EncryptToJSON($tokenBundle, $oMainAccount->CryptKey()) + ); + } + + private function stateNonceKey(string $nonce) : string + { + return 'login-o365.state.' . $nonce; + } + + private function b64url(string $bin) : string + { + return \rtrim(\strtr(\base64_encode($bin), '+/', '-_'), '='); + } + + private function b64urlDecode(string $b64url) /*: string|false*/ + { + $pad = (4 - (\strlen($b64url) % 4)) % 4; + return \base64_decode(\strtr($b64url . \str_repeat('=', $pad), '-_', '+/'), true); + } + + private function stateHmacKey() : string + { + // Uses the plugin client_secret (server-side only) as HMAC key. + // This prevents any user-controlled tampering of the state payload. + $key = \trim($this->Config()->getDecrypted('plugin', 'client_secret', '')); + if (!$key) { + // Fallback for misconfiguration; keeps behavior deterministic. + $key = 'login-o365'; + } + return $key; + } + + private function signState(array $payload) : string + { + $json = \json_encode($payload); + if (!$json) { + $json = '{}'; + } + $payloadB64 = $this->b64url($json); + $sig = \hash_hmac('sha256', $payloadB64, $this->stateHmacKey(), true); + return $payloadB64 . '.' . $this->b64url($sig); + } + + /** + * Verify signature + CSRF + nonce, then consumes nonce to prevent replay. + * Returns decoded payload on success, null on failure. + */ + private function verifyAndConsumeState(string $state) : ?array + { + $parts = \explode('.', $state, 2); + if (2 !== \count($parts)) { + return null; + } + [$payloadB64, $sigB64] = $parts; + $sig = $this->b64urlDecode($sigB64); + if ($sig === false) { + return null; + } + + $expected = \hash_hmac('sha256', $payloadB64, $this->stateHmacKey(), true); + if (!\hash_equals($expected, $sig)) { + return null; + } + + $payloadJson = $this->b64urlDecode($payloadB64); + if ($payloadJson === false) { + return null; + } + $payload = \json_decode($payloadJson, true); + if (!\is_array($payload) || empty($payload['csrf']) || empty($payload['nonce']) || empty($payload['op'])) { + return null; + } + + // Must match the current browser session. + if ($payload['csrf'] !== \RainLoop\Utils::GetCsrfToken()) { + return null; + } + + // Replay protection: nonce must exist server-side and is consumed once. + $oActions = \RainLoop\Api::Actions(); + $key = $this->stateNonceKey((string) $payload['nonce']); + $seen = $oActions->StorageProvider()->Get(null, StorageType::NOBODY, $key); + if (!$seen) { + return null; + } + + $ts = (int) ($payload['ts'] ?? 0); + if ($ts && \abs(\time() - $ts) > 900) { // 15 minutes + // Expired: clear nonce to avoid accumulating stale entries. + $oActions->StorageProvider()->Clear(null, StorageType::NOBODY, $key); + return null; + } + + $oActions->StorageProvider()->Clear(null, StorageType::NOBODY, $key); + + return $payload; + } +} \ No newline at end of file diff --git a/plugins/login-oauth2/OAuth2/Client.php b/plugins/login-oauth2/OAuth2/Client.php new file mode 100644 index 000000000..176240d5b --- /dev/null +++ b/plugins/login-oauth2/OAuth2/Client.php @@ -0,0 +1,526 @@ + + * @author Anis Berejeb + * @version 1.3.1-dev + */ +namespace OAuth2; + +class Client +{ + /** + * Different AUTH method + */ + const AUTH_TYPE_URI = 0; + const AUTH_TYPE_AUTHORIZATION_BASIC = 1; + const AUTH_TYPE_FORM = 2; + + /** + * Different Access token type + */ + const ACCESS_TOKEN_URI = 0; + const ACCESS_TOKEN_BEARER = 1; + const ACCESS_TOKEN_OAUTH = 2; + const ACCESS_TOKEN_MAC = 3; + + /** + * Different Grant types + */ + const GRANT_TYPE_AUTH_CODE = 'authorization_code'; + const GRANT_TYPE_PASSWORD = 'password'; + const GRANT_TYPE_CLIENT_CREDENTIALS = 'client_credentials'; + const GRANT_TYPE_REFRESH_TOKEN = 'refresh_token'; + + /** + * HTTP Methods + */ + const HTTP_METHOD_GET = 'GET'; + const HTTP_METHOD_POST = 'POST'; + const HTTP_METHOD_PUT = 'PUT'; + const HTTP_METHOD_DELETE = 'DELETE'; + const HTTP_METHOD_HEAD = 'HEAD'; + const HTTP_METHOD_PATCH = 'PATCH'; + + /** + * HTTP Form content types + */ + const HTTP_FORM_CONTENT_TYPE_APPLICATION = 0; + const HTTP_FORM_CONTENT_TYPE_MULTIPART = 1; + + /** + * Client ID + * + * @var string + */ + protected $client_id = null; + + /** + * Client Secret + * + * @var string + */ + protected $client_secret = null; + + /** + * Client Authentication method + * + * @var int + */ + protected $client_auth = self::AUTH_TYPE_URI; + + /** + * Access Token + * + * @var string + */ + protected $access_token = null; + + /** + * Access Token Type + * + * @var int + */ + protected $access_token_type = self::ACCESS_TOKEN_URI; + + /** + * Access Token Secret + * + * @var string + */ + protected $access_token_secret = null; + + /** + * Access Token crypt algorithm + * + * @var string + */ + protected $access_token_algorithm = null; + + /** + * Access Token Parameter name + * + * @var string + */ + protected $access_token_param_name = 'access_token'; + + /** + * The path to the certificate file to use for https connections + * + * @var string Defaults to . + */ + protected $certificate_file = null; + + /** + * cURL options + * + * @var array + */ + protected $curl_options = array(); + + /** + * Construct + * + * @param string $client_id Client ID + * @param string $client_secret Client Secret + * @param int $client_auth (AUTH_TYPE_URI, AUTH_TYPE_AUTHORIZATION_BASIC, AUTH_TYPE_FORM) + * @param string $certificate_file Indicates if we want to use a certificate file to trust the server. Optional, defaults to null. + * @return void + */ + public function __construct($client_id, $client_secret, $client_auth = self::AUTH_TYPE_URI, $certificate_file = null) + { + if (!extension_loaded('curl')) { + throw new Exception('The PHP exention curl must be installed to use this library.', Exception::CURL_NOT_FOUND); + } + + $this->client_id = $client_id; + $this->client_secret = $client_secret; + $this->client_auth = $client_auth; + $this->certificate_file = $certificate_file; + if (!empty($this->certificate_file) && !is_file($this->certificate_file)) { + throw new InvalidArgumentException('The certificate file was not found', InvalidArgumentException::CERTIFICATE_NOT_FOUND); + } + } + + /** + * Get the client Id + * + * @return string Client ID + */ + public function getClientId() + { + return $this->client_id; + } + + /** + * Get the client Secret + * + * @return string Client Secret + */ + public function getClientSecret() + { + return $this->client_secret; + } + + /** + * getAuthenticationUrl + * + * @param string $auth_endpoint Url of the authentication endpoint + * @param string $redirect_uri Redirection URI + * @param array $extra_parameters Array of extra parameters like scope or state (Ex: array('scope' => null, 'state' => '')) + * @return string URL used for authentication + */ + public function getAuthenticationUrl($auth_endpoint, $redirect_uri, array $extra_parameters = array()) + { + $parameters = array_merge(array( + 'response_type' => 'code', + 'client_id' => $this->client_id, + 'redirect_uri' => $redirect_uri + ), $extra_parameters); + return $auth_endpoint . '?' . http_build_query($parameters, '', '&'); + } + + /** + * getAccessToken + * + * @param string $token_endpoint Url of the token endpoint + * @param string $grant_type Grant Type ('authorization_code', 'password', 'client_credentials', 'refresh_token', or a custom code (@see GrantType Classes) + * @param array $parameters Array sent to the server (depend on which grant type you're using) + * @param array $extra_headers Array of extra headers + * @return array Array of parameters required by the grant_type (CF SPEC) + */ + public function getAccessToken($token_endpoint, $grant_type, array $parameters, array $extra_headers = array()) + { + if (!$grant_type) { + throw new InvalidArgumentException('The grant_type is mandatory.', InvalidArgumentException::INVALID_GRANT_TYPE); + } + $grantTypeClassName = $this->convertToCamelCase($grant_type); + $grantTypeClass = __NAMESPACE__ . '\\GrantType\\' . $grantTypeClassName; + if (!class_exists($grantTypeClass)) { + throw new InvalidArgumentException('Unknown grant type \'' . $grant_type . '\'', InvalidArgumentException::INVALID_GRANT_TYPE); + } + $grantTypeObject = new $grantTypeClass(); + $grantTypeObject->validateParameters($parameters); + if (!defined($grantTypeClass . '::GRANT_TYPE')) { + throw new Exception('Unknown constant GRANT_TYPE for class ' . $grantTypeClassName, Exception::GRANT_TYPE_ERROR); + } + $parameters['grant_type'] = $grantTypeClass::GRANT_TYPE; + $http_headers = $extra_headers; + switch ($this->client_auth) { + case self::AUTH_TYPE_URI: + case self::AUTH_TYPE_FORM: + $parameters['client_id'] = $this->client_id; + $parameters['client_secret'] = $this->client_secret; + break; + case self::AUTH_TYPE_AUTHORIZATION_BASIC: + $parameters['client_id'] = $this->client_id; + $http_headers['Authorization'] = 'Basic ' . base64_encode($this->client_id . ':' . $this->client_secret); + break; + default: + throw new Exception('Unknown client auth type.', Exception::INVALID_CLIENT_AUTHENTICATION_TYPE); + break; + } + + return $this->executeRequest($token_endpoint, $parameters, self::HTTP_METHOD_POST, $http_headers, self::HTTP_FORM_CONTENT_TYPE_APPLICATION); + } + + /** + * setToken + * + * @param string $token Set the access token + * @return void + */ + public function setAccessToken($token) + { + $this->access_token = $token; + } + + /** + * Check if there is an access token present + * + * @return bool Whether the access token is present + */ + public function hasAccessToken() + { + return !!$this->access_token; + } + + /** + * Set the client authentication type + * + * @param string $client_auth (AUTH_TYPE_URI, AUTH_TYPE_AUTHORIZATION_BASIC, AUTH_TYPE_FORM) + * @return void + */ + public function setClientAuthType($client_auth) + { + $this->client_auth = $client_auth; + } + + /** + * Set an option for the curl transfer + * + * @param int $option The CURLOPT_XXX option to set + * @param mixed $value The value to be set on option + * @return void + */ + public function setCurlOption($option, $value) + { + $this->curl_options[$option] = $value; + } + + /** + * Set multiple options for a cURL transfer + * + * @param array $options An array specifying which options to set and their values + * @return void + */ + public function setCurlOptions($options) + { + $this->curl_options = array_merge($this->curl_options, $options); + } + + /** + * Set the access token type + * + * @param int $type Access token type (ACCESS_TOKEN_BEARER, ACCESS_TOKEN_MAC, ACCESS_TOKEN_URI) + * @param string $secret The secret key used to encrypt the MAC header + * @param string $algorithm Algorithm used to encrypt the signature + * @return void + */ + public function setAccessTokenType($type, $secret = null, $algorithm = null) + { + $this->access_token_type = $type; + $this->access_token_secret = $secret; + $this->access_token_algorithm = $algorithm; + } + + /** + * Fetch a protected ressource + * + * @param string $protected_ressource_url Protected resource URL + * @param array $parameters Array of parameters + * @param string $http_method HTTP Method to use (POST, PUT, GET, HEAD, DELETE) + * @param array $http_headers HTTP headers + * @param int $form_content_type HTTP form content type to use + * @return array + */ + public function fetch($protected_resource_url, $parameters = array(), $http_method = self::HTTP_METHOD_GET, array $http_headers = array(), $form_content_type = self::HTTP_FORM_CONTENT_TYPE_MULTIPART) + { + if ($this->access_token) { + switch ($this->access_token_type) { + case self::ACCESS_TOKEN_URI: + if (is_array($parameters)) { + $parameters[$this->access_token_param_name] = $this->access_token; + } else { + throw new InvalidArgumentException( + 'You need to give parameters as array if you want to give the token within the URI.', + InvalidArgumentException::REQUIRE_PARAMS_AS_ARRAY + ); + } + break; + case self::ACCESS_TOKEN_BEARER: + $http_headers['Authorization'] = 'Bearer ' . $this->access_token; + break; + case self::ACCESS_TOKEN_OAUTH: + $http_headers['Authorization'] = 'OAuth ' . $this->access_token; + break; + case self::ACCESS_TOKEN_MAC: + $http_headers['Authorization'] = 'MAC ' . $this->generateMACSignature($protected_resource_url, $parameters, $http_method); + break; + default: + throw new Exception('Unknown access token type.', Exception::INVALID_ACCESS_TOKEN_TYPE); + break; + } + } + return $this->executeRequest($protected_resource_url, $parameters, $http_method, $http_headers, $form_content_type); + } + + /** + * Generate the MAC signature + * + * @param string $url Called URL + * @param array $parameters Parameters + * @param string $http_method Http Method + * @return string + */ + private function generateMACSignature($url, $parameters, $http_method) + { + $timestamp = time(); + $nonce = uniqid(); + $parsed_url = parse_url($url); + if (!isset($parsed_url['port'])) + { + $parsed_url['port'] = ($parsed_url['scheme'] == 'https') ? 443 : 80; + } + if ($http_method == self::HTTP_METHOD_GET) { + if (is_array($parameters)) { + $parsed_url['path'] .= '?' . http_build_query($parameters, '', '&'); + } elseif ($parameters) { + $parsed_url['path'] .= '?' . $parameters; + } + } + + $signature = base64_encode(hash_hmac($this->access_token_algorithm, + $timestamp . "\n" + . $nonce . "\n" + . $http_method . "\n" + . $parsed_url['path'] . "\n" + . $parsed_url['host'] . "\n" + . $parsed_url['port'] . "\n\n" + , $this->access_token_secret, true)); + + return 'id="' . $this->access_token . '", ts="' . $timestamp . '", nonce="' . $nonce . '", mac="' . $signature . '"'; + } + + /** + * Execute a request (with curl) + * + * @param string $url URL + * @param mixed $parameters Array of parameters + * @param string $http_method HTTP Method + * @param array $http_headers HTTP Headers + * @param int $form_content_type HTTP form content type to use + * @return array + */ + private function executeRequest($url, $parameters = array(), $http_method = self::HTTP_METHOD_GET, ?array $http_headers = null, $form_content_type = self::HTTP_FORM_CONTENT_TYPE_MULTIPART) + { + $curl_options = array( + CURLOPT_RETURNTRANSFER => true, + CURLOPT_SSL_VERIFYPEER => true, + CURLOPT_CUSTOMREQUEST => $http_method + ); + + switch($http_method) { + case self::HTTP_METHOD_POST: + $curl_options[CURLOPT_POST] = true; + /* No break */ + case self::HTTP_METHOD_PUT: + case self::HTTP_METHOD_PATCH: + + /** + * Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data, + * while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded. + * http://php.net/manual/en/function.curl-setopt.php + */ + if(is_array($parameters) && self::HTTP_FORM_CONTENT_TYPE_APPLICATION === $form_content_type) { + $parameters = http_build_query($parameters, '', '&'); + } + $curl_options[CURLOPT_POSTFIELDS] = $parameters; + break; + case self::HTTP_METHOD_HEAD: + $curl_options[CURLOPT_NOBODY] = true; + /* No break */ + case self::HTTP_METHOD_DELETE: + case self::HTTP_METHOD_GET: + if (is_array($parameters) && count($parameters) > 0) { + $url .= '?' . http_build_query($parameters, '', '&'); + } elseif ($parameters) { + $url .= '?' . $parameters; + } + break; + default: + break; + } + + $curl_options[CURLOPT_URL] = $url; + + if (is_array($http_headers)) { + $header = array(); + foreach($http_headers as $key => $parsed_urlvalue) { + $header[] = "$key: $parsed_urlvalue"; + } + $curl_options[CURLOPT_HTTPHEADER] = $header; + } + + $ch = curl_init(); + curl_setopt_array($ch, $curl_options); + // https handling + if (!empty($this->certificate_file)) { + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($ch, CURLOPT_CAINFO, $this->certificate_file); + } else { + // bypass ssl verification + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); + } + if (!empty($this->curl_options)) { + curl_setopt_array($ch, $this->curl_options); + } + $result = curl_exec($ch); + $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); + $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); + if ($curl_error = curl_error($ch)) { + throw new Exception($curl_error, Exception::CURL_ERROR); + } else { + $json_decode = json_decode($result, true); + } + curl_close($ch); + + return array( + 'result' => (null === $json_decode) ? $result : $json_decode, + 'code' => $http_code, + 'content_type' => $content_type + ); + } + + /** + * Set the name of the parameter that carry the access token + * + * @param string $name Token parameter name + * @return void + */ + public function setAccessTokenParamName($name) + { + $this->access_token_param_name = $name; + } + + /** + * Converts the class name to camel case + * + * @param mixed $grant_type the grant type + * @return string + */ + private function convertToCamelCase($grant_type) + { + $parts = explode('_', $grant_type); + array_walk($parts, function(&$item) { $item = ucfirst($item);}); + return implode('', $parts); + } +} + +class Exception extends \Exception +{ + const CURL_NOT_FOUND = 0x01; + const CURL_ERROR = 0x02; + const GRANT_TYPE_ERROR = 0x03; + const INVALID_CLIENT_AUTHENTICATION_TYPE = 0x04; + const INVALID_ACCESS_TOKEN_TYPE = 0x05; +} + +class InvalidArgumentException extends \InvalidArgumentException +{ + const INVALID_GRANT_TYPE = 0x01; + const CERTIFICATE_NOT_FOUND = 0x02; + const REQUIRE_PARAMS_AS_ARRAY = 0x03; + const MISSING_PARAMETER = 0x04; +} diff --git a/plugins/login-oauth2/OAuth2/GrantType/AuthorizationCode.php b/plugins/login-oauth2/OAuth2/GrantType/AuthorizationCode.php new file mode 100644 index 000000000..f3436e4c5 --- /dev/null +++ b/plugins/login-oauth2/OAuth2/GrantType/AuthorizationCode.php @@ -0,0 +1,41 @@ + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 + USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random + Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/plugins/login-oauth2/OAuth2/README.md b/plugins/login-oauth2/OAuth2/README.md new file mode 100644 index 000000000..9de3570e0 --- /dev/null +++ b/plugins/login-oauth2/OAuth2/README.md @@ -0,0 +1,105 @@ +# Light PHP wrapper for the OAuth 2.0 + +[![Latest Stable Version](https://poser.pugx.org/adoy/fastcgi-client/v/stable)](https://packagist.org/packages/adoy/fastcgi-client) +[![GitHub](https://img.shields.io/github/license/adoy/PHP-OAuth2)](LICENSE) +[![Total Downloads](https://poser.pugx.org/adoy/fastcgi-client/downloads)](https://packagist.org/packages/adoy/fastcgi-client) + + +## How can I use it ? + +```php +getAuthenticationUrl(AUTHORIZATION_ENDPOINT, REDIRECT_URI); + header('Location: ' . $auth_url); + die('Redirect'); +} +else +{ + $params = array('code' => $_GET['code'], 'redirect_uri' => REDIRECT_URI); + $response = $client->getAccessToken(TOKEN_ENDPOINT, 'authorization_code', $params); + parse_str($response['result'], $info); + $client->setAccessToken($info['access_token']); + $response = $client->fetch('https://graph.facebook.com/me'); + var_dump($response, $response['result']); +} +``` + +## How can I add a new Grant Type ? + +Simply write a new class in the namespace OAuth2\GrantType. You can place the class file under GrantType. +Here is an example : + +```php +getAccessToken(TOKEN_ENDPOINT, 'my_custom_grant_type', $params); +``` + +## LICENSE + +This Code is released under the GNU LGPL + +Please do not change the header of the file(s). + +This library is free software; you can redistribute it and/or modify it +under the terms of the GNU Lesser General Public License as published +by the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This library is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +or FITNESS FOR A PARTICULAR PURPOSE. + +See the GNU Lesser General Public License for more details. diff --git a/plugins/login-oauth2/index.php b/plugins/login-oauth2/index.php index 2c266833d..99351c81b 100644 --- a/plugins/login-oauth2/index.php +++ b/plugins/login-oauth2/index.php @@ -4,9 +4,9 @@ class LoginOAuth2Plugin extends \RainLoop\Plugins\AbstractPlugin { const NAME = 'OAuth2', - VERSION = '1.0', - RELEASE = '2021-11-12', - REQUIRED = '2.9.1', + VERSION = '1.3', + RELEASE = '2024-03-27', + REQUIRED = '2.36.1', CATEGORY = 'Login', DESCRIPTION = 'IMAP, Sieve & SMTP login using RFC 7628 OAuth2'; @@ -19,19 +19,26 @@ class LoginOAuth2Plugin extends \RainLoop\Plugins\AbstractPlugin { $this->UseLangs(true); $this->addJs('LoginOAuth2.js'); -// $this->addHook('imap.before-connect', array($this, $oImapClient, &$aCredentials)); -// $this->addHook('imap.after-connect', array($this, $oImapClient, $aCredentials)); +// $this->addHook('imap.before-connect', array($this, $oImapClient, $oSettings)); +// $this->addHook('imap.after-connect', array($this, $oImapClient, $oSettings)); $this->addHook('imap.before-login', 'clientLogin'); -// $this->addHook('imap.after-login', array($this, $oImapClient, $aCredentials)); -// $this->addHook('smtp.before-connect', array($this, $oSmtpClient, &$aCredentials)); -// $this->addHook('smtp.after-connect', array($this, $oSmtpClient, $aCredentials)); +// $this->addHook('imap.after-login', array($this, $oImapClient, $oSettings)); +// $this->addHook('smtp.before-connect', array($this, $oSmtpClient, $oSettings)); +// $this->addHook('smtp.after-connect', array($this, $oSmtpClient, $oSettings)); $this->addHook('smtp.before-login', 'clientLogin'); -// $this->addHook('smtp.after-login', array($this, $oSmtpClient, $aCredentials)); -// $this->addHook('sieve.before-connect', array($this, $oSieveClient, &$aCredentials)); -// $this->addHook('sieve.after-connect', array($this, $oSieveClient, $aCredentials)); +// $this->addHook('smtp.after-login', array($this, $oSmtpClient, $oSettings)); +// $this->addHook('sieve.before-connect', array($this, $oSieveClient, $oSettings)); +// $this->addHook('sieve.after-connect', array($this, $oSieveClient, $oSettings)); $this->addHook('sieve.before-login', 'clientLogin'); -// $this->addHook('sieve.after-login', array($this, $oSieveClient, $aCredentials)); +// $this->addHook('sieve.after-login', array($this, $oSieveClient, $oSettings)); $this->addHook('filter.account', 'filterAccount'); + +// set_include_path(get_include_path() . PATH_SEPARATOR . __DIR__); + spl_autoload_register(function($classname){ + if (str_starts_with($classname, 'OAuth2\\')) { + include_once __DIR__ . strtr("\\{$sClassName}", '\\', DIRECTORY_SEPARATOR) . '.php'; + } + }); } public function configMapping() : array @@ -46,9 +53,9 @@ class LoginOAuth2Plugin extends \RainLoop\Plugins\AbstractPlugin ]; } - public function clientLogin(\RainLoop\Model\Account $oAccount, \MailSo\Net\NetClient $oClient, array &$aCredentials) : void + public function clientLogin(\RainLoop\Model\Account $oAccount, \MailSo\Net\NetClient $oClient, \MailSo\Net\ConnectSettings $oSettings) : void { - $sPassword = $aCredentials['Password']; + $sPassword = $oSettings->passphrase; $iGatLen = \strlen(static::GMAIL_TOKENS_PREFIX); if ($sPassword && static::GMAIL_TOKENS_PREFIX === \substr($sPassword, 0, $iGatLen)) { $aTokens = \json_decode(\substr($sPassword, $iGatLen)); @@ -56,8 +63,8 @@ class LoginOAuth2Plugin extends \RainLoop\Plugins\AbstractPlugin $sRefreshToken = !empty($aTokens[1]) ? $aTokens[1] : ''; } if ($sAccessToken && $sRefreshToken) { - $aCredentials['Password'] = $this->gmailRefreshToken($sAccessToken, $sRefreshToken); - \array_unshift($aCredentials['SASLMechanisms'], 'OAUTHBEARER', 'XOAUTH2'); + $oSettings->passphrase = $this->gmailRefreshToken($sAccessToken, $sRefreshToken); + \array_unshift($oSettings->SASLMechanisms, 'OAUTHBEARER', 'XOAUTH2'); } } @@ -70,8 +77,8 @@ class LoginOAuth2Plugin extends \RainLoop\Plugins\AbstractPlugin * So we need to securely save a cryptkey. * Encrypted using the old/new refresh token is an option: * 1. decrypt cryptkey with the old refresh token - * 2. $oAccount->SetCryptKey('cryptkey') - * 3. encrypt cryptkey with the new refresh token + * 2. encrypt cryptkey with the new refresh token + * = $oAccount->resealCryptKey(new \SnappyMail\SensitiveString('old refresh token')) */ } } @@ -82,9 +89,8 @@ class LoginOAuth2Plugin extends \RainLoop\Plugins\AbstractPlugin $iErrorCode = \RainLoop\Notifications::UnknownError; try { - $oAccount = $oActions->LoginProcess($sEmail, $sPassword, '', '', false, true); + $oAccount = $oActions->LoginProcess($sEmail, $sPassword); if ($oAccount instanceof \RainLoop\Model\Account) { - $oActions->AuthToken($oAccount); $iErrorCode = 0; } else { $oAccount = null; @@ -175,10 +181,10 @@ class LoginOAuth2Plugin extends \RainLoop\Plugins\AbstractPlugin $client_id = \trim($this->Config()->Get('plugin', 'client_id', '')); $client_secret = \trim($this->Config()->Get('plugin', 'client_secret', '')); if ($client_id && $client_secret) { - include_once APP_VERSION_ROOT_PATH.'app/libraries/PHP-OAuth2/Client.php'; - include_once APP_VERSION_ROOT_PATH.'app/libraries/PHP-OAuth2/GrantType/IGrantType.php'; - include_once APP_VERSION_ROOT_PATH.'app/libraries/PHP-OAuth2/GrantType/AuthorizationCode.php'; - include_once APP_VERSION_ROOT_PATH.'app/libraries/PHP-OAuth2/GrantType/RefreshToken.php'; +// include_once __DIR__ . '/OAuth2/Client.php'; +// include_once __DIR__ . '/OAuth2/GrantType/IGrantType.php'; +// include_once __DIR__ . '/OAuth2/GrantType/AuthorizationCode.php'; +// include_once __DIR__ . '/OAuth2/GrantType/RefreshToken.php'; try { @@ -194,7 +200,7 @@ class LoginOAuth2Plugin extends \RainLoop\Plugins\AbstractPlugin } catch (\Exception $oException) { - $oActions->Logger()->WriteException($oException, \MailSo\Log\Enumerations\Type::ERROR); + $oActions->Logger()->WriteException($oException, \LOG_ERR); } } @@ -292,7 +298,7 @@ class LoginOAuth2Plugin extends \RainLoop\Plugins\AbstractPlugin } catch (\Exception $oException) { - $oActions->Logger()->WriteException($oException, \MailSo\Log\Enumerations\Type::ERROR); + $oActions->Logger()->WriteException($oException, \LOG_ERR); } $oActions = \RainLoop::Actions(); diff --git a/plugins/proxyauth-login-example/LICENSE b/plugins/login-override/LICENSE similarity index 100% rename from plugins/proxyauth-login-example/LICENSE rename to plugins/login-override/LICENSE diff --git a/plugins/login-override/index.php b/plugins/login-override/index.php new file mode 100644 index 000000000..cef399dd9 --- /dev/null +++ b/plugins/login-override/index.php @@ -0,0 +1,86 @@ +addHook('login.credentials', 'MapEmailAddress'); + $this->addHook('imap.before-login', 'MapImapCredentials'); + $this->addHook('smtp.before-login', 'MapSmtpCredentials'); + } + + public function MapEmailAddress(string &$sEmail, string &$sImapUser, string &$sPassword, string &$sSmtpUser) + { + $sMapping = \trim($this->Config()->Get('plugin', 'email_mapping', '')); + if (!empty($sMapping)) { + $aList = \preg_split('/\\R/', $sMapping); + foreach ($aList as $sLine) { + $aData = \explode(':', $sLine, 2); + if (!empty($aData[1]) && $sEmail === \trim($aData[0])) { + $sEmail = \trim($aData[1]); + break; + } + } + } + } + + public function MapImapCredentials(\RainLoop\Model\Account $oAccount, \MailSo\Imap\ImapClient $oSmtpClient, \MailSo\Imap\Settings $oSettings) + { + static::MapCredentials($oAccount, $oSettings, $this->Config()->getDecrypted('plugin', 'imap_mapping', '')); + } + + public function MapSmtpCredentials(\RainLoop\Model\Account $oAccount, \MailSo\Smtp\SmtpClient $oSmtpClient, \MailSo\Smtp\Settings $oSettings) + { + static::MapCredentials($oAccount, $oSettings, $this->Config()->getDecrypted('plugin', 'smtp_mapping', '')); + } + + private static function MapCredentials(\RainLoop\Model\Account $oAccount, \MailSo\Net\ConnectSettings $oSettings, string $sMapping) + { + $sEmail = $oAccount->Email(); + $aList = \preg_split('/\\R/', \trim($sMapping)); + foreach ($aList as $line) { + $line = \explode(':', $line, 3); + if (!empty($line[0]) && $line[0] === $sEmail) { + if (!empty($line[1])) { + $oSettings->username = $line[1]; + } + if (!empty($line[2])) { + $oSettings->passphrase = $line[2]; + } + break; + } + } + } + + protected function configMapping() : array + { + return array( + \RainLoop\Plugins\Property::NewInstance('email_mapping') + ->SetLabel('Email mapping') + ->SetType(\RainLoop\Enumerations\PluginPropertyType::STRING_TEXT) + ->SetDescription('Changes email address as login@example.com:email@example.com') + ->SetDefaultValue('john-user1@example.com:john.doe@example.com') + ->SetEncrypted(), + \RainLoop\Plugins\Property::NewInstance('imap_mapping') + ->SetLabel('IMAP mapping') + ->SetType(\RainLoop\Enumerations\PluginPropertyType::STRING_TEXT) + ->SetDescription('Each line as email:loginname:password, loginname or password may be empty to use default') + ->SetDefaultValue('user@example.com:user1:password1') + ->SetEncrypted(), + \RainLoop\Plugins\Property::NewInstance('smtp_mapping') + ->SetLabel('SMTP mapping') + ->SetType(\RainLoop\Enumerations\PluginPropertyType::STRING_TEXT) + ->SetDescription('Each line as email:loginname:password, loginname or password may be empty to use default') + ->SetDefaultValue('user@example.com:user1:password1') + ->SetEncrypted() + ); + } +} diff --git a/plugins/login-proxyauth-example/LICENSE b/plugins/login-proxyauth-example/LICENSE new file mode 100644 index 000000000..f709b02e2 --- /dev/null +++ b/plugins/login-proxyauth-example/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2016 RainLoop Team + +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/plugins/login-proxyauth-example/index.php b/plugins/login-proxyauth-example/index.php new file mode 100644 index 000000000..7b3ebcf4b --- /dev/null +++ b/plugins/login-proxyauth-example/index.php @@ -0,0 +1,33 @@ +addHook('imap.before-login', 'beforeLogin'); + $this->addHook('imap.after-login', 'afterLogin'); + } + + public function beforeLogin(\RainLoop\Model\Account $oAccount, \MailSo\Net\NetClient $oImapClient, \MailSo\Net\ConnectSettings $oSettings) : void + { + if ('example.com' === $oAccount->Domain()->Name()) { + $oSettings->username = 'AdminUsername'; + $oSettings->passphrase = 'AdminPassword'; + } + } + + public function afterLogin(\RainLoop\Model\Account $oAccount, \MailSo\Imap\ImapClient $oImapClient, bool $bSuccess) + { + if ($bSuccess && 'example.com' === $oAccount->Domain()->Name()) { + $oImapClient->SendRequestGetResponse('PROXYAUTH', array($oImapClient->EscapeString($oAccount->IncLogin()))); + } + } +} diff --git a/plugins/login-register/index.php b/plugins/login-register/index.php index ff149c791..7d7a62e11 100644 --- a/plugins/login-register/index.php +++ b/plugins/login-register/index.php @@ -4,9 +4,9 @@ class LoginRegisterPlugin extends \RainLoop\Plugins\AbstractPlugin { const NAME = 'Register and Forgot', - VERSION = '2.1', - RELEASE = '2021-10-04', - REQUIRED = '2.5.2', + VERSION = '2.2', + RELEASE = '2024-03-29', + REQUIRED = '2.36.0', CATEGORY = 'Login', DESCRIPTION = 'Links on login screen for registration and forgotten password'; diff --git a/plugins/login-register/langs/ar-SA.json b/plugins/login-register/langs/ar.json similarity index 100% rename from plugins/login-register/langs/ar-SA.json rename to plugins/login-register/langs/ar.json diff --git a/plugins/login-register/langs/bg-BG.json b/plugins/login-register/langs/bg.json similarity index 100% rename from plugins/login-register/langs/bg-BG.json rename to plugins/login-register/langs/bg.json diff --git a/plugins/login-register/langs/cs-CZ.json b/plugins/login-register/langs/cs.json similarity index 100% rename from plugins/login-register/langs/cs-CZ.json rename to plugins/login-register/langs/cs.json diff --git a/plugins/login-register/langs/da-DK.json b/plugins/login-register/langs/da.json similarity index 100% rename from plugins/login-register/langs/da-DK.json rename to plugins/login-register/langs/da.json diff --git a/plugins/login-register/langs/de-DE.json b/plugins/login-register/langs/de.json similarity index 100% rename from plugins/login-register/langs/de-DE.json rename to plugins/login-register/langs/de.json diff --git a/plugins/login-register/langs/el-GR.json b/plugins/login-register/langs/el.json similarity index 100% rename from plugins/login-register/langs/el-GR.json rename to plugins/login-register/langs/el.json diff --git a/plugins/login-register/langs/es-ES.json b/plugins/login-register/langs/es.json similarity index 100% rename from plugins/login-register/langs/es-ES.json rename to plugins/login-register/langs/es.json diff --git a/plugins/login-register/langs/et-EE.json b/plugins/login-register/langs/et.json similarity index 100% rename from plugins/login-register/langs/et-EE.json rename to plugins/login-register/langs/et.json diff --git a/plugins/login-register/langs/fa-IR.json b/plugins/login-register/langs/fa.json similarity index 100% rename from plugins/login-register/langs/fa-IR.json rename to plugins/login-register/langs/fa.json diff --git a/plugins/login-register/langs/fi-FI.json b/plugins/login-register/langs/fi.json similarity index 100% rename from plugins/login-register/langs/fi-FI.json rename to plugins/login-register/langs/fi.json diff --git a/plugins/login-register/langs/fr-FR.json b/plugins/login-register/langs/fr.json similarity index 51% rename from plugins/login-register/langs/fr-FR.json rename to plugins/login-register/langs/fr.json index 3f0c91586..d317903f8 100644 --- a/plugins/login-register/langs/fr-FR.json +++ b/plugins/login-register/langs/fr.json @@ -4,7 +4,7 @@ "LABEL_REGISTRATION": "S'enregistrer" }, "TAB_LOGIN": { - "LABEL_FORGOT_PASSWORD_LINK_URL": "Forgot password url", - "LABEL_REGISTRATION_LINK_URL": "Register url" + "LABEL_FORGOT_PASSWORD_LINK_URL": "URL du mot de passe oublié", + "LABEL_REGISTRATION_LINK_URL": "URL d'enregistrement" } } diff --git a/plugins/login-register/langs/hu-HU.json b/plugins/login-register/langs/hu.json similarity index 100% rename from plugins/login-register/langs/hu-HU.json rename to plugins/login-register/langs/hu.json diff --git a/plugins/login-register/langs/id-ID.json b/plugins/login-register/langs/id.json similarity index 100% rename from plugins/login-register/langs/id-ID.json rename to plugins/login-register/langs/id.json diff --git a/plugins/login-register/langs/is-IS.json b/plugins/login-register/langs/is.json similarity index 100% rename from plugins/login-register/langs/is-IS.json rename to plugins/login-register/langs/is.json diff --git a/plugins/login-register/langs/it-IT.json b/plugins/login-register/langs/it.json similarity index 100% rename from plugins/login-register/langs/it-IT.json rename to plugins/login-register/langs/it.json diff --git a/plugins/login-register/langs/ja-JP.json b/plugins/login-register/langs/ja.json similarity index 100% rename from plugins/login-register/langs/ja-JP.json rename to plugins/login-register/langs/ja.json diff --git a/plugins/login-register/langs/ko-KR.json b/plugins/login-register/langs/ko.json similarity index 100% rename from plugins/login-register/langs/ko-KR.json rename to plugins/login-register/langs/ko.json diff --git a/plugins/login-register/langs/lt-LT.json b/plugins/login-register/langs/lt.json similarity index 100% rename from plugins/login-register/langs/lt-LT.json rename to plugins/login-register/langs/lt.json diff --git a/plugins/login-register/langs/lv-LV.json b/plugins/login-register/langs/lv.json similarity index 100% rename from plugins/login-register/langs/lv-LV.json rename to plugins/login-register/langs/lv.json diff --git a/plugins/login-register/langs/nb-NO.json b/plugins/login-register/langs/nb.json similarity index 100% rename from plugins/login-register/langs/nb-NO.json rename to plugins/login-register/langs/nb.json diff --git a/plugins/login-register/langs/nl-NL.json b/plugins/login-register/langs/nl.json similarity index 100% rename from plugins/login-register/langs/nl-NL.json rename to plugins/login-register/langs/nl.json diff --git a/plugins/login-register/langs/pl-PL.json b/plugins/login-register/langs/pl.json similarity index 100% rename from plugins/login-register/langs/pl-PL.json rename to plugins/login-register/langs/pl.json diff --git a/plugins/login-register/langs/pt-PT.json b/plugins/login-register/langs/pt-PT.json deleted file mode 100644 index a667b32c1..000000000 --- a/plugins/login-register/langs/pt-PT.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "LOGIN": { - "LABEL_FORGOT_PASSWORD": "Esqueci-me da palavra-passe", - "LABEL_REGISTRATION": "Registo" - }, - "TAB_LOGIN": { - "LABEL_FORGOT_PASSWORD_LINK_URL": "Forgot password url", - "LABEL_REGISTRATION_LINK_URL": "Register url" - } -} diff --git a/plugins/login-register/langs/pt-BR.json b/plugins/login-register/langs/pt.json similarity index 100% rename from plugins/login-register/langs/pt-BR.json rename to plugins/login-register/langs/pt.json diff --git a/plugins/login-register/langs/ro-RO.json b/plugins/login-register/langs/ro.json similarity index 100% rename from plugins/login-register/langs/ro-RO.json rename to plugins/login-register/langs/ro.json diff --git a/plugins/login-register/langs/ru-RU.json b/plugins/login-register/langs/ru.json similarity index 100% rename from plugins/login-register/langs/ru-RU.json rename to plugins/login-register/langs/ru.json diff --git a/plugins/login-register/langs/sk-SK.json b/plugins/login-register/langs/sk.json similarity index 100% rename from plugins/login-register/langs/sk-SK.json rename to plugins/login-register/langs/sk.json diff --git a/plugins/login-register/langs/sl-SI.json b/plugins/login-register/langs/sl.json similarity index 100% rename from plugins/login-register/langs/sl-SI.json rename to plugins/login-register/langs/sl.json diff --git a/plugins/login-register/langs/sv-SE.json b/plugins/login-register/langs/sv.json similarity index 100% rename from plugins/login-register/langs/sv-SE.json rename to plugins/login-register/langs/sv.json diff --git a/plugins/login-register/langs/tr-TR.json b/plugins/login-register/langs/tr.json similarity index 100% rename from plugins/login-register/langs/tr-TR.json rename to plugins/login-register/langs/tr.json diff --git a/plugins/login-register/langs/uk-UA.json b/plugins/login-register/langs/uk.json similarity index 100% rename from plugins/login-register/langs/uk-UA.json rename to plugins/login-register/langs/uk.json diff --git a/plugins/login-register/langs/zh-CN.json b/plugins/login-register/langs/zh.json similarity index 51% rename from plugins/login-register/langs/zh-CN.json rename to plugins/login-register/langs/zh.json index a1c5787c0..08823a0cb 100644 --- a/plugins/login-register/langs/zh-CN.json +++ b/plugins/login-register/langs/zh.json @@ -4,7 +4,7 @@ "LABEL_REGISTRATION": "注册" }, "TAB_LOGIN": { - "LABEL_FORGOT_PASSWORD_LINK_URL": "Forgot password url", - "LABEL_REGISTRATION_LINK_URL": "Register url" + "LABEL_FORGOT_PASSWORD_LINK_URL": "忘记密码 Url", + "LABEL_REGISTRATION_LINK_URL": "注册 Url" } } diff --git a/plugins/login-remote/LICENSE b/plugins/login-remote/LICENSE new file mode 100644 index 000000000..f709b02e2 --- /dev/null +++ b/plugins/login-remote/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2016 RainLoop Team + +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/plugins/login-remote/index.php b/plugins/login-remote/index.php new file mode 100644 index 000000000..fe5bb7282 --- /dev/null +++ b/plugins/login-remote/index.php @@ -0,0 +1,78 @@ +addPartHook('RemoteAutoLogin', 'ServiceRemoteAutoLogin'); + $this->addHook('filter.app-data', 'FilterAppData'); + $this->addHook('login.credentials', 'FilterLoginCredentials'); + } + + public function FilterAppData($bAdmin, &$aResult) + { + if (!$bAdmin && \is_array($aResult) && empty($aResult['Auth']) && isset($_ENV['REMOTE_USER'])) { + $aResult['DevEmail'] = $_ENV['REMOTE_USER']; +// $aResult['DevPassword'] = $_ENV['REMOTE_PASSWORD']; + } + } + + private static bool $login = false; + public function ServiceRemoteAutoLogin() : bool + { + $oActions = \RainLoop\Api::Actions(); + + $oException = null; + $oAccount = null; + + $sEmail = $_ENV['REMOTE_USER'] ?? ''; + $sPassword = $_ENV['REMOTE_PASSWORD'] ?? ''; + + if (\strlen($sEmail) && \strlen($sPassword)) { + try + { + static::$login = true; + $sPassword = new \SnappyMail\SensitiveString($sPassword); + $oAccount = $oActions->LoginProcess($sEmail, $sPassword); + } + catch (\Throwable $oException) + { + $oLogger = $oActions->Logger(); + $oLogger && $oLogger->WriteException($oException); + } + } + + \MailSo\Base\Http::Location('./'); + return true; + } + + public function FilterLoginCredentials(string &$sEmail, string &$sImapUser, string &$sPassword, string &$sSmtpUser) + { + // cPanel https://github.com/the-djmaze/snappymail/issues/697 +// && !empty($_ENV['CPANEL']) + if (static::$login/* && $sImapUser == $_ENV['REMOTE_USER']*/) { + if (empty($_ENV['REMOTE_TEMP_USER'])) { + $iPos = \strpos($sPassword, '[::cpses::]'); + if ($iPos) { + $_ENV['REMOTE_TEMP_USER'] = \substr($sPassword, 0, $iPos); + } + } + if (!empty($_ENV['REMOTE_TEMP_USER'])) { + $sImapUser = $_ENV['REMOTE_USER'] . '/' . $_ENV['REMOTE_TEMP_USER']; + $sSmtpUser = $_ENV['REMOTE_USER'] . '/' . $_ENV['REMOTE_TEMP_USER']; + } + } + } + +} diff --git a/plugins/login-virtuser/index.php b/plugins/login-virtuser/index.php new file mode 100644 index 000000000..88207baec --- /dev/null +++ b/plugins/login-virtuser/index.php @@ -0,0 +1,71 @@ +addHook('login.credentials', 'ParseVirtuserFiles'); + } + + /** + * @param string $sEmail + * @param string $sImapUser + * @param string $sPassword + * @param string $sSmtpUser + * + * @throws \RainLoop\Exceptions\ClientException + */ + public function ParseVirtuserFiles(string &$sEmail, string &$sImapUser, string &$sPassword, string &$sSmtpUser) + { + $sFiles = \trim($this->Config()->Get('plugin', 'virtuser_files', '')); + if (!empty($sFiles)) + { + $aFiles = \explode("\n", \preg_replace('/[\r\n\t\s]+/', "\n", $sFiles)); + foreach ($aFiles as $sFile) + { + $fContent = file("$sFile"); + if (empty($fContent)) { + continue; + } + + foreach($fContent as $sLine) { + $sLine = trim($sLine); + if (empty($sLine) || $sLine[0] == '#') { + continue; + } + + $aData = preg_split( '/[[:blank:]]+/', $sLine, 3, PREG_SPLIT_NO_EMPTY); + if (is_array($aData) && !empty($aData[0]) && isset($aData[1])) { + if ($sEmail === $aData[0] && 0 < strlen($aData[1])) { + $sImapUser = $aData[1]; + return; + } + } + } + } + } + } + + /** + * @return array + */ + protected function configMapping() : array + { + return array( + \RainLoop\Plugins\Property::NewInstance('virtuser_files')->SetLabel('Virtuser files') + ->SetType(\RainLoop\Enumerations\PluginPropertyType::STRING_TEXT) + ->SetDescription('Each line is an absolute path to virtuser file') + ->SetDefaultValue("/etc/postfix/virtual\n/etc/mail/virtusertable") + ); + } +} diff --git a/plugins/mailbox-detect/index.php b/plugins/mailbox-detect/index.php new file mode 100644 index 000000000..04ffe68d0 --- /dev/null +++ b/plugins/mailbox-detect/index.php @@ -0,0 +1,228 @@ +addHook('json.after-folders', 'AfterFolders'); + } + + protected function configMapping() : array + { + return array( + \RainLoop\Plugins\Property::NewInstance('autocreate_system_folders')->SetLabel('Autocreate system folders') + ->SetType(\RainLoop\Enumerations\PluginPropertyType::BOOL) + ->SetDefaultValue(false), + ); + } + + protected function Logger() : \MailSo\Log\Logger + { + return $this->Manager()->Actions()->Logger(); + } + + public function AfterFolders(array &$aResponse) + { + if (!empty($aResponse['Result']['@Collection'])) { + $oActions = \RainLoop\Api::Actions(); + $oAccount = $oActions->getAccountFromToken(); + if (!$oAccount) { + $this->Logger()->Write('No Account'); + return; + } + $oSettingsLocal = $oActions->SettingsProvider(true)->Load($oAccount); + $roles = [ + 'inbox' => false, + 'sent' => !!$oSettingsLocal->GetConf('SentFolder', ''), + 'drafts' => !!$oSettingsLocal->GetConf('DraftsFolder', ''), + 'junk' => !!$oSettingsLocal->GetConf('JunkFolder', ''), + 'trash' => !!$oSettingsLocal->GetConf('TrashFolder', ''), + 'archive' => !!$oSettingsLocal->GetConf('ArchiveFolder', '') + ]; + $types = [ + FolderType::SENT => 'sent', + FolderType::DRAFTS => 'drafts', + FolderType::JUNK => 'junk', + FolderType::TRASH => 'trash', + FolderType::ARCHIVE => 'archive' + ]; + $found = [ + 'inbox' => [], + 'sent' => [], + 'drafts' => [], + 'junk' => [], + 'trash' => [], + 'archive' => [] + ]; + $aMap = $this->systemFoldersNames($oAccount); + $sDelimiter = ''; + foreach ($aResponse['Result']['@Collection'] as $i => $folder) { + $sDelimiter || ($sDelimiter = $folder['delimiter']); + if ($folder['role']) { + $roles[$folder['role']] = true; + } else if (\in_array('\\sentmail', $folder['attributes'])) { + $found['sent'][] = $i; + } else if (\in_array('\\spam', $folder['attributes'])) { + $found['junk'][] = $i; + } else if (\in_array('\\bin', $folder['attributes'])) { + $found['trash'][] = $i; + } else if (\in_array('\\starred', $folder['attributes'])) { + $found['flagged'][] = $i; + } else { + // Kolab + $kolab = $folder['metadata'][MetadataKeys::KOLAB_CTYPE] + ?? $folder['metadata'][MetadataKeys::KOLAB_CTYPE_SHARED] + ?? ''; + if ('mail.inbox' === $kolab) { + $found['inbox'][] = $i; + } else if ('mail.sentitems' === $kolab /*|| 'mail.outbox' === $kolab*/) { + $found['sent'][] = $i; + } else if ('mail.drafts' === $kolab) { + $found['drafts'][] = $i; + } else if ('mail.junkemail' === $kolab) { + $found['junk'][] = $i; + } else if ('mail.wastebasket' === $kolab) { + $found['trash'][] = $i; + } else { + $iFolderType = 0; + if (isset($aMap[$folder['fullName']])) { + $iFolderType = $aMap[$folder['fullName']]; + } else if (isset($aMap[$folder['name']]) || isset($aMap["INBOX{$folder['delimiter']}{$folder['name']}"])) { + $iFolderType = $aMap[$folder['name']]; + } + if ($iFolderType && isset($types[$iFolderType])) { + $found[$types[$iFolderType]][] = $i; + } + } + } + } + foreach ($roles as $role => $hasRole) { + if ($hasRole) { + unset($found[$role]); + } + } + if ($found) { + foreach ($found as $role => $folders) { + if (isset($folders[0])) { + // Set the first as default + $aFolder = &$aResponse['Result']['@Collection'][$folders[0]]; + $this->Logger()->Write("Set {$role} mailbox to {$aFolder['fullName']}"); + $aFolder['role'] = $role; + } else if ($this->Config()->Get('plugin', 'autocreate_system_folders', false)) { + try + { + $sParent = \substr($aResponse['Result']['namespace'], 0, -1); + $sFolderNameToCreate = \ucfirst($role); +/* + $this->Manager()->RunHook('filter.folders-system-types', array($oAccount, &$aList)); + $iPos = \strrpos($sFolderNameToCreate, $sDelimiter); + if (false !== $iPos) { + $mNewParent = \substr($sFolderNameToCreate, 0, $iPos); + $mNewFolderNameToCreate = \substr($sFolderNameToCreate, $iPos + 1); + if (\strlen($mNewFolderNameToCreate)) { + $sFolderNameToCreate = $mNewFolderNameToCreate; + } + + if (\strlen($mNewParent)) { + $sParent = \strlen($sParent) ? $sParent.$sDelimiter.$mNewParent : $mNewParent; + } + } +*/ + $this->Logger()->Write("Create {$role} mailbox {$sFolderNameToCreate}"); + $aFolder = $oActions->MailClient()->FolderCreate( + $sFolderNameToCreate, + $sParent, + true, + $sDelimiter + )->jsonSerialize(); + $aFolder['role'] = $role; + $aResponse['Result']['@Collection'][] = $aFolder; + } + catch (\Throwable $oException) + { + $this->Logger()->WriteException($oException); + } + } else { + $this->Logger()->Write("Mailbox for {$role} not created"); + } + } + } + } + } + + /** + * @staticvar array $aCache + */ + private function systemFoldersNames(\RainLoop\Model\Account $oAccount) : array + { + static $aCache = null; + if (null === $aCache) { + $aCache = array( + 'Sent' => FolderType::SENT, + 'Send' => FolderType::SENT, + 'Outbox' => FolderType::SENT, + 'Out box' => FolderType::SENT, + 'Sent Item' => FolderType::SENT, + 'Sent Items' => FolderType::SENT, + 'Send Item' => FolderType::SENT, + 'Send Items' => FolderType::SENT, + 'Sent Mail' => FolderType::SENT, + 'Sent Mails' => FolderType::SENT, + 'Send Mail' => FolderType::SENT, + 'Send Mails' => FolderType::SENT, + + 'Drafts' => FolderType::DRAFTS, + 'Draft' => FolderType::DRAFTS, + 'Draft Mail' => FolderType::DRAFTS, + 'Draft Mails' => FolderType::DRAFTS, + 'Drafts Mail' => FolderType::DRAFTS, + 'Drafts Mails' => FolderType::DRAFTS, + + 'Junk' => FolderType::JUNK, + 'Junk E-mail' => FolderType::JUNK, + 'Spam' => FolderType::JUNK, + 'Spams' => FolderType::JUNK, + 'Bulk Mail' => FolderType::JUNK, + 'Bulk Mails' => FolderType::JUNK, + + 'Trash' => FolderType::TRASH, + 'Deleted' => FolderType::TRASH, + 'Deleted Items' => FolderType::TRASH, + 'Bin' => FolderType::TRASH, + + 'Archive' => FolderType::ARCHIVE, + 'Archives' => FolderType::ARCHIVE, + + 'All' => FolderType::ALL, + 'All Mail' => FolderType::ALL, + 'All Mails' => FolderType::ALL, + ); + + $aNewCache = array(); + foreach ($aCache as $sKey => $iType) { + $aNewCache[$sKey] = $iType; + $aNewCache[\str_replace(' ', '', $sKey)] = $iType; + } + + $aCache = $aNewCache; + + $this->Manager()->RunHook('filter.system-folders-names', array($oAccount, &$aCache)); + } + + return $aCache; + } +} diff --git a/plugins/nextcloud/LICENSE b/plugins/nextcloud/LICENSE new file mode 100644 index 000000000..9e5e56cdd --- /dev/null +++ b/plugins/nextcloud/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2022 SnappyMail + +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/plugins/nextcloud/NextcloudContactsSuggestions.php b/plugins/nextcloud/NextcloudContactsSuggestions.php new file mode 100644 index 000000000..34d1cbe49 --- /dev/null +++ b/plugins/nextcloud/NextcloudContactsSuggestions.php @@ -0,0 +1,80 @@ +ignoreSystemAddressbook = $ignoreSystemAddressbook; + } + + public function Process(\RainLoop\Model\Account $oAccount, string $sQuery, int $iLimit = 20): array + { + try + { + $sQuery = \trim($sQuery); + if ('' === $sQuery) { + return []; + } + + $cm = \OC::$server->getContactsManager(); + if (!$cm || !$cm->isEnabled()) { + return []; + } + + // Unregister system addressbook so as to return only contacts in user's addressbooks + if ($this->ignoreSystemAddressbook) { + foreach($cm->getUserAddressBooks() as $addressBook) { + if($addressBook->isSystemAddressBook()) { + $cm->unregisterAddressBook($addressBook); + } + } + } + + $aSearchResult = $cm->search($sQuery, array('FN', 'NICKNAME', 'TITLE', 'EMAIL')); + + //$this->oLogger->WriteDump($aSearchResult); + + if (\is_array($aSearchResult) && 0 < \count($aSearchResult)) { + $iInputLimit = $iLimit; + $aResult = array(); + foreach ($aSearchResult as $aContact) { + if (0 >= $iLimit) { + break; + } + if (!empty($aContact['UID'])) { + $sUid = $aContact['UID']; + $mEmails = isset($aContact['EMAIL']) ? $aContact['EMAIL'] : ''; + + $sFullName = isset($aContact['FN']) ? \trim($aContact['FN']) : ''; + if (empty($sFullName) && isset($aContact['NICKNAME'])) { + $sFullName = \trim($aContact['NICKNAME']); + } + + if (!\is_array($mEmails)) { + $mEmails = array($mEmails); + } + + foreach ($mEmails as $sEmail) { + $sHash = $sFullName.'|'.$sEmail; + if (!isset($aResult[$sHash])) { + $aResult[$sHash] = array($sEmail, $sFullName); + --$iLimit; + } + } + } + } + return \array_slice(\array_values($aResult), 0, $iInputLimit); + } + } + catch (\Exception $oException) + { + $this->logException($oException); + } + + return []; + } +} diff --git a/plugins/nextcloud/index.php b/plugins/nextcloud/index.php new file mode 100644 index 000000000..9999577cd --- /dev/null +++ b/plugins/nextcloud/index.php @@ -0,0 +1,418 @@ +UseLangs(true); + + $this->addHook('main.fabrica', 'MainFabrica'); + $this->addHook('filter.app-data', 'FilterAppData'); + $this->addHook('filter.language', 'FilterLanguage'); + + $this->addCss('style.css'); + + $this->addJs('js/webdav.js'); + + $this->addJs('js/message.js'); + $this->addHook('json.attachments', 'DoAttachmentsActions'); + $this->addJsonHook('NextcloudSaveMsg', 'NextcloudSaveMsg'); + + $this->addJs('js/composer.js'); + $this->addJsonHook('NextcloudAttachFile', 'NextcloudAttachFile'); + + $this->addJs('js/messagelist.js'); + + $this->addTemplate('templates/PopupsNextcloudFiles.html'); + $this->addTemplate('templates/PopupsNextcloudCalendars.html'); + +// $this->addHook('login.credentials.step-2', 'loginCredentials2'); +// $this->addHook('login.credentials', 'loginCredentials'); + $this->addHook('imap.before-login', 'beforeLogin'); + $this->addHook('smtp.before-login', 'beforeLogin'); + $this->addHook('sieve.before-login', 'beforeLogin'); + } else { + \SnappyMail\Log::debug('Nextcloud', 'NOT integrated'); + // SnappyMailHelper::getConfig()->getAppValue('snappymail', 'snappymail-no-embed'); + $this->addHook('main.content-security-policy', 'ContentSecurityPolicy'); + } + } + + public function ContentSecurityPolicy(\SnappyMail\HTTP\CSP $CSP) + { + if (\method_exists($CSP, 'add')) { + $CSP->add('frame-ancestors', "'self'"); + } + } + + public function Supported() : string + { + return static::IsIntegrated() ? '' : 'Nextcloud not found to use this plugin'; + } + + public static function IsIntegrated() + { + return \class_exists('OC') && isset(\OC::$server); + } + + public static function IsLoggedIn() + { + return static::IsIntegrated() && SnappyMailHelper::getUserSession()->isLoggedIn(); + } + + public function loginCredentials(string &$sEmail, string &$sLogin, ?string &$sPassword = null) : void + { + /** + * This has an issue. + * When user changes email address, all settings are gone as the new + * _data_/_default_/storage/{domain}/{local-part} is used + */ +// $ocUser = SnappyMailHelper::getUser(); +// $sEmail = $ocUser->getEMailAddress() ?: $ocUser->getPrimaryEMailAddress() ?: $sEmail; + } + + public function loginCredentials2(string &$sEmail, ?string &$sPassword = null) : void + { + $ocUser = SnappyMailHelper::getUser(); + $sEmail = $ocUser->getEMailAddress() ?: $ocUser->getPrimaryEMailAddress() ?: $sEmail; + } + + public function beforeLogin(\RainLoop\Model\Account $oAccount, \MailSo\Net\NetClient $oClient, \MailSo\Net\ConnectSettings $oSettings) : void + { + // Only login with OIDC access token if + // it is enabled in config, the user is currently logged in with OIDC, + // the current snappymail account is the OIDC account and no account defined explicitly + if ($oAccount instanceof \RainLoop\Model\MainAccount + && SnappyMailHelper::isOIDCLogin() +// && $oClient->supportsAuthType('OAUTHBEARER') // v2.28 + && \str_starts_with($oSettings->passphrase, 'oidc_login|') + ) { +// $oSettings->passphrase = SnappyMailHelper::getSessionValue('snappymail-passphrase'); + $oSettings->passphrase = SnappyMailHelper::getSessionValue('oidc_access_token'); + \array_unshift($oSettings->SASLMechanisms, 'OAUTHBEARER'); + } + } + + /* + \OC::$server->getCalendarManager(); + \OC::$server->getLDAPProvider(); + */ + + public function NextcloudAttachFile() : array + { + $aResult = [ + 'success' => false, + 'tempName' => '' + ]; + $sFile = $this->jsonParam('file', ''); + $oFiles = \OCP\Files::getStorage('files'); + if ($oFiles && $oFiles->is_file($sFile) && $fp = $oFiles->fopen($sFile, 'rb')) { + $oActions = \RainLoop\Api::Actions(); + $oAccount = $oActions->getAccountFromToken(); + if ($oAccount) { + $sSavedName = 'nextcloud-file-' . \sha1($sFile . \microtime()); + if (!$oActions->FilesProvider()->PutFile($oAccount, $sSavedName, $fp)) { + $aResult['error'] = 'failed'; + } else { + $aResult['tempName'] = $sSavedName; + $aResult['success'] = true; + } + } + } + return $this->jsonResponse(__FUNCTION__, $aResult); + } + + public function NextcloudSaveMsg() : array + { + $sSaveFolder = \ltrim($this->jsonParam('folder', ''), '/'); +// $aValues = \RainLoop\Api::Actions()->decodeRawKey($this->jsonParam('msgHash', '')); + $msgHash = $this->jsonParam('msgHash', ''); + $aValues = \json_decode(\MailSo\Base\Utils::UrlSafeBase64Decode($msgHash), true); + $aResult = [ + 'folder' => '', + 'filename' => '', + 'success' => false + ]; + if ($sSaveFolder && !empty($aValues['folder']) && !empty($aValues['uid'])) { + $oActions = \RainLoop\Api::Actions(); + $oMailClient = $oActions->MailClient(); + if (!$oMailClient->IsLoggined()) { + $oAccount = $oActions->getAccountFromToken(); + $oAccount->ImapConnectAndLogin($oActions->Plugins(), $oMailClient->ImapClient(), $oActions->Config()); + } + + $sSaveFolder = $sSaveFolder ?: 'Emails'; + $oFiles = \OCP\Files::getStorage('files'); + if ($oFiles) { + $oFiles->is_dir($sSaveFolder) || $oFiles->mkdir($sSaveFolder); + } + $aResult['folder'] = $sSaveFolder; + $aResult['filename'] = \MailSo\Base\Utils::SecureFileName( + \mb_substr($this->jsonParam('filename', '') ?: \date('YmdHis'), 0, 100) + ) . '.' . \md5($msgHash) . '.eml'; + + + $oMailClient->MessageMimeStream( + function ($rResource) use ($oFiles, $aResult) { + if (\is_resource($rResource)) { + $aResult['success'] = $oFiles->file_put_contents("{$aResult['folder']}/{$aResult['filename']}", $rResource); + } + }, + (string) $aValues['folder'], + (int) $aValues['uid'], + isset($aValues['mimeIndex']) ? (string) $aValues['mimeIndex'] : '' + ); + } + + return $this->jsonResponse(__FUNCTION__, $aResult); + } + + public function DoAttachmentsActions(\SnappyMail\AttachmentsAction $data) + { + if (static::isLoggedIn() && 'nextcloud' === $data->action) { + $oFiles = \OCP\Files::getStorage('files'); + if ($oFiles && \method_exists($oFiles, 'file_put_contents')) { + $sSaveFolder = \ltrim($this->jsonParam('NcFolder', ''), '/'); + $sSaveFolder = $sSaveFolder ?: 'Attachments'; + $oFiles->is_dir($sSaveFolder) || $oFiles->mkdir($sSaveFolder); + $data->result = true; + foreach ($data->items as $aItem) { + $sSavedFileName = empty($aItem['fileName']) ? 'file.dat' : $aItem['fileName']; + if (!empty($aItem['data'])) { + $sSavedFileNameFull = static::SmartFileExists($sSaveFolder.'/'.$sSavedFileName, $oFiles); + if (!$oFiles->file_put_contents($sSavedFileNameFull, $aItem['data'])) { + $data->result = false; + } + } else if (!empty($aItem['fileHash'])) { + $fFile = $data->filesProvider->GetFile($data->account, $aItem['fileHash'], 'rb'); + if (\is_resource($fFile)) { + $sSavedFileNameFull = static::SmartFileExists($sSaveFolder.'/'.$sSavedFileName, $oFiles); + if (!$oFiles->file_put_contents($sSavedFileNameFull, $fFile)) { + $data->result = false; + } + if (\is_resource($fFile)) { + \fclose($fFile); + } + } + } + } + } + } + } + + public function FilterAppData($bAdmin, &$aResult) : void + { + if (!$bAdmin && \is_array($aResult)) { + $ocUser = SnappyMailHelper::getUser(); + $sUID = $ocUser->getUID(); + $oUrlGen = \OC::$server->getURLGenerator(); + $sWebDAV = $oUrlGen->getAbsoluteURL($oUrlGen->linkTo('', 'remote.php') . '/dav'); +// $sWebDAV = \OCP\Util::linkToRemote('dav'); + $aResult['Nextcloud'] = [ + 'UID' => $sUID, + 'WebDAV' => $sWebDAV, + 'CalDAV' => $this->Config()->Get('plugin', 'calendar', false) +// 'WebDAV_files' => $sWebDAV . '/files/' . $sUID + ]; + if (empty($aResult['Auth'])) { + $config = SnappyMailHelper::getConfig(); + $sEmail = ''; + // Only store the user's password in the current session if they have + // enabled auto-login using Nextcloud username or email address. + if ($config->getAppValue('snappymail', 'snappymail-autologin', false)) { + $sEmail = $sUID; + } else if ($config->getAppValue('snappymail', 'snappymail-autologin-with-email', false)) { + $sEmail = $config->getUserValue($sUID, 'settings', 'email', ''); + } else { + \SnappyMail\Log::debug('Nextcloud', 'snappymail-autologin is off'); + } + // If the user has set credentials for SnappyMail in their personal + // settings, override everything before and use those instead. + $sCustomEmail = $config->getUserValue($sUID, 'snappymail', 'snappymail-email', ''); + if ($sCustomEmail) { + $sEmail = $sCustomEmail; + } + if (!$sEmail) { + $sEmail = $ocUser->getEMailAddress(); +// ?: $ocUser->getPrimaryEMailAddress(); + } +/* + if ($config->getAppValue('snappymail', 'snappymail-autologin-oidc', false)) { + if (SnappyMailHelper::getSessionValue('is_oidc')) { + $sEmail = "{$sUID}@nextcloud"; + $aResult['DevPassword'] = SnappyMailHelper::getSessionValue('oidc_access_token'); + } else { + \SnappyMail\Log::debug('Nextcloud', 'Not an OIDC login'); + } + } else { + \SnappyMail\Log::debug('Nextcloud', 'OIDC is off'); + } +*/ + $aResult['DevEmail'] = $sEmail ?: ''; + } else if (!empty($aResult['ContactsSync'])) { + $bSave = false; + if (empty($aResult['ContactsSync']['Url'])) { + $aResult['ContactsSync']['Url'] = "{$sWebDAV}/addressbooks/users/{$sUID}/contacts/"; + $bSave = true; + } + if (empty($aResult['ContactsSync']['User'])) { + $aResult['ContactsSync']['User'] = $sUID; + $bSave = true; + } + $pass = SnappyMailHelper::getSessionValue('snappymail-passphrase'); + if ($pass/* && empty($aResult['ContactsSync']['Password'])*/) { + $pass = \SnappyMail\Crypt::DecryptUrlSafe($pass, $sUID); + if ($pass) { + $aResult['ContactsSync']['Password'] = $pass; + $bSave = true; + } + } + if ($bSave) { + $oActions = \RainLoop\Api::Actions(); + $oActions->setContactsSyncData( + $oActions->getAccountFromToken(), + array( + 'Mode' => $aResult['ContactsSync']['Mode'], + 'User' => $aResult['ContactsSync']['User'], + 'Password' => $aResult['ContactsSync']['Password'], + 'Url' => $aResult['ContactsSync']['Url'] + ) + ); + } + } + } + } + + public function FilterLanguage(&$sLanguage, $bAdmin) : void + { + if (!\RainLoop\Api::Config()->Get('webmail', 'allow_languages_on_settings', true)) { + $aResultLang = \SnappyMail\L10n::getLanguages($bAdmin); + $userId = SnappyMailHelper::getUID(); + $userLang = SnappyMailHelper::getConfig()->getUserValue($userId, 'core', 'lang', 'en'); + $userLang = \strtr($userLang, '_', '-'); + $sLanguage = $this->determineLocale($userLang, $aResultLang); + // Check if $sLanguage is null + if (!$sLanguage) { + $sLanguage = 'en'; // Assign 'en' if $sLanguage is null + } + } + } + + /** + * Determine locale from user language. + * + * @param string $langCode The name of the input. + * @param array $languagesArray The value of the array. + * + * @return string return locale + */ + private function determineLocale(string $langCode, array $languagesArray) : ?string + { + // Direct check for the language code + if (\in_array($langCode, $languagesArray)) { + return $langCode; + } + + // Check without country code + if (\str_contains($langCode, '-')) { + $langCode = \explode('-', $langCode)[0]; + if (\in_array($langCode, $languagesArray)) { + return $langCode; + } + } + + // Check with uppercase country code + $langCodeWithUpperCase = $langCode . '-' . \strtoupper($langCode); + if (\in_array($langCodeWithUpperCase, $languagesArray)) { + return $langCodeWithUpperCase; + } + + // If no match is found + return null; + } + + /** + * @param mixed $mResult + */ + public function MainFabrica(string $sName, &$mResult) + { + if (static::isLoggedIn()) { + if ('suggestions' === $sName && $this->Config()->Get('plugin', 'suggestions', true)) { + if (!\is_array($mResult)) { + $mResult = array(); + } + include_once __DIR__ . '/NextcloudContactsSuggestions.php'; + $mResult[] = new NextcloudContactsSuggestions( + $this->Config()->Get('plugin', 'ignoreSystemAddressbook', true) + ); + } +/* + if ($this->Config()->Get('plugin', 'storage', false) && ('storage' === $sName || 'storage-local' === $sName)) { + require_once __DIR__ . '/storage.php'; + $oDriver = new \NextcloudStorage(APP_PRIVATE_DATA.'storage', $sName === 'storage-local'); + } +*/ + } + } + + protected function configMapping() : array + { + return array( + \RainLoop\Plugins\Property::NewInstance('suggestions')->SetLabel('Suggestions') + ->SetType(\RainLoop\Enumerations\PluginPropertyType::BOOL) + ->SetDefaultValue(true), + \RainLoop\Plugins\Property::NewInstance('ignoreSystemAddressbook')->SetLabel('Ignore system addressbook') + ->SetType(\RainLoop\Enumerations\PluginPropertyType::BOOL) + ->SetDefaultValue(true), +/* + \RainLoop\Plugins\Property::NewInstance('storage')->SetLabel('Use Nextcloud user ID in config storage path') + ->SetType(\RainLoop\Enumerations\PluginPropertyType::BOOL) + ->SetDefaultValue(false) +*/ + \RainLoop\Plugins\Property::NewInstance('calendar')->SetLabel('Enable "Put ICS in calendar"') + ->SetType(\RainLoop\Enumerations\PluginPropertyType::BOOL) + ->SetDefaultValue(false) + ); + } + + private static function SmartFileExists(string $sFilePath, $oFiles) : string + { + $sFilePath = \str_replace('\\', '/', \trim($sFilePath)); + + if (!$oFiles->file_exists($sFilePath)) { + return $sFilePath; + } + + $aFileInfo = \pathinfo($sFilePath); + + $iIndex = 0; + + while (true) { + ++$iIndex; + $sFilePathNew = $aFileInfo['dirname'].'/'. + \preg_replace('/\(\d{1,2}\)$/', '', $aFileInfo['filename']). + ' ('.$iIndex.')'. + (empty($aFileInfo['extension']) ? '' : '.'.$aFileInfo['extension']) + ; + if (!$oFiles->file_exists($sFilePathNew)) { + return $sFilePathNew; + } + if (10 < $iIndex) { + break; + } + } + return $sFilePath; + } +} diff --git a/plugins/nextcloud/js/composer.js b/plugins/nextcloud/js/composer.js new file mode 100644 index 000000000..5c2ab7662 --- /dev/null +++ b/plugins/nextcloud/js/composer.js @@ -0,0 +1,68 @@ +(rl => { +// if (rl.settings.get('Nextcloud')) + + addEventListener('rl-view-model.create', e => { + if ('PopupsCompose' === e.detail.viewModelTemplateID) { + let view = e.detail; + view.nextcloudAttach = () => { + rl.nextcloud.selectFiles().then(files => { + let urls = []; + files && files.forEach(file => { + if (file.name) { + let attachment = view.addAttachmentHelper( + Jua?.randomId(), + file.name.replace(/^.*\/([^/]+)$/, '$1'), + file.size + ); + + rl.pluginRemoteRequest( + (iError, data) => { + attachment.uploading(false).complete(true); + if (iError) { + attachment.error(data?.Result?.error || 'failed'); + } else { + attachment.tempName(data.Result.tempName); + } + }, + 'NextcloudAttachFile', + { + 'file': file.name + } + ); + } else if (file.url) { + urls.push(file.url); + } + }); + if (urls.length) { + // TODO: other editors and text/plain + // https://github.com/the-djmaze/snappymail/issues/981 + view.oEditor.editor.squire.insertHTML(urls.join("
")); + } + }); + }; + } + }); + + let template = document.getElementById('PopupsCompose'); + const uploadBtn = template.content.querySelector('#composeUploadButton'); + if (uploadBtn) { + uploadBtn.after(Element.fromHTML(`◦◯◦`)); + } + +/** + https://docs.nextcloud.com/server/latest/developer_manual/client_apis/OCS/ocs-share-api.html + POST /ocs/v2.php/apps/files_sharing/api/v1/shares + JSON { + "path":"/Nextcloud intro.mp4", + "shareType":3, // public link + "shareWith":"user@example.com", +// "publicUpload":false, +// "password":null, +// "permissions":1, // default +// "expireDate":"YYYY-MM-DD", +// "note":"Especially for you" + } +*/ + +})(window.rl); diff --git a/plugins/nextcloud/js/message.js b/plugins/nextcloud/js/message.js new file mode 100644 index 000000000..f5154b745 --- /dev/null +++ b/plugins/nextcloud/js/message.js @@ -0,0 +1,188 @@ +(rl => { +// if (rl.settings.get('Nextcloud')) + const templateId = 'MailMessageView'; + + addEventListener('rl-view-model.create', e => { + if (templateId === e.detail.viewModelTemplateID) { + + const + template = document.getElementById(templateId), + cfg = rl.settings.get('Nextcloud'), + attachmentsControls = template.content.querySelector('.attachmentsControls'), + msgMenu = template.content.querySelector('#more-view-dropdown-id + menu'); + + if (attachmentsControls) { + attachmentsControls.append(Element.fromHTML(` + ✖ + 💾 + + `)); + + // https://github.com/nextcloud/calendar/issues/4684 + if (cfg.CalDAV) { + attachmentsControls.append(Element.fromHTML(` + + `)); + } + } +/* + // https://github.com/the-djmaze/snappymail/issues/592 + if (cfg.CalDAV) { + const attachmentsPlace = template.content.querySelector('.attachmentsPlace'); + attachmentsPlace.after(Element.fromHTML(` + + + + + + + + + +
Summary
Organizer
Start
End
Transparency
`)); + } +*/ + if (msgMenu) { + msgMenu.append(Element.fromHTML(`
  • + +
  • `)); + } + + let view = e.detail; + view.saveNextcloudError = ko.observable(false).extend({ falseTimeout: 7000 }); + view.saveNextcloudLoading = ko.observable(false); + view.saveNextcloud = () => { + const + hashes = (view.message()?.attachments || []) + .map(item => item?.checked() /*&& !item?.isLinked()*/ ? item.download : '') + .filter(v => v); + if (hashes.length) { + view.saveNextcloudLoading(true); + rl.nextcloud.selectFolder().then(folder => { + if (folder) { + rl.fetchJSON('./?/Json/&q[]=/0/', {}, { + Action: 'AttachmentsActions', + target: 'nextcloud', + hashes: hashes, + NcFolder: folder + }) + .then(result => { + view.saveNextcloudLoading(false); + if (result?.Result) { + // success + } else { + view.saveNextcloudError(true); + } + }) + .catch(() => { + view.saveNextcloudLoading(false); + view.saveNextcloudError(true); + }); + } else { + view.saveNextcloudLoading(false); + } + }); + } + }; + + view.nextcloudSaveMsg = () => { + rl.nextcloud.selectFolder().then(folder => { + let msg = view.message(); + folder && rl.pluginRemoteRequest( + (iError, data) => { + console.dir({ + iError:iError, + data:data + }); + }, + 'NextcloudSaveMsg', + { + 'msgHash': msg.requestHash, + 'folder': folder, + 'filename': msg.subject() + } + ); + }); + }; + + view.nextcloudICS = ko.observable(null); + + view.nextcloudSaveICS = () => { + let VEVENT = view.nextcloudICS(); + VEVENT && rl.nextcloud.selectCalendar() + .then(href => href && rl.nextcloud.calendarPut(href, VEVENT)); + } + + /** + * TODO + */ + view.message.subscribe(msg => { + view.nextcloudICS(null); + if (msg && cfg.CalDAV) { +// let ics = msg.attachments.find(attachment => 'application/ics' == attachment.mimeType); + let ics = msg.attachments.find(attachment => 'text/calendar' == attachment.mimeType); + if (ics && ics.download) { + // fetch it and parse the VEVENT + rl.fetch(ics.linkDownload()) + .then(response => (response.status < 400) ? response.text() : Promise.reject(new Error({ response }))) + .then(text => { + let VEVENT, + VALARM, + multiple = ['ATTACH','ATTENDEE','CATEGORIES','COMMENT','CONTACT','EXDATE', + 'EXRULE','RSTATUS','RELATED','RESOURCES','RDATE','RRULE'], + lines = text.split(/\r?\n/), + i = lines.length; + while (i--) { + let line = lines[i]; + if (VEVENT) { + while (line.startsWith(' ') && i--) { + line = lines[i] + line.slice(1); + } + if (line.startsWith('END:VALARM')) { + VALARM = {}; + continue; + } else if (line.startsWith('BEGIN:VALARM')) { + VEVENT.VALARM || (VEVENT.VALARM = []); + VEVENT.VALARM.push(VALARM); + VALARM = null; + continue; + } else if (line.startsWith('BEGIN:VEVENT')) { + break; + } + line = line.match(/^([^:;]+)[:;](.+)$/); + if (line) { + if (VALARM) { + VALARM[line[1]] = line[2]; + } else if (multiple.includes(line[1]) || 'X-' == line[1].slice(0,2)) { + VEVENT[line[1]] || (VEVENT[line[1]] = []); + VEVENT[line[1]].push(line[2]); + } else { + VEVENT[line[1]] = line[2]; + } + } + } else if (line.startsWith('END:VEVENT')) { + VEVENT = {}; + } + } +// METHOD:REPLY || METHOD:REQUEST +// console.dir({VEVENT:VEVENT}); + if (VEVENT) { + VEVENT.rawText = text; + VEVENT.isCancelled = () => VEVENT.STATUS?.includes('CANCELLED'); + VEVENT.isConfirmed = () => VEVENT.STATUS?.includes('CONFIRMED'); + VEVENT.shouldReply = () => VEVENT.METHOD?.includes('REPLY'); + console.dir({ + isCancelled: VEVENT.isCancelled(), + shouldReply: VEVENT.shouldReply() + }); + view.nextcloudICS(VEVENT); + } + }); + } + } + }); + } + }); + +})(window.rl); diff --git a/plugins/nextcloud/js/messagelist.js b/plugins/nextcloud/js/messagelist.js new file mode 100644 index 000000000..8b8681afa --- /dev/null +++ b/plugins/nextcloud/js/messagelist.js @@ -0,0 +1,39 @@ +(rl => { +// if (rl.settings.get('Nextcloud')) + + addEventListener('rl-view-model.create', e => { + if ('MailMessageList' === e.detail.viewModelTemplateID) { + let view = e.detail; + view.nextcloudSaveMsgs = () => { + view.messageList.hasChecked() + && rl.nextcloud.selectFolder().then(folder => { + folder && view.messageList.forEach(msg => { + msg.checked() && rl.pluginRemoteRequest( + (iError, data) => { + console.dir({ + iError:iError, + data:data + }); + }, + 'NextcloudSaveMsg', + { + 'msgHash': msg.requestHash, + 'folder': folder, + 'filename': msg.subject() + } + ); + }); + }); + }; + } + }); + + const msgMenu = document.getElementById('MailMessageList') + .content.querySelector('#more-list-dropdown-id + menu [data-bind*="forwardCommand"]'); + if (msgMenu) { + msgMenu.after(Element.fromHTML(`
  • + +
  • `)); + } + +})(window.rl); diff --git a/plugins/nextcloud/js/webdav.js b/plugins/nextcloud/js/webdav.js new file mode 100644 index 000000000..24aa1f226 --- /dev/null +++ b/plugins/nextcloud/js/webdav.js @@ -0,0 +1,502 @@ +(rl => { + +const + nsDAV = 'DAV:', + nsNC = 'http://nextcloud.org/ns', + nsOC = 'http://owncloud.org/ns', + nsOCS = 'http://open-collaboration-services.org/ns', + nsCalDAV = 'urn:ietf:params:xml:ns:caldav', + + OC = () => parent.OC, + + // Nextcloud 19 deprecated generateUrl, but screw `import { generateUrl } from "@nextcloud/router"` + shareUrl = () => OC().webroot + '/ocs/v2.php/apps/files_sharing/api/v1/shares', + generateUrl = path => OC().webroot + (OC().config.modRewriteWorking ? '' : '/index.php') + path, + generateRemoteUrl = path => location.protocol + '//' + location.host + generateUrl(path), + +// shareTypes = {0 = user, 1 = group, 3 = public link} + + propfindFiles = ` + + + + + + + + + +`, + + propfindCal = ` + + + + + + + +`, + + xmlParser = new DOMParser(), + pathRegex = /.*\/remote.php\/dav\/[^/]+\/[^/]+/g, + + getElementsByTagName = (parent, namespace, localName) => parent.getElementsByTagNameNS(namespace, localName), + getDavElementsByTagName = (parent, localName) => getElementsByTagName(parent, nsDAV, localName), + getDavElementByTagName = (parent, localName) => getDavElementsByTagName(parent, localName)?.item(0), + getElementByTagName = (parent, localName) => +parent.getElementsByTagName(localName)?.item(0), + + ncFetch = (path, options) => { + if (!OC().requestToken) { + return Promise.reject(new Error('OC.requestToken missing')); + } + options = Object.assign({ + mode: 'same-origin', + cache: 'no-cache', + redirect: 'error', + credentials: 'same-origin', + headers: {} + }, options); + options.headers.requesttoken = OC().requestToken; + return fetch(path, options); + }, + + davFetch = (mode, path, options) => { + let cfg = rl.settings.get('Nextcloud'); +// cfg.UID = document.head.dataset.user + return ncFetch(cfg.WebDAV + '/' + mode + '/' + cfg.UID + path, options); + }, + + davFetchFiles = (path, options) => davFetch('files', path, options), + + createDirectory = path => davFetchFiles(path, { method: 'MKCOL' }), + + fetchFiles = path => { + if (!OC().requestToken) { + return Promise.reject(new Error('OC.requestToken missing')); + } + return davFetchFiles(path, { + method: 'PROPFIND', + headers: { + 'Content-Type': 'application/xml; charset=utf-8' + }, + body: propfindFiles + }) + .then(response => (response.status < 400) ? response.text() : Promise.reject(new Error({ response }))) + .then(text => { + const + elemList = [], + responseList = getDavElementsByTagName( + xmlParser.parseFromString(text, 'application/xml').documentElement, + 'response' + ); + path = path.replace(/\/$/, ''); + for (let i = 0; i < responseList.length; ++i) { + const + e = responseList.item(i), + elem = { + name: decodeURIComponent(getDavElementByTagName(e, 'href').textContent + .replace(pathRegex, '').replace(/\/$/, '')), + isFile: false + }; + if (getDavElementsByTagName(getDavElementByTagName(e, 'resourcetype'), 'collection').length) { + // skip current directory + if (elem.name === path) { + continue; + } + } else { + elem.isFile = true; + elem.id = e.getElementsByTagNameNS(nsOC, 'fileid')?.item(0)?.textContent; + elem.size = getDavElementByTagName(e, 'getcontentlength')?.textContent + || getElementByTagName(e, 'oc:size')?.textContent; + elem.shared = [...e.getElementsByTagNameNS(nsOC, 'share-type')].some(node => '3' == node.textContent); + } + elemList.push(elem); + } + // https://github.com/the-djmaze/snappymail/issues/1177 +// elemList.sort((a, b) => a.isFile != b.isFile ? (a.isFile ? 1 : -1) : a.name.localeCompare(b.name)); + return Promise.resolve(elemList); + }); + }, + + buildTree = (view, parent, items, path) => { + if (items.length) { + try { + // https://github.com/the-djmaze/snappymail/issues/1109 + let collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'}); + items.sort((a, b) => collator.compare(a.name, b.name)); + } catch (e) { + console.error(e); + } + items.forEach(item => { + if (!item.isFile) { + let li = document.createElement('li'), + details = document.createElement('details'), + summary = document.createElement('summary'), + ul = document.createElement('ul'); + details.addEventListener('toggle', () => { + ul.children.length + || fetchFiles(item.name).then(items => buildTree(view, ul, items, item.name)); + }); + summary.textContent = item.name.replace(/^.*\/([^/]+)$/, '$1'); + summary.dataset.icon = '📁'; + if (!view.files()) { + let btn = document.createElement('button'); + btn.name = 'select'; + btn.textContent = 'select'; + btn.className = 'button-vue'; + summary.append(btn); + summary.item_name = item.name; + } + details.append(summary); + details.append(ul); +// a.append('- ' + item.name.replace(/^\/+/, '')); + li.append(details); + parent.append(li); + } + }); + if (view.files()) { + items.forEach(item => { + if (item.isFile) { + let li = document.createElement('li'), + cb = document.createElement('input'); + + li.item = item; + li.textContent = item.name.replace(/^.*\/([^/]+)$/, '$1'); + li.dataset.icon = '🗎'; + + cb.type = 'checkbox'; + li.append(cb); + + parent.append(li); + } + }); + } + } + if (!view.files()) { + let li = document.createElement('li'), + input = document.createElement('input'), + btn = document.createElement('button'); + btn.name = 'create'; + btn.textContent = 'create & select'; + btn.className = 'button-vue'; + btn.input = input; + li.item_path = path; + li.append(input); + li.append(btn); + parent.append(li); + } + }; + +class NextcloudFilesPopupView extends rl.pluginPopupView { + constructor() { + super('NextcloudFiles'); + this.addObservables({ + files: false + }); + } + + attach() { + this.select = []; + this.tree.querySelectorAll('input').forEach(input => + input.checked && this.select.push(input.parentNode.item) + ); + this.close(); + } + + shareInternal() { + this.select = []; + this.tree.querySelectorAll('input').forEach(input => + input.checked && this.select.push({url:generateRemoteUrl(`/f/${input.parentNode.item.id}`)}) + ); + this.close(); + } + + sharePublic() { + const inputs = [...this.tree.querySelectorAll('input')], + loop = () => { + if (!inputs.length) { + this.close(); + return; + } + const input = inputs.pop(); + if (!input.checked) { + loop(); + } else { + const item = input.parentNode.item; + if (item.shared) { + ncFetch( + shareUrl() + `?format=json&path=${encodeURIComponent(item.name)}&reshares=true` + ) + .then(response => (response.status < 400) ? response.json() : Promise.reject(new Error({ response }))) + .then(json => { + this.select.push({url:json.ocs.data[0].url}); + loop(); +// json.data[0].password + }); + } else { + ncFetch( + shareUrl(), + { + method:'POST', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + path:item.name, + shareType:3, + attributes:"[]" + }) + } + ) + .then(response => (response.status < 400) ? response.json() : Promise.reject(new Error({ response }))) + .then(json => { +// PUT /ocs/v2.php/apps/files_sharing/api/v1/shares/2 {"password":"ABC09"} + this.select.push({url:json.ocs.data.url}); + loop(); + }); + } + } + }; + + this.select = []; + loop(); + } + + onBuild(dom) { + this.tree = dom.querySelector('#sm-nc-files-tree'); + this.tree.addEventListener('click', event => { + let el = event.target; + if (el.matches('button')) { + let parent = el.parentNode; + if ('select' == el.name) { + this.select = parent.item_name; + this.close(); + } else if ('create' == el.name) { + let name = el.input.value.replace(/[|\\?*<":>+[]\/&\s]/g, ''); + if (name.length) { + name = parent.item_path + '/' + name; + createDirectory(name).then(response => { + if (response.status == 201) { + this.select = name; + this.close(); + } + }); + } + } + } + }); + } + + // Happens after showModal() + beforeShow(files, fResolve) { + this.select = ''; + this.files(!!files); + this.fResolve = fResolve; + + this.tree.innerHTML = ''; + fetchFiles('/').then(items => { + buildTree(this, this.tree, items, '/'); + }).catch(err => console.error(err)) + } + + onHide() { + this.fResolve(this.select); + } +/* +beforeShow() {} // Happens before showModal() +onShow() {} // Happens after showModal() +afterShow() {} // Happens after showModal() animation transitionend +onHide() {} // Happens before animation transitionend +afterHide() {} // Happens after animation transitionend +close() {} +*/ +} + +class NextcloudCalendarsPopupView extends rl.pluginPopupView { + constructor() { + super('NextcloudCalendars'); + } + + onBuild(dom) { + this.tree = dom.querySelector('#sm-nc-calendars'); + this.tree.addEventListener('click', event => { + let el = event.target; + if (el.matches('button')) { + this.select = el.href; + this.close(); + } + }); + } + createCalendarListItem(calendarData, treeElement) { + const { + displayName, + href, + calendarColor + } = calendarData; + + const li = document.createElement('li'); + li.style.display = 'flex'; + + const span = document.createElement('span'); + span.setAttribute('role', 'img'); + span.className = 'material-design-icon checkbox-blank-circle-icon'; + span.style.fill = calendarColor; + span.style.width = '20px'; + span.style.height = '20px'; + + const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + svg.setAttribute('width', '20'); + svg.setAttribute('height', '20'); + svg.setAttribute('viewBox', '0 0 24 24'); + + const path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + path.setAttribute('d', 'M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z'); + svg.appendChild(path); + + span.appendChild(svg); + + const button = document.createElement('button'); + button.className = 'button-vue'; + button.style.backgroundColor = 'transparent'; + button.style.border = '0'; + button.style.fontSize = 'large'; + button.style.padding = '0'; + button.style.cursor = 'pointer'; + button.style.marginLeft = '5px'; + button.href = href.replace(pathRegex, '').replace(/\/$/, ''); + button.textContent = displayName; + button.style.color = '#1968DF'; + + li.appendChild(span); + li.appendChild(button); + + treeElement.appendChild(li); + } + // Happens after showModal() + beforeShow(fResolve) { + this.select = ''; + this.fResolve = fResolve; + this.tree.innerHTML = ''; + davFetch('calendars', '/', { + method: 'PROPFIND', + headers: { + 'Content-Type': 'application/xml; charset=utf-8' + }, + body: propfindCal + }) + .then(response => (response.status < 400) ? response.text() : Promise.reject(new Error({ response }))) + .then(text => { + // Parse the XML text + const xmlDoc = xmlParser.parseFromString(text, 'application/xml').documentElement; + const responseList = getElementsInNamespaces(xmlDoc, 'response'); + for (let i = 0; i < responseList.length; ++i) { + const e = responseList[i]; + if (getDavElementByTagName(e, 'resourcetype').getElementsByTagNameNS(nsCalDAV, 'calendar').length) { + const displayNameElement = getElementsInNamespaces(e, 'displayname')[0]; + const displayName = displayNameElement ? displayNameElement.textContent.trim() : ''; + + const hrefElement = getElementsInNamespaces(e, 'href')[0]; + const href = hrefElement ? hrefElement.textContent.trim() : ''; + + const calendarColorElement = getElementsInNamespaces(e, 'calendar-color')[0]; + const calendarColor = calendarColorElement ? calendarColorElement.textContent.trim() : '#000000'; + + // Create an object to hold calendar data + const calendarData = { + displayName, + href, + calendarColor + }; + + // Call the function to create and append the list item + this.createCalendarListItem(calendarData, this.tree); + } + } + }) + .catch(err => console.error(err)); + } + + onHide() { + this.fResolve(this.select); + } +/* +beforeShow() {} // Happens before showModal() +onShow() {} // Happens after showModal() +afterShow() {} // Happens after showModal() animation transitionend +onHide() {} // Happens before animation transitionend +afterHide() {} // Happens after animation transitionend +close() {} +*/ +} + +rl.nextcloud = { + selectCalendar: () => + new Promise(resolve => { + NextcloudCalendarsPopupView.showModal([ + href => resolve(href), + ]); + }), + + calendarPut: (path, event) => { + davFetch('calendars', path + '/' + event.UID + '.ics', { + method: 'PUT', + headers: { + 'Content-Type': 'text/calendar' + }, + // Validation error in iCalendar: A calendar object on a CalDAV server MUST NOT have a METHOD property. + body: event.rawText + .replace('METHOD:', 'X-METHOD:') + // https://github.com/nextcloud/calendar/issues/4684 + .replace('ATTENDEE:', 'X-ATTENDEE:') + .replace('ORGANIZER:', 'X-ORGANIZER:') + .replace(/RSVP=TRUE/g, 'RSVP=FALSE') + .replace(/\r?\n/g, '\r\n') + }) + .then(response => { + if (201 == response.status) { + // Created + } else if (204 == response.status) { + // Not modified + } else { +// response.text().then(text => console.error({status:response.status, body:text})); + Promise.reject(new Error({ response })); + } + }); + }, + + selectFolder: () => + new Promise(resolve => { + NextcloudFilesPopupView.showModal([ + false, + folder => resolve(folder), + ]); + }), + + selectFiles: () => + new Promise(resolve => { + NextcloudFilesPopupView.showModal([ + true, + files => resolve(files), + ]); + }) +}; + +})(window.rl); + +function getElementsInNamespaces(xmlDocument, tagName) { + const namespaces = { + d: 'DAV:', + x1: 'http://apple.com/ns/ical/', + }; + const results = []; + for (const prefix in namespaces) { + const namespaceURI = namespaces[prefix]; + const elements = xmlDocument.getElementsByTagNameNS(namespaceURI, tagName); + for (const element of elements) { + results.push(element); + } + } + return results; +} diff --git a/plugins/nextcloud/langs/de.json b/plugins/nextcloud/langs/de.json new file mode 100644 index 000000000..5f43f1357 --- /dev/null +++ b/plugins/nextcloud/langs/de.json @@ -0,0 +1,14 @@ +{ + "NEXTCLOUD": { + "SAVE_ATTACHMENTS": "Speichern Sie in Nextcloud", + "SAVE_EML": "Als .eml in Nextcloud speichern", + "SAVE_ICS": "Kalender eintragen", + "SELECT_FOLDER": "Ordner auswählen", + "SELECT_FILES": "Datei(en) auswählen", + "ATTACH_FILES": "Nextcloud-Dateien anhängen", + "SELECT_CALENDAR": "Kalender auswählen", + "FILE_ATTACH": "anfügen", + "FILE_INTERNAL": "intern", + "FILE_PUBLIC": "öffentlich" + } +} diff --git a/plugins/nextcloud/langs/en.json b/plugins/nextcloud/langs/en.json new file mode 100644 index 000000000..2c19d11c2 --- /dev/null +++ b/plugins/nextcloud/langs/en.json @@ -0,0 +1,14 @@ +{ + "NEXTCLOUD": { + "SAVE_ATTACHMENTS": "Save in Nextcloud", + "SAVE_EML": "Save as .eml in Nextcloud", + "SAVE_ICS": "Add to calendar", + "SELECT_FOLDER": "Select folder", + "SELECT_FILES": "Select file(s)", + "ATTACH_FILES": "Attach Nextcloud files", + "SELECT_CALENDAR": "Select calendar", + "FILE_ATTACH": "attach", + "FILE_INTERNAL": "internal", + "FILE_PUBLIC": "public" + } +} diff --git a/plugins/nextcloud/langs/pl.json b/plugins/nextcloud/langs/pl.json new file mode 100644 index 000000000..82e0d4f18 --- /dev/null +++ b/plugins/nextcloud/langs/pl.json @@ -0,0 +1,14 @@ +{ + "NEXTCLOUD": { + "SAVE_ATTACHMENTS": "Zapisz w Nextcloudzie", + "SAVE_EML": "Zapisz jako .eml w Nextcloudzie", + "SAVE_ICS": "Dodaj do Kalendarza", + "SELECT_FOLDER": "Wybierz folder", + "SELECT_FILES": "Wybierz plik(i)", + "ATTACH_FILES": "Dodaj załącznik z Nextclouda", + "SELECT_CALENDAR": "Wybierz kalendarz", + "FILE_ATTACH": "dołącz", + "FILE_INTERNAL": "link wewnętrzny", + "FILE_PUBLIC": "link publiczny" + } +} diff --git a/plugins/nextcloud/langs/ru.json b/plugins/nextcloud/langs/ru.json new file mode 100644 index 000000000..a8b28372d --- /dev/null +++ b/plugins/nextcloud/langs/ru.json @@ -0,0 +1,14 @@ +{ + "NEXTCLOUD": { + "SAVE_ATTACHMENTS": "Сохранить в Nextcloud", + "SAVE_EML": "Сохранить как .eml в Nextcloud", + "SAVE_ICS": "Вставить в календарь", + "SELECT_FOLDER": "Выбрите папку", + "SELECT_FILES": "Выберите файл(ы)", + "ATTACH_FILES": "Прикрепить файлы из Nextcloud", + "SELECT_CALENDAR": "Выбрать календарь", + "FILE_ATTACH": "Прикрепить с ПК", + "FILE_INTERNAL": "Внутреняя", + "FILE_PUBLIC": "Публичная" + } +} diff --git a/plugins/nextcloud/langs/zh-TW.json b/plugins/nextcloud/langs/zh-TW.json new file mode 100644 index 000000000..292d02286 --- /dev/null +++ b/plugins/nextcloud/langs/zh-TW.json @@ -0,0 +1,14 @@ +{ + "NEXTCLOUD": { + "SAVE_ATTACHMENTS": "儲存到 Nextcloud", + "SAVE_EML": "以 .eml 檔案儲存到 Nextcloud", + "SAVE_ICS": "新增到日曆", + "SELECT_FOLDER": "選擇檔案夾", + "SELECT_FILES": "選擇檔案", + "ATTACH_FILES": "新增 Nextcloud 檔案", + "SELECT_CALENDAR": "選擇日曆", + "FILE_ATTACH": "附加", + "FILE_INTERNAL": "內部", + "FILE_PUBLIC": "公開" + } +} diff --git a/plugins/nextcloud/langs/zh.json b/plugins/nextcloud/langs/zh.json new file mode 100644 index 000000000..39b20ac2e --- /dev/null +++ b/plugins/nextcloud/langs/zh.json @@ -0,0 +1,14 @@ +{ + "NEXTCLOUD": { + "SAVE_ATTACHMENTS": "保存到 Nextcloud", + "SAVE_EML": "以 .eml 文件保存到 Nextcloud", + "SAVE_ICS": "添加到日历", + "SELECT_FOLDER": "选择文件夹", + "SELECT_FILES": "选择文件", + "ATTACH_FILES": "添加 Nextcloud 文件", + "SELECT_CALENDAR": "选择日历", + "FILE_ATTACH": "附加", + "FILE_INTERNAL": "内部", + "FILE_PUBLIC": "公开" + } +} diff --git a/plugins/nextcloud/storage.php b/plugins/nextcloud/storage.php new file mode 100644 index 000000000..90b5f313e --- /dev/null +++ b/plugins/nextcloud/storage.php @@ -0,0 +1,22 @@ + + × +

    + + diff --git a/plugins/nextcloud/templates/PopupsNextcloudFiles.html b/plugins/nextcloud/templates/PopupsNextcloudFiles.html new file mode 100644 index 000000000..dcc03d7e8 --- /dev/null +++ b/plugins/nextcloud/templates/PopupsNextcloudFiles.html @@ -0,0 +1,18 @@ +
    + × +

    +

    +
    + +
    + + + +
    diff --git a/plugins/override-smtp-credentials/index.php b/plugins/override-smtp-credentials/index.php index ef9d6057e..e524bef71 100644 --- a/plugins/override-smtp-credentials/index.php +++ b/plugins/override-smtp-credentials/index.php @@ -4,55 +4,71 @@ class OverrideSmtpCredentialsPlugin extends \RainLoop\Plugins\AbstractPlugin { const NAME = 'Override SMTP Credentials', - VERSION = '2.2', - RELEASE = '2022-04-13', - REQUIRED = '2.5.0', + VERSION = '2.5', + RELEASE = '2024-03-12', + REQUIRED = '2.35.3', CATEGORY = 'Filters', DESCRIPTION = 'Override SMTP credentials for specific users.'; public function Init() : void { - $this->addHook('smtp.before-connect', 'FilterSmtpCredentials'); + $this->addHook('smtp.before-connect', 'FilterSmtpConnect'); $this->addHook('smtp.before-login', 'FilterSmtpCredentials'); } /** * @param \RainLoop\Model\Account $oAccount * @param \MailSo\Smtp\SmtpClient $oSmtpClient - * @param array $aSmtpCredentials + * @param \MailSo\Smtp\Settings $oSettings */ - public function FilterSmtpCredentials($oAccount, $oSmtpClient, &$aSmtpCredentials) + public function FilterSmtpConnect(\RainLoop\Model\Account $oAccount, \MailSo\Smtp\SmtpClient $oSmtpClient, \MailSo\Smtp\Settings $oSettings) { - if ($oAccount instanceof \RainLoop\Model\Account && \is_array($aSmtpCredentials)) - { - $sEmail = $oAccount->Email(); - + $sEmail = $oAccount->Email(); + $sWhiteList = \trim($this->Config()->Get('plugin', 'override_users', '')); + $sFoundValue = ''; + if (\strlen($sWhiteList) && \RainLoop\Plugins\Helper::ValidateWildcardValues($sEmail, $sWhiteList, $sFoundValue)) { + \SnappyMail\LOG::debug('SMTP Override', "{$sEmail} matched {$sFoundValue}"); + $oSettings->usePhpMail = false; $sHost = \trim($this->Config()->Get('plugin', 'smtp_host', '')); - $sWhiteList = \trim($this->Config()->Get('plugin', 'override_users', '')); - - if (0 < strlen($sWhiteList) && 0 < \strlen($sHost) && \RainLoop\Plugins\Helper::ValidateWildcardValues($sEmail, $sWhiteList)) - { - $aSmtpCredentials['Host'] = $sHost; - $aSmtpCredentials['Port'] = (int) $this->Config()->Get('plugin', 'smtp_port', 25); - + if (\strlen($sHost)) { + $oSettings->host = $sHost; + $oSettings->port = (int) $this->Config()->Get('plugin', 'smtp_port', 25); $sSecure = \trim($this->Config()->Get('plugin', 'smtp_secure', 'None')); switch ($sSecure) { case 'SSL': - $aSmtpCredentials['Secure'] = MailSo\Net\Enumerations\ConnectionSecurityType::SSL; + $oSettings->type = MailSo\Net\Enumerations\ConnectionSecurityType::SSL; break; case 'TLS': - $aSmtpCredentials['Secure'] = MailSo\Net\Enumerations\ConnectionSecurityType::STARTTLS; + case 'STARTTLS': + $oSettings->type = MailSo\Net\Enumerations\ConnectionSecurityType::STARTTLS; + break; + case 'Detect': + $oSettings->type = MailSo\Net\Enumerations\ConnectionSecurityType::AUTO_DETECT; break; default: - $aSmtpCredentials['Secure'] = MailSo\Net\Enumerations\ConnectionSecurityType::NONE; + $oSettings->type = MailSo\Net\Enumerations\ConnectionSecurityType::NONE; break; } - - $aSmtpCredentials['UseAuth'] = (bool) $this->Config()->Get('plugin', 'smtp_auth', true); - $aSmtpCredentials['Login'] = \trim($this->Config()->Get('plugin', 'smtp_user', '')); - $aSmtpCredentials['Password'] = (string) $this->Config()->Get('plugin', 'smtp_password', ''); } + } else { + \SnappyMail\LOG::debug('SMTP Override', "{$sEmail} no match"); + } + } + + /** + * @param \RainLoop\Model\Account $oAccount + * @param \MailSo\Smtp\SmtpClient $oSmtpClient + * @param \MailSo\Smtp\Settings $oSettings + */ + public function FilterSmtpCredentials(\RainLoop\Model\Account $oAccount, \MailSo\Smtp\SmtpClient $oSmtpClient, \MailSo\Smtp\Settings $oSettings) + { + $sWhiteList = \trim($this->Config()->Get('plugin', 'override_users', '')); + $sFoundValue = ''; + if (\strlen($sWhiteList) && \RainLoop\Plugins\Helper::ValidateWildcardValues($oAccount->Email(), $sWhiteList, $sFoundValue)) { + $oSettings->useAuth = (bool) $this->Config()->Get('plugin', 'smtp_auth', true); + $oSettings->username = \trim($this->Config()->Get('plugin', 'smtp_user', '')); + $oSettings->passphrase = (string) $this->Config()->Get('plugin', 'smtp_password', ''); } } @@ -69,7 +85,7 @@ class OverrideSmtpCredentialsPlugin extends \RainLoop\Plugins\AbstractPlugin ->SetDefaultValue(25), \RainLoop\Plugins\Property::NewInstance('smtp_secure')->SetLabel('SMTP Secure') ->SetType(\RainLoop\Enumerations\PluginPropertyType::SELECTION) - ->SetDefaultValue(array('None', 'SSL', 'TLS')), + ->SetDefaultValue(array('None', 'Detect', 'SSL', 'STARTTLS')), \RainLoop\Plugins\Property::NewInstance('smtp_auth')->SetLabel('Use auth') ->SetType(\RainLoop\Enumerations\PluginPropertyType::BOOL) ->SetDefaultValue(true), diff --git a/plugins/proxy-auth/LICENSE b/plugins/proxy-auth/LICENSE new file mode 100644 index 000000000..172df18fd --- /dev/null +++ b/plugins/proxy-auth/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2023 Philipp Mundhenk + +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/plugins/proxy-auth/README.md b/plugins/proxy-auth/README.md new file mode 100644 index 000000000..c9db401e6 --- /dev/null +++ b/plugins/proxy-auth/README.md @@ -0,0 +1,91 @@ +# SnappyMail Proxy Auth + +This plugin allows to authenticate a user through the remote user header, effectively allowing single-sign on. +This is achieved through "master user"-like functionality. + +## Example Configuration + +The exact setup depends on your mailserver, reverse proxy, authentication solution, etc. +The following example is for Traefik with Authelia and Dovecot as mailserver. + +### SnappyMail + +The following steps are require in SnappyMail: + +- To open SnappyMail through a reverse proxy server (with redirect of authentication system), make sure to enable the correct secfetch policies: ```mode=navigate,dest=document,site=cross-site,user=true;mode=navigate,dest=document,site=same-site,user=true``` in the admin panel -> Config -> Security -> secfetch_allow. +- Activate plugin in admin panel -> Extensions +- Configure the plugin with the required data: + - Master User Separator is dependent on Dovecot config (see below) + - Master User is dependent on Dovecot config (see below) + - Master User Password is dependent on Dovecot config (see below) + - Header Name is dependent on authentication solution. This is the header containing the name of currently logged in user. In case of Authelia, this is "Remote-User". + - Automatic Login: Automatically logs in the user of user header is present (see below) + +> **Security note** +> +> This plugin trusts the configured request header as proof of identity. Anyone who can reach the SnappyMail container directly and set that header can log in as any user. You **must** ensure that SnappyMail is only reachable through your reverse proxy / SSO chain (e.g. via the docker network, a firewall, or by binding SnappyMail to a non-public interface) and that the upstream proxy strips any client-supplied value of the header before forwarding. The plugin itself does no source-IP validation — earlier versions had a `check_proxy` option, but it inspected the forwarded client IP (the end user's IP) and therefore did not actually verify that the request came from the proxy. It has been removed; gate access at the network layer instead. + +This concludes the setup of SnappyMail. + +### Dovecot + +In Dovecot, you need to enable Master User. +Enable ```!include auth-master.conf.ext``` in /etc/dovecot/conf.d/10-auth.conf. +In Dovecot 2.3, the file /etc/dovecot/conf.d/auth-master.conf.ext should contain: +``` +passdb { + driver = passwd-file + master = yes + args = /etc/dovecot/master-users + pass = yes +} +``` + +In Dovecot 2.4, the file /etc/dovecot/conf.d/auth-master.conf.ext should contain: +``` +passdb passwd-file { + master = yes + passwd_file_path = /etc/dovecot/master-users + result_success = continue +} +``` + +You then need to create a master user in /etc/dovecot/master-users: +``` +admin:PASSWORD::::::allow_nets=local,172.17.0.0/16 +``` +where the encrypted password ```PASSWORD``` can be created from a cleartext password with ```doveadm pw -s CRYPT```. +It should start with ```{CRYPT}```. +Username and password need to configured in the SnappyMail ProxyAuth plugin (see above). + +You likely also want to limit the access by an IP address filter, e.g., to ```local,172.17.0.0/16```, if you are running Postfix (```local```) and within a default Docker environment (```172.17.0.0/16```). +Otherwise, master user login (assuming password is known) is possible from every connectable system. +This is an unnecessary security risk. + +Additionally, you need to set the master user separator in /etc/dovecot/conf.d/10-auth.conf, e.g., ```auth_master_user_separator = *```. +The separator needs to be configured in the SnappyMail ProxyAuth plugin (see above). + +## Test + +Once configured correctly, you should be able to access SnappyMail through your reverse proxy at ```https://snappymail.tld/?ProxyAuth```. +If your reverse proxy provides the username in the configured header (e.g., Remote-User), you will automatically be logged in to your account. +If not, you will be redirected to the login page. + +## Automatic Login + +By default, automatic login is activated. +Behind the scenes, this checks for the existence of the configured user header (through ```/?UserHeaderSet```) and automatically redirects to ```https://snappymail.tld/?ProxyAuth```, trying to log in the user. +Note that due to this implementation, logout is impossible, as once logged out, the user will automatically be logged in again. +The user is always considered logged in, as authentication is handled through reverse proxy and authentication system. + +Auto login can be disabled in the plugin settings. +You can also change the logout link in admin panel -> Config -> custom_logout_link to the one of your authentication system, e.g., ```https://auth.yourdomain.com/logout```. +In this case, you can log out from your overall system via SnappyMail. + +## Troubleshooting + +### IMAP `AUTHENTICATIONFAILED` after a container rebuild / upgrade + +The master user/password fields are encrypted at rest using SnappyMail's `APP_SALT`. If that salt is regenerated (e.g., the data volume was reset, the container was rebuilt without persisting `_data_`, or the salt file was rotated), the values in `plugin-proxy-auth.json` can no longer be decrypted. `getDecrypted()` then silently returns `null`, an empty password is passed to IMAP, and Dovecot rejects the login with `AUTHENTICATIONFAILED`. + +Fix: open admin panel -> Extensions -> Proxy Auth, re-enter the Master User and Master Password (and any other previously-set encrypted fields), and save. The values will be re-encrypted under the current salt. diff --git a/plugins/proxy-auth/index.php b/plugins/proxy-auth/index.php new file mode 100644 index 000000000..36db5d9c2 --- /dev/null +++ b/plugins/proxy-auth/index.php @@ -0,0 +1,139 @@ +addJs('js/auto-login.js'); + $this->addPartHook('ProxyAuth', 'ServiceProxyAuth'); + $this->addPartHook('UserHeaderSet', 'ServiceUserHeaderSet'); + $this->addHook('login.credentials', 'MapEmailAddress'); + } + + public function MapEmailAddress(string &$sEmail, string &$sImapUser, string &$sPassword, string &$sSmtpUser) + { + $oActions = \RainLoop\Api::Actions(); + $oLogger = $oActions->Logger(); + $sPrefix = "ProxyAuth"; + $sLevel = LOG_DEBUG; + $sMsg = "sEmail= " . $sEmail; + $oLogger->Write($sMsg, $sLevel, $sPrefix); + + $sMasterUser = \trim($this->Config()->getDecrypted('plugin', 'master_user', '')); + $sMasterSeparator = \trim($this->Config()->getDecrypted('plugin', 'master_separator', '')); + + /* remove superuser from email for proper UI */ + if (static::$login) { + $sEmail = str_replace($sMasterUser, "", $sEmail); + $sEmail = str_replace($sMasterSeparator, "", $sEmail); + } + } + + private static bool $login = false; + public function ServiceProxyAuth() : bool + { + $oActions = \RainLoop\Api::Actions(); + + $oException = null; + $oAccount = null; + + $oLogger = $oActions->Logger(); + $sLevel = LOG_DEBUG; + $sPrefix = "ProxyAuth"; + + $sMasterUser = \trim($this->Config()->getDecrypted('plugin', 'master_user', '')); + $sMasterSeparator = \trim($this->Config()->getDecrypted('plugin', 'master_separator', '')); + $sHeaderName = \trim($this->Config()->getDecrypted('plugin', 'header_name', '')); + + $sRemoteUser = $this->Manager()->Actions()->Http()->GetHeader($sHeaderName); + $sMsg = "Remote User: " . $sRemoteUser; + $oLogger->Write($sMsg, $sLevel, $sPrefix); + + /* create master user login from remote user header and settings */ + $sEmail = $sRemoteUser . $sMasterSeparator . $sMasterUser; + $sPassword = new \SnappyMail\SensitiveString(\trim($this->Config()->getDecrypted('plugin', 'master_password', ''))); + + try + { + static::$login = true; + $oAccount = $oActions->LoginProcess($sEmail, $sPassword); + } + catch (\Throwable $oException) + { + $oLogger = $oActions->Logger(); + $oLogger && $oLogger->WriteException($oException); + } + + \MailSo\Base\Http::Location('./'); + return true; + } + + public function ServiceUserHeaderSet() : bool + { + $oActions = \RainLoop\Api::Actions(); + + $oLogger = $oActions->Logger(); + $sLevel = LOG_DEBUG; + $sPrefix = "ProxyAuth"; + + $sHeaderName = \trim($this->Config()->getDecrypted('plugin', 'header_name', '')); + + $sRemoteUser = $this->Manager()->Actions()->Http()->GetHeader($sHeaderName); + $sMsg = "Remote User: " . $sRemoteUser; + $oLogger->Write($sMsg, $sLevel, $sPrefix); + + if (strlen($sRemoteUser) > 0) { + \MailSo\Base\Http::StatusHeader('200'); + } else { + \MailSo\Base\Http::StatusHeader('401'); + } + return true; + } + + protected function configMapping() : array + { + return array( + \RainLoop\Plugins\Property::NewInstance('master_separator') + ->SetLabel('Master User separator') + ->SetType(\RainLoop\Enumerations\PluginPropertyType::STRING_TEXT) + ->SetDescription('Sets the master user separator (format: )') + ->SetDefaultValue('*') + ->SetEncrypted(), + \RainLoop\Plugins\Property::NewInstance('master_user') + ->SetLabel('Master User') + ->SetType(\RainLoop\Enumerations\PluginPropertyType::STRING_TEXT) + ->SetDescription('Username of master user') + ->SetDefaultValue('admin') + ->SetEncrypted(), + \RainLoop\Plugins\Property::NewInstance('master_password') + ->SetLabel('Master Password') + ->SetType(\RainLoop\Enumerations\PluginPropertyType::STRING_TEXT) + ->SetDescription('Password for master user') + ->SetDefaultValue('adminpassword') + ->SetEncrypted(), + \RainLoop\Plugins\Property::NewInstance('header_name') + ->SetLabel('Header Name') + ->SetType(\RainLoop\Enumerations\PluginPropertyType::STRING_TEXT) + ->SetDescription('Name of header containing username') + ->SetDefaultValue('Remote-User') + ->SetEncrypted(), + \RainLoop\Plugins\Property::NewInstance('auto_login') + ->SetAllowedInJs(true) + ->SetLabel('Activate automatic login') + ->SetType(\RainLoop\Enumerations\PluginPropertyType::BOOL) + ->SetDescription('Activates automatic login, if User Header is set (note: Use custom_logout_link to enable logout, see plugin README)') + ->SetDefaultValue(true) + ); + } +} diff --git a/plugins/proxy-auth/js/auto-login.js b/plugins/proxy-auth/js/auto-login.js new file mode 100644 index 000000000..ba5e0e617 --- /dev/null +++ b/plugins/proxy-auth/js/auto-login.js @@ -0,0 +1,32 @@ +(rl => { + + rl && addEventListener('rl-view-model', e => { + const id = e.detail.viewModelTemplateID; + if (e.detail && ('Login' === id)) { + let + auto_login = window.rl.pluginSettingsGet('proxy-auth', 'auto_login'); + ; + + const + ForwardProxyAuth = () => { + if (auto_login) { + var xhr = new XMLHttpRequest(); + xhr.open("GET", "?UserHeaderSet", true); + + xhr.onreadystatechange = function () { + if (xhr.readyState == 4 && xhr.status == 200) { + window.location.href = "?ProxyAuth"; + } + }; + + xhr.send(); + } + }; + + window.ForwardProxyAuth = ForwardProxyAuth; + + ForwardProxyAuth(); + } + }); +})(window.rl); + diff --git a/plugins/proxyauth-login-example/index.php b/plugins/proxyauth-login-example/index.php deleted file mode 100644 index afa590482..000000000 --- a/plugins/proxyauth-login-example/index.php +++ /dev/null @@ -1,57 +0,0 @@ -addHook('login.success', 'EventLoginPostLoginProvide'); - } - - /** - * @param string $sLogin - * @param string $sPassword - */ - public function isValidAccount($sLogin, $sPassword) - { - return !empty($sLogin) && !empty($sPassword); - } - - /** - * @param \RainLoop\Model\Account $oAccount - */ - public function EventLoginPostLoginProvide(&$oAccount) - { - if ($oAccount instanceof \RainLoop\Model\Account) - { - // Verify logic - $bValid = $this->isValidAccount($oAccount->Login(), $oAccount->Password()); - - /** - * $oAccount->Email(); // Email (It is not a IMAP login) - * $oAccount->Login(); // IMAP login - * $oAccount->Password(); // IMAP password - * $oAccount->DomainIncHost(); // IMAP host - * - * @see \RainLoo\Model\Account for more - */ - - if (!$bValid) // if verify failed - { - // throw a Auth Error Exception - throw new \RainLoop\Exceptions\ClientException(\RainLoop\Notifications::AuthError); - } - else // Or setup your proxyauth admin account credentials - { - $oAccount->SetProxyAuthUser('admin@domain.com'); - $oAccount->SetProxyAuthPassword('secret-admin-password'); - } - } - } -} diff --git a/plugins/recaptcha/index.php b/plugins/recaptcha/index.php index a0fd55ffe..9245bd512 100644 --- a/plugins/recaptcha/index.php +++ b/plugins/recaptcha/index.php @@ -6,9 +6,9 @@ class RecaptchaPlugin extends \RainLoop\Plugins\AbstractPlugin NAME = 'reCaptcha', AUTHOR = 'SnappyMail', URL = 'https://snappymail.eu/', - VERSION = '2.12.1', - RELEASE = '2022-02-14', - REQUIRED = '2.12.1', + VERSION = '2.16', + RELEASE = '2024-03-12', + REQUIRED = '2.35.3', CATEGORY = 'General', LICENSE = 'MIT', DESCRIPTION = 'A CAPTCHA (v2) is a program that can generate and grade tests that humans can pass but current computer programs cannot. For example, humans can read distorted text as the one shown below, but current computer programs can\'t. More info at https://developers.google.com/recaptcha'; @@ -22,8 +22,8 @@ class RecaptchaPlugin extends \RainLoop\Plugins\AbstractPlugin $this->addJs('js/recaptcha.js'); - $this->addHook('json.action-pre-call', 'AjaxActionPreCall'); - $this->addHook('filter.json-response', 'FilterAjaxResponse'); + $this->addHook('json.before-login', 'BeforeLogin'); + $this->addHook('json.after-login', 'AfterLogin'); $this->addHook('main.content-security-policy', 'ContentSecurityPolicy'); } @@ -64,7 +64,7 @@ class RecaptchaPlugin extends \RainLoop\Plugins\AbstractPlugin $oCacher = $this->Manager()->Actions()->Cacher(); $sLimit = $oCacher && $oCacher->IsInited() ? $oCacher->Get($this->getCaptchaCacherKey()) : '0'; - if (\strlen($sLimit) && \is_numeric($sLimit)) { + if (\is_numeric($sLimit)) { $iConfigLimit -= (int) $sLimit; } } @@ -82,16 +82,13 @@ class RecaptchaPlugin extends \RainLoop\Plugins\AbstractPlugin } } - /** - * @param string $sAction - */ - public function AjaxActionPreCall(string $sAction) + public function BeforeLogin() { - if ('Login' === $sAction && 0 >= $this->getLimit()) { + if (0 >= $this->getLimit()) { $bResult = false; $HTTP = \SnappyMail\HTTP\Request::factory(); - $oResponse = $HTTP->doRequest('POST', 'https://www.google.com/recaptcha/api/siteverify', array( + $oResponse = $HTTP->doRequest('POST', 'https://www.recaptcha.net/recaptcha/api/siteverify', array( 'secret' => $this->Config()->Get('plugin', 'private_key', ''), 'response' => $this->Manager()->Actions()->GetActionParam('RecaptchaResponse', '') )); @@ -112,28 +109,28 @@ class RecaptchaPlugin extends \RainLoop\Plugins\AbstractPlugin /** * @param string $sAction - * @param array $aResponseItem + * @param array $aResponse */ - public function FilterAjaxResponse(string $sAction, array &$aResponseItem) + public function AfterLogin(array &$aResponse) { - if ('Login' === $sAction && $aResponseItem && isset($aResponseItem['Result'])) { + if (isset($aResponse['Result'])) { $oCacher = $this->Manager()->Actions()->Cacher(); $iConfigLimit = (int) $this->Config()->Get('plugin', 'error_limit', 0); $sKey = $this->getCaptchaCacherKey(); if (0 < $iConfigLimit && $oCacher && $oCacher->IsInited()) { - if (false === $aResponseItem['Result']) { + if (false === $aResponse['Result']) { $iLimit = 0; $sLimut = $oCacher->Get($sKey); - if (\strlen($sLimut) && \is_numeric($sLimut)) { + if (\is_numeric($sLimut)) { $iLimit = (int) $sLimut; } $oCacher->Set($sKey, ++$iLimit); if ($iConfigLimit <= $iLimit) { - $aResponseItem['Captcha'] = true; + $aResponse['Captcha'] = true; } } else { $oCacher->Delete($sKey); @@ -144,10 +141,9 @@ class RecaptchaPlugin extends \RainLoop\Plugins\AbstractPlugin public function ContentSecurityPolicy(\SnappyMail\HTTP\CSP $CSP) { - $CSP->script[] = 'https://www.google.com/recaptcha/'; - $CSP->script[] = 'https://www.gstatic.com/recaptcha/'; - $CSP->frame[] = 'https://www.google.com/recaptcha/'; - $CSP->frame[] = 'https://recaptcha.google.com/recaptcha/'; + $CSP->add('script-src', 'https://www.gstatic.com/recaptcha/'); + $CSP->add('script-src', 'https://www.recaptcha.net/recaptcha/'); + $CSP->add('frame-src', 'https://www.recaptcha.net/recaptcha/'); } } diff --git a/plugins/recaptcha/js/recaptcha.js b/plugins/recaptcha/js/recaptcha.js index 246d7adc2..591d26598 100644 --- a/plugins/recaptcha/js/recaptcha.js +++ b/plugins/recaptcha/js/recaptcha.js @@ -36,7 +36,7 @@ } else if (!script) { script = doc.createElement('script'); // script.onload = ShowRecaptcha; - script.src = 'https://www.google.com/recaptcha/api.js?onload=ShowRecaptcha&render=explicit&hl=' + doc.documentElement.lang; + script.src = 'https://www.recaptcha.net/recaptcha/api.js?onload=ShowRecaptcha&render=explicit&hl=' + doc.documentElement.lang; doc.head.append(script); } }; diff --git a/plugins/search-filters/index.php b/plugins/search-filters/index.php new file mode 100644 index 000000000..f48cae1ae --- /dev/null +++ b/plugins/search-filters/index.php @@ -0,0 +1,245 @@ +UseLangs(true); + + $this->addHook('imap.after-login', 'ApplyFilters'); + + $this->addTemplate('templates/STabSearchFilters.html'); + + $this->addTemplate('templates/PopupsSearchFilters.html'); + $this->addTemplate('templates/PopupsSTabAdvancedSearch.html'); + $this->addJs('js/SearchFilters.js'); + + $this->addJsonHook('SGetFilters', 'GetFilters'); + $this->addJsonHook('SAddEditFilter', 'AddEditFilter'); + $this->addJsonHook('SUpdateSearchQ', 'UpdateSearchQ'); + $this->addJsonHook('SDeleteFilter', 'DeleteFilter'); + } + + public function ApplyFilters( + \RainLoop\Model\Account $oAccount, + \MailSo\Imap\ImapClient $oImapClient, + bool $bSuccess, + \MailSo\Imap\Settings $oSettings + ) { + if (!$bSuccess) { + return; + } + + $aSettings = $this->getUserSettings(); + if (empty($aSettings['SFilters'])) { + $aSettings['SFilters'] = []; + $this->saveUserSettings($aSettings); + return; + } + + $Filters = $aSettings['SFilters']; + + foreach ($Filters as $filter) { + $this->Manager()->logWrite(json_encode(['filter' => $filter]), LOG_WARNING); + + $searchQ = $filter['searchQ']; + + // obsługa keyword (multi-folder) + if (stripos($searchQ, 'keyword=') !== false) { + $oMailClient = $this->Manager()->Actions()->MailClient(); + + // Pobieramy wszystkie foldery top-level + $folders = $oMailClient->Folders('', false, ''); + foreach ($folders as $f) { + $folder = $f->FullName ?? null; + if (!$folder) continue; + + $uids = $this->searchMessages($oImapClient, $searchQ, $folder); + if (!empty($uids)) { + $this->applyActions($oImapClient, $filter, $uids, $folder); + } + } + + continue; // przechodzimy do następnego filtra + } + + // normalny search w INBOX + $uids = $this->searchMessages($oImapClient, $searchQ, 'INBOX'); + if (!empty($uids)) { + $this->applyActions($oImapClient, $filter, $uids, 'INBOX'); + } + } + } + + private function searchMessages( + \MailSo\Imap\ImapClient $imapClient, + string $search, + string $folder = "INBOX" + ): array { + try { + $bUseCache = false; + $oSearchCriterias = \MailSo\Imap\SearchCriterias::fromString( + $imapClient, + $folder, + $search, + true, + $bUseCache + ); + + $imapClient->FolderSelect($folder); + return $imapClient->MessageSearch($oSearchCriterias, true); + + } catch (\Throwable $e) { + $this->Manager()->logWrite( + 'SearchFilters IMAP error in folder "' . $folder . + '" for search "' . $search . '": ' . $e->getMessage(), + LOG_ERR + ); + return []; + } + } + + private function applyActions( + \MailSo\Imap\ImapClient $imapClient, + array $filter, + array $uids, + string $folder + ) { + // Mark as read/seen + if (!empty($filter['fSeen'])) { + foreach ($uids as $uid) { + $oRange = new \MailSo\Imap\SequenceSet([$uid]); + $this->Manager()->Actions()->MailClient()->MessageSetFlag( + $folder, + $oRange, + \MailSo\Imap\Enumerations\MessageFlag::SEEN + ); + } + } + + // Flag/Star message + if (!empty($filter['fFlag'])) { + foreach ($uids as $uid) { + $oRange = new \MailSo\Imap\SequenceSet([$uid]); + $this->Manager()->Actions()->MailClient()->MessageSetFlag( + $folder, + $oRange, + \MailSo\Imap\Enumerations\MessageFlag::FLAGGED + ); + } + } + + // Move to folder + if (!empty($filter['fFolder']) && $filter['fFolder'] !== -1) { + foreach ($uids as $uid) { + $oRange = new \MailSo\Imap\SequenceSet([$uid]); + $imapClient->MessageMove('INBOX', $filter['fFolder'], $oRange); + } + } + } + + public function GetFilters() + { + $aSettings = $this->getUserSettings(); + $Filters = $aSettings['SFilters'] ?? []; + + $Search = $this->jsonParam('SSearchQ'); + if (!$Search) { + return $this->jsonResponse(__FUNCTION__, ['SFilters' => $Filters]); + } + + $Filter = null; + foreach ($aSettings['SFilters'] as $filter) { + if ($filter['searchQ'] == $Search) { + $Filter = $filter; + } + } + + return $this->jsonResponse(__FUNCTION__, ['SFilter' => $Filter]); + } + + public function AddEditFilter() + { + $SFilter = $this->jsonParam('SFilter'); + $newFilter = [ + 'searchQ' => $SFilter['searchQ'], + 'priority' => $SFilter['priority'] ?? 1, + 'fFolder' => $SFilter['fFolder'], + 'fSeen' => $SFilter['fSeen'], + 'fFlag' => $SFilter['fFlag'], + ]; + + $aSettings = $this->getUserSettings(); + $aSettings['SFilters'] = $aSettings['SFilters'] ?? []; + + $foundIndex = null; + foreach ($aSettings['SFilters'] as $index => $filter) { + if ($filter['searchQ'] == $SFilter['searchQ']) { + if ($filter['priority'] != $SFilter['priority']) { + array_splice($aSettings['SFilters'], $index, 1); + } else { + $foundIndex = $index; + } + } + } + + if ($foundIndex === null) { + $insertIndex = 0; + foreach ($aSettings['SFilters'] as $index => $filter) + if ($filter['priority'] >= $newFilter['priority']) + $insertIndex = $index + 1; + else + break; + + array_splice($aSettings['SFilters'], $insertIndex, 0, [$newFilter]); + } else { + $aSettings['SFilters'][$foundIndex] = $newFilter; + } + return $this->jsonResponse(__FUNCTION__, $this->saveUserSettings($aSettings)); + } + + public function UpdateSearchQ() + { + $SFilter = $this->jsonParam('SFilter'); + + $aSettings = $this->getUserSettings(); + $aSettings['SFilters'] = $aSettings['SFilters'] ?? []; + + foreach ($aSettings['SFilters'] as $index => $filter) { + if ($filter['searchQ'] == $SFilter['oldSearchQ']) { + $filter['searchQ'] = $SFilter['searchQ']; + $aSettings['SFilters'][$index] = $filter; + break; + } + } + + return $this->jsonResponse(__FUNCTION__, $this->saveUserSettings($aSettings)); + } + + public function DeleteFilter() + { + $Search = $this->jsonParam('SSearchQ'); + + $aSettings = $this->getUserSettings(); + $aSettings['SFilters'] = $aSettings['SFilters'] ?? []; + + foreach ($aSettings['SFilters'] as $index => $filter) { + if ($filter['searchQ'] == $Search) { + array_splice($aSettings['SFilters'], $index, 1); + } + } + + return $this->jsonResponse(__FUNCTION__, $this->saveUserSettings($aSettings)); + } +} diff --git a/plugins/search-filters/js/SearchFilters.js b/plugins/search-filters/js/SearchFilters.js new file mode 100644 index 000000000..d2d5385f2 --- /dev/null +++ b/plugins/search-filters/js/SearchFilters.js @@ -0,0 +1,340 @@ +((rl) => { + const Folders = ko.computed(() => { + const + aResult = [{ + id: -1, + name: '' + }], + sDeepPrefix = '\u00A0\u00A0\u00A0', + showUnsubscribed = true/*!SettingsUserStore.hideUnsubscribed()*/, + foldersWalk = folders => { + folders.forEach(oItem => { + if (showUnsubscribed || oItem.hasSubscriptions() || !oItem.exists) { + aResult.push({ + id: oItem.fullName, + name: sDeepPrefix.repeat(oItem.deep) + oItem.detailedName() + }); + } + + if (oItem.subFolders.length) { + foldersWalk(oItem.subFolders()); + } + }); + }; + foldersWalk(rl.app.folderList()); + return aResult; + }); + + const Priorities = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + const searchQ = ko.observable(''), + priority = ko.observable(1), + oldSearchQ = ko.observable(''), + fFolder = ko.observable(''), + fSeen = ko.observable(false), + fFlag = ko.observable(false), + ioFilters = ko.observableArray([]); + + const i18n = (val) => rl.i18n(`SFILTERS/${val}`); + + const ServerActions = { + GetFilters(loading) { + ioFilters([]); + rl.pluginRemoteRequest((iError, oData) => { + if (iError) return console.error(iError); + + oData.Result.SFilters.forEach((f) => ioFilters.push(ko.observable(f))); + + if (loading) loading(false); + }, 'SGetFilters'); + }, + GetFilter() { + rl.pluginRemoteRequest( + (iError, oData) => { + if (iError) return console.error(iError); + + const filter = oData.Result.SFilter || {}; + priority(filter.priority || 1); + fFolder(filter.fFolder); + fSeen(filter.fSeen); + fFlag(filter.fFlag); + }, + 'SGetFilters', + { + SSearchQ: searchQ() + } + ); + }, + AddOrEditFilter() { + rl.pluginRemoteRequest( + (iError, oData) => { + if (!iError) this.GetFilters(); + }, + 'SAddEditFilter', + { + SFilter: { + searchQ: oldSearchQ() || searchQ(), + priority: priority(), + fFolder: fFolder(), + fSeen: fSeen(), + fFlag: fFlag() + } + } + ); + }, + UpdateSearchQ(newSearchQ) { + rl.pluginRemoteRequest( + (iError, oData) => { + if (!iError) this.GetFilters(); + }, + 'SUpdateSearchQ', + { + SFilter: { + oldSearchQ: oldSearchQ(), + searchQ: newSearchQ + } + } + ); + }, + RemoveFilter(searchQToRemove) { + rl.pluginRemoteRequest( + (iError, oData) => { + if (iError) return console.error(iError, oData); + const index = ioFilters().findIndex((f) => f.searchQ() === searchQToRemove); + ioFilters.splice(index, 1); + }, + 'SDeleteFilter', + { + SSearchQ: searchQToRemove + } + ); + } + }; + + addEventListener('rl-view-model', (event) => { + const advS = event.detail; + if (advS.viewModelTemplateID == 'PopupsAdvancedSearch') { + const button = document.createElement('button'); + button.setAttribute('class', 'btn'); + button.setAttribute('data-i18n', 'SFILTERS/CREATE_FILTER'); + button.addEventListener('click', function () { + searchQ(advS.buildSearchString()); + if (searchQ()) SearchFiltersPopupView.showModal(); + }); + + const footer = advS.querySelector('footer'); + footer.style.display = 'flex'; + footer.style.justifyContent = 'space-between'; + + footer.prepend(button); + } + }); + + class SearchFiltersSettingsTab { + constructor() { + this.folders = Folders; + this.Priorities = Priorities; + this.ioFilters = ioFilters; + + this.loading = ko.observable(false); + this.saving = ko.observable(false); + + this.i18n = i18n; + + this.savingOrLoading = ko.computed(() => { + return this.loading() || this.saving(); + }); + } + + edit(filter) { + oldSearchQ(filter.searchQ); + searchQ(filter.searchQ); + priority(filter.priority || 1); + fFolder(filter.fFolder); + fSeen(filter.fSeen); + fFlag(filter.fFlag); + AdvancedSearchPopupView.showModal(); + } + + remove(filter) { + ServerActions.RemoveFilter(filter.searchQ); + } + + onShow() { + this.clear(); + this.loading(true); + ServerActions.GetFilters(this.loading); + } + + clear() { + this.ioFilters([]); + this.loading(false); + this.saving(false); + } + } + + rl.addSettingsViewModel(SearchFiltersSettingsTab, 'STabSearchFilters', 'Search Filters', 'searchfilters'); + + class SearchFiltersPopupView extends rl.pluginPopupView { + constructor() { + super('SearchFilters'); + + this.folders = Folders; + this.Priorities = Priorities; + + this.priority = priority; + this.fFolder = fFolder; + this.fSeen = fSeen; + this.fFlag = fFlag; + + this.usefFolder = ko.observable(false); + this.fFolder.subscribe((v) => this.usefFolder(!!v)); + } + + submitForm() { + if (!this.usefFolder()) fFolder(''); + ServerActions.AddOrEditFilter(); + this.close(); + } + + beforeShow() { + if (!oldSearchQ()) { + ServerActions.GetFilter(); + } else { + this.usefFolder(!!fFolder()); + } + } + } + + class AdvancedSearchPopupView extends rl.pluginPopupView { + constructor() { + super('STabAdvancedSearch'); + + this.addObservables({ + from: '', + to: '', + subject: '', + text: '', + repliedValue: -1, + selectedDateValue: -1, + selectedTreeValue: '', + + hasAttachment: false, + starred: false, + unseen: false + }); + + this.addComputables({ + repliedOptions: () => { + return [ + { id: -1, name: '' }, + { id: 1, name: rl.i18n('GLOBAL/YES') }, + { id: 0, name: rl.i18n('GLOBAL/NO') } + ]; + }, + + selectedDates: () => { + let prefix = 'SEARCH/DATE_'; + return [ + { id: -1, name: rl.i18n(prefix + 'ALL') }, + { id: 3, name: rl.i18n(prefix + '3_DAYS') }, + { id: 7, name: rl.i18n(prefix + '7_DAYS') }, + { id: 30, name: rl.i18n(prefix + 'MONTH') }, + { id: 90, name: rl.i18n(prefix + '3_MONTHS') }, + { id: 180, name: rl.i18n(prefix + '6_MONTHS') }, + { id: 365, name: rl.i18n(prefix + 'YEAR') } + ]; + }, + + selectedTree: () => { + let prefix = 'SEARCH/SUBFOLDERS_'; + return [ + { id: '', name: rl.i18n(prefix + 'NONE') }, + { id: 'subtree-one', name: rl.i18n(prefix + 'SUBTREE_ONE') }, + { id: 'subtree', name: rl.i18n(prefix + 'SUBTREE') } + ]; + } + }); + } + + submitForm() { + const newSearchQ = this.buildSearchString(); + if (newSearchQ != oldSearchQ()) ServerActions.UpdateSearchQ(newSearchQ); + this.close(); + } + + editFilters() { + SearchFiltersPopupView.showModal(); + } + + buildSearchString() { + const self = this, + data = new FormData(), + append = (key, value) => value.length && data.append(key, value); + + append('from', self.from().trim()); + append('to', self.to().trim()); + append('subject', self.subject().trim()); + append('text', self.text().trim()); + append('in', self.selectedTreeValue()); + if (-1 < self.selectedDateValue()) { + let d = new Date(); + d.setDate(d.getDate() - self.selectedDateValue()); + append('since', d.toISOString().split('T')[0]); + } + + let result = decodeURIComponent(new URLSearchParams(data).toString()); + + if (self.hasAttachment()) { + result += '&attachment'; + } + if (self.unseen()) { + result += '&unseen'; + } + if (self.starred()) { + result += '&flagged'; + } + if (1 == self.repliedValue()) { + result += '&answered'; + } + if (0 == self.repliedValue()) { + result += '&unanswered'; + } + + return result.replace(/^&+/, ''); + } + + onShow() { + const pString = (value) => (null != value ? '' + value : ''); + + const self = this, + params = new URLSearchParams('?' + searchQ()); + self.from(pString(params.get('from'))); + self.to(pString(params.get('to'))); + self.subject(pString(params.get('subject'))); + self.text(pString(params.get('text'))); + self.selectedTreeValue(pString(params.get('in'))); + self.selectedDateValue(-1); + self.hasAttachment(params.has('attachment')); + self.starred(params.has('flagged')); + self.unseen(params.has('unseen')); + if (params.has('answered')) { + self.repliedValue(1); + } else if (params.has('unanswered')) { + self.repliedValue(0); + } + } + + clear() { + oldSearchQ(''); + searchQ(''); + fFolder(''); + priority(1); + fSeen(false); + fFlag(false); + } + + onHide() { + this.clear(); + } + } +})(window.rl); diff --git a/plugins/search-filters/langs/en.json b/plugins/search-filters/langs/en.json new file mode 100644 index 000000000..6fb25bbf3 --- /dev/null +++ b/plugins/search-filters/langs/en.json @@ -0,0 +1,21 @@ +{ + "SFILTERS": { + "WHEN_MESSAGE_MATCH_SEARCH_CRITERIA": "When a message is an exact match for your search criteria:", + "FILTERS": "Filters", + "FILTER": "Filter", + "MOVE_TO_FOLDER": "Move to folder: ", + "CREATE_FILTER": "Create filter", + "EDIT_FILTERS": "Edit filters", + "MATCHES": "Matches: ", + "DO_THIS": "Do this: ", + "SAVE": "Save", + "EDIT": "Edit", + "REMOVE": "Remove", + "NO_FILTERS": "You haven't added any filters yet.", + "THE_FOLLOWING_FILTERS_ARE_APPLIED": "The following filters are applied to all incoming mail: ", + "MARK_AS_READ": "Mark as read", + "STAR_IT": "Star it", + "PRIORITY_LABLE": "Priority points, Higher means it'll apply first", + "PRIORITY_POINTS": "Priority points" + } +} \ No newline at end of file diff --git a/plugins/search-filters/templates/PopupsSTabAdvancedSearch.html b/plugins/search-filters/templates/PopupsSTabAdvancedSearch.html new file mode 100644 index 000000000..d1a260551 --- /dev/null +++ b/plugins/search-filters/templates/PopupsSTabAdvancedSearch.html @@ -0,0 +1,82 @@ +
    + × +

    +
    + +
    + + +
    \ No newline at end of file diff --git a/plugins/search-filters/templates/PopupsSearchFilters.html b/plugins/search-filters/templates/PopupsSearchFilters.html new file mode 100644 index 000000000..c85ca8914 --- /dev/null +++ b/plugins/search-filters/templates/PopupsSearchFilters.html @@ -0,0 +1,54 @@ +
    + × +

    +
    + +
    + +
    diff --git a/plugins/search-filters/templates/STabSearchFilters.html b/plugins/search-filters/templates/STabSearchFilters.html new file mode 100644 index 000000000..d006da345 --- /dev/null +++ b/plugins/search-filters/templates/STabSearchFilters.html @@ -0,0 +1,39 @@ +
    +
    +
    + +     + +
    + +
    + +
    + + + +
    + + +
    +
    + + +
    +
    \ No newline at end of file diff --git a/plugins/send-save-in/LICENSE b/plugins/send-save-in/LICENSE new file mode 100644 index 000000000..f709b02e2 --- /dev/null +++ b/plugins/send-save-in/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2016 RainLoop Team + +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/plugins/send-save-in/index.php b/plugins/send-save-in/index.php new file mode 100644 index 000000000..2289c18f3 --- /dev/null +++ b/plugins/send-save-in/index.php @@ -0,0 +1,23 @@ +UseLangs(true); // start use langs folder + $this->addJs('savein.js'); + } +} diff --git a/plugins/send-save-in/savein.js b/plugins/send-save-in/savein.js new file mode 100644 index 000000000..b95e18892 --- /dev/null +++ b/plugins/send-save-in/savein.js @@ -0,0 +1,75 @@ +(rl => { + const templateId = 'PopupsCompose', + folderListOptionsBuilder = () => { + const + aResult = [{ + id: '', + name: '', + system: false, + disabled: false + }], + sDeepPrefix = '\u00A0\u00A0\u00A0', + showUnsubscribed = true/*!SettingsUserStore.hideUnsubscribed()*/, + + foldersWalk = folders => { + folders.forEach(oItem => { + if (showUnsubscribed || oItem.hasSubscriptions() || !oItem.exists) { + aResult.push({ + id: oItem.fullName, + name: sDeepPrefix.repeat(oItem.deep) + oItem.detailedName(), + system: false, + disabled: !oItem.selectable() + }); + } + + if (oItem.subFolders.length) { + foldersWalk(oItem.subFolders()); + } + }); + }; + + + // FolderUserStore.folderList() + foldersWalk(rl.app.folderList() || []); + + return aResult; + }; + + let oldSentFolderFn; + + addEventListener('rl-view-model.create', e => { + if (templateId === e.detail.viewModelTemplateID) { + const view = e.detail; // ComposePopupView + + view.sentFolderValue = ko.observable(''); + view.sentFolderSelectList = ko.computed(folderListOptionsBuilder, {'pure':true}); + view.defaultOptionsAfterRender = (domItem, item) => + item && undefined !== item.disabled && domItem?.classList.toggle('disabled', domItem.disabled = item.disabled); + + oldSentFolderFn = view.sentFolder.bind(view); + view.sentFolder = () => view.sentFolderValue() || oldSentFolderFn(); + + document.getElementById(templateId).content.querySelector('.b-header tbody').append(Element.fromHTML(` + + Store in + + + (When send, store a copy of the message in the selected folder) + + `)); + + view.currentIdentity.subscribe(()=>{ + view.sentFolderValue(oldSentFolderFn()); + }); + } + }); + + addEventListener('rl-vm-visible', e => { + if (templateId === e.detail.viewModelTemplateID) { + const view = e.detail; // ComposePopupView + view.sentFolderValue(oldSentFolderFn()); + } + }); + +})(window.rl); diff --git a/plugins/custom-auth-example/LICENSE b/plugins/set-remote-addr/LICENSE similarity index 100% rename from plugins/custom-auth-example/LICENSE rename to plugins/set-remote-addr/LICENSE diff --git a/plugins/set-remote-addr/index.php b/plugins/set-remote-addr/index.php new file mode 100644 index 000000000..dbc10f8a6 --- /dev/null +++ b/plugins/set-remote-addr/index.php @@ -0,0 +1,23 @@ +addHook('filter.smtp-from', 'FilterDetectFrom'); + $this->addHook('smtp.before-connect', 'FilterSmtpConnect'); + $this->addHook('smtp.before-login', 'FilterSmtpCredentials'); + } + + /** + * \RainLoop\Model\Account $oAccount + * \MailSo\Mime\Message $oMessage + * string &$sFrom + */ + public function FilterDetectFrom(\RainLoop\Model\Account $oAccount, \MailSo\Mime\Message $oMessage, string &$sFrom) + { + $sWhiteList = \trim($this->Config()->Get('plugin', 'from_adress_pattern', '')); + $sFoundValue = ''; + if (\strlen($sWhiteList) && \RainLoop\Plugins\Helper::ValidateWildcardValues($sFrom, $sWhiteList, $sFoundValue) && $sFrom != $oAccount->Email()) { + \SnappyMail\LOG::info(get_class($this) ,'From address different from account recognized: '. $oAccount->Email().' -> '.$sFrom . '(~ '.$sFoundValue.')'); + $oMainAccount; + $oFromAccount; + if ($oAccount instanceof \RainLoop\Model\MainAccount ) { + $oMainAccount=$oAccount; + } else { + $oMainAccount=$this->Manager()->Actions()->getMainAccountFromToken(); + if ($oMainAccount->Email() == $sFrom) { + $this->aFromAccount[$oAccount->Email()]=$oMainAccount; + return; + } + } + $aAccounts = $this->Manager()->Actions()->getAccounts($oMainAccount); + foreach ($aAccounts as &$value) { + $oValue=\RainLoop\Model\AdditionalAccount::NewInstanceFromTokenArray($this->Manager()->Actions(), $value); + if ($oValue->Email()==$sFrom) { + $oFromAccount = $oValue; + break; + } + } + if (is_null($oFromAccount)){ + \SnappyMail\LOG::info(get_class($this),'No Account found for '. $sFrom); + if ($this->Config()->Get('plugin', 'throw_notfound_exception', true)) { + throw new \RainLoop\Exceptions\ClientException(\RainLoop\Notifications::AccountDoesNotExist); + } + return; + } + $this->aFromAccount[$oAccount->Email()]=$oFromAccount; + } + } + /** + * @param \RainLoop\Model\Account $oAccount + * @param \MailSo\Smtp\SmtpClient $oSmtpClient + * @param \MailSo\Smtp\Settings $oSettings + */ + public function FilterSmtpConnect(\RainLoop\Model\Account $oAccount, \MailSo\Smtp\SmtpClient $oSmtpClient, \MailSo\Smtp\Settings $oSettings) + { + if ( isset($this->aFromAccount[$oAccount->Email()]) ) { + $oFromAccount = $this->aFromAccount[$oAccount->Email()]; + $oSettings->host = $oFromAccount->Domain()->SmtpSettings()->host; + $oSettings->port = (int) $oFromAccount->Domain()->SmtpSettings()->port; + $oSettings->type = $oFromAccount->Domain()->SmtpSettings()->type; + \SnappyMail\LOG::info(get_class($this),'Smtp config rewrite: '. $oSettings->host); + } + } + + /** + * @param \RainLoop\Model\Account $oAccount + * @param \MailSo\Smtp\SmtpClient $oSmtpClient + * @param \MailSo\Smtp\Settings $oSettings + */ + public function FilterSmtpCredentials(\RainLoop\Model\Account $oAccount, \MailSo\Smtp\SmtpClient $oSmtpClient, \MailSo\Smtp\Settings $oSettings) + { + if ( isset($this->aFromAccount[$oAccount->Email()]) ) { + $oFromAccount = $this->aFromAccount[$oAccount->Email()]; + unset($this->aFromAccount[$oAccount->Email()]); + $oSettings->useAuth = $oFromAccount->Domain()->SmtpSettings()->useAuth; + $oSettings->username = $oFromAccount->OutLogin(); + $oSettings->passphrase = $oFromAccount->IncPassword(); + \SnappyMail\LOG::info(get_class($this),'user/pwd rewrite: '. $oFromAccount->Email()); + } + } + + /** + * @return array + */ + protected function configMapping() : array + { + return array( + \RainLoop\Plugins\Property::NewInstance('from_adress_pattern')->SetLabel('From-Address pattern') + ->SetType(\RainLoop\Enumerations\PluginPropertyType::STRING_TEXT) + ->SetDescription('space as delimiter, wildcard supported.') + ->SetDefaultValue('user@example.com *@example2.com'), + \RainLoop\Plugins\Property::NewInstance('throw_notfound_exception')->SetLabel('Throw Exception, if from-adr is not found as account') + ->SetType(\RainLoop\Enumerations\PluginPropertyType::BOOL) + ->SetDescription('it is not possible to send eMails in this case, regardless of whether the smtp-server would do it') + ->SetDefaultValue(true) + ); + } + +} diff --git a/plugins/snowfall-on-login-screen/index.php b/plugins/snowfall-on-login-screen/index.php index 065716af8..b3ccb1d41 100644 --- a/plugins/snowfall-on-login-screen/index.php +++ b/plugins/snowfall-on-login-screen/index.php @@ -4,7 +4,7 @@ class SnowfallOnLoginScreenPlugin extends \RainLoop\Plugins\AbstractPlugin { const NAME = 'Snowfall on login screen', - VERSION = '2.0', + VERSION = '2.1', CATEGORY = 'Fun', DESCRIPTION = 'Snowfall on login screen (just for fun).'; diff --git a/plugins/snowfall-on-login-screen/js/include.js b/plugins/snowfall-on-login-screen/js/include.js index 5a461d625..e8adf5505 100644 --- a/plugins/snowfall-on-login-screen/js/include.js +++ b/plugins/snowfall-on-login-screen/js/include.js @@ -1,12 +1,17 @@ if (!/iphone|ipod|ipad|android/i.test(navigator.userAgent)) { - document.addEventListener('DOMContentLoaded', () => { - if (window.snowFall && window.rl && !rl.settings.get('Auth')) - { - window.snowFall.snow(document.getElementsByTagName('body'), { - shadow: true, round: true, minSize: 2, maxSize: 5 - }); - } - }); + if (window.snowFall && window.rl) + { + let body = document.body; + addEventListener('sm-show-screen', e => { + if ('login' == e.detail) { + window.snowFall.snow(body, { + shadow: true, round: true, minSize: 2, maxSize: 5 + }); + } else if (body.snow) { + body.snow.clear(); + } + }); + } } diff --git a/plugins/snowfall-on-login-screen/js/snowfall.js b/plugins/snowfall-on-login-screen/js/snowfall.js index 6fa0c799e..671b44e50 100644 --- a/plugins/snowfall-on-login-screen/js/snowfall.js +++ b/plugins/snowfall-on-login-screen/js/snowfall.js @@ -47,7 +47,7 @@ */ // Paul Irish requestAnimationFrame polyfill -(function(window) { +(window => { var lastTime = 0; var vendors = ['webkit', 'moz']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { @@ -57,11 +57,10 @@ } if (!window.requestAnimationFrame) - window.requestAnimationFrame = function(callback, element) { + window.requestAnimationFrame = callback => { var currTime = new Date().getTime(); var timeToCall = window.Math.max(0, 16 - (currTime - lastTime)); - var id = window.setTimeout(function() { callback(currTime + timeToCall); }, - timeToCall); + var id = window.setTimeout(() => callback(currTime + timeToCall), timeToCall); lastTime = currTime + timeToCall; return id; }; @@ -70,7 +69,7 @@ window.cancelAnimationFrame = function(id) { clearTimeout(id); }; -}(window)); +})(window); var snowFall = (function(){ function jSnow(){ @@ -248,28 +247,14 @@ var snowFall = (function(){ cancelAnimationFrame(snowTimeout); } }; - }; + } return{ - snow : function(elements, options){ + snow : (elements, options) => { if(typeof(options) === 'string'){ - if(elements.length > 0){ - for(var i = 0; i < elements.length; i++){ - if(elements[i].snow){ - elements[i].snow.clear(); - } - } - }else{ - elements.snow.clear(); - } + elements.snow.clear(); }else{ - if(elements.length > 0){ - for(var i = 0; i < elements.length; i++){ - new jSnow().snow(elements[i], options); - } - }else{ - new jSnow().snow(elements, options); - } + new jSnow().snow(elements, options); } } }; -})(); \ No newline at end of file +})(); diff --git a/plugins/two-factor-auth/index.php b/plugins/two-factor-auth/index.php index f9e7da5eb..21b449daa 100644 --- a/plugins/two-factor-auth/index.php +++ b/plugins/two-factor-auth/index.php @@ -1,15 +1,16 @@ addJs('js/TwoFactorAuthSettings.js'); $this->addHook('login.success', 'DoLogin'); + $this->addHook('filter.app-data', 'FilterAppData'); $this->addJsonHook('GetTwoFactorInfo', 'DoGetTwoFactorInfo'); $this->addJsonHook('CreateTwoFactorSecret', 'DoCreateTwoFactorSecret'); @@ -33,11 +35,34 @@ class TwoFactorAuthPlugin extends \RainLoop\Plugins\AbstractPlugin $this->addTemplate('templates/PopupsTwoFactorAuthTest.html'); } + public function configMapping() : array + { + return [ + \RainLoop\Plugins\Property::NewInstance("force_two_factor_auth") +// ->SetLabel('PLUGIN_TWO_FACTOR/LABEL_FORCE') + ->SetLabel('Enforce 2-Step Verification') + ->SetType(\RainLoop\Enumerations\PluginPropertyType::BOOL), + ]; + } + + public function FilterAppData($bAdmin, &$aResult) + { + if (!$bAdmin && \is_array($aResult)/* && isset($aResult['Auth']) && !$aResult['Auth']*/) { + $aResult['RequireTwoFactor'] = (bool) $this->Config()->Get('plugin', 'force_two_factor_auth', false); + + $aResult['SetupTwoFactor'] = false; + if ($aResult['RequireTwoFactor'] && !empty($aResult['Auth'])) { + $aData = $this->getTwoFactorInfo($this->getMainAccountFromToken()); + $aResult['SetupTwoFactor'] = empty($aData['IsSet']) || empty($aData['Enable']) || empty($aData['Secret']); + } + } + } + public function DoLogin(MainAccount $oAccount) { if ($this->TwoFactorAuthProvider($oAccount)) { $aData = $this->getTwoFactorInfo($oAccount); - if ($aData && isset($aData['IsSet'], $aData['Enable']) && !empty($aData['Secret']) && $aData['IsSet'] && $aData['Enable']) { + if (isset($aData['IsSet'], $aData['Enable']) && !empty($aData['Secret']) && $aData['IsSet'] && $aData['Enable']) { $sCode = \trim($this->jsonParam('totp_code', '')); if (empty($sCode)) { $this->Logger()->Write("TFA: Code required for {$oAccount->Email()}"); @@ -49,7 +74,7 @@ class TwoFactorAuthPlugin extends \RainLoop\Plugins\AbstractPlugin $aBackupCodes = \explode(' ', \trim(\preg_replace('/[^\d]+/', ' ', $aData['BackupCodes']))); $bUseBackupCode = \in_array($sCode, $aBackupCodes); if ($bUseBackupCode) { - $this->removeBackupCodeFromTwoFactorInfo($oAccount->Email(), $sCode); + $this->removeBackupCodeFromTwoFactorInfo($oAccount, $sCode); } } @@ -86,11 +111,7 @@ class TwoFactorAuthPlugin extends \RainLoop\Plugins\AbstractPlugin $sSecret = $this->TwoFactorAuthProvider($oAccount)->CreateSecret(); - $aCodes = array(); - for ($iIndex = 9; $iIndex > 0; $iIndex--) - { - $aCodes[] = \rand(100000000, 900000000); - } + $aCodes = \array_map(function(){return \rand(100000000, 900000000);}, \array_fill(0, 8, null)); $this->StorageProvider()->Put($oAccount, \RainLoop\Providers\Storage\Enumerations\StorageType::CONFIG, @@ -99,6 +120,7 @@ class TwoFactorAuthPlugin extends \RainLoop\Plugins\AbstractPlugin 'User' => $sEmail, 'Enable' => false, 'Secret' => $sSecret, + 'QRCode' => static::getQRCode($oAccount, $sSecret), 'BackupCodes' => \implode(' ', $aCodes) )) ); @@ -106,6 +128,18 @@ class TwoFactorAuthPlugin extends \RainLoop\Plugins\AbstractPlugin return $this->jsonResponse(__FUNCTION__, $this->getTwoFactorInfo($oAccount)); } + private static function getQRCode(MainAccount $oAccount, string $secret) : string + { + $email = \rawurlencode($oAccount->Email()); +// $issuer = \rawurlencode(\RainLoop\Api::Config()->Get('webmail', 'title', 'SnappyMail')); + $QR = \SnappyMail\QRCode::getMinimumQRCode( +// "otpauth://totp/{$issuer}:{$email}?secret={$secret}&issuer={$issuer}", + "otpauth://totp/{$email}?secret={$secret}", + \SnappyMail\QRCode::ERROR_CORRECT_LEVEL_M + ); + return $QR->__toString(); + } + public function DoShowTwoFactorSecret() : array { $oAccount = $this->getMainAccountFromToken(); @@ -117,14 +151,7 @@ class TwoFactorAuthPlugin extends \RainLoop\Plugins\AbstractPlugin $aResult = $this->getTwoFactorInfo($oAccount); unset($aResult['BackupCodes']); - $name = \rawurlencode($oAccount->Email()); -// $issuer = \rawurlencode(\RainLoop\API::Config()->Get('webmail', 'title', 'SnappyMail')); - $QR = \SnappyMail\QRCode::getMinimumQRCode( -// "otpauth://totp/{$issuer}:{$name}?secret={$aResult['Secret']}&issuer={$issuer}", - "otpauth://totp/{$name}?secret={$aResult['Secret']}", - \SnappyMail\QRCode::ERROR_CORRECT_LEVEL_M - ); - $aResult['QRCode'] = $QR->__toString(); + $aResult['QRCode'] = static::getQRCode($oAccount, $aResult['Secret']); return $this->jsonResponse(__FUNCTION__, $aResult); } @@ -137,18 +164,17 @@ class TwoFactorAuthPlugin extends \RainLoop\Plugins\AbstractPlugin return $this->jsonResponse(__FUNCTION__, false); } - $oSettings = $this->Manager()->Actions()->SettingsProvider()->Load($oAccount); - if ($this->Manager()->Actions()->HasActionParam('EnableTwoFactor')) { - $sValue = $this->GetActionParam('EnableTwoFactor', ''); - $oSettings->SetConf('EnableTwoFactor', !empty($sValue)); + $oActions = $this->Manager()->Actions(); + if ($oActions->HasActionParam('EnableTwoFactor')) { + $sValue = $oActions->GetActionParam('EnableTwoFactor', ''); + $oActions->SettingsProvider()->Load($oAccount)->SetConf('EnableTwoFactor', !empty($sValue)); } $sEmail = $oAccount->Email(); $bResult = false; $mData = $this->getTwoFactorInfo($oAccount); - if (isset($mData['Secret'], $mData['BackupCodes'])) - { + if (isset($mData['Secret'], $mData['BackupCodes'])) { $bResult = $this->StorageProvider()->Put($oAccount, \RainLoop\Providers\Storage\Enumerations\StorageType::CONFIG, 'two_factor', @@ -210,7 +236,7 @@ class TwoFactorAuthPlugin extends \RainLoop\Plugins\AbstractPlugin return $this->Manager()->Actions()->StorageProvider(); } - private $oTwoFactorAuthProvider; + private $oTwoFactorAuthProvider = null; protected function TwoFactorAuthProvider(MainAccount $oAccount) : ?TwoFactorAuthInterface { if (!$this->oTwoFactorAuthProvider) { @@ -232,12 +258,10 @@ class TwoFactorAuthPlugin extends \RainLoop\Plugins\AbstractPlugin 'IsSet' => false, 'Enable' => false, 'Secret' => '', - 'UrlTitle' => '', 'BackupCodes' => '' ); - if (!empty($sEmail)) - { + if (!empty($sEmail)) { $aResult['User'] = $sEmail; $sData = $this->StorageProvider()->Get($oAccount, @@ -245,8 +269,7 @@ class TwoFactorAuthPlugin extends \RainLoop\Plugins\AbstractPlugin 'two_factor' ); - if ($sData) - { + if ($sData) { $mData = static::DecodeKeyValues($sData); } } @@ -259,23 +282,15 @@ class TwoFactorAuthPlugin extends \RainLoop\Plugins\AbstractPlugin $aResult['Enable'] = isset($mData['Enable']) ? !!$mData['Enable'] : false; $aResult['Secret'] = $mData['Secret']; $aResult['BackupCodes'] = $mData['BackupCodes']; - $aResult['UrlTitle'] = $this->Config()->Get('webmail', 'title', ''); + $aResult['QRCode'] = static::getQRCode($oAccount, $mData['Secret']); } - if ($bRemoveSecret) - { - if (isset($aResult['Secret'])) - { + if ($bRemoveSecret) { + if (isset($aResult['Secret'])) { unset($aResult['Secret']); } - if (isset($aResult['UrlTitle'])) - { - unset($aResult['UrlTitle']); - } - - if (isset($aResult['BackupCodes'])) - { + if (isset($aResult['BackupCodes'])) { unset($aResult['BackupCodes']); } } @@ -285,8 +300,7 @@ class TwoFactorAuthPlugin extends \RainLoop\Plugins\AbstractPlugin protected function removeBackupCodeFromTwoFactorInfo(MainAccount $oAccount, string $sCode) : bool { - if (!$oAccount || empty($sCode)) - { + if (!$oAccount || empty($sCode)) { return false; } @@ -295,12 +309,10 @@ class TwoFactorAuthPlugin extends \RainLoop\Plugins\AbstractPlugin 'two_factor' ); - if ($sData) - { + if ($sData) { $mData = static::DecodeKeyValues($sData); - if (!empty($mData['BackupCodes'])) - { + if (!empty($mData['BackupCodes'])) { $sBackupCodes = \preg_replace('/[^\d]+/', ' ', ' '.$mData['BackupCodes'].' '); $sBackupCodes = \str_replace(' '.$sCode.' ', '', $sBackupCodes); diff --git a/plugins/two-factor-auth/js/TwoFactorAuthLogin.js b/plugins/two-factor-auth/js/TwoFactorAuthLogin.js index 98ac5fac4..aa71747c2 100644 --- a/plugins/two-factor-auth/js/TwoFactorAuthLogin.js +++ b/plugins/two-factor-auth/js/TwoFactorAuthLogin.js @@ -1,16 +1,23 @@ (rl => { - rl && addEventListener('rl-view-model', e => { - if (e.detail && 'Login' === e.detail.viewModelTemplateID) { + const + forceTOTP = () => { + if (rl.settings.get('SetupTwoFactor')) { + setTimeout(() => document.location.hash = '#/settings/two-factor-auth', 50); + } + }; + + addEventListener('rl-view-model', e => { + if ('Login' === e.detail.viewModelTemplateID) { const container = e.detail.viewModelDom.querySelector('#plugin-Login-BottomControlGroup'), - placeholder = 'LOGIN/LABEL_TWO_FACTOR_CODE'; + placeholder = 'PLUGIN_2FA/LABEL_TWO_FACTOR_CODE'; if (container) { container.prepend(Element.fromHTML('
    ' + '⏱' + '' + '
    ')); @@ -18,4 +25,12 @@ } }); + // https://github.com/the-djmaze/snappymail/issues/349 + addEventListener('sm-show-screen', e => { + if (!e.detail.startsWith('settings') && rl.settings.get('SetupTwoFactor')) { + e.preventDefault(); + forceTOTP(); + } + }); + })(window.rl); diff --git a/plugins/two-factor-auth/js/TwoFactorAuthSettings.js b/plugins/two-factor-auth/js/TwoFactorAuthSettings.js index 8f043fd79..79d8c6bb5 100644 --- a/plugins/two-factor-auth/js/TwoFactorAuthSettings.js +++ b/plugins/two-factor-auth/js/TwoFactorAuthSettings.js @@ -56,11 +56,12 @@ class TwoFactorAuthSettings value = !!value; if (value && this.twoFactorTested()) { this.viewEnable_(value); - Remote.enableTwoFactor(fn, value); + Remote.enableTwoFactor(iError => { + fn(iError); + rl.settings.get('RequireTwoFactor') && rl.settings.set('SetupTwoFactor', !!iError); + }, value); } else { - if (!value) { - this.viewEnable_(value); - } + value || this.viewEnable_(value); Remote.enableTwoFactor(fn, false); } } @@ -70,12 +71,12 @@ class TwoFactorAuthSettings // translatorTrigger(); return this.twoFactorTested() || this.viewEnable_() ? '' - : rl.i18n('POPUPS_TWO_FACTOR_CFG/TWO_FACTOR_SECRET_TEST_BEFORE_DESC'); + : rl.i18n('PLUGIN_2FA/TWO_FACTOR_SECRET_TEST_BEFORE_DESC'); }, viewTwoFactorStatus: () => { // translatorTrigger(); - return rl.i18n('POPUPS_TWO_FACTOR_CFG/TWO_FACTOR_SECRET_' + return rl.i18n('PLUGIN_2FA/TWO_FACTOR_SECRET_' + (this.twoFactorStatus() ? '' : 'NOT_') + 'CONFIGURED_DESC' ); @@ -105,7 +106,12 @@ class TwoFactorAuthSettings } testTwoFactor() { - TwoFactorAuthTestPopupView.showModal([this.twoFactorTested]); + TwoFactorAuthTestPopupView.showModal([ + () => { + this.twoFactorTested(true); + this.viewEnable(true); + } + ]); } clearTwoFactor() { @@ -187,22 +193,22 @@ class TwoFactorAuthTestPopupView extends rl.pluginPopupView { Remote.verifyCode(iError => { this.testing(false); this.codeStatus(!iError); - this.twoFactorTested(!iError); + iError || (this.onSuccess() | this.close()); }, this.code()); } - onShow(twoFactorTested) { + onShow(onSuccess) { this.code(''); this.codeStatus(null); this.testing(false); - this.twoFactorTested = twoFactorTested; + this.onSuccess = onSuccess; } } rl.addSettingsViewModel( TwoFactorAuthSettings, 'TwoFactorAuthSettings', - 'POPUPS_TWO_FACTOR_CFG/LEGEND_TWO_FACTOR_AUTH', + 'PLUGIN_2FA/LEGEND_TWO_FACTOR_AUTH', 'two-factor-auth' ); diff --git a/plugins/two-factor-auth/langs/cs.ini b/plugins/two-factor-auth/langs/cs.ini new file mode 100644 index 000000000..2324476fc --- /dev/null +++ b/plugins/two-factor-auth/langs/cs.ini @@ -0,0 +1,20 @@ +[PLUGIN_2FA] +LEGEND_TWO_FACTOR_AUTH = "Dvoufázové ověření" +LABEL_ENABLE_TWO_FACTOR = "Povolit dvoufázové ověření" +LABEL_TWO_FACTOR_USER = "Uživatel" +LABEL_TWO_FACTOR_STATUS = "Stav" +LABEL_TWO_FACTOR_SECRET = "Tajný klíč" +LABEL_TWO_FACTOR_BACKUP_CODES = "Backup codes" +BUTTON_CREATE = "Create a secret" +BUTTON_ACTIVATE = "Activate" +LINK_TEST = "test" +BUTTON_SHOW_SECRET = "Show Secret" +BUTTON_HIDE_SECRET = "Hide Secret" +TWO_FACTOR_SECRET_CONFIGURED_DESC = "Configured" +TWO_FACTOR_SECRET_NOT_CONFIGURED_DESC = "Not configured" +TWO_FACTOR_SECRET_DESC = "Import this info into your Google Authenticator client (or other TOTP client) using the provided QR code below or by entering the code manually." +TWO_FACTOR_BACKUP_CODES_DESC = "If you can't receive codes via Google Authenticator (or other TOTP client), you can use backup codes to sign in. After you’ve used a backup code to sign in, it will become inactive." +TWO_FACTOR_SECRET_TEST_BEFORE_DESC = "You can't change this setting before test." +TITLE_TEST_CODE = "2-Step verification test" +LABEL_CODE = "Code" +LABEL_TWO_FACTOR_CODE = "Verification Code" diff --git a/plugins/two-factor-auth/langs/de_DE.ini b/plugins/two-factor-auth/langs/de.ini similarity index 95% rename from plugins/two-factor-auth/langs/de_DE.ini rename to plugins/two-factor-auth/langs/de.ini index 9e050e280..90ad5d35c 100644 --- a/plugins/two-factor-auth/langs/de_DE.ini +++ b/plugins/two-factor-auth/langs/de.ini @@ -1,4 +1,4 @@ -[POPUPS_TWO_FACTOR_CFG] +[PLUGIN_2FA] LEGEND_TWO_FACTOR_AUTH = "Zwei-Faktor-Authentifizierung" LABEL_ENABLE_TWO_FACTOR = "Zwei-Faktor-Authentifizierung aktivieren" LABEL_TWO_FACTOR_USER = "Benutzer" @@ -15,8 +15,6 @@ TWO_FACTOR_SECRET_NOT_CONFIGURED_DESC = "Nicht konfiguriert" TWO_FACTOR_SECRET_DESC = "Importieren Sie diese Information in Ihre Google-Authenticator-Anwendung (oder andere TOTP-Anwendung), indem Sie den unten bereitgestellten QR-Code verwenden oder den Code manuell eingeben." TWO_FACTOR_BACKUP_CODES_DESC = "Sollten Sie keine Codes über den Google Authenticator erhalten, können Sie einen Sicherungscode zur Anmeldung verwenden. Der Sicherungscode wird inaktiv, sobald Sie ihn zur Anmeldung verwendet haben." TWO_FACTOR_SECRET_TEST_BEFORE_DESC = "Sie können diese Einstellung nicht ohne vorherigen Test verändern." -[POPUPS_TWO_FACTOR_TEST] TITLE_TEST_CODE = "Zwei-Faktor-Authentifizierung" LABEL_CODE = "Code" -[LOGIN] LABEL_TWO_FACTOR_CODE = "Verifizierungscode" diff --git a/plugins/two-factor-auth/langs/en.ini b/plugins/two-factor-auth/langs/en.ini index 4133b4fdb..003a50a31 100644 --- a/plugins/two-factor-auth/langs/en.ini +++ b/plugins/two-factor-auth/langs/en.ini @@ -1,7 +1,4 @@ -[POPUPS_TWO_FACTOR_TEST] -TITLE_TEST_CODE = "2-Step verification test" -LABEL_CODE = "Code" -[POPUPS_TWO_FACTOR_CFG] +[PLUGIN_2FA] LEGEND_TWO_FACTOR_AUTH = "2-Step Verification (TOTP)" LABEL_ENABLE_TWO_FACTOR = "Enable 2-Step verification" LABEL_TWO_FACTOR_USER = "User" @@ -15,8 +12,9 @@ BUTTON_SHOW_SECRET = "Show Secret" BUTTON_HIDE_SECRET = "Hide Secret" TWO_FACTOR_SECRET_CONFIGURED_DESC = "Configured" TWO_FACTOR_SECRET_NOT_CONFIGURED_DESC = "Not configured" -TWO_FACTOR_SECRET_DESC = "Import this info into your Google Authenticator client (or other TOTP client) using the provided QR code below or by entering the code manually.\n" -TWO_FACTOR_BACKUP_CODES_DESC = "If you can't receive codes via Google Authenticator (or other TOTP client), you can use backup codes to sign in. After you’ve used a backup code to sign in, it will become inactive.\n" +TWO_FACTOR_SECRET_DESC = "Import this info into your Google Authenticator client (or other TOTP client) using the provided QR code below or by entering the code manually." +TWO_FACTOR_BACKUP_CODES_DESC = "If you can't receive codes via Google Authenticator (or other TOTP client), you can use backup codes to sign in. After you’ve used a backup code to sign in, it will become inactive." TWO_FACTOR_SECRET_TEST_BEFORE_DESC = "You can't change this setting before test." -[LOGIN] +TITLE_TEST_CODE = "2-Step verification test" +LABEL_CODE = "Code" LABEL_TWO_FACTOR_CODE = "Verification Code" diff --git a/plugins/two-factor-auth/langs/es_ES.ini b/plugins/two-factor-auth/langs/es.ini similarity index 95% rename from plugins/two-factor-auth/langs/es_ES.ini rename to plugins/two-factor-auth/langs/es.ini index e57238d9d..85fe09191 100644 --- a/plugins/two-factor-auth/langs/es_ES.ini +++ b/plugins/two-factor-auth/langs/es.ini @@ -1,7 +1,4 @@ -[POPUPS_TWO_FACTOR_TEST] -TITLE_TEST_CODE = "Prueba de verificación de 2 pasos" -LABEL_CODE = "Código" -[POPUPS_TWO_FACTOR_CFG] +[PLUGIN_2FA] LEGEND_TWO_FACTOR_AUTH = "Verificación de 2 Pasos" LABEL_ENABLE_TWO_FACTOR = "Activar la verificación de 2 pasos" LABEL_TWO_FACTOR_USER = "Usuario" @@ -18,5 +15,6 @@ TWO_FACTOR_SECRET_NOT_CONFIGURED_DESC = "No configurado" TWO_FACTOR_SECRET_DESC = "Importar esta información en su cliente Google Authenticator (u otro cliente TOTP) utilizando el código QR ​​se indica debajo o introduciendo el código manualmente." TWO_FACTOR_BACKUP_CODES_DESC = "Si usted no puede recibir los códigos a través de Google Authenticator, puede utilizar códigos de copia de seguridad para firmar pulg Después de que usted ha utilizado un código de copia de seguridad para iniciar sesión, se convertirá en inactiva." TWO_FACTOR_SECRET_TEST_BEFORE_DESC = "You can't change this setting before test." -[LOGIN] +TITLE_TEST_CODE = "Prueba de verificación de 2 pasos" +LABEL_CODE = "Código" LABEL_TWO_FACTOR_CODE = "Código de verificación" diff --git a/plugins/two-factor-auth/langs/fr_FR.ini b/plugins/two-factor-auth/langs/fr.ini similarity index 95% rename from plugins/two-factor-auth/langs/fr_FR.ini rename to plugins/two-factor-auth/langs/fr.ini index 4e816a027..82cbd64dc 100644 --- a/plugins/two-factor-auth/langs/fr_FR.ini +++ b/plugins/two-factor-auth/langs/fr.ini @@ -1,4 +1,4 @@ -[POPUPS_TWO_FACTOR_CFG] +[PLUGIN_2FA] LEGEND_TWO_FACTOR_AUTH = "Authentification en deux étapes" LABEL_ENABLE_TWO_FACTOR = "Activer l'authentification en deux étapes" LABEL_TWO_FACTOR_USER = "Utilisateur" @@ -15,8 +15,6 @@ TWO_FACTOR_SECRET_NOT_CONFIGURED_DESC = "Non configuré" TWO_FACTOR_SECRET_DESC = "Importez ces informations dans votre client Google Authenticator (ou un autre client TOTP) en utilisant le code QR fourni ci-dessous ou en entrant les valeurs manuellement." TWO_FACTOR_BACKUP_CODES_DESC = "Si vous ne pouvez pas recevoir les codes par Google Authenticator, vous pouvez utiliser les codes de sauvegarde pour vous connecter. Après avoir fait cela, il deviendra inactif." TWO_FACTOR_SECRET_TEST_BEFORE_DESC = "Vous ne pouvez pas modifier ce paramètre avant de l'avoir essayé." -[POPUPS_TWO_FACTOR_TEST] TITLE_TEST_CODE = "Test d'authentification en deux étapes" LABEL_CODE = "Code" -[LOGIN] LABEL_TWO_FACTOR_CODE = "Code de vérification" diff --git a/plugins/two-factor-auth/langs/hu-HU.ini b/plugins/two-factor-auth/langs/hu.ini similarity index 86% rename from plugins/two-factor-auth/langs/hu-HU.ini rename to plugins/two-factor-auth/langs/hu.ini index 62c83aa2c..a847b1be4 100644 --- a/plugins/two-factor-auth/langs/hu-HU.ini +++ b/plugins/two-factor-auth/langs/hu.ini @@ -1,4 +1,4 @@ -[POPUPS_TWO_FACTOR_CFG] +[PLUGIN_2FA] LEGEND_TWO_FACTOR_AUTH = "2 lépcsős hitelesítés" LABEL_ENABLE_TWO_FACTOR = "2 lépcsős hitelesítés engedélyezése" LABEL_TWO_FACTOR_USER = "Felhasználó" @@ -12,11 +12,9 @@ BUTTON_SHOW_SECRET = "Titok megjelenítése" BUTTON_HIDE_SECRET = "Titok elrejtése" TWO_FACTOR_SECRET_CONFIGURED_DESC = "Beállítva" TWO_FACTOR_SECRET_NOT_CONFIGURED_DESC = "Nincs beállítva" -TWO_FACTOR_SECRET_DESC = "Importáld ezt az infót a Google Authenticator kliensedbe (vagy más TOTP kliensbe) az alábbi QR kód használatával vagy a kód manuális megadatásával.\n" -TWO_FACTOR_BACKUP_CODES_DESC = "Ha nem kapod meg a kódokat a Google Authenticator kliensből (vagy más TOTP kliensből), akkor a bejelentkezéshez használhatod a biztonsági kódot. A biztonsági kód használata után inaktívvá válik.\n" +TWO_FACTOR_SECRET_DESC = "Importáld ezt az infót a Google Authenticator kliensedbe (vagy más TOTP kliensbe) az alábbi QR kód használatával vagy a kód manuális megadatásával." +TWO_FACTOR_BACKUP_CODES_DESC = "Ha nem kapod meg a kódokat a Google Authenticator kliensből (vagy más TOTP kliensből), akkor a bejelentkezéshez használhatod a biztonsági kódot. A biztonsági kód használata után inaktívvá válik." TWO_FACTOR_SECRET_TEST_BEFORE_DESC = "Tesztelés nélkül nem lehet megváltoztatni ezt a beállítást." -[POPUPS_TWO_FACTOR_TEST] TITLE_TEST_CODE = "2-lépéses hitelesítés teszt" LABEL_CODE = "Kód" -[LOGIN] LABEL_TWO_FACTOR_CODE = "Megerősítő kód" diff --git a/plugins/two-factor-auth/langs/it_IT.ini b/plugins/two-factor-auth/langs/it.ini similarity index 90% rename from plugins/two-factor-auth/langs/it_IT.ini rename to plugins/two-factor-auth/langs/it.ini index a8252fedc..fbd44f45d 100644 --- a/plugins/two-factor-auth/langs/it_IT.ini +++ b/plugins/two-factor-auth/langs/it.ini @@ -1,7 +1,4 @@ -[POPUPS_TWO_FACTOR_TEST] -TITLE_TEST_CODE = "Test di verifica a 2 fattori" -LABEL_CODE = "Codice" -[POPUPS_TWO_FACTOR_CFG] +[PLUGIN_2FA] LEGEND_TWO_FACTOR_AUTH = "Verifica a 2 Fattori" LABEL_ENABLE_TWO_FACTOR = "Abilita la verifica a 2 fattori" LABEL_TWO_FACTOR_USER = "Utente" @@ -15,8 +12,9 @@ BUTTON_SHOW_SECRET = "Mostra la chiave segreta" BUTTON_HIDE_SECRET = "Nascondi la chiave segreta" TWO_FACTOR_SECRET_CONFIGURED_DESC = "Configurato" TWO_FACTOR_SECRET_NOT_CONFIGURED_DESC = "Non configurato" -TWO_FACTOR_SECRET_DESC = "Importa queste informazioni nella tua app Google Authenticator (o un altro programma per l'autenticazione a due fattori) utilizzando il codice QR fornito qui sotto o inserendo il codice manualmente.\n" -TWO_FACTOR_BACKUP_CODES_DESC = "Se non riesci a ricevere i codici tramite Google Authenticator (o un altro programma per l'autenticazione a due fattori), puoi utilizzare i codici di backup per accedere. Dopo che hai utilizzato un codice di backup per accedere, diventerà inattivo.\n" +TWO_FACTOR_SECRET_DESC = "Importa queste informazioni nella tua app Google Authenticator (o un altro programma per l'autenticazione a due fattori) utilizzando il codice QR fornito qui sotto o inserendo il codice manualmente." +TWO_FACTOR_BACKUP_CODES_DESC = "Se non riesci a ricevere i codici tramite Google Authenticator (o un altro programma per l'autenticazione a due fattori), puoi utilizzare i codici di backup per accedere. Dopo che hai utilizzato un codice di backup per accedere, diventerà inattivo." TWO_FACTOR_SECRET_TEST_BEFORE_DESC = "Non puoi modificare questa impostazione prima del test." -[LOGIN] +TITLE_TEST_CODE = "Test di verifica a 2 fattori" +LABEL_CODE = "Codice" LABEL_TWO_FACTOR_CODE = "Codice di Verifica" diff --git a/plugins/two-factor-auth/langs/nl_NL.ini b/plugins/two-factor-auth/langs/nl.ini similarity index 93% rename from plugins/two-factor-auth/langs/nl_NL.ini rename to plugins/two-factor-auth/langs/nl.ini index d48c636d7..425558d5f 100644 --- a/plugins/two-factor-auth/langs/nl_NL.ini +++ b/plugins/two-factor-auth/langs/nl.ini @@ -1,4 +1,4 @@ -[POPUPS_TWO_FACTOR_CFG] +[PLUGIN_2FA] LEGEND_TWO_FACTOR_AUTH = "2-Stap verificatie" LABEL_ENABLE_TWO_FACTOR = "Gebruik 2-Stap verificatie" LABEL_TWO_FACTOR_USER = "Gebruikersnaam" @@ -6,7 +6,7 @@ LABEL_TWO_FACTOR_STATUS = "Status" LABEL_TWO_FACTOR_SECRET = "Geheime sleutel" LABEL_TWO_FACTOR_BACKUP_CODES = "Backup codes" BUTTON_CREATE = "Nieuwe geheime sleutel aanmaken" -BUTTON_ACTIVATE = "Activate" +BUTTON_ACTIVATE = "Activeren" LINK_TEST = "test" BUTTON_SHOW_SECRET = "Bekijk geheime sleutel" BUTTON_HIDE_SECRET = "Verberg geheime sleutel" @@ -15,8 +15,6 @@ TWO_FACTOR_SECRET_NOT_CONFIGURED_DESC = "Niet geconfigureerd" TWO_FACTOR_SECRET_DESC = "Importeer deze informatie in uw Google Authenticator-client (of andere TOTP-client) door gebruik te maken van de QR code hier beneden of door de code handmatig in te voeren." TWO_FACTOR_BACKUP_CODES_DESC = "Als u geen codes ontvangt via de Google Authenticator kunt u de backup codes gebruiken om in te loggen. Na gebruik van de backup code wordt deze inactief." TWO_FACTOR_SECRET_TEST_BEFORE_DESC = "U kunt 2-stap verificatie niet activeren voordat u het succesvol getest heeft." -[POPUPS_TWO_FACTOR_TEST] TITLE_TEST_CODE = "2-Stap verificatie test" LABEL_CODE = "Code" -[LOGIN] LABEL_TWO_FACTOR_CODE = "Verificatie Code" diff --git a/plugins/two-factor-auth/langs/pl.ini b/plugins/two-factor-auth/langs/pl.ini new file mode 100644 index 000000000..2e00f7683 --- /dev/null +++ b/plugins/two-factor-auth/langs/pl.ini @@ -0,0 +1,20 @@ +[PLUGIN_2FA] +LEGEND_TWO_FACTOR_AUTH = "2FA (TOTP)" +LABEL_ENABLE_TWO_FACTOR = "Włącz weryfikację 2-stopniową" +LABEL_TWO_FACTOR_USER = "Użytkownik" +LABEL_TWO_FACTOR_STATUS = "Status" +LABEL_TWO_FACTOR_SECRET = "Twój sekretny klucz" +LABEL_TWO_FACTOR_BACKUP_CODES = "Kody zapasowe" +BUTTON_CREATE = "Utwórz sekretny klucz" +BUTTON_ACTIVATE = "Aktywuj" +LINK_TEST = "Testuj" +BUTTON_SHOW_SECRET = "Pokaż Twój sekretny klucz" +BUTTON_HIDE_SECRET = "Ukryj klucz" +TWO_FACTOR_SECRET_CONFIGURED_DESC = "Skonfigurowano" +TWO_FACTOR_SECRET_NOT_CONFIGURED_DESC = "Nieskonfigurowano" +TWO_FACTOR_SECRET_DESC = "Zaimportuj tę infomację do aplikacji Google Authenticator (lub innego klienta TOTP) używając kodu QR poniżej lub wpisz sekretny klucz ręcznie." +TWO_FACTOR_BACKUP_CODES_DESC = "Jeśli nie możesz uzyskać kodów poprzez aplikację Google Authenticator (lub innego klienta TOTP), możesz użyć kodów zapasowych aby się zalogować. Po użyciu kodu zapasowego do zalogowania, stanie się on nieaktywny." +TWO_FACTOR_SECRET_TEST_BEFORE_DESC = "Nie możesz zmienić tego ustawienia przed testem." +TITLE_TEST_CODE = "Test weryfikacji 2-stopniowej" +LABEL_CODE = "Kod" +LABEL_TWO_FACTOR_CODE = "Kod weryfikacyjny" diff --git a/plugins/two-factor-auth/langs/sv-SE.ini b/plugins/two-factor-auth/langs/sv.ini similarity index 95% rename from plugins/two-factor-auth/langs/sv-SE.ini rename to plugins/two-factor-auth/langs/sv.ini index 479151159..7ffd23f21 100644 --- a/plugins/two-factor-auth/langs/sv-SE.ini +++ b/plugins/two-factor-auth/langs/sv.ini @@ -1,4 +1,4 @@ -[POPUPS_TWO_FACTOR_CFG] +[PLUGIN_2FA] LEGEND_TWO_FACTOR_AUTH = "Tvåstegsverifiering (TOTP)" LABEL_ENABLE_TWO_FACTOR = "Aktivera tvåstegsverifiering" LABEL_TWO_FACTOR_USER = "Användare" @@ -15,8 +15,6 @@ TWO_FACTOR_SECRET_NOT_CONFIGURED_DESC = "Inte konfigurarad" TWO_FACTOR_SECRET_DESC = "Importera denna information till din Google Authenticator klient (eller annan TOTP klient) med denna QR kod eller manuellt med koden här nedan." TWO_FACTOR_BACKUP_CODES_DESC = "Om du inte kan ta emot koderna med Google Authenticator, så använd backupkoderna för att logga in. När du använt backupkoderna för att logga in så blir dom inaktiva." TWO_FACTOR_SECRET_TEST_BEFORE_DESC = "Du kan inte ändra denna inställning innan test." -[POPUPS_TWO_FACTOR_TEST] TITLE_TEST_CODE = "Tvåstegsverifieringstest" LABEL_CODE = "Kod" -[LOGIN] LABEL_TWO_FACTOR_CODE = "Verifikationskod" diff --git a/plugins/two-factor-auth/langs/uk.ini b/plugins/two-factor-auth/langs/uk.ini new file mode 100644 index 000000000..5f09cfb09 --- /dev/null +++ b/plugins/two-factor-auth/langs/uk.ini @@ -0,0 +1,20 @@ +[PLUGIN_2FA] +LEGEND_TWO_FACTOR_AUTH = "2-етапна перевірка (TOTP)" +LABEL_ENABLE_TWO_FACTOR = "Увімкнути 2-етапну перевірку" +LABEL_TWO_FACTOR_USER = "Ім'я користувача" +LABEL_TWO_FACTOR_STATUS = "Статус" +LABEL_TWO_FACTOR_SECRET = "Ключ" +LABEL_TWO_FACTOR_BACKUP_CODES = "Резервні коди" +BUTTON_CREATE = "Create a secret" +BUTTON_ACTIVATE = "Activate" +LINK_TEST = "Тестувати" +BUTTON_SHOW_SECRET = "Показати ключ" +BUTTON_HIDE_SECRET = "Приховати ключ" +TWO_FACTOR_SECRET_CONFIGURED_DESC = "Налаштовано" +TWO_FACTOR_SECRET_NOT_CONFIGURED_DESC = "Не налаштовано" +TWO_FACTOR_SECRET_DESC = "Імпортуйте цю інформацію у свій клієнт Google Authenticator (або інший клієнт TOTP), використовуючи наданий нижче QR-код або ввівши код вручну" +TWO_FACTOR_BACKUP_CODES_DESC = "Якщо ви не можете отримати код через Google Authenticator (або інший клієнт TOTP), ви можете скористатися резервними кодами для входу. Після того, як ви використаєте резервний код для входу, він стане неактивним. Закреслюйте його" +TWO_FACTOR_SECRET_TEST_BEFORE_DESC = "Ви не можете змінити це налаштування перед тестуванням." +TITLE_TEST_CODE = "Тест 2-етапної перевірки" +LABEL_CODE = "Код" +LABEL_TWO_FACTOR_CODE = "Код підтвердження" diff --git a/plugins/two-factor-auth/langs/zh_CN.ini b/plugins/two-factor-auth/langs/zh.ini similarity index 87% rename from plugins/two-factor-auth/langs/zh_CN.ini rename to plugins/two-factor-auth/langs/zh.ini index 948a6d886..87c530e92 100644 --- a/plugins/two-factor-auth/langs/zh_CN.ini +++ b/plugins/two-factor-auth/langs/zh.ini @@ -1,4 +1,4 @@ -[POPUPS_TWO_FACTOR_CFG] +[PLUGIN_2FA] LEGEND_TWO_FACTOR_AUTH = "两步验证 (TOTP)" LABEL_ENABLE_TWO_FACTOR = "启用两步验证" LABEL_TWO_FACTOR_USER = "用户" @@ -12,11 +12,9 @@ BUTTON_SHOW_SECRET = "显示密钥" BUTTON_HIDE_SECRET = "隐藏密钥" TWO_FACTOR_SECRET_CONFIGURED_DESC = "已设置" TWO_FACTOR_SECRET_NOT_CONFIGURED_DESC = "未设置" -TWO_FACTOR_SECRET_DESC = "将下面的信息导入 Google Authenticator (或其他 TOTP 客户端)。 扫描下面的二维码或手动输入密钥。\n" -TWO_FACTOR_BACKUP_CODES_DESC = "如果你无法从验证器获取验证码,你可以使用备用代码登录。 当你使用过某一个备用代码后,它将会失效。\n" +TWO_FACTOR_SECRET_DESC = "将下面的信息导入 Google Authenticator (或其他 TOTP 客户端)。 扫描下面的二维码或手动输入密钥。" +TWO_FACTOR_BACKUP_CODES_DESC = "如果你无法从验证器获取验证码,你可以使用备用代码登录。 当你使用过某一个备用代码后,它将会失效。" TWO_FACTOR_SECRET_TEST_BEFORE_DESC = "完成测试前你无法更改此设置。" -[POPUPS_TWO_FACTOR_TEST] TITLE_TEST_CODE = "两步验证测试" LABEL_CODE = "代码" -[LOGIN] LABEL_TWO_FACTOR_CODE = "验证码" diff --git a/plugins/two-factor-auth/templates/PopupsTwoFactorAuthTest.html b/plugins/two-factor-auth/templates/PopupsTwoFactorAuthTest.html index 556a324ef..f6242c74d 100644 --- a/plugins/two-factor-auth/templates/PopupsTwoFactorAuthTest.html +++ b/plugins/two-factor-auth/templates/PopupsTwoFactorAuthTest.html @@ -1,10 +1,10 @@
    × -

    +

    - -   - -
    -
    +

    @@ -31,4 +27,16 @@ + + +
    + +    + +
    + +
    + + +
    diff --git a/snappymail/v/0.0.0/app/templates/Views/Admin/AdminSettingsGeneral.html b/snappymail/v/0.0.0/app/templates/Views/Admin/AdminSettingsGeneral.html index 2d4f30a3b..e31f81108 100644 --- a/snappymail/v/0.0.0/app/templates/Views/Admin/AdminSettingsGeneral.html +++ b/snappymail/v/0.0.0/app/templates/Views/Admin/AdminSettingsGeneral.html @@ -8,11 +8,9 @@
    @@ -68,13 +66,6 @@ value: capaUserBackground } }">
    -
    @@ -97,7 +88,7 @@

    - PHP:  + PHP:
    diff --git a/snappymail/v/0.0.0/app/templates/Views/Admin/AdminSettingsLogin.html b/snappymail/v/0.0.0/app/templates/Views/Admin/AdminSettingsLogin.html index 4f0aa2f20..0add30ff6 100644 --- a/snappymail/v/0.0.0/app/templates/Views/Admin/AdminSettingsLogin.html +++ b/snappymail/v/0.0.0/app/templates/Views/Admin/AdminSettingsLogin.html @@ -2,14 +2,7 @@
    -
    +
    @@ -17,7 +10,6 @@ name: 'Checkbox', params: { value: determineUserDomain, label: 'TAB_LOGIN/LABEL_DETERMINE_USER_DOMAIN' } }">
    -
    -
    -
    diff --git a/snappymail/v/0.0.0/app/templates/Views/Admin/AdminSettingsPackages.html b/snappymail/v/0.0.0/app/templates/Views/Admin/AdminSettingsPackages.html index b56b24597..b52152d44 100644 --- a/snappymail/v/0.0.0/app/templates/Views/Admin/AdminSettingsPackages.html +++ b/snappymail/v/0.0.0/app/templates/Views/Admin/AdminSettingsPackages.html @@ -1,5 +1,5 @@
    - +
    @@ -15,20 +15,23 @@

    + +
    +
    -   + ()
    -
    +
    diff --git a/snappymail/v/0.0.0/app/templates/Views/Admin/AdminSettingsPluginProperty.html b/snappymail/v/0.0.0/app/templates/Views/Admin/AdminSettingsPluginProperty.html index 38ae29e2b..130d710dc 100644 --- a/snappymail/v/0.0.0/app/templates/Views/Admin/AdminSettingsPluginProperty.html +++ b/snappymail/v/0.0.0/app/templates/Views/Admin/AdminSettingsPluginProperty.html @@ -1,35 +1,36 @@ - - - + + - + - - + - -
    + + - - + + - +
    - + - - + + + + + diff --git a/snappymail/v/0.0.0/app/templates/Views/Admin/AdminSettingsSecurity.html b/snappymail/v/0.0.0/app/templates/Views/Admin/AdminSettingsSecurity.html index d670d3152..d96bf34bf 100644 --- a/snappymail/v/0.0.0/app/templates/Views/Admin/AdminSettingsSecurity.html +++ b/snappymail/v/0.0.0/app/templates/Views/Admin/AdminSettingsSecurity.html @@ -1,81 +1,79 @@
    +
    +
    +
    +
    +
    +
    +
    -
    +
    +
    + + +
    -
    -
    - - -
    -
    -
    - +
    - + +
    
     	
    -
    -
    -
    -
    -
    -    - () -
    -
    -
    + +
    -
    + diff --git a/snappymail/v/0.0.0/app/templates/Views/Admin/PopupsDomain.html b/snappymail/v/0.0.0/app/templates/Views/Admin/PopupsDomain.html index ec24f31bd..b78891e18 100644 --- a/snappymail/v/0.0.0/app/templates/Views/Admin/PopupsDomain.html +++ b/snappymail/v/0.0.0/app/templates/Views/Admin/PopupsDomain.html @@ -2,109 +2,199 @@ ×

    -