Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

3843 lines
124 KiB

  1. <?php
  2. /**
  3. * @file src/Model/Item.php
  4. */
  5. namespace Friendica\Model;
  6. use Friendica\Content\Text\BBCode;
  7. use Friendica\Content\Text\HTML;
  8. use Friendica\Core\Config;
  9. use Friendica\Core\Hook;
  10. use Friendica\Core\L10n;
  11. use Friendica\Core\Logger;
  12. use Friendica\Core\Protocol;
  13. use Friendica\Core\Renderer;
  14. use Friendica\Core\Session;
  15. use Friendica\Core\System;
  16. use Friendica\Core\Worker;
  17. use Friendica\Database\DBA;
  18. use Friendica\DI;
  19. use Friendica\Protocol\Activity;
  20. use Friendica\Protocol\ActivityPub;
  21. use Friendica\Protocol\Diaspora;
  22. use Friendica\Protocol\OStatus;
  23. use Friendica\Util\DateTimeFormat;
  24. use Friendica\Util\Map;
  25. use Friendica\Util\Network;
  26. use Friendica\Util\Security;
  27. use Friendica\Util\Strings;
  28. use Friendica\Util\XML;
  29. use Friendica\Worker\Delivery;
  30. use Text_LanguageDetect;
  31. class Item
  32. {
  33. // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
  34. const PT_ARTICLE = 0;
  35. const PT_NOTE = 1;
  36. const PT_PAGE = 2;
  37. const PT_IMAGE = 16;
  38. const PT_AUDIO = 17;
  39. const PT_VIDEO = 18;
  40. const PT_DOCUMENT = 19;
  41. const PT_EVENT = 32;
  42. const PT_PERSONAL_NOTE = 128;
  43. // Field list that is used to display the items
  44. const DISPLAY_FIELDLIST = [
  45. 'uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network', 'gravity',
  46. 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
  47. 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach', 'language',
  48. 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
  49. 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
  50. 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
  51. 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
  52. 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
  53. 'writable', 'self', 'cid', 'alias', 'pinned',
  54. 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
  55. 'event-summary', 'event-desc', 'event-location', 'event-type',
  56. 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id',
  57. 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
  58. ];
  59. // Field list that is used to deliver items via the protocols
  60. const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid',
  61. 'parent-guid', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
  62. 'private', 'title', 'body', 'location', 'coord', 'app',
  63. 'attach', 'tag', 'deleted', 'extid', 'post-type',
  64. 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
  65. 'author-id', 'author-link', 'owner-link', 'contact-uid',
  66. 'signed_text', 'signature', 'signer', 'network'];
  67. // Field list for "item-content" table that is mixed with the item table
  68. const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
  69. 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
  70. 'object-type', 'object', 'target-type', 'target', 'plink'];
  71. // Field list for "item-content" table that is not present in the "item" table
  72. const CONTENT_FIELDLIST = ['language'];
  73. // All fields in the item table
  74. const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
  75. 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'iaid', 'psid',
  76. 'created', 'edited', 'commented', 'received', 'changed', 'verb',
  77. 'postopts', 'plink', 'resource-id', 'event-id', 'tag', 'attach', 'inform',
  78. 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
  79. 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
  80. 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
  81. 'title', 'content-warning', 'body', 'location', 'coord', 'app',
  82. 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
  83. 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
  84. 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
  85. // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
  86. // The item-activity table only stores the index and needs this array to know the matching activity.
  87. const ACTIVITIES = [
  88. Activity::LIKE, Activity::DISLIKE,
  89. Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
  90. Activity::FOLLOW,
  91. Activity::ANNOUNCE];
  92. private static $legacy_mode = null;
  93. public static function isLegacyMode()
  94. {
  95. if (is_null(self::$legacy_mode)) {
  96. self::$legacy_mode = (Config::get("system", "post_update_version") < 1279);
  97. }
  98. return self::$legacy_mode;
  99. }
  100. /**
  101. * Set the pinned state of an item
  102. *
  103. * @param integer $iid Item ID
  104. * @param integer $uid User ID
  105. * @param boolean $pinned Pinned state
  106. */
  107. public static function setPinned(int $iid, int $uid, bool $pinned)
  108. {
  109. DBA::update('user-item', ['pinned' => $pinned], ['iid' => $iid, 'uid' => $uid], true);
  110. }
  111. /**
  112. * Get the pinned state
  113. *
  114. * @param integer $iid Item ID
  115. * @param integer $uid User ID
  116. *
  117. * @return boolean pinned state
  118. */
  119. public static function getPinned(int $iid, int $uid)
  120. {
  121. $useritem = DBA::selectFirst('user-item', ['pinned'], ['iid' => $iid, 'uid' => $uid]);
  122. if (!DBA::isResult($useritem)) {
  123. return false;
  124. }
  125. return (bool)$useritem['pinned'];
  126. }
  127. /**
  128. * @brief Select pinned rows from the item table for a given user
  129. *
  130. * @param integer $uid User ID
  131. * @param array $selected Array of selected fields, empty for all
  132. * @param array $condition Array of fields for condition
  133. * @param array $params Array of several parameters
  134. *
  135. * @return boolean|object
  136. * @throws \Exception
  137. */
  138. public static function selectPinned(int $uid, array $selected = [], array $condition = [], $params = [])
  139. {
  140. $useritems = DBA::select('user-item', ['iid'], ['uid' => $uid, 'pinned' => true]);
  141. if (!DBA::isResult($useritems)) {
  142. return $useritems;
  143. }
  144. $pinned = [];
  145. while ($useritem = self::fetch($useritems)) {
  146. $pinned[] = $useritem['iid'];
  147. }
  148. DBA::close($useritems);
  149. if (empty($pinned)) {
  150. return [];
  151. }
  152. if (empty($condition) || !is_array($condition)) {
  153. $condition = ['iid' => $pinned];
  154. } else {
  155. reset($condition);
  156. $first_key = key($condition);
  157. if (!is_int($first_key)) {
  158. $condition['iid'] = $pinned;
  159. } else {
  160. $values_string = substr(str_repeat("?, ", count($pinned)), 0, -2);
  161. $condition[0] = '(' . $condition[0] . ") AND `iid` IN (" . $values_string . ")";
  162. $condition = array_merge($condition, $pinned);
  163. }
  164. }
  165. return self::selectThreadForUser($uid, $selected, $condition, $params);
  166. }
  167. /**
  168. * @brief returns an activity index from an activity string
  169. *
  170. * @param string $activity activity string
  171. * @return integer Activity index
  172. */
  173. public static function activityToIndex($activity)
  174. {
  175. $index = array_search($activity, self::ACTIVITIES);
  176. if (is_bool($index)) {
  177. $index = -1;
  178. }
  179. return $index;
  180. }
  181. /**
  182. * @brief returns an activity string from an activity index
  183. *
  184. * @param integer $index activity index
  185. * @return string Activity string
  186. */
  187. private static function indexToActivity($index)
  188. {
  189. if (is_null($index) || !array_key_exists($index, self::ACTIVITIES)) {
  190. return '';
  191. }
  192. return self::ACTIVITIES[$index];
  193. }
  194. /**
  195. * @brief Fetch a single item row
  196. *
  197. * @param mixed $stmt statement object
  198. * @return array current row
  199. */
  200. public static function fetch($stmt)
  201. {
  202. $row = DBA::fetch($stmt);
  203. if (is_bool($row)) {
  204. return $row;
  205. }
  206. // ---------------------- Transform item structure data ----------------------
  207. // We prefer the data from the user's contact over the public one
  208. if (!empty($row['author-link']) && !empty($row['contact-link']) &&
  209. ($row['author-link'] == $row['contact-link'])) {
  210. if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
  211. $row['author-avatar'] = $row['contact-avatar'];
  212. }
  213. if (isset($row['author-name']) && !empty($row['contact-name'])) {
  214. $row['author-name'] = $row['contact-name'];
  215. }
  216. }
  217. if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
  218. ($row['owner-link'] == $row['contact-link'])) {
  219. if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
  220. $row['owner-avatar'] = $row['contact-avatar'];
  221. }
  222. if (isset($row['owner-name']) && !empty($row['contact-name'])) {
  223. $row['owner-name'] = $row['contact-name'];
  224. }
  225. }
  226. // We can always comment on posts from these networks
  227. if (array_key_exists('writable', $row) &&
  228. in_array($row['internal-network'], Protocol::FEDERATED)) {
  229. $row['writable'] = true;
  230. }
  231. // ---------------------- Transform item content data ----------------------
  232. // Fetch data from the item-content table whenever there is content there
  233. if (self::isLegacyMode()) {
  234. $legacy_fields = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
  235. foreach ($legacy_fields as $field) {
  236. if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
  237. $row[$field] = $row['internal-item-' . $field];
  238. }
  239. unset($row['internal-item-' . $field]);
  240. }
  241. }
  242. if (!empty($row['internal-iaid']) && array_key_exists('verb', $row)) {
  243. $row['verb'] = self::indexToActivity($row['internal-activity']);
  244. if (array_key_exists('title', $row)) {
  245. $row['title'] = '';
  246. }
  247. if (array_key_exists('body', $row)) {
  248. $row['body'] = $row['verb'];
  249. }
  250. if (array_key_exists('object', $row)) {
  251. $row['object'] = '';
  252. }
  253. if (array_key_exists('object-type', $row)) {
  254. $row['object-type'] = Activity\ObjectType::NOTE;
  255. }
  256. } elseif (array_key_exists('verb', $row) && in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) {
  257. // Posts don't have a target - but having tags or files.
  258. // We safe some performance by building tag and file strings only here.
  259. // We remove the target since they aren't used for this type.
  260. // In mail posts we do store some mail header data in the object.
  261. if (array_key_exists('target', $row)) {
  262. $row['target'] = '';
  263. }
  264. }
  265. if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) {
  266. // Build the tag string out of the term entries
  267. if (array_key_exists('tag', $row) && empty($row['tag'])) {
  268. $row['tag'] = Term::tagTextFromItemId($row['internal-iid']);
  269. }
  270. // Build the file string out of the term entries
  271. if (array_key_exists('file', $row) && empty($row['file'])) {
  272. $row['file'] = Term::fileTextFromItemId($row['internal-iid']);
  273. }
  274. }
  275. if (array_key_exists('signed_text', $row) && array_key_exists('interaction', $row) && !is_null($row['interaction'])) {
  276. $row['signed_text'] = $row['interaction'];
  277. }
  278. if (array_key_exists('ignored', $row) && array_key_exists('internal-user-ignored', $row) && !is_null($row['internal-user-ignored'])) {
  279. $row['ignored'] = $row['internal-user-ignored'];
  280. }
  281. // Remove internal fields
  282. unset($row['internal-activity']);
  283. unset($row['internal-network']);
  284. unset($row['internal-iid']);
  285. unset($row['internal-iaid']);
  286. unset($row['internal-icid']);
  287. unset($row['internal-user-ignored']);
  288. unset($row['interaction']);
  289. return $row;
  290. }
  291. /**
  292. * @brief Fills an array with data from an item query
  293. *
  294. * @param object $stmt statement object
  295. * @param bool $do_close
  296. * @return array Data array
  297. */
  298. public static function inArray($stmt, $do_close = true) {
  299. if (is_bool($stmt)) {
  300. return $stmt;
  301. }
  302. $data = [];
  303. while ($row = self::fetch($stmt)) {
  304. $data[] = $row;
  305. }
  306. if ($do_close) {
  307. DBA::close($stmt);
  308. }
  309. return $data;
  310. }
  311. /**
  312. * @brief Check if item data exists
  313. *
  314. * @param array $condition array of fields for condition
  315. *
  316. * @return boolean Are there rows for that condition?
  317. * @throws \Exception
  318. */
  319. public static function exists($condition) {
  320. $stmt = self::select(['id'], $condition, ['limit' => 1]);
  321. if (is_bool($stmt)) {
  322. $retval = $stmt;
  323. } else {
  324. $retval = (DBA::numRows($stmt) > 0);
  325. }
  326. DBA::close($stmt);
  327. return $retval;
  328. }
  329. /**
  330. * Retrieve a single record from the item table for a given user and returns it in an associative array
  331. *
  332. * @brief Retrieve a single record from a table
  333. * @param integer $uid User ID
  334. * @param array $selected
  335. * @param array $condition
  336. * @param array $params
  337. * @return bool|array
  338. * @throws \Exception
  339. * @see DBA::select
  340. */
  341. public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
  342. {
  343. $params['uid'] = $uid;
  344. if (empty($selected)) {
  345. $selected = Item::DISPLAY_FIELDLIST;
  346. }
  347. return self::selectFirst($selected, $condition, $params);
  348. }
  349. /**
  350. * @brief Select rows from the item table for a given user
  351. *
  352. * @param integer $uid User ID
  353. * @param array $selected Array of selected fields, empty for all
  354. * @param array $condition Array of fields for condition
  355. * @param array $params Array of several parameters
  356. *
  357. * @return boolean|object
  358. * @throws \Exception
  359. */
  360. public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
  361. {
  362. $params['uid'] = $uid;
  363. if (empty($selected)) {
  364. $selected = Item::DISPLAY_FIELDLIST;
  365. }
  366. return self::select($selected, $condition, $params);
  367. }
  368. /**
  369. * Retrieve a single record from the item table and returns it in an associative array
  370. *
  371. * @brief Retrieve a single record from a table
  372. * @param array $fields
  373. * @param array $condition
  374. * @param array $params
  375. * @return bool|array
  376. * @throws \Exception
  377. * @see DBA::select
  378. */
  379. public static function selectFirst(array $fields = [], array $condition = [], $params = [])
  380. {
  381. $params['limit'] = 1;
  382. $result = self::select($fields, $condition, $params);
  383. if (is_bool($result)) {
  384. return $result;
  385. } else {
  386. $row = self::fetch($result);
  387. DBA::close($result);
  388. return $row;
  389. }
  390. }
  391. /**
  392. * @brief Select rows from the item table and returns them as an array
  393. *
  394. * @param array $selected Array of selected fields, empty for all
  395. * @param array $condition Array of fields for condition
  396. * @param array $params Array of several parameters
  397. *
  398. * @return array
  399. * @throws \Exception
  400. */
  401. public static function selectToArray(array $fields = [], array $condition = [], $params = [])
  402. {
  403. $result = self::select($fields, $condition, $params);
  404. if (is_bool($result)) {
  405. return [];
  406. }
  407. $data = [];
  408. while ($row = self::fetch($result)) {
  409. $data[] = $row;
  410. }
  411. DBA::close($result);
  412. return $data;
  413. }
  414. /**
  415. * @brief Select rows from the item table
  416. *
  417. * @param array $selected Array of selected fields, empty for all
  418. * @param array $condition Array of fields for condition
  419. * @param array $params Array of several parameters
  420. *
  421. * @return boolean|object
  422. * @throws \Exception
  423. */
  424. public static function select(array $selected = [], array $condition = [], $params = [])
  425. {
  426. $uid = 0;
  427. $usermode = false;
  428. if (isset($params['uid'])) {
  429. $uid = $params['uid'];
  430. $usermode = true;
  431. }
  432. $fields = self::fieldlist($usermode);
  433. $select_fields = self::constructSelectFields($fields, $selected);
  434. $condition_string = DBA::buildCondition($condition);
  435. $condition_string = self::addTablesToFields($condition_string, $fields);
  436. if ($usermode) {
  437. $condition_string = $condition_string . ' AND ' . self::condition(false);
  438. }
  439. $param_string = self::addTablesToFields(DBA::buildParameter($params), $fields);
  440. $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
  441. $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
  442. return DBA::p($sql, $condition);
  443. }
  444. /**
  445. * @brief Select rows from the starting post in the item table
  446. *
  447. * @param integer $uid User ID
  448. * @param array $selected
  449. * @param array $condition Array of fields for condition
  450. * @param array $params Array of several parameters
  451. *
  452. * @return boolean|object
  453. * @throws \Exception
  454. */
  455. public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
  456. {
  457. $params['uid'] = $uid;
  458. if (empty($selected)) {
  459. $selected = Item::DISPLAY_FIELDLIST;
  460. }
  461. return self::selectThread($selected, $condition, $params);
  462. }
  463. /**
  464. * Retrieve a single record from the starting post in the item table and returns it in an associative array
  465. *
  466. * @brief Retrieve a single record from a table
  467. * @param integer $uid User ID
  468. * @param array $selected
  469. * @param array $condition
  470. * @param array $params
  471. * @return bool|array
  472. * @throws \Exception
  473. * @see DBA::select
  474. */
  475. public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
  476. {
  477. $params['uid'] = $uid;
  478. if (empty($selected)) {
  479. $selected = Item::DISPLAY_FIELDLIST;
  480. }
  481. return self::selectFirstThread($selected, $condition, $params);
  482. }
  483. /**
  484. * Retrieve a single record from the starting post in the item table and returns it in an associative array
  485. *
  486. * @brief Retrieve a single record from a table
  487. * @param array $fields
  488. * @param array $condition
  489. * @param array $params
  490. * @return bool|array
  491. * @throws \Exception
  492. * @see DBA::select
  493. */
  494. public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
  495. {
  496. $params['limit'] = 1;
  497. $result = self::selectThread($fields, $condition, $params);
  498. if (is_bool($result)) {
  499. return $result;
  500. } else {
  501. $row = self::fetch($result);
  502. DBA::close($result);
  503. return $row;
  504. }
  505. }
  506. /**
  507. * @brief Select rows from the starting post in the item table
  508. *
  509. * @param array $selected Array of selected fields, empty for all
  510. * @param array $condition Array of fields for condition
  511. * @param array $params Array of several parameters
  512. *
  513. * @return boolean|object
  514. * @throws \Exception
  515. */
  516. public static function selectThread(array $selected = [], array $condition = [], $params = [])
  517. {
  518. $uid = 0;
  519. $usermode = false;
  520. if (isset($params['uid'])) {
  521. $uid = $params['uid'];
  522. $usermode = true;
  523. }
  524. $fields = self::fieldlist($usermode);
  525. $fields['thread'] = ['mention', 'ignored', 'iid'];
  526. $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
  527. 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
  528. 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
  529. 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
  530. $select_fields = self::constructSelectFields($fields, $selected);
  531. $condition_string = DBA::buildCondition($condition);
  532. $condition_string = self::addTablesToFields($condition_string, $threadfields);
  533. $condition_string = self::addTablesToFields($condition_string, $fields);
  534. if ($usermode) {
  535. $condition_string = $condition_string . ' AND ' . self::condition(true);
  536. }
  537. $param_string = DBA::buildParameter($params);
  538. $param_string = self::addTablesToFields($param_string, $threadfields);
  539. $param_string = self::addTablesToFields($param_string, $fields);
  540. $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
  541. $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
  542. return DBA::p($sql, $condition);
  543. }
  544. /**
  545. * @brief Returns a list of fields that are associated with the item table
  546. *
  547. * @param $usermode
  548. * @return array field list
  549. */
  550. private static function fieldlist($usermode)
  551. {
  552. $fields = [];
  553. $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
  554. 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
  555. 'created', 'edited', 'commented', 'received', 'changed', 'psid',
  556. 'resource-id', 'event-id', 'tag', 'attach', 'post-type', 'file',
  557. 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
  558. 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
  559. 'id' => 'item_id', 'network', 'icid', 'iaid', 'id' => 'internal-iid',
  560. 'network' => 'internal-network', 'icid' => 'internal-icid',
  561. 'iaid' => 'internal-iaid'];
  562. if ($usermode) {
  563. $fields['user-item'] = ['pinned', 'notification-type', 'ignored' => 'internal-user-ignored'];
  564. }
  565. $fields['item-activity'] = ['activity', 'activity' => 'internal-activity'];
  566. $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
  567. $fields['item-delivery-data'] = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, ItemDeliveryData::FIELD_LIST);
  568. $fields['permissionset'] = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
  569. $fields['author'] = ['url' => 'author-link', 'name' => 'author-name', 'addr' => 'author-addr',
  570. 'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
  571. $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name', 'addr' => 'owner-addr',
  572. 'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
  573. $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
  574. 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
  575. 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
  576. $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network'];
  577. $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name'];
  578. $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
  579. 'start' => 'event-start','finish' => 'event-finish',
  580. 'summary' => 'event-summary','desc' => 'event-desc',
  581. 'location' => 'event-location', 'type' => 'event-type',
  582. 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
  583. 'ignore' => 'event-ignore', 'id' => 'event-id'];
  584. $fields['sign'] = ['signed_text', 'signature', 'signer'];
  585. $fields['diaspora-interaction'] = ['interaction'];
  586. return $fields;
  587. }
  588. /**
  589. * @brief Returns SQL condition for the "select" functions
  590. *
  591. * @param boolean $thread_mode Called for the items (false) or for the threads (true)
  592. *
  593. * @return string SQL condition
  594. */
  595. private static function condition($thread_mode)
  596. {
  597. if ($thread_mode) {
  598. $master_table = "`thread`";
  599. } else {
  600. $master_table = "`item`";
  601. }
  602. return sprintf("$master_table.`visible` AND NOT $master_table.`deleted` AND NOT $master_table.`moderated`
  603. AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
  604. AND (`user-author`.`blocked` IS NULL OR NOT `user-author`.`blocked`)
  605. AND (`user-author`.`ignored` IS NULL OR NOT `user-author`.`ignored` OR `item`.`gravity` != %d)
  606. AND (`user-owner`.`blocked` IS NULL OR NOT `user-owner`.`blocked`)
  607. AND (`user-owner`.`ignored` IS NULL OR NOT `user-owner`.`ignored` OR `item`.`gravity` != %d) ",
  608. GRAVITY_PARENT, GRAVITY_PARENT);
  609. }
  610. /**
  611. * @brief Returns all needed "JOIN" commands for the "select" functions
  612. *
  613. * @param integer $uid User ID
  614. * @param string $sql_commands The parts of the built SQL commands in the "select" functions
  615. * @param boolean $thread_mode Called for the items (false) or for the threads (true)
  616. *
  617. * @param $user_mode
  618. * @return string The SQL joins for the "select" functions
  619. */
  620. private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
  621. {
  622. if ($thread_mode) {
  623. $master_table = "`thread`";
  624. $master_table_key = "`thread`.`iid`";
  625. $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
  626. } else {
  627. $master_table = "`item`";
  628. $master_table_key = "`item`.`id`";
  629. $joins = '';
  630. }
  631. if ($user_mode) {
  632. $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
  633. AND NOT `contact`.`blocked`
  634. AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
  635. OR `contact`.`self` OR `item`.`gravity` != %d OR `contact`.`uid` = 0)
  636. STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
  637. STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
  638. LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d
  639. LEFT JOIN `user-contact` AS `user-author` ON `user-author`.`cid` = $master_table.`author-id` AND `user-author`.`uid` = %d
  640. LEFT JOIN `user-contact` AS `user-owner` ON `user-owner`.`cid` = $master_table.`owner-id` AND `user-owner`.`uid` = %d",
  641. Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, intval($uid), intval($uid), intval($uid));
  642. } else {
  643. if (strpos($sql_commands, "`contact`.") !== false) {
  644. $joins .= "LEFT JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
  645. }
  646. if (strpos($sql_commands, "`author`.") !== false) {
  647. $joins .= " LEFT JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
  648. }
  649. if (strpos($sql_commands, "`owner`.") !== false) {
  650. $joins .= " LEFT JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
  651. }
  652. }
  653. if (strpos($sql_commands, "`group_member`.") !== false) {
  654. $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
  655. }
  656. if (strpos($sql_commands, "`user`.") !== false) {
  657. $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
  658. }
  659. if (strpos($sql_commands, "`event`.") !== false) {
  660. $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
  661. }
  662. if (strpos($sql_commands, "`sign`.") !== false) {
  663. $joins .= " LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`";
  664. }
  665. if (strpos($sql_commands, "`diaspora-interaction`.") !== false) {
  666. $joins .= " LEFT JOIN `diaspora-interaction` ON `diaspora-interaction`.`uri-id` = `item`.`uri-id`";
  667. }
  668. if (strpos($sql_commands, "`item-activity`.") !== false) {
  669. $joins .= " LEFT JOIN `item-activity` ON `item-activity`.`uri-id` = `item`.`uri-id`";
  670. }
  671. if (strpos($sql_commands, "`item-content`.") !== false) {
  672. $joins .= " LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`";
  673. }
  674. if (strpos($sql_commands, "`item-delivery-data`.") !== false) {
  675. $joins .= " LEFT JOIN `item-delivery-data` ON `item-delivery-data`.`iid` = `item`.`id`";
  676. }
  677. if (strpos($sql_commands, "`permissionset`.") !== false) {
  678. $joins .= " LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`";
  679. }
  680. if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
  681. $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
  682. }
  683. if (strpos($sql_commands, "`parent-item-author`.") !== false) {
  684. $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
  685. }
  686. return $joins;
  687. }
  688. /**
  689. * @brief Add the field list for the "select" functions
  690. *
  691. * @param array $fields The field definition array
  692. * @param array $selected The array with the selected fields from the "select" functions
  693. *
  694. * @return string The field list
  695. */
  696. private static function constructSelectFields($fields, $selected)
  697. {
  698. if (!empty($selected)) {
  699. $selected[] = 'internal-iid';
  700. $selected[] = 'internal-iaid';
  701. $selected[] = 'internal-icid';
  702. $selected[] = 'internal-network';
  703. }
  704. if (in_array('verb', $selected)) {
  705. $selected[] = 'internal-activity';
  706. }
  707. if (in_array('ignored', $selected)) {
  708. $selected[] = 'internal-user-ignored';
  709. }
  710. if (in_array('signed_text', $selected)) {
  711. $selected[] = 'interaction';
  712. }
  713. $legacy_fields = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
  714. $selection = [];
  715. foreach ($fields as $table => $table_fields) {
  716. foreach ($table_fields as $field => $select) {
  717. if (empty($selected) || in_array($select, $selected)) {
  718. if (self::isLegacyMode() && in_array($select, $legacy_fields)) {
  719. $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
  720. }
  721. if (is_int($field)) {
  722. $selection[] = "`" . $table . "`.`" . $select . "`";
  723. } else {
  724. $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
  725. }
  726. }
  727. }
  728. }
  729. return implode(", ", $selection);
  730. }
  731. /**
  732. * @brief add table definition to fields in an SQL query
  733. *
  734. * @param string $query SQL query
  735. * @param array $fields The field definition array
  736. *
  737. * @return string the changed SQL query
  738. */
  739. private static function addTablesToFields($query, $fields)
  740. {
  741. foreach ($fields as $table => $table_fields) {
  742. foreach ($table_fields as $alias => $field) {
  743. if (is_int($alias)) {
  744. $replace_field = $field;
  745. } else {
  746. $replace_field = $alias;
  747. }
  748. $search = "/([^\.])`" . $field . "`/i";
  749. $replace = "$1`" . $table . "`.`" . $replace_field . "`";
  750. $query = preg_replace($search, $replace, $query);
  751. }
  752. }
  753. return $query;
  754. }
  755. /**
  756. * @brief Update existing item entries
  757. *
  758. * @param array $fields The fields that are to be changed
  759. * @param array $condition The condition for finding the item entries
  760. *
  761. * In the future we may have to change permissions as well.
  762. * Then we had to add the user id as third parameter.
  763. *
  764. * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
  765. *
  766. * @return integer|boolean number of affected rows - or "false" if there was an error
  767. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  768. */
  769. public static function update(array $fields, array $condition)
  770. {
  771. if (empty($condition) || empty($fields)) {
  772. return false;
  773. }
  774. // To ensure the data integrity we do it in an transaction
  775. DBA::transaction();
  776. // We cannot simply expand the condition to check for origin entries
  777. // The condition needn't to be a simple array but could be a complex condition.
  778. // And we have to execute this query before the update to ensure to fetch the same data.
  779. $items = DBA::select('item', ['id', 'origin', 'uri', 'uri-id', 'iaid', 'icid', 'tag', 'file'], $condition);
  780. $content_fields = [];
  781. foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
  782. if (isset($fields[$field])) {
  783. $content_fields[$field] = $fields[$field];
  784. if (in_array($field, self::CONTENT_FIELDLIST) || !self::isLegacyMode()) {
  785. unset($fields[$field]);
  786. } else {
  787. $fields[$field] = null;
  788. }
  789. }
  790. }
  791. $delivery_data = ItemDeliveryData::extractFields($fields);
  792. $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'postopts', 'inform'];
  793. foreach ($clear_fields as $field) {
  794. if (array_key_exists($field, $fields)) {
  795. $fields[$field] = null;
  796. }
  797. }
  798. if (array_key_exists('tag', $fields)) {
  799. $tags = $fields['tag'];
  800. $fields['tag'] = null;
  801. } else {
  802. $tags = null;
  803. }
  804. if (array_key_exists('file', $fields)) {
  805. $files = $fields['file'];
  806. $fields['file'] = null;
  807. } else {
  808. $files = null;
  809. }
  810. if (!empty($fields)) {
  811. $success = DBA::update('item', $fields, $condition);
  812. if (!$success) {
  813. DBA::close($items);
  814. DBA::rollback();
  815. return false;
  816. }
  817. }
  818. // When there is no content for the "old" item table, this will count the fetched items
  819. $rows = DBA::affectedRows();
  820. $notify_items = [];
  821. while ($item = DBA::fetch($items)) {
  822. if (!empty($item['iaid']) || (!empty($content_fields['verb']) && (self::activityToIndex($content_fields['verb']) >= 0))) {
  823. self::updateActivity($content_fields, ['uri-id' => $item['uri-id']]);
  824. if (empty($item['iaid'])) {
  825. $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
  826. if (DBA::isResult($item_activity)) {
  827. $item_fields = ['iaid' => $item_activity['id'], 'icid' => null];
  828. foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
  829. if (self::isLegacyMode()) {
  830. $item_fields[$field] = null;
  831. } else {
  832. unset($item_fields[$field]);
  833. }
  834. }
  835. DBA::update('item', $item_fields, ['id' => $item['id']]);
  836. if (!empty($item['icid']) && !DBA::exists('item', ['icid' => $item['icid']])) {
  837. DBA::delete('item-content', ['id' => $item['icid']]);
  838. }
  839. }
  840. } elseif (!empty($item['icid'])) {
  841. DBA::update('item', ['icid' => null], ['id' => $item['id']]);
  842. if (!DBA::exists('item', ['icid' => $item['icid']])) {
  843. DBA::delete('item-content', ['id' => $item['icid']]);
  844. }
  845. }
  846. } else {
  847. self::updateContent($content_fields, ['uri-id' => $item['uri-id']]);
  848. if (empty($item['icid'])) {
  849. $item_content = DBA::selectFirst('item-content', [], ['uri-id' => $item['uri-id']]);
  850. if (DBA::isResult($item_content)) {
  851. $item_fields = ['icid' => $item_content['id']];
  852. // Clear all fields in the item table that have a content in the item-content table
  853. foreach ($item_content as $field => $content) {
  854. if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($item_content[$field])) {
  855. if (self::isLegacyMode()) {
  856. $item_fields[$field] = null;
  857. } else {
  858. unset($item_fields[$field]);
  859. }
  860. }
  861. }
  862. DBA::update('item', $item_fields, ['id' => $item['id']]);
  863. }
  864. }
  865. }
  866. if (!is_null($tags)) {
  867. Term::insertFromTagFieldByItemId($item['id'], $tags);
  868. if (!empty($item['tag'])) {
  869. DBA::update('item', ['tag' => ''], ['id' => $item['id']]);
  870. }
  871. }
  872. if (!is_null($files)) {
  873. Term::insertFromFileFieldByItemId($item['id'], $files);
  874. if (!empty($item['file'])) {
  875. DBA::update('item', ['file' => ''], ['id' => $item['id']]);
  876. }
  877. }
  878. ItemDeliveryData::update($item['id'], $delivery_data);
  879. self::updateThread($item['id']);
  880. // We only need to notfiy others when it is an original entry from us.
  881. // Only call the notifier when the item has some content relevant change.
  882. if ($item['origin'] && in_array('edited', array_keys($fields))) {
  883. $notify_items[] = $item['id'];
  884. }
  885. }
  886. DBA::close($items);
  887. DBA::commit();
  888. foreach ($notify_items as $notify_item) {
  889. Worker::add(PRIORITY_HIGH, "Notifier", Delivery::POST, $notify_item);
  890. }
  891. return $rows;
  892. }
  893. /**
  894. * @brief Delete an item and notify others about it - if it was ours
  895. *
  896. * @param array $condition The condition for finding the item entries
  897. * @param integer $priority Priority for the notification
  898. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  899. */
  900. public static function delete($condition, $priority = PRIORITY_HIGH)
  901. {
  902. $items = self::select(['id'], $condition);
  903. while ($item = self::fetch($items)) {
  904. self::deleteById($item['id'], $priority);
  905. }
  906. DBA::close($items);
  907. }
  908. /**
  909. * @brief Delete an item for an user and notify others about it - if it was ours
  910. *
  911. * @param array $condition The condition for finding the item entries
  912. * @param integer $uid User who wants to delete this item
  913. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  914. */
  915. public static function deleteForUser($condition, $uid)
  916. {
  917. if ($uid == 0) {
  918. return;
  919. }
  920. $items = self::select(['id', 'uid'], $condition);
  921. while ($item = self::fetch($items)) {
  922. // "Deleting" global items just means hiding them
  923. if ($item['uid'] == 0) {
  924. DBA::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
  925. // Delete notifications
  926. DBA::delete('notify', ['iid' => $item['id'], 'uid' => $uid]);
  927. } elseif ($item['uid'] == $uid) {
  928. self::deleteById($item['id'], PRIORITY_HIGH);
  929. } else {
  930. Logger::log('Wrong ownership. Not deleting item ' . $item['id']);
  931. }
  932. }
  933. DBA::close($items);
  934. }
  935. /**
  936. * @brief Delete an item and notify others about it - if it was ours
  937. *
  938. * @param integer $item_id Item ID that should be delete
  939. * @param integer $priority Priority for the notification
  940. *
  941. * @return boolean success
  942. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  943. */
  944. public static function deleteById($item_id, $priority = PRIORITY_HIGH)
  945. {
  946. // locate item to be deleted
  947. $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
  948. 'deleted', 'file', 'resource-id', 'event-id', 'attach',
  949. 'verb', 'object-type', 'object', 'target', 'contact-id',
  950. 'icid', 'iaid', 'psid'];
  951. $item = self::selectFirst($fields, ['id' => $item_id]);
  952. if (!DBA::isResult($item)) {
  953. Logger::log('Item with ID ' . $item_id . " hasn't been found.", Logger::DEBUG);
  954. return false;
  955. }
  956. if ($item['deleted']) {
  957. Logger::log('Item with ID ' . $item_id . ' has already been deleted.', Logger::DEBUG);
  958. return false;
  959. }
  960. $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
  961. if (!DBA::isResult($parent)) {
  962. $parent = ['origin' => false];
  963. }
  964. // clean up categories and tags so they don't end up as orphans
  965. $matches = false;
  966. $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
  967. if ($cnt) {
  968. foreach ($matches as $mtch) {
  969. FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],true);
  970. }
  971. }
  972. $matches = false;
  973. $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
  974. if ($cnt) {
  975. foreach ($matches as $mtch) {
  976. FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],false);
  977. }
  978. }
  979. /*
  980. * If item is a link to a photo resource, nuke all the associated photos
  981. * (visitors will not have photo resources)
  982. * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
  983. * generate a resource-id and therefore aren't intimately linked to the item.
  984. */
  985. /// @TODO: this should first check if photo is used elsewhere
  986. if (strlen($item['resource-id'])) {
  987. Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
  988. }
  989. // If item is a link to an event, delete the event.
  990. if (intval($item['event-id'])) {
  991. Event::delete($item['event-id']);
  992. }
  993. // If item has attachments, drop them
  994. /// @TODO: this should first check if attachment is used elsewhere
  995. foreach (explode(",", $item['attach']) as $attach) {
  996. preg_match("|attach/(\d+)|", $attach, $matches);
  997. if (is_array($matches) && count($matches) > 1) {
  998. Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
  999. }
  1000. }
  1001. // Delete tags that had been attached to other items
  1002. self::deleteTagsFromItem($item);
  1003. // Delete notifications
  1004. DBA::delete('notify', ['iid' => $item['id'], 'uid' => $item['uid']]);
  1005. // Set the item to "deleted"
  1006. $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
  1007. DBA::update('item', $item_fields, ['id' => $item['id']]);
  1008. Term::insertFromTagFieldByItemId($item['id'], '');
  1009. Term::insertFromFileFieldByItemId($item['id'], '');
  1010. self::deleteThread($item['id'], $item['parent-uri']);
  1011. if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
  1012. self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
  1013. }
  1014. ItemDeliveryData::delete($item['id']);
  1015. // We don't delete the item-activity here, since we need some of the data for ActivityPub
  1016. if (!empty($item['icid']) && !self::exists(['icid' => $item['icid'], 'deleted' => false])) {
  1017. DBA::delete('item-content', ['id' => $item['icid']], ['cascade' => false]);
  1018. }
  1019. // When the permission set will be used in photo and events as well,
  1020. // this query here needs to be extended.
  1021. // @todo Currently deactivated. We need the permission set in the deletion process.
  1022. // This is a reminder to add the removal somewhere else.
  1023. //if (!empty($item['psid']) && !self::exists(['psid' => $item['psid'], 'deleted' => false])) {
  1024. // DBA::delete('permissionset', ['id' => $item['psid']], ['cascade' => false]);
  1025. //}
  1026. // If it's the parent of a comment thread, kill all the kids
  1027. if ($item['id'] == $item['parent']) {
  1028. self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
  1029. }
  1030. // Is it our comment and/or our thread?
  1031. if ($item['origin'] || $parent['origin']) {
  1032. // When we delete the original post we will delete all existing copies on the server as well
  1033. self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
  1034. // send the notification upstream/downstream
  1035. Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", Delivery::DELETION, intval($item['id']));
  1036. } elseif ($item['uid'] != 0) {
  1037. // When we delete just our local user copy of an item, we have to set a marker to hide it
  1038. $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
  1039. if (DBA::isResult($global_item)) {
  1040. DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
  1041. }
  1042. }
  1043. Logger::log('Item with ID ' . $item_id . " has been deleted.", Logger::DEBUG);
  1044. return true;
  1045. }
  1046. private static function deleteTagsFromItem($item)
  1047. {
  1048. if (($item["verb"] != Activity::TAG) || ($item["object-type"] != Activity\ObjectType::TAGTERM)) {
  1049. return;
  1050. }
  1051. $xo = XML::parseString($item["object"], false);
  1052. $xt = XML::parseString($item["target"], false);
  1053. if ($xt->type != Activity\ObjectType::NOTE) {
  1054. return;
  1055. }
  1056. $i = self::selectFirst(['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
  1057. if (!DBA::isResult($i)) {
  1058. return;
  1059. }
  1060. // For tags, the owner cannot remove the tag on the author's copy of the post.
  1061. $owner_remove = ($item["contact-id"] == $i["contact-id"]);
  1062. $author_copy = $item["origin"];
  1063. if (($owner_remove && $author_copy) || !$owner_remove) {
  1064. return;
  1065. }
  1066. $tags = explode(',', $i["tag"]);
  1067. $newtags = [];
  1068. if (count($tags)) {
  1069. foreach ($tags as $tag) {
  1070. if (trim($tag) !== trim($xo->body)) {
  1071. $newtags[] = trim($tag);
  1072. }
  1073. }
  1074. }
  1075. self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
  1076. }
  1077. private static function guid($item, $notify)
  1078. {
  1079. if (!empty($item['guid'])) {
  1080. return Strings::escapeTags(trim($item['guid']));
  1081. }
  1082. if ($notify) {
  1083. // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
  1084. // We add the hash of our own host because our host is the original creator of the post.
  1085. $prefix_host = DI::baseUrl()->getHostname();
  1086. } else {
  1087. $prefix_host = '';
  1088. // We are only storing the post so we create a GUID from the original hostname.
  1089. if (!empty($item['author-link'])) {
  1090. $parsed = parse_url($item['author-link']);
  1091. if (!empty($parsed['host'])) {
  1092. $prefix_host = $parsed['host'];
  1093. }
  1094. }
  1095. if (empty($prefix_host) && !empty($item['plink'])) {
  1096. $parsed = parse_url($item['plink']);
  1097. if (!empty($parsed['host'])) {
  1098. $prefix_host = $parsed['host'];
  1099. }
  1100. }
  1101. if (empty($prefix_host) && !empty($item['uri'])) {
  1102. $parsed = parse_url($item['uri']);
  1103. if (!empty($parsed['host'])) {
  1104. $prefix_host = $parsed['host'];
  1105. }
  1106. }
  1107. // Is it in the format data@host.tld? - Used for mail contacts
  1108. if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
  1109. $mailparts = explode('@', $item['author-link']);
  1110. $prefix_host = array_pop($mailparts);
  1111. }
  1112. }
  1113. if (!empty($item['plink'])) {
  1114. $guid = self::guidFromUri($item['plink'], $prefix_host);
  1115. } elseif (!empty($item['uri'])) {
  1116. $guid = self::guidFromUri($item['uri'], $prefix_host);
  1117. } else {
  1118. $guid = System::createUUID(hash('crc32', $prefix_host));
  1119. }
  1120. return $guid;
  1121. }
  1122. private static function contactId($item)
  1123. {
  1124. if (!empty($item['contact-id']) && DBA::exists('contact', ['self' => true, 'id' => $item['contact-id']])) {
  1125. return $item['contact-id'];
  1126. } elseif (($item['gravity'] == GRAVITY_PARENT) && !empty($item['uid']) && !empty($item['contact-id']) && Contact::isSharing($item['contact-id'], $item['uid'])) {
  1127. return $item['contact-id'];
  1128. } elseif (!empty($item['uid']) && !Contact::isSharing($item['author-id'], $item['uid'])) {
  1129. return $item['author-id'];
  1130. } elseif (!empty($item['contact-id'])) {
  1131. return $item['contact-id'];
  1132. } else {
  1133. $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
  1134. if (!empty($contact_id)) {
  1135. return $contact_id;
  1136. }
  1137. }
  1138. return $item['author-id'];
  1139. }
  1140. // This function will finally cover most of the preparation functionality in mod/item.php
  1141. public static function prepare(&$item)
  1142. {
  1143. /*
  1144. * @TODO: Unused code triggering inspection errors
  1145. *
  1146. $data = BBCode::getAttachmentData($item['body']);
  1147. if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
  1148. && ($posttype != Item::PT_PERSONAL_NOTE)) {
  1149. $posttype = Item::PT_PAGE;
  1150. $objecttype = ACTIVITY_OBJ_BOOKMARK;
  1151. }
  1152. */
  1153. }
  1154. /**
  1155. * Write an item array into a spool file to be inserted later.
  1156. * This command is called whenever there are issues storing an item.
  1157. *
  1158. * @param array $item The item fields that are to be inserted
  1159. * @throws \Exception
  1160. */
  1161. private static function spool($orig_item)
  1162. {
  1163. // Now we store the data in the spool directory
  1164. // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
  1165. $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
  1166. $spoolpath = get_spoolpath();
  1167. if ($spoolpath != "") {
  1168. $spool = $spoolpath . '/' . $file;
  1169. file_put_contents($spool, json_encode($orig_item));
  1170. Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
  1171. }
  1172. }
  1173. public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
  1174. {
  1175. $orig_item = $item;
  1176. $priority = PRIORITY_HIGH;
  1177. // If it is a posting where users should get notifications, then define it as wall posting
  1178. if ($notify) {
  1179. $item['wall'] = 1;
  1180. $item['origin'] = 1;
  1181. $item['network'] = Protocol::DFRN;
  1182. $item['protocol'] = Conversation::PARCEL_DFRN;
  1183. if (is_int($notify)) {
  1184. $priority = $notify;
  1185. }
  1186. } else {
  1187. $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
  1188. }
  1189. $item['guid'] = self::guid($item, $notify);
  1190. $item['uri'] = Strings::escapeTags(trim(($item['uri'] ?? '') ?: self::newURI($item['uid'], $item['guid'])));
  1191. // Store URI data
  1192. $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
  1193. // Store conversation data
  1194. $item = Conversation::insert($item);
  1195. /*
  1196. * If a Diaspora signature structure was passed in, pull it out of the
  1197. * item array and set it aside for later storage.
  1198. */
  1199. $dsprsig = null;
  1200. if (isset($item['dsprsig'])) {
  1201. $encoded_signature = $item['dsprsig'];
  1202. $dsprsig = json_decode(base64_decode($item['dsprsig']));
  1203. unset($item['dsprsig']);
  1204. }
  1205. $diaspora_signed_text = '';
  1206. if (isset($item['diaspora_signed_text'])) {
  1207. $diaspora_signed_text = $item['diaspora_signed_text'];
  1208. unset($item['diaspora_signed_text']);
  1209. }
  1210. // Converting the plink
  1211. /// @TODO Check if this is really still needed
  1212. if ($item['network'] == Protocol::OSTATUS) {
  1213. if (isset($item['plink'])) {
  1214. $item['plink'] = OStatus::convertHref($item['plink']);
  1215. } elseif (isset($item['uri'])) {
  1216. $item['plink'] = OStatus::convertHref($item['uri']);
  1217. }
  1218. }
  1219. if (!empty($item['thr-parent'])) {
  1220. $item['parent-uri'] = $item['thr-parent'];
  1221. }
  1222. $activity = DI::activity();
  1223. if (isset($item['gravity'])) {
  1224. $item['gravity'] = intval($item['gravity']);
  1225. } elseif ($item['parent-uri'] === $item['uri']) {
  1226. $item['gravity'] = GRAVITY_PARENT;
  1227. } elseif ($activity->match($item['verb'], Activity::POST)) {
  1228. $item['gravity'] = GRAVITY_COMMENT;
  1229. } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
  1230. $item['gravity'] = GRAVITY_ACTIVITY;
  1231. } else {
  1232. $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
  1233. Logger::log('Unknown gravity for verb: ' . $item['verb'], Logger::DEBUG);
  1234. }
  1235. $uid = intval($item['uid']);
  1236. // check for create date and expire time
  1237. $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
  1238. $user = DBA::selectFirst('user', ['expire'], ['uid' => $uid]);
  1239. if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
  1240. $expire_interval = $user['expire'];
  1241. }
  1242. if (($expire_interval > 0) && !empty($item['created'])) {
  1243. $expire_date = time() - ($expire_interval * 86400);
  1244. $created_date = strtotime($item['created']);
  1245. if ($created_date < $expire_date) {
  1246. Logger::notice('Item created before expiration interval.', [
  1247. 'created' => date('c', $created_date),
  1248. 'expired' => date('c', $expire_date),
  1249. '$item' => $item
  1250. ]);
  1251. return 0;
  1252. }
  1253. }
  1254. /*
  1255. * Do we already have this item?
  1256. * We have to check several networks since Friendica posts could be repeated
  1257. * via OStatus (maybe Diasporsa as well)
  1258. */
  1259. if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
  1260. $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
  1261. trim($item['uri']), $item['uid'],
  1262. Protocol::ACTIVITYPUB, Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS];
  1263. $existing = self::selectFirst(['id', 'network'], $condition);
  1264. if (DBA::isResult($existing)) {
  1265. // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
  1266. if ($uid != 0) {
  1267. Logger::notice('Item already existed for user', [
  1268. 'uri' => $item['uri'],
  1269. 'uid' => $uid,
  1270. 'network' => $item['network'],
  1271. 'existing_id' => $existing["id"],
  1272. 'existing_network' => $existing["network"]
  1273. ]);
  1274. }
  1275. return $existing["id"];
  1276. }
  1277. }
  1278. $item['wall'] = intval($item['wall'] ?? 0);
  1279. $item['extid'] = trim($item['extid'] ?? '');
  1280. $item['author-name'] = trim($item['author-name'] ?? '');
  1281. $item['author-link'] = trim($item['author-link'] ?? '');
  1282. $item['author-avatar'] = trim($item['author-avatar'] ?? '');
  1283. $item['owner-name'] = trim($item['owner-name'] ?? '');
  1284. $item['owner-link'] = trim($item['owner-link'] ?? '');
  1285. $item['owner-avatar'] = trim($item['owner-avatar'] ?? '');
  1286. $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
  1287. $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
  1288. $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
  1289. $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
  1290. $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
  1291. $item['title'] = trim($item['title'] ?? '');
  1292. $item['location'] = trim($item['location'] ?? '');
  1293. $item['coord'] = trim($item['coord'] ?? '');
  1294. $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
  1295. $item['deleted'] = 0;
  1296. $item['parent-uri'] = trim(($item['parent-uri'] ?? '') ?: $item['uri']);
  1297. $item['post-type'] = ($item['post-type'] ?? '') ?: self::PT_ARTICLE;
  1298. $item['verb'] = trim($item['verb'] ?? '');
  1299. $item['object-type'] = trim($item['object-type'] ?? '');
  1300. $item['object'] = trim($item['object'] ?? '');
  1301. $item['target-type'] = trim($item['target-type'] ?? '');
  1302. $item['target'] = trim($item['target'] ?? '');
  1303. $item['plink'] = trim($item['plink'] ?? '');
  1304. $item['allow_cid'] = trim($item['allow_cid'] ?? '');
  1305. $item['allow_gid'] = trim($item['allow_gid'] ?? '');
  1306. $item['deny_cid'] = trim($item['deny_cid'] ?? '');
  1307. $item['deny_gid'] = trim($item['deny_gid'] ?? '');
  1308. $item['private'] = intval($item['private'] ?? 0);
  1309. $item['body'] = trim($item['body'] ?? '');
  1310. $item['tag'] = trim($item['tag'] ?? '');
  1311. $item['attach'] = trim($item['attach'] ?? '');
  1312. $item['app'] = trim($item['app'] ?? '');
  1313. $item['origin'] = intval($item['origin'] ?? 0);
  1314. $item['postopts'] = trim($item['postopts'] ?? '');
  1315. $item['resource-id'] = trim($item['resource-id'] ?? '');
  1316. $item['event-id'] = intval($item['event-id'] ?? 0);
  1317. $item['inform'] = trim($item['inform'] ?? '');
  1318. $item['file'] = trim($item['file'] ?? '');
  1319. // When there is no content then we don't post it
  1320. if ($item['body'].$item['title'] == '') {
  1321. Logger::notice('No body, no title.');
  1322. return 0;
  1323. }
  1324. self::addLanguageToItemArray($item);
  1325. // Items cannot be stored before they happen ...
  1326. if ($item['created'] > DateTimeFormat::utcNow()) {
  1327. $item['created'] = DateTimeFormat::utcNow();
  1328. }
  1329. // We haven't invented time travel by now.
  1330. if ($item['edited'] > DateTimeFormat::utcNow()) {
  1331. $item['edited'] = DateTimeFormat::utcNow();
  1332. }
  1333. $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
  1334. $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
  1335. 'photo' => $item['author-avatar'], 'network' => $item['network']];
  1336. $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, false, $default);
  1337. if (Contact::isBlocked($item['author-id'])) {
  1338. Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
  1339. return 0;
  1340. }
  1341. if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
  1342. Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
  1343. return 0;
  1344. }
  1345. if (!empty($uid) && Contact::isBlockedByUser($item['author-id'], $uid)) {
  1346. Logger::notice('Author is blocked by user', ['author-link' => $item['author-link'], 'uid' => $uid, 'item-uri' => $item['uri']]);
  1347. return 0;
  1348. }
  1349. $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
  1350. 'photo' => $item['owner-avatar'], 'network' => $item['network']];
  1351. $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, false, $default);
  1352. if (Contact::isBlocked($item['owner-id'])) {
  1353. Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
  1354. return 0;
  1355. }
  1356. if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
  1357. Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
  1358. return 0;
  1359. }
  1360. if (!empty($uid) && Contact::isBlockedByUser($item['owner-id'], $uid)) {
  1361. Logger::notice('Owner is blocked by user', ['owner-link' => $item['owner-link'], 'uid' => $uid, 'item-uri' => $item['uri']]);
  1362. return 0;
  1363. }
  1364. // The causer is set during a thread completion, for example because of a reshare. It countains the responsible actor.
  1365. if (!empty($uid) && !empty($item['causer-id']) && Contact::isBlockedByUser($item['causer-id'], $uid)) {
  1366. Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'], 'uid' => $uid, 'item-uri' => $item['uri']]);
  1367. return 0;
  1368. }
  1369. if (!empty($uid) && !empty($item['causer-id']) && ($item['parent-uri'] == $item['uri']) && Contact::isIgnoredByUser($item['causer-id'], $uid)) {
  1370. Logger::notice('Causer is ignored by user', ['causer-link' => $item['causer-link'], 'uid' => $uid, 'item-uri' => $item['uri']]);
  1371. return 0;
  1372. }
  1373. // We don't store the causer, we only have it here for the checks above
  1374. unset($item['causer-id']);
  1375. unset($item['causer-link']);
  1376. // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
  1377. $item["contact-id"] = self::contactId($item);
  1378. if ($item['network'] == Protocol::PHANTOM) {
  1379. $item['network'] = Protocol::DFRN;
  1380. Logger::notice('Missing network, setting to {network}.', [
  1381. 'uri' => $item["uri"],
  1382. 'network' => $item['network'],
  1383. 'callstack' => System::callstack()
  1384. ]);
  1385. }
  1386. // Checking if there is already an item with the same guid
  1387. $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
  1388. if (self::exists($condition)) {
  1389. Logger::notice('Found already existing item', [
  1390. 'guid' => $item['guid'],
  1391. 'uid' => $item['uid'],
  1392. 'network' => $item['network']
  1393. ]);
  1394. return 0;
  1395. }
  1396. if ($item['verb'] == Activity::FOLLOW) {
  1397. if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($uid))) {
  1398. // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
  1399. Logger::log("Follow: Don't store not origin follow request from us for " . $item['parent-uri'], Logger::DEBUG);
  1400. return 0;
  1401. }
  1402. $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
  1403. 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
  1404. if (self::exists($condition)) {
  1405. // It happens that we receive multiple follow requests by the same author - we only store one.
  1406. Logger::log('Follow: Found existing follow request from author ' . $item['author-id'] . ' for ' . $item['parent-uri'], Logger::DEBUG);
  1407. return 0;
  1408. }
  1409. }
  1410. // Check for hashtags in the body and repair or add hashtag links
  1411. self::setHashtags($item);
  1412. $item['thr-parent'] = $item['parent-uri'];
  1413. $notify_type = Delivery::POST;
  1414. $allow_cid = '';
  1415. $allow_gid = '';
  1416. $deny_cid = '';
  1417. $deny_gid = '';
  1418. if ($item['parent-uri'] === $item['uri']) {
  1419. $parent_id = 0;
  1420. $parent_deleted = 0;
  1421. $allow_cid = $item['allow_cid'];
  1422. $allow_gid = $item['allow_gid'];
  1423. $deny_cid = $item['deny_cid'];
  1424. $deny_gid = $item['deny_gid'];
  1425. } else {
  1426. // find the parent and snarf the item id and ACLs
  1427. // and anything else we need to inherit
  1428. $fields = ['uri', 'parent-uri', 'id', 'deleted',
  1429. 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
  1430. 'wall', 'private', 'forum_mode', 'origin'];
  1431. $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
  1432. $params = ['order' => ['id' => false]];
  1433. $parent = self::selectFirst($fields, $condition, $params);
  1434. if (DBA::isResult($parent)) {
  1435. // is the new message multi-level threaded?
  1436. // even though we don't support it now, preserve the info
  1437. // and re-attach to the conversation parent.
  1438. if ($parent['uri'] != $parent['parent-uri']) {
  1439. $item['parent-uri'] = $parent['parent-uri'];
  1440. $condition = ['uri' => $item['parent-uri'],
  1441. 'parent-uri' => $item['parent-uri'],
  1442. 'uid' => $item['uid']];
  1443. $params = ['order' => ['id' => false]];
  1444. $toplevel_parent = self::selectFirst($fields, $condition, $params);
  1445. if (DBA::isResult($toplevel_parent)) {
  1446. $parent = $toplevel_parent;
  1447. }
  1448. }
  1449. $parent_id = $parent['id'];
  1450. $parent_deleted = $parent['deleted'];
  1451. $allow_cid = $parent['allow_cid'];
  1452. $allow_gid = $parent['allow_gid'];
  1453. $deny_cid = $parent['deny_cid'];
  1454. $deny_gid = $parent['deny_gid'];
  1455. $item['wall'] = $parent['wall'];
  1456. /*
  1457. * If the parent is private, force privacy for the entire conversation
  1458. * This differs from the above settings as it subtly allows comments from
  1459. * email correspondents to be private even if the overall thread is not.
  1460. */
  1461. if ($parent['private']) {
  1462. $item['private'] = $parent['private'];
  1463. }
  1464. /*
  1465. * Edge case. We host a public forum that was originally posted to privately.
  1466. * The original author commented, but as this is a comment, the permissions
  1467. * weren't fixed up so it will still show the comment as private unless we fix it here.
  1468. */
  1469. if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
  1470. $item['private'] = 0;
  1471. }
  1472. // If its a post that originated here then tag the thread as "mention"
  1473. if ($item['origin'] && $item['uid']) {
  1474. DBA::update('thread', ['mention' => true], ['iid' => $parent_id]);
  1475. Logger::log('tagged thread ' . $parent_id . ' as mention for user ' . $item['uid'], Logger::DEBUG);
  1476. }
  1477. } else {
  1478. /*
  1479. * Allow one to see reply tweets from status.net even when
  1480. * we don't have or can't see the original post.
  1481. */
  1482. if ($force_parent) {
  1483. Logger::log('$force_parent=true, reply converted to top-level post.');
  1484. $parent_id = 0;
  1485. $item['parent-uri'] = $item['uri'];
  1486. $item['gravity'] = GRAVITY_PARENT;
  1487. } else {
  1488. Logger::log('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
  1489. return 0;
  1490. }
  1491. $parent_deleted = 0;
  1492. }
  1493. }
  1494. if (stristr($item['verb'], Activity::POKE)) {
  1495. $notify_type = Delivery::POKE;
  1496. }
  1497. $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
  1498. $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
  1499. $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
  1500. $item['uri'], $item['network'], Protocol::DFRN, $item['uid']];
  1501. if (self::exists($condition)) {
  1502. Logger::log('duplicated item with the same uri found. '.print_r($item,true));
  1503. return 0;
  1504. }
  1505. // On Friendica and Diaspora the GUID is unique
  1506. if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
  1507. $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
  1508. if (self::exists($condition)) {
  1509. Logger::log('duplicated item with the same guid found. '.print_r($item,true));
  1510. return 0;
  1511. }
  1512. } elseif ($item['network'] == Protocol::OSTATUS) {
  1513. // Check for an existing post with the same content. There seems to be a problem with OStatus.
  1514. $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
  1515. $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
  1516. if (self::exists($condition)) {
  1517. Logger::log('duplicated item with the same body found. '.print_r($item,true));
  1518. return 0;
  1519. }
  1520. }
  1521. // Is this item available in the global items (with uid=0)?
  1522. if ($item["uid"] == 0) {
  1523. $item["global"] = true;
  1524. // Set the global flag on all items if this was a global item entry
  1525. DBA::update('item', ['global' => true], ['uri' => $item["uri"]]);
  1526. } else {
  1527. $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
  1528. }
  1529. // ACL settings
  1530. if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
  1531. $private = 1;
  1532. } else {
  1533. $private = $item['private'];
  1534. }
  1535. $item["allow_cid"] = $allow_cid;
  1536. $item["allow_gid"] = $allow_gid;
  1537. $item["deny_cid"] = $deny_cid;
  1538. $item["deny_gid"] = $deny_gid;
  1539. $item["private"] = $private;
  1540. $item["deleted"] = $parent_deleted;
  1541. // Fill the cache field
  1542. self::putInCache($item);
  1543. if ($notify) {
  1544. $item['edit'] = false;
  1545. $item['parent'] = $parent_id;
  1546. Hook::callAll('post_local', $item);
  1547. unset($item['edit']);
  1548. unset($item['parent']);
  1549. } else {
  1550. Hook::callAll('post_remote', $item);
  1551. }
  1552. // This array field is used to trigger some automatic reactions
  1553. // It is mainly used in the "post_local" hook.
  1554. unset($item['api_source']);
  1555. if (!empty($item['cancel'])) {
  1556. Logger::log('post cancelled by addon.');
  1557. return 0;
  1558. }
  1559. /*
  1560. * Check for already added items.
  1561. * There is a timing issue here that sometimes creates double postings.
  1562. * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
  1563. */
  1564. if ($item["uid"] == 0) {
  1565. if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
  1566. Logger::log('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], Logger::DEBUG);
  1567. return 0;
  1568. }
  1569. }
  1570. Logger::log('' . print_r($item,true), Logger::DATA);
  1571. if (array_key_exists('tag', $item)) {
  1572. $tags = $item['tag'];
  1573. unset($item['tag']);
  1574. } else {
  1575. $tags = '';
  1576. }
  1577. if (array_key_exists('file', $item)) {
  1578. $files = $item['file'];
  1579. unset($item['file']);
  1580. } else {
  1581. $files = '';
  1582. }
  1583. // Creates or assigns the permission set
  1584. $item['psid'] = PermissionSet::fetchIDForPost($item);
  1585. // We are doing this outside of the transaction to avoid timing problems
  1586. if (!self::insertActivity($item)) {
  1587. self::insertContent($item);
  1588. }
  1589. $delivery_data = ItemDeliveryData::extractFields($item);
  1590. unset($item['postopts']);
  1591. unset($item['inform']);
  1592. // These fields aren't stored anymore in the item table, they are fetched upon request
  1593. unset($item['author-link']);
  1594. unset($item['author-name']);
  1595. unset($item['author-avatar']);
  1596. unset($item['author-network']);
  1597. unset($item['owner-link']);
  1598. unset($item['owner-name']);
  1599. unset($item['owner-avatar']);
  1600. $like_no_comment = Config::get('system', 'like_no_comment');
  1601. DBA::transaction();
  1602. $ret = DBA::insert('item', $item);
  1603. // When the item was successfully stored we fetch the ID of the item.
  1604. if (DBA::isResult($ret)) {
  1605. $current_post = DBA::lastInsertId();
  1606. } else {
  1607. // This can happen - for example - if there are locking timeouts.
  1608. DBA::rollback();
  1609. // Store the data into a spool file so that we can try again later.
  1610. self::spool($orig_item);
  1611. return 0;
  1612. }
  1613. if ($current_post == 0) {
  1614. // This is one of these error messages that never should occur.
  1615. Logger::log("couldn't find created item - we better quit now.");
  1616. DBA::rollback();
  1617. return 0;
  1618. }
  1619. // How much entries have we created?
  1620. // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
  1621. $entries = DBA::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
  1622. if ($entries > 1) {
  1623. // There are duplicates. We delete our just created entry.
  1624. Logger::log('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
  1625. // Yes, we could do a rollback here - but we are having many users with MyISAM.
  1626. DBA::delete('item', ['id' => $current_post]);
  1627. DBA::commit();
  1628. return 0;
  1629. } elseif ($entries == 0) {
  1630. // This really should never happen since we quit earlier if there were problems.
  1631. Logger::log("Something is terribly wrong. We haven't found our created entry.");
  1632. DBA::rollback();
  1633. return 0;
  1634. }
  1635. Logger::log('created item '.$current_post);
  1636. if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
  1637. $parent_id = $current_post;
  1638. }
  1639. // Set parent id
  1640. DBA::update('item', ['parent' => $parent_id], ['id' => $current_post]);
  1641. $item['id'] = $current_post;
  1642. $item['parent'] = $parent_id;
  1643. // update the commented timestamp on the parent
  1644. // Only update "commented" if it is really a comment
  1645. if (($item['gravity'] != GRAVITY_ACTIVITY) || !$like_no_comment) {
  1646. DBA::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
  1647. } else {
  1648. DBA::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
  1649. }
  1650. if ($dsprsig) {
  1651. /*
  1652. * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
  1653. * We can check for this condition when we decode and encode the stuff again.
  1654. */
  1655. if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
  1656. $dsprsig->signature = base64_decode($dsprsig->signature);
  1657. Logger::log("Repaired double encoded signature from handle ".$dsprsig->signer, Logger::DEBUG);
  1658. }
  1659. if (!empty($dsprsig->signed_text) && empty($dsprsig->signature) && empty($dsprsig->signer)) {
  1660. DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $dsprsig->signed_text], true);
  1661. } else {
  1662. // The other fields are used by very old Friendica servers, so we currently store them differently
  1663. DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
  1664. 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
  1665. }
  1666. }
  1667. if (!empty($diaspora_signed_text)) {
  1668. DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $diaspora_signed_text], true);
  1669. }
  1670. if ($item['parent-uri'] === $item['uri']) {
  1671. self::addThread($current_post);
  1672. } else {
  1673. self::updateThread($parent_id);
  1674. }
  1675. if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
  1676. ItemDeliveryData::insert($current_post, $delivery_data);
  1677. }
  1678. DBA::commit();
  1679. /*
  1680. * Due to deadlock issues with the "term" table we are doing these steps after the commit.
  1681. * This is not perfect - but a workable solution until we found the reason for the problem.
  1682. */
  1683. if (!empty($tags)) {
  1684. Term::insertFromTagFieldByItemId($current_post, $tags);
  1685. }
  1686. if (!empty($files)) {
  1687. Term::insertFromFileFieldByItemId($current_post, $files);
  1688. }
  1689. // In that function we check if this is a forum post. Additionally we delete the item under certain circumstances
  1690. if (self::tagDeliver($item['uid'], $current_post)) {
  1691. // Get the user information for the logging
  1692. $user = User::getById($uid);
  1693. Logger::notice('Item had been deleted', ['id' => $current_post, 'user' => $uid, 'account-type' => $user['account-type']]);
  1694. return 0;
  1695. }
  1696. if (!$dontcache) {
  1697. $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
  1698. if (DBA::isResult($posted_item)) {
  1699. if ($notify) {
  1700. Hook::callAll('post_local_end', $posted_item);
  1701. } else {
  1702. Hook::callAll('post_remote_end', $posted_item);
  1703. }
  1704. } else {
  1705. Logger::log('new item not found in DB, id ' . $current_post);
  1706. }
  1707. }
  1708. if ($item['parent-uri'] === $item['uri']) {
  1709. self::addShadow($current_post);
  1710. } else {
  1711. self::addShadowPost($current_post);
  1712. }
  1713. self::updateContact($item);
  1714. UserItem::setNotification($current_post);
  1715. check_user_notification($current_post);
  1716. if ($notify || ($item['visible'] && ((!empty($parent) && $parent['origin']) || $item['origin']))) {
  1717. Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, $current_post);
  1718. }
  1719. return $current_post;
  1720. }
  1721. /**
  1722. * @brief Insert a new item content entry
  1723. *
  1724. * @param array $item The item fields that are to be inserted
  1725. * @return bool
  1726. * @throws \Exception
  1727. */
  1728. private static function insertActivity(&$item)
  1729. {
  1730. $activity_index = self::activityToIndex($item['verb']);
  1731. if ($activity_index < 0) {
  1732. return false;
  1733. }
  1734. $fields = ['activity' => $activity_index, 'uri-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
  1735. // We just remove everything that is content
  1736. foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
  1737. unset($item[$field]);
  1738. }
  1739. // To avoid timing problems, we are using locks.
  1740. $locked = DI::lock()->acquire('item_insert_activity');
  1741. if (!$locked) {
  1742. Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
  1743. }
  1744. // Do we already have this content?
  1745. $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
  1746. if (DBA::isResult($item_activity)) {
  1747. $item['iaid'] = $item_activity['id'];
  1748. Logger::log('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
  1749. } elseif (DBA::insert('item-activity', $fields)) {
  1750. $item['iaid'] = DBA::lastInsertId();
  1751. Logger::log('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
  1752. } else {
  1753. // This shouldn't happen.
  1754. Logger::log('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
  1755. DI::lock()->release('item_insert_activity');
  1756. return false;
  1757. }
  1758. if ($locked) {
  1759. DI::lock()->release('item_insert_activity');
  1760. }
  1761. return true;
  1762. }
  1763. /**
  1764. * @brief Insert a new item content entry
  1765. *
  1766. * @param array $item The item fields that are to be inserted
  1767. * @throws \Exception
  1768. */
  1769. private static function insertContent(&$item)
  1770. {
  1771. $fields = ['uri-plink-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
  1772. foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
  1773. if (isset($item[$field])) {
  1774. $fields[$field] = $item[$field];
  1775. unset($item[$field]);
  1776. }
  1777. }
  1778. // To avoid timing problems, we are using locks.
  1779. $locked = DI::lock()->acquire('item_insert_content');
  1780. if (!$locked) {
  1781. Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
  1782. }
  1783. // Do we already have this content?
  1784. $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
  1785. if (DBA::isResult($item_content)) {
  1786. $item['icid'] = $item_content['id'];
  1787. Logger::log('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
  1788. } elseif (DBA::insert('item-content', $fields)) {
  1789. $item['icid'] = DBA::lastInsertId();
  1790. Logger::log('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
  1791. } else {
  1792. // This shouldn't happen.
  1793. Logger::log('Could not insert content for URI ' . $item['uri'] . ' - should not happen');
  1794. }
  1795. if ($locked) {
  1796. DI::lock()->release('item_insert_content');
  1797. }
  1798. }
  1799. /**
  1800. * @brief Update existing item content entries
  1801. *
  1802. * @param array $item The item fields that are to be changed
  1803. * @param array $condition The condition for finding the item content entries
  1804. * @return bool
  1805. * @throws \Exception
  1806. */
  1807. private static function updateActivity($item, $condition)
  1808. {
  1809. if (empty($item['verb'])) {
  1810. return false;
  1811. }
  1812. $activity_index = self::activityToIndex($item['verb']);
  1813. if ($activity_index < 0) {
  1814. return false;
  1815. }
  1816. $fields = ['activity' => $activity_index];
  1817. Logger::log('Update activity for ' . json_encode($condition));
  1818. DBA::update('item-activity', $fields, $condition, true);
  1819. return true;
  1820. }
  1821. /**
  1822. * @brief Update existing item content entries
  1823. *
  1824. * @param array $item The item fields that are to be changed
  1825. * @param array $condition The condition for finding the item content entries
  1826. * @throws \Exception
  1827. */
  1828. private static function updateContent($item, $condition)
  1829. {
  1830. // We have to select only the fields from the "item-content" table
  1831. $fields = [];
  1832. foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
  1833. if (isset($item[$field])) {
  1834. $fields[$field] = $item[$field];
  1835. }
  1836. }
  1837. if (empty($fields)) {
  1838. // when there are no fields at all, just use the condition
  1839. // This is to ensure that we always store content.
  1840. $fields = $condition;
  1841. }
  1842. Logger::log('Update content for ' . json_encode($condition));
  1843. DBA::update('item-content', $fields, $condition, true);
  1844. }
  1845. /**
  1846. * @brief Distributes public items to the receivers
  1847. *
  1848. * @param integer $itemid Item ID that should be added
  1849. * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
  1850. * @throws \Exception
  1851. */
  1852. public static function distribute($itemid, $signed_text = '')
  1853. {
  1854. $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
  1855. $parent = self::selectFirst(['owner-id'], $condition);
  1856. if (!DBA::isResult($parent)) {
  1857. return;
  1858. }
  1859. // Only distribute public items from native networks
  1860. $condition = ['id' => $itemid, 'uid' => 0,
  1861. 'network' => array_merge(Protocol::FEDERATED ,['']),
  1862. 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
  1863. $item = self::selectFirst(self::ITEM_FIELDLIST, $condition);
  1864. if (!DBA::isResult($item)) {
  1865. return;
  1866. }
  1867. $origin = $item['origin'];
  1868. unset($item['id']);
  1869. unset($item['parent']);
  1870. unset($item['mention']);
  1871. unset($item['wall']);
  1872. unset($item['origin']);
  1873. unset($item['starred']);
  1874. $users = [];
  1875. /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
  1876. $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
  1877. if (!DBA::isResult($owner)) {
  1878. return;
  1879. }
  1880. $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
  1881. $contacts = DBA::select('contact', ['uid'], $condition);
  1882. while ($contact = DBA::fetch($contacts)) {
  1883. if ($contact['uid'] == 0) {
  1884. continue;
  1885. }
  1886. $users[$contact['uid']] = $contact['uid'];
  1887. }
  1888. DBA::close($contacts);
  1889. $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
  1890. $contacts = DBA::select('contact', ['uid'], $condition);
  1891. while ($contact = DBA::fetch($contacts)) {
  1892. if ($contact['uid'] == 0) {
  1893. continue;
  1894. }
  1895. $users[$contact['uid']] = $contact['uid'];
  1896. }
  1897. DBA::close($contacts);
  1898. if (!empty($owner['alias'])) {
  1899. $condition = ['url' => $owner['alias'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
  1900. $contacts = DBA::select('contact', ['uid'], $condition);
  1901. while ($contact = DBA::fetch($contacts)) {
  1902. if ($contact['uid'] == 0) {
  1903. continue;
  1904. }
  1905. $users[$contact['uid']] = $contact['uid'];
  1906. }
  1907. DBA::close($contacts);
  1908. }
  1909. $origin_uid = 0;
  1910. if ($item['uri'] != $item['parent-uri']) {
  1911. $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
  1912. while ($parent = self::fetch($parents)) {
  1913. $users[$parent['uid']] = $parent['uid'];
  1914. if ($parent['origin'] && !$origin) {
  1915. $origin_uid = $parent['uid'];
  1916. }
  1917. }
  1918. }
  1919. foreach ($users as $uid) {
  1920. if ($origin_uid == $uid) {
  1921. $item['diaspora_signed_text'] = $signed_text;
  1922. }
  1923. self::storeForUser($itemid, $item, $uid);
  1924. }
  1925. }
  1926. /**
  1927. * @brief Store public items for the receivers
  1928. *
  1929. * @param integer $itemid Item ID that should be added
  1930. * @param array $item The item entry that will be stored
  1931. * @param integer $uid The user that will receive the item entry
  1932. * @throws \Exception
  1933. */
  1934. private static function storeForUser($itemid, $item, $uid)
  1935. {
  1936. $item['uid'] = $uid;
  1937. $item['origin'] = 0;
  1938. $item['wall'] = 0;
  1939. if ($item['uri'] == $item['parent-uri']) {
  1940. $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
  1941. } else {
  1942. $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
  1943. }
  1944. if (empty($item['contact-id'])) {
  1945. $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
  1946. if (!DBA::isResult($self)) {
  1947. return;
  1948. }
  1949. $item['contact-id'] = $self['id'];
  1950. }
  1951. /// @todo Handling of "event-id"
  1952. $notify = false;
  1953. if ($item['uri'] == $item['parent-uri']) {
  1954. $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
  1955. if (DBA::isResult($contact)) {
  1956. $notify = self::isRemoteSelf($contact, $item);
  1957. }
  1958. }
  1959. $distributed = self::insert($item, false, $notify, true);
  1960. if (!$distributed) {
  1961. Logger::log("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", Logger::DEBUG);
  1962. } else {
  1963. Logger::log("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, Logger::DEBUG);
  1964. }
  1965. }
  1966. /**
  1967. * @brief Add a shadow entry for a given item id that is a thread starter
  1968. *
  1969. * We store every public item entry additionally with the user id "0".
  1970. * This is used for the community page and for the search.
  1971. * It is planned that in the future we will store public item entries only once.
  1972. *
  1973. * @param integer $itemid Item ID that should be added
  1974. * @throws \Exception
  1975. */
  1976. public static function addShadow($itemid)
  1977. {
  1978. $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
  1979. $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
  1980. $item = self::selectFirst($fields, $condition);
  1981. if (!DBA::isResult($item)) {
  1982. return;
  1983. }
  1984. // is it already a copy?
  1985. if (($itemid == 0) || ($item['uid'] == 0)) {
  1986. return;
  1987. }
  1988. // Is it a visible public post?
  1989. if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
  1990. return;
  1991. }
  1992. // is it an entry from a connector? Only add an entry for natively connected networks
  1993. if (!in_array($item["network"], array_merge(Protocol::FEDERATED ,['']))) {
  1994. return;
  1995. }
  1996. if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
  1997. return;
  1998. }
  1999. $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
  2000. if (DBA::isResult($item)) {
  2001. // Preparing public shadow (removing user specific data)
  2002. $item['uid'] = 0;
  2003. unset($item['id']);
  2004. unset($item['parent']);
  2005. unset($item['wall']);
  2006. unset($item['mention']);
  2007. unset($item['origin']);
  2008. unset($item['starred']);
  2009. unset($item['postopts']);
  2010. unset($item['inform']);
  2011. if ($item['uri'] == $item['parent-uri']) {
  2012. $item['contact-id'] = $item['owner-id'];
  2013. } else {
  2014. $item['contact-id'] = $item['author-id'];
  2015. }
  2016. $public_shadow = self::insert($item, false, false, true);
  2017. Logger::log("Stored public shadow for thread ".$itemid." under id ".$public_shadow, Logger::DEBUG);
  2018. }
  2019. }
  2020. /**
  2021. * @brief Add a shadow entry for a given item id that is a comment
  2022. *
  2023. * This function does the same like the function above - but for comments
  2024. *
  2025. * @param integer $itemid Item ID that should be added
  2026. * @throws \Exception
  2027. */
  2028. public static function addShadowPost($itemid)
  2029. {
  2030. $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
  2031. if (!DBA::isResult($item)) {
  2032. return;
  2033. }
  2034. // Is it a toplevel post?
  2035. if ($item['id'] == $item['parent']) {
  2036. self::addShadow($itemid);
  2037. return;
  2038. }
  2039. // Is this a shadow entry?
  2040. if ($item['uid'] == 0) {
  2041. return;
  2042. }
  2043. // Is there a shadow parent?
  2044. if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
  2045. return;
  2046. }
  2047. // Is there already a shadow entry?
  2048. if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
  2049. return;
  2050. }
  2051. // Save "origin" and "parent" state
  2052. $origin = $item['origin'];
  2053. $parent = $item['parent'];
  2054. // Preparing public shadow (removing user specific data)
  2055. $item['uid'] = 0;
  2056. unset($item['id']);
  2057. unset($item['parent']);
  2058. unset($item['wall']);
  2059. unset($item['mention']);
  2060. unset($item['origin']);
  2061. unset($item['starred']);
  2062. unset($item['postopts']);
  2063. unset($item['inform']);
  2064. $item['contact-id'] = Contact::getIdForURL($item['author-link']);
  2065. $public_shadow = self::insert($item, false, false, true);
  2066. Logger::log("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, Logger::DEBUG);
  2067. // If this was a comment to a Diaspora post we don't get our comment back.
  2068. // This means that we have to distribute the comment by ourselves.
  2069. if ($origin && self::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
  2070. self::distribute($public_shadow);
  2071. }
  2072. }
  2073. /**
  2074. * Adds a language specification in a "language" element of given $arr.
  2075. * Expects "body" element to exist in $arr.
  2076. *
  2077. * @param $item
  2078. * @throws \Text_LanguageDetect_Exception
  2079. */
  2080. private static function addLanguageToItemArray(&$item)
  2081. {
  2082. $naked_body = BBCode::toPlaintext($item['body'], false);
  2083. $ld = new Text_LanguageDetect();
  2084. $ld->setNameMode(2);
  2085. $languages = $ld->detect($naked_body, 3);
  2086. if (is_array($languages)) {
  2087. $item['language'] = json_encode($languages);
  2088. }
  2089. }
  2090. /**
  2091. * @brief Creates an unique guid out of a given uri
  2092. *
  2093. * @param string $uri uri of an item entry
  2094. * @param string $host hostname for the GUID prefix
  2095. * @return string unique guid
  2096. */
  2097. public static function guidFromUri($uri, $host)
  2098. {
  2099. // Our regular guid routine is using this kind of prefix as well
  2100. // We have to avoid that different routines could accidentally create the same value
  2101. $parsed = parse_url($uri);
  2102. // We use a hash of the hostname as prefix for the guid
  2103. $guid_prefix = hash("crc32", $host);
  2104. // Remove the scheme to make sure that "https" and "http" doesn't make a difference
  2105. unset($parsed["scheme"]);
  2106. // Glue it together to be able to make a hash from it
  2107. $host_id = implode("/", $parsed);
  2108. // We could use any hash algorithm since it isn't a security issue
  2109. $host_hash = hash("ripemd128", $host_id);
  2110. return $guid_prefix.$host_hash;
  2111. }
  2112. /**
  2113. * generate an unique URI
  2114. *
  2115. * @param integer $uid User id
  2116. * @param string $guid An existing GUID (Otherwise it will be generated)
  2117. *
  2118. * @return string
  2119. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  2120. */
  2121. public static function newURI($uid, $guid = "")
  2122. {
  2123. if ($guid == "") {
  2124. $guid = System::createUUID();
  2125. }
  2126. return DI::baseUrl()->get() . '/objects/' . $guid;
  2127. }
  2128. /**
  2129. * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
  2130. *
  2131. * This can be used to filter for inactive contacts.
  2132. * Only do this for public postings to avoid privacy problems, since poco data is public.
  2133. * Don't set this value if it isn't from the owner (could be an author that we don't know)
  2134. *
  2135. * @param array $arr Contains the just posted item record
  2136. * @throws \Exception
  2137. */
  2138. private static function updateContact($arr)
  2139. {
  2140. // Unarchive the author
  2141. $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
  2142. if (DBA::isResult($contact)) {
  2143. Contact::unmarkForArchival($contact);
  2144. }
  2145. // Unarchive the contact if it's not our own contact
  2146. $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
  2147. if (DBA::isResult($contact)) {
  2148. Contact::unmarkForArchival($contact);
  2149. }
  2150. $update = (!$arr['private'] && ((($arr['author-link'] ?? '') === ($arr['owner-link'] ?? '')) || ($arr["parent-uri"] === $arr["uri"])));
  2151. // Is it a forum? Then we don't care about the rules from above
  2152. if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri"] === $arr["uri"])) {
  2153. if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
  2154. $update = true;
  2155. }
  2156. }
  2157. if ($update) {
  2158. DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
  2159. ['id' => $arr['contact-id']]);
  2160. }
  2161. // Now do the same for the system wide contacts with uid=0
  2162. if (!$arr['private']) {
  2163. DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
  2164. ['id' => $arr['owner-id']]);
  2165. if ($arr['owner-id'] != $arr['author-id']) {
  2166. DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
  2167. ['id' => $arr['author-id']]);
  2168. }
  2169. }
  2170. }
  2171. public static function setHashtags(&$item)
  2172. {
  2173. $tags = BBCode::getTags($item["body"]);
  2174. // No hashtags?
  2175. if (!count($tags)) {
  2176. return false;
  2177. }
  2178. // What happens in [code], stays in [code]!
  2179. // escape the # and the [
  2180. // hint: we will also get in trouble with #tags, when we want markdown in posts -> ### Headline 3
  2181. $item["body"] = preg_replace_callback("/\[code(.*?)\](.*?)\[\/code\]/ism",
  2182. function ($match) {
  2183. // we truly ESCape all # and [ to prevent gettin weird tags in [code] blocks
  2184. $find = ['#', '['];
  2185. $replace = [chr(27).'sharp', chr(27).'leftsquarebracket'];
  2186. return ("[code" . $match[1] . "]" . str_replace($find, $replace, $match[2]) . "[/code]");
  2187. }, $item["body"]);
  2188. // This sorting is important when there are hashtags that are part of other hashtags
  2189. // Otherwise there could be problems with hashtags like #test and #test2
  2190. rsort($tags);
  2191. $URLSearchString = "^\[\]";
  2192. // All hashtags should point to the home server if "local_tags" is activated
  2193. if (Config::get('system', 'local_tags')) {
  2194. $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
  2195. "#[url=".DI::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
  2196. $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
  2197. "#[url=".DI::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
  2198. }
  2199. // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
  2200. $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
  2201. function ($match) {
  2202. return ("[url=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/url]");
  2203. }, $item["body"]);
  2204. $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
  2205. function ($match) {
  2206. return ("[bookmark=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/bookmark]");
  2207. }, $item["body"]);
  2208. $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
  2209. function ($match) {
  2210. return ("[attachment " . str_replace("#", "&num;", $match[1]) . "]" . $match[2] . "[/attachment]");
  2211. }, $item["body"]);
  2212. // Repair recursive urls
  2213. $item["body"] = preg_replace("/&num;\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
  2214. "&num;$2", $item["body"]);
  2215. foreach ($tags as $tag) {
  2216. if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
  2217. continue;
  2218. }
  2219. $basetag = str_replace('_',' ',substr($tag,1));
  2220. $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
  2221. $item["body"] = str_replace($tag, $newtag, $item["body"]);
  2222. if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
  2223. if (strlen($item["tag"])) {
  2224. $item["tag"] = ',' . $item["tag"];
  2225. }
  2226. $item["tag"] = $newtag . $item["tag"];
  2227. }
  2228. }
  2229. // Convert back the masked hashtags
  2230. $item["body"] = str_replace("&num;", "#", $item["body"]);
  2231. // Remember! What happens in [code], stays in [code]
  2232. // roleback the # and [
  2233. $item["body"] = preg_replace_callback("/\[code(.*?)\](.*?)\[\/code\]/ism",
  2234. function ($match) {
  2235. // we truly unESCape all sharp and leftsquarebracket
  2236. $find = [chr(27).'sharp', chr(27).'leftsquarebracket'];
  2237. $replace = ['#', '['];
  2238. return ("[code" . $match[1] . "]" . str_replace($find, $replace, $match[2]) . "[/code]");
  2239. }, $item["body"]);
  2240. }
  2241. /**
  2242. * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
  2243. *
  2244. * @param int $uid
  2245. * @param int $item_id
  2246. * @return boolean true if item was deleted, else false
  2247. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  2248. * @throws \ImagickException
  2249. */
  2250. private static function tagDeliver($uid, $item_id)
  2251. {
  2252. $mention = false;
  2253. $user = DBA::selectFirst('user', [], ['uid' => $uid]);
  2254. if (!DBA::isResult($user)) {
  2255. return false;
  2256. }
  2257. $community_page = (($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? true : false);
  2258. $prvgroup = (($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP) ? true : false);
  2259. $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
  2260. if (!DBA::isResult($item)) {
  2261. return false;
  2262. }
  2263. $link = Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']);
  2264. /*
  2265. * Diaspora uses their own hardwired link URL in @-tags
  2266. * instead of the one we supply with webfinger
  2267. */
  2268. $dlink = Strings::normaliseLink(DI::baseUrl() . '/u/' . $user['nickname']);
  2269. $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
  2270. if ($cnt) {
  2271. foreach ($matches as $mtch) {
  2272. if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
  2273. $mention = true;
  2274. Logger::log('mention found: ' . $mtch[2]);
  2275. }
  2276. }
  2277. }
  2278. if (!$mention) {
  2279. if (($community_page || $prvgroup) &&
  2280. !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
  2281. // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
  2282. // delete it!
  2283. Logger::log("no-mention top-level post to community or private group. delete.");
  2284. DBA::delete('item', ['id' => $item_id]);
  2285. return true;
  2286. }
  2287. return false;
  2288. }
  2289. $arr = ['item' => $item, 'user' => $user];
  2290. Hook::callAll('tagged', $arr);
  2291. if (!$community_page && !$prvgroup) {
  2292. return false;
  2293. }
  2294. /*
  2295. * tgroup delivery - setup a second delivery chain
  2296. * prevent delivery looping - only proceed
  2297. * if the message originated elsewhere and is a top-level post
  2298. */
  2299. if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
  2300. return false;
  2301. }
  2302. // now change this copy of the post to a forum head message and deliver to all the tgroup members
  2303. $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
  2304. if (!DBA::isResult($self)) {
  2305. return false;
  2306. }
  2307. $owner_id = Contact::getIdForURL($self['url']);
  2308. // also reset all the privacy bits to the forum default permissions
  2309. $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
  2310. $psid = PermissionSet::fetchIDForPost($user);
  2311. $forum_mode = ($prvgroup ? 2 : 1);
  2312. $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
  2313. 'owner-id' => $owner_id, 'private' => $private, 'psid' => $psid];
  2314. self::update($fields, ['id' => $item_id]);
  2315. self::updateThread($item_id);
  2316. Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', Delivery::POST, $item_id);
  2317. return false;
  2318. }
  2319. public static function isRemoteSelf($contact, &$datarray)
  2320. {
  2321. if (!$contact['remote_self']) {
  2322. return false;
  2323. }
  2324. // Prevent the forwarding of posts that are forwarded
  2325. if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
  2326. Logger::log('Already forwarded', Logger::DEBUG);
  2327. return false;
  2328. }
  2329. // Prevent to forward already forwarded posts
  2330. if ($datarray["app"] == DI::baseUrl()->getHostname()) {
  2331. Logger::log('Already forwarded (second test)', Logger::DEBUG);
  2332. return false;
  2333. }
  2334. // Only forward posts
  2335. if ($datarray["verb"] != Activity::POST) {
  2336. Logger::log('No post', Logger::DEBUG);
  2337. return false;
  2338. }
  2339. if (($contact['network'] != Protocol::FEED) && $datarray['private']) {
  2340. Logger::log('Not public', Logger::DEBUG);
  2341. return false;
  2342. }
  2343. $datarray2 = $datarray;
  2344. Logger::log('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), Logger::DEBUG);
  2345. if ($contact['remote_self'] == 2) {
  2346. $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
  2347. ['uid' => $contact['uid'], 'self' => true]);
  2348. if (DBA::isResult($self)) {
  2349. $datarray['contact-id'] = $self["id"];
  2350. $datarray['owner-name'] = $self["name"];
  2351. $datarray['owner-link'] = $self["url"];
  2352. $datarray['owner-avatar'] = $self["thumb"];
  2353. $datarray['author-name'] = $datarray['owner-name'];
  2354. $datarray['author-link'] = $datarray['owner-link'];
  2355. $datarray['author-avatar'] = $datarray['owner-avatar'];
  2356. unset($datarray['edited']);
  2357. unset($datarray['network']);
  2358. unset($datarray['owner-id']);
  2359. unset($datarray['author-id']);
  2360. }
  2361. if ($contact['network'] != Protocol::FEED) {
  2362. $datarray["guid"] = System::createUUID();
  2363. unset($datarray["plink"]);
  2364. $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
  2365. $datarray["parent-uri"] = $datarray["uri"];
  2366. $datarray["thr-parent"] = $datarray["uri"];
  2367. $datarray["extid"] = Protocol::DFRN;
  2368. $urlpart = parse_url($datarray2['author-link']);
  2369. $datarray["app"] = $urlpart["host"];
  2370. } else {
  2371. $datarray['private'] = 0;
  2372. }
  2373. }
  2374. if ($contact['network'] != Protocol::FEED) {
  2375. // Store the original post
  2376. $result = self::insert($datarray2, false, false);
  2377. Logger::log('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), Logger::DEBUG);
  2378. } else {
  2379. $datarray["app"] = "Feed";
  2380. $result = true;
  2381. }
  2382. // Trigger automatic reactions for addons
  2383. $datarray['api_source'] = true;
  2384. // We have to tell the hooks who we are - this really should be improved
  2385. $_SESSION["authenticated"] = true;
  2386. $_SESSION["uid"] = $contact['uid'];
  2387. return $result;
  2388. }
  2389. /**
  2390. *
  2391. * @param string $s
  2392. * @param int $uid
  2393. * @param array $item
  2394. * @param int $cid
  2395. * @return string
  2396. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  2397. * @throws \ImagickException
  2398. */
  2399. public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
  2400. {
  2401. if (Config::get('system', 'disable_embedded')) {
  2402. return $s;
  2403. }
  2404. Logger::log('check for photos', Logger::DEBUG);
  2405. $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
  2406. $orig_body = $s;
  2407. $new_body = '';
  2408. $img_start = strpos($orig_body, '[img');
  2409. $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
  2410. $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
  2411. while (($img_st_close !== false) && ($img_len !== false)) {
  2412. $img_st_close++; // make it point to AFTER the closing bracket
  2413. $image = substr($orig_body, $img_start + $img_st_close, $img_len);
  2414. Logger::log('found photo ' . $image, Logger::DEBUG);
  2415. if (stristr($image, $site . '/photo/')) {
  2416. // Only embed locally hosted photos
  2417. $replace = false;
  2418. $i = basename($image);
  2419. $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
  2420. $x = strpos($i, '-');
  2421. if ($x) {
  2422. $res = substr($i, $x + 1);
  2423. $i = substr($i, 0, $x);
  2424. $photo = Photo::getPhotoForUser($uid, $i, $res);
  2425. if (DBA::isResult($photo)) {
  2426. /*
  2427. * Check to see if we should replace this photo link with an embedded image
  2428. * 1. No need to do so if the photo is public
  2429. * 2. If there's a contact-id provided, see if they're in the access list
  2430. * for the photo. If so, embed it.
  2431. * 3. Otherwise, if we have an item, see if the item permissions match the photo
  2432. * permissions, regardless of order but first check to see if they're an exact
  2433. * match to save some processing overhead.
  2434. */
  2435. if (self::hasPermissions($photo)) {
  2436. if ($cid) {
  2437. $recips = self::enumeratePermissions($photo);
  2438. if (in_array($cid, $recips)) {
  2439. $replace = true;
  2440. }
  2441. } elseif ($item) {
  2442. if (self::samePermissions($uid, $item, $photo)) {
  2443. $replace = true;
  2444. }
  2445. }
  2446. }
  2447. if ($replace) {
  2448. $photo_img = Photo::getImageForPhoto($photo);
  2449. // If a custom width and height were specified, apply before embedding
  2450. if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
  2451. Logger::log('scaling photo', Logger::DEBUG);
  2452. $width = intval($match[1]);
  2453. $height = intval($match[2]);
  2454. $photo_img->scaleDown(max($width, $height));
  2455. }
  2456. $data = $photo_img->asString();
  2457. $type = $photo_img->getType();
  2458. Logger::log('replacing photo', Logger::DEBUG);
  2459. $image = 'data:' . $type . ';base64,' . base64_encode($data);
  2460. Logger::log('replaced: ' . $image, Logger::DATA);
  2461. }
  2462. }
  2463. }
  2464. }
  2465. $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
  2466. $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
  2467. if ($orig_body === false) {
  2468. $orig_body = '';
  2469. }
  2470. $img_start = strpos($orig_body, '[img');
  2471. $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
  2472. $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
  2473. }
  2474. $new_body = $new_body . $orig_body;
  2475. return $new_body;
  2476. }
  2477. private static function hasPermissions($obj)
  2478. {
  2479. return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
  2480. !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
  2481. }
  2482. private static function samePermissions($uid, $obj1, $obj2)
  2483. {
  2484. // first part is easy. Check that these are exactly the same.
  2485. if (($obj1['allow_cid'] == $obj2['allow_cid'])
  2486. && ($obj1['allow_gid'] == $obj2['allow_gid'])
  2487. && ($obj1['deny_cid'] == $obj2['deny_cid'])
  2488. && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
  2489. return true;
  2490. }
  2491. // This is harder. Parse all the permissions and compare the resulting set.
  2492. $recipients1 = self::enumeratePermissions($obj1);
  2493. $recipients2 = self::enumeratePermissions($obj2);
  2494. sort($recipients1);
  2495. sort($recipients2);
  2496. /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
  2497. return ($recipients1 == $recipients2);
  2498. }
  2499. /**
  2500. * Returns an array of contact-ids that are allowed to see this object
  2501. *
  2502. * @param array $obj Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
  2503. * @param bool $check_dead Prunes unavailable contacts from the result
  2504. * @return array
  2505. * @throws \Exception
  2506. */
  2507. public static function enumeratePermissions(array $obj, bool $check_dead = false)
  2508. {
  2509. $aclFormater = DI::aclFormatter();
  2510. $allow_people = $aclFormater->expand($obj['allow_cid']);
  2511. $allow_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['allow_gid']), $check_dead);
  2512. $deny_people = $aclFormater->expand($obj['deny_cid']);
  2513. $deny_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['deny_gid']), $check_dead);
  2514. $recipients = array_unique(array_merge($allow_people, $allow_groups));
  2515. $deny = array_unique(array_merge($deny_people, $deny_groups));
  2516. $recipients = array_diff($recipients, $deny);
  2517. return $recipients;
  2518. }
  2519. public static function getFeedTags($item)
  2520. {
  2521. $ret = [];
  2522. $matches = false;
  2523. $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
  2524. if ($cnt) {
  2525. for ($x = 0; $x < $cnt; $x ++) {
  2526. if ($matches[1][$x]) {
  2527. $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
  2528. }
  2529. }
  2530. }
  2531. $matches = false;
  2532. $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
  2533. if ($cnt) {
  2534. for ($x = 0; $x < $cnt; $x ++) {
  2535. if ($matches[1][$x]) {
  2536. $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
  2537. }
  2538. }
  2539. }
  2540. return $ret;
  2541. }
  2542. public static function expire($uid, $days, $network = "", $force = false)
  2543. {
  2544. if (!$uid || ($days < 1)) {
  2545. return;
  2546. }
  2547. $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
  2548. $uid, GRAVITY_PARENT];
  2549. /*
  2550. * $expire_network_only = save your own wall posts
  2551. * and just expire conversations started by others
  2552. */
  2553. $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
  2554. if ($expire_network_only) {
  2555. $condition[0] .= " AND NOT `wall`";
  2556. }
  2557. if ($network != "") {
  2558. $condition[0] .= " AND `network` = ?";
  2559. $condition[] = $network;
  2560. }
  2561. $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
  2562. $condition[] = $days;
  2563. $items = self::select(['file', 'resource-id', 'starred', 'type', 'id', 'post-type'], $condition);
  2564. if (!DBA::isResult($items)) {
  2565. return;
  2566. }
  2567. $expire_items = DI::pConfig()->get($uid, 'expire', 'items', true);
  2568. // Forcing expiring of items - but not notes and marked items
  2569. if ($force) {
  2570. $expire_items = true;
  2571. }
  2572. $expire_notes = DI::pConfig()->get($uid, 'expire', 'notes', true);
  2573. $expire_starred = DI::pConfig()->get($uid, 'expire', 'starred', true);
  2574. $expire_photos = DI::pConfig()->get($uid, 'expire', 'photos', false);
  2575. $expired = 0;
  2576. while ($item = Item::fetch($items)) {
  2577. // don't expire filed items
  2578. if (strpos($item['file'], '[') !== false) {
  2579. continue;
  2580. }
  2581. // Only expire posts, not photos and photo comments
  2582. if (!$expire_photos && strlen($item['resource-id'])) {
  2583. continue;
  2584. } elseif (!$expire_starred && intval($item['starred'])) {
  2585. continue;
  2586. } elseif (!$expire_notes && (($item['type'] == 'note') || ($item['post-type'] == Item::PT_PERSONAL_NOTE))) {
  2587. continue;
  2588. } elseif (!$expire_items && ($item['type'] != 'note') && ($item['post-type'] != Item::PT_PERSONAL_NOTE)) {
  2589. continue;
  2590. }
  2591. self::deleteById($item['id'], PRIORITY_LOW);
  2592. ++$expired;
  2593. }
  2594. DBA::close($items);
  2595. Logger::log('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
  2596. }
  2597. public static function firstPostDate($uid, $wall = false)
  2598. {
  2599. $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
  2600. $params = ['order' => ['received' => false]];
  2601. $thread = DBA::selectFirst('thread', ['received'], $condition, $params);
  2602. if (DBA::isResult($thread)) {
  2603. return substr(DateTimeFormat::local($thread['received']), 0, 10);
  2604. }
  2605. return false;
  2606. }
  2607. /**
  2608. * @brief add/remove activity to an item
  2609. *
  2610. * Toggle activities as like,dislike,attend of an item
  2611. *
  2612. * @param string $item_id
  2613. * @param string $verb
  2614. * Activity verb. One of
  2615. * like, unlike, dislike, undislike, attendyes, unattendyes,
  2616. * attendno, unattendno, attendmaybe, unattendmaybe
  2617. * @return bool
  2618. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  2619. * @throws \ImagickException
  2620. * @hook 'post_local_end'
  2621. * array $arr
  2622. * 'post_id' => ID of posted item
  2623. */
  2624. public static function performLike($item_id, $verb)
  2625. {
  2626. if (!Session::isAuthenticated()) {
  2627. return false;
  2628. }
  2629. switch ($verb) {
  2630. case 'like':
  2631. case 'unlike':
  2632. $activity = Activity::LIKE;
  2633. break;
  2634. case 'dislike':
  2635. case 'undislike':
  2636. $activity = Activity::DISLIKE;
  2637. break;
  2638. case 'attendyes':
  2639. case 'unattendyes':
  2640. $activity = Activity::ATTEND;
  2641. break;
  2642. case 'attendno':
  2643. case 'unattendno':
  2644. $activity = Activity::ATTENDNO;
  2645. break;
  2646. case 'attendmaybe':
  2647. case 'unattendmaybe':
  2648. $activity = Activity::ATTENDMAYBE;
  2649. break;
  2650. default:
  2651. Logger::log('like: unknown verb ' . $verb . ' for item ' . $item_id);
  2652. return false;
  2653. }
  2654. // Enable activity toggling instead of on/off
  2655. $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
  2656. Logger::log('like: verb ' . $verb . ' item ' . $item_id);
  2657. $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
  2658. if (!DBA::isResult($item)) {
  2659. Logger::log('like: unknown item ' . $item_id);
  2660. return false;
  2661. }
  2662. $item_uri = $item['uri'];
  2663. $uid = $item['uid'];
  2664. if (($uid == 0) && local_user()) {
  2665. $uid = local_user();
  2666. }
  2667. if (!Security::canWriteToUserWall($uid)) {
  2668. Logger::log('like: unable to write on wall ' . $uid);
  2669. return false;
  2670. }
  2671. // Retrieves the local post owner
  2672. $owner_self_contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
  2673. if (!DBA::isResult($owner_self_contact)) {
  2674. Logger::log('like: unknown owner ' . $uid);
  2675. return false;
  2676. }
  2677. // Retrieve the current logged in user's public contact
  2678. $author_id = public_contact();
  2679. $author_contact = DBA::selectFirst('contact', ['url'], ['id' => $author_id]);
  2680. if (!DBA::isResult($author_contact)) {
  2681. Logger::log('like: unknown author ' . $author_id);
  2682. return false;
  2683. }
  2684. // Contact-id is the uid-dependant author contact
  2685. if (local_user() == $uid) {
  2686. $item_contact_id = $owner_self_contact['id'];
  2687. } else {
  2688. $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
  2689. $item_contact = DBA::selectFirst('contact', [], ['id' => $item_contact_id]);
  2690. if (!DBA::isResult($item_contact)) {
  2691. Logger::log('like: unknown item contact ' . $item_contact_id);
  2692. return false;
  2693. }
  2694. }
  2695. // Look for an existing verb row
  2696. // event participation are essentially radio toggles. If you make a subsequent choice,
  2697. // we need to eradicate your first choice.
  2698. if ($event_verb_flag) {
  2699. $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
  2700. // Translate to the index based activity index
  2701. $activities = [];
  2702. foreach ($verbs as $verb) {
  2703. $activities[] = self::activityToIndex($verb);
  2704. }
  2705. } else {
  2706. $activities = self::activityToIndex($activity);
  2707. }
  2708. $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
  2709. 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
  2710. $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
  2711. // If it exists, mark it as deleted
  2712. if (DBA::isResult($like_item)) {
  2713. self::deleteById($like_item['id']);
  2714. if (!$event_verb_flag || $like_item['verb'] == $activity) {
  2715. return true;
  2716. }
  2717. }
  2718. // Verb is "un-something", just trying to delete existing entries
  2719. if (strpos($verb, 'un') === 0) {
  2720. return true;
  2721. }
  2722. $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
  2723. $new_item = [
  2724. 'guid' => System::createUUID(),
  2725. 'uri' => self::newURI($item['uid']),
  2726. 'uid' => $item['uid'],
  2727. 'contact-id' => $item_contact_id,
  2728. 'wall' => $item['wall'],
  2729. 'origin' => 1,
  2730. 'network' => Protocol::DFRN,
  2731. 'gravity' => GRAVITY_ACTIVITY,
  2732. 'parent' => $item['id'],
  2733. 'parent-uri' => $item['uri'],
  2734. 'thr-parent' => $item['uri'],
  2735. 'owner-id' => $author_id,
  2736. 'author-id' => $author_id,
  2737. 'body' => $activity,
  2738. 'verb' => $activity,
  2739. 'object-type' => $objtype,
  2740. 'allow_cid' => $item['allow_cid'],
  2741. 'allow_gid' => $item['allow_gid'],
  2742. 'deny_cid' => $item['deny_cid'],
  2743. 'deny_gid' => $item['deny_gid'],
  2744. 'visible' => 1,
  2745. 'unseen' => 1,
  2746. ];
  2747. $signed = Diaspora::createLikeSignature($uid, $new_item);
  2748. if (!empty($signed)) {
  2749. $new_item['diaspora_signed_text'] = json_encode($signed);
  2750. }
  2751. $new_item_id = self::insert($new_item);
  2752. // If the parent item isn't visible then set it to visible
  2753. if (!$item['visible']) {
  2754. self::update(['visible' => true], ['id' => $item['id']]);
  2755. }
  2756. $new_item['id'] = $new_item_id;
  2757. Hook::callAll('post_local_end', $new_item);
  2758. return true;
  2759. }
  2760. private static function addThread($itemid, $onlyshadow = false)
  2761. {
  2762. $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
  2763. 'moderated', 'visible', 'starred', 'contact-id', 'post-type',
  2764. 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
  2765. $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
  2766. $item = self::selectFirst($fields, $condition);
  2767. if (!DBA::isResult($item)) {
  2768. return;
  2769. }
  2770. $item['iid'] = $itemid;
  2771. if (!$onlyshadow) {
  2772. $result = DBA::insert('thread', $item);
  2773. Logger::log("Add thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
  2774. }
  2775. }
  2776. private static function updateThread($itemid, $setmention = false)
  2777. {
  2778. $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
  2779. 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id',
  2780. 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
  2781. $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
  2782. $item = self::selectFirst($fields, $condition);
  2783. if (!DBA::isResult($item)) {
  2784. return;
  2785. }
  2786. if ($setmention) {
  2787. $item["mention"] = 1;
  2788. }
  2789. $fields = [];
  2790. foreach ($item as $field => $data) {
  2791. if (!in_array($field, ["guid"])) {
  2792. $fields[$field] = $data;
  2793. }
  2794. }
  2795. $result = DBA::update('thread', $fields, ['iid' => $itemid]);
  2796. Logger::log("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, Logger::DEBUG);
  2797. }
  2798. private static function deleteThread($itemid, $itemuri = "")
  2799. {
  2800. $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
  2801. if (!DBA::isResult($item)) {
  2802. Logger::log('No thread found for id '.$itemid, Logger::DEBUG);
  2803. return;
  2804. }
  2805. $result = DBA::delete('thread', ['iid' => $itemid], ['cascade' => false]);
  2806. Logger::log("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
  2807. if ($itemuri != "") {
  2808. $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
  2809. if (!self::exists($condition)) {
  2810. DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
  2811. Logger::log("deleteThread: Deleted shadow for item ".$itemuri, Logger::DEBUG);
  2812. }
  2813. }
  2814. }
  2815. public static function getPermissionsSQLByUserId($owner_id)
  2816. {
  2817. $local_user = local_user();
  2818. $remote_user = Session::getRemoteContactID($owner_id);
  2819. /*
  2820. * Construct permissions
  2821. *
  2822. * default permissions - anonymous user
  2823. */
  2824. $sql = " AND NOT `item`.`private`";
  2825. // Profile owner - everything is visible
  2826. if ($local_user && ($local_user == $owner_id)) {
  2827. $sql = '';
  2828. } elseif ($remote_user) {
  2829. /*
  2830. * Authenticated visitor. Unless pre-verified,
  2831. * check that the contact belongs to this $owner_id
  2832. * and load the groups the visitor belongs to.
  2833. * If pre-verified, the caller is expected to have already
  2834. * done this and passed the groups into this function.
  2835. */
  2836. $set = PermissionSet::get($owner_id, $remote_user);
  2837. if (!empty($set)) {
  2838. $sql_set = " OR (`item`.`private` IN (1,2) AND `item`.`wall` AND `item`.`psid` IN (" . implode(',', $set) . "))";
  2839. } else {
  2840. $sql_set = '';
  2841. }
  2842. $sql = " AND (NOT `item`.`private`" . $sql_set . ")";
  2843. }
  2844. return $sql;
  2845. }
  2846. /**
  2847. * get translated item type
  2848. *
  2849. * @param $item
  2850. * @return string
  2851. */
  2852. public static function postType($item)
  2853. {
  2854. if (!empty($item['event-id'])) {
  2855. return L10n::t('event');
  2856. } elseif (!empty($item['resource-id'])) {
  2857. return L10n::t('photo');
  2858. } elseif (!empty($item['verb']) && $item['verb'] !== Activity::POST) {
  2859. return L10n::t('activity');
  2860. } elseif ($item['id'] != $item['parent']) {
  2861. return L10n::t('comment');
  2862. }
  2863. return L10n::t('post');
  2864. }
  2865. /**
  2866. * Sets the "rendered-html" field of the provided item
  2867. *
  2868. * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
  2869. *
  2870. * @param array $item
  2871. * @param bool $update
  2872. *
  2873. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  2874. * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
  2875. */
  2876. public static function putInCache(&$item, $update = false)
  2877. {
  2878. $body = $item["body"];
  2879. $rendered_hash = $item['rendered-hash'] ?? '';
  2880. $rendered_html = $item['rendered-html'] ?? '';
  2881. if ($rendered_hash == ''
  2882. || $rendered_html == ""
  2883. || $rendered_hash != hash("md5", $item["body"])
  2884. || Config::get("system", "ignore_cache")
  2885. ) {
  2886. self::addRedirToImageTags($item);
  2887. $item["rendered-html"] = BBCode::convert($item["body"]);
  2888. $item["rendered-hash"] = hash("md5", $item["body"]);
  2889. $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
  2890. Hook::callAll('put_item_in_cache', $hook_data);
  2891. $item['rendered-html'] = $hook_data['rendered-html'];
  2892. $item['rendered-hash'] = $hook_data['rendered-hash'];
  2893. unset($hook_data);
  2894. // Force an update if the generated values differ from the existing ones
  2895. if ($rendered_hash != $item["rendered-hash"]) {
  2896. $update = true;
  2897. }
  2898. // Only compare the HTML when we forcefully ignore the cache
  2899. if (Config::get("system", "ignore_cache") && ($rendered_html != $item["rendered-html"])) {
  2900. $update = true;
  2901. }
  2902. if ($update && !empty($item["id"])) {
  2903. self::update(
  2904. [
  2905. 'rendered-html' => $item["rendered-html"],
  2906. 'rendered-hash' => $item["rendered-hash"]
  2907. ],
  2908. ['id' => $item["id"]]
  2909. );
  2910. }
  2911. }
  2912. $item["body"] = $body;
  2913. }
  2914. /**
  2915. * @brief Find any non-embedded images in private items and add redir links to them
  2916. *
  2917. * @param array &$item The field array of an item row
  2918. */
  2919. private static function addRedirToImageTags(array &$item)
  2920. {
  2921. $app = DI::app();
  2922. $matches = [];
  2923. $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
  2924. if ($cnt) {
  2925. foreach ($matches as $mtch) {
  2926. if (strpos($mtch[1], '/redir') !== false) {
  2927. continue;
  2928. }
  2929. if ((local_user() == $item['uid']) && ($item['private'] == 1) && ($item['contact-id'] != $app->contact['id']) && ($item['network'] == Protocol::DFRN)) {
  2930. $img_url = 'redir/' . $item['contact-id'] . '?url=' . urlencode($mtch[1]);
  2931. $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
  2932. }
  2933. }
  2934. }
  2935. }
  2936. /**
  2937. * @brief Given an item array, convert the body element from bbcode to html and add smilie icons.
  2938. * If attach is true, also add icons for item attachments.
  2939. *
  2940. * @param array $item
  2941. * @param boolean $attach
  2942. * @param boolean $is_preview
  2943. * @return string item body html
  2944. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  2945. * @throws \ImagickException
  2946. * @hook prepare_body_init item array before any work
  2947. * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
  2948. * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
  2949. * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
  2950. */
  2951. public static function prepareBody(array &$item, $attach = false, $is_preview = false)
  2952. {
  2953. $a = DI::app();
  2954. Hook::callAll('prepare_body_init', $item);
  2955. // In order to provide theme developers more possibilities, event items
  2956. // are treated differently.
  2957. if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
  2958. $ev = Event::getItemHTML($item);
  2959. return $ev;
  2960. }
  2961. $tags = Term::populateTagsFromItem($item);
  2962. $item['tags'] = $tags['tags'];
  2963. $item['hashtags'] = $tags['hashtags'];
  2964. $item['mentions'] = $tags['mentions'];
  2965. // Compile eventual content filter reasons
  2966. $filter_reasons = [];
  2967. if (!$is_preview && public_contact() != $item['author-id']) {
  2968. if (!empty($item['content-warning']) && (!local_user() || !DI::pConfig()->get(local_user(), 'system', 'disable_cw', false))) {
  2969. $filter_reasons[] = L10n::t('Content warning: %s', $item['content-warning']);
  2970. }
  2971. $hook_data = [
  2972. 'item' => $item,
  2973. 'filter_reasons' => $filter_reasons
  2974. ];
  2975. Hook::callAll('prepare_body_content_filter', $hook_data);
  2976. $filter_reasons = $hook_data['filter_reasons'];
  2977. unset($hook_data);
  2978. }
  2979. // Update the cached values if there is no "zrl=..." on the links.
  2980. $update = (!Session::isAuthenticated() && ($item["uid"] == 0));
  2981. // Or update it if the current viewer is the intented viewer.
  2982. if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
  2983. $update = true;
  2984. }
  2985. self::putInCache($item, $update);
  2986. $s = $item["rendered-html"];
  2987. $hook_data = [
  2988. 'item' => $item,
  2989. 'html' => $s,
  2990. 'preview' => $is_preview,
  2991. 'filter_reasons' => $filter_reasons
  2992. ];
  2993. Hook::callAll('prepare_body', $hook_data);
  2994. $s = $hook_data['html'];
  2995. unset($hook_data);
  2996. if (!$attach) {
  2997. // Replace the blockquotes with quotes that are used in mails.
  2998. $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
  2999. $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
  3000. return $s;
  3001. }
  3002. $as = '';
  3003. $vhead = false;
  3004. $matches = [];
  3005. preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $item['attach'], $matches, PREG_SET_ORDER);
  3006. foreach ($matches as $mtch) {
  3007. $mime = $mtch[3];
  3008. $the_url = Contact::magicLinkById($item['author-id'], $mtch[1]);
  3009. if (strpos($mime, 'video') !== false) {
  3010. if (!$vhead) {
  3011. $vhead = true;
  3012. DI::page()['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('videos_head.tpl'));
  3013. }
  3014. $url_parts = explode('/', $the_url);
  3015. $id = end($url_parts);
  3016. $as .= Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
  3017. '$video' => [
  3018. 'id' => $id,
  3019. 'title' => L10n::t('View Video'),
  3020. 'src' => $the_url,
  3021. 'mime' => $mime,
  3022. ],
  3023. ]);
  3024. }
  3025. $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
  3026. if ($filetype) {
  3027. $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
  3028. $filesubtype = str_replace('.', '-', $filesubtype);
  3029. } else {
  3030. $filetype = 'unkn';
  3031. $filesubtype = 'unkn';
  3032. }
  3033. $title = Strings::escapeHtml(trim(($mtch[4] ?? '') ?: $mtch[1]));
  3034. $title .= ' ' . $mtch[2] . ' ' . L10n::t('bytes');
  3035. $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
  3036. $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
  3037. }
  3038. if ($as != '') {
  3039. $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
  3040. }
  3041. // Map.
  3042. if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
  3043. $x = Map::byCoordinates(trim($item['coord']));
  3044. if ($x) {
  3045. $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
  3046. }
  3047. }
  3048. // Replace friendica image url size with theme preference.
  3049. if (!empty($a->theme_info['item_image_size'])) {
  3050. $ps = $a->theme_info['item_image_size'];
  3051. $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
  3052. }
  3053. $s = HTML::applyContentFilter($s, $filter_reasons);
  3054. $hook_data = ['item' => $item, 'html' => $s];
  3055. Hook::callAll('prepare_body_final', $hook_data);
  3056. return $hook_data['html'];
  3057. }
  3058. /**
  3059. * get private link for item
  3060. *
  3061. * @param array $item
  3062. * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
  3063. * @throws \Exception
  3064. */
  3065. public static function getPlink($item)
  3066. {
  3067. $a = DI::app();
  3068. if ($a->user['nickname'] != "") {
  3069. $ret = [
  3070. 'href' => "display/" . $item['guid'],
  3071. 'orig' => "display/" . $item['guid'],
  3072. 'title' => L10n::t('View on separate page'),
  3073. 'orig_title' => L10n::t('view on separate page'),
  3074. ];
  3075. if (!empty($item['plink'])) {
  3076. $ret["href"] = DI::baseUrl()->remove($item['plink']);
  3077. $ret["title"] = L10n::t('link to source');
  3078. }
  3079. } elseif (!empty($item['plink']) && ($item['private'] != 1)) {
  3080. $ret = [
  3081. 'href' => $item['plink'],
  3082. 'orig' => $item['plink'],
  3083. 'title' => L10n::t('link to source'),
  3084. ];
  3085. } else {
  3086. $ret = [];
  3087. }
  3088. return $ret;
  3089. }
  3090. /**
  3091. * Is the given item array a post that is sent as starting post to a forum?
  3092. *
  3093. * @param array $item
  3094. * @param array $owner
  3095. *
  3096. * @return boolean "true" when it is a forum post
  3097. */
  3098. public static function isForumPost(array $item, array $owner = [])
  3099. {
  3100. if (empty($owner)) {
  3101. $owner = User::getOwnerDataById($item['uid']);
  3102. if (empty($owner)) {
  3103. return false;
  3104. }
  3105. }
  3106. if (($item['author-id'] == $item['owner-id']) ||
  3107. ($owner['id'] == $item['contact-id']) ||
  3108. ($item['uri'] != $item['parent-uri']) ||
  3109. $item['origin']) {
  3110. return false;
  3111. }
  3112. return Contact::isForum($item['contact-id']);
  3113. }
  3114. /**
  3115. * Search item id for given URI or plink
  3116. *
  3117. * @param string $uri
  3118. * @param integer $uid
  3119. *
  3120. * @return integer item id
  3121. */
  3122. public static function searchByLink($uri, $uid = 0)
  3123. {
  3124. $ssl_uri = str_replace('http://', 'https://', $uri);
  3125. $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
  3126. $item = DBA::selectFirst('item', ['id'], ['uri' => $uris, 'uid' => $uid]);
  3127. if (DBA::isResult($item)) {
  3128. return $item['id'];
  3129. }
  3130. $itemcontent = DBA::selectFirst('item-content', ['uri-id'], ['plink' => $uris]);
  3131. if (!DBA::isResult($itemcontent)) {
  3132. return 0;
  3133. }
  3134. $itemuri = DBA::selectFirst('item-uri', ['uri'], ['id' => $itemcontent['uri-id']]);
  3135. if (!DBA::isResult($itemuri)) {
  3136. return 0;
  3137. }
  3138. $item = DBA::selectFirst('item', ['id'], ['uri' => $itemuri['uri'], 'uid' => $uid]);
  3139. if (DBA::isResult($item)) {
  3140. return $item['id'];
  3141. }
  3142. return 0;
  3143. }
  3144. /**
  3145. * Fetches item for given URI or plink
  3146. *
  3147. * @param string $uri
  3148. * @param integer $uid
  3149. *
  3150. * @return integer item id
  3151. */
  3152. public static function fetchByLink($uri, $uid = 0)
  3153. {
  3154. $item_id = self::searchByLink($uri, $uid);
  3155. if (!empty($item_id)) {
  3156. return $item_id;
  3157. }
  3158. if (ActivityPub\Processor::fetchMissingActivity($uri)) {
  3159. $item_id = self::searchByLink($uri, $uid);
  3160. } else {
  3161. $item_id = Diaspora::fetchByURL($uri);
  3162. }
  3163. if (!empty($item_id)) {
  3164. return $item_id;
  3165. }
  3166. return 0;
  3167. }
  3168. /**
  3169. * Return share data from an item array (if the item is shared item)
  3170. * We are providing the complete Item array, because at some time in the future
  3171. * we hopefully will define these values not in the body anymore but in some item fields.
  3172. * This function is meant to replace all similar functions in the system.
  3173. *
  3174. * @param array $item
  3175. *
  3176. * @return array with share information
  3177. */
  3178. public static function getShareArray($item)
  3179. {
  3180. if (!preg_match("/(.*?)\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", $item['body'], $matches)) {
  3181. return [];
  3182. }
  3183. $attribute_string = $matches[2];
  3184. $attributes = ['comment' => trim($matches[1]), 'shared' => trim($matches[3])];
  3185. foreach (['author', 'profile', 'avatar', 'guid', 'posted', 'link'] as $field) {
  3186. if (preg_match("/$field=(['\"])(.+?)\\1/ism", $attribute_string, $matches)) {
  3187. $attributes[$field] = trim(html_entity_decode($matches[2] ?? '', ENT_QUOTES, 'UTF-8'));
  3188. }
  3189. }
  3190. return $attributes;
  3191. }
  3192. /**
  3193. * Fetch item information for shared items from the original items and adds it.
  3194. *
  3195. * @param array $item
  3196. *
  3197. * @return array item array with data from the original item
  3198. */
  3199. public static function addShareDataFromOriginal($item)
  3200. {
  3201. $shared = self::getShareArray($item);
  3202. if (empty($shared)) {
  3203. return $item;
  3204. }
  3205. // Real reshares always have got a GUID.
  3206. if (empty($shared['guid'])) {
  3207. return $item;
  3208. }
  3209. $uid = $item['uid'] ?? 0;
  3210. // first try to fetch the item via the GUID. This will work for all reshares that had been created on this system
  3211. $shared_item = self::selectFirst(['title', 'body', 'attach'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
  3212. if (!DBA::isResult($shared_item)) {
  3213. // Otherwhise try to find (and possibly fetch) the item via the link. This should work for Diaspora and ActivityPub posts
  3214. $id = self::fetchByLink($shared['link'], $uid);
  3215. if (empty($id)) {
  3216. Logger::info('Original item not found', ['url' => $shared['link'], 'callstack' => System::callstack()]);
  3217. return $item;
  3218. }
  3219. $shared_item = self::selectFirst(['title', 'body', 'attach'], ['id' => $id]);
  3220. if (!DBA::isResult($shared_item)) {
  3221. return $item;
  3222. }
  3223. Logger::info('Got shared data from url', ['url' => $shared['link'], 'callstack' => System::callstack()]);
  3224. } else {
  3225. Logger::info('Got shared data from guid', ['guid' => $shared['guid'], 'callstack' => System::callstack()]);
  3226. }
  3227. if (!empty($shared_item['title'])) {
  3228. $body = '[h3]' . $shared_item['title'] . "[/h3]\n" . $shared_item['body'];
  3229. unset($shared_item['title']);
  3230. } else {
  3231. $body = $shared_item['body'];
  3232. }
  3233. $item['body'] = preg_replace("/\[share ([^\[\]]*)\].*\[\/share\]/ism", '[share $1]' . $body . '[/share]', $item['body']);
  3234. unset($shared_item['body']);
  3235. return array_merge($item, $shared_item);
  3236. }
  3237. }