├── .github └── FUNDING.yml ├── modules └── civicrmtheme │ ├── config │ ├── install │ │ └── civicrmtheme.settings.yml │ └── schema │ │ └── civicrmtheme.schema.yml │ ├── civicrmtheme.info.yml │ ├── civicrmtheme.services.yml │ ├── civicrmtheme.module │ └── src │ └── Theme │ └── CivicrmThemeNegotiator.php ├── civicrm.permissions.yml ├── icons ├── 787878 │ ├── CiviCRM.png │ └── CiviCRM.svg ├── 000000 │ ├── CiviCRM.png │ └── CiviCRM.svg ├── bebebe │ ├── CiviCRM.png │ └── CiviCRM.svg └── ffffff │ ├── CiviCRM.png │ └── CiviCRM.svg ├── civicrm.libraries.yml ├── civicrm.links.menu.yml ├── src ├── Exception │ └── CiviCRMConfigException.php ├── CivicrmPermissions.php ├── Plugin │ ├── Derivative │ │ ├── CivicrmBlock.php │ │ └── LocalTasks.php │ └── Block │ │ └── CivicrmBlock.php ├── Routing │ └── Routes.php ├── Entity │ └── CivicrmDatabaseStorage.php ├── CivicrmBreadcrumbBuilder.php ├── PathProcessor │ └── CivicrmPathProcessor.php ├── Controller │ └── CivicrmController.php ├── CivicrmPageState.php ├── Form │ └── UserProfile.php └── Civicrm.php ├── templates ├── civicrm-user-profile.html.twig └── civicrm-contact.html.twig ├── civicrm.info.yml ├── civicrm.links.task.yml ├── civicrm.services.yml ├── COPYRIGHT.txt ├── composer.json ├── civicrm.routing.yml ├── css └── civicrm.icons.css ├── civicrm.config.php.drupal ├── README.md ├── civicrm.user.inc ├── tests └── src │ └── FunctionalJavascript │ └── CiviCrmTestBase.php ├── civicrm.install ├── civicrm.module ├── LICENSE.txt └── drush └── civicrm.drush.inc /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | custom: https://civicrm.org/civicrm/contribute/transact?reset=1&id=47 2 | -------------------------------------------------------------------------------- /modules/civicrmtheme/config/install/civicrmtheme.settings.yml: -------------------------------------------------------------------------------- 1 | admin_theme: '' 2 | public_theme: '' 3 | -------------------------------------------------------------------------------- /civicrm.permissions.yml: -------------------------------------------------------------------------------- 1 | permission_callbacks: 2 | - Drupal\civicrm\CivicrmPermissions::permissions 3 | -------------------------------------------------------------------------------- /icons/000000/CiviCRM.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/civicrm/civicrm-drupal-8/HEAD/icons/000000/CiviCRM.png -------------------------------------------------------------------------------- /icons/787878/CiviCRM.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/civicrm/civicrm-drupal-8/HEAD/icons/787878/CiviCRM.png -------------------------------------------------------------------------------- /icons/bebebe/CiviCRM.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/civicrm/civicrm-drupal-8/HEAD/icons/bebebe/CiviCRM.png -------------------------------------------------------------------------------- /icons/ffffff/CiviCRM.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/civicrm/civicrm-drupal-8/HEAD/icons/ffffff/CiviCRM.png -------------------------------------------------------------------------------- /civicrm.libraries.yml: -------------------------------------------------------------------------------- 1 | civicrm-icons: 2 | version: VERSION 3 | css: 4 | component: 5 | css/civicrm.icons.css: { media: screen } -------------------------------------------------------------------------------- /civicrm.links.menu.yml: -------------------------------------------------------------------------------- 1 | civicrm.admin_config_civicrm: 2 | route_name: civicrm.admin_config_civicrm 3 | parent: system.admin_config 4 | title: CiviCRM 5 | weight: -10 6 | -------------------------------------------------------------------------------- /src/Exception/CiviCRMConfigException.php: -------------------------------------------------------------------------------- 1 | 8 |

{{ elements['#title'] }}

