├── srcs ├── adminer │ ├── start.sh │ ├── adminer.php │ └── Dockerfile ├── mysql │ ├── my.cnf │ ├── Dockerfile │ └── start.sh ├── ftp │ ├── start.sh │ ├── Dockerfile │ └── vsftpd.conf ├── wordpress │ ├── start.sh │ ├── Dockerfile │ ├── wp-config.php │ ├── www.conf │ └── object-cache.php ├── nginx │ ├── Dockerfile │ └── default.conf └── docker-compose.yml ├── README.md └── Makefile /srcs/adminer/start.sh: -------------------------------------------------------------------------------- 1 | mv ./adminer.php /var/www/wordpress/adminer.php 2 | php-fpm7.3 -F -------------------------------------------------------------------------------- /srcs/adminer/adminer.php: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fmira21/compose-lemp-stack/HEAD/srcs/adminer/adminer.php -------------------------------------------------------------------------------- /srcs/mysql/my.cnf: -------------------------------------------------------------------------------- 1 | [mysqld] 2 | user=root 3 | port=3306 4 | datadir=/var/lib/mysql 5 | skip-networking=false 6 | bind-address=0.0.0.0 -------------------------------------------------------------------------------- /srcs/ftp/start.sh: -------------------------------------------------------------------------------- 1 | 2 | #chown for ftp work dir 3 | chown -R fmira:fmira /home/fmira 4 | 5 | #start ftp-server 6 | vsftpd /etc/vsftpd.conf -------------------------------------------------------------------------------- /srcs/wordpress/start.sh: -------------------------------------------------------------------------------- 1 | # Exchange the WP files 2 | cp -rf /var/www/data/wordpress/* /var/www/wordpress/ 3 | rm -rf /var/www/data 4 | 5 | /usr/sbin/php-fpm7 -F 6 | -------------------------------------------------------------------------------- /srcs/mysql/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM alpine:3.12 2 | VOLUME ["/sys/fs/cgroup"] 3 | RUN apk update && apk upgrade && apk add openrc mariadb mariadb-common mariadb-client 4 | COPY my.cnf /etc/ 5 | COPY start.sh / 6 | CMD sh start.sh -------------------------------------------------------------------------------- /srcs/adminer/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM debian:buster 2 | RUN apt-get update && apt-get upgrade && apt-get install -y wget php libapache2-mod-php php-curl php-cli php-mysql php-gd php-fpm 3 | RUN mkdir /var/www/wordpress/ 4 | RUN mkdir -p /run/php/ 5 | COPY adminer.php / 6 | COPY start.sh / 7 | ENTRYPOINT ["sh", "start.sh"] 8 | -------------------------------------------------------------------------------- /srcs/ftp/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM debian:buster 2 | 3 | RUN apt-get update && apt-get upgrade 4 | RUN apt-get install -y vsftpd 5 | RUN mkdir -p /var/run/vsftpd/empty/ 6 | COPY ./vsftpd.conf /etc/ 7 | RUN adduser --disabled-password --gecos 'fmira' fmira 8 | RUN echo "fmira:1234" | chpasswd 9 | RUN echo "fmira" | tee -a /etc/vsftpd.userlist 10 | COPY start.sh / 11 | ENTRYPOINT ["sh", "start.sh"] -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LEMP stack in Docker Compose 2 | This repository is done for demonstration and educational purposes only. 3 | 4 | Here, you will find an example of the complete Dockerised LEMP stack to deploy via Docker Compose on a single machine. 5 | 6 | Additionally, the deployment contains following self-built services: 7 | 8 | - Adminer to manage MariaDB 9 | - Basic FTP server 10 | 11 | All credentials are passed without restrictions. 12 | 13 | Read through the Makefile for additional instructions. -------------------------------------------------------------------------------- /srcs/ftp/vsftpd.conf: -------------------------------------------------------------------------------- 1 | listen=YES 2 | listen_ipv6=NO 3 | connect_from_port_20=YES 4 | anonymous_enable=NO 5 | local_enable=YES 6 | write_enable=YES 7 | chroot_local_user=YES 8 | allow_writeable_chroot=YES 9 | secure_chroot_dir=/var/run/vsftpd/empty 10 | pam_service_name=vsftpd 11 | pasv_enable=YES 12 | userlist_enable=YES 13 | userlist_file=/etc/vsftpd.userlist 14 | userlist_deny=NO 15 | xferlog_enable=YES 16 | seccomp_sandbox=NO 17 | pasv_address=127.0.0.1 18 | pasv_min_port=21000 19 | pasv_max_port=21000 -------------------------------------------------------------------------------- /srcs/wordpress/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM alpine:3.12 2 | RUN apk update && apk upgrade && apk add php7 php7-fpm php7-session php7-json php7-mysqli php7-xml php7-curl php7-iconv php7-phar php7-redis php7-ctype 3 | ADD https://wordpress.org/latest.tar.gz /var/www/data/ 4 | RUN cd /var/www/data/ && tar -xf latest.tar.gz && rm -rf latest.tar.gz 5 | COPY wp-config.php /var/www/data/wordpress/ 6 | COPY www.conf /etc/php7/php-fpm.d/ 7 | COPY ./start.sh / 8 | 9 | #REDIS 10 | COPY ./object-cache.php /var/www/data/wordpress/wp-content 11 | 12 | ENTRYPOINT ["sh", "start.sh"] 13 | -------------------------------------------------------------------------------- /srcs/nginx/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM alpine:3.12 2 | RUN apk update && apk upgrade && apk add nginx openssl 3 | COPY ./default.conf /etc/nginx/conf.d/default.conf 4 | RUN openssl req -x509 -nodes -days 365 -subj "/C=UK/ST=London/L=London/O=London/OU=Place/CN=fmira" -newkey rsa:2048 -keyout /etc/ssl/private/nginx.key -out /etc/ssl/certs/nginx.crt; 5 | 6 | # NGINX PID file will be stored here. Othervise, the container will stop with the NODIR error. 7 | RUN mkdir /run/nginx/ 8 | 9 | # Start the server as a process, not a daemon. 10 | ENTRYPOINT ["nginx", "-g", "daemon off;"] -------------------------------------------------------------------------------- /srcs/mysql/start.sh: -------------------------------------------------------------------------------- 1 | # rc is deprecated: use openrc to silence the system warning. 2 | openrc default 3 | /etc/init.d/mariadb setup 4 | rc-service mariadb start 5 | 6 | 7 | mysql -u root --password=rootpass -e "CREATE DATABASE IF NOT EXISTS $SQL_DB;" 8 | mysql -u root --password=rootpass -e "CREATE USER IF NOT EXISTS '$SQL_DB_USER'@'%' IDENTIFIED BY '$SQL_DB_PASS';" 9 | mysql -u root --password=rootpass -e "CREATE USER IF NOT EXISTS '$SQL_DB_USER'@'localhost' IDENTIFIED BY '$SQL_DB_PASS';" 10 | mysql -u root --password=rootpass -e "GRANT ALL PRIVILEGES ON $SQL_DB.* TO '$SQL_DB_USER'@'%';" 11 | mysql -u root --password=rootpass -e "GRANT ALL PRIVILEGES ON $SQL_DB.* TO '$SQL_DB_USER'@'localhost';" 12 | mysql -u root --password=rootpass -e "FLUSH PRIVILEGES;" 13 | 14 | mysql -u root --password=rootpass -e "ALTER USER 'root'@'localhost' IDENTIFIED BY '$SQL_ROOT_PASS';" 15 | 16 | rc-service mariadb stop 17 | /usr/bin/mysqld_safe 18 | 19 | # Note that mysqld safe will properly hang up the container for execution. 20 | #This configuration will put the mysqld log into STDOUT of the terminal. -------------------------------------------------------------------------------- /srcs/nginx/default.conf: -------------------------------------------------------------------------------- 1 | # HTTPS only: nothing will be available via http://localhost 2 | server { 3 | listen 443 ssl; 4 | listen [::]:443 ssl; 5 | 6 | server_name fmira.42.fr; 7 | 8 | ssl_certificate_key /etc/ssl/private/nginx.key; 9 | ssl_certificate /etc/ssl/certs/nginx.crt; 10 | ssl_protocols TLSv1.2 TLSv1.3; 11 | 12 | index index.php; 13 | root /var/www/wordpress; 14 | 15 | location / { 16 | try_files $uri $uri/ /index.php$is_args$args; 17 | } 18 | 19 | # Adminer regexp. In fact, Adminer itself is located in the Wordpress volume, but uses its own PHP environment from the container. 20 | location /adminer { 21 | rewrite ^/adminer$ /adminer.php; 22 | } 23 | 24 | # Docsite regexp: just redirect to its containerized NGINX listening to 443 25 | location /docsite { 26 | rewrite /docsite(.*) /$1 break; 27 | proxy_pass https://docsite:443; 28 | } 29 | 30 | # Here: regexp for proper PHP script addressing + a set of options (see the NGINX WP documentation) 31 | location ~ [^/]\.php(/|$) { 32 | try_files $uri =404; 33 | fastcgi_split_path_info ^(.+\.php)(/.+)$; 34 | fastcgi_pass wordpress:9000; 35 | fastcgi_index index.php; 36 | include fastcgi_params; 37 | fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 38 | fastcgi_param PATH_INFO $fastcgi_path_info; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Basic rule: build or rebuild the composed containers 2 | all: 3 | docker-compose -f srcs/docker-compose.yml --env-file ./srcs/.env up --build 4 | # Assign domain name to the localhost 5 | hosts: 6 | echo "127.0.0.1 lemp-stack.com" | tee -a /etc/hosts 7 | # Stop the containers 8 | clean: 9 | docker-compose -f srcs/docker-compose.yml down 10 | # Remove the volumes. To remove the images, use the RELOAD rule 11 | fclean: clean 12 | docker system prune -a --volumes 13 | # Remove all volumes and images. In order to stop all containers, remove them and clear volume directories, launch the separate reload.sh script. 14 | reload: clean 15 | docker stop $(docker ps -qa) 16 | docker rm $(docker ps -qa) 17 | docker rmi -f $(docker images -qa) 18 | docker volume rm $(docker volume ls -q) 19 | docker network rm $(docker network ls -q) 2>/dev/null 20 | # Remove all volumes and rebuild 21 | re: fclean all 22 | # Backup data directory with all volumes 23 | backup: 24 | rm -rf backup 25 | mkdir backup 26 | cp -r $HOME/data/* ./backup/ 27 | # Restore the backup 28 | restore: 29 | rm -rf $HOME/data 30 | cp -r ./backup/* $HOME/data/ 31 | # Connect containers 32 | connect: 33 | docker-compose -f srcs/docker-compose.yml exec $(service) bash 34 | # Force-stop the setup 35 | force-stop: 36 | killall containerd-shim 37 | docker-compose -f srcs/docker-compose.yml down 38 | # Reload the setup 39 | reload: 40 | docker stop $(docker ps -qa) 41 | docker rm $(docker ps -qa) 42 | docker rmi -f $(docker images -qa) 43 | docker volume rm $(docker volume ls -q) 44 | docker network rm $(docker network ls -q) 2>/dev/null 45 | 46 | -------------------------------------------------------------------------------- /srcs/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.5" 2 | 3 | networks: 4 | supernetwork: 5 | name: supernetwork 6 | 7 | volumes: 8 | wordpress: 9 | name: wordpress 10 | driver: local 11 | driver_opts: 12 | type: none 13 | o: bind 14 | device: $HOME/data/wordpress 15 | mysql: 16 | name: mysql 17 | driver: local 18 | driver_opts: 19 | type: none 20 | o: bind 21 | device: $HOME/data/mysql 22 | sphinx: 23 | name: sphinx 24 | driver: local 25 | driver_opts: 26 | type: none 27 | o: bind 28 | device: $HOME/data/sphinx 29 | docs: 30 | name: docs 31 | driver: local 32 | driver_opts: 33 | type: none 34 | o: bind 35 | device: $HOME/data/docs 36 | 37 | services: 38 | nginx: 39 | container_name: nginx_alpine 40 | build: 41 | context: ./nginx 42 | image: nginx 43 | restart: always 44 | ports: 45 | - 443:443 46 | volumes: 47 | - wordpress:/var/www/wordpress 48 | networks: 49 | - supernetwork 50 | depends_on: 51 | - wordpress 52 | 53 | wordpress: 54 | container_name: wordpress_alpine 55 | build: 56 | context: ./wordpress 57 | image: wordpress 58 | restart: always 59 | volumes: 60 | - wordpress:/var/www/wordpress 61 | networks: 62 | - supernetwork 63 | depends_on: 64 | - mysql 65 | environment: 66 | - WP_DB=${WP_DB} 67 | - DB_USER=${DB_USER} 68 | - DB_PASS=${DB_PASS} 69 | - DB_HOST=${DB_HOST} 70 | mysql: 71 | container_name: mysql_alpine 72 | build: 73 | context: ./mysql 74 | image: mysql 75 | restart: always 76 | volumes: 77 | - mysql:/var/lib/mysql 78 | networks: 79 | - supernetwork 80 | environment: 81 | - SQL_DB=${SQL_DB} 82 | - SQL_DB_USER=${SQL_DB_USER} 83 | - SQL_DB_PASS=${SQL_DB_PASS} 84 | - SQL_ROOT_PASS=${SQL_ROOT_PASS} 85 | - NETWORK=${NETWORK} 86 | ftp: 87 | container_name: ftp_debian 88 | build: 89 | context: ./ftp 90 | tty: true 91 | image: ftp 92 | restart: always 93 | ports: 94 | - 21000:21000 95 | - "21:21" 96 | volumes: 97 | - wordpress:/wp_data 98 | networks: 99 | - supernetwork 100 | depends_on: 101 | - wordpress 102 | 103 | redis: 104 | container_name: redis_debian 105 | build: 106 | context: ./redis 107 | tty: true 108 | image: redis 109 | restart: always 110 | ports: 111 | - "6379:6379" 112 | networks: 113 | - supernetwork 114 | 115 | adminer: 116 | container_name: adminer_debian 117 | build: 118 | context: ./adminer 119 | tty: true 120 | image: adminer 121 | restart: always 122 | depends_on: 123 | - wordpress 124 | ports: 125 | - 8080:8080 126 | networks: 127 | - supernetwork 128 | volumes: 129 | - wordpress:/var/www/wordpress/ 130 | 131 | -------------------------------------------------------------------------------- /srcs/wordpress/wp-config.php: -------------------------------------------------------------------------------- 1 | [FJ|@X|Us#i*vSsO?+{G-W&3aQMixXf=lCdPMeEOxuE^fP?=~'); 64 | define('LOGGED_IN_KEY', '`^h=TVJz:plG<-`PK.a`+kA!zA:8.%%(ISSAcz!,nUVnB0Pry. u-KeF>72__g/ '); 65 | define('NONCE_KEY', 'k(UHNA@]-2.DpU068HU6LoJUI.jV=D/;/qN(1!_BH|W5~*h*PQW3;oK(ny$Ydt9o'); 66 | define('AUTH_SALT', '=[,zH51B:+ 4O(V5K&aORZ6nybI[(qOoK5m;v?C^PqW:-SI%XE~i.!UyN<4DVKAP'); 67 | define('SECURE_AUTH_SALT', '+Cj?f&ln4p-Xip1[P>QLq)Kz'); 70 | 71 | /**#@-*/ 72 | 73 | /** 74 | * WordPress Database Table prefix. 75 | * 76 | * You can have multiple installations in one database if you give each 77 | * a unique prefix. Only numbers, letters, and underscores please! 78 | */ 79 | $table_prefix = 'wp_'; 80 | 81 | /** 82 | * For developers: WordPress debugging mode. 83 | * 84 | * Change this to true to enable the display of notices during development. 85 | * It is strongly recommended that plugin and theme developers use WP_DEBUG 86 | * in their development environments. 87 | * 88 | * For information on other constants that can be used for debugging, 89 | * visit the documentation. 90 | * 91 | * @link https://wordpress.org/support/article/debugging-in-wordpress/ 92 | */ 93 | define( 'WP_DEBUG', true ); 94 | 95 | define( 'WP_DEBUG_LOG', true ); 96 | 97 | define( 'WP_DEBUG_DISPLAY', false ); 98 | /* That's all, stop editing! Happy publishing. */ 99 | 100 | /** Absolute path to the WordPress directory. */ 101 | if ( ! defined( 'ABSPATH' ) ) { 102 | define( 'ABSPATH', __DIR__ . '/' ); 103 | } 104 | 105 | /** Sets up WordPress vars and included files. */ 106 | require_once ABSPATH . 'wp-settings.php'; 107 | ?> -------------------------------------------------------------------------------- /srcs/wordpress/www.conf: -------------------------------------------------------------------------------- 1 | ; Start a new pool named 'www'. 2 | ; the variable $pool can be used in any directive and will be replaced by the 3 | ; pool name ('www' here) 4 | [www] 5 | 6 | ; Per pool prefix 7 | ; It only applies on the following directives: 8 | ; - 'access.log' 9 | ; - 'slowlog' 10 | ; - 'listen' (unixsocket) 11 | ; - 'chroot' 12 | ; - 'chdir' 13 | ; - 'php_values' 14 | ; - 'php_admin_values' 15 | ; When not set, the global prefix (or /usr) applies instead. 16 | ; Note: This directive can also be relative to the global prefix. 17 | ; Default Value: none 18 | ;prefix = /path/to/pools/$pool 19 | 20 | ; Unix user/group of processes 21 | ; Note: The user is mandatory. If the group is not set, the default user's group 22 | ; will be used. 23 | user = nobody 24 | group = nobody 25 | 26 | ; The address on which to accept FastCGI requests. 27 | ; Valid syntaxes are: 28 | ; 'ip.add.re.ss:port' - to listen on a TCP socket to a specific IPv4 address on 29 | ; a specific port; 30 | ; '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on 31 | ; a specific port; 32 | ; 'port' - to listen on a TCP socket to all addresses 33 | ; (IPv6 and IPv4-mapped) on a specific port; 34 | ; '/path/to/unix/socket' - to listen on a unix socket. 35 | ; Note: This value is mandatory. 36 | listen = wordpress:9000 37 | 38 | ; Set listen(2) backlog. 39 | ; Default Value: 511 (-1 on FreeBSD and OpenBSD) 40 | ;listen.backlog = 511 41 | 42 | ; Set permissions for unix socket, if one is used. In Linux, read/write 43 | ; permissions must be set in order to allow connections from a web server. Many 44 | ; BSD-derived systems allow connections regardless of permissions. 45 | ; Default Values: user and group are set as the running user 46 | ; mode is set to 0660 47 | ;listen.owner = nobody 48 | ;listen.group = nobody 49 | ;listen.mode = 0660 50 | ; When POSIX Access Control Lists are supported you can set them using 51 | ; these options, value is a comma separated list of user/group names. 52 | ; When set, listen.owner and listen.group are ignored 53 | ;listen.acl_users = 54 | ;listen.acl_groups = 55 | 56 | ; List of addresses (IPv4/IPv6) of FastCGI clients which are allowed to connect. 57 | ; Equivalent to the FCGI_WEB_SERVER_ADDRS environment variable in the original 58 | ; PHP FCGI (5.2.2+). Makes sense only with a tcp listening socket. Each address 59 | ; must be separated by a comma. If this value is left blank, connections will be 60 | ; accepted from any ip address. 61 | ; Default Value: any 62 | ;listen.allowed_clients = nginx 63 | 64 | ; Specify the nice(2) priority to apply to the pool processes (only if set) 65 | ; The value can vary from -19 (highest priority) to 20 (lower priority) 66 | ; Note: - It will only work if the FPM master process is launched as root 67 | ; - The pool processes will inherit the master process priority 68 | ; unless it specified otherwise 69 | ; Default Value: no set 70 | ; process.priority = -19 71 | 72 | ; Set the process dumpable flag (PR_SET_DUMPABLE prctl) even if the process user 73 | ; or group is differrent than the master process user. It allows to create process 74 | ; core dump and ptrace the process for the pool user. 75 | ; Default Value: no 76 | ; process.dumpable = yes 77 | 78 | ; Choose how the process manager will control the number of child processes. 79 | ; Possible Values: 80 | ; static - a fixed number (pm.max_children) of child processes; 81 | ; dynamic - the number of child processes are set dynamically based on the 82 | ; following directives. With this process management, there will be 83 | ; always at least 1 children. 84 | ; pm.max_children - the maximum number of children that can 85 | ; be alive at the same time. 86 | ; pm.start_servers - the number of children created on startup. 87 | ; pm.min_spare_servers - the minimum number of children in 'idle' 88 | ; state (waiting to process). If the number 89 | ; of 'idle' processes is less than this 90 | ; number then some children will be created. 91 | ; pm.max_spare_servers - the maximum number of children in 'idle' 92 | ; state (waiting to process). If the number 93 | ; of 'idle' processes is greater than this 94 | ; number then some children will be killed. 95 | ; ondemand - no children are created at startup. Children will be forked when 96 | ; new requests will connect. The following parameter are used: 97 | ; pm.max_children - the maximum number of children that 98 | ; can be alive at the same time. 99 | ; pm.process_idle_timeout - The number of seconds after which 100 | ; an idle process will be killed. 101 | ; Note: This value is mandatory. 102 | pm = dynamic 103 | 104 | ; The number of child processes to be created when pm is set to 'static' and the 105 | ; maximum number of child processes when pm is set to 'dynamic' or 'ondemand'. 106 | ; This value sets the limit on the number of simultaneous requests that will be 107 | ; served. Equivalent to the ApacheMaxClients directive with mpm_prefork. 108 | ; Equivalent to the PHP_FCGI_CHILDREN environment variable in the original PHP 109 | ; CGI. The below defaults are based on a server without much resources. Don't 110 | ; forget to tweak pm.* to fit your needs. 111 | ; Note: Used when pm is set to 'static', 'dynamic' or 'ondemand' 112 | ; Note: This value is mandatory. 113 | pm.max_children = 5 114 | 115 | ; The number of child processes created on startup. 116 | ; Note: Used only when pm is set to 'dynamic' 117 | ; Default Value: min_spare_servers + (max_spare_servers - min_spare_servers) / 2 118 | pm.start_servers = 2 119 | 120 | ; The desired minimum number of idle server processes. 121 | ; Note: Used only when pm is set to 'dynamic' 122 | ; Note: Mandatory when pm is set to 'dynamic' 123 | pm.min_spare_servers = 1 124 | 125 | ; The desired maximum number of idle server processes. 126 | ; Note: Used only when pm is set to 'dynamic' 127 | ; Note: Mandatory when pm is set to 'dynamic' 128 | pm.max_spare_servers = 3 129 | 130 | ; The number of seconds after which an idle process will be killed. 131 | ; Note: Used only when pm is set to 'ondemand' 132 | ; Default Value: 10s 133 | ;pm.process_idle_timeout = 10s; 134 | 135 | ; The number of requests each child process should execute before respawning. 136 | ; This can be useful to work around memory leaks in 3rd party libraries. For 137 | ; endless request processing specify '0'. Equivalent to PHP_FCGI_MAX_REQUESTS. 138 | ; Default Value: 0 139 | ;pm.max_requests = 500 140 | 141 | ; The URI to view the FPM status page. If this value is not set, no URI will be 142 | ; recognized as a status page. It shows the following informations: 143 | ; pool - the name of the pool; 144 | ; process manager - static, dynamic or ondemand; 145 | ; start time - the date and time FPM has started; 146 | ; start since - number of seconds since FPM has started; 147 | ; accepted conn - the number of request accepted by the pool; 148 | ; listen queue - the number of request in the queue of pending 149 | ; connections (see backlog in listen(2)); 150 | ; max listen queue - the maximum number of requests in the queue 151 | ; of pending connections since FPM has started; 152 | ; listen queue len - the size of the socket queue of pending connections; 153 | ; idle processes - the number of idle processes; 154 | ; active processes - the number of active processes; 155 | ; total processes - the number of idle + active processes; 156 | ; max active processes - the maximum number of active processes since FPM 157 | ; has started; 158 | ; max children reached - number of times, the process limit has been reached, 159 | ; when pm tries to start more children (works only for 160 | ; pm 'dynamic' and 'ondemand'); 161 | ; Value are updated in real time. 162 | ; Example output: 163 | ; pool: www 164 | ; process manager: static 165 | ; start time: 01/Jul/2011:17:53:49 +0200 166 | ; start since: 62636 167 | ; accepted conn: 190460 168 | ; listen queue: 0 169 | ; max listen queue: 1 170 | ; listen queue len: 42 171 | ; idle processes: 4 172 | ; active processes: 11 173 | ; total processes: 15 174 | ; max active processes: 12 175 | ; max children reached: 0 176 | ; 177 | ; By default the status page output is formatted as text/plain. Passing either 178 | ; 'html', 'xml' or 'json' in the query string will return the corresponding 179 | ; output syntax. Example: 180 | ; http://www.foo.bar/status 181 | ; http://www.foo.bar/status?json 182 | ; http://www.foo.bar/status?html 183 | ; http://www.foo.bar/status?xml 184 | ; 185 | ; By default the status page only outputs short status. Passing 'full' in the 186 | ; query string will also return status for each pool process. 187 | ; Example: 188 | ; http://www.foo.bar/status?full 189 | ; http://www.foo.bar/status?json&full 190 | ; http://www.foo.bar/status?html&full 191 | ; http://www.foo.bar/status?xml&full 192 | ; The Full status returns for each process: 193 | ; pid - the PID of the process; 194 | ; state - the state of the process (Idle, Running, ...); 195 | ; start time - the date and time the process has started; 196 | ; start since - the number of seconds since the process has started; 197 | ; requests - the number of requests the process has served; 198 | ; request duration - the duration in µs of the requests; 199 | ; request method - the request method (GET, POST, ...); 200 | ; request URI - the request URI with the query string; 201 | ; content length - the content length of the request (only with POST); 202 | ; user - the user (PHP_AUTH_USER) (or '-' if not set); 203 | ; script - the main script called (or '-' if not set); 204 | ; last request cpu - the %cpu the last request consumed 205 | ; it's always 0 if the process is not in Idle state 206 | ; because CPU calculation is done when the request 207 | ; processing has terminated; 208 | ; last request memory - the max amount of memory the last request consumed 209 | ; it's always 0 if the process is not in Idle state 210 | ; because memory calculation is done when the request 211 | ; processing has terminated; 212 | ; If the process is in Idle state, then informations are related to the 213 | ; last request the process has served. Otherwise informations are related to 214 | ; the current request being served. 215 | ; Example output: 216 | ; ************************ 217 | ; pid: 31330 218 | ; state: Running 219 | ; start time: 01/Jul/2011:17:53:49 +0200 220 | ; start since: 63087 221 | ; requests: 12808 222 | ; request duration: 1250261 223 | ; request method: GET 224 | ; request URI: /test_mem.php?N=10000 225 | ; content length: 0 226 | ; user: - 227 | ; script: /home/fat/web/docs/php/test_mem.php 228 | ; last request cpu: 0.00 229 | ; last request memory: 0 230 | ; 231 | ; Note: There is a real-time FPM status monitoring sample web page available 232 | ; It's available in: /usr/share/php7/fpm/status.html 233 | ; 234 | ; Note: The value must start with a leading slash (/). The value can be 235 | ; anything, but it may not be a good idea to use the .php extension or it 236 | ; may conflict with a real PHP file. 237 | ; Default Value: not set 238 | ;pm.status_path = /status 239 | 240 | ; The ping URI to call the monitoring page of FPM. If this value is not set, no 241 | ; URI will be recognized as a ping page. This could be used to test from outside 242 | ; that FPM is alive and responding, or to 243 | ; - create a graph of FPM availability (rrd or such); 244 | ; - remove a server from a group if it is not responding (load balancing); 245 | ; - trigger alerts for the operating team (24/7). 246 | ; Note: The value must start with a leading slash (/). The value can be 247 | ; anything, but it may not be a good idea to use the .php extension or it 248 | ; may conflict with a real PHP file. 249 | ; Default Value: not set 250 | ;ping.path = /ping 251 | 252 | ; This directive may be used to customize the response of a ping request. The 253 | ; response is formatted as text/plain with a 200 response code. 254 | ; Default Value: pong 255 | ;ping.response = pong 256 | 257 | ; The access log file 258 | ; Default: not set 259 | ;access.log = log/php7/$pool.access.log 260 | 261 | ; The access log format. 262 | ; The following syntax is allowed 263 | ; %%: the '%' character 264 | ; %C: %CPU used by the request 265 | ; it can accept the following format: 266 | ; - %{user}C for user CPU only 267 | ; - %{system}C for system CPU only 268 | ; - %{total}C for user + system CPU (default) 269 | ; %d: time taken to serve the request 270 | ; it can accept the following format: 271 | ; - %{seconds}d (default) 272 | ; - %{miliseconds}d 273 | ; - %{mili}d 274 | ; - %{microseconds}d 275 | ; - %{micro}d 276 | ; %e: an environment variable (same as $_ENV or $_SERVER) 277 | ; it must be associated with embraces to specify the name of the env 278 | ; variable. Some exemples: 279 | ; - server specifics like: %{REQUEST_METHOD}e or %{SERVER_PROTOCOL}e 280 | ; - HTTP headers like: %{HTTP_HOST}e or %{HTTP_USER_AGENT}e 281 | ; %f: script filename 282 | ; %l: content-length of the request (for POST request only) 283 | ; %m: request method 284 | ; %M: peak of memory allocated by PHP 285 | ; it can accept the following format: 286 | ; - %{bytes}M (default) 287 | ; - %{kilobytes}M 288 | ; - %{kilo}M 289 | ; - %{megabytes}M 290 | ; - %{mega}M 291 | ; %n: pool name 292 | ; %o: output header 293 | ; it must be associated with embraces to specify the name of the header: 294 | ; - %{Content-Type}o 295 | ; - %{X-Powered-By}o 296 | ; - %{Transfert-Encoding}o 297 | ; - .... 298 | ; %p: PID of the child that serviced the request 299 | ; %P: PID of the parent of the child that serviced the request 300 | ; %q: the query string 301 | ; %Q: the '?' character if query string exists 302 | ; %r: the request URI (without the query string, see %q and %Q) 303 | ; %R: remote IP address 304 | ; %s: status (response code) 305 | ; %t: server time the request was received 306 | ; it can accept a strftime(3) format: 307 | ; %d/%b/%Y:%H:%M:%S %z (default) 308 | ; The strftime(3) format must be encapsuled in a %{}t tag 309 | ; e.g. for a ISO8601 formatted timestring, use: %{%Y-%m-%dT%H:%M:%S%z}t 310 | ; %T: time the log has been written (the request has finished) 311 | ; it can accept a strftime(3) format: 312 | ; %d/%b/%Y:%H:%M:%S %z (default) 313 | ; The strftime(3) format must be encapsuled in a %{}t tag 314 | ; e.g. for a ISO8601 formatted timestring, use: %{%Y-%m-%dT%H:%M:%S%z}t 315 | ; %u: remote user 316 | ; 317 | ; Default: "%R - %u %t \"%m %r\" %s" 318 | ;access.format = "%R - %u %t \"%m %r%Q%q\" %s %f %{mili}d %{kilo}M %C%%" 319 | 320 | ; The log file for slow requests 321 | ; Default Value: not set 322 | ; Note: slowlog is mandatory if request_slowlog_timeout is set 323 | ;slowlog = log/php7/$pool.slow.log 324 | 325 | ; The timeout for serving a single request after which a PHP backtrace will be 326 | ; dumped to the 'slowlog' file. A value of '0s' means 'off'. 327 | ; Available units: s(econds)(default), m(inutes), h(ours), or d(ays) 328 | ; Default Value: 0 329 | ;request_slowlog_timeout = 0 330 | 331 | ; Depth of slow log stack trace. 332 | ; Default Value: 20 333 | ;request_slowlog_trace_depth = 20 334 | 335 | ; The timeout for serving a single request after which the worker process will 336 | ; be killed. This option should be used when the 'max_execution_time' ini option 337 | ; does not stop script execution for some reason. A value of '0' means 'off'. 338 | ; Available units: s(econds)(default), m(inutes), h(ours), or d(ays) 339 | ; Default Value: 0 340 | ;request_terminate_timeout = 0 341 | 342 | ; The timeout set by 'request_terminate_timeout' ini option is not engaged after 343 | ; application calls 'fastcgi_finish_request' or when application has finished and 344 | ; shutdown functions are being called (registered via register_shutdown_function). 345 | ; This option will enable timeout limit to be applied unconditionally 346 | ; even in such cases. 347 | ; Default Value: no 348 | ;request_terminate_timeout_track_finished = no 349 | 350 | ; Set open file descriptor rlimit. 351 | ; Default Value: system defined value 352 | ;rlimit_files = 1024 353 | 354 | ; Set max core size rlimit. 355 | ; Possible Values: 'unlimited' or an integer greater or equal to 0 356 | ; Default Value: system defined value 357 | ;rlimit_core = 0 358 | 359 | ; Chroot to this directory at the start. This value must be defined as an 360 | ; absolute path. When this value is not set, chroot is not used. 361 | ; Note: you can prefix with '$prefix' to chroot to the pool prefix or one 362 | ; of its subdirectories. If the pool prefix is not set, the global prefix 363 | ; will be used instead. 364 | ; Note: chrooting is a great security feature and should be used whenever 365 | ; possible. However, all PHP paths will be relative to the chroot 366 | ; (error_log, sessions.save_path, ...). 367 | ; Default Value: not set 368 | ;chroot = 369 | 370 | ; Chdir to this directory at the start. 371 | ; Note: relative path can be used. 372 | ; Default Value: current directory or / when chroot 373 | ;chdir = /var/www 374 | 375 | ; Redirect worker stdout and stderr into main error log. If not set, stdout and 376 | ; stderr will be redirected to /dev/null according to FastCGI specs. 377 | ; Note: on highloaded environement, this can cause some delay in the page 378 | ; process time (several ms). 379 | ; Default Value: no 380 | ;catch_workers_output = yes 381 | 382 | ; Decorate worker output with prefix and suffix containing information about 383 | ; the child that writes to the log and if stdout or stderr is used as well as 384 | ; log level and time. This options is used only if catch_workers_output is yes. 385 | ; Settings to "no" will output data as written to the stdout or stderr. 386 | ; Default value: yes 387 | ;decorate_workers_output = no 388 | 389 | ; Clear environment in FPM workers 390 | ; Prevents arbitrary environment variables from reaching FPM worker processes 391 | ; by clearing the environment in workers before env vars specified in this 392 | ; pool configuration are added. 393 | ; Setting to "no" will make all environment variables available to PHP code 394 | ; via getenv(), $_ENV and $_SERVER. 395 | ; Default Value: yes 396 | clear_env = no 397 | 398 | ; Limits the extensions of the main script FPM will allow to parse. This can 399 | ; prevent configuration mistakes on the web server side. You should only limit 400 | ; FPM to .php extensions to prevent malicious users to use other extensions to 401 | ; execute php code. 402 | ; Note: set an empty value to allow all extensions. 403 | ; Default Value: .php 404 | ;security.limit_extensions = .php .php3 .php4 .php5 .php7 405 | 406 | ; Pass environment variables like LD_LIBRARY_PATH. All $VARIABLEs are taken from 407 | ; the current environment. 408 | ; Default Value: clean env 409 | ;env[HOSTNAME] = $HOSTNAME 410 | ;env[PATH] = /usr/local/bin:/usr/bin:/bin 411 | ;env[TMP] = /tmp 412 | ;env[TMPDIR] = /tmp 413 | ;env[TEMP] = /tmp 414 | 415 | ; Additional php.ini defines, specific to this pool of workers. These settings 416 | ; overwrite the values previously defined in the php.ini. The directives are the 417 | ; same as the PHP SAPI: 418 | ; php_value/php_flag - you can set classic ini defines which can 419 | ; be overwritten from PHP call 'ini_set'. 420 | ; php_admin_value/php_admin_flag - these directives won't be overwritten by 421 | ; PHP call 'ini_set' 422 | ; For php_*flag, valid values are on, off, 1, 0, true, false, yes or no. 423 | 424 | ; Defining 'extension' will load the corresponding shared extension from 425 | ; extension_dir. Defining 'disable_functions' or 'disable_classes' will not 426 | ; overwrite previously defined php.ini values, but will append the new value 427 | ; instead. 428 | 429 | ; Note: path INI options can be relative and will be expanded with the prefix 430 | ; (pool, global or /usr) 431 | 432 | ; Default Value: nothing is defined by default except the values in php.ini and 433 | ; specified at startup with the -d argument 434 | ;php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f www@my.domain.com 435 | ;php_flag[display_errors] = off 436 | ;php_admin_value[error_log] = /var/log/php7/$pool.error.log 437 | ;php_admin_flag[log_errors] = on 438 | ;php_admin_value[memory_limit] = 32M -------------------------------------------------------------------------------- /srcs/wordpress/object-cache.php: -------------------------------------------------------------------------------- 1 | add( $key, $value, $group, $expiration ); 37 | } 38 | 39 | /** 40 | * Closes the cache. 41 | * 42 | * This function has ceased to do anything since WordPress 2.5. The 43 | * functionality was removed along with the rest of the persistent cache. This 44 | * does not mean that plugins can't implement this function when they need to 45 | * make sure that the cache is cleaned up after WordPress no longer needs it. 46 | * 47 | * @return bool Always returns True 48 | */ 49 | function wp_cache_close() { 50 | return true; 51 | } 52 | 53 | /** 54 | * Decrement a numeric item's value. 55 | * 56 | * @param string $key The key under which to store the value. 57 | * @param int $offset The amount by which to decrement the item's value. 58 | * @param string $group The group value appended to the $key. 59 | * 60 | * @return int|bool Returns item's new value on success or FALSE on failure. 61 | */ 62 | function wp_cache_decr( $key, $offset = 1, $group = '' ) { 63 | global $wp_object_cache; 64 | 65 | return $wp_object_cache->decrement( $key, $offset, $group ); 66 | } 67 | 68 | /** 69 | * Remove the item from the cache. 70 | * 71 | * @param string $key The key under which to store the value. 72 | * @param string $group The group value appended to the $key. 73 | * @param int $time The amount of time the server will wait to delete the item in seconds. 74 | * 75 | * @return bool Returns TRUE on success or FALSE on failure. 76 | */ 77 | function wp_cache_delete( $key, $group = '', $time = 0 ) { 78 | global $wp_object_cache; 79 | 80 | return $wp_object_cache->delete( $key, $group, $time ); 81 | } 82 | 83 | /** 84 | * Invalidate all items in the cache. If `WP_REDIS_SELECTIVE_FLUSH` is `true`, 85 | * only keys prefixed with the `WP_REDIS_PREFIX` are flushed. 86 | * 87 | * @param int $delay Number of seconds to wait before invalidating the items. 88 | * 89 | * @return bool Returns TRUE on success or FALSE on failure. 90 | */ 91 | function wp_cache_flush( $delay = 0 ) { 92 | global $wp_object_cache; 93 | 94 | return $wp_object_cache->flush( $delay ); 95 | } 96 | 97 | /** 98 | * Retrieve object from cache. 99 | * 100 | * Gets an object from cache based on $key and $group. 101 | * 102 | * @param string $key The key under which to store the value. 103 | * @param string $group The group value appended to the $key. 104 | * @param bool $force Optional. Whether to force an update of the local cache from the persistent 105 | * cache. Default false. 106 | * @param bool $found Optional. Whether the key was found in the cache. Disambiguates a return of false, 107 | * a storable value. Passed by reference. Default null. 108 | * 109 | * @return bool|mixed Cached object value. 110 | */ 111 | function wp_cache_get( $key, $group = '', $force = false, &$found = null ) { 112 | global $wp_object_cache; 113 | 114 | return $wp_object_cache->get( $key, $group, $force, $found ); 115 | } 116 | 117 | /** 118 | * Retrieves multiple values from the cache in one call. 119 | * 120 | * @param array $keys Array of keys under which the cache contents are stored. 121 | * @param string $group Optional. Where the cache contents are grouped. Default empty. 122 | * @param bool $force Optional. Whether to force an update of the local cache 123 | * from the persistent cache. Default false. 124 | * @return array Array of values organized into groups. 125 | */ 126 | function wp_cache_get_multiple( $keys, $group = '', $force = false ) { 127 | global $wp_object_cache; 128 | 129 | return $wp_object_cache->get_multiple( $keys, $group, $force ); 130 | } 131 | 132 | /** 133 | * Increment a numeric item's value. 134 | * 135 | * @param string $key The key under which to store the value. 136 | * @param int $offset The amount by which to increment the item's value. 137 | * @param string $group The group value appended to the $key. 138 | * 139 | * @return int|bool Returns item's new value on success or FALSE on failure. 140 | */ 141 | function wp_cache_incr( $key, $offset = 1, $group = '' ) { 142 | global $wp_object_cache; 143 | 144 | return $wp_object_cache->increment( $key, $offset, $group ); 145 | } 146 | 147 | /** 148 | * Sets up Object Cache Global and assigns it. 149 | * 150 | * @return void 151 | */ 152 | function wp_cache_init() { 153 | global $wp_object_cache; 154 | 155 | if ( ! defined( 'WP_REDIS_PREFIX' ) && getenv( 'WP_REDIS_PREFIX' ) ) { 156 | define( 'WP_REDIS_PREFIX', getenv( 'WP_REDIS_PREFIX' ) ); 157 | } 158 | 159 | if ( ! defined( 'WP_REDIS_SELECTIVE_FLUSH' ) && getenv( 'WP_REDIS_SELECTIVE_FLUSH' ) ) { 160 | define( 'WP_REDIS_SELECTIVE_FLUSH', (bool) getenv( 'WP_REDIS_SELECTIVE_FLUSH' ) ); 161 | } 162 | 163 | // Backwards compatibility: map `WP_CACHE_KEY_SALT` constant to `WP_REDIS_PREFIX`. 164 | if ( defined( 'WP_CACHE_KEY_SALT' ) && ! defined( 'WP_REDIS_PREFIX' ) ) { 165 | define( 'WP_REDIS_PREFIX', WP_CACHE_KEY_SALT ); 166 | } 167 | 168 | if ( ! ( $wp_object_cache instanceof WP_Object_Cache ) ) { 169 | $fail_gracefully = ! defined( 'WP_REDIS_GRACEFUL' ) || WP_REDIS_GRACEFUL; 170 | 171 | // We need to override this WordPress global in order to inject our cache. 172 | // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited 173 | $wp_object_cache = new WP_Object_Cache( $fail_gracefully ); 174 | } 175 | } 176 | 177 | /** 178 | * Replaces a value in cache. 179 | * 180 | * This method is similar to "add"; however, is does not successfully set a value if 181 | * the object's key is not already set in cache. 182 | * 183 | * @param string $key The key under which to store the value. 184 | * @param mixed $value The value to store. 185 | * @param string $group The group value appended to the $key. 186 | * @param int $expiration The expiration time, defaults to 0. 187 | * 188 | * @return bool Returns TRUE on success or FALSE on failure. 189 | */ 190 | function wp_cache_replace( $key, $value, $group = '', $expiration = 0 ) { 191 | global $wp_object_cache; 192 | 193 | return $wp_object_cache->replace( $key, $value, $group, $expiration ); 194 | } 195 | 196 | /** 197 | * Sets a value in cache. 198 | * 199 | * The value is set whether or not this key already exists in Redis. 200 | * 201 | * @param string $key The key under which to store the value. 202 | * @param mixed $value The value to store. 203 | * @param string $group The group value appended to the $key. 204 | * @param int $expiration The expiration time, defaults to 0. 205 | * 206 | * @return bool Returns TRUE on success or FALSE on failure. 207 | */ 208 | function wp_cache_set( $key, $value, $group = '', $expiration = 0 ) { 209 | global $wp_object_cache; 210 | 211 | return $wp_object_cache->set( $key, $value, $group, $expiration ); 212 | } 213 | 214 | /** 215 | * Switch the internal blog id. 216 | * 217 | * This changes the blog id used to create keys in blog specific groups. 218 | * 219 | * @param int $_blog_id The blog ID. 220 | * 221 | * @return bool 222 | */ 223 | function wp_cache_switch_to_blog( $_blog_id ) { 224 | global $wp_object_cache; 225 | 226 | return $wp_object_cache->switch_to_blog( $_blog_id ); 227 | } 228 | 229 | /** 230 | * Adds a group or set of groups to the list of Redis groups. 231 | * 232 | * @param string|array $groups A group or an array of groups to add. 233 | * 234 | * @return void 235 | */ 236 | function wp_cache_add_global_groups( $groups ) { 237 | global $wp_object_cache; 238 | 239 | $wp_object_cache->add_global_groups( $groups ); 240 | } 241 | 242 | /** 243 | * Adds a group or set of groups to the list of non-Redis groups. 244 | * 245 | * @param string|array $groups A group or an array of groups to add. 246 | * 247 | * @return void 248 | */ 249 | function wp_cache_add_non_persistent_groups( $groups ) { 250 | global $wp_object_cache; 251 | 252 | $wp_object_cache->add_non_persistent_groups( $groups ); 253 | } 254 | 255 | /** 256 | * Object cache class definition 257 | */ 258 | class WP_Object_Cache { 259 | /** 260 | * Operation pertains to internal cache, not Redis. 261 | * 262 | * @since 2.0.18 263 | * @var int 264 | */ 265 | const TRACE_FLAG_INTERNAL = 1 << 0; 266 | /** 267 | * Operation resulted in a cache hit. 268 | * 269 | * @since 2.0.18 270 | * @var int 271 | */ 272 | const TRACE_FLAG_HIT = 1 << 1; 273 | /** 274 | * Read operation. 275 | * 276 | * @since 2.0.18 277 | * @var int 278 | */ 279 | const TRACE_FLAG_READ = 1 << 2; 280 | /** 281 | * Write operation. 282 | * 283 | * @since 2.0.18 284 | * @var int 285 | */ 286 | const TRACE_FLAG_WRITE = 1 << 3; 287 | /** 288 | * Delete operation. 289 | * 290 | * @since 2.0.18 291 | * @var int 292 | */ 293 | const TRACE_FLAG_DEL = 1 << 4; 294 | /** 295 | * Operation bypassed internal cache. 296 | * 297 | * @since 2.0.18 298 | * @var int 299 | */ 300 | const TRACE_FLAG_REFRESH = 1 << 5; 301 | 302 | /** 303 | * The Redis client. 304 | * 305 | * @var mixed 306 | */ 307 | private $redis; 308 | 309 | /** 310 | * The Redis server version. 311 | * 312 | * @var null|string 313 | */ 314 | private $redis_version = null; 315 | 316 | /** 317 | * Track if Redis is available. 318 | * 319 | * @var bool 320 | */ 321 | private $redis_connected = false; 322 | 323 | /** 324 | * Check to fail gracefully or throw an exception. 325 | * 326 | * @var bool 327 | */ 328 | private $fail_gracefully = true; 329 | 330 | /** 331 | * Holds the non-Redis objects. 332 | * 333 | * @var array 334 | */ 335 | public $cache = []; 336 | 337 | /** 338 | * Holds the diagnostics values. 339 | * 340 | * @var array 341 | */ 342 | public $diagnostics = null; 343 | 344 | /** 345 | * Holds the error messages. 346 | * 347 | * @var array 348 | */ 349 | public $trace_enabled = false; 350 | 351 | /** 352 | * Holds the error messages. 353 | * 354 | * @var array 355 | */ 356 | public $errors = []; 357 | 358 | /** 359 | * List of global groups. 360 | * 361 | * @var array 362 | */ 363 | public $global_groups = [ 364 | 'blog-details', 365 | 'blog-id-cache', 366 | 'blog-lookup', 367 | 'global-posts', 368 | 'networks', 369 | 'rss', 370 | 'sites', 371 | 'site-details', 372 | 'site-lookup', 373 | 'site-options', 374 | 'site-transient', 375 | 'users', 376 | 'useremail', 377 | 'userlogins', 378 | 'usermeta', 379 | 'user_meta', 380 | 'userslugs', 381 | ]; 382 | 383 | /** 384 | * List of groups that will not be flushed. 385 | * 386 | * @var array 387 | */ 388 | public $unflushable_groups = []; 389 | 390 | /** 391 | * List of groups not saved to Redis. 392 | * 393 | * @var array 394 | */ 395 | public $ignored_groups = [ 396 | 'counts', 397 | 'plugins', 398 | 'themes', 399 | ]; 400 | 401 | /** 402 | * Prefix used for global groups. 403 | * 404 | * @var string 405 | */ 406 | public $global_prefix = ''; 407 | 408 | /** 409 | * Prefix used for non-global groups. 410 | * 411 | * @var string 412 | */ 413 | public $blog_prefix = ''; 414 | 415 | /** 416 | * Track how many requests were found in cache. 417 | * 418 | * @var int 419 | */ 420 | public $cache_hits = 0; 421 | 422 | /** 423 | * Track how may requests were not cached. 424 | * 425 | * @var int 426 | */ 427 | public $cache_misses = 0; 428 | 429 | /** 430 | * Track how long request took. 431 | * 432 | * @var float 433 | */ 434 | public $cache_time = 0; 435 | 436 | /** 437 | * Track how may calls were made. 438 | * 439 | * @var int 440 | */ 441 | public $cache_calls = 0; 442 | 443 | /** 444 | * Instantiate the Redis class. 445 | * 446 | * @param bool $fail_gracefully Handles and logs errors if true throws exceptions otherwise. 447 | */ 448 | public function __construct( $fail_gracefully = true ) { 449 | global $blog_id, $table_prefix; 450 | 451 | $this->fail_gracefully = $fail_gracefully; 452 | 453 | if ( defined( 'WP_REDIS_GLOBAL_GROUPS' ) && is_array( WP_REDIS_GLOBAL_GROUPS ) ) { 454 | $this->global_groups = array_map( [ $this, 'sanitize_key_part' ], WP_REDIS_GLOBAL_GROUPS ); 455 | } 456 | 457 | $this->global_groups[] = 'redis-cache'; 458 | 459 | if ( defined( 'WP_REDIS_IGNORED_GROUPS' ) && is_array( WP_REDIS_IGNORED_GROUPS ) ) { 460 | $this->ignored_groups = array_map( [ $this, 'sanitize_key_part' ], WP_REDIS_IGNORED_GROUPS ); 461 | } 462 | 463 | if ( defined( 'WP_REDIS_UNFLUSHABLE_GROUPS' ) && is_array( WP_REDIS_UNFLUSHABLE_GROUPS ) ) { 464 | $this->unflushable_groups = array_map( [ $this, 'sanitize_key_part' ], WP_REDIS_UNFLUSHABLE_GROUPS ); 465 | } 466 | 467 | if ( defined( 'WP_REDIS_TRACE' ) && WP_REDIS_TRACE ) { 468 | $this->trace_enabled = true; 469 | } 470 | 471 | $client = $this->determine_client(); 472 | $parameters = $this->build_parameters(); 473 | 474 | try { 475 | switch ( $client ) { 476 | case 'hhvm': 477 | $this->connect_using_hhvm( $parameters ); 478 | break; 479 | case 'phpredis': 480 | $this->connect_using_phpredis( $parameters ); 481 | break; 482 | case 'credis': 483 | $this->connect_using_credis( $parameters ); 484 | break; 485 | case 'predis': 486 | default: 487 | $this->connect_using_predis( $parameters ); 488 | break; 489 | } 490 | 491 | if ( defined( 'WP_REDIS_CLUSTER' ) ) { 492 | $this->diagnostics[ 'ping' ] = $this->redis->ping( current( array_values( WP_REDIS_CLUSTER ) ) ); 493 | } else { 494 | $this->diagnostics[ 'ping' ] = $this->redis->ping(); 495 | } 496 | 497 | $this->fetch_info(); 498 | 499 | $this->redis_connected = true; 500 | } catch ( Exception $exception ) { 501 | $this->handle_exception( $exception ); 502 | } 503 | 504 | // Assign global and blog prefixes for use with keys. 505 | if ( function_exists( 'is_multisite' ) ) { 506 | $this->global_prefix = is_multisite() ? '' : $table_prefix; 507 | $this->blog_prefix = is_multisite() ? $blog_id : $table_prefix; 508 | } 509 | } 510 | 511 | /** 512 | * Determine the Redis client. 513 | * 514 | * @return string 515 | */ 516 | protected function determine_client() { 517 | $client = 'predis'; 518 | 519 | if ( class_exists( 'Redis' ) ) { 520 | $client = defined( 'HHVM_VERSION' ) ? 'hhvm' : 'phpredis'; 521 | } 522 | 523 | if ( defined( 'WP_REDIS_CLIENT' ) ) { 524 | $client = (string) WP_REDIS_CLIENT; 525 | $client = str_replace( 'pecl', 'phpredis', $client ); 526 | } 527 | 528 | return trim( strtolower( $client ) ); 529 | } 530 | 531 | /** 532 | * Build the connection parameters from config constants. 533 | * 534 | * @return array 535 | */ 536 | protected function build_parameters() { 537 | $parameters = [ 538 | 'scheme' => 'tcp', 539 | 'host' => '127.0.0.1', 540 | 'port' => 6379, 541 | 'database' => 0, 542 | 'timeout' => 1, 543 | 'read_timeout' => 1, 544 | 'retry_interval' => null, 545 | ]; 546 | 547 | $settings = [ 548 | 'scheme', 549 | 'host', 550 | 'port', 551 | 'path', 552 | 'password', 553 | 'database', 554 | 'timeout', 555 | 'read_timeout', 556 | 'retry_interval', 557 | ]; 558 | 559 | foreach ( $settings as $setting ) { 560 | $constant = sprintf( 'WP_REDIS_%s', strtoupper( $setting ) ); 561 | 562 | if ( defined( $constant ) ) { 563 | $parameters[ $setting ] = constant( $constant ); 564 | } 565 | } 566 | 567 | if ( isset( $parameters[ 'password' ] ) && $parameters[ 'password' ] === '' ) { 568 | unset( $parameters[ 'password' ] ); 569 | } 570 | 571 | return $parameters; 572 | } 573 | 574 | /** 575 | * Connect to Redis using the PhpRedis (PECL) extention. 576 | * 577 | * @param array $parameters Connection parameters built by the `build_parameters` method. 578 | * @return void 579 | */ 580 | protected function connect_using_phpredis( $parameters ) { 581 | $version = phpversion( 'redis' ); 582 | 583 | $this->diagnostics[ 'client' ] = sprintf( 'PhpRedis (v%s)', $version ); 584 | 585 | if ( defined( 'WP_REDIS_SHARDS' ) ) { 586 | $this->redis = new RedisArray( array_values( WP_REDIS_SHARDS ) ); 587 | 588 | $this->diagnostics[ 'shards' ] = WP_REDIS_SHARDS; 589 | } elseif ( defined( 'WP_REDIS_CLUSTER' ) ) { 590 | $args = [ 591 | 'cluster' => array_values( WP_REDIS_CLUSTER ), 592 | 'timeout' => $parameters['timeout'], 593 | 'read_timeout' => $parameters['read_timeout'], 594 | ]; 595 | 596 | if ( isset( $parameters['password'] ) && version_compare( $version, '4.3.0', '>=' ) ) { 597 | $args['password'] = $parameters['password']; 598 | } 599 | 600 | $this->redis = new RedisCluster( null, ...array_values( $args ) ); 601 | 602 | $this->diagnostics += $args; 603 | } else { 604 | $this->redis = new Redis(); 605 | 606 | $args = [ 607 | 'host' => $parameters['host'], 608 | 'port' => $parameters['port'], 609 | 'timeout' => $parameters['timeout'], 610 | null, 611 | 'retry_interval' => $parameters['retry_interval'], 612 | ]; 613 | 614 | if ( strcasecmp( 'tls', $parameters['scheme'] ) === 0 ) { 615 | $args['host'] = sprintf( 616 | '%s://%s', 617 | $parameters['scheme'], 618 | str_replace( 'tls://', '', $parameters['host'] ) 619 | ); 620 | } 621 | 622 | if ( strcasecmp( 'unix', $parameters['scheme'] ) === 0 ) { 623 | $args['host'] = $parameters['path']; 624 | $args['port'] = null; 625 | } 626 | 627 | if ( version_compare( $version, '3.1.3', '>=' ) ) { 628 | $args['read_timeout'] = $parameters['read_timeout']; 629 | } 630 | 631 | call_user_func_array( [ $this->redis, 'connect' ], array_values( $args ) ); 632 | 633 | if ( isset( $parameters['password'] ) ) { 634 | $args['password'] = $parameters['password']; 635 | $this->redis->auth( $parameters['password'] ); 636 | } 637 | 638 | if ( isset( $parameters['database'] ) ) { 639 | if ( ctype_digit( $parameters['database'] ) ) { 640 | $parameters['database'] = (int) $parameters['database']; 641 | } 642 | 643 | $args['database'] = $parameters['database']; 644 | 645 | if ( $parameters['database'] ) { 646 | $this->redis->select( $parameters['database'] ); 647 | } 648 | } 649 | 650 | $this->diagnostics += $args; 651 | } 652 | 653 | if ( defined( 'WP_REDIS_SERIALIZER' ) && ! empty( WP_REDIS_SERIALIZER ) ) { 654 | $this->redis->setOption( Redis::OPT_SERIALIZER, WP_REDIS_SERIALIZER ); 655 | } 656 | } 657 | 658 | /** 659 | * Connect to Redis using the Predis library. 660 | * 661 | * @param array $parameters Connection parameters built by the `build_parameters` method. 662 | * @throws \Exception If the Predis library was not found or is unreadable. 663 | * @return void 664 | */ 665 | protected function connect_using_predis( $parameters ) { 666 | $client = 'Predis'; 667 | 668 | // Load bundled Predis library. 669 | if ( ! class_exists( 'Predis\Client' ) ) { 670 | $predis = sprintf( 671 | '%s/redis-cache/dependencies/predis/predis/autoload.php', 672 | defined( 'WP_PLUGIN_DIR' ) ? WP_PLUGIN_DIR : WP_CONTENT_DIR . '/plugins' 673 | ); 674 | 675 | if ( is_readable( $predis ) ) { 676 | require_once $predis; 677 | } else { 678 | throw new Exception( 679 | 'Predis library not found. Re-install Redis Cache plugin or delete the object-cache.php.' 680 | ); 681 | } 682 | } 683 | 684 | $servers = false; 685 | $options = []; 686 | 687 | if ( defined( 'WP_REDIS_SHARDS' ) ) { 688 | $servers = WP_REDIS_SHARDS; 689 | $parameters['shards'] = $servers; 690 | } elseif ( defined( 'WP_REDIS_SENTINEL' ) ) { 691 | $servers = WP_REDIS_SERVERS; 692 | $parameters['servers'] = $servers; 693 | $options['replication'] = 'sentinel'; 694 | $options['service'] = WP_REDIS_SENTINEL; 695 | } elseif ( defined( 'WP_REDIS_SERVERS' ) ) { 696 | $servers = WP_REDIS_SERVERS; 697 | $parameters['servers'] = $servers; 698 | $options['replication'] = true; 699 | } elseif ( defined( 'WP_REDIS_CLUSTER' ) ) { 700 | $servers = WP_REDIS_CLUSTER; 701 | $parameters['cluster'] = $servers; 702 | $options['cluster'] = 'redis'; 703 | } 704 | 705 | if ( isset( $parameters['read_timeout'] ) && $parameters['read_timeout'] ) { 706 | $parameters['read_write_timeout'] = $parameters['read_timeout']; 707 | } 708 | 709 | foreach ( [ 'WP_REDIS_SERVERS', 'WP_REDIS_SHARDS', 'WP_REDIS_CLUSTER' ] as $constant ) { 710 | if ( defined( $constant ) ) { 711 | if ( $parameters['database'] ) { 712 | $options['parameters']['database'] = $parameters['database']; 713 | } 714 | 715 | if ( isset( $parameters['password'] ) ) { 716 | $options['parameters']['password'] = WP_REDIS_PASSWORD; 717 | } 718 | } 719 | } 720 | 721 | $this->redis = new Predis\Client( $servers ?: $parameters, $options ); 722 | $this->redis->connect(); 723 | 724 | $this->diagnostics = array_merge( 725 | [ 'client' => sprintf( '%s (v%s)', $client, Predis\Client::VERSION ) ], 726 | $parameters, 727 | $options 728 | ); 729 | } 730 | 731 | /** 732 | * Connect to Redis using the Credis library. 733 | * 734 | * @param array $parameters Connection parameters built by the `build_parameters` method. 735 | * @throws \Exception If the Credis library was not found or is unreadable. 736 | * @throws \Exception If redis sharding should be configured as Credis does not support sharding. 737 | * @throws \Exception If more than one seninel is configured as Credis does not support multiple sentinel servers. 738 | * @return void 739 | */ 740 | protected function connect_using_credis( $parameters ) { 741 | $client = 'Credis'; 742 | 743 | $creds_path = sprintf( 744 | '%s/redis-cache/dependencies/colinmollenhour/credis/', 745 | defined( 'WP_PLUGIN_DIR' ) ? WP_PLUGIN_DIR : WP_CONTENT_DIR . '/plugins' 746 | ); 747 | 748 | $to_load = []; 749 | 750 | if ( ! class_exists( 'Credis_Client' ) ) { 751 | $to_load[] = 'Client.php'; 752 | } 753 | 754 | $has_shards = defined( 'WP_REDIS_SHARDS' ); 755 | $has_sentinel = defined( 'WP_REDIS_SENTINEL' ); 756 | $has_servers = defined( 'WP_REDIS_SERVERS' ); 757 | $has_cluster = defined( 'WP_REDIS_CLUSTER' ); 758 | 759 | if ( ( $has_shards || $has_sentinel || $has_servers || $has_cluster ) && ! class_exists( 'Credis_Cluster' ) ) { 760 | $to_load[] = 'Cluster.php'; 761 | 762 | if ( defined( 'WP_REDIS_SENTINEL' ) && ! class_exists( 'Credis_Sentinel' ) ) { 763 | $to_load[] = 'Sentinel.php'; 764 | } 765 | } 766 | 767 | foreach ( $to_load as $sub_path ) { 768 | $path = $creds_path . $sub_path; 769 | 770 | if ( file_exists( $path ) ) { 771 | require_once $path; 772 | } else { 773 | throw new Exception( 774 | 'Credis library not found. Re-install Redis Cache plugin or delete object-cache.php.' 775 | ); 776 | } 777 | } 778 | 779 | if ( defined( 'WP_REDIS_SHARDS' ) ) { 780 | throw new Exception( 781 | 'Sharding not supported by bundled Credis library. Please review your Redis Cache configuration.' 782 | ); 783 | } 784 | 785 | if ( defined( 'WP_REDIS_SENTINEL' ) ) { 786 | if ( is_array( WP_REDIS_SERVERS ) && count( WP_REDIS_SERVERS ) > 1 ) { 787 | throw new Exception( 788 | 'Multipe sentinel servers are not supported by the bundled Credis library. Please review your Redis Cache configuration.' 789 | ); 790 | } 791 | 792 | $connection_string = array_values( WP_REDIS_SERVERS )[0]; 793 | $sentinel = new Credis_Sentinel( new Credis_Client( $connection_string ) ); 794 | $this->redis = $sentinel->getCluster( WP_REDIS_SENTINEL ); 795 | $args['servers'] = WP_REDIS_SERVERS; 796 | } elseif ( defined( 'WP_REDIS_CLUSTER' ) || defined( 'WP_REDIS_SERVERS' ) ) { 797 | $parameters['db'] = $parameters['database']; 798 | 799 | $is_cluster = defined( 'WP_REDIS_CLUSTER' ); 800 | $clients = $is_cluster ? WP_REDIS_CLUSTER : WP_REDIS_SERVERS; 801 | 802 | foreach ( $clients as $index => $connection_string ) { 803 | // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url 804 | $url_components = parse_url( $connection_string ); 805 | 806 | parse_str( $url_components['query'], $add_params ); 807 | 808 | if ( ! $is_cluster && isset( $add_params['alias'] ) ) { 809 | $add_params['master'] = 'master' === $add_params['alias']; 810 | } 811 | 812 | $add_params['host'] = $url_components['host']; 813 | 814 | if ( ! isset( $add_params['alias'] ) ) { 815 | $add_params['alias'] = "redis-$index"; 816 | } 817 | 818 | $clients[ $index ] = array_merge( $parameters, $add_params ); 819 | } 820 | 821 | $this->redis = new Credis_Cluster( $clients ); 822 | 823 | foreach ( $clients as $index => $_client ) { 824 | $connection_string = "{$_client['scheme']}://{$_client['host']}:{$_client['port']}"; 825 | unset( $_client['scheme'], $_client['host'], $_client['port'] ); 826 | 827 | $params = array_filter( $_client ); 828 | 829 | if ( $params ) { 830 | $connection_string .= '?' . http_build_query( $params, null, '&' ); 831 | } 832 | 833 | $clients[ $index ] = $connection_string; 834 | } 835 | 836 | $args['servers'] = $clients; 837 | } else { 838 | $args = [ 839 | 'host' => $parameters['scheme'] === 'unix' ? $parameters['path'] : $parameters['host'], 840 | 'port' => $parameters['port'], 841 | 'timeout' => $parameters['timeout'], 842 | 'persistent' => null, 843 | 'database' => $parameters['database'], 844 | 'password' => isset( $parameters['password'] ) ? $parameters['password'] : null, 845 | ]; 846 | 847 | $this->redis = new Credis_Client( ...array_values( $args ) ); 848 | } 849 | 850 | // Don't use PhpRedis if it is available. 851 | $this->redis->forceStandalone(); 852 | 853 | $this->redis->connect(); 854 | 855 | if ( $parameters['read_timeout'] ) { 856 | $args['read_timeout'] = $parameters['read_timeout']; 857 | $this->redis->setReadTimeout( $parameters['read_timeout'] ); 858 | } 859 | 860 | $this->diagnostics = array_merge( 861 | [ 'client' => sprintf( '%s (v%s)', $client, Credis_Client::VERSION ) ], 862 | $args 863 | ); 864 | } 865 | 866 | /** 867 | * Connect to Redis using HHVM's Redis extention. 868 | * 869 | * @param array $parameters Connection parameters built by the `build_parameters` method. 870 | * @return void 871 | */ 872 | protected function connect_using_hhvm( $parameters ) { 873 | $this->redis = new Redis(); 874 | 875 | // Adjust host and port if the scheme is `unix`. 876 | if ( strcasecmp( 'unix', $parameters['scheme'] ) === 0 ) { 877 | $parameters['host'] = 'unix://' . $parameters['path']; 878 | $parameters['port'] = 0; 879 | } 880 | 881 | $this->redis->connect( 882 | $parameters['host'], 883 | $parameters['port'], 884 | $parameters['timeout'], 885 | null, 886 | $parameters['retry_interval'] 887 | ); 888 | 889 | if ( $parameters['read_timeout'] ) { 890 | $this->redis->setOption( Redis::OPT_READ_TIMEOUT, $parameters['read_timeout'] ); 891 | } 892 | 893 | if ( isset( $parameters['password'] ) ) { 894 | $this->redis->auth( $parameters['password'] ); 895 | } 896 | 897 | if ( isset( $parameters['database'] ) ) { 898 | if ( ctype_digit( $parameters['database'] ) ) { 899 | $parameters['database'] = (int) $parameters['database']; 900 | } 901 | 902 | if ( $parameters['database'] ) { 903 | $this->redis->select( $parameters['database'] ); 904 | } 905 | } 906 | 907 | $this->diagnostics = array_merge( 908 | [ 'client' => sprintf( 'HHVM Extension (v%s)', HHVM_VERSION ) ], 909 | $parameters 910 | ); 911 | } 912 | 913 | /** 914 | * Fetches Redis `INFO` mostly for server version. 915 | * 916 | * @return void 917 | */ 918 | public function fetch_info() { 919 | $options = method_exists( $this->redis, 'getOptions' ) 920 | ? $this->redis->getOptions() 921 | : new stdClass(); 922 | 923 | if ( isset( $options->replication ) && $options->replication ) { 924 | return; 925 | } 926 | 927 | if ( defined( 'WP_REDIS_CLUSTER' ) ) { 928 | $info = $this->redis->info( current( array_values( WP_REDIS_CLUSTER ) ) ); 929 | } else { 930 | $info = $this->redis->info(); 931 | } 932 | 933 | if ( isset( $info['redis_version'] ) ) { 934 | $this->redis_version = $info['redis_version']; 935 | } elseif ( isset( $info['Server']['redis_version'] ) ) { 936 | $this->redis_version = $info['Server']['redis_version']; 937 | } 938 | } 939 | 940 | /** 941 | * Is Redis available? 942 | * 943 | * @return bool 944 | */ 945 | public function redis_status() { 946 | return (bool) $this->redis_connected; 947 | } 948 | 949 | /** 950 | * Returns the Redis instance. 951 | * 952 | * @return mixed 953 | */ 954 | public function redis_instance() { 955 | return $this->redis; 956 | } 957 | 958 | /** 959 | * Returns the Redis server version. 960 | * 961 | * @return null|string 962 | */ 963 | public function redis_version() { 964 | return $this->redis_version; 965 | } 966 | 967 | /** 968 | * Adds a value to cache. 969 | * 970 | * If the specified key already exists, the value is not stored and the function 971 | * returns false. 972 | * 973 | * @param string $key The key under which to store the value. 974 | * @param mixed $value The value to store. 975 | * @param string $group The group value appended to the $key. 976 | * @param int $expiration The expiration time, defaults to 0. 977 | * @return bool Returns TRUE on success or FALSE on failure. 978 | */ 979 | public function add( $key, $value, $group = 'default', $expiration = 0 ) { 980 | return $this->add_or_replace( true, $key, $value, $group, $expiration ); 981 | } 982 | 983 | /** 984 | * Replace a value in the cache. 985 | * 986 | * If the specified key doesn't exist, the value is not stored and the function 987 | * returns false. 988 | * 989 | * @param string $key The key under which to store the value. 990 | * @param mixed $value The value to store. 991 | * @param string $group The group value appended to the $key. 992 | * @param int $expiration The expiration time, defaults to 0. 993 | * @return bool Returns TRUE on success or FALSE on failure. 994 | */ 995 | public function replace( $key, $value, $group = 'default', $expiration = 0 ) { 996 | return $this->add_or_replace( false, $key, $value, $group, $expiration ); 997 | } 998 | 999 | /** 1000 | * Add or replace a value in the cache. 1001 | * 1002 | * Add does not set the value if the key exists; replace does not replace if the value doesn't exist. 1003 | * 1004 | * @param bool $add True if should only add if value doesn't exist, false to only add when value already exists. 1005 | * @param string $key The key under which to store the value. 1006 | * @param mixed $value The value to store. 1007 | * @param string $group The group value appended to the $key. 1008 | * @param int $expiration The expiration time, defaults to 0. 1009 | * @return bool Returns TRUE on success or FALSE on failure. 1010 | */ 1011 | protected function add_or_replace( $add, $key, $value, $group = 'default', $expiration = 0 ) { 1012 | $cache_addition_suspended = function_exists( 'wp_suspend_cache_addition' ) 1013 | ? wp_suspend_cache_addition() 1014 | : false; 1015 | 1016 | if ( $add && $cache_addition_suspended ) { 1017 | return false; 1018 | } 1019 | 1020 | $result = true; 1021 | $derived_key = $this->build_key( $key, $group ); 1022 | 1023 | // Save if group not excluded and redis is up. 1024 | if ( ! $this->is_ignored_group( $group ) && $this->redis_status() ) { 1025 | try { 1026 | $orig_exp = $expiration; 1027 | $expiration = $this->validate_expiration( $expiration ); 1028 | 1029 | /** 1030 | * Filters the cache expiration time 1031 | * 1032 | * @since 1.4.2 1033 | * @param int $expiration The time in seconds the entry expires. 0 for no expiry. 1034 | * @param string $key The cache key. 1035 | * @param string $group The cache group. 1036 | * @param mixed $orig_exp The original expiration value before validation. 1037 | */ 1038 | $expiration = apply_filters( 'redis_cache_expiration', $expiration, $key, $group, $orig_exp ); 1039 | $start_time = microtime( true ); 1040 | 1041 | if ( $add ) { 1042 | $args = [ $derived_key, $this->maybe_serialize( $value ) ]; 1043 | 1044 | if ( $this->redis instanceof Predis\Client ) { 1045 | $args[] = 'nx'; 1046 | 1047 | if ( $expiration ) { 1048 | $args[] = 'ex'; 1049 | $args[] = $expiration; 1050 | } 1051 | } else { 1052 | if ( $expiration ) { 1053 | $args[] = [ 1054 | 'nx', 1055 | 'ex' => $expiration, 1056 | ]; 1057 | } else { 1058 | $args[] = [ 'nx' ]; 1059 | } 1060 | } 1061 | 1062 | $result = $this->parse_redis_response( 1063 | $this->redis->set( ...$args ) 1064 | ); 1065 | 1066 | if ( ! $result ) { 1067 | return false; 1068 | } 1069 | } elseif ( $expiration ) { 1070 | $result = $this->parse_redis_response( $this->redis->setex( $derived_key, $expiration, $this->maybe_serialize( $value ) ) ); 1071 | } else { 1072 | $result = $this->parse_redis_response( $this->redis->set( $derived_key, $this->maybe_serialize( $value ) ) ); 1073 | } 1074 | 1075 | $execute_time = microtime( true ) - $start_time; 1076 | 1077 | if ( $this->trace_enabled ) { 1078 | $this->trace_command( 'set', $group, [ 1079 | $key => [ 1080 | 'value' => $value, 1081 | 'status' => self::TRACE_FLAG_WRITE, 1082 | ], 1083 | ], microtime( true ) - $start_time ); 1084 | } 1085 | 1086 | $this->cache_calls++; 1087 | $this->cache_time += $execute_time; 1088 | } catch ( Exception $exception ) { 1089 | $this->handle_exception( $exception ); 1090 | 1091 | return false; 1092 | } 1093 | } 1094 | 1095 | $exists = isset( $this->cache[ $derived_key ] ); 1096 | 1097 | if ( (bool) $add === $exists ) { 1098 | return false; 1099 | } 1100 | 1101 | if ( $result ) { 1102 | $this->add_to_internal_cache( $derived_key, $value ); 1103 | } 1104 | 1105 | return $result; 1106 | } 1107 | 1108 | /** 1109 | * Remove the item from the cache. 1110 | * 1111 | * @param string $key The key under which to store the value. 1112 | * @param string $group The group value appended to the $key. 1113 | * @return bool Returns TRUE on success or FALSE on failure. 1114 | */ 1115 | public function delete( $key, $group = 'default' ) { 1116 | $result = false; 1117 | $derived_key = $this->build_key( $key, $group ); 1118 | 1119 | if ( isset( $this->cache[ $derived_key ] ) ) { 1120 | unset( $this->cache[ $derived_key ] ); 1121 | $result = true; 1122 | } 1123 | 1124 | $start_time = microtime( true ); 1125 | 1126 | if ( $this->redis_status() && ! $this->is_ignored_group( $group ) ) { 1127 | try { 1128 | $result = $this->parse_redis_response( $this->redis->del( $derived_key ) ); 1129 | } catch ( Exception $exception ) { 1130 | $this->handle_exception( $exception ); 1131 | 1132 | return false; 1133 | } 1134 | } 1135 | 1136 | $execute_time = microtime( true ) - $start_time; 1137 | 1138 | if ( $this->trace_enabled ) { 1139 | $this->trace_command( 'del', $group, [ 1140 | $key => [ 1141 | 'value' => null, 1142 | 'status' => self::TRACE_FLAG_DEL, 1143 | ], 1144 | ], $execute_time ); 1145 | } 1146 | 1147 | $this->cache_calls++; 1148 | $this->cache_time += $execute_time; 1149 | 1150 | if ( function_exists( 'do_action' ) ) { 1151 | /** 1152 | * Fires on every cache key deletion 1153 | * 1154 | * @since 1.3.3 1155 | * @param string $key The cache key. 1156 | * @param string $group The group value appended to the $key. 1157 | * @param float $execute_time Execution time for the request in seconds. 1158 | */ 1159 | do_action( 'redis_object_cache_delete', $key, $group, $execute_time ); 1160 | } 1161 | 1162 | return (bool) $result; 1163 | } 1164 | 1165 | /** 1166 | * Invalidate all items in the cache. If `WP_REDIS_SELECTIVE_FLUSH` is `true`, 1167 | * only keys prefixed with the `WP_REDIS_PREFIX` are flushed. 1168 | * 1169 | * @param int $delay Number of seconds to wait before invalidating the items. 1170 | * @return bool Returns TRUE on success or FALSE on failure. 1171 | */ 1172 | public function flush( $delay = 0 ) { 1173 | $delay = abs( (int) $delay ); 1174 | 1175 | if ( $delay ) { 1176 | sleep( $delay ); 1177 | } 1178 | 1179 | $results = []; 1180 | $this->cache = []; 1181 | 1182 | if ( $this->redis_status() ) { 1183 | $salt = defined( 'WP_REDIS_PREFIX' ) ? trim( WP_REDIS_PREFIX ) : null; 1184 | $selective = defined( 'WP_REDIS_SELECTIVE_FLUSH' ) ? WP_REDIS_SELECTIVE_FLUSH : null; 1185 | 1186 | $start_time = microtime( true ); 1187 | 1188 | if ( $salt && $selective ) { 1189 | $script = $this->get_flush_closure( $salt ); 1190 | 1191 | if ( defined( 'WP_REDIS_CLUSTER' ) ) { 1192 | try { 1193 | foreach ( $this->redis->_masters() as $master ) { 1194 | $redis = new Redis(); 1195 | $redis->connect( $master[0], $master[1] ); 1196 | $results[] = $this->parse_redis_response( $script() ); 1197 | unset( $redis ); 1198 | } 1199 | } catch ( Exception $exception ) { 1200 | $this->handle_exception( $exception ); 1201 | 1202 | return false; 1203 | } 1204 | } else { 1205 | try { 1206 | $results[] = $this->parse_redis_response( $script() ); 1207 | } catch ( Exception $exception ) { 1208 | $this->handle_exception( $exception ); 1209 | 1210 | return false; 1211 | } 1212 | } 1213 | } else { 1214 | if ( defined( 'WP_REDIS_CLUSTER' ) ) { 1215 | try { 1216 | foreach ( $this->redis->_masters() as $master ) { 1217 | $results[] = $this->parse_redis_response( $this->redis->flushdb( $master ) ); 1218 | } 1219 | } catch ( Exception $exception ) { 1220 | $this->handle_exception( $exception ); 1221 | 1222 | return false; 1223 | } 1224 | } else { 1225 | try { 1226 | $results[] = $this->parse_redis_response( $this->redis->flushdb() ); 1227 | } catch ( Exception $exception ) { 1228 | $this->handle_exception( $exception ); 1229 | 1230 | return false; 1231 | } 1232 | } 1233 | } 1234 | 1235 | if ( function_exists( 'do_action' ) ) { 1236 | $execute_time = microtime( true ) - $start_time; 1237 | 1238 | /** 1239 | * Fires on every cache flush 1240 | * 1241 | * @since 1.3.5 1242 | * @param null|array $results Array of flush results. 1243 | * @param int $delay Given number of seconds to waited before invalidating the items. 1244 | * @param bool $seletive Whether a selective flush took place. 1245 | * @param string $salt The defined key prefix. 1246 | * @param float $execute_time Execution time for the request in seconds. 1247 | */ 1248 | do_action( 'redis_object_cache_flush', $results, $delay, $selective, $salt, $execute_time ); 1249 | } 1250 | } 1251 | 1252 | if ( empty( $results ) ) { 1253 | return false; 1254 | } 1255 | 1256 | foreach ( $results as $result ) { 1257 | if ( ! $result ) { 1258 | return false; 1259 | } 1260 | } 1261 | 1262 | return true; 1263 | } 1264 | 1265 | /** 1266 | * Returns a closure to flush selectively. 1267 | * 1268 | * @param string $salt The salt to be used to differentiate. 1269 | * @return callable Generated callable executing the lua script. 1270 | */ 1271 | protected function get_flush_closure( $salt ) { 1272 | if ( $this->unflushable_groups ) { 1273 | return $this->lua_flush_extended_closure( $salt ); 1274 | } else { 1275 | return $this->lua_flush_closure( $salt ); 1276 | } 1277 | } 1278 | 1279 | /** 1280 | * Quotes a string for usage in the `glob` function 1281 | * 1282 | * @param string $string The string to quote. 1283 | * @return string 1284 | */ 1285 | protected function glob_quote( $string ) { 1286 | $characters = [ '*', '+', '?', '!', '{', '}', '[', ']', '(', ')', '|', '@' ]; 1287 | 1288 | return str_replace( 1289 | $characters, 1290 | array_map( 1291 | function ( $character ) { 1292 | return "[{$character}]"; 1293 | }, 1294 | $characters 1295 | ), 1296 | $string 1297 | ); 1298 | } 1299 | 1300 | /** 1301 | * Returns a closure ready to be called to flush selectively ignoring unflushable groups. 1302 | * 1303 | * @param string $salt The salt to be used to differentiate. 1304 | * @return callable Generated callable executing the lua script. 1305 | */ 1306 | protected function lua_flush_closure( $salt ) { 1307 | $salt = $this->glob_quote( $salt ); 1308 | 1309 | return function () use ( $salt ) { 1310 | $script = <<redis_version(), '5', '<' ) && version_compare( $this->redis_version(), '3.2', '>=' ) ) { 1328 | $script = 'redis.replicate_commands()' . "\n" . $script; 1329 | } 1330 | 1331 | $args = ( $this->redis instanceof Predis\Client ) 1332 | ? [ $script, 0 ] 1333 | : [ $script ]; 1334 | 1335 | return call_user_func_array( [ $this->redis, 'eval' ], $args ); 1336 | }; 1337 | } 1338 | 1339 | /** 1340 | * Returns a closure ready to be called to flush selectively. 1341 | * 1342 | * @param string $salt The salt to be used to differentiate. 1343 | * @return callable Generated callable executing the lua script. 1344 | */ 1345 | protected function lua_flush_extended_closure( $salt ) { 1346 | $salt = $this->glob_quote( $salt ); 1347 | 1348 | return function () use ( $salt ) { 1349 | $salt_length = strlen( $salt ); 1350 | 1351 | $unflushable = array_map( 1352 | function ( $group ) { 1353 | return ":{$group}:"; 1354 | }, 1355 | $this->unflushable_groups 1356 | ); 1357 | 1358 | $script = <<redis_version(), '5', '<' ) && version_compare( $this->redis_version(), '3.2', '>=' ) ) { 1382 | $script = 'redis.replicate_commands()' . "\n" . $script; 1383 | } 1384 | 1385 | $args = ( $this->redis instanceof Predis\Client ) 1386 | ? array_merge( [ $script, count( $unflushable ) ], $unflushable ) 1387 | : [ $script, $unflushable, count( $unflushable ) ]; 1388 | 1389 | return call_user_func_array( [ $this->redis, 'eval' ], $args ); 1390 | }; 1391 | } 1392 | 1393 | /** 1394 | * Retrieve object from cache. 1395 | * 1396 | * Gets an object from cache based on $key and $group. 1397 | * 1398 | * @param string $key The key under which to store the value. 1399 | * @param string $group The group value appended to the $key. 1400 | * @param bool $force Optional. Whether to force a refetch rather than relying on the local 1401 | * cache. Default false. 1402 | * @param bool $found Optional. Whether the key was found in the cache. Disambiguates a return of 1403 | * false, a storable value. Passed by reference. Default null. 1404 | * @return bool|mixed Cached object value. 1405 | */ 1406 | public function get( $key, $group = 'default', $force = false, &$found = null ) { 1407 | $trace_flags = self::TRACE_FLAG_READ; 1408 | 1409 | if ( $force ) { 1410 | $trace_flags |= self::TRACE_FLAG_REFRESH; 1411 | } 1412 | 1413 | $start_time = microtime( true ); 1414 | $derived_key = $this->build_key( $key, $group ); 1415 | 1416 | if ( isset( $this->cache[ $derived_key ] ) && ! $force ) { 1417 | $found = true; 1418 | $this->cache_hits++; 1419 | $value = $this->get_from_internal_cache( $derived_key ); 1420 | 1421 | if ( $this->trace_enabled ) { 1422 | $this->trace_command( 'get', $group, [ 1423 | $key => [ 1424 | 'value' => $value, 1425 | 'status' => $trace_flags | self::TRACE_FLAG_HIT | self::TRACE_FLAG_INTERNAL, 1426 | ], 1427 | ], microtime( true ) - $start_time); 1428 | } 1429 | 1430 | return $value; 1431 | } elseif ( $this->is_ignored_group( $group ) || ! $this->redis_status() ) { 1432 | $found = false; 1433 | $this->cache_misses++; 1434 | 1435 | if ( $this->trace_enabled ) { 1436 | $this->trace_command( 'get', $group, [ 1437 | $key => [ 1438 | 'value' => null, 1439 | 'status' => $trace_flags | self::TRACE_FLAG_INTERNAL, 1440 | ], 1441 | ], microtime( true ) - $start_time ); 1442 | } 1443 | 1444 | return false; 1445 | } 1446 | 1447 | 1448 | try { 1449 | $result = $this->redis->get( $derived_key ); 1450 | } catch ( Exception $exception ) { 1451 | $this->handle_exception( $exception ); 1452 | 1453 | return false; 1454 | } 1455 | 1456 | $execute_time = microtime( true ) - $start_time; 1457 | 1458 | $this->cache_calls++; 1459 | $this->cache_time += $execute_time; 1460 | 1461 | if ( $result === null || $result === false ) { 1462 | $found = false; 1463 | $this->cache_misses++; 1464 | 1465 | if ( $this->trace_enabled ) { 1466 | $this->trace_command( 'get', $group, [ 1467 | $key => [ 1468 | 'value' => null, 1469 | 'status' => $trace_flags, 1470 | ], 1471 | ], microtime( true ) - $start_time ); 1472 | } 1473 | 1474 | return false; 1475 | } else { 1476 | $found = true; 1477 | $this->cache_hits++; 1478 | $value = $this->maybe_unserialize( $result ); 1479 | } 1480 | 1481 | $this->add_to_internal_cache( $derived_key, $value ); 1482 | 1483 | if ( $this->trace_enabled ) { 1484 | $this->trace_command( 'get', $group, [ 1485 | $key => [ 1486 | 'value' => $value, 1487 | 'status' => $trace_flags | self::TRACE_FLAG_HIT, 1488 | ], 1489 | ], microtime( true ) - $start_time ); 1490 | } 1491 | 1492 | if ( function_exists( 'do_action' ) ) { 1493 | /** 1494 | * Fires on every cache get request 1495 | * 1496 | * @since 1.2.2 1497 | * @param mixed $value Value of the cache entry. 1498 | * @param string $key The cache key. 1499 | * @param string $group The group value appended to the $key. 1500 | * @param bool $force Whether a forced refetch has taken place rather than relying on the local cache. 1501 | * @param bool $found Whether the key was found in the cache. 1502 | * @param float $execute_time Execution time for the request in seconds. 1503 | */ 1504 | do_action( 'redis_object_cache_get', $key, $value, $group, $force, $found, $execute_time ); 1505 | } 1506 | 1507 | if ( function_exists( 'apply_filters' ) && function_exists( 'has_filter' ) ) { 1508 | if ( has_filter( 'redis_object_cache_get_value' ) ) { 1509 | /** 1510 | * Filters the return value 1511 | * 1512 | * @since 1.4.2 1513 | * @param mixed $value Value of the cache entry. 1514 | * @param string $key The cache key. 1515 | * @param string $group The group value appended to the $key. 1516 | * @param bool $force Whether a forced refetch has taken place rather than relying on the local cache. 1517 | * @param bool $found Whether the key was found in the cache. 1518 | */ 1519 | return apply_filters( 'redis_object_cache_get_value', $value, $key, $group, $force, $found ); 1520 | } 1521 | } 1522 | 1523 | return $value; 1524 | } 1525 | 1526 | /** 1527 | * Retrieves multiple values from the cache in one call. 1528 | * 1529 | * @param array $keys Array of keys under which the cache contents are stored. 1530 | * @param string $group Optional. Where the cache contents are grouped. Default empty. 1531 | * @param bool $force Optional. Whether to force an update of the local cache 1532 | * from the persistent cache. Default false. 1533 | * @return array Array of values organized into groups. 1534 | */ 1535 | public function get_multiple( $keys, $group = 'default', $force = false ) { 1536 | if ( ! is_array( $keys ) ) { 1537 | return false; 1538 | } 1539 | 1540 | $trace_flags = self::TRACE_FLAG_READ; 1541 | 1542 | if ( $force ) { 1543 | $trace_flags |= self::TRACE_FLAG_REFRESH; 1544 | } 1545 | 1546 | $cache = []; 1547 | $derived_keys = []; 1548 | $start_time = microtime( true ); 1549 | 1550 | foreach ( $keys as $key ) { 1551 | $derived_keys[ $key ] = $this->build_key( $key, $group ); 1552 | } 1553 | 1554 | if ( $this->is_ignored_group( $group ) || ! $this->redis_status() ) { 1555 | $traceKV = []; 1556 | 1557 | foreach ( $keys as $key ) { 1558 | $value = $this->get_from_internal_cache( $derived_keys[ $key ] ); 1559 | $cache[ $key ] = $value; 1560 | 1561 | if ($value === false) { 1562 | $this->cache_misses++; 1563 | 1564 | if ( $this->trace_enabled ) { 1565 | $traceKV[ $key ] = [ 1566 | 'value' => null, 1567 | 'status' => $trace_flags | self::TRACE_FLAG_INTERNAL, 1568 | ]; 1569 | } 1570 | } else { 1571 | $this->cache_hits++; 1572 | 1573 | if ( $this->trace_enabled ) { 1574 | $traceKV[ $key ] = [ 1575 | 'value' => $value, 1576 | 'status' => $trace_flags | self::TRACE_FLAG_HIT | self::TRACE_FLAG_INTERNAL, 1577 | ]; 1578 | } 1579 | } 1580 | } 1581 | 1582 | $this->trace_command( 'mget', $group, $traceKV, microtime( true ) - $start_time ); 1583 | 1584 | return $cache; 1585 | } 1586 | 1587 | $traceKV = []; 1588 | 1589 | if ( ! $force ) { 1590 | foreach ( $keys as $key ) { 1591 | $value = $this->get_from_internal_cache( $derived_keys[ $key ] ); 1592 | 1593 | if ( $value === false ) { 1594 | $this->cache_misses++; 1595 | 1596 | if ( $this->trace_enabled ) { 1597 | $traceKV[ $key ] = [ 1598 | 'value' => null, 1599 | 'status' => $trace_flags | self::TRACE_FLAG_INTERNAL, 1600 | ]; 1601 | } 1602 | } else { 1603 | $cache[ $key ] = $value; 1604 | $this->cache_hits++; 1605 | 1606 | if ( $this->trace_enabled ) { 1607 | $traceKV[ $key ] = [ 1608 | 'value' => $value, 1609 | 'status' => $trace_flags | self::TRACE_FLAG_HIT | self::TRACE_FLAG_INTERNAL, 1610 | ]; 1611 | } 1612 | } 1613 | } 1614 | } 1615 | 1616 | $remaining_keys = array_filter( 1617 | $keys, 1618 | function ( $key ) use ( $cache ) { 1619 | return ! isset( $cache[ $key ] ); 1620 | } 1621 | ); 1622 | 1623 | if ( empty( $remaining_keys ) ) { 1624 | $this->trace_enabled 1625 | && $this->trace_command( 'mget', $group, $traceKV, microtime( true ) - $start_time ); 1626 | 1627 | return $cache; 1628 | } 1629 | 1630 | $start_time = microtime( true ); 1631 | 1632 | try { 1633 | $remaining_ids = array_map( 1634 | function ( $key ) use ( $derived_keys ) { 1635 | return $derived_keys[ $key ]; 1636 | }, 1637 | $remaining_keys 1638 | ); 1639 | 1640 | $results = array_combine( 1641 | $remaining_keys, 1642 | $this->redis->mget( $remaining_ids ) 1643 | ?: array_fill( 0, count( $remaining_ids ), false ) 1644 | ); 1645 | } catch ( Exception $exception ) { 1646 | $this->handle_exception( $exception ); 1647 | 1648 | $cache = array_fill( 0, count( $derived_keys ) - 1, false ); 1649 | } 1650 | 1651 | $execute_time = microtime( true ) - $start_time; 1652 | 1653 | $this->cache_calls++; 1654 | $this->cache_time += $execute_time; 1655 | 1656 | foreach ( $results as $key => $value ) { 1657 | if ( $value === null || $value === false ) { 1658 | $cache[ $key ] = false; 1659 | $this->cache_misses++; 1660 | 1661 | if ( $this->trace_enabled ) { 1662 | $traceKV[ $key ] = [ 1663 | 'value' => null, 1664 | 'status' => $trace_flags, 1665 | ]; 1666 | } 1667 | } else { 1668 | $cache[ $key ] = $this->maybe_unserialize( $value ); 1669 | $this->add_to_internal_cache( $derived_keys[ $key ], $cache[ $key ] ); 1670 | $this->cache_hits++; 1671 | 1672 | if ( $this->trace_enabled ) { 1673 | $traceKV[ $key ] = [ 1674 | 'value' => $value, 1675 | 'status' => $trace_flags | self::TRACE_FLAG_HIT, 1676 | ]; 1677 | } 1678 | } 1679 | } 1680 | 1681 | $this->trace_enabled 1682 | && $this->trace_command( 'mget', $group, $traceKV, $execute_time ); 1683 | 1684 | if ( function_exists( 'do_action' ) ) { 1685 | /** 1686 | * Fires on every cache get multiple request 1687 | * 1688 | * @since 2.0.6 1689 | * @param mixed $value Value of the cache entry. 1690 | * @param string $key The cache key. 1691 | * @param string $group The group value appended to the $key. 1692 | * @param bool $force Whether a forced refetch has taken place rather than relying on the local cache. 1693 | * @param float $execute_time Execution time for the request in seconds. 1694 | */ 1695 | do_action( 'redis_object_cache_get_multiple', $keys, $cache, $group, $force, $execute_time ); 1696 | } 1697 | 1698 | if ( function_exists( 'apply_filters' ) && function_exists( 'has_filter' ) ) { 1699 | if ( has_filter( 'redis_object_cache_get_value' ) ) { 1700 | foreach ( $cache as $key => $value ) { 1701 | /** 1702 | * Filters the return value 1703 | * 1704 | * @since 1.4.2 1705 | * @param mixed $value Value of the cache entry. 1706 | * @param string $key The cache key. 1707 | * @param string $group The group value appended to the $key. 1708 | * @param bool $force Whether a forced refetch has taken place rather than relying on the local cache. 1709 | */ 1710 | $cache[ $key ] = apply_filters( 'redis_object_cache_get_value', $value, $key, $group, $force ); 1711 | } 1712 | } 1713 | } 1714 | 1715 | return $cache; 1716 | } 1717 | 1718 | /** 1719 | * Sets a value in cache. 1720 | * 1721 | * The value is set whether or not this key already exists in Redis. 1722 | * 1723 | * @param string $key The key under which to store the value. 1724 | * @param mixed $value The value to store. 1725 | * @param string $group The group value appended to the $key. 1726 | * @param int $expiration The expiration time, defaults to 0. 1727 | * @return bool Returns TRUE on success or FALSE on failure. 1728 | */ 1729 | public function set( $key, $value, $group = 'default', $expiration = 0 ) { 1730 | $result = true; 1731 | $start_time = microtime( true ); 1732 | $derived_key = $this->build_key( $key, $group ); 1733 | 1734 | // Save if group not excluded from redis and redis is up. 1735 | if ( ! $this->is_ignored_group( $group ) && $this->redis_status() ) { 1736 | $orig_exp = $expiration; 1737 | $expiration = $this->validate_expiration( $expiration ); 1738 | 1739 | /** 1740 | * Filters the cache expiration time 1741 | * 1742 | * @since 1.4.2 1743 | * @param int $expiration The time in seconds the entry expires. 0 for no expiry. 1744 | * @param string $key The cache key. 1745 | * @param string $group The cache group. 1746 | * @param mixed $orig_exp The original expiration value before validation. 1747 | */ 1748 | $expiration = apply_filters( 'redis_cache_expiration', $expiration, $key, $group, $orig_exp ); 1749 | 1750 | try { 1751 | if ( $expiration ) { 1752 | $result = $this->parse_redis_response( $this->redis->setex( $derived_key, $expiration, $this->maybe_serialize( $value ) ) ); 1753 | } else { 1754 | $result = $this->parse_redis_response( $this->redis->set( $derived_key, $this->maybe_serialize( $value ) ) ); 1755 | } 1756 | } catch ( Exception $exception ) { 1757 | $this->handle_exception( $exception ); 1758 | 1759 | return false; 1760 | } 1761 | 1762 | $execute_time = microtime( true ) - $start_time; 1763 | $this->cache_calls++; 1764 | $this->cache_time += $execute_time; 1765 | 1766 | if ( $this->trace_enabled ) { 1767 | $this->trace_command( 'set', $group, [ 1768 | $key => [ 1769 | 'value' => null, 1770 | 'status' => self::TRACE_FLAG_WRITE, 1771 | ], 1772 | ], $execute_time ); 1773 | } 1774 | } 1775 | 1776 | // If the set was successful, or we didn't go to redis. 1777 | if ( $result ) { 1778 | $this->add_to_internal_cache( $derived_key, $value ); 1779 | } 1780 | 1781 | if ( function_exists( 'do_action' ) ) { 1782 | $execute_time = microtime( true ) - $start_time; 1783 | 1784 | /** 1785 | * Fires on every cache set 1786 | * 1787 | * @since 1.2.2 1788 | * @param string $key The cache key. 1789 | * @param mixed $value Value of the cache entry. 1790 | * @param string $group The group value appended to the $key. 1791 | * @param int $expiration The time in seconds the entry expires. 0 for no expiry. 1792 | * @param float $execute_time Execution time for the request in seconds. 1793 | */ 1794 | do_action( 'redis_object_cache_set', $key, $value, $group, $expiration, $execute_time ); 1795 | } 1796 | 1797 | return $result; 1798 | } 1799 | 1800 | /** 1801 | * Increment a Redis counter by the amount specified 1802 | * 1803 | * @param string $key The key name. 1804 | * @param int $offset Optional. The increment. Defaults to 1. 1805 | * @param string $group Optional. The key group. Default is 'default'. 1806 | * @return int|bool 1807 | */ 1808 | public function increment( $key, $offset = 1, $group = 'default' ) { 1809 | $offset = (int) $offset; 1810 | $start_time = microtime( true ); 1811 | $derived_key = $this->build_key( $key, $group ); 1812 | $trace_flags = self::TRACE_FLAG_READ | self::TRACE_FLAG_WRITE; 1813 | 1814 | // If group is a non-Redis group, save to internal cache, not Redis. 1815 | if ( $this->is_ignored_group( $group ) || ! $this->redis_status() ) { 1816 | $value = $this->get_from_internal_cache( $derived_key ); 1817 | $value += $offset; 1818 | $this->add_to_internal_cache( $derived_key, $value ); 1819 | 1820 | if ( $this->trace_enabled ) { 1821 | $this->trace_command( 'incr', $group, [ 1822 | $key => [ 1823 | 'value' => $value, 1824 | 'status' => $trace_flags | self::TRACE_FLAG_INTERNAL, 1825 | ], 1826 | ], microtime( true ) - $start_time ); 1827 | } 1828 | 1829 | return $value; 1830 | } 1831 | 1832 | try { 1833 | $result = $this->parse_redis_response( $this->redis->incrBy( $derived_key, $offset ) ); 1834 | 1835 | $this->add_to_internal_cache( $derived_key, (int) $this->redis->get( $derived_key ) ); 1836 | } catch ( Exception $exception ) { 1837 | $this->handle_exception( $exception ); 1838 | 1839 | return false; 1840 | } 1841 | 1842 | $execute_time = microtime( true ) - $start_time; 1843 | 1844 | if ( $this->trace_enabled ) { 1845 | $this->trace_command( 'incr', $group, [ 1846 | $key => [ 1847 | 'value' => $result, 1848 | 'status' => $trace_flags, 1849 | ], 1850 | ], $execute_time ); 1851 | } 1852 | 1853 | $this->cache_calls += 2; 1854 | $this->cache_time += $execute_time; 1855 | 1856 | return $result; 1857 | } 1858 | 1859 | /** 1860 | * Alias of `increment()`. 1861 | * 1862 | * @see self::increment() 1863 | * @param string $key The key name. 1864 | * @param int $offset Optional. The increment. Defaults to 1. 1865 | * @param string $group Optional. The key group. Default is 'default'. 1866 | * @return int|bool 1867 | */ 1868 | public function incr( $key, $offset = 1, $group = 'default' ) { 1869 | return $this->increment( $key, $offset, $group ); 1870 | } 1871 | 1872 | /** 1873 | * Decrement a Redis counter by the amount specified 1874 | * 1875 | * @param string $key The key name. 1876 | * @param int $offset Optional. The decrement. Defaults to 1. 1877 | * @param string $group Optional. The key group. Default is 'default'. 1878 | * @return int|bool 1879 | */ 1880 | public function decrement( $key, $offset = 1, $group = 'default' ) { 1881 | $offset = (int) $offset; 1882 | $start_time = microtime( true ); 1883 | $derived_key = $this->build_key( $key, $group ); 1884 | $trace_flags = self::TRACE_FLAG_READ | self::TRACE_FLAG_WRITE; 1885 | 1886 | // If group is a non-Redis group, save to internal cache, not Redis. 1887 | if ( $this->is_ignored_group( $group ) || ! $this->redis_status() ) { 1888 | $value = $this->get_from_internal_cache( $derived_key ); 1889 | $value -= $offset; 1890 | $this->add_to_internal_cache( $derived_key, $value ); 1891 | 1892 | if ( $this->trace_enabled ) { 1893 | $this->trace_command( 'decr', $group, [ 1894 | $key => [ 1895 | 'value' => $value, 1896 | 'status' => $trace_flags | self::TRACE_FLAG_INTERNAL, 1897 | ], 1898 | ], microtime( true ) - $start_time ); 1899 | } 1900 | 1901 | return $value; 1902 | } 1903 | 1904 | 1905 | try { 1906 | // Save to Redis. 1907 | $result = $this->parse_redis_response( $this->redis->decrBy( $derived_key, $offset ) ); 1908 | 1909 | $this->add_to_internal_cache( $derived_key, (int) $this->redis->get( $derived_key ) ); 1910 | } catch ( Exception $exception ) { 1911 | $this->handle_exception( $exception ); 1912 | 1913 | return false; 1914 | } 1915 | 1916 | $execute_time = microtime( true ) - $start_time; 1917 | 1918 | if ( $this->trace_enabled ) { 1919 | $this->trace_command( 'decr', $group, [ 1920 | $key => [ 1921 | 'value' => $result, 1922 | 'status' => $trace_flags, 1923 | ], 1924 | ], $execute_time ); 1925 | } 1926 | 1927 | $this->cache_calls += 2; 1928 | $this->cache_time += $execute_time; 1929 | 1930 | return $result; 1931 | } 1932 | 1933 | /** 1934 | * Render data about current cache requests 1935 | * Used by the Debug bar plugin 1936 | * 1937 | * @return void 1938 | */ 1939 | public function stats() { 1940 | ?> 1941 |

