]> git.mxchange.org Git - friendica.git/blob - src/Model/GContact.php
Merge pull request #7789 from annando/warnings
[friendica.git] / src / Model / GContact.php
1 <?php
2 /**
3  * @file src/Model/GlobalContact.php
4  * @brief This file includes the GlobalContact class with directory related functions
5  */
6 namespace Friendica\Model;
7
8 use DOMDocument;
9 use DOMXPath;
10 use Exception;
11 use Friendica\Core\Config;
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\Protocol\ActivityPub;
19 use Friendica\Protocol\PortableContact;
20 use Friendica\Util\DateTimeFormat;
21 use Friendica\Util\Network;
22 use Friendica\Util\Strings;
23
24 /**
25  * @brief This class handles GlobalContact related functions
26  */
27 class GContact
28 {
29         /**
30          * @brief Search global contact table by nick or name
31          *
32          * @param string $search Name or nick
33          * @param string $mode   Search mode (e.g. "community")
34          *
35          * @return array with search results
36          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
37          */
38         public static function searchByName($search, $mode = '')
39         {
40                 if (empty($search)) {
41                         return [];
42                 }
43
44                 // check supported networks
45                 if (Config::get('system', 'diaspora_enabled')) {
46                         $diaspora = Protocol::DIASPORA;
47                 } else {
48                         $diaspora = Protocol::DFRN;
49                 }
50
51                 if (!Config::get('system', 'ostatus_disabled')) {
52                         $ostatus = Protocol::OSTATUS;
53                 } else {
54                         $ostatus = Protocol::DFRN;
55                 }
56
57                 // check if we search only communities or every contact
58                 if ($mode === 'community') {
59                         $extra_sql = ' AND `community`';
60                 } else {
61                         $extra_sql = '';
62                 }
63
64                 $search .= '%';
65
66                 $results = DBA::p("SELECT `nurl` FROM `gcontact`
67                         WHERE NOT `hide` AND `network` IN (?, ?, ?, ?) AND
68                                 ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`)) AND
69                                 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
70                                 GROUP BY `nurl` ORDER BY `nurl` DESC LIMIT 1000",
71                         Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, $search, $search, $search
72                 );
73
74                 $gcontacts = [];
75                 while ($result = DBA::fetch($results)) {
76                         $urlparts = parse_url($result['nurl']);
77
78                         // Ignore results that look strange.
79                         // For historic reasons the gcontact table does contain some garbage.
80                         if (!empty($urlparts['query']) || !empty($urlparts['fragment'])) {
81                                 continue;
82                         }
83
84                         $gcontacts[] = Contact::getDetailsByURL($result['nurl'], local_user());
85                 }
86                 return $gcontacts;
87         }
88
89         /**
90          * @brief Link the gcontact entry with user, contact and global contact
91          *
92          * @param integer $gcid Global contact ID
93          * @param integer $uid  User ID
94          * @param integer $cid  Contact ID
95          * @param integer $zcid Global Contact ID
96          * @return void
97          * @throws Exception
98          */
99         public static function link($gcid, $uid = 0, $cid = 0, $zcid = 0)
100         {
101                 if ($gcid <= 0) {
102                         return;
103                 }
104
105                 $condition = ['cid' => $cid, 'uid' => $uid, 'gcid' => $gcid, 'zcid' => $zcid];
106                 DBA::update('glink', ['updated' => DateTimeFormat::utcNow()], $condition, true);
107         }
108
109         /**
110          * @brief Sanitize the given gcontact data
111          *
112          * Generation:
113          *  0: No definition
114          *  1: Profiles on this server
115          *  2: Contacts of profiles on this server
116          *  3: Contacts of contacts of profiles on this server
117          *  4: ...
118          *
119          * @param array $gcontact array with gcontact data
120          * @return array $gcontact
121          * @throws Exception
122          */
123         public static function sanitize($gcontact)
124         {
125                 if (empty($gcontact['url'])) {
126                         throw new Exception('URL is empty');
127                 }
128
129                 $gcontact['server_url'] = $gcontact['server_url'] ?? '';
130
131                 $urlparts = parse_url($gcontact['url']);
132                 if (empty($urlparts['scheme'])) {
133                         throw new Exception('This (' . $gcontact['url'] . ") doesn't seem to be an url.");
134                 }
135
136                 if (in_array($urlparts['host'], ['twitter.com', 'identi.ca'])) {
137                         throw new Exception('Contact from a non federated network ignored. (' . $gcontact['url'] . ')');
138                 }
139
140                 // Don't store the statusnet connector as network
141                 // We can't simply set this to Protocol::OSTATUS since the connector could have fetched posts from friendica as well
142                 if ($gcontact['network'] == Protocol::STATUSNET) {
143                         $gcontact['network'] = '';
144                 }
145
146                 // Assure that there are no parameter fragments in the profile url
147                 if (empty($gcontact['*network']) || in_array($gcontact['network'], Protocol::FEDERATED)) {
148                         $gcontact['url'] = self::cleanContactUrl($gcontact['url']);
149                 }
150
151                 // The global contacts should contain the original picture, not the cached one
152                 if (($gcontact['generation'] != 1) && stristr(Strings::normaliseLink($gcontact['photo']), Strings::normaliseLink(System::baseUrl() . '/photo/'))) {
153                         $gcontact['photo'] = '';
154                 }
155
156                 if (empty($gcontact['network'])) {
157                         $gcontact['network'] = '';
158
159                         $condition = ["`uid` = 0 AND `nurl` = ? AND `network` != '' AND `network` != ?",
160                                 Strings::normaliseLink($gcontact['url']), Protocol::STATUSNET];
161                         $contact = DBA::selectFirst('contact', ['network'], $condition);
162                         if (DBA::isResult($contact)) {
163                                 $gcontact['network'] = $contact['network'];
164                         }
165
166                         if (($gcontact['network'] == '') || ($gcontact['network'] == Protocol::OSTATUS)) {
167                                 $condition = ["`uid` = 0 AND `alias` IN (?, ?) AND `network` != '' AND `network` != ?",
168                                         $gcontact['url'], Strings::normaliseLink($gcontact['url']), Protocol::STATUSNET];
169                                 $contact = DBA::selectFirst('contact', ['network'], $condition);
170                                 if (DBA::isResult($contact)) {
171                                         $gcontact['network'] = $contact['network'];
172                                 }
173                         }
174                 }
175
176                 $fields = ['network', 'updated', 'server_url', 'url', 'addr'];
177                 $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($gcontact['url'])]);
178                 if (DBA::isResult($gcnt)) {
179                         if (!isset($gcontact['network']) && ($gcnt['network'] != Protocol::STATUSNET)) {
180                                 $gcontact['network'] = $gcnt['network'];
181                         }
182                         if ($gcontact['updated'] <= DBA::NULL_DATETIME) {
183                                 $gcontact['updated'] = $gcnt['updated'];
184                         }
185                         if (!isset($gcontact['server_url']) && (Strings::normaliseLink($gcnt['server_url']) != Strings::normaliseLink($gcnt['url']))) {
186                                 $gcontact['server_url'] = $gcnt['server_url'];
187                         }
188                         if (!isset($gcontact['addr'])) {
189                                 $gcontact['addr'] = $gcnt['addr'];
190                         }
191                 }
192
193                 if ((!isset($gcontact['network']) || !isset($gcontact['name']) || !isset($gcontact['addr']) || !isset($gcontact['photo']) || !isset($gcontact['server_url']))
194                         && GServer::reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)
195                 ) {
196                         $data = Probe::uri($gcontact['url']);
197
198                         if ($data['network'] == Protocol::PHANTOM) {
199                                 throw new Exception('Probing for URL ' . $gcontact['url'] . ' failed');
200                         }
201
202                         $orig_profile = $gcontact['url'];
203
204                         $gcontact['server_url'] = $data['baseurl'];
205
206                         $gcontact = array_merge($gcontact, $data);
207                 }
208
209                 if (!isset($gcontact['name']) || !isset($gcontact['photo'])) {
210                         throw new Exception('No name and photo for URL '.$gcontact['url']);
211                 }
212
213                 if (!in_array($gcontact['network'], Protocol::FEDERATED)) {
214                         throw new Exception('No federated network (' . $gcontact['network'] . ') detected for URL ' . $gcontact['url']);
215                 }
216
217                 if (empty($gcontact['server_url'])) {
218                         // We check the server url to be sure that it is a real one
219                         $server_url = Contact::getBasepath($gcontact['url']);
220
221                         // We are now sure that it is a correct URL. So we use it in the future
222                         if ($server_url != '') {
223                                 $gcontact['server_url'] = $server_url;
224                         }
225                 }
226
227                 // The server URL doesn't seem to be valid, so we don't store it.
228                 if (!GServer::check($gcontact['server_url'], $gcontact['network'])) {
229                         $gcontact['server_url'] = '';
230                 }
231
232                 return $gcontact;
233         }
234
235         /**
236          * @param integer $uid id
237          * @param integer $cid id
238          * @return integer
239          * @throws Exception
240          */
241         public static function countCommonFriends($uid, $cid)
242         {
243                 $r = q(
244                         "SELECT count(*) as `total`
245                         FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
246                         WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
247                         ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR
248                         (`gcontact`.`updated` >= `gcontact`.`last_failure`))
249                         AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d) ",
250                         intval($cid),
251                         intval($uid),
252                         intval($uid),
253                         intval($cid)
254                 );
255
256                 if (DBA::isResult($r)) {
257                         return $r[0]['total'];
258                 }
259                 return 0;
260         }
261
262         /**
263          * @param integer $uid  id
264          * @param integer $zcid zcid
265          * @return integer
266          * @throws Exception
267          */
268         public static function countCommonFriendsZcid($uid, $zcid)
269         {
270                 $r = q(
271                         "SELECT count(*) as `total`
272                         FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
273                         where `glink`.`zcid` = %d
274                         and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0) ",
275                         intval($zcid),
276                         intval($uid)
277                 );
278
279                 if (DBA::isResult($r)) {
280                         return $r[0]['total'];
281                 }
282
283                 return 0;
284         }
285
286         /**
287          * @param integer $uid     user
288          * @param integer $cid     cid
289          * @param integer $start   optional, default 0
290          * @param integer $limit   optional, default 9999
291          * @param boolean $shuffle optional, default false
292          * @return object
293          * @throws Exception
294          */
295         public static function commonFriends($uid, $cid, $start = 0, $limit = 9999, $shuffle = false)
296         {
297                 if ($shuffle) {
298                         $sql_extra = " order by rand() ";
299                 } else {
300                         $sql_extra = " order by `gcontact`.`name` asc ";
301                 }
302
303                 $r = q(
304                         "SELECT `gcontact`.*, `contact`.`id` AS `cid`
305                         FROM `glink`
306                         INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
307                         INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
308                         WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
309                                 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
310                                 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
311                                 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
312                                 $sql_extra LIMIT %d, %d",
313                         intval($cid),
314                         intval($uid),
315                         intval($uid),
316                         intval($cid),
317                         intval($start),
318                         intval($limit)
319                 );
320
321                 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
322                 return $r;
323         }
324
325         /**
326          * @param integer $uid     user
327          * @param integer $zcid    zcid
328          * @param integer $start   optional, default 0
329          * @param integer $limit   optional, default 9999
330          * @param boolean $shuffle optional, default false
331          * @return object
332          * @throws Exception
333          */
334         public static function commonFriendsZcid($uid, $zcid, $start = 0, $limit = 9999, $shuffle = false)
335         {
336                 if ($shuffle) {
337                         $sql_extra = " order by rand() ";
338                 } else {
339                         $sql_extra = " order by `gcontact`.`name` asc ";
340                 }
341
342                 $r = q(
343                         "SELECT `gcontact`.*
344                         FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
345                         where `glink`.`zcid` = %d
346                         and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0)
347                         $sql_extra limit %d, %d",
348                         intval($zcid),
349                         intval($uid),
350                         intval($start),
351                         intval($limit)
352                 );
353
354                 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
355                 return $r;
356         }
357
358         /**
359          * @param integer $uid user
360          * @param integer $cid cid
361          * @return integer
362          * @throws Exception
363          */
364         public static function countAllFriends($uid, $cid)
365         {
366                 $r = q(
367                         "SELECT count(*) as `total`
368                         FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
369                         where `glink`.`cid` = %d and `glink`.`uid` = %d AND
370                         ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
371                         intval($cid),
372                         intval($uid)
373                 );
374
375                 if (DBA::isResult($r)) {
376                         return $r[0]['total'];
377                 }
378
379                 return 0;
380         }
381
382         /**
383          * @param integer $uid   user
384          * @param integer $cid   cid
385          * @param integer $start optional, default 0
386          * @param integer $limit optional, default 80
387          * @return array
388          * @throws Exception
389          */
390         public static function allFriends($uid, $cid, $start = 0, $limit = 80)
391         {
392                 $r = q(
393                         "SELECT `gcontact`.*, `contact`.`id` AS `cid`
394                         FROM `glink`
395                         INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
396                         LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
397                         WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
398                         ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
399                         ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
400                         intval($uid),
401                         intval($cid),
402                         intval($uid),
403                         intval($start),
404                         intval($limit)
405                 );
406
407                 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
408                 return $r;
409         }
410
411         /**
412          * @param int     $uid   user
413          * @param integer $start optional, default 0
414          * @param integer $limit optional, default 80
415          * @return array
416          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
417          */
418         public static function suggestionQuery($uid, $start = 0, $limit = 80)
419         {
420                 if (!$uid) {
421                         return [];
422                 }
423
424                 $network = [Protocol::DFRN, Protocol::ACTIVITYPUB];
425
426                 if (Config::get('system', 'diaspora_enabled')) {
427                         $network[] = Protocol::DIASPORA;
428                 }
429
430                 if (!Config::get('system', 'ostatus_disabled')) {
431                         $network[] = Protocol::OSTATUS;
432                 }
433
434                 $sql_network = "'" . implode("', '", $network) . "'";
435
436                 /// @todo This query is really slow
437                 // By now we cache the data for five minutes
438                 $r = q(
439                         "SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
440                         INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
441                         where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
442                         AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
443                         AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
444                         AND `gcontact`.`updated` >= '%s' AND NOT `gcontact`.`hide`
445                         AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
446                         AND `gcontact`.`network` IN (%s)
447                         GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
448                         intval($uid),
449                         intval($uid),
450                         intval($uid),
451                         intval($uid),
452                         DBA::NULL_DATETIME,
453                         $sql_network,
454                         intval($start),
455                         intval($limit)
456                 );
457
458                 if (DBA::isResult($r) && count($r) >= ($limit -1)) {
459                         return $r;
460                 }
461
462                 $r2 = q(
463                         "SELECT gcontact.* FROM gcontact
464                         INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
465                         WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
466                         AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
467                         AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
468                         AND `gcontact`.`updated` >= '%s'
469                         AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
470                         AND `gcontact`.`network` IN (%s)
471                         ORDER BY rand() LIMIT %d, %d",
472                         intval($uid),
473                         intval($uid),
474                         intval($uid),
475                         DBA::NULL_DATETIME,
476                         $sql_network,
477                         intval($start),
478                         intval($limit)
479                 );
480
481                 $list = [];
482                 foreach ($r2 as $suggestion) {
483                         $list[$suggestion['nurl']] = $suggestion;
484                 }
485
486                 foreach ($r as $suggestion) {
487                         $list[$suggestion['nurl']] = $suggestion;
488                 }
489
490                 while (sizeof($list) > ($limit)) {
491                         array_pop($list);
492                 }
493
494                 return $list;
495         }
496
497         /**
498          * @return void
499          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
500          */
501         public static function updateSuggestions()
502         {
503                 $done = [];
504
505                 /// @TODO Check if it is really neccessary to poll the own server
506                 PortableContact::loadWorker(0, 0, 0, System::baseUrl() . '/poco');
507
508                 $done[] = System::baseUrl() . '/poco';
509
510                 if (strlen(Config::get('system', 'directory'))) {
511                         $x = Network::fetchUrl(get_server() . '/pubsites');
512                         if (!empty($x)) {
513                                 $j = json_decode($x);
514                                 if (!empty($j->entries)) {
515                                         foreach ($j->entries as $entry) {
516                                                 GServer::check($entry->url);
517
518                                                 $url = $entry->url . '/poco';
519                                                 if (!in_array($url, $done)) {
520                                                         PortableContact::loadWorker(0, 0, 0, $url);
521                                                         $done[] = $url;
522                                                 }
523                                         }
524                                 }
525                         }
526                 }
527
528                 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
529                 $contacts = DBA::p("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN (?, ?)", Protocol::DFRN, Protocol::DIASPORA);
530                 while ($contact = DBA::fetch($contacts)) {
531                         $base = substr($contact['poco'], 0, strrpos($contact['poco'], '/'));
532                         if (!in_array($base, $done)) {
533                                 PortableContact::loadWorker(0, 0, 0, $base);
534                         }
535                 }
536         }
537
538         /**
539          * @brief Removes unwanted parts from a contact url
540          *
541          * @param string $url Contact url
542          *
543          * @return string Contact url with the wanted parts
544          * @throws Exception
545          */
546         public static function cleanContactUrl($url)
547         {
548                 $parts = parse_url($url);
549
550                 if (empty($parts['scheme']) || empty($parts['host'])) {
551                         return $url;
552                 }
553
554                 $new_url = $parts['scheme'] . '://' . $parts['host'];
555
556                 if (!empty($parts['port'])) {
557                         $new_url .= ':' . $parts['port'];
558                 }
559
560                 if (!empty($parts['path'])) {
561                         $new_url .= $parts['path'];
562                 }
563
564                 if ($new_url != $url) {
565                         Logger::info('Cleaned contact url', ['url' => $url, 'new_url' => $new_url, 'callstack' => System::callstack()]);
566                 }
567
568                 return $new_url;
569         }
570
571         /**
572          * @brief Fetch the gcontact id, add an entry if not existed
573          *
574          * @param array $contact contact array
575          *
576          * @return bool|int Returns false if not found, integer if contact was found
577          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
578          * @throws \ImagickException
579          */
580         public static function getId($contact)
581         {
582                 $gcontact_id = 0;
583                 $doprobing = false;
584                 $last_failure_str = '';
585                 $last_contact_str = '';
586
587                 if (empty($contact['network'])) {
588                         Logger::notice('Empty network', ['url' => $contact['url'], 'callstack' => System::callstack()]);
589                         return false;
590                 }
591
592                 if (in_array($contact['network'], [Protocol::PHANTOM])) {
593                         Logger::notice('Invalid network', ['url' => $contact['url'], 'callstack' => System::callstack()]);
594                         return false;
595                 }
596
597                 if ($contact['network'] == Protocol::STATUSNET) {
598                         $contact['network'] = Protocol::OSTATUS;
599                 }
600
601                 // All new contacts are hidden by default
602                 if (!isset($contact['hide'])) {
603                         $contact['hide'] = true;
604                 }
605
606                 // Remove unwanted parts from the contact url (e.g. '?zrl=...')
607                 if (in_array($contact['network'], Protocol::FEDERATED)) {
608                         $contact['url'] = self::cleanContactUrl($contact['url']);
609                 }
610
611                 DBA::lock('gcontact');
612                 $fields = ['id', 'last_contact', 'last_failure', 'network'];
613                 $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
614                 if (DBA::isResult($gcnt)) {
615                         $gcontact_id = $gcnt['id'];
616
617                         // Update every 90 days
618                         if (empty($gcnt['network']) || in_array($gcnt['network'], Protocol::FEDERATED)) {
619                                 $last_failure_str = $gcnt['last_failure'];
620                                 $last_failure = strtotime($gcnt['last_failure']);
621                                 $last_contact_str = $gcnt['last_contact'];
622                                 $last_contact = strtotime($gcnt['last_contact']);
623                                 $doprobing = (((time() - $last_contact) > (90 * 86400)) && ((time() - $last_failure) > (90 * 86400)));
624                         }
625                 } else {
626                         $contact['location'] = $contact['location'] ?? '';
627                         $contact['about'] = $contact['about'] ?? '';
628                         $contact['generation'] = $contact['generation'] ?? 0;
629
630                         $fields = ['name' => $contact['name'], 'nick' => $contact['nick'], 'addr' => $contact['addr'], 'network' => $contact['network'],
631                                 'url' => $contact['url'], 'nurl' => Strings::normaliseLink($contact['url']), 'photo' => $contact['photo'],
632                                 'created' => DateTimeFormat::utcNow(), 'updated' => DateTimeFormat::utcNow(), 'location' => $contact['location'],
633                                 'about' => $contact['about'], 'hide' => $contact['hide'], 'generation' => $contact['generation']];
634                         DBA::insert('gcontact', $fields);
635
636                         $condition = ['nurl' => Strings::normaliseLink($contact['url'])];
637                         $cnt = DBA::selectFirst('gcontact', ['id', 'network'], $condition, ['order' => ['id']]);
638                         if (DBA::isResult($cnt)) {
639                                 $gcontact_id = $cnt['id'];
640                                 $doprobing = (empty($cnt['network']) || in_array($cnt['network'], Protocol::FEDERATED));
641                         }
642                 }
643                 DBA::unlock();
644
645                 if ($doprobing) {
646                         Logger::notice('Probing', ['contact' => $last_contact_str, "failure" => $last_failure_str, "checking" => $contact['url']]);
647                         Worker::add(PRIORITY_LOW, 'GProbe', $contact['url']);
648                 }
649
650                 return $gcontact_id;
651         }
652
653         /**
654          * @brief Updates the gcontact table from a given array
655          *
656          * @param array $contact contact array
657          *
658          * @return bool|int Returns false if not found, integer if contact was found
659          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
660          * @throws \ImagickException
661          */
662         public static function update($contact)
663         {
664                 // Check for invalid "contact-type" value
665                 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
666                         $contact['contact-type'] = 0;
667                 }
668
669                 /// @todo update contact table as well
670
671                 $gcontact_id = self::getId($contact);
672
673                 if (!$gcontact_id) {
674                         return false;
675                 }
676
677                 $public_contact = DBA::selectFirst('gcontact', [
678                         'name', 'nick', 'photo', 'location', 'about', 'addr', 'generation', 'birthday', 'gender', 'keywords',
679                         'contact-type', 'hide', 'nsfw', 'network', 'alias', 'notify', 'server_url', 'connect', 'updated', 'url'
680                 ], ['id' => $gcontact_id]);
681
682                 if (!DBA::isResult($public_contact)) {
683                         return false;
684                 }
685
686                 // Get all field names
687                 $fields = [];
688                 foreach ($public_contact as $field => $data) {
689                         $fields[$field] = $data;
690                 }
691
692                 unset($fields['url']);
693                 unset($fields['updated']);
694                 unset($fields['hide']);
695
696                 // Bugfix: We had an error in the storing of keywords which lead to the "0"
697                 // This value is still transmitted via poco.
698                 if (isset($contact['keywords']) && ($contact['keywords'] == '0')) {
699                         unset($contact['keywords']);
700                 }
701
702                 if (isset($public_contact['keywords']) && ($public_contact['keywords'] == '0')) {
703                         $public_contact['keywords'] = '';
704                 }
705
706                 // assign all unassigned fields from the database entry
707                 foreach ($fields as $field => $data) {
708                         if (empty($contact[$field])) {
709                                 $contact[$field] = $public_contact[$field];
710                         }
711                 }
712
713                 if (!isset($contact['hide'])) {
714                         $contact['hide'] = $public_contact['hide'];
715                 }
716
717                 $fields['hide'] = $public_contact['hide'];
718
719                 if ($contact['network'] == Protocol::STATUSNET) {
720                         $contact['network'] = Protocol::OSTATUS;
721                 }
722
723                 if (!isset($contact['updated'])) {
724                         $contact['updated'] = DateTimeFormat::utcNow();
725                 }
726
727                 if ($contact['network'] == Protocol::TWITTER) {
728                         $contact['server_url'] = 'http://twitter.com';
729                 }
730
731                 if (empty($contact['server_url'])) {
732                         $data = Probe::uri($contact['url']);
733                         if ($data['network'] != Protocol::PHANTOM) {
734                                 $contact['server_url'] = $data['baseurl'];
735                         }
736                 } else {
737                         $contact['server_url'] = Strings::normaliseLink($contact['server_url']);
738                 }
739
740                 if (empty($contact['addr']) && !empty($contact['server_url']) && !empty($contact['nick'])) {
741                         $hostname = str_replace('http://', '', $contact['server_url']);
742                         $contact['addr'] = $contact['nick'] . '@' . $hostname;
743                 }
744
745                 // Check if any field changed
746                 $update = false;
747                 unset($fields['generation']);
748
749                 if ((($contact['generation'] > 0) && ($contact['generation'] <= $public_contact['generation'])) || ($public_contact['generation'] == 0)) {
750                         foreach ($fields as $field => $data) {
751                                 if ($contact[$field] != $public_contact[$field]) {
752                                         Logger::debug('Difference found.', ['contact' => $contact['url'], 'field' => $field, 'new' => $contact[$field], 'old' => $public_contact[$field]]);
753                                         $update = true;
754                                 }
755                         }
756
757                         if ($contact['generation'] < $public_contact['generation']) {
758                                 Logger::debug('Difference found.', ['contact' => $contact['url'], 'field' => 'generation', 'new' => $contact['generation'], 'old' => $public_contact['generation']]);
759                                 $update = true;
760                         }
761                 }
762
763                 if ($update) {
764                         Logger::debug('Update gcontact.', ['contact' => $contact['url']]);
765                         $condition = ["`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)",
766                                         Strings::normaliseLink($contact['url']), $contact['generation']];
767                         $contact['updated'] = DateTimeFormat::utc($contact['updated']);
768
769                         $updated = [
770                                 'photo' => $contact['photo'], 'name' => $contact['name'],
771                                 'nick' => $contact['nick'], 'addr' => $contact['addr'],
772                                 'network' => $contact['network'], 'birthday' => $contact['birthday'],
773                                 'gender' => $contact['gender'], 'keywords' => $contact['keywords'],
774                                 'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
775                                 'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
776                                 'notify' => $contact['notify'], 'url' => $contact['url'],
777                                 'location' => $contact['location'], 'about' => $contact['about'],
778                                 'generation' => $contact['generation'], 'updated' => $contact['updated'],
779                                 'server_url' => $contact['server_url'], 'connect' => $contact['connect']
780                         ];
781
782                         DBA::update('gcontact', $updated, $condition, $fields);
783                 }
784
785                 return $gcontact_id;
786         }
787
788         /**
789          * Set the last date that the contact had posted something
790          *
791          * @param string $data  Probing result
792          * @param bool   $force force updating
793          */
794         public static function setLastUpdate(array $data, bool $force = false)
795         {
796                 // Fetch the global contact
797                 $gcontact = DBA::selectFirst('gcontact', ['created', 'updated', 'last_contact', 'last_failure'],
798                         ['nurl' => Strings::normaliseLink($data['url'])]);
799                 if (!DBA::isResult($gcontact)) {
800                         return;
801                 }
802
803                 if (!$force && !PortableContact::updateNeeded($gcontact['created'], $gcontact['updated'], $gcontact['last_failure'], $gcontact['last_contact'])) {
804                         Logger::info("Don't update profile", ['url' => $data['url'], 'updated' => $gcontact['updated']]);
805                         return;
806                 }
807
808                 if (self::updateFromNoScrape($data)) {
809                         return;
810                 }
811
812                 // When the profile doesn't have got a feed, then we exit here
813                 if (empty($data['poll'])) {
814                         return;
815                 }
816
817                 if ($data['network'] == Protocol::ACTIVITYPUB) {
818                         self::updateFromOutbox($data['poll'], $data);
819                 } else {
820                         self::updateFromFeed($data);
821                 }
822         }
823
824         /**
825          * Update a global contact via the "noscrape" endpoint
826          *
827          * @param string $data Probing result
828          *
829          * @return bool 'true' if update was successful or the server was unreachable
830          */
831         private static function updateFromNoScrape(array $data)
832         {
833                 // Check the 'noscrape' endpoint when it is a Friendica server
834                 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
835                 Strings::normaliseLink($data['baseurl'])]);
836                 if (!DBA::isResult($gserver)) {
837                         return false;
838                 }
839
840                 $curlResult = Network::curl($gserver['noscrape'] . '/' . $data['nick']);
841
842                 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
843                         $noscrape = json_decode($curlResult->getBody(), true);
844                         if (!empty($noscrape) && !empty($noscrape['updated'])) {
845                                 $noscrape['updated'] = DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
846                                 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $noscrape['updated']];
847                                 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
848                                 return true;
849                         }
850                 } elseif ($curlResult->isTimeout()) {
851                         // On a timeout return the existing value, but mark the contact as failure
852                         $fields = ['last_failure' => DateTimeFormat::utcNow()];
853                         DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
854                         return true;
855                 }
856                 return false;
857         }
858
859         /**
860          * Update a global contact via an ActivityPub Outbox
861          *
862          * @param string $feed
863          * @param array  $data Probing result
864          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
865          */
866         private static function updateFromOutbox(string $feed, array $data)
867         {
868                 $outbox = ActivityPub::fetchContent($feed);
869                 if (empty($outbox)) {
870                         return;
871                 }
872
873                 if (!empty($outbox['orderedItems'])) {
874                         $items = $outbox['orderedItems'];
875                 } elseif (!empty($outbox['first']['orderedItems'])) {
876                         $items = $outbox['first']['orderedItems'];
877                 } elseif (!empty($outbox['first']['href'])) {
878                         self::updateFromOutbox($outbox['first']['href'], $data);
879                         return;
880                 } elseif (!empty($outbox['first'])) {
881                         self::updateFromOutbox($outbox['first'], $data);
882                         return;
883                 } else {
884                         $items = [];
885                 }
886
887                 $last_updated = '';
888
889                 foreach ($items as $activity) {
890                         if ($last_updated < $activity['published']) {
891                                 $last_updated = $activity['published'];
892                         }
893                 }
894
895                 if (empty($last_updated)) {
896                         return;
897                 }
898
899                 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
900                 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
901         }
902
903         /**
904          * Update a global contact via an XML feed
905          *
906          * @param string $data Probing result
907          */
908         private static function updateFromFeed(array $data)
909         {
910                 // Search for the newest entry in the feed
911                 $curlResult = Network::curl($data['poll']);
912                 if (!$curlResult->isSuccess()) {
913                         $fields = ['last_failure' => DateTimeFormat::utcNow()];
914                         DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($profile)]);
915
916                         Logger::info("Profile wasn't reachable (no feed)", ['url' => $data['url']]);
917                         return;
918                 }
919
920                 $doc = new DOMDocument();
921                 @$doc->loadXML($curlResult->getBody());
922
923                 $xpath = new DOMXPath($doc);
924                 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
925
926                 $entries = $xpath->query('/atom:feed/atom:entry');
927
928                 $last_updated = '';
929
930                 foreach ($entries as $entry) {
931                         $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
932                         $updated_item   = $xpath->query('atom:updated/text()'  , $entry)->item(0);
933                         $published      = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
934                         $updated        = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
935
936                         if (empty($published) || empty($updated)) {
937                                 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
938                                 continue;
939                         }
940
941                         if ($last_updated < $published) {
942                                 $last_updated = $published;
943                         }
944
945                         if ($last_updated < $updated) {
946                                 $last_updated = $updated;
947                         }
948                 }
949
950                 if (empty($last_updated)) {
951                         return;
952                 }
953
954                 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
955                 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
956         }
957         /**
958          * @brief Updates the gcontact entry from a given public contact id
959          *
960          * @param integer $cid contact id
961          * @return void
962          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
963          * @throws \ImagickException
964          */
965         public static function updateFromPublicContactID($cid)
966         {
967                 self::updateFromPublicContact(['id' => $cid]);
968         }
969
970         /**
971          * @brief Updates the gcontact entry from a given public contact url
972          *
973          * @param string $url contact url
974          * @return integer gcontact id
975          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
976          * @throws \ImagickException
977          */
978         public static function updateFromPublicContactURL($url)
979         {
980                 return self::updateFromPublicContact(['nurl' => Strings::normaliseLink($url)]);
981         }
982
983         /**
984          * @brief Helper function for updateFromPublicContactID and updateFromPublicContactURL
985          *
986          * @param array $condition contact condition
987          * @return integer gcontact id
988          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
989          * @throws \ImagickException
990          */
991         private static function updateFromPublicContact($condition)
992         {
993                 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gender',
994                         'bd', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archive', 'term-date',
995                         'created', 'updated', 'avatar', 'success_update', 'failure_update', 'forum', 'prv',
996                         'baseurl', 'sensitive', 'unsearchable'];
997
998                 $contact = DBA::selectFirst('contact', $fields, array_merge($condition, ['uid' => 0, 'network' => Protocol::FEDERATED]));
999                 if (!DBA::isResult($contact)) {
1000                         return 0;
1001                 }
1002
1003                 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gender', 'generation',
1004                         'birthday', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archived', 'archive_date',
1005                         'created', 'updated', 'photo', 'last_contact', 'last_failure', 'community', 'connect',
1006                         'server_url', 'nsfw', 'hide', 'id'];
1007
1008                 $old_gcontact = DBA::selectFirst('gcontact', $fields, ['nurl' => $contact['nurl']]);
1009                 $do_insert = !DBA::isResult($old_gcontact);
1010                 if ($do_insert) {
1011                         $old_gcontact = [];
1012                 }
1013
1014                 $gcontact = [];
1015
1016                 // These fields are identical in both contact and gcontact
1017                 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gender',
1018                         'contact-type', 'network', 'addr', 'notify', 'alias', 'created', 'updated'];
1019
1020                 foreach ($fields as $field) {
1021                         $gcontact[$field] = $contact[$field];
1022                 }
1023
1024                 // These fields are having different names but the same content
1025                 $gcontact['server_url'] = $contact['baseurl'] ?? ''; // "baseurl" can be null, "server_url" not
1026                 $gcontact['nsfw'] = $contact['sensitive'];
1027                 $gcontact['hide'] = $contact['unsearchable'];
1028                 $gcontact['archived'] = $contact['archive'];
1029                 $gcontact['archive_date'] = $contact['term-date'];
1030                 $gcontact['birthday'] = $contact['bd'];
1031                 $gcontact['photo'] = $contact['avatar'];
1032                 $gcontact['last_contact'] = $contact['success_update'];
1033                 $gcontact['last_failure'] = $contact['failure_update'];
1034                 $gcontact['community'] = ($contact['forum'] || $contact['prv']);
1035
1036                 foreach (['last_contact', 'last_failure', 'updated'] as $field) {
1037                         if (!empty($old_gcontact[$field]) && ($old_gcontact[$field] >= $gcontact[$field])) {
1038                                 unset($gcontact[$field]);
1039                         }
1040                 }
1041
1042                 if (!$gcontact['archived']) {
1043                         $gcontact['archive_date'] = DBA::NULL_DATETIME;
1044                 }
1045
1046                 if (!empty($old_gcontact['created']) && ($old_gcontact['created'] > DBA::NULL_DATETIME)
1047                         && ($old_gcontact['created'] <= $gcontact['created'])) {
1048                         unset($gcontact['created']);
1049                 }
1050
1051                 if (empty($gcontact['birthday']) && ($gcontact['birthday'] <= DBA::NULL_DATETIME)) {
1052                         unset($gcontact['birthday']);
1053                 }
1054
1055                 if (empty($old_gcontact['generation']) || ($old_gcontact['generation'] > 2)) {
1056                         $gcontact['generation'] = 2; // We fetched the data directly from the other server
1057                 }
1058
1059                 if (!$do_insert) {
1060                         DBA::update('gcontact', $gcontact, ['nurl' => $contact['nurl']], $old_gcontact);
1061                         return $old_gcontact['id'];
1062                 } elseif (!$gcontact['archived']) {
1063                         DBA::insert('gcontact', $gcontact);
1064                         return DBA::lastInsertId();
1065                 }
1066         }
1067
1068         /**
1069          * @brief Updates the gcontact entry from probe
1070          *
1071          * @param string  $url   profile link
1072          * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1073          *
1074          * @return boolean 'true' when contact had been updated
1075          *
1076          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1077          * @throws \ImagickException
1078          */
1079         public static function updateFromProbe($url, $force = false)
1080         {
1081                 $data = Probe::uri($url, $force);
1082
1083                 if (in_array($data['network'], [Protocol::PHANTOM])) {
1084                         $fields = ['last_failure' => DateTimeFormat::utcNow()];
1085                         DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1086                         Logger::info('Invalid network for contact', ['url' => $data['url'], 'callstack' => System::callstack()]);
1087                         return false;
1088                 }
1089
1090                 $data['server_url'] = $data['baseurl'];
1091
1092                 self::update($data);
1093
1094                 // Set the date of the latest post
1095                 self::setLastUpdate($data, $force);
1096
1097                 return true;
1098         }
1099
1100         /**
1101          * @brief Update the gcontact entry for a given user id
1102          *
1103          * @param int $uid User ID
1104          * @return bool
1105          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1106          * @throws \ImagickException
1107          */
1108         public static function updateForUser($uid)
1109         {
1110                 $profile = Profile::getByUID($uid);
1111                 if (empty($profile)) {
1112                         Logger::error('Cannot find profile', ['uid' => $uid]);
1113                         return false;
1114                 }
1115
1116                 $user = User::getOwnerDataById($uid);
1117                 if (empty($user)) {
1118                         Logger::error('Cannot find user', ['uid' => $uid]);
1119                         return false;
1120                 }
1121
1122                 $userdata = array_merge($profile, $user);
1123
1124                 $location = Profile::formatLocation(
1125                         ['locality' => $userdata['locality'], 'region' => $userdata['region'], 'country-name' => $userdata['country-name']]
1126                 );
1127
1128                 $gcontact = ['name' => $userdata['name'], 'location' => $location, 'about' => $userdata['about'],
1129                                 'gender' => $userdata['gender'], 'keywords' => $userdata['pub_keywords'],
1130                                 'birthday' => $userdata['dob'], 'photo' => $userdata['photo'],
1131                                 "notify" => $userdata['notify'], 'url' => $userdata['url'],
1132                                 "hide" => ($userdata['hidewall'] || !$userdata['net-publish']),
1133                                 'nick' => $userdata['nickname'], 'addr' => $userdata['addr'],
1134                                 "connect" => $userdata['addr'], "server_url" => System::baseUrl(),
1135                                 "generation" => 1, 'network' => Protocol::DFRN];
1136
1137                 self::update($gcontact);
1138         }
1139
1140         /**
1141          * @brief Fetches users of given GNU Social server
1142          *
1143          * If the "Statistics" addon is enabled (See http://gstools.org/ for details) we query user data with this.
1144          *
1145          * @param string $server Server address
1146          * @return bool
1147          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1148          * @throws \ImagickException
1149          */
1150         public static function fetchGsUsers($server)
1151         {
1152                 Logger::info('Fetching users from GNU Social server', ['server' => $server]);
1153
1154                 $url = $server . '/main/statistics';
1155
1156                 $curlResult = Network::curl($url);
1157                 if (!$curlResult->isSuccess()) {
1158                         return false;
1159                 }
1160
1161                 $statistics = json_decode($curlResult->getBody());
1162
1163                 if (!empty($statistics->config->instance_address)) {
1164                         if (!empty($statistics->config->instance_with_ssl)) {
1165                                 $server = 'https://';
1166                         } else {
1167                                 $server = 'http://';
1168                         }
1169
1170                         $server .= $statistics->config->instance_address;
1171
1172                         $hostname = $statistics->config->instance_address;
1173                 } elseif (!empty($statistics->instance_address)) {
1174                         if (!empty($statistics->instance_with_ssl)) {
1175                                 $server = 'https://';
1176                         } else {
1177                                 $server = 'http://';
1178                         }
1179
1180                         $server .= $statistics->instance_address;
1181
1182                         $hostname = $statistics->instance_address;
1183                 }
1184
1185                 if (!empty($statistics->users)) {
1186                         foreach ($statistics->users as $nick => $user) {
1187                                 $profile_url = $server . '/' . $user->nickname;
1188
1189                                 $contact = ['url' => $profile_url,
1190                                                 'name' => $user->fullname,
1191                                                 'addr' => $user->nickname . '@' . $hostname,
1192                                                 'nick' => $user->nickname,
1193                                                 "network" => Protocol::OSTATUS,
1194                                                 'photo' => System::baseUrl() . '/images/person-300.jpg'];
1195
1196                                 if (isset($user->bio)) {
1197                                         $contact['about'] = $user->bio;
1198                                 }
1199
1200                                 self::getId($contact);
1201                         }
1202                 }
1203         }
1204
1205         /**
1206          * @brief Asking GNU Social server on a regular base for their user data
1207          * @return void
1208          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1209          * @throws \ImagickException
1210          */
1211         public static function discoverGsUsers()
1212         {
1213                 $requery_days = intval(Config::get('system', 'poco_requery_days'));
1214
1215                 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1216
1217                 $r = DBA::select('gserver', ['nurl', 'url'], [
1218                         '`network` = ?
1219                         AND `last_contact` >= `last_failure`
1220                         AND `last_poco_query` < ?',
1221                         Protocol::OSTATUS,
1222                         $last_update
1223                 ], [
1224                         'limit' => 5,
1225                         'order' => ['RAND()']
1226                 ]);
1227
1228                 if (!DBA::isResult($r)) {
1229                         return;
1230                 }
1231
1232                 foreach ($r as $server) {
1233                         self::fetchGsUsers($server['url']);
1234                         DBA::update('gserver', ['last_poco_query' => DateTimeFormat::utcNow()], ['nurl' => $server['nurl']]);
1235                 }
1236         }
1237
1238         /**
1239          * Returns a random, global contact of the current node
1240          *
1241          * @return string The profile URL
1242          * @throws Exception
1243          */
1244         public static function getRandomUrl()
1245         {
1246                 $r = DBA::selectFirst('gcontact', ['url'], [
1247                         '`network` = ? 
1248                         AND `last_contact` >= `last_failure`  
1249                         AND `updated` > ?',
1250                         Protocol::DFRN,
1251                         DateTimeFormat::utc('now - 1 month'),
1252                 ], ['order' => ['RAND()']]);
1253
1254                 if (DBA::isResult($r)) {
1255                         return $r['url'];
1256                 }
1257
1258                 return '';
1259         }
1260 }