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.

3541 lines
115KB

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