1942 | Redis Status: 1943 | redis_status() ? 'Connected' : 'Not connected'; ?> 1944 |
1945 | Redis Client: 1946 | diagnostics['client'] ?: 'Unknown'; ?> 1947 |
1948 | Cache Hits: 1949 | cache_hits; ?> 1950 |
1951 | Cache Misses: 1952 | cache_misses; ?> 1953 |
1954 | Cache Size: 1955 | cache ) ) / 1024, 2 ); ?> kB 1956 |

1957 | cache_hits + $this->cache_misses; 1967 | 1968 | $bytes = array_map( 1969 | function ( $keys ) { 1970 | // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize 1971 | return strlen( serialize( $keys ) ); 1972 | }, 1973 | $this->cache 1974 | ); 1975 | 1976 | return (object) [ 1977 | // Connected, Disabled, Unknown, Not connected 1978 | // 'status' => '...', 1979 | 'hits' => $this->cache_hits, 1980 | 'misses' => $this->cache_misses, 1981 | 'ratio' => $total > 0 ? round( $this->cache_hits / ( $total / 100 ), 1 ) : 100, 1982 | 'bytes' => array_sum( $bytes ), 1983 | 'time' => $this->cache_time, 1984 | 'calls' => $this->cache_calls, 1985 | 'groups' => (object) [ 1986 | 'global' => $this->global_groups, 1987 | 'non_persistent' => $this->ignored_groups, 1988 | 'unflushable' => $this->unflushable_groups, 1989 | ], 1990 | 'errors' => empty( $this->errors ) ? null : $this->errors, 1991 | 'meta' => [ 1992 | 'Client' => $this->diagnostics['client'] ?: 'Unknown', 1993 | 'Redis Version' => $this->redis_version, 1994 | ], 1995 | ]; 1996 | } 1997 | 1998 | /** 1999 | * Builds a key for the cached object using the prefix, group and key. 2000 | * 2001 | * @param string $key The key under which to store the value. 2002 | * @param string $group The group value appended to the $key. 2003 | * 2004 | * @return string 2005 | */ 2006 | public function build_key( $key, $group = 'default' ) { 2007 | if ( empty( $group ) ) { 2008 | $group = 'default'; 2009 | } 2010 | 2011 | $salt = defined( 'WP_REDIS_PREFIX' ) ? trim( WP_REDIS_PREFIX ) : ''; 2012 | $prefix = $this->is_global_group( $group ) ? $this->global_prefix : $this->blog_prefix; 2013 | 2014 | $key = $this->sanitize_key_part( $key ); 2015 | $group = $this->sanitize_key_part( $group ); 2016 | 2017 | $prefix = trim( $prefix, '_-:$' ); 2018 | 2019 | return "{$salt}{$prefix}:{$group}:{$key}"; 2020 | } 2021 | 2022 | /** 2023 | * Replaces the set group separator by another one 2024 | * 2025 | * @param string $part The string to sanitize. 2026 | * @return string Sanitized string. 2027 | */ 2028 | protected function sanitize_key_part( $part ) { 2029 | return str_replace( ':', '-', $part ); 2030 | } 2031 | 2032 | /** 2033 | * Checks if the given group is part the ignored group array 2034 | * 2035 | * @param string $group Name of the group to check. 2036 | * @return bool 2037 | */ 2038 | protected function is_ignored_group( $group ) { 2039 | return in_array( $this->sanitize_key_part( $group ), $this->ignored_groups, true ); 2040 | } 2041 | 2042 | /** 2043 | * Checks if the given group is part the global group array 2044 | * 2045 | * @param string $group Name of the group to check. 2046 | * @return bool 2047 | */ 2048 | protected function is_global_group( $group ) { 2049 | return in_array( $this->sanitize_key_part( $group ), $this->global_groups, true ); 2050 | } 2051 | 2052 | /** 2053 | * Checks if the given group is part the unflushable group array 2054 | * 2055 | * @param string $group Name of the group to check. 2056 | * @return bool 2057 | */ 2058 | protected function is_unflushable_group( $group ) { 2059 | return in_array( $this->sanitize_key_part( $group ), $this->unflushable_groups, true ); 2060 | } 2061 | 2062 | /** 2063 | * Convert Redis responses into something meaningful 2064 | * 2065 | * @param mixed $response Response sent from the redis instance. 2066 | * @return mixed 2067 | */ 2068 | protected function parse_redis_response( $response ) { 2069 | if ( is_bool( $response ) ) { 2070 | return $response; 2071 | } 2072 | 2073 | if ( is_numeric( $response ) ) { 2074 | return $response; 2075 | } 2076 | 2077 | if ( is_object( $response ) && method_exists( $response, 'getPayload' ) ) { 2078 | return $response->getPayload() === 'OK'; 2079 | } 2080 | 2081 | return false; 2082 | } 2083 | 2084 | /** 2085 | * Simple wrapper for saving object to the internal cache. 2086 | * 2087 | * @param string $derived_key Key to save value under. 2088 | * @param mixed $value Object value. 2089 | */ 2090 | public function add_to_internal_cache( $derived_key, $value ) { 2091 | if ( is_object( $value ) ) { 2092 | $value = clone $value; 2093 | } 2094 | 2095 | $this->cache[ $derived_key ] = $value; 2096 | } 2097 | 2098 | /** 2099 | * Get a value specifically from the internal, run-time cache, not Redis. 2100 | * 2101 | * @param int|string $derived_key Key value. 2102 | * 2103 | * @return bool|mixed Value on success; false on failure. 2104 | */ 2105 | public function get_from_internal_cache( $derived_key ) { 2106 | if ( ! isset( $this->cache[ $derived_key ] ) ) { 2107 | return false; 2108 | } 2109 | 2110 | if ( is_object( $this->cache[ $derived_key ] ) ) { 2111 | return clone $this->cache[ $derived_key ]; 2112 | } 2113 | 2114 | return $this->cache[ $derived_key ]; 2115 | } 2116 | 2117 | /** 2118 | * In multisite, switch blog prefix when switching blogs 2119 | * 2120 | * @param int $_blog_id Blog ID. 2121 | * @return bool 2122 | */ 2123 | public function switch_to_blog( $_blog_id ) { 2124 | if ( ! function_exists( 'is_multisite' ) || ! is_multisite() ) { 2125 | return false; 2126 | } 2127 | 2128 | $this->blog_prefix = $_blog_id; 2129 | 2130 | return true; 2131 | } 2132 | 2133 | /** 2134 | * Sets the list of global groups. 2135 | * 2136 | * @param array $groups List of groups that are global. 2137 | */ 2138 | public function add_global_groups( $groups ) { 2139 | $groups = (array) $groups; 2140 | 2141 | if ( $this->redis_status() ) { 2142 | $this->global_groups = array_unique( array_merge( $this->global_groups, $groups ) ); 2143 | } else { 2144 | $this->ignored_groups = array_unique( array_merge( $this->ignored_groups, $groups ) ); 2145 | } 2146 | } 2147 | 2148 | /** 2149 | * Sets the list of groups not to be cached by Redis. 2150 | * 2151 | * @param array $groups List of groups that are to be ignored. 2152 | */ 2153 | public function add_non_persistent_groups( $groups ) { 2154 | $groups = (array) $groups; 2155 | 2156 | $this->ignored_groups = array_unique( array_merge( $this->ignored_groups, $groups ) ); 2157 | } 2158 | 2159 | /** 2160 | * Sets the list of groups not to flushed cached. 2161 | * 2162 | * @param array $groups List of groups that are unflushable. 2163 | */ 2164 | public function add_unflushable_groups( $groups ) { 2165 | $groups = (array) $groups; 2166 | 2167 | $this->unflushable_groups = array_unique( array_merge( $this->unflushable_groups, $groups ) ); 2168 | } 2169 | 2170 | /** 2171 | * Wrapper to validate the cache keys expiration value 2172 | * 2173 | * @param mixed $expiration Incoming expiration value (whatever it is). 2174 | */ 2175 | protected function validate_expiration( $expiration ) { 2176 | $expiration = is_int( $expiration ) || ctype_digit( $expiration ) ? (int) $expiration : 0; 2177 | 2178 | if ( defined( 'WP_REDIS_MAXTTL' ) ) { 2179 | $max = (int) WP_REDIS_MAXTTL; 2180 | 2181 | if ( $expiration === 0 || $expiration > $max ) { 2182 | $expiration = $max; 2183 | } 2184 | } 2185 | 2186 | return $expiration; 2187 | } 2188 | 2189 | /** 2190 | * Unserialize value only if it was serialized. 2191 | * 2192 | * @param string $original Maybe unserialized original, if is needed. 2193 | * @return mixed Unserialized data can be any type. 2194 | */ 2195 | protected function maybe_unserialize( $original ) { 2196 | if ( defined( 'WP_REDIS_SERIALIZER' ) && ! empty( WP_REDIS_SERIALIZER ) ) { 2197 | return $original; 2198 | } 2199 | 2200 | if ( defined( 'WP_REDIS_IGBINARY' ) && WP_REDIS_IGBINARY && function_exists( 'igbinary_unserialize' ) ) { 2201 | return igbinary_unserialize( $original ); 2202 | } 2203 | 2204 | // Don't attempt to unserialize data that wasn't serialized going in. 2205 | if ( $this->is_serialized( $original ) ) { 2206 | // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize 2207 | $value = @unserialize( $original ); 2208 | 2209 | return is_object( $value ) ? clone $value : $value; 2210 | } 2211 | 2212 | return $original; 2213 | } 2214 | 2215 | /** 2216 | * Serialize data, if needed. 2217 | * 2218 | * @param mixed $data Data that might be serialized. 2219 | * @return mixed A scalar data 2220 | */ 2221 | protected function maybe_serialize( $data ) { 2222 | if ( is_object( $data ) ) { 2223 | $data = clone $data; 2224 | } 2225 | 2226 | if ( defined( 'WP_REDIS_SERIALIZER' ) && ! empty( WP_REDIS_SERIALIZER ) ) { 2227 | return $data; 2228 | } 2229 | 2230 | if ( defined( 'WP_REDIS_IGBINARY' ) && WP_REDIS_IGBINARY && function_exists( 'igbinary_serialize' ) ) { 2231 | return igbinary_serialize( $data ); 2232 | } 2233 | 2234 | if ( is_array( $data ) || is_object( $data ) ) { 2235 | // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize 2236 | return serialize( $data ); 2237 | } 2238 | 2239 | if ( $this->is_serialized( $data, false ) ) { 2240 | // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize 2241 | return serialize( $data ); 2242 | } 2243 | 2244 | return $data; 2245 | } 2246 | 2247 | /** 2248 | * Check value to find if it was serialized. 2249 | * 2250 | * If $data is not an string, then returned value will always be false. 2251 | * Serialized data is always a string. 2252 | * 2253 | * @param string $data Value to check to see if was serialized. 2254 | * @param bool $strict Optional. Whether to be strict about the end of the string. Default true. 2255 | * @return bool False if not serialized and true if it was. 2256 | */ 2257 | protected function is_serialized( $data, $strict = true ) { 2258 | // if it isn't a string, it isn't serialized. 2259 | if ( ! is_string( $data ) ) { 2260 | return false; 2261 | } 2262 | 2263 | $data = trim( $data ); 2264 | 2265 | if ( 'N;' === $data ) { 2266 | return true; 2267 | } 2268 | 2269 | if ( strlen( $data ) < 4 ) { 2270 | return false; 2271 | } 2272 | 2273 | if ( ':' !== $data[1] ) { 2274 | return false; 2275 | } 2276 | 2277 | if ( $strict ) { 2278 | $lastc = substr( $data, -1 ); 2279 | 2280 | if ( ';' !== $lastc && '}' !== $lastc ) { 2281 | return false; 2282 | } 2283 | } else { 2284 | $semicolon = strpos( $data, ';' ); 2285 | $brace = strpos( $data, '}' ); 2286 | 2287 | // Either ; or } must exist. 2288 | if ( false === $semicolon && false === $brace ) { 2289 | return false; 2290 | } 2291 | 2292 | // But neither must be in the first X characters. 2293 | if ( false !== $semicolon && $semicolon < 3 ) { 2294 | return false; 2295 | } 2296 | 2297 | if ( false !== $brace && $brace < 4 ) { 2298 | return false; 2299 | } 2300 | } 2301 | $token = $data[0]; 2302 | 2303 | switch ( $token ) { 2304 | case 's': 2305 | if ( $strict ) { 2306 | if ( '"' !== substr( $data, -2, 1 ) ) { 2307 | return false; 2308 | } 2309 | } elseif ( false === strpos( $data, '"' ) ) { 2310 | return false; 2311 | } 2312 | // Or else fall through. 2313 | // No break! 2314 | case 'a': 2315 | case 'O': 2316 | return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data ); 2317 | case 'b': 2318 | case 'i': 2319 | case 'd': 2320 | $end = $strict ? '$' : ''; 2321 | 2322 | return (bool) preg_match( "/^{$token}:[0-9.E-]+;$end/", $data ); 2323 | } 2324 | 2325 | return false; 2326 | } 2327 | 2328 | /** 2329 | * Invoke the `redis_object_cache_trace` hook. 2330 | * 2331 | * @param string $command 2332 | * @param string $group 2333 | * @param array[string]array $keyValues 2334 | * @param float $duration 2335 | * @return void 2336 | */ 2337 | private function trace_command ( $command, $group, $keyValues, $duration ) { 2338 | if ( ! $this->trace_enabled || ! function_exists( 'do_action' ) ) { 2339 | return; 2340 | } 2341 | 2342 | /** 2343 | * Fires on every cache call. 2344 | * 2345 | * This hook is called on every cache request. 2346 | * It reports statistics per key involved. @see WP_Object_Cache::TRACE_FLAG_READ and friends. 2347 | * 2348 | * @param string $command The command that was executed. 2349 | * @param string $group Key group. 2350 | * @param array[string]array $keyValues Maps keys to the returned values (if any) and the resulting status. 2351 | * $keyValues = [ 2352 | * "foo" => ["value" => "bar", "status" => TRACE_FLAG_READ | TRACE_FLAG_HIT], // hit on redis (implies internal miss) 2353 | * "baz" => ["value" => "quo", "status" => TRACE_FLAG_READ | TRACE_FLAG_HIT | TRACE_FLAG_INTERNAL], // hit on internal cache 2354 | * "eta" => ["value" => null, "status" => TRACE_FLAG_READ], // miss 2355 | * ]; 2356 | * @param float $duration Duration of the request in microseconds. 2357 | * @return void 2358 | */ 2359 | do_action( 'redis_object_cache_trace', $command, $group, $keyValues, $duration ); 2360 | } 2361 | 2362 | /** 2363 | * Handle the redis failure gracefully or throw an exception. 2364 | * 2365 | * @param \Exception $exception Exception thrown. 2366 | * @throws \Exception If `fail_gracefully` flag is set to a falsy value. 2367 | * @return void 2368 | */ 2369 | protected function handle_exception( $exception ) { 2370 | $this->redis_connected = false; 2371 | 2372 | // When Redis is unavailable, fall back to the internal cache by forcing all groups to be "no redis" groups. 2373 | $this->ignored_groups = array_unique( array_merge( $this->ignored_groups, $this->global_groups ) ); 2374 | 2375 | if ( ! $this->fail_gracefully ) { 2376 | throw $exception; 2377 | } 2378 | 2379 | $this->errors[] = $exception->getMessage(); 2380 | 2381 | error_log( $exception ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log 2382 | 2383 | if ( function_exists( 'do_action' ) ) { 2384 | /** 2385 | * Fires on every cache error 2386 | * 2387 | * @since 1.5.0 2388 | * @param \Exception $exception The exception triggered. 2389 | */ 2390 | do_action( 'redis_object_cache_error', $exception ); 2391 | } 2392 | } 2393 | 2394 | /** 2395 | * Allows access to private properties for backwards compatibility. 2396 | * 2397 | * @param string $name Name of the property. 2398 | * @return mixed 2399 | */ 2400 | public function __get( $name ) { 2401 | return isset( $this->{$name} ) ? $this->{$name} : null; 2402 | } 2403 | } 2404 | 2405 | endif; 2406 | // phpcs:enable Generic.WhiteSpace.ScopeIndent.IncorrectExact, Generic.WhiteSpace.ScopeIndent.Incorrect --------------------------------------------------------------------------------