message_thread.module 11.7 KB
Newer Older
New Zeal's avatar
New Zeal committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
<?php
/**
 * @file
 *   Module functions and hooks for message_thread
 */

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\message_thread\Entity\MessageThreadTemplate;
use Drupal\message_thread\Entity\MessageThread;
use Drupal\views\Views;
use Drupal\Core\Form\FormStateInterface;
use Drupal\message\Entity\MessageTemplate;
use Drupal\user\Entity\User;
use Drupal\Core\Access\AccessResult;
19 20
use Drupal\message_thread\MessageThreadAccessControlHandler;
use Drupal\message_private\MessagePrivateAccessControlHandler;
New Zeal's avatar
New Zeal committed
21

22 23 24 25 26 27 28 29 30 31

/**
 * Implements hook_installed.
 * Flush cache after install to ensure that all routes are read
 */
function message_thread_modules_installed() {
  drupal_flush_all_caches();
}


New Zeal's avatar
New Zeal committed
32 33 34 35 36 37 38 39 40 41 42
/**
 * Implements hook_help().
 */
function message_thread_help($route_name, RouteMatchInterface $arg) {
  switch ($route_name) {
    case 'help.page.message_thread':
      $output = file_get_contents(drupal_get_path('module', 'message_thread') . '/README.md');
      return \Drupal::moduleHandler()->moduleExists('markdown') ? \Drupal\Component\Utility\Xss::filterAdmin(\Drupal::moduleHandler()->invoke('markdown', 'filter', ['process', 0, -1, $output])) : '<h3>Message Private README</h3><pre>' . \Drupal\Component\Utility\Html::escape($output) . '</pre>';
  }
}

43 44 45
/*
 * Implements hook_form_alter().
 */
New Zeal's avatar
New Zeal committed
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
function message_thread_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  // When a message is created we need to ensure that the participants are included
  // This is best done in the validation hook to ensure participants are not missed from submit functions
  $thread_templates = \Drupal::entityTypeManager()->getListBuilder('message_thread_template')->load();
  foreach ($thread_templates as $name => $template) {
    $settings = $template->getSettings();
    $message_template = MessageTemplate::load($settings['message_template']);
    $message_form_id = 'message_' . $message_template->getTemplate() . '_form';
    if ($form_id == $message_form_id) {
      $parameters = \Drupal::routeMatch()->getParameters();

      $owner = $form['uid']['widget'][0]['target_id']['#default_value'];

      if ($parameters->has('message_thread')) {
        $form['message_thread'] = [
          '#type' => 'hidden',
          '#value' => $parameters->get('message_thread')
        ];
        $message_thread = MessageThread::load( $parameters->get('message_thread'));
        $participants = $message_thread->get('field_thread_participants')->getValue();
        $widget_base = $form['field_message_private_to_user']['widget'][0];
        foreach ($participants as $key => $participant) {
          // Don't include the sender
          if ($participant['target_id'] == $owner->id()) {
            unset ($form['field_message_private_to_user']['widget'][$key]);
            continue;
          }
          $form['field_message_private_to_user']['widget'][$key] = $widget_base;
          $form['field_message_private_to_user']['widget'][$key]['target_id']['#default_value'] = User::load($participant['target_id']);
        }
76 77
        // We also should disable the to field because this is controlled from the thread
        $form['field_message_private_to_user']['#disabled'] = TRUE;
New Zeal's avatar
New Zeal committed
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108


        foreach (array_keys($form['actions']) as $action) {
          if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
            $form['actions'][$action]['#submit'][] = 'message_thread_submit_message';
          }
        }

        break;
        // Todo If there is no message thread parameter then we abort
      }

    }

  }
}

/*
 * Submit callback
 */
function message_thread_submit_message(array &$form, FormStateInterface $form_state) {
  // Save the relationship between the thread and the message
  db_insert('message_thread_index')
    ->fields(
      array(
        'mid' => $form_state->getValue('mid'),
        'thread_id' => $form_state->getValue('message_thread'),
        'created' => REQUEST_TIME
      )
    )->execute();
}
109