9 | {{ elements }} 10 | -------------------------------------------------------------------------------- /modules/civicrmtheme/civicrmtheme.services.yml: -------------------------------------------------------------------------------- 1 | services: 2 | civicrmtheme.negotiator: 3 | class: Drupal\civicrmtheme\Theme\CivicrmThemeNegotiator 4 | arguments: ['@current_user', '@config.factory', '@civicrm'] 5 | tags: 6 | - { name: theme_negotiator, priority: 11 } 7 | -------------------------------------------------------------------------------- /civicrm.info.yml: -------------------------------------------------------------------------------- 1 | name: CiviCRM Core 2 | type: module 3 | description: 'Constituent Relationship Management system. Allows sites to manage contacts, relationships and groups, and track contact activities, contributions, memberships and events.' 4 | package: CiviCRM 5 | core_version_requirement: ^9 || ^10 || ^11 6 | -------------------------------------------------------------------------------- /templates/civicrm-contact.html.twig: -------------------------------------------------------------------------------- 1 | {# 2 | /** 3 | * This is really very useless as a template. However, it 4 | * offers the ability to swap out the display of contacts 5 | * very easily via a template override, allowing customised 6 | * display of contact information. 7 | */ 8 | #} 9 | {{ civicrm_contact.label }} -------------------------------------------------------------------------------- /modules/civicrmtheme/config/schema/civicrmtheme.schema.yml: -------------------------------------------------------------------------------- 1 | # Scheme for configuration files of the CiviCRM theme module. 2 | 3 | civicrmtheme.settings: 4 | type: config_object 5 | label: 'CiviCRM theme settings' 6 | mapping: 7 | admin_theme: 8 | type: string 9 | label: 'Administration theme' 10 | public_theme: 11 | type: string 12 | label: 'Public theme' 13 | -------------------------------------------------------------------------------- /civicrm.links.task.yml: -------------------------------------------------------------------------------- 1 | civicrm.account: 2 | route_name: entity.user.edit_form 3 | title: 'Account' 4 | base_route: civicrm_account 5 | parent_id: entity.user.edit_form 6 | 7 | civicrm.user_profile: 8 | route_name: civicrm.user_profile 9 | title: derived 10 | base_route: civicrm_account 11 | parent_id: entity.user.edit_form 12 | deriver: Drupal\civicrm\Plugin\Derivative\LocalTasks 13 | weight: 100 14 | -------------------------------------------------------------------------------- /civicrm.services.yml: -------------------------------------------------------------------------------- 1 | services: 2 | civicrm: 3 | class: Drupal\civicrm\Civicrm 4 | civicrm.page_state: 5 | class: Drupal\civicrm\CivicrmPageState 6 | civicrm.breadcrumb: 7 | class: Drupal\civicrm\CivicrmBreadcrumbBuilder 8 | arguments: ['@string_translation', '@civicrm.page_state'] 9 | tags: 10 | - { name: breadcrumb_builder, priority: 1002 } 11 | civicrm.path_processor: 12 | class: Drupal\civicrm\PathProcessor\CivicrmPathProcessor 13 | tags: 14 | - { name: path_processor_inbound, priority: 250 } 15 | -------------------------------------------------------------------------------- /COPYRIGHT.txt: -------------------------------------------------------------------------------- 1 | Copyright (C) 2014 Torrance Hodgson 2 | 3 | This program is free software: you can redistribute it and/or modify 4 | it under the terms of the GNU General Public License as published by 5 | the Free Software Foundation, either version 3 of the License, or 6 | (at your option) any later version. 7 | 8 | This program is distributed in the hope that it will be useful, 9 | but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | GNU General Public License for more details. 12 | 13 | You should have received a copy of the GNU General Public License 14 | along with this program. If not, see . 15 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "civicrm/civicrm-drupal-8", 3 | "description": "Open source constituent relationship management for non-profits, NGOs and advocacy organizations.", 4 | "type": "drupal-module", 5 | "license": "AGPL-3.0", 6 | "authors": [ 7 | { 8 | "name": "Coleman Watts", 9 | "role": "Product Manager" 10 | }, 11 | { 12 | "name": "Joshua Gowans", 13 | "role": "Project Manager" 14 | }, 15 | { 16 | "name": "Mathieu Lutfy", 17 | "role": "Infrastructure" 18 | }, 19 | { 20 | "name": "Tim Otten", 21 | "role": "Software Architect" 22 | }, 23 | { 24 | "name": "CiviCRM Community", 25 | "homepage": "https://civicrm.org" 26 | } 27 | ], 28 | "require": { 29 | "composer/installers": "^1 || ^2", 30 | "civicrm/civicrm-asset-plugin": "~1.1", 31 | "civicrm/civicrm-core" : ">=5.21.0 || dev-master" 32 | }, 33 | "extra": { 34 | "installer-name": "civicrm" 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /civicrm.routing.yml: -------------------------------------------------------------------------------- 1 | route_callbacks: 2 | - '\Drupal\civicrm\Routing\Routes::listRoutes' 3 | 4 | # Let Drupal handle logouts directly. This entry clobbers the entry that will be 5 | # automatically generated in the route_callback above. 6 | civicrm.civicrm_logout: 7 | path: '/civicrm/logout' 8 | defaults: 9 | _controller: '\Drupal\user\Controller\UserController::logout' 10 | requirements: 11 | _user_is_logged_in: 'TRUE' 12 | 13 | civicrm.admin_config_civicrm: 14 | path: '/admin/config/civicrm' 15 | defaults: 16 | _controller: '\Drupal\system\Controller\SystemController::systemAdminMenuBlockPage' 17 | _title: 'CiviCRM' 18 | requirements: 19 | _permission: 'access administration pages' 20 | 21 | civicrm.user_profile: 22 | path: '/user/{user}/edit/profile/{profile}' 23 | defaults: 24 | _form: '\Drupal\civicrm\Form\UserProfile' 25 | options: 26 | _admin_route: TRUE 27 | requirements: 28 | _custom_access: '\Drupal\civicrm\Form\UserProfile::access' 29 | -------------------------------------------------------------------------------- /css/civicrm.icons.css: -------------------------------------------------------------------------------- 1 | /** 2 | * @file 3 | * Styling for CiviCRM toolbar icons. 4 | */ 5 | 6 | /* Bar Icons */ 7 | .toolbar-bar .toolbar-icon-civicrm:before { 8 | background-image: url("../icons/bebebe/CiviCRM.svg"); 9 | } 10 | .no-svg .toolbar-bar .toolbar-icon-civicrm:before { 11 | background-image: url("../icons/bebebe/CiviCRM.png"); 12 | } 13 | .toolbar-bar .toolbar-icon-civicrm:active:before, 14 | .toolbar-bar .toolbar-icon-civicrm.is-active:before { 15 | background-image: url("../icons/ffffff/CiviCRM.svg"); 16 | } 17 | .no-svg .toolbar-bar .toolbar-icon-civicrm:active:before, 18 | .no-svg .toolbar-bar .toolbar-icon-civicrm.active:before { 19 | background-image: url("../icons/ffffff/CiviCRM.png"); 20 | } 21 | 22 | /* Tray Icons */ 23 | .toolbar-tray .toolbar-icon-civicrm:before { 24 | background-image: url("../icons/787878/CiviCRM.svg"); 25 | } 26 | .no-svg .toolbar-tray .toolbar-icon-civicrm:before { 27 | background-image: url("../icons/787878/CiviCRM.png"); 28 | } 29 | .toolbar-tray .toolbar-icon-civicrm:active:before, 30 | .toolbar-tray .toolbar-icon-civicrm.is-active:before { 31 | background-image: url("../icons/000000/CiviCRM.svg"); 32 | } 33 | .no-svg .toolbar-tray .toolbar-icon-civicrm:active:before, 34 | .no-svg .toolbar-tray .toolbar-icon-civicrm.active:before { 35 | background-image: url("../icons/000000/CiviCRM.png"); 36 | } -------------------------------------------------------------------------------- /src/CivicrmPermissions.php: -------------------------------------------------------------------------------- 1 | initialize(); 21 | } 22 | 23 | /** 24 | * {@inheritdoc} 25 | */ 26 | public static function create(ContainerInterface $container) { 27 | return new static( 28 | $container->get('civicrm') 29 | ); 30 | } 31 | 32 | /** 33 | * Returns an array of CiviCRM's basic permissions. 34 | * 35 | * @return array 36 | * An array of all permissions, keyed by the machine name. 37 | */ 38 | public function permissions() { 39 | $permissions = []; 40 | foreach (\CRM_Core_Permission::basicPermissions(FALSE, TRUE) as $permission => $attr) { 41 | $permissions[$permission] = ['title' => $attr['label']]; 42 | 43 | if (!empty($attr['description'])) { 44 | $permissions[$permission]['description'] = $attr['description']; 45 | } 46 | } 47 | return $permissions; 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /icons/000000/CiviCRM.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 6 | 7 | 12 | 13 | 14 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /src/Plugin/Derivative/CivicrmBlock.php: -------------------------------------------------------------------------------- 1 | initialize(); 20 | } 21 | 22 | /** 23 | * {@inheritdoc} 24 | */ 25 | public static function create(ContainerInterface $container, $base_plugin_id) { 26 | return new static( 27 | $container->get('civicrm') 28 | ); 29 | } 30 | 31 | /** 32 | * {@inheritdoc} 33 | */ 34 | public function getDerivativeDefinitions($base_plugin_definition) { 35 | $blocks = \CRM_Core_Block::getInfo(); 36 | foreach ($blocks as $block_id => $block) { 37 | // There's no need to prefix each block label with 'CiviCRM', because we 38 | // are already our blocks in the Civicrm category. 39 | $label = str_replace('CiviCRM ', '', $block['info']); 40 | 41 | $this->derivatives[$block_id] = $base_plugin_definition; 42 | $this->derivatives[$block_id]['admin_label'] = $label; 43 | // @Todo Ensure blocks aren't cached. 44 | } 45 | return $this->derivatives; 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/Plugin/Derivative/LocalTasks.php: -------------------------------------------------------------------------------- 1 | initialize(); 20 | } 21 | 22 | /** 23 | * {@inheritdoc} 24 | */ 25 | public static function create(ContainerInterface $container, $base_plugin_id) { 26 | return new static( 27 | $container->get('civicrm') 28 | ); 29 | } 30 | 31 | /** 32 | * {@inheritdoc} 33 | */ 34 | public function getDerivativeDefinitions($base_plugin_definition) { 35 | $uf_groups = \CRM_Core_BAO_UFGroup::getModuleUFGroup('User Account'); 36 | 37 | foreach ($uf_groups as $key => $uf_group) { 38 | if ($uf_group['is_active']) { 39 | $this->derivatives["civicrm.{$key}"] = $base_plugin_definition; 40 | $this->derivatives["civicrm.{$key}"]['title'] = empty($uf_group['frontend_title']) ? $uf_group['title'] : $uf_group['frontend_title']; 41 | $this->derivatives["civicrm.{$key}"]['route_parameters'] = ['profile' => $key]; 42 | } 43 | } 44 | 45 | return $this->derivatives; 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/Routing/Routes.php: -------------------------------------------------------------------------------- 1 | initialize(); 24 | $d8System = \CRM_Core_Config::singleton()->userSystem; 25 | 26 | $items = \CRM_Core_Menu::items(); 27 | 28 | // CiviCRM doesn't list optional path components. So we include 5 optional 29 | // components for each route, and let each default to empty string. 30 | foreach ($items as $path => $item) { 31 | $route = new Route( 32 | '/' . $path . '/{extra}', 33 | [ 34 | '_title' => isset($item['title']) ? $item['title'] : 'CiviCRM', 35 | '_controller' => 'Drupal\civicrm\Controller\CivicrmController::main', 36 | 'args' => $path, 37 | 'extra' => '', 38 | ], 39 | [ 40 | '_access' => 'TRUE', 41 | 'extra' => '.+', 42 | ] 43 | ); 44 | $route_name = $d8System->parseUrl($path)['route_name']; 45 | $collection->add($route_name, $route); 46 | } 47 | 48 | return $collection; 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /icons/787878/CiviCRM.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 8 | 9 | 10 | 15 | 16 | 17 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /icons/bebebe/CiviCRM.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 8 | 9 | 10 | 15 | 16 | 17 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /icons/ffffff/CiviCRM.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 8 | 9 | 10 | 15 | 16 | 17 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /src/Entity/CivicrmDatabaseStorage.php: -------------------------------------------------------------------------------- 1 | get('database'); 26 | } 27 | return new static( 28 | $entity_type, 29 | $database, 30 | $container->get('entity.manager'), 31 | $container->get('cache.entity'), 32 | $container->get('language_manager') 33 | ); 34 | } 35 | 36 | /** 37 | * {@inheritdoc} 38 | */ 39 | public function onEntityTypeCreate(EntityTypeInterface $entity_type) { 40 | // Do nothing. 41 | } 42 | 43 | /** 44 | * {@inheritdoc} 45 | */ 46 | public function onEntityTypeDelete(EntityTypeInterface $entity_type) { 47 | // Do nothing. 48 | } 49 | 50 | /** 51 | * {@inheritdoc} 52 | */ 53 | public function onEntityTypeUpdate(EntityTypeInterface $entity_type, EntityTypeInterface $original) { 54 | // Do nothing. 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /civicrm.config.php.drupal: -------------------------------------------------------------------------------- 1 | 'fieldset', 17 | '#title' => t('CiviCRM'), 18 | '#collapsible' => TRUE, 19 | '#weight' => 9, 20 | ]; 21 | 22 | $args = $form_state->getBuildInfo()['args']; 23 | $theme_options = $args[0]; 24 | 25 | $config = \Drupal::config('civicrmtheme.settings'); 26 | 27 | $form['admin_theme']['civicrm']['civicrm_admin'] = [ 28 | '#type' => 'select', 29 | '#options' => ['' => t('Default theme')] + $theme_options, 30 | '#title' => t('CiviCRM Administration theme'), 31 | '#description' => t('Choose theme for CiviCRM administration/backend pages.'), 32 | '#default_value' => $config->get('admin_theme'), 33 | ]; 34 | 35 | $form['admin_theme']['civicrm']['civicrm_public'] = [ 36 | '#type' => 'select', 37 | '#options' => ['' => t('Default theme')] + $theme_options, 38 | '#title' => t('CiviCRM Public theme'), 39 | '#description' => t('Choose theme for CiviCRM frontend pages.'), 40 | '#default_value' => $config->get('public_theme'), 41 | ]; 42 | 43 | // Add extra submit. 44 | $form['#submit'][] = 'civicrmtheme_system_themes_admin_form_submit'; 45 | $form['admin_theme']['actions']['#weight'] = 10; 46 | } 47 | 48 | /** 49 | * Process system_themes_form extra submit. 50 | */ 51 | function civicrmtheme_system_themes_admin_form_submit($form, FormStateInterface $form_state) { 52 | $config = \Drupal::configFactory()->getEditable('civicrmtheme.settings'); 53 | $config->set('admin_theme', $form_state->getValue('civicrm_admin')); 54 | $config->set('public_theme', $form_state->getValue('civicrm_public')); 55 | $config->save(); 56 | 57 | $form_state->unsetValue('civicrm_admin'); 58 | $form_state->unsetValue('civicrm_public'); 59 | } 60 | -------------------------------------------------------------------------------- /src/Plugin/Block/CivicrmBlock.php: -------------------------------------------------------------------------------- 1 | initialize(); 38 | \CRM_Core_Resources::singleton()->addCoreResources(); 39 | } 40 | 41 | /** 42 | * {@inheritdoc} 43 | */ 44 | public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { 45 | return new static( 46 | $container->get('civicrm'), 47 | $configuration, 48 | $plugin_id, 49 | $plugin_definition 50 | ); 51 | } 52 | 53 | /** 54 | * {@inheritdoc} 55 | */ 56 | public function build() { 57 | $block_id = $this->getDerivativeId(); 58 | $block = \CRM_Core_Block::getContent($block_id); 59 | 60 | // Bypass Drupal SafeString escaping by setting output as already escaped. 61 | if (!empty($block['content'])) { 62 | return [ 63 | '#markup' => Markup::create($block['content']), 64 | '#cache' => ['max-age' => 0], 65 | ]; 66 | } 67 | return []; 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /src/CivicrmBreadcrumbBuilder.php: -------------------------------------------------------------------------------- 1 | stringTranslation = $stringTranslation; 28 | $this->civicrmPageState = $civicrmPageState; 29 | } 30 | 31 | /** 32 | * {@inheritdoc} 33 | */ 34 | public function applies(RouteMatchInterface $route_match, ?CacheableMetadata $cacheable_metadata = NULL) { 35 | $route_object = $route_match->getRouteObject(); 36 | 37 | if ($cacheable_metadata) { 38 | $cacheable_metadata->addCacheContexts(['route']); 39 | } 40 | 41 | // No route object is defined, so we can't inspect it. 42 | if (!$route_object) { 43 | return FALSE; 44 | } 45 | 46 | $controller = $route_object->getDefault('_controller'); 47 | 48 | // When we're looking at a page that does not come from a route to a 49 | // controller (such as an entity, view, or something else), this can't be 50 | // our CiviCRM controller. 51 | if ($controller === NULL) { 52 | return FALSE; 53 | } 54 | 55 | if ($controller === 'Drupal\civicrm\Controller\CivicrmController::main') { 56 | return TRUE; 57 | } 58 | return FALSE; 59 | } 60 | 61 | /** 62 | * {@inheritdoc} 63 | */ 64 | public function build(RouteMatchInterface $route_match) { 65 | $breadcrumb = new Breadcrumb(); 66 | $breadcrumb->addCacheContexts(['url']); 67 | $breadcrumb->addLink(Link::createFromRoute($this->t('Home'), '')); 68 | 69 | foreach ($this->civicrmPageState->getBreadcrumbs() as $name => $url) { 70 | // All urls here have been passed trough CRM_Utils_System::url, so we have 71 | // to parse and decode them before creating a drupal Url object. 72 | $url = Url::fromUserInput(html_entity_decode($url)); 73 | $breadcrumb->addLink(new Link($name, $url)); 74 | } 75 | return $breadcrumb; 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /src/PathProcessor/CivicrmPathProcessor.php: -------------------------------------------------------------------------------- 1 | initialize(); 31 | // Fetch civicrm menu items. 32 | $items = \Civi::cache('long')->get('CivicrmPathProcessor-Core_Menu_items'); 33 | if (empty($items)) { 34 | $items = \CRM_Core_Menu::items(); 35 | \Civi::cache('long')->set('CivicrmPathProcessor-Core_Menu_items', $items); 36 | } 37 | \Civi::$statics[__CLASS__]['knownPaths'][$path] = $path; 38 | $longest = ''; 39 | foreach (array_keys($items) as $item) { 40 | $item = '/' . $item; 41 | if ($path === $item) { 42 | $longest = $item; 43 | break; 44 | } 45 | if (str_starts_with($path, "$item/") && strlen($item) > strlen($longest)) { 46 | $longest = $item; 47 | } 48 | } 49 | if (!empty($longest)) { 50 | // Parse url component parameters from path. 51 | $params = str_replace($longest, '', $path); 52 | // Replace slashes with colons and the controller will piece it back 53 | // together. 54 | if (strlen($params)) { 55 | $params = str_replace('/', ':', $params); 56 | if (substr($params, 0, 1) == ':') { 57 | $params = substr($params, 1); 58 | } 59 | \Civi::$statics[__CLASS__]['knownPaths'][$path] = "$longest/$params"; 60 | } 61 | else { 62 | \Civi::$statics[__CLASS__]['knownPaths'][$path] = $longest; 63 | } 64 | } 65 | return \Civi::$statics[__CLASS__]['knownPaths'][$path]; 66 | } 67 | return $path; 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | CiviCRM Drupal 8 Module 2 | ======================= 3 | 4 | This is the integration module required to allow CiviCRM and 5 | Drupal 8 to work together. 6 | 7 | For Views integration, please use: [civicrm_entity](https://github.com/eileenmcnaughton/civicrm_entity/tree/8.x-3.x). As per [dev/drupal#39](https://lab.civicrm.org/dev/drupal/issues/39), the views integration from this module has been removed. 8 | 9 | Documentation 10 | ---------------------------- 11 | 12 | To install CiviCRM on Drupal 8 see the [Drupal 8 section of the CiviCRM Installation Guide](https://docs.civicrm.org/installation/en/latest/drupal8/) 13 | 14 | Contribute 15 | ---------- 16 | 17 | If you want to contribute to the development of this module, please bear the following in mind: 18 | 19 | * We currently do not have any automated testing setup on Drupal8, so please do a fair amount of testing. 20 | * Many of the pull-request reviewers are not yet fully up to date on Drupal8. Please provide enough information so that we can understand the proposed change and the potential impacts. 21 | * Please open issues on CiviCRM's Gitlab: https://lab.civicrm.org/dev/drupal/issues/ 22 | 23 | If you have any questions, please join the [Drupal channel on CiviCRM's chat](https://chat.civicrm.org/civicrm/channels/drupal) 24 | 25 | We are very grateful for the contributions so far, a lot of amazing work has been done already. The CiviCRM Drupal8 integration is almost ready and there are many organisations already using it in production. However, we also need to invest into improving some of the CiviCRM core bits that will make it easier to use Composer, improve our continuous integration and test coverage for Drupal, and fix a few remaining difficult issues that for now require various workarounds. 26 | 27 | Welcome to CiviCRM and thank you for contributing! 28 | 29 | About CiviCRM 30 | ------------- 31 | 32 | CiviCRM is web-based, open source, Constituent Relationship Management (CRM) software geared toward meeting the needs of non-profit and other civic-sector organizations. 33 | 34 | As a non profit committed to the public good itself, CiviCRM understands that forging and growing strong relationships with constituents is about more than collecting and tracking constituent data - it is about sustaining relationships with supporters over time. 35 | 36 | To this end, CiviCRM has created a robust web-based, open source, highly customizable, CRM to meet organizations’ highest expectations right out-of-the box. Each new release of this open source software reflects the very real needs of its users as enhancements are continually given back to the community. 37 | 38 | With CiviCRM's robust feature set, organizations can further their mission through contact management, fundraising, event management, member management, mass e-mail marketing, peer-to-peer campaigns, case management, and much more. 39 | 40 | CiviCRM is localized in over 20 languages including: Chinese (Taiwan, China), Dutch, English (Australia, Canada, U.S., UK), French (France, Canada), German, Italian, Japanese, Russian, and Swedish. 41 | 42 | For more information, visit the CiviCRM website. 43 | -------------------------------------------------------------------------------- /civicrm.user.inc: -------------------------------------------------------------------------------- 1 | initialize(); 16 | 17 | if (\Drupal::hasService('masquerade')) { 18 | // https://github.com/civicrm/civicrm-drupal-8/pull/31 19 | // In theory this is harmless whether we masquerade or not, but for now narrowing 20 | // the scope, in case it causes regressions. 21 | // Not using isMasquerading() because it does not seem to be 22 | // initialized at this point (it always returns false). 23 | \CRM_Core_Session::singleton()->reset(FALSE); 24 | } 25 | 26 | \Drupal::service('civicrm')->synchronizeUser($account); 27 | } 28 | 29 | /** 30 | * Implements hook_user_insert(). 31 | */ 32 | function civicrm_user_insert(AccountInterface $account) { 33 | $civicrm = \Drupal::service('civicrm'); 34 | $civicrm->initialize(); 35 | civicrm_key_disable(); 36 | $userSystem = CRM_Core_Config::singleton()->userSystem; 37 | $userSystemID = $userSystem->getBestUFID($account); 38 | $uniqId = $userSystem->getBestUFUniqueIdentifier($account); 39 | \CRM_Core_BAO_UFMatch::synchronizeUFMatch($account, $userSystemID, $uniqId, 'Drupal8', NULL, 'Individual', $isLogin = FALSE); 40 | 41 | // As per CRM-7858, the email address in CiviCRM isn't always set 42 | // with a call to synchronize(). So we force this through. 43 | $contact_id = \CRM_Core_BAO_UFMatch::getContactId($account->id()); 44 | if (empty($contact_id)) { 45 | return; 46 | } 47 | \CRM_Core_BAO_UFMatch::updateContactEmail($contact_id, $account->getEmail()); 48 | 49 | // If already in CiviCRM, we don't do then next bit because it will cause 50 | // the current request to exit, stopping execution. 51 | $config = CRM_Core_Config::singleton(); 52 | if ($config->inCiviCRM) { 53 | return; 54 | } 55 | 56 | // Process any profile form fields that may have been submitted. 57 | // In particular, this will pick up form fields that were submitted on the 58 | // user_registration page. 59 | if (civicrm_on_user_page()) { 60 | \CRM_Core_BAO_UFGroup::getEditHTML($contact_id, '', 2, TRUE, FALSE, NULL, FALSE, $civicrm->getCtype()); 61 | } 62 | } 63 | 64 | /** 65 | * Implements hook_user_update(). 66 | */ 67 | function civicrm_user_update(AccountInterface $account) { 68 | \Drupal::service('civicrm')->initialize(); 69 | 70 | // Update primary email address of contact if it has changed. 71 | $contact_id = \CRM_Core_BAO_UFMatch::getContactId($account->id()); 72 | if ($contact_id) { 73 | $contact_email = \CRM_Contact_BAO_Contact::getPrimaryEmail($contact_id); 74 | if ($contact_email != $account->getEmail()) { 75 | \CRM_Core_BAO_UFMatch::updateContactEmail($contact_id, $account->getEmail()); 76 | } 77 | } 78 | 79 | // @Todo Drupal 7 code cleared navigation menu if it detected a change in roles. 80 | // \CRM_Core_BAO_Navigation::resetNavigation($contact_id); 81 | } 82 | 83 | /** 84 | * Implements hook_user_delete(). 85 | */ 86 | function civicrm_user_delete(AccountInterface $account) { 87 | \Drupal::service('civicrm')->initialize(); 88 | \CRM_Core_BAO_UFMatch::deleteUser($account->id()); 89 | } 90 | -------------------------------------------------------------------------------- /tests/src/FunctionalJavascript/CiviCrmTestBase.php: -------------------------------------------------------------------------------- 1 | drupalPlaceBlock('page_title_block'); 26 | $this->drupalPlaceBlock('local_tasks_block'); 27 | $this->drupalPlaceBlock('local_actions_block'); 28 | } 29 | 30 | /** 31 | * {@inheritdoc} 32 | */ 33 | protected function cleanupEnvironment() { 34 | parent::cleanupEnvironment(); 35 | $civicrm_test_conn = Database::getConnection('default', 'civicrm_test'); 36 | // Disable foreign key checks so that tables can be dropped. 37 | $civicrm_test_conn->query('SET FOREIGN_KEY_CHECKS = 0;')->execute(); 38 | $civicrm_schema = $civicrm_test_conn->schema(); 39 | $tables = $civicrm_schema->findTables('%'); 40 | // Comment out if you want to view the tables/contents before deleting them 41 | // throw new \Exception(var_export($tables, TRUE)); 42 | foreach ($tables as $table) { 43 | if ($civicrm_schema->dropTable($table)) { 44 | unset($tables[$table]); 45 | } 46 | } 47 | $civicrm_test_conn->query('SET FOREIGN_KEY_CHECKS = 1;')->execute(); 48 | } 49 | 50 | /** 51 | * {@inheritdoc} 52 | */ 53 | protected function changeDatabasePrefix(): void { 54 | parent::changeDatabasePrefix(); 55 | $connection_info = Database::getConnectionInfo('default'); 56 | // CiviCRM does not leverage table prefixes, so we unset it. This way any 57 | // `civicrm_` tables are more easily cleaned up at the end of the test. 58 | $civicrm_connection_info = $connection_info['default']; 59 | unset($civicrm_connection_info['prefix']); 60 | Database::addConnectionInfo('civicrm_test', 'default', $civicrm_connection_info); 61 | Database::addConnectionInfo('civicrm', 'default', $civicrm_connection_info); 62 | 63 | // Assert that there are no `civicrm_` tables in the test database. 64 | $connection = Database::getConnection('default', 'civicrm_test'); 65 | $schema = $connection->schema(); 66 | $tables = $schema->findTables('civicrm_%'); 67 | if (count($tables) > 0) { 68 | throw new \RuntimeException('The provided database connection in SIMPLETEST_DB contains CiviCRM tables, use a different database.'); 69 | } 70 | } 71 | 72 | /** 73 | * {@inheritdoc} 74 | */ 75 | protected function prepareSettings() { 76 | parent::prepareSettings(); 77 | 78 | // Set the test environment variables for CiviCRM. 79 | $filename = $this->siteDirectory . '/settings.php'; 80 | chmod($filename, 0666); 81 | 82 | $constants = <<civicrm = $civicrm; 42 | $this->civicrmPageState = $civicrmPageState; 43 | } 44 | 45 | /** 46 | * {@inheritdoc} 47 | */ 48 | public static function create(ContainerInterface $container) { 49 | return new static( 50 | $container->get('civicrm'), 51 | $container->get('civicrm.page_state') 52 | ); 53 | } 54 | 55 | /** 56 | * Main controller, passes trough to CiviCRM. 57 | */ 58 | public function main($args, $extra) { 59 | // $args should usually be a `string`, but (when upgrading, e.g. from 5.61.0) it may be `array`. 60 | $args = is_array($args) ? $args : explode('/', $args); 61 | 62 | if ($extra) { 63 | $args = array_merge($args, explode(':', $extra)); 64 | } 65 | 66 | // CiviCRM's Invoke.php has hardwired in the expectation that the query 67 | // parameter 'q' is being used. We recreate that parameter. Ideally in the 68 | // future, this data should be passed in explicitly and not tied to an 69 | // environment variable. 70 | $_GET['q'] = implode('/', $args); 71 | 72 | // Need to disable the page cache. 73 | \Drupal::service('page_cache_kill_switch')->trigger(); 74 | 75 | // Synchronize the Drupal user with the Contacts database (dev/drupal#107) 76 | if (!$this->currentUser()->isAnonymous()) { 77 | $this->civicrm->synchronizeUser(User::load($this->currentUser()->id())); 78 | } 79 | 80 | // @Todo: Enable CiviCRM's CRM_Core_TemporaryErrorScope::useException() and 81 | // possibly catch exceptions. At the moment, civicrm doesn't allow 82 | // exceptions to bubble up to Drupal. See CRM-15022. 83 | $content = $this->civicrm->invoke($args); 84 | 85 | if ($this->civicrmPageState->isAccessDenied()) { 86 | throw new AccessDeniedHttpException(); 87 | } 88 | 89 | // We set the CiviCRM markup as safe and assume all XSS (an other) issues 90 | // have already been taken care of. 91 | $build = [ 92 | '#markup' => Markup::create($content), 93 | '#cache' => [ 94 | 'max-age' => 0, 95 | ], 96 | ]; 97 | 98 | // Override default title value if one has been set in the course 99 | // of calling \CRM_Core_Invoke::invoke(). 100 | if ($title = $this->civicrmPageState->getTitle()) { 101 | // Mark the pageTitle as safe so markup is not escaped by Drupal. 102 | // This handles the case where, eg. the page title is surrounded by 103 | // . 104 | // @TODO: This is a naughty way to do this. Better to have CiviCRM passing 105 | // us no markup whatsoever. 106 | $build['#title'] = Markup::create($title); 107 | } 108 | 109 | return $build; 110 | } 111 | 112 | } 113 | -------------------------------------------------------------------------------- /src/CivicrmPageState.php: -------------------------------------------------------------------------------- 1 | title = $title; 60 | } 61 | 62 | /** 63 | * Returns the page title. 64 | * 65 | * @return string 66 | * The page title. 67 | */ 68 | public function getTitle() { 69 | return $this->title; 70 | } 71 | 72 | /** 73 | * Adds extra css files. 74 | * 75 | * @todo Are we sure this needs to be an array, this is different from ::addJs 76 | * for no reason? 77 | * 78 | * @param string[] $css 79 | * A list of css files to add. 80 | */ 81 | public function addCSS(array $css) { 82 | $this->css[] = $css; 83 | } 84 | 85 | /** 86 | * Returns all css files. 87 | * 88 | * @return string[] 89 | * A list of css files. 90 | */ 91 | public function getCSS() { 92 | return $this->css; 93 | } 94 | 95 | /** 96 | * Adds extra js files. 97 | * 98 | * @param string[] $script 99 | * A list of js files to add. 100 | */ 101 | public function addJS($script) { 102 | $this->js[] = $script; 103 | } 104 | 105 | /** 106 | * Returns all js files. 107 | * 108 | * @return string[] 109 | * A list of js files. 110 | */ 111 | public function getJS() { 112 | return $this->js; 113 | } 114 | 115 | /** 116 | * Add a breadcrumb item. 117 | * 118 | * @param string $name 119 | * The title of the breadcrumb item. 120 | * @param string $url 121 | * The url the item should link to. 122 | */ 123 | public function addBreadcrumb($name, $url) { 124 | $this->breadcrumbs[$name] = $url; 125 | } 126 | 127 | /** 128 | * Reset the breadcrumbs back to an empty list. 129 | */ 130 | public function resetBreadcrumbs() { 131 | $this->breadcrumbs = []; 132 | } 133 | 134 | /** 135 | * Returns all breadcrumb items. 136 | * 137 | * @return string[] 138 | * A list of breadcrumb urls, keyed by name. 139 | */ 140 | public function getBreadcrumbs() { 141 | return $this->breadcrumbs; 142 | } 143 | 144 | /** 145 | * Add html header items. 146 | * 147 | * @param string $html 148 | * Add another item to the html head section. 149 | */ 150 | public function addHtmlHeader($html) { 151 | $this->htmlHeaders[] = $html; 152 | } 153 | 154 | /** 155 | * Returns a list of header items. 156 | * 157 | * @return string[] 158 | * A list of items to add to the html head section. 159 | */ 160 | public function getHtmlHeaders() { 161 | return implode(' ', $this->htmlHeaders); 162 | } 163 | 164 | /** 165 | * Set the page to deny access. 166 | */ 167 | public function setAccessDenied() { 168 | $this->accessDenied = TRUE; 169 | } 170 | 171 | /** 172 | * Returns the access state for this page. 173 | * 174 | * @return bool 175 | * Returns TRUE when access is denied. 176 | */ 177 | public function isAccessDenied() { 178 | return $this->accessDenied; 179 | } 180 | 181 | } 182 | -------------------------------------------------------------------------------- /modules/civicrmtheme/src/Theme/CivicrmThemeNegotiator.php: -------------------------------------------------------------------------------- 1 | user = $user; 49 | $this->configFactory = $config_factory; 50 | $this->civicrm = $civicrm; 51 | } 52 | 53 | /** 54 | * {@inheritdoc} 55 | */ 56 | public function applies(RouteMatchInterface $route_match) { 57 | $route = $route_match->getRouteObject(); 58 | 59 | // Some pages, like 404 pages, don't have a route objet. 60 | if (!$route) { 61 | return FALSE; 62 | } 63 | 64 | $parts = explode('/', ltrim($route->getPath(), '/')); 65 | 66 | if ($parts[0] != 'civicrm') { 67 | return FALSE; 68 | } 69 | 70 | $config = $this->configFactory->get('civicrmtheme.settings'); 71 | $admin_theme = $config->get('admin_theme'); 72 | $public_theme = $config->get('public_theme'); 73 | 74 | if (!$admin_theme && !$public_theme) { 75 | return FALSE; 76 | } 77 | 78 | // Attempt to initialize CiviCRM. 79 | try { 80 | $this->civicrm->initialize(); 81 | } 82 | catch (\Exception $e) { 83 | return FALSE; 84 | } 85 | 86 | return TRUE; 87 | } 88 | 89 | /** 90 | * {@inheritdoc} 91 | */ 92 | public function determineActiveTheme(RouteMatchInterface $route_match) { 93 | $path = ltrim($route_match->getRouteObject()->getPath(), '/'); 94 | 95 | $config = $this->configFactory->get('civicrmtheme.settings'); 96 | $admin_theme = $config->get('admin_theme'); 97 | $public_theme = $config->get('public_theme'); 98 | 99 | // If neither the admin_theme or public theme have been set, we return NULL 100 | // to let Drupal choose the correct active theme. 101 | if (!$admin_theme && !$public_theme) { 102 | return NULL; 103 | } 104 | 105 | // If the public theme is configured and the user does not have permission 106 | // to access CiviCRM pages, use the public theme. 107 | if (!$this->user->hasPermission('access CiviCRM')) { 108 | if ($public_theme) { 109 | return $public_theme; 110 | } 111 | return NULL; 112 | } 113 | 114 | // Initialize CiviCRM and get the CiviCRM menu item definition for this 115 | // path. 116 | $this->civicrm->initialize(); 117 | $item = \CRM_Core_Menu::get($path); 118 | 119 | // If the current menu item is public, we use the public theme, in other 120 | // cases the admin_theme is used. 121 | if (\CRM_Utils_Array::value('is_public', $item) && $public_theme) { 122 | return $public_theme; 123 | } 124 | 125 | // If the current menu item is not public apply civicrm admin theme. 126 | if (!\CRM_Utils_Array::value('is_public', $item) && ($admin_theme)) { 127 | return $admin_theme; 128 | } 129 | 130 | return NULL; 131 | } 132 | 133 | } 134 | -------------------------------------------------------------------------------- /src/Form/UserProfile.php: -------------------------------------------------------------------------------- 1 | initialize(); 45 | } 46 | 47 | /** 48 | * {@inheritdoc} 49 | */ 50 | public static function create(ContainerInterface $container) { 51 | return new static( 52 | $container->get('civicrm') 53 | ); 54 | } 55 | 56 | /** 57 | * {@inheritdoc} 58 | */ 59 | public function getFormId() { 60 | return 'civicrm_user_profile'; 61 | } 62 | 63 | /** 64 | * {@inheritdoc} 65 | */ 66 | public function buildForm(array $form, FormStateInterface $form_state, AccountInterface $user = NULL, $profile = NULL) { 67 | // Make the controller state available to form overrides. 68 | $form_state->set('controller', $this); 69 | $this->user = $user; 70 | 71 | // Search for the profile form, otherwise generate a 404. 72 | $uf_groups = \CRM_Core_BAO_UFGroup::getModuleUFGroup('User Account'); 73 | if (empty($uf_groups[$profile])) { 74 | throw new ResourceNotFoundException(); 75 | } 76 | $this->ufGroup = $uf_groups[$profile]; 77 | 78 | // Grab the form html. 79 | $this->contactId = \CRM_Core_BAO_UFMatch::getContactId($user->id()); 80 | $html = \CRM_Core_BAO_UFGroup::getEditHTML($this->contactId, $this->ufGroup['title']); 81 | 82 | // Include additional civicrm core (js/css) resources (e.g. for radio buttons) 83 | $html .= \CRM_Core_Region::instance('form-bottom')->render('', FALSE); 84 | \CRM_Core_Resources::singleton()->addCoreResources(); 85 | 86 | $form['#title'] = $this->user->getDisplayName(); 87 | $form['#attributes'] = ['enctype' => "multipart/form-data"]; 88 | $form['form'] = [ 89 | '#type' => 'fieldset', 90 | '#title' => $this->ufGroup['title'], 91 | 'html' => [ 92 | '#markup' => Markup::create($html), 93 | ], 94 | ]; 95 | $form['actions'] = [ 96 | '#type' => 'actions', 97 | 'submit' => [ 98 | '#type' => 'submit', 99 | '#value' => t('Save'), 100 | '#button_type' => 'primary', 101 | ], 102 | ]; 103 | 104 | return $form; 105 | } 106 | 107 | /** 108 | * {@inheritdoc} 109 | */ 110 | public function validateForm(array &$form, FormStateInterface $form_state) { 111 | $errors = \CRM_Core_BAO_UFGroup::isValid($this->contactId, $this->ufGroup['name']); 112 | 113 | if (is_array($errors)) { 114 | foreach ($errors as $name => $error) { 115 | $form_state->setErrorByName($name, $error); 116 | } 117 | } 118 | } 119 | 120 | /** 121 | * {@inheritdoc} 122 | */ 123 | public function submitForm(array &$form, FormStateInterface $form_state) { 124 | // Somehow, somewhere, CiviCRM is processing our form. I have no idea how. 125 | // Invalidate caches for user, so that latest profile information shows. 126 | Cache::invalidateTags(['user:' . $this->user->id()]); 127 | $this->messenger()->addMessage($this->t("Profile successfully updated.")); 128 | } 129 | 130 | /** 131 | * Controls access for this form. 132 | */ 133 | public function access($profile, $user) { 134 | $uf_groups = \CRM_Core_BAO_UFGroup::getModuleUFGroup('User Account', 0, FALSE, \CRM_Core_Permission::EDIT); 135 | $cid = \CRM_Core_BAO_UFMatch::getContactId($user); 136 | 137 | if (isset($uf_groups[$profile]) && isset($cid) && \CRM_Contact_BAO_Contact_Permission::allow($cid, \CRM_Core_Permission::EDIT)) { 138 | return AccessResult::allowed(); 139 | } 140 | return AccessResult::forbidden(); 141 | } 142 | 143 | } 144 | -------------------------------------------------------------------------------- /src/Civicrm.php: -------------------------------------------------------------------------------- 1 | isInitialized()) { 27 | return; 28 | } 29 | 30 | // Get ready for problems. 31 | $docLinkInstall = "http://wiki.civicrm.org/confluence/display/CRMDOC/Drupal+Installation+Guide"; 32 | $docLinkTrouble = "http://wiki.civicrm.org/confluence/display/CRMDOC/Installation+and+Configuration+Trouble-shooting"; 33 | $forumLink = "http://forum.civicrm.org/index.php/board,6.0.html"; 34 | 35 | $errorMsgAdd = t("Please review the Drupal Installation Guide and the Trouble-shooting page for assistance. If you still need help installing, you can often find solutions to your issue by searching for the error message in the installation support section of the community forum.

", 36 | ['!1' => $docLinkInstall, '!2' => $docLinkTrouble, '!3' => $forumLink] 37 | ); 38 | 39 | $settingsFile = \Drupal::service('kernel')->getSitePath() . '/civicrm.settings.php'; 40 | if (!defined('CIVICRM_SETTINGS_PATH')) { 41 | define('CIVICRM_SETTINGS_PATH', $settingsFile); 42 | } 43 | 44 | $output = include_once $settingsFile; 45 | if ($output == FALSE) { 46 | $msg = t("The CiviCRM settings file (civicrm.settings.php) was not found in the expected location: %location", ['%location' => $settingsFile]) . ' ' . $errorMsgAdd; 47 | throw new CiviCRMConfigException($msg); 48 | } 49 | 50 | // This does pretty much all of the civicrm initialization. 51 | $output = include_once 'CRM/Core/Config.php'; 52 | if ($output == FALSE) { 53 | $msg = t("The path for including CiviCRM code files is not set properly. Most likely there is an error in the civicrm_root setting in your CiviCRM settings file (!1).", 54 | ['!1' => $settingsFile] 55 | ) . t("civicrm_root is currently set to: !1.", ['!1' => $civicrm_root]) . $errorMsgAdd; 56 | throw new CiviCRMConfigException($msg); 57 | } 58 | 59 | // Initialize the system by creating a config object. 60 | \CRM_Core_Config::singleton()->userSystem->setMySQLTimeZone(); 61 | 62 | // Mark CiviCRM as initialized. 63 | static::$initialized = TRUE; 64 | } 65 | 66 | /** 67 | * Checks if the CiviCRM link is already initialized. 68 | */ 69 | public function isInitialized() { 70 | return static::$initialized; 71 | } 72 | 73 | /** 74 | * Invoke a CiviCRM method from Drupal. 75 | * 76 | * Wraps around \CRM_Core_Invoke::invoke. 77 | */ 78 | public function invoke($args) { 79 | $this->initialize(); 80 | 81 | // Add CSS, JS, etc. that is required for this page. 82 | \CRM_Core_Resources::singleton()->addCoreResources(); 83 | 84 | // CiviCRM will echo/print directly to stdout. We need to capture it so that 85 | // we can return the output as a renderable array. 86 | ob_start(); 87 | $content = \CRM_Core_Invoke::invoke($args); 88 | $output = ob_get_clean(); 89 | return !empty($content) ? $content : $output; 90 | } 91 | 92 | /** 93 | * Synchronize a Drupal account with CiviCRM. 94 | * 95 | * This is a wrapper for CRM_Core_BAO_UFMatch::synchronize(). 96 | * 97 | * @param \Drupal\Core\Session\AccountInterface $account 98 | * The drupal user. 99 | * @param string $contact_type 100 | * The user contact type. 101 | */ 102 | public function synchronizeUser(AccountInterface $account, $contact_type = 'Individual') { 103 | $this->initialize(); 104 | \CRM_Core_BAO_UFMatch::synchronize($account, FALSE, 'Drupal', $this->getCtype($contact_type)); 105 | } 106 | 107 | /** 108 | * Function to get the contact type. 109 | * 110 | * @param string $default 111 | * Default contact type. 112 | * 113 | * @return string 114 | * The contact type. 115 | * 116 | * @Todo: Document what this function is doing and why. 117 | */ 118 | public function getCtype($default = 'Individual') { 119 | if (!empty($_REQUEST['ctype'])) { 120 | $ctype = $_REQUEST['ctype']; 121 | } 122 | elseif (!empty($_REQUEST['edit']['ctype'])) { 123 | $ctype = $_REQUEST['edit']['ctype']; 124 | } 125 | else { 126 | $ctype = $default; 127 | } 128 | 129 | if (!in_array($ctype, ['Individual', 'Organization', 'Household'])) { 130 | $ctype = $default; 131 | } 132 | return $ctype; 133 | } 134 | 135 | } 136 | -------------------------------------------------------------------------------- /civicrm.install: -------------------------------------------------------------------------------- 1 | getPendingAction() !== NULL) { 18 | // Ex: If you do an advanced installation with `cv core:install`, then 19 | // `hook_install` shouldn't activate the default/unconfigured install. 20 | return; 21 | } 22 | 23 | $installed = $setup->checkInstalled(); 24 | if ($installed->isDatabaseInstalled()) { 25 | throw new \Exception("CiviCRM appears to have already been installed. Skipping full installation."); 26 | } 27 | if ($installed->isSettingInstalled()) { 28 | $setup->getModel()->setValues(['doNotCreateSettingsFile' => TRUE]); 29 | } 30 | 31 | $setup->installFiles(); 32 | $setup->installDatabase(); 33 | } 34 | 35 | /** 36 | * Implements hook_uninstall(). 37 | */ 38 | function civicrm_uninstall() { 39 | /** @var \Civi\Setup $setup */ 40 | $setup = _civicrm_setup(); 41 | 42 | $setup->uninstallFiles(); 43 | $setup->uninstallDatabase(); 44 | } 45 | 46 | /** 47 | * Implements hook_requirements(). 48 | */ 49 | function civicrm_requirements($phase) { 50 | $requirements = []; 51 | 52 | $civicrm_base = _civicrm_find_civicrm(); 53 | 54 | if ($civicrm_base) { 55 | $requirements['civicrm.location'] = [ 56 | 'title' => 'CiviCRM location', 57 | 'severity' => REQUIREMENT_OK, 58 | 'description' => 'CiviCRM core directory', 59 | ]; 60 | } 61 | else { 62 | $requirements['civicrm.location'] = [ 63 | 'title' => 'CiviCRM location', 64 | 'severity' => REQUIREMENT_ERROR, 65 | 'description' => 'CiviCRM must be installed via composer.', 66 | ]; 67 | return $requirements; 68 | } 69 | 70 | /** @var \Civi\Setup $setup */ 71 | $setup = _civicrm_setup(); 72 | if ($phase === 'install' && !$setup->checkAuthorized()->isAuthorized()) { 73 | $requirements['civicrm.checkAuthorized'] = [ 74 | 'title' => 'CiviCRM Installation Not Authorized', 75 | 'description' => 'The current user does not have sufficient permissions to perform installation.', 76 | 'severity' => REQUIREMENT_WARNING, 77 | ]; 78 | return $requirements; 79 | } 80 | 81 | $severityMap = [ 82 | 'info' => REQUIREMENT_OK, 83 | 'warning' => REQUIREMENT_WARNING, 84 | 'error' => REQUIREMENT_ERROR, 85 | ]; 86 | $sections = [ 87 | 'system' => 'CiviCRM: System', 88 | 'database' => 'CiviCRM: Database', 89 | 'other' => 'CiviCRM: Other', 90 | ]; 91 | 92 | if ($phase !== 'runtime') { 93 | foreach ($setup->checkRequirements()->getMessages() as $msg) { 94 | $section = isset($sections[$msg['section']]) ? $sections[$msg['section']] : $sections['other']; 95 | $key = 'civicrm.' . $msg['section'] . '.' . $msg['name']; 96 | $requirements[$key] = [ 97 | 'title' => $section . ': ' . $msg['message'], 98 | 'description' => $section . ': ' . $msg['message'], 99 | 'severity' => $severityMap[$msg['severity']], 100 | ]; 101 | } 102 | } 103 | 104 | ksort($requirements); 105 | 106 | return $requirements; 107 | } 108 | 109 | /** 110 | * @return \Civi\Setup 111 | */ 112 | function _civicrm_setup() { 113 | if (defined('CIVI_SETUP')) { 114 | return Civi\Setup::instance(); 115 | } 116 | 117 | $civicrm_base = _civicrm_find_civicrm(); 118 | require_once $civicrm_base . '/CRM/Core/ClassLoader.php'; 119 | CRM_Core_ClassLoader::singleton()->register(); 120 | 121 | \Civi\Setup::assertProtocolCompatibility(1.0); 122 | \Civi\Setup::init([ 123 | 'cms' => 'Drupal8', 124 | 'srcPath' => $civicrm_base, 125 | ]); 126 | 127 | return Civi\Setup::instance(); 128 | } 129 | 130 | /** 131 | * Returns the path to where CiviCRM is installed. 132 | * 133 | * Installation via composer is recommended. We also allow /modules/civicrm, 134 | * which seems to work fine. 135 | * 136 | * @return string|null 137 | * A string to the location if we can find where CiviCRM is installed, NULL 138 | * if we can't. 139 | */ 140 | function _civicrm_find_civicrm() { 141 | // TODO: This works with standard composer layouts but would be easy to break 142 | // via installer-paths. However, it should be possible to replace this - since we 143 | // can count on composer's autoloader being setup already. Some ideas: 144 | // - Use ReflectionClass('Civi') to find the path 145 | // - Update `Civi.php` to provide a function with its __DIR__ 146 | 147 | $possible_paths = []; 148 | 149 | if ($path = \Drupal::service('extension.list.module')->getPath('civicrm')) { 150 | $possible_paths[] = $path; 151 | } 152 | $possible_paths[] = 'vendor/civicrm/civicrm-core'; 153 | $possible_paths[] = '../vendor/civicrm/civicrm-core'; 154 | 155 | foreach ($possible_paths as $path) { 156 | if (file_exists($path . '/CRM/Core/ClassLoader.php')) { 157 | return \Drupal::service('file_system')->realpath($path); 158 | } 159 | } 160 | 161 | return NULL; 162 | } 163 | -------------------------------------------------------------------------------- /civicrm.module: -------------------------------------------------------------------------------- 1 | addCoreStyles(); 33 | 34 | /** @var \Drupal\civicrm\CivicrmPageState $page_state */ 35 | $page_state = \Drupal::service('civicrm.page_state'); 36 | 37 | // Merge CiviCRM stuff into HTML header. 38 | if ($region = \CRM_Core_Region::instance('html-header', FALSE)) { 39 | $page_state->addHtmlHeader($region->render('')); 40 | } 41 | 42 | // Attach CSS and JS. 43 | foreach ($page_state->getCSS() as $counter => $css) { 44 | $page['#attached']['html_head'][] = [$css, 'civicrm-css-' . $counter]; 45 | } 46 | foreach ($page_state->getJS() as $counter => $js) { 47 | $page['#attached']['html_head'][] = [$js, 'civicrm-js-' . $counter]; 48 | } 49 | 50 | // Any other miscellaneous headers. 51 | $headers = $page_state->getHtmlHeaders(); 52 | $markup = [ 53 | '#type' => 'markup', 54 | '#weight' => -99, 55 | '#markup' => Markup::create($headers), 56 | ]; 57 | $page['#attached']['html_head'][] = [$markup, 'civicrm-headers']; 58 | 59 | // if we load CiviCRM content on a page, we add a general cache tag 60 | // so we can invalidate Drupal's cache when CiviCRM is flushed 61 | $page['#cache']['tags'][] = 'civicrm'; 62 | } 63 | 64 | /** 65 | * Implements hook_toolbar(). 66 | * 67 | * Injects a link into the Drupal toolbar to /civicrm for users with 68 | * 'access civicrm' permission. 69 | */ 70 | function civicrm_toolbar() { 71 | $items = []; 72 | 73 | // Always return it with right cache context even if it's empty so that the 74 | // permissions can control it's visibility. 75 | $items['civicrm'] = [ 76 | '#cache' => [ 77 | 'contexts' => ['user.permissions', 'url.path'], 78 | ], 79 | ]; 80 | 81 | $user = \Drupal::currentUser(); 82 | if ($user->hasPermission('access CiviCRM')) { 83 | $items['civicrm'] += [ 84 | '#type' => 'toolbar_item', 85 | 'tab' => [ 86 | '#type' => 'link', 87 | '#title' => t('CiviCRM'), 88 | '#url' => Url::fromRoute('civicrm.civicrm'), 89 | '#options' => [ 90 | 'attributes' => [ 91 | 'title' => t('CiviCRM'), 92 | 'class' => [ 93 | 'toolbar-item', 94 | 'toolbar-icon', 95 | 'toolbar-icon-civicrm', 96 | ], 97 | ], 98 | ], 99 | ], 100 | '#attached' => [ 101 | 'library' => [ 102 | 'civicrm/civicrm-icons', 103 | ], 104 | ], 105 | ]; 106 | // Add tray if we are on a CiviCRM screen 107 | $path = ltrim(\Drupal::service('path.current')->getPath(), '/'); 108 | if (strpos($path, 'civicrm') === 0) { 109 | $items['civicrm']['tray'] = [ 110 | '#wrapper_attributes' => [ 111 | 'id' => 'toolbar-tray-civicrm', 112 | ], 113 | 'content' => [ 114 | '#markup' => ' ', 115 | ], 116 | ]; 117 | } 118 | } 119 | 120 | return $items; 121 | } 122 | 123 | /** 124 | * Implements hook_entity_extra_field_info(). 125 | * 126 | * Add additional pseudo-fields to the user display. This allows the UI to 127 | * control the order in which these are displayed, or whether they are displayed 128 | * at all. 129 | * 130 | * @Todo: set these fields are visible ONLY for the 'full' user display. 131 | */ 132 | function civicrm_entity_extra_field_info() { 133 | $extra['user']['user']['display']['civicrm_record'] = [ 134 | 'label' => t('CiviCRM record link'), 135 | 'description' => t('Link to user’s CiviCRM record.'), 136 | 'weight' => 0, 137 | 'visible' => FALSE, 138 | ]; 139 | $extra['user']['user']['display']['civicrm_dashboard'] = [ 140 | 'label' => t('CiviCRM dashboard link'), 141 | 'description' => t('Link to user’s CiviCRM dashboard.'), 142 | 'weight' => 0, 143 | 'visible' => FALSE, 144 | ]; 145 | $extra['user']['user']['display']['civicrm_profiles'] = [ 146 | 'label' => t('CiviCRM profile summaries'), 147 | 'description' => t('A list CiviCRM profile summaries.'), 148 | 'weight' => 0, 149 | 'visible' => FALSE, 150 | ]; 151 | 152 | return $extra; 153 | } 154 | 155 | /** 156 | * Implements hook_ENTITY_TYPE_view(). 157 | * 158 | * We use this hook to add the pseudo-fields we've added in 159 | * civicrm_entity_extra_field_info() to the user display. 160 | */ 161 | function civicrm_user_view(array &$build, UserInterface $account, EntityViewDisplayInterface $display, $view_mode) { 162 | \Drupal::service('civicrm')->initialize(); 163 | 164 | // We need the $contact_id so that we know what data to pull out of Civicrm. 165 | // And we need the contact_id of the current user ($current_contact_id) so 166 | // that we can perform proper access checks. 167 | $current_user = \Drupal::currentUser(); 168 | $contact_id = \CRM_Core_BAO_UFMatch::getContactId($account->id()); 169 | $current_contact_id = \CRM_Core_BAO_UFMatch::getContactId($current_user->id()); 170 | if (!$contact_id || !$current_contact_id) { 171 | return; 172 | } 173 | 174 | // Contact record link. 175 | if (($conf = $display->getComponent('civicrm_record')) && $current_user->hasPermission('access CiviCRM') && \CRM_Contact_BAO_Contact_Permission::allow($current_contact_id)) { 176 | $build['civicrm_record'] = [ 177 | '#type' => 'item', 178 | '#weight' => $conf['weight'], 179 | 0 => [ 180 | '#type' => 'link', 181 | '#title' => t('View contact record'), 182 | '#url' => Url::fromRoute('civicrm.civicrm_contact_view', [ 183 | 'reset' => 1, 184 | 'cid' => $contact_id, 185 | ]), 186 | '#prefix' => '» ', 187 | '#suffix' => '', 188 | ], 189 | ]; 190 | } 191 | 192 | // Contact dashboard link. 193 | if (($conf = $display->getComponent('civicrm_dashboard')) && $current_user->hasPermission('access Contact Dashboard') && \CRM_Contact_BAO_Contact_Permission::allow($current_contact_id)) { 194 | $build['civicrm_dashboard'] = [ 195 | '#type' => 'item', 196 | '#weight' => $conf['weight'], 197 | 0 => [ 198 | '#type' => 'link', 199 | '#title' => t('View contact dashboard'), 200 | '#url' => Url::fromRoute('civicrm.civicrm_user', [ 201 | 'reset' => 1, 202 | 'id' => $contact_id, 203 | ]), 204 | '#prefix' => '» ', 205 | '#suffix' => '', 206 | ], 207 | ]; 208 | } 209 | 210 | // Add profile summaries. 211 | // @Todo Do we need to check permissions before viewing each profile? 212 | if (($conf = $display->getComponent('civicrm_profiles')) && $current_user->hasPermission('profile view')) { 213 | $build['civicrm_profiles'] = [ 214 | '#weight' => $conf['weight'], 215 | ]; 216 | 217 | // We need the CiviCRM core Javascript. 218 | CRM_Core_Resources::singleton()->addCoreResources(); 219 | 220 | foreach (_civicrm_get_profiles($contact_id) as $id => $profile) { 221 | $html = (new \CRM_Profile_Page_Dynamic($contact_id, $id, NULL))->run(); 222 | $build['civicrm_profiles']["civicrm_profile_{$id}"] = [ 223 | '#theme' => 'civicrm_user_profile', 224 | '#title' => $profile['title'], 225 | 0 => [ 226 | '#markup' => Markup::create($html), 227 | ], 228 | // @Todo Check access to this route before displaying the link 229 | 1 => [ 230 | '#type' => 'link', 231 | '#options' => ['html' => TRUE], 232 | '#title' => t('Edit %profile_name', ['%profile_name' => $profile['title']]), 233 | '#url' => Url::fromRoute('civicrm.user_profile', [ 234 | 'user' => $account->id(), 235 | 'profile' => $id, 236 | ]), 237 | '#prefix' => '» ', 238 | '#suffix' => '', 239 | ], 240 | ]; 241 | } 242 | } 243 | } 244 | 245 | /** 246 | * Get 'User Account' profiles. 247 | * 248 | * We return a list of profiles filtered down to only those that are Contact 249 | * based on the $contact_id's contact type. 250 | */ 251 | function _civicrm_get_profiles($contact_id) { 252 | \Drupal::service('civicrm')->initialize(); 253 | $profiles = []; 254 | $ctype = \CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contact_id, 'contact_type'); 255 | 256 | foreach (\CRM_Core_BAO_UFGroup::getModuleUFGroup('User Account') as $id => $uf_group) { 257 | $fieldType = CRM_Core_BAO_UFField::getProfileType($id); 258 | if (CRM_Contact_BAO_ContactType::isaSubType($fieldType)) { 259 | $fieldType = CRM_Contact_BAO_ContactType::getBasicType($fieldType); 260 | } 261 | 262 | // Filter profiles. 263 | if ($fieldType == 'Contact' || $fieldType == $ctype) { 264 | $profiles[$id] = $uf_group; 265 | } 266 | } 267 | return $profiles; 268 | } 269 | 270 | /** 271 | * Implements hook_form_user_form_alter(). 272 | */ 273 | function civicrm_form_user_form_alter(&$form, &$form_state, $form_id) { 274 | // Email is required because otherwise synchronization with contacts 275 | // doesn't work. 276 | $form['account']['mail']['#required'] = TRUE; 277 | } 278 | 279 | /** 280 | * Implements hook_form_TAG_ID_alter(). 281 | * 282 | * Attach any relevant profile form fields to user registration form. 283 | */ 284 | function civicrm_form_user_register_form_alter(&$form, &$form_state, $form_id) { 285 | $civicrm = \Drupal::service('civicrm'); 286 | $civicrm->initialize(); 287 | civicrm_key_disable(); 288 | $html = \CRM_Core_BAO_UFGroup::getEditHTML(NULL, '', NULL, TRUE, TRUE, NULL, FALSE, $civicrm->getCtype()); 289 | 290 | if (str_contains($html, 'type="file"')) { 291 | // If Drupal doesn't set the enctype, CiviCRM will not be able to upload 292 | // the file. Drupal only add this if the form has a file upload field. it 293 | // does not look at the civicrm elements. 294 | $form['#attributes']['enctype'] = 'multipart/form-data'; 295 | } 296 | 297 | // Need to disable the page cache. 298 | \Drupal::service('page_cache_kill_switch')->trigger(); 299 | 300 | // We need the CiviCRM core Javascript. 301 | CRM_Core_Resources::singleton()->addCoreResources(); 302 | 303 | // Email is required because otherwise synchronization with contacts 304 | // doesn't work. 305 | $form['account']['mail']['#required'] = TRUE; 306 | 307 | $form['civicrm_profile_register'] = [ 308 | '#markup' => Markup::create($html), 309 | '#cache' => [ 310 | 'max-age' => 0, 311 | ], 312 | ]; 313 | $form['#validate'][] = '_civicrm_user_register_form_validate'; 314 | } 315 | 316 | /** 317 | * Validation function for additional profile fields on user registration. 318 | */ 319 | function _civicrm_user_register_form_validate(&$form, FormStateInterface $form_state) { 320 | \Drupal::service('civicrm')->initialize(); 321 | civicrm_key_disable(); 322 | $errors = CRM_Core_BAO_UFGroup::isValid(NULL, '', TRUE); 323 | 324 | if (is_array($errors)) { 325 | foreach ($errors as $name => $message) { 326 | $form_state->setErrorByName($name, $message); 327 | } 328 | } 329 | } 330 | 331 | /** 332 | * Determine if the user is on a CiviCRM generated page. 333 | * 334 | * i.e. does the form have some civicrm unique token? 335 | */ 336 | function civicrm_on_user_page() { 337 | return isset($_POST['_qf_default']); 338 | } 339 | 340 | /** 341 | * Implements hook_theme(). 342 | */ 343 | function civicrm_theme() { 344 | return [ 345 | 'civicrm_contact' => [ 346 | 'render element' => 'elements', 347 | 'template' => 'civicrm-contact', 348 | ], 349 | 'civicrm_user_profile' => [ 350 | 'render element' => 'elements', 351 | 'template' => 'civicrm-user-profile', 352 | ], 353 | ]; 354 | } 355 | 356 | /** 357 | * Implements hook_preprocess_html(). 358 | */ 359 | function civicrm_preprocess_html(array &$variables) { 360 | // Get current route name and CiviCRM args parameter. 361 | $name = \Drupal::routeMatch()->getRouteName(); 362 | $args = \Drupal::routeMatch()->getParameter('args'); 363 | 364 | // Get module from route name. 365 | $segments = explode('.', $name); 366 | $module = $segments[0]; 367 | 368 | // Is this a CiviCRM route and are arguments given? 369 | if (($module == 'civicrm') && $args) { 370 | $args = is_array($args) ? $args : explode('/', $args); 371 | 372 | // Since the body class of a sub-page inherits the args of its 373 | // parent page(s) a prefix is initiated. 374 | $prefix = ''; 375 | 376 | // Generate classes from arguments. 377 | foreach ($args as &$arg) { 378 | $page = (empty($prefix) ? $arg : $prefix . '-' . $arg); 379 | $class = 'page-' . $page; 380 | 381 | // Add body class to variables. 382 | $variables['attributes']['class'][] = $class; 383 | 384 | // Update prefix. 385 | $prefix = $page; 386 | } 387 | } 388 | } 389 | 390 | /** 391 | * Prepares variables for civicrm_contact templates. 392 | * 393 | * Default template: civicrm-contact.html.twig. 394 | */ 395 | function template_preprocess_civicrm_contact(&$vars) { 396 | $vars['civicrm_contact'] = $vars['elements']['#civicrm_contact']; 397 | } 398 | 399 | /** 400 | * Disable civicrm key for all forms that interact with the CMS. 401 | * 402 | * We do not control the CMS form generation and hence should suppress 403 | * qfKey 404 | */ 405 | function civicrm_key_disable() { 406 | \CRM_Core_Config::singleton()->keyDisable = TRUE; 407 | } 408 | 409 | /** 410 | * Alter metatags generated by metatag module. 411 | */ 412 | function civicrm_metatags_alter(array &$metatags, array &$context) { 413 | $route_object = \Drupal::routeMatch()->getRouteObject(); 414 | if ($route_object instanceof Route) { 415 | $routeDetails = $route_object->getDefaults(); 416 | // If this is a CiviCRM Route. 417 | if (isset($routeDetails['_controller']) && $routeDetails['_controller'] === 'Drupal\civicrm\Controller\CivicrmController::main') { 418 | 419 | /** @var \Drupal\civicrm\CivicrmPageState $page_state */ 420 | $page_state = \Drupal::service('civicrm.page_state'); 421 | $metatags['title'] = str_replace('[current-page:title]', $page_state->getTitle(), $metatags['title']); 422 | } 423 | } 424 | } 425 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /drush/civicrm.drush.inc: -------------------------------------------------------------------------------- 1 | 'CLI access to CiviCRM APIs. It can return pretty-printor json formatted data.', 59 | 'examples' => 60 | [ 61 | 'drush civicrm-api contact.create first_name=John last_name=Doe contact_type=Individual' => 'Create a new contact named John Doe', 62 | 'drush civicrm-api contact.create id=1 --out=json' => 'Find/display a contact in JSON format', 63 | ], 64 | 'options' => [ 65 | 'in' => 'Input type: "args" (command-line), "json" (STDIN)', 66 | 'out' => 'Output type: "pretty" (STDOUT), "json" (STDOUT)', 67 | ], 68 | 'aliases' => ['cvapi'], 69 | ]; 70 | $items['civicrm-ext-list'] = [ 71 | 'description' => "List of CiviCRM extensions enabled.", 72 | 'options' => [ 73 | 'status' => 'Filter by extension status (installed, uninstalled, disabled).', 74 | 'out' => 'Output type: "pretty" (STDOUT) by default, "json" (STDOUT)', 75 | ], 76 | 'examples' => [ 77 | 'Standard example' => 'drush civicrm-ext-list', 78 | 'Display installed extensions' => 'drush civicrm-ext-list --status=installed', 79 | 'Display disabled extensions as json' => 'drush civicrm-ext-list --status=disabled --out=json', 80 | ], 81 | 'aliases' => ['cel'], 82 | ]; 83 | $items['civicrm-ext-install'] = [ 84 | 'description' => "Install a CiviCRM extension.", 85 | 'arguments' => [ 86 | 'ename' => 'Extension name.', 87 | ], 88 | 'required-arguments' => TRUE, 89 | 'examples' => [ 90 | 'Standard example' => 'drush civicrm-ext-install civimobile', 91 | ], 92 | 'aliases' => ['cei'], 93 | ]; 94 | $items['civicrm-ext-disable'] = [ 95 | 'description' => "Disable a CiviCRM extension.", 96 | 'arguments' => [ 97 | 'ename' => 'Extension name.', 98 | ], 99 | 'required-arguments' => TRUE, 100 | 'examples' => [ 101 | 'Standard example' => 'drush civicrm-ext-disable civimobile', 102 | ], 103 | 'aliases' => ['ced'], 104 | ]; 105 | $items['civicrm-ext-uninstall'] = [ 106 | 'description' => "Uninstall a CiviCRM extension.", 107 | 'arguments' => [ 108 | 'ename' => 'Extension name.', 109 | ], 110 | 'required-arguments' => TRUE, 111 | 'examples' => [ 112 | 'Standard example' => 'drush civicrm-ext-uninstall civimobile', 113 | ], 114 | 'aliases' => ['ceui'], 115 | ]; 116 | 117 | $items['civicrm-upgrade-db'] = [ 118 | 'description' => "Execute the civicrm/upgrade?reset=1 process from the command line.", 119 | 'aliases' => ['cvupdb'], 120 | ]; 121 | $items['civicrm-update-cfg'] = [ 122 | 'description' => "Update config_backend to correct config settings, especially when the CiviCRM site has been cloned / migrated.", 123 | 'examples' => 124 | [ 125 | 'drush -l http://example.com/civicrm civicrm-update-cfg' => 126 | 'Update config_backend to correct config settings for civicrm installation on example.com site.', 127 | ], 128 | 'aliases' => ['cvupcfg'], 129 | ]; 130 | $items['civicrm-enable-debug'] = [ 131 | 'description' => "Enable CiviCRM Debugging.", 132 | ]; 133 | $items['civicrm-pipe'] = [ 134 | 'description' => 'Start a Civi::pipe session (JSON-RPC 2.0)', 135 | 'examples' => [ 136 | 'drush civicrm-pipe' => 'Begin a session with default flags', 137 | 'drush civicrm-pipe vt' => 'Begin a session with connection flags (ex: version, trusted)', 138 | 'drush civicrm-pipe vu' => 'Begin a session with connection flags (ex: version, untrusted)', 139 | ], 140 | 'arguments' => [ 141 | 'connection-flags' => 'List of connection flags (https://docs.civicrm.org/dev/en/latest/framework/pipe#flags)', 142 | ], 143 | 'aliases' => ['cvpipe'], 144 | ]; 145 | $items['civicrm-upgrade'] = [ 146 | 'description' => "Replace CiviCRM codebase with new specified tarfile and upgrade database by executing the CiviCRM upgrade process - civicrm/upgrade?reset=1.", 147 | 'examples' => 148 | [ 149 | 'drush civicrm-upgrade --tarfile=~/tarballs/civicrm-4.1.2-drupal.tar.gz' => 150 | 'Replace old CiviCRM codebase with new v4.1.2 and run upgrade process.', 151 | ], 152 | 'options' => 153 | [ 154 | 'tarfile' => 155 | 'Path of new CiviCRM tarfile, with which current CiviCRM codebase is to be replaced.', 156 | 'backup-dir' => 157 | 'Specify a directory to backup current CiviCRM codebase and database into, defaults to a backup directory above your Drupal root.', 158 | ], 159 | 'aliases' => ['cvup'], 160 | ]; 161 | $items['civicrm-restore'] = [ 162 | 'description' => 'Restore CiviCRM codebase and database back from the specified backup directory.', 163 | 'examples' => 164 | [ 165 | 'drush civicrm-restore --restore-dir=../backup/modules/20100309200249' => 166 | 'Replace current civicrm codebase with the $restore-dir/civicrm codebase, and reload the database with $restore-dir/civicrm.sql file', 167 | ], 168 | 'options' => 169 | [ 170 | 'restore-dir' => 171 | 'Path of directory having backed up CiviCRM codebase and database.', 172 | 'backup-dir' => 173 | 'Specify a directory to backup current CiviCRM codebase and database into, defaults to a backup directory above your Drupal root.', 174 | ], 175 | ]; 176 | $items['civicrm-rest'] = [ 177 | 'description' => "Rest interface for accessing CiviCRM APIs. It can return xml or json formatted data.", 178 | 'examples' => 179 | [ 180 | "drush civicrm-rest --query='civicrm/contact/search&json=1&key=7decb879f28ac4a0c6a92f0f7889a0c9&api_key=7decb879f28ac4a0c6a92f0f7889a0c9'" => 181 | 'Use contact search api to return data in json format.', 182 | ], 183 | // TODO: This really makes more sense as an argument. 184 | 'options' => 185 | ['query' => 'Query part of url. Refer CiviCRM wiki doc for more details.'], 186 | 'aliases' => ['cvr'], 187 | ]; 188 | $items['civicrm-sql-conf'] = [ 189 | // Explicit callback declaration and non-standard name to avoid collision with "sql-conf". 190 | 'callback' => 'drush_civicrm_sqlconf', 191 | 'description' => 'Print CiviCRM database connection details.', 192 | ]; 193 | $items['civicrm-sql-connect'] = [ 194 | // Explicit callback declaration and non-standard name to avoid collision with "sql-connect". 195 | 'callback' => 'drush_civicrm_sqlconnect', 196 | 'description' => 'A string for connecting to the CiviCRM DB.', 197 | ]; 198 | $items['civicrm-sql-dump'] = [ 199 | // Explicit callback declaration and non-standard name to avoid collision with "sql-dump". 200 | 'callback' => 'drush_civicrm_sqldump', 201 | 'description' => 'Exports the CiviCRM DB as SQL using mysqldump.', 202 | 'examples' => [ 203 | 'drush civicrm-sql-dump --result-file=../CiviCRM.sql' => 'Save SQL dump to the directory above Drupal root.', 204 | ], 205 | 'options' => [ 206 | 'data-only' => 'Dump data without statements to create any of the schema.', 207 | 'gzip' => 'Compress the dump using the gzip program which must be in your $PATH.', 208 | 'result-file' => 'Save to a file.', 209 | 'tables-list' => 'comma-separated list of tables to transfer.', 210 | ], 211 | ]; 212 | $items['civicrm-sql-query'] = [ 213 | // Explicit callback declaration and non-standard name to avoid collision with "sql-query". 214 | 'callback' => 'drush_civicrm_sqlquery', 215 | 'description' => 'Execute a query against the CiviCRM database.', 216 | 'examples' => [ 217 | 'drush civicrm-sql-query "SELECT * FROM civicrm_contact WHERE id=1"' => 'Browse user record', 218 | ], 219 | 'arguments' => [ 220 | 'query' => 'A SQL query. Mandatory.', 221 | ], 222 | ]; 223 | $items['civicrm-sql-cli'] = [ 224 | // Explicit callback declaration and non-standard name to avoid collision with "sql-cli". 225 | 'callback' => 'drush_civicrm_sqlcli', 226 | 'description' => "Open a SQL command-line interface using CiviCRM's credentials.", 227 | 'aliases' => ['cvsqlc'], 228 | ]; 229 | $items['civicrm-process-mail-queue'] = [ 230 | 'description' => "Process pending CiviMail mailing jobs.", 231 | 'examples' => 232 | [ 233 | 'drush civicrm-process-mail-queue -u admin' => 234 | 'Process CiviMail queue with admin credentials.', 235 | ], 236 | ]; 237 | $items['civicrm-member-records'] = [ 238 | 'description' => "Run the CiviMember UpdateMembershipRecord cron (civicrm-member-records).", 239 | ]; 240 | 241 | return $items; 242 | } 243 | 244 | /** 245 | * Implementation of database specification for the active DB connection. 246 | */ 247 | function drush_civicrm_get_db_spec() { 248 | if (version_compare(DRUSH_VERSION, 7, '>=')) { 249 | $sql = drush_sql_get_class(); 250 | $db_spec = $sql->db_spec(); 251 | } 252 | else { 253 | $db_spec = _drush_sql_get_db_spec(); 254 | } 255 | return $db_spec; 256 | } 257 | 258 | /** 259 | * 260 | */ 261 | function _civicrm_extract_tarfile($destinationPath, $option = 'tarfile') { 262 | $tarpath = drush_get_option($option, FALSE); 263 | if (drush_shell_exec("gzip -d " . $tarfile)) { 264 | $tarpath = substr($tarfile, 0, strlen($tarfile) - 3); 265 | } 266 | drush_shell_exec("tar -xf $tarpath -C \"$destinationPath\""); 267 | } 268 | 269 | /** 270 | * Implementation of hook_drush_help(). 271 | * 272 | * This function is called whenever a drush user calls 273 | * 'drush help ' 274 | * 275 | * @param 276 | * A string with the help section (prepend with 'drush:') 277 | * 278 | * @return 279 | * A string with the help text for your command. 280 | */ 281 | function civicrm_drush_help($section) { 282 | switch ($section) { 283 | case 'drush:civicrm-upgrade-db': 284 | return dt("Run civicrm/upgrade?reset=1 just as a web browser would."); 285 | 286 | case 'drush:civicrm-update-cfg': 287 | return dt("Update config_backend to correct config settings, especially when the CiviCRM site has been cloned / migrated."); 288 | 289 | case 'drush:civicrm-upgrade': 290 | return dt("Take backups, replace CiviCRM codebase with new specified tarfile and upgrade database by executing the CiviCRM upgrade process - civicrm/upgrade?reset=1. Use civicrm-restore to revert to previous state in case anything goes wrong."); 291 | 292 | case 'drush:civicrm-restore': 293 | return dt("Restore CiviCRM codebase and database back from the specified backup directory."); 294 | 295 | case 'drush:civicrm-rest': 296 | return dt("Rest interface for accessing CiviCRM APIs. It can return xml or json formatted data."); 297 | 298 | case 'drush:civicrm-sql-conf': 299 | return dt('Show civicrm database connection details.'); 300 | 301 | case 'drush:civicrm-sql-connect': 302 | return dt('A string which connects to the civicrm database.'); 303 | 304 | case 'drush:civicrm-sql-cli': 305 | return dt('Quickly enter the mysql command line.'); 306 | 307 | case 'drush:civicrm-sql-dump': 308 | return dt('Prints the whole CiviCRM database to STDOUT or save to a file.'); 309 | 310 | case 'drush:civicrm-sql-query': 311 | return dt("Usage: drush [options] civicrm-sql-query ...\n is a SQL statement, which can alternatively be passed via STDIN. Any additional arguments are passed to the mysql command directly."); 312 | } 313 | } 314 | 315 | /** 316 | * Implementation of command 'civicrm-ext-list'. 317 | */ 318 | function drush_civicrm_ext_list() { 319 | \Drupal::service('civicrm')->initialize(); 320 | $status = drush_get_option('status', FALSE); 321 | $params = [ 322 | 'options' => [ 323 | 'limit' => 0, 324 | ], 325 | ]; 326 | if ($status) { 327 | if (!in_array($status, ['installed', 'uninstalled', 'disabled'])) { 328 | return drush_set_error('CIVICRM_INVALID_STATUS', dt("Extension status @status is invalid.", ['@status' => $status])); 329 | } 330 | $params['status'] = $status; 331 | } 332 | 333 | try { 334 | $result = civicrm_api3('extension', 'get', $params); 335 | $rows = [[dt('App name'), dt('Status'), dt('Version')]]; 336 | foreach ($result['values'] as $k => $extension_data) { 337 | $rows[] = [ 338 | $extension_data['key'], 339 | $extension_data['status'], 340 | $extension_data['version'], 341 | ]; 342 | } 343 | unset($result); 344 | $format = drush_get_option('out', 'pretty'); 345 | switch ($format) { 346 | case 'pretty': 347 | drush_print_table($rows, TRUE); 348 | break; 349 | 350 | case 'json': 351 | drush_print(json_encode($rows)); 352 | break; 353 | 354 | default: 355 | return drush_set_error('CIVICRM_UNKNOWN_FORMAT', dt('Unknown format: @format', ['@format' => $format])); 356 | } 357 | } 358 | catch (CiviCRM_API3_Exception $e) { 359 | // Handle error here. 360 | $errorMessage = $e->getMessage(); 361 | $errorCode = $e->getErrorCode(); 362 | $errorData = $e->getExtraParams(); 363 | drush_log(dt("!error", ['!error' => $errorData], 'error')); 364 | } 365 | } 366 | 367 | /** 368 | * Implementation of command 'civicrm-ext-install'. 369 | */ 370 | function drush_civicrm_ext_install($extension_name) { 371 | \Drupal::service('civicrm')->initialize(); 372 | try { 373 | $result = civicrm_api('extension', 'install', ['key' => $extension_name, 'version' => 3]); 374 | if ($result['values'] && $result['values'] == 1) { 375 | drush_print(dt("Extension !ename installed.", ['!ename' => $extension_name])); 376 | } 377 | else { 378 | drush_log(t('Extension !ename could not be installed.', ['!ename' => $extension_name]), 'error'); 379 | } 380 | } 381 | catch (CiviCRM_API3_Exception $e) { 382 | // Handle error here. 383 | $errorMessage = $e->getMessage(); 384 | $errorCode = $e->getErrorCode(); 385 | $errorData = $e->getExtraParams(); 386 | drush_log(dt("!error", ['!error' => $errorData], 'error')); 387 | } 388 | } 389 | 390 | /** 391 | * Implementation of command 'civicrm-ext-disable'. 392 | */ 393 | function drush_civicrm_ext_disable($extension_name) { 394 | \Drupal::service('civicrm')->initialize(); 395 | try { 396 | $result = civicrm_api('extension', 'disable', ['key' => $extension_name, 'version' => 3]); 397 | if ($result['values'] && $result['values'] == 1) { 398 | drush_print(dt("Extension !ename disabled.", ['!ename' => $extension_name])); 399 | } 400 | else { 401 | drush_log(t('Extension !ename could not be disabled.', ['!ename' => $extension_name]), 'error'); 402 | } 403 | } 404 | catch (CiviCRM_API3_Exception $e) { 405 | // Handle error here. 406 | $errorMessage = $e->getMessage(); 407 | $errorCode = $e->getErrorCode(); 408 | $errorData = $e->getExtraParams(); 409 | drush_log(dt("!error", ['!error' => $errorData], 'error')); 410 | } 411 | } 412 | 413 | /** 414 | * Implementation of command 'civicrm-ext-uninstall'. 415 | */ 416 | function drush_civicrm_ext_uninstall($extension_name) { 417 | \Drupal::service('civicrm')->initialize(); 418 | try { 419 | $result = civicrm_api('extension', 'uninstall', ['key' => $extension_name, 'version' => 3]); 420 | if ($result['values'] && $result['values'] == 1) { 421 | drush_print(dt("Extension !ename uninstalled.", ['!ename' => $extension_name])); 422 | } 423 | else { 424 | drush_log(t('Extension !ename could not be uninstalled.', ['!ename' => $extension_name]), 'error'); 425 | } 426 | } 427 | catch (CiviCRM_API3_Exception $e) { 428 | // Handle error here. 429 | $errorMessage = $e->getMessage(); 430 | $errorCode = $e->getErrorCode(); 431 | $errorData = $e->getExtraParams(); 432 | drush_log(dt("!error", ['!error' => $errorData], 'error')); 433 | } 434 | } 435 | 436 | /** 437 | * Implementation of drush_hook_COMMAND_validate for command 'civicrm-upgrade-db'. 438 | */ 439 | function drush_civicrm_upgrade_db_validate() { 440 | if (!defined('CIVICRM_UPGRADE_ACTIVE')) { 441 | define('CIVICRM_UPGRADE_ACTIVE', 1); 442 | } 443 | $_GET['q'] = 'civicrm/upgrade'; 444 | 445 | if (!_civicrm_init()) { 446 | return FALSE; 447 | } 448 | 449 | $_POST['upgrade'] = 1; 450 | $_GET['q'] = 'civicrm/upgrade'; 451 | require_once 'CRM/Core/Config.php'; 452 | 453 | require_once 'CRM/Utils/System.php'; 454 | require_once 'CRM/Core/BAO/Domain.php'; 455 | $codeVer = CRM_Utils_System::version(); 456 | $dbVer = CRM_Core_BAO_Domain::version(); 457 | if (!$dbVer) { 458 | return drush_set_error('CIVICRM_VERSION_MISSING_DATABASE', dt('Version information missing in civicrm database.')); 459 | } 460 | elseif (stripos($dbVer, 'upgrade')) { 461 | return drush_set_error('CIVICRM_DATABASE_CHECK_FAIL', dt('Database check failed - the database looks to have been partially upgraded. You may want to reload the database with the backup and try the upgrade process again.')); 462 | } 463 | elseif (!$codeVer) { 464 | return drush_set_error('CIVICRM_VERSION_MISSING_CODE', dt('Version information missing in civicrm codebase.')); 465 | } 466 | elseif (version_compare($codeVer, $dbVer) > 0) { 467 | drush_log(dt("Starting with v!dbVer -> v!codeVer upgrade ..", ['!dbVer' => $dbVer, '!codeVer' => $codeVer])); 468 | } 469 | elseif (version_compare($codeVer, $dbVer) < 0) { 470 | return drush_set_error('CIVICRM_VERSION_UNEXPECTED', dt("Database is marked with an unexpected version '!dbVer' which is higher than that of codebase version '!codeVer'.", ['!dbVer' => $dbVer, '!codeVer' => $codeVer])); 471 | } 472 | 473 | return TRUE; 474 | } 475 | 476 | /** 477 | * Implementation of command 'civicrm-upgrade-db'. 478 | */ 479 | function drush_civicrm_upgrade_db() { 480 | if (class_exists('CRM_Upgrade_Headless')) { 481 | // Note: CRM_Upgrade_Headless introduced in 4.2 -- at the same time as class auto-loading. 482 | $upgradeHeadless = new CRM_Upgrade_Headless(); 483 | // FIXME Exception handling? 484 | $result = $upgradeHeadless->run(); 485 | drush_print("Upgrade outputs: " . "\"" . $result['message'] . "\""); 486 | } 487 | else { 488 | require_once 'CRM/Core/Smarty.php'; 489 | $template = CRM_Core_Smarty::singleton(); 490 | 491 | require_once 'CRM/Upgrade/Page/Upgrade.php'; 492 | $upgrade = new CRM_Upgrade_Page_Upgrade(); 493 | 494 | // New since CiviCRM 4.1. 495 | if (is_callable([ 496 | $upgrade, 'setPrint', 497 | ])) { 498 | $upgrade->setPrint(TRUE); 499 | } 500 | 501 | // To suppress html output /w source code. 502 | ob_start(); 503 | $upgrade->run(); 504 | // Capture the required message. 505 | $result = $template->get_template_vars('message'); 506 | ob_end_clean(); 507 | drush_print("Upgrade outputs: " . "\"$result\""); 508 | } 509 | } 510 | 511 | /** 512 | * Implementation of drush_hook_COMMAND_validate for command 'civicrm-update-cfg'. 513 | */ 514 | function drush_civicrm_update_cfg_validate() { 515 | return _civicrm_init(); 516 | } 517 | 518 | /** 519 | * Implementation of command 'civicrm-update-cfg'. 520 | */ 521 | function drush_civicrm_update_cfg() { 522 | $defaultValues = []; 523 | $states = ['old', 'new']; 524 | for ($i = 1; $i <= 3; $i++) { 525 | foreach ($states as $state) { 526 | $name = "{$state}Val_{$i}"; 527 | $value = drush_get_option($name, NULL); 528 | if ($value) { 529 | $defaultValues[$name] = $value; 530 | } 531 | } 532 | } 533 | 534 | require_once 'CRM/Core/I18n.php'; 535 | require_once 'CRM/Core/BAO/ConfigSetting.php'; 536 | $result = CRM_Core_BAO_ConfigSetting::doSiteMove($defaultValues); 537 | 538 | if ($result) { 539 | 540 | drush_log(dt('Config successfully updated.'), 'completed'); 541 | 542 | } 543 | else { 544 | drush_log(dt('Config update failed.'), 'failed'); 545 | } 546 | } 547 | 548 | /** 549 | * Implements hook_drush_cache_clear. 550 | */ 551 | function civicrm_drush_cache_clear(&$types) { 552 | if (_civicrm_init(FALSE)) { 553 | $types['civicrm'] = 'drush_civicrm_cacheclear'; 554 | } 555 | } 556 | 557 | /** 558 | * Cache clear callback. 559 | * 560 | * Warning: do not name drush_civicrm_cache_clear() otherwise it will 561 | * conflict with hook_drush_cache_clear() and be called systematically 562 | * when "drush cc" is called. 563 | */ 564 | function drush_civicrm_cacheclear() { 565 | _civicrm_init(); 566 | 567 | // Flush all caches using the API. 568 | $params = ['version' => 3]; 569 | if (drush_get_option('triggers', FALSE)) { 570 | $params['triggers'] = 1; 571 | } 572 | 573 | if (drush_get_option('sessions', FALSE)) { 574 | $params['session'] = 1; 575 | } 576 | 577 | // Need to set API version or drush cc civicrm fails. 578 | $params['version'] = 3; 579 | $result = civicrm_api('System', 'flush', $params); 580 | 581 | if ($result['is_error']) { 582 | drush_log(dt('An error occurred: !message', ['!message' => $result['error_message']]), 'error'); 583 | return; 584 | } 585 | 586 | drush_log(dt('The CiviCRM cache has been cleared.'), 'ok'); 587 | } 588 | 589 | /** 590 | * Implementation of drush_hook_COMMAND_validate for command 'civicrm-enable-debug'. 591 | */ 592 | function drush_civicrm_enable_debug_validate() { 593 | return _civicrm_init(); 594 | } 595 | 596 | /** 597 | * 598 | */ 599 | function drush_civicrm_enable_debug() { 600 | $settings = [ 601 | 'debug_enabled' => 1, 602 | 'backtrace' => 1, 603 | ]; 604 | 605 | foreach ($settings as $key => $val) { 606 | $result = civicrm_api('Setting', 'create', ['version' => 3, $key => $val]); 607 | 608 | if ($result['is_error']) { 609 | drush_log(dt('An error occurred: !message', ['!message' => $result['error_message']]), 'error'); 610 | return; 611 | } 612 | } 613 | 614 | drush_log(dt('CiviCRM debug setting enabled.'), 'ok'); 615 | } 616 | 617 | /** 618 | * Implementation of drush_hook_COMMAND_validate for command 'civicrm-disable-debug'. 619 | */ 620 | function drush_civicrm_disable_debug_validate() { 621 | return _civicrm_init(); 622 | } 623 | 624 | /** 625 | * 626 | */ 627 | function drush_civicrm_disable_debug() { 628 | $settings = [ 629 | 'debug_enabled' => 0, 630 | 'backtrace' => 0, 631 | ]; 632 | 633 | foreach ($settings as $key => $val) { 634 | $result = civicrm_api('Setting', 'create', ['version' => 3, $key => $val]); 635 | 636 | if ($result['is_error']) { 637 | drush_log(dt('An error occurred: !message', ['!message' => $result['error_message']]), 'error'); 638 | return; 639 | } 640 | } 641 | 642 | drush_log(dt('CiviCRM debug setting disabled.'), 'ok'); 643 | } 644 | 645 | /** 646 | * Implementation of drush_hook_COMMAND_validate for command 'civicrm-upgrade'. 647 | */ 648 | function drush_civicrm_upgrade_validate() { 649 | // TODO: use Drush to download tarfile. 650 | // TODO: if tarfile is not specified, see if the code already exists and use that instead. 651 | $tarfile = drush_get_option('tarfile', FALSE); 652 | if (!$tarfile) { 653 | return drush_set_error('CIVICRM_TAR_NOT_SPECIFIED', dt('Tarfile not specified.')); 654 | } 655 | // FIXME: throw error if tarfile is not in a valid format. 656 | if (!defined('CIVICRM_UPGRADE_ACTIVE')) { 657 | define('CIVICRM_UPGRADE_ACTIVE', 1); 658 | } 659 | return _civicrm_init(); 660 | } 661 | 662 | /** 663 | * Implementation of command 'civicrm-upgrade'. 664 | */ 665 | function drush_civicrm_upgrade() { 666 | global $civicrm_root; 667 | 668 | $tarfile = drush_get_option('tarfile', FALSE); 669 | $date = date('YmdHis'); 670 | $backup_file = "civicrm"; 671 | 672 | $basepath = explode('/', $civicrm_root); 673 | array_pop($basepath); 674 | $project_path = implode('/', $basepath) . '/'; 675 | 676 | $drupal_root = drush_get_context('DRUSH_DRUPAL_ROOT'); 677 | $backup_dir = drush_get_option('backup-dir', $drupal_root . '/../backup'); 678 | $backup_dir = rtrim($backup_dir, '/'); 679 | 680 | drush_print(dt("\nThe upgrade process involves - ")); 681 | drush_print(dt("1. Backing up current CiviCRM code as => !path", 682 | ['!path' => "$backup_dir/modules/$date/$backup_file"] 683 | )); 684 | drush_print(dt("2. Backing up database as => !path", 685 | ['!path' => "$backup_dir/modules/$date/$backup_file.sql"] 686 | )); 687 | drush_print(dt("3. Unpacking tarfile to => !path", 688 | ['!path' => "$project_path"] 689 | )); 690 | drush_print(dt("4. Executing civicrm/upgrade?reset=1 just as a browser would.\n")); 691 | if (!drush_confirm(dt('Do you really want to continue?'))) { 692 | return drush_user_abort(); 693 | } 694 | 695 | @drush_op('mkdir', $backup_dir, 0777); 696 | $backup_dir .= '/modules'; 697 | @drush_op('mkdir', $backup_dir, 0777); 698 | $backup_dir .= "/$date"; 699 | @drush_op('mkdir', $backup_dir, 0777); 700 | $backup_target = $backup_dir . '/' . $backup_file; 701 | if (!drush_op('rename', $civicrm_root, $backup_target)) { 702 | return drush_set_error('CIVICRM_BACKUP_FAILED', dt('Failed to backup CiviCRM project directory !source to !backup_target', 703 | ['!source' => $civicrm_root, '!backup_target' => $backup_target] 704 | )); 705 | } 706 | drush_log(dt("\n1. Code backed up."), 'ok'); 707 | 708 | drush_set_option('result-file', $backup_target . '.sql'); 709 | drush_civicrm_sqldump(); 710 | drush_log(dt('2. Database backed up.'), 'ok'); 711 | 712 | // Decompress & Untar. 713 | _civicrm_extract_tarfile($project_path); 714 | drush_log(dt('3. Tarfile unpacked.'), 'ok'); 715 | 716 | drush_log(dt("4. ")); 717 | 718 | if (drush_civicrm_upgrade_db_validate()) { 719 | drush_civicrm_upgrade_db(); 720 | } 721 | drush_log(dt("\nProcess completed."), 'completed'); 722 | } 723 | 724 | /** 725 | * Implementation of drush_hook_COMMAND_validate for command 'civicrm-restore'. 726 | */ 727 | function drush_civicrm_restore_validate() { 728 | _civicrm_dsn_init(); 729 | 730 | $restore_dir = drush_get_option('restore-dir', FALSE); 731 | $restore_dir = rtrim($restore_dir, '/'); 732 | if (!$restore_dir) { 733 | return drush_set_error('CIVICRM_RESTORE_NOT_SPECIFIED', dt('Restore-dir not specified.')); 734 | } 735 | $sql_file = $restore_dir . '/civicrm.sql'; 736 | if (!file_exists($sql_file)) { 737 | return drush_set_error('CIVICRM_RESTORE_CIVICRM_SQL_NOT_FOUND', dt('Could not locate civicrm.sql file in the restore directory.')); 738 | } 739 | $code_dir = $restore_dir . '/civicrm'; 740 | if (!is_dir($code_dir)) { 741 | return drush_set_error('CIVICRM_RESTORE_DIR_NOT_FOUND', dt('Could not locate civicrm directory inside restore-dir.')); 742 | } 743 | elseif (!file_exists("$code_dir/civicrm-version.php")) { 744 | return drush_set_error('CIVICRM_RESTORE_DIR_NOT_VALID', dt('civicrm directory inside restore-dir, doesn\'t look to be a valid civicrm codebase.')); 745 | } 746 | 747 | return TRUE; 748 | } 749 | 750 | /** 751 | * Implementation of command 'civicrm-restore'. 752 | */ 753 | function drush_civicrm_restore() { 754 | $restore_dir = drush_get_option('restore-dir', FALSE); 755 | $restore_dir = rtrim($restore_dir, '/'); 756 | $sql_file = $restore_dir . '/civicrm.sql'; 757 | $code_dir = $restore_dir . '/civicrm'; 758 | $date = date('YmdHis'); 759 | 760 | global $civicrm_root; 761 | $civicrm_root_base = explode('/', $civicrm_root); 762 | array_pop($civicrm_root_base); 763 | $civicrm_root_base = implode('/', $civicrm_root_base) . '/'; 764 | 765 | $drupal_root = drush_get_context('DRUSH_DRUPAL_ROOT'); 766 | $restore_backup_dir = drush_get_option('backup-dir', $drupal_root . '/../backup'); 767 | $restore_backup_dir = rtrim($restore_backup_dir, '/'); 768 | 769 | // Get confirmation from user -. 770 | $db_spec = drush_civicrm_get_db_spec(); 771 | drush_print(dt("\nProcess involves :")); 772 | drush_print(dt("1. Restoring '\$restore-dir/civicrm' directory to '!toDir'.", ['!toDir' => $civicrm_root_base])); 773 | drush_print(dt("2. Dropping and creating '!db' database.", ['!db' => $db_spec['database']])); 774 | drush_print(dt("3. Loading '\$restore-dir/civicrm.sql' file into the database.")); 775 | drush_print(); 776 | drush_print(dt("Note: Before restoring a backup will be taken in '!path' directory.", 777 | ['!path' => "$restore_backup_dir/modules/restore"] 778 | )); 779 | drush_print(); 780 | if (!drush_confirm(dt('Do you really want to continue?'))) { 781 | return drush_user_abort(); 782 | } 783 | 784 | // Create restore-backup-dir if not already exists. 785 | @drush_op('mkdir', $restore_backup_dir, 0777); 786 | $restore_backup_dir .= '/modules'; 787 | @drush_op('mkdir', $restore_backup_dir, 0777); 788 | $restore_backup_dir .= '/restore'; 789 | @drush_op('mkdir', $restore_backup_dir, 0777); 790 | $restore_backup_dir .= "/$date"; 791 | @drush_op('mkdir', $restore_backup_dir, 0777); 792 | 793 | // 1. backup and restore codebase. 794 | drush_log(dt('Restoring civicrm codebase ..')); 795 | if (is_dir($civicrm_root) && !drush_op('rename', $civicrm_root, $restore_backup_dir . '/civicrm')) { 796 | return drush_set_error('CIVICRM_RESTORE_CODE_FAILED', dt("Failed to take backup for '!destination' directory", 797 | ['!destination' => $civicrm_root] 798 | )); 799 | } 800 | if (!drush_op('rename', $code_dir, $civicrm_root)) { 801 | return drush_set_error('CIVICRM_RESTORE_DESTINATION_FAILED', dt("Failed to restore civicrm directory '!source' to '!dest'", 802 | ['!source' => $code_dir, '!dest' => $civicrm_root_base] 803 | )); 804 | } 805 | drush_log(dt('Codebase restored.'), 'ok'); 806 | 807 | // 2. backup, drop and create database. 808 | drush_set_option('result-file', $restore_backup_dir . '/civicrm.sql'); 809 | drush_civicrm_sqldump(); 810 | 811 | drush_log(dt('Database backed up.'), 'ok'); 812 | 813 | if (version_compare(DRUSH_VERSION, 7, '>=')) { 814 | $sql = drush_sql_get_class(); 815 | $exec = 'mysql ' . $sql->creds() . ' -e '; 816 | $dbDriver = $db_spec['driver']; 817 | } 818 | else { 819 | $exec = 'mysql' . _drush_sql_get_credentials() . ' -e '; 820 | $dbDriver = _drush_sql_get_scheme(); 821 | } 822 | drush_log(dt("\nDropping database '!db' ..", ['!db' => $db_spec['database']])); 823 | if (drush_op('system', $exec . '"DROP DATABASE IF EXISTS ' . $db_spec['database'] . '"')) { 824 | return drush_set_error('CIVICRM_RESTORE_DATABASE_DROP_FAILED', dt('Could not drop database: @name', ['@name' => $db_spec['database']])); 825 | } 826 | drush_log(dt('Database dropped.'), 'ok'); 827 | $exec = str_replace($db_spec['database'], '', $exec); 828 | if (drush_op('system', $exec . '"CREATE DATABASE ' . $db_spec['database'] . '"')) { 829 | return drush_set_error('CIVICRM_RESTORE_DATABASE_CREATE_FAILED', dt('Could not create new database: @name', ['@name' => $db_spec['database']])); 830 | } 831 | drush_log(dt('Database created.'), 'ok'); 832 | 833 | // 3. restore database. 834 | switch ($dbDriver) { 835 | case 'mysql': 836 | if (version_compare(DRUSH_VERSION, 7, '>=')) { 837 | $send = 'mysql ' . $sql->creds(); 838 | } 839 | else { 840 | $send = 'mysql' . _drush_sql_get_credentials(); 841 | } 842 | break; 843 | 844 | case 'pgsql': 845 | if (version_compare(DRUSH_VERSION, 7, '>=')) { 846 | $send .= 'psql -d ' . $sql->creds() . ' --file -'; 847 | } 848 | else { 849 | $send .= 'psql -d ' . _drush_sql_get_credentials() . ' --file -'; 850 | } 851 | break; 852 | } 853 | $exec = "$send < $sql_file"; 854 | drush_log(dt('Loading civicrm.sql file from restore-dir ..')); 855 | drush_op('system', $exec); 856 | drush_log(dt('Database restored.'), 'ok'); 857 | 858 | drush_log(dt('Restore process completed.'), 'completed'); 859 | 860 | _civicrm_dsn_close(); 861 | } 862 | 863 | /** 864 | * Implementation of command 'civicrm-member-records'. 865 | */ 866 | function drush_civicrm_member_records() { 867 | _civicrm_init(); 868 | 869 | $_REQUEST['name'] = drush_get_option('civicrm_cron_username', NULL); 870 | $_REQUEST['pass'] = drush_get_option('civicrm_cron_password', NULL); 871 | $_REQUEST['key'] = drush_get_option('civicrm_sitekey', NULL); 872 | 873 | global $argv; 874 | $argv = [ 875 | 0 => "drush", 876 | 1 => "-u" . $_REQUEST['name'], 877 | 2 => "-p" . $_REQUEST['pass'], 878 | 3 => "-s" . drush_get_option('uri', FALSE), 879 | ]; 880 | 881 | if (!defined('CIVICRM_CONFDIR')) { 882 | define('CIVICRM_CONFDIR', drush_get_context('DRUSH_DRUPAL_ROOT') . '/sites/'); 883 | } 884 | 885 | include "bin/UpdateMembershipRecord.php"; 886 | } 887 | 888 | /** 889 | * Implementation of drush_hook_COMMAND_validate for command 'civicrm-rest' ('cvr') 890 | */ 891 | function drush_civicrm_rest_validate() { 892 | $query = drush_get_option('query', FALSE); 893 | if (!$query) { 894 | drush_set_error('CIVICRM_REST_EMPTY_QUERY', dt('query not specified.')); 895 | } 896 | 897 | return _civicrm_init(); 898 | } 899 | 900 | /** 901 | * Implementation of command 'civicrm-rest' ('cvr') 902 | */ 903 | function drush_civicrm_rest() { 904 | $query = drush_get_option('query', FALSE); 905 | $query = explode('&', $query); 906 | $_GET['q'] = array_shift($query); 907 | foreach ($query as $keyVal) { 908 | list($key, $val) = explode('=', $keyVal); 909 | $_REQUEST[$key] = $val; 910 | $_GET[$key] = $val; 911 | } 912 | 913 | require_once 'CRM/Utils/REST.php'; 914 | $rest = new CRM_Utils_REST(); 915 | 916 | require_once 'CRM/Core/Config.php'; 917 | $config = CRM_Core_Config::singleton(); 918 | 919 | global $civicrm_root; 920 | // Adding dummy script, since based on this api file path is computed. 921 | $_SERVER['SCRIPT_FILENAME'] = "$civicrm_root/extern/rest.php"; 922 | 923 | if (isset($_GET['json']) && 924 | $_GET['json'] 925 | ) { 926 | header('Content-Type: text/javascript'); 927 | } 928 | else { 929 | header('Content-Type: text/xml'); 930 | } 931 | echo $rest->run($config); 932 | } 933 | 934 | /** 935 | * Implements drush_hook_pre_COMMAND(). 936 | * 937 | * This function is called when using drush 6. 938 | */ 939 | function drush_civicrm_pre_civicrm_sql_dump() { 940 | _civicrm_dsn_init(); 941 | } 942 | 943 | /** 944 | * Implements drush_hook_pre_COMMAND(). 945 | * 946 | * This function is called when using drush 5. 947 | */ 948 | function drush_civicrm_pre_civicrm_sqldump() { 949 | _civicrm_dsn_init(); 950 | } 951 | 952 | /** 953 | * Implementation of command 'civicrm-sql-dump'. 954 | */ 955 | function drush_civicrm_sqldump() { 956 | if (version_compare(DRUSH_VERSION, 7, '>=')) { 957 | drush_sql_dump(); 958 | } 959 | else { 960 | drush_sql_dump_execute(); 961 | } 962 | } 963 | 964 | /** 965 | * Implements drush_hook_post_COMMAND(). 966 | * 967 | * This function is called when using drush 6. 968 | */ 969 | function drush_civicrm_post_civicrm_sql_dump() { 970 | _civicrm_dsn_close(); 971 | } 972 | 973 | /** 974 | * Implements drush_hook_post_COMMAND(). 975 | * 976 | * This function is called when using drush 5. 977 | */ 978 | function drush_civicrm_post_civicrm_sqldump() { 979 | _civicrm_dsn_close(); 980 | } 981 | 982 | /** 983 | * Implements drush_hook_pre_COMMAND(). 984 | * 985 | * This function is called when using drush 6. 986 | */ 987 | function drush_civicrm_pre_civicrm_sql_conf() { 988 | _civicrm_dsn_init(); 989 | } 990 | 991 | /** 992 | * Implements drush_hook_post_COMMAND(). 993 | * 994 | * This function is called when using drush 5. 995 | */ 996 | function drush_civicrm_pre_civicrm_sqlconf() { 997 | _civicrm_dsn_init(); 998 | } 999 | 1000 | /** 1001 | * Implementation of command 'civicrm-sql-conf'. 1002 | */ 1003 | function drush_civicrm_sqlconf() { 1004 | $conf = drush_sql_conf(); 1005 | // Before drush 6 drush_sql_conf already does drush_print_r, so it shouldn't 1006 | // be called again. 1007 | if (version_compare(DRUSH_VERSION, 6, '>=')) { 1008 | drush_print_r($conf); 1009 | } 1010 | } 1011 | 1012 | /** 1013 | * Implements drush_hook_post_COMMAND(). 1014 | * 1015 | * This function is called when using drush 6. 1016 | */ 1017 | function drush_civicrm_post_civicrm_sql_conf() { 1018 | _civicrm_dsn_close(); 1019 | } 1020 | 1021 | /** 1022 | * Implements drush_hook_post_COMMAND(). 1023 | * 1024 | * This function is called when using drush 5. 1025 | */ 1026 | function drush_civicrm_post_civicrm_sqlconf() { 1027 | _civicrm_dsn_close(); 1028 | } 1029 | 1030 | /** 1031 | * Implements drush_hook_pre_COMMAND(). 1032 | * 1033 | * This function is called when using drush 6. 1034 | */ 1035 | function drush_civicrm_pre_civicrm_sql_connect() { 1036 | _civicrm_dsn_init(); 1037 | } 1038 | 1039 | /** 1040 | * Implements drush_hook_pre_COMMAND(). 1041 | * 1042 | * This function is called when using drush 5. 1043 | */ 1044 | function drush_civicrm_pre_civicrm_sqlconnect() { 1045 | _civicrm_dsn_init(); 1046 | } 1047 | 1048 | /** 1049 | * Implementation of command 'civicrm-sql-connect'. 1050 | */ 1051 | function drush_civicrm_sqlconnect() { 1052 | return drush_sql_connect(); 1053 | } 1054 | 1055 | /** 1056 | * Implements drush_hook_post_COMMAND(). 1057 | * 1058 | * This function is called when using drush 6. 1059 | */ 1060 | function drush_civicrm_post_civicrm_sql_connect() { 1061 | _civicrm_dsn_close(); 1062 | } 1063 | 1064 | /** 1065 | * Implements drush_hook_post_COMMAND(). 1066 | * 1067 | * This function is called when using drush 5. 1068 | */ 1069 | function drush_civicrm_post_civicrm_sqlconnect() { 1070 | _civicrm_dsn_close(); 1071 | } 1072 | 1073 | /** 1074 | * Implements drush_hook_pre_COMMAND(). 1075 | * 1076 | * This function is called when using drush 6. 1077 | */ 1078 | function drush_civicrm_pre_civicrm_sql_query() { 1079 | _civicrm_dsn_init(); 1080 | } 1081 | 1082 | /** 1083 | * Implements drush_hook_pre_COMMAND(). 1084 | * 1085 | * This function is called when using drush 5. 1086 | */ 1087 | function drush_civicrm_pre_civicrm_sqlquery() { 1088 | _civicrm_dsn_init(); 1089 | } 1090 | 1091 | /** 1092 | * Implementation of command 'civicrm-sql-query'. 1093 | */ 1094 | function drush_civicrm_sqlquery($query) { 1095 | return drush_sql_query($query); 1096 | } 1097 | 1098 | /** 1099 | * Implements drush_hook_post_COMMAND(). 1100 | * 1101 | * This function is called when using drush 6. 1102 | */ 1103 | function drush_civicrm_post_civicrm_sql_query() { 1104 | _civicrm_dsn_close(); 1105 | } 1106 | 1107 | /** 1108 | * Implements drush_hook_post_COMMAND(). 1109 | * 1110 | * This function is called when using drush 5. 1111 | */ 1112 | function drush_civicrm_post_civicrm_sqlquery() { 1113 | _civicrm_dsn_close(); 1114 | } 1115 | 1116 | /** 1117 | * Implements drush_hook_pre_COMMAND(). 1118 | * 1119 | * This function is called when using drush 6. 1120 | */ 1121 | function drush_civicrm_pre_civicrm_sql_cli() { 1122 | _civicrm_dsn_init(); 1123 | } 1124 | 1125 | /** 1126 | * Implements drush_hook_pre_COMMAND(). 1127 | * 1128 | * This function is called when using drush 5. 1129 | */ 1130 | function drush_civicrm_pre_civicrm_sqlcli() { 1131 | _civicrm_dsn_init(); 1132 | } 1133 | 1134 | /** 1135 | * Implementation of command 'civicrm-sql-cli'. 1136 | */ 1137 | function drush_civicrm_sqlcli() { 1138 | drush_sql_cli(); 1139 | } 1140 | 1141 | /** 1142 | * Implements drush_hook_post_COMMAND(). 1143 | * 1144 | * This function is called when using drush 6. 1145 | */ 1146 | function drush_civicrm_post_civicrm_sql_cli() { 1147 | _civicrm_dsn_close(); 1148 | } 1149 | 1150 | /** 1151 | * Implements drush_hook_post_COMMAND(). 1152 | * 1153 | * This function is called when using drush 5. 1154 | */ 1155 | function drush_civicrm_post_civicrm_sqlcli() { 1156 | _civicrm_dsn_close(); 1157 | } 1158 | 1159 | /** 1160 | * 1161 | */ 1162 | function _civicrm_dsn_init($reset = FALSE) { 1163 | static $globalDbUrl = NULL; 1164 | 1165 | if (!_civicrm_init()) { 1166 | return FALSE; 1167 | } 1168 | 1169 | // Check if we're using the old-style $GLOBALS['db_url'] 1170 | // or the new style ( > drupal 7 ) 1171 | if (drush_drupal_major_version() >= 7) { 1172 | $database = drush_get_option('database', 'default'); 1173 | $target = drush_get_option('target', 'default'); 1174 | if (!$globalDbUrl && CIVICRM_DSN) { 1175 | if (isset($GLOBALS['databases'][$database][$target])) { 1176 | // Keep a copy so that we can put it back. 1177 | $globalDbUrl = $GLOBALS['databases'][$database][$target]; 1178 | } 1179 | // Now modify $GLOBALS so that drush works on CIVICRM_DSN instead of drupal's. 1180 | $GLOBALS['databases'][$database][$target] = drush_convert_db_from_db_url(CIVICRM_DSN); 1181 | } 1182 | } 1183 | else { 1184 | if (!$globalDbUrl && CIVICRM_DSN) { 1185 | // Keep a copy so that we can put it back. 1186 | $globalDbUrl = $GLOBALS['db_url']; 1187 | } 1188 | // Now modify $GLOBALS so that drush works on CIVICRM_DSN instead of drupal's. 1189 | $GLOBALS['db_url'] = CIVICRM_DSN; 1190 | } 1191 | $dbUrl = $globalDbUrl; 1192 | $globalDbUrl = $reset ? NULL : $globalDbUrl; 1193 | 1194 | return $dbUrl; 1195 | } 1196 | 1197 | /** 1198 | * 1199 | */ 1200 | function _civicrm_dsn_close() { 1201 | $globalDbUrl = _civicrm_dsn_init(TRUE); 1202 | if ($globalDbUrl) { 1203 | if (drush_drupal_major_version() >= 7) { 1204 | $database = drush_get_option('database', 'default'); 1205 | $target = drush_get_option('target', 'default'); 1206 | $GLOBALS['databases'][$database][$target] = $globalDbUrl; 1207 | } 1208 | else { 1209 | $GLOBALS['db_url'] = $globalDbUrl; 1210 | } 1211 | } 1212 | } 1213 | 1214 | /** 1215 | * Initializes the CiviCRM environment and configuration. 1216 | * TODO: document why we can't call civicrm_initialize() directly. 1217 | * 1218 | * @param bool fail 1219 | * If true, will halt drush. Otherwise, return false but do not interrupt. 1220 | * 1221 | * @return bool 1222 | * Returns TRUE if CiviCRM was initialized. 1223 | */ 1224 | function _civicrm_init($fail = TRUE) { 1225 | static $init = NULL; 1226 | 1227 | // Return if already initialized. 1228 | if ($init) { 1229 | return $init; 1230 | } 1231 | 1232 | global $cmsPath; 1233 | $cmsPath = $drupal_root = drush_get_context('DRUSH_DRUPAL_ROOT'); 1234 | $site_root = drush_get_context('DRUSH_DRUPAL_SITE_ROOT', FALSE); 1235 | $civicrmSettingsFile = "$drupal_root/$site_root/civicrm.settings.php"; 1236 | 1237 | if (!file_exists($civicrmSettingsFile)) { 1238 | $sites_subdir = drush_get_option('sites-subdir', 'default'); 1239 | $civicrmSettingsFile = "$drupal_root/sites/$sites_subdir/civicrm.settings.php"; 1240 | if (!file_exists($civicrmSettingsFile)) { 1241 | if ($fail) { 1242 | return drush_set_error('CIVICRM_INIT_SETTINGS_NOT_FOUND', dt('Could not locate civicrm settings file.')); 1243 | } 1244 | else { 1245 | return FALSE; 1246 | } 1247 | } 1248 | } 1249 | // Include settings file. 1250 | define('CIVICRM_SETTINGS_PATH', $civicrmSettingsFile); 1251 | include_once $civicrmSettingsFile; 1252 | global $civicrm_root; 1253 | if (!is_dir($civicrm_root)) { 1254 | return drush_set_error('CIVICRM_INIT_CODEBASE_NOT_FOUND', dt('Could not locate CiviCRM codebase. Make sure CiviCRM settings file has correct information.')); 1255 | } 1256 | 1257 | require_once $civicrm_root . '/CRM/Core/ClassLoader.php'; 1258 | CRM_Core_ClassLoader::singleton()->register(); 1259 | // Also initialize config object. 1260 | CRM_Core_Config::singleton(); 1261 | 1262 | $init = TRUE; 1263 | return $init; 1264 | } 1265 | 1266 | /** 1267 | * 1268 | */ 1269 | function _civicrm_get_crmpath() { 1270 | if (!$crmpath = drush_get_option('destination', FALSE)) { 1271 | $crmpath = drush_get_context('DRUSH_DRUPAL_SITE_ROOT', FALSE) . '/modules/'; 1272 | if (!is_dir($crmpath)) { 1273 | $crmpath = "sites/all/modules"; 1274 | } 1275 | } 1276 | return $crmpath; 1277 | } 1278 | 1279 | /** 1280 | * (Drush callback) 1281 | * 1282 | * Implementation of command 'civicrm-api' 1283 | */ 1284 | function drush_civicrm_api() { 1285 | $DEFAULTS = ['version' => 3]; 1286 | 1287 | $args = func_get_args(); 1288 | list($entity, $action) = explode('.', $args[0]); 1289 | array_shift($args); 1290 | 1291 | // Parse $params. 1292 | switch (drush_get_option('in', 'args')) { 1293 | case 'args': 1294 | $params = $DEFAULTS; 1295 | foreach ($args as $arg) { 1296 | preg_match('/^([^=]+)=(.*)$/', $arg, $matches); 1297 | $params[$matches[1]] = $matches[2]; 1298 | } 1299 | break; 1300 | 1301 | case 'json': 1302 | $json = stream_get_contents(STDIN); 1303 | if (empty($json)) { 1304 | $params = $DEFAULTS; 1305 | } 1306 | else { 1307 | $params = array_merge($DEFAULTS, json_decode($json, TRUE)); 1308 | } 1309 | break; 1310 | 1311 | default: 1312 | drush_set_error(dt('Unknown format: @format', ['@format' => $format])); 1313 | break; 1314 | } 1315 | 1316 | \Drupal::service('civicrm')->initialize(); 1317 | 1318 | global $user; 1319 | CRM_Core_BAO_UFMatch::synchronize($user, FALSE, 'Drupal', 'Individual' 1320 | ); 1321 | 1322 | $result = civicrm_api($entity, $action, $params); 1323 | 1324 | switch (drush_get_option('out', 'pretty')) { 1325 | case 'pretty': 1326 | drush_print_r($result); 1327 | break; 1328 | 1329 | case 'json': 1330 | drush_print(json_encode($result)); 1331 | break; 1332 | 1333 | default: 1334 | return drush_set_error('CIVICRM_UNKNOWN_FORMAT', dt('Unknown format: @format', ['@format' => $format])); 1335 | } 1336 | } 1337 | 1338 | /** 1339 | * (Drush callback) 1340 | * 1341 | * Implementation of command 'civicrm-pipe' 1342 | */ 1343 | function drush_civicrm_pipe(?string $connection_flags = NULL) { 1344 | if (!civicrm_initialize()) { 1345 | return drush_set_error('CIVICRM_UNINSTALLED', dt('CiviCRM is not setup.')); 1346 | } 1347 | if (!is_callable(['Civi', 'pipe'])) { 1348 | return drush_set_error('CIVICRM_PIPE_UNSUPPORTED', dt('This version of CiviCRM does not include Civi::pipe() support.')); 1349 | } 1350 | if (!empty($connection_flags)) { 1351 | Civi::pipe($connection_flags); 1352 | } 1353 | else { 1354 | Civi::pipe(); 1355 | } 1356 | } 1357 | 1358 | /** 1359 | * Callback function for civicrm-process-mail-queue. 1360 | * 1361 | * Call the process_mailing job to process any outstanding mailing jobs. This 1362 | * command will need to be run as a user with the correct permissions to 1363 | * process mailings. 1364 | * 1365 | * @see civicrm_drush_command() 1366 | */ 1367 | function drush_civicrm_process_mail_queue() { 1368 | $init = _civicrm_init(); 1369 | $facility = new CRM_Core_JobManager(); 1370 | $facility->setSingleRunParams('Job', 'process_mailing', [], 'Started by drush'); 1371 | $facility->executeJobByAction('Job', 'process_mailing'); 1372 | } 1373 | --------------------------------------------------------------------------------