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.

2134 lines
68KB

  1. <?php
  2. /**
  3. * @file src/Model/Contact.php
  4. */
  5. namespace Friendica\Model;
  6. use Friendica\BaseObject;
  7. use Friendica\Content\Pager;
  8. use Friendica\Core\Addon;
  9. use Friendica\Core\Config;
  10. use Friendica\Core\Hook;
  11. use Friendica\Core\L10n;
  12. use Friendica\Core\Logger;
  13. use Friendica\Core\Protocol;
  14. use Friendica\Core\System;
  15. use Friendica\Core\Worker;
  16. use Friendica\Database\DBA;
  17. use Friendica\Network\Probe;
  18. use Friendica\Object\Image;
  19. use Friendica\Protocol\ActivityPub;
  20. use Friendica\Protocol\DFRN;
  21. use Friendica\Protocol\Diaspora;
  22. use Friendica\Protocol\OStatus;
  23. use Friendica\Protocol\PortableContact;
  24. use Friendica\Protocol\Salmon;
  25. use Friendica\Util\DateTimeFormat;
  26. use Friendica\Util\Network;
  27. use Friendica\Util\Strings;
  28. /**
  29. * @brief functions for interacting with a contact
  30. */
  31. class Contact extends BaseObject
  32. {
  33. /**
  34. * @name page/profile types
  35. *
  36. * PAGE_NORMAL is a typical personal profile account
  37. * PAGE_SOAPBOX automatically approves all friend requests as Contact::SHARING, (readonly)
  38. * PAGE_COMMUNITY automatically approves all friend requests as Contact::SHARING, but with
  39. * write access to wall and comments (no email and not included in page owner's ACL lists)
  40. * PAGE_FREELOVE automatically approves all friend requests as full friends (Contact::FRIEND).
  41. *
  42. * @{
  43. */
  44. const PAGE_NORMAL = 0;
  45. const PAGE_SOAPBOX = 1;
  46. const PAGE_COMMUNITY = 2;
  47. const PAGE_FREELOVE = 3;
  48. const PAGE_BLOG = 4;
  49. const PAGE_PRVGROUP = 5;
  50. /**
  51. * @}
  52. */
  53. /**
  54. * @name account types
  55. *
  56. * ACCOUNT_TYPE_PERSON - the account belongs to a person
  57. * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
  58. *
  59. * ACCOUNT_TYPE_ORGANISATION - the account belongs to an organisation
  60. * Associated page type: PAGE_SOAPBOX
  61. *
  62. * ACCOUNT_TYPE_NEWS - the account is a news reflector
  63. * Associated page type: PAGE_SOAPBOX
  64. *
  65. * ACCOUNT_TYPE_COMMUNITY - the account is community forum
  66. * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
  67. *
  68. * ACCOUNT_TYPE_RELAY - the account is a relay
  69. * This will only be assigned to contacts, not to user accounts
  70. * @{
  71. */
  72. const ACCOUNT_TYPE_PERSON = 0;
  73. const ACCOUNT_TYPE_ORGANISATION = 1;
  74. const ACCOUNT_TYPE_NEWS = 2;
  75. const ACCOUNT_TYPE_COMMUNITY = 3;
  76. const ACCOUNT_TYPE_RELAY = 4;
  77. /**
  78. * @}
  79. */
  80. /**
  81. * @name Contact_is
  82. *
  83. * Relationship types
  84. * @{
  85. */
  86. const FOLLOWER = 1;
  87. const SHARING = 2;
  88. const FRIEND = 3;
  89. /**
  90. * @}
  91. */
  92. /**
  93. * @brief Tests if the given contact is a follower
  94. *
  95. * @param int $cid Either public contact id or user's contact id
  96. * @param int $uid User ID
  97. *
  98. * @return boolean is the contact id a follower?
  99. */
  100. public static function isFollower($cid, $uid)
  101. {
  102. if (self::isBlockedByUser($cid, $uid)) {
  103. return false;
  104. }
  105. $cdata = self::getPublicAndUserContacID($cid, $uid);
  106. if (empty($cdata['user'])) {
  107. return false;
  108. }
  109. $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
  110. return DBA::exists('contact', $condition);
  111. }
  112. /**
  113. * @brief Get the basepath for a given contact link
  114. * @todo Add functionality to store this value in the contact table
  115. *
  116. * @param string $url The contact link
  117. *
  118. * @return string basepath
  119. */
  120. public static function getBasepath($url)
  121. {
  122. $data = Probe::uri($url);
  123. if (!empty($data['baseurl'])) {
  124. return $data['baseurl'];
  125. }
  126. // When we can't probe the server, we use some ugly function that does some pattern matching
  127. return PortableContact::detectServer($url);
  128. }
  129. /**
  130. * @brief Returns the contact id for the user and the public contact id for a given contact id
  131. *
  132. * @param int $cid Either public contact id or user's contact id
  133. * @param int $uid User ID
  134. *
  135. * @return array with public and user's contact id
  136. */
  137. public static function getPublicAndUserContacID($cid, $uid)
  138. {
  139. if (empty($uid) || empty($cid)) {
  140. return [];
  141. }
  142. $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
  143. if (!DBA::isResult($contact)) {
  144. return [];
  145. }
  146. // We quit when the user id don't match the user id of the provided contact
  147. if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
  148. return [];
  149. }
  150. if ($contact['uid'] != 0) {
  151. $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
  152. if (empty($pcid)) {
  153. return [];
  154. }
  155. $ucid = $contact['id'];
  156. } else {
  157. $pcid = $contact['id'];
  158. $ucid = Contact::getIdForURL($contact['url'], $uid, true);
  159. }
  160. return ['public' => $pcid, 'user' => $ucid];
  161. }
  162. /**
  163. * @brief Block contact id for user id
  164. *
  165. * @param int $cid Either public contact id or user's contact id
  166. * @param int $uid User ID
  167. * @param boolean $blocked Is the contact blocked or unblocked?
  168. */
  169. public static function setBlockedForUser($cid, $uid, $blocked)
  170. {
  171. $cdata = self::getPublicAndUserContacID($cid, $uid);
  172. if (empty($cdata)) {
  173. return;
  174. }
  175. if ($cdata['user'] != 0) {
  176. DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
  177. }
  178. DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
  179. }
  180. /**
  181. * @brief Returns "block" state for contact id and user id
  182. *
  183. * @param int $cid Either public contact id or user's contact id
  184. * @param int $uid User ID
  185. *
  186. * @return boolean is the contact id blocked for the given user?
  187. */
  188. public static function isBlockedByUser($cid, $uid)
  189. {
  190. $cdata = self::getPublicAndUserContacID($cid, $uid);
  191. if (empty($cdata)) {
  192. return;
  193. }
  194. $public_blocked = false;
  195. if (!empty($cdata['public'])) {
  196. $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
  197. if (DBA::isResult($public_contact)) {
  198. $public_blocked = $public_contact['blocked'];
  199. }
  200. }
  201. $user_blocked = $public_blocked;
  202. if (!empty($cdata['user'])) {
  203. $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
  204. if (DBA::isResult($user_contact)) {
  205. $user_blocked = $user_contact['blocked'];
  206. }
  207. }
  208. if ($user_blocked != $public_blocked) {
  209. DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
  210. }
  211. return $user_blocked;
  212. }
  213. /**
  214. * @brief Ignore contact id for user id
  215. *
  216. * @param int $cid Either public contact id or user's contact id
  217. * @param int $uid User ID
  218. * @param boolean $ignored Is the contact ignored or unignored?
  219. */
  220. public static function setIgnoredForUser($cid, $uid, $ignored)
  221. {
  222. $cdata = self::getPublicAndUserContacID($cid, $uid);
  223. if (empty($cdata)) {
  224. return;
  225. }
  226. if ($cdata['user'] != 0) {
  227. DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
  228. }
  229. DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
  230. }
  231. /**
  232. * @brief Returns "ignore" state for contact id and user id
  233. *
  234. * @param int $cid Either public contact id or user's contact id
  235. * @param int $uid User ID
  236. *
  237. * @return boolean is the contact id ignored for the given user?
  238. */
  239. public static function isIgnoredByUser($cid, $uid)
  240. {
  241. $cdata = self::getPublicAndUserContacID($cid, $uid);
  242. if (empty($cdata)) {
  243. return;
  244. }
  245. $public_ignored = false;
  246. if (!empty($cdata['public'])) {
  247. $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
  248. if (DBA::isResult($public_contact)) {
  249. $public_ignored = $public_contact['ignored'];
  250. }
  251. }
  252. $user_ignored = $public_ignored;
  253. if (!empty($cdata['user'])) {
  254. $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
  255. if (DBA::isResult($user_contact)) {
  256. $user_ignored = $user_contact['readonly'];
  257. }
  258. }
  259. if ($user_ignored != $public_ignored) {
  260. DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
  261. }
  262. return $user_ignored;
  263. }
  264. /**
  265. * @brief Set "collapsed" for contact id and user id
  266. *
  267. * @param int $cid Either public contact id or user's contact id
  268. * @param int $uid User ID
  269. * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
  270. */
  271. public static function setCollapsedForUser($cid, $uid, $collapsed)
  272. {
  273. $cdata = self::getPublicAndUserContacID($cid, $uid);
  274. if (empty($cdata)) {
  275. return;
  276. }
  277. DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
  278. }
  279. /**
  280. * @brief Returns "collapsed" state for contact id and user id
  281. *
  282. * @param int $cid Either public contact id or user's contact id
  283. * @param int $uid User ID
  284. *
  285. * @return boolean is the contact id blocked for the given user?
  286. */
  287. public static function isCollapsedByUser($cid, $uid)
  288. {
  289. $cdata = self::getPublicAndUserContacID($cid, $uid);
  290. if (empty($cdata)) {
  291. return;
  292. }
  293. $collapsed = false;
  294. if (!empty($cdata['public'])) {
  295. $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
  296. if (DBA::isResult($public_contact)) {
  297. $collapsed = $public_contact['collapsed'];
  298. }
  299. }
  300. return $collapsed;
  301. }
  302. /**
  303. * @brief Returns a list of contacts belonging in a group
  304. *
  305. * @param int $gid
  306. * @return array
  307. */
  308. public static function getByGroupId($gid)
  309. {
  310. $return = [];
  311. if (intval($gid)) {
  312. $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
  313. FROM `contact`
  314. INNER JOIN `group_member`
  315. ON `contact`.`id` = `group_member`.`contact-id`
  316. WHERE `gid` = ?
  317. AND `contact`.`uid` = ?
  318. AND NOT `contact`.`self`
  319. AND NOT `contact`.`blocked`
  320. AND NOT `contact`.`pending`
  321. ORDER BY `contact`.`name` ASC',
  322. $gid,
  323. local_user()
  324. );
  325. if (DBA::isResult($stmt)) {
  326. $return = DBA::toArray($stmt);
  327. }
  328. }
  329. return $return;
  330. }
  331. /**
  332. * @brief Returns the count of OStatus contacts in a group
  333. *
  334. * @param int $gid
  335. * @return int
  336. */
  337. public static function getOStatusCountByGroupId($gid)
  338. {
  339. $return = 0;
  340. if (intval($gid)) {
  341. $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
  342. FROM `contact`
  343. INNER JOIN `group_member`
  344. ON `contact`.`id` = `group_member`.`contact-id`
  345. WHERE `gid` = ?
  346. AND `contact`.`uid` = ?
  347. AND `contact`.`network` = ?
  348. AND `contact`.`notify` != ""',
  349. $gid,
  350. local_user(),
  351. Protocol::OSTATUS
  352. );
  353. $return = $contacts['count'];
  354. }
  355. return $return;
  356. }
  357. /**
  358. * Creates the self-contact for the provided user id
  359. *
  360. * @param int $uid
  361. * @return bool Operation success
  362. */
  363. public static function createSelfFromUserId($uid)
  364. {
  365. // Only create the entry if it doesn't exist yet
  366. if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
  367. return true;
  368. }
  369. $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
  370. if (!DBA::isResult($user)) {
  371. return false;
  372. }
  373. $return = DBA::insert('contact', [
  374. 'uid' => $user['uid'],
  375. 'created' => DateTimeFormat::utcNow(),
  376. 'self' => 1,
  377. 'name' => $user['username'],
  378. 'nick' => $user['nickname'],
  379. 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
  380. 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
  381. 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
  382. 'blocked' => 0,
  383. 'pending' => 0,
  384. 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
  385. 'nurl' => Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']),
  386. 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
  387. 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
  388. 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
  389. 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
  390. 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
  391. 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
  392. 'name-date' => DateTimeFormat::utcNow(),
  393. 'uri-date' => DateTimeFormat::utcNow(),
  394. 'avatar-date' => DateTimeFormat::utcNow(),
  395. 'closeness' => 0
  396. ]);
  397. return $return;
  398. }
  399. /**
  400. * Updates the self-contact for the provided user id
  401. *
  402. * @param int $uid
  403. * @param boolean $update_avatar Force the avatar update
  404. */
  405. public static function updateSelfFromUserID($uid, $update_avatar = false)
  406. {
  407. $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
  408. 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl',
  409. 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
  410. $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
  411. if (!DBA::isResult($self)) {
  412. return;
  413. }
  414. $fields = ['nickname', 'page-flags', 'account-type'];
  415. $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
  416. if (!DBA::isResult($user)) {
  417. return;
  418. }
  419. $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
  420. 'country-name', 'gender', 'pub_keywords', 'xmpp'];
  421. $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
  422. if (!DBA::isResult($profile)) {
  423. return;
  424. }
  425. $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
  426. 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
  427. 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
  428. 'gender' => $profile['gender'], 'avatar' => $profile['photo'],
  429. 'contact-type' => $user['account-type'], 'xmpp' => $profile['xmpp']];
  430. $avatar = DBA::selectFirst('photo', ['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
  431. if (DBA::isResult($avatar)) {
  432. if ($update_avatar) {
  433. $fields['avatar-date'] = DateTimeFormat::utcNow();
  434. }
  435. // Creating the path to the avatar, beginning with the file suffix
  436. $types = Image::supportedTypes();
  437. if (isset($types[$avatar['type']])) {
  438. $file_suffix = $types[$avatar['type']];
  439. } else {
  440. $file_suffix = 'jpg';
  441. }
  442. // We are adding a timestamp value so that other systems won't use cached content
  443. $timestamp = strtotime($fields['avatar-date']);
  444. $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
  445. $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
  446. $fields['photo'] = $prefix . '4' . $suffix;
  447. $fields['thumb'] = $prefix . '5' . $suffix;
  448. $fields['micro'] = $prefix . '6' . $suffix;
  449. } else {
  450. // We hadn't found a photo entry, so we use the default avatar
  451. $fields['photo'] = System::baseUrl() . '/images/person-300.jpg';
  452. $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
  453. $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
  454. }
  455. $fields['forum'] = $user['page-flags'] == self::PAGE_COMMUNITY;
  456. $fields['prv'] = $user['page-flags'] == self::PAGE_PRVGROUP;
  457. // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
  458. $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
  459. $fields['nurl'] = Strings::normaliseLink($fields['url']);
  460. $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
  461. $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
  462. $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
  463. $fields['poll'] = System::baseUrl() . '/dfrn_poll/'. $user['nickname'];
  464. $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
  465. $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
  466. $update = false;
  467. foreach ($fields as $field => $content) {
  468. if ($self[$field] != $content) {
  469. $update = true;
  470. }
  471. }
  472. if ($update) {
  473. $fields['name-date'] = DateTimeFormat::utcNow();
  474. DBA::update('contact', $fields, ['id' => $self['id']]);
  475. // Update the public contact as well
  476. DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
  477. // Update the profile
  478. $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.jpg',
  479. 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.jpg'];
  480. DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
  481. }
  482. }
  483. /**
  484. * @brief Marks a contact for removal
  485. *
  486. * @param int $id contact id
  487. * @return null
  488. */
  489. public static function remove($id)
  490. {
  491. // We want just to make sure that we don't delete our "self" contact
  492. $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
  493. if (!DBA::isResult($contact) || !intval($contact['uid'])) {
  494. return;
  495. }
  496. // Archive the contact
  497. DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
  498. // Delete it in the background
  499. Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
  500. }
  501. /**
  502. * @brief Sends an unfriend message. Does not remove the contact
  503. *
  504. * @param array $user User unfriending
  505. * @param array $contact Contact unfriended
  506. * @param boolean $dissolve Remove the contact on the remote side
  507. * @return void
  508. */
  509. public static function terminateFriendship(array $user, array $contact, $dissolve = false)
  510. {
  511. if (($contact['network'] == Protocol::DFRN) && $dissolve) {
  512. DFRN::deliver($user, $contact, 'placeholder', true);
  513. } elseif (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
  514. // create an unfollow slap
  515. $item = [];
  516. $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
  517. $item['follow'] = $contact["url"];
  518. $item['body'] = '';
  519. $item['title'] = '';
  520. $item['guid'] = '';
  521. $item['tag'] = '';
  522. $item['attach'] = '';
  523. $slap = OStatus::salmon($item, $user);
  524. if (!empty($contact['notify'])) {
  525. Salmon::slapper($user, $contact['notify'], $slap);
  526. }
  527. } elseif ($contact['network'] == Protocol::DIASPORA) {
  528. Diaspora::sendUnshare($user, $contact);
  529. } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
  530. ActivityPub\Transmitter::sendContactUndo($contact['url'], $user['uid']);
  531. if ($dissolve) {
  532. ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
  533. }
  534. }
  535. }
  536. /**
  537. * @brief Marks a contact for archival after a communication issue delay
  538. *
  539. * Contact has refused to recognise us as a friend. We will start a countdown.
  540. * If they still don't recognise us in 32 days, the relationship is over,
  541. * and we won't waste any more time trying to communicate with them.
  542. * This provides for the possibility that their database is temporarily messed
  543. * up or some other transient event and that there's a possibility we could recover from it.
  544. *
  545. * @param array $contact contact to mark for archival
  546. * @return null
  547. */
  548. public static function markForArchival(array $contact)
  549. {
  550. if (!isset($contact['url']) && !empty($contact['id'])) {
  551. $fields = ['id', 'url', 'archive', 'self', 'term-date'];
  552. $contact = DBA::selectFirst('contact', [], ['id' => $contact['id']]);
  553. if (!DBA::isResult($contact)) {
  554. return;
  555. }
  556. } elseif (!isset($contact['url'])) {
  557. Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
  558. }
  559. // Contact already archived or "self" contact? => nothing to do
  560. if ($contact['archive'] || $contact['self']) {
  561. return;
  562. }
  563. if ($contact['term-date'] <= DBA::NULL_DATETIME) {
  564. DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
  565. DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
  566. } else {
  567. /* @todo
  568. * We really should send a notification to the owner after 2-3 weeks
  569. * so they won't be surprised when the contact vanishes and can take
  570. * remedial action if this was a serious mistake or glitch
  571. */
  572. /// @todo Check for contact vitality via probing
  573. $archival_days = Config::get('system', 'archival_days', 32);
  574. $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
  575. if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
  576. /* Relationship is really truly dead. archive them rather than
  577. * delete, though if the owner tries to unarchive them we'll start
  578. * the whole process over again.
  579. */
  580. DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
  581. DBA::update('contact', ['archive' => 1], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
  582. }
  583. }
  584. }
  585. /**
  586. * @brief Cancels the archival countdown
  587. *
  588. * @see Contact::markForArchival()
  589. *
  590. * @param array $contact contact to be unmarked for archival
  591. * @return null
  592. */
  593. public static function unmarkForArchival(array $contact)
  594. {
  595. $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
  596. $exists = DBA::exists('contact', $condition);
  597. // We don't need to update, we never marked this contact for archival
  598. if (!$exists) {
  599. return;
  600. }
  601. if (!isset($contact['url']) && !empty($contact['id'])) {
  602. $fields = ['id', 'url', 'batch'];
  603. $contact = DBA::selectFirst('contact', [], ['id' => $contact['id']]);
  604. if (!DBA::isResult($contact)) {
  605. return;
  606. }
  607. }
  608. // It's a miracle. Our dead contact has inexplicably come back to life.
  609. $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
  610. DBA::update('contact', $fields, ['id' => $contact['id']]);
  611. DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
  612. if (!empty($contact['batch'])) {
  613. $condition = ['batch' => $contact['batch'], 'contact-type' => self::ACCOUNT_TYPE_RELAY];
  614. DBA::update('contact', $fields, $condition);
  615. }
  616. }
  617. /**
  618. * @brief Get contact data for a given profile link
  619. *
  620. * The function looks at several places (contact table and gcontact table) for the contact
  621. * It caches its result for the same script execution to prevent duplicate calls
  622. *
  623. * @param string $url The profile link
  624. * @param int $uid User id
  625. * @param array $default If not data was found take this data as default value
  626. *
  627. * @return array Contact data
  628. */
  629. public static function getDetailsByURL($url, $uid = -1, array $default = [])
  630. {
  631. static $cache = [];
  632. if ($url == '') {
  633. return $default;
  634. }
  635. if ($uid == -1) {
  636. $uid = local_user();
  637. }
  638. if (isset($cache[$url][$uid])) {
  639. return $cache[$url][$uid];
  640. }
  641. $ssl_url = str_replace('http://', 'https://', $url);
  642. // Fetch contact data from the contact table for the given user
  643. $s = DBA::p("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
  644. `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
  645. FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
  646. $r = DBA::toArray($s);
  647. // Fetch contact data from the contact table for the given user, checking with the alias
  648. if (!DBA::isResult($r)) {
  649. $s = DBA::p("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
  650. `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
  651. FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
  652. $r = DBA::toArray($s);
  653. }
  654. // Fetch the data from the contact table with "uid=0" (which is filled automatically)
  655. if (!DBA::isResult($r)) {
  656. $s = DBA::p("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
  657. `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
  658. FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
  659. $r = DBA::toArray($s);
  660. }
  661. // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
  662. if (!DBA::isResult($r)) {
  663. $s = DBA::p("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
  664. `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
  665. FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
  666. $r = DBA::toArray($s);
  667. }
  668. // Fetch the data from the gcontact table
  669. if (!DBA::isResult($r)) {
  670. $s = DBA::p("SELECT 0 AS `id`, 0 AS `cid`, `id` AS `gid`, 0 AS `zid`, 0 AS `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, '' AS `xmpp`,
  671. `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
  672. FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
  673. $r = DBA::toArray($s);
  674. }
  675. if (DBA::isResult($r)) {
  676. // If there is more than one entry we filter out the connector networks
  677. if (count($r) > 1) {
  678. foreach ($r as $id => $result) {
  679. if ($result["network"] == Protocol::STATUSNET) {
  680. unset($r[$id]);
  681. }
  682. }
  683. }
  684. $profile = array_shift($r);
  685. // "bd" always contains the upcoming birthday of a contact.
  686. // "birthday" might contain the birthday including the year of birth.
  687. if ($profile["birthday"] > DBA::NULL_DATE) {
  688. $bd_timestamp = strtotime($profile["birthday"]);
  689. $month = date("m", $bd_timestamp);
  690. $day = date("d", $bd_timestamp);
  691. $current_timestamp = time();
  692. $current_year = date("Y", $current_timestamp);
  693. $current_month = date("m", $current_timestamp);
  694. $current_day = date("d", $current_timestamp);
  695. $profile["bd"] = $current_year . "-" . $month . "-" . $day;
  696. $current = $current_year . "-" . $current_month . "-" . $current_day;
  697. if ($profile["bd"] < $current) {
  698. $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
  699. }
  700. } else {
  701. $profile["bd"] = DBA::NULL_DATE;
  702. }
  703. } else {
  704. $profile = $default;
  705. }
  706. if (empty($profile["photo"]) && isset($default["photo"])) {
  707. $profile["photo"] = $default["photo"];
  708. }
  709. if (empty($profile["name"]) && isset($default["name"])) {
  710. $profile["name"] = $default["name"];
  711. }
  712. if (empty($profile["network"]) && isset($default["network"])) {
  713. $profile["network"] = $default["network"];
  714. }
  715. if (empty($profile["thumb"]) && isset($profile["photo"])) {
  716. $profile["thumb"] = $profile["photo"];
  717. }
  718. if (empty($profile["micro"]) && isset($profile["thumb"])) {
  719. $profile["micro"] = $profile["thumb"];
  720. }
  721. if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
  722. && in_array($profile["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])
  723. ) {
  724. Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
  725. }
  726. // Show contact details of Diaspora contacts only if connected
  727. if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
  728. $profile["location"] = "";
  729. $profile["about"] = "";
  730. $profile["gender"] = "";
  731. $profile["birthday"] = DBA::NULL_DATE;
  732. }
  733. $cache[$url][$uid] = $profile;
  734. return $profile;
  735. }
  736. /**
  737. * @brief Get contact data for a given address
  738. *
  739. * The function looks at several places (contact table and gcontact table) for the contact
  740. *
  741. * @param string $addr The profile link
  742. * @param int $uid User id
  743. *
  744. * @return array Contact data
  745. */
  746. public static function getDetailsByAddr($addr, $uid = -1)
  747. {
  748. static $cache = [];
  749. if ($addr == '') {
  750. return [];
  751. }
  752. if ($uid == -1) {
  753. $uid = local_user();
  754. }
  755. // Fetch contact data from the contact table for the given user
  756. $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
  757. `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
  758. FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
  759. DBA::escape($addr),
  760. intval($uid)
  761. );
  762. // Fetch the data from the contact table with "uid=0" (which is filled automatically)
  763. if (!DBA::isResult($r)) {
  764. $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
  765. `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
  766. FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
  767. DBA::escape($addr)
  768. );
  769. }
  770. // Fetch the data from the gcontact table
  771. if (!DBA::isResult($r)) {
  772. $r = q("SELECT 0 AS `id`, 0 AS `cid`, `id` AS `gid`, 0 AS `zid`, 0 AS `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, '' AS `xmpp`,
  773. `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
  774. FROM `gcontact` WHERE `addr` = '%s'",
  775. DBA::escape($addr)
  776. );
  777. }
  778. if (!DBA::isResult($r)) {
  779. $data = Probe::uri($addr);
  780. $profile = self::getDetailsByURL($data['url'], $uid);
  781. } else {
  782. $profile = $r[0];
  783. }
  784. return $profile;
  785. }
  786. /**
  787. * @brief Returns the data array for the photo menu of a given contact
  788. *
  789. * @param array $contact contact
  790. * @param int $uid optional, default 0
  791. * @return array
  792. */
  793. public static function photoMenu(array $contact, $uid = 0)
  794. {
  795. // @todo Unused, to be removed
  796. $a = get_app();
  797. $contact_url = '';
  798. $pm_url = '';
  799. $status_link = '';
  800. $photos_link = '';
  801. $posts_link = '';
  802. $contact_drop_link = '';
  803. $poke_link = '';
  804. if ($uid == 0) {
  805. $uid = local_user();
  806. }
  807. if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
  808. if ($uid == 0) {
  809. $profile_link = self::magicLink($contact['url']);
  810. $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
  811. return $menu;
  812. }
  813. // Look for our own contact if the uid doesn't match and isn't public
  814. $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
  815. if (DBA::isResult($contact_own)) {
  816. return self::photoMenu($contact_own, $uid);
  817. }
  818. }
  819. $sparkle = false;
  820. if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
  821. $sparkle = true;
  822. $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
  823. } else {
  824. $profile_link = $contact['url'];
  825. }
  826. if ($profile_link === 'mailbox') {
  827. $profile_link = '';
  828. }
  829. if ($sparkle) {
  830. $status_link = $profile_link . '?url=status';
  831. $photos_link = $profile_link . '?url=photos';
  832. $profile_link = $profile_link . '?url=profile';
  833. }
  834. if (in_array($contact['network'], [Protocol::DFRN, Protocol::DIASPORA]) && !$contact['self']) {
  835. $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
  836. }
  837. if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
  838. $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
  839. }
  840. $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
  841. $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
  842. if (!$contact['self']) {
  843. $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
  844. }
  845. /**
  846. * Menu array:
  847. * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
  848. */
  849. if (empty($contact['uid'])) {
  850. $connlnk = 'follow/?url=' . $contact['url'];
  851. $menu = [
  852. 'profile' => [L10n::t('View Profile'), $profile_link, true],
  853. 'network' => [L10n::t('Network Posts'), $posts_link, false],
  854. 'edit' => [L10n::t('View Contact'), $contact_url, false],
  855. 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
  856. ];
  857. } else {
  858. $menu = [
  859. 'status' => [L10n::t('View Status'), $status_link, true],
  860. 'profile' => [L10n::t('View Profile'), $profile_link, true],
  861. 'photos' => [L10n::t('View Photos'), $photos_link, true],
  862. 'network' => [L10n::t('Network Posts'), $posts_link, false],
  863. 'edit' => [L10n::t('View Contact'), $contact_url, false],
  864. 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
  865. 'pm' => [L10n::t('Send PM'), $pm_url, false],
  866. 'poke' => [L10n::t('Poke'), $poke_link, false],
  867. ];
  868. }
  869. $args = ['contact' => $contact, 'menu' => &$menu];
  870. Addon::callHooks('contact_photo_menu', $args);
  871. $menucondensed = [];
  872. foreach ($menu as $menuname => $menuitem) {
  873. if ($menuitem[1] != '') {
  874. $menucondensed[$menuname] = $menuitem;
  875. }
  876. }
  877. return $menucondensed;
  878. }
  879. /**
  880. * @brief Returns ungrouped contact count or list for user
  881. *
  882. * Returns either the total number of ungrouped contacts for the given user
  883. * id or a paginated list of ungrouped contacts.
  884. *
  885. * @param int $uid uid
  886. * @param int $start optional, default 0
  887. * @param int $count optional, default 0
  888. *
  889. * @return array
  890. */
  891. public static function getUngroupedList($uid)
  892. {
  893. return q("SELECT *
  894. FROM `contact`
  895. WHERE `uid` = %d
  896. AND NOT `self`
  897. AND NOT `blocked`
  898. AND NOT `pending`
  899. AND `id` NOT IN (
  900. SELECT DISTINCT(`contact-id`)
  901. FROM `group_member`
  902. INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
  903. WHERE `group`.`uid` = %d
  904. )", intval($uid), intval($uid));
  905. }
  906. /**
  907. * @brief Fetch the contact id for a given URL and user
  908. *
  909. * First lookup in the contact table to find a record matching either `url`, `nurl`,
  910. * `addr` or `alias`.
  911. *
  912. * If there's no record and we aren't looking for a public contact, we quit.
  913. * If there's one, we check that it isn't time to update the picture else we
  914. * directly return the found contact id.
  915. *
  916. * Second, we probe the provided $url whether it's http://server.tld/profile or
  917. * nick@server.tld. We quit if we can't get any info back.
  918. *
  919. * Third, we create the contact record if it doesn't exist
  920. *
  921. * Fourth, we update the existing record with the new data (avatar, alias, nick)
  922. * if there's any updates
  923. *
  924. * @param string $url Contact URL
  925. * @param integer $uid The user id for the contact (0 = public contact)
  926. * @param boolean $no_update Don't update the contact
  927. * @param array $default Default value for creating the contact when every else fails
  928. * @param boolean $in_loop Internally used variable to prevent an endless loop
  929. *
  930. * @return integer Contact ID
  931. */
  932. public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
  933. {
  934. Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
  935. $contact_id = 0;
  936. if ($url == '') {
  937. return 0;
  938. }
  939. /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
  940. // We first try the nurl (http://server.tld/nick), most common case
  941. $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false]);
  942. // Then the addr (nick@server.tld)
  943. if (!DBA::isResult($contact)) {
  944. $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['addr' => $url, 'uid' => $uid, 'deleted' => false]);
  945. }
  946. // Then the alias (which could be anything)
  947. if (!DBA::isResult($contact)) {
  948. // The link could be provided as http although we stored it as https
  949. $ssl_url = str_replace('http://', 'https://', $url);
  950. $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
  951. $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
  952. }
  953. if (DBA::isResult($contact)) {
  954. $contact_id = $contact["id"];
  955. // Update the contact every 7 days
  956. $update_contact = ($contact['avatar-date'] < DateTimeFormat::utc('now -7 days'));
  957. // We force the update if the avatar is empty
  958. if (empty($contact['avatar'])) {
  959. $update_contact = true;
  960. }
  961. if (!$update_contact || $no_update) {
  962. return $contact_id;
  963. }
  964. } elseif ($uid != 0) {
  965. // Non-existing user-specific contact, exiting
  966. return 0;
  967. }
  968. // When we don't want to update, we look if some of our users already know this contact
  969. if ($no_update) {
  970. $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
  971. 'photo', 'keywords', 'location', 'about', 'network',
  972. 'priority', 'batch', 'request', 'confirm', 'poco'];
  973. $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
  974. if (DBA::isResult($data)) {
  975. // For security reasons we don't fetch key data from our users
  976. $data["pubkey"] = '';
  977. }
  978. } else {
  979. $data = [];
  980. }
  981. if (empty($data)) {
  982. $data = Probe::uri($url, "", $uid);
  983. // Ensure that there is a gserver entry
  984. if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
  985. PortableContact::checkServer($data['baseurl']);
  986. }
  987. }
  988. // Last try in gcontact for unsupported networks
  989. if (!in_array($data["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
  990. if ($uid != 0) {
  991. return 0;
  992. }
  993. // Get data from the gcontact table
  994. $fields = ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'];
  995. $contact = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
  996. if (!DBA::isResult($contact)) {
  997. $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
  998. }
  999. if (!DBA::isResult($contact)) {
  1000. $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
  1001. 'photo', 'keywords', 'location', 'about', 'network',
  1002. 'priority', 'batch', 'request', 'confirm', 'poco'];
  1003. $contact = DBA::selectFirst('contact', $fields, ['addr' => $url]);
  1004. }
  1005. if (!DBA::isResult($contact)) {
  1006. // The link could be provided as http although we stored it as https
  1007. $ssl_url = str_replace('http://', 'https://', $url);
  1008. $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
  1009. $contact = DBA::selectFirst('contact', $fields, $condition);
  1010. }
  1011. if (!DBA::isResult($contact)) {
  1012. $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
  1013. 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
  1014. $condition = ['url' => [$url, Strings::normaliseLink($url), $ssl_url]];
  1015. $contact = DBA::selectFirst('fcontact', $fields, $condition);
  1016. }
  1017. if (!empty($default)) {
  1018. $contact = $default;
  1019. }
  1020. if (!DBA::isResult($contact)) {
  1021. return 0;
  1022. } else {
  1023. $data = array_merge($data, $contact);
  1024. }
  1025. }
  1026. if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url) && !$in_loop) {
  1027. $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
  1028. }
  1029. $url = $data["url"];
  1030. if (!$contact_id) {
  1031. $fields = [
  1032. 'uid' => $uid,
  1033. 'created' => DateTimeFormat::utcNow(),
  1034. 'url' => $data["url"],
  1035. 'nurl' => Strings::normaliseLink($data["url"]),
  1036. 'addr' => $data["addr"],
  1037. 'alias' => $data["alias"],
  1038. 'notify' => $data["notify"],
  1039. 'poll' => $data["poll"],
  1040. 'name' => $data["name"],
  1041. 'nick' => $data["nick"],
  1042. 'photo' => $data["photo"],
  1043. 'keywords' => $data["keywords"],
  1044. 'location' => $data["location"],
  1045. 'about' => $data["about"],
  1046. 'network' => $data["network"],
  1047. 'pubkey' => $data["pubkey"],
  1048. 'rel' => self::SHARING,
  1049. 'priority' => $data["priority"],
  1050. 'batch' => $data["batch"],
  1051. 'request' => $data["request"],
  1052. 'confirm' => $data["confirm"],
  1053. 'poco' => $data["poco"],
  1054. 'name-date' => DateTimeFormat::utcNow(),
  1055. 'uri-date' => DateTimeFormat::utcNow(),
  1056. 'avatar-date' => DateTimeFormat::utcNow(),
  1057. 'writable' => 1,
  1058. 'blocked' => 0,
  1059. 'readonly' => 0,
  1060. 'pending' => 0];
  1061. $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
  1062. DBA::update('contact', $fields, $condition, true);
  1063. $s = DBA::select('contact', ['id'], $condition, ['order' => ['id'], 'limit' => 2]);
  1064. $contacts = DBA::toArray($s);
  1065. if (!DBA::isResult($contacts)) {
  1066. return 0;
  1067. }
  1068. $contact_id = $contacts[0]["id"];
  1069. // Update the newly created contact from data in the gcontact table
  1070. $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => Strings::normaliseLink($data["url"])]);
  1071. if (DBA::isResult($gcontact)) {
  1072. // Only use the information when the probing hadn't fetched these values
  1073. if ($data['keywords'] != '') {
  1074. unset($gcontact['keywords']);
  1075. }
  1076. if ($data['location'] != '') {
  1077. unset($gcontact['location']);
  1078. }
  1079. if ($data['about'] != '') {
  1080. unset($gcontact['about']);
  1081. }
  1082. DBA::update('contact', $gcontact, ['id' => $contact_id]);
  1083. }
  1084. if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
  1085. $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self`",
  1086. Strings::normaliseLink($data["url"]), 0, $contact_id];
  1087. Logger::log('Deleting duplicate contact ' . json_encode($condition), Logger::DEBUG);
  1088. DBA::delete('contact', $condition);
  1089. }
  1090. }
  1091. self::updateAvatar($data["photo"], $uid, $contact_id);
  1092. $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
  1093. $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
  1094. // This condition should always be true
  1095. if (!DBA::isResult($contact)) {
  1096. return $contact_id;
  1097. }
  1098. $updated = ['addr' => $data['addr'],
  1099. 'alias' => $data['alias'],
  1100. 'url' => $data['url'],
  1101. 'nurl' => Strings::normaliseLink($data['url']),
  1102. 'name' => $data['name'],
  1103. 'nick' => $data['nick']];
  1104. if ($data['keywords'] != '') {
  1105. $updated['keywords'] = $data['keywords'];
  1106. }
  1107. if ($data['location'] != '') {
  1108. $updated['location'] = $data['location'];
  1109. }
  1110. // Update the technical stuff as well - if filled
  1111. if ($data['notify'] != '') {
  1112. $updated['notify'] = $data['notify'];
  1113. }
  1114. if ($data['poll'] != '') {
  1115. $updated['poll'] = $data['poll'];
  1116. }
  1117. if ($data['batch'] != '') {
  1118. $updated['batch'] = $data['batch'];
  1119. }
  1120. if ($data['request'] != '') {
  1121. $updated['request'] = $data['request'];
  1122. }
  1123. if ($data['confirm'] != '') {
  1124. $updated['confirm'] = $data['confirm'];
  1125. }
  1126. if ($data['poco'] != '') {
  1127. $updated['poco'] = $data['poco'];
  1128. }
  1129. // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
  1130. if (empty($contact['pubkey'])) {
  1131. $updated['pubkey'] = $data['pubkey'];
  1132. }
  1133. if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
  1134. $updated['uri-date'] = DateTimeFormat::utcNow();
  1135. }
  1136. if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
  1137. $updated['name-date'] = DateTimeFormat::utcNow();
  1138. }
  1139. $updated['avatar-date'] = DateTimeFormat::utcNow();
  1140. DBA::update('contact', $updated, ['id' => $contact_id], $contact);
  1141. return $contact_id;
  1142. }
  1143. /**
  1144. * @brief Checks if the contact is blocked
  1145. *
  1146. * @param int $cid contact id
  1147. *
  1148. * @return boolean Is the contact blocked?
  1149. */
  1150. public static function isBlocked($cid)
  1151. {
  1152. if ($cid == 0) {
  1153. return false;
  1154. }
  1155. $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
  1156. if (!DBA::isResult($blocked)) {
  1157. return false;
  1158. }
  1159. if (Network::isUrlBlocked($blocked['url'])) {
  1160. return true;
  1161. }
  1162. return (bool) $blocked['blocked'];
  1163. }
  1164. /**
  1165. * @brief Checks if the contact is hidden
  1166. *
  1167. * @param int $cid contact id
  1168. *
  1169. * @return boolean Is the contact hidden?
  1170. */
  1171. public static function isHidden($cid)
  1172. {
  1173. if ($cid == 0) {
  1174. return false;
  1175. }
  1176. $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
  1177. if (!DBA::isResult($hidden)) {
  1178. return false;
  1179. }
  1180. return (bool) $hidden['hidden'];
  1181. }
  1182. /**
  1183. * @brief Returns posts from a given contact url
  1184. *
  1185. * @param string $contact_url Contact URL
  1186. *
  1187. * @return string posts in HTML
  1188. */
  1189. public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
  1190. {
  1191. $a = self::getApp();
  1192. $cid = Self::getIdForURL($contact_url);
  1193. $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
  1194. if (!DBA::isResult($contact)) {
  1195. return '';
  1196. }
  1197. if (in_array($contact["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
  1198. $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
  1199. } else {
  1200. $sql = "`item`.`uid` = ?";
  1201. }
  1202. $contact_field = ($contact["contact-type"] == self::ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
  1203. if ($thread_mode) {
  1204. $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
  1205. $cid, GRAVITY_PARENT, local_user()];
  1206. } else {
  1207. $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
  1208. $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
  1209. }
  1210. $pager = new Pager($a->query_string);
  1211. $params = ['order' => ['created' => true],
  1212. 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
  1213. if ($thread_mode) {
  1214. $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
  1215. $items = Item::inArray($r);
  1216. $o = conversation($a, $items, $pager, 'contacts', $update);
  1217. } else {
  1218. $r = Item::selectForUser(local_user(), [], $condition, $params);
  1219. $items = Item::inArray($r);
  1220. $o = conversation($a, $items, $pager, 'contact-posts', false);
  1221. }
  1222. if (!$update) {
  1223. $o .= $pager->renderMinimal(count($items));
  1224. }
  1225. return $o;
  1226. }
  1227. /**
  1228. * @brief Returns the account type name
  1229. *
  1230. * The function can be called with either the user or the contact array
  1231. *
  1232. * @param array $contact contact or user array
  1233. * @return string
  1234. */
  1235. public static function getAccountType(array $contact)
  1236. {
  1237. // There are several fields that indicate that the contact or user is a forum
  1238. // "page-flags" is a field in the user table,
  1239. // "forum" and "prv" are used in the contact table. They stand for self::PAGE_COMMUNITY and self::PAGE_PRVGROUP.
  1240. // "community" is used in the gcontact table and is true if the contact is self::PAGE_COMMUNITY or self::PAGE_PRVGROUP.
  1241. if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_COMMUNITY))
  1242. || (isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_PRVGROUP))
  1243. || (isset($contact['forum']) && intval($contact['forum']))
  1244. || (isset($contact['prv']) && intval($contact['prv']))
  1245. || (isset($contact['community']) && intval($contact['community']))
  1246. ) {
  1247. $type = self::ACCOUNT_TYPE_COMMUNITY;
  1248. } else {
  1249. $type = self::ACCOUNT_TYPE_PERSON;
  1250. }
  1251. // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
  1252. if (isset($contact["contact-type"])) {
  1253. $type = $contact["contact-type"];
  1254. }
  1255. if (isset($contact["account-type"])) {
  1256. $type = $contact["account-type"];
  1257. }
  1258. switch ($type) {
  1259. case self::ACCOUNT_TYPE_ORGANISATION:
  1260. $account_type = L10n::t("Organisation");
  1261. break;
  1262. case self::ACCOUNT_TYPE_NEWS:
  1263. $account_type = L10n::t('News');
  1264. break;
  1265. case self::ACCOUNT_TYPE_COMMUNITY:
  1266. $account_type = L10n::t("Forum");
  1267. break;
  1268. default:
  1269. $account_type = "";
  1270. break;
  1271. }
  1272. return $account_type;
  1273. }
  1274. /**
  1275. * @brief Blocks a contact
  1276. *
  1277. * @param int $uid
  1278. * @return bool
  1279. */
  1280. public static function block($uid)
  1281. {
  1282. $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
  1283. return $return;
  1284. }
  1285. /**
  1286. * @brief Unblocks a contact
  1287. *
  1288. * @param int $uid
  1289. * @return bool
  1290. */
  1291. public static function unblock($uid)
  1292. {
  1293. $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
  1294. return $return;
  1295. }
  1296. /**
  1297. * @brief Updates the avatar links in a contact only if needed
  1298. *
  1299. * @param string $avatar Link to avatar picture
  1300. * @param int $uid User id of contact owner
  1301. * @param int $cid Contact id
  1302. * @param bool $force force picture update
  1303. *
  1304. * @return array Returns array of the different avatar sizes
  1305. */
  1306. public static function updateAvatar($avatar, $uid, $cid, $force = false)
  1307. {
  1308. $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
  1309. if (!DBA::isResult($contact)) {
  1310. return false;
  1311. } else {
  1312. $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
  1313. }
  1314. if (($contact["avatar"] != $avatar) || $force) {
  1315. $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
  1316. if ($photos) {
  1317. DBA::update(
  1318. 'contact',
  1319. ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
  1320. ['id' => $cid]
  1321. );
  1322. // Update the public contact (contact id = 0)
  1323. if ($uid != 0) {
  1324. $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
  1325. if (DBA::isResult($pcontact)) {
  1326. self::updateAvatar($avatar, 0, $pcontact['id'], $force);
  1327. }
  1328. }
  1329. return $photos;
  1330. }
  1331. }
  1332. return $data;
  1333. }
  1334. /**
  1335. * @param integer $id contact id
  1336. * @param string $network Optional network we are probing for
  1337. * @return boolean
  1338. */
  1339. public static function updateFromProbe($id, $network = '')
  1340. {
  1341. /*
  1342. Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
  1343. This will reliably kill your communication with Friendica contacts.
  1344. */
  1345. $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
  1346. $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
  1347. if (!DBA::isResult($contact)) {
  1348. return false;
  1349. }
  1350. $ret = Probe::uri($contact["url"], $network);
  1351. // If Probe::uri fails the network code will be different
  1352. if (($ret["network"] != $contact["network"]) && !in_array($ret["network"], [Protocol::ACTIVITYPUB, $network])) {
  1353. return false;
  1354. }
  1355. $update = false;
  1356. // make sure to not overwrite existing values with blank entries
  1357. foreach ($ret as $key => $val) {
  1358. if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
  1359. $ret[$key] = $contact[$key];
  1360. }
  1361. if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
  1362. $update = true;
  1363. }
  1364. }
  1365. if (!$update) {
  1366. return true;
  1367. }
  1368. DBA::update(
  1369. 'contact', [
  1370. 'url' => $ret['url'],
  1371. 'nurl' => Strings::normaliseLink($ret['url']),
  1372. 'network' => $ret['network'],
  1373. 'addr' => $ret['addr'],
  1374. 'alias' => $ret['alias'],
  1375. 'batch' => $ret['batch'],
  1376. 'notify' => $ret['notify'],
  1377. 'poll' => $ret['poll'],
  1378. 'poco' => $ret['poco']
  1379. ],
  1380. ['id' => $id]
  1381. );
  1382. // Update the corresponding gcontact entry
  1383. PortableContact::lastUpdated($ret["url"]);
  1384. return true;
  1385. }
  1386. /**
  1387. * Takes a $uid and a url/handle and adds a new contact
  1388. * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
  1389. * dfrn_request page.
  1390. *
  1391. * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
  1392. *
  1393. * Returns an array
  1394. * $return['success'] boolean true if successful
  1395. * $return['message'] error text if success is false.
  1396. *
  1397. * @brief Takes a $uid and a url/handle and adds a new contact
  1398. * @param int $uid
  1399. * @param string $url
  1400. * @param bool $interactive
  1401. * @param string $network
  1402. * @return boolean|string
  1403. */
  1404. public static function createFromProbe($uid, $url, $interactive = false, $network = '')
  1405. {
  1406. $result = ['cid' => -1, 'success' => false, 'message' => ''];
  1407. $a = get_app();
  1408. // remove ajax junk, e.g. Twitter
  1409. $url = str_replace('/#!/', '/', $url);
  1410. if (!Network::isUrlAllowed($url)) {
  1411. $result['message'] = L10n::t('Disallowed profile URL.');
  1412. return $result;
  1413. }
  1414. if (Network::isUrlBlocked($url)) {
  1415. $result['message'] = L10n::t('Blocked domain');
  1416. return $result;
  1417. }
  1418. if (!$url) {
  1419. $result['message'] = L10n::t('Connect URL missing.');
  1420. return $result;
  1421. }
  1422. $arr = ['url' => $url, 'contact' => []];
  1423. Hook::callAll('follow', $arr);
  1424. if (empty($arr)) {
  1425. $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
  1426. return $result;
  1427. }
  1428. if (!empty($arr['contact']['name'])) {
  1429. $ret = $arr['contact'];
  1430. } else {
  1431. $ret = Probe::uri($url, $network, $uid, false);
  1432. }
  1433. if (($network != '') && ($ret['network'] != $network)) {
  1434. Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
  1435. return $result;
  1436. }
  1437. // check if we already have a contact
  1438. // the poll url is more reliable than the profile url, as we may have
  1439. // indirect links or webfinger links
  1440. $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
  1441. $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
  1442. if (!DBA::isResult($contact)) {
  1443. $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
  1444. $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
  1445. }
  1446. if (($ret['network'] === Protocol::DFRN) && !DBA::isResult($contact)) {
  1447. if ($interactive) {
  1448. if (strlen($a->getURLPath())) {
  1449. $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
  1450. } else {
  1451. $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
  1452. }
  1453. $a->internalRedirect($ret['request'] . "&addr=$myaddr");
  1454. // NOTREACHED
  1455. }
  1456. } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
  1457. $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
  1458. $result['message'] != L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
  1459. return $result;
  1460. }
  1461. // This extra param just confuses things, remove it
  1462. if ($ret['network'] === Protocol::DIASPORA) {
  1463. $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
  1464. }
  1465. // do we have enough information?
  1466. if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
  1467. $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
  1468. if (empty($ret['poll'])) {
  1469. $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
  1470. }
  1471. if (empty($ret['name'])) {
  1472. $result['message'] .= L10n::t('An author or name was not found.') . EOL;
  1473. }
  1474. if (empty($ret['url'])) {
  1475. $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
  1476. }
  1477. if (strpos($url, '@') !== false) {
  1478. $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
  1479. $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
  1480. }
  1481. return $result;
  1482. }
  1483. if ($ret['network'] === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
  1484. $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
  1485. $ret['notify'] = '';
  1486. }
  1487. if (!$ret['notify']) {
  1488. $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
  1489. }
  1490. $writeable = ((($ret['network'] === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
  1491. $subhub = (($ret['network'] === Protocol::OSTATUS) ? true : false);
  1492. $hidden = (($ret['network'] === Protocol::MAIL) ? 1 : 0);
  1493. if (in_array($ret['network'], [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
  1494. $writeable = 1;
  1495. }
  1496. if (DBA::isResult($contact)) {
  1497. // update contact
  1498. $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
  1499. $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
  1500. DBA::update('contact', $fields, ['id' => $contact['id']]);
  1501. } else {
  1502. $new_relation = (in_array($ret['network'], [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
  1503. // create contact record
  1504. DBA::insert('contact', [
  1505. 'uid' => $uid,
  1506. 'created' => DateTimeFormat::utcNow(),
  1507. 'url' => $ret['url'],
  1508. 'nurl' => Strings::normaliseLink($ret['url']),
  1509. 'addr' => $ret['addr'],
  1510. 'alias' => $ret['alias'],
  1511. 'batch' => $ret['batch'],
  1512. 'notify' => $ret['notify'],
  1513. 'poll' => $ret['poll'],
  1514. 'poco' => $ret['poco'],
  1515. 'name' => $ret['name'],
  1516. 'nick' => $ret['nick'],
  1517. 'network' => $ret['network'],
  1518. 'pubkey' => $ret['pubkey'],
  1519. 'rel' => $new_relation,
  1520. 'priority'=> $ret['priority'],
  1521. 'writable'=> $writeable,
  1522. 'hidden' => $hidden,
  1523. 'blocked' => 0,
  1524. 'readonly'=> 0,
  1525. 'pending' => 0,
  1526. 'subhub' => $subhub
  1527. ]);
  1528. }
  1529. $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
  1530. if (!DBA::isResult($contact)) {
  1531. $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
  1532. return $result;
  1533. }
  1534. $contact_id = $contact['id'];
  1535. $result['cid'] = $contact_id;
  1536. Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
  1537. // Update the avatar
  1538. self::updateAvatar($ret['photo'], $uid, $contact_id);
  1539. // pull feed and consume it, which should subscribe to the hub.
  1540. Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
  1541. $owner = User::getOwnerDataById($uid);
  1542. if (DBA::isResult($owner)) {
  1543. if (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
  1544. // create a follow slap
  1545. $item = [];
  1546. $item['verb'] = ACTIVITY_FOLLOW;
  1547. $item['follow'] = $contact["url"];
  1548. $item['body'] = '';
  1549. $item['title'] = '';
  1550. $item['guid'] = '';
  1551. $item['tag'] = '';
  1552. $item['attach'] = '';
  1553. $slap = OStatus::salmon($item, $owner);
  1554. if (!empty($contact['notify'])) {
  1555. Salmon::slapper($owner, $contact['notify'], $slap);
  1556. }
  1557. } elseif ($contact['network'] == Protocol::DIASPORA) {
  1558. $ret = Diaspora::sendShare($a->user, $contact);
  1559. Logger::log('share returns: ' . $ret);
  1560. } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
  1561. $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid);
  1562. Logger::log('Follow returns: ' . $ret);
  1563. }
  1564. }
  1565. $result['success'] = true;
  1566. return $result;
  1567. }
  1568. /**
  1569. * @brief Updated contact's SSL policy
  1570. *
  1571. * @param array $contact Contact array
  1572. * @param string $new_policy New policy, valid: self,full
  1573. *
  1574. * @return array Contact array with updated values
  1575. */
  1576. public static function updateSslPolicy(array $contact, $new_policy)
  1577. {
  1578. $ssl_changed = false;
  1579. if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
  1580. $ssl_changed = true;
  1581. $contact['url'] = str_replace('https:', 'http:', $contact['url']);
  1582. $contact['request'] = str_replace('https:', 'http:', $contact['request']);
  1583. $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
  1584. $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
  1585. $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
  1586. $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
  1587. }
  1588. if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
  1589. $ssl_changed = true;
  1590. $contact['url'] = str_replace('http:', 'https:', $contact['url']);
  1591. $contact['request'] = str_replace('http:', 'https:', $contact['request']);
  1592. $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
  1593. $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
  1594. $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
  1595. $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
  1596. }
  1597. if ($ssl_changed) {
  1598. $fields = ['url' => $contact['url'], 'request' => $contact['request'],
  1599. 'notify' => $contact['notify'], 'poll' => $contact['poll'],
  1600. 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
  1601. DBA::update('contact', $fields, ['id' => $contact['id']]);
  1602. }
  1603. return $contact;
  1604. }
  1605. public static function addRelationship($importer, $contact, $datarray, $item = '', $sharing = false) {
  1606. // Should always be set
  1607. if (empty($datarray['author-id'])) {
  1608. return;
  1609. }
  1610. $fields = ['url', 'name', 'nick', 'photo', 'network'];
  1611. $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
  1612. if (!DBA::isResult($pub_contact)) {
  1613. // Should never happen
  1614. return;
  1615. }
  1616. $url = defaults($datarray, 'author-link', $pub_contact['url']);
  1617. $name = $pub_contact['name'];
  1618. $photo = $pub_contact['photo'];
  1619. $nick = $pub_contact['nick'];
  1620. $network = $pub_contact['network'];
  1621. if (is_array($contact)) {
  1622. if (($contact['rel'] == self::SHARING)
  1623. || ($sharing && $contact['rel'] == self::FOLLOWER)) {
  1624. DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true],
  1625. ['id' => $contact['id'], 'uid' => $importer['uid']]);
  1626. }
  1627. if ($contact['network'] == Protocol::ACTIVITYPUB) {
  1628. ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
  1629. }
  1630. // send email notification to owner?
  1631. } else {
  1632. if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
  1633. Logger::log('ignoring duplicated connection request from pending contact ' . $url);
  1634. return;
  1635. }
  1636. // create contact record
  1637. q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
  1638. `blocked`, `readonly`, `pending`, `writable`)
  1639. VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
  1640. intval($importer['uid']),
  1641. DBA::escape(DateTimeFormat::utcNow()),
  1642. DBA::escape($url),
  1643. DBA::escape(Strings::normaliseLink($url)),
  1644. DBA::escape($name),
  1645. DBA::escape($nick),
  1646. DBA::escape($photo),
  1647. DBA::escape($network),
  1648. intval(self::FOLLOWER)
  1649. );
  1650. $contact_record = [
  1651. 'id' => DBA::lastInsertId(),
  1652. 'network' => $network,
  1653. 'name' => $name,
  1654. 'url' => $url,
  1655. 'photo' => $photo
  1656. ];
  1657. Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
  1658. /// @TODO Encapsulate this into a function/method
  1659. $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
  1660. $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
  1661. if (DBA::isResult($user) && !in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
  1662. // create notification
  1663. $hash = Strings::getRandomHex();
  1664. if (is_array($contact_record)) {
  1665. DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
  1666. 'blocked' => false, 'knowyou' => false,
  1667. 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
  1668. }
  1669. Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
  1670. if (($user['notify-flags'] & NOTIFY_INTRO) &&
  1671. in_array($user['page-flags'], [self::PAGE_NORMAL])) {
  1672. notification([
  1673. 'type' => NOTIFY_INTRO,
  1674. 'notify_flags' => $user['notify-flags'],
  1675. 'language' => $user['language'],
  1676. 'to_name' => $user['username'],
  1677. 'to_email' => $user['email'],
  1678. 'uid' => $user['uid'],
  1679. 'link' => System::baseUrl() . '/notifications/intro',
  1680. 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
  1681. 'source_link' => $contact_record['url'],
  1682. 'source_photo' => $contact_record['photo'],
  1683. 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
  1684. 'otype' => 'intro'
  1685. ]);
  1686. }
  1687. } elseif (DBA::isResult($user) && in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
  1688. $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
  1689. DBA::update('contact', ['pending' => false], $condition);
  1690. $contact = DBA::selectFirst('contact', ['url', 'network', 'hub-verify'], ['id' => $contact_record['id']]);
  1691. if ($contact['network'] == Protocol::ACTIVITYPUB) {
  1692. ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
  1693. }
  1694. }
  1695. }
  1696. }
  1697. public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
  1698. {
  1699. if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
  1700. DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
  1701. } else {
  1702. Contact::remove($contact['id']);
  1703. }
  1704. }
  1705. public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
  1706. {
  1707. if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
  1708. DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
  1709. } else {
  1710. Contact::remove($contact['id']);
  1711. }
  1712. }
  1713. /**
  1714. * @brief Create a birthday event.
  1715. *
  1716. * Update the year and the birthday.
  1717. */
  1718. public static function updateBirthdays()
  1719. {
  1720. $condition = [
  1721. '`bd` != ""
  1722. AND `bd` > "0001-01-01"
  1723. AND SUBSTRING(`bd`, 1, 4) != `bdyear`
  1724. AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
  1725. AND NOT `contact`.`pending`
  1726. AND NOT `contact`.`hidden`
  1727. AND NOT `contact`.`blocked`
  1728. AND NOT `contact`.`archive`
  1729. AND NOT `contact`.`deleted`',
  1730. Contact::SHARING,
  1731. Contact::FRIEND
  1732. ];
  1733. $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
  1734. while ($contact = DBA::fetch($contacts)) {
  1735. Logger::log('update_contact_birthday: ' . $contact['bd']);
  1736. $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
  1737. if (Event::createBirthday($contact, $nextbd)) {
  1738. // update bdyear
  1739. DBA::update(
  1740. 'contact',
  1741. ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
  1742. ['id' => $contact['id']]
  1743. );
  1744. }
  1745. }
  1746. }
  1747. /**
  1748. * Remove the unavailable contact ids from the provided list
  1749. *
  1750. * @param array $contact_ids Contact id list
  1751. */
  1752. public static function pruneUnavailable(array &$contact_ids)
  1753. {
  1754. if (empty($contact_ids)) {
  1755. return;
  1756. }
  1757. $str = DBA::escape(implode(',', $contact_ids));
  1758. $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
  1759. $return = [];
  1760. while($contact = DBA::fetch($stmt)) {
  1761. $return[] = $contact['id'];
  1762. }
  1763. DBA::close($stmt);
  1764. $contact_ids = $return;
  1765. }
  1766. /**
  1767. * @brief Returns a magic link to authenticate remote visitors
  1768. *
  1769. * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
  1770. *
  1771. * @param string $contact_url The address of the target contact profile
  1772. * @param string $url An url that we will be redirected to after the authentication
  1773. *
  1774. * @return string with "redir" link
  1775. */
  1776. public static function magicLink($contact_url, $url = '')
  1777. {
  1778. if (!local_user()) {
  1779. return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
  1780. }
  1781. $cid = self::getIdForURL($contact_url, 0, true);
  1782. if (empty($cid)) {
  1783. return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
  1784. }
  1785. return self::magicLinkbyId($cid, $url);
  1786. }
  1787. /**
  1788. * @brief Returns a magic link to authenticate remote visitors
  1789. *
  1790. * @param integer $cid The contact id of the target contact profile
  1791. * @param integer $url An url that we will be redirected to after the authentication
  1792. *
  1793. * @return string with "redir" link
  1794. */
  1795. public static function magicLinkbyId($cid, $url = '')
  1796. {
  1797. $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
  1798. return self::magicLinkbyContact($contact, $url);
  1799. }
  1800. /**
  1801. * @brief Returns a magic link to authenticate remote visitors
  1802. *
  1803. * @param array $contact The contact array with "uid", "network" and "url"
  1804. * @param string $url An url that we will be redirected to after the authentication
  1805. *
  1806. * @return string with "redir" link
  1807. */
  1808. public static function magicLinkbyContact($contact, $url = '')
  1809. {
  1810. if (!local_user() || ($contact['network'] != Protocol::DFRN)) {
  1811. return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
  1812. }
  1813. // Only redirections to the same host do make sense
  1814. if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
  1815. return $url;
  1816. }
  1817. if ($contact['uid'] != 0) {
  1818. return self::magicLink($contact['url'], $url);
  1819. }
  1820. $redirect = 'redir/' . $contact['id'];
  1821. if ($url != '') {
  1822. $redirect .= '?url=' . $url;
  1823. }
  1824. return $redirect;
  1825. }
  1826. }