110 111 112 113 114
/**
 * Implements hook_preprocess_links().
 *
 * @param $variables
 * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
New Zeal's avatar
New Zeal committed
115 116
 *
 * todo should use this hook: message_ui_message_ui_views_contextual_links_info
117 118 119
 */
function message_thread_preprocess_links(&$variables) {

New Zeal's avatar
New Zeal committed
120 121 122 123
  if (!message_thread_is_message_route()) {
    return;
  }

124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
  if ($variables['theme_hook_original'] == 'links__dropbutton__operations') {
    $account = \Drupal::currentUser();

    foreach ($variables['links'] as $key => $link) {
      $route_name = $link['link']['#url']->getRouteName();
      $route_parameters = $link['link']['#url']->getRouteParameters();

      $entity_type = key($route_parameters);
      $entity = \Drupal::entityTypeManager()->getStorage($entity_type)->load($route_parameters[$entity_type]);

      if (!$entity) {
        continue;
      }
      $operation = strtolower($link['link']['#title']->__toString());
      if (substr($route_name, 0, 15) == 'entity.message.') {
139 140 141
//        $message_access_manager = new MessagePrivateAccessControlHandler($entity->getEntityType());
//        $access = $message_access_manager->checkAccess($entity, $operation, $account);
        $access = message_private_message_access($entity, $operation, $account);
142 143 144 145
        // Disable link if user does not have access
        if ($access instanceof Drupal\Core\Access\AccessResultForbidden) {
          unset ($variables['links'][$key]);
        }
146
      }
147 148 149 150
    }
  }
}

New Zeal's avatar
New Zeal committed
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
/*
 * Test if the current route is a message thread or message route
 */
function message_thread_is_message_route() {
  $message = \Drupal::routeMatch()->getParameter('message');
  if ($message) {
    return TRUE;
  }
  $message_thread = \Drupal::routeMatch()->getParameter('message>_thread');
  if ($message_thread) {
    return TRUE;
  }
  return FALSE;
}

New Zeal's avatar
New Zeal committed
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
/**
 * Implements hook_entity_extra_field_info().
 */
function message_thread_entity_extra_field_info() {
  $bundles = \Drupal::entityManager()->getBundleInfo('message_thread');

  foreach ($bundles as $machine_name => $bundle) {

    $extra_fields['message_thread'][$machine_name]['display']['message_thread_messages'] = [
      'label' => t('Messages'),
      'description' => t('Show all messages inside a thread'),
      'weight' => 0,
      'visible' => FALSE,
    ];

    $extra_fields['message_thread'][$machine_name]['display']['message_thread_reply'] = [
      'label' => t('Reply'),
      'description' => t('Reply to this thread'),
      'weight' => 0,
      'visible' => FALSE,
    ];

    $extra_fields['message_thread'][$machine_name]['display']['uid'] = [
      'label' => t('Author'),
      'description' => t('Creator of this thread'),
      'weight' => 0,
      'visible' => FALSE,
    ];

    $extra_fields['message_thread'][$machine_name]['display']['created'] = [
      'label' => t('Created'),
      'description' => t('Date this thread was created'),
      'weight' => 0,
      'visible' => FALSE,
    ];

  }

  return $extra_fields;
}

/**
 * Implements hook_entity_view_alter().
 */
function message_thread_entity_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {

  // Add the link to all message thread types
  // Maybe this should be controlled through settings but let's see if there are other uses for this module first
  // Other than as conversation threads
  if ($entity->getEntityTypeId() === 'message_thread') {
    if ($component = $display->getComponent('message_thread_messages')) {
      $template = $entity->bundle();
      $config_entity = MessageThreadTemplate::load($template);
      $settings = $config_entity->getSettings();

      $build['message_thread_messages'] = [
        0 => message_thread_get_messages_display($settings, $entity),
        '#weight' => $component['weight']
      ];
    }
    if ($component = $display->getComponent('message_thread_reply')) {
      $build['reply'] = message_thread_reply_link($entity, $component);
    }

  }
}

/**
 * Helper function to display the messages as a View
 * @param $settings
 * @return array|bool|null
 */
