Compare commits

..

1 Commits

Author SHA1 Message Date
B. Endres f10f67d6cf implementing #29 (WIP) 2019-11-26 16:15:52 +01:00
38 changed files with 571 additions and 1112 deletions

View File

@ -1,8 +1 @@
## About Documentation on CiviProxy can be found here: https://docs.civicrm.org/civiproxy/en/latest/
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-2021 SYSTOPIA | | Copyright (C) 2015 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]+)(?:-[0-9A-Za-z-]+)?)<\/p>/", $response, $output_array); $result = preg_match("/<p id=\"version\">CiviProxy Version ([0-9]+\.[0-9]+|[0-9]+\.[0-9]+\.[0-9]+)<\/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: (%s)'), $url)); return array('is_error' => 1, 'message' => sprintf(ts('Error: failed to parse version information'), $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-2021 SYSTOPIA | | Copyright (C) 2015 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) | | Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ | | http://www.systopia.de/ |
+--------------------------------------------------------+ +--------------------------------------------------------+
@ -17,23 +17,12 @@ 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, $driver, $params) { public function __construct($mailer) {
$this->mailer = $mailer; $this->mailer = $mailer;
$this->driver = $driver;
$this->params = $params;
} }
/** /**
@ -58,26 +47,17 @@ 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}sites/all/modules/civicrm/extern/open.php#i", $proxy_base.'/open.php', $value);
$value = preg_replace("#{$system_base}civicrm/mailing/open#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/all/modules/civicrm/extern/open.php#i", $proxy_base.'/open.php', $value); $value = preg_replace("#{$system_base}civicrm/mosaico/img\?src=#i", $proxy_base.'/mosaico.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\?method=placeholder(&|&amp;)params=#i", $proxy_base.'/mosaico.php?ph=', $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);
@ -92,11 +72,4 @@ 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

@ -1,70 +0,0 @@
<?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,199 +3,240 @@
// AUTO-GENERATED FILE -- Civix may overwrite any changes made to this file // AUTO-GENERATED FILE -- Civix may overwrite any changes made to this file
/** /**
* The ExtensionUtil class provides small stubs for accessing resources of this * (Delegated) Implementation of hook_civicrm_config
* extension.
*/ */
class CRM_Civiproxy_ExtensionUtil { function _civiproxy_civix_civicrm_config(&$config = NULL) {
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) { if ($configured) return;
return;
}
$configured = TRUE; $configured = TRUE;
$extRoot = __DIR__ . DIRECTORY_SEPARATOR; $template =& CRM_Core_Smarty::singleton();
$include_path = $extRoot . PATH_SEPARATOR . get_include_path();
set_include_path($include_path); $extRoot = dirname( __FILE__ ) . DIRECTORY_SEPARATOR;
// Based on <compatibility>, this does not currently require mixin/polyfill.php. $extDir = $extRoot . 'templates';
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 );
} }
/** /**
* Implements hook_civicrm_install(). * (Delegated) Implementation of hook_civicrm_xmlMenu
* *
* @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_install * @param $files array(string)
*/
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();
// Based on <compatibility>, this does not currently require mixin/polyfill.php. if ($upgrader = _civiproxy_civix_upgrader()) {
return $upgrader->onInstall();
}
} }
/** /**
* (Delegated) Implements hook_civicrm_enable(). * Implementation of hook_civicrm_uninstall
*
* @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_enable
*/ */
function _civiproxy_civix_civicrm_enable(): void { function _civiproxy_civix_civicrm_uninstall() {
_civiproxy_civix_civicrm_config(); _civiproxy_civix_civicrm_config();
// Based on <compatibility>, this does not currently require mixin/polyfill.php. if ($upgrader = _civiproxy_civix_upgrader()) {
return $upgrader->onUninstall();
}
} }
/** /**
* Inserts a navigation menu item at a given place in the hierarchy. * (Delegated) Implementation of hook_civicrm_enable
*
* @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_insert_navigation_menu(&$menu, $path, $item) { function _civiproxy_civix_civicrm_enable() {
_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)) {
$menu[] = [ if (!$navId) $navId = CRM_Core_DAO::singleValueQuery("SELECT max(id) FROM civicrm_navigation");
'attributes' => array_merge([ $navId ++;
'label' => $item['name'] ?? NULL, $menu[$navId] = array (
'active' => 1, 'attributes' => array_merge($item, array(
], $item), 'label' => CRM_Utils_Array::value('name', $item),
]; 'active' => 1,
return TRUE; 'parentID' => $parentId,
} '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 (!isset($entry['child'])) { if (!$entry['child']) $entry['child'] = array();
$entry['child'] = []; $found = _civiproxy_civix_insert_navigation_menu($entry['child'], implode('/', $path), $item, $key);
}
$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-2021 SYSTOPIA | | Copyright (C) 2015 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, $driver, $params); $mailer = new CRM_Civiproxy_Mailer($mailer);
} }
/** /**
@ -25,6 +25,15 @@ 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
*/ */
@ -32,6 +41,13 @@ 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
*/ */
@ -39,9 +55,61 @@ 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,36 +3,21 @@
<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>AGPL</license> <license></license>
<maintainer> <maintainer>
<author>B. Endres</author> <author>B. Endres</author>
<email>endres@systopia.de</email> <email>endres@systopia.de</email>
</maintainer> </maintainer>
<urls> <releaseDate>2018-03-01</releaseDate>
<url desc="Main Extension Page">https://github.com/systopia/CiviProxy</url> <version>0.5</version>
<url desc="Documentation">https://docs.civicrm.org/civiproxy/en/latest/</url> <develStage>stable</develStage>
<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>5.45</ver> <ver>4.4</ver>
<ver>4.6</ver>
<ver>4.7</ver>
</compatibility> </compatibility>
<comments>This is the companion extension to SYSTOPIA's CiviProxy security system</comments> <comments>This is an addition 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

@ -1,40 +0,0 @@
<?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

@ -1,78 +0,0 @@
<?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-2021 SYSTOPIA | | Copyright (C) 2015 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-2021 SYSTOPIA | | Copyright (C) 2015 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

