heartbeat.module 17 KB

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