heartbeat.module 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. <?php
  2. /**
  3. * @file
  4. * Contains heartbeat.module.
  5. */
  6. use Drupal\Core\Routing\RouteMatchInterface;
  7. use Drupal\Core\Entity\EntityInterface;
  8. use Drupal\Core\Url;
  9. use Drupal\Core\Form\FormState;
  10. use Drupal\node\NodeInterface;
  11. use Drupal\Core\Session\AccountInterface;
  12. use Drupal\Core\Entity;
  13. use Drupal\Component\Utility\Html;
  14. use Drupal\Core\Database\Database;
  15. use Drupal\heartbeat\Entity\FILE_FIELD;
  16. use Drupal\heartbeat\Entity\Heartbeat;
  17. use GuzzleHttp\Exception\RequestException;
  18. use Drupal\heartbeat\Entity\HeartbeatType;
  19. use Drupal\heartbeat\Ajax\UpdateFeedCommand;
  20. /**
  21. * Implements hook_help().
  22. */
  23. function heartbeat_help($route_name, RouteMatchInterface $route_match) {
  24. switch ($route_name) {
  25. // Main module help for the heartbeat module.
  26. case 'help.page.heartbeat':
  27. $output = '';
  28. $output .= '<h3>' . t('About') . '</h3>';
  29. $output .= '<p>' . t('Heartbeat for Drupal 8') . '</p>';
  30. return $output;
  31. default:
  32. }
  33. }
  34. /**
  35. * Implements hook_theme().
  36. */
  37. function heartbeat_theme() {
  38. $theme = [];
  39. $theme['heartbeat'] = array(
  40. 'render element' => 'elements',
  41. 'file' => 'heartbeat.page.inc',
  42. 'template' => 'heartbeat',
  43. );
  44. $theme['heartbeat_content_add_list'] = [
  45. 'render element' => 'content',
  46. 'variables' => ['content' => NULL],
  47. 'file' => 'heartbeat.page.inc',
  48. ];
  49. $theme['heartbeat_stream'] = [
  50. 'variables' => array(
  51. 'messages' => NULL,
  52. 'zilla' => 2,
  53. )
  54. ];
  55. return $theme;
  56. }
  57. /**
  58. * Implements hook_theme_suggestions_HOOK().
  59. */
  60. function heartbeat_theme_suggestions_heartbeat(array $variables) {
  61. $suggestions = array();
  62. $entity = $variables['elements']['#heartbeat'];
  63. $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
  64. $suggestions[] = 'heartbeat__' . $sanitized_view_mode;
  65. $suggestions[] = 'heartbeat__' . $entity->bundle();
  66. $suggestions[] = 'heartbeat__' . $entity->bundle() . '__' . $sanitized_view_mode;
  67. $suggestions[] = 'heartbeat__' . $entity->id();
  68. $suggestions[] = 'heartbeat__' . $entity->id() . '__' . $sanitized_view_mode;
  69. return $suggestions;
  70. }
  71. /**
  72. * Implements hook_entity_insert().
  73. */
  74. function heartbeat_entity_insert(EntityInterface $entity) {
  75. $bundleSaved = false;
  76. switch (true) {
  77. case $entity instanceof \Drupal\node\Entity\Node:
  78. $user = $entity->getOwner();
  79. $media = HeartBeat::mediaFieldTypes($entity->getFields());
  80. if ($entity->id() && $user->isAuthenticated()) {
  81. $heartbeatTypeService = \Drupal::service('heartbeat.heartbeattype');
  82. $tokenService = \Drupal::service('token');
  83. foreach ($heartbeatTypeService->getTypes() as $type) {
  84. $heartbeatTypeEntity = $heartbeatTypeService->load($type);
  85. if ($heartbeatTypeEntity->getMainEntity() == 'node') {
  86. $arguments = json_decode($heartbeatTypeEntity->getArguments());
  87. foreach ($arguments as $key => $argument) {
  88. $variables[$key] = $argument;
  89. }
  90. $preparsedMessageString = strtr($heartbeatTypeEntity->getMessage(), $variables);
  91. $entities = array(
  92. 'node' => $entity,
  93. 'user' => $user,
  94. );
  95. if ($entity->bundle() === $heartbeatTypeEntity->getBundle()
  96. &&
  97. array_key_exists($heartbeatTypeEntity->getBundle(), $heartbeatTypeService->getEntityBundles($entity->getEntityType()))
  98. ) {
  99. $heartbeatMessage = Heartbeat::buildMessage($tokenService, $preparsedMessageString, $entities, $entity->getEntityTypeId(), $media);
  100. $heartbeatActivity = Heartbeat::create([
  101. 'type' => $heartbeatTypeEntity->id(),
  102. 'uid' => $user->id(),
  103. 'nid' => $entity->id(),
  104. 'name' => $entity->getTitle(),
  105. ]);
  106. //TODO Find better fix than this str_replace
  107. $heartbeatActivity->setMessage(str_replace('&039;', "'", $heartbeatMessage));
  108. if ($heartbeatActivity->save()) {
  109. $bundleSaved = true;
  110. }
  111. continue;
  112. } else if ($heartbeatTypeEntity->getBundle() === null || trim($heartbeatTypeEntity->getBundle()) === '') {
  113. $heartbeatMessage = Heartbeat::buildMessage($tokenService, $preparsedMessageString, $entities, $entity->getEntityTypeId(), $media);
  114. // $translatedMessage = t($messageTemplate);
  115. $heartbeatActivity = Heartbeat::create([
  116. 'type' => $heartbeatTypeEntity->id(),
  117. 'uid' => $user->id(),
  118. 'nid' => $entity->id(),
  119. 'name' => 'Dev Test',
  120. 'status' => !$bundleSaved ? 1 : 0,
  121. ]);
  122. $heartbeatActivity->setMessage($heartbeatMessage);
  123. $heartbeatActivity->save();
  124. } else {
  125. continue;
  126. }
  127. }
  128. }
  129. updateFeeds();
  130. }
  131. break;
  132. case $entity instanceof \Drupal\user\Entity\User:
  133. // $userService = \Drupal\User\Entity\user
  134. break;
  135. case $entity instanceof \Drupal\flag\Entity\Flag:
  136. break;
  137. case $entity instanceof \Drupal\statusmessage\Entity\Status:
  138. $user = \Drupal\user\Entity\User::load($entity->get('uid')->getValue()[0]['target_id']);
  139. $heartbeatTypeService = \Drupal::service('heartbeat.heartbeattype');
  140. $tokenService = \Drupal::service('token');
  141. heartbeat_handle_entity($entity, $tokenService, $heartbeatTypeService, $user, 'status');
  142. break;
  143. }
  144. }
  145. function heartbeat_handle_entity($entity, $tokenService, $heartbeatTypeService, $user, $mainEntity) {
  146. $bundleSaved = false;
  147. if ($entity->id() && $user->isAuthenticated()) {
  148. $media = HeartBeat::mediaFieldTypes($entity->getFields());
  149. foreach ($heartbeatTypeService->getTypes() as $type) {
  150. $heartbeatTypeEntity = $heartbeatTypeService->load($type);
  151. if ($heartbeatTypeEntity->getMainEntity() == $mainEntity) {
  152. $arguments = json_decode($heartbeatTypeEntity->getArguments());
  153. foreach ($arguments as $key => $argument) {
  154. $variables[$key] = $argument;
  155. }
  156. $preparsedMessageString = strtr($heartbeatTypeEntity->getMessage(), $variables);
  157. $entities = array(
  158. $mainEntity => $entity,
  159. 'user' => $user,
  160. );
  161. if ($entity->bundle() === $heartbeatTypeEntity->getBundle()
  162. &&
  163. array_key_exists($heartbeatTypeEntity->getBundle(), $heartbeatTypeService->getEntityBundles($entity->getEntityType()))
  164. ) {
  165. $heartbeatMessage = Heartbeat::buildMessage($tokenService, $preparsedMessageString, $entities, $entity->getEntityTypeId(), $media);
  166. $heartbeatActivity = Heartbeat::create([
  167. 'type' => $heartbeatTypeEntity->id(),
  168. 'uid' => $user->id(),
  169. 'nid' => $entity->id(),
  170. 'name' => 'Dev Test',
  171. ]);
  172. $heartbeatActivity->setMessage($heartbeatMessage);
  173. if ($heartbeatActivity->save()) {
  174. $bundleSaved = true;
  175. }
  176. continue;
  177. } else if ($heartbeatTypeEntity->getBundle() === null || trim($heartbeatTypeEntity->getBundle()) === '') {
  178. $heartbeatMessage = Heartbeat::buildMessage($tokenService, $preparsedMessageString, $entities, $entity->getEntityTypeId(), $media);
  179. // $translatedMessage = t($messageTemplate);
  180. $heartbeatActivity = Heartbeat::create([
  181. 'type' => $heartbeatTypeEntity->id(),
  182. 'uid' => $user->id(),
  183. 'nid' => $entity->id(),
  184. 'name' => 'Dev Test',
  185. 'status' => !$bundleSaved ? 1 : 0,
  186. ]);
  187. $heartbeatActivity->setMessage($heartbeatMessage);
  188. $heartbeatActivity->save();
  189. } else {
  190. continue;
  191. }
  192. }
  193. }
  194. }
  195. updateFeeds();
  196. }
  197. function updateFeeds() {
  198. $configFactory = \Drupal::service('config.factory');
  199. $updateFeedConfig = $configFactory->getEditable('heartbeat_update_feed.settings');
  200. $feedConfig = $configFactory->get('heartbeat_feed.settings');
  201. // $form = \Drupal::formBuilder()->getForm('\Drupal\heartbeat\Form\HeartbeatUpdateFeedForm');
  202. // $form_state = new FormState();
  203. // $form_state->set('timestamp', $updateFeedConfig->get('timestamp'));
  204. // \Drupal::formBuilder()->submitForm('\Drupal\heartbeat\Form\HeartbeatUpdateFeedForm', $form_state);
  205. // $errors = $form_state->getErrors();
  206. // $updateFeedConfig->set('update', true)->save();
  207. // $feedUpdateConfig = new stdClass();
  208. // $feedUpdateConfig->feed = $feedConfig->get('message');
  209. // $feedUpdateConfig->update = true;
  210. // $feedUpdateConfig->timestamp = $updateFeedConfig->get('timestamp');
  211. // $curlQuery = '/heartbeat/update_feed/' . $updateFeedConfig->get('timestamp');
  212. //Set options for the curl request
  213. // $curlOptions = array(
  214. // 'headers' => array(
  215. // 'X-DataSource-Auth' => 'a',
  216. // 'method' => 'POST',
  217. // ),
  218. // );
  219. // //Perform the request and decode the results
  220. // $result = chr_curl_http_request($curlQuery, $curlOptions);
  221. }
  222. //public function saveHeartbeatMessage($entity, $tokenService, $preparsedMessageString, $entities, $entityTypeId, $media) {
  223. // $heartbeatMessage = Heartbeat::buildMessage($tokenService, $preparsedMessageString, $entities, $entity->getEntityTypeId(), $media);
  224. //
  225. //
  226. // $heartbeatActivity = Heartbeat::create([
  227. // 'type' => $heartbeatTypeEntity->id(),
  228. // 'uid' => $user->id(),
  229. // 'nid' => $entity->id(),
  230. // 'name' => 'Dev Test',
  231. // ]);
  232. //
  233. // $heartbeatActivity->setMessage($heartbeatMessage);
  234. // $heartbeatActivity->save();
  235. //}
  236. /**
  237. * Implements hook_entity_view().
  238. */
  239. function heartbeat_entity_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {
  240. if ($entity instanceof \Drupal\user\Entity\User) {
  241. if (isset($build['flag_friendship']) && \Drupal::currentUser()->id() === $entity->id()) {
  242. \Drupal::logger('heartbeat_friendship_entityView')->debug('IDs are %id1 and %id2', array(
  243. '%id1' => \Drupal::currentUser()->id(),
  244. '%id2' => $entity->id(),
  245. ));
  246. unset($build['flag_friendship']);
  247. }
  248. }
  249. }
  250. /**
  251. * Implements hook_cron().
  252. */
  253. function heartbeat_cron() {
  254. $friendship = false;
  255. //Iterate over the Heartbeat Types and ensure that the weight of bundle-specific types are lower than that of their
  256. //parent type. This will allow us to ensure Bundle specific types end up being published as opposed to
  257. //Types which represent all content types
  258. $heartbeatTypes = \Drupal::service('entity.query')->get('heartbeat_type')->condition('mainentity', 'node')->execute();
  259. foreach($heartbeatTypes as $heartbeatType) {
  260. $entity = \Drupal::service('entity_type.manager')->getStorage('heartbeat_type')->load($heartbeatType);
  261. if ($entity->getBundle() === null) {
  262. $entity->setWeight(99);
  263. $entity->save();
  264. } else {
  265. $entity->setWeight(0);
  266. $entity->save();
  267. }
  268. if ($entity->getMainEntity() === 'flagging') {
  269. $friendship = true;
  270. $flagService = \Drupal::service('flag');
  271. foreach ($flagService->getAllFlags('user') as $flag) {
  272. if ($flag->id() === 'friendship') {
  273. $flaggings = \Drupal\Core\Database\Database::getConnection()->select('flagging', 'f')
  274. ->fields('f', array('entity_id', 'uid'))
  275. ->condition('flag_id', $flag->id())->execute();
  276. foreach ($flaggings->fetchAll() as $flagging) {
  277. $friendship = \Drupal\Core\Database\Database::getConnection()->select('heartbeat_friendship', 'hf')
  278. ->fields(array('status'))
  279. ->condition('uid', $flagging->uid)
  280. ->condition('uid_target', $flagging->entity_id)
  281. ->execute();
  282. if ($friendship = $friendship->fetchObject()) {
  283. $status = $friendship->status;
  284. $revFriendship = \Drupal\Core\Database\Database::getConnection()->select('heartbeat_friendship', 'hf')
  285. ->fields(array('status'))
  286. ->condition('uid', $flagging->entity_id)
  287. ->condition('uid_target', $flagging->uid)
  288. ->execute();
  289. if ($revFriendship = $revFriendship->fetchObject()) {
  290. $revStatus = $revFriendship->status;
  291. }
  292. }
  293. }
  294. }
  295. }
  296. }
  297. // $entityQuery = \Drupal::service('entity.query')->get('flag
  298. // foreach ($flagService->)
  299. }
  300. heartbeat_friendship_maintenance();
  301. }
  302. function heartbeat_friendship_maintenance() {
  303. $flagService = \Drupal::service('flag');
  304. $entityTypeManager = \Drupal::service('entity_type.manager');
  305. $flag = $flagService->getFlagById('friendship');
  306. $friendships = Database::getConnection()->select("heartbeat_friendship", "hf")
  307. ->fields('hf', array('status', 'uid', 'uid_target'))
  308. ->execute();
  309. foreach ($friendships->fetchAll() as $friendship) {
  310. $revFriendship = Database::getConnection()->select('heartbeat_friendship', 'hf')
  311. ->fields('hf', array('status'))
  312. ->condition('uid', $friendship->uid_target)
  313. ->condition('uid_target', $friendship->uid)
  314. ->execute();
  315. $revFriendResult = $revFriendship->fetchField();
  316. if ($revFriendResult > -2) {
  317. if ($revFriendResult !== $friendship->status) {
  318. $update = Database::getConnection()->update('heartbeat_friendship')
  319. ->fields(array(
  320. ':status' => 1,
  321. )
  322. )
  323. ->condition('uid', $friendship->uid)
  324. ->condition('uid_target', $friendship->uid_target);
  325. if ($updated = !$update->execute()) {
  326. \Drupal::logger('Heartbeat Cron')->error('Could not update status for friendship');
  327. }
  328. }
  329. if ($revFriendResult === $friendship->status ||
  330. $updated) {
  331. $userEntity = $entityTypeManager->getStorage('user')->load($friendship->uid);
  332. $userTargetEntity = $entityTypeManager->getStorage('user')->load($friendship->uid_target);
  333. $flaggingFound = false;
  334. foreach ($flagService->getEntityFlaggings($flag, $userTargetEntity) as $flagging) {
  335. $flOwner = $flagging->getOwnerId();
  336. $usId = $userEntity->id();
  337. $flaggableId = $flagging->getFlaggableId();
  338. //TODO ownerId and entity Id seem to be reversed.
  339. if ($flagging->getOwnerId() == $userEntity->id() && $flagging->getFlaggableId() == $friendship->uid_target) {
  340. $flaggingFound = true;
  341. break;
  342. }
  343. }
  344. if (!$flaggingFound) {
  345. $flagging = $flagService->flag($flag, $userTargetEntity, $userEntity);
  346. }
  347. $flaggingReverseFound = false;
  348. foreach ($flagService->getEntityFlaggings($flag, $userEntity) as $flagging) {
  349. if ($flagging->getOwnerId() == $userTargetEntity->id() && $flagging->getFlaggableId() == $friendship->uid) {
  350. $flaggingReverseFound = true;
  351. break;
  352. }
  353. }
  354. if (!$flaggingReverseFound) {
  355. $flagging = $flagService->flag($flag, $userEntity, $userTargetEntity);
  356. }
  357. //TODO update flagging values or create flaggings
  358. }
  359. } else if ($friendship->status === 1) {
  360. //TODO Add reverse friendship
  361. $insertReverse = Database::getConnection()->insert('heartbeat_friendship')
  362. ->fields([
  363. 'uid' => $friendship->uid_target,
  364. 'uid_target' => $friendship->uid,
  365. 'created' => time(),
  366. 'status' => 1
  367. ]);
  368. if ($insertReverse->execute()) {
  369. if ($friendship->status < 1) {
  370. $updateFriendship = Database::getConnection()->update('heartbeat_friendship')
  371. ->fields(array(
  372. 'status' => 1,
  373. ))
  374. ->condition('uid', $friendship->uid)
  375. ->condition('uid_target', $friendship->uid_target);
  376. if (!$updateFriendship->execute()) {
  377. \Drupal::logger('Friendship update failed');
  378. }
  379. }
  380. } else {
  381. \Drupal::logger('Heartbeat')->debug('Unable to insert or update for User with ID %id', ['%id' => $friendship->uid]);
  382. }
  383. } else {
  384. //TODO figure out how to set friendship pending
  385. }
  386. }
  387. }
  388. /**
  389. * Implements hook_cron().
  390. */
  391. function heartbeat_update_type_weight() {
  392. //Iterate over the Heartbeat Types and ensure that the weight of bundle-specific types are lower than that of their
  393. //parent type. This will allow us to ensure Bundle specific types end up being published as opposed to
  394. //Types which represent all content types
  395. $heartbeatTypes = \Drupal::service('entity.query')->get('heartbeat_type')->condition('mainentity', 'node')->execute();
  396. if (count($heartbeatTypes) > 1) {
  397. foreach($heartbeatTypes as $heartbeatType) {
  398. $entity = \Drupal::service('entity_type.manager')->getStorage('heartbeat_type')->load($heartbeatType);
  399. if ($entity->getBundle() === null) {
  400. $entity->setWeight(99);
  401. $entity->save();
  402. } else {
  403. $entity->setWeight(0);
  404. $entity->save();
  405. }
  406. }
  407. }
  408. }
  409. /**
  410. * Implements hook_page_attachments_alter().
  411. */
  412. function heartbeat_page_attachments_alter(array &$attachments) {
  413. $jigganull = 'naul';
  414. $jiagganull = 'naul';
  415. $mattachments = $attachments;
  416. $attachments['#attached']['library'][] = 'heartbeat/heartbeat';
  417. }
  418. function heartbeat_link_alter(&$variables) {
  419. if (!is_object($variables['text']) && $variables['text'] === 'Account Settings') {
  420. $token_service = \Drupal::token();
  421. $replacement = $token_service->replace($variables['url']->getUri(), [\Drupal::currentUser()]);
  422. unset($variables['url']);
  423. $url = Url::fromUserInput('/' . substr($replacement, 5));
  424. $variables['url'] = $url;
  425. }
  426. }
  427. /**
  428. * Implements hook_form_alter().
  429. */
  430. function heartbeat_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  431. }