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