@ -65,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 . '/civicrm/mailing/url'; $target_url = $target_civicrm . '/sites/all/modules/civicrm/extern/url.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 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 . '/civicrm/mailing/url/open.php'; $target_open = $target_civicrm . '/sites/all/modules/civicrm/extern/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

@ -3,7 +3,7 @@
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/Ubuntu, run `apt-get install php-pear`) 2. PHP PEAR (to install on Debian/Ubunto, run `apt-get install php-pear`)
3. The `php-curl` module 3. The `php-curl` module
4. Read/write permissions on your webspace 4. Read/write permissions on your webspace
5. Reasonable amount of protection, i.e. only authorised users (you) can upload/download the files 5. Reasonable amount of protection, i.e. only authorised users (you) can upload/download the files

View File

@ -1,9 +1,8 @@
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: theme: material
name: material pages:
nav:
- Introduction: index.md - Introduction: index.md
- Technical Requirements: requirements.md - Technical Requirements: requirements.md
- Installing CiviProxy: installation.md - Installing CiviProxy: installation.md
@ -16,8 +15,7 @@ markdown_extensions:
- admonition - admonition
- def_list - def_list
- codehilite - codehilite
- toc: - toc:(permalink=true)
permalink: true
- pymdownx.superfences - pymdownx.superfences
- pymdownx.emoji - pymdownx.emoji

View File

@ -1,6 +0,0 @@
# 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>

View File

@ -1,82 +0,0 @@
<?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;
}

View File

@ -2,8 +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/ |
+---------------------------------------------------------*/ +---------------------------------------------------------*/
@ -12,17 +11,10 @@
/**************************************************************** /****************************************************************
** INSTALLATION ** ** INSTALLATION **
** ** ** **
** 0. Read https://docs.civicrm.org/civiproxy/en/latest **
** 1. Make a copy of this file called config.php ** ** 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 ** ** URLS **
****************************************************************/ ****************************************************************/
@ -41,18 +33,11 @@ $target_civicrm = 'https://your.civicrm.installation.org';
// default paths, override if you want. Set to NULL to disable // default paths, override if you want. Set to NULL to disable
$target_rest = $target_civicrm . '/sites/all/modules/civicrm/extern/rest.php'; $target_rest = $target_civicrm . '/sites/all/modules/civicrm/extern/rest.php';
// base URL for api4 calls. Will append entity and action path segments $target_url = $target_civicrm . '/sites/all/modules/civicrm/extern/url.php';
$target_rest4 = $target_civicrm . '/civicrm/ajax/api4/'; $target_open = $target_civicrm . '/sites/all/modules/civicrm/extern/open.php';
$target_file = $target_civicrm . '/sites/default/files/civicrm/persist/'; $target_file = $target_civicrm . '/sites/default/files/civicrm/persist/';
$target_mosaico = NULL; // (disabled by default): $target_civicrm . '/civicrm/mosaico/img?src='; $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_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 ** ** GENERAL OPTIONS **
@ -60,11 +45,11 @@ $target_open = $target_civicrm . '/civicrm/mailing/open';
// This logo is shown if the proxy server is address with a web browser // This logo is shown if the proxy server is address with a web browser
// add your own logo here // add your own logo here
$civiproxy_logo = "<img src='{$proxy_base}/static/images/proxy-logo.png' alt='SYSTOPIA Organisationsberatung'></img>"; $civiproxy_logo = "<img src='{$proxy_base}/static/images/proxy-logo.png' alt='SYSTOPIA Organisationsberatung'></img>";
// Set api-key for mail subscribe/unsubscribe user // Set api-key for mail subscribe/unsubscribe user
// Set to NULL/FALSE to disable the feature // Set to NULL/FALSE to disable the feature
// Can/shoud also be defined in secrets.php
$mail_subscription_user_key = NULL; $mail_subscription_user_key = NULL;
// CAREFUL: only enable temporarily on debug systems. // CAREFUL: only enable temporarily on debug systems.
@ -73,77 +58,35 @@ $mail_subscription_user_key = NULL;
$debug = NULL; //'LUXFbiaoz4dVWuAHEcuBAe7YQ4YP96rN4MCDmKj89p.log'; $debug = NULL; //'LUXFbiaoz4dVWuAHEcuBAe7YQ4YP96rN4MCDmKj89p.log';
// Local network interface or IP to be used for the relayed query // Local network interface or IP to be used for the relayed query
// This is useful in some VPN configurations (see CURLOPT_INTERFACE) // This is usefull in some VPN configurations (see CURLOPT_INTERFACE)
$target_interface = NULL; $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 ** ** 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 // define file cache options, see http://pear.php.net/manual/en/package.caching.cache-lite.cache-lite.cache-lite.php
$file_cache_options = [ $file_cache_options = array(
'cacheDir' => 'file_cache/', 'cacheDir' => 'file_cache/',
'lifeTime' => 86400 'lifeTime' => 86400
]; );
// define regex patterns that shoud NOT be accepted // define regex patterns that shoud NOT be accepted
$file_cache_exclude = []; $file_cache_exclude = array();
// if set, cached file must match at least one of these regex patterns // if set, cached file must match at least one of these regex patterns
$file_cache_include = [ $file_cache_include = array(
//'#.+[.](png|jpe?g|gif)#i' // only media files //'#.+[.](png|jpe?g|gif)#i' // only media files
]; );
@ -160,35 +103,33 @@ $rest_evaluate_json_parameter = FALSE;
// - 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 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 // - 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. // found ,the 'all' ones are checked next.
$rest_allowed_actions = [ $rest_allowed_actions = array(
'all' => [ 'all' => array(
'Contact' => [ 'Contact' => array(
'getsingle' => [ 'getsingle' => array(
'email' => 'string', 'email' => 'string',
], ),
], ),
], ),
'123.45.67.8' => [ '123.45.67.8' => array(
'Contact' => [ 'Contact' => array(
'getsingle' => [ 'getsingle' => array(
'first_name' => 'string', 'first_name' => 'string',
'last_name' => 'string', 'last_name' => 'string',
// the following means *all* remaining parameters will be // the following means *all* remaining parameters will be
// added and sanitised as 'string'. Better leave it out // added and sanitised as 'string'. Better leave it out
// if you know which parameters you expect // if you know which parameters you expect
'*' => 'string', '*' => 'string',
], ),
], ),
], ),
]; );
/**************************************************************** /****************************************************************
** WebHook2API CONFIGURATIONS ** ** 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
// remove if you don't want this feature or rename to $webhook2api to activate
$_webhook2api = [ $_webhook2api = [
"configurations" => [ "configurations" => [
"default" => [ "default" => [
@ -214,4 +155,4 @@ $_webhook2api = [
"parameter_sanitation" => [], "parameter_sanitation" => [],
] ]
] ]
]; ];

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-2021 SYSTOPIA | | Copyright (C) 2015 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) | | Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ | | http://www.systopia.de/ |
+---------------------------------------------------------*/ +---------------------------------------------------------*/
@ -15,6 +15,7 @@ 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-2021 SYSTOPIA | | Copyright (C) 2015 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-2021 SYSTOPIA | | Copyright (C) 2015 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) | | Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ | | http://www.systopia.de/ |
+---------------------------------------------------------*/ +---------------------------------------------------------*/
@ -16,6 +16,7 @@ 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

