From 4cff11efa4daadefa900954c012e268a96be542d Mon Sep 17 00:00:00 2001 From: Jan Michalski Date: Tue, 27 Aug 2024 11:12:09 -0400 Subject: [PATCH] theme: remove unused dynamic PHP scripts On security request. Note: Some of them are still referenced here and there. But since PHP doesn't work anyway we can have them removed. It doesn't change the outcome. Signed-off-by: Jan Michalski --- themes/pmem-hugo/layouts/partials/head.html | 2 - themes/pmem-hugo/static/css/colors.css | 307 - themes/pmem-hugo/static/css/colors.php | 295 - .../include/ajax/portfolio-ajax-gallery.php | 105 - .../include/ajax/portfolio-ajax-image.php | 85 - .../include/ajax/portfolio-ajax-slider.php | 95 - .../include/ajax/portfolio-ajax-video.php | 84 - .../campaign-monitor/class/base_classes.php | 287 - .../include/campaign-monitor/class/log.php | 19 - .../campaign-monitor/class/serialisation.php | 129 - .../campaign-monitor/class/services_json.php | 782 --- .../campaign-monitor/class/transport.php | 335 -- .../campaign-monitor/csrest_subscribers.php | 230 - themes/pmem-hugo/static/include/form.php | 411 -- .../pmem-hugo/static/include/getresponse.php | 15 - .../getresponse/GetResponseAPI3.class.php | 406 -- .../static/include/instagram/instagram.php | 58 - .../include/phpmailer/src/Exception.php | 40 - .../static/include/phpmailer/src/OAuth.php | 139 - .../include/phpmailer/src/PHPMailer.php | 4983 ----------------- .../static/include/phpmailer/src/POP3.php | 448 -- .../static/include/phpmailer/src/SMTP.php | 1456 ----- .../pmem-hugo/static/include/subscribe-cm.php | 33 - .../static/include/subscribe-email.php | 58 - themes/pmem-hugo/static/include/subscribe.php | 58 - .../static/include/twitter/oauth/OAuth.php | 874 --- .../include/twitter/oauth/twitteroauth.php | 241 - .../static/include/twitter/tweets.php | 58 - 28 files changed, 12033 deletions(-) delete mode 100644 themes/pmem-hugo/static/css/colors.css delete mode 100644 themes/pmem-hugo/static/css/colors.php delete mode 100644 themes/pmem-hugo/static/include/ajax/portfolio-ajax-gallery.php delete mode 100644 themes/pmem-hugo/static/include/ajax/portfolio-ajax-image.php delete mode 100644 themes/pmem-hugo/static/include/ajax/portfolio-ajax-slider.php delete mode 100644 themes/pmem-hugo/static/include/ajax/portfolio-ajax-video.php delete mode 100644 themes/pmem-hugo/static/include/campaign-monitor/class/base_classes.php delete mode 100644 themes/pmem-hugo/static/include/campaign-monitor/class/log.php delete mode 100644 themes/pmem-hugo/static/include/campaign-monitor/class/serialisation.php delete mode 100644 themes/pmem-hugo/static/include/campaign-monitor/class/services_json.php delete mode 100644 themes/pmem-hugo/static/include/campaign-monitor/class/transport.php delete mode 100644 themes/pmem-hugo/static/include/campaign-monitor/csrest_subscribers.php delete mode 100644 themes/pmem-hugo/static/include/form.php delete mode 100644 themes/pmem-hugo/static/include/getresponse.php delete mode 100644 themes/pmem-hugo/static/include/getresponse/GetResponseAPI3.class.php delete mode 100644 themes/pmem-hugo/static/include/instagram/instagram.php delete mode 100644 themes/pmem-hugo/static/include/phpmailer/src/Exception.php delete mode 100644 themes/pmem-hugo/static/include/phpmailer/src/OAuth.php delete mode 100644 themes/pmem-hugo/static/include/phpmailer/src/PHPMailer.php delete mode 100644 themes/pmem-hugo/static/include/phpmailer/src/POP3.php delete mode 100644 themes/pmem-hugo/static/include/phpmailer/src/SMTP.php delete mode 100644 themes/pmem-hugo/static/include/subscribe-cm.php delete mode 100644 themes/pmem-hugo/static/include/subscribe-email.php delete mode 100644 themes/pmem-hugo/static/include/subscribe.php delete mode 100644 themes/pmem-hugo/static/include/twitter/oauth/OAuth.php delete mode 100644 themes/pmem-hugo/static/include/twitter/oauth/twitteroauth.php delete mode 100644 themes/pmem-hugo/static/include/twitter/tweets.php diff --git a/themes/pmem-hugo/layouts/partials/head.html b/themes/pmem-hugo/layouts/partials/head.html index f2aaa944ef..08884ecb15 100644 --- a/themes/pmem-hugo/layouts/partials/head.html +++ b/themes/pmem-hugo/layouts/partials/head.html @@ -58,8 +58,6 @@ - - diff --git a/themes/pmem-hugo/static/css/colors.css b/themes/pmem-hugo/static/css/colors.css deleted file mode 100644 index 8014ba0ea9..0000000000 --- a/themes/pmem-hugo/static/css/colors.css +++ /dev/null @@ -1,307 +0,0 @@ -/* ---------------------------------------------------------------- - Colors - - Replace the HEX Code with your Desired Color HEX ------------------------------------------------------------------*/ - - -:root { - --themecolor: #1ABC9C; /* Change this Color */ -} - - -::selection { - background: var(--themecolor); -} - -::-moz-selection { - background: var(--themecolor); -} - -::-webkit-selection { - background: var(--themecolor); -} - - -a, -h1 > span:not(.nocolor):not(.badge), -h2 > span:not(.nocolor):not(.badge), -h3 > span:not(.nocolor):not(.badge), -h4 > span:not(.nocolor):not(.badge), -h5 > span:not(.nocolor):not(.badge), -h6 > span:not(.nocolor):not(.badge), -.header-extras li .he-text span, -.menu-item:hover > .menu-link, -.menu-item.current > .menu-link, -.dark .menu-item:hover > .menu-link, -.dark .menu-item.current > .menu-link, -.top-cart-item-desc a:hover, -.top-cart-action .top-checkout-price, -.breadcrumb a:hover, -.grid-filter li:not(.activeFilter) a:hover, -.portfolio-desc h3 a:hover, -#portfolio-navigation a:hover, -.entry-title h2 a:hover, -.entry-title h3 a:hover, -.entry-title h4 a:hover, -.post-timeline .entry:hover .entry-timeline, -.post-timeline .entry:hover .timeline-divider, -.comment-content .comment-author a:hover, -.product-title h3 a:hover, -.single-product .product-title h2 a:hover, -.product-price ins, -.single-product .product-price, -.process-steps li.active h5, -.process-steps li.ui-tabs-active h5, -.tab-nav-lg li.ui-tabs-active a, -.team-title span, -.btn-link, -.page-link, -.page-link:hover, -.page-link:focus, -.fbox-plain .fbox-icon i, -.fbox-plain .fbox-icon img, -.fbox-border .fbox-icon i, -.fbox-border .fbox-icon img, -.iconlist > li [class^="icon-"]:first-child, -.dark .menu-item:hover > .menu-link, -.dark .menu-item.current > .menu-link, -.dark .top-cart-item-desc a:hover, -.dark .breadcrumb a:hover, -.dark .portfolio-desc h3 a:hover, -.dark #portfolio-navigation a:hover, -.dark .entry-title h2 a:hover, -.dark .entry-title h3 a:hover, -.dark .entry-title h4 a:hover, -.dark .product-title h3 a:hover, -.dark .single-product .product-title h2 a:hover, -.dark .product-price ins, -.dark .tab-nav-lg li.ui-tabs-active a { - color: var(--themecolor); -} - -.color, -.h-text-color:hover, -a.h-text-color:hover, -.grid-filter.style-3 li.activeFilter a, -.faqlist li a:hover, -.tagcloud a:hover, -.nav-tree li:hover > a, -.nav-tree li.current > a, -.nav-tree li.active > a { - color: var(--themecolor) !important; -} - -.top-cart-number::before, -#page-menu-wrap, -.page-menu-nav, -.control-solid .flex-control-nav li:hover a, -.control-solid .flex-control-nav li a.flex-active, -.grid-filter li.activeFilter a, -.grid-filter.style-4 li.activeFilter a::after, -.grid-shuffle:hover, -.entry-link:hover, -.button, -.button.button-dark:hover, -.button.button-3d:hover, -.fbox-icon i, -.fbox-icon img, -.fbox-effect.fbox-dark .fbox-icon i:hover, -.fbox-effect.fbox-dark:hover .fbox-icon i, -.fbox-border.fbox-effect.fbox-dark .fbox-icon i::after, -.i-rounded:hover, -.i-circled:hover, -.tab-nav.tab-nav2 li.ui-state-active a, -.testimonial .flex-control-nav li a, -.skills li .progress, -.owl-carousel .owl-dots .owl-dot, -#gotoTop:hover, -input.switch-toggle-round:checked + label::before, -input.switch-toggle-flat:checked + label, -input.switch-toggle-flat:checked + label::after, -.nav-pills > li.active > a, -.nav-pills > li.active > a:hover, -.nav-pills > li.active > a:focus, -input.switch-toggle-round:checked + label:before, -input.switch-toggle-flat:checked + label, -input.switch-toggle-flat:checked + label:after, -.irs-bar, -.dark .entry-link:hover, -.dark .fbox-effect.fbox-dark .fbox-icon i:hover, -.dark .fbox-effect.fbox-dark:hover .fbox-icon i, -.dark .fbox-border.fbox-effect.fbox-dark .fbox-icon i:after, -.dark .i-rounded:hover, -.dark .i-circled:hover, -.dark .tab-nav.tab-nav2 li.ui-state-active a, -.dark #gotoTop:hover, -.dark input.switch-toggle-round:checked + label::before, -.dark input.switch-toggle-flat:checked + label, -.dark input.switch-toggle-flat:checked + label::after { - background-color: var(--themecolor); -} - -.bg-color, -.bg-color #header-wrap, -.h-bg-color:hover, -.process-steps li.active a, -.process-steps li.ui-tabs-active a, -.sidenav > .ui-tabs-active > a, -.sidenav > .ui-tabs-active > a:hover, -.owl-carousel .owl-nav [class*=owl-]:hover, -.widget-filter-links li.active-filter span, -.page-item.active .page-link, -.page-link:hover, -.page-link:focus { - background-color: var(--themecolor) !important; -} - -.bootstrap-switch .bootstrap-switch-handle-on.bootstrap-switch-themecolor, -.bootstrap-switch .bootstrap-switch-handle-off.bootstrap-switch-themecolor, -.checkbox-style:checked + .checkbox-style-1-label:before, -.checkbox-style:checked + .checkbox-style-2-label:before, -.checkbox-style:checked + .checkbox-style-3-label:before, -.radio-style:checked + .radio-style-3-label:before { - background: var(--themecolor); -} - -.irs-bar, -.irs-from, -.irs-to, -.irs-single, -.irs-handle > i:first-child, -.irs-handle.state_hover > i:first-child, -.irs-handle:hover > i:first-child { - background-color: var(--themecolor) !important; -} - -.top-cart-item-image:hover, -.grid-filter.style-3 li.activeFilter a, -.post-timeline .entry:hover .entry-timeline, -.post-timeline .entry:hover .timeline-divider, -.cart-product-thumbnail img:hover, -.fbox-outline .fbox-icon a, -.fbox-border .fbox-icon a, -.heading-block.border-color::after, -.page-item.active .page-link, -.page-link:focus, -.dark .cart-product-thumbnail img:hover { - border-color: var(--themecolor); -} - -.border-color, -.process-steps li.active a, -.process-steps li.ui-tabs-active a, -.tagcloud a:hover, -.page-link:hover { - border-color: var(--themecolor) !important; -} - -.top-links-sub-menu, -.top-links-section, -.tabs-tb .tab-nav li.ui-tabs-active a, -.dark .top-links-sub-menu, -.dark .top-links-section, -.dark .tabs-tb .tab-nav li.ui-tabs-active a { - border-top-color: var(--themecolor); -} - -.title-border-color::before, -.title-border-color::after, -.irs-from:after, -.irs-single:after, -.irs-to:after, -.irs-from:before, -.irs-to:before, -.irs-single:before { - border-top-color: var(--themecolor) !important; -} - -.title-block { - border-left-color: var(--themecolor); -} - -.rtl .title-block { - border-left-color: transparent; - border-right-color: var(--themecolor); -} - -.title-block-right { - border-right-color: var(--themecolor); -} - -.rtl .title-block-right { - border-right-color: transparent; - border-left-color: var(--themecolor); -} - -.more-link, -.tabs-bb .tab-nav li.ui-tabs-active a, -.title-bottom-border h1, -.title-bottom-border h2, -.title-bottom-border h3, -.title-bottom-border h4, -.title-bottom-border h5, -.title-bottom-border h6 { - border-bottom-color: var(--themecolor); -} - -.fbox-effect.fbox-dark .fbox-icon i::after, -.dark .fbox-effect.fbox-dark .fbox-icon i:after { - box-shadow: 0 0 0 2px var(--themecolor); -} - -.fbox-border.fbox-effect.fbox-dark .fbox-icon i:hover, -.fbox-border.fbox-effect.fbox-dark:hover .fbox-icon i, -.dark .fbox-border.fbox-effect.fbox-dark .fbox-icon i:hover, -.dark .fbox-border.fbox-effect.fbox-dark:hover .fbox-icon i { - box-shadow: 0 0 0 1px var(--themecolor); -} - - -@media (min-width: 992px) { - - .sub-menu-container .menu-item:hover > .menu-link, - .mega-menu-style-2 .mega-menu-title > .menu-link:hover, - .dark .primary-menu:not(.not-dark) .sub-menu-container .menu-item:hover > .menu-link, - .dark .mega-menu-style-2 .mega-menu-title:hover > .menu-link { - color: var(--themecolor); - } - - .style-3 .menu-container > .menu-item.current > .menu-link, - .sub-title .menu-container > .menu-item:hover > .menu-link::after, - .sub-title .menu-container > .menu-item.current > .menu-link::after, - .page-menu-sub-menu, - .dots-menu .page-menu-item.current > a, - .dots-menu .page-menu-item div, - .dark .style-3 .menu-container > .menu-item.current > .menu-link { - background-color: var(--themecolor); - } - - .style-4 .menu-container > .menu-item:hover > .menu-link, - .style-4 .menu-container > .menu-item.current > .menu-link, - .dots-menu.dots-menu-border .page-menu-item.current > a { - border-color: var(--themecolor); - } - - .sub-menu-container, - .mega-menu-content, - .style-6 .menu-container > .menu-item > .menu-link::after, - .style-6 .menu-container > .menu-item.current > .menu-link::after, - .top-cart-content, - .dark .sub-menu-container, - .dark .mega-menu-content, - .dark .primary-menu:not(.not-dark) .sub-menu-container, - .dark .primary-menu:not(.not-dark) .mega-menu-content, - .dark .top-cart-content { - border-top-color: var(--themecolor); - } - - .dots-menu .page-menu-item div::after { - border-left-color: var(--themecolor); - } - - .rtl .dots-menu .page-menu-item div::after { - border-left-color: transparent; - border-right-color: var(--themecolor); - } -} \ No newline at end of file diff --git a/themes/pmem-hugo/static/css/colors.php b/themes/pmem-hugo/static/css/colors.php deleted file mode 100644 index c67856457c..0000000000 --- a/themes/pmem-hugo/static/css/colors.php +++ /dev/null @@ -1,295 +0,0 @@ - - - -/* ---------------------------------------------------------------- - Colors - - Replace the HEX Code with your Desired Color HEX ------------------------------------------------------------------*/ - - -::selection { background: ; } - -::-moz-selection { background: ; } - -::-webkit-selection { background: ; } - - -a, -h1 > span:not(.nocolor):not(.badge), -h2 > span:not(.nocolor):not(.badge), -h3 > span:not(.nocolor):not(.badge), -h4 > span:not(.nocolor):not(.badge), -h5 > span:not(.nocolor):not(.badge), -h6 > span:not(.nocolor):not(.badge), -.header-extras li .he-text span, -.menu-item:hover > .menu-link, -.menu-item.current > .menu-link, -.dark .menu-item:hover > .menu-link, -.dark .menu-item.current > .menu-link, -.top-cart-item-desc a:hover, -.top-cart-action .top-checkout-price, -.breadcrumb a:hover, -.grid-filter li:not(.activeFilter) a:hover, -.portfolio-desc h3 a:hover, -#portfolio-navigation a:hover, -.entry-title h2 a:hover, -.entry-title h3 a:hover, -.entry-title h4 a:hover, -.post-timeline .entry:hover .entry-timeline, -.post-timeline .entry:hover .timeline-divider, -.comment-content .comment-author a:hover, -.product-title h3 a:hover, -.single-product .product-title h2 a:hover, -.product-price ins, -.single-product .product-price, -.process-steps li.active h5, -.process-steps li.ui-tabs-active h5, -.tab-nav-lg li.ui-tabs-active a, -.team-title span, -.btn-link, -.page-link, -.page-link:hover, -.page-link:focus, -.fbox-plain .fbox-icon i, -.fbox-plain .fbox-icon img, -.fbox-border .fbox-icon i, -.fbox-border .fbox-icon img, -.iconlist > li [class^="icon-"]:first-child, -.dark .menu-item:hover > .menu-link, -.dark .menu-item.current > .menu-link, -.dark .top-cart-item-desc a:hover, -.dark .breadcrumb a:hover, -.dark .portfolio-desc h3 a:hover, -.dark #portfolio-navigation a:hover, -.dark .entry-title h2 a:hover, -.dark .entry-title h3 a:hover, -.dark .entry-title h4 a:hover, -.dark .product-title h3 a:hover, -.dark .single-product .product-title h2 a:hover, -.dark .product-price ins, -.dark .tab-nav-lg li.ui-tabs-active a { color: ; } - -.color, -.h-text-color:hover, -a.h-text-color:hover, -.grid-filter.style-3 li.activeFilter a, -.faqlist li a:hover, -.tagcloud a:hover, -.nav-tree li:hover > a, -.nav-tree li.current > a, -.nav-tree li.active > a { color: !important; } - -.top-cart-number::before, -#page-menu-wrap, -.page-menu-nav, -.control-solid .flex-control-nav li:hover a, -.control-solid .flex-control-nav li a.flex-active, -.grid-filter li.activeFilter a, -.grid-filter.style-4 li.activeFilter a::after, -.grid-shuffle:hover, -.entry-link:hover, -.button, -.button.button-dark:hover, -.button.button-3d:hover, -.fbox-icon i, -.fbox-icon img, -.fbox-effect.fbox-dark .fbox-icon i:hover, -.fbox-effect.fbox-dark:hover .fbox-icon i, -.fbox-border.fbox-effect.fbox-dark .fbox-icon i::after, -.i-rounded:hover, -.i-circled:hover, -.tab-nav.tab-nav2 li.ui-state-active a, -.testimonial .flex-control-nav li a, -.skills li .progress, -.owl-carousel .owl-dots .owl-dot, -#gotoTop:hover, -input.switch-toggle-round:checked + label::before, -input.switch-toggle-flat:checked + label, -input.switch-toggle-flat:checked + label::after, -.nav-pills > li.active > a, -.nav-pills > li.active > a:hover, -.nav-pills > li.active > a:focus, -input.switch-toggle-round:checked + label::before, -input.switch-toggle-flat:checked + label, -input.switch-toggle-flat:checked + label::after, -.dark .entry-link:hover, -.dark .fbox-effect.fbox-dark .fbox-icon i:hover, -.dark .fbox-effect.fbox-dark:hover .fbox-icon i, -.dark .fbox-border.fbox-effect.fbox-dark .fbox-icon i::after, -.dark .i-rounded:hover, -.dark .i-circled:hover, -.dark .tab-nav.tab-nav2 li.ui-state-active a, -.dark #gotoTop:hover, -.dark input.switch-toggle-round:checked + label::before, -.dark input.switch-toggle-flat:checked + label, -.dark input.switch-toggle-flat:checked + label::after { background-color: ; } - -.bg-color, -.bg-color #header-wrap, -.h-bg-color:hover, -.process-steps li.active a, -.process-steps li.ui-tabs-active a, -.sidenav > .ui-tabs-active > a, -.sidenav > .ui-tabs-active > a:hover, -.owl-carousel .owl-nav [class*=owl-]:hover, -.widget-filter-links li.active-filter span, -.page-item.active .page-link, -.page-link:hover, -.page-link:focus { background-color: !important; } - -.bootstrap-switch .bootstrap-switch-handle-on.bootstrap-switch-themecolor, -.bootstrap-switch .bootstrap-switch-handle-off.bootstrap-switch-themecolor, -.checkbox-style:checked + .checkbox-style-1-label::before, -.checkbox-style:checked + .checkbox-style-2-label::before, -.checkbox-style:checked + .checkbox-style-3-label::before, -.radio-style:checked + .radio-style-3-label::before { background: ; } - -.irs-bar, -.irs-from, -.irs-to, -.irs-single, -.irs-handle > i:first-child, -.irs-handle.state_hover > i:first-child, -.irs-handle:hover > i:first-child { background-color: !important; } - -.top-cart-item-image:hover, -.grid-filter.style-3 li.activeFilter a, -.post-timeline .entry:hover .entry-timeline, -.post-timeline .entry:hover .timeline-divider, -.cart-product-thumbnail img:hover, -.fbox-outline .fbox-icon a, -.fbox-border .fbox-icon a, -.heading-block.border-color::after, -.page-item.active .page-link, -.page-link:focus, -.dark .cart-product-thumbnail img:hover { border-color: ; } - -.border-color, -.process-steps li.active a, -.process-steps li.ui-tabs-active a, -.tagcloud a:hover, -.page-link:hover { border-color: !important; } - -.top-links-sub-menu, -.top-links-section, -.tabs-tb .tab-nav li.ui-tabs-active a, -.dark .top-links-sub-menu, -.dark .top-links-section, -.dark .tabs-tb .tab-nav li.ui-tabs-active a { border-top-color: ; } - -.title-border-color::before, -.title-border-color::after, -.irs-from::after, -.irs-single::after, -.irs-to::after, -.irs-from::before, -.irs-to::before, -.irs-single::before { border-top-color: !important; } - -.title-block { border-left-color: ; } - -.rtl .title-block { - border-left-color: transparent; - border-right-color: ; -} - -.title-block-right { border-right-color: ; } - -.rtl .title-block-right { - border-right-color: transparent; - border-left-color: ; -} - -.more-link, -.tabs-bb .tab-nav li.ui-tabs-active a, -.title-bottom-border h1, -.title-bottom-border h2, -.title-bottom-border h3, -.title-bottom-border h4, -.title-bottom-border h5, -.title-bottom-border h6 { border-bottom-color: ; } - -.fbox-effect.fbox-dark .fbox-icon i::after, -.dark .fbox-effect.fbox-dark .fbox-icon i::after { box-shadow: 0 0 0 2px ; } - -.fbox-border.fbox-effect.fbox-dark .fbox-icon i:hover, -.fbox-border.fbox-effect.fbox-dark:hover .fbox-icon i, -.dark .fbox-border.fbox-effect.fbox-dark .fbox-icon i:hover, -.dark .fbox-border.fbox-effect.fbox-dark:hover .fbox-icon i { box-shadow: 0 0 0 1px ; } - - -@media (min-width: 992px) { - - .sub-menu-container .menu-item:hover > .menu-link, - .mega-menu-style-2 .mega-menu-title > .menu-link:hover, - .dark .mega-menu-style-2 .mega-menu-title:hover > .menu-link { color: ; } - - .style-3 .menu-container > .menu-item.current > .menu-link, - .sub-title .menu-container > .menu-item:hover > .menu-link::after, - .sub-title .menu-container > .menu-item.current > .menu-link::after, - .page-menu-sub-menu, - .dots-menu .page-menu-item.current > a, - .dots-menu .page-menu-item div, - .dark .style-3 .menu-container > .menu-item.current > .menu-link { background-color: ; } - - .style-4 .menu-container > .menu-item:hover > .menu-link, - .style-4 .menu-container > .menu-item.current > .menu-link, - .dots-menu.dots-menu-border .page-menu-item.current > a { border-color: ; } - - .sub-menu-container, - .mega-menu-content, - .style-6 .menu-container > .menu-item > .menu-link::after, - .style-6 .menu-container > .menu-item.current > .menu-link::after, - .top-cart-content, - .dark .sub-menu-container, - .dark .mega-menu-content, - .dark .top-cart-content { border-top-color: ; } - - .dots-menu .page-menu-item div::after { border-left-color: ; } - - .rtl .dots-menu .page-menu-item div::after { - border-left-color: transparent; - border-right-color: ; - } -} \ No newline at end of file diff --git a/themes/pmem-hugo/static/include/ajax/portfolio-ajax-gallery.php b/themes/pmem-hugo/static/include/ajax/portfolio-ajax-gallery.php deleted file mode 100644 index c0fbe655cd..0000000000 --- a/themes/pmem-hugo/static/include/ajax/portfolio-ajax-gallery.php +++ /dev/null @@ -1,105 +0,0 @@ - - -
- -
-

Single Item with Thumbs

-
- - - -
-
- -
- -
- -
-
- Gallery Thumb 1 - Gallery Thumb 2 - Gallery Thumb 3 - Gallery Thumb 4 - Gallery Thumb 5 - Gallery Thumb 6 - Gallery Thumb 7 -
-
- -
- -
-
-
    -
  • Created by: John Doe
  • -
  • Completed on: 17th March 2021
  • -
  • Skills: HTML5 / PHP / CSS3
  • -
  • Client: Google
  • -
-
-
- - - - - -
- - -
- -
-
-

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquam, labore deserunt ex cupiditate est blanditiis dignissimos nesciunt doloremque laboriosam ullam necessitatibus voluptatum tempora itaque quia porro voluptates quo excepturi veritatis!

-
- -
-

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatem, sed.

-

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nemo, soluta explicabo sunt aliquam officiis autem.

-
-
- -
-
- -
\ No newline at end of file diff --git a/themes/pmem-hugo/static/include/ajax/portfolio-ajax-image.php b/themes/pmem-hugo/static/include/ajax/portfolio-ajax-image.php deleted file mode 100644 index fd9e9d87a9..0000000000 --- a/themes/pmem-hugo/static/include/ajax/portfolio-ajax-image.php +++ /dev/null @@ -1,85 +0,0 @@ - - -
- -
-

Single Item with Image

-
- - - -
-
- -
- -
- -
- Image -
- - -
- -

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Perferendis, dolores, facere, corrupti delectus ex quidem adipisci tempore.

-

Illum molestias cupiditate eveniet dolore obcaecati voluptatibus est quos eos id recusandae officia. Cupiditate, voluptates quibusdam ipsum vel corporis laboriosam id est doloremque.

- - -
- - -
    -
  • Created by: John Doe
  • -
  • Completed on: 17th March 2021
  • -
  • Skills: HTML5 / PHP / CSS3
  • -
  • Client: Google
  • -
- - - - - -
-
- -
\ No newline at end of file diff --git a/themes/pmem-hugo/static/include/ajax/portfolio-ajax-slider.php b/themes/pmem-hugo/static/include/ajax/portfolio-ajax-slider.php deleted file mode 100644 index 0a92207585..0000000000 --- a/themes/pmem-hugo/static/include/ajax/portfolio-ajax-slider.php +++ /dev/null @@ -1,95 +0,0 @@ - - -
- -
-

Single Item with Slider Gallery

-
- - - -
-
- -
- -
- -
-
-
-
-
Image
-
Image
-
Image
-
-
-
-
- - -
- - -

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Perferendis, dolores, facere, corrupti delectus ex quidem adipisci tempore.

-

Illum molestias cupiditate eveniet dolore obcaecati voluptatibus est quos eos id recusandae officia. Cupiditate, voluptates quibusdam ipsum vel corporis laboriosam id est doloremque.

- - -
- - -
    -
  • Created by: John Doe
  • -
  • Completed on: 17th March 2021
  • -
  • Skills: HTML5 / PHP / CSS3
  • -
  • Client: Google
  • -
- - - - - - -
-
- -
\ No newline at end of file diff --git a/themes/pmem-hugo/static/include/ajax/portfolio-ajax-video.php b/themes/pmem-hugo/static/include/ajax/portfolio-ajax-video.php deleted file mode 100644 index d8af45537b..0000000000 --- a/themes/pmem-hugo/static/include/ajax/portfolio-ajax-video.php +++ /dev/null @@ -1,84 +0,0 @@ - - -
- -
-

Single Item with Video

-
- - - -
-
- -
- -
- -
- -

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Perferendis, dolores, facere, corrupti delectus ex quidem adipisci tempore. Illum molestias cupiditate eveniet dolore obcaecati voluptatibus est.

- - -
- - -
    -
  • Created by: John Doe
  • -
  • Completed on: 17th March 2021
  • -
  • Skills: HTML5 / PHP / CSS3
  • -
  • Client: Google
  • -
- - - - - -
- - -
- -
-
- -
\ No newline at end of file diff --git a/themes/pmem-hugo/static/include/campaign-monitor/class/base_classes.php b/themes/pmem-hugo/static/include/campaign-monitor/class/base_classes.php deleted file mode 100644 index 264b7ea372..0000000000 --- a/themes/pmem-hugo/static/include/campaign-monitor/class/base_classes.php +++ /dev/null @@ -1,287 +0,0 @@ -response = $response; - $this->http_status_code = $code; - } - - /** - * Can be used to check if a call to the api resulted in a successful response. - * @return boolean False if the call failed. Check the response property for the failure reason. - * @access public - */ - function was_successful() { - return $this->http_status_code >= 200 && $this->http_status_code < 300; - } -} - -/** - * Base class for the create send PHP wrapper. - * This class includes functions to access the general data, - * i.e timezones, clients and getting your API Key from username and password - * @author tobyb - * - */ -class CS_REST_Wrapper_Base { - /** - * The protocol to use while accessing the api - * @var string http or https - * @access private - */ - var $_protocol; - - /** - * The base route of the create send api. - * @var string - * @access private - */ - var $_base_route; - - /** - * The serialiser to use for serialisation and deserialisation - * of API request and response data - * @var CS_REST_JsonSerialiser or CS_REST_XmlSerialiser - * @access private - */ - var $_serialiser; - - /** - * The transport to use to send API requests - * @var CS_REST_CurlTransport or CS_REST_SocketTransport or your own custom transport. - * @access private - */ - var $_transport; - - /** - * The logger to use for debugging of all API requests - * @var CS_REST_Log - * @access private - */ - var $_log; - - /** - * The default options to use for each API request. - * These can be overridden by passing in an array as the call_options argument - * to a single api request. - * Valid options are: - * - * deserialise boolean: - * Set this to false if you want to get the raw response. - * This can be useful if your passing json directly to javascript. - * - * While there are clearly other options there is no need to change them. - * @var array - * @access private - */ - var $_default_call_options; - - /** - * Constructor. - * @param $auth_details array Authentication details to use for API calls. - * This array must take one of the following forms: - * If using OAuth to authenticate: - * array( - * 'access_token' => 'your access token', - * 'refresh_token' => 'your refresh token') - * - * Or if using an API key: - * array('api_key' => 'your api key') - * - * Note that this method will continue to work in the deprecated - * case when $auth_details is passed in as a string containing an - * API key. - * @param $protocol string The protocol to use for requests (http|https) - * @param $debug_level int The level of debugging required CS_REST_LOG_NONE | CS_REST_LOG_ERROR | CS_REST_LOG_WARNING | CS_REST_LOG_VERBOSE - * @param $host string The host to send API requests to. There is no need to change this - * @param $log CS_REST_Log The logger to use. Used for dependency injection - * @param $serialiser The serialiser to use. Used for dependency injection - * @param $transport The transport to use. Used for dependency injection - * @access public - */ - function CS_REST_Wrapper_Base( - $auth_details, - $protocol = 'https', - $debug_level = CS_REST_LOG_NONE, - $host = CS_HOST, - $log = NULL, - $serialiser = NULL, - $transport = NULL) { - - if (is_string($auth_details)) { - # If $auth_details is a string, assume it is an API key - $auth_details = array('api_key' => $auth_details); - } - - $this->_log = is_null($log) ? new CS_REST_Log($debug_level) : $log; - - $this->_protocol = $protocol; - $this->_base_route = $protocol.'://'.$host.'/api/v3.1/'; - - $this->_log->log_message('Creating wrapper for '.$this->_base_route, get_class($this), CS_REST_LOG_VERBOSE); - - $this->_transport = is_null($transport) ? - CS_REST_TRANSPORT_get_available($this->is_secure(), $this->_log) : - $transport; - - $transport_type = method_exists($this->_transport, 'get_type') ? $this->_transport->get_type() : 'Unknown'; - $this->_log->log_message('Using '.$transport_type.' for transport', get_class($this), CS_REST_LOG_WARNING); - - $this->_serialiser = is_null($serialiser) ? - CS_REST_SERIALISATION_get_available($this->_log) : $serialiser; - - $this->_log->log_message('Using '.$this->_serialiser->get_type().' json serialising', get_class($this), CS_REST_LOG_WARNING); - - $this->_default_call_options = array ( - 'authdetails' => $auth_details, - 'userAgent' => 'CS_REST_Wrapper v'.CS_REST_WRAPPER_VERSION. - ' PHPv'.phpversion().' over '.$transport_type.' with '.$this->_serialiser->get_type(), - 'contentType' => 'application/json; charset=utf-8', - 'deserialise' => true, - 'host' => $host, - 'protocol' => $protocol - ); - } - - /** - * Refresh the current OAuth token using the current refresh token. - * @access public - */ - function refresh_token() { - if (!isset($this->_default_call_options['authdetails']) || - !isset($this->_default_call_options['authdetails']['refresh_token'])) { - trigger_error( - 'Error refreshing token. There is no refresh token set on this object.', - E_USER_ERROR); - return array(NULL, NULL, NULL); - } - $body = "grant_type=refresh_token&refresh_token=".urlencode( - $this->_default_call_options['authdetails']['refresh_token']); - $options = array('contentType' => 'application/x-www-form-urlencoded'); - $wrap = new CS_REST_Wrapper_Base( - NULL, 'https', CS_REST_LOG_NONE, CS_HOST, NULL, - new CS_REST_DoNothingSerialiser(), NULL); - - $result = $wrap->post_request(CS_OAUTH_TOKEN_URI, $body, $options); - if ($result->was_successful()) { - $access_token = $result->response->access_token; - $expires_in = $result->response->expires_in; - $refresh_token = $result->response->refresh_token; - $this->_default_call_options['authdetails'] = array( - 'access_token' => $access_token, - 'refresh_token' => $refresh_token - ); - return array($access_token, $expires_in, $refresh_token); - } else { - trigger_error( - 'Error refreshing token. '.$result->response->error.': '.$result->response->error_description, - E_USER_ERROR); - return array(NULL, NULL, NULL); - } - } - - /** - * @return boolean True if the wrapper is using SSL. - * @access public - */ - function is_secure() { - return $this->_protocol === 'https'; - } - - function put_request($route, $data, $call_options = array()) { - return $this->_call($call_options, CS_REST_PUT, $route, $data); - } - - function post_request($route, $data, $call_options = array()) { - return $this->_call($call_options, CS_REST_POST, $route, $data); - } - - function delete_request($route, $call_options = array()) { - return $this->_call($call_options, CS_REST_DELETE, $route); - } - - function get_request($route, $call_options = array()) { - return $this->_call($call_options, CS_REST_GET, $route); - } - - function get_request_paged($route, $page_number, $page_size, $order_field, $order_direction, - $join_char = '&') { - if(!is_null($page_number)) { - $route .= $join_char.'page='.$page_number; - $join_char = '&'; - } - - if(!is_null($page_size)) { - $route .= $join_char.'pageSize='.$page_size; - $join_char = '&'; - } - - if(!is_null($order_field)) { - $route .= $join_char.'orderField='.$order_field; - $join_char = '&'; - } - - if(!is_null($order_direction)) { - $route .= $join_char.'orderDirection='.$order_direction; - $join_char = '&'; - } - - return $this->get_request($route); - } - - /** - * Internal method to make a general API request based on the provided options - * @param $call_options - * @access private - */ - function _call($call_options, $method, $route, $data = NULL) { - $call_options['route'] = $route; - $call_options['method'] = $method; - - if(!is_null($data)) { - $call_options['data'] = $this->_serialiser->serialise($data); - } - - $call_options = array_merge($this->_default_call_options, $call_options); - $this->_log->log_message('Making '.$call_options['method'].' call to: '.$call_options['route'], get_class($this), CS_REST_LOG_WARNING); - - $call_result = $this->_transport->make_call($call_options); - - $this->_log->log_message('Call result:
'.var_export($call_result, true).'
', - get_class($this), CS_REST_LOG_VERBOSE); - - if($call_options['deserialise']) { - $call_result['response'] = $this->_serialiser->deserialise($call_result['response']); - } - - return new CS_REST_Wrapper_Result($call_result['response'], $call_result['code']); - } -} diff --git a/themes/pmem-hugo/static/include/campaign-monitor/class/log.php b/themes/pmem-hugo/static/include/campaign-monitor/class/log.php deleted file mode 100644 index 7a4a4ff0e3..0000000000 --- a/themes/pmem-hugo/static/include/campaign-monitor/class/log.php +++ /dev/null @@ -1,19 +0,0 @@ -_level = $level; - } - - function log_message($message, $module, $level) { - if($this->_level >= $level) { - echo date('G:i:s').' - '.$module.': '.$message."
\n"; - } - } -} \ No newline at end of file diff --git a/themes/pmem-hugo/static/include/campaign-monitor/class/serialisation.php b/themes/pmem-hugo/static/include/campaign-monitor/class/serialisation.php deleted file mode 100644 index 8b218a7f1a..0000000000 --- a/themes/pmem-hugo/static/include/campaign-monitor/class/serialisation.php +++ /dev/null @@ -1,129 +0,0 @@ -log_message('Getting serialiser', __FUNCTION__, CS_REST_LOG_VERBOSE); - if(function_exists('json_decode') && function_exists('json_encode')) { - return new CS_REST_NativeJsonSerialiser($log); - } else { - return new CS_REST_ServicesJsonSerialiser($log); - } -} -class CS_REST_BaseSerialiser { - - var $_log; - - function CS_REST_BaseSerialiser($log) { - $this->_log = $log; - } - - /** - * Recursively ensures that all data values are utf-8 encoded. - * @param array $data All values of this array are checked for utf-8 encoding. - */ - function check_encoding($data) { - - foreach($data as $k => $v) { - // If the element is a sub-array then recusively encode the array - if(is_array($v)) { - $data[$k] = $this->check_encoding($v); - // Otherwise if the element is a string then we need to check the encoding - } else if(is_string($v)) { - if((function_exists('mb_detect_encoding') && mb_detect_encoding($v) !== 'UTF-8') || - (function_exists('mb_check_encoding') && !mb_check_encoding($v, 'UTF-8'))) { - // The string is using some other encoding, make sure we utf-8 encode - $v = utf8_encode($v); - } - - $data[$k] = $v; - } - } - - return $data; - } -} - -class CS_REST_DoNothingSerialiser extends CS_REST_BaseSerialiser { - function CS_REST_DoNothingSerialiser() {} - function get_type() { return 'do_nothing'; } - function serialise($data) { return $data; } - function deserialise($text) { - $data = json_decode($text); - return is_null($data) ? $text : $data; - } - function check_encoding($data) { return $data; } -} - -class CS_REST_NativeJsonSerialiser extends CS_REST_BaseSerialiser { - - function CS_REST_NativeJsonSerialiser($log) { - $this->CS_REST_BaseSerialiser($log); - } - - function get_format() { - return 'json'; - } - - function get_type() { - return 'native'; - } - - function serialise($data) { - if(is_null($data) || $data == '') return ''; - return json_encode($this->check_encoding($data)); - } - - function deserialise($text) { - $data = json_decode($text); - - return $this->strip_surrounding_quotes(is_null($data) ? $text : $data); - } - - /** - * We've had sporadic reports of people getting ID's from create routes with the surrounding quotes present. - * There is no case where these should be present. Just get rid of it. - */ - function strip_surrounding_quotes($data) { - if(is_string($data)) { - return trim($data, '"'); - } - - return $data; - } -} - -class CS_REST_ServicesJsonSerialiser extends CS_REST_BaseSerialiser { - - var $_serialiser; - - function CS_REST_ServicesJsonSerialiser($log) { - $this->CS_REST_BaseSerialiser($log); - $this->_serialiser = new Services_JSON(); - } - - function get_content_type() { - return 'application/json'; - } - - function get_format() { - return 'json'; - } - - function get_type() { - return 'services_json'; - } - - function serialise($data) { - if(is_null($data) || $data == '') return ''; - return $this->_serialiser->encode($this->check_encoding($data)); - } - - function deserialise($text) { - $data = $this->_serialiser->decode($text); - - return is_null($data) ? $text : $data; - } -} diff --git a/themes/pmem-hugo/static/include/campaign-monitor/class/services_json.php b/themes/pmem-hugo/static/include/campaign-monitor/class/services_json.php deleted file mode 100644 index a73cfad2a8..0000000000 --- a/themes/pmem-hugo/static/include/campaign-monitor/class/services_json.php +++ /dev/null @@ -1,782 +0,0 @@ - - * @author Matt Knapp - * @author Brett Stimmerman - * @copyright 2005 Michal Migurski - * @version CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $ - * @license http://www.opensource.org/licenses/bsd-license.php - * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198 - */ - -/** - * Marker constant for Services_JSON::decode(), used to flag stack state - */ -define('SERVICES_JSON_SLICE', 1); - -/** - * Marker constant for Services_JSON::decode(), used to flag stack state - */ -define('SERVICES_JSON_IN_STR', 2); - -/** - * Marker constant for Services_JSON::decode(), used to flag stack state - */ -define('SERVICES_JSON_IN_ARR', 3); - -/** - * Marker constant for Services_JSON::decode(), used to flag stack state - */ -define('SERVICES_JSON_IN_OBJ', 4); - -/** - * Marker constant for Services_JSON::decode(), used to flag stack state - */ -define('SERVICES_JSON_IN_CMT', 5); - -/** - * Behavior switch for Services_JSON::decode() - */ -define('SERVICES_JSON_LOOSE_TYPE', 16); - -/** - * Behavior switch for Services_JSON::decode() - */ -define('SERVICES_JSON_SUPPRESS_ERRORS', 32); - -/** - * Converts to and from JSON format. - * - * Brief example of use: - * - * - * // create a new instance of Services_JSON - * $json = new Services_JSON(); - * - * // convert a complexe value to JSON notation, and send it to the browser - * $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4))); - * $output = $json->encode($value); - * - * print($output); - * // prints: ["foo","bar",[1,2,"baz"],[3,[4]]] - * - * // accept incoming POST data, assumed to be in JSON notation - * $input = file_get_contents('php://input', 1000000); - * $value = $json->decode($input); - * - */ -class Services_JSON -{ - /** - * constructs a new JSON instance - * - * @param int $use object behavior flags; combine with boolean-OR - * - * possible values: - * - SERVICES_JSON_LOOSE_TYPE: loose typing. - * "{...}" syntax creates associative arrays - * instead of objects in decode(). - * - SERVICES_JSON_SUPPRESS_ERRORS: error suppression. - * Values which can't be encoded (e.g. resources) - * appear as NULL instead of throwing errors. - * By default, a deeply-nested resource will - * bubble up with an error, so all return values - * from encode() should be checked with isError() - */ - function Services_JSON($use = 0) - { - $this->use = $use; - } - - /** - * convert a string from one UTF-16 char to one UTF-8 char - * - * Normally should be handled by mb_convert_encoding, but - * provides a slower PHP-only method for installations - * that lack the multibye string extension. - * - * @param string $utf16 UTF-16 character - * @return string UTF-8 character - * @access private - */ - function utf162utf8($utf16) - { - // oh please oh please oh please oh please oh please - if(function_exists('mb_convert_encoding')) { - return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16'); - } - - $bytes = (ord($utf16{0}) << 8) | ord($utf16{1}); - - switch(true) { - case ((0x7F & $bytes) == $bytes): - // this case should never be reached, because we are in ASCII range - // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return chr(0x7F & $bytes); - - case (0x07FF & $bytes) == $bytes: - // return a 2-byte UTF-8 character - // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return chr(0xC0 | (($bytes >> 6) & 0x1F)) - . chr(0x80 | ($bytes & 0x3F)); - - case (0xFFFF & $bytes) == $bytes: - // return a 3-byte UTF-8 character - // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return chr(0xE0 | (($bytes >> 12) & 0x0F)) - . chr(0x80 | (($bytes >> 6) & 0x3F)) - . chr(0x80 | ($bytes & 0x3F)); - } - - // ignoring UTF-32 for now, sorry - return ''; - } - - /** - * convert a string from one UTF-8 char to one UTF-16 char - * - * Normally should be handled by mb_convert_encoding, but - * provides a slower PHP-only method for installations - * that lack the multibye string extension. - * - * @param string $utf8 UTF-8 character - * @return string UTF-16 character - * @access private - */ - function utf82utf16($utf8) - { - // oh please oh please oh please oh please oh please - if(function_exists('mb_convert_encoding')) { - return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8'); - } - - switch(strlen($utf8)) { - case 1: - // this case should never be reached, because we are in ASCII range - // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return $utf8; - - case 2: - // return a UTF-16 character from a 2-byte UTF-8 char - // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return chr(0x07 & (ord($utf8{0}) >> 2)) - . chr((0xC0 & (ord($utf8{0}) << 6)) - | (0x3F & ord($utf8{1}))); - - case 3: - // return a UTF-16 character from a 3-byte UTF-8 char - // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return chr((0xF0 & (ord($utf8{0}) << 4)) - | (0x0F & (ord($utf8{1}) >> 2))) - . chr((0xC0 & (ord($utf8{1}) << 6)) - | (0x7F & ord($utf8{2}))); - } - - // ignoring UTF-32 for now, sorry - return ''; - } - - /** - * encodes an arbitrary variable into JSON format - * - * @param mixed $var any number, boolean, string, array, or object to be encoded. - * see argument 1 to Services_JSON() above for array-parsing behavior. - * if var is a strng, note that encode() always expects it - * to be in ASCII or UTF-8 format! - * - * @return mixed JSON string representation of input var or an error if a problem occurs - * @access public - */ - function encode($var) - { - switch (gettype($var)) { - case 'boolean': - return $var ? 'true' : 'false'; - - case 'NULL': - return 'null'; - - case 'integer': - return (int) $var; - - case 'double': - case 'float': - return (float) $var; - - case 'string': - // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT - $ascii = ''; - $strlen_var = strlen($var); - - /* - * Iterate over every character in the string, - * escaping with a slash or encoding to UTF-8 where necessary - */ - for ($c = 0; $c < $strlen_var; ++$c) { - - $ord_var_c = ord($var{$c}); - - switch (true) { - case $ord_var_c == 0x08: - $ascii .= '\b'; - break; - case $ord_var_c == 0x09: - $ascii .= '\t'; - break; - case $ord_var_c == 0x0A: - $ascii .= '\n'; - break; - case $ord_var_c == 0x0C: - $ascii .= '\f'; - break; - case $ord_var_c == 0x0D: - $ascii .= '\r'; - break; - - case $ord_var_c == 0x22: - case $ord_var_c == 0x2F: - case $ord_var_c == 0x5C: - // double quote, slash, slosh - $ascii .= '\\'.$var{$c}; - break; - - case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)): - // characters U-00000000 - U-0000007F (same as ASCII) - $ascii .= $var{$c}; - break; - - case (($ord_var_c & 0xE0) == 0xC0): - // characters U-00000080 - U-000007FF, mask 110XXXXX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $char = pack('C*', $ord_var_c, ord($var{$c + 1})); - $c += 1; - $utf16 = $this->utf82utf16($char); - $ascii .= sprintf('\u%04s', bin2hex($utf16)); - break; - - case (($ord_var_c & 0xF0) == 0xE0): - // characters U-00000800 - U-0000FFFF, mask 1110XXXX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $char = pack('C*', $ord_var_c, - ord($var{$c + 1}), - ord($var{$c + 2})); - $c += 2; - $utf16 = $this->utf82utf16($char); - $ascii .= sprintf('\u%04s', bin2hex($utf16)); - break; - - case (($ord_var_c & 0xF8) == 0xF0): - // characters U-00010000 - U-001FFFFF, mask 11110XXX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $char = pack('C*', $ord_var_c, - ord($var{$c + 1}), - ord($var{$c + 2}), - ord($var{$c + 3})); - $c += 3; - $utf16 = $this->utf82utf16($char); - $ascii .= sprintf('\u%04s', bin2hex($utf16)); - break; - - case (($ord_var_c & 0xFC) == 0xF8): - // characters U-00200000 - U-03FFFFFF, mask 111110XX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $char = pack('C*', $ord_var_c, - ord($var{$c + 1}), - ord($var{$c + 2}), - ord($var{$c + 3}), - ord($var{$c + 4})); - $c += 4; - $utf16 = $this->utf82utf16($char); - $ascii .= sprintf('\u%04s', bin2hex($utf16)); - break; - - case (($ord_var_c & 0xFE) == 0xFC): - // characters U-04000000 - U-7FFFFFFF, mask 1111110X - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $char = pack('C*', $ord_var_c, - ord($var{$c + 1}), - ord($var{$c + 2}), - ord($var{$c + 3}), - ord($var{$c + 4}), - ord($var{$c + 5})); - $c += 5; - $utf16 = $this->utf82utf16($char); - $ascii .= sprintf('\u%04s', bin2hex($utf16)); - break; - } - } - - return '"'.$ascii.'"'; - - case 'array': - /* - * As per JSON spec if any array key is not an integer - * we must treat the the whole array as an object. We - * also try to catch a sparsely populated associative - * array with numeric keys here because some JS engines - * will create an array with empty indexes up to - * max_index which can cause memory issues and because - * the keys, which may be relevant, will be remapped - * otherwise. - * - * As per the ECMA and JSON specification an object may - * have any string as a property. Unfortunately due to - * a hole in the ECMA specification if the key is a - * ECMA reserved word or starts with a digit the - * parameter is only accessible using ECMAScript's - * bracket notation. - */ - - // treat as a JSON object - if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) { - $properties = array_map(array($this, 'name_value'), - array_keys($var), - array_values($var)); - - foreach($properties as $property) { - if($this->isError($property)) { - return $property; - } - } - - return '{' . join(',', $properties) . '}'; - } - - // treat it like a regular array - $elements = array_map(array($this, 'encode'), $var); - - foreach($elements as $element) { - if($this->isError($element)) { - return $element; - } - } - - return '[' . join(',', $elements) . ']'; - - case 'object': - $vars = get_object_vars($var); - - $properties = array_map(array($this, 'name_value'), - array_keys($vars), - array_values($vars)); - - foreach($properties as $property) { - if($this->isError($property)) { - return $property; - } - } - - return '{' . join(',', $properties) . '}'; - - default: - return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS) - ? 'null' - : new Services_JSON_Error(gettype($var)." can not be encoded as JSON string"); - } - } - - /** - * array-walking function for use in generating JSON-formatted name-value pairs - * - * @param string $name name of key to use - * @param mixed $value reference to an array element to be encoded - * - * @return string JSON-formatted name-value pair, like '"name":value' - * @access private - */ - function name_value($name, $value) - { - $encoded_value = $this->encode($value); - - if($this->isError($encoded_value)) { - return $encoded_value; - } - - return $this->encode(strval($name)) . ':' . $encoded_value; - } - - /** - * reduce a string by removing leading and trailing comments and whitespace - * - * @param $str string string value to strip of comments and whitespace - * - * @return string string value stripped of comments and whitespace - * @access private - */ - function reduce_string($str) - { - $str = preg_replace(array( - - // eliminate single line comments in '// ...' form - '#^\s*//(.+)$#m', - - // eliminate multi-line comments in '/* ... */' form, at start of string - '#^\s*/\*(.+)\*/#Us', - - // eliminate multi-line comments in '/* ... */' form, at end of string - '#/\*(.+)\*/\s*$#Us' - - ), '', $str); - - // eliminate extraneous space - return trim($str); - } - - /** - * decodes a JSON string into appropriate variable - * - * @param string $str JSON-formatted string - * - * @return mixed number, boolean, string, array, or object - * corresponding to given JSON input string. - * See argument 1 to Services_JSON() above for object-output behavior. - * Note that decode() always returns strings - * in ASCII or UTF-8 format! - * @access public - */ - function decode($str) - { - $str = $this->reduce_string($str); - - switch (strtolower($str)) { - case 'true': - return true; - - case 'false': - return false; - - case 'null': - return null; - - default: - $m = array(); - - if (is_numeric($str)) { - // Lookie-loo, it's a number - - // This would work on its own, but I'm trying to be - // good about returning integers where appropriate: - // return (float)$str; - - // Return float or int, as appropriate - return ((float)$str == (integer)$str) - ? (integer)$str - : (float)$str; - - } elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) { - // STRINGS RETURNED IN UTF-8 FORMAT - $delim = substr($str, 0, 1); - $chrs = substr($str, 1, -1); - $utf8 = ''; - $strlen_chrs = strlen($chrs); - - for ($c = 0; $c < $strlen_chrs; ++$c) { - - $substr_chrs_c_2 = substr($chrs, $c, 2); - $ord_chrs_c = ord($chrs{$c}); - - switch (true) { - case $substr_chrs_c_2 == '\b': - $utf8 .= chr(0x08); - ++$c; - break; - case $substr_chrs_c_2 == '\t': - $utf8 .= chr(0x09); - ++$c; - break; - case $substr_chrs_c_2 == '\n': - $utf8 .= chr(0x0A); - ++$c; - break; - case $substr_chrs_c_2 == '\f': - $utf8 .= chr(0x0C); - ++$c; - break; - case $substr_chrs_c_2 == '\r': - $utf8 .= chr(0x0D); - ++$c; - break; - - case $substr_chrs_c_2 == '\\"': - case $substr_chrs_c_2 == '\\\'': - case $substr_chrs_c_2 == '\\\\': - case $substr_chrs_c_2 == '\\/': - if (($delim == '"' && $substr_chrs_c_2 != '\\\'') || - ($delim == "'" && $substr_chrs_c_2 != '\\"')) { - $utf8 .= $chrs{++$c}; - } - break; - - case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)): - // single, escaped unicode character - $utf16 = chr(hexdec(substr($chrs, ($c + 2), 2))) - . chr(hexdec(substr($chrs, ($c + 4), 2))); - $utf8 .= $this->utf162utf8($utf16); - $c += 5; - break; - - case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F): - $utf8 .= $chrs{$c}; - break; - - case ($ord_chrs_c & 0xE0) == 0xC0: - // characters U-00000080 - U-000007FF, mask 110XXXXX - //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $utf8 .= substr($chrs, $c, 2); - ++$c; - break; - - case ($ord_chrs_c & 0xF0) == 0xE0: - // characters U-00000800 - U-0000FFFF, mask 1110XXXX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $utf8 .= substr($chrs, $c, 3); - $c += 2; - break; - - case ($ord_chrs_c & 0xF8) == 0xF0: - // characters U-00010000 - U-001FFFFF, mask 11110XXX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $utf8 .= substr($chrs, $c, 4); - $c += 3; - break; - - case ($ord_chrs_c & 0xFC) == 0xF8: - // characters U-00200000 - U-03FFFFFF, mask 111110XX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $utf8 .= substr($chrs, $c, 5); - $c += 4; - break; - - case ($ord_chrs_c & 0xFE) == 0xFC: - // characters U-04000000 - U-7FFFFFFF, mask 1111110X - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $utf8 .= substr($chrs, $c, 6); - $c += 5; - break; - - } - - } - - return $utf8; - - } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) { - // array, or object notation - - if ($str{0} == '[') { - $stk = array(SERVICES_JSON_IN_ARR); - $arr = array(); - } else { - if ($this->use & SERVICES_JSON_LOOSE_TYPE) { - $stk = array(SERVICES_JSON_IN_OBJ); - $obj = array(); - } else { - $stk = array(SERVICES_JSON_IN_OBJ); - $obj = new stdClass(); - } - } - - array_push($stk, array('what' => SERVICES_JSON_SLICE, - 'where' => 0, - 'delim' => false)); - - $chrs = substr($str, 1, -1); - $chrs = $this->reduce_string($chrs); - - if ($chrs == '') { - if (reset($stk) == SERVICES_JSON_IN_ARR) { - return $arr; - - } else { - return $obj; - - } - } - - //print("\nparsing {$chrs}\n"); - - $strlen_chrs = strlen($chrs); - - for ($c = 0; $c <= $strlen_chrs; ++$c) { - - $top = end($stk); - $substr_chrs_c_2 = substr($chrs, $c, 2); - - if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) { - // found a comma that is not inside a string, array, etc., - // OR we've reached the end of the character list - $slice = substr($chrs, $top['where'], ($c - $top['where'])); - array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false)); - //print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); - - if (reset($stk) == SERVICES_JSON_IN_ARR) { - // we are in an array, so just push an element onto the stack - array_push($arr, $this->decode($slice)); - - } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) { - // we are in an object, so figure - // out the property name and set an - // element in an associative array, - // for now - $parts = array(); - - if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) { - // "name":value pair - $key = $this->decode($parts[1]); - $val = $this->decode($parts[2]); - - if ($this->use & SERVICES_JSON_LOOSE_TYPE) { - $obj[$key] = $val; - } else { - $obj->$key = $val; - } - } elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) { - // name:value pair, where name is unquoted - $key = $parts[1]; - $val = $this->decode($parts[2]); - - if ($this->use & SERVICES_JSON_LOOSE_TYPE) { - $obj[$key] = $val; - } else { - $obj->$key = $val; - } - } - - } - - } elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) { - // found a quote, and we are not inside a string - array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c})); - //print("Found start of string at {$c}\n"); - - } elseif (($chrs{$c} == $top['delim']) && - ($top['what'] == SERVICES_JSON_IN_STR) && - ((strlen(substr($chrs, 0, $c)) - strlen(rtrim(substr($chrs, 0, $c), '\\'))) % 2 != 1)) { - // found a quote, we're in a string, and it's not escaped - // we know that it's not escaped becase there is _not_ an - // odd number of backslashes at the end of the string so far - array_pop($stk); - //print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n"); - - } elseif (($chrs{$c} == '[') && - in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { - // found a left-bracket, and we are in an array, object, or slice - array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false)); - //print("Found start of array at {$c}\n"); - - } elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) { - // found a right-bracket, and we're in an array - array_pop($stk); - //print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); - - } elseif (($chrs{$c} == '{') && - in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { - // found a left-brace, and we are in an array, object, or slice - array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false)); - //print("Found start of object at {$c}\n"); - - } elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) { - // found a right-brace, and we're in an object - array_pop($stk); - //print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); - - } elseif (($substr_chrs_c_2 == '/*') && - in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { - // found a comment start, and we are in an array, object, or slice - array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false)); - $c++; - //print("Found start of comment at {$c}\n"); - - } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) { - // found a comment end, and we're in one now - array_pop($stk); - $c++; - - for ($i = $top['where']; $i <= $c; ++$i) - $chrs = substr_replace($chrs, ' ', $i, 1); - - //print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); - - } - - } - - if (reset($stk) == SERVICES_JSON_IN_ARR) { - return $arr; - - } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) { - return $obj; - - } - - } - } - } - - function isError($data, $code = null) - { - if (is_object($data) && (get_class($data) == 'services_json_error' || - is_subclass_of($data, 'services_json_error'))) { - return true; - } - - return false; - } -} - -class Services_JSON_Error -{ - function Services_JSON_Error($message = 'unknown error', $code = null, - $mode = null, $options = null, $userinfo = null) - { - - } -} - -?> diff --git a/themes/pmem-hugo/static/include/campaign-monitor/class/transport.php b/themes/pmem-hugo/static/include/campaign-monitor/class/transport.php deleted file mode 100644 index 5452f4d686..0000000000 --- a/themes/pmem-hugo/static/include/campaign-monitor/class/transport.php +++ /dev/null @@ -1,335 +0,0 @@ -log_message('No transport is available', __FUNCTION__, CS_REST_LOG_ERROR); - trigger_error('No transport is available.'. - ($requires_ssl ? ' Try using non-secure (http) mode or ' : ' Please '). - 'ensure the cURL extension is loaded', E_USER_ERROR); - } -} -function CS_REST_TRANSPORT_can_use_raw_socket($requires_ssl) { - if(function_exists('fsockopen')) { - if($requires_ssl) { - return extension_loaded('openssl'); - } - - return true; - } - - return false; -} -class CS_REST_BaseTransport { - - var $_log; - - function CS_REST_BaseTransport($log) { - $this->_log = $log; - } - - function split_and_inflate($response, $may_be_compressed) { - $ra = explode("\r\n\r\n", $response); - - $result = array_pop($ra); - $headers = array_pop($ra); - - if($may_be_compressed && preg_match('/^Content-Encoding:\s+gzip\s+$/im', $headers)) { - $original_length = strlen($response); - $result = gzinflate(substr($result, 10, -8)); - - $this->_log->log_message('Inflated gzipped response: '.$original_length.' bytes ->'. - strlen($result).' bytes', get_class(), CS_REST_LOG_VERBOSE); - } - - return array($headers, $result); - } -} -/** - * Provide HTTP request functionality via cURL extensions - * - * @author tobyb - * @since 1.0 - */ -class CS_REST_CurlTransport extends CS_REST_BaseTransport { - - var $_curl_zlib; - - function CS_REST_CurlTransport($log) { - $this->CS_REST_BaseTransport($log); - - $curl_version = curl_version(); - $this->_curl_zlib = isset($curl_version['libz_version']); - } - - /** - * @return string The type of transport used - */ - function get_type() { - return 'cURL'; - } - - function make_call($call_options) { - $ch = curl_init(); - - curl_setopt($ch, CURLOPT_URL, $call_options['route']); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch, CURLOPT_HEADER, true); - $headers = array(); - $headers[] = 'Content-Type: '.$call_options['contentType']; - - - if (array_key_exists('authdetails', $call_options) && - isset($call_options['authdetails'])) { - if (array_key_exists('username', $call_options['authdetails']) && - array_key_exists('password', $call_options['authdetails'])) { - # Authenticating using basic auth for retrieving user's API key. - curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); - curl_setopt($ch, CURLOPT_USERPWD, $call_options['authdetails']['username'].':'.$call_options['authdetails']['password']); - } elseif (array_key_exists('access_token', $call_options['authdetails'])) { - # Authenticating using OAuth. - $access_token = $call_options['authdetails']['access_token']; - $headers[] = 'Authorization: Bearer '.$access_token; - } elseif (array_key_exists('api_key', $call_options['authdetails'])) { - # Authenticating using an API key. - curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); - $api_key = $call_options['authdetails']['api_key']; - curl_setopt($ch, CURLOPT_USERPWD, $api_key.':nopass'); - } - } - - curl_setopt($ch, CURLOPT_USERAGENT, $call_options['userAgent']); - curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, CS_REST_SOCKET_TIMEOUT); - curl_setopt($ch, CURLOPT_TIMEOUT, CS_REST_CALL_TIMEOUT); - - $inflate_response = false; - if($this->_curl_zlib) { - $this->_log->log_message('curl+zlib support available. Requesting gzipped response.', - get_class($this), CS_REST_LOG_VERBOSE); - curl_setopt($ch, CURLOPT_ENCODING, 'gzip'); - } else if(function_exists('gzinflate')) { - $headers[] = 'Accept-Encoding: gzip'; - $inflate_response = true; - } - - if($call_options['protocol'] === 'https') { - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); - - if(strlen(ini_get('curl.cainfo')) === 0) { - curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__).'/cacert.pem'); - } - } - - switch($call_options['method']) { - case CS_REST_PUT: - curl_setopt($ch, CURLOPT_CUSTOMREQUEST, CS_REST_PUT); - $headers[] = 'Content-Length: '.strlen($call_options['data']); - curl_setopt($ch, CURLOPT_POSTFIELDS, $call_options['data']); - break; - case CS_REST_POST: - curl_setopt($ch, CURLOPT_POST, true); - curl_setopt($ch, CURLOPT_POSTFIELDS, isset($call_options['data']) ? $call_options['data'] : ''); - break; - case CS_REST_DELETE: - curl_setopt($ch, CURLOPT_CUSTOMREQUEST, CS_REST_DELETE); - break; - } - - if(count($headers) > 0) { - curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); - } - - $response = curl_exec($ch); - - if(!$response && $response !== '') { - $this->_log->log_message('Error making request with curl_error: '.curl_errno($ch), - get_class($this), CS_REST_LOG_ERROR); - trigger_error('Error making request with curl_error: '.curl_error($ch), E_USER_ERROR); - } - - list( $headers, $result ) = $this->split_and_inflate($response, $inflate_response); - - $this->_log->log_message('API Call Info for '.$call_options['method'].' '. - curl_getinfo($ch, CURLINFO_EFFECTIVE_URL).': '.curl_getinfo($ch, CURLINFO_SIZE_UPLOAD). - ' bytes uploaded. '.curl_getinfo($ch, CURLINFO_SIZE_DOWNLOAD).' bytes downloaded'. - ' Total time (seconds): '.curl_getinfo($ch, CURLINFO_TOTAL_TIME), - get_class($this), CS_REST_LOG_VERBOSE); - - $result = array( - 'code' => curl_getinfo($ch, CURLINFO_HTTP_CODE), - 'response' => $result - ); - - curl_close($ch); - - return $result; - } -} - -class CS_REST_SocketWrapper { - var $socket; - - function open($domain, $port) { - $this->socket = fsockopen($domain, $port, $errno, $errstr, CS_REST_SOCKET_TIMEOUT); - - if(!$this->socket) { - die('Error making request with '.$errno.': '.$errstr); - return false; - } else if(function_exists('stream_set_timeout')) { - stream_set_timeout($this->socket, CS_REST_SOCKET_TIMEOUT); - } - - return true; - } - - function write($data) { - fwrite($this->socket, $data); - } - - function read() { - ob_start(); - fpassthru($this->socket); - - return ob_get_clean(); - } - - function close() { - fclose($this->socket); - } -} - -class CS_REST_SocketTransport extends CS_REST_BaseTransport { - - var $_socket_wrapper; - - function CS_REST_SocketTransport($log, $socket_wrapper = NULL) { - $this->CS_REST_BaseTransport($log); - - if(is_null($socket_wrapper)) { - $socket_wrapper = new CS_REST_SocketWrapper(); - } - - $this->_socket_wrapper = $socket_wrapper; - } - - /** - * @return string The type of transport used - */ - function get_type() { - return 'Socket'; - } - - function make_call($call_options) { - $start_host = strpos($call_options['route'], $call_options['host']); - $host_len = strlen($call_options['host']); - - $domain = substr($call_options['route'], $start_host, $host_len); - $host = $domain; - $path = substr($call_options['route'], $start_host + $host_len); - $protocol = substr($call_options['route'], 0, $start_host); - $port = 80; - - $this->_log->log_message('Creating socket to '.$domain.' over '.$protocol.' for request to '.$path, - get_class($this), CS_REST_LOG_VERBOSE); - - if($protocol === 'https://') { - $domain = 'ssl://'.$domain; - $port = 443; - } - - if($this->_socket_wrapper->open($domain, $port)) { - $inflate_response = function_exists('gzinflate'); - - $request = $this->_build_request($call_options, $host, $path, $inflate_response); - $this->_log->log_message('Sending
'.$request.'
down the socket', - get_class($this), CS_REST_LOG_VERBOSE); - - $this->_socket_wrapper->write($request); - $response = $this->_socket_wrapper->read(); - $this->_socket_wrapper->close(); - - $this->_log->log_message('API Call Info for '.$call_options['method'].' '. - $call_options['route'].': '.strlen($request). - ' bytes uploaded. '.strlen($response).' bytes downloaded', - get_class($this), CS_REST_LOG_VERBOSE); - - list( $headers, $result ) = $this->split_and_inflate($response, $inflate_response); - - $this->_log->log_message('Received headers
'.$headers.'
', - get_class($this), CS_REST_LOG_VERBOSE); - - return array( - 'code' => $this->_get_status_code($headers), - 'response' => trim($result) - ); - } - } - - function _get_status_code($headers) { - if (preg_match('%^\s*HTTP/1\.1 (?P\d{3})%', $headers, $regs)) { - $this->_log->log_message('Got HTTP Status Code: '.$regs['code'], - get_class($this), CS_REST_LOG_VERBOSE); - return $regs['code']; - } - - $this->_log->log_message('Failed to get HTTP status code from request headers
'.$headers.'
', - get_class($this), CS_REST_LOG_ERROR); - trigger_error('Failed to get HTTP status code from request', E_USER_ERROR); - } - - function _build_request($call_options, $host, $path, $accept_gzip) { - $request_auth_details = ''; - - if (array_key_exists('authdetails', $call_options)) { - if (array_key_exists('username', $call_options['authdetails']) && - array_key_exists('password', $call_options['authdetails'])) { - # Authenticating using basic auth for retrieving user's API key. - $request_auth_details .= 'Authorization: Basic '.base64_encode($call_options['authdetails']['username'].':'.$call_options['authdetails']['password'])."\n"; - } elseif (array_key_exists('access_token', $call_options['authdetails'])) { - # Authenticating using OAuth. - $access_token = $call_options['authdetails']['access_token']; - $request_auth_details .= 'Authorization: Bearer '.$access_token."\n"; - } elseif (array_key_exists('api_key', $call_options['authdetails'])) { - # Authenticating using an API key. - $api_key = $call_options['authdetails']['api_key']; - $request_auth_details .= 'Authorization: Basic '.base64_encode($api_key.':nopass')."\n"; - } - } - - $request = -$call_options['method'].' '.$path." HTTP/1.1\n". -'Host: '.$host."\n". -$request_auth_details. -'User-Agent: '.$call_options['userAgent']."\n". -"Connection: Close\n". -'Content-Type: '.$call_options['contentType']."\n"; - - if($accept_gzip) { - $request .= -"Accept-Encoding: gzip\n"; - } - - if(isset($call_options['data'])) { - $request .= -'Content-Length: '.strlen($call_options['data'])."\n\n". -$call_options['data']; - } - - return $request."\n\n"; - } -} diff --git a/themes/pmem-hugo/static/include/campaign-monitor/csrest_subscribers.php b/themes/pmem-hugo/static/include/campaign-monitor/csrest_subscribers.php deleted file mode 100644 index ab5bdcee4c..0000000000 --- a/themes/pmem-hugo/static/include/campaign-monitor/csrest_subscribers.php +++ /dev/null @@ -1,230 +0,0 @@ - 'your access token', - * 'refresh_token' => 'your refresh token') - * - * Or if using an API key: - * array('api_key' => 'your api key') - * @param $protocol string The protocol to use for requests (http|https) - * @param $debug_level int The level of debugging required CS_REST_LOG_NONE | CS_REST_LOG_ERROR | CS_REST_LOG_WARNING | CS_REST_LOG_VERBOSE - * @param $host string The host to send API requests to. There is no need to change this - * @param $log CS_REST_Log The logger to use. Used for dependency injection - * @param $serialiser The serialiser to use. Used for dependency injection - * @param $transport The transport to use. Used for dependency injection - * @access public - */ - function CS_REST_Subscribers ( - $list_id, - $auth_details, - $protocol = 'https', - $debug_level = CS_REST_LOG_NONE, - $host = 'api.createsend.com', - $log = NULL, - $serialiser = NULL, - $transport = NULL) { - $this->CS_REST_Wrapper_Base($auth_details, $protocol, $debug_level, $host, $log, $serialiser, $transport); - $this->set_list_id($list_id); - - } - - /** - * Change the list id used for calls after construction - * @param $list_id - * @access public - */ - function set_list_id($list_id) { - $this->_subscribers_base_route = $this->_base_route.'subscribers/'.$list_id; - } - - /** - * Adds a new subscriber to the specified list - * @param array $subscriber The subscriber details to use during creation. - * This array should be of the form - * array ( - * 'EmailAddress' => The new subscribers email address - * 'Name' => The name of the new subscriber - * 'CustomFields' => array( - * array( - * 'Key' => The custom fields personalisation tag - * 'Value' => The value for this subscriber - * ) - * ) - * 'Resubscribe' => Whether we should resubscribe this subscriber if they already exist in the list - * 'RestartSubscriptionBasedAutoResponders' => Whether we should restart subscription based auto responders which are sent when the subscriber first subscribes to a list. - * ) - * @access public - * @return CS_REST_Wrapper_Result A successful response will be empty - */ - function add($subscriber) { - return $this->post_request($this->_subscribers_base_route.'.json', $subscriber); - } - - /** - * Updates an existing subscriber (email, name, state, or custom fields) in the specified list. - * The update is performed even for inactive subscribers, but will return an error in the event of the - * given email not existing in the list. - * @param string $email The email address of the susbcriber to be updated - * @param array $subscriber The subscriber details to use for the update. Empty parameters will remain unchanged - * This array should be of the form - * array ( - * 'EmailAddress' => The new email address - * 'Name' => The name of the subscriber - * 'CustomFields' => array( - * array( - * 'Key' => The custom fields personalisation tag - * 'Value' => The value for this subscriber - * 'Clear' => true/false (pass true to remove this custom field. in the case of a [multi-option, select many] field, pass an option in the 'Value' field to clear that option or leave Value blank to remove all options) - * ) - * ) - * 'Resubscribe' => Whether we should resubscribe this subscriber if they already exist in the list - * 'RestartSubscriptionBasedAutoResponders' => Whether we should restart subscription based auto responders which are sent when the subscriber first subscribes to a list. - * ) - * @access public - * @return CS_REST_Wrapper_Result A successful response will be empty - */ - function update($email, $subscriber) { - return $this->put_request($this->_subscribers_base_route.'.json?email='.urlencode($email), $subscriber); - } - - /** - * Imports an array of subscribers into the current list - * @param array $subscribers An array of subscribers to import. - * This array should be of the form - * array ( - * array ( - * 'EmailAddress' => The new subscribers email address - * 'Name' => The name of the new subscriber - * 'CustomFields' => array( - * array( - * 'Key' => The custom fields personalisation tag - * 'Value' => The value for this subscriber - * 'Clear' => true/false (pass true to remove this custom field. in the case of a [multi-option, select many] field, pass an option in the 'Value' field to clear that option or leave Value blank to remove all options) - * ) - * ) - * ) - * ) - * @param $resubscribe Whether we should resubscribe any existing subscribers - * @param $queueSubscriptionBasedAutoResponders By default, subscription based auto responders do not trigger during an import. Pass a value of true to override this behaviour - * @param $restartSubscriptionBasedAutoResponders By default, subscription based auto responders will not be restarted - * @access public - * @return CS_REST_Wrapper_Result A successful response will be an object of the form - * { - * 'TotalUniqueEmailsSubmitted' => The number of unique emails submitted in the call - * 'TotalExistingSubscribers' => The number of subscribers who already existed in the list - * 'TotalNewSubscribers' => The number of new subscriptions to the list - * 'DuplicateEmailsInSubmission' => array The emails which appeared more than once in the batch - * 'FailureDetails' => array ( - * { - * 'EmailAddress' => The email address which failed - * 'Code' => The Create Send API Error code - * 'Message' => The reason for the failure - * } - * ) - * } - * - */ - function import($subscribers, $resubscribe, $queueSubscriptionBasedAutoResponders = false, $restartSubscriptionBasedAutoResponders = false) { - $subscribers = array( - 'Resubscribe' => $resubscribe, - 'QueueSubscriptionBasedAutoResponders' => $queueSubscriptionBasedAutoResponders, - 'Subscribers' => $subscribers, - 'RestartSubscriptionBasedAutoresponders' => $restartSubscriptionBasedAutoResponders - ); - - return $this->post_request($this->_subscribers_base_route.'/import.json', $subscribers); - } - - /** - * Gets a subscriber details, including custom fields - * @access public - * @return CS_REST_Wrapper_Result A successful response will be an object of the form - * { - * 'EmailAddress' => The subscriber email address - * 'Name' => The subscribers name - * 'Date' => The date the subscriber was added to the list - * 'State' => The current state of the subscriber - * 'CustomFields' => array( - * { - * 'Key' => The custom fields personalisation tag - * 'Value' => The custom field value for this subscriber - * } - * ) - * } - */ - function get($email) { - return $this->get_request($this->_subscribers_base_route.'.json?email='.urlencode($email)); - } - - /** - * Gets the sending history to a specific subscriber - * @access public - * @return CS_REST_Wrapper_Result A successful response will be an object of the form - * array( - * { - * ID => The id of the email which was sent - * Type => 'Campaign' - * Name => The name of the email - * Actions => array( - * { - * Event => The type of action (Click, Open, Unsubscribe etc) - * Date => The date the event occurred - * IPAddress => The IP that the event originated from - * Detail => Any available details about the event i.e the URL for clicks - * } - * ) - * } - * ) - */ - function get_history($email) { - return $this->get_request($this->_subscribers_base_route.'/history.json?email='.urlencode($email)); - } - - /** - * Unsubscribes the given subscriber from the current list - * @param string $email The email address to unsubscribe - * @access public - * @return CS_REST_Wrapper_Result A successful response will be empty - */ - function unsubscribe($email) { - // We need to build the subscriber data structure. - $email = array( - 'EmailAddress' => $email - ); - - return $this->post_request($this->_subscribers_base_route.'/unsubscribe.json', $email); - } - - /** - * deletes the given subscriber from the current list - * @param string $email The email address to delete - * @access public - * @return CS_REST_Wrapper_Result A successful response will be empty - */ - function delete($email) { - return $this->delete_request($this->_subscribers_base_route.'.json?email='.urlencode($email)); - } -} \ No newline at end of file diff --git a/themes/pmem-hugo/static/include/form.php b/themes/pmem-hugo/static/include/form.php deleted file mode 100644 index aed76340cb..0000000000 --- a/themes/pmem-hugo/static/include/form.php +++ /dev/null @@ -1,411 +0,0 @@ - 'your-email@website.com', // Your Email Address - 'name' => 'Your Name' // Your Name - ); - - -/*------------------------------------------------- - Sender's Email ----------------------------------------------------*/ - -$fromemail = array( - 'email' => 'no-reply@website.com', // Company's Email Address (preferably currently used Domain Name) - 'name' => 'Company Name' // Company Name - ); - - -/*------------------------------------------------- - reCaptcha ----------------------------------------------------*/ - -// Add this only if you use reCaptcha with your Contact Forms -$recaptcha_secret = ''; // Your reCaptcha Secret - - -/*------------------------------------------------- - PHPMailer Initialization ----------------------------------------------------*/ - -$mail = new PHPMailer(); - -/* Add your SMTP Codes after this Line */ - - -// End of SMTP - - -/*------------------------------------------------- - Form Messages ----------------------------------------------------*/ - -$message = array( - 'success' => 'We have successfully received your Message and will get Back to you as soon as possible.', - 'error' => 'Email could not be sent due to some Unexpected Error. Please Try Again later.', - 'error_bot' => 'Bot Detected! Form could not be processed! Please Try Again!', - 'error_unexpected' => 'An unexpected error occured. Please Try Again later.', - 'recaptcha_invalid' => 'Captcha not Validated! Please Try Again!', - 'recaptcha_error' => 'Captcha not Submitted! Please Try Again.' -); - - -/*------------------------------------------------- - Blocked Words from Forms ----------------------------------------------------*/ - -$spam_keywords = array( - 'viagra', - 'cialis', - 'levitra' -); - - -/*------------------------------------------------- - Form Processor ----------------------------------------------------*/ - -if( $_SERVER['REQUEST_METHOD'] == 'POST' ) { - - $prefix = !empty( $_POST['prefix'] ) ? $_POST['prefix'] : ''; - $submits = $_POST; - $botpassed = false; - - - $message_form = !empty( $submits['message'] ) ? $submits['message'] : array(); - $message['success'] = !empty( $message_form['success'] ) ? $message_form['success'] : $message['success']; - $message['error'] = !empty( $message_form['error'] ) ? $message_form['error'] : $message['error']; - $message['error_bot'] = !empty( $message_form['error_bot'] ) ? $message_form['error_bot'] : $message['error_bot']; - $message['error_unexpected'] = !empty( $message_form['error_unexpected'] ) ? $message_form['error_unexpected'] : $message['error_unexpected']; - $message['recaptcha_invalid'] = !empty( $message_form['recaptcha_invalid'] ) ? $message_form['recaptcha_invalid'] : $message['recaptcha_invalid']; - $message['recaptcha_error'] = !empty( $message_form['recaptcha_error'] ) ? $message_form['recaptcha_error'] : $message['recaptcha_error']; - - - /*------------------------------------------------- - Bot Protection - ---------------------------------------------------*/ - - if( isset( $submits[ $prefix . 'botcheck' ] ) ) { - $botpassed = true; - } - - if( !empty( $submits[ $prefix . 'botcheck' ] ) ) { - $botpassed = false; - } - - if( $botpassed == false ) { - echo '{ "alert": "error", "message": "' . $message['error_bot'] . '" }'; - exit; - } - - - /*------------------------------------------------- - SPAM Protection - ---------------------------------------------------*/ - - function spam_keyword_check( $submitted, $spamwords ) { - if( is_array( $submitted ) ) { - return false; - } - if( !is_array( $spamwords ) ) $spamwords = array( $spamwords ); - foreach( $spamwords as $spamstring ) { - if( ( $position = stripos( $submitted, $spamstring ) ) !== false ) return $position; - } - return false; - } - - foreach( $submits as $spam_submit ) { - if( spam_keyword_check( $spam_submit, $spam_keywords ) ) { - // A successful message is displayed to the submitter that makes him think that the Form has been sent so that he cannot modify the keywords to prevent SPAM - echo '{ "alert": "success", "message": "' . $message['success'] . '" }'; - exit; - } - } - - - /*------------------------------------------------- - reCaptcha - ---------------------------------------------------*/ - - if( isset( $submits['g-recaptcha-response'] ) ) { - - $recaptcha_data = array( - 'secret' => $recaptcha_secret, - 'response' => $submits['g-recaptcha-response'] - ); - - $recap_verify = curl_init(); - curl_setopt( $recap_verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify" ); - curl_setopt( $recap_verify, CURLOPT_POST, true ); - curl_setopt( $recap_verify, CURLOPT_POSTFIELDS, http_build_query( $recaptcha_data ) ); - curl_setopt( $recap_verify, CURLOPT_SSL_VERIFYPEER, false ); - curl_setopt( $recap_verify, CURLOPT_RETURNTRANSFER, true ); - $recap_response = curl_exec( $recap_verify ); - - $g_response = json_decode( $recap_response ); - - if ( $g_response->success !== true ) { - echo '{ "alert": "error", "message": "' . $message['recaptcha_invalid'] . '" }'; - exit; - } - } - - $template = !empty( $submits['template'] ) ? $submits['template'] : 'html'; - $html_title = !empty( $submits['html_title'] ) ? $submits['html_title'] : 'Form Response'; - $forcerecap = ( !empty( $submits['force_recaptcha'] ) && $submits['force_recaptcha'] != 'false' ) ? true : false; - $replyto = !empty( $submits['replyto'] ) ? explode( ',', $submits['replyto'] ) : false; - - if( $forcerecap ) { - if( !isset( $submits['g-recaptcha-response'] ) ) { - echo '{ "alert": "error", "message": "' . $message['recaptcha_error'] . '" }'; - exit; - } - } - - /*------------------------------------------------- - Auto-Responders - ---------------------------------------------------*/ - - $autores = ( !empty( $submits['autoresponder'] ) && $submits['autoresponder'] != 'false' ) ? true : false; - $ar_subject = !empty( $submits['ar_subject'] ) ? $submits['ar_subject'] : 'Thanks for your Email'; - $ar_title = !empty( $submits['ar_title'] ) ? $submits['ar_title'] : 'Its so good to hear from You!'; - $ar_message = !empty( $submits['ar_message'] ) ? $submits['ar_message'] : 'Autoresponder Message'; - - preg_match_all('#\{(.*?)\}#', $ar_message, $ar_matches); - if( !empty( $ar_matches[1] ) ) { - foreach( $ar_matches[1] as $ar_key => $ar_value ) { - $ar_message = str_replace( '{' . $ar_value . '}' , $submits[ $ar_value ], $ar_message ); - } - } - - $ar_footer = !empty( $submits['ar_footer'] ) ? $submits['ar_footer'] : 'Copyrights © ' . date('Y') . ' SemiColonWeb. All Rights Reserved.'; - - $mail->Subject = !empty( $submits['subject'] ) ? $submits['subject'] : 'Form Response from your Website'; - $mail->SetFrom( $fromemail['email'] , $fromemail['name'] ); - - if( !empty( $replyto ) ) { - if( count( $replyto ) > 1 ) { - $replyto_e = $submits[ $replyto[0] ]; - $replyto_n = $submits[ $replyto[1] ]; - $mail->AddReplyTo( $replyto_e , $replyto_n ); - } elseif( count( $replyto ) == 1 ) { - $replyto_e = $submits[ $replyto[0] ]; - $mail->AddReplyTo( $replyto_e ); - } - } - - foreach( $toemails as $toemail ) { - $mail->AddAddress( $toemail['email'] , $toemail['name'] ); - } - - $unsets = array( 'prefix', 'subject', 'replyto', 'template', 'html_title', 'message', 'autoresponder', 'ar_subject', 'ar_title', 'ar_message', 'ar_footer', $prefix . 'botcheck', 'g-recaptcha-response', 'force_recaptcha', $prefix . 'submit' ); - - foreach( $unsets as $unset ) { - unset( $submits[ $unset ] ); - } - - $fields = array(); - - foreach( $submits as $name => $value ) { - - if( empty( $value ) ) continue; - - $name = str_replace( $prefix , '', $name ); - $name = mb_convert_case( $name, MB_CASE_TITLE, "UTF-8" ); - - if( is_array( $value ) ) { - $value = implode( ', ', $value ); - } - - $fields[$name] = nl2br( $value ); - - } - - $files = $_FILES; - - foreach( $files as $file => $filevalue ) { - - if( is_array( $filevalue['name'] ) ) { - - $filecount = count( $filevalue['name'] ); - - for( $f = 0; $f < $filecount; $f++ ) { - if ( isset( $_FILES[ $file ] ) && $_FILES[ $file ]['error'][ $f ] == UPLOAD_ERR_OK ) { - $mail->IsHTML(true); - $mail->AddAttachment( $_FILES[ $file ]['tmp_name'][ $f ], $_FILES[ $file ]['name'][ $f ] ); - } - } - - } else { - - if ( isset( $_FILES[ $file ] ) && $_FILES[ $file ]['error'] == UPLOAD_ERR_OK ) { - $mail->IsHTML(true); - $mail->AddAttachment( $_FILES[ $file ]['tmp_name'], $_FILES[ $file ]['name'] ); - } - - } - - } - - $response = array(); - - foreach( $fields as $fieldname => $fieldvalue ) { - if( $template == 'text' ) { - $response[] = $fieldname . ': ' . $fieldvalue; - } else { - $fieldname = ' - ' . $fieldname . ' - '; - $fieldvalue = ' - ' . $fieldvalue . ' - '; - $response[] = $fieldname . $fieldvalue; - } - } - - $referrer = $_SERVER['HTTP_REFERER'] ? '


This Form was submitted from: ' . $_SERVER['HTTP_REFERER'] : ''; - - $html_before = ' - - - -
- - - - -
- '; - - $html_after = '
-
'; - - if( $template == 'text' ) { - $body = implode( "
", $response ) . $referrer; - } else { - $html = $html_before . ' - - - - -
- ' . $html_title . ' -
- - - - ' . implode( '', $response ) . ' -
- - - - - - -
- - - - -
' . strip_tags( $referrer ) . '
-
- ' . $html_after; - - $body = $html; - } - - if( $autores && !empty( $replyto_e ) ) { - $autoresponder = new PHPMailer(); - - /* Add your Auto-Responder SMTP Codes after this Line */ - - - // End of Auto-Responder SMTP - - $autoresponder->SetFrom( $fromemail['email'] , $fromemail['name'] ); - if( !empty( $replyto_n ) ) { - $autoresponder->AddAddress( $replyto_e , $replyto_n ); - } else { - $autoresponder->AddAddress( $replyto_e ); - } - $autoresponder->Subject = $ar_subject; - - $ar_body = $html_before . ' - - - - -
- ' . $ar_title . ' -
- - - - - - -
' . $ar_message . '
- - - - - - -
- - - - -
' . $ar_footer . '
-
- ' . $html_after; - - $autoresponder->MsgHTML( $ar_body ); - } - - $mail->MsgHTML( $body ); - $mail->CharSet = "UTF-8"; - $sendEmail = $mail->Send(); - - if( $sendEmail == true ): - - if( $autores && !empty( $replyto_e ) ) { - $send_arEmail = $autoresponder->Send(); - } - - echo '{ "alert": "success", "message": "' . $message['success'] . '" }'; - else: - echo '{ "alert": "error", "message": "' . $message['error'] . '

Reason:
' . $mail->ErrorInfo . '" }'; - endif; - -} else { - echo '{ "alert": "error", "message": "' . $message['error_unexpected'] . '" }'; -} - -?> \ No newline at end of file diff --git a/themes/pmem-hugo/static/include/getresponse.php b/themes/pmem-hugo/static/include/getresponse.php deleted file mode 100644 index a2e8d365c4..0000000000 --- a/themes/pmem-hugo/static/include/getresponse.php +++ /dev/null @@ -1,15 +0,0 @@ -addContact(array( - 'name' => $name, - 'email' => $email, - 'dayOfCycle' => 0, - 'campaign' => array('campaignId' => 'your-campaign-id'), - 'ipAddress' => $_SERVER['REMOTE_ADDR'] -)); - -?> \ No newline at end of file diff --git a/themes/pmem-hugo/static/include/getresponse/GetResponseAPI3.class.php b/themes/pmem-hugo/static/include/getresponse/GetResponseAPI3.class.php deleted file mode 100644 index 2782e2fe8b..0000000000 --- a/themes/pmem-hugo/static/include/getresponse/GetResponseAPI3.class.php +++ /dev/null @@ -1,406 +0,0 @@ - - * @author Grzegorz Struczynski - * - * @see http://apidocs.getresponse.com/en/v3/resources - * @see https://github.com/GetResponse/getresponse-api-php - */ -class GetResponse -{ - - private $api_key; - private $api_url = 'https://api.getresponse.com/v3'; - private $timeout = 8; - public $http_status; - - /** - * X-Domain header value if empty header will be not provided - * @var string|null - */ - private $enterprise_domain = null; - - /** - * X-APP-ID header value if empty header will be not provided - * @var string|null - */ - private $app_id = null; - - /** - * Set api key and optionally API endpoint - * @param $api_key - * @param null $api_url - */ - public function __construct($api_key, $api_url = null) - { - $this->api_key = $api_key; - - if (!empty($api_url)) { - $this->api_url = $api_url; - } - } - - /** - * We can modify internal settings - * @param $key - * @param $value - */ - function __set($key, $value) - { - $this->{$key} = $value; - } - - /** - * get account details - * - * @return mixed - */ - public function accounts() - { - return $this->call('accounts'); - } - - /** - * @return mixed - */ - public function ping() - { - return $this->accounts(); - } - - /** - * Return all campaigns - * @return mixed - */ - public function getCampaigns() - { - return $this->call('campaigns'); - } - - /** - * get single campaign - * @param string $campaign_id retrieved using API - * @return mixed - */ - public function getCampaign($campaign_id) - { - return $this->call('campaigns/' . $campaign_id); - } - - /** - * adding campaign - * @param $params - * @return mixed - */ - public function createCampaign($params) - { - return $this->call('campaigns', 'POST', $params); - } - - /** - * list all RSS newsletters - * @return mixed - */ - public function getRSSNewsletters() - { - $this->call('rss-newsletters', 'GET', null); - } - - /** - * send one newsletter - * - * @param $params - * @return mixed - */ - public function sendNewsletter($params) - { - return $this->call('newsletters', 'POST', $params); - } - - /** - * @param $params - * @return mixed - */ - public function sendDraftNewsletter($params) - { - return $this->call('newsletters/send-draft', 'POST', $params); - } - - /** - * add single contact into your campaign - * - * @param $params - * @return mixed - */ - public function addContact($params) - { - return $this->call('contacts', 'POST', $params); - } - - /** - * retrieving contact by id - * - * @param string $contact_id - contact id obtained by API - * @return mixed - */ - public function getContact($contact_id) - { - return $this->call('contacts/' . $contact_id); - } - - - /** - * search contacts - * - * @param $params - * @return mixed - */ - public function searchContacts($params = null) - { - return $this->call('search-contacts?' . $this->setParams($params)); - } - - /** - * retrieve segment - * - * @param $id - * @return mixed - */ - public function getContactsSearch($id) - { - return $this->call('search-contacts/' . $id); - } - - /** - * add contacts search - * - * @param $params - * @return mixed - */ - public function addContactsSearch($params) - { - return $this->call('search-contacts/', 'POST', $params); - } - - /** - * add contacts search - * - * @param $id - * @return mixed - */ - public function deleteContactsSearch($id) - { - return $this->call('search-contacts/' . $id, 'DELETE'); - } - - /** - * get contact activities - * @param $contact_id - * @return mixed - */ - public function getContactActivities($contact_id) - { - return $this->call('contacts/' . $contact_id . '/activities'); - } - - /** - * retrieving contact by params - * @param array $params - * - * @return mixed - */ - public function getContacts($params = array()) - { - return $this->call('contacts?' . $this->setParams($params)); - } - - /** - * updating any fields of your subscriber (without email of course) - * @param $contact_id - * @param array $params - * - * @return mixed - */ - public function updateContact($contact_id, $params = array()) - { - return $this->call('contacts/' . $contact_id, 'POST', $params); - } - - /** - * drop single user by ID - * - * @param string $contact_id - obtained by API - * @return mixed - */ - public function deleteContact($contact_id) - { - return $this->call('contacts/' . $contact_id, 'DELETE'); - } - - /** - * retrieve account custom fields - * @param array $params - * - * @return mixed - */ - public function getCustomFields($params = array()) - { - return $this->call('custom-fields?' . $this->setParams($params)); - } - - /** - * add custom field - * - * @param $params - * @return mixed - */ - public function setCustomField($params) - { - return $this->call('custom-fields', 'POST', $params); - } - - /** - * retrieve single custom field - * - * @param string $cs_id obtained by API - * @return mixed - */ - public function getCustomField($custom_id) - { - return $this->call('custom-fields/' . $custom_id, 'GET'); - } - - /** - * retrieving billing information - * - * @return mixed - */ - public function getBillingInfo() - { - return $this->call('accounts/billing'); - } - - /** - * get single web form - * - * @param int $w_id - * @return mixed - */ - public function getWebForm($w_id) - { - return $this->call('webforms/' . $w_id); - } - - /** - * retrieve all webforms - * @param array $params - * - * @return mixed - */ - public function getWebForms($params = array()) - { - return $this->call('webforms?' . $this->setParams($params)); - } - - /** - * get single form - * - * @param int $form_id - * @return mixed - */ - public function getForm($form_id) - { - return $this->call('forms/' . $form_id); - } - - /** - * retrieve all forms - * @param array $params - * - * @return mixed - */ - public function getForms($params = array()) - { - return $this->call('forms?' . $this->setParams($params)); - } - - /** - * Curl run request - * - * @param null $api_method - * @param string $http_method - * @param array $params - * @return mixed - * @throws Exception - */ - private function call($api_method = null, $http_method = 'GET', $params = array()) - { - if (empty($api_method)) { - return (object)array( - 'httpStatus' => '400', - 'code' => '1010', - 'codeDescription' => 'Error in external resources', - 'message' => 'Invalid api method' - ); - } - - $params = json_encode($params); - $url = $this->api_url . '/' . $api_method; - - $options = array( - CURLOPT_URL => $url, - CURLOPT_ENCODING => 'gzip,deflate', - CURLOPT_FRESH_CONNECT => 1, - CURLOPT_RETURNTRANSFER => 1, - CURLOPT_TIMEOUT => $this->timeout, - CURLOPT_HEADER => false, - CURLOPT_USERAGENT => 'PHP GetResponse client 0.0.2', - CURLOPT_HTTPHEADER => array('X-Auth-Token: api-key ' . $this->api_key, 'Content-Type: application/json') - ); - - if (!empty($this->enterprise_domain)) { - $options[CURLOPT_HTTPHEADER][] = 'X-Domain: ' . $this->enterprise_domain; - } - - if (!empty($this->app_id)) { - $options[CURLOPT_HTTPHEADER][] = 'X-APP-ID: ' . $this->app_id; - } - - if ($http_method == 'POST') { - $options[CURLOPT_POST] = 1; - $options[CURLOPT_POSTFIELDS] = $params; - } else if ($http_method == 'DELETE') { - $options[CURLOPT_CUSTOMREQUEST] = 'DELETE'; - } - - $curl = curl_init(); - curl_setopt_array($curl, $options); - - $response = json_decode(curl_exec($curl)); - - $this->http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE); - - curl_close($curl); - return (object)$response; - } - - /** - * @param array $params - * - * @return string - */ - private function setParams($params = array()) - { - $result = array(); - if (is_array($params)) { - foreach ($params as $key => $value) { - $result[$key] = $value; - } - } - return http_build_query($result); - } - -} \ No newline at end of file diff --git a/themes/pmem-hugo/static/include/instagram/instagram.php b/themes/pmem-hugo/static/include/instagram/instagram.php deleted file mode 100644 index 49a0f54a05..0000000000 --- a/themes/pmem-hugo/static/include/instagram/instagram.php +++ /dev/null @@ -1,58 +0,0 @@ - $interval ) ) { - - $instagram_api = curl_init(); - curl_setopt( $instagram_api, CURLOPT_URL, "https://graph.instagram.com/me/media?fields=id&access_token=" . $accesstoken ); - curl_setopt( $instagram_api, CURLOPT_SSL_VERIFYPEER, false ); - curl_setopt( $instagram_api, CURLOPT_RETURNTRANSFER, true ); - $instagram_response = curl_exec( $instagram_api ); - - $images = json_decode( $instagram_response, true ); - $images = $images['data']; - - $image_list = array(); - - if( is_array( $images ) && ! empty( $images ) ) { - foreach( $images as $image ) { - - $insta_image = curl_init(); - curl_setopt( $insta_image, CURLOPT_URL, "https://graph.instagram.com/" . $image['id'] . "?fields=media_url,permalink,media_type,thumbnail_url&access_token=" . $accesstoken ); - curl_setopt( $insta_image, CURLOPT_SSL_VERIFYPEER, false ); - curl_setopt( $insta_image, CURLOPT_RETURNTRANSFER, true ); - $insta_image_resp = curl_exec( $insta_image ); - - $image_list[] = json_decode( $insta_image_resp, true ); - - } - } - - $cached_shots = serialize( $image_list ); - - if ( !empty( $cached_shots ) ) { - $cache_static = fopen( $cache_file, 'wb' ); - fwrite( $cache_static, $cached_shots ); - fclose( $cache_static ); - } - - $shots = @unserialize( file_get_contents( $cache_file ) ); -} else { - $shots = @unserialize( file_get_contents( $cache_file ) ); -} - -echo json_encode( $shots ); - -?> \ No newline at end of file diff --git a/themes/pmem-hugo/static/include/phpmailer/src/Exception.php b/themes/pmem-hugo/static/include/phpmailer/src/Exception.php deleted file mode 100644 index 52eaf95158..0000000000 --- a/themes/pmem-hugo/static/include/phpmailer/src/Exception.php +++ /dev/null @@ -1,40 +0,0 @@ - - * @author Jim Jagielski (jimjag) - * @author Andy Prevost (codeworxtech) - * @author Brent R. Matzelle (original founder) - * @copyright 2012 - 2020 Marcus Bointon - * @copyright 2010 - 2012 Jim Jagielski - * @copyright 2004 - 2009 Andy Prevost - * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License - * @note This program is distributed in the hope that it will be useful - WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -namespace PHPMailer\PHPMailer; - -/** - * PHPMailer exception handler. - * - * @author Marcus Bointon - */ -class Exception extends \Exception -{ - /** - * Prettify error message output. - * - * @return string - */ - public function errorMessage() - { - return '' . htmlspecialchars($this->getMessage(), ENT_COMPAT | ENT_HTML401) . "
\n"; - } -} diff --git a/themes/pmem-hugo/static/include/phpmailer/src/OAuth.php b/themes/pmem-hugo/static/include/phpmailer/src/OAuth.php deleted file mode 100644 index c93d0be1b5..0000000000 --- a/themes/pmem-hugo/static/include/phpmailer/src/OAuth.php +++ /dev/null @@ -1,139 +0,0 @@ - - * @author Jim Jagielski (jimjag) - * @author Andy Prevost (codeworxtech) - * @author Brent R. Matzelle (original founder) - * @copyright 2012 - 2020 Marcus Bointon - * @copyright 2010 - 2012 Jim Jagielski - * @copyright 2004 - 2009 Andy Prevost - * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License - * @note This program is distributed in the hope that it will be useful - WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -namespace PHPMailer\PHPMailer; - -use League\OAuth2\Client\Grant\RefreshToken; -use League\OAuth2\Client\Provider\AbstractProvider; -use League\OAuth2\Client\Token\AccessToken; - -/** - * OAuth - OAuth2 authentication wrapper class. - * Uses the oauth2-client package from the League of Extraordinary Packages. - * - * @see http://oauth2-client.thephpleague.com - * - * @author Marcus Bointon (Synchro/coolbru) - */ -class OAuth -{ - /** - * An instance of the League OAuth Client Provider. - * - * @var AbstractProvider - */ - protected $provider; - - /** - * The current OAuth access token. - * - * @var AccessToken - */ - protected $oauthToken; - - /** - * The user's email address, usually used as the login ID - * and also the from address when sending email. - * - * @var string - */ - protected $oauthUserEmail = ''; - - /** - * The client secret, generated in the app definition of the service you're connecting to. - * - * @var string - */ - protected $oauthClientSecret = ''; - - /** - * The client ID, generated in the app definition of the service you're connecting to. - * - * @var string - */ - protected $oauthClientId = ''; - - /** - * The refresh token, used to obtain new AccessTokens. - * - * @var string - */ - protected $oauthRefreshToken = ''; - - /** - * OAuth constructor. - * - * @param array $options Associative array containing - * `provider`, `userName`, `clientSecret`, `clientId` and `refreshToken` elements - */ - public function __construct($options) - { - $this->provider = $options['provider']; - $this->oauthUserEmail = $options['userName']; - $this->oauthClientSecret = $options['clientSecret']; - $this->oauthClientId = $options['clientId']; - $this->oauthRefreshToken = $options['refreshToken']; - } - - /** - * Get a new RefreshToken. - * - * @return RefreshToken - */ - protected function getGrant() - { - return new RefreshToken(); - } - - /** - * Get a new AccessToken. - * - * @return AccessToken - */ - protected function getToken() - { - return $this->provider->getAccessToken( - $this->getGrant(), - ['refresh_token' => $this->oauthRefreshToken] - ); - } - - /** - * Generate a base64-encoded OAuth token. - * - * @return string - */ - public function getOauth64() - { - //Get a new token if it's not available or has expired - if (null === $this->oauthToken || $this->oauthToken->hasExpired()) { - $this->oauthToken = $this->getToken(); - } - - return base64_encode( - 'user=' . - $this->oauthUserEmail . - "\001auth=Bearer " . - $this->oauthToken . - "\001\001" - ); - } -} diff --git a/themes/pmem-hugo/static/include/phpmailer/src/PHPMailer.php b/themes/pmem-hugo/static/include/phpmailer/src/PHPMailer.php deleted file mode 100644 index 25e94adbd3..0000000000 --- a/themes/pmem-hugo/static/include/phpmailer/src/PHPMailer.php +++ /dev/null @@ -1,4983 +0,0 @@ - - * @author Jim Jagielski (jimjag) - * @author Andy Prevost (codeworxtech) - * @author Brent R. Matzelle (original founder) - * @copyright 2012 - 2020 Marcus Bointon - * @copyright 2010 - 2012 Jim Jagielski - * @copyright 2004 - 2009 Andy Prevost - * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License - * @note This program is distributed in the hope that it will be useful - WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -namespace PHPMailer\PHPMailer; - -/** - * PHPMailer - PHP email creation and transport class. - * - * @author Marcus Bointon (Synchro/coolbru) - * @author Jim Jagielski (jimjag) - * @author Andy Prevost (codeworxtech) - * @author Brent R. Matzelle (original founder) - */ -class PHPMailer -{ - const CHARSET_ASCII = 'us-ascii'; - const CHARSET_ISO88591 = 'iso-8859-1'; - const CHARSET_UTF8 = 'utf-8'; - - const CONTENT_TYPE_PLAINTEXT = 'text/plain'; - const CONTENT_TYPE_TEXT_CALENDAR = 'text/calendar'; - const CONTENT_TYPE_TEXT_HTML = 'text/html'; - const CONTENT_TYPE_MULTIPART_ALTERNATIVE = 'multipart/alternative'; - const CONTENT_TYPE_MULTIPART_MIXED = 'multipart/mixed'; - const CONTENT_TYPE_MULTIPART_RELATED = 'multipart/related'; - - const ENCODING_7BIT = '7bit'; - const ENCODING_8BIT = '8bit'; - const ENCODING_BASE64 = 'base64'; - const ENCODING_BINARY = 'binary'; - const ENCODING_QUOTED_PRINTABLE = 'quoted-printable'; - - const ENCRYPTION_STARTTLS = 'tls'; - const ENCRYPTION_SMTPS = 'ssl'; - - const ICAL_METHOD_REQUEST = 'REQUEST'; - const ICAL_METHOD_PUBLISH = 'PUBLISH'; - const ICAL_METHOD_REPLY = 'REPLY'; - const ICAL_METHOD_ADD = 'ADD'; - const ICAL_METHOD_CANCEL = 'CANCEL'; - const ICAL_METHOD_REFRESH = 'REFRESH'; - const ICAL_METHOD_COUNTER = 'COUNTER'; - const ICAL_METHOD_DECLINECOUNTER = 'DECLINECOUNTER'; - - /** - * Email priority. - * Options: null (default), 1 = High, 3 = Normal, 5 = low. - * When null, the header is not set at all. - * - * @var int|null - */ - public $Priority; - - /** - * The character set of the message. - * - * @var string - */ - public $CharSet = self::CHARSET_ISO88591; - - /** - * The MIME Content-type of the message. - * - * @var string - */ - public $ContentType = self::CONTENT_TYPE_PLAINTEXT; - - /** - * The message encoding. - * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable". - * - * @var string - */ - public $Encoding = self::ENCODING_8BIT; - - /** - * Holds the most recent mailer error message. - * - * @var string - */ - public $ErrorInfo = ''; - - /** - * The From email address for the message. - * - * @var string - */ - public $From = 'root@localhost'; - - /** - * The From name of the message. - * - * @var string - */ - public $FromName = 'Root User'; - - /** - * The envelope sender of the message. - * This will usually be turned into a Return-Path header by the receiver, - * and is the address that bounces will be sent to. - * If not empty, will be passed via `-f` to sendmail or as the 'MAIL FROM' value over SMTP. - * - * @var string - */ - public $Sender = ''; - - /** - * The Subject of the message. - * - * @var string - */ - public $Subject = ''; - - /** - * An HTML or plain text message body. - * If HTML then call isHTML(true). - * - * @var string - */ - public $Body = ''; - - /** - * The plain-text message body. - * This body can be read by mail clients that do not have HTML email - * capability such as mutt & Eudora. - * Clients that can read HTML will view the normal Body. - * - * @var string - */ - public $AltBody = ''; - - /** - * An iCal message part body. - * Only supported in simple alt or alt_inline message types - * To generate iCal event structures, use classes like EasyPeasyICS or iCalcreator. - * - * @see http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/ - * @see http://kigkonsult.se/iCalcreator/ - * - * @var string - */ - public $Ical = ''; - - /** - * Value-array of "method" in Contenttype header "text/calendar" - * - * @var string[] - */ - protected static $IcalMethods = [ - self::ICAL_METHOD_REQUEST, - self::ICAL_METHOD_PUBLISH, - self::ICAL_METHOD_REPLY, - self::ICAL_METHOD_ADD, - self::ICAL_METHOD_CANCEL, - self::ICAL_METHOD_REFRESH, - self::ICAL_METHOD_COUNTER, - self::ICAL_METHOD_DECLINECOUNTER, - ]; - - /** - * The complete compiled MIME message body. - * - * @var string - */ - protected $MIMEBody = ''; - - /** - * The complete compiled MIME message headers. - * - * @var string - */ - protected $MIMEHeader = ''; - - /** - * Extra headers that createHeader() doesn't fold in. - * - * @var string - */ - protected $mailHeader = ''; - - /** - * Word-wrap the message body to this number of chars. - * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance. - * - * @see static::STD_LINE_LENGTH - * - * @var int - */ - public $WordWrap = 0; - - /** - * Which method to use to send mail. - * Options: "mail", "sendmail", or "smtp". - * - * @var string - */ - public $Mailer = 'mail'; - - /** - * The path to the sendmail program. - * - * @var string - */ - public $Sendmail = '/usr/sbin/sendmail'; - - /** - * Whether mail() uses a fully sendmail-compatible MTA. - * One which supports sendmail's "-oi -f" options. - * - * @var bool - */ - public $UseSendmailOptions = true; - - /** - * The email address that a reading confirmation should be sent to, also known as read receipt. - * - * @var string - */ - public $ConfirmReadingTo = ''; - - /** - * The hostname to use in the Message-ID header and as default HELO string. - * If empty, PHPMailer attempts to find one with, in order, - * $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value - * 'localhost.localdomain'. - * - * @see PHPMailer::$Helo - * - * @var string - */ - public $Hostname = ''; - - /** - * An ID to be used in the Message-ID header. - * If empty, a unique id will be generated. - * You can set your own, but it must be in the format "", - * as defined in RFC5322 section 3.6.4 or it will be ignored. - * - * @see https://tools.ietf.org/html/rfc5322#section-3.6.4 - * - * @var string - */ - public $MessageID = ''; - - /** - * The message Date to be used in the Date header. - * If empty, the current date will be added. - * - * @var string - */ - public $MessageDate = ''; - - /** - * SMTP hosts. - * Either a single hostname or multiple semicolon-delimited hostnames. - * You can also specify a different port - * for each host by using this format: [hostname:port] - * (e.g. "smtp1.example.com:25;smtp2.example.com"). - * You can also specify encryption type, for example: - * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465"). - * Hosts will be tried in order. - * - * @var string - */ - public $Host = 'localhost'; - - /** - * The default SMTP server port. - * - * @var int - */ - public $Port = 25; - - /** - * The SMTP HELO/EHLO name used for the SMTP connection. - * Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find - * one with the same method described above for $Hostname. - * - * @see PHPMailer::$Hostname - * - * @var string - */ - public $Helo = ''; - - /** - * What kind of encryption to use on the SMTP connection. - * Options: '', static::ENCRYPTION_STARTTLS, or static::ENCRYPTION_SMTPS. - * - * @var string - */ - public $SMTPSecure = ''; - - /** - * Whether to enable TLS encryption automatically if a server supports it, - * even if `SMTPSecure` is not set to 'tls'. - * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid. - * - * @var bool - */ - public $SMTPAutoTLS = true; - - /** - * Whether to use SMTP authentication. - * Uses the Username and Password properties. - * - * @see PHPMailer::$Username - * @see PHPMailer::$Password - * - * @var bool - */ - public $SMTPAuth = false; - - /** - * Options array passed to stream_context_create when connecting via SMTP. - * - * @var array - */ - public $SMTPOptions = []; - - /** - * SMTP username. - * - * @var string - */ - public $Username = ''; - - /** - * SMTP password. - * - * @var string - */ - public $Password = ''; - - /** - * SMTP auth type. - * Options are CRAM-MD5, LOGIN, PLAIN, XOAUTH2, attempted in that order if not specified. - * - * @var string - */ - public $AuthType = ''; - - /** - * An instance of the PHPMailer OAuth class. - * - * @var OAuth - */ - protected $oauth; - - /** - * The SMTP server timeout in seconds. - * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2. - * - * @var int - */ - public $Timeout = 300; - - /** - * Comma separated list of DSN notifications - * 'NEVER' under no circumstances a DSN must be returned to the sender. - * If you use NEVER all other notifications will be ignored. - * 'SUCCESS' will notify you when your mail has arrived at its destination. - * 'FAILURE' will arrive if an error occurred during delivery. - * 'DELAY' will notify you if there is an unusual delay in delivery, but the actual - * delivery's outcome (success or failure) is not yet decided. - * - * @see https://tools.ietf.org/html/rfc3461 See section 4.1 for more information about NOTIFY - */ - public $dsn = ''; - - /** - * SMTP class debug output mode. - * Debug output level. - * Options: - * @see SMTP::DEBUG_OFF: No output - * @see SMTP::DEBUG_CLIENT: Client messages - * @see SMTP::DEBUG_SERVER: Client and server messages - * @see SMTP::DEBUG_CONNECTION: As SERVER plus connection status - * @see SMTP::DEBUG_LOWLEVEL: Noisy, low-level data output, rarely needed - * - * @see SMTP::$do_debug - * - * @var int - */ - public $SMTPDebug = 0; - - /** - * How to handle debug output. - * Options: - * * `echo` Output plain-text as-is, appropriate for CLI - * * `html` Output escaped, line breaks converted to `
`, appropriate for browser output - * * `error_log` Output to error log as configured in php.ini - * By default PHPMailer will use `echo` if run from a `cli` or `cli-server` SAPI, `html` otherwise. - * Alternatively, you can provide a callable expecting two params: a message string and the debug level: - * - * ```php - * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";}; - * ``` - * - * Alternatively, you can pass in an instance of a PSR-3 compatible logger, though only `debug` - * level output is used: - * - * ```php - * $mail->Debugoutput = new myPsr3Logger; - * ``` - * - * @see SMTP::$Debugoutput - * - * @var string|callable|\Psr\Log\LoggerInterface - */ - public $Debugoutput = 'echo'; - - /** - * Whether to keep the SMTP connection open after each message. - * If this is set to true then the connection will remain open after a send, - * and closing the connection will require an explicit call to smtpClose(). - * It's a good idea to use this if you are sending multiple messages as it reduces overhead. - * See the mailing list example for how to use it. - * - * @var bool - */ - public $SMTPKeepAlive = false; - - /** - * Whether to split multiple to addresses into multiple messages - * or send them all in one message. - * Only supported in `mail` and `sendmail` transports, not in SMTP. - * - * @var bool - * - * @deprecated 6.0.0 PHPMailer isn't a mailing list manager! - */ - public $SingleTo = false; - - /** - * Storage for addresses when SingleTo is enabled. - * - * @var array - */ - protected $SingleToArray = []; - - /** - * Whether to generate VERP addresses on send. - * Only applicable when sending via SMTP. - * - * @see https://en.wikipedia.org/wiki/Variable_envelope_return_path - * @see http://www.postfix.org/VERP_README.html Postfix VERP info - * - * @var bool - */ - public $do_verp = false; - - /** - * Whether to allow sending messages with an empty body. - * - * @var bool - */ - public $AllowEmpty = false; - - /** - * DKIM selector. - * - * @var string - */ - public $DKIM_selector = ''; - - /** - * DKIM Identity. - * Usually the email address used as the source of the email. - * - * @var string - */ - public $DKIM_identity = ''; - - /** - * DKIM passphrase. - * Used if your key is encrypted. - * - * @var string - */ - public $DKIM_passphrase = ''; - - /** - * DKIM signing domain name. - * - * @example 'example.com' - * - * @var string - */ - public $DKIM_domain = ''; - - /** - * DKIM Copy header field values for diagnostic use. - * - * @var bool - */ - public $DKIM_copyHeaderFields = true; - - /** - * DKIM Extra signing headers. - * - * @example ['List-Unsubscribe', 'List-Help'] - * - * @var array - */ - public $DKIM_extraHeaders = []; - - /** - * DKIM private key file path. - * - * @var string - */ - public $DKIM_private = ''; - - /** - * DKIM private key string. - * - * If set, takes precedence over `$DKIM_private`. - * - * @var string - */ - public $DKIM_private_string = ''; - - /** - * Callback Action function name. - * - * The function that handles the result of the send email action. - * It is called out by send() for each email sent. - * - * Value can be any php callable: http://www.php.net/is_callable - * - * Parameters: - * bool $result result of the send action - * array $to email addresses of the recipients - * array $cc cc email addresses - * array $bcc bcc email addresses - * string $subject the subject - * string $body the email body - * string $from email address of sender - * string $extra extra information of possible use - * "smtp_transaction_id' => last smtp transaction id - * - * @var string - */ - public $action_function = ''; - - /** - * What to put in the X-Mailer header. - * Options: An empty string for PHPMailer default, whitespace/null for none, or a string to use. - * - * @var string|null - */ - public $XMailer = ''; - - /** - * Which validator to use by default when validating email addresses. - * May be a callable to inject your own validator, but there are several built-in validators. - * The default validator uses PHP's FILTER_VALIDATE_EMAIL filter_var option. - * - * @see PHPMailer::validateAddress() - * - * @var string|callable - */ - public static $validator = 'php'; - - /** - * An instance of the SMTP sender class. - * - * @var SMTP - */ - protected $smtp; - - /** - * The array of 'to' names and addresses. - * - * @var array - */ - protected $to = []; - - /** - * The array of 'cc' names and addresses. - * - * @var array - */ - protected $cc = []; - - /** - * The array of 'bcc' names and addresses. - * - * @var array - */ - protected $bcc = []; - - /** - * The array of reply-to names and addresses. - * - * @var array - */ - protected $ReplyTo = []; - - /** - * An array of all kinds of addresses. - * Includes all of $to, $cc, $bcc. - * - * @see PHPMailer::$to - * @see PHPMailer::$cc - * @see PHPMailer::$bcc - * - * @var array - */ - protected $all_recipients = []; - - /** - * An array of names and addresses queued for validation. - * In send(), valid and non duplicate entries are moved to $all_recipients - * and one of $to, $cc, or $bcc. - * This array is used only for addresses with IDN. - * - * @see PHPMailer::$to - * @see PHPMailer::$cc - * @see PHPMailer::$bcc - * @see PHPMailer::$all_recipients - * - * @var array - */ - protected $RecipientsQueue = []; - - /** - * An array of reply-to names and addresses queued for validation. - * In send(), valid and non duplicate entries are moved to $ReplyTo. - * This array is used only for addresses with IDN. - * - * @see PHPMailer::$ReplyTo - * - * @var array - */ - protected $ReplyToQueue = []; - - /** - * The array of attachments. - * - * @var array - */ - protected $attachment = []; - - /** - * The array of custom headers. - * - * @var array - */ - protected $CustomHeader = []; - - /** - * The most recent Message-ID (including angular brackets). - * - * @var string - */ - protected $lastMessageID = ''; - - /** - * The message's MIME type. - * - * @var string - */ - protected $message_type = ''; - - /** - * The array of MIME boundary strings. - * - * @var array - */ - protected $boundary = []; - - /** - * The array of available languages. - * - * @var array - */ - protected $language = []; - - /** - * The number of errors encountered. - * - * @var int - */ - protected $error_count = 0; - - /** - * The S/MIME certificate file path. - * - * @var string - */ - protected $sign_cert_file = ''; - - /** - * The S/MIME key file path. - * - * @var string - */ - protected $sign_key_file = ''; - - /** - * The optional S/MIME extra certificates ("CA Chain") file path. - * - * @var string - */ - protected $sign_extracerts_file = ''; - - /** - * The S/MIME password for the key. - * Used only if the key is encrypted. - * - * @var string - */ - protected $sign_key_pass = ''; - - /** - * Whether to throw exceptions for errors. - * - * @var bool - */ - protected $exceptions = false; - - /** - * Unique ID used for message ID and boundaries. - * - * @var string - */ - protected $uniqueid = ''; - - /** - * The PHPMailer Version number. - * - * @var string - */ - const VERSION = '6.5.0'; - - /** - * Error severity: message only, continue processing. - * - * @var int - */ - const STOP_MESSAGE = 0; - - /** - * Error severity: message, likely ok to continue processing. - * - * @var int - */ - const STOP_CONTINUE = 1; - - /** - * Error severity: message, plus full stop, critical error reached. - * - * @var int - */ - const STOP_CRITICAL = 2; - - /** - * The SMTP standard CRLF line break. - * If you want to change line break format, change static::$LE, not this. - */ - const CRLF = "\r\n"; - - /** - * "Folding White Space" a white space string used for line folding. - */ - const FWS = ' '; - - /** - * SMTP RFC standard line ending; Carriage Return, Line Feed. - * - * @var string - */ - protected static $LE = self::CRLF; - - /** - * The maximum line length supported by mail(). - * - * Background: mail() will sometimes corrupt messages - * with headers headers longer than 65 chars, see #818. - * - * @var int - */ - const MAIL_MAX_LINE_LENGTH = 63; - - /** - * The maximum line length allowed by RFC 2822 section 2.1.1. - * - * @var int - */ - const MAX_LINE_LENGTH = 998; - - /** - * The lower maximum line length allowed by RFC 2822 section 2.1.1. - * This length does NOT include the line break - * 76 means that lines will be 77 or 78 chars depending on whether - * the line break format is LF or CRLF; both are valid. - * - * @var int - */ - const STD_LINE_LENGTH = 76; - - /** - * Constructor. - * - * @param bool $exceptions Should we throw external exceptions? - */ - public function __construct($exceptions = null) - { - if (null !== $exceptions) { - $this->exceptions = (bool) $exceptions; - } - //Pick an appropriate debug output format automatically - $this->Debugoutput = (strpos(PHP_SAPI, 'cli') !== false ? 'echo' : 'html'); - } - - /** - * Destructor. - */ - public function __destruct() - { - //Close any open SMTP connection nicely - $this->smtpClose(); - } - - /** - * Call mail() in a safe_mode-aware fashion. - * Also, unless sendmail_path points to sendmail (or something that - * claims to be sendmail), don't pass params (not a perfect fix, - * but it will do). - * - * @param string $to To - * @param string $subject Subject - * @param string $body Message Body - * @param string $header Additional Header(s) - * @param string|null $params Params - * - * @return bool - */ - private function mailPassthru($to, $subject, $body, $header, $params) - { - //Check overloading of mail function to avoid double-encoding - if (ini_get('mbstring.func_overload') & 1) { - $subject = $this->secureHeader($subject); - } else { - $subject = $this->encodeHeader($this->secureHeader($subject)); - } - //Calling mail() with null params breaks - $this->edebug('Sending with mail()'); - $this->edebug('Sendmail path: ' . ini_get('sendmail_path')); - $this->edebug("Envelope sender: {$this->Sender}"); - $this->edebug("To: {$to}"); - $this->edebug("Subject: {$subject}"); - $this->edebug("Headers: {$header}"); - if (!$this->UseSendmailOptions || null === $params) { - $result = @mail($to, $subject, $body, $header); - } else { - $this->edebug("Additional params: {$params}"); - $result = @mail($to, $subject, $body, $header, $params); - } - $this->edebug('Result: ' . ($result ? 'true' : 'false')); - return $result; - } - - /** - * Output debugging info via a user-defined method. - * Only generates output if debug output is enabled. - * - * @see PHPMailer::$Debugoutput - * @see PHPMailer::$SMTPDebug - * - * @param string $str - */ - protected function edebug($str) - { - if ($this->SMTPDebug <= 0) { - return; - } - //Is this a PSR-3 logger? - if ($this->Debugoutput instanceof \Psr\Log\LoggerInterface) { - $this->Debugoutput->debug($str); - - return; - } - //Avoid clash with built-in function names - if (is_callable($this->Debugoutput) && !in_array($this->Debugoutput, ['error_log', 'html', 'echo'])) { - call_user_func($this->Debugoutput, $str, $this->SMTPDebug); - - return; - } - switch ($this->Debugoutput) { - case 'error_log': - //Don't output, just log - /** @noinspection ForgottenDebugOutputInspection */ - error_log($str); - break; - case 'html': - //Cleans up output a bit for a better looking, HTML-safe output - echo htmlentities( - preg_replace('/[\r\n]+/', '', $str), - ENT_QUOTES, - 'UTF-8' - ), "
\n"; - break; - case 'echo': - default: - //Normalize line breaks - $str = preg_replace('/\r\n|\r/m', "\n", $str); - echo gmdate('Y-m-d H:i:s'), - "\t", - //Trim trailing space - trim( - //Indent for readability, except for trailing break - str_replace( - "\n", - "\n \t ", - trim($str) - ) - ), - "\n"; - } - } - - /** - * Sets message type to HTML or plain. - * - * @param bool $isHtml True for HTML mode - */ - public function isHTML($isHtml = true) - { - if ($isHtml) { - $this->ContentType = static::CONTENT_TYPE_TEXT_HTML; - } else { - $this->ContentType = static::CONTENT_TYPE_PLAINTEXT; - } - } - - /** - * Send messages using SMTP. - */ - public function isSMTP() - { - $this->Mailer = 'smtp'; - } - - /** - * Send messages using PHP's mail() function. - */ - public function isMail() - { - $this->Mailer = 'mail'; - } - - /** - * Send messages using $Sendmail. - */ - public function isSendmail() - { - $ini_sendmail_path = ini_get('sendmail_path'); - - if (false === stripos($ini_sendmail_path, 'sendmail')) { - $this->Sendmail = '/usr/sbin/sendmail'; - } else { - $this->Sendmail = $ini_sendmail_path; - } - $this->Mailer = 'sendmail'; - } - - /** - * Send messages using qmail. - */ - public function isQmail() - { - $ini_sendmail_path = ini_get('sendmail_path'); - - if (false === stripos($ini_sendmail_path, 'qmail')) { - $this->Sendmail = '/var/qmail/bin/qmail-inject'; - } else { - $this->Sendmail = $ini_sendmail_path; - } - $this->Mailer = 'qmail'; - } - - /** - * Add a "To" address. - * - * @param string $address The email address to send to - * @param string $name - * - * @throws Exception - * - * @return bool true on success, false if address already used or invalid in some way - */ - public function addAddress($address, $name = '') - { - return $this->addOrEnqueueAnAddress('to', $address, $name); - } - - /** - * Add a "CC" address. - * - * @param string $address The email address to send to - * @param string $name - * - * @throws Exception - * - * @return bool true on success, false if address already used or invalid in some way - */ - public function addCC($address, $name = '') - { - return $this->addOrEnqueueAnAddress('cc', $address, $name); - } - - /** - * Add a "BCC" address. - * - * @param string $address The email address to send to - * @param string $name - * - * @throws Exception - * - * @return bool true on success, false if address already used or invalid in some way - */ - public function addBCC($address, $name = '') - { - return $this->addOrEnqueueAnAddress('bcc', $address, $name); - } - - /** - * Add a "Reply-To" address. - * - * @param string $address The email address to reply to - * @param string $name - * - * @throws Exception - * - * @return bool true on success, false if address already used or invalid in some way - */ - public function addReplyTo($address, $name = '') - { - return $this->addOrEnqueueAnAddress('Reply-To', $address, $name); - } - - /** - * Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer - * can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still - * be modified after calling this function), addition of such addresses is delayed until send(). - * Addresses that have been added already return false, but do not throw exceptions. - * - * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo' - * @param string $address The email address to send, resp. to reply to - * @param string $name - * - * @throws Exception - * - * @return bool true on success, false if address already used or invalid in some way - */ - protected function addOrEnqueueAnAddress($kind, $address, $name) - { - $address = trim($address); - $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim - $pos = strrpos($address, '@'); - if (false === $pos) { - //At-sign is missing. - $error_message = sprintf( - '%s (%s): %s', - $this->lang('invalid_address'), - $kind, - $address - ); - $this->setError($error_message); - $this->edebug($error_message); - if ($this->exceptions) { - throw new Exception($error_message); - } - - return false; - } - $params = [$kind, $address, $name]; - //Enqueue addresses with IDN until we know the PHPMailer::$CharSet. - if (static::idnSupported() && $this->has8bitChars(substr($address, ++$pos))) { - if ('Reply-To' !== $kind) { - if (!array_key_exists($address, $this->RecipientsQueue)) { - $this->RecipientsQueue[$address] = $params; - - return true; - } - } elseif (!array_key_exists($address, $this->ReplyToQueue)) { - $this->ReplyToQueue[$address] = $params; - - return true; - } - - return false; - } - - //Immediately add standard addresses without IDN. - return call_user_func_array([$this, 'addAnAddress'], $params); - } - - /** - * Add an address to one of the recipient arrays or to the ReplyTo array. - * Addresses that have been added already return false, but do not throw exceptions. - * - * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo' - * @param string $address The email address to send, resp. to reply to - * @param string $name - * - * @throws Exception - * - * @return bool true on success, false if address already used or invalid in some way - */ - protected function addAnAddress($kind, $address, $name = '') - { - if (!in_array($kind, ['to', 'cc', 'bcc', 'Reply-To'])) { - $error_message = sprintf( - '%s: %s', - $this->lang('Invalid recipient kind'), - $kind - ); - $this->setError($error_message); - $this->edebug($error_message); - if ($this->exceptions) { - throw new Exception($error_message); - } - - return false; - } - if (!static::validateAddress($address)) { - $error_message = sprintf( - '%s (%s): %s', - $this->lang('invalid_address'), - $kind, - $address - ); - $this->setError($error_message); - $this->edebug($error_message); - if ($this->exceptions) { - throw new Exception($error_message); - } - - return false; - } - if ('Reply-To' !== $kind) { - if (!array_key_exists(strtolower($address), $this->all_recipients)) { - $this->{$kind}[] = [$address, $name]; - $this->all_recipients[strtolower($address)] = true; - - return true; - } - } elseif (!array_key_exists(strtolower($address), $this->ReplyTo)) { - $this->ReplyTo[strtolower($address)] = [$address, $name]; - - return true; - } - - return false; - } - - /** - * Parse and validate a string containing one or more RFC822-style comma-separated email addresses - * of the form "display name
" into an array of name/address pairs. - * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available. - * Note that quotes in the name part are removed. - * - * @see http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation - * - * @param string $addrstr The address list string - * @param bool $useimap Whether to use the IMAP extension to parse the list - * - * @return array - */ - public static function parseAddresses($addrstr, $useimap = true) - { - $addresses = []; - if ($useimap && function_exists('imap_rfc822_parse_adrlist')) { - //Use this built-in parser if it's available - $list = imap_rfc822_parse_adrlist($addrstr, ''); - // Clear any potential IMAP errors to get rid of notices begin thrown at end of script. - imap_errors(); - foreach ($list as $address) { - if ( - ('.SYNTAX-ERROR.' !== $address->host) && static::validateAddress( - $address->mailbox . '@' . $address->host - ) - ) { - //Decode the name part if it's present and encoded - if ( - property_exists($address, 'personal') && - extension_loaded('mbstring') && - preg_match('/^=\?.*\?=$/', $address->personal) - ) { - $address->personal = mb_decode_mimeheader($address->personal); - } - - $addresses[] = [ - 'name' => (property_exists($address, 'personal') ? $address->personal : ''), - 'address' => $address->mailbox . '@' . $address->host, - ]; - } - } - } else { - //Use this simpler parser - $list = explode(',', $addrstr); - foreach ($list as $address) { - $address = trim($address); - //Is there a separate name part? - if (strpos($address, '<') === false) { - //No separate name, just use the whole thing - if (static::validateAddress($address)) { - $addresses[] = [ - 'name' => '', - 'address' => $address, - ]; - } - } else { - list($name, $email) = explode('<', $address); - $email = trim(str_replace('>', '', $email)); - $name = trim($name); - if (static::validateAddress($email)) { - //If this name is encoded, decode it - if (preg_match('/^=\?.*\?=$/', $name)) { - $name = mb_decode_mimeheader($name); - } - $addresses[] = [ - //Remove any surrounding quotes and spaces from the name - 'name' => trim($name, '\'" '), - 'address' => $email, - ]; - } - } - } - } - - return $addresses; - } - - /** - * Set the From and FromName properties. - * - * @param string $address - * @param string $name - * @param bool $auto Whether to also set the Sender address, defaults to true - * - * @throws Exception - * - * @return bool - */ - public function setFrom($address, $name = '', $auto = true) - { - $address = trim($address); - $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim - //Don't validate now addresses with IDN. Will be done in send(). - $pos = strrpos($address, '@'); - if ( - (false === $pos) - || ((!$this->has8bitChars(substr($address, ++$pos)) || !static::idnSupported()) - && !static::validateAddress($address)) - ) { - $error_message = sprintf( - '%s (From): %s', - $this->lang('invalid_address'), - $address - ); - $this->setError($error_message); - $this->edebug($error_message); - if ($this->exceptions) { - throw new Exception($error_message); - } - - return false; - } - $this->From = $address; - $this->FromName = $name; - if ($auto && empty($this->Sender)) { - $this->Sender = $address; - } - - return true; - } - - /** - * Return the Message-ID header of the last email. - * Technically this is the value from the last time the headers were created, - * but it's also the message ID of the last sent message except in - * pathological cases. - * - * @return string - */ - public function getLastMessageID() - { - return $this->lastMessageID; - } - - /** - * Check that a string looks like an email address. - * Validation patterns supported: - * * `auto` Pick best pattern automatically; - * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0; - * * `pcre` Use old PCRE implementation; - * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL; - * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements. - * * `noregex` Don't use a regex: super fast, really dumb. - * Alternatively you may pass in a callable to inject your own validator, for example: - * - * ```php - * PHPMailer::validateAddress('user@example.com', function($address) { - * return (strpos($address, '@') !== false); - * }); - * ``` - * - * You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator. - * - * @param string $address The email address to check - * @param string|callable $patternselect Which pattern to use - * - * @return bool - */ - public static function validateAddress($address, $patternselect = null) - { - if (null === $patternselect) { - $patternselect = static::$validator; - } - //Don't allow strings as callables, see SECURITY.md and CVE-2021-3603 - if (is_callable($patternselect) && !is_string($patternselect)) { - return call_user_func($patternselect, $address); - } - //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321 - if (strpos($address, "\n") !== false || strpos($address, "\r") !== false) { - return false; - } - switch ($patternselect) { - case 'pcre': //Kept for BC - case 'pcre8': - /* - * A more complex and more permissive version of the RFC5322 regex on which FILTER_VALIDATE_EMAIL - * is based. - * In addition to the addresses allowed by filter_var, also permits: - * * dotless domains: `a@b` - * * comments: `1234 @ local(blah) .machine .example` - * * quoted elements: `'"test blah"@example.org'` - * * numeric TLDs: `a@b.123` - * * unbracketed IPv4 literals: `a@192.168.0.1` - * * IPv6 literals: 'first.last@[IPv6:a1::]' - * Not all of these will necessarily work for sending! - * - * @see http://squiloople.com/2009/12/20/email-address-validation/ - * @copyright 2009-2010 Michael Rushton - * Feel free to use and redistribute this code. But please keep this copyright notice. - */ - return (bool) preg_match( - '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' . - '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' . - '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' . - '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' . - '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' . - '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' . - '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' . - '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' . - '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', - $address - ); - case 'html5': - /* - * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements. - * - * @see https://html.spec.whatwg.org/#e-mail-state-(type=email) - */ - return (bool) preg_match( - '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' . - '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD', - $address - ); - case 'php': - default: - return filter_var($address, FILTER_VALIDATE_EMAIL) !== false; - } - } - - /** - * Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the - * `intl` and `mbstring` PHP extensions. - * - * @return bool `true` if required functions for IDN support are present - */ - public static function idnSupported() - { - return function_exists('idn_to_ascii') && function_exists('mb_convert_encoding'); - } - - /** - * Converts IDN in given email address to its ASCII form, also known as punycode, if possible. - * Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet. - * This function silently returns unmodified address if: - * - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form) - * - Conversion to punycode is impossible (e.g. required PHP functions are not available) - * or fails for any reason (e.g. domain contains characters not allowed in an IDN). - * - * @see PHPMailer::$CharSet - * - * @param string $address The email address to convert - * - * @return string The encoded address in ASCII form - */ - public function punyencodeAddress($address) - { - //Verify we have required functions, CharSet, and at-sign. - $pos = strrpos($address, '@'); - if ( - !empty($this->CharSet) && - false !== $pos && - static::idnSupported() - ) { - $domain = substr($address, ++$pos); - //Verify CharSet string is a valid one, and domain properly encoded in this CharSet. - if ($this->has8bitChars($domain) && @mb_check_encoding($domain, $this->CharSet)) { - //Convert the domain from whatever charset it's in to UTF-8 - $domain = mb_convert_encoding($domain, self::CHARSET_UTF8, $this->CharSet); - //Ignore IDE complaints about this line - method signature changed in PHP 5.4 - $errorcode = 0; - if (defined('INTL_IDNA_VARIANT_UTS46')) { - //Use the current punycode standard (appeared in PHP 7.2) - $punycode = idn_to_ascii($domain, $errorcode, \INTL_IDNA_VARIANT_UTS46); - } elseif (defined('INTL_IDNA_VARIANT_2003')) { - //Fall back to this old, deprecated/removed encoding - $punycode = idn_to_ascii($domain, $errorcode, \INTL_IDNA_VARIANT_2003); - } else { - //Fall back to a default we don't know about - $punycode = idn_to_ascii($domain, $errorcode); - } - if (false !== $punycode) { - return substr($address, 0, $pos) . $punycode; - } - } - } - - return $address; - } - - /** - * Create a message and send it. - * Uses the sending method specified by $Mailer. - * - * @throws Exception - * - * @return bool false on error - See the ErrorInfo property for details of the error - */ - public function send() - { - try { - if (!$this->preSend()) { - return false; - } - - return $this->postSend(); - } catch (Exception $exc) { - $this->mailHeader = ''; - $this->setError($exc->getMessage()); - if ($this->exceptions) { - throw $exc; - } - - return false; - } - } - - /** - * Prepare a message for sending. - * - * @throws Exception - * - * @return bool - */ - public function preSend() - { - if ( - 'smtp' === $this->Mailer - || ('mail' === $this->Mailer && (\PHP_VERSION_ID >= 80000 || stripos(PHP_OS, 'WIN') === 0)) - ) { - //SMTP mandates RFC-compliant line endings - //and it's also used with mail() on Windows - static::setLE(self::CRLF); - } else { - //Maintain backward compatibility with legacy Linux command line mailers - static::setLE(PHP_EOL); - } - //Check for buggy PHP versions that add a header with an incorrect line break - if ( - 'mail' === $this->Mailer - && ((\PHP_VERSION_ID >= 70000 && \PHP_VERSION_ID < 70017) - || (\PHP_VERSION_ID >= 70100 && \PHP_VERSION_ID < 70103)) - && ini_get('mail.add_x_header') === '1' - && stripos(PHP_OS, 'WIN') === 0 - ) { - trigger_error( - 'Your version of PHP is affected by a bug that may result in corrupted messages.' . - ' To fix it, switch to sending using SMTP, disable the mail.add_x_header option in' . - ' your php.ini, switch to MacOS or Linux, or upgrade your PHP to version 7.0.17+ or 7.1.3+.', - E_USER_WARNING - ); - } - - try { - $this->error_count = 0; //Reset errors - $this->mailHeader = ''; - - //Dequeue recipient and Reply-To addresses with IDN - foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) { - $params[1] = $this->punyencodeAddress($params[1]); - call_user_func_array([$this, 'addAnAddress'], $params); - } - if (count($this->to) + count($this->cc) + count($this->bcc) < 1) { - throw new Exception($this->lang('provide_address'), self::STOP_CRITICAL); - } - - //Validate From, Sender, and ConfirmReadingTo addresses - foreach (['From', 'Sender', 'ConfirmReadingTo'] as $address_kind) { - $this->$address_kind = trim($this->$address_kind); - if (empty($this->$address_kind)) { - continue; - } - $this->$address_kind = $this->punyencodeAddress($this->$address_kind); - if (!static::validateAddress($this->$address_kind)) { - $error_message = sprintf( - '%s (%s): %s', - $this->lang('invalid_address'), - $address_kind, - $this->$address_kind - ); - $this->setError($error_message); - $this->edebug($error_message); - if ($this->exceptions) { - throw new Exception($error_message); - } - - return false; - } - } - - //Set whether the message is multipart/alternative - if ($this->alternativeExists()) { - $this->ContentType = static::CONTENT_TYPE_MULTIPART_ALTERNATIVE; - } - - $this->setMessageType(); - //Refuse to send an empty message unless we are specifically allowing it - if (!$this->AllowEmpty && empty($this->Body)) { - throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL); - } - - //Trim subject consistently - $this->Subject = trim($this->Subject); - //Create body before headers in case body makes changes to headers (e.g. altering transfer encoding) - $this->MIMEHeader = ''; - $this->MIMEBody = $this->createBody(); - //createBody may have added some headers, so retain them - $tempheaders = $this->MIMEHeader; - $this->MIMEHeader = $this->createHeader(); - $this->MIMEHeader .= $tempheaders; - - //To capture the complete message when using mail(), create - //an extra header list which createHeader() doesn't fold in - if ('mail' === $this->Mailer) { - if (count($this->to) > 0) { - $this->mailHeader .= $this->addrAppend('To', $this->to); - } else { - $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;'); - } - $this->mailHeader .= $this->headerLine( - 'Subject', - $this->encodeHeader($this->secureHeader($this->Subject)) - ); - } - - //Sign with DKIM if enabled - if ( - !empty($this->DKIM_domain) - && !empty($this->DKIM_selector) - && (!empty($this->DKIM_private_string) - || (!empty($this->DKIM_private) - && static::isPermittedPath($this->DKIM_private) - && file_exists($this->DKIM_private) - ) - ) - ) { - $header_dkim = $this->DKIM_Add( - $this->MIMEHeader . $this->mailHeader, - $this->encodeHeader($this->secureHeader($this->Subject)), - $this->MIMEBody - ); - $this->MIMEHeader = static::stripTrailingWSP($this->MIMEHeader) . static::$LE . - static::normalizeBreaks($header_dkim) . static::$LE; - } - - return true; - } catch (Exception $exc) { - $this->setError($exc->getMessage()); - if ($this->exceptions) { - throw $exc; - } - - return false; - } - } - - /** - * Actually send a message via the selected mechanism. - * - * @throws Exception - * - * @return bool - */ - public function postSend() - { - try { - //Choose the mailer and send through it - switch ($this->Mailer) { - case 'sendmail': - case 'qmail': - return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody); - case 'smtp': - return $this->smtpSend($this->MIMEHeader, $this->MIMEBody); - case 'mail': - return $this->mailSend($this->MIMEHeader, $this->MIMEBody); - default: - $sendMethod = $this->Mailer . 'Send'; - if (method_exists($this, $sendMethod)) { - return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody); - } - - return $this->mailSend($this->MIMEHeader, $this->MIMEBody); - } - } catch (Exception $exc) { - if ($this->Mailer === 'smtp' && $this->SMTPKeepAlive == true) { - $this->smtp->reset(); - } - $this->setError($exc->getMessage()); - $this->edebug($exc->getMessage()); - if ($this->exceptions) { - throw $exc; - } - } - - return false; - } - - /** - * Send mail using the $Sendmail program. - * - * @see PHPMailer::$Sendmail - * - * @param string $header The message headers - * @param string $body The message body - * - * @throws Exception - * - * @return bool - */ - protected function sendmailSend($header, $body) - { - if ($this->Mailer === 'qmail') { - $this->edebug('Sending with qmail'); - } else { - $this->edebug('Sending with sendmail'); - } - $header = static::stripTrailingWSP($header) . static::$LE . static::$LE; - //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver - //A space after `-f` is optional, but there is a long history of its presence - //causing problems, so we don't use one - //Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html - //Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html - //Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html - //Example problem: https://www.drupal.org/node/1057954 - if (empty($this->Sender) && !empty(ini_get('sendmail_from'))) { - //PHP config has a sender address we can use - $this->Sender = ini_get('sendmail_from'); - } - //CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped. - if (!empty($this->Sender) && static::validateAddress($this->Sender) && self::isShellSafe($this->Sender)) { - if ($this->Mailer === 'qmail') { - $sendmailFmt = '%s -f%s'; - } else { - $sendmailFmt = '%s -oi -f%s -t'; - } - } else { - //allow sendmail to choose a default envelope sender. It may - //seem preferable to force it to use the From header as with - //SMTP, but that introduces new problems (see - //), and - //it has historically worked this way. - $sendmailFmt = '%s -oi -t'; - } - - $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender); - $this->edebug('Sendmail path: ' . $this->Sendmail); - $this->edebug('Sendmail command: ' . $sendmail); - $this->edebug('Envelope sender: ' . $this->Sender); - $this->edebug("Headers: {$header}"); - - if ($this->SingleTo) { - foreach ($this->SingleToArray as $toAddr) { - $mail = @popen($sendmail, 'w'); - if (!$mail) { - throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); - } - $this->edebug("To: {$toAddr}"); - fwrite($mail, 'To: ' . $toAddr . "\n"); - fwrite($mail, $header); - fwrite($mail, $body); - $result = pclose($mail); - $addrinfo = static::parseAddresses($toAddr); - $this->doCallback( - ($result === 0), - [[$addrinfo['address'], $addrinfo['name']]], - $this->cc, - $this->bcc, - $this->Subject, - $body, - $this->From, - [] - ); - $this->edebug("Result: " . ($result === 0 ? 'true' : 'false')); - if (0 !== $result) { - throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); - } - } - } else { - $mail = @popen($sendmail, 'w'); - if (!$mail) { - throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); - } - fwrite($mail, $header); - fwrite($mail, $body); - $result = pclose($mail); - $this->doCallback( - ($result === 0), - $this->to, - $this->cc, - $this->bcc, - $this->Subject, - $body, - $this->From, - [] - ); - $this->edebug("Result: " . ($result === 0 ? 'true' : 'false')); - if (0 !== $result) { - throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); - } - } - - return true; - } - - /** - * Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters. - * Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows. - * - * @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report - * - * @param string $string The string to be validated - * - * @return bool - */ - protected static function isShellSafe($string) - { - //Future-proof - if ( - escapeshellcmd($string) !== $string - || !in_array(escapeshellarg($string), ["'$string'", "\"$string\""]) - ) { - return false; - } - - $length = strlen($string); - - for ($i = 0; $i < $length; ++$i) { - $c = $string[$i]; - - //All other characters have a special meaning in at least one common shell, including = and +. - //Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here. - //Note that this does permit non-Latin alphanumeric characters based on the current locale. - if (!ctype_alnum($c) && strpos('@_-.', $c) === false) { - return false; - } - } - - return true; - } - - /** - * Check whether a file path is of a permitted type. - * Used to reject URLs and phar files from functions that access local file paths, - * such as addAttachment. - * - * @param string $path A relative or absolute path to a file - * - * @return bool - */ - protected static function isPermittedPath($path) - { - //Matches scheme definition from https://tools.ietf.org/html/rfc3986#section-3.1 - return !preg_match('#^[a-z][a-z\d+.-]*://#i', $path); - } - - /** - * Check whether a file path is safe, accessible, and readable. - * - * @param string $path A relative or absolute path to a file - * - * @return bool - */ - protected static function fileIsAccessible($path) - { - if (!static::isPermittedPath($path)) { - return false; - } - $readable = file_exists($path); - //If not a UNC path (expected to start with \\), check read permission, see #2069 - if (strpos($path, '\\\\') !== 0) { - $readable = $readable && is_readable($path); - } - return $readable; - } - - /** - * Send mail using the PHP mail() function. - * - * @see http://www.php.net/manual/en/book.mail.php - * - * @param string $header The message headers - * @param string $body The message body - * - * @throws Exception - * - * @return bool - */ - protected function mailSend($header, $body) - { - $header = static::stripTrailingWSP($header) . static::$LE . static::$LE; - - $toArr = []; - foreach ($this->to as $toaddr) { - $toArr[] = $this->addrFormat($toaddr); - } - $to = implode(', ', $toArr); - - $params = null; - //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver - //A space after `-f` is optional, but there is a long history of its presence - //causing problems, so we don't use one - //Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html - //Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html - //Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html - //Example problem: https://www.drupal.org/node/1057954 - //CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped. - if (empty($this->Sender) && !empty(ini_get('sendmail_from'))) { - //PHP config has a sender address we can use - $this->Sender = ini_get('sendmail_from'); - } - if (!empty($this->Sender) && static::validateAddress($this->Sender)) { - if (self::isShellSafe($this->Sender)) { - $params = sprintf('-f%s', $this->Sender); - } - $old_from = ini_get('sendmail_from'); - ini_set('sendmail_from', $this->Sender); - } - $result = false; - if ($this->SingleTo && count($toArr) > 1) { - foreach ($toArr as $toAddr) { - $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params); - $addrinfo = static::parseAddresses($toAddr); - $this->doCallback( - $result, - [[$addrinfo['address'], $addrinfo['name']]], - $this->cc, - $this->bcc, - $this->Subject, - $body, - $this->From, - [] - ); - } - } else { - $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params); - $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From, []); - } - if (isset($old_from)) { - ini_set('sendmail_from', $old_from); - } - if (!$result) { - throw new Exception($this->lang('instantiate'), self::STOP_CRITICAL); - } - - return true; - } - - /** - * Get an instance to use for SMTP operations. - * Override this function to load your own SMTP implementation, - * or set one with setSMTPInstance. - * - * @return SMTP - */ - public function getSMTPInstance() - { - if (!is_object($this->smtp)) { - $this->smtp = new SMTP(); - } - - return $this->smtp; - } - - /** - * Provide an instance to use for SMTP operations. - * - * @return SMTP - */ - public function setSMTPInstance(SMTP $smtp) - { - $this->smtp = $smtp; - - return $this->smtp; - } - - /** - * Send mail via SMTP. - * Returns false if there is a bad MAIL FROM, RCPT, or DATA input. - * - * @see PHPMailer::setSMTPInstance() to use a different class. - * - * @uses \PHPMailer\PHPMailer\SMTP - * - * @param string $header The message headers - * @param string $body The message body - * - * @throws Exception - * - * @return bool - */ - protected function smtpSend($header, $body) - { - $header = static::stripTrailingWSP($header) . static::$LE . static::$LE; - $bad_rcpt = []; - if (!$this->smtpConnect($this->SMTPOptions)) { - throw new Exception($this->lang('smtp_connect_failed'), self::STOP_CRITICAL); - } - //Sender already validated in preSend() - if ('' === $this->Sender) { - $smtp_from = $this->From; - } else { - $smtp_from = $this->Sender; - } - if (!$this->smtp->mail($smtp_from)) { - $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError())); - throw new Exception($this->ErrorInfo, self::STOP_CRITICAL); - } - - $callbacks = []; - //Attempt to send to all recipients - foreach ([$this->to, $this->cc, $this->bcc] as $togroup) { - foreach ($togroup as $to) { - if (!$this->smtp->recipient($to[0], $this->dsn)) { - $error = $this->smtp->getError(); - $bad_rcpt[] = ['to' => $to[0], 'error' => $error['detail']]; - $isSent = false; - } else { - $isSent = true; - } - - $callbacks[] = ['issent' => $isSent, 'to' => $to[0], 'name' => $to[1]]; - } - } - - //Only send the DATA command if we have viable recipients - if ((count($this->all_recipients) > count($bad_rcpt)) && !$this->smtp->data($header . $body)) { - throw new Exception($this->lang('data_not_accepted'), self::STOP_CRITICAL); - } - - $smtp_transaction_id = $this->smtp->getLastTransactionID(); - - if ($this->SMTPKeepAlive) { - $this->smtp->reset(); - } else { - $this->smtp->quit(); - $this->smtp->close(); - } - - foreach ($callbacks as $cb) { - $this->doCallback( - $cb['issent'], - [[$cb['to'], $cb['name']]], - [], - [], - $this->Subject, - $body, - $this->From, - ['smtp_transaction_id' => $smtp_transaction_id] - ); - } - - //Create error message for any bad addresses - if (count($bad_rcpt) > 0) { - $errstr = ''; - foreach ($bad_rcpt as $bad) { - $errstr .= $bad['to'] . ': ' . $bad['error']; - } - throw new Exception($this->lang('recipients_failed') . $errstr, self::STOP_CONTINUE); - } - - return true; - } - - /** - * Initiate a connection to an SMTP server. - * Returns false if the operation failed. - * - * @param array $options An array of options compatible with stream_context_create() - * - * @throws Exception - * - * @uses \PHPMailer\PHPMailer\SMTP - * - * @return bool - */ - public function smtpConnect($options = null) - { - if (null === $this->smtp) { - $this->smtp = $this->getSMTPInstance(); - } - - //If no options are provided, use whatever is set in the instance - if (null === $options) { - $options = $this->SMTPOptions; - } - - //Already connected? - if ($this->smtp->connected()) { - return true; - } - - $this->smtp->setTimeout($this->Timeout); - $this->smtp->setDebugLevel($this->SMTPDebug); - $this->smtp->setDebugOutput($this->Debugoutput); - $this->smtp->setVerp($this->do_verp); - $hosts = explode(';', $this->Host); - $lastexception = null; - - foreach ($hosts as $hostentry) { - $hostinfo = []; - if ( - !preg_match( - '/^(?:(ssl|tls):\/\/)?(.+?)(?::(\d+))?$/', - trim($hostentry), - $hostinfo - ) - ) { - $this->edebug($this->lang('invalid_hostentry') . ' ' . trim($hostentry)); - //Not a valid host entry - continue; - } - //$hostinfo[1]: optional ssl or tls prefix - //$hostinfo[2]: the hostname - //$hostinfo[3]: optional port number - //The host string prefix can temporarily override the current setting for SMTPSecure - //If it's not specified, the default value is used - - //Check the host name is a valid name or IP address before trying to use it - if (!static::isValidHost($hostinfo[2])) { - $this->edebug($this->lang('invalid_host') . ' ' . $hostinfo[2]); - continue; - } - $prefix = ''; - $secure = $this->SMTPSecure; - $tls = (static::ENCRYPTION_STARTTLS === $this->SMTPSecure); - if ('ssl' === $hostinfo[1] || ('' === $hostinfo[1] && static::ENCRYPTION_SMTPS === $this->SMTPSecure)) { - $prefix = 'ssl://'; - $tls = false; //Can't have SSL and TLS at the same time - $secure = static::ENCRYPTION_SMTPS; - } elseif ('tls' === $hostinfo[1]) { - $tls = true; - //TLS doesn't use a prefix - $secure = static::ENCRYPTION_STARTTLS; - } - //Do we need the OpenSSL extension? - $sslext = defined('OPENSSL_ALGO_SHA256'); - if (static::ENCRYPTION_STARTTLS === $secure || static::ENCRYPTION_SMTPS === $secure) { - //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled - if (!$sslext) { - throw new Exception($this->lang('extension_missing') . 'openssl', self::STOP_CRITICAL); - } - } - $host = $hostinfo[2]; - $port = $this->Port; - if ( - array_key_exists(3, $hostinfo) && - is_numeric($hostinfo[3]) && - $hostinfo[3] > 0 && - $hostinfo[3] < 65536 - ) { - $port = (int) $hostinfo[3]; - } - if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) { - try { - if ($this->Helo) { - $hello = $this->Helo; - } else { - $hello = $this->serverHostname(); - } - $this->smtp->hello($hello); - //Automatically enable TLS encryption if: - //* it's not disabled - //* we have openssl extension - //* we are not already using SSL - //* the server offers STARTTLS - if ($this->SMTPAutoTLS && $sslext && 'ssl' !== $secure && $this->smtp->getServerExt('STARTTLS')) { - $tls = true; - } - if ($tls) { - if (!$this->smtp->startTLS()) { - throw new Exception($this->lang('connect_host')); - } - //We must resend EHLO after TLS negotiation - $this->smtp->hello($hello); - } - if ( - $this->SMTPAuth && !$this->smtp->authenticate( - $this->Username, - $this->Password, - $this->AuthType, - $this->oauth - ) - ) { - throw new Exception($this->lang('authenticate')); - } - - return true; - } catch (Exception $exc) { - $lastexception = $exc; - $this->edebug($exc->getMessage()); - //We must have connected, but then failed TLS or Auth, so close connection nicely - $this->smtp->quit(); - } - } - } - //If we get here, all connection attempts have failed, so close connection hard - $this->smtp->close(); - //As we've caught all exceptions, just report whatever the last one was - if ($this->exceptions && null !== $lastexception) { - throw $lastexception; - } - - return false; - } - - /** - * Close the active SMTP session if one exists. - */ - public function smtpClose() - { - if ((null !== $this->smtp) && $this->smtp->connected()) { - $this->smtp->quit(); - $this->smtp->close(); - } - } - - /** - * Set the language for error messages. - * Returns false if it cannot load the language file. - * The default language is English. - * - * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr") - * @param string $lang_path Path to the language file directory, with trailing separator (slash).D - * Do not set this from user input! - * - * @return bool - */ - public function setLanguage($langcode = 'en', $lang_path = '') - { - //Backwards compatibility for renamed language codes - $renamed_langcodes = [ - 'br' => 'pt_br', - 'cz' => 'cs', - 'dk' => 'da', - 'no' => 'nb', - 'se' => 'sv', - 'rs' => 'sr', - 'tg' => 'tl', - 'am' => 'hy', - ]; - - if (array_key_exists($langcode, $renamed_langcodes)) { - $langcode = $renamed_langcodes[$langcode]; - } - - //Define full set of translatable strings in English - $PHPMAILER_LANG = [ - 'authenticate' => 'SMTP Error: Could not authenticate.', - 'connect_host' => 'SMTP Error: Could not connect to SMTP host.', - 'data_not_accepted' => 'SMTP Error: data not accepted.', - 'empty_message' => 'Message body empty', - 'encoding' => 'Unknown encoding: ', - 'execute' => 'Could not execute: ', - 'file_access' => 'Could not access file: ', - 'file_open' => 'File Error: Could not open file: ', - 'from_failed' => 'The following From address failed: ', - 'instantiate' => 'Could not instantiate mail function.', - 'invalid_address' => 'Invalid address: ', - 'invalid_hostentry' => 'Invalid hostentry: ', - 'invalid_host' => 'Invalid host: ', - 'mailer_not_supported' => ' mailer is not supported.', - 'provide_address' => 'You must provide at least one recipient email address.', - 'recipients_failed' => 'SMTP Error: The following recipients failed: ', - 'signing' => 'Signing Error: ', - 'smtp_connect_failed' => 'SMTP connect() failed.', - 'smtp_error' => 'SMTP server error: ', - 'variable_set' => 'Cannot set or reset variable: ', - 'extension_missing' => 'Extension missing: ', - ]; - if (empty($lang_path)) { - //Calculate an absolute path so it can work if CWD is not here - $lang_path = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'language' . DIRECTORY_SEPARATOR; - } - //Validate $langcode - if (!preg_match('/^[a-z]{2}(?:_[a-zA-Z]{2})?$/', $langcode)) { - $langcode = 'en'; - } - $foundlang = true; - $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php'; - //There is no English translation file - if ('en' !== $langcode) { - //Make sure language file path is readable - if (!static::fileIsAccessible($lang_file)) { - $foundlang = false; - } else { - //$foundlang = include $lang_file; - $lines = file($lang_file); - foreach ($lines as $line) { - //Translation file lines look like this: - //$PHPMAILER_LANG['authenticate'] = 'SMTP-Fehler: Authentifizierung fehlgeschlagen.'; - //These files are parsed as text and not PHP so as to avoid the possibility of code injection - //See https://blog.stevenlevithan.com/archives/match-quoted-string - $matches = []; - if ( - preg_match( - '/^\$PHPMAILER_LANG\[\'([a-z\d_]+)\'\]\s*=\s*(["\'])(.+)*?\2;/', - $line, - $matches - ) && - //Ignore unknown translation keys - array_key_exists($matches[1], $PHPMAILER_LANG) - ) { - //Overwrite language-specific strings so we'll never have missing translation keys. - $PHPMAILER_LANG[$matches[1]] = (string)$matches[3]; - } - } - } - } - $this->language = $PHPMAILER_LANG; - - return $foundlang; //Returns false if language not found - } - - /** - * Get the array of strings for the current language. - * - * @return array - */ - public function getTranslations() - { - return $this->language; - } - - /** - * Create recipient headers. - * - * @param string $type - * @param array $addr An array of recipients, - * where each recipient is a 2-element indexed array with element 0 containing an address - * and element 1 containing a name, like: - * [['joe@example.com', 'Joe User'], ['zoe@example.com', 'Zoe User']] - * - * @return string - */ - public function addrAppend($type, $addr) - { - $addresses = []; - foreach ($addr as $address) { - $addresses[] = $this->addrFormat($address); - } - - return $type . ': ' . implode(', ', $addresses) . static::$LE; - } - - /** - * Format an address for use in a message header. - * - * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name like - * ['joe@example.com', 'Joe User'] - * - * @return string - */ - public function addrFormat($addr) - { - if (empty($addr[1])) { //No name provided - return $this->secureHeader($addr[0]); - } - - return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . - ' <' . $this->secureHeader($addr[0]) . '>'; - } - - /** - * Word-wrap message. - * For use with mailers that do not automatically perform wrapping - * and for quoted-printable encoded messages. - * Original written by philippe. - * - * @param string $message The message to wrap - * @param int $length The line length to wrap to - * @param bool $qp_mode Whether to run in Quoted-Printable mode - * - * @return string - */ - public function wrapText($message, $length, $qp_mode = false) - { - if ($qp_mode) { - $soft_break = sprintf(' =%s', static::$LE); - } else { - $soft_break = static::$LE; - } - //If utf-8 encoding is used, we will need to make sure we don't - //split multibyte characters when we wrap - $is_utf8 = static::CHARSET_UTF8 === strtolower($this->CharSet); - $lelen = strlen(static::$LE); - $crlflen = strlen(static::$LE); - - $message = static::normalizeBreaks($message); - //Remove a trailing line break - if (substr($message, -$lelen) === static::$LE) { - $message = substr($message, 0, -$lelen); - } - - //Split message into lines - $lines = explode(static::$LE, $message); - //Message will be rebuilt in here - $message = ''; - foreach ($lines as $line) { - $words = explode(' ', $line); - $buf = ''; - $firstword = true; - foreach ($words as $word) { - if ($qp_mode && (strlen($word) > $length)) { - $space_left = $length - strlen($buf) - $crlflen; - if (!$firstword) { - if ($space_left > 20) { - $len = $space_left; - if ($is_utf8) { - $len = $this->utf8CharBoundary($word, $len); - } elseif ('=' === substr($word, $len - 1, 1)) { - --$len; - } elseif ('=' === substr($word, $len - 2, 1)) { - $len -= 2; - } - $part = substr($word, 0, $len); - $word = substr($word, $len); - $buf .= ' ' . $part; - $message .= $buf . sprintf('=%s', static::$LE); - } else { - $message .= $buf . $soft_break; - } - $buf = ''; - } - while ($word !== '') { - if ($length <= 0) { - break; - } - $len = $length; - if ($is_utf8) { - $len = $this->utf8CharBoundary($word, $len); - } elseif ('=' === substr($word, $len - 1, 1)) { - --$len; - } elseif ('=' === substr($word, $len - 2, 1)) { - $len -= 2; - } - $part = substr($word, 0, $len); - $word = (string) substr($word, $len); - - if ($word !== '') { - $message .= $part . sprintf('=%s', static::$LE); - } else { - $buf = $part; - } - } - } else { - $buf_o = $buf; - if (!$firstword) { - $buf .= ' '; - } - $buf .= $word; - - if ('' !== $buf_o && strlen($buf) > $length) { - $message .= $buf_o . $soft_break; - $buf = $word; - } - } - $firstword = false; - } - $message .= $buf . static::$LE; - } - - return $message; - } - - /** - * Find the last character boundary prior to $maxLength in a utf-8 - * quoted-printable encoded string. - * Original written by Colin Brown. - * - * @param string $encodedText utf-8 QP text - * @param int $maxLength Find the last character boundary prior to this length - * - * @return int - */ - public function utf8CharBoundary($encodedText, $maxLength) - { - $foundSplitPos = false; - $lookBack = 3; - while (!$foundSplitPos) { - $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack); - $encodedCharPos = strpos($lastChunk, '='); - if (false !== $encodedCharPos) { - //Found start of encoded character byte within $lookBack block. - //Check the encoded byte value (the 2 chars after the '=') - $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2); - $dec = hexdec($hex); - if ($dec < 128) { - //Single byte character. - //If the encoded char was found at pos 0, it will fit - //otherwise reduce maxLength to start of the encoded char - if ($encodedCharPos > 0) { - $maxLength -= $lookBack - $encodedCharPos; - } - $foundSplitPos = true; - } elseif ($dec >= 192) { - //First byte of a multi byte character - //Reduce maxLength to split at start of character - $maxLength -= $lookBack - $encodedCharPos; - $foundSplitPos = true; - } elseif ($dec < 192) { - //Middle byte of a multi byte character, look further back - $lookBack += 3; - } - } else { - //No encoded character found - $foundSplitPos = true; - } - } - - return $maxLength; - } - - /** - * Apply word wrapping to the message body. - * Wraps the message body to the number of chars set in the WordWrap property. - * You should only do this to plain-text bodies as wrapping HTML tags may break them. - * This is called automatically by createBody(), so you don't need to call it yourself. - */ - public function setWordWrap() - { - if ($this->WordWrap < 1) { - return; - } - - switch ($this->message_type) { - case 'alt': - case 'alt_inline': - case 'alt_attach': - case 'alt_inline_attach': - $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap); - break; - default: - $this->Body = $this->wrapText($this->Body, $this->WordWrap); - break; - } - } - - /** - * Assemble message headers. - * - * @return string The assembled headers - */ - public function createHeader() - { - $result = ''; - - $result .= $this->headerLine('Date', '' === $this->MessageDate ? self::rfcDate() : $this->MessageDate); - - //The To header is created automatically by mail(), so needs to be omitted here - if ('mail' !== $this->Mailer) { - if ($this->SingleTo) { - foreach ($this->to as $toaddr) { - $this->SingleToArray[] = $this->addrFormat($toaddr); - } - } elseif (count($this->to) > 0) { - $result .= $this->addrAppend('To', $this->to); - } elseif (count($this->cc) === 0) { - $result .= $this->headerLine('To', 'undisclosed-recipients:;'); - } - } - $result .= $this->addrAppend('From', [[trim($this->From), $this->FromName]]); - - //sendmail and mail() extract Cc from the header before sending - if (count($this->cc) > 0) { - $result .= $this->addrAppend('Cc', $this->cc); - } - - //sendmail and mail() extract Bcc from the header before sending - if ( - ( - 'sendmail' === $this->Mailer || 'qmail' === $this->Mailer || 'mail' === $this->Mailer - ) - && count($this->bcc) > 0 - ) { - $result .= $this->addrAppend('Bcc', $this->bcc); - } - - if (count($this->ReplyTo) > 0) { - $result .= $this->addrAppend('Reply-To', $this->ReplyTo); - } - - //mail() sets the subject itself - if ('mail' !== $this->Mailer) { - $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject))); - } - - //Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4 - //https://tools.ietf.org/html/rfc5322#section-3.6.4 - if ( - '' !== $this->MessageID && - preg_match( - '/^<((([a-z\d!#$%&\'*+\/=?^_`{|}~-]+(\.[a-z\d!#$%&\'*+\/=?^_`{|}~-]+)*)' . - '|("(([\x01-\x08\x0B\x0C\x0E-\x1F\x7F]|[\x21\x23-\x5B\x5D-\x7E])' . - '|(\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*"))@(([a-z\d!#$%&\'*+\/=?^_`{|}~-]+' . - '(\.[a-z\d!#$%&\'*+\/=?^_`{|}~-]+)*)|(\[(([\x01-\x08\x0B\x0C\x0E-\x1F\x7F]' . - '|[\x21-\x5A\x5E-\x7E])|(\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*\])))>$/Di', - $this->MessageID - ) - ) { - $this->lastMessageID = $this->MessageID; - } else { - $this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname()); - } - $result .= $this->headerLine('Message-ID', $this->lastMessageID); - if (null !== $this->Priority) { - $result .= $this->headerLine('X-Priority', $this->Priority); - } - if ('' === $this->XMailer) { - $result .= $this->headerLine( - 'X-Mailer', - 'PHPMailer ' . self::VERSION . ' (https://github.com/PHPMailer/PHPMailer)' - ); - } else { - $myXmailer = trim($this->XMailer); - if ($myXmailer) { - $result .= $this->headerLine('X-Mailer', $myXmailer); - } - } - - if ('' !== $this->ConfirmReadingTo) { - $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>'); - } - - //Add custom headers - foreach ($this->CustomHeader as $header) { - $result .= $this->headerLine( - trim($header[0]), - $this->encodeHeader(trim($header[1])) - ); - } - if (!$this->sign_key_file) { - $result .= $this->headerLine('MIME-Version', '1.0'); - $result .= $this->getMailMIME(); - } - - return $result; - } - - /** - * Get the message MIME type headers. - * - * @return string - */ - public function getMailMIME() - { - $result = ''; - $ismultipart = true; - switch ($this->message_type) { - case 'inline': - $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';'); - $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"'); - break; - case 'attach': - case 'inline_attach': - case 'alt_attach': - case 'alt_inline_attach': - $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_MIXED . ';'); - $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"'); - break; - case 'alt': - case 'alt_inline': - $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';'); - $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"'); - break; - default: - //Catches case 'plain': and case '': - $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet); - $ismultipart = false; - break; - } - //RFC1341 part 5 says 7bit is assumed if not specified - if (static::ENCODING_7BIT !== $this->Encoding) { - //RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE - if ($ismultipart) { - if (static::ENCODING_8BIT === $this->Encoding) { - $result .= $this->headerLine('Content-Transfer-Encoding', static::ENCODING_8BIT); - } - //The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible - } else { - $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding); - } - } - - return $result; - } - - /** - * Returns the whole MIME message. - * Includes complete headers and body. - * Only valid post preSend(). - * - * @see PHPMailer::preSend() - * - * @return string - */ - public function getSentMIMEMessage() - { - return static::stripTrailingWSP($this->MIMEHeader . $this->mailHeader) . - static::$LE . static::$LE . $this->MIMEBody; - } - - /** - * Create a unique ID to use for boundaries. - * - * @return string - */ - protected function generateId() - { - $len = 32; //32 bytes = 256 bits - $bytes = ''; - if (function_exists('random_bytes')) { - try { - $bytes = random_bytes($len); - } catch (\Exception $e) { - //Do nothing - } - } elseif (function_exists('openssl_random_pseudo_bytes')) { - /** @noinspection CryptographicallySecureRandomnessInspection */ - $bytes = openssl_random_pseudo_bytes($len); - } - if ($bytes === '') { - //We failed to produce a proper random string, so make do. - //Use a hash to force the length to the same as the other methods - $bytes = hash('sha256', uniqid((string) mt_rand(), true), true); - } - - //We don't care about messing up base64 format here, just want a random string - return str_replace(['=', '+', '/'], '', base64_encode(hash('sha256', $bytes, true))); - } - - /** - * Assemble the message body. - * Returns an empty string on failure. - * - * @throws Exception - * - * @return string The assembled message body - */ - public function createBody() - { - $body = ''; - //Create unique IDs and preset boundaries - $this->uniqueid = $this->generateId(); - $this->boundary[1] = 'b1_' . $this->uniqueid; - $this->boundary[2] = 'b2_' . $this->uniqueid; - $this->boundary[3] = 'b3_' . $this->uniqueid; - - if ($this->sign_key_file) { - $body .= $this->getMailMIME() . static::$LE; - } - - $this->setWordWrap(); - - $bodyEncoding = $this->Encoding; - $bodyCharSet = $this->CharSet; - //Can we do a 7-bit downgrade? - if (static::ENCODING_8BIT === $bodyEncoding && !$this->has8bitChars($this->Body)) { - $bodyEncoding = static::ENCODING_7BIT; - //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit - $bodyCharSet = static::CHARSET_ASCII; - } - //If lines are too long, and we're not already using an encoding that will shorten them, - //change to quoted-printable transfer encoding for the body part only - if (static::ENCODING_BASE64 !== $this->Encoding && static::hasLineLongerThanMax($this->Body)) { - $bodyEncoding = static::ENCODING_QUOTED_PRINTABLE; - } - - $altBodyEncoding = $this->Encoding; - $altBodyCharSet = $this->CharSet; - //Can we do a 7-bit downgrade? - if (static::ENCODING_8BIT === $altBodyEncoding && !$this->has8bitChars($this->AltBody)) { - $altBodyEncoding = static::ENCODING_7BIT; - //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit - $altBodyCharSet = static::CHARSET_ASCII; - } - //If lines are too long, and we're not already using an encoding that will shorten them, - //change to quoted-printable transfer encoding for the alt body part only - if (static::ENCODING_BASE64 !== $altBodyEncoding && static::hasLineLongerThanMax($this->AltBody)) { - $altBodyEncoding = static::ENCODING_QUOTED_PRINTABLE; - } - //Use this as a preamble in all multipart message types - $mimepre = 'This is a multi-part message in MIME format.' . static::$LE . static::$LE; - switch ($this->message_type) { - case 'inline': - $body .= $mimepre; - $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding); - $body .= $this->encodeString($this->Body, $bodyEncoding); - $body .= static::$LE; - $body .= $this->attachAll('inline', $this->boundary[1]); - break; - case 'attach': - $body .= $mimepre; - $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding); - $body .= $this->encodeString($this->Body, $bodyEncoding); - $body .= static::$LE; - $body .= $this->attachAll('attachment', $this->boundary[1]); - break; - case 'inline_attach': - $body .= $mimepre; - $body .= $this->textLine('--' . $this->boundary[1]); - $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';'); - $body .= $this->textLine(' boundary="' . $this->boundary[2] . '";'); - $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"'); - $body .= static::$LE; - $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding); - $body .= $this->encodeString($this->Body, $bodyEncoding); - $body .= static::$LE; - $body .= $this->attachAll('inline', $this->boundary[2]); - $body .= static::$LE; - $body .= $this->attachAll('attachment', $this->boundary[1]); - break; - case 'alt': - $body .= $mimepre; - $body .= $this->getBoundary( - $this->boundary[1], - $altBodyCharSet, - static::CONTENT_TYPE_PLAINTEXT, - $altBodyEncoding - ); - $body .= $this->encodeString($this->AltBody, $altBodyEncoding); - $body .= static::$LE; - $body .= $this->getBoundary( - $this->boundary[1], - $bodyCharSet, - static::CONTENT_TYPE_TEXT_HTML, - $bodyEncoding - ); - $body .= $this->encodeString($this->Body, $bodyEncoding); - $body .= static::$LE; - if (!empty($this->Ical)) { - $method = static::ICAL_METHOD_REQUEST; - foreach (static::$IcalMethods as $imethod) { - if (stripos($this->Ical, 'METHOD:' . $imethod) !== false) { - $method = $imethod; - break; - } - } - $body .= $this->getBoundary( - $this->boundary[1], - '', - static::CONTENT_TYPE_TEXT_CALENDAR . '; method=' . $method, - '' - ); - $body .= $this->encodeString($this->Ical, $this->Encoding); - $body .= static::$LE; - } - $body .= $this->endBoundary($this->boundary[1]); - break; - case 'alt_inline': - $body .= $mimepre; - $body .= $this->getBoundary( - $this->boundary[1], - $altBodyCharSet, - static::CONTENT_TYPE_PLAINTEXT, - $altBodyEncoding - ); - $body .= $this->encodeString($this->AltBody, $altBodyEncoding); - $body .= static::$LE; - $body .= $this->textLine('--' . $this->boundary[1]); - $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';'); - $body .= $this->textLine(' boundary="' . $this->boundary[2] . '";'); - $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"'); - $body .= static::$LE; - $body .= $this->getBoundary( - $this->boundary[2], - $bodyCharSet, - static::CONTENT_TYPE_TEXT_HTML, - $bodyEncoding - ); - $body .= $this->encodeString($this->Body, $bodyEncoding); - $body .= static::$LE; - $body .= $this->attachAll('inline', $this->boundary[2]); - $body .= static::$LE; - $body .= $this->endBoundary($this->boundary[1]); - break; - case 'alt_attach': - $body .= $mimepre; - $body .= $this->textLine('--' . $this->boundary[1]); - $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';'); - $body .= $this->textLine(' boundary="' . $this->boundary[2] . '"'); - $body .= static::$LE; - $body .= $this->getBoundary( - $this->boundary[2], - $altBodyCharSet, - static::CONTENT_TYPE_PLAINTEXT, - $altBodyEncoding - ); - $body .= $this->encodeString($this->AltBody, $altBodyEncoding); - $body .= static::$LE; - $body .= $this->getBoundary( - $this->boundary[2], - $bodyCharSet, - static::CONTENT_TYPE_TEXT_HTML, - $bodyEncoding - ); - $body .= $this->encodeString($this->Body, $bodyEncoding); - $body .= static::$LE; - if (!empty($this->Ical)) { - $method = static::ICAL_METHOD_REQUEST; - foreach (static::$IcalMethods as $imethod) { - if (stripos($this->Ical, 'METHOD:' . $imethod) !== false) { - $method = $imethod; - break; - } - } - $body .= $this->getBoundary( - $this->boundary[2], - '', - static::CONTENT_TYPE_TEXT_CALENDAR . '; method=' . $method, - '' - ); - $body .= $this->encodeString($this->Ical, $this->Encoding); - } - $body .= $this->endBoundary($this->boundary[2]); - $body .= static::$LE; - $body .= $this->attachAll('attachment', $this->boundary[1]); - break; - case 'alt_inline_attach': - $body .= $mimepre; - $body .= $this->textLine('--' . $this->boundary[1]); - $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';'); - $body .= $this->textLine(' boundary="' . $this->boundary[2] . '"'); - $body .= static::$LE; - $body .= $this->getBoundary( - $this->boundary[2], - $altBodyCharSet, - static::CONTENT_TYPE_PLAINTEXT, - $altBodyEncoding - ); - $body .= $this->encodeString($this->AltBody, $altBodyEncoding); - $body .= static::$LE; - $body .= $this->textLine('--' . $this->boundary[2]); - $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';'); - $body .= $this->textLine(' boundary="' . $this->boundary[3] . '";'); - $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"'); - $body .= static::$LE; - $body .= $this->getBoundary( - $this->boundary[3], - $bodyCharSet, - static::CONTENT_TYPE_TEXT_HTML, - $bodyEncoding - ); - $body .= $this->encodeString($this->Body, $bodyEncoding); - $body .= static::$LE; - $body .= $this->attachAll('inline', $this->boundary[3]); - $body .= static::$LE; - $body .= $this->endBoundary($this->boundary[2]); - $body .= static::$LE; - $body .= $this->attachAll('attachment', $this->boundary[1]); - break; - default: - //Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types - //Reset the `Encoding` property in case we changed it for line length reasons - $this->Encoding = $bodyEncoding; - $body .= $this->encodeString($this->Body, $this->Encoding); - break; - } - - if ($this->isError()) { - $body = ''; - if ($this->exceptions) { - throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL); - } - } elseif ($this->sign_key_file) { - try { - if (!defined('PKCS7_TEXT')) { - throw new Exception($this->lang('extension_missing') . 'openssl'); - } - - $file = tempnam(sys_get_temp_dir(), 'srcsign'); - $signed = tempnam(sys_get_temp_dir(), 'mailsign'); - file_put_contents($file, $body); - - //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197 - if (empty($this->sign_extracerts_file)) { - $sign = @openssl_pkcs7_sign( - $file, - $signed, - 'file://' . realpath($this->sign_cert_file), - ['file://' . realpath($this->sign_key_file), $this->sign_key_pass], - [] - ); - } else { - $sign = @openssl_pkcs7_sign( - $file, - $signed, - 'file://' . realpath($this->sign_cert_file), - ['file://' . realpath($this->sign_key_file), $this->sign_key_pass], - [], - PKCS7_DETACHED, - $this->sign_extracerts_file - ); - } - - @unlink($file); - if ($sign) { - $body = file_get_contents($signed); - @unlink($signed); - //The message returned by openssl contains both headers and body, so need to split them up - $parts = explode("\n\n", $body, 2); - $this->MIMEHeader .= $parts[0] . static::$LE . static::$LE; - $body = $parts[1]; - } else { - @unlink($signed); - throw new Exception($this->lang('signing') . openssl_error_string()); - } - } catch (Exception $exc) { - $body = ''; - if ($this->exceptions) { - throw $exc; - } - } - } - - return $body; - } - - /** - * Return the start of a message boundary. - * - * @param string $boundary - * @param string $charSet - * @param string $contentType - * @param string $encoding - * - * @return string - */ - protected function getBoundary($boundary, $charSet, $contentType, $encoding) - { - $result = ''; - if ('' === $charSet) { - $charSet = $this->CharSet; - } - if ('' === $contentType) { - $contentType = $this->ContentType; - } - if ('' === $encoding) { - $encoding = $this->Encoding; - } - $result .= $this->textLine('--' . $boundary); - $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet); - $result .= static::$LE; - //RFC1341 part 5 says 7bit is assumed if not specified - if (static::ENCODING_7BIT !== $encoding) { - $result .= $this->headerLine('Content-Transfer-Encoding', $encoding); - } - $result .= static::$LE; - - return $result; - } - - /** - * Return the end of a message boundary. - * - * @param string $boundary - * - * @return string - */ - protected function endBoundary($boundary) - { - return static::$LE . '--' . $boundary . '--' . static::$LE; - } - - /** - * Set the message type. - * PHPMailer only supports some preset message types, not arbitrary MIME structures. - */ - protected function setMessageType() - { - $type = []; - if ($this->alternativeExists()) { - $type[] = 'alt'; - } - if ($this->inlineImageExists()) { - $type[] = 'inline'; - } - if ($this->attachmentExists()) { - $type[] = 'attach'; - } - $this->message_type = implode('_', $type); - if ('' === $this->message_type) { - //The 'plain' message_type refers to the message having a single body element, not that it is plain-text - $this->message_type = 'plain'; - } - } - - /** - * Format a header line. - * - * @param string $name - * @param string|int $value - * - * @return string - */ - public function headerLine($name, $value) - { - return $name . ': ' . $value . static::$LE; - } - - /** - * Return a formatted mail line. - * - * @param string $value - * - * @return string - */ - public function textLine($value) - { - return $value . static::$LE; - } - - /** - * Add an attachment from a path on the filesystem. - * Never use a user-supplied path to a file! - * Returns false if the file could not be found or read. - * Explicitly *does not* support passing URLs; PHPMailer is not an HTTP client. - * If you need to do that, fetch the resource yourself and pass it in via a local file or string. - * - * @param string $path Path to the attachment - * @param string $name Overrides the attachment name - * @param string $encoding File encoding (see $Encoding) - * @param string $type MIME type, e.g. `image/jpeg`; determined automatically from $path if not specified - * @param string $disposition Disposition to use - * - * @throws Exception - * - * @return bool - */ - public function addAttachment( - $path, - $name = '', - $encoding = self::ENCODING_BASE64, - $type = '', - $disposition = 'attachment' - ) { - try { - if (!static::fileIsAccessible($path)) { - throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE); - } - - //If a MIME type is not specified, try to work it out from the file name - if ('' === $type) { - $type = static::filenameToType($path); - } - - $filename = (string) static::mb_pathinfo($path, PATHINFO_BASENAME); - if ('' === $name) { - $name = $filename; - } - if (!$this->validateEncoding($encoding)) { - throw new Exception($this->lang('encoding') . $encoding); - } - - $this->attachment[] = [ - 0 => $path, - 1 => $filename, - 2 => $name, - 3 => $encoding, - 4 => $type, - 5 => false, //isStringAttachment - 6 => $disposition, - 7 => $name, - ]; - } catch (Exception $exc) { - $this->setError($exc->getMessage()); - $this->edebug($exc->getMessage()); - if ($this->exceptions) { - throw $exc; - } - - return false; - } - - return true; - } - - /** - * Return the array of attachments. - * - * @return array - */ - public function getAttachments() - { - return $this->attachment; - } - - /** - * Attach all file, string, and binary attachments to the message. - * Returns an empty string on failure. - * - * @param string $disposition_type - * @param string $boundary - * - * @throws Exception - * - * @return string - */ - protected function attachAll($disposition_type, $boundary) - { - //Return text of body - $mime = []; - $cidUniq = []; - $incl = []; - - //Add all attachments - foreach ($this->attachment as $attachment) { - //Check if it is a valid disposition_filter - if ($attachment[6] === $disposition_type) { - //Check for string attachment - $string = ''; - $path = ''; - $bString = $attachment[5]; - if ($bString) { - $string = $attachment[0]; - } else { - $path = $attachment[0]; - } - - $inclhash = hash('sha256', serialize($attachment)); - if (in_array($inclhash, $incl, true)) { - continue; - } - $incl[] = $inclhash; - $name = $attachment[2]; - $encoding = $attachment[3]; - $type = $attachment[4]; - $disposition = $attachment[6]; - $cid = $attachment[7]; - if ('inline' === $disposition && array_key_exists($cid, $cidUniq)) { - continue; - } - $cidUniq[$cid] = true; - - $mime[] = sprintf('--%s%s', $boundary, static::$LE); - //Only include a filename property if we have one - if (!empty($name)) { - $mime[] = sprintf( - 'Content-Type: %s; name=%s%s', - $type, - static::quotedString($this->encodeHeader($this->secureHeader($name))), - static::$LE - ); - } else { - $mime[] = sprintf( - 'Content-Type: %s%s', - $type, - static::$LE - ); - } - //RFC1341 part 5 says 7bit is assumed if not specified - if (static::ENCODING_7BIT !== $encoding) { - $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, static::$LE); - } - - //Only set Content-IDs on inline attachments - if ((string) $cid !== '' && $disposition === 'inline') { - $mime[] = 'Content-ID: <' . $this->encodeHeader($this->secureHeader($cid)) . '>' . static::$LE; - } - - //Allow for bypassing the Content-Disposition header - if (!empty($disposition)) { - $encoded_name = $this->encodeHeader($this->secureHeader($name)); - if (!empty($encoded_name)) { - $mime[] = sprintf( - 'Content-Disposition: %s; filename=%s%s', - $disposition, - static::quotedString($encoded_name), - static::$LE . static::$LE - ); - } else { - $mime[] = sprintf( - 'Content-Disposition: %s%s', - $disposition, - static::$LE . static::$LE - ); - } - } else { - $mime[] = static::$LE; - } - - //Encode as string attachment - if ($bString) { - $mime[] = $this->encodeString($string, $encoding); - } else { - $mime[] = $this->encodeFile($path, $encoding); - } - if ($this->isError()) { - return ''; - } - $mime[] = static::$LE; - } - } - - $mime[] = sprintf('--%s--%s', $boundary, static::$LE); - - return implode('', $mime); - } - - /** - * Encode a file attachment in requested format. - * Returns an empty string on failure. - * - * @param string $path The full path to the file - * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' - * - * @return string - */ - protected function encodeFile($path, $encoding = self::ENCODING_BASE64) - { - try { - if (!static::fileIsAccessible($path)) { - throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE); - } - $file_buffer = file_get_contents($path); - if (false === $file_buffer) { - throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE); - } - $file_buffer = $this->encodeString($file_buffer, $encoding); - - return $file_buffer; - } catch (Exception $exc) { - $this->setError($exc->getMessage()); - $this->edebug($exc->getMessage()); - if ($this->exceptions) { - throw $exc; - } - - return ''; - } - } - - /** - * Encode a string in requested format. - * Returns an empty string on failure. - * - * @param string $str The text to encode - * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' - * - * @throws Exception - * - * @return string - */ - public function encodeString($str, $encoding = self::ENCODING_BASE64) - { - $encoded = ''; - switch (strtolower($encoding)) { - case static::ENCODING_BASE64: - $encoded = chunk_split( - base64_encode($str), - static::STD_LINE_LENGTH, - static::$LE - ); - break; - case static::ENCODING_7BIT: - case static::ENCODING_8BIT: - $encoded = static::normalizeBreaks($str); - //Make sure it ends with a line break - if (substr($encoded, -(strlen(static::$LE))) !== static::$LE) { - $encoded .= static::$LE; - } - break; - case static::ENCODING_BINARY: - $encoded = $str; - break; - case static::ENCODING_QUOTED_PRINTABLE: - $encoded = $this->encodeQP($str); - break; - default: - $this->setError($this->lang('encoding') . $encoding); - if ($this->exceptions) { - throw new Exception($this->lang('encoding') . $encoding); - } - break; - } - - return $encoded; - } - - /** - * Encode a header value (not including its label) optimally. - * Picks shortest of Q, B, or none. Result includes folding if needed. - * See RFC822 definitions for phrase, comment and text positions. - * - * @param string $str The header value to encode - * @param string $position What context the string will be used in - * - * @return string - */ - public function encodeHeader($str, $position = 'text') - { - $matchcount = 0; - switch (strtolower($position)) { - case 'phrase': - if (!preg_match('/[\200-\377]/', $str)) { - //Can't use addslashes as we don't know the value of magic_quotes_sybase - $encoded = addcslashes($str, "\0..\37\177\\\""); - if (($str === $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) { - return $encoded; - } - - return "\"$encoded\""; - } - $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches); - break; - /* @noinspection PhpMissingBreakStatementInspection */ - case 'comment': - $matchcount = preg_match_all('/[()"]/', $str, $matches); - //fallthrough - case 'text': - default: - $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches); - break; - } - - if ($this->has8bitChars($str)) { - $charset = $this->CharSet; - } else { - $charset = static::CHARSET_ASCII; - } - - //Q/B encoding adds 8 chars and the charset ("` =??[QB]??=`"). - $overhead = 8 + strlen($charset); - - if ('mail' === $this->Mailer) { - $maxlen = static::MAIL_MAX_LINE_LENGTH - $overhead; - } else { - $maxlen = static::MAX_LINE_LENGTH - $overhead; - } - - //Select the encoding that produces the shortest output and/or prevents corruption. - if ($matchcount > strlen($str) / 3) { - //More than 1/3 of the content needs encoding, use B-encode. - $encoding = 'B'; - } elseif ($matchcount > 0) { - //Less than 1/3 of the content needs encoding, use Q-encode. - $encoding = 'Q'; - } elseif (strlen($str) > $maxlen) { - //No encoding needed, but value exceeds max line length, use Q-encode to prevent corruption. - $encoding = 'Q'; - } else { - //No reformatting needed - $encoding = false; - } - - switch ($encoding) { - case 'B': - if ($this->hasMultiBytes($str)) { - //Use a custom function which correctly encodes and wraps long - //multibyte strings without breaking lines within a character - $encoded = $this->base64EncodeWrapMB($str, "\n"); - } else { - $encoded = base64_encode($str); - $maxlen -= $maxlen % 4; - $encoded = trim(chunk_split($encoded, $maxlen, "\n")); - } - $encoded = preg_replace('/^(.*)$/m', ' =?' . $charset . "?$encoding?\\1?=", $encoded); - break; - case 'Q': - $encoded = $this->encodeQ($str, $position); - $encoded = $this->wrapText($encoded, $maxlen, true); - $encoded = str_replace('=' . static::$LE, "\n", trim($encoded)); - $encoded = preg_replace('/^(.*)$/m', ' =?' . $charset . "?$encoding?\\1?=", $encoded); - break; - default: - return $str; - } - - return trim(static::normalizeBreaks($encoded)); - } - - /** - * Check if a string contains multi-byte characters. - * - * @param string $str multi-byte text to wrap encode - * - * @return bool - */ - public function hasMultiBytes($str) - { - if (function_exists('mb_strlen')) { - return strlen($str) > mb_strlen($str, $this->CharSet); - } - - //Assume no multibytes (we can't handle without mbstring functions anyway) - return false; - } - - /** - * Does a string contain any 8-bit chars (in any charset)? - * - * @param string $text - * - * @return bool - */ - public function has8bitChars($text) - { - return (bool) preg_match('/[\x80-\xFF]/', $text); - } - - /** - * Encode and wrap long multibyte strings for mail headers - * without breaking lines within a character. - * Adapted from a function by paravoid. - * - * @see http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283 - * - * @param string $str multi-byte text to wrap encode - * @param string $linebreak string to use as linefeed/end-of-line - * - * @return string - */ - public function base64EncodeWrapMB($str, $linebreak = null) - { - $start = '=?' . $this->CharSet . '?B?'; - $end = '?='; - $encoded = ''; - if (null === $linebreak) { - $linebreak = static::$LE; - } - - $mb_length = mb_strlen($str, $this->CharSet); - //Each line must have length <= 75, including $start and $end - $length = 75 - strlen($start) - strlen($end); - //Average multi-byte ratio - $ratio = $mb_length / strlen($str); - //Base64 has a 4:3 ratio - $avgLength = floor($length * $ratio * .75); - - $offset = 0; - for ($i = 0; $i < $mb_length; $i += $offset) { - $lookBack = 0; - do { - $offset = $avgLength - $lookBack; - $chunk = mb_substr($str, $i, $offset, $this->CharSet); - $chunk = base64_encode($chunk); - ++$lookBack; - } while (strlen($chunk) > $length); - $encoded .= $chunk . $linebreak; - } - - //Chomp the last linefeed - return substr($encoded, 0, -strlen($linebreak)); - } - - /** - * Encode a string in quoted-printable format. - * According to RFC2045 section 6.7. - * - * @param string $string The text to encode - * - * @return string - */ - public function encodeQP($string) - { - return static::normalizeBreaks(quoted_printable_encode($string)); - } - - /** - * Encode a string using Q encoding. - * - * @see http://tools.ietf.org/html/rfc2047#section-4.2 - * - * @param string $str the text to encode - * @param string $position Where the text is going to be used, see the RFC for what that means - * - * @return string - */ - public function encodeQ($str, $position = 'text') - { - //There should not be any EOL in the string - $pattern = ''; - $encoded = str_replace(["\r", "\n"], '', $str); - switch (strtolower($position)) { - case 'phrase': - //RFC 2047 section 5.3 - $pattern = '^A-Za-z0-9!*+\/ -'; - break; - /* - * RFC 2047 section 5.2. - * Build $pattern without including delimiters and [] - */ - /* @noinspection PhpMissingBreakStatementInspection */ - case 'comment': - $pattern = '\(\)"'; - /* Intentional fall through */ - case 'text': - default: - //RFC 2047 section 5.1 - //Replace every high ascii, control, =, ? and _ characters - $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern; - break; - } - $matches = []; - if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) { - //If the string contains an '=', make sure it's the first thing we replace - //so as to avoid double-encoding - $eqkey = array_search('=', $matches[0], true); - if (false !== $eqkey) { - unset($matches[0][$eqkey]); - array_unshift($matches[0], '='); - } - foreach (array_unique($matches[0]) as $char) { - $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded); - } - } - //Replace spaces with _ (more readable than =20) - //RFC 2047 section 4.2(2) - return str_replace(' ', '_', $encoded); - } - - /** - * Add a string or binary attachment (non-filesystem). - * This method can be used to attach ascii or binary data, - * such as a BLOB record from a database. - * - * @param string $string String attachment data - * @param string $filename Name of the attachment - * @param string $encoding File encoding (see $Encoding) - * @param string $type File extension (MIME) type - * @param string $disposition Disposition to use - * - * @throws Exception - * - * @return bool True on successfully adding an attachment - */ - public function addStringAttachment( - $string, - $filename, - $encoding = self::ENCODING_BASE64, - $type = '', - $disposition = 'attachment' - ) { - try { - //If a MIME type is not specified, try to work it out from the file name - if ('' === $type) { - $type = static::filenameToType($filename); - } - - if (!$this->validateEncoding($encoding)) { - throw new Exception($this->lang('encoding') . $encoding); - } - - //Append to $attachment array - $this->attachment[] = [ - 0 => $string, - 1 => $filename, - 2 => static::mb_pathinfo($filename, PATHINFO_BASENAME), - 3 => $encoding, - 4 => $type, - 5 => true, //isStringAttachment - 6 => $disposition, - 7 => 0, - ]; - } catch (Exception $exc) { - $this->setError($exc->getMessage()); - $this->edebug($exc->getMessage()); - if ($this->exceptions) { - throw $exc; - } - - return false; - } - - return true; - } - - /** - * Add an embedded (inline) attachment from a file. - * This can include images, sounds, and just about any other document type. - * These differ from 'regular' attachments in that they are intended to be - * displayed inline with the message, not just attached for download. - * This is used in HTML messages that embed the images - * the HTML refers to using the $cid value. - * Never use a user-supplied path to a file! - * - * @param string $path Path to the attachment - * @param string $cid Content ID of the attachment; Use this to reference - * the content when using an embedded image in HTML - * @param string $name Overrides the attachment name - * @param string $encoding File encoding (see $Encoding) - * @param string $type File MIME type - * @param string $disposition Disposition to use - * - * @throws Exception - * - * @return bool True on successfully adding an attachment - */ - public function addEmbeddedImage( - $path, - $cid, - $name = '', - $encoding = self::ENCODING_BASE64, - $type = '', - $disposition = 'inline' - ) { - try { - if (!static::fileIsAccessible($path)) { - throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE); - } - - //If a MIME type is not specified, try to work it out from the file name - if ('' === $type) { - $type = static::filenameToType($path); - } - - if (!$this->validateEncoding($encoding)) { - throw new Exception($this->lang('encoding') . $encoding); - } - - $filename = (string) static::mb_pathinfo($path, PATHINFO_BASENAME); - if ('' === $name) { - $name = $filename; - } - - //Append to $attachment array - $this->attachment[] = [ - 0 => $path, - 1 => $filename, - 2 => $name, - 3 => $encoding, - 4 => $type, - 5 => false, //isStringAttachment - 6 => $disposition, - 7 => $cid, - ]; - } catch (Exception $exc) { - $this->setError($exc->getMessage()); - $this->edebug($exc->getMessage()); - if ($this->exceptions) { - throw $exc; - } - - return false; - } - - return true; - } - - /** - * Add an embedded stringified attachment. - * This can include images, sounds, and just about any other document type. - * If your filename doesn't contain an extension, be sure to set the $type to an appropriate MIME type. - * - * @param string $string The attachment binary data - * @param string $cid Content ID of the attachment; Use this to reference - * the content when using an embedded image in HTML - * @param string $name A filename for the attachment. If this contains an extension, - * PHPMailer will attempt to set a MIME type for the attachment. - * For example 'file.jpg' would get an 'image/jpeg' MIME type. - * @param string $encoding File encoding (see $Encoding), defaults to 'base64' - * @param string $type MIME type - will be used in preference to any automatically derived type - * @param string $disposition Disposition to use - * - * @throws Exception - * - * @return bool True on successfully adding an attachment - */ - public function addStringEmbeddedImage( - $string, - $cid, - $name = '', - $encoding = self::ENCODING_BASE64, - $type = '', - $disposition = 'inline' - ) { - try { - //If a MIME type is not specified, try to work it out from the name - if ('' === $type && !empty($name)) { - $type = static::filenameToType($name); - } - - if (!$this->validateEncoding($encoding)) { - throw new Exception($this->lang('encoding') . $encoding); - } - - //Append to $attachment array - $this->attachment[] = [ - 0 => $string, - 1 => $name, - 2 => $name, - 3 => $encoding, - 4 => $type, - 5 => true, //isStringAttachment - 6 => $disposition, - 7 => $cid, - ]; - } catch (Exception $exc) { - $this->setError($exc->getMessage()); - $this->edebug($exc->getMessage()); - if ($this->exceptions) { - throw $exc; - } - - return false; - } - - return true; - } - - /** - * Validate encodings. - * - * @param string $encoding - * - * @return bool - */ - protected function validateEncoding($encoding) - { - return in_array( - $encoding, - [ - self::ENCODING_7BIT, - self::ENCODING_QUOTED_PRINTABLE, - self::ENCODING_BASE64, - self::ENCODING_8BIT, - self::ENCODING_BINARY, - ], - true - ); - } - - /** - * Check if an embedded attachment is present with this cid. - * - * @param string $cid - * - * @return bool - */ - protected function cidExists($cid) - { - foreach ($this->attachment as $attachment) { - if ('inline' === $attachment[6] && $cid === $attachment[7]) { - return true; - } - } - - return false; - } - - /** - * Check if an inline attachment is present. - * - * @return bool - */ - public function inlineImageExists() - { - foreach ($this->attachment as $attachment) { - if ('inline' === $attachment[6]) { - return true; - } - } - - return false; - } - - /** - * Check if an attachment (non-inline) is present. - * - * @return bool - */ - public function attachmentExists() - { - foreach ($this->attachment as $attachment) { - if ('attachment' === $attachment[6]) { - return true; - } - } - - return false; - } - - /** - * Check if this message has an alternative body set. - * - * @return bool - */ - public function alternativeExists() - { - return !empty($this->AltBody); - } - - /** - * Clear queued addresses of given kind. - * - * @param string $kind 'to', 'cc', or 'bcc' - */ - public function clearQueuedAddresses($kind) - { - $this->RecipientsQueue = array_filter( - $this->RecipientsQueue, - static function ($params) use ($kind) { - return $params[0] !== $kind; - } - ); - } - - /** - * Clear all To recipients. - */ - public function clearAddresses() - { - foreach ($this->to as $to) { - unset($this->all_recipients[strtolower($to[0])]); - } - $this->to = []; - $this->clearQueuedAddresses('to'); - } - - /** - * Clear all CC recipients. - */ - public function clearCCs() - { - foreach ($this->cc as $cc) { - unset($this->all_recipients[strtolower($cc[0])]); - } - $this->cc = []; - $this->clearQueuedAddresses('cc'); - } - - /** - * Clear all BCC recipients. - */ - public function clearBCCs() - { - foreach ($this->bcc as $bcc) { - unset($this->all_recipients[strtolower($bcc[0])]); - } - $this->bcc = []; - $this->clearQueuedAddresses('bcc'); - } - - /** - * Clear all ReplyTo recipients. - */ - public function clearReplyTos() - { - $this->ReplyTo = []; - $this->ReplyToQueue = []; - } - - /** - * Clear all recipient types. - */ - public function clearAllRecipients() - { - $this->to = []; - $this->cc = []; - $this->bcc = []; - $this->all_recipients = []; - $this->RecipientsQueue = []; - } - - /** - * Clear all filesystem, string, and binary attachments. - */ - public function clearAttachments() - { - $this->attachment = []; - } - - /** - * Clear all custom headers. - */ - public function clearCustomHeaders() - { - $this->CustomHeader = []; - } - - /** - * Add an error message to the error container. - * - * @param string $msg - */ - protected function setError($msg) - { - ++$this->error_count; - if ('smtp' === $this->Mailer && null !== $this->smtp) { - $lasterror = $this->smtp->getError(); - if (!empty($lasterror['error'])) { - $msg .= $this->lang('smtp_error') . $lasterror['error']; - if (!empty($lasterror['detail'])) { - $msg .= ' Detail: ' . $lasterror['detail']; - } - if (!empty($lasterror['smtp_code'])) { - $msg .= ' SMTP code: ' . $lasterror['smtp_code']; - } - if (!empty($lasterror['smtp_code_ex'])) { - $msg .= ' Additional SMTP info: ' . $lasterror['smtp_code_ex']; - } - } - } - $this->ErrorInfo = $msg; - } - - /** - * Return an RFC 822 formatted date. - * - * @return string - */ - public static function rfcDate() - { - //Set the time zone to whatever the default is to avoid 500 errors - //Will default to UTC if it's not set properly in php.ini - date_default_timezone_set(@date_default_timezone_get()); - - return date('D, j M Y H:i:s O'); - } - - /** - * Get the server hostname. - * Returns 'localhost.localdomain' if unknown. - * - * @return string - */ - protected function serverHostname() - { - $result = ''; - if (!empty($this->Hostname)) { - $result = $this->Hostname; - } elseif (isset($_SERVER) && array_key_exists('SERVER_NAME', $_SERVER)) { - $result = $_SERVER['SERVER_NAME']; - } elseif (function_exists('gethostname') && gethostname() !== false) { - $result = gethostname(); - } elseif (php_uname('n') !== false) { - $result = php_uname('n'); - } - if (!static::isValidHost($result)) { - return 'localhost.localdomain'; - } - - return $result; - } - - /** - * Validate whether a string contains a valid value to use as a hostname or IP address. - * IPv6 addresses must include [], e.g. `[::1]`, not just `::1`. - * - * @param string $host The host name or IP address to check - * - * @return bool - */ - public static function isValidHost($host) - { - //Simple syntax limits - if ( - empty($host) - || !is_string($host) - || strlen($host) > 256 - || !preg_match('/^([a-zA-Z\d.-]*|\[[a-fA-F\d:]+])$/', $host) - ) { - return false; - } - //Looks like a bracketed IPv6 address - if (strlen($host) > 2 && substr($host, 0, 1) === '[' && substr($host, -1, 1) === ']') { - return filter_var(substr($host, 1, -1), FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false; - } - //If removing all the dots results in a numeric string, it must be an IPv4 address. - //Need to check this first because otherwise things like `999.0.0.0` are considered valid host names - if (is_numeric(str_replace('.', '', $host))) { - //Is it a valid IPv4 address? - return filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false; - } - if (filter_var('http://' . $host, FILTER_VALIDATE_URL) !== false) { - //Is it a syntactically valid hostname? - return true; - } - - return false; - } - - /** - * Get an error message in the current language. - * - * @param string $key - * - * @return string - */ - protected function lang($key) - { - if (count($this->language) < 1) { - $this->setLanguage(); //Set the default language - } - - if (array_key_exists($key, $this->language)) { - if ('smtp_connect_failed' === $key) { - //Include a link to troubleshooting docs on SMTP connection failure. - //This is by far the biggest cause of support questions - //but it's usually not PHPMailer's fault. - return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting'; - } - - return $this->language[$key]; - } - - //Return the key as a fallback - return $key; - } - - /** - * Check if an error occurred. - * - * @return bool True if an error did occur - */ - public function isError() - { - return $this->error_count > 0; - } - - /** - * Add a custom header. - * $name value can be overloaded to contain - * both header name and value (name:value). - * - * @param string $name Custom header name - * @param string|null $value Header value - * - * @throws Exception - */ - public function addCustomHeader($name, $value = null) - { - if (null === $value && strpos($name, ':') !== false) { - //Value passed in as name:value - list($name, $value) = explode(':', $name, 2); - } - $name = trim($name); - $value = (null === $value) ? '' : trim($value); - //Ensure name is not empty, and that neither name nor value contain line breaks - if (empty($name) || strpbrk($name . $value, "\r\n") !== false) { - if ($this->exceptions) { - throw new Exception('Invalid header name or value'); - } - - return false; - } - $this->CustomHeader[] = [$name, $value]; - - return true; - } - - /** - * Returns all custom headers. - * - * @return array - */ - public function getCustomHeaders() - { - return $this->CustomHeader; - } - - /** - * Create a message body from an HTML string. - * Automatically inlines images and creates a plain-text version by converting the HTML, - * overwriting any existing values in Body and AltBody. - * Do not source $message content from user input! - * $basedir is prepended when handling relative URLs, e.g. and must not be empty - * will look for an image file in $basedir/images/a.png and convert it to inline. - * If you don't provide a $basedir, relative paths will be left untouched (and thus probably break in email) - * Converts data-uri images into embedded attachments. - * If you don't want to apply these transformations to your HTML, just set Body and AltBody directly. - * - * @param string $message HTML message string - * @param string $basedir Absolute path to a base directory to prepend to relative paths to images - * @param bool|callable $advanced Whether to use the internal HTML to text converter - * or your own custom converter - * @return string The transformed message body - * - * @throws Exception - * - * @see PHPMailer::html2text() - */ - public function msgHTML($message, $basedir = '', $advanced = false) - { - preg_match_all('/(? 1 && '/' !== substr($basedir, -1)) { - //Ensure $basedir has a trailing / - $basedir .= '/'; - } - foreach ($images[2] as $imgindex => $url) { - //Convert data URIs into embedded images - //e.g. "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" - $match = []; - if (preg_match('#^data:(image/(?:jpe?g|gif|png));?(base64)?,(.+)#', $url, $match)) { - if (count($match) === 4 && static::ENCODING_BASE64 === $match[2]) { - $data = base64_decode($match[3]); - } elseif ('' === $match[2]) { - $data = rawurldecode($match[3]); - } else { - //Not recognised so leave it alone - continue; - } - //Hash the decoded data, not the URL, so that the same data-URI image used in multiple places - //will only be embedded once, even if it used a different encoding - $cid = substr(hash('sha256', $data), 0, 32) . '@phpmailer.0'; //RFC2392 S 2 - - if (!$this->cidExists($cid)) { - $this->addStringEmbeddedImage( - $data, - $cid, - 'embed' . $imgindex, - static::ENCODING_BASE64, - $match[1] - ); - } - $message = str_replace( - $images[0][$imgindex], - $images[1][$imgindex] . '="cid:' . $cid . '"', - $message - ); - continue; - } - if ( - //Only process relative URLs if a basedir is provided (i.e. no absolute local paths) - !empty($basedir) - //Ignore URLs containing parent dir traversal (..) - && (strpos($url, '..') === false) - //Do not change urls that are already inline images - && 0 !== strpos($url, 'cid:') - //Do not change absolute URLs, including anonymous protocol - && !preg_match('#^[a-z][a-z0-9+.-]*:?//#i', $url) - ) { - $filename = static::mb_pathinfo($url, PATHINFO_BASENAME); - $directory = dirname($url); - if ('.' === $directory) { - $directory = ''; - } - //RFC2392 S 2 - $cid = substr(hash('sha256', $url), 0, 32) . '@phpmailer.0'; - if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) { - $basedir .= '/'; - } - if (strlen($directory) > 1 && '/' !== substr($directory, -1)) { - $directory .= '/'; - } - if ( - $this->addEmbeddedImage( - $basedir . $directory . $filename, - $cid, - $filename, - static::ENCODING_BASE64, - static::_mime_types((string) static::mb_pathinfo($filename, PATHINFO_EXTENSION)) - ) - ) { - $message = preg_replace( - '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui', - $images[1][$imgindex] . '="cid:' . $cid . '"', - $message - ); - } - } - } - } - $this->isHTML(); - //Convert all message body line breaks to LE, makes quoted-printable encoding work much better - $this->Body = static::normalizeBreaks($message); - $this->AltBody = static::normalizeBreaks($this->html2text($message, $advanced)); - if (!$this->alternativeExists()) { - $this->AltBody = 'This is an HTML-only message. To view it, activate HTML in your email application.' - . static::$LE; - } - - return $this->Body; - } - - /** - * Convert an HTML string into plain text. - * This is used by msgHTML(). - * Note - older versions of this function used a bundled advanced converter - * which was removed for license reasons in #232. - * Example usage: - * - * ```php - * //Use default conversion - * $plain = $mail->html2text($html); - * //Use your own custom converter - * $plain = $mail->html2text($html, function($html) { - * $converter = new MyHtml2text($html); - * return $converter->get_text(); - * }); - * ``` - * - * @param string $html The HTML text to convert - * @param bool|callable $advanced Any boolean value to use the internal converter, - * or provide your own callable for custom conversion. - * *Never* pass user-supplied data into this parameter - * - * @return string - */ - public function html2text($html, $advanced = false) - { - if (is_callable($advanced)) { - return call_user_func($advanced, $html); - } - - return html_entity_decode( - trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))), - ENT_QUOTES, - $this->CharSet - ); - } - - /** - * Get the MIME type for a file extension. - * - * @param string $ext File extension - * - * @return string MIME type of file - */ - public static function _mime_types($ext = '') - { - $mimes = [ - 'xl' => 'application/excel', - 'js' => 'application/javascript', - 'hqx' => 'application/mac-binhex40', - 'cpt' => 'application/mac-compactpro', - 'bin' => 'application/macbinary', - 'doc' => 'application/msword', - 'word' => 'application/msword', - 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', - 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', - 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', - 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', - 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', - 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', - 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', - 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12', - 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12', - 'class' => 'application/octet-stream', - 'dll' => 'application/octet-stream', - 'dms' => 'application/octet-stream', - 'exe' => 'application/octet-stream', - 'lha' => 'application/octet-stream', - 'lzh' => 'application/octet-stream', - 'psd' => 'application/octet-stream', - 'sea' => 'application/octet-stream', - 'so' => 'application/octet-stream', - 'oda' => 'application/oda', - 'pdf' => 'application/pdf', - 'ai' => 'application/postscript', - 'eps' => 'application/postscript', - 'ps' => 'application/postscript', - 'smi' => 'application/smil', - 'smil' => 'application/smil', - 'mif' => 'application/vnd.mif', - 'xls' => 'application/vnd.ms-excel', - 'ppt' => 'application/vnd.ms-powerpoint', - 'wbxml' => 'application/vnd.wap.wbxml', - 'wmlc' => 'application/vnd.wap.wmlc', - 'dcr' => 'application/x-director', - 'dir' => 'application/x-director', - 'dxr' => 'application/x-director', - 'dvi' => 'application/x-dvi', - 'gtar' => 'application/x-gtar', - 'php3' => 'application/x-httpd-php', - 'php4' => 'application/x-httpd-php', - 'php' => 'application/x-httpd-php', - 'phtml' => 'application/x-httpd-php', - 'phps' => 'application/x-httpd-php-source', - 'swf' => 'application/x-shockwave-flash', - 'sit' => 'application/x-stuffit', - 'tar' => 'application/x-tar', - 'tgz' => 'application/x-tar', - 'xht' => 'application/xhtml+xml', - 'xhtml' => 'application/xhtml+xml', - 'zip' => 'application/zip', - 'mid' => 'audio/midi', - 'midi' => 'audio/midi', - 'mp2' => 'audio/mpeg', - 'mp3' => 'audio/mpeg', - 'm4a' => 'audio/mp4', - 'mpga' => 'audio/mpeg', - 'aif' => 'audio/x-aiff', - 'aifc' => 'audio/x-aiff', - 'aiff' => 'audio/x-aiff', - 'ram' => 'audio/x-pn-realaudio', - 'rm' => 'audio/x-pn-realaudio', - 'rpm' => 'audio/x-pn-realaudio-plugin', - 'ra' => 'audio/x-realaudio', - 'wav' => 'audio/x-wav', - 'mka' => 'audio/x-matroska', - 'bmp' => 'image/bmp', - 'gif' => 'image/gif', - 'jpeg' => 'image/jpeg', - 'jpe' => 'image/jpeg', - 'jpg' => 'image/jpeg', - 'png' => 'image/png', - 'tiff' => 'image/tiff', - 'tif' => 'image/tiff', - 'webp' => 'image/webp', - 'avif' => 'image/avif', - 'heif' => 'image/heif', - 'heifs' => 'image/heif-sequence', - 'heic' => 'image/heic', - 'heics' => 'image/heic-sequence', - 'eml' => 'message/rfc822', - 'css' => 'text/css', - 'html' => 'text/html', - 'htm' => 'text/html', - 'shtml' => 'text/html', - 'log' => 'text/plain', - 'text' => 'text/plain', - 'txt' => 'text/plain', - 'rtx' => 'text/richtext', - 'rtf' => 'text/rtf', - 'vcf' => 'text/vcard', - 'vcard' => 'text/vcard', - 'ics' => 'text/calendar', - 'xml' => 'text/xml', - 'xsl' => 'text/xml', - 'wmv' => 'video/x-ms-wmv', - 'mpeg' => 'video/mpeg', - 'mpe' => 'video/mpeg', - 'mpg' => 'video/mpeg', - 'mp4' => 'video/mp4', - 'm4v' => 'video/mp4', - 'mov' => 'video/quicktime', - 'qt' => 'video/quicktime', - 'rv' => 'video/vnd.rn-realvideo', - 'avi' => 'video/x-msvideo', - 'movie' => 'video/x-sgi-movie', - 'webm' => 'video/webm', - 'mkv' => 'video/x-matroska', - ]; - $ext = strtolower($ext); - if (array_key_exists($ext, $mimes)) { - return $mimes[$ext]; - } - - return 'application/octet-stream'; - } - - /** - * Map a file name to a MIME type. - * Defaults to 'application/octet-stream', i.e.. arbitrary binary data. - * - * @param string $filename A file name or full path, does not need to exist as a file - * - * @return string - */ - public static function filenameToType($filename) - { - //In case the path is a URL, strip any query string before getting extension - $qpos = strpos($filename, '?'); - if (false !== $qpos) { - $filename = substr($filename, 0, $qpos); - } - $ext = static::mb_pathinfo($filename, PATHINFO_EXTENSION); - - return static::_mime_types($ext); - } - - /** - * Multi-byte-safe pathinfo replacement. - * Drop-in replacement for pathinfo(), but multibyte- and cross-platform-safe. - * - * @see http://www.php.net/manual/en/function.pathinfo.php#107461 - * - * @param string $path A filename or path, does not need to exist as a file - * @param int|string $options Either a PATHINFO_* constant, - * or a string name to return only the specified piece - * - * @return string|array - */ - public static function mb_pathinfo($path, $options = null) - { - $ret = ['dirname' => '', 'basename' => '', 'extension' => '', 'filename' => '']; - $pathinfo = []; - if (preg_match('#^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^.\\\\/]+?)|))[\\\\/.]*$#m', $path, $pathinfo)) { - if (array_key_exists(1, $pathinfo)) { - $ret['dirname'] = $pathinfo[1]; - } - if (array_key_exists(2, $pathinfo)) { - $ret['basename'] = $pathinfo[2]; - } - if (array_key_exists(5, $pathinfo)) { - $ret['extension'] = $pathinfo[5]; - } - if (array_key_exists(3, $pathinfo)) { - $ret['filename'] = $pathinfo[3]; - } - } - switch ($options) { - case PATHINFO_DIRNAME: - case 'dirname': - return $ret['dirname']; - case PATHINFO_BASENAME: - case 'basename': - return $ret['basename']; - case PATHINFO_EXTENSION: - case 'extension': - return $ret['extension']; - case PATHINFO_FILENAME: - case 'filename': - return $ret['filename']; - default: - return $ret; - } - } - - /** - * Set or reset instance properties. - * You should avoid this function - it's more verbose, less efficient, more error-prone and - * harder to debug than setting properties directly. - * Usage Example: - * `$mail->set('SMTPSecure', static::ENCRYPTION_STARTTLS);` - * is the same as: - * `$mail->SMTPSecure = static::ENCRYPTION_STARTTLS;`. - * - * @param string $name The property name to set - * @param mixed $value The value to set the property to - * - * @return bool - */ - public function set($name, $value = '') - { - if (property_exists($this, $name)) { - $this->$name = $value; - - return true; - } - $this->setError($this->lang('variable_set') . $name); - - return false; - } - - /** - * Strip newlines to prevent header injection. - * - * @param string $str - * - * @return string - */ - public function secureHeader($str) - { - return trim(str_replace(["\r", "\n"], '', $str)); - } - - /** - * Normalize line breaks in a string. - * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format. - * Defaults to CRLF (for message bodies) and preserves consecutive breaks. - * - * @param string $text - * @param string $breaktype What kind of line break to use; defaults to static::$LE - * - * @return string - */ - public static function normalizeBreaks($text, $breaktype = null) - { - if (null === $breaktype) { - $breaktype = static::$LE; - } - //Normalise to \n - $text = str_replace([self::CRLF, "\r"], "\n", $text); - //Now convert LE as needed - if ("\n" !== $breaktype) { - $text = str_replace("\n", $breaktype, $text); - } - - return $text; - } - - /** - * Remove trailing breaks from a string. - * - * @param string $text - * - * @return string The text to remove breaks from - */ - public static function stripTrailingWSP($text) - { - return rtrim($text, " \r\n\t"); - } - - /** - * Return the current line break format string. - * - * @return string - */ - public static function getLE() - { - return static::$LE; - } - - /** - * Set the line break format string, e.g. "\r\n". - * - * @param string $le - */ - protected static function setLE($le) - { - static::$LE = $le; - } - - /** - * Set the public and private key files and password for S/MIME signing. - * - * @param string $cert_filename - * @param string $key_filename - * @param string $key_pass Password for private key - * @param string $extracerts_filename Optional path to chain certificate - */ - public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '') - { - $this->sign_cert_file = $cert_filename; - $this->sign_key_file = $key_filename; - $this->sign_key_pass = $key_pass; - $this->sign_extracerts_file = $extracerts_filename; - } - - /** - * Quoted-Printable-encode a DKIM header. - * - * @param string $txt - * - * @return string - */ - public function DKIM_QP($txt) - { - $line = ''; - $len = strlen($txt); - for ($i = 0; $i < $len; ++$i) { - $ord = ord($txt[$i]); - if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord === 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) { - $line .= $txt[$i]; - } else { - $line .= '=' . sprintf('%02X', $ord); - } - } - - return $line; - } - - /** - * Generate a DKIM signature. - * - * @param string $signHeader - * - * @throws Exception - * - * @return string The DKIM signature value - */ - public function DKIM_Sign($signHeader) - { - if (!defined('PKCS7_TEXT')) { - if ($this->exceptions) { - throw new Exception($this->lang('extension_missing') . 'openssl'); - } - - return ''; - } - $privKeyStr = !empty($this->DKIM_private_string) ? - $this->DKIM_private_string : - file_get_contents($this->DKIM_private); - if ('' !== $this->DKIM_passphrase) { - $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase); - } else { - $privKey = openssl_pkey_get_private($privKeyStr); - } - if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) { - if (\PHP_MAJOR_VERSION < 8) { - openssl_pkey_free($privKey); - } - - return base64_encode($signature); - } - if (\PHP_MAJOR_VERSION < 8) { - openssl_pkey_free($privKey); - } - - return ''; - } - - /** - * Generate a DKIM canonicalization header. - * Uses the 'relaxed' algorithm from RFC6376 section 3.4.2. - * Canonicalized headers should *always* use CRLF, regardless of mailer setting. - * - * @see https://tools.ietf.org/html/rfc6376#section-3.4.2 - * - * @param string $signHeader Header - * - * @return string - */ - public function DKIM_HeaderC($signHeader) - { - //Normalize breaks to CRLF (regardless of the mailer) - $signHeader = static::normalizeBreaks($signHeader, self::CRLF); - //Unfold header lines - //Note PCRE \s is too broad a definition of whitespace; RFC5322 defines it as `[ \t]` - //@see https://tools.ietf.org/html/rfc5322#section-2.2 - //That means this may break if you do something daft like put vertical tabs in your headers. - $signHeader = preg_replace('/\r\n[ \t]+/', ' ', $signHeader); - //Break headers out into an array - $lines = explode(self::CRLF, $signHeader); - foreach ($lines as $key => $line) { - //If the header is missing a :, skip it as it's invalid - //This is likely to happen because the explode() above will also split - //on the trailing LE, leaving an empty line - if (strpos($line, ':') === false) { - continue; - } - list($heading, $value) = explode(':', $line, 2); - //Lower-case header name - $heading = strtolower($heading); - //Collapse white space within the value, also convert WSP to space - $value = preg_replace('/[ \t]+/', ' ', $value); - //RFC6376 is slightly unclear here - it says to delete space at the *end* of each value - //But then says to delete space before and after the colon. - //Net result is the same as trimming both ends of the value. - //By elimination, the same applies to the field name - $lines[$key] = trim($heading, " \t") . ':' . trim($value, " \t"); - } - - return implode(self::CRLF, $lines); - } - - /** - * Generate a DKIM canonicalization body. - * Uses the 'simple' algorithm from RFC6376 section 3.4.3. - * Canonicalized bodies should *always* use CRLF, regardless of mailer setting. - * - * @see https://tools.ietf.org/html/rfc6376#section-3.4.3 - * - * @param string $body Message Body - * - * @return string - */ - public function DKIM_BodyC($body) - { - if (empty($body)) { - return self::CRLF; - } - //Normalize line endings to CRLF - $body = static::normalizeBreaks($body, self::CRLF); - - //Reduce multiple trailing line breaks to a single one - return static::stripTrailingWSP($body) . self::CRLF; - } - - /** - * Create the DKIM header and body in a new message header. - * - * @param string $headers_line Header lines - * @param string $subject Subject - * @param string $body Body - * - * @throws Exception - * - * @return string - */ - public function DKIM_Add($headers_line, $subject, $body) - { - $DKIMsignatureType = 'rsa-sha256'; //Signature & hash algorithms - $DKIMcanonicalization = 'relaxed/simple'; //Canonicalization methods of header & body - $DKIMquery = 'dns/txt'; //Query method - $DKIMtime = time(); - //Always sign these headers without being asked - //Recommended list from https://tools.ietf.org/html/rfc6376#section-5.4.1 - $autoSignHeaders = [ - 'from', - 'to', - 'cc', - 'date', - 'subject', - 'reply-to', - 'message-id', - 'content-type', - 'mime-version', - 'x-mailer', - ]; - if (stripos($headers_line, 'Subject') === false) { - $headers_line .= 'Subject: ' . $subject . static::$LE; - } - $headerLines = explode(static::$LE, $headers_line); - $currentHeaderLabel = ''; - $currentHeaderValue = ''; - $parsedHeaders = []; - $headerLineIndex = 0; - $headerLineCount = count($headerLines); - foreach ($headerLines as $headerLine) { - $matches = []; - if (preg_match('/^([^ \t]*?)(?::[ \t]*)(.*)$/', $headerLine, $matches)) { - if ($currentHeaderLabel !== '') { - //We were previously in another header; This is the start of a new header, so save the previous one - $parsedHeaders[] = ['label' => $currentHeaderLabel, 'value' => $currentHeaderValue]; - } - $currentHeaderLabel = $matches[1]; - $currentHeaderValue = $matches[2]; - } elseif (preg_match('/^[ \t]+(.*)$/', $headerLine, $matches)) { - //This is a folded continuation of the current header, so unfold it - $currentHeaderValue .= ' ' . $matches[1]; - } - ++$headerLineIndex; - if ($headerLineIndex >= $headerLineCount) { - //This was the last line, so finish off this header - $parsedHeaders[] = ['label' => $currentHeaderLabel, 'value' => $currentHeaderValue]; - } - } - $copiedHeaders = []; - $headersToSignKeys = []; - $headersToSign = []; - foreach ($parsedHeaders as $header) { - //Is this header one that must be included in the DKIM signature? - if (in_array(strtolower($header['label']), $autoSignHeaders, true)) { - $headersToSignKeys[] = $header['label']; - $headersToSign[] = $header['label'] . ': ' . $header['value']; - if ($this->DKIM_copyHeaderFields) { - $copiedHeaders[] = $header['label'] . ':' . //Note no space after this, as per RFC - str_replace('|', '=7C', $this->DKIM_QP($header['value'])); - } - continue; - } - //Is this an extra custom header we've been asked to sign? - if (in_array($header['label'], $this->DKIM_extraHeaders, true)) { - //Find its value in custom headers - foreach ($this->CustomHeader as $customHeader) { - if ($customHeader[0] === $header['label']) { - $headersToSignKeys[] = $header['label']; - $headersToSign[] = $header['label'] . ': ' . $header['value']; - if ($this->DKIM_copyHeaderFields) { - $copiedHeaders[] = $header['label'] . ':' . //Note no space after this, as per RFC - str_replace('|', '=7C', $this->DKIM_QP($header['value'])); - } - //Skip straight to the next header - continue 2; - } - } - } - } - $copiedHeaderFields = ''; - if ($this->DKIM_copyHeaderFields && count($copiedHeaders) > 0) { - //Assemble a DKIM 'z' tag - $copiedHeaderFields = ' z='; - $first = true; - foreach ($copiedHeaders as $copiedHeader) { - if (!$first) { - $copiedHeaderFields .= static::$LE . ' |'; - } - //Fold long values - if (strlen($copiedHeader) > self::STD_LINE_LENGTH - 3) { - $copiedHeaderFields .= substr( - chunk_split($copiedHeader, self::STD_LINE_LENGTH - 3, static::$LE . self::FWS), - 0, - -strlen(static::$LE . self::FWS) - ); - } else { - $copiedHeaderFields .= $copiedHeader; - } - $first = false; - } - $copiedHeaderFields .= ';' . static::$LE; - } - $headerKeys = ' h=' . implode(':', $headersToSignKeys) . ';' . static::$LE; - $headerValues = implode(static::$LE, $headersToSign); - $body = $this->DKIM_BodyC($body); - //Base64 of packed binary SHA-256 hash of body - $DKIMb64 = base64_encode(pack('H*', hash('sha256', $body))); - $ident = ''; - if ('' !== $this->DKIM_identity) { - $ident = ' i=' . $this->DKIM_identity . ';' . static::$LE; - } - //The DKIM-Signature header is included in the signature *except for* the value of the `b` tag - //which is appended after calculating the signature - //https://tools.ietf.org/html/rfc6376#section-3.5 - $dkimSignatureHeader = 'DKIM-Signature: v=1;' . - ' d=' . $this->DKIM_domain . ';' . - ' s=' . $this->DKIM_selector . ';' . static::$LE . - ' a=' . $DKIMsignatureType . ';' . - ' q=' . $DKIMquery . ';' . - ' t=' . $DKIMtime . ';' . - ' c=' . $DKIMcanonicalization . ';' . static::$LE . - $headerKeys . - $ident . - $copiedHeaderFields . - ' bh=' . $DKIMb64 . ';' . static::$LE . - ' b='; - //Canonicalize the set of headers - $canonicalizedHeaders = $this->DKIM_HeaderC( - $headerValues . static::$LE . $dkimSignatureHeader - ); - $signature = $this->DKIM_Sign($canonicalizedHeaders); - $signature = trim(chunk_split($signature, self::STD_LINE_LENGTH - 3, static::$LE . self::FWS)); - - return static::normalizeBreaks($dkimSignatureHeader . $signature); - } - - /** - * Detect if a string contains a line longer than the maximum line length - * allowed by RFC 2822 section 2.1.1. - * - * @param string $str - * - * @return bool - */ - public static function hasLineLongerThanMax($str) - { - return (bool) preg_match('/^(.{' . (self::MAX_LINE_LENGTH + strlen(static::$LE)) . ',})/m', $str); - } - - /** - * If a string contains any "special" characters, double-quote the name, - * and escape any double quotes with a backslash. - * - * @param string $str - * - * @return string - * - * @see RFC822 3.4.1 - */ - public static function quotedString($str) - { - if (preg_match('/[ ()<>@,;:"\/\[\]?=]/', $str)) { - //If the string contains any of these chars, it must be double-quoted - //and any double quotes must be escaped with a backslash - return '"' . str_replace('"', '\\"', $str) . '"'; - } - - //Return the string untouched, it doesn't need quoting - return $str; - } - - /** - * Allows for public read access to 'to' property. - * Before the send() call, queued addresses (i.e. with IDN) are not yet included. - * - * @return array - */ - public function getToAddresses() - { - return $this->to; - } - - /** - * Allows for public read access to 'cc' property. - * Before the send() call, queued addresses (i.e. with IDN) are not yet included. - * - * @return array - */ - public function getCcAddresses() - { - return $this->cc; - } - - /** - * Allows for public read access to 'bcc' property. - * Before the send() call, queued addresses (i.e. with IDN) are not yet included. - * - * @return array - */ - public function getBccAddresses() - { - return $this->bcc; - } - - /** - * Allows for public read access to 'ReplyTo' property. - * Before the send() call, queued addresses (i.e. with IDN) are not yet included. - * - * @return array - */ - public function getReplyToAddresses() - { - return $this->ReplyTo; - } - - /** - * Allows for public read access to 'all_recipients' property. - * Before the send() call, queued addresses (i.e. with IDN) are not yet included. - * - * @return array - */ - public function getAllRecipientAddresses() - { - return $this->all_recipients; - } - - /** - * Perform a callback. - * - * @param bool $isSent - * @param array $to - * @param array $cc - * @param array $bcc - * @param string $subject - * @param string $body - * @param string $from - * @param array $extra - */ - protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from, $extra) - { - if (!empty($this->action_function) && is_callable($this->action_function)) { - call_user_func($this->action_function, $isSent, $to, $cc, $bcc, $subject, $body, $from, $extra); - } - } - - /** - * Get the OAuth instance. - * - * @return OAuth - */ - public function getOAuth() - { - return $this->oauth; - } - - /** - * Set an OAuth instance. - */ - public function setOAuth(OAuth $oauth) - { - $this->oauth = $oauth; - } -} diff --git a/themes/pmem-hugo/static/include/phpmailer/src/POP3.php b/themes/pmem-hugo/static/include/phpmailer/src/POP3.php deleted file mode 100644 index b38964b190..0000000000 --- a/themes/pmem-hugo/static/include/phpmailer/src/POP3.php +++ /dev/null @@ -1,448 +0,0 @@ - - * @author Jim Jagielski (jimjag) - * @author Andy Prevost (codeworxtech) - * @author Brent R. Matzelle (original founder) - * @copyright 2012 - 2020 Marcus Bointon - * @copyright 2010 - 2012 Jim Jagielski - * @copyright 2004 - 2009 Andy Prevost - * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License - * @note This program is distributed in the hope that it will be useful - WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -namespace PHPMailer\PHPMailer; - -/** - * PHPMailer POP-Before-SMTP Authentication Class. - * Specifically for PHPMailer to use for RFC1939 POP-before-SMTP authentication. - * 1) This class does not support APOP authentication. - * 2) Opening and closing lots of POP3 connections can be quite slow. If you need - * to send a batch of emails then just perform the authentication once at the start, - * and then loop through your mail sending script. Providing this process doesn't - * take longer than the verification period lasts on your POP3 server, you should be fine. - * 3) This is really ancient technology; you should only need to use it to talk to very old systems. - * 4) This POP3 class is deliberately lightweight and incomplete, implementing just - * enough to do authentication. - * If you want a more complete class there are other POP3 classes for PHP available. - * - * @author Richard Davey (original author) - * @author Marcus Bointon (Synchro/coolbru) - * @author Jim Jagielski (jimjag) - * @author Andy Prevost (codeworxtech) - */ -class POP3 -{ - /** - * The POP3 PHPMailer Version number. - * - * @var string - */ - const VERSION = '6.5.0'; - - /** - * Default POP3 port number. - * - * @var int - */ - const DEFAULT_PORT = 110; - - /** - * Default timeout in seconds. - * - * @var int - */ - const DEFAULT_TIMEOUT = 30; - - /** - * POP3 class debug output mode. - * Debug output level. - * Options: - * @see POP3::DEBUG_OFF: No output - * @see POP3::DEBUG_SERVER: Server messages, connection/server errors - * @see POP3::DEBUG_CLIENT: Client and Server messages, connection/server errors - * - * @var int - */ - public $do_debug = self::DEBUG_OFF; - - /** - * POP3 mail server hostname. - * - * @var string - */ - public $host; - - /** - * POP3 port number. - * - * @var int - */ - public $port; - - /** - * POP3 Timeout Value in seconds. - * - * @var int - */ - public $tval; - - /** - * POP3 username. - * - * @var string - */ - public $username; - - /** - * POP3 password. - * - * @var string - */ - public $password; - - /** - * Resource handle for the POP3 connection socket. - * - * @var resource - */ - protected $pop_conn; - - /** - * Are we connected? - * - * @var bool - */ - protected $connected = false; - - /** - * Error container. - * - * @var array - */ - protected $errors = []; - - /** - * Line break constant. - */ - const LE = "\r\n"; - - /** - * Debug level for no output. - * - * @var int - */ - const DEBUG_OFF = 0; - - /** - * Debug level to show server -> client messages - * also shows clients connection errors or errors from server - * - * @var int - */ - const DEBUG_SERVER = 1; - - /** - * Debug level to show client -> server and server -> client messages. - * - * @var int - */ - const DEBUG_CLIENT = 2; - - /** - * Simple static wrapper for all-in-one POP before SMTP. - * - * @param string $host The hostname to connect to - * @param int|bool $port The port number to connect to - * @param int|bool $timeout The timeout value - * @param string $username - * @param string $password - * @param int $debug_level - * - * @return bool - */ - public static function popBeforeSmtp( - $host, - $port = false, - $timeout = false, - $username = '', - $password = '', - $debug_level = 0 - ) { - $pop = new self(); - - return $pop->authorise($host, $port, $timeout, $username, $password, $debug_level); - } - - /** - * Authenticate with a POP3 server. - * A connect, login, disconnect sequence - * appropriate for POP-before SMTP authorisation. - * - * @param string $host The hostname to connect to - * @param int|bool $port The port number to connect to - * @param int|bool $timeout The timeout value - * @param string $username - * @param string $password - * @param int $debug_level - * - * @return bool - */ - public function authorise($host, $port = false, $timeout = false, $username = '', $password = '', $debug_level = 0) - { - $this->host = $host; - //If no port value provided, use default - if (false === $port) { - $this->port = static::DEFAULT_PORT; - } else { - $this->port = (int) $port; - } - //If no timeout value provided, use default - if (false === $timeout) { - $this->tval = static::DEFAULT_TIMEOUT; - } else { - $this->tval = (int) $timeout; - } - $this->do_debug = $debug_level; - $this->username = $username; - $this->password = $password; - //Reset the error log - $this->errors = []; - //Connect - $result = $this->connect($this->host, $this->port, $this->tval); - if ($result) { - $login_result = $this->login($this->username, $this->password); - if ($login_result) { - $this->disconnect(); - - return true; - } - } - //We need to disconnect regardless of whether the login succeeded - $this->disconnect(); - - return false; - } - - /** - * Connect to a POP3 server. - * - * @param string $host - * @param int|bool $port - * @param int $tval - * - * @return bool - */ - public function connect($host, $port = false, $tval = 30) - { - //Are we already connected? - if ($this->connected) { - return true; - } - - //On Windows this will raise a PHP Warning error if the hostname doesn't exist. - //Rather than suppress it with @fsockopen, capture it cleanly instead - set_error_handler([$this, 'catchWarning']); - - if (false === $port) { - $port = static::DEFAULT_PORT; - } - - //Connect to the POP3 server - $errno = 0; - $errstr = ''; - $this->pop_conn = fsockopen( - $host, //POP3 Host - $port, //Port # - $errno, //Error Number - $errstr, //Error Message - $tval - ); //Timeout (seconds) - //Restore the error handler - restore_error_handler(); - - //Did we connect? - if (false === $this->pop_conn) { - //It would appear not... - $this->setError( - "Failed to connect to server $host on port $port. errno: $errno; errstr: $errstr" - ); - - return false; - } - - //Increase the stream time-out - stream_set_timeout($this->pop_conn, $tval, 0); - - //Get the POP3 server response - $pop3_response = $this->getResponse(); - //Check for the +OK - if ($this->checkResponse($pop3_response)) { - //The connection is established and the POP3 server is talking - $this->connected = true; - - return true; - } - - return false; - } - - /** - * Log in to the POP3 server. - * Does not support APOP (RFC 2828, 4949). - * - * @param string $username - * @param string $password - * - * @return bool - */ - public function login($username = '', $password = '') - { - if (!$this->connected) { - $this->setError('Not connected to POP3 server'); - } - if (empty($username)) { - $username = $this->username; - } - if (empty($password)) { - $password = $this->password; - } - - //Send the Username - $this->sendString("USER $username" . static::LE); - $pop3_response = $this->getResponse(); - if ($this->checkResponse($pop3_response)) { - //Send the Password - $this->sendString("PASS $password" . static::LE); - $pop3_response = $this->getResponse(); - if ($this->checkResponse($pop3_response)) { - return true; - } - } - - return false; - } - - /** - * Disconnect from the POP3 server. - */ - public function disconnect() - { - $this->sendString('QUIT'); - //The QUIT command may cause the daemon to exit, which will kill our connection - //So ignore errors here - try { - @fclose($this->pop_conn); - } catch (Exception $e) { - //Do nothing - } - } - - /** - * Get a response from the POP3 server. - * - * @param int $size The maximum number of bytes to retrieve - * - * @return string - */ - protected function getResponse($size = 128) - { - $response = fgets($this->pop_conn, $size); - if ($this->do_debug >= self::DEBUG_SERVER) { - echo 'Server -> Client: ', $response; - } - - return $response; - } - - /** - * Send raw data to the POP3 server. - * - * @param string $string - * - * @return int - */ - protected function sendString($string) - { - if ($this->pop_conn) { - if ($this->do_debug >= self::DEBUG_CLIENT) { //Show client messages when debug >= 2 - echo 'Client -> Server: ', $string; - } - - return fwrite($this->pop_conn, $string, strlen($string)); - } - - return 0; - } - - /** - * Checks the POP3 server response. - * Looks for for +OK or -ERR. - * - * @param string $string - * - * @return bool - */ - protected function checkResponse($string) - { - if (strpos($string, '+OK') !== 0) { - $this->setError("Server reported an error: $string"); - - return false; - } - - return true; - } - - /** - * Add an error to the internal error store. - * Also display debug output if it's enabled. - * - * @param string $error - */ - protected function setError($error) - { - $this->errors[] = $error; - if ($this->do_debug >= self::DEBUG_SERVER) { - echo '
';
-            foreach ($this->errors as $e) {
-                print_r($e);
-            }
-            echo '
'; - } - } - - /** - * Get an array of error messages, if any. - * - * @return array - */ - public function getErrors() - { - return $this->errors; - } - - /** - * POP3 connection error handler. - * - * @param int $errno - * @param string $errstr - * @param string $errfile - * @param int $errline - */ - protected function catchWarning($errno, $errstr, $errfile, $errline) - { - $this->setError( - 'Connecting to the POP3 server raised a PHP warning:' . - "errno: $errno errstr: $errstr; errfile: $errfile; errline: $errline" - ); - } -} diff --git a/themes/pmem-hugo/static/include/phpmailer/src/SMTP.php b/themes/pmem-hugo/static/include/phpmailer/src/SMTP.php deleted file mode 100644 index a4a91ed0dc..0000000000 --- a/themes/pmem-hugo/static/include/phpmailer/src/SMTP.php +++ /dev/null @@ -1,1456 +0,0 @@ - - * @author Jim Jagielski (jimjag) - * @author Andy Prevost (codeworxtech) - * @author Brent R. Matzelle (original founder) - * @copyright 2012 - 2020 Marcus Bointon - * @copyright 2010 - 2012 Jim Jagielski - * @copyright 2004 - 2009 Andy Prevost - * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License - * @note This program is distributed in the hope that it will be useful - WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -namespace PHPMailer\PHPMailer; - -/** - * PHPMailer RFC821 SMTP email transport class. - * Implements RFC 821 SMTP commands and provides some utility methods for sending mail to an SMTP server. - * - * @author Chris Ryan - * @author Marcus Bointon - */ -class SMTP -{ - /** - * The PHPMailer SMTP version number. - * - * @var string - */ - const VERSION = '6.5.0'; - - /** - * SMTP line break constant. - * - * @var string - */ - const LE = "\r\n"; - - /** - * The SMTP port to use if one is not specified. - * - * @var int - */ - const DEFAULT_PORT = 25; - - /** - * The maximum line length allowed by RFC 5321 section 4.5.3.1.6, - * *excluding* a trailing CRLF break. - * - * @see https://tools.ietf.org/html/rfc5321#section-4.5.3.1.6 - * - * @var int - */ - const MAX_LINE_LENGTH = 998; - - /** - * The maximum line length allowed for replies in RFC 5321 section 4.5.3.1.5, - * *including* a trailing CRLF line break. - * - * @see https://tools.ietf.org/html/rfc5321#section-4.5.3.1.5 - * - * @var int - */ - const MAX_REPLY_LENGTH = 512; - - /** - * Debug level for no output. - * - * @var int - */ - const DEBUG_OFF = 0; - - /** - * Debug level to show client -> server messages. - * - * @var int - */ - const DEBUG_CLIENT = 1; - - /** - * Debug level to show client -> server and server -> client messages. - * - * @var int - */ - const DEBUG_SERVER = 2; - - /** - * Debug level to show connection status, client -> server and server -> client messages. - * - * @var int - */ - const DEBUG_CONNECTION = 3; - - /** - * Debug level to show all messages. - * - * @var int - */ - const DEBUG_LOWLEVEL = 4; - - /** - * Debug output level. - * Options: - * * self::DEBUG_OFF (`0`) No debug output, default - * * self::DEBUG_CLIENT (`1`) Client commands - * * self::DEBUG_SERVER (`2`) Client commands and server responses - * * self::DEBUG_CONNECTION (`3`) As DEBUG_SERVER plus connection status - * * self::DEBUG_LOWLEVEL (`4`) Low-level data output, all messages. - * - * @var int - */ - public $do_debug = self::DEBUG_OFF; - - /** - * How to handle debug output. - * Options: - * * `echo` Output plain-text as-is, appropriate for CLI - * * `html` Output escaped, line breaks converted to `
`, appropriate for browser output - * * `error_log` Output to error log as configured in php.ini - * Alternatively, you can provide a callable expecting two params: a message string and the debug level: - * - * ```php - * $smtp->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";}; - * ``` - * - * Alternatively, you can pass in an instance of a PSR-3 compatible logger, though only `debug` - * level output is used: - * - * ```php - * $mail->Debugoutput = new myPsr3Logger; - * ``` - * - * @var string|callable|\Psr\Log\LoggerInterface - */ - public $Debugoutput = 'echo'; - - /** - * Whether to use VERP. - * - * @see http://en.wikipedia.org/wiki/Variable_envelope_return_path - * @see http://www.postfix.org/VERP_README.html Info on VERP - * - * @var bool - */ - public $do_verp = false; - - /** - * The timeout value for connection, in seconds. - * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2. - * This needs to be quite high to function correctly with hosts using greetdelay as an anti-spam measure. - * - * @see http://tools.ietf.org/html/rfc2821#section-4.5.3.2 - * - * @var int - */ - public $Timeout = 300; - - /** - * How long to wait for commands to complete, in seconds. - * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2. - * - * @var int - */ - public $Timelimit = 300; - - /** - * Patterns to extract an SMTP transaction id from reply to a DATA command. - * The first capture group in each regex will be used as the ID. - * MS ESMTP returns the message ID, which may not be correct for internal tracking. - * - * @var string[] - */ - protected $smtp_transaction_id_patterns = [ - 'exim' => '/[\d]{3} OK id=(.*)/', - 'sendmail' => '/[\d]{3} 2.0.0 (.*) Message/', - 'postfix' => '/[\d]{3} 2.0.0 Ok: queued as (.*)/', - 'Microsoft_ESMTP' => '/[0-9]{3} 2.[\d].0 (.*)@(?:.*) Queued mail for delivery/', - 'Amazon_SES' => '/[\d]{3} Ok (.*)/', - 'SendGrid' => '/[\d]{3} Ok: queued as (.*)/', - 'CampaignMonitor' => '/[\d]{3} 2.0.0 OK:([a-zA-Z\d]{48})/', - 'Haraka' => '/[\d]{3} Message Queued \((.*)\)/', - ]; - - /** - * The last transaction ID issued in response to a DATA command, - * if one was detected. - * - * @var string|bool|null - */ - protected $last_smtp_transaction_id; - - /** - * The socket for the server connection. - * - * @var ?resource - */ - protected $smtp_conn; - - /** - * Error information, if any, for the last SMTP command. - * - * @var array - */ - protected $error = [ - 'error' => '', - 'detail' => '', - 'smtp_code' => '', - 'smtp_code_ex' => '', - ]; - - /** - * The reply the server sent to us for HELO. - * If null, no HELO string has yet been received. - * - * @var string|null - */ - protected $helo_rply; - - /** - * The set of SMTP extensions sent in reply to EHLO command. - * Indexes of the array are extension names. - * Value at index 'HELO' or 'EHLO' (according to command that was sent) - * represents the server name. In case of HELO it is the only element of the array. - * Other values can be boolean TRUE or an array containing extension options. - * If null, no HELO/EHLO string has yet been received. - * - * @var array|null - */ - protected $server_caps; - - /** - * The most recent reply received from the server. - * - * @var string - */ - protected $last_reply = ''; - - /** - * Output debugging info via a user-selected method. - * - * @param string $str Debug string to output - * @param int $level The debug level of this message; see DEBUG_* constants - * - * @see SMTP::$Debugoutput - * @see SMTP::$do_debug - */ - protected function edebug($str, $level = 0) - { - if ($level > $this->do_debug) { - return; - } - //Is this a PSR-3 logger? - if ($this->Debugoutput instanceof \Psr\Log\LoggerInterface) { - $this->Debugoutput->debug($str); - - return; - } - //Avoid clash with built-in function names - if (is_callable($this->Debugoutput) && !in_array($this->Debugoutput, ['error_log', 'html', 'echo'])) { - call_user_func($this->Debugoutput, $str, $level); - - return; - } - switch ($this->Debugoutput) { - case 'error_log': - //Don't output, just log - error_log($str); - break; - case 'html': - //Cleans up output a bit for a better looking, HTML-safe output - echo gmdate('Y-m-d H:i:s'), ' ', htmlentities( - preg_replace('/[\r\n]+/', '', $str), - ENT_QUOTES, - 'UTF-8' - ), "
\n"; - break; - case 'echo': - default: - //Normalize line breaks - $str = preg_replace('/\r\n|\r/m', "\n", $str); - echo gmdate('Y-m-d H:i:s'), - "\t", - //Trim trailing space - trim( - //Indent for readability, except for trailing break - str_replace( - "\n", - "\n \t ", - trim($str) - ) - ), - "\n"; - } - } - - /** - * Connect to an SMTP server. - * - * @param string $host SMTP server IP or host name - * @param int $port The port number to connect to - * @param int $timeout How long to wait for the connection to open - * @param array $options An array of options for stream_context_create() - * - * @return bool - */ - public function connect($host, $port = null, $timeout = 30, $options = []) - { - //Clear errors to avoid confusion - $this->setError(''); - //Make sure we are __not__ connected - if ($this->connected()) { - //Already connected, generate error - $this->setError('Already connected to a server'); - - return false; - } - if (empty($port)) { - $port = self::DEFAULT_PORT; - } - //Connect to the SMTP server - $this->edebug( - "Connection: opening to $host:$port, timeout=$timeout, options=" . - (count($options) > 0 ? var_export($options, true) : 'array()'), - self::DEBUG_CONNECTION - ); - - $this->smtp_conn = $this->getSMTPConnection($host, $port, $timeout, $options); - - if ($this->smtp_conn === false) { - //Error info already set inside `getSMTPConnection()` - return false; - } - - $this->edebug('Connection: opened', self::DEBUG_CONNECTION); - - //Get any announcement - $this->last_reply = $this->get_lines(); - $this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER); - $responseCode = (int)substr($this->last_reply, 0, 3); - if ($responseCode === 220) { - return true; - } - //Anything other than a 220 response means something went wrong - //RFC 5321 says the server will wait for us to send a QUIT in response to a 554 error - //https://tools.ietf.org/html/rfc5321#section-3.1 - if ($responseCode === 554) { - $this->quit(); - } - //This will handle 421 responses which may not wait for a QUIT (e.g. if the server is being shut down) - $this->edebug('Connection: closing due to error', self::DEBUG_CONNECTION); - $this->close(); - return false; - } - - /** - * Create connection to the SMTP server. - * - * @param string $host SMTP server IP or host name - * @param int $port The port number to connect to - * @param int $timeout How long to wait for the connection to open - * @param array $options An array of options for stream_context_create() - * - * @return false|resource - */ - protected function getSMTPConnection($host, $port = null, $timeout = 30, $options = []) - { - static $streamok; - //This is enabled by default since 5.0.0 but some providers disable it - //Check this once and cache the result - if (null === $streamok) { - $streamok = function_exists('stream_socket_client'); - } - - $errno = 0; - $errstr = ''; - if ($streamok) { - $socket_context = stream_context_create($options); - set_error_handler([$this, 'errorHandler']); - $connection = stream_socket_client( - $host . ':' . $port, - $errno, - $errstr, - $timeout, - STREAM_CLIENT_CONNECT, - $socket_context - ); - restore_error_handler(); - } else { - //Fall back to fsockopen which should work in more places, but is missing some features - $this->edebug( - 'Connection: stream_socket_client not available, falling back to fsockopen', - self::DEBUG_CONNECTION - ); - set_error_handler([$this, 'errorHandler']); - $connection = fsockopen( - $host, - $port, - $errno, - $errstr, - $timeout - ); - restore_error_handler(); - } - - //Verify we connected properly - if (!is_resource($connection)) { - $this->setError( - 'Failed to connect to server', - '', - (string) $errno, - $errstr - ); - $this->edebug( - 'SMTP ERROR: ' . $this->error['error'] - . ": $errstr ($errno)", - self::DEBUG_CLIENT - ); - - return false; - } - - //SMTP server can take longer to respond, give longer timeout for first read - //Windows does not have support for this timeout function - if (strpos(PHP_OS, 'WIN') !== 0) { - $max = (int)ini_get('max_execution_time'); - //Don't bother if unlimited, or if set_time_limit is disabled - if (0 !== $max && $timeout > $max && strpos(ini_get('disable_functions'), 'set_time_limit') === false) { - @set_time_limit($timeout); - } - stream_set_timeout($connection, $timeout, 0); - } - - return $connection; - } - - /** - * Initiate a TLS (encrypted) session. - * - * @return bool - */ - public function startTLS() - { - if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) { - return false; - } - - //Allow the best TLS version(s) we can - $crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT; - - //PHP 5.6.7 dropped inclusion of TLS 1.1 and 1.2 in STREAM_CRYPTO_METHOD_TLS_CLIENT - //so add them back in manually if we can - if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) { - $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT; - $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT; - } - - //Begin encrypted connection - set_error_handler([$this, 'errorHandler']); - $crypto_ok = stream_socket_enable_crypto( - $this->smtp_conn, - true, - $crypto_method - ); - restore_error_handler(); - - return (bool) $crypto_ok; - } - - /** - * Perform SMTP authentication. - * Must be run after hello(). - * - * @see hello() - * - * @param string $username The user name - * @param string $password The password - * @param string $authtype The auth type (CRAM-MD5, PLAIN, LOGIN, XOAUTH2) - * @param OAuth $OAuth An optional OAuth instance for XOAUTH2 authentication - * - * @return bool True if successfully authenticated - */ - public function authenticate( - $username, - $password, - $authtype = null, - $OAuth = null - ) { - if (!$this->server_caps) { - $this->setError('Authentication is not allowed before HELO/EHLO'); - - return false; - } - - if (array_key_exists('EHLO', $this->server_caps)) { - //SMTP extensions are available; try to find a proper authentication method - if (!array_key_exists('AUTH', $this->server_caps)) { - $this->setError('Authentication is not allowed at this stage'); - //'at this stage' means that auth may be allowed after the stage changes - //e.g. after STARTTLS - - return false; - } - - $this->edebug('Auth method requested: ' . ($authtype ?: 'UNSPECIFIED'), self::DEBUG_LOWLEVEL); - $this->edebug( - 'Auth methods available on the server: ' . implode(',', $this->server_caps['AUTH']), - self::DEBUG_LOWLEVEL - ); - - //If we have requested a specific auth type, check the server supports it before trying others - if (null !== $authtype && !in_array($authtype, $this->server_caps['AUTH'], true)) { - $this->edebug('Requested auth method not available: ' . $authtype, self::DEBUG_LOWLEVEL); - $authtype = null; - } - - if (empty($authtype)) { - //If no auth mechanism is specified, attempt to use these, in this order - //Try CRAM-MD5 first as it's more secure than the others - foreach (['CRAM-MD5', 'LOGIN', 'PLAIN', 'XOAUTH2'] as $method) { - if (in_array($method, $this->server_caps['AUTH'], true)) { - $authtype = $method; - break; - } - } - if (empty($authtype)) { - $this->setError('No supported authentication methods found'); - - return false; - } - $this->edebug('Auth method selected: ' . $authtype, self::DEBUG_LOWLEVEL); - } - - if (!in_array($authtype, $this->server_caps['AUTH'], true)) { - $this->setError("The requested authentication method \"$authtype\" is not supported by the server"); - - return false; - } - } elseif (empty($authtype)) { - $authtype = 'LOGIN'; - } - switch ($authtype) { - case 'PLAIN': - //Start authentication - if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) { - return false; - } - //Send encoded username and password - if ( - //Format from https://tools.ietf.org/html/rfc4616#section-2 - //We skip the first field (it's forgery), so the string starts with a null byte - !$this->sendCommand( - 'User & Password', - base64_encode("\0" . $username . "\0" . $password), - 235 - ) - ) { - return false; - } - break; - case 'LOGIN': - //Start authentication - if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) { - return false; - } - if (!$this->sendCommand('Username', base64_encode($username), 334)) { - return false; - } - if (!$this->sendCommand('Password', base64_encode($password), 235)) { - return false; - } - break; - case 'CRAM-MD5': - //Start authentication - if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) { - return false; - } - //Get the challenge - $challenge = base64_decode(substr($this->last_reply, 4)); - - //Build the response - $response = $username . ' ' . $this->hmac($challenge, $password); - - //send encoded credentials - return $this->sendCommand('Username', base64_encode($response), 235); - case 'XOAUTH2': - //The OAuth instance must be set up prior to requesting auth. - if (null === $OAuth) { - return false; - } - $oauth = $OAuth->getOauth64(); - - //Start authentication - if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) { - return false; - } - break; - default: - $this->setError("Authentication method \"$authtype\" is not supported"); - - return false; - } - - return true; - } - - /** - * Calculate an MD5 HMAC hash. - * Works like hash_hmac('md5', $data, $key) - * in case that function is not available. - * - * @param string $data The data to hash - * @param string $key The key to hash with - * - * @return string - */ - protected function hmac($data, $key) - { - if (function_exists('hash_hmac')) { - return hash_hmac('md5', $data, $key); - } - - //The following borrowed from - //http://php.net/manual/en/function.mhash.php#27225 - - //RFC 2104 HMAC implementation for php. - //Creates an md5 HMAC. - //Eliminates the need to install mhash to compute a HMAC - //by Lance Rushing - - $bytelen = 64; //byte length for md5 - if (strlen($key) > $bytelen) { - $key = pack('H*', md5($key)); - } - $key = str_pad($key, $bytelen, chr(0x00)); - $ipad = str_pad('', $bytelen, chr(0x36)); - $opad = str_pad('', $bytelen, chr(0x5c)); - $k_ipad = $key ^ $ipad; - $k_opad = $key ^ $opad; - - return md5($k_opad . pack('H*', md5($k_ipad . $data))); - } - - /** - * Check connection state. - * - * @return bool True if connected - */ - public function connected() - { - if (is_resource($this->smtp_conn)) { - $sock_status = stream_get_meta_data($this->smtp_conn); - if ($sock_status['eof']) { - //The socket is valid but we are not connected - $this->edebug( - 'SMTP NOTICE: EOF caught while checking if connected', - self::DEBUG_CLIENT - ); - $this->close(); - - return false; - } - - return true; //everything looks good - } - - return false; - } - - /** - * Close the socket and clean up the state of the class. - * Don't use this function without first trying to use QUIT. - * - * @see quit() - */ - public function close() - { - $this->setError(''); - $this->server_caps = null; - $this->helo_rply = null; - if (is_resource($this->smtp_conn)) { - //Close the connection and cleanup - fclose($this->smtp_conn); - $this->smtp_conn = null; //Makes for cleaner serialization - $this->edebug('Connection: closed', self::DEBUG_CONNECTION); - } - } - - /** - * Send an SMTP DATA command. - * Issues a data command and sends the msg_data to the server, - * finializing the mail transaction. $msg_data is the message - * that is to be send with the headers. Each header needs to be - * on a single line followed by a with the message headers - * and the message body being separated by an additional . - * Implements RFC 821: DATA . - * - * @param string $msg_data Message data to send - * - * @return bool - */ - public function data($msg_data) - { - //This will use the standard timelimit - if (!$this->sendCommand('DATA', 'DATA', 354)) { - return false; - } - - /* The server is ready to accept data! - * According to rfc821 we should not send more than 1000 characters on a single line (including the LE) - * so we will break the data up into lines by \r and/or \n then if needed we will break each of those into - * smaller lines to fit within the limit. - * We will also look for lines that start with a '.' and prepend an additional '.'. - * NOTE: this does not count towards line-length limit. - */ - - //Normalize line breaks before exploding - $lines = explode("\n", str_replace(["\r\n", "\r"], "\n", $msg_data)); - - /* To distinguish between a complete RFC822 message and a plain message body, we check if the first field - * of the first line (':' separated) does not contain a space then it _should_ be a header and we will - * process all lines before a blank line as headers. - */ - - $field = substr($lines[0], 0, strpos($lines[0], ':')); - $in_headers = false; - if (!empty($field) && strpos($field, ' ') === false) { - $in_headers = true; - } - - foreach ($lines as $line) { - $lines_out = []; - if ($in_headers && $line === '') { - $in_headers = false; - } - //Break this line up into several smaller lines if it's too long - //Micro-optimisation: isset($str[$len]) is faster than (strlen($str) > $len), - while (isset($line[self::MAX_LINE_LENGTH])) { - //Working backwards, try to find a space within the last MAX_LINE_LENGTH chars of the line to break on - //so as to avoid breaking in the middle of a word - $pos = strrpos(substr($line, 0, self::MAX_LINE_LENGTH), ' '); - //Deliberately matches both false and 0 - if (!$pos) { - //No nice break found, add a hard break - $pos = self::MAX_LINE_LENGTH - 1; - $lines_out[] = substr($line, 0, $pos); - $line = substr($line, $pos); - } else { - //Break at the found point - $lines_out[] = substr($line, 0, $pos); - //Move along by the amount we dealt with - $line = substr($line, $pos + 1); - } - //If processing headers add a LWSP-char to the front of new line RFC822 section 3.1.1 - if ($in_headers) { - $line = "\t" . $line; - } - } - $lines_out[] = $line; - - //Send the lines to the server - foreach ($lines_out as $line_out) { - //Dot-stuffing as per RFC5321 section 4.5.2 - //https://tools.ietf.org/html/rfc5321#section-4.5.2 - if (!empty($line_out) && $line_out[0] === '.') { - $line_out = '.' . $line_out; - } - $this->client_send($line_out . static::LE, 'DATA'); - } - } - - //Message data has been sent, complete the command - //Increase timelimit for end of DATA command - $savetimelimit = $this->Timelimit; - $this->Timelimit *= 2; - $result = $this->sendCommand('DATA END', '.', 250); - $this->recordLastTransactionID(); - //Restore timelimit - $this->Timelimit = $savetimelimit; - - return $result; - } - - /** - * Send an SMTP HELO or EHLO command. - * Used to identify the sending server to the receiving server. - * This makes sure that client and server are in a known state. - * Implements RFC 821: HELO - * and RFC 2821 EHLO. - * - * @param string $host The host name or IP to connect to - * - * @return bool - */ - public function hello($host = '') - { - //Try extended hello first (RFC 2821) - if ($this->sendHello('EHLO', $host)) { - return true; - } - - //Some servers shut down the SMTP service here (RFC 5321) - if (substr($this->helo_rply, 0, 3) == '421') { - return false; - } - - return $this->sendHello('HELO', $host); - } - - /** - * Send an SMTP HELO or EHLO command. - * Low-level implementation used by hello(). - * - * @param string $hello The HELO string - * @param string $host The hostname to say we are - * - * @return bool - * - * @see hello() - */ - protected function sendHello($hello, $host) - { - $noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250); - $this->helo_rply = $this->last_reply; - if ($noerror) { - $this->parseHelloFields($hello); - } else { - $this->server_caps = null; - } - - return $noerror; - } - - /** - * Parse a reply to HELO/EHLO command to discover server extensions. - * In case of HELO, the only parameter that can be discovered is a server name. - * - * @param string $type `HELO` or `EHLO` - */ - protected function parseHelloFields($type) - { - $this->server_caps = []; - $lines = explode("\n", $this->helo_rply); - - foreach ($lines as $n => $s) { - //First 4 chars contain response code followed by - or space - $s = trim(substr($s, 4)); - if (empty($s)) { - continue; - } - $fields = explode(' ', $s); - if (!empty($fields)) { - if (!$n) { - $name = $type; - $fields = $fields[0]; - } else { - $name = array_shift($fields); - switch ($name) { - case 'SIZE': - $fields = ($fields ? $fields[0] : 0); - break; - case 'AUTH': - if (!is_array($fields)) { - $fields = []; - } - break; - default: - $fields = true; - } - } - $this->server_caps[$name] = $fields; - } - } - } - - /** - * Send an SMTP MAIL command. - * Starts a mail transaction from the email address specified in - * $from. Returns true if successful or false otherwise. If True - * the mail transaction is started and then one or more recipient - * commands may be called followed by a data command. - * Implements RFC 821: MAIL FROM: . - * - * @param string $from Source address of this message - * - * @return bool - */ - public function mail($from) - { - $useVerp = ($this->do_verp ? ' XVERP' : ''); - - return $this->sendCommand( - 'MAIL FROM', - 'MAIL FROM:<' . $from . '>' . $useVerp, - 250 - ); - } - - /** - * Send an SMTP QUIT command. - * Closes the socket if there is no error or the $close_on_error argument is true. - * Implements from RFC 821: QUIT . - * - * @param bool $close_on_error Should the connection close if an error occurs? - * - * @return bool - */ - public function quit($close_on_error = true) - { - $noerror = $this->sendCommand('QUIT', 'QUIT', 221); - $err = $this->error; //Save any error - if ($noerror || $close_on_error) { - $this->close(); - $this->error = $err; //Restore any error from the quit command - } - - return $noerror; - } - - /** - * Send an SMTP RCPT command. - * Sets the TO argument to $toaddr. - * Returns true if the recipient was accepted false if it was rejected. - * Implements from RFC 821: RCPT TO: . - * - * @param string $address The address the message is being sent to - * @param string $dsn Comma separated list of DSN notifications. NEVER, SUCCESS, FAILURE - * or DELAY. If you specify NEVER all other notifications are ignored. - * - * @return bool - */ - public function recipient($address, $dsn = '') - { - if (empty($dsn)) { - $rcpt = 'RCPT TO:<' . $address . '>'; - } else { - $dsn = strtoupper($dsn); - $notify = []; - - if (strpos($dsn, 'NEVER') !== false) { - $notify[] = 'NEVER'; - } else { - foreach (['SUCCESS', 'FAILURE', 'DELAY'] as $value) { - if (strpos($dsn, $value) !== false) { - $notify[] = $value; - } - } - } - - $rcpt = 'RCPT TO:<' . $address . '> NOTIFY=' . implode(',', $notify); - } - - return $this->sendCommand( - 'RCPT TO', - $rcpt, - [250, 251] - ); - } - - /** - * Send an SMTP RSET command. - * Abort any transaction that is currently in progress. - * Implements RFC 821: RSET . - * - * @return bool True on success - */ - public function reset() - { - return $this->sendCommand('RSET', 'RSET', 250); - } - - /** - * Send a command to an SMTP server and check its return code. - * - * @param string $command The command name - not sent to the server - * @param string $commandstring The actual command to send - * @param int|array $expect One or more expected integer success codes - * - * @return bool True on success - */ - protected function sendCommand($command, $commandstring, $expect) - { - if (!$this->connected()) { - $this->setError("Called $command without being connected"); - - return false; - } - //Reject line breaks in all commands - if ((strpos($commandstring, "\n") !== false) || (strpos($commandstring, "\r") !== false)) { - $this->setError("Command '$command' contained line breaks"); - - return false; - } - $this->client_send($commandstring . static::LE, $command); - - $this->last_reply = $this->get_lines(); - //Fetch SMTP code and possible error code explanation - $matches = []; - if (preg_match('/^([\d]{3})[ -](?:([\d]\\.[\d]\\.[\d]{1,2}) )?/', $this->last_reply, $matches)) { - $code = (int) $matches[1]; - $code_ex = (count($matches) > 2 ? $matches[2] : null); - //Cut off error code from each response line - $detail = preg_replace( - "/{$code}[ -]" . - ($code_ex ? str_replace('.', '\\.', $code_ex) . ' ' : '') . '/m', - '', - $this->last_reply - ); - } else { - //Fall back to simple parsing if regex fails - $code = (int) substr($this->last_reply, 0, 3); - $code_ex = null; - $detail = substr($this->last_reply, 4); - } - - $this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER); - - if (!in_array($code, (array) $expect, true)) { - $this->setError( - "$command command failed", - $detail, - $code, - $code_ex - ); - $this->edebug( - 'SMTP ERROR: ' . $this->error['error'] . ': ' . $this->last_reply, - self::DEBUG_CLIENT - ); - - return false; - } - - $this->setError(''); - - return true; - } - - /** - * Send an SMTP SAML command. - * Starts a mail transaction from the email address specified in $from. - * Returns true if successful or false otherwise. If True - * the mail transaction is started and then one or more recipient - * commands may be called followed by a data command. This command - * will send the message to the users terminal if they are logged - * in and send them an email. - * Implements RFC 821: SAML FROM: . - * - * @param string $from The address the message is from - * - * @return bool - */ - public function sendAndMail($from) - { - return $this->sendCommand('SAML', "SAML FROM:$from", 250); - } - - /** - * Send an SMTP VRFY command. - * - * @param string $name The name to verify - * - * @return bool - */ - public function verify($name) - { - return $this->sendCommand('VRFY', "VRFY $name", [250, 251]); - } - - /** - * Send an SMTP NOOP command. - * Used to keep keep-alives alive, doesn't actually do anything. - * - * @return bool - */ - public function noop() - { - return $this->sendCommand('NOOP', 'NOOP', 250); - } - - /** - * Send an SMTP TURN command. - * This is an optional command for SMTP that this class does not support. - * This method is here to make the RFC821 Definition complete for this class - * and _may_ be implemented in future. - * Implements from RFC 821: TURN . - * - * @return bool - */ - public function turn() - { - $this->setError('The SMTP TURN command is not implemented'); - $this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT); - - return false; - } - - /** - * Send raw data to the server. - * - * @param string $data The data to send - * @param string $command Optionally, the command this is part of, used only for controlling debug output - * - * @return int|bool The number of bytes sent to the server or false on error - */ - public function client_send($data, $command = '') - { - //If SMTP transcripts are left enabled, or debug output is posted online - //it can leak credentials, so hide credentials in all but lowest level - if ( - self::DEBUG_LOWLEVEL > $this->do_debug && - in_array($command, ['User & Password', 'Username', 'Password'], true) - ) { - $this->edebug('CLIENT -> SERVER: [credentials hidden]', self::DEBUG_CLIENT); - } else { - $this->edebug('CLIENT -> SERVER: ' . $data, self::DEBUG_CLIENT); - } - set_error_handler([$this, 'errorHandler']); - $result = fwrite($this->smtp_conn, $data); - restore_error_handler(); - - return $result; - } - - /** - * Get the latest error. - * - * @return array - */ - public function getError() - { - return $this->error; - } - - /** - * Get SMTP extensions available on the server. - * - * @return array|null - */ - public function getServerExtList() - { - return $this->server_caps; - } - - /** - * Get metadata about the SMTP server from its HELO/EHLO response. - * The method works in three ways, dependent on argument value and current state: - * 1. HELO/EHLO has not been sent - returns null and populates $this->error. - * 2. HELO has been sent - - * $name == 'HELO': returns server name - * $name == 'EHLO': returns boolean false - * $name == any other string: returns null and populates $this->error - * 3. EHLO has been sent - - * $name == 'HELO'|'EHLO': returns the server name - * $name == any other string: if extension $name exists, returns True - * or its options (e.g. AUTH mechanisms supported). Otherwise returns False. - * - * @param string $name Name of SMTP extension or 'HELO'|'EHLO' - * - * @return string|bool|null - */ - public function getServerExt($name) - { - if (!$this->server_caps) { - $this->setError('No HELO/EHLO was sent'); - - return; - } - - if (!array_key_exists($name, $this->server_caps)) { - if ('HELO' === $name) { - return $this->server_caps['EHLO']; - } - if ('EHLO' === $name || array_key_exists('EHLO', $this->server_caps)) { - return false; - } - $this->setError('HELO handshake was used; No information about server extensions available'); - - return; - } - - return $this->server_caps[$name]; - } - - /** - * Get the last reply from the server. - * - * @return string - */ - public function getLastReply() - { - return $this->last_reply; - } - - /** - * Read the SMTP server's response. - * Either before eof or socket timeout occurs on the operation. - * With SMTP we can tell if we have more lines to read if the - * 4th character is '-' symbol. If it is a space then we don't - * need to read anything else. - * - * @return string - */ - protected function get_lines() - { - //If the connection is bad, give up straight away - if (!is_resource($this->smtp_conn)) { - return ''; - } - $data = ''; - $endtime = 0; - stream_set_timeout($this->smtp_conn, $this->Timeout); - if ($this->Timelimit > 0) { - $endtime = time() + $this->Timelimit; - } - $selR = [$this->smtp_conn]; - $selW = null; - while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) { - //Must pass vars in here as params are by reference - //solution for signals inspired by https://github.com/symfony/symfony/pull/6540 - set_error_handler([$this, 'errorHandler']); - $n = stream_select($selR, $selW, $selW, $this->Timelimit); - restore_error_handler(); - - if ($n === false) { - $message = $this->getError()['detail']; - - $this->edebug( - 'SMTP -> get_lines(): select failed (' . $message . ')', - self::DEBUG_LOWLEVEL - ); - - //stream_select returns false when the `select` system call is interrupted - //by an incoming signal, try the select again - if (stripos($message, 'interrupted system call') !== false) { - $this->edebug( - 'SMTP -> get_lines(): retrying stream_select', - self::DEBUG_LOWLEVEL - ); - $this->setError(''); - continue; - } - - break; - } - - if (!$n) { - $this->edebug( - 'SMTP -> get_lines(): select timed-out in (' . $this->Timelimit . ' sec)', - self::DEBUG_LOWLEVEL - ); - break; - } - - //Deliberate noise suppression - errors are handled afterwards - $str = @fgets($this->smtp_conn, self::MAX_REPLY_LENGTH); - $this->edebug('SMTP INBOUND: "' . trim($str) . '"', self::DEBUG_LOWLEVEL); - $data .= $str; - //If response is only 3 chars (not valid, but RFC5321 S4.2 says it must be handled), - //or 4th character is a space or a line break char, we are done reading, break the loop. - //String array access is a significant micro-optimisation over strlen - if (!isset($str[3]) || $str[3] === ' ' || $str[3] === "\r" || $str[3] === "\n") { - break; - } - //Timed-out? Log and break - $info = stream_get_meta_data($this->smtp_conn); - if ($info['timed_out']) { - $this->edebug( - 'SMTP -> get_lines(): stream timed-out (' . $this->Timeout . ' sec)', - self::DEBUG_LOWLEVEL - ); - break; - } - //Now check if reads took too long - if ($endtime && time() > $endtime) { - $this->edebug( - 'SMTP -> get_lines(): timelimit reached (' . - $this->Timelimit . ' sec)', - self::DEBUG_LOWLEVEL - ); - break; - } - } - - return $data; - } - - /** - * Enable or disable VERP address generation. - * - * @param bool $enabled - */ - public function setVerp($enabled = false) - { - $this->do_verp = $enabled; - } - - /** - * Get VERP address generation mode. - * - * @return bool - */ - public function getVerp() - { - return $this->do_verp; - } - - /** - * Set error messages and codes. - * - * @param string $message The error message - * @param string $detail Further detail on the error - * @param string $smtp_code An associated SMTP error code - * @param string $smtp_code_ex Extended SMTP code - */ - protected function setError($message, $detail = '', $smtp_code = '', $smtp_code_ex = '') - { - $this->error = [ - 'error' => $message, - 'detail' => $detail, - 'smtp_code' => $smtp_code, - 'smtp_code_ex' => $smtp_code_ex, - ]; - } - - /** - * Set debug output method. - * - * @param string|callable $method The name of the mechanism to use for debugging output, or a callable to handle it - */ - public function setDebugOutput($method = 'echo') - { - $this->Debugoutput = $method; - } - - /** - * Get debug output method. - * - * @return string - */ - public function getDebugOutput() - { - return $this->Debugoutput; - } - - /** - * Set debug output level. - * - * @param int $level - */ - public function setDebugLevel($level = 0) - { - $this->do_debug = $level; - } - - /** - * Get debug output level. - * - * @return int - */ - public function getDebugLevel() - { - return $this->do_debug; - } - - /** - * Set SMTP timeout. - * - * @param int $timeout The timeout duration in seconds - */ - public function setTimeout($timeout = 0) - { - $this->Timeout = $timeout; - } - - /** - * Get SMTP timeout. - * - * @return int - */ - public function getTimeout() - { - return $this->Timeout; - } - - /** - * Reports an error number and string. - * - * @param int $errno The error number returned by PHP - * @param string $errmsg The error message returned by PHP - * @param string $errfile The file the error occurred in - * @param int $errline The line number the error occurred on - */ - protected function errorHandler($errno, $errmsg, $errfile = '', $errline = 0) - { - $notice = 'Connection failed.'; - $this->setError( - $notice, - $errmsg, - (string) $errno - ); - $this->edebug( - "$notice Error #$errno: $errmsg [$errfile line $errline]", - self::DEBUG_CONNECTION - ); - } - - /** - * Extract and return the ID of the last SMTP transaction based on - * a list of patterns provided in SMTP::$smtp_transaction_id_patterns. - * Relies on the host providing the ID in response to a DATA command. - * If no reply has been received yet, it will return null. - * If no pattern was matched, it will return false. - * - * @return bool|string|null - */ - protected function recordLastTransactionID() - { - $reply = $this->getLastReply(); - - if (empty($reply)) { - $this->last_smtp_transaction_id = null; - } else { - $this->last_smtp_transaction_id = false; - foreach ($this->smtp_transaction_id_patterns as $smtp_transaction_id_pattern) { - $matches = []; - if (preg_match($smtp_transaction_id_pattern, $reply, $matches)) { - $this->last_smtp_transaction_id = trim($matches[1]); - break; - } - } - } - - return $this->last_smtp_transaction_id; - } - - /** - * Get the queue/transaction ID of the last SMTP transaction - * If no reply has been received yet, it will return null. - * If no pattern was matched, it will return false. - * - * @return bool|string|null - * - * @see recordLastTransactionID() - */ - public function getLastTransactionID() - { - return $this->last_smtp_transaction_id; - } -} diff --git a/themes/pmem-hugo/static/include/subscribe-cm.php b/themes/pmem-hugo/static/include/subscribe-cm.php deleted file mode 100644 index 7477beffa5..0000000000 --- a/themes/pmem-hugo/static/include/subscribe-cm.php +++ /dev/null @@ -1,33 +0,0 @@ - $apiKey); - - $wrap = new CS_REST_Subscribers( $listId, $auth); - - $result = $wrap->add(array( - 'EmailAddress' => $email, - 'Resubscribe' => true - )); - - if($result->was_successful()) { - echo '{ "alert": "success", "message": "You have been successfully subscribed to our Email List." }'; - } else { - echo '{ "alert": "error", "message": "Failed with code ' . $result->http_status_code . "\n
";
-		var_dump($result->response);
-		echo '
" }'; - } - -} \ No newline at end of file diff --git a/themes/pmem-hugo/static/include/subscribe-email.php b/themes/pmem-hugo/static/include/subscribe-email.php deleted file mode 100644 index 19736023dd..0000000000 --- a/themes/pmem-hugo/static/include/subscribe-email.php +++ /dev/null @@ -1,58 +0,0 @@ - 'username@website.com', // Your Email Address - 'name' => 'Your Name' // Your Name - ); - -// Form Processing Messages -$message_success = 'We have successfully received your Message and will get Back to you as soon as possible.'; - -$mail = new PHPMailer(); - -// If you intend you use SMTP, add your SMTP Code after this Line - - -if( isset( $_POST['widget-subscribe-form-email'] ) ) { - if( $_POST['widget-subscribe-form-email'] != '' ) { - - $email = $_POST['widget-subscribe-form-email']; - - $subject = 'Subscribe me to the List'; - - $mail->SetFrom( $email , 'New Subscriber' ); - $mail->AddReplyTo( $email ); - foreach( $toemails as $toemail ) { - $mail->AddAddress( $toemail['email'] , $toemail['name'] ); - } - $mail->Subject = $subject; - - $email = isset($email) ? "Email: $email

" : ''; - - $referrer = $_SERVER['HTTP_REFERER'] ? '


This Form was submitted from: ' . $_SERVER['HTTP_REFERER'] : ''; - - $body = "$email $referrer"; - - $mail->MsgHTML( $body ); - $sendEmail = $mail->Send(); - - if( $sendEmail == true ): - echo '{ "alert": "success", "message": "' . $message_success . '" }'; - else: - echo '{ "alert": "error", "message": "Email could not be sent due to some Unexpected Error. Please Try Again later.

Reason:
' . $mail->ErrorInfo . '" }'; - endif; - } else { - echo '{ "alert": "error", "message": "Please Fill up all the Fields and Try Again." }'; - } -} else { - echo '{ "alert": "error", "message": "An unexpected error occured. Please Try Again later." }'; -} - -?> \ No newline at end of file diff --git a/themes/pmem-hugo/static/include/subscribe.php b/themes/pmem-hugo/static/include/subscribe.php deleted file mode 100644 index 0938d04fd5..0000000000 --- a/themes/pmem-hugo/static/include/subscribe.php +++ /dev/null @@ -1,58 +0,0 @@ - $email, - 'status' => 'subscribed' - ); - - if( !empty( $merge_vars ) ) { $data['merge_fields'] = $merge_vars; } - - $payload = json_encode($data); - - $auth = base64_encode( 'user:' . $apiKey ); - - $header = array(); - $header[] = 'Content-type: application/json; charset=utf-8'; - $header[] = 'Authorization: Basic ' . $auth; - - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $submit_url); - curl_setopt($ch, CURLOPT_HTTPHEADER, $header); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch, CURLOPT_TIMEOUT, 10); - curl_setopt($ch, CURLOPT_POST, true); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); - curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); - - $result = curl_exec($ch); - curl_close($ch); - $data = json_decode($result); - - if ( isset( $data->status ) AND $data->status == 'subscribed' ){ - echo '{ "alert": "success", "message": "You have been successfully subscribed to our Email List." }'; - } else { - echo '{ "alert": "error", "message": "' . $data->title . '" }'; - } - -} - -?> \ No newline at end of file diff --git a/themes/pmem-hugo/static/include/twitter/oauth/OAuth.php b/themes/pmem-hugo/static/include/twitter/oauth/OAuth.php deleted file mode 100644 index 67a94c4790..0000000000 --- a/themes/pmem-hugo/static/include/twitter/oauth/OAuth.php +++ /dev/null @@ -1,874 +0,0 @@ -key = $key; - $this->secret = $secret; - $this->callback_url = $callback_url; - } - - function __toString() { - return "OAuthConsumer[key=$this->key,secret=$this->secret]"; - } -} - -class OAuthToken { - // access tokens and request tokens - public $key; - public $secret; - - /** - * key = the token - * secret = the token secret - */ - function __construct($key, $secret) { - $this->key = $key; - $this->secret = $secret; - } - - /** - * generates the basic string serialization of a token that a server - * would respond to request_token and access_token calls with - */ - function to_string() { - return "oauth_token=" . - OAuthUtil::urlencode_rfc3986($this->key) . - "&oauth_token_secret=" . - OAuthUtil::urlencode_rfc3986($this->secret); - } - - function __toString() { - return $this->to_string(); - } -} - -/** - * A class for implementing a Signature Method - * See section 9 ("Signing Requests") in the spec - */ -abstract class OAuthSignatureMethod { - /** - * Needs to return the name of the Signature Method (ie HMAC-SHA1) - * @return string - */ - abstract public function get_name(); - - /** - * Build up the signature - * NOTE: The output of this function MUST NOT be urlencoded. - * the encoding is handled in OAuthRequest when the final - * request is serialized - * @param OAuthRequest $request - * @param OAuthConsumer $consumer - * @param OAuthToken $token - * @return string - */ - abstract public function build_signature($request, $consumer, $token); - - /** - * Verifies that a given signature is correct - * @param OAuthRequest $request - * @param OAuthConsumer $consumer - * @param OAuthToken $token - * @param string $signature - * @return bool - */ - public function check_signature($request, $consumer, $token, $signature) { - $built = $this->build_signature($request, $consumer, $token); - return $built == $signature; - } -} - -/** - * The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104] - * where the Signature Base String is the text and the key is the concatenated values (each first - * encoded per Parameter Encoding) of the Consumer Secret and Token Secret, separated by an '&' - * character (ASCII code 38) even if empty. - * - Chapter 9.2 ("HMAC-SHA1") - */ -class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod { - function get_name() { - return "HMAC-SHA1"; - } - - public function build_signature($request, $consumer, $token) { - $base_string = $request->get_signature_base_string(); - $request->base_string = $base_string; - - $key_parts = array( - $consumer->secret, - ($token) ? $token->secret : "" - ); - - $key_parts = OAuthUtil::urlencode_rfc3986($key_parts); - $key = implode('&', $key_parts); - - return base64_encode(hash_hmac('sha1', $base_string, $key, true)); - } -} - -/** - * The PLAINTEXT method does not provide any security protection and SHOULD only be used - * over a secure channel such as HTTPS. It does not use the Signature Base String. - * - Chapter 9.4 ("PLAINTEXT") - */ -class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod { - public function get_name() { - return "PLAINTEXT"; - } - - /** - * oauth_signature is set to the concatenated encoded values of the Consumer Secret and - * Token Secret, separated by a '&' character (ASCII code 38), even if either secret is - * empty. The result MUST be encoded again. - * - Chapter 9.4.1 ("Generating Signatures") - * - * Please note that the second encoding MUST NOT happen in the SignatureMethod, as - * OAuthRequest handles this! - */ - public function build_signature($request, $consumer, $token) { - $key_parts = array( - $consumer->secret, - ($token) ? $token->secret : "" - ); - - $key_parts = OAuthUtil::urlencode_rfc3986($key_parts); - $key = implode('&', $key_parts); - $request->base_string = $key; - - return $key; - } -} - -/** - * The RSA-SHA1 signature method uses the RSASSA-PKCS1-v1_5 signature algorithm as defined in - * [RFC3447] section 8.2 (more simply known as PKCS#1), using SHA-1 as the hash function for - * EMSA-PKCS1-v1_5. It is assumed that the Consumer has provided its RSA public key in a - * verified way to the Service Provider, in a manner which is beyond the scope of this - * specification. - * - Chapter 9.3 ("RSA-SHA1") - */ -abstract class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod { - public function get_name() { - return "RSA-SHA1"; - } - - // Up to the SP to implement this lookup of keys. Possible ideas are: - // (1) do a lookup in a table of trusted certs keyed off of consumer - // (2) fetch via http using a url provided by the requester - // (3) some sort of specific discovery code based on request - // - // Either way should return a string representation of the certificate - protected abstract function fetch_public_cert(&$request); - - // Up to the SP to implement this lookup of keys. Possible ideas are: - // (1) do a lookup in a table of trusted certs keyed off of consumer - // - // Either way should return a string representation of the certificate - protected abstract function fetch_private_cert(&$request); - - public function build_signature($request, $consumer, $token) { - $base_string = $request->get_signature_base_string(); - $request->base_string = $base_string; - - // Fetch the private key cert based on the request - $cert = $this->fetch_private_cert($request); - - // Pull the private key ID from the certificate - $privatekeyid = openssl_get_privatekey($cert); - - // Sign using the key - $ok = openssl_sign($base_string, $signature, $privatekeyid); - - // Release the key resource - openssl_free_key($privatekeyid); - - return base64_encode($signature); - } - - public function check_signature($request, $consumer, $token, $signature) { - $decoded_sig = base64_decode($signature); - - $base_string = $request->get_signature_base_string(); - - // Fetch the public key cert based on the request - $cert = $this->fetch_public_cert($request); - - // Pull the public key ID from the certificate - $publickeyid = openssl_get_publickey($cert); - - // Check the computed signature against the one passed in the query - $ok = openssl_verify($base_string, $decoded_sig, $publickeyid); - - // Release the key resource - openssl_free_key($publickeyid); - - return $ok == 1; - } -} - -class OAuthRequest { - private $parameters; - private $http_method; - private $http_url; - // for debug purposes - public $base_string; - public static $version = '1.0'; - public static $POST_INPUT = 'php://input'; - - function __construct($http_method, $http_url, $parameters=NULL) { - @$parameters or $parameters = array(); - $parameters = array_merge( OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)), $parameters); - $this->parameters = $parameters; - $this->http_method = $http_method; - $this->http_url = $http_url; - } - - - /** - * attempt to build up a request from what was passed to the server - */ - public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) { - $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on") - ? 'http' - : 'https'; - @$http_url or $http_url = $scheme . - '://' . $_SERVER['HTTP_HOST'] . - ':' . - $_SERVER['SERVER_PORT'] . - $_SERVER['REQUEST_URI']; - @$http_method or $http_method = $_SERVER['REQUEST_METHOD']; - - // We weren't handed any parameters, so let's find the ones relevant to - // this request. - // If you run XML-RPC or similar you should use this to provide your own - // parsed parameter-list - if (!$parameters) { - // Find request headers - $request_headers = OAuthUtil::get_headers(); - - // Parse the query-string to find GET parameters - $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']); - - // It's a POST request of the proper content-type, so parse POST - // parameters and add those overriding any duplicates from GET - if ($http_method == "POST" - && @strstr($request_headers["Content-Type"], - "application/x-www-form-urlencoded") - ) { - $post_data = OAuthUtil::parse_parameters( - file_get_contents(self::$POST_INPUT) - ); - $parameters = array_merge($parameters, $post_data); - } - - // We have a Authorization-header with OAuth data. Parse the header - // and add those overriding any duplicates from GET or POST - if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") { - $header_parameters = OAuthUtil::split_header( - $request_headers['Authorization'] - ); - $parameters = array_merge($parameters, $header_parameters); - } - - } - - return new OAuthRequest($http_method, $http_url, $parameters); - } - - /** - * pretty much a helper function to set up the request - */ - public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) { - @$parameters or $parameters = array(); - $defaults = array("oauth_version" => OAuthRequest::$version, - "oauth_nonce" => OAuthRequest::generate_nonce(), - "oauth_timestamp" => OAuthRequest::generate_timestamp(), - "oauth_consumer_key" => $consumer->key); - if ($token) - $defaults['oauth_token'] = $token->key; - - $parameters = array_merge($defaults, $parameters); - - return new OAuthRequest($http_method, $http_url, $parameters); - } - - public function set_parameter($name, $value, $allow_duplicates = true) { - if ($allow_duplicates && isset($this->parameters[$name])) { - // We have already added parameter(s) with this name, so add to the list - if (is_scalar($this->parameters[$name])) { - // This is the first duplicate, so transform scalar (string) - // into an array so we can add the duplicates - $this->parameters[$name] = array($this->parameters[$name]); - } - - $this->parameters[$name][] = $value; - } else { - $this->parameters[$name] = $value; - } - } - - public function get_parameter($name) { - return isset($this->parameters[$name]) ? $this->parameters[$name] : null; - } - - public function get_parameters() { - return $this->parameters; - } - - public function unset_parameter($name) { - unset($this->parameters[$name]); - } - - /** - * The request parameters, sorted and concatenated into a normalized string. - * @return string - */ - public function get_signable_parameters() { - // Grab all parameters - $params = $this->parameters; - - // Remove oauth_signature if present - // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.") - if (isset($params['oauth_signature'])) { - unset($params['oauth_signature']); - } - - return OAuthUtil::build_http_query($params); - } - - /** - * Returns the base string of this request - * - * The base string defined as the method, the url - * and the parameters (normalized), each urlencoded - * and the concated with &. - */ - public function get_signature_base_string() { - $parts = array( - $this->get_normalized_http_method(), - $this->get_normalized_http_url(), - $this->get_signable_parameters() - ); - - $parts = OAuthUtil::urlencode_rfc3986($parts); - - return implode('&', $parts); - } - - /** - * just uppercases the http method - */ - public function get_normalized_http_method() { - return strtoupper($this->http_method); - } - - /** - * parses the url and rebuilds it to be - * scheme://host/path - */ - public function get_normalized_http_url() { - $parts = parse_url($this->http_url); - - $port = @$parts['port']; - $scheme = $parts['scheme']; - $host = $parts['host']; - $path = @$parts['path']; - - $port or $port = ($scheme == 'https') ? '443' : '80'; - - if (($scheme == 'https' && $port != '443') - || ($scheme == 'http' && $port != '80')) { - $host = "$host:$port"; - } - return "$scheme://$host$path"; - } - - /** - * builds a url usable for a GET request - */ - public function to_url() { - $post_data = $this->to_postdata(); - $out = $this->get_normalized_http_url(); - if ($post_data) { - $out .= '?'.$post_data; - } - return $out; - } - - /** - * builds the data one would send in a POST request - */ - public function to_postdata() { - return OAuthUtil::build_http_query($this->parameters); - } - - /** - * builds the Authorization: header - */ - public function to_header($realm=null) { - $first = true; - if($realm) { - $out = 'Authorization: OAuth realm="' . OAuthUtil::urlencode_rfc3986($realm) . '"'; - $first = false; - } else - $out = 'Authorization: OAuth'; - - $total = array(); - foreach ($this->parameters as $k => $v) { - if (substr($k, 0, 5) != "oauth") continue; - if (is_array($v)) { - throw new OAuthException('Arrays not supported in headers'); - } - $out .= ($first) ? ' ' : ','; - $out .= OAuthUtil::urlencode_rfc3986($k) . - '="' . - OAuthUtil::urlencode_rfc3986($v) . - '"'; - $first = false; - } - return $out; - } - - public function __toString() { - return $this->to_url(); - } - - - public function sign_request($signature_method, $consumer, $token) { - $this->set_parameter( - "oauth_signature_method", - $signature_method->get_name(), - false - ); - $signature = $this->build_signature($signature_method, $consumer, $token); - $this->set_parameter("oauth_signature", $signature, false); - } - - public function build_signature($signature_method, $consumer, $token) { - $signature = $signature_method->build_signature($this, $consumer, $token); - return $signature; - } - - /** - * util function: current timestamp - */ - private static function generate_timestamp() { - return time(); - } - - /** - * util function: current nonce - */ - private static function generate_nonce() { - $mt = microtime(); - $rand = mt_rand(); - - return md5($mt . $rand); // md5s look nicer than numbers - } -} - -class OAuthServer { - protected $timestamp_threshold = 300; // in seconds, five minutes - protected $version = '1.0'; // hi blaine - protected $signature_methods = array(); - - protected $data_store; - - function __construct($data_store) { - $this->data_store = $data_store; - } - - public function add_signature_method($signature_method) { - $this->signature_methods[$signature_method->get_name()] = - $signature_method; - } - - // high level functions - - /** - * process a request_token request - * returns the request token on success - */ - public function fetch_request_token(&$request) { - $this->get_version($request); - - $consumer = $this->get_consumer($request); - - // no token required for the initial token request - $token = NULL; - - $this->check_signature($request, $consumer, $token); - - // Rev A change - $callback = $request->get_parameter('oauth_callback'); - $new_token = $this->data_store->new_request_token($consumer, $callback); - - return $new_token; - } - - /** - * process an access_token request - * returns the access token on success - */ - public function fetch_access_token(&$request) { - $this->get_version($request); - - $consumer = $this->get_consumer($request); - - // requires authorized request token - $token = $this->get_token($request, $consumer, "request"); - - $this->check_signature($request, $consumer, $token); - - // Rev A change - $verifier = $request->get_parameter('oauth_verifier'); - $new_token = $this->data_store->new_access_token($token, $consumer, $verifier); - - return $new_token; - } - - /** - * verify an api call, checks all the parameters - */ - public function verify_request(&$request) { - $this->get_version($request); - $consumer = $this->get_consumer($request); - $token = $this->get_token($request, $consumer, "access"); - $this->check_signature($request, $consumer, $token); - return array($consumer, $token); - } - - // Internals from here - /** - * version 1 - */ - private function get_version(&$request) { - $version = $request->get_parameter("oauth_version"); - if (!$version) { - // Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present. - // Chapter 7.0 ("Accessing Protected Ressources") - $version = '1.0'; - } - if ($version !== $this->version) { - throw new OAuthException("OAuth version '$version' not supported"); - } - return $version; - } - - /** - * figure out the signature with some defaults - */ - private function get_signature_method(&$request) { - $signature_method = - @$request->get_parameter("oauth_signature_method"); - - if (!$signature_method) { - // According to chapter 7 ("Accessing Protected Ressources") the signature-method - // parameter is required, and we can't just fallback to PLAINTEXT - throw new OAuthException('No signature method parameter. This parameter is required'); - } - - if (!in_array($signature_method, - array_keys($this->signature_methods))) { - throw new OAuthException( - "Signature method '$signature_method' not supported " . - "try one of the following: " . - implode(", ", array_keys($this->signature_methods)) - ); - } - return $this->signature_methods[$signature_method]; - } - - /** - * try to find the consumer for the provided request's consumer key - */ - private function get_consumer(&$request) { - $consumer_key = @$request->get_parameter("oauth_consumer_key"); - if (!$consumer_key) { - throw new OAuthException("Invalid consumer key"); - } - - $consumer = $this->data_store->lookup_consumer($consumer_key); - if (!$consumer) { - throw new OAuthException("Invalid consumer"); - } - - return $consumer; - } - - /** - * try to find the token for the provided request's token key - */ - private function get_token(&$request, $consumer, $token_type="access") { - $token_field = @$request->get_parameter('oauth_token'); - $token = $this->data_store->lookup_token( - $consumer, $token_type, $token_field - ); - if (!$token) { - throw new OAuthException("Invalid $token_type token: $token_field"); - } - return $token; - } - - /** - * all-in-one function to check the signature on a request - * should guess the signature method appropriately - */ - private function check_signature(&$request, $consumer, $token) { - // this should probably be in a different method - $timestamp = @$request->get_parameter('oauth_timestamp'); - $nonce = @$request->get_parameter('oauth_nonce'); - - $this->check_timestamp($timestamp); - $this->check_nonce($consumer, $token, $nonce, $timestamp); - - $signature_method = $this->get_signature_method($request); - - $signature = $request->get_parameter('oauth_signature'); - $valid_sig = $signature_method->check_signature( - $request, - $consumer, - $token, - $signature - ); - - if (!$valid_sig) { - throw new OAuthException("Invalid signature"); - } - } - - /** - * check that the timestamp is new enough - */ - private function check_timestamp($timestamp) { - if( ! $timestamp ) - throw new OAuthException( - 'Missing timestamp parameter. The parameter is required' - ); - - // verify that timestamp is recentish - $now = time(); - if (abs($now - $timestamp) > $this->timestamp_threshold) { - throw new OAuthException( - "Expired timestamp, yours $timestamp, ours $now" - ); - } - } - - /** - * check that the nonce is not repeated - */ - private function check_nonce($consumer, $token, $nonce, $timestamp) { - if( ! $nonce ) - throw new OAuthException( - 'Missing nonce parameter. The parameter is required' - ); - - // verify that the nonce is uniqueish - $found = $this->data_store->lookup_nonce( - $consumer, - $token, - $nonce, - $timestamp - ); - if ($found) { - throw new OAuthException("Nonce already used: $nonce"); - } - } - -} - -class OAuthDataStore { - function lookup_consumer($consumer_key) { - // implement me - } - - function lookup_token($consumer, $token_type, $token) { - // implement me - } - - function lookup_nonce($consumer, $token, $nonce, $timestamp) { - // implement me - } - - function new_request_token($consumer, $callback = null) { - // return a new token attached to this consumer - } - - function new_access_token($token, $consumer, $verifier = null) { - // return a new access token attached to this consumer - // for the user associated with this token if the request token - // is authorized - // should also invalidate the request token - } - -} - -class OAuthUtil { - public static function urlencode_rfc3986($input) { - if (is_array($input)) { - return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input); - } else if (is_scalar($input)) { - return str_replace( - '+', - ' ', - str_replace('%7E', '~', rawurlencode($input)) - ); - } else { - return ''; - } -} - - - // This decode function isn't taking into consideration the above - // modifications to the encoding process. However, this method doesn't - // seem to be used anywhere so leaving it as is. - public static function urldecode_rfc3986($string) { - return urldecode($string); - } - - // Utility function for turning the Authorization: header into - // parameters, has to do some unescaping - // Can filter out any non-oauth parameters if needed (default behaviour) - public static function split_header($header, $only_allow_oauth_parameters = true) { - $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/'; - $offset = 0; - $params = array(); - while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) { - $match = $matches[0]; - $header_name = $matches[2][0]; - $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0]; - if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) { - $params[$header_name] = OAuthUtil::urldecode_rfc3986($header_content); - } - $offset = $match[1] + strlen($match[0]); - } - - if (isset($params['realm'])) { - unset($params['realm']); - } - - return $params; - } - - // helper to try to sort out headers for people who aren't running apache - public static function get_headers() { - if (function_exists('apache_request_headers')) { - // we need this to get the actual Authorization: header - // because apache tends to tell us it doesn't exist - $headers = apache_request_headers(); - - // sanitize the output of apache_request_headers because - // we always want the keys to be Cased-Like-This and arh() - // returns the headers in the same case as they are in the - // request - $out = array(); - foreach( $headers AS $key => $value ) { - $key = str_replace( - " ", - "-", - ucwords(strtolower(str_replace("-", " ", $key))) - ); - $out[$key] = $value; - } - } else { - // otherwise we don't have apache and are just going to have to hope - // that $_SERVER actually contains what we need - $out = array(); - if( isset($_SERVER['CONTENT_TYPE']) ) - $out['Content-Type'] = $_SERVER['CONTENT_TYPE']; - if( isset($_ENV['CONTENT_TYPE']) ) - $out['Content-Type'] = $_ENV['CONTENT_TYPE']; - - foreach ($_SERVER as $key => $value) { - if (substr($key, 0, 5) == "HTTP_") { - // this is chaos, basically it is just there to capitalize the first - // letter of every word that is not an initial HTTP and strip HTTP - // code from przemek - $key = str_replace( - " ", - "-", - ucwords(strtolower(str_replace("_", " ", substr($key, 5)))) - ); - $out[$key] = $value; - } - } - } - return $out; - } - - // This function takes a input like a=b&a=c&d=e and returns the parsed - // parameters like this - // array('a' => array('b','c'), 'd' => 'e') - public static function parse_parameters( $input ) { - if (!isset($input) || !$input) return array(); - - $pairs = explode('&', $input); - - $parsed_parameters = array(); - foreach ($pairs as $pair) { - $split = explode('=', $pair, 2); - $parameter = OAuthUtil::urldecode_rfc3986($split[0]); - $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : ''; - - if (isset($parsed_parameters[$parameter])) { - // We have already recieved parameter(s) with this name, so add to the list - // of parameters with this name - - if (is_scalar($parsed_parameters[$parameter])) { - // This is the first duplicate, so transform scalar (string) into an array - // so we can add the duplicates - $parsed_parameters[$parameter] = array($parsed_parameters[$parameter]); - } - - $parsed_parameters[$parameter][] = $value; - } else { - $parsed_parameters[$parameter] = $value; - } - } - return $parsed_parameters; - } - - public static function build_http_query($params) { - if (!$params) return ''; - - // Urlencode both keys and values - $keys = OAuthUtil::urlencode_rfc3986(array_keys($params)); - $values = OAuthUtil::urlencode_rfc3986(array_values($params)); - $params = array_combine($keys, $values); - - // Parameters are sorted by name, using lexicographical byte value ordering. - // Ref: Spec: 9.1.1 (1) - uksort($params, 'strcmp'); - - $pairs = array(); - foreach ($params as $parameter => $value) { - if (is_array($value)) { - // If two or more parameters share the same name, they are sorted by their value - // Ref: Spec: 9.1.1 (1) - natsort($value); - foreach ($value as $duplicate_value) { - $pairs[] = $parameter . '=' . $duplicate_value; - } - } else { - $pairs[] = $parameter . '=' . $value; - } - } - // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61) - // Each name-value pair is separated by an '&' character (ASCII code 38) - return implode('&', $pairs); - } -} - -?> diff --git a/themes/pmem-hugo/static/include/twitter/oauth/twitteroauth.php b/themes/pmem-hugo/static/include/twitter/oauth/twitteroauth.php deleted file mode 100644 index e089552400..0000000000 --- a/themes/pmem-hugo/static/include/twitter/oauth/twitteroauth.php +++ /dev/null @@ -1,241 +0,0 @@ -http_status; } - function lastAPICall() { return $this->last_api_call; } - - /** - * construct TwitterOAuth object - */ - function __construct($consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) { - $this->sha1_method = new OAuthSignatureMethod_HMAC_SHA1(); - $this->consumer = new OAuthConsumer($consumer_key, $consumer_secret); - if (!empty($oauth_token) && !empty($oauth_token_secret)) { - $this->token = new OAuthConsumer($oauth_token, $oauth_token_secret); - } else { - $this->token = NULL; - } - } - - - /** - * Get a request_token from Twitter - * - * @returns a key/value array containing oauth_token and oauth_token_secret - */ - function getRequestToken($oauth_callback) { - $parameters = array(); - $parameters['oauth_callback'] = $oauth_callback; - $request = $this->oAuthRequest($this->requestTokenURL(), 'GET', $parameters); - $token = OAuthUtil::parse_parameters($request); - $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']); - return $token; - } - - /** - * Get the authorize URL - * - * @returns a string - */ - function getAuthorizeURL($token, $sign_in_with_twitter = TRUE) { - if (is_array($token)) { - $token = $token['oauth_token']; - } - if (empty($sign_in_with_twitter)) { - return $this->authorizeURL() . "?oauth_token={$token}"; - } else { - return $this->authenticateURL() . "?oauth_token={$token}"; - } - } - - /** - * Exchange request token and secret for an access token and - * secret, to sign API calls. - * - * @returns array("oauth_token" => "the-access-token", - * "oauth_token_secret" => "the-access-secret", - * "user_id" => "9436992", - * "screen_name" => "abraham") - */ - function getAccessToken($oauth_verifier) { - $parameters = array(); - $parameters['oauth_verifier'] = $oauth_verifier; - $request = $this->oAuthRequest($this->accessTokenURL(), 'GET', $parameters); - $token = OAuthUtil::parse_parameters($request); - $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']); - return $token; - } - - /** - * One time exchange of username and password for access token and secret. - * - * @returns array("oauth_token" => "the-access-token", - * "oauth_token_secret" => "the-access-secret", - * "user_id" => "9436992", - * "screen_name" => "abraham", - * "x_auth_expires" => "0") - */ - function getXAuthToken($username, $password) { - $parameters = array(); - $parameters['x_auth_username'] = $username; - $parameters['x_auth_password'] = $password; - $parameters['x_auth_mode'] = 'client_auth'; - $request = $this->oAuthRequest($this->accessTokenURL(), 'POST', $parameters); - $token = OAuthUtil::parse_parameters($request); - $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']); - return $token; - } - - /** - * GET wrapper for oAuthRequest. - */ - function get($url, $parameters = array()) { - $response = $this->oAuthRequest($url, 'GET', $parameters); - if ($this->format === 'json' && $this->decode_json) { - return json_decode($response); - } - return $response; - } - - /** - * POST wrapper for oAuthRequest. - */ - function post($url, $parameters = array()) { - $response = $this->oAuthRequest($url, 'POST', $parameters); - if ($this->format === 'json' && $this->decode_json) { - return json_decode($response); - } - return $response; - } - - /** - * DELETE wrapper for oAuthReqeust. - */ - function delete($url, $parameters = array()) { - $response = $this->oAuthRequest($url, 'DELETE', $parameters); - if ($this->format === 'json' && $this->decode_json) { - return json_decode($response); - } - return $response; - } - - /** - * Format and sign an OAuth / API request - */ - function oAuthRequest($url, $method, $parameters) { - if (strrpos($url, 'https://') !== 0 && strrpos($url, 'http://') !== 0) { - $url = "{$this->host}{$url}.{$this->format}"; - } - $request = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $url, $parameters); - $request->sign_request($this->sha1_method, $this->consumer, $this->token); - switch ($method) { - case 'GET': - return $this->http($request->to_url(), 'GET'); - default: - return $this->http($request->get_normalized_http_url(), $method, $request->to_postdata()); - } - } - - /** - * Make an HTTP request - * - * @return API results - */ - function http($url, $method, $postfields = NULL) { - $this->http_info = array(); - $ci = curl_init(); - /* Curl settings */ - curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent); - curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout); - curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout); - curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE); - curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:')); - curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer); - curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader')); - curl_setopt($ci, CURLOPT_HEADER, FALSE); - - switch ($method) { - case 'POST': - curl_setopt($ci, CURLOPT_POST, TRUE); - if (!empty($postfields)) { - curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields); - } - break; - case 'DELETE': - curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE'); - if (!empty($postfields)) { - $url = "{$url}?{$postfields}"; - } - } - - curl_setopt($ci, CURLOPT_URL, $url); - $response = curl_exec($ci); - $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE); - $this->http_info = array_merge($this->http_info, curl_getinfo($ci)); - $this->url = $url; - curl_close ($ci); - return $response; - } - - /** - * Get the header info to store. - */ - function getHeader($ch, $header) { - $i = strpos($header, ':'); - if (!empty($i)) { - $key = str_replace('-', '_', strtolower(substr($header, 0, $i))); - $value = trim(substr($header, $i + 2)); - $this->http_header[$key] = $value; - } - return strlen($header); - } -} diff --git a/themes/pmem-hugo/static/include/twitter/tweets.php b/themes/pmem-hugo/static/include/twitter/tweets.php deleted file mode 100644 index 82c5b8f4a3..0000000000 --- a/themes/pmem-hugo/static/include/twitter/tweets.php +++ /dev/null @@ -1,58 +0,0 @@ - $interval) ) { - - $context = stream_context_create(array( - 'http' => array( - 'timeout' => 3 - ) - )); - - $connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret); - $twitter_feed = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$username."&count=".$limit); - - $cache_rss = serialize($twitter_feed); - - if (!empty($cache_rss)) { - $cache_static = fopen($cache_file, 'wb'); - fwrite($cache_static, $cache_rss); - fclose($cache_static); - } - - $rss = @unserialize(file_get_contents($cache_file)); - } else { - $rss = @unserialize(file_get_contents($cache_file)); - } - - echo json_encode($rss); - -endif; - -?> \ No newline at end of file