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.
 
 
 
 
 
 

3548 lines
114 KiB

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