Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
n/a
0 / 0
100.00% covered (success)
100.00%
1 / 1
CRAP
n/a
0 / 0
jetpack_shim_setcookie
n/a
0 / 0
n/a
0 / 0
16
1<?php // phpcs:ignore WordPress.Files.FileName.NotHyphenatedLowercase
2/**
3 * This file is meant to be the home for any function handling cookies that can
4 * be accessed anywhere within Jetpack.
5 *
6 * This file is loaded whether or not Jetpack is connected to WP.com.
7 *
8 * @package automattic/jetpack
9 */
10
11/**
12 * A PHP 7.0 compatible version of the array argument version of PHP 7.3's setcookie().
13 *
14 * Useful for setting SameSite cookies in PHP 7.2 or earlier.
15 *
16 * @deprecated since 16.2. Use `setcookie()` instead now that we've dropped PHP 7.2 support.
17 * @param string $name    Name of the cookie.
18 * @param string $value   Value of the cookie.
19 * @param array  $options Options to include with the cookie.
20 * @return bool False when error happens, other wise true.
21 */
22function jetpack_shim_setcookie( $name, $value, $options ) {
23    _deprecated_function( __FUNCTION__, 'jetpack-16.2', 'setcookie' );
24
25    $not_allowed_chars = ",; \t\r\n\013\014";
26
27    if ( false !== strpbrk( $name, $not_allowed_chars ) ) {
28        return false;
29    }
30
31    if ( headers_sent() ) {
32        return false;
33    }
34
35    $cookie = 'Set-Cookie: ' . $name . '=' . rawurlencode( $value ) . '; ';
36
37    if ( ! empty( $options['expires'] ) ) {
38        $cookie_date = gmdate( 'D, d M Y H:i:s \G\M\T', $options['expires'] );
39        $cookie     .= sprintf( 'expires=%s', $cookie_date ) . ';';
40    }
41
42    if ( ! empty( $options['secure'] ) && true === $options['secure'] ) {
43        $cookie .= 'secure; ';
44    }
45
46    if ( ! empty( $options['httponly'] ) && true === $options['httponly'] ) {
47        $cookie .= 'HttpOnly; ';
48    }
49
50    if ( ! empty( $options['domain'] ) && is_string( $options['domain'] ) ) {
51        if ( false !== strpbrk( $options['domain'], $not_allowed_chars ) ) {
52            return false;
53        }
54        $cookie .= sprintf( 'domain=%s', $options['domain'] . '; ' );
55    }
56
57    if ( ! empty( $options['path'] ) && is_string( $options['path'] ) ) {
58        if ( false !== strpbrk( $options['path'], $not_allowed_chars ) ) {
59            return false;
60        }
61        $cookie .= sprintf( 'path=%s', $options['path'] . '; ' );
62    }
63
64    if ( ! empty( $options['samesite'] ) && is_string( $options['samesite'] ) ) {
65        $cookie .= sprintf( 'SameSite=%s', $options['samesite'] . '; ' );
66    }
67
68    $cookie = trim( $cookie );
69    $cookie = trim( $cookie, ';' );
70    header( $cookie, false );
71
72    return true;
73}