heartbeat.module 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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' => $entity->getTitle(),
  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' => $entity->getTitle(),
  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' => $entity->getName(),
  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. }
  200. /**
  201. * Implements hook_entity_view().
  202. */
  203. function heartbeat_entity_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {
  204. if ($entity instanceof \Drupal\user\Entity\User) {
  205. if (isset($build['flag_friendship']) && \Drupal::currentUser()->id() === $entity->id()) {
  206. \Drupal::logger('heartbeat_friendship_entityView')->debug('IDs are %id1 and %id2', array(
  207. '%id1' => \Drupal::currentUser()->id(),
  208. '%id2' => $entity->id(),
  209. ));
  210. unset($build['flag_friendship']);
  211. }
  212. }
  213. }
  214. /**
  215. * Implements hook_cron().
  216. */
  217. function heartbeat_cron() {
  218. //Iterate over the Heartbeat Types and ensure that the weight of bundle-specific types are lower than that of their
  219. //parent type. This will allow us to ensure Bundle specific types end up being published as opposed to
  220. //Types which represent all content types
  221. $heartbeatTypes = \Drupal::service('entity.query')->get('heartbeat_type')->condition('mainentity', 'node')->execute();
  222. foreach($heartbeatTypes as $heartbeatType) {
  223. $entity = \Drupal::service('entity_type.manager')->getStorage('heartbeat_type')->load($heartbeatType);
  224. if ($entity->getBundle() === null) {
  225. $entity->setWeight(99);
  226. $entity->save();
  227. } else {
  228. $entity->setWeight(0);
  229. $entity->save();
  230. }
  231. if ($entity->getMainEntity() === 'flagging') {
  232. $friendship = true;
  233. $flagService = \Drupal::service('flag');
  234. foreach ($flagService->getAllFlags('user') as $flag) {
  235. if ($flag->id() === 'friendship') {
  236. $flaggings = \Drupal\Core\Database\Database::getConnection()->select('flagging', 'f')
  237. ->fields('f', array('entity_id', 'uid'))
  238. ->condition('flag_id', $flag->id())->execute();
  239. foreach ($flaggings->fetchAll() as $flagging) {
  240. $friendship = \Drupal\Core\Database\Database::getConnection()->select('heartbeat_friendship', 'hf')
  241. ->fields(array('status'))
  242. ->condition('uid', $flagging->uid)
  243. ->condition('uid_target', $flagging->entity_id)
  244. ->execute();
  245. if ($friendship = $friendship->fetchObject()) {
  246. $status = $friendship->status;
  247. $revFriendship = \Drupal\Core\Database\Database::getConnection()->select('heartbeat_friendship', 'hf')
  248. ->fields(array('status'))
  249. ->condition('uid', $flagging->entity_id)
  250. ->condition('uid_target', $flagging->uid)
  251. ->execute();
  252. if ($revFriendship = $revFriendship->fetchObject()) {
  253. $revStatus = $revFriendship->status;
  254. }
  255. }
  256. }
  257. }
  258. }
  259. }
  260. // $entityQuery = \Drupal::service('entity.query')->get('flag
  261. // foreach ($flagService->)
  262. }
  263. heartbeat_friendship_maintenance();
  264. }
  265. function heartbeat_friendship_maintenance() {
  266. $flagService = \Drupal::service('flag');
  267. $entityTypeManager = \Drupal::service('entity_type.manager');
  268. $flag = $flagService->getFlagById('friendship');
  269. $friendships = Database::getConnection()->select("heartbeat_friendship", "hf")
  270. ->fields('hf', array('status', 'uid', 'uid_target'))
  271. ->execute();
  272. foreach ($friendships->fetchAll() as $friendship) {
  273. $revFriendship = Database::getConnection()->select('heartbeat_friendship', 'hf')
  274. ->fields('hf', array('status'))
  275. ->condition('uid', $friendship->uid_target)
  276. ->condition('uid_target', $friendship->uid)
  277. ->execute();
  278. $revFriendResult = $revFriendship->fetchField();
  279. if ($revFriendResult > -2) {
  280. if ($revFriendResult !== $friendship->status) {
  281. $update = Database::getConnection()->update('heartbeat_friendship')
  282. ->fields(array(
  283. ':status' => 1,
  284. )
  285. )
  286. ->condition('uid', $friendship->uid)
  287. ->condition('uid_target', $friendship->uid_target);
  288. if ($updated = !$update->execute()) {
  289. \Drupal::logger('Heartbeat Cron')->error('Could not update status for friendship');
  290. }
  291. }
  292. if ($revFriendResult === $friendship->status ||
  293. $updated) {
  294. $userEntity = $entityTypeManager->getStorage('user')->load($friendship->uid);
  295. $userTargetEntity = $entityTypeManager->getStorage('user')->load($friendship->uid_target);
  296. $flaggingFound = false;
  297. foreach ($flagService->getEntityFlaggings($flag, $userTargetEntity) as $flagging) {
  298. $flOwner = $flagging->getOwnerId();
  299. $usId = $userEntity->id();
  300. $flaggableId = $flagging->getFlaggableId();
  301. //TODO ownerId and entity Id seem to be reversed.
  302. if ($flagging->getOwnerId() == $userEntity->id() && $flagging->getFlaggableId() == $friendship->uid_target) {
  303. $flaggingFound = true;
  304. break;
  305. }
  306. }
  307. if (!$flaggingFound) {
  308. $flagging = $flagService->flag($flag, $userTargetEntity, $userEntity);
  309. }
  310. $flaggingReverseFound = false;
  311. foreach ($flagService->getEntityFlaggings($flag, $userEntity) as $flagging) {
  312. if ($flagging->getOwnerId() == $userTargetEntity->id() && $flagging->getFlaggableId() == $friendship->uid) {
  313. $flaggingReverseFound = true;
  314. break;
  315. }
  316. }
  317. if (!$flaggingReverseFound) {
  318. $flagging = $flagService->flag($flag, $userEntity, $userTargetEntity);
  319. }
  320. //TODO update flagging values or create flaggings
  321. }
  322. } else if ($friendship->status === 1) {
  323. //TODO Add reverse friendship
  324. $insertReverse = Database::getConnection()->insert('heartbeat_friendship')
  325. ->fields([
  326. 'uid' => $friendship->uid_target,
  327. 'uid_target' => $friendship->uid,
  328. 'created' => time(),
  329. 'status' => 1
  330. ]);
  331. if ($insertReverse->execute()) {
  332. if ($friendship->status < 1) {
  333. $updateFriendship = Database::getConnection()->update('heartbeat_friendship')
  334. ->fields(array(
  335. 'status' => 1,
  336. ))
  337. ->condition('uid', $friendship->uid)
  338. ->condition('uid_target', $friendship->uid_target);
  339. if (!$updateFriendship->execute()) {
  340. \Drupal::logger('Friendship update failed');
  341. }
  342. }
  343. } else {
  344. \Drupal::logger('Heartbeat')->debug('Unable to insert or update for User with ID %id', ['%id' => $friendship->uid]);
  345. }
  346. } else {
  347. //TODO figure out how to set friendship pending
  348. }
  349. }
  350. }
  351. /**
  352. * Implements hook_cron().
  353. */
  354. function heartbeat_update_type_weight() {
  355. //Iterate over the Heartbeat Types and ensure that the weight of bundle-specific types are lower than that of their
  356. //parent type. This will allow us to ensure Bundle specific types end up being published as opposed to
  357. //Types which represent all content types
  358. $heartbeatTypes = \Drupal::service('entity.query')->get('heartbeat_type')->condition('mainentity', 'node')->execute();
  359. if (count($heartbeatTypes) > 1) {
  360. foreach($heartbeatTypes as $heartbeatType) {
  361. $entity = \Drupal::service('entity_type.manager')->getStorage('heartbeat_type')->load($heartbeatType);
  362. if ($entity->getBundle() === null) {
  363. $entity->setWeight(99);
  364. $entity->save();
  365. } else {
  366. $entity->setWeight(0);
  367. $entity->save();
  368. }
  369. }
  370. }
  371. }
  372. /**
  373. * Implements hook_page_attachments_alter().
  374. */
  375. function heartbeat_page_attachments_alter(array &$attachments) {
  376. $jigganull = 'naul';
  377. $jiagganull = 'naul';
  378. $mattachments = $attachments;
  379. $attachments['#attached']['library'][] = 'heartbeat/heartbeat';
  380. }
  381. function heartbeat_link_alter(&$variables) {
  382. if (!is_object($variables['text']) && $variables['text'] === 'Account Settings') {
  383. $token_service = \Drupal::token();
  384. $replacement = $token_service->replace($variables['url']->getUri(), [\Drupal::currentUser()]);
  385. unset($variables['url']);
  386. $url = Url::fromUserInput('/' . substr($replacement, 5));
  387. $variables['url'] = $url;
  388. }
  389. }
  390. /**
  391. * Implements hook_form_alter().
  392. */
  393. function heartbeat_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  394. }