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_ajax_render_alter().
  237. */
  238. function heartbeat_ajax_render_alter(array &$data) {
  239. $nullll = 'null';
  240. $muhData = $data;
  241. if ($data !== null) {
  242. $saysomething = 'here';
  243. }
  244. }
  245. /**
  246. * Implements hook_cron().
  247. */
  248. function heartbeat_cron() {
  249. $friendship = false;
  250. //Iterate over the Heartbeat Types and ensure that the weight of bundle-specific types are lower than that of their
  251. //parent type. This will allow us to ensure Bundle specific types end up being published as opposed to
  252. //Types which represent all content types
  253. $heartbeatTypes = \Drupal::service('entity.query')->get('heartbeat_type')->condition('mainentity', 'node')->execute();
  254. foreach($heartbeatTypes as $heartbeatType) {
  255. $entity = \Drupal::service('entity_type.manager')->getStorage('heartbeat_type')->load($heartbeatType);
  256. if ($entity->getBundle() === null) {
  257. $entity->setWeight(99);
  258. $entity->save();
  259. } else {
  260. $entity->setWeight(0);
  261. $entity->save();
  262. }
  263. if ($entity->getMainEntity() === 'flagging') {
  264. $friendship = true;
  265. $flagService = \Drupal::service('flag');
  266. foreach ($flagService->getAllFlags('user') as $flag) {
  267. if ($flag->id() === 'friendship') {
  268. $flaggings = \Drupal\Core\Database\Database::getConnection()->select('flagging', 'f')
  269. ->fields('f', array('entity_id', 'uid'))
  270. ->condition('flag_id', $flag->id())->execute();
  271. foreach ($flaggings->fetchAll() as $flagging) {
  272. $friendship = \Drupal\Core\Database\Database::getConnection()->select('heartbeat_friendship', 'hf')
  273. ->fields(array('status'))
  274. ->condition('uid', $flagging->uid)
  275. ->condition('uid_target', $flagging->entity_id)
  276. ->execute();
  277. if ($friendship = $friendship->fetchObject()) {
  278. $status = $friendship->status;
  279. $revFriendship = \Drupal\Core\Database\Database::getConnection()->select('heartbeat_friendship', 'hf')
  280. ->fields(array('status'))
  281. ->condition('uid', $flagging->entity_id)
  282. ->condition('uid_target', $flagging->uid)
  283. ->execute();
  284. if ($revFriendship = $revFriendship->fetchObject()) {
  285. $revStatus = $revFriendship->status;
  286. }
  287. }
  288. }
  289. }
  290. }
  291. }
  292. // $entityQuery = \Drupal::service('entity.query')->get('flag
  293. // foreach ($flagService->)
  294. }
  295. heartbeat_friendship_maintenance();
  296. }
  297. function heartbeat_friendship_maintenance() {
  298. $flagService = \Drupal::service('flag');
  299. $entityTypeManager = \Drupal::service('entity_type.manager');
  300. $flag = $flagService->getFlagById('friendship');
  301. $friendships = Database::getConnection()->select("heartbeat_friendship", "hf")
  302. ->fields('hf', array('status', 'uid', 'uid_target'))
  303. ->execute();
  304. foreach ($friendships->fetchAll() as $friendship) {
  305. $revFriendship = Database::getConnection()->select('heartbeat_friendship', 'hf')
  306. ->fields('hf', array('status'))
  307. ->condition('uid', $friendship->uid_target)
  308. ->condition('uid_target', $friendship->uid)
  309. ->execute();
  310. $revFriendResult = $revFriendship->fetchField();
  311. if ($revFriendResult > -2) {
  312. if ($revFriendResult !== $friendship->status) {
  313. $update = Database::getConnection()->update('heartbeat_friendship')
  314. ->fields(array(
  315. ':status' => 1,
  316. )
  317. )
  318. ->condition('uid', $friendship->uid)
  319. ->condition('uid_target', $friendship->uid_target);
  320. if ($updated = !$update->execute()) {
  321. \Drupal::logger('Heartbeat Cron')->error('Could not update status for friendship');
  322. }
  323. }
  324. if ($revFriendResult === $friendship->status ||
  325. $updated) {
  326. $userEntity = $entityTypeManager->getStorage('user')->load($friendship->uid);
  327. $userTargetEntity = $entityTypeManager->getStorage('user')->load($friendship->uid_target);
  328. $flaggingFound = false;
  329. foreach ($flagService->getEntityFlaggings($flag, $userTargetEntity) as $flagging) {
  330. $flOwner = $flagging->getOwnerId();
  331. $usId = $userEntity->id();
  332. $flaggableId = $flagging->getFlaggableId();
  333. //TODO ownerId and entity Id seem to be reversed.
  334. if ($flagging->getOwnerId() == $userEntity->id() && $flagging->getFlaggableId() == $friendship->uid_target) {
  335. $flaggingFound = true;
  336. break;
  337. }
  338. }
  339. if (!$flaggingFound) {
  340. $flagging = $flagService->flag($flag, $userTargetEntity, $userEntity);
  341. }
  342. $flaggingReverseFound = false;
  343. foreach ($flagService->getEntityFlaggings($flag, $userEntity) as $flagging) {
  344. if ($flagging->getOwnerId() == $userTargetEntity->id() && $flagging->getFlaggableId() == $friendship->uid) {
  345. $flaggingReverseFound = true;
  346. break;
  347. }
  348. }
  349. if (!$flaggingReverseFound) {
  350. $flagging = $flagService->flag($flag, $userEntity, $userTargetEntity);
  351. }
  352. //TODO update flagging values or create flaggings
  353. }
  354. } else if ($friendship->status === 1) {
  355. //TODO Add reverse friendship
  356. $insertReverse = Database::getConnection()->insert('heartbeat_friendship')
  357. ->fields([
  358. 'uid' => $friendship->uid_target,
  359. 'uid_target' => $friendship->uid,
  360. 'created' => time(),
  361. 'status' => 1
  362. ]);
  363. if ($insertReverse->execute()) {
  364. if ($friendship->status < 1) {
  365. $updateFriendship = Database::getConnection()->update('heartbeat_friendship')
  366. ->fields(array(
  367. 'status' => 1,
  368. ))
  369. ->condition('uid', $friendship->uid)
  370. ->condition('uid_target', $friendship->uid_target);
  371. if (!$updateFriendship->execute()) {
  372. \Drupal::logger('Friendship update failed');
  373. }
  374. }
  375. } else {
  376. \Drupal::logger('Heartbeat')->debug('Unable to insert or update for User with ID %id', ['%id' => $friendship->uid]);
  377. }
  378. } else {
  379. //TODO figure out how to set friendship pending
  380. }
  381. }
  382. }
  383. /**
  384. * Implements hook_cron().
  385. */
  386. function heartbeat_update_type_weight() {
  387. //Iterate over the Heartbeat Types and ensure that the weight of bundle-specific types are lower than that of their
  388. //parent type. This will allow us to ensure Bundle specific types end up being published as opposed to
  389. //Types which represent all content types
  390. $heartbeatTypes = \Drupal::service('entity.query')->get('heartbeat_type')->condition('mainentity', 'node')->execute();
  391. if (count($heartbeatTypes) > 1) {
  392. foreach($heartbeatTypes as $heartbeatType) {
  393. $entity = \Drupal::service('entity_type.manager')->getStorage('heartbeat_type')->load($heartbeatType);
  394. if ($entity->getBundle() === null) {
  395. $entity->setWeight(99);
  396. $entity->save();
  397. } else {
  398. $entity->setWeight(0);
  399. $entity->save();
  400. }
  401. }
  402. }
  403. }
  404. /**
  405. * Implements hook_page_attachments_alter().
  406. */
  407. function heartbeat_page_attachments_alter(array &$attachments) {
  408. $jigganull = 'naul';
  409. $jiagganull = 'naul';
  410. $mattachments = $attachments;
  411. $attachments['#attached']['library'][] = 'heartbeat/heartbeat';
  412. }