diff --git a/CRM/Emailamender.php b/CRM/Emailamender.php index 185ef73..ae46145 100644 --- a/CRM/Emailamender.php +++ b/CRM/Emailamender.php @@ -94,7 +94,7 @@ public function is_autocorrect_enabled() { * * @return bool correction took place * - * @throws \CiviCRM_API3_Exception + * @throws \CRM_Core_Exception */ public function fixEmailAddress($iEmailId, $iContactId, $sRawEmail) { @@ -136,7 +136,7 @@ public function fixEmailAddress($iEmailId, $iContactId, $sRawEmail) { // Recalculate display name. civicrm_api3('Contact', 'create', ['id' => $iContactId]); } - catch (CiviCRM_API3_Exception $e) { + catch (CRM_Core_Exception $e) { CRM_Core_Session::setStatus(ts("Error when correcting email - contact ID $iContactId"), ts('Email Address Corrector'), 'error'); throw $e; } diff --git a/CRM/Emailamender/Page/EmailAmenderSettings.php b/CRM/Emailamender/Page/EmailAmenderSettings.php index 4ec31c1..7eb9626 100755 --- a/CRM/Emailamender/Page/EmailAmenderSettings.php +++ b/CRM/Emailamender/Page/EmailAmenderSettings.php @@ -14,7 +14,8 @@ function run() { $this->assign('compound_top_level_domains', Civi::settings()->get('emailamender.compound_top_level_domains')); $this->assign('equivalent_domain_settings', Civi::settings()->get('emailamender.equivalent_domains')); - + $this->assign('hasEditPermission', CRM_Core_Permission::check('administer_email_amender')); + $this->assign('hasEnablePermission', CRM_Core_Permission::check('administer CiviCRM')); parent::run(); } } diff --git a/CRM/Emailamender/Upgrader.php b/CRM/Emailamender/Upgrader.php index 8255348..8874d7b 100644 --- a/CRM/Emailamender/Upgrader.php +++ b/CRM/Emailamender/Upgrader.php @@ -3,7 +3,7 @@ /** * Collection of upgrade steps */ -class CRM_Emailamender_Upgrader extends CRM_Emailamender_Upgrader_Base { +class CRM_Emailamender_Upgrader extends CRM_Extension_Upgrader_Base { // By convention, functions that look like "function upgrade_NNNN()" are // upgrade tasks. They are executed in order (like Drupal's hook_update_N). diff --git a/CRM/Emailamender/Upgrader/Base.php b/CRM/Emailamender/Upgrader/Base.php deleted file mode 100644 index aeb6dd3..0000000 --- a/CRM/Emailamender/Upgrader/Base.php +++ /dev/null @@ -1,298 +0,0 @@ -ctx = array_shift($args); - $instance->queue = $instance->ctx->queue; - $method = array_shift($args); - return call_user_func_array(array($instance, $method), $args); - } - - public function __construct($extensionName, $extensionDir) { - $this->extensionName = $extensionName; - $this->extensionDir = $extensionDir; - } - - // ******** Task helpers ******** - - /** - * Run a CustomData file - * - * @param string $relativePath the CustomData XML file path (relative to this extension's dir) - * @return bool - */ - public function executeCustomDataFile($relativePath) { - $xml_file = $this->extensionDir . '/' . $relativePath; - return $this->executeCustomDataFileByAbsPath($xml_file); - } - - /** - * Run a CustomData file - * - * @param string $xml_file the CustomData XML file path (absolute path) - * @return bool - */ - protected static function executeCustomDataFileByAbsPath($xml_file) { - require_once 'CRM/Utils/Migrate/Import.php'; - $import = new CRM_Utils_Migrate_Import(); - $import->run($xml_file); - return TRUE; - } - - /** - * Run a SQL file - * - * @param string $relativePath the SQL file path (relative to this extension's dir) - * @return bool - */ - public function executeSqlFile($relativePath) { - CRM_Utils_File::sourceSQLFile( - CIVICRM_DSN, - $this->extensionDir . '/' . $relativePath - ); - return TRUE; - } - - /** - * Run one SQL query - * - * This is just a wrapper for CRM_Core_DAO::executeSql, but it - * provides syntatic sugar for queueing several tasks that - * run different queries - */ - public function executeSql($query, $params = array()) { - // FIXME verify that we raise an exception on error - CRM_Core_DAO::executeSql($query, $params); - return TRUE; - } - - /** - * Syntatic sugar for enqueuing a task which calls a function - * in this class. The task is weighted so that it is processed - * as part of the currently-pending revision. - * - * After passing the $funcName, you can also pass parameters that will go to - * the function. Note that all params must be serializable. - */ - public function addTask($title) { - $args = func_get_args(); - $title = array_shift($args); - $task = new CRM_Queue_Task( - array(get_class($this), '_queueAdapter'), - $args, - $title - ); - return $this->queue->createItem($task, array('weight' => -1)); - } - - // ******** Revision-tracking helpers ******** - - /** - * Determine if there are any pending revisions - * - * @return bool - */ - public function hasPendingRevisions() { - $revisions = $this->getRevisions(); - $currentRevision = $this->getCurrentRevision(); - - if (empty($revisions)) { - return FALSE; - } - if (empty($currentRevision)) { - return TRUE; - } - - return ($currentRevision < max($revisions)); - } - - /** - * Add any pending revisions to the queue - */ - public function enqueuePendingRevisions(CRM_Queue_Queue $queue) { - $this->queue = $queue; - - $currentRevision = $this->getCurrentRevision(); - foreach ($this->getRevisions() as $revision) { - if ($revision > $currentRevision) { - $title = ts('Upgrade %1 to revision %2', array( - 1 => $this->extensionName, - 2 => $revision, - )); - - // note: don't use addTask() because it sets weight=-1 - - $task = new CRM_Queue_Task( - array(get_class($this), '_queueAdapter'), - array('upgrade_' . $revision), - $title - ); - $this->queue->createItem($task); - - $task = new CRM_Queue_Task( - array(get_class($this), '_queueAdapter'), - array('setCurrentRevision', $revision), - $title - ); - $this->queue->createItem($task); - } - } - } - - /** - * Get a list of revisions - * - * @return array(revisionNumbers) sorted numerically - */ - public function getRevisions() { - if (! is_array($this->revisions)) { - $this->revisions = array(); - - $clazz = new ReflectionClass(get_class($this)); - $methods = $clazz->getMethods(); - foreach ($methods as $method) { - if (preg_match('/^upgrade_(.*)/', $method->name, $matches)) { - $this->revisions[] = $matches[1]; - } - } - sort($this->revisions, SORT_NUMERIC); - } - - return $this->revisions; - } - - public function getCurrentRevision() { - // return CRM_Core_BAO_Extension::getSchemaVersion($this->extensionName); - $key = $this->extensionName . ':version'; - return Civi::settings()->get($key); - } - - public function setCurrentRevision($revision) { - // We call this during hook_civicrm_install, but the underlying SQL - // UPDATE fails because the extension record hasn't been INSERTed yet. - // Instead, track revisions in our own namespace. - // CRM_Core_BAO_Extension::setSchemaVersion($this->extensionName, $revision); - - $key = $this->extensionName . ':version'; - Civi::settings()->set($key, $revision); - return TRUE; - } - - // ******** Hook delegates ******** - - public function onInstall() { - $files = glob($this->extensionDir . '/sql/*_install.sql'); - if (is_array($files)) { - foreach ($files as $file) { - CRM_Utils_File::sourceSQLFile(CIVICRM_DSN, $file); - } - } - $files = glob($this->extensionDir . '/xml/*_install.xml'); - if (is_array($files)) { - foreach ($files as $file) { - $this->executeCustomDataFileByAbsPath($file); - } - } - if (is_callable(array($this, 'install'))) { - $this->install(); - } - $revisions = $this->getRevisions(); - if (!empty($revisions)) { - $this->setCurrentRevision(max($revisions)); - } - } - - public function onUninstall() { - if (is_callable(array($this, 'uninstall'))) { - $this->uninstall(); - } - $files = glob($this->extensionDir . '/sql/*_uninstall.sql'); - if (is_array($files)) { - foreach ($files as $file) { - CRM_Utils_File::sourceSQLFile(CIVICRM_DSN, $file); - } - } - $this->setCurrentRevision(NULL); - } - - public function onEnable() { - // stub for possible future use - if (is_callable(array($this, 'enable'))) { - $this->enable(); - } - } - - public function onDisable() { - // stub for possible future use - if (is_callable(array($this, 'disable'))) { - $this->disable(); - } - } - - public function onUpgrade($op, CRM_Queue_Queue $queue = NULL) { - switch($op) { - case 'check': - return array($this->hasPendingRevisions()); - case 'enqueue': - return $this->enqueuePendingRevisions($queue); - default: - } - } -} diff --git a/Managed/ActivityType.mgd.php b/Managed/ActivityType.mgd.php new file mode 100644 index 0000000..a25df8d --- /dev/null +++ b/Managed/ActivityType.mgd.php @@ -0,0 +1,23 @@ + 'ActivityType - corrected_email_address', + 'entity' => 'OptionValue', + 'cleanup' => 'unused', + 'update' => 'unmodified', + 'params' => [ + 'version' => 4, + 'match' => ['option_group_id', 'name'], + 'values' => [ + 'label' => E::ts('Corrected Email Address'), + 'name' => 'corrected_email_address', + 'description' => 'Automatically corrected emails (by the Email Address Corrector extension).', + 'option_group_id:name' => 'activity_type', + 'filter' => 1, + ], + ], + ], +]; diff --git a/Managed/Navigation.mgd.php b/Managed/Navigation.mgd.php new file mode 100644 index 0000000..8d907fb --- /dev/null +++ b/Managed/Navigation.mgd.php @@ -0,0 +1,34 @@ +addSelect('id') + ->execute(); +foreach ($domains as $domain) { + $menuItems[] = [ + 'name' => 'EmailAmenderSettings', + 'entity' => 'Navigation', + 'cleanup' => 'always', + 'update' => 'unmodified', + 'params' => [ + 'version' => 4, + 'values' => [ + 'label' => E::ts('Email Address Corrector Settings'), + 'name' => 'EmailAmenderSettings', + 'url' => 'civicrm/emailamendersettings', + 'permission' => NULL, + 'permission_operator' => 'OR', + 'parent_id.name' => 'System Settings', + 'is_active' => TRUE, + 'has_separator' => 2, + 'weight' => 15, + 'domain_id' => $domain['id'], + ], + 'match' => ['domain_id', 'name'], + ], + ]; +} +return $menuItems; diff --git a/README.md b/README.md index 15a2e27..d30353f 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ This can increase the reach of your mass mailings and can prevent your organisat * Automatic correction of email addresses is disabled by default, to give you a chance to review the rules before enabling it. * These settings are available under Administrator -> System Settings -> Email Address Corrector Settings. -### 2. Mass correction of existing email addresses. +### 2. Mass correction of existing email addresses. * This extension also offers mass updating of existing email through the "Email - correct email addresses" advanced search task. * Uses the correction rules set under Administrator -> System Settings -> Email Address Corrector Settings. diff --git a/api/v3/EmailAmender/FindCandidates.php b/api/v3/EmailAmender/FindCandidates.php index 732c2cc..2add284 100644 --- a/api/v3/EmailAmender/FindCandidates.php +++ b/api/v3/EmailAmender/FindCandidates.php @@ -19,8 +19,7 @@ function _civicrm_api3_email_amender_find_candidates_spec(&$spec) { * * @return array API result descriptor * - * @throws \CiviCRM_API3_Exception - * @throws \API_Exception + * @throws \CRM_Core_Exception * * @see civicrm_api3_create_success */ @@ -36,7 +35,7 @@ function civicrm_api3_email_amender_find_candidates($params) { // edge cases like gmai@gmai.gmai.com but it feels like it can stay out of scope of this // api at this stage. $values = CRM_Core_DAO::executeQuery(" - SELECT id, contact_id, email FROM civicrm_email + SELECT id, contact_id, email FROM civicrm_email WHERE email REGEXP '\.({$topLevelDomainList})$' OR email REGEXP '@({$secondLevelDomainList})\\\.' LIMIT " . $options['limit'] diff --git a/api/v3/EmailAmender/FixEmail.php b/api/v3/EmailAmender/FixEmail.php index aaa8243..16cc07f 100644 --- a/api/v3/EmailAmender/FixEmail.php +++ b/api/v3/EmailAmender/FixEmail.php @@ -19,7 +19,7 @@ function _civicrm_api3_email_amender_fix_email_spec(&$spec) { * * @return array API result descriptor * - * @throws \CiviCRM_API3_Exception + * @throws \CRM_Core_Exception * * @see civicrm_api3_create_success */ diff --git a/api/v3/EmailAmender/UpdateCompoundTLDs.php b/api/v3/EmailAmender/UpdateCompoundTLDs.php index 0c95f9f..188677c 100755 --- a/api/v3/EmailAmender/UpdateCompoundTLDs.php +++ b/api/v3/EmailAmender/UpdateCompoundTLDs.php @@ -19,7 +19,7 @@ function _civicrm_api3_email_amender_update_compound_t_l_ds_spec(&$spec) { * @return array API result descriptor * @see civicrm_api3_create_success * @see civicrm_api3_create_error - * @throws API_Exception + * @throws \CRM_Core_Exception */ function civicrm_api3_email_amender_update_compound_t_l_ds($params) { @@ -33,4 +33,3 @@ function civicrm_api3_email_amender_update_compound_t_l_ds($params) { return civicrm_api3_create_success(array(), $params, 'EmailAmenderCompoundTLDs', 'Update'); } - diff --git a/api/v3/EmailAmender/UpdateCorrections.php b/api/v3/EmailAmender/UpdateCorrections.php index aaea15b..fee6e09 100755 --- a/api/v3/EmailAmender/UpdateCorrections.php +++ b/api/v3/EmailAmender/UpdateCorrections.php @@ -19,8 +19,8 @@ function _civicrm_api3_email_amender_update_corrections_spec(&$spec) { * @param array $params * @return array API result descriptor * @see civicrm_api3_create_success - * @see civicrm_api3_create_error - * @throws API_Exception + * + * @throws \CRM_Core_Exception */ function civicrm_api3_email_amender_update_corrections($params) { $aEscapedCorrections = []; @@ -42,9 +42,8 @@ function civicrm_api3_email_amender_update_corrections($params) { break; default: - throw new API_Exception(ts('Invalid domain amender setting update')); + throw new CRM_Core_Exception(ts('Invalid domain amender setting update')); } return civicrm_api3_create_success([], $params, 'EmailAmender', 'UpdateCorrections'); } - diff --git a/emailamender.civix.php b/emailamender.civix.php index fa004e6..a90c500 100755 --- a/emailamender.civix.php +++ b/emailamender.civix.php @@ -24,7 +24,7 @@ class CRM_Emailamender_ExtensionUtil { * Translated text. * @see ts */ - public static function ts($text, $params = []) { + public static function ts($text, $params = []): string { if (!array_key_exists('domain', $params)) { $params['domain'] = [self::LONG_NAME, NULL]; } @@ -41,7 +41,7 @@ public static function ts($text, $params = []) { * 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) { + public static function url($file = NULL): string { if ($file === NULL) { return rtrim(CRM_Core_Resources::singleton()->getUrl(self::LONG_NAME), '/'); } @@ -75,49 +75,61 @@ public static function findClass($suffix) { return self::CLASS_PREFIX . '_' . str_replace('\\', '_', $suffix); } + /** + * @return \CiviMix\Schema\SchemaHelperInterface + */ + public static function schema() { + if (!isset($GLOBALS['CiviMixSchema'])) { + pathload()->loadPackage('civimix-schema@5', TRUE); + } + return $GLOBALS['CiviMixSchema']->getHelper(static::LONG_NAME); + } + } use CRM_Emailamender_ExtensionUtil as E; +spl_autoload_register('_emailamender_civix_class_loader', TRUE, TRUE); + +function _emailamender_civix_class_loader($class) { + if ($class === 'CRM_Emailamender_DAO_Base') { + if (version_compare(CRM_Utils_System::version(), '5.74.beta', '>=')) { + class_alias('CRM_Core_DAO_Base', 'CRM_Emailamender_DAO_Base'); + // ^^ Materialize concrete names -- encourage IDE's to pick up on this association. + } + else { + $realClass = 'CiviMix\\Schema\\Emailamender\\DAO'; + class_alias($realClass, $class); + // ^^ Abstract names -- discourage IDE's from picking up on this association. + } + return; + } + + // This allows us to tap-in to the installation process (without incurring real file-reads on typical requests). + if (strpos($class, 'CiviMix\\Schema\\Emailamender\\') === 0) { + // civimix-schema@5 is designed for backported use in download/activation workflows, + // where new revisions may become dynamically available. + pathload()->loadPackage('civimix-schema@5', TRUE); + CiviMix\Schema\loadClass($class); + } +} + /** * (Delegated) Implements hook_civicrm_config(). * * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_config */ -function _emailamender_civix_civicrm_config(&$config = NULL) { +function _emailamender_civix_civicrm_config($config = NULL) { static $configured = FALSE; if ($configured) { return; } $configured = TRUE; - $template =& CRM_Core_Smarty::singleton(); - - $extRoot = dirname(__FILE__) . DIRECTORY_SEPARATOR; - $extDir = $extRoot . 'templates'; - - if (is_array($template->template_dir)) { - array_unshift($template->template_dir, $extDir); - } - else { - $template->template_dir = [$extDir, $template->template_dir]; - } - + $extRoot = __DIR__ . DIRECTORY_SEPARATOR; $include_path = $extRoot . PATH_SEPARATOR . get_include_path(); set_include_path($include_path); -} - -/** - * (Delegated) Implements hook_civicrm_xmlMenu(). - * - * @param $files array(string) - * - * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_xmlMenu - */ -function _emailamender_civix_civicrm_xmlMenu(&$files) { - foreach (_emailamender_civix_glob(__DIR__ . '/xml/Menu/*.xml') as $file) { - $files[] = $file; - } + // Based on , this does not currently require mixin/polyfill.php. } /** @@ -127,35 +139,7 @@ function _emailamender_civix_civicrm_xmlMenu(&$files) { */ function _emailamender_civix_civicrm_install() { _emailamender_civix_civicrm_config(); - if ($upgrader = _emailamender_civix_upgrader()) { - $upgrader->onInstall(); - } -} - -/** - * Implements hook_civicrm_postInstall(). - * - * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_postInstall - */ -function _emailamender_civix_civicrm_postInstall() { - _emailamender_civix_civicrm_config(); - if ($upgrader = _emailamender_civix_upgrader()) { - if (is_callable([$upgrader, 'onPostInstall'])) { - $upgrader->onPostInstall(); - } - } -} - -/** - * Implements hook_civicrm_uninstall(). - * - * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_uninstall - */ -function _emailamender_civix_civicrm_uninstall() { - _emailamender_civix_civicrm_config(); - if ($upgrader = _emailamender_civix_upgrader()) { - $upgrader->onUninstall(); - } + // Based on , this does not currently require mixin/polyfill.php. } /** @@ -163,212 +147,9 @@ function _emailamender_civix_civicrm_uninstall() { * * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_enable */ -function _emailamender_civix_civicrm_enable() { - _emailamender_civix_civicrm_config(); - if ($upgrader = _emailamender_civix_upgrader()) { - if (is_callable([$upgrader, 'onEnable'])) { - $upgrader->onEnable(); - } - } -} - -/** - * (Delegated) Implements hook_civicrm_disable(). - * - * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_disable - * @return mixed - */ -function _emailamender_civix_civicrm_disable() { +function _emailamender_civix_civicrm_enable(): void { _emailamender_civix_civicrm_config(); - if ($upgrader = _emailamender_civix_upgrader()) { - if (is_callable([$upgrader, 'onDisable'])) { - $upgrader->onDisable(); - } - } -} - -/** - * (Delegated) Implements 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 - * - * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_upgrade - */ -function _emailamender_civix_civicrm_upgrade($op, CRM_Queue_Queue $queue = NULL) { - if ($upgrader = _emailamender_civix_upgrader()) { - return $upgrader->onUpgrade($op, $queue); - } -} - -/** - * @return CRM_Emailamender_Upgrader - */ -function _emailamender_civix_upgrader() { - if (!file_exists(__DIR__ . '/CRM/Emailamender/Upgrader.php')) { - return NULL; - } - else { - return CRM_Emailamender_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 string $dir base dir - * @param string $pattern , glob pattern, eg "*.txt" - * - * @return array - */ -function _emailamender_civix_find_files($dir, $pattern) { - if (is_callable(['CRM_Utils_File', 'findFiles'])) { - return CRM_Utils_File::findFiles($dir, $pattern); - } - - $todos = [$dir]; - $result = []; - while (!empty($todos)) { - $subdir = array_shift($todos); - foreach (_emailamender_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) Implements hook_civicrm_managed(). - * - * Find any *.mgd.php files, merge their content, and return. - * - * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_managed - */ -function _emailamender_civix_civicrm_managed(&$entities) { - $mgdFiles = _emailamender_civix_find_files(__DIR__, '*.mgd.php'); - sort($mgdFiles); - foreach ($mgdFiles as $file) { - $es = include $file; - foreach ($es as $e) { - if (empty($e['module'])) { - $e['module'] = E::LONG_NAME; - } - if (empty($e['params']['version'])) { - $e['params']['version'] = '3'; - } - $entities[] = $e; - } - } -} - -/** - * (Delegated) Implements hook_civicrm_caseTypes(). - * - * Find any and return any files matching "xml/case/*.xml" - * - * Note: This hook only runs in CiviCRM 4.4+. - * - * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_caseTypes - */ -function _emailamender_civix_civicrm_caseTypes(&$caseTypes) { - if (!is_dir(__DIR__ . '/xml/case')) { - return; - } - - foreach (_emailamender_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)); - throw new CRM_Core_Exception($errorMessage); - } - $caseTypes[$name] = [ - 'module' => E::LONG_NAME, - 'name' => $name, - 'file' => $file, - ]; - } -} - -/** - * (Delegated) Implements hook_civicrm_angularModules(). - * - * Find any and return any files matching "ang/*.ang.php" - * - * Note: This hook only runs in CiviCRM 4.5+. - * - * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_angularModules - */ -function _emailamender_civix_civicrm_angularModules(&$angularModules) { - if (!is_dir(__DIR__ . '/ang')) { - return; - } - - $files = _emailamender_civix_glob(__DIR__ . '/ang/*.ang.php'); - foreach ($files as $file) { - $name = preg_replace(':\.ang\.php$:', '', basename($file)); - $module = include $file; - if (empty($module['ext'])) { - $module['ext'] = E::LONG_NAME; - } - $angularModules[$name] = $module; - } -} - -/** - * (Delegated) Implements hook_civicrm_themes(). - * - * Find any and return any files matching "*.theme.php" - */ -function _emailamender_civix_civicrm_themes(&$themes) { - $files = _emailamender_civix_glob(__DIR__ . '/*.theme.php'); - foreach ($files as $file) { - $themeMeta = include $file; - if (empty($themeMeta['name'])) { - $themeMeta['name'] = preg_replace(':\.theme\.php$:', '', basename($file)); - } - if (empty($themeMeta['ext'])) { - $themeMeta['ext'] = E::LONG_NAME; - } - $themes[$themeMeta['name']] = $themeMeta; - } -} - -/** - * 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. - * - * @link http://php.net/glob - * @param string $pattern - * - * @return array - */ -function _emailamender_civix_glob($pattern) { - $result = glob($pattern); - return is_array($result) ? $result : []; + // Based on , this does not currently require mixin/polyfill.php. } /** @@ -387,8 +168,8 @@ function _emailamender_civix_insert_navigation_menu(&$menu, $path, $item) { if (empty($path)) { $menu[] = [ 'attributes' => array_merge([ - 'label' => CRM_Utils_Array::value('name', $item), - 'active' => 1, + 'label' => $item['name'] ?? NULL, + 'active' => 1, ], $item), ]; return TRUE; @@ -452,26 +233,3 @@ function _emailamender_civix_fixNavigationMenuItems(&$nodes, &$maxNavID, $parent } } } - -/** - * (Delegated) Implements hook_civicrm_alterSettingsFolders(). - * - * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_alterSettingsFolders - */ -function _emailamender_civix_civicrm_alterSettingsFolders(&$metaDataFolders = NULL) { - $settingsDir = __DIR__ . DIRECTORY_SEPARATOR . 'settings'; - if (!in_array($settingsDir, $metaDataFolders) && is_dir($settingsDir)) { - $metaDataFolders[] = $settingsDir; - } -} - -/** - * (Delegated) Implements hook_civicrm_entityTypes(). - * - * Find any *.entityType.php files, merge their content, and return. - * - * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_entityTypes - */ -function _emailamender_civix_civicrm_entityTypes(&$entityTypes) { - $entityTypes = array_merge($entityTypes, []); -} diff --git a/emailamender.php b/emailamender.php index 0dd200c..76407e4 100755 --- a/emailamender.php +++ b/emailamender.php @@ -2,6 +2,8 @@ require_once 'emailamender.civix.php'; +use CRM_Emailamender_ExtensionUtil as E; + /** * Implements hook_civicrm_config(). */ @@ -9,66 +11,11 @@ function emailamender_civicrm_config(&$config) { _emailamender_civix_civicrm_config($config); } -/** - * Implements hook_civicrm_xmlMenu(). - */ -function emailamender_civicrm_xmlMenu(&$files) { - _emailamender_civix_civicrm_xmlMenu($files); -} - -/** - * Implements hook_civicrm_install(). - */ -function emailamender_civicrm_install() { - CRM_Core_BAO_OptionValue::ensureOptionValueExists([ - 'label' => 'Corrected Email Address', - 'name' => 'corrected_email_address', - 'weight' => '1', - 'description' => 'Automatically corrected emails (by the Email Address Corrector extension).', - 'option_group_id' => 'activity_type', - ]); - return _emailamender_civix_civicrm_install(); -} - /** * Implements hook_civicrm_uninstall(). */ function emailamender_civicrm_uninstall() { - CRM_Core_DAO::executeQuery("DELETE FROM civicrm_setting WHERE name LIKE 'emailamender%'"); - - return _emailamender_civix_civicrm_uninstall(); -} - -/** - * Implements hook_civicrm_enable(). - */ -function emailamender_civicrm_enable() { - return _emailamender_civix_civicrm_enable(); -} - -/** - * Implements hook_civicrm_disable(). - */ -function emailamender_civicrm_disable() { - return _emailamender_civix_civicrm_disable(); -} - -/** - * Implements hook_civicrm_upgrade(). - */ -function emailamender_civicrm_upgrade($op, CRM_Queue_Queue $queue = NULL) { - return _emailamender_civix_civicrm_upgrade($op, $queue); -} - -/** - * Implements hook_civicrm_managed(). - * - * Generate a list of entities to create/deactivate/delete when this module - * is installed, disabled, uninstalled. - */ -function emailamender_civicrm_managed(&$entities) { - return _emailamender_civix_civicrm_managed($entities); } /** @@ -93,67 +40,31 @@ function emailamender_civicrm_emailProcessorContact($email, $contactID, &$result CRM_Emailamender_Equivalentmatcher::processHook($email, $contactID, $result); } -/** - * Implements hook_civicrm_alterSettingsFolders(). - * - * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_alterSettingsFolders - */ -function emailamender_civicrm_alterSettingsFolders(&$metaDataFolders = NULL) { - _emailamender_civix_civicrm_alterSettingsFolders($metaDataFolders); -} - -/** - * civicrm_civicrm_navigationMenu - * - * implementation of civicrm_civicrm_navigationMenu - * - */ -function emailamender_civicrm_navigationMenu(&$params) { - $sAdministerMenuId = CRM_Core_DAO::getFieldValue('CRM_Core_BAO_Navigation', 'Administer', 'id', 'name'); - $sSystemSettingsMenuId = CRM_Core_DAO::getFieldValue('CRM_Core_BAO_Navigation', 'System Settings', 'id', 'name'); - - // Get the maximum key of $params - $maxKey = max(array_keys($params)); - - $params[$sAdministerMenuId]['child'][$sSystemSettingsMenuId]['child'][$maxKey + 1] = array( - 'attributes' => array( - 'label' => 'Email Address Corrector Settings', - 'name' => 'EmailAmenderSettings', - 'url' => 'civicrm/emailamendersettings', - 'permission' => NULL, - 'operator' => NULL, - 'separator' => NULL, - 'parentID' => $sSystemSettingsMenuId, - 'navID' => $maxKey + 1, - 'active' => 1, - ), - ); -} - /** * Implements hook_civicrm_searchTasks(). */ function emailamender_civicrm_searchTasks($objectType, &$tasks) { if ($objectType === 'contact') { - $tasks[] = array( + $tasks[] = [ 'title' => ts('Email - correct email addresses'), 'class' => 'CRM_Emailamender_Form_Task_Correctemailaddresses', 'result' => TRUE, - ); + ]; } } /** - * Implements hook_civicrm_angularModules(). - * - * Generate a list of Angular modules. - * Generate a list of Angular modules. - * - * Note: This hook only runs in CiviCRM 4.5+. It may - * use features only available in v4.6+. + * Implements hook_civicrm_permission(). * - * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_angularModules + * @see CRM_Utils_Hook::permission() */ -function emailamender_civicrm_angularModules(&$angularModules) { - _emailamender_civix_civicrm_angularModules($angularModules); +function emailamender_civicrm_permission(array &$permissions) { + $permissions['administer_email_amender'] = [ + 'label' => E::ts('Email Amender'), + 'description' => E::ts('administer email corrections'), + ]; +} + +function emailamender_civicrm_alterAPIPermissions($entity, $action, &$params, &$permissions) { + $permissions['email_amender']['default'] = 'administer_email_amender'; } diff --git a/info.xml b/info.xml index 38755d6..6b4797d 100755 --- a/info.xml +++ b/info.xml @@ -4,21 +4,29 @@ Email Address Corrector This extension allows automatic and manual correction of email addresses that are added to your database. i.e. john@hotmai.cpm is corrected to john@hotmail.com. - Settings under Administrator -> System Settings -> Email Address Corrector. Automatic correction is disabled by default. Also supports domain equivalents to reduce duplicates. See comments. + Settings under Administrator -> System Settings -> Email Address Corrector. Automatic correction is disabled by default. Also supports domain equivalents to reduce duplicates. See comments. AGPL 3.0 John P Kirk john@civifirst.com - 2016-11-20 - 3.0.1 + 2025-09-02 + 3.3.3 stable - 4.7 - 5.18 - 5.22 + 6.6 + + 8.0 + 8.1 + 8.2 + 8.3 + 8.4 + + + 5 + Data Cleaning Existing email addresses aren't affected automatically. Corrections only take place when email addresses are added, not when they are edited. @@ -28,6 +36,20 @@ CRM/Emailamender + 25.01.1 - https://github.com/JohnFF/Email-Amender/wiki + + https://github.com/eileenmcnaughton/Email-Amender/blob/master/README.md + + + menu-xml@1.0.0 + setting-php@1.0.0 + mgd-php@1.0.0 + smarty@1.0.3 + + + + + + CiviMix\Schema\Emailamender\AutomaticUpgrader diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 0f9f25d..fc8f870 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,5 +1,5 @@ - + ./tests/phpunit diff --git a/templates/CRM/Emailamender/Page/EmailAmenderSettings.js b/templates/CRM/Emailamender/Page/EmailAmenderSettings.js index 0e58592..7c6d9ff 100755 --- a/templates/CRM/Emailamender/Page/EmailAmenderSettings.js +++ b/templates/CRM/Emailamender/Page/EmailAmenderSettings.js @@ -1,202 +1,202 @@ -var CRM = CRM || {}; - -function on_any_change(filter_id) { - jQuery('#' + filter_id).children('h3').css('background-color', '#98FB98'); - jQuery('#' + filter_id).children('.save_changes_button').fadeIn(); -} +CRM.$(function($) { + function on_any_change(filter_id) { + $('#' + filter_id).children('h3').css('background-color', '#98FB98'); + $('#' + filter_id).children('.save_changes_button').fadeIn(); + } -function input_box_change() { - var filter_id = jQuery(this).attr('filter_id'); + function input_box_change() { + var filter_id = $(this).attr('filter_id'); - var allPassedValidation = true; + var allPassedValidation = true; // TODO only adjust messages for this one - jQuery('#' + filter_id).find('input').each(function () { - var thisPassedValidation = true; + $('#' + filter_id).find('input').each(function () { + var thisPassedValidation = true; - // does it contain a full stop? if so bail - if (jQuery(this).val().indexOf('.') >= 0 && jQuery(this).hasClass('correction_from') && filter_id != 'equivalent_domain') { - jQuery(this).siblings('.error_msg').text('Top level domains can\'t have full stops.'); - allPassedValidation = false; - thisPassedValidation = false; + // does it contain a full stop? if so bail + if ($(this).val().indexOf('.') >= 0 && $(this).hasClass('correction_from') && filter_id != 'equivalent_domain') { + $(this).siblings('.error_msg').text('Top level domains can\'t have full stops.'); + allPassedValidation = false; + thisPassedValidation = false; - // input box can't be empty - } else if (jQuery(this).val().length == 0) { - jQuery(this).siblings('.error_msg').text('Corrections cannot be empty.'); - allPassedValidation = false; - thisPassedValidation = false; - } + // input box can't be empty + } else if ($(this).val().length == 0) { + $(this).siblings('.error_msg').text('Corrections cannot be empty.'); + allPassedValidation = false; + thisPassedValidation = false; + } - if (jQuery(this).siblings('.error_msg').is(':visible') && thisPassedValidation) { - jQuery(this).siblings('.error_msg').fadeOut(function () { - jQuery(this).text(''); - }); + if ($(this).siblings('.error_msg').is(':visible') && thisPassedValidation) { + $(this).siblings('.error_msg').fadeOut(function () { + $(this).text(''); + }); - } else if (!jQuery(this).siblings('.error_msg').is(':visible') && !thisPassedValidation) { - jQuery(this).siblings('.error_msg').fadeIn(); + } else if (!$(this).siblings('.error_msg').is(':visible') && !thisPassedValidation) { + $(this).siblings('.error_msg').fadeIn(); + } + }); + + if (!allPassedValidation) { + $('#' + filter_id).children('h3').css('background-color', '#FFB6C1'); + $('#' + filter_id).children('.save_changes_button').fadeOut(); + return; } - }); - if (!allPassedValidation) { - jQuery('#' + filter_id).children('h3').css('background-color', '#FFB6C1'); - jQuery('#' + filter_id).children('.save_changes_button').fadeOut(); - return; + on_any_change(filter_id); } - on_any_change(filter_id); -} + function delete_button() { + var filter_id = $(this).attr('filter_id'); + on_any_change(filter_id); -function delete_button() { - var filter_id = jQuery(this).attr('filter_id'); - on_any_change(filter_id); - - jQuery(this).parent().parent().fadeOut(function () { - jQuery(this).remove(); - }); - - return false; -} + $(this).parent().parent().fadeOut(function () { + $(this).remove(); + }); -function on_save() { - var filter_id = jQuery(this).attr('filter_id'); + return false; + } - var aInputValuesFrom = []; - var aInputValuesTo = []; + function on_save() { + var filter_id = $(this).attr('filter_id'); - jQuery('#' + filter_id).find('.correction_from').each(function () { - aInputValuesFrom.push(jQuery(this).val()); - }); + var aInputValuesFrom = []; + var aInputValuesTo = []; - jQuery('#' + filter_id).find('.correction_to').each(function () { - aInputValuesTo.push(jQuery(this).val()); - }); + $('#' + filter_id).find('.correction_from').each(function () { + aInputValuesFrom.push($(this).val()); + }); - CRM.api3('EmailAmender', 'update_corrections', { - 'sequential': '1', - 'domain_level': filter_id, - 'correction_keys': aInputValuesFrom, - 'correction_values': aInputValuesTo - } - , { - success: function (data) { - // TODO indicate a successful save - // cj.each(data, function(key, value) {// do something }); - jQuery('#' + filter_id).children('.save_changes_button').fadeOut(); - jQuery('#' + filter_id).find('h3').css('background-color', '#CDE8FE'); - } + $('#' + filter_id).find('.correction_to').each(function () { + aInputValuesTo.push($(this).val()); }); -} -function on_tld_save() { - var aInputValues = new Array(); - jQuery('#compound_tld').find(':text').each(function () { - aInputValues.push(jQuery(this).val()); - }); - CRM.api3('EmailAmender', 'update_compound_t_l_ds', {'sequential': '1', 'compound_tlds': aInputValues} - , { - success: function (data) { - // TODO indicate a successful save - // cj.each(data, function(key, value) {// do something }); - jQuery('#compound_tld').find('.save_tld_changes').fadeOut(); - jQuery('#compound_tld').find('h3').css('background-color', '#CDE8FE'); + CRM.api3('EmailAmender', 'update_corrections', { + 'sequential': '1', + 'domain_level': filter_id, + 'correction_keys': aInputValuesFrom, + 'correction_values': aInputValuesTo } + , { + success: function (data) { + // TODO indicate a successful save + // cj.each(data, function(key, value) {// do something }); + $('#' + filter_id).children('.save_changes_button').fadeOut(); + $('#' + filter_id).find('h3').css('background-color', '#CDE8FE'); + } + }); + } + + function on_tld_save() { + var aInputValues = new Array(); + $('#compound_tld').find(':text').each(function () { + aInputValues.push($(this).val()); }); -} + CRM.api3('EmailAmender', 'update_compound_t_l_ds', {'sequential': '1', 'compound_tlds': aInputValues} + , { + success: function (data) { + // TODO indicate a successful save + // cj.each(data, function(key, value) {// do something }); + $('#compound_tld').find('.save_tld_changes').fadeOut(); + $('#compound_tld').find('h3').css('background-color', '#CDE8FE'); + } + }); + } -jQuery('.add_new_correction').click(function () { - var filter = jQuery(this).attr('filter_id'); + $('.add_new_correction').click(function () { + var filter = $(this).attr('filter_id'); - var newFilterRow = ''; - jQuery('#' + filter + '_table tbody').append(newFilterRow); + var newFilterRow = ''; + $('#' + filter + '_table tbody').append(newFilterRow); - // Add new input boxes - var newFilterTextBox = ''; - jQuery('#' + filter + '_table tbody').children().last().children(':lt(2)').append(newFilterTextBox); - jQuery('#' + filter + '_table tbody').children().last().children(':lt(2)').append(''); + // Add new input boxes + var newFilterTextBox = ''; + $('#' + filter + '_table tbody').children().last().children(':lt(2)').append(newFilterTextBox); + $('#' + filter + '_table tbody').children().last().children(':lt(2)').append(''); - // add the correction_from and correction_to classes - jQuery('#' + filter + '_table tbody').children().last().children(':eq(0)').find('input').addClass('correction_from'); - jQuery('#' + filter + '_table tbody').children().last().children(':eq(1)').find('input').addClass('correction_to'); + // add the correction_from and correction_to classes + $('#' + filter + '_table tbody').children().last().children(':eq(0)').find('input').addClass('correction_from'); + $('#' + filter + '_table tbody').children().last().children(':eq(1)').find('input').addClass('correction_to'); - // Add change listener to both new input boxes - jQuery('#' + filter + '_table tbody').children().last().find('input').change(input_box_change); + // Add change listener to both new input boxes + $('#' + filter + '_table tbody').children().last().find('input').change(input_box_change); - // Add new delete button - var newDeleteButton = jQuery('Delete this correction').click(delete_button); - jQuery('#' + filter + '_table tbody').children().last().children().last().append(newDeleteButton); + // Add new delete button + var newDeleteButton = $('Delete this correction').click(delete_button); + $('#' + filter + '_table tbody').children().last().children().last().append(newDeleteButton); - jQuery('#' + filter + '_table').find('tr:hidden').fadeIn(); + $('#' + filter + '_table').find('tr:hidden').fadeIn(); -}); + }); // Very similar to .add_new_correction, except we're switching around the display of the 'key' box and the 'value' box -jQuery('.add_new_equivalent').click(function () { - var filter = jQuery(this).attr('filter_id'); + $('.add_new_equivalent').click(function () { + var filter = $(this).attr('filter_id'); - var newFilterRow = ''; - jQuery('#' + filter + '_table tbody').append(newFilterRow); + var newFilterRow = ''; + $('#' + filter + '_table tbody').append(newFilterRow); - // Add new input boxes - var newFilterTextBox = ''; - jQuery('#' + filter + '_table tbody').children().last().children(':lt(2)').append(newFilterTextBox); - jQuery('#' + filter + '_table tbody').children().last().children(':lt(2)').append(''); + // Add new input boxes + var newFilterTextBox = ''; + $('#' + filter + '_table tbody').children().last().children(':lt(2)').append(newFilterTextBox); + $('#' + filter + '_table tbody').children().last().children(':lt(2)').append(''); - // add the correction_from and correction_to classes - jQuery('#' + filter + '_table tbody').children().last().children(':eq(0)').find('input').addClass('correction_to'); - jQuery('#' + filter + '_table tbody').children().last().children(':eq(1)').find('input').addClass('correction_from'); + // add the correction_from and correction_to classes + $('#' + filter + '_table tbody').children().last().children(':eq(0)').find('input').addClass('correction_to'); + $('#' + filter + '_table tbody').children().last().children(':eq(1)').find('input').addClass('correction_from'); - // Add change listener to both new input boxes - jQuery('#' + filter + '_table tbody').children().last().find('input').change(input_box_change); + // Add change listener to both new input boxes + $('#' + filter + '_table tbody').children().last().find('input').change(input_box_change); - // Add new delete button - var newDeleteButton = jQuery('Delete this equivalent').click(delete_button); - jQuery('#' + filter + '_table tbody').children().last().children().last().append(newDeleteButton); + // Add new delete button + var newDeleteButton = $('Delete this equivalent').click(delete_button); + $('#' + filter + '_table tbody').children().last().children().last().append(newDeleteButton); - jQuery('#' + filter + '_table').find('tr:hidden').fadeIn(); + $('#' + filter + '_table').find('tr:hidden').fadeIn(); -}); - -jQuery('.add_new_compound_tld').click(function () { - var filter = jQuery(this).attr('filter_id'); + }); - var newCompoundTLDRow = ''; - jQuery('#compound_tld_table tbody').append(newCompoundTLDRow); + $('.add_new_compound_tld').click(function () { + var filter = $(this).attr('filter_id'); - // Add new input boxes - var newCompoundTLDTextBox = ''; - jQuery('#compound_tld_table tbody').children().last().children(':lt(1)').append(newCompoundTLDTextBox); - jQuery('#compound_tld_table tbody').children().last().children(':lt(1)').append(''); + var newCompoundTLDRow = ''; + $('#compound_tld_table tbody').append(newCompoundTLDRow); - // Add change listener to both new input boxes - jQuery('#compound_tld_table tbody').children().last().find('input').change(input_box_change); + // Add new input boxes + var newCompoundTLDTextBox = ''; + $('#compound_tld_table tbody').children().last().children(':lt(1)').append(newCompoundTLDTextBox); + $('#compound_tld_table tbody').children().last().children(':lt(1)').append(''); - // Add new delete button - var newDeleteButton = jQuery('Delete this compound tld').click(delete_button); - jQuery('#compound_tld_table tbody').children().last().children().last().append(newDeleteButton); + // Add change listener to both new input boxes + $('#compound_tld_table tbody').children().last().find('input').change(input_box_change); - jQuery('#compound_tld_table').find('tr:hidden').fadeIn(); -}); + // Add new delete button + var newDeleteButton = $('Delete this compound tld').click(delete_button); + $('#compound_tld_table tbody').children().last().children().last().append(newDeleteButton); -jQuery('#email_amender_enabled').click(function () { - CRM.api3('Setting', 'create', { - 'emailamender.email_amender_enabled': jQuery(this).is(':checked') - } - , { - success: function (data) { + $('#compound_tld_table').find('tr:hidden').fadeIn(); + }); + $('#email_amender_enabled').click(function () { + CRM.api3('Setting', 'create', { + 'emailamender.email_amender_enabled': $(this).is(':checked') } - }); -}); + , { + success: function (data) { + + } + }); + }); // add event listeners -jQuery('.deleteButton').click(delete_button); -jQuery('input').change(input_box_change); -jQuery('.save_correction_changes').click(on_save); -jQuery('.save_tld_changes').click(on_tld_save); - -jQuery('h3').css('-webkit-transition', 'background-color 0.4s linear'); -jQuery('h3').css('-moz-transition', 'background-color 0.4s linear'); -jQuery('h3').css('-ms-transition', 'background-color 0.4s linear'); -jQuery('h3').css('-o-transition', 'background-color 0.4s linear'); -jQuery('h3').css('transition', 'background-color 0.4s linear'); + $('.deleteButton').click(delete_button); + $('input').change(input_box_change); + $('.save_correction_changes').click(on_save); + $('.save_tld_changes').click(on_tld_save); + + $('h3').css('-webkit-transition', 'background-color 0.4s linear'); + $('h3').css('-moz-transition', 'background-color 0.4s linear'); + $('h3').css('-ms-transition', 'background-color 0.4s linear'); + $('h3').css('-o-transition', 'background-color 0.4s linear'); + $('h3').css('transition', 'background-color 0.4s linear'); +});s \ No newline at end of file diff --git a/templates/CRM/Emailamender/Page/EmailAmenderSettings.tpl b/templates/CRM/Emailamender/Page/EmailAmenderSettings.tpl index 85e6478..cfc9963 100755 --- a/templates/CRM/Emailamender/Page/EmailAmenderSettings.tpl +++ b/templates/CRM/Emailamender/Page/EmailAmenderSettings.tpl @@ -1,11 +1,19 @@ +{if !$hasEditPermission} +

{ts}You do not have the permission EmailAmender:administer email corrections so this table is view only.{/ts}

+{/if} + + diff --git a/templates/CRM/Emailamender/Page/EmailAmenderSettingsTable.tpl b/templates/CRM/Emailamender/Page/EmailAmenderSettingsTable.tpl index cd76bdd..aa88ed2 100755 --- a/templates/CRM/Emailamender/Page/EmailAmenderSettingsTable.tpl +++ b/templates/CRM/Emailamender/Page/EmailAmenderSettingsTable.tpl @@ -1,25 +1,30 @@
-

{ts}{$title}{/ts}

+

{ts}{$title|escape}{/ts}

+ - - - -{foreach from=$data key=find item=replaceWith} - - - - - -{/foreach} + + + + {foreach from=$data key=find item=replaceWith} + + + + + + {/foreach}
{ts}Incorrect Domain{/ts}{ts}Replace with{/ts}{ts}Options{/ts}
- - - - - - - Delete this correction -
{ts}Incorrect Domain{/ts}{ts}Replace with{/ts}{ts}Options{/ts}
+ + + + + + + {if $hasEditPermission} + Delete this correction + {/if} +
- - +{if $hasEditPermission} + + +{/if}
diff --git a/templates/CRM/Emailamender/Page/EquivalentsTable.tpl b/templates/CRM/Emailamender/Page/EquivalentsTable.tpl index d7a25d5..d1e3a22 100755 --- a/templates/CRM/Emailamender/Page/EquivalentsTable.tpl +++ b/templates/CRM/Emailamender/Page/EquivalentsTable.tpl @@ -1,5 +1,6 @@
-

{ts}{$title}{/ts}

+

{ts}{$title|escape}{/ts}

+

{ts}When an e-mail arrives from an address for which there is no existing contact in the system, normally a new contact is created with that @@ -21,25 +22,29 @@ It does not change any existing data for a contact.{/ts}

- - - + + + {foreach from=$data key=find item=replaceWith} - - - - - + + + + + {/foreach}
{ts}Group identifier{/ts}{ts}Equivalent domain{/ts}{ts}Options{/ts}{ts}Group identifier{/ts}{ts}Equivalent domain{/ts}{ts}Options{/ts}
- - - - - - - Delete this equivalent -
+ + + + + + + {if $hasEditPermission} + Delete this equivalent + {/if} +
- - + {if $hasEditPermission} + + + {/if}
diff --git a/tests/phpunit/CRM/Emailamender/BatchUpdateTest.php b/tests/phpunit/CRM/Emailamender/BatchUpdateTest.php index 584e9a0..e780294 100644 --- a/tests/phpunit/CRM/Emailamender/BatchUpdateTest.php +++ b/tests/phpunit/CRM/Emailamender/BatchUpdateTest.php @@ -21,8 +21,9 @@ class CRM_Emailamender_BatchUpdateTest extends \PHPUnit\Framework\TestCase implements HeadlessInterface, HookInterface, TransactionalInterface { use Civi\Test\Api3TestTrait; + use Civi\Test\EntityTrait; - protected $maxExistingActivityID; + protected int $maxExistingActivityID; /** * @return \Civi\Test\CiviEnvBuilder @@ -37,14 +38,12 @@ public function setUpHeadless() { } public function setUp(): void { - $this->callAPISuccess('Setting', 'create', [ - 'emailamender.email_amender_enabled' => 'true', - ]); + \Civi::settings()->set('emailamender.email_amender_enabled', TRUE); // Cleanup first in case any values are 'hanging around' $this->callApiSuccess('EmailAmender', 'batch_update', [])['values']; parent::setUp(); $activities = $this->callAPISuccess('Activity', 'get', ['return' => 'id', 'activity_type_id' => 'corrected_email_address', 'sequential' => 1, 'options' => ['sort' => 'id DESC', 'limit' => 1]])['values']; - $this->maxExistingActivityID = $activities[0] ?? 0; + $this->maxExistingActivityID = $activities[0]['id'] ?? 0; } public function tearDown(): void { @@ -57,11 +56,9 @@ public function tearDown(): void { /** * Test for email addresses on contacts created via the API. - * - * @throws \CRM_Core_Exception */ public function testBatchUpdate() { - $this->callApiSuccess('Setting', 'create', ['emailamender.email_amender_enabled' => FALSE]); + \Civi::settings()->set('emailamender.email_amender_enabled', FALSE); $testEmailCorrections = [ // Test contacts with an incorrect top level domain. 'john@gmail.cpm' => 'john@gmail.com', @@ -86,7 +83,7 @@ public function testBatchUpdate() { ]; foreach ($testEmailCorrections as $incorrectEmailAddress => $expectedOutput) { - $this->ids['Contact'][] = $this->callApiSuccess('Contact', 'create', ['contact_type' => 'Individual', 'email' => $incorrectEmailAddress])['id']; + $this->createTestEntity('Contact', ['contact_type' => 'Individual', 'email_primary.email' => $incorrectEmailAddress], $incorrectEmailAddress); } $candidates = $this->callApiSuccess('EmailAmender', 'find_candidates', [])['values']; @@ -100,7 +97,7 @@ public function testBatchUpdate() { $this->assertCount(2, $candidates); $this->callApiSuccessGetCount('Activity', ['activity_type_id' => 'corrected_email_address', 'id' => ['>' => $this->maxExistingActivityID]], 10); - $this->assertEquals('john@gmail.com', $this->callAPISuccessGetValue('Contact', ['id' => $this->ids['Contact'][0], 'return' => 'display_name'])); + $this->assertEquals('john@gmail.com', $this->callAPISuccessGetValue('Contact', ['id' => $this->ids['Contact']['john@gmail.cpm'], 'return' => 'display_name'])); } } diff --git a/tests/phpunit/CRM/Emailamender/IntegrationTest.php b/tests/phpunit/CRM/Emailamender/IntegrationTest.php index 4efdad9..6e51158 100644 --- a/tests/phpunit/CRM/Emailamender/IntegrationTest.php +++ b/tests/phpunit/CRM/Emailamender/IntegrationTest.php @@ -20,6 +20,9 @@ */ class CRM_Emailamender_IntegrationTest extends \PHPUnit\Framework\TestCase implements HeadlessInterface, HookInterface, TransactionalInterface { use \Civi\Test\Api3TestTrait; + use \Civi\Test\EntityTrait; + + protected int $maxExistingActivityID; public function setUpHeadless() { // Civi\Test has many helpers, like install(), uninstall(), sql(), and sqlFile(). @@ -58,14 +61,12 @@ public function tearDown(): void { * @param string $emailAddress * * @return array - * - * @throws \CRM_Core_Exception */ - public function createTestContact($emailAddress) { - $createContactResults = $this->callApiSuccess('Contact', 'create', [ - 'contact_type' => 'individual', - 'email' => $emailAddress, - ]); + public function createTestContact(string $emailAddress): array { + $createContactResults = $this->createTestEntity('Contact', [ + 'contact_type' => 'Individual', + 'email_primary.email' => $emailAddress, + ], $emailAddress); return $this->callApiSuccessGetSingle('Email', ['contact_id' => $createContactResults['id']]); } @@ -74,9 +75,8 @@ public function createTestContact($emailAddress) { * @param int $contactId * * @return array|int - * @throws \CRM_Core_Exception */ - public function getCorrectedEmailAddressActivityCount($contactId) { + public function getCorrectedEmailAddressActivityCount($contactId): array|int { return $this->callApiSuccessGetCount('Activity', [ 'contact_id' => $contactId, 'activity_type_id' => 'corrected_email_address', @@ -140,7 +140,7 @@ public function testEnabledSettingOff() { */ public function testTwoCorrections() { $emailDetails = $this->createTestContact('john@yaho.com'); - $this->callApiSuccess('Email', 'create', [ + $this->createTestEntity('Email', [ 'contact_id' => $emailDetails['contact_id'], 'location_type_id' => 1, 'email' => 'john@yaho.com', @@ -156,92 +156,4 @@ public function testTwoCorrections() { $this->assertEquals(2, $this->getCorrectedEmailAddressActivityCount($emailDetails['contact_id'])); } - /** - * @throws \CRM_Core_Exception - * @throws \CiviCRM_API3_Exception - */ - public function testCsvImportCreateSingleContact() { - $originalValues = [ - 'first_name' => 'Bill', - 'last_name' => 'Gates', - 'email' => 'john@yaho.com', - ]; - - $fields = array_keys($originalValues); - $values = array_values($originalValues); - $parser = new CRM_Contact_Import_Parser_Contact($fields); - $parser->_contactType = 'Individual'; - $parser->_onDuplicate = CRM_Import_Parser::DUPLICATE_NOCHECK; - $parser->init(); - $this->assertEquals( - CRM_Import_Parser::VALID, - $parser->import(CRM_Import_Parser::DUPLICATE_NOCHECK, $values), - 'Return code from parser import was not as expected' - ); - - // Will assert if contact doesn't exist. - $this->ids['Contact'][0] = $this->callApiSuccessGetSingle('Contact', ['first_name' => 'Bill', 'last_name' => 'Gates'])['id']; - - $this->callApiSuccessGetSingle('Email', [ - 'contact_id' => $this->ids['Contact'][0], - 'email' => 'john@yahoo.com', - ]); - } - - /** - * @throws \CRM_Core_Exception - * @throws \CiviCRM_API3_Exception - */ - public function testCsvImportDuplicateActionTypes() { - $this->ids['Contact'] = $this->ids['Contact'] ?? []; - $duplicateActionTypes = [ - CRM_Import_Parser::DUPLICATE_SKIP, - CRM_Import_Parser::DUPLICATE_REPLACE, - CRM_Import_Parser::DUPLICATE_UPDATE, - CRM_Import_Parser::DUPLICATE_FILL, - CRM_Import_Parser::DUPLICATE_NOCHECK, - ]; - - foreach ($duplicateActionTypes as $duplicateActionType) { - // Initialise the duplicate contact. - $firstName = 'Bill ' . $duplicateActionType; - $incorrectEmailAddress = 'bill' . $duplicateActionType . '@hotmial.com'; - $correctEmailAddress = 'bill' . $duplicateActionType . '@hotmail.com'; - - // Create the duplicate contact. - $this->callApiSuccess('Contact', 'create', [ - 'contact_type' => 'Individual', - 'first_name' => $firstName, - 'last_name' => 'Gates', - 'email' => $correctEmailAddress, - ])['id']; - - // Perform the import of duplicate contacts. - $importValues = [ - 'first_name' => $firstName, - 'last_name' => 'Gates', - 'email' => $incorrectEmailAddress, - ]; - - $fields = array_keys($importValues); - $values = array_values($importValues); - $parser = new CRM_Contact_Import_Parser_Contact($fields); - $parser->_contactType = 'Individual'; - $parser->_onDuplicate = $duplicateActionType; - $parser->init(); - $this->assertEquals( - CRM_Import_Parser::VALID, - $parser->import($duplicateActionType, $values), - 'Return code from parser import was not as expected' - ); - - // Check the results. - // Currently the Email Address Corrector doesn't dedupe after changing the email address. - // So we just check that both contacts exist and haven't broken on their way in. - $getContacts = $this->callApiSuccess('Contact', 'get', ['first_name' => $firstName, 'last_name' => 'Gates', 'email' => $correctEmailAddress])['values']; - $this->ids['Contact'] = array_merge(array_keys($getContacts), $this->ids['Contact']); - $this->assertCount(2, $getContacts); - } - } - }