@ -79,7 +79,7 @@ class Cache_Lite
* @var string $_file * @var string $_file
*/ */
var $_file; var $_file;
/** /**
* File name (without path) * File name (without path)
* *
@ -128,7 +128,7 @@ class Cache_Lite
* @var int $_pearErrorMode * @var int $_pearErrorMode
*/ */
var $_pearErrorMode = CACHE_LITE_ERROR_RETURN; var $_pearErrorMode = CACHE_LITE_ERROR_RETURN;
/** /**
* Current cache id * Current cache id
* *
@ -146,7 +146,7 @@ class Cache_Lite
/** /**
* Enable / Disable "Memory Caching" * Enable / Disable "Memory Caching"
* *
* NB : There is no lifetime for memory caching ! * NB : There is no lifetime for memory caching !
* *
* @var boolean $_memoryCaching * @var boolean $_memoryCaching
*/ */
@ -180,7 +180,7 @@ class Cache_Lite
* @var int $memoryCachingLimit * @var int $memoryCachingLimit
*/ */
var $_memoryCachingLimit = 1000; var $_memoryCachingLimit = 1000;
/** /**
* File Name protection * File Name protection
* *
@ -192,17 +192,17 @@ class Cache_Lite
* @var boolean $fileNameProtection * @var boolean $fileNameProtection
*/ */
var $_fileNameProtection = true; var $_fileNameProtection = true;
/** /**
* Enable / disable automatic serialization * Enable / disable automatic serialization
* *
* it can be used to save directly datas which aren't strings * it can be used to save directly datas which aren't strings
* (but it's slower) * (but it's slower)
* *
* @var boolean $_serialize * @var boolean $_serialize
*/ */
var $_automaticSerialization = false; var $_automaticSerialization = false;
/** /**
* Disable / Tune the automatic cleaning process * Disable / Tune the automatic cleaning process
* *
@ -215,45 +215,45 @@ class Cache_Lite
* @var int $_automaticCleaning * @var int $_automaticCleaning
*/ */
var $_automaticCleaningFactor = 0; var $_automaticCleaningFactor = 0;
/** /**
* Nested directory level * Nested directory level
* *
* Set the hashed directory structure level. 0 means "no hashed directory * Set the hashed directory structure level. 0 means "no hashed directory
* structure", 1 means "one level of directory", 2 means "two levels"... * structure", 1 means "one level of directory", 2 means "two levels"...
* This option can speed up Cache_Lite only when you have many thousands of * This option can speed up Cache_Lite only when you have many thousands of
* cache file. Only specific benchs can help you to choose the perfect value * cache file. Only specific benchs can help you to choose the perfect value
* for you. Maybe, 1 or 2 is a good start. * for you. Maybe, 1 or 2 is a good start.
* *
* @var int $_hashedDirectoryLevel * @var int $_hashedDirectoryLevel
*/ */
var $_hashedDirectoryLevel = 0; var $_hashedDirectoryLevel = 0;
/** /**
* Umask for hashed directory structure * Umask for hashed directory structure
* *
* @var int $_hashedDirectoryUmask * @var int $_hashedDirectoryUmask
*/ */
var $_hashedDirectoryUmask = 0700; var $_hashedDirectoryUmask = 0700;
/** /**
* API break for error handling in CACHE_LITE_ERROR_RETURN mode * API break for error handling in CACHE_LITE_ERROR_RETURN mode
* *
* In CACHE_LITE_ERROR_RETURN mode, error handling was not good because * In CACHE_LITE_ERROR_RETURN mode, error handling was not good because
* for example save() method always returned a boolean (a PEAR_Error object * for example save() method always returned a boolean (a PEAR_Error object
* would be better in CACHE_LITE_ERROR_RETURN mode). To correct this without * would be better in CACHE_LITE_ERROR_RETURN mode). To correct this without
* breaking the API, this option (false by default) can change this handling. * breaking the API, this option (false by default) can change this handling.
* *
* @var boolean * @var boolean
*/ */
var $_errorHandlingAPIBreak = false; var $_errorHandlingAPIBreak = false;
var $_hashedDirectoryGroup = NULL; var $_hashedDirectoryGroup = NULL;
var $_cacheFileMode = NULL; var $_cacheFileMode = NULL;
var $_cacheFileGroup = NULL; var $_cacheFileGroup = NULL;
// --- Public methods --- // --- Public methods ---
/** /**
@ -282,19 +282,19 @@ class Cache_Lite
* 'cacheFileMode' => filesystem mode of newly created cache files (int) * 'cacheFileMode' => filesystem mode of newly created cache files (int)
* 'cacheFileGroup' => group of newly created cache files (int | string) (see function chgrp) * 'cacheFileGroup' => group of newly created cache files (int | string) (see function chgrp)
* ); * );
* *
* If sys_get_temp_dir() is available and the * If sys_get_temp_dir() is available and the
* 'cacheDir' option is not provided in the * 'cacheDir' option is not provided in the
* constructor options array its output is used * constructor options array its output is used
* to determine the suitable temporary directory. * to determine the suitable temporary directory.
* *
* @see http://de.php.net/sys_get_temp_dir * @see http://de.php.net/sys_get_temp_dir
* @see http://pear.php.net/bugs/bug.php?id=18328 * @see http://pear.php.net/bugs/bug.php?id=18328
* *
* @param array $options options * @param array $options options
* @access public * @access public
*/ */
function __construct($options = array(NULL)) function Cache_Lite($options = array(NULL))
{ {
foreach($options as $key => $value) { foreach($options as $key => $value) {
$this->setOption($key, $value); $this->setOption($key, $value);
@ -303,17 +303,7 @@ class Cache_Lite
$this->setOption('cacheDir', sys_get_temp_dir() . DIRECTORY_SEPARATOR); $this->setOption('cacheDir', sys_get_temp_dir() . DIRECTORY_SEPARATOR);
} }
} }
/**
* 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
* *
@ -323,7 +313,7 @@ class Cache_Lite
* @var mixed $value value of the option * @var mixed $value value of the option
* @access public * @access public
*/ */
function setOption($name, $value) function setOption($name, $value)
{ {
$availableOptions = array('errorHandlingAPIBreak', 'hashedDirectoryUmask', 'hashedDirectoryLevel', 'automaticCleaningFactor', 'automaticSerialization', 'fileNameProtection', 'memoryCaching', 'onlyMemoryCaching', 'memoryCachingLimit', 'cacheDir', 'caching', 'lifeTime', 'fileLocking', 'writeControl', 'readControl', 'readControlType', 'pearErrorMode', 'hashedDirectoryGroup', 'cacheFileMode', 'cacheFileGroup'); $availableOptions = array('errorHandlingAPIBreak', 'hashedDirectoryUmask', 'hashedDirectoryLevel', 'automaticCleaningFactor', 'automaticSerialization', 'fileNameProtection', 'memoryCaching', 'onlyMemoryCaching', 'memoryCachingLimit', 'cacheDir', 'caching', 'lifeTime', 'fileLocking', 'writeControl', 'readControl', 'readControlType', 'pearErrorMode', 'hashedDirectoryGroup', 'cacheFileMode', 'cacheFileGroup');
if (in_array($name, $availableOptions)) { if (in_array($name, $availableOptions)) {
@ -331,7 +321,7 @@ class Cache_Lite
$this->$property = $value; $this->$property = $value;
} }
} }
/** /**
* Test if a cache is available and (if yes) return it * Test if a cache is available and (if yes) return it
* *
@ -359,7 +349,7 @@ class Cache_Lite
} }
if ($this->_onlyMemoryCaching) { if ($this->_onlyMemoryCaching) {
return false; return false;
} }
} }
if (($doNotTestCacheValidity) || (is_null($this->_refreshTime))) { if (($doNotTestCacheValidity) || (is_null($this->_refreshTime))) {
if (file_exists($this->_file)) { if (file_exists($this->_file)) {
@ -380,7 +370,7 @@ class Cache_Lite
} }
return false; return false;
} }
/** /**
* Save some data in a cache file * Save some data in a cache file
* *
@ -406,24 +396,24 @@ class Cache_Lite
} }
} }
if ($this->_automaticCleaningFactor>0 && ($this->_automaticCleaningFactor==1 || mt_rand(1, $this->_automaticCleaningFactor)==1)) { if ($this->_automaticCleaningFactor>0 && ($this->_automaticCleaningFactor==1 || mt_rand(1, $this->_automaticCleaningFactor)==1)) {
$this->clean(false, 'old'); $this->clean(false, 'old');
} }
if ($this->_writeControl) { if ($this->_writeControl) {
$res = $this->_writeAndControl($data); $res = $this->_writeAndControl($data);
if (is_bool($res)) { if (is_bool($res)) {
if ($res) { if ($res) {
return true; return true;
} }
// if $res if false, we need to invalidate the cache // if $res if false, we need to invalidate the cache
@touch($this->_file, time() - 2*abs($this->_lifeTime)); @touch($this->_file, time() - 2*abs($this->_lifeTime));
return false; return false;
} }
} else { } else {
$res = $this->_write($data); $res = $this->_write($data);
} }
if (is_object($res)) { if (is_object($res)) {
// $res is a PEAR_Error object // $res is a PEAR_Error object
if (!($this->_errorHandlingAPIBreak)) { if (!($this->_errorHandlingAPIBreak)) {
return false; // we return false (old API) return false; // we return false (old API)
} }
} }
@ -466,7 +456,7 @@ class Cache_Lite
* else only cache files of the specified group will be destroyed * else only cache files of the specified group will be destroyed
* *
* @param string $group name of the cache group * @param string $group name of the cache group
* @param string $mode flush cache mode : 'old', 'ingroup', 'notingroup', * @param string $mode flush cache mode : 'old', 'ingroup', 'notingroup',
* 'callback_myFunction' * 'callback_myFunction'
* @return boolean true if no problem * @return boolean true if no problem
* @access public * @access public
@ -475,12 +465,12 @@ class Cache_Lite
{ {
return $this->_cleanDir($this->_cacheDir, $group, $mode); return $this->_cleanDir($this->_cacheDir, $group, $mode);
} }
/** /**
* Set to debug mode * Set to debug mode
* *
* When an error is found, the script will stop and the message will be displayed * When an error is found, the script will stop and the message will be displayed
* (in debug mode only). * (in debug mode only).
* *
* @access public * @access public
*/ */
@ -538,7 +528,7 @@ class Cache_Lite
} }
} }
} }
/** /**
* Return the cache last modification time * Return the cache last modification time
* *
@ -546,11 +536,11 @@ class Cache_Lite
* *
* @return int last modification time * @return int last modification time
*/ */
function lastModified() function lastModified()
{ {
return @filemtime($this->_file); return @filemtime($this->_file);
} }
/** /**
* Trigger a PEAR error * Trigger a PEAR error
* *
@ -564,29 +554,30 @@ 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);
} }
/** /**
* Extend the life of a valid cache file * Extend the life of a valid cache file
* *
* see http://pear.php.net/bugs/bug.php?id=6681 * see http://pear.php.net/bugs/bug.php?id=6681
* *
* @access public * @access public
*/ */
function extendLife() function extendLife()
{ {
@touch($this->_file); @touch($this->_file);
} }
// --- Private methods --- // --- Private methods ---
/** /**
* Compute & set the refresh time * Compute & set the refresh time
* *
* @access private * @access private
*/ */
function _setRefreshTime() function _setRefreshTime()
{ {
if (is_null($this->_lifeTime)) { if (is_null($this->_lifeTime)) {
$this->_refreshTime = null; $this->_refreshTime = null;
@ -594,10 +585,10 @@ class Cache_Lite
$this->_refreshTime = time() - $this->_lifeTime; $this->_refreshTime = time() - $this->_lifeTime;
} }
} }
/** /**
* Remove a file * Remove a file
* *
* @param string $file complete file path and name * @param string $file complete file path and name
* @return boolean true if no problem * @return boolean true if no problem
* @access private * @access private
@ -607,7 +598,7 @@ class Cache_Lite
if (!@unlink($file)) { if (!@unlink($file)) {
return $this->raiseError('Cache_Lite : Unable to remove cache !', -3); return $this->raiseError('Cache_Lite : Unable to remove cache !', -3);
} }
return true; return true;
} }
/** /**
@ -620,7 +611,7 @@ class Cache_Lite
* @return boolean true if no problem * @return boolean true if no problem
* @access private * @access private
*/ */
function _cleanDir($dir, $group = false, $mode = 'ingroup') function _cleanDir($dir, $group = false, $mode = 'ingroup')
{ {
if ($this->_fileNameProtection) { if ($this->_fileNameProtection) {
$motif = ($group) ? 'cache_'.md5($group).'_' : 'cache_'; $motif = ($group) ? 'cache_'.md5($group).'_' : 'cache_';
@ -638,7 +629,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;
@ -707,10 +698,8 @@ 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) {
$key = key($this->_memoryCachingArray); list($key, ) = each($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;
} }
@ -725,7 +714,7 @@ class Cache_Lite
*/ */
function _setFileName($id, $group) function _setFileName($id, $group)
{ {
if ($this->_fileNameProtection) { if ($this->_fileNameProtection) {
$suffix = 'cache_'.md5($group).'_'.md5($id); $suffix = 'cache_'.md5($group).'_'.md5($id);
} else { } else {
@ -736,12 +725,12 @@ class Cache_Lite
$hash = md5($suffix); $hash = md5($suffix);
for ($i=0 ; $i<$this->_hashedDirectoryLevel ; $i++) { for ($i=0 ; $i<$this->_hashedDirectoryLevel ; $i++) {
$root = $root . 'cache_' . substr($hash, 0, $i + 1) . '/'; $root = $root . 'cache_' . substr($hash, 0, $i + 1) . '/';
} }
} }
$this->_fileName = $suffix; $this->_fileName = $suffix;
$this->_file = $root.$suffix; $this->_file = $root.$suffix;
} }
/** /**
* Read the cache file and return the content * Read the cache file and return the content
* *
@ -755,7 +744,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 = (function_exists('get_magic_quotes_runtime') ? @get_magic_quotes_runtime() : 0); $mqr = get_magic_quotes_runtime();
if ($mqr) { if ($mqr) {
set_magic_quotes_runtime(0); set_magic_quotes_runtime(0);
} }
@ -781,7 +770,7 @@ class Cache_Lite
$hashData = $this->_hash($data, $this->_readControlType); $hashData = $this->_hash($data, $this->_readControlType);
if ($hashData != $hashControl) { if ($hashData != $hashControl) {
if (!(is_null($this->_lifeTime))) { if (!(is_null($this->_lifeTime))) {
@touch($this->_file, time() - 2*abs($this->_lifeTime)); @touch($this->_file, time() - 2*abs($this->_lifeTime));
} else { } else {
@unlink($this->_file); @unlink($this->_file);
} }
@ -790,9 +779,9 @@ class Cache_Lite
} }
return $data; return $data;
} }
return $this->raiseError('Cache_Lite : Unable to read cache !', -2); return $this->raiseError('Cache_Lite : Unable to read cache !', -2);
} }
/** /**
* Write the given data in the cache file * Write the given data in the cache file
* *
@ -819,7 +808,7 @@ class Cache_Lite
} }
// if both _cacheFileMode and _cacheFileGroup is null, then we don't need to call // if both _cacheFileMode and _cacheFileGroup is null, then we don't need to call
// file_exists (see below: if ($is_newfile) ...) // file_exists (see below: if ($is_newfile) ...)
$is_newfile = (! is_null($this->_cacheFileMode) || !is_null($this->_cacheFileGroup)) $is_newfile = (! is_null($this->_cacheFileMode) || !is_null($this->_cacheFileGroup))
&& ! @file_exists($this->_file); && ! @file_exists($this->_file);
$fp = @fopen($this->_file, "wb"); $fp = @fopen($this->_file, "wb");
if ($fp) { if ($fp) {
@ -834,7 +823,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 = (function_exists('get_magic_quotes_runtime') ? @get_magic_quotes_runtime() : 0); $mqr = get_magic_quotes_runtime();
if ($mqr) { if ($mqr) {
set_magic_quotes_runtime(0); set_magic_quotes_runtime(0);
} }
@ -845,10 +834,10 @@ class Cache_Lite
if ($this->_fileLocking) @flock($fp, LOCK_UN); if ($this->_fileLocking) @flock($fp, LOCK_UN);
@fclose($fp); @fclose($fp);
return true; return true;
} }
return $this->raiseError('Cache_Lite : Unable to write cache file : '.$this->_file, -1); return $this->raiseError('Cache_Lite : Unable to write cache file : '.$this->_file, -1);
} }
/** /**
* Write the given data in the cache file and control it just after to avoir corrupted cache entries * Write the given data in the cache file and control it just after to avoir corrupted cache entries
* *
@ -867,11 +856,11 @@ class Cache_Lite
return $dataRead; # We return the PEAR_Error object return $dataRead; # We return the PEAR_Error object
} }
if ((is_bool($dataRead)) && (!$dataRead)) { if ((is_bool($dataRead)) && (!$dataRead)) {
return false; return false;
} }
return ($dataRead==$data); return ($dataRead==$data);
} }
/** /**
* Make a control key with the string containing datas * Make a control key with the string containing datas
* *
@ -893,5 +882,5 @@ class Cache_Lite
return $this->raiseError('Unknown controlType ! (available values are only \'md5\', \'crc32\', \'strlen\')', -5); return $this->raiseError('Unknown controlType ! (available values are only \'md5\', \'crc32\', \'strlen\')', -5);
} }
} }
} }

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 __construct($options = array(NULL)) function Cache_Lite_File($options = array(NULL))
{ {
$options['lifetime'] = 0; $options['lifetime'] = 0;
parent::__construct($options); $this->Cache_Lite($options);
if (isset($options['masterFile'])) { if (isset($options['masterFile'])) {
$this->_masterFile = $options['masterFile']; $this->_masterFile = $options['masterFile'];
} else { } else {
@ -65,16 +65,6 @@ class Cache_Lite_File extends Cache_Lite
return $this->raiseError('Cache_Lite_File : Unable to read masterFile : '.$this->_masterFile, -3); return $this->raiseError('Cache_Lite_File : Unable to read masterFile : '.$this->_masterFile, -3);
} }
} }
/**
* 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,27 +81,17 @@ class Cache_Lite_Function extends Cache_Lite
* @param array $options options * @param array $options options
* @access public * @access public
*/ */
function __construct($options = array(NULL)) function Cache_Lite_Function($options = array(NULL))
{ {
$availableOptions = array('debugCacheLiteFunction', 'defaultGroup', 'dontCacheWhenTheOutputContainsNOCACHE', 'dontCacheWhenTheResultIsFalse', 'dontCacheWhenTheResultIsNull'); $availableOptions = array('debugCacheLiteFunction', 'defaultGroup', 'dontCacheWhenTheOutputContainsNOCACHE', 'dontCacheWhenTheResultIsFalse', 'dontCacheWhenTheResultIsNull');
foreach ($options as $name => $value) { while (list($name, $value) = each($options)) {
if (in_array($name, $availableOptions)) { if (in_array($name, $availableOptions)) {
$property = '_'.$name; $property = '_'.$name;
$this->$property = $value; $this->$property = $value;
} }
} }
reset($options); reset($options);
parent::__construct($options); $this->Cache_Lite($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,19 +26,9 @@ class Cache_Lite_Output extends Cache_Lite
* @param array $options options * @param array $options options
* @access public * @access public
*/ */
function __construct($options) function Cache_Lite_Output($options)
{ {
parent::__construct($options); $this->Cache_Lite($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,25 +1,19 @@
# 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 execute To build, simply
pear package pear package
## Installation
### PEAR
To install from scratch To install from scratch
pear install package.xml pear install package.xml
@ -27,15 +21,3 @@ 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-2021 SYSTOPIA | | Copyright (C) 2015 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' => 'string'); 'h' => 'hex');
$parameters = civiproxy_get_parameters($valid_parameters); $parameters = civiproxy_get_parameters($valid_parameters);
// check if parameters specified // check if parameters specified
@ -45,6 +45,7 @@ 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-2021 SYSTOPIA | | Copyright (C) 2015 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', 'cid' => 'int', 'cs' => 'string' ); $valid_parameters = array( 'id' => 'int' );
$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-2021 SYSTOPIA | | Copyright (C) 2015 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-2021 SYSTOPIA | | Copyright (C) 2015 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' => 'string'); 'h' => 'hex');
$parameters = civiproxy_get_parameters($valid_parameters); $parameters = civiproxy_get_parameters($valid_parameters);
// check if parameters specified // check if parameters specified
@ -45,6 +45,7 @@ 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-2021 SYSTOPIA | | Copyright (C) 2015 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) | | Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ | | http://www.systopia.de/ |
+---------------------------------------------------------*/ +---------------------------------------------------------*/
@ -83,6 +83,7 @@ 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-2021 SYSTOPIA | | Copyright (C) 2015 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' => 'string'); 'h' => 'hex');
$parameters = civiproxy_get_parameters($valid_parameters); $parameters = civiproxy_get_parameters($valid_parameters);
// check if parameters specified // check if parameters specified
@ -45,6 +45,7 @@ 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-2021 SYSTOPIA | | Copyright (C) 2017 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) | | Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ | | http://www.systopia.de/ |
+---------------------------------------------------------*/ +---------------------------------------------------------*/
@ -17,69 +17,51 @@ 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', 'template_url' => 'string' ); $valid_parameters = array('id' => 'string', 'ph' => 'string');
$parameters = civiproxy_get_parameters($valid_parameters); $parameters = civiproxy_get_parameters($valid_parameters);
// check if id or ph
if (!empty($parameters['id'])) { if (!empty($parameters['id'])) {
// check restrictions // that's a regular image resource
if (!empty($file_cache_exclude)) { $type = 'image';
foreach ($file_cache_exclude as $pattern) { $reqd = $parameters['id'];
if (preg_match($pattern, $parameters['id'])) { } elseif (!empty($parameters['ph'])) {
civiproxy_http_error("Invalid Resource", 403); // that's a placeholder
} $type = 'placeholder';
} $reqd = $parameters['ph'];
}
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);
}
}
// look up the required resource
$header_key = 'header&' . $parameters['id'];
$data_key = 'data&' . $parameters['id'];
$url = $target_mosaico . $parameters['id'];
} 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 (!empty($file_cache_include)) {
$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 { } else {
civiproxy_http_error("Resource not found"); civiproxy_http_error("Resource not found");
} }
// check restrictions
if (!empty($file_cache_exclude)) {
foreach ($file_cache_exclude as $pattern) {
if (preg_match($pattern, $reqd)) {
civiproxy_http_error("Invalid Resource", 403);
}
}
}
if (!empty($file_cache_include)) {
$accept_id = FALSE;
foreach ($file_cache_include as $pattern) {
if (preg_match($pattern, $reqd)) {
$accept_id = TRUE;
}
}
if (!$accept_id) {
civiproxy_http_error("Invalid Resource", 403);
}
}
// load PEAR file cache // load PEAR file cache
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . 'libs'); ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . 'libs');
if (!file_exists($file_cache_options['cacheDir'])) mkdir($file_cache_options['cacheDir']); if (!file_exists($file_cache_options['cacheDir'])) mkdir($file_cache_options['cacheDir']);
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&' . $reqd;
$data_key = 'data&' . $reqd;
$header = $file_cache->get($header_key); $header = $file_cache->get($header_key);
$data = $file_cache->get($data_key); $data = $file_cache->get($data_key);
@ -96,6 +78,16 @@ if ($header && $data) {
} }
// if we get here, we have a cache miss => load // if we get here, we have a cache miss => load
if ($type == 'image') {
// that's a regular image resource
$url = $target_mosaico . $reqd;
} else {
// that's a placeholder
$target_placeholder = str_replace('img?src=', 'img?method=placeholder&params=', $target_mosaico);
$url = $target_placeholder . $reqd;
}
// run the query
$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);

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-2021 SYSTOPIA | | Copyright (C) 2015 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) | | Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ | | http://www.systopia.de/ |
+---------------------------------------------------------*/ +---------------------------------------------------------*/
@ -16,5 +16,8 @@ if (!$target_open) civiproxy_http_error("Feature disabled", 405);
// basic check // basic check
civiproxy_security_check('open'); civiproxy_security_check('open');
$parameters = civiproxy_get_parameters($valid_open_parameters); // basic restraints
$valid_parameters = array( 'q' => 'int' );
$parameters = civiproxy_get_parameters($valid_parameters);
civiproxy_redirect($target_open, $parameters); civiproxy_redirect($target_open, $parameters);