function message_thread_get_messages_display($settings, $entity) {
239

New Zeal's avatar
New Zeal committed
240 241 242 243 244 245 246 247 248 249 250 251 252
  $view_name = $settings['view_id'];
  $display_id = $settings['view_display_id'];
  $view = Views::getView($view_name);
  // Someone may have deleted the View.
  if (!is_object($view)) {
    return FALSE;
  }

  $view->setDisplay($display_id);
  $view->setArguments(array($entity->id()));
  $view->build($display_id);
  $view->preExecute();
  $view->execute($display_id);
253
  $view->element['#attached']['library'][] = 'message_thread/thread-styles';
New Zeal's avatar
New Zeal committed
254 255 256 257 258 259 260

  if (!empty($view->result) || !empty($view->empty)) {
    return $view->buildRenderable($display_id);
  }
  return FALSE;
}

261 262 263
/*
 * Helper function to build the reply link
 */
New Zeal's avatar
New Zeal committed
264
function message_thread_reply_link($entity, $component) {
265 266 267 268 269 270 271 272 273
  // Find out if any messages in this conversation
  $query = \Drupal::database()->select('message_thread_index', 't');
  $query->condition('t.thread_id', $entity->id());
  $query->addExpression('COUNT(*)');
  $count = $query->execute()->fetchField();
  $label = t('Send a message');
  if ($count > 0) {
    $label = t('Reply');
  }
New Zeal's avatar
New Zeal committed
274 275 276 277 278 279 280 281 282 283 284 285 286 287
  // Todo template should reference actual template
  $params = array(
    'message_template' => 'private_message',
    'message_thread' => $entity->id()
  );
  $options = [
    'query' => [
      'destination' => '/message-thread/' . $entity->id()
    ]
  ];
  $url = Url::fromRoute('message_thread.reply', $params, $options);
  return array(
    '#type' => 'link',
    '#url' => $url,
288
    '#title' => $label,
New Zeal's avatar
New Zeal committed
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
    '#weight' => $component['weight'],
    '#attributes' => array(
      'class' => array('message-thread-reply')
    )
  );
}

/*
 * Message submit callback
 * See Drupal\message_thread\Controller\MessageThreadController.php
 */
function message_thread_add_message_form_submit(&$form, FormStateInterface &$form_state) {
  $values = $form_state->getValues();
  return;


}

/**
 * Implements hook_entity_base_field_info_alter().
 *
 * Extend the message entity type's field by providing display handlers.
 */
function message_thread_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
  // Alter the uid and created field to include display settings.
  if ($entity_type->id() != 'message_thread') {
    return;
  }

  if (!empty($fields['uid'])) {
    /* @var Drupal\Core\Field\BaseFieldDefinition $fields['uid'] */
    $fields['uid']
      ->setDisplayOptions('form', [
        'type' => 'entity_reference_autocomplete',
        'weight' => 5,
        '#group' => 'advanced',
        'settings' => [
          'match_operator' => 'CONTAINS',
          'size' => '60',
          'placeholder' => '',
        ],
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setRequired(TRUE);
  }
  if (!empty($fields['created'])) {
    $fields['created']
      ->setDisplayOptions('form', [
        'type' => 'datetime_timestamp',
        'weight' => 10,
      ])
      ->setDisplayConfigurable('form', TRUE);
  }
}


345 346 347 348 349 350
/*
 * Implements hook_local_tasks_alter().
 */
function message_thread_local_tasks_alter(&$local_tasks) {
  //We no longer need the private message local task on the user page
  unset($local_tasks['message_private.messages']);
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
}

/**
 * Views Plugin access callback.
 *
 * @return \Drupal\Core\Access\AccessResult
 */
function message_thread_tab_access_check() {
  $account = \Drupal::currentUser();
  // Load the current node.
  $uid = \Drupal::routeMatch()->getParameter('user');

  // Check if the current user owns the inbox.
  if (!empty($uid) && $account->id() == $uid) {
    return AccessResult::allowed();
  }

  // Allow if the user has the bypass permission
  return AccessResult::allowedIfHasPermission($account, 'bypass private message access control');
}