Compare commits

...

104 Commits
0.5 ... master

Author SHA1 Message Date
Phil a73477c9f2 1.0.0-beta 2025-01-07 14:15:39 +01:00
Phil 625c27878f Civix Upgrade, fixes #77 2025-01-07 14:11:45 +01:00
Phil 8d1863c4eb CiviX Upgrade #77
Civix upgrade should fix install error
2025-01-06 15:33:13 +01:00
Phil 6a5cb00131 Fix Webhook error handling logic 2024-10-02 16:52:26 +02:00
Phil 9beb8136fe 1.0.0-alpha2 2024-09-05 09:22:57 +02:00
Phil e8df834277 Merge branch 'issue/74' 2024-09-05 09:21:53 +02:00
Phil d4cfd0a173 [#74] hash value now uses string instead of hex 2024-09-05 09:20:15 +02:00
Phil 4972a5dbc1 1.0.0-alpha1
Fix for #75
2024-09-04 21:45:55 +02:00
Phil 79c278170f Merge branch 'issue/75' 2024-09-04 21:43:13 +02:00
Phil 38c378cc80 [#75] Add driver to Mailer class
see 26192
2024-09-04 21:42:24 +02:00
Phil 6e455e4438 1.0.0-alpha 2024-08-21 15:12:16 +02:00
Phil 1c5ebea422 Merge branch 'dev/69' 2024-08-16 16:44:21 +02:00
Phil c902a5ff1f Merge branch 'issue/62_php8' 2024-08-16 16:39:39 +02:00
Jens Schuppe 0822bc7bee Back to dev (0.8-dev) 2024-06-18 12:15:23 +02:00
Jens Schuppe 2bb4050eab Version 0.7.0 2024-06-18 12:14:53 +02:00
Jens Schuppe acaf9e7477 Merge remote-tracking branch 'ejegg/API4' 2024-06-18 12:08:30 +02:00
Phil b4e2f7a5b9 #62 update Cache_Lite pear Library in place
via https://github.com/pear/Cache_Lite
2024-05-24 15:17:17 +02:00
Phil 7779d71711 Make parrameters configurable 2024-05-24 08:24:56 +02:00
Phil 016886a5e6 0.6.0
CiviProxy Stable Release
2024-01-24 17:50:15 +01:00
Jaap Jansma 405bb04c7c Fix for #69 2024-01-17 14:39:54 +01:00
peth-systopia 01c7e9f726
Update README.md 2024-01-09 14:24:35 +01:00
Elliott Eggleston c8cbb54651 Proxy requests to API4, support authx flows
In order to use the .htaccess rewrite rules you'll need to inlcude
the appropriate AllowOverride in your apache site config.

Introduces new configuration options $target_rest4 (URL to API4
endpoint), authx_internal_flow, and authx_external_flow
(both of which are explained in config.dist.php). Note that this
commit only supports authx flows on API4 requests.

Fixes #66
2023-11-08 10:13:07 -05:00
peth-systopia e172aa196e
Update requirements.md 2023-06-21 11:35:39 +02:00
Jo Franz 010e7d8ed6 Docs 2022-12-28 23:14:53 +01:00
Philipp Batroff fe1ee908c1 [#62] update commenting for PHP8
#[ is no longer interpreted as the start of a comment, as this syntax is now used for attributes.
2022-12-14 08:40:12 +01:00
Anna 5d41d0f460 [#62]civix upgrade 2022-11-15 15:21:34 +01:00
Björn Endres dbdaa25468
Merge pull request #60 from systopia/issue/59
#59 remove googlefonts api
2022-08-23 11:17:57 +02:00
Johannes e3ace146f8 #59 remove googlefonts api 2022-08-23 11:11:26 +02:00
B. Endres 5c1e804055 bump back to 0.6-dev 2022-05-25 12:18:24 +02:00
B. Endres 98dd7c85f1 tagged 0.6-beta5 2022-05-25 12:17:39 +02:00
Björn Endres 5eb314df89
Merge pull request #57 from systopia/issue/44
Add qid to valid parameter list for opening tracking (#44)
2022-05-25 08:51:21 +02:00
Philipp Batroff 61f25b53f2 Add qid to valid parameter list for opening tracking 2022-05-13 17:14:55 +02:00
B. Endres ecc6eebfb0 back to 0.6-dev 2022-03-24 14:39:59 +01:00
B. Endres 3d4bda9bbe tagged 0.6-beta4 2022-03-24 14:39:07 +01:00
Björn Endres 668b7ea150
Merge pull request #56 from jaapjansma/issue_55
Fix for issue #55: view in browser link is broken
2022-03-24 14:35:24 +01:00
Jaap Jansma 611e21ac04 Fix for issue #55: view in browser link is broken 2022-03-24 14:31:37 +01:00
B. Endres 555ac6a796 bump back to 0.6-dev 2021-11-19 17:02:10 +01:00
B. Endres a26ca725cf 0.6-beta3 2021-11-19 17:01:35 +01:00
Björn Endres b6176c3609
Merge pull request #54 from jaapjansma/fix_for_38
Fix for #38
2021-11-19 16:33:28 +01:00
B. Endres 4ed9d58050 [#39] added mosacio compatibility for wordpress, merged PR-39 2021-11-19 16:32:19 +01:00
Jaap Jansma cd780e50e1 Fix for #38: added url encoding to mosaico template images, so that google+.png works 2021-11-19 16:31:05 +01:00
B. Endres d8c7b3cee8 bump back to 0.6-dev 2021-11-19 16:30:46 +01:00
Jaap Jansma 199cb98991
Merge branch 'master' into fix_for_38 2021-11-19 16:29:05 +01:00
B. Endres cf02dcd0c5 Revert "Merge pull request #53 from jaapjansma/wp_compatibility"
This reverts commit afd597495e, reversing
changes made to 3e0cf56c0d.
2021-11-19 16:28:05 +01:00
Björn Endres afd597495e
Merge pull request #53 from jaapjansma/wp_compatibility
Issue #39: added mosacio compatibility for wordpress
2021-11-19 16:22:46 +01:00
Jaap Jansma 59b7544b0b Fix for #38: added url encoding to mosaico template images, so that google+.png works 2021-11-19 16:19:48 +01:00
Jaap Jansma 6828950f9c Fix for #38
Fix for #38
2021-09-30 12:01:16 +02:00
Jaap Jansma 8952b72285 Issue #39: added mosacio compatibility for wordpress 2021-09-24 14:22:05 +02:00
B. Endres 3e0cf56c0d released 0.6-beta2 2021-06-14 10:51:03 +02:00
B. Endres 9e03e018e5 [#52] updated CacheLite to v1.8.3 2021-06-14 10:45:12 +02:00
B. Endres 45950312f7 [#52] don't use PEAR error logging 2021-06-09 16:47:30 +02:00
B. Endres ba21ed8a6f updated config template 2021-06-07 20:32:19 +02:00
B. Endres 13ddf6d6f0 updated file headers 2021-06-07 12:07:31 +02:00
B. Endres be59f15252 [#52] updated CacheLite to v1.8.3 2021-06-07 11:51:15 +02:00
Björn Endres d967a3febe
Merge pull request #48 from eileenmcnaughton/master
Fix url references to preferred urls
2020-11-20 09:40:45 +01:00
eileen 9f3b3e9ed5 Fix typo 2020-11-19 13:41:28 +13:00
eileen efc483e277 Fix url references to preferred urls
The older urls are still commented in the config.dist.php file so should not
be too hard to find for someone dealing with an older site
2020-11-19 13:38:17 +13:00
Björn Endres aaa7cccc26
Merge pull request #47 from codebymikey/codebymikey-version-regex
Add ability to match pre-releases and build labels e.g. "-dev"
2020-10-12 11:49:02 +02:00
Michael S 21f2d22506
Update ProxySettings.php
#46 Add ability to match pre-releases and build labels e.g. "-dev"
2020-10-12 09:22:51 +01:00
B. Endres bbf5c3c9e9 cleaned up logging and typos 2020-09-16 09:14:32 +02:00
Björn Endres b82c633663
Merge pull request #45 from seamuslee001/seamus_master
Update autogenrated civix file to be most recent version
2020-09-08 10:35:41 +02:00
Seamus Lee 76b5d8f49a Update autogenrated civix file to be most recent version 2020-09-08 18:07:47 +10:00
B. Endres c8c5694b52 [#44] alignment for readability 2020-09-07 09:36:17 +02:00
B. Endres 0ae1acb426 [#44] merged CiviCRM's new routes by @seamuslee001 2020-09-07 09:34:18 +02:00
B. Endres 1f46d5e5da [#44] added warning for CiviCRM < 5.27 2020-09-07 09:32:57 +02:00
Björn Endres 911f9ec3d3
Merge pull request #43 from seamuslee001/normal_routing
Add in normal url routes for tracked opens and tracking urls to the m…
2020-09-07 09:28:15 +02:00
Seamus Lee a88b621758 Add in normal url routes for tracked opens and tracking urls to the mend urls function and also make use of the normal routes when quering the target civi 2020-09-04 16:41:31 +10:00
Björn Endres 999345f4b5
Merge pull request #41 from MikeyMJCO/patch-1
MkDocs upgrade fix.
2020-04-14 12:46:04 +02:00
Mikey O'Toole d5062f8345
Update mkdocs.yml 2020-04-13 16:07:45 +01:00
Mikey O'Toole 9600bdd11c
MkDocs upgrade fix. 2020-04-13 12:21:41 +01:00
B. Endres e8fc1b1b0d bump back to 0.6-dev 2020-03-17 07:52:14 +01:00
Philipp Batroff c941a1248e Added logging to successful webhook handling 2019-11-27 17:11:00 +01:00
B. Endres 42c95f62c7 0.6-beta1 2019-11-26 16:20:14 +01:00
B. Endres 6478762b74 [#38] merged mosaico relative url fix (dev_38) 2019-11-26 16:09:41 +01:00
B. Endres 8aeaa3120b [#32] merged webhook2api (dev_32) 2019-11-26 16:08:11 +01:00
Philipp Batroff 20140a0d41 [#38] Fix relative file paths for view in browser 2019-11-25 17:48:32 +01:00
Björn Endres 5763a2b792
Merge pull request #36 from d1ss0nanz/master
simplify email regex; allow + in user part
2019-09-26 15:12:52 +02:00
Daniel Stutz 1bb61efd32 simplify email regex; allow + in user part 2019-09-25 17:39:26 +02:00
Björn Endres ccb0c41377
Merge pull request #28 from pbatroff/dev_27
Fix for #27: Correct link generation. Needs a bit more testing
2019-09-24 14:14:18 +02:00
Björn Endres d4853095ce
Merge branch 'master' into dev_27 2019-09-24 14:14:09 +02:00
Björn Endres 9b4c5f8f99
Merge pull request #34 from jaapjansma/issue_33
Issue #33 case insesntive entity and action specification
2019-09-03 07:28:44 +02:00
Jaap Jansma cad78b5496 Issue #33 case insesntive entity and action specification 2019-08-30 14:38:48 +02:00
Philipp Batroff 917af8650d Changed http return code to 200 if the command was parsed successfully, but a civiCRM error occured. In that case we shouldn't return an error code, because it's an internal error 2019-07-18 12:18:38 +02:00
Philipp Batroff f83fc0c77e udpate parsing of response codes from civicrm api 2019-07-18 11:34:18 +02:00
Philipp Batroff 1ffa67865d implementing webhook2api, amendment for json array parameter parsing. WiP - debuggin output for error_log 2019-07-17 14:15:52 +02:00
B. Endres f044515feb [#32] improved documentation 2019-01-04 17:41:45 +01:00
B. Endres 2207a95c2b [#32] implementing webhook2api 2019-01-04 17:28:52 +01:00
B. Endres d87d5a6c24 [#32] implementing webhook2api 2019-01-04 16:22:43 +01:00
B. Endres 3eae978200 Merge remote-tracking branch 'Michael/config-dist' 2019-01-04 10:45:44 +01:00
B. Endres aef6fbeaa2 bump master back to 0.6-dev 2019-01-04 10:06:15 +01:00
B. Endres bf53d03b3b [#31] added remark about clean URLs 2018-11-26 09:02:22 +01:00
B. Endres abb46397d3 [#30] added php-curl requirement 2018-11-26 07:24:38 +01:00
Philipp Batroff 47f6f1b4b8 Fix for #27: Correct link generation. Needs a bit more testing 2018-07-02 11:50:44 +02:00
SYSTOPIA 5894bce133
Merge pull request #24 from michaelmcandrew/docker
adding Dockerfile
2018-03-12 13:16:09 +01:00
Michael McAndrew 8f1aba57e7 Merge branch 'master' of https://github.com/systopia/CiviProxy into config-dist 2018-03-12 09:02:29 +00:00
Michael McAndrew 8116bdd128 Merge branch 'master' of https://github.com/systopia/CiviProxy into docker 2018-03-12 09:02:19 +00:00
Michael McAndrew 3f0a766241 adding Dockerfile 2018-03-09 17:27:26 +00:00
Michael McAndrew 1b1d5e8bd4 a hint on installation in the config.dist.php file 2018-03-09 17:25:16 +00:00
Michael McAndrew aaa5330591 distribute a config.dist.php file 2018-03-09 17:24:13 +00:00
systopia d846c1d9ff implemented #22 2018-03-01 11:12:11 +01:00
systopia 1e280e1f0e Merge remote-tracking branch 'origin/dev_20' 2018-03-01 11:09:58 +01:00
systopia a23f0cfb05 implementing #20 2018-03-01 11:08:44 +01:00
systopia 2346076e72 implementing #20 2018-03-01 10:15:59 +01:00
systopia 9f1caed052 implementing #20 2018-02-28 17:06:02 +01:00
42 changed files with 1708 additions and 654 deletions

1
.gitignore vendored
View File

@ -1,4 +1,5 @@
secrets.php secrets.php
proxy/file_cache proxy/file_cache
proxy/config.php
debug.log debug.log
.idea .idea

8
Dockerfile Normal file
View File

@ -0,0 +1,8 @@
# You may find this Dockerfile useful in development or production
# From the CiviProxy directory
# * Build a docker image with `docker build . -t civiproxy`
# * Run a development container with `run -d -p 4050:80 -v $PWD/proxy:/var/www/html --name civiproxy civiproxy`
FROM php:7-apache
COPY proxy/ /var/www/html

View File

@ -1 +1,8 @@
Documentation on CiviProxy can be found here: https://docs.civicrm.org/civiproxy/en/latest/ ## About
CiviProxy is a tool to set up a security proxy server specifically for your CiviCRM instance. It uses whitelisting and parameter sanitation to allow only legitimate requests to pass through.
## Documentation
The documentation on CiviProxy can be found here: https://docs.civicrm.org/civiproxy/en/latest/
## We need your support
This software is provided as Free and Open Source Software, and we are happy if you find it useful. However, we have put a lot of work into it (and continue to do so), much of it unpaid for. So if you benefit from our software, please consider making a financial contribution so we can continue to maintain and develop it further.
If you are willing to support us in developing this tool, please send an email to info@systopia.de to get an invoice or agree a different payment method. Thank you!

View File

@ -1,7 +1,7 @@
<?php <?php
/*-------------------------------------------------------+ /*-------------------------------------------------------+
| CiviProxy | | CiviProxy |
| Copyright (C) 2015 SYSTOPIA | | Copyright (C) 2015-2021 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) | | Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ | | http://www.systopia.de/ |
+--------------------------------------------------------+ +--------------------------------------------------------+
@ -105,9 +105,9 @@ class CRM_Admin_Form_Setting_ProxySettings extends CRM_Admin_Form_Setting
if($response === FALSE) { if($response === FALSE) {
return array('is_error' => 1, 'message' => sprintf(ts('Error: cannot access "%s"'), $url)); return array('is_error' => 1, 'message' => sprintf(ts('Error: cannot access "%s"'), $url));
}else{ }else{
$result = preg_match("/<p id=\"version\">CiviProxy Version ([0-9]+\.[0-9]+|[0-9]+\.[0-9]+\.[0-9]+)<\/p>/", $response, $output_array); $result = preg_match("/<p id=\"version\">CiviProxy Version (([0-9]+\.[0-9]+|[0-9]+\.[0-9]+\.[0-9]+)(?:-[0-9A-Za-z-]+)?)<\/p>/", $response, $output_array);
if ($result === FALSE || $result === 0){ if ($result === FALSE || $result === 0){
return array('is_error' => 1, 'message' => sprintf(ts('Error: failed to parse version information'), $url)); return array('is_error' => 1, 'message' => sprintf(ts('Error: failed to parse version information: (%s)'), $url));
}else{ }else{
return array('is_error' => 0, 'version' => $output_array[1]); return array('is_error' => 0, 'version' => $output_array[1]);
} }

View File

@ -1,7 +1,7 @@
<?php <?php
/*-------------------------------------------------------+ /*-------------------------------------------------------+
| CiviProxy | | CiviProxy |
| Copyright (C) 2015 SYSTOPIA | | Copyright (C) 2015-2021 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) | | Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ | | http://www.systopia.de/ |
+--------------------------------------------------------+ +--------------------------------------------------------+
@ -17,12 +17,23 @@ class CRM_Civiproxy_Mailer {
* this is the orginal, wrapped mailer * this is the orginal, wrapped mailer
*/ */
protected $mailer = NULL; protected $mailer = NULL;
/**
* @var Mail Driver
*/
protected $driver = NULL;
/**
* @var array Mail Params, currently not used
*/
protected $params = [];
/** /**
* construct this mailer wrapping another one * construct this mailer wrapping another one
*/ */
public function __construct($mailer) { public function __construct($mailer, $driver, $params) {
$this->mailer = $mailer; $this->mailer = $mailer;
$this->driver = $driver;
$this->params = $params;
} }
/** /**
@ -47,16 +58,26 @@ class CRM_Civiproxy_Mailer {
$enabled = CRM_Core_BAO_Setting::getItem('CiviProxy Settings', 'proxy_enabled'); $enabled = CRM_Core_BAO_Setting::getItem('CiviProxy Settings', 'proxy_enabled');
if (!$enabled) return; if (!$enabled) return;
$mosaico = CRM_Civiproxy_Mosaico::singleton();
// get the URLs // get the URLs
$config = CRM_Core_Config::singleton(); $config = CRM_Core_Config::singleton();
$system_base = $config->userFrameworkBaseURL; $system_base = $config->userFrameworkBaseURL;
$proxy_base = CRM_Core_BAO_Setting::getItem('CiviProxy Settings', 'proxy_url'); $proxy_base = CRM_Core_BAO_Setting::getItem('CiviProxy Settings', 'proxy_url');
// General external functions // General external functions
$value = preg_replace("#{$system_base}civicrm/mailing/url#i", $proxy_base.'/url.php', $value);
$value = preg_replace("#{$system_base}sites/all/modules/civicrm/extern/url.php#i", $proxy_base.'/url.php', $value); $value = preg_replace("#{$system_base}sites/all/modules/civicrm/extern/url.php#i", $proxy_base.'/url.php', $value);
$value = preg_replace("#{$system_base}civicrm/mailing/open#i", $proxy_base.'/open.php', $value);
$value = preg_replace("#{$system_base}sites/all/modules/civicrm/extern/open.php#i", $proxy_base.'/open.php', $value); $value = preg_replace("#{$system_base}sites/all/modules/civicrm/extern/open.php#i", $proxy_base.'/open.php', $value);
$value = preg_replace("#{$system_base}sites/default/files/civicrm/persist/#i", $proxy_base.'/file.php?id=', $value); $value = preg_replace("#{$system_base}sites/default/files/civicrm/persist/#i", $proxy_base.'/file.php?id=', $value);
$value = preg_replace("#{$system_base}civicrm/mosaico/img\?src=#i", $proxy_base.'/mosaico.php?id=', $value); $value = preg_replace("#{$system_base}civicrm/mosaico/img\?src=#i", $proxy_base.'/mosaico.php?id=', $value);
$value = preg_replace("#{$system_base}civicrm/mosaico/img/\?src=#i", $proxy_base.'/mosaico.php?id=', $value);
if ($mosaico->isMosaicoInstalled()) {
$value = preg_replace_callback("#({$mosaico->getMosaicoExtensionUrl()}/packages/mosaico/templates/)(\S*)([\"'])#i", function($matches) use ($proxy_base) {
return $proxy_base . '/mosaico.php?template_url=' . urlencode($matches[2]) . $matches[3];
}, $value);
}
// Mailing related functions // Mailing related functions
$value = preg_replace("#{$system_base}civicrm/mailing/view#i", $proxy_base.'/mailing/mail.php', $value); $value = preg_replace("#{$system_base}civicrm/mailing/view#i", $proxy_base.'/mailing/mail.php', $value);
@ -71,4 +92,11 @@ class CRM_Civiproxy_Mailer {
$value = preg_replace("#{$system_base}civicrm/mailing/{$function}#i", $new_url, $value); $value = preg_replace("#{$system_base}civicrm/mailing/{$function}#i", $new_url, $value);
} }
} }
/**
* @return Mail|null
*/
public function getDriver() {
return $this->driver;
}
} }

View File

@ -0,0 +1,70 @@
<?php
/**
* Copyright (C) 2021 Jaap Jansma (jaap.jansma@civicoop.org)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
class CRM_Civiproxy_Mosaico {
/**
* @var CRM_Civiproxy_Mosaico
*/
private static $singleton;
/**
* @var String
*/
private $mosiacoExtenionUrl;
/**
* @var bool
*/
private $isMosaicoInstalled = false;
private function __construct() {
try {
$mosaicoExt = civicrm_api3('Extension', 'getsingle', ['full_name' => "uk.co.vedaconsulting.mosaico"]);
$this->isMosaicoInstalled = true;
$this->mosiacoExtenionUrl = CRM_Mosaico_ExtensionUtil::url();
} catch (\Exception $ex) {
// Do nothing
}
}
/**
* @return CRM_Civiproxy_Mosaico
*/
public static function singleton() {
if (!self::$singleton) {
self::$singleton = new CRM_Civiproxy_Mosaico();
}
return self::$singleton;
}
/**
* @return bool
*/
public function isMosaicoInstalled() {
return $this->isMosaicoInstalled;
}
/**
* @return string
*/
public function getMosaicoExtensionUrl() {
return $this->mosiacoExtenionUrl;
}
}

View File

@ -3,240 +3,199 @@
// AUTO-GENERATED FILE -- Civix may overwrite any changes made to this file // AUTO-GENERATED FILE -- Civix may overwrite any changes made to this file
/** /**
* (Delegated) Implementation of hook_civicrm_config * The ExtensionUtil class provides small stubs for accessing resources of this
* extension.
*/ */
function _civiproxy_civix_civicrm_config(&$config = NULL) { class CRM_Civiproxy_ExtensionUtil {
const SHORT_NAME = 'civiproxy';
const LONG_NAME = 'de.systopia.civiproxy';
const CLASS_PREFIX = 'CRM_Civiproxy';
/**
* Translate a string using the extension's domain.
*
* If the extension doesn't have a specific translation
* for the string, fallback to the default translations.
*
* @param string $text
* Canonical message text (generally en_US).
* @param array $params
* @return string
* Translated text.
* @see ts
*/
public static function ts($text, $params = []): string {
if (!array_key_exists('domain', $params)) {
$params['domain'] = [self::LONG_NAME, NULL];
}
return ts($text, $params);
}
/**
* Get the URL of a resource file (in this extension).
*
* @param string|NULL $file
* Ex: NULL.
* Ex: 'css/foo.css'.
* @return string
* Ex: 'http://example.org/sites/default/ext/org.example.foo'.
* Ex: 'http://example.org/sites/default/ext/org.example.foo/css/foo.css'.
*/
public static function url($file = NULL): string {
if ($file === NULL) {
return rtrim(CRM_Core_Resources::singleton()->getUrl(self::LONG_NAME), '/');
}
return CRM_Core_Resources::singleton()->getUrl(self::LONG_NAME, $file);
}
/**
* Get the path of a resource file (in this extension).
*
* @param string|NULL $file
* Ex: NULL.
* Ex: 'css/foo.css'.
* @return string
* Ex: '/var/www/example.org/sites/default/ext/org.example.foo'.
* Ex: '/var/www/example.org/sites/default/ext/org.example.foo/css/foo.css'.
*/
public static function path($file = NULL) {
// return CRM_Core_Resources::singleton()->getPath(self::LONG_NAME, $file);
return __DIR__ . ($file === NULL ? '' : (DIRECTORY_SEPARATOR . $file));
}
/**
* Get the name of a class within this extension.
*
* @param string $suffix
* Ex: 'Page_HelloWorld' or 'Page\\HelloWorld'.
* @return string
* Ex: 'CRM_Foo_Page_HelloWorld'.
*/
public static function findClass($suffix) {
return self::CLASS_PREFIX . '_' . str_replace('\\', '_', $suffix);
}
}
use CRM_Civiproxy_ExtensionUtil as E;
/**
* (Delegated) Implements hook_civicrm_config().
*
* @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_config
*/
function _civiproxy_civix_civicrm_config($config = NULL) {
static $configured = FALSE; static $configured = FALSE;
if ($configured) return; if ($configured) {
return;
}
$configured = TRUE; $configured = TRUE;
$template =& CRM_Core_Smarty::singleton(); $extRoot = __DIR__ . DIRECTORY_SEPARATOR;
$include_path = $extRoot . PATH_SEPARATOR . get_include_path();
$extRoot = dirname( __FILE__ ) . DIRECTORY_SEPARATOR; set_include_path($include_path);
$extDir = $extRoot . 'templates'; // Based on <compatibility>, this does not currently require mixin/polyfill.php.
if ( is_array( $template->template_dir ) ) {
array_unshift( $template->template_dir, $extDir );
} else {
$template->template_dir = array( $extDir, $template->template_dir );
}
$include_path = $extRoot . PATH_SEPARATOR . get_include_path( );
set_include_path( $include_path );
} }
/** /**
* (Delegated) Implementation of hook_civicrm_xmlMenu * Implements hook_civicrm_install().
* *
* @param $files array(string) * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_install
*/
function _civiproxy_civix_civicrm_xmlMenu(&$files) {
foreach (_civiproxy_civix_glob(__DIR__ . '/xml/Menu/*.xml') as $file) {
$files[] = $file;
}
}
/**
* Implementation of hook_civicrm_install
*/ */
function _civiproxy_civix_civicrm_install() { function _civiproxy_civix_civicrm_install() {
_civiproxy_civix_civicrm_config(); _civiproxy_civix_civicrm_config();
if ($upgrader = _civiproxy_civix_upgrader()) { // Based on <compatibility>, this does not currently require mixin/polyfill.php.
return $upgrader->onInstall();
}
} }
/** /**
* Implementation of hook_civicrm_uninstall * (Delegated) Implements hook_civicrm_enable().
*
* @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_enable
*/ */
function _civiproxy_civix_civicrm_uninstall() { function _civiproxy_civix_civicrm_enable(): void {
_civiproxy_civix_civicrm_config(); _civiproxy_civix_civicrm_config();
if ($upgrader = _civiproxy_civix_upgrader()) { // Based on <compatibility>, this does not currently require mixin/polyfill.php.
return $upgrader->onUninstall();
}
} }
/** /**
* (Delegated) Implementation of hook_civicrm_enable * Inserts a navigation menu item at a given place in the hierarchy.
*
* @param array $menu - menu hierarchy
* @param string $path - path to parent of this item, e.g. 'my_extension/submenu'
* 'Mailing', or 'Administer/System Settings'
* @param array $item - the item to insert (parent/child attributes will be
* filled for you)
*
* @return bool
*/ */
function _civiproxy_civix_civicrm_enable() { function _civiproxy_civix_insert_navigation_menu(&$menu, $path, $item) {
_civiproxy_civix_civicrm_config();
if ($upgrader = _civiproxy_civix_upgrader()) {
if (is_callable(array($upgrader, 'onEnable'))) {
return $upgrader->onEnable();
}
}
}
/**
* (Delegated) Implementation of hook_civicrm_disable
*/
function _civiproxy_civix_civicrm_disable() {
_civiproxy_civix_civicrm_config();
if ($upgrader = _civiproxy_civix_upgrader()) {
if (is_callable(array($upgrader, 'onDisable'))) {
return $upgrader->onDisable();
}
}
}
/**
* (Delegated) Implementation of hook_civicrm_upgrade
*
* @param $op string, the type of operation being performed; 'check' or 'enqueue'
* @param $queue CRM_Queue_Queue, (for 'enqueue') the modifiable list of pending up upgrade tasks
*
* @return mixed based on op. for 'check', returns array(boolean) (TRUE if upgrades are pending)
* for 'enqueue', returns void
*/
function _civiproxy_civix_civicrm_upgrade($op, CRM_Queue_Queue $queue = NULL) {
if ($upgrader = _civiproxy_civix_upgrader()) {
return $upgrader->onUpgrade($op, $queue);
}
}
function _civiproxy_civix_upgrader() {
if (!file_exists(__DIR__.'/CRM/Civiproxy/Upgrader.php')) {
return NULL;
} else {
return CRM_Civiproxy_Upgrader_Base::instance();
}
}
/**
* Search directory tree for files which match a glob pattern
*
* Note: Dot-directories (like "..", ".git", or ".svn") will be ignored.
* Note: In Civi 4.3+, delegate to CRM_Utils_File::findFiles()
*
* @param $dir string, base dir
* @param $pattern string, glob pattern, eg "*.txt"
* @return array(string)
*/
function _civiproxy_civix_find_files($dir, $pattern) {
if (is_callable(array('CRM_Utils_File', 'findFiles'))) {
return CRM_Utils_File::findFiles($dir, $pattern);
}
$todos = array($dir);
$result = array();
while (!empty($todos)) {
$subdir = array_shift($todos);
foreach (_civiproxy_civix_glob("$subdir/$pattern") as $match) {
if (!is_dir($match)) {
$result[] = $match;
}
}
if ($dh = opendir($subdir)) {
while (FALSE !== ($entry = readdir($dh))) {
$path = $subdir . DIRECTORY_SEPARATOR . $entry;
if ($entry{0} == '.') {
} elseif (is_dir($path)) {
$todos[] = $path;
}
}
closedir($dh);
}
}
return $result;
}
/**
* (Delegated) Implementation of hook_civicrm_managed
*
* Find any *.mgd.php files, merge their content, and return.
*/
function _civiproxy_civix_civicrm_managed(&$entities) {
$mgdFiles = _civiproxy_civix_find_files(__DIR__, '*.mgd.php');
foreach ($mgdFiles as $file) {
$es = include $file;
foreach ($es as $e) {
if (empty($e['module'])) {
$e['module'] = 'de.systopia.civiproxy';
}
$entities[] = $e;
}
}
}
/**
* (Delegated) Implementation of hook_civicrm_caseTypes
*
* Find any and return any files matching "xml/case/*.xml"
*
* Note: This hook only runs in CiviCRM 4.4+.
*/
function _civiproxy_civix_civicrm_caseTypes(&$caseTypes) {
if (!is_dir(__DIR__ . '/xml/case')) {
return;
}
foreach (_civiproxy_civix_glob(__DIR__ . '/xml/case/*.xml') as $file) {
$name = preg_replace('/\.xml$/', '', basename($file));
if ($name != CRM_Case_XMLProcessor::mungeCaseType($name)) {
$errorMessage = sprintf("Case-type file name is malformed (%s vs %s)", $name, CRM_Case_XMLProcessor::mungeCaseType($name));
CRM_Core_Error::fatal($errorMessage);
// throw new CRM_Core_Exception($errorMessage);
}
$caseTypes[$name] = array(
'module' => 'de.systopia.civiproxy',
'name' => $name,
'file' => $file,
);
}
}
/**
* Glob wrapper which is guaranteed to return an array.
*
* The documentation for glob() says, "On some systems it is impossible to
* distinguish between empty match and an error." Anecdotally, the return
* result for an empty match is sometimes array() and sometimes FALSE.
* This wrapper provides consistency.
*
* @see http://php.net/glob
* @param string $pattern
* @return array, possibly empty
*/
function _civiproxy_civix_glob($pattern) {
$result = glob($pattern);
return is_array($result) ? $result : array();
}
/**
* Inserts a navigation menu item at a given place in the hierarchy
*
* $menu - menu hierarchy
* $path - path where insertion should happen (ie. Administer/System Settings)
* $item - menu you need to insert (parent/child attributes will be filled for you)
* $parentId - used internally to recurse in the menu structure
*/
function _civiproxy_civix_insert_navigation_menu(&$menu, $path, $item, $parentId = NULL) {
static $navId;
// If we are done going down the path, insert menu // If we are done going down the path, insert menu
if (empty($path)) { if (empty($path)) {
if (!$navId) $navId = CRM_Core_DAO::singleValueQuery("SELECT max(id) FROM civicrm_navigation"); $menu[] = [
$navId ++; 'attributes' => array_merge([
$menu[$navId] = array ( 'label' => $item['name'] ?? NULL,
'attributes' => array_merge($item, array( 'active' => 1,
'label' => CRM_Utils_Array::value('name', $item), ], $item),
'active' => 1, ];
'parentID' => $parentId, return TRUE;
'navID' => $navId, }
)) else {
);
return true;
} else {
// Find an recurse into the next level down // Find an recurse into the next level down
$found = false; $found = FALSE;
$path = explode('/', $path); $path = explode('/', $path);
$first = array_shift($path); $first = array_shift($path);
foreach ($menu as $key => &$entry) { foreach ($menu as $key => &$entry) {
if ($entry['attributes']['name'] == $first) { if ($entry['attributes']['name'] == $first) {
if (!$entry['child']) $entry['child'] = array(); if (!isset($entry['child'])) {
$found = _civiproxy_civix_insert_navigation_menu($entry['child'], implode('/', $path), $item, $key); $entry['child'] = [];
}
$found = _civiproxy_civix_insert_navigation_menu($entry['child'], implode('/', $path), $item);
} }
} }
return $found; return $found;
} }
} }
/**
* (Delegated) Implements hook_civicrm_navigationMenu().
*/
function _civiproxy_civix_navigationMenu(&$nodes) {
if (!is_callable(['CRM_Core_BAO_Navigation', 'fixNavigationMenu'])) {
_civiproxy_civix_fixNavigationMenu($nodes);
}
}
/**
* Given a navigation menu, generate navIDs for any items which are
* missing them.
*/
function _civiproxy_civix_fixNavigationMenu(&$nodes) {
$maxNavID = 1;
array_walk_recursive($nodes, function($item, $key) use (&$maxNavID) {
if ($key === 'navID') {
$maxNavID = max($maxNavID, $item);
}
});
_civiproxy_civix_fixNavigationMenuItems($nodes, $maxNavID, NULL);
}
function _civiproxy_civix_fixNavigationMenuItems(&$nodes, &$maxNavID, $parentID) {
$origKeys = array_keys($nodes);
foreach ($origKeys as $origKey) {
if (!isset($nodes[$origKey]['attributes']['parentID']) && $parentID !== NULL) {
$nodes[$origKey]['attributes']['parentID'] = $parentID;
}
// If no navID, then assign navID and fix key.
if (!isset($nodes[$origKey]['attributes']['navID'])) {
$newKey = ++$maxNavID;
$nodes[$origKey]['attributes']['navID'] = $newKey;
$nodes[$newKey] = $nodes[$origKey];
unset($nodes[$origKey]);
$origKey = $newKey;
}
if (isset($nodes[$origKey]['child']) && is_array($nodes[$origKey]['child'])) {
_civiproxy_civix_fixNavigationMenuItems($nodes[$origKey]['child'], $maxNavID, $nodes[$origKey]['attributes']['navID']);
}
}
}

View File

@ -1,7 +1,7 @@
<?php <?php
/*-------------------------------------------------------+ /*-------------------------------------------------------+
| CiviProxy | | CiviProxy |
| Copyright (C) 2015 SYSTOPIA | | Copyright (C) 2015-2021 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) | | Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ | | http://www.systopia.de/ |
+--------------------------------------------------------+ +--------------------------------------------------------+
@ -15,7 +15,7 @@ require_once 'civiproxy.civix.php';
* so we can mend all the URLs in outgoing emails * so we can mend all the URLs in outgoing emails
*/ */
function civiproxy_civicrm_alterMailer(&$mailer, $driver, $params) { function civiproxy_civicrm_alterMailer(&$mailer, $driver, $params) {
$mailer = new CRM_Civiproxy_Mailer($mailer); $mailer = new CRM_Civiproxy_Mailer($mailer, $driver, $params);
} }
/** /**
@ -25,15 +25,6 @@ function civiproxy_civicrm_config(&$config) {
_civiproxy_civix_civicrm_config($config); _civiproxy_civix_civicrm_config($config);
} }
/**
* Implementation of hook_civicrm_xmlMenu
*
* @param $files array(string)
*/
function civiproxy_civicrm_xmlMenu(&$files) {
_civiproxy_civix_civicrm_xmlMenu($files);
}
/** /**
* Implementation of hook_civicrm_install * Implementation of hook_civicrm_install
*/ */
@ -41,13 +32,6 @@ function civiproxy_civicrm_install() {
return _civiproxy_civix_civicrm_install(); return _civiproxy_civix_civicrm_install();
} }
/**
* Implementation of hook_civicrm_uninstall
*/
function civiproxy_civicrm_uninstall() {
return _civiproxy_civix_civicrm_uninstall();
}
/** /**
* Implementation of hook_civicrm_enable * Implementation of hook_civicrm_enable
*/ */
@ -55,61 +39,9 @@ function civiproxy_civicrm_enable() {
return _civiproxy_civix_civicrm_enable(); return _civiproxy_civix_civicrm_enable();
} }
/**
* Implementation of hook_civicrm_disable
*/
function civiproxy_civicrm_disable() {
return _civiproxy_civix_civicrm_disable();
}
/**
* Implementation of hook_civicrm_upgrade
*
* @param $op string, the type of operation being performed; 'check' or 'enqueue'
* @param $queue CRM_Queue_Queue, (for 'enqueue') the modifiable list of pending up upgrade tasks
*
* @return mixed based on op. for 'check', returns array(boolean) (TRUE if upgrades are pending)
* for 'enqueue', returns void
*/
function civiproxy_civicrm_upgrade($op, CRM_Queue_Queue $queue = NULL) {
return _civiproxy_civix_civicrm_upgrade($op, $queue);
}
/**
* Implementation of hook_civicrm_managed
*
* Generate a list of entities to create/deactivate/delete when this module
* is installed, disabled, uninstalled.
*/
function civiproxy_civicrm_managed(&$entities) {
return _civiproxy_civix_civicrm_managed($entities);
}
/**
* Implementation of hook_civicrm_caseTypes
*
* Generate a list of case-types
*
* Note: This hook only runs in CiviCRM 4.4+.
*/
function civiproxy_civicrm_caseTypes(&$caseTypes) {
_civiproxy_civix_civicrm_caseTypes($caseTypes);
}
/** /**
* Implementation of hook_civicrm_alterSettingsFolders * Implementation of hook_civicrm_alterSettingsFolders
* *
* Scan for settings in custom folder and import them * Scan for settings in custom folder and import them
* *
*/ */
function civiproxy_civicrm_alterSettingsFolders(&$metaDataFolders = NULL){
static $configured = FALSE;
if ($configured) return;
$configured = TRUE;
$extRoot = dirname( __FILE__ ) . DIRECTORY_SEPARATOR;
$extDir = $extRoot . 'settings';
if(!in_array($extDir, $metaDataFolders)){
$metaDataFolders[] = $extDir;
}
}

View File

@ -3,21 +3,36 @@
<file>civiproxy</file> <file>civiproxy</file>
<name>CiviProxy</name> <name>CiviProxy</name>
<description>This will enable CiviProxy support for mailings</description> <description>This will enable CiviProxy support for mailings</description>
<license></license> <license>AGPL</license>
<maintainer> <maintainer>
<author>B. Endres</author> <author>B. Endres</author>
<email>endres@systopia.de</email> <email>endres@systopia.de</email>
</maintainer> </maintainer>
<releaseDate>2018-03-01</releaseDate> <urls>
<version>0.5</version> <url desc="Main Extension Page">https://github.com/systopia/CiviProxy</url>
<develStage>stable</develStage> <url desc="Documentation">https://docs.civicrm.org/civiproxy/en/latest/</url>
<url desc="Support">https://github.com/systopia/CiviProxy/issues</url>
<url desc="Licensing">http://www.gnu.org/licenses/agpl-3.0.html</url>
</urls>
<releaseDate>2024-01-07</releaseDate>
<version>1.0.0-beta</version>
<develStage>beta</develStage>
<compatibility> <compatibility>
<ver>4.4</ver> <ver>5.45</ver>
<ver>4.6</ver>
<ver>4.7</ver>
</compatibility> </compatibility>
<comments>This is an addition to SYSTOPIA's CiviProxy security system</comments> <comments>This is the companion extension to SYSTOPIA's CiviProxy security system</comments>
<civix> <civix>
<namespace>CRM/Civiproxy</namespace> <namespace>CRM/Civiproxy</namespace>
<format>24.09.1</format>
</civix> </civix>
<mixins>
<mixin>menu-xml@1.0.0</mixin>
<mixin>setting-php@1.0.0</mixin>
<mixin>smarty-v2@1.0.3</mixin>
<mixin>entity-types-php@2.0.0</mixin>
</mixins>
<classloader>
<psr0 prefix="CRM_" path="."/>
<psr4 prefix="Civi\" path="Civi"/>
</classloader>
</extension> </extension>

View File

@ -0,0 +1,40 @@
<?php
/**
* Auto-register entity declarations from `schema/*.entityType.php`.
*
* @mixinName entity-types-php
* @mixinVersion 2.0.0
* @since 5.73
*
* Changelog:
* - v2.0 scans /schema directory instead of /xml/schema/*
* - v2.0 supports only one entity per file
* - v2.0 adds 'module' key to each entity
*
* @param CRM_Extension_MixInfo $mixInfo
* On newer deployments, this will be an instance of MixInfo. On older deployments, Civix may polyfill with a work-a-like.
* @param \CRM_Extension_BootCache $bootCache
* On newer deployments, this will be an instance of BootCache. On older deployments, Civix may polyfill with a work-a-like.
*/
return function ($mixInfo, $bootCache) {
/**
* @param \Civi\Core\Event\GenericHookEvent $e
* @see CRM_Utils_Hook::entityTypes()
*/
Civi::dispatcher()->addListener('hook_civicrm_entityTypes', function ($e) use ($mixInfo) {
// When deactivating on a polyfill/pre-mixin system, listeners may not cleanup automatically.
if (!$mixInfo->isActive() || !is_dir($mixInfo->getPath('schema'))) {
return;
}
$files = (array) glob($mixInfo->getPath('schema/*.entityType.php'));
foreach ($files as $file) {
$entity = include $file;
$entity['module'] = $mixInfo->longName;
$e->entityTypes[$entity['name']] = $entity;
}
});
};

View File

@ -0,0 +1,78 @@
<?php
/**
* Auto-register "templates/" folder.
*
* @mixinName smarty-v2
* @mixinVersion 1.0.3
* @since 5.59
*
* @deprecated - it turns out that the mixin is not version specific so the 'smarty'
* mixin is preferred over smarty-v2 (they are the same but not having the version
* in the name is less misleading.)
*
* @param CRM_Extension_MixInfo $mixInfo
* On newer deployments, this will be an instance of MixInfo. On older deployments, Civix may polyfill with a work-a-like.
* @param \CRM_Extension_BootCache $bootCache
* On newer deployments, this will be an instance of MixInfo. On older deployments, Civix may polyfill with a work-a-like.
*/
return function ($mixInfo, $bootCache) {
$dir = $mixInfo->getPath('templates');
if (!file_exists($dir)) {
return;
}
$register = function($newDirs) {
$smarty = CRM_Core_Smarty::singleton();
$v2 = isset($smarty->_version) && version_compare($smarty->_version, 3, '<');
$templateDirs = (array) ($v2 ? $smarty->template_dir : $smarty->getTemplateDir());
$templateDirs = array_merge($newDirs, $templateDirs);
$templateDirs = array_unique(array_map(function($v) {
$v = str_replace(DIRECTORY_SEPARATOR, '/', $v);
$v = rtrim($v, '/') . '/';
return $v;
}, $templateDirs));
if ($v2) {
$smarty->template_dir = $templateDirs;
}
else {
$smarty->setTemplateDir($templateDirs);
}
};
// Let's figure out what environment we're in -- so that we know the best way to call $register().
if (!empty($GLOBALS['_CIVIX_MIXIN_POLYFILL'])) {
// Polyfill Loader (v<=5.45): We're already in the middle of firing `hook_config`.
if ($mixInfo->isActive()) {
$register([$dir]);
}
return;
}
if (CRM_Extension_System::singleton()->getManager()->extensionIsBeingInstalledOrEnabled($mixInfo->longName)) {
// New Install, Standard Loader: The extension has just been enabled, and we're now setting it up.
// System has already booted. New templates may be needed for upcoming installation steps.
$register([$dir]);
return;
}
// Typical Pageview, Standard Loader: Defer the actual registration for a moment -- to ensure that Smarty is online.
// We need to bundle-up all dirs -- Smarty 3/4/5 is inefficient with processing repeated calls to `getTemplateDir()`+`setTemplateDir()`
if (!isset(Civi::$statics[__FILE__]['event'])) {
Civi::$statics[__FILE__]['event'] = 'civi.smarty-v2.addPaths.' . md5(__FILE__);
Civi::dispatcher()->addListener('hook_civicrm_config', function() use ($register) {
$dirs = [];
$event = \Civi\Core\Event\GenericHookEvent::create(['dirs' => &$dirs]);
Civi::dispatcher()->dispatch(Civi::$statics[__FILE__]['event'], $event);
$register($dirs);
});
}
Civi::dispatcher()->addListener(Civi::$statics[__FILE__]['event'], function($event) use ($mixInfo, $dir) {
if ($mixInfo->isActive()) {
array_unshift($event->dirs, $dir);
}
});
};

View File

@ -1,6 +1,6 @@
{*-------------------------------------------------------+ {*-------------------------------------------------------+
| CiviProxy | | CiviProxy |
| Copyright (C) 2015 SYSTOPIA | | Copyright (C) 2015-2021 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) | | Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ | | http://www.systopia.de/ |
+--------------------------------------------------------+ +--------------------------------------------------------+

View File

@ -1,6 +1,6 @@
{*-------------------------------------------------------+ {*-------------------------------------------------------+
| CiviProxy | | CiviProxy |
| Copyright (C) 2015 SYSTOPIA | | Copyright (C) 2015-2021 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) | | Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ | | http://www.systopia.de/ |
+--------------------------------------------------------+ +--------------------------------------------------------+

View File

@ -36,16 +36,24 @@ The CiviProxy server is the actual policeman that receives all requests and deci
Once you have installed your CiviProxy server you need to complete a few configuration steps. Once you have installed your CiviProxy server you need to complete a few configuration steps.
### The Config.php file ### The Config.php file
The configuration of CiviProxy is mainly controlled with one PHP file called `config.php`. You will need to locate that file in your CiviProxy scripts:
The configuration of CiviProxy is mainly controlled with one PHP file called `config.php`. Create this file by copying or renaming the `config.dist.php` file.
![List of files on your CiviProxy server](img/file%20list%20proxy.png) ![List of files on your CiviProxy server](img/file%20list%20proxy.png)
### Configuring the URL of your CiviProxy server ### Configuring the URL of your CiviProxy server
First thing you need to configure is the base URL of your CiviProxy server using the `$proxy_base` variable in the `config.php` file. As I have used a local test installation I have used `http://localhost/proxy`: First thing you need to configure is the base URL of your CiviProxy server using the `$proxy_base` variable in the `config.php` file. As I have used a local test installation I have used `http://localhost/proxy`:
```php ```php
// this should point to the base address of the CiviProxy installation // this should point to the base address of the CiviProxy installation
$proxy_base = 'http://localhost/proxy'; $proxy_base = 'http://localhost/proxy';
``` ```
!!! note
This guide assumes a Drupal7 target CiviCRM with clean URLs enabled. If this is not the case for you, you might have to adjust the URLs and/or encounter issues. If so, please report on GitHub!
### Configuring the link to the secure target CiviCRM ### Configuring the link to the secure target CiviCRM
Next thing you want to configure is what your target CiviCRM is. This is the CiviCRM installation which you want CiviProxy to police, so the one where the actual data resides and is collected from or sent to. Next thing you want to configure is what your target CiviCRM is. This is the CiviCRM installation which you want CiviProxy to police, so the one where the actual data resides and is collected from or sent to.
The assumption is that this CiviCRM resides in some kind of VPN and will accept traffic only from the CiviProxy IP address (and probably a few trusted others like home workers or support people). The assumption is that this CiviCRM resides in some kind of VPN and will accept traffic only from the CiviProxy IP address (and probably a few trusted others like home workers or support people).
@ -57,13 +65,13 @@ You can set the URL of the target CiviCRM using the variable `$target_civirm` in
### Setting for the click tracking url ### Setting for the click tracking url
There is a setting in CiviCRM which is used for tracking the clicks in your mailing. On your CiviProxy server this setting is captured in the variable `$target_url` in the `config.php` file: There is a setting in CiviCRM which is used for tracking the clicks in your mailing. On your CiviProxy server this setting is captured in the variable `$target_url` in the `config.php` file:
```php ```php
$target_url = $target_civicrm . '/sites/all/modules/civicrm/extern/url.php'; $target_url = $target_civicrm . '/civicrm/mailing/url';
``` ```
If you set it to the value NULL this functionality will not be available on your CiviProxy server. If you set it to the value NULL this functionality will not be available on your CiviProxy server.
### Setting for the open tracking ### Setting for the open tracking
CiviCRM tracks if a mailing has been opened in a certain way. CiviProxy has this setting in the variable `$target_open` in the `config.php` file: CiviCRM tracks if a mailing has been opened in a certain way. CiviProxy has this setting in the variable `$target_open` in the `config.php` file:
```php ```php
$target_open = $target_civicrm . '/sites/all/modules/civicrm/extern/open.php'; $target_open = $target_civicrm . '/civicrm/mailing/url/open.php';
``` ```
If you set it to the value NULL this functionality will not be available on your CiviProxy server. If you set it to the value NULL this functionality will not be available on your CiviProxy server.
### Setting for the location of images and included files in your mail(ing) ### Setting for the location of images and included files in your mail(ing)

View File

@ -49,6 +49,8 @@ Installing CiviProxy should be pretty straightforward:
* check the [Configuring CiviProxy](configuration.md) page to see how to configure the CiviProxy extension. * check the [Configuring CiviProxy](configuration.md) page to see how to configure the CiviProxy extension.
## Installing the Proxy scripts your your CiviProxy server ## Installing the Proxy scripts your your CiviProxy server
All you need to do is copy the **proxy** folder on the webspace you want to use for CiviProxy.
As described in [Configuring CiviProxy](configuration.md), you will need to make changes to the `config.php` file. You can either do those changes locally first and then move all the files to your webspace, or move all the files to your webspace first and then changes the `config.php` file there. 1. Copy the **proxy** folder on the webspace you want to use for CiviProxy
2. Create a `config.php` file using `config.dist.php` as a template.
See [Configuring CiviProxy](configuration.md) for details on what you need to include in the `config.php` file.

View File

@ -3,7 +3,8 @@
There shouldn't be any requirements that any web hoster wouldn't comply with, but here they are: There shouldn't be any requirements that any web hoster wouldn't comply with, but here they are:
1. PHP 5.3+ 1. PHP 5.3+
2. PHP PEAR (to install on Debian/Ubunto, run `apt-get install php-pear`) 2. PHP PEAR (to install on Debian/Ubuntu, run `apt-get install php-pear`)
3. Read/write permissions on your webspace 3. The `php-curl` module
4. Reasonable amount of protection, i.e. only authorised users (you) can upload/download the files 4. Read/write permissions on your webspace
5. Ideally with it's own IP address (makes configuring the VPN easier) 5. Reasonable amount of protection, i.e. only authorised users (you) can upload/download the files
6. Ideally with it's own IP address (makes configuring the VPN easier)

View File

@ -1,8 +1,9 @@
site_name: CiviProxy Guide site_name: CiviProxy Guide
site_description: Guide using and installing CiviProxy to manage the traffic to and from your CiviCRM installation site_description: Guide using and installing CiviProxy to manage the traffic to and from your CiviCRM installation
repo_url: https://github.com/systopia/CiviProxy repo_url: https://github.com/systopia/CiviProxy
theme: material theme:
pages: name: material
nav:
- Introduction: index.md - Introduction: index.md
- Technical Requirements: requirements.md - Technical Requirements: requirements.md
- Installing CiviProxy: installation.md - Installing CiviProxy: installation.md
@ -15,7 +16,8 @@ markdown_extensions:
- admonition - admonition
- def_list - def_list
- codehilite - codehilite
- toc:(permalink=true) - toc:
permalink: true
- pymdownx.superfences - pymdownx.superfences
- pymdownx.emoji - pymdownx.emoji

6
proxy/.htaccess Normal file
View File

@ -0,0 +1,6 @@
# Serve
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_URI} ^/civicrm/ajax/api4
RewriteRule ^civicrm/ajax/api4/([^/]*)/([^/]*) rest4.php?entity=$1&action=$2 [QSA,B]
</IfModule>

82
proxy/checks.php Normal file
View File

@ -0,0 +1,82 @@
<?php
/**
* generates a CiviCRM REST API compliant error
* and ends processing
*/
function civiproxy_rest_error($message) {
$error = array( 'is_error' => 1,
'error_message' => $message);
// TODO: Implement header();
print json_encode($error);
exit();
}
/**
* Updates $credentials['api_key'] in-place, or displays an error if api key
* is missing or does not correspond to an entry in $api_key_map (which should
* be set in config.php).
* @param array $credentials
* @param array $api_key_map
*/
function civiproxy_map_api_key(array &$credentials, array $api_key_map) {
if (empty($credentials['api_key'])) {
civiproxy_rest_error("No API key given");
}
else {
if (isset($api_key_map[$credentials['api_key']])) {
$credentials['api_key'] = $api_key_map[$credentials['api_key']];
}
else {
civiproxy_rest_error("Invalid api key");
}
}
}
/**
* Updates $credentials['key'] in-place, or displays an error if site key
* is missing or does not correspond to an entry in $sys_key_map (which should
* be set in config.php).
* @param array $credentials
* @param array $sys_key_map
*/
function civiproxy_map_site_key(array &$credentials, array $sys_key_map) {
if (empty($credentials['key'])) {
civiproxy_rest_error("No site key given");
}
else {
if (isset($sys_key_map[$credentials['key']])) {
$credentials['key'] = $sys_key_map[$credentials['key']];
}
else {
civiproxy_rest_error("Invalid site key");
}
}
}
/**
* @param array $action should have both 'entity' and 'action' keys set
* @param array $rest_allowed_actions from config.php
* @return array
*/
function civiproxy_get_valid_parameters(array $action, array $rest_allowed_actions) {
// in release 0.4, allowed entity/actions per IP were introduced. To introduce backward compatibility,
// the previous test is still used when no 'all' key is found in the array
if (isset($rest_allowed_actions['all'])) {
// get valid key for the rest_allowed_actions
$valid_allowed_key = civiproxy_get_valid_allowed_actions_key($action, $rest_allowed_actions);
$valid_parameters = civiproxy_retrieve_api_parameters($valid_allowed_key, $action['entity'], $action['action'], $rest_allowed_actions);
if (!$valid_parameters) {
civiproxy_rest_error("Invalid entity/action.");
}
}
else {
if (isset($rest_allowed_actions[$action['entity']]) && isset($rest_allowed_actions[$action['entity']][$action['action']])) {
$valid_parameters = $rest_allowed_actions[$action['entity']][$action['action']];
}
else {
civiproxy_rest_error("Invalid entity/action.");
}
}
return $valid_parameters;
}

217
proxy/config.dist.php Normal file
View File

@ -0,0 +1,217 @@
<?php
/*--------------------------------------------------------+
| SYSTOPIA CiviProxy |
| a simple proxy solution for external access to CiviCRM |
| |
| Copyright (C) 2015-2021 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ |
+---------------------------------------------------------*/
/****************************************************************
** INSTALLATION **
** **
** 0. Read https://docs.civicrm.org/civiproxy/en/latest **
** 1. Make a copy of this file called config.php **
** 2. Adjust the parameters and enable needed features **
** 3. Some features (like mailings) require the CiviProxy **
** extension to be enabled on the target CiviCRM **
** **
****************************************************************/
/****************************************************************
** URLS **
****************************************************************/
// this should point to the base address of the CiviProxy installation
$proxy_base = 'https://proxy.yourdomain.org';
// this should point to the target CiviCRM system
$target_civicrm = 'https://your.civicrm.installation.org';
/****************************************************************
** FEATURES / DEFAULT PATHS **
** **
** set to NULL to disable a feature **
****************************************************************/
// default paths, override if you want. Set to NULL to disable
$target_rest = $target_civicrm . '/sites/all/modules/civicrm/extern/rest.php';
// base URL for api4 calls. Will append entity and action path segments
$target_rest4 = $target_civicrm . '/civicrm/ajax/api4/';
$target_file = $target_civicrm . '/sites/default/files/civicrm/persist/';
$target_mosaico = NULL; // (disabled by default): $target_civicrm . '/civicrm/mosaico/img?src=';
$target_mosaico_template_url = NULL; // (disabled by default): $target_civicrm . '/wp-content/uploads/civicrm/ext/uk.co.vedaconsulting.mosaico/packages/mosaico/templates/';
$target_mail_view = $target_civicrm . '/civicrm/mailing/view';
$target_url = $target_civicrm . '/civicrm/mailing/url';
$target_open = $target_civicrm . '/civicrm/mailing/open';
// CAUTION: use the following for CiviCRM < 5.27 or "Extern URL Style" = "Standalone Scripts"
//$target_url = $target_civicrm . '/sites/all/modules/civicrm/extern/url.php';
//$target_open = $target_civicrm . '/sites/all/modules/civicrm/extern/open.php';
/****************************************************************
** GENERAL OPTIONS **
****************************************************************/
// This logo is shown if the proxy server is address with a web browser
// add your own logo here
$civiproxy_logo = "<img src='{$proxy_base}/static/images/proxy-logo.png' alt='SYSTOPIA Organisationsberatung'></img>";
// Set api-key for mail subscribe/unsubscribe user
// Set to NULL/FALSE to disable the feature
// Can/shoud also be defined in secrets.php
$mail_subscription_user_key = NULL;
// CAREFUL: only enable temporarily on debug systems.
// Will log all queries to given PUBLIC file
// Also: use some random name (not this one!)
$debug = NULL; //'LUXFbiaoz4dVWuAHEcuBAe7YQ4YP96rN4MCDmKj89p.log';
// Local network interface or IP to be used for the relayed query
// This is useful in some VPN configurations (see CURLOPT_INTERFACE)
$target_interface = NULL;
/***************************************************************
** Authentication Options **
***************************************************************/
// API and SITE keys (you may add keys here)
$api_key_map = [
'my_api_key' => 'my_api_key', // use this to allow API key
'ext_api_key' => 'real_api_key' // use this to allow and map API key
];
$sys_key_map = [
'REAL_SITE_KEY' => 'REAL_SITE_KEY', // use this to allow site key
'EXT_SITE_KEY' => 'REAL_SITE_KEY' // use this to allow and map site key
];
// source secrets.php to overwrite keys
if (file_exists(dirname(__FILE__)."/secrets.php")) {
// keys can also be stored in 'secrets.php'
require "secrets.php";
}
// Parameter whitelisting for open tracking and URL tracking
// basic civicrm URL/open parameter are u, q and qid (as int)
// If additional parameters are needed, best practise would be to whitelist each one as needed in
// $valid_url_parameters and/or $valid_open_parameters.
// Alternatively it is also possible to allow all parameters with the wildcard parameter '*' => 'string'
$valid_url_parameters = [
'u' => 'int',
'q' => 'int',
'qid' => 'int',
// '*' => 'string' // whildcard, whitelist all url parameters
];
$valid_open_parameters = [
'u' => 'int',
'q' => 'int',
'qid' => 'int',
// '*' => 'string' // wildcard, whitelist *all* open parameters
];
// CiviCRM's API can authenticate with different flows
// https://docs.civicrm.org/dev/en/latest/framework/authx/#flows
// CiviProxy supports 'header', 'xheader', 'legacyrest', and 'param'.
// These flows are supported for API4 but could be extended to API3.
// $authx_internal_flow controls how CiviProxy sends credentials to CiviCRM, and
// $authx_external_flow where CiviProxy looks for credentials on incoming requests.
// The internal setting needs to have a single scalar value, but the
// external setting can be an array of accepted flows.
// There is no standard header for site key, so in both header and xheader
// flows it uses X-Civi-Key
$authx_internal_flow = 'header';
$authx_external_flow = ['legacyrest'];
/****************************************************************
** File Caching Options **
****************************************************************/
// define file cache options, see http://pear.php.net/manual/en/package.caching.cache-lite.cache-lite.cache-lite.php
$file_cache_options = [
'cacheDir' => 'file_cache/',
'lifeTime' => 86400
];
// define regex patterns that shoud NOT be accepted
$file_cache_exclude = [];
// if set, cached file must match at least one of these regex patterns
$file_cache_include = [
//'#.+[.](png|jpe?g|gif)#i' // only media files
];
/****************************************************************
** REST API OPTIONS **
****************************************************************/
// if you enable this, the system will also try to
// parse the 'json' parameter, which holds additional
// input data according to the CiviCRM REST API specs
$rest_evaluate_json_parameter = FALSE;
// whitelisting is done per IP address ($_SERVER['REMOTE_ADDR']) with a 'all' for the generic stuff that applies to all IP addresses
// - if a request comes in and the IP is not a key in the array, the whitelisted in 'all' are used
// - if a request comes in and the IP is indeed a key in the array, the whitelisted in the IP are checked first. If nothing is
// found ,the 'all' ones are checked next.
$rest_allowed_actions = [
'all' => [
'Contact' => [
'getsingle' => [
'email' => 'string',
],
],
],
'123.45.67.8' => [
'Contact' => [
'getsingle' => [
'first_name' => 'string',
'last_name' => 'string',
// the following means *all* remaining parameters will be
// added and sanitised as 'string'. Better leave it out
// if you know which parameters you expect
'*' => 'string',
],
],
],
];
/****************************************************************
** WebHook2API CONFIGURATIONS **
** Translates typical webhook calls into CiviCRM API calls **
****************************************************************/
// Example configuration:
// remove if you don't want this feature or rename to $webhook2api to activate
$_webhook2api = [
"configurations" => [
"default" => [
"name" => "Example",
"ip_sources" => ['172.10.0.1/24', '192.168.1.1/24'], // only accept source ID from the given range
"data_sources" => ["POST/json", "REQUEST"], // POST/json json-decodes the post data, REQUEST is PHP's $_REQUEST array
"sentinel" => [["type", "equal:customer.created"]], // only execute if all of these are true
"entity" => "Contact",
"action" => "create",
"api_key" => "api key",
"parameter_mapping" => [
[["data", "object", "metadata", "salutation"], ["prefix_id"]],
[["data", "object", "metadata", "first_name"], ["first_name"]],
[["data", "object", "metadata", "last_name"], ["last_name"]],
[["data", "object", "metadata", "street"], ["street_address"]],
[["data", "object", "metadata", "zip_code"], ["postal_code"]],
[["data", "object", "metadata", "city"], ["city"]],
[["data", "object", "metadata", "country"], ["country_id"]],
[["data", "object", "metadata", "telephone"], ["phone"]],
[["data", "object", "metadata", "birthday"], ["birth_date"]],
[["data", "object", "metadata", "email"], ["email"]]
],
"parameter_sanitation" => [],
]
]
];

View File

@ -1,105 +0,0 @@
<?php
/*--------------------------------------------------------+
| SYSTOPIA CiviProxy |
| a simple proxy solution for external access to CiviCRM |
| Copyright (C) 2015 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ |
+---------------------------------------------------------*/
/****************************************************************
** URLS **
****************************************************************/
// this should point to the base address of the CiviProxy installation
$proxy_base = 'https://proxy.yourdomain.org';
// this should point to the target CiviCRM system
$target_civicrm = 'https://your.civicrm.installation.org';
/****************************************************************
** DEFAULT PATHS **
** **
** set to NULL to disable a feature **
****************************************************************/
// default paths, override if you want. Set to NULL to disable
$target_rest = $target_civicrm . '/sites/all/modules/civicrm/extern/rest.php';
$target_url = $target_civicrm . '/sites/all/modules/civicrm/extern/url.php';
$target_open = $target_civicrm . '/sites/all/modules/civicrm/extern/open.php';
$target_file = $target_civicrm . '/sites/default/files/civicrm/persist/';
$target_mosaico = NULL; // (disabled by default): $target_civicrm . '/civicrm/mosaico/img?src=';
$target_mail_view = $target_civicrm . '/civicrm/mailing/view';
// Set api-key for mail subscribe/unsubscribe user
// Set to NULL/FALSE to disable the feature
$mail_subscription_user_key = NULL;
// CAREFUL: only enable temporarily on debug systems.
// Will log all queries to given PUBLIC file
// Also: use some random name (not this one!)
$debug = NULL; //'LUXFbiaoz4dVWuAHEcuBAe7YQ4YP96rN4MCDmKj89p.log';
// Local network interface or IP to be used for the relayed query
// This is usefull in some VPN configurations (see CURLOPT_INTERFACE)
$target_interface = NULL;
/****************************************************************
** File Caching Options **
****************************************************************/
// API and SITE keys
$api_key_map = array();
$sys_key_map = array();
if (file_exists(dirname(__FILE__)."/secrets.php")) {
// keys can also be stored in 'secrets.php'
require "secrets.php";
}
// define file cache options, see http://pear.php.net/manual/en/package.caching.cache-lite.cache-lite.cache-lite.php
$file_cache_options = array(
'cacheDir' => 'file_cache/',
'lifeTime' => 86400
);
// define regex patterns that shoud NOT be accepted
$file_cache_exclude = array();
// if set, cached file must match at least one of these regex patterns
$file_cache_include = array(
//'#.+[.](png|jpe?g|gif)#i' // only media files
);
/****************************************************************
** REST API OPTIONS **
****************************************************************/
// whitelisting is done per IP address ($_SERVER['REMOTE_ADDR']) with a 'all' for the generic stuff that applies to all IP addresses
// - if a request comes in and the IP is not a key in the array, the whitelisted in 'all' are used
// - if a request comes in and the IP is indeed a key in the array, the whitelisted in the IP are checked first. If nothing is
// found ,the 'all' ones are checked next.
$rest_allowed_actions = array(
'all' => array(
'Contact' => array(
'getsingle' => array(
'email' => 'string',
),
),
),
'123.45.678.1' => array(
'Contact' => array(
'getsingle' => array(
'first_name' => 'string',
'last_name' => 'string',
// the following means *all* remaining parameters will be
// added and sanitised as 'string'. Better leave it out
// if you know which parameters you expect
'*' => 'string',
),
),
),
);

View File

@ -2,7 +2,7 @@
/*--------------------------------------------------------+ /*--------------------------------------------------------+
| SYSTOPIA CiviProxy | | SYSTOPIA CiviProxy |
| a simple proxy solution for external access to CiviCRM | | a simple proxy solution for external access to CiviCRM |
| Copyright (C) 2015 SYSTOPIA | | Copyright (C) 2015-2021 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) | | Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ | | http://www.systopia.de/ |
+---------------------------------------------------------*/ +---------------------------------------------------------*/
@ -15,7 +15,6 @@ require_once "proxy.php";
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>CiviProxy Error</title> <title>CiviProxy Error</title>
<link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css">
<style type="text/css"> <style type="text/css">
body { body {
margin: 0; margin: 0;

View File

@ -2,7 +2,7 @@
/*--------------------------------------------------------+ /*--------------------------------------------------------+
| SYSTOPIA CiviProxy | | SYSTOPIA CiviProxy |
| a simple proxy solution for external access to CiviCRM | | a simple proxy solution for external access to CiviCRM |
| Copyright (C) 2015 SYSTOPIA | | Copyright (C) 2015-2021 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) | | Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ | | http://www.systopia.de/ |
+---------------------------------------------------------*/ +---------------------------------------------------------*/
@ -76,7 +76,7 @@ curl_setopt($curlSession, CURLOPT_URL, $url);
curl_setopt($curlSession, CURLOPT_HEADER, 1); curl_setopt($curlSession, CURLOPT_HEADER, 1);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER,1); curl_setopt($curlSession, CURLOPT_RETURNTRANSFER,1);
curl_setopt($curlSession, CURLOPT_TIMEOUT, 30); curl_setopt($curlSession, CURLOPT_TIMEOUT, 30);
curl_setopt($curlSession, CURLOPT_SSL_VERIFYHOST, 1); curl_setopt($curlSession, CURLOPT_SSL_VERIFYHOST, 2);
if (!empty($target_interface)) { if (!empty($target_interface)) {
curl_setopt($curlSession, CURLOPT_INTERFACE, $target_interface); curl_setopt($curlSession, CURLOPT_INTERFACE, $target_interface);
} }

View File

@ -2,7 +2,7 @@
/*--------------------------------------------------------+ /*--------------------------------------------------------+
| SYSTOPIA CiviProxy | | SYSTOPIA CiviProxy |
| a simple proxy solution for external access to CiviCRM | | a simple proxy solution for external access to CiviCRM |
| Copyright (C) 2015 SYSTOPIA | | Copyright (C) 2015-2021 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) | | Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ | | http://www.systopia.de/ |
+---------------------------------------------------------*/ +---------------------------------------------------------*/
@ -16,7 +16,6 @@ require_once "proxy.php";
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>CiviProxy Version <?php echo $civiproxy_version;?></title> <title>CiviProxy Version <?php echo $civiproxy_version;?></title>
<link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css">
<style type="text/css"> <style type="text/css">
body { body {
margin: 0; margin: 0;

View File

@ -294,7 +294,7 @@ class Cache_Lite
* @param array $options options * @param array $options options
* @access public * @access public
*/ */
function Cache_Lite($options = array(NULL)) function __construct($options = array(NULL))
{ {
foreach($options as $key => $value) { foreach($options as $key => $value) {
$this->setOption($key, $value); $this->setOption($key, $value);
@ -304,6 +304,16 @@ class Cache_Lite
} }
} }
/**
* PHP4 constructor for backwards compatibility with older code
*
* @param array $options Options
*/
function Cache_Lite($options = array(NULL))
{
self::__construct($options);
}
/** /**
* Generic way to set a Cache_Lite option * Generic way to set a Cache_Lite option
* *
@ -554,7 +564,6 @@ class Cache_Lite
*/ */
function raiseError($msg, $code) function raiseError($msg, $code)
{ {
include_once('PEAR.php');
return PEAR::raiseError($msg, $code, $this->_pearErrorMode); return PEAR::raiseError($msg, $code, $this->_pearErrorMode);
} }
@ -629,7 +638,7 @@ class Cache_Lite
return true; return true;
} }
} }
if (!($dh = opendir($dir))) { if (!($dh = @opendir($dir))) {
return $this->raiseError('Cache_Lite : Unable to open cache directory !', -4); return $this->raiseError('Cache_Lite : Unable to open cache directory !', -4);
} }
$result = true; $result = true;
@ -698,8 +707,10 @@ class Cache_Lite
$this->_touchCacheFile(); $this->_touchCacheFile();
$this->_memoryCachingArray[$this->_file] = $data; $this->_memoryCachingArray[$this->_file] = $data;
if ($this->_memoryCachingCounter >= $this->_memoryCachingLimit) { if ($this->_memoryCachingCounter >= $this->_memoryCachingLimit) {
list($key, ) = each($this->_memoryCachingArray); $key = key($this->_memoryCachingArray);
next($this->_memoryCachingArray);
unset($this->_memoryCachingArray[$key]); unset($this->_memoryCachingArray[$key]);
} else { } else {
$this->_memoryCachingCounter = $this->_memoryCachingCounter + 1; $this->_memoryCachingCounter = $this->_memoryCachingCounter + 1;
} }
@ -744,7 +755,7 @@ class Cache_Lite
if ($this->_fileLocking) @flock($fp, LOCK_SH); if ($this->_fileLocking) @flock($fp, LOCK_SH);
clearstatcache(); clearstatcache();
$length = @filesize($this->_file); $length = @filesize($this->_file);
$mqr = get_magic_quotes_runtime(); $mqr = (function_exists('get_magic_quotes_runtime') ? @get_magic_quotes_runtime() : 0);
if ($mqr) { if ($mqr) {
set_magic_quotes_runtime(0); set_magic_quotes_runtime(0);
} }
@ -823,7 +834,7 @@ class Cache_Lite
if ($this->_readControl) { if ($this->_readControl) {
@fwrite($fp, $this->_hash($data, $this->_readControlType), 32); @fwrite($fp, $this->_hash($data, $this->_readControlType), 32);
} }
$mqr = get_magic_quotes_runtime(); $mqr = (function_exists('get_magic_quotes_runtime') ? @get_magic_quotes_runtime() : 0);
if ($mqr) { if ($mqr) {
set_magic_quotes_runtime(0); set_magic_quotes_runtime(0);
} }

View File

@ -52,10 +52,10 @@ class Cache_Lite_File extends Cache_Lite
* @param array $options options * @param array $options options
* @access public * @access public
*/ */
function Cache_Lite_File($options = array(NULL)) function __construct($options = array(NULL))
{ {
$options['lifetime'] = 0; $options['lifetime'] = 0;
$this->Cache_Lite($options); parent::__construct($options);
if (isset($options['masterFile'])) { if (isset($options['masterFile'])) {
$this->_masterFile = $options['masterFile']; $this->_masterFile = $options['masterFile'];
} else { } else {
@ -66,6 +66,16 @@ class Cache_Lite_File extends Cache_Lite
} }
} }
/**
* PHP4 constructor for backwards compatibility with older code
*
* @param array $options Options
*/
function Cache_Lite_File($options = array(NULL))
{
self::__construct($options);
}
/** /**
* Test if a cache is available and (if yes) return it * Test if a cache is available and (if yes) return it
* *

View File

@ -81,17 +81,27 @@ class Cache_Lite_Function extends Cache_Lite
* @param array $options options * @param array $options options
* @access public * @access public
*/ */
function Cache_Lite_Function($options = array(NULL)) function __construct($options = array(NULL))
{ {
$availableOptions = array('debugCacheLiteFunction', 'defaultGroup', 'dontCacheWhenTheOutputContainsNOCACHE', 'dontCacheWhenTheResultIsFalse', 'dontCacheWhenTheResultIsNull'); $availableOptions = array('debugCacheLiteFunction', 'defaultGroup', 'dontCacheWhenTheOutputContainsNOCACHE', 'dontCacheWhenTheResultIsFalse', 'dontCacheWhenTheResultIsNull');
while (list($name, $value) = each($options)) { foreach ($options as $name => $value) {
if (in_array($name, $availableOptions)) { if (in_array($name, $availableOptions)) {
$property = '_'.$name; $property = '_'.$name;
$this->$property = $value; $this->$property = $value;
} }
} }
reset($options); reset($options);
$this->Cache_Lite($options); parent::__construct($options);
}
/**
* PHP4 constructor for backwards compatibility with older code
*
* @param array $options Options
*/
function Cache_Lite_Function($options = array(NULL))
{
self::__construct($options);
} }
/** /**

View File

@ -26,9 +26,19 @@ class Cache_Lite_Output extends Cache_Lite
* @param array $options options * @param array $options options
* @access public * @access public
*/ */
function Cache_Lite_Output($options) function __construct($options)
{ {
$this->Cache_Lite($options); parent::__construct($options);
}
/**
* PHP4 constructor for backwards compatibility with older code
*
* @param array $options Options
*/
function Cache_Lite_Output($options = array(NULL))
{
self::__construct($options);
} }
/** /**

View File

@ -1,19 +1,25 @@
# PEAR Cache_Lite # PEAR Cache_Lite
Fast and safe little cache system.
This package is a little cache system optimized for file containers.
t is fast and safe (because it uses file locking and/or anti-corruption tests).
[![Build Status](https://travis-ci.org/pear/Cache_Lite.svg)](https://travis-ci.org/pear/Cache_Lite) [![Build Status](https://travis-ci.org/pear/Cache_Lite.svg)](https://travis-ci.org/pear/Cache_Lite)
This package is [Cache_Lite](http://pear.php.net/package/Cache_Lite).
Please report all new issues via the [PEAR bug tracker](http://pear.php.net/bugs/).
## Building
To test this package, run To test this package, run
phpunit tests/ phpunit tests/
To build, simply To build, simply execute
pear package pear package
## Installation
### PEAR
To install from scratch To install from scratch
pear install package.xml pear install package.xml
@ -21,3 +27,15 @@ To install from scratch
To upgrade To upgrade
pear upgrade -f package.xml pear upgrade -f package.xml
### Composer
composer require pear/cache_lite
## Links
- Homepage: http://pear.php.net/package/Cache_Lite
- Source code: https://github.com/pear/Cache_Lite
- Issue tracker: http://pear.php.net/bugs/search.php?cmd=display&package_name[]=Cache_Lite
- Unit test status: https://travis-ci.org/pear/Cache_Lite
- Packagist: https://packagist.org/packages/pear/cache_lite

View File

@ -2,7 +2,7 @@
/*--------------------------------------------------------+ /*--------------------------------------------------------+
| SYSTOPIA CiviProxy | | SYSTOPIA CiviProxy |
| a simple proxy solution for external access to CiviCRM | | a simple proxy solution for external access to CiviCRM |
| Copyright (C) 2015 SYSTOPIA | | Copyright (C) 2015-2021 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) | | Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ | | http://www.systopia.de/ |
+---------------------------------------------------------*/ +---------------------------------------------------------*/
@ -19,7 +19,7 @@ civiproxy_security_check('mail-confirm');
// basic restraints // basic restraints
$valid_parameters = array( 'sid' => 'int', $valid_parameters = array( 'sid' => 'int',
'cid' => 'int', 'cid' => 'int',
'h' => 'hex'); 'h' => 'string');
$parameters = civiproxy_get_parameters($valid_parameters); $parameters = civiproxy_get_parameters($valid_parameters);
// check if parameters specified // check if parameters specified
@ -45,7 +45,6 @@ if (!empty($group_query['is_error'])) {
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>CiviProxy Version <?php echo $civiproxy_version;?></title> <title>CiviProxy Version <?php echo $civiproxy_version;?></title>
<link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css">
<style type="text/css"> <style type="text/css">
body { body {
margin: 0; margin: 0;

View File

@ -2,7 +2,7 @@
/*--------------------------------------------------------+ /*--------------------------------------------------------+
| SYSTOPIA CiviProxy | | SYSTOPIA CiviProxy |
| a simple proxy solution for external access to CiviCRM | | a simple proxy solution for external access to CiviCRM |
| Copyright (C) 2015 SYSTOPIA | | Copyright (C) 2015-2021 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) | | Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ | | http://www.systopia.de/ |
+---------------------------------------------------------*/ +---------------------------------------------------------*/
@ -17,7 +17,7 @@ if (!$target_mail_view) civiproxy_http_error("Feature disabled", 405);
civiproxy_security_check('mail-view'); civiproxy_security_check('mail-view');
// basic restraints // basic restraints
$valid_parameters = array( 'id' => 'int' ); $valid_parameters = array( 'id' => 'int', 'cid' => 'int', 'cs' => 'string' );
$parameters = civiproxy_get_parameters($valid_parameters); $parameters = civiproxy_get_parameters($valid_parameters);
// check if id specified // check if id specified

View File

@ -2,7 +2,7 @@
/*--------------------------------------------------------+ /*--------------------------------------------------------+
| SYSTOPIA CiviProxy | | SYSTOPIA CiviProxy |
| a simple proxy solution for external access to CiviCRM | | a simple proxy solution for external access to CiviCRM |
| Copyright (C) 2015 SYSTOPIA | | Copyright (C) 2015-2021 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) | | Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ | | http://www.systopia.de/ |
+---------------------------------------------------------*/ +---------------------------------------------------------*/

View File

@ -2,7 +2,7 @@
/*--------------------------------------------------------+ /*--------------------------------------------------------+
| SYSTOPIA CiviProxy | | SYSTOPIA CiviProxy |
| a simple proxy solution for external access to CiviCRM | | a simple proxy solution for external access to CiviCRM |
| Copyright (C) 2015 SYSTOPIA | | Copyright (C) 2015-2021 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) | | Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ | | http://www.systopia.de/ |
+---------------------------------------------------------*/ +---------------------------------------------------------*/
@ -19,7 +19,7 @@ civiproxy_security_check('mail-resubscribe');
// basic restraints // basic restraints
$valid_parameters = array( 'jid' => 'int', $valid_parameters = array( 'jid' => 'int',
'qid' => 'int', 'qid' => 'int',
'h' => 'hex'); 'h' => 'string');
$parameters = civiproxy_get_parameters($valid_parameters); $parameters = civiproxy_get_parameters($valid_parameters);
// check if parameters specified // check if parameters specified
@ -45,7 +45,6 @@ if (!empty($group_query['is_error'])) {
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>CiviProxy Version <?php echo $civiproxy_version;?></title> <title>CiviProxy Version <?php echo $civiproxy_version;?></title>
<link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css">
<style type="text/css"> <style type="text/css">
body { body {
margin: 0; margin: 0;

View File

@ -2,7 +2,7 @@
/*--------------------------------------------------------+ /*--------------------------------------------------------+
| SYSTOPIA CiviProxy | | SYSTOPIA CiviProxy |
| a simple proxy solution for external access to CiviCRM | | a simple proxy solution for external access to CiviCRM |
| Copyright (C) 2015 SYSTOPIA | | Copyright (C) 2015-2021 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) | | Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ | | http://www.systopia.de/ |
+---------------------------------------------------------*/ +---------------------------------------------------------*/
@ -83,7 +83,6 @@ if (!empty($_REQUEST['email'])) {
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>CiviProxy Version <?php echo $civiproxy_version;?></title> <title>CiviProxy Version <?php echo $civiproxy_version;?></title>
<link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css">
<style type="text/css"> <style type="text/css">
body { body {
margin: 0; margin: 0;

View File

@ -2,7 +2,7 @@
/*--------------------------------------------------------+ /*--------------------------------------------------------+
| SYSTOPIA CiviProxy | | SYSTOPIA CiviProxy |
| a simple proxy solution for external access to CiviCRM | | a simple proxy solution for external access to CiviCRM |
| Copyright (C) 2015 SYSTOPIA | | Copyright (C) 2015-2021 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) | | Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ | | http://www.systopia.de/ |
+---------------------------------------------------------*/ +---------------------------------------------------------*/
@ -19,7 +19,7 @@ civiproxy_security_check('mail-unsubscribe');
// basic restraints // basic restraints
$valid_parameters = array( 'jid' => 'int', $valid_parameters = array( 'jid' => 'int',
'qid' => 'int', 'qid' => 'int',
'h' => 'hex'); 'h' => 'string');
$parameters = civiproxy_get_parameters($valid_parameters); $parameters = civiproxy_get_parameters($valid_parameters);
// check if parameters specified // check if parameters specified
@ -45,7 +45,6 @@ if (!empty($group_query['is_error'])) {
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>CiviProxy Version <?php echo $civiproxy_version;?></title> <title>CiviProxy Version <?php echo $civiproxy_version;?></title>
<link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css">
<style type="text/css"> <style type="text/css">
body { body {
margin: 0; margin: 0;

View File

@ -2,7 +2,7 @@
/*--------------------------------------------------------+ /*--------------------------------------------------------+
| SYSTOPIA CiviProxy | | SYSTOPIA CiviProxy |
| a simple proxy solution for external access to CiviCRM | | a simple proxy solution for external access to CiviCRM |
| Copyright (C) 2017 SYSTOPIA | | Copyright (C) 2017-2021 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) | | Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ | | http://www.systopia.de/ |
+---------------------------------------------------------*/ +---------------------------------------------------------*/
@ -17,30 +17,61 @@ if (!$target_mosaico) civiproxy_http_error("Feature disabled", 405);
civiproxy_security_check('file'); civiproxy_security_check('file');
// basic restraints // basic restraints
$valid_parameters = array( 'id' => 'string' ); $valid_parameters = array( 'id' => 'string', 'template_url' => 'string' );
$parameters = civiproxy_get_parameters($valid_parameters); $parameters = civiproxy_get_parameters($valid_parameters);
// check if id specified if (!empty($parameters['id'])) {
if (empty($parameters['id'])) civiproxy_http_error("Resource not found"); // check restrictions
if (!empty($file_cache_exclude)) {
// check restrictions foreach ($file_cache_exclude as $pattern) {
if (!empty($file_cache_exclude)) { if (preg_match($pattern, $parameters['id'])) {
foreach ($file_cache_exclude as $pattern) { civiproxy_http_error("Invalid Resource", 403);
if (preg_match($pattern, $parameters['id'])) { }
}
}
if (!empty($file_cache_include)) {
$accept_id = FALSE;
foreach ($file_cache_include as $pattern) {
if (preg_match($pattern, $parameters['id'])) {
$accept_id = TRUE;
}
}
if (!$accept_id) {
civiproxy_http_error("Invalid Resource", 403); civiproxy_http_error("Invalid Resource", 403);
} }
} }
}
if (!empty($file_cache_include)) { // look up the required resource
$accept_id = FALSE; $header_key = 'header&' . $parameters['id'];
foreach ($file_cache_include as $pattern) { $data_key = 'data&' . $parameters['id'];
if (preg_match($pattern, $parameters['id'])) { $url = $target_mosaico . $parameters['id'];
$accept_id = TRUE; } elseif (!empty($parameters['template_url'])) {
// check restrictions
if (!empty($file_cache_exclude)) {
foreach ($file_cache_exclude as $pattern) {
if (preg_match($pattern, $parameters['template_url'])) {
civiproxy_http_error("Invalid Resource", 403);
}
} }
} }
if (!$accept_id) { if (!empty($file_cache_include)) {
civiproxy_http_error("Invalid Resource", 403); $accept_id = FALSE;
foreach ($file_cache_include as $pattern) {
if (preg_match($pattern, $parameters['template_url'])) {
$accept_id = TRUE;
}
}
if (!$accept_id) {
civiproxy_http_error("Invalid Resource", 403);
}
} }
// look up the required resource
$header_key = 'header&' . $parameters['template_url'];
$data_key = 'data&' . $parameters['template_url'];
$url = $target_mosaico_template_url . $parameters['template_url'];
} else {
civiproxy_http_error("Resource not found");
} }
// load PEAR file cache // load PEAR file cache
@ -49,9 +80,6 @@ if (!file_exists($file_cache_options['cacheDir'])) mkdir($file_cache_options['ca
require_once('Cache/Lite.php'); require_once('Cache/Lite.php');
$file_cache = new Cache_Lite($file_cache_options); $file_cache = new Cache_Lite($file_cache_options);
// look up the required resource
$header_key = 'header&' . $parameters['id'];
$data_key = 'data&' . $parameters['id'];
$header = $file_cache->get($header_key); $header = $file_cache->get($header_key);
$data = $file_cache->get($data_key); $data = $file_cache->get($data_key);
@ -68,14 +96,12 @@ if ($header && $data) {
} }
// if we get here, we have a cache miss => load // if we get here, we have a cache miss => load
$url = $target_mosaico . $parameters['id'];
$curlSession = curl_init(); $curlSession = curl_init();
curl_setopt($curlSession, CURLOPT_URL, $url); curl_setopt($curlSession, CURLOPT_URL, $url);
curl_setopt($curlSession, CURLOPT_HEADER, 1); curl_setopt($curlSession, CURLOPT_HEADER, 1);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER,1); curl_setopt($curlSession, CURLOPT_RETURNTRANSFER,1);
curl_setopt($curlSession, CURLOPT_TIMEOUT, 30); curl_setopt($curlSession, CURLOPT_TIMEOUT, 30);
curl_setopt($curlSession, CURLOPT_SSL_VERIFYHOST, 1); curl_setopt($curlSession, CURLOPT_SSL_VERIFYHOST, 2);
if (!empty($target_interface)) { if (!empty($target_interface)) {
curl_setopt($curlSession, CURLOPT_INTERFACE, $target_interface); curl_setopt($curlSession, CURLOPT_INTERFACE, $target_interface);
} }

View File

@ -2,7 +2,7 @@
/*--------------------------------------------------------+ /*--------------------------------------------------------+
| SYSTOPIA CiviProxy | | SYSTOPIA CiviProxy |
| a simple proxy solution for external access to CiviCRM | | a simple proxy solution for external access to CiviCRM |
| Copyright (C) 2015 SYSTOPIA | | Copyright (C) 2015-2021 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) | | Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ | | http://www.systopia.de/ |
+---------------------------------------------------------*/ +---------------------------------------------------------*/
@ -16,8 +16,5 @@ if (!$target_open) civiproxy_http_error("Feature disabled", 405);
// basic check // basic check
civiproxy_security_check('open'); civiproxy_security_check('open');
// basic restraints $parameters = civiproxy_get_parameters($valid_open_parameters);
$valid_parameters = array( 'q' => 'int' );
$parameters = civiproxy_get_parameters($valid_parameters);
civiproxy_redirect($target_open, $parameters); civiproxy_redirect($target_open, $parameters);

View File

@ -2,14 +2,13 @@
/*--------------------------------------------------------+ /*--------------------------------------------------------+
| SYSTOPIA CiviProxy | | SYSTOPIA CiviProxy |
| a simple proxy solution for external access to CiviCRM | | a simple proxy solution for external access to CiviCRM |
| Copyright (C) 2015 SYSTOPIA | | Copyright (C) 2015-2021 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) | | Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ | | http://www.systopia.de/ |
+---------------------------------------------------------*/ +---------------------------------------------------------*/
require_once "config.php"; require_once "config.php";
$civiproxy_version = '0.5'; $civiproxy_version = '1.0.0-beta';
$civiproxy_logo = "<img src='{$proxy_base}/static/images/proxy-logo.png' alt='SYSTOPIA Organisationsberatung'></img>";
/** /**
* this will redirect the request to another URL, * this will redirect the request to another URL,
@ -49,7 +48,7 @@ function civiproxy_redirect($url_requested, $parameters) {
curl_setopt($curlSession, CURLOPT_HEADER, 1); curl_setopt($curlSession, CURLOPT_HEADER, 1);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER,1); curl_setopt($curlSession, CURLOPT_RETURNTRANSFER,1);
curl_setopt($curlSession, CURLOPT_TIMEOUT, 30); curl_setopt($curlSession, CURLOPT_TIMEOUT, 30);
curl_setopt($curlSession, CURLOPT_SSL_VERIFYHOST, 1); curl_setopt($curlSession, CURLOPT_SSL_VERIFYHOST, 2);
if (!empty($target_interface)) { if (!empty($target_interface)) {
curl_setopt($curlSession, CURLOPT_INTERFACE, $target_interface); curl_setopt($curlSession, CURLOPT_INTERFACE, $target_interface);
} }
@ -91,13 +90,155 @@ function civiproxy_redirect($url_requested, $parameters) {
curl_close ($curlSession); curl_close ($curlSession);
} }
/**
* this will redirect the request to an API4 URL,
* i.e. will pass the reply on to this request
*
* @see losely based on https://code.google.com/p/php-proxy/
*
* @param $url_requested string the URL to which the request should be sent
* @param $parameters array
* @param $credentials array
*/
function civiproxy_redirect4($url_requested, $parameters, $credentials) {
global $target_interface, $authx_internal_flow;
$url = $url_requested;
$curlSession = curl_init();
$credential_params = civiproxy_build_credential_params($credentials, $authx_internal_flow);
$credential_headers = civiproxy_build_credential_headers($credentials, $authx_internal_flow);
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
// POST requests should be passed on as POST
curl_setopt($curlSession, CURLOPT_POST, 1);
$urlparams = 'params=' . urlencode(json_encode($parameters)) . $credential_params;
curl_setopt($curlSession, CURLOPT_POSTFIELDS, $urlparams);
} else {
// GET requests will get the parameters as url params
if (!empty($parameters)) {
$url .= '?params=' . urlencode(json_encode($parameters)) . $credential_params;
}
}
curl_setopt($curlSession, CURLOPT_HTTPHEADER, array_merge([
'Content-Type: application/x-www-form-urlencoded'
], $credential_headers));
curl_setopt($curlSession, CURLOPT_URL, $url);
curl_setopt($curlSession, CURLOPT_HEADER, 1);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER,1);
curl_setopt($curlSession, CURLOPT_TIMEOUT, 30);
curl_setopt($curlSession, CURLOPT_SSL_VERIFYHOST, 2);
if (!empty($target_interface)) {
curl_setopt($curlSession, CURLOPT_INTERFACE, $target_interface);
}
if (file_exists(dirname(__FILE__).'/target.pem')) {
curl_setopt($curlSession, CURLOPT_CAINFO, dirname(__FILE__).'/target.pem');
}
//Send the request and store the result in an array
$response = curl_exec($curlSession);
// Check that a connection was made
if (curl_error($curlSession)){
civiproxy_http_error(curl_error($curlSession), curl_errno($curlSession));
} else {
//clean duplicate header that seems to appear on fastcgi with output buffer on some servers!!
$response = str_replace("HTTP/1.1 100 Continue\r\n\r\n","",$response);
// split header / content
$content = explode("\r\n\r\n", $response, 2);
$header = $content[0];
$body = $content[1];
// handle headers - simply re-outputing them
$header_ar = explode(chr(10), $header);
foreach ($header_ar as $header_line){
if (!preg_match("/^Transfer-Encoding/", $header_line)){
civiproxy_mend_URLs($header_line);
header(trim($header_line));
}
}
//rewrite all hard coded urls to ensure the links still work!
civiproxy_mend_URLs($body);
print $body;
}
curl_close($curlSession);
}
/**
* Creates a string with the API credentials to be appended to an API4 GET or POST request.
* When $api4_internal_auth_flow is 'header' or 'xheader', returns a blank string
*
* @param array $credentials
* @param string $authx_internal_flow
* @return string credential string, including leading '&'
*/
function civiproxy_build_credential_params(array $credentials, string $authx_internal_flow): string {
switch($authx_internal_flow) {
case 'legacyrest':
$map = ['api_key' => 'api_key', 'key' => 'key'];
break;
case 'param':
$map = ['api_key' => '_authx', 'key' => '_authxSiteKey'];
break;
default:
return '';
}
$params = [];
foreach($map as $credential_key => $param_name) {
if (isset($credentials[$credential_key])) {
$credential_value = $credentials[$credential_key];
if ($param_name === '_authx') {
$credential_value = 'Bearer ' . $credential_value;
}
$params[$param_name] = $credential_value;
}
}
$param_string = http_build_query($params);
if (!empty($param_string)) {
$param_string = '&' . $param_string;
}
return $param_string;
}
/**
* Builds an array of headers to send on an API4 request. When $api4_internal_auth_flow
* is 'param' or 'legacyrest', will always return an empty array.
*
* @param array $credentials
* @param string $authx_internal_flow
* @return array
*/
function civiproxy_build_credential_headers(array $credentials, string $authx_internal_flow): array {
switch($authx_internal_flow) {
case 'header':
$map = ['api_key' => 'Authorization: Bearer', 'key' => 'X-Civi-Key:'];
break;
case 'xheader':
$map = ['api_key' => 'X-Civi-Auth: Bearer', 'key' => 'X-Civi-Key:'];
break;
default:
return [];
}
$headers = [];
foreach($map as $credential_key => $header_prefix) {
if (isset($credentials[$credential_key])) {
$headers[] = $header_prefix . ' ' . $credentials[$credential_key];
}
}
return $headers;
}
/** /**
* Will mend all the URLs in the string that point to the target, * Will mend all the URLs in the string that point to the target,
* so they will point to this proxy instead * so they will point to this proxy instead
*/ */
function civiproxy_mend_URLs(&$string) { function civiproxy_mend_URLs(&$string) {
global $target_rest, $target_url, $target_open, $target_file, $target_mail, $proxy_base, $target_mosaico; global $target_rest, $target_url, $target_open, $target_file, $target_mail, $proxy_base, $target_mosaico, $target_civicrm;
if ($target_rest) { if ($target_rest) {
$string = preg_replace("#{$target_rest}#", $proxy_base . '/rest.php', $string); $string = preg_replace("#{$target_rest}#", $proxy_base . '/rest.php', $string);
@ -113,11 +254,16 @@ function civiproxy_mend_URLs(&$string) {
} }
if ($target_file) { if ($target_file) {
$string = preg_replace("#{$target_file}#", $proxy_base . '/file.php?id=', $string); $string = preg_replace("#{$target_file}#", $proxy_base . '/file.php?id=', $string);
// https://github.com/systopia/CiviProxy/issues/38
// fix for relative
if ($target_mosaico) {
$string = preg_replace("#src=\"\/sites\/default\/files\/civicrm\/persist\/#", 'src="' . $proxy_base . '/file.php?id=', $string);
}
} }
if ($target_mosaico) { if ($target_mosaico) {
// replace full, and relative URL // replace full, and relative URL
$string = preg_replace("#{$target_mosaico}#", $proxy_base . '/mosaico.php?id=', $string); // $string = preg_replace("#{$target_mosaico}#", $proxy_base . '/mosaico.php?id=', $string);
$string = preg_replace("#/civicrm/mosaico/img\\?src=#", $proxy_base . '/mosaico.php?id=', $string); $string = preg_replace("#{$target_civicrm}/civicrm/mosaico/img\?src=#", $proxy_base . '/mosaico.php?id=', $string);
} }
} }
@ -127,11 +273,12 @@ function civiproxy_mend_URLs(&$string) {
* unauthorized access quantities, etc. * unauthorized access quantities, etc.
* *
* @param $target * @param $target
* @param $quit if TRUE, quit immediately if access denied * @param $quit bool if TRUE, quit immediately if access denied
* @param $log_headers array add these headers (sanitized) to log data
* *
* @return TRUE if allowed, FALSE if not (or quits if $quit is set) * @return TRUE if allowed, FALSE if not (or quits if $quit is set)
*/ */
function civiproxy_security_check($target, $quit=TRUE) { function civiproxy_security_check($target, $quit=TRUE, $log_headers = []) {
// verify that we're SSL encrypted // verify that we're SSL encrypted
if ($_SERVER['HTTPS'] != "on") { if ($_SERVER['HTTPS'] != "on") {
civiproxy_http_error("This CiviProxy installation requires SSL encryption.", 400); civiproxy_http_error("This CiviProxy installation requires SSL encryption.", 400);
@ -139,34 +286,56 @@ function civiproxy_security_check($target, $quit=TRUE) {
global $debug; global $debug;
if (!empty($debug)) { if (!empty($debug)) {
$file = fopen($debug, 'a');
// filter log data // filter log data
$log_data = $_REQUEST; $log_data = $_REQUEST;
if (isset($log_data['api_key'])) { $sanitize_params = ['api_key', 'key', '_authxSiteKey', '_authx'];
$log_data['api_key'] = substr($log_data['api_key'], 0, 4) . '...'; foreach ($sanitize_params as $param) {
} if (isset($log_data[$param])) {
if (isset($log_data['key'])) { $log_data[$param] = substr($log_data[$param], 0, 4) . '...';
$log_data['key'] = substr($log_data['key'], 0, 4) . '...'; }
} }
// write log record foreach($log_headers as $header) {
fwrite($file, "REQUEST FROM " . $_SERVER['REMOTE_ADDR'] . " ON " . date('Y-m-d H:i:s') . ' -- ' . print_r($log_data ,1)); if (!empty($_SERVER[$header]))
fclose($file); $log_data[$header] = substr($_SERVER[$header], 0, 4) . '...';
}
// log
civiproxy_log("REQUEST FROM " . $_SERVER['REMOTE_ADDR'] . " ON " . date('Y-m-d H:i:s') . ' -- ' . print_r($log_data ,1));
} }
// TODO: implement // TODO: implement
return TRUE; return TRUE;
} }
/**
* Log a message to the proxy log - if enabled
*
* @param $message string the log message
*/
function civiproxy_log($message) {
global $debug;
if (!empty($debug)) {
$file = fopen($debug, 'a');
fwrite($file, $message);
fclose($file);
}
}
/** /**
* extract and type check the parameters from the call params * extract and type check the parameters from the call params
* *
* @param $valid_parameters array '<parameter name> => '<expected type>' * @param $valid_parameters array '<parameter name> => '<expected type>'
* where type can be 'int', 'string' (unchecked), * where type can be 'int', 'string' (unchecked),
* @param $request provides the request data to use,
* defaults to $_REQUEST
*/ */
function civiproxy_get_parameters($valid_parameters) { function civiproxy_get_parameters($valid_parameters, $request = NULL) {
if ($request === NULL) {
$request = $_REQUEST;
}
$result = array(); $result = array();
$default_sanitation = NULL; $default_sanitation = NULL;
@ -177,16 +346,15 @@ function civiproxy_get_parameters($valid_parameters) {
continue; continue;
} }
if (isset($_REQUEST[$name])) { if (isset($request[$name])) {
$result[$name] = civiproxy_sanitise($_REQUEST[$name], $type); $result[$name] = civiproxy_sanitise($request[$name], $type);
} }
} }
// process wildcard elements // process wildcard elements
if ($default_sanitation !== NULL) { if ($default_sanitation !== NULL) {
// i.e. we want the others too // i.e. we want the others too
$remove_parameters = array('key', 'api_key', 'version', 'entity', 'action'); $remove_parameters = array('key', 'api_key', '_authx', '_authxSiteKey', 'version', 'entity', 'action');
foreach ($_REQUEST as $name => $value) { foreach ($request as $name => $value) {
if (!in_array($name, $remove_parameters) && !isset($valid_parameters[$name])) { if (!in_array($name, $remove_parameters) && !isset($valid_parameters[$name])) {
$result[$name] = civiproxy_sanitise($value, $default_sanitation); $result[$name] = civiproxy_sanitise($value, $default_sanitation);
} }
@ -196,6 +364,26 @@ function civiproxy_get_parameters($valid_parameters) {
return $result; return $result;
} }
/**
* Get the value of a header on the incoming request
*
* @param string $header name of the header, in all uppercase
* @param string $prefix to be stripped off the value of the header
* @return string|null value of the header, or null if not found.
*/
function civiproxy_get_header($header, $prefix = ''): ?string {
if (!empty($_SERVER['HTTP_' . $header])) {
$value = $_SERVER['HTTP_' . $header];
if ($prefix === '') {
return $value;
}
if (strpos($value, $prefix) === 0) {
return trim(substr($value, strlen($prefix)));
}
}
return NULL;
}
/** /**
* sanitise the given value with the given sanitiation type * sanitise the given value with the given sanitiation type
*/ */
@ -216,10 +404,23 @@ function civiproxy_sanitise($value, $type) {
} }
} elseif ($type == 'email') { } elseif ($type == 'email') {
// valid email // valid email
if (!preg_match("#^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$#i", $value)) { if (!preg_match("#^[_a-z0-9-]+[._a-z0-9-+]*@[a-z0-9-]+[.a-z0-9-]*\.[a-z]{2,3}$#i", $value)) {
error_log("CiviProxy: removed invalid email parameter: " . $value); error_log("CiviProxy: removed invalid email parameter: " . $value);
$value = ''; $value = '';
} }
} elseif ($type == 'json') {
// valid json
$json_data = json_decode($value, true);
if ($json_data === NULL) {
$value = '';
} else {
$value = json_encode($value);
}
} elseif ($type == 'array') {
// this should only happen _inside_ the json field
if (!is_array($value)) {
$value = '';
}
} elseif (is_array($type)) { } elseif (is_array($type)) {
// this is a list of valid options // this is a list of valid options
$requested_value = $value; $requested_value = $value;
@ -282,7 +483,7 @@ function civicrm_api3($entity, $action, $data) {
curl_setopt($curlSession, CURLOPT_INTERFACE, $target_interface); curl_setopt($curlSession, CURLOPT_INTERFACE, $target_interface);
} }
// curl_setopt($curlSession, CURLOPT_SSL_VERIFYPEER, 1); // curl_setopt($curlSession, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($curlSession, CURLOPT_SSL_VERIFYHOST, 1); curl_setopt($curlSession, CURLOPT_SSL_VERIFYHOST, 2);
if (file_exists(dirname(__FILE__).'/target.pem')) { if (file_exists(dirname(__FILE__).'/target.pem')) {
curl_setopt($curlSession, CURLOPT_CAINFO, dirname(__FILE__).'/target.pem'); curl_setopt($curlSession, CURLOPT_CAINFO, dirname(__FILE__).'/target.pem');
} }
@ -307,7 +508,7 @@ function civiproxy_get_valid_allowed_actions_key($action, $rest_allowed_actions)
$remote_addr = $_SERVER['REMOTE_ADDR']; $remote_addr = $_SERVER['REMOTE_ADDR'];
// check IP specific whitelisting if specified for this address // check IP specific whitelisting if specified for this address
if (isset($rest_allowed_actions[$remote_addr])) { if (isset($rest_allowed_actions[$remote_addr])) {
if (isset($rest_allowed_actions[$remote_addr][$action['entity']]) && isset($rest_allowed_actions[$remote_addr][$action['entity']][$action['action']])) { if (civiproxy_validate_api_entity_and_action($remote_addr, $action['entity'], $action['action'], $rest_allowed_actions)) {
$valid_key = $remote_addr; $valid_key = $remote_addr;
} else { } else {
$valid_key = 'all'; $valid_key = 'all';
@ -318,3 +519,81 @@ function civiproxy_get_valid_allowed_actions_key($action, $rest_allowed_actions)
return $valid_key; return $valid_key;
} }
/**
* Function to check whether the api entity and api action are valid for the remote address.
* This function does a case insensitive comparison.
*
* @param $remote_addr
* 'all', or the remote address.
* @param $api_entity
* The api entity.
* @param $api_action
* The api action.
* @param $rest_allowed_actions
* The array with the allowed actions.
* @return bool
*/
function civiproxy_validate_api_entity_and_action($remote_addr, $api_entity, $api_action, $rest_allowed_actions) {
if (!isset($rest_allowed_actions[$remote_addr])) {
return false;
}
$api_entity = strtolower($api_entity);
$api_action = strtolower($api_action);
if (isset($rest_allowed_actions[$remote_addr][$api_entity]) && isset($rest_allowed_actions[$remote_addr][$api_entity][$api_action])) {
return true;
}
// Did not find the lower case variant.
// loop through the array
foreach($rest_allowed_actions[$remote_addr] as $allowed_entity => $allowed_actions) {
if (strtolower($allowed_entity) == $api_entity) {
foreach($allowed_actions as $allowed_action => $fields) {
if (strtolower($allowed_action) == $api_action) {
return true;
}
}
}
}
return false;
}
/**
* Function to retrieve the valid parameters of an api call
* This function does a case insensitive comparison.
*
* @param $remote_addr
* 'all', or the remote address.
* @param $api_entity
* The api entity.
* @param $api_action
* The api action.
* @param $rest_allowed_actions
* The array with the allowed actions.
* @return array()|null
**/
function civiproxy_retrieve_api_parameters($remote_addr, $api_entity, $api_action, $rest_allowed_actions) {
if (!isset($rest_allowed_actions[$remote_addr])) {
return null;
}
$api_entity = strtolower($api_entity);
$api_action = strtolower($api_action);
if (isset($rest_allowed_actions[$remote_addr][$api_entity]) && isset($rest_allowed_actions[$remote_addr][$api_entity][$api_action])) {
return $rest_allowed_actions[$remote_addr][$api_entity][$api_action];
}
// Did not find the lower case variant.
// loop through the array
foreach($rest_allowed_actions[$remote_addr] as $allowed_entity => $allowed_actions) {
if (strtolower($allowed_entity) == $api_entity) {
foreach($allowed_actions as $allowed_action => $parameters) {
if (strtolower($allowed_action) == $api_action) {
return $parameters;
}
}
}
}
return null;
}

View File

@ -2,18 +2,18 @@
/*--------------------------------------------------------+ /*--------------------------------------------------------+
| SYSTOPIA CiviProxy | | SYSTOPIA CiviProxy |
| a simple proxy solution for external access to CiviCRM | | a simple proxy solution for external access to CiviCRM |
| Copyright (C) 2015 SYSTOPIA | | Copyright (C) 2015-2021 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) | | Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ | | http://www.systopia.de/ |
+---------------------------------------------------------*/ +---------------------------------------------------------*/
require_once "config.php"; require_once "config.php";
require_once "proxy.php"; require_once "proxy.php";
require_once "checks.php";
// see if REST API is enabled // see if REST API is enabled
if (!$target_rest) civiproxy_http_error("Feature disabled", 405); if (!$target_rest) civiproxy_http_error("Feature disabled", 405);
// basic check // basic check
if (!civiproxy_security_check('rest')) { if (!civiproxy_security_check('rest')) {
civiproxy_rest_error("Access denied."); civiproxy_rest_error("Access denied.");
@ -21,25 +21,9 @@ if (!civiproxy_security_check('rest')) {
// check credentials // check credentials
$credentials = civiproxy_get_parameters(array('key' => 'string', 'api_key' => 'string')); $credentials = civiproxy_get_parameters(array('key' => 'string', 'api_key' => 'string'));
if (empty($credentials['key'])) {
civiproxy_rest_error("No site key given");
} else {
if (isset($sys_key_map[$credentials['key']])) {
$credentials['key'] = $sys_key_map[$credentials['key']];
} else {
civiproxy_rest_error("Invalid site key");
}
}
if (empty($credentials['api_key'])) { civiproxy_map_site_key($credentials, $sys_key_map);
civiproxy_rest_error("No API key given"); civiproxy_map_api_key($credentials, $api_key_map);
} else {
if (isset($api_key_map[$credentials['api_key']])) {
$credentials['api_key'] = $api_key_map[$credentials['api_key']];
} else {
civiproxy_rest_error("Invalid api key");
}
}
// check if the call itself is allowed // check if the call itself is allowed
$action = civiproxy_get_parameters(array('entity' => 'string', 'action' => 'string', 'version' => 'int', 'json' => 'int', 'sequential' => 'int')); $action = civiproxy_get_parameters(array('entity' => 'string', 'action' => 'string', 'version' => 'int', 'json' => 'int', 'sequential' => 'int'));
@ -47,24 +31,7 @@ if (!isset($action['version']) || $action['version'] != 3) {
civiproxy_rest_error("API 'version' information missing."); civiproxy_rest_error("API 'version' information missing.");
} }
// in release 0.4, allowed entity/actions per IP were introduced. To introduce backward compatibility, $valid_parameters= civiproxy_get_valid_parameters($action, $rest_allowed_actions);
// the previous test is still used when no 'all' key is found in the array
if (isset($rest_allowed_actions['all'])) {
// get valid key for the rest_allowed_actions
$valid_allowed_key = civiproxy_get_valid_allowed_actions_key($action, $rest_allowed_actions);
if (isset($rest_allowed_actions[$valid_allowed_key][$action['entity']]) && isset($rest_allowed_actions[$valid_allowed_key][$action['entity']][$action['action']])) {
$valid_parameters = $rest_allowed_actions[$valid_allowed_key][$action['entity']][$action['action']];
} else {
civiproxy_rest_error("Invalid entity/action.");
}
} else {
if (isset($rest_allowed_actions[$action['entity']]) && isset($rest_allowed_actions[$action['entity']][$action['action']])) {
$valid_parameters = $rest_allowed_actions[$action['entity']][$action['action']];
} else {
civiproxy_rest_error("Invalid entity/action.");
}
}
// extract parameters and add credentials and action data // extract parameters and add credentials and action data
$parameters = civiproxy_get_parameters($valid_parameters); $parameters = civiproxy_get_parameters($valid_parameters);
@ -75,19 +42,18 @@ foreach ($action as $key => $value) {
$parameters[$key] = $value; $parameters[$key] = $value;
} }
// finally execute query // evaluate the JSON parameter
civiproxy_redirect($target_rest, $parameters); global $rest_evaluate_json_parameter;
if ($rest_evaluate_json_parameter) {
if (isset($_REQUEST['json'])) {
/** $json_data = json_decode($_REQUEST['json'], true);
* generates a CiviCRM REST API compliant error if (!empty($json_data) && is_array($json_data)) {
* and ends processing $json_parameters = civiproxy_get_parameters($valid_parameters, $json_data);
*/ $parameters['json'] = json_encode($json_parameters);
function civiproxy_rest_error($message) { }
$error = array( 'is_error' => 1, }
'error_message' => $message);
// TODO: Implement
//header();
print json_encode($error);
exit();
} }
// finally execute query
civiproxy_log($target_rest);
civiproxy_redirect($target_rest, $parameters);

89
proxy/rest4.php Normal file
View File

@ -0,0 +1,89 @@
<?php
/*--------------------------------------------------------+
| SYSTOPIA CiviProxy |
| a simple proxy solution for external access to CiviCRM |
| Copyright (C) 2015-2021 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ |
+---------------------------------------------------------*/
require_once "config.php";
require_once "proxy.php";
require_once "checks.php";
// see if REST API is enabled
if (!$target_rest4) {
civiproxy_http_error("Feature disabled");
}
$valid_flows = ['header', 'xheader', 'legacyrest', 'param'];
$headers_by_flow = [
'header' => ['HTTP_AUTHORIZATION', 'HTTP_X_CIVI_KEY'],
'xheader' => ['HTTP_X_CIVI_AUTH', 'HTTP_X_CIVI_KEY'],
'legacyrest' => [],
'param' => [],
];
if (!in_array($authx_internal_flow, $valid_flows)) {
civiproxy_http_error("Invalid internal auth flow '$authx_internal_flow'", 500);
}
$headers_to_log = [];
foreach ($authx_external_flow as $external_flow) {
if (!in_array($external_flow, $valid_flows)) {
civiproxy_http_error("Invalid external auth flow '$external_flow'", 500);
}
$headers_to_log = array_merge($headers_to_log, $headers_by_flow[$external_flow]);
}
// basic check
if (!civiproxy_security_check('rest', TRUE, $headers_to_log)) {
civiproxy_rest_error("Access denied.");
}
$credentials = [];
// Find credentials on the incoming request
foreach ($authx_external_flow as $external_flow) {
switch($external_flow) {
case 'header':
$credentials['api_key'] = civiproxy_get_header('AUTHORIZATION', 'Bearer ');
$credentials['key'] = civiproxy_get_header('HTTP_X_CIVI_KEY');
break;
case 'xheader':
$credentials['api_key'] = civiproxy_get_header('X_CIVI_AUTH', 'Bearer ');
$credentials['key'] = civiproxy_get_header('HTTP_X_CIVI_KEY');
break;
case 'legacyrest':
$credentials = civiproxy_get_parameters(array('api_key' => 'string', 'key' => 'string'));
break;
case 'param':
$authx_credentials = civiproxy_get_parameters(array('_authx' => 'string', '_authxSiteKey' => 'string'));
if (!empty($authx_credentials['_authx'])) {
// Snip off leading 'Bearer ' or 'Bearer+'
if (substr($authx_credentials['_authx'], 0, 6) === 'Bearer') {
$credentials['api_key'] = substr($authx_credentials['_authx'], 7);
}
}
if (!empty($authx_credentials['_authxSiteKey'])) {
$credentials['key'] = $authx_credentials['_authxSiteKey'];
}
break;
}
if (!empty($credentials['api_key'])) {
break;
}
}
civiproxy_map_api_key($credentials, $api_key_map);
if (!empty($credentials['key'])) {
civiproxy_map_site_key( $credentials, $sys_key_map);
}
// check if the call itself is allowed
$action = civiproxy_get_parameters(array('entity' => 'string', 'action' => 'string'));
$valid_parameters = civiproxy_get_valid_parameters($action, $rest_allowed_actions);
// extract parameters and add action data
$parameters = civiproxy_get_parameters($valid_parameters, json_decode($_REQUEST['params'], true));
// finally execute query
civiproxy_log($target_rest4);
civiproxy_redirect4($target_rest4 . $action['entity'] . '/' . $action['action'] , $parameters, $credentials);

View File

@ -2,7 +2,7 @@
/*--------------------------------------------------------+ /*--------------------------------------------------------+
| SYSTOPIA CiviProxy | | SYSTOPIA CiviProxy |
| a simple proxy solution for external access to CiviCRM | | a simple proxy solution for external access to CiviCRM |
| Copyright (C) 2015 SYSTOPIA | | Copyright (C) 2015-2021 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) | | Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ | | http://www.systopia.de/ |
+---------------------------------------------------------*/ +---------------------------------------------------------*/
@ -16,10 +16,5 @@ if (!$target_url) civiproxy_http_error("Feature disabled", 405);
// basic check // basic check
civiproxy_security_check('url'); civiproxy_security_check('url');
// basic restraints $parameters = civiproxy_get_parameters($valid_url_parameters);
$valid_parameters = array( 'u' => 'int',
'q' => 'int',
'qid' => 'int');
$parameters = civiproxy_get_parameters($valid_parameters);
civiproxy_redirect($target_url, $parameters); civiproxy_redirect($target_url, $parameters);

298
proxy/webhook2api.php Normal file
View File

@ -0,0 +1,298 @@
<?php
/*--------------------------------------------------------+
| SYSTOPIA CiviProxy |
| a simple proxy solution for external access to CiviCRM |
| Copyright (C) 2019-2021 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ |
+---------------------------------------------------------*/
require_once "config.php";
require_once "proxy.php";
// first check if webhooks are enabled
if (empty($webhook2api)) civiproxy_http_error("Feature disabled", 405);
// basic check
if (!civiproxy_security_check('webhook2api')) {
civiproxy_http_error("Access denied", 403);
}
// find the right configuration
if (!empty($_REQUEST['id']) && isset($webhook2api['configurations'][$_REQUEST['id']])) {
// we found the if in the configurations
$configurations = [$webhook2api['configurations'][$_REQUEST['id']]];
} elseif (empty($_REQUEST['id']) && isset($webhook2api['configurations']['default'])) {
// this is teh default configuration
$configurations = [$webhook2api['configurations']['default']];
} else {
// use all of them (first one matching is executed)
$configurations = $webhook2api['configurations'];
}
// read some input
$post_input = @file_get_contents('php://input');
// MAIN: iterate through all (eligible) configurations
$last_error = ["No handler found", 501];
foreach ($configurations as $configuration) {
$last_error = webhook2api_processConfiguration($configuration, $post_input);
if ($last_error == NULL) {
// success!
break;
}
}
// finally - if there was only errors, return the last one
if ($last_error) {
civiproxy_http_error($last_error[0], $last_error[1]);
}
/**
* Apply the given configuration. If it matches and executes,
* it returns NULL, otherwise
*
* @param $configuration array configuration/specification
* @return null|array [status_code, error message]
*/
function webhook2api_processConfiguration($configuration, $post_input) {
// check the IP/range restrictions
if (!empty($configuration['ip_sources']) && is_array($configuration['ip_sources'])) {
$ip = $_SERVER['REMOTE_ADDR'];
$access_granted = FALSE;
foreach ($configuration['ip_sources'] as $netmask) {
// copied from https://secure.php.net/manual/de/ref.network.php
list ($net, $mask) = explode("/", $netmask);
$ip_net = ip2long ($net);
$ip_mask = ~((1 << (32 - $mask)) - 1);
$ip_ip = ip2long ($ip);
$ip_ip_net = $ip_ip & $ip_mask;
if ($ip_ip_net == $ip_net) {
$access_granted = TRUE;
break;
}
}
if (!$access_granted) {
// this configuration is not eligible
return ["Access denied", 403];
}
}
// gather source data
$data = [];
if (!empty($configuration['data_sources']) && is_array($configuration['data_sources'])) {
foreach ($configuration['data_sources'] as $data_source) {
switch ($data_source) {
case 'POST/json': # JSON data in POST field
$more_data = json_decode($post_input, TRUE);
$data = array_merge_recursive($data, $more_data);
break;
case 'REQUEST': # simple request parameters
$data = array_merge_recursive($data, $_REQUEST);
break;
default:
civiproxy_log("Webhook2API[{$configuration['name']}]: unknown source '{$data_source}' in configuration. Ignored.");
}
}
}
// default return code if everything goes according to plan
$http_code = 200;
// check if we have a json_array and react accordingly
if (isset($data[0]) && is_array($data[0])) {
foreach ($data as $d) {
$result = webhook2api_callCiviApi($configuration, $d);
if(isset($result['internal_error'])) {
// internal communication Error occurred. Aborting process
civiproxy_log("Webhook2API[{$configuration['name']}]: internal error occurred: " . json_encode($result['internal_error']));
return $result['internal_error'];
}
if (!empty($result['values']['http_code'])) {
$http_code = $result['values']['http_code'];
} else {
$http_code = 403;
break;
}
}
} else {
$result = webhook2api_callCiviApi($configuration, $data);
if(isset($result['internal_error'])) {
// internal communication Error occurred. Aborting process
civiproxy_log("Webhook2API[{$configuration['name']}]: internal error occurred: " . json_encode($result['internal_error']));
return $result['internal_error'];
}
if (!empty($result['values']['http_code'])) {
$http_code = $result['values']['http_code'];
} elseif ($result['is_error'] != 0) {
$http_code = 403;
}
}
if ($http_code != '200') {
// we received and parsed the webhook event successfully, but an error occurred with civicrm:
civiproxy_log("Webhook2API[{$configuration['name']}]: Internal CiviCRM Error. Error Code: {$http_code}. Full Message: " . json_encode($result));
}
// process result
if (!empty($configuration['response_mapping']) && is_array($configuration['response_mapping'])) {
// TODO: implement
http_response_code('200');
civiproxy_log("Webhook successful, response mapped.");
} else {
// default behaviour:
http_response_code('200');
civiproxy_log("Webhook successful.");
}
// all done
exit();
}
/**
* Parse Configuration and given data set, apply it and send it to civicrm.
* Returns an internal error if communication to civicrm isn't successful
*
* @param $configuration
* @param $data
*
* @return array|mixed|void
* @throws \CiviCRM_API3_Exception
*/
function webhook2api_callCiviApi($configuration, $data) {
// evaluate sentinels
if (!empty($configuration['sentinel']) && is_array($configuration['sentinel'])) {
foreach ($configuration['sentinel'] as $sentinel) {
list($value_source, $check) = $sentinel;
$value = webhook2api_getValue($data, $value_source);
if (substr($check, 0, 6) == "equal:") {
// check if terms a equal
if (substr($check, 6) != $value) {
return ["internal_error" => "Access denied", 403];
}
} else {
echo "Error";
// unknown instruction
civiproxy_log("Webhook2API[{$configuration['name']}]: don't understand sentinel '{$check}'. Ignored.");
}
}
}
// compile API query
$params = [];
if (!empty($configuration['parameter_mapping']) && is_array($configuration['parameter_mapping'])) {
foreach ($configuration['parameter_mapping'] as $mapping) {
$source_path = $mapping[0];
$target_path = $mapping[1];
$modifiers = isset($mapping[2]) ? $mapping[2] : [];
// get value
$value = webhook2api_getValue($data, $source_path);
// run modifiers
foreach ($modifiers as $modifier) {
// TODO: implement
civiproxy_log("Webhook2API.modifiers: not implemented!");
}
// set to target
webhook2api_setValue($params, $target_path, $value);
}
} else {
$params = $data;
}
// sanitise data
if (!empty($configuration['parameter_sanitation']) && is_array($configuration['parameter_sanitation'])) {
// TODO: implement
civiproxy_log("Webhook2API.sanitation: not implemented!");
}
// send to target REST API
if (empty($configuration['entity']) || empty($configuration['action'])) {
civiproxy_log("Webhook2API[{$configuration['name']}]: Missing entity/action.");
return ["internal_error" => "Configuration error", 403];
}
if (empty($configuration['api_key'])) {
civiproxy_log("Webhook2API[{$configuration['name']}]: Missing api_key.");
return ["internal_error" => "Configuration error", 403];
}
$params['api_key'] = $configuration['api_key'];
// run API call
return civicrm_api3($configuration['entity'], $configuration['action'], $params);
}
/**
* Get the value from a multidimensional array,
* specified by the path
*
* @param $data array multidimensional data array
* @param $path array|string path description
* @return mixed value
*/
function webhook2api_getValue($data, $path) {
if (is_string($path)) {
if (isset($data[$path])) {
return $data[$path];
} else {
return NULL;
}
} elseif (is_array($path)) {
if (count($path) == 0) {
return NULL;
} elseif (count($path) == 1) {
return webhook2api_getValue($data, $path[0]);
} else {
$path_element = array_shift($path);
$sub_data = webhook2api_getValue($data, $path_element);
if (is_array($sub_data)) {
return webhook2api_getValue($sub_data, $path);
} else {
return NULL;
}
}
}
}
/**
* Set the value from a multidimensional array as specified by the path
*
* @param $data array the data
* @param $target_path array destination
* @param $value mixed value
*/
function webhook2api_setValue(&$data, $target_path, $value) {
if (is_array($target_path)) {
if (count($target_path) == 0) {
civiproxy_log("Webhook2API.setValue: Empty target path!");
return;
} elseif (count($target_path) == 1) {
// last element -> set value
$data[$target_path[0]] = $value;
} else {
// not last element
$element = array_shift($target_path);
if (!isset($data[$element])) {
$data[$element] = [];
}
if (is_array($data[$element])) {
webhook2api_setValue($data[$element], $target_path, $value);
} else {
civiproxy_log("Webhook2API.setValue: path node is not an array!");
}
}
} elseif (is_string($target_path)) {
webhook2api_setValue($data, [$target_path], $value);
} else {
civiproxy_log("Webhook2API.setValue: path neither string nor array!");
}
}