View File

@ -2,13 +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-2021 SYSTOPIA | | Copyright (C) 2015 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 = '1.0.0-beta'; $civiproxy_version = '0.6-dev';
/** /**
* this will redirect the request to another URL, * this will redirect the request to another URL,
@ -90,148 +90,6 @@ 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,
@ -273,12 +131,11 @@ function civiproxy_mend_URLs(&$string) {
* unauthorized access quantities, etc. * unauthorized access quantities, etc.
* *
* @param $target * @param $target
* @param $quit bool if TRUE, quit immediately if access denied * @param $quit 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, $log_headers = []) { function civiproxy_security_check($target, $quit=TRUE) {
// 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);
@ -288,16 +145,11 @@ function civiproxy_security_check($target, $quit=TRUE, $log_headers = []) {
if (!empty($debug)) { if (!empty($debug)) {
// filter log data // filter log data
$log_data = $_REQUEST; $log_data = $_REQUEST;
$sanitize_params = ['api_key', 'key', '_authxSiteKey', '_authx']; if (isset($log_data['api_key'])) {
foreach ($sanitize_params as $param) { $log_data['api_key'] = substr($log_data['api_key'], 0, 4) . '...';
if (isset($log_data[$param])) {
$log_data[$param] = substr($log_data[$param], 0, 4) . '...';
}
} }
if (isset($log_data['key'])) {
foreach($log_headers as $header) { $log_data['key'] = substr($log_data['key'], 0, 4) . '...';
if (!empty($_SERVER[$header]))
$log_data[$header] = substr($_SERVER[$header], 0, 4) . '...';
} }
// log // log
@ -353,7 +205,7 @@ function civiproxy_get_parameters($valid_parameters, $request = NULL) {
// 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', '_authx', '_authxSiteKey', 'version', 'entity', 'action'); $remove_parameters = array('key', 'api_key', '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);
@ -364,26 +216,6 @@ function civiproxy_get_parameters($valid_parameters, $request = NULL) {
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
*/ */

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-2021 SYSTOPIA | | Copyright (C) 2015 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,9 +21,25 @@ 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");
}
}
civiproxy_map_site_key($credentials, $sys_key_map); if (empty($credentials['api_key'])) {
civiproxy_map_api_key($credentials, $api_key_map); 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");
}
}
// 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'));
@ -31,7 +47,22 @@ if (!isset($action['version']) || $action['version'] != 3) {
civiproxy_rest_error("API 'version' information missing."); civiproxy_rest_error("API 'version' information missing.");
} }
$valid_parameters= civiproxy_get_valid_parameters($action, $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.");
}
}
// 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);
@ -55,5 +86,18 @@ if ($rest_evaluate_json_parameter) {
} }
// finally execute query // finally execute query
civiproxy_log($target_rest);
civiproxy_redirect($target_rest, $parameters); civiproxy_redirect($target_rest, $parameters);
/**
* 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();
}

View File

@ -1,89 +0,0 @@
<?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-2021 SYSTOPIA | | Copyright (C) 2015 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) | | Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ | | http://www.systopia.de/ |
+---------------------------------------------------------*/ +---------------------------------------------------------*/
@ -16,5 +16,10 @@ if (!$target_url) civiproxy_http_error("Feature disabled", 405);
// basic check // basic check
civiproxy_security_check('url'); civiproxy_security_check('url');
$parameters = civiproxy_get_parameters($valid_url_parameters); // basic restraints
$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);

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) 2019-2021 SYSTOPIA | | Copyright (C) 2019 SYSTOPIA |
| Author: B. Endres (endres -at- systopia.de) | | Author: B. Endres (endres -at- systopia.de) |
| http://www.systopia.de/ | | http://www.systopia.de/ |
+---------------------------------------------------------*/ +---------------------------------------------------------*/
@ -32,6 +32,7 @@ if (!empty($_REQUEST['id']) && isset($webhook2api['configurations'][$_REQUEST['i
// read some input // read some input
$post_input = @file_get_contents('php://input'); $post_input = @file_get_contents('php://input');
error_log("DEBUG: " . json_encode($post_input));
// MAIN: iterate through all (eligible) configurations // MAIN: iterate through all (eligible) configurations
$last_error = ["No handler found", 501]; $last_error = ["No handler found", 501];
@ -84,10 +85,12 @@ function webhook2api_processConfiguration($configuration, $post_input) {
// gather source data // gather source data
$data = []; $data = [];
if (!empty($configuration['data_sources']) && is_array($configuration['data_sources'])) { if (!empty($configuration['data_sources']) && is_array($configuration['data_sources'])) {
error_log(json_encode($configuration));
foreach ($configuration['data_sources'] as $data_source) { foreach ($configuration['data_sources'] as $data_source) {
switch ($data_source) { switch ($data_source) {
case 'POST/json': # JSON data in POST field case 'POST/json': # JSON data in POST field
$more_data = json_decode($post_input, TRUE); $more_data = json_decode($post_input, TRUE);
error_log(json_encode($more_data));
$data = array_merge_recursive($data, $more_data); $data = array_merge_recursive($data, $more_data);
break; break;
case 'REQUEST': # simple request parameters case 'REQUEST': # simple request parameters
@ -106,8 +109,8 @@ function webhook2api_processConfiguration($configuration, $post_input) {
foreach ($data as $d) { foreach ($data as $d) {
$result = webhook2api_callCiviApi($configuration, $d); $result = webhook2api_callCiviApi($configuration, $d);
if(isset($result['internal_error'])) { if(isset($result['internal_error'])) {
// internal communication Error occurred. Aborting process // internal communication Error occured. Aborting process
civiproxy_log("Webhook2API[{$configuration['name']}]: internal error occurred: " . json_encode($result['internal_error'])); civiproxy_log("Webhook2API[{$configuration['name']}]: internal error occured: " . json_encode($result['internal_error']));
return $result['internal_error']; return $result['internal_error'];
} }
if (!empty($result['values']['http_code'])) { if (!empty($result['values']['http_code'])) {
@ -120,30 +123,30 @@ function webhook2api_processConfiguration($configuration, $post_input) {
} else { } else {
$result = webhook2api_callCiviApi($configuration, $data); $result = webhook2api_callCiviApi($configuration, $data);
if(isset($result['internal_error'])) { if(isset($result['internal_error'])) {
// internal communication Error occurred. Aborting process // internal communication Error occured. Aborting process
civiproxy_log("Webhook2API[{$configuration['name']}]: internal error occurred: " . json_encode($result['internal_error'])); civiproxy_log("Webhook2API[{$configuration['name']}]: internal error occured: " . json_encode($result['internal_error']));
return $result['internal_error']; return $result['internal_error'];
} }
if (!empty($result['values']['http_code'])) { if (!empty($result['values']['http_code'])) {
$http_code = $result['values']['http_code']; $http_code = $result['values']['http_code'];
} elseif ($result['is_error'] != 0) { } else {
$http_code = 403; $http_code = 403;
} }
} }
if ($http_code != '200') { if ($http_code != '200') {
// we received and parsed the webhook event successfully, but an error occurred with civicrm: // we received and parsed the webhook event successfully, but an error occured with civicrm:
civiproxy_log("Webhook2API[{$configuration['name']}]: Internal CiviCRM Error. Error Code: {$http_code}. Full Message: " . json_encode($result)); civiproxy_log("Webhook2API[{$configuration['name']}]: Internal CiviCRM Error. Error Code: {$http_code}. Full Message: " . json_encode($result));
} }
// process result // process result
if (!empty($configuration['response_mapping']) && is_array($configuration['response_mapping'])) { if (!empty($configuration['response_mapping']) && is_array($configuration['response_mapping'])) {
// TODO: implement // TODO: implement
//error_log("Webhook2API.response_mapping: not implemented!");
http_response_code('200'); http_response_code('200');
civiproxy_log("Webhook successful, response mapped.");
} else { } else {
// default behaviour: // default behaviour:
http_response_code('200'); http_response_code('200');
civiproxy_log("Webhook successful.");
} }
// all done // all done
exit(); exit();
@ -174,7 +177,7 @@ function webhook2api_callCiviApi($configuration, $data) {
} else { } else {
echo "Error"; echo "Error";
// unknown instruction // unknown instruction
civiproxy_log("Webhook2API[{$configuration['name']}]: don't understand sentinel '{$check}'. Ignored."); // //error_log("Webhook2API[{$configuration['name']}]: don't understad sentinel '{$check}'. Ignored.");
} }
} }
} }
@ -193,8 +196,7 @@ function webhook2api_callCiviApi($configuration, $data) {
// run modifiers // run modifiers
foreach ($modifiers as $modifier) { foreach ($modifiers as $modifier) {
// TODO: implement // TODO: implement
//error_log("Webhook2API.modifiers: not implemented!");
civiproxy_log("Webhook2API.modifiers: not implemented!");
} }
// set to target // set to target
@ -207,16 +209,16 @@ function webhook2api_callCiviApi($configuration, $data) {
// sanitise data // sanitise data
if (!empty($configuration['parameter_sanitation']) && is_array($configuration['parameter_sanitation'])) { if (!empty($configuration['parameter_sanitation']) && is_array($configuration['parameter_sanitation'])) {
// TODO: implement // TODO: implement
civiproxy_log("Webhook2API.sanitation: not implemented!"); //error_log("Webhook2API.sanitation: not implemented!");
} }
// send to target REST API // send to target REST API
if (empty($configuration['entity']) || empty($configuration['action'])) { if (empty($configuration['entity']) || empty($configuration['action'])) {
civiproxy_log("Webhook2API[{$configuration['name']}]: Missing entity/action."); //error_log("Webhook2API[{$configuration['name']}]: Missing entity/action.");
return ["internal_error" => "Configuration error", 403]; return ["internal_error" => "Configuration error", 403];
} }
if (empty($configuration['api_key'])) { if (empty($configuration['api_key'])) {
civiproxy_log("Webhook2API[{$configuration['name']}]: Missing api_key."); //error_log("Webhook2API[{$configuration['name']}]: Missing api_key.");
return ["internal_error" => "Configuration error", 403]; return ["internal_error" => "Configuration error", 403];
} }
$params['api_key'] = $configuration['api_key']; $params['api_key'] = $configuration['api_key'];