heartbeat.module 16 KB

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