]> git.mxchange.org Git - friendica.git/blob - src/Model/GlobalContact.php
Merge pull request #3917 from annando/worker-again
[friendica.git] / src / Model / GlobalContact.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 Friendica\Core\Config;
9 use Friendica\Core\System;
10 use Friendica\Core\Worker;
11 use Friendica\Database\DBM;
12 use Friendica\Network\Probe;
13 use Friendica\Protocol\PortableContact;
14 use dba;
15 use Exception;
16
17 require_once 'include/datetime.php';
18 require_once 'include/network.php';
19 require_once 'include/html2bbcode.php';
20 require_once 'include/Contact.php';
21 require_once 'include/Photo.php';
22
23 /**
24  * @brief This class handles GlobalContact related functions
25  */
26 class GlobalContact
27 {
28         /**
29          * @brief Search global contact table by nick or name
30          *
31          * @param string $search Name or nick
32          * @param string $mode   Search mode (e.g. "community")
33          *
34          * @return array with search results
35          */
36         public static function searchByName($search, $mode = '')
37         {
38                 if ($search) {
39                         // check supported networks
40                         if (Config::get('system', 'diaspora_enabled')) {
41                                 $diaspora = NETWORK_DIASPORA;
42                         } else {
43                                 $diaspora = NETWORK_DFRN;
44                         }
45
46                         if (!Config::get('system', 'ostatus_disabled')) {
47                                 $ostatus = NETWORK_OSTATUS;
48                         } else {
49                                 $ostatus = NETWORK_DFRN;
50                         }
51
52                         // check if we search only communities or every contact
53                         if ($mode === "community") {
54                                 $extra_sql = " AND `community`";
55                         } else {
56                                 $extra_sql = "";
57                         }
58
59                         $search .= "%";
60
61                         $results = q(
62                                 "SELECT `contact`.`id` AS `cid`, `gcontact`.`url`, `gcontact`.`name`, `gcontact`.`nick`, `gcontact`.`photo`,
63                                                 `gcontact`.`network`, `gcontact`.`keywords`, `gcontact`.`addr`, `gcontact`.`community`
64                                 FROM `gcontact`
65                                 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl`
66                                         AND `contact`.`uid` = %d AND NOT `contact`.`blocked`
67                                         AND NOT `contact`.`pending` AND `contact`.`rel` IN ('%s', '%s')
68                                 WHERE (`contact`.`id` > 0 OR (NOT `gcontact`.`hide` AND `gcontact`.`network` IN ('%s', '%s', '%s') AND
69                                 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR
70                                 (`gcontact`.`updated` >= `gcontact`.`last_failure`)))) AND
71                                 (`gcontact`.`addr` LIKE '%s' OR `gcontact`.`name` LIKE '%s' OR `gcontact`.`nick` LIKE '%s') $extra_sql
72                                         GROUP BY `gcontact`.`nurl`
73                                         ORDER BY `gcontact`.`nurl` DESC
74                                         LIMIT 1000",
75                                 intval(local_user()),
76                                 dbesc(CONTACT_IS_SHARING),
77                                 dbesc(CONTACT_IS_FRIEND),
78                                 dbesc(NETWORK_DFRN),
79                                 dbesc($ostatus),
80                                 dbesc($diaspora),
81                                 dbesc(escape_tags($search)),
82                                 dbesc(escape_tags($search)),
83                                 dbesc(escape_tags($search))
84                         );
85
86                         return $results;
87                 }
88         }
89
90         /**
91          * @brief Link the gcontact entry with user, contact and global contact
92          *
93          * @param integer $gcid Global contact ID
94          * @param integer $uid  User ID
95          * @param integer $cid  Contact ID
96          * @param integer $zcid Global Contact ID
97          */
98         public static function link($gcid, $uid = 0, $cid = 0, $zcid = 0)
99         {
100                 if ($gcid <= 0) {
101                         return;
102                 }
103
104                 $r = q(
105                         "SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
106                         intval($cid),
107                         intval($uid),
108                         intval($gcid),
109                         intval($zcid)
110                 );
111
112                 if (!DBM::is_result($r)) {
113                         q(
114                                 "INSERT INTO `glink` (`cid`, `uid`, `gcid`, `zcid`, `updated`) VALUES (%d, %d, %d, %d, '%s') ",
115                                 intval($cid),
116                                 intval($uid),
117                                 intval($gcid),
118                                 intval($zcid),
119                                 dbesc(datetime_convert())
120                         );
121                 } else {
122                         q(
123                                 "UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
124                                 dbesc(datetime_convert()),
125                                 intval($cid),
126                                 intval($uid),
127                                 intval($gcid),
128                                 intval($zcid)
129                         );
130                 }
131         }
132
133         /**
134          * @brief Sanitize the given gcontact data
135          *
136          * @param array $gcontact array with gcontact data
137          * @throw Exception
138          *
139          * Generation:
140          *  0: No definition
141          *  1: Profiles on this server
142          *  2: Contacts of profiles on this server
143          *  3: Contacts of contacts of profiles on this server
144          *  4: ...
145          */
146         public static function sanitize($gcontact)
147         {
148                 if ($gcontact['url'] == "") {
149                         throw new Exception('URL is empty');
150                 }
151
152                 $urlparts = parse_url($gcontact['url']);
153                 if (!isset($urlparts["scheme"])) {
154                         throw new Exception("This (".$gcontact['url'].") doesn't seem to be an url.");
155                 }
156
157                 if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com", "identi.ca", "alpha.app.net"))) {
158                         throw new Exception('Contact from a non federated network ignored. ('.$gcontact['url'].')');
159                 }
160
161                 // Don't store the statusnet connector as network
162                 // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
163                 if ($gcontact['network'] == NETWORK_STATUSNET) {
164                         $gcontact['network'] = "";
165                 }
166
167                 // Assure that there are no parameter fragments in the profile url
168                 if (in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
169                         $gcontact['url'] = self::cleanContactUrl($gcontact['url']);
170                 }
171
172                 $alternate = PortableContact::alternateOStatusUrl($gcontact['url']);
173
174                 // The global contacts should contain the original picture, not the cached one
175                 if (($gcontact['generation'] != 1) && stristr(normalise_link($gcontact['photo']), normalise_link(System::baseUrl()."/photo/"))) {
176                         $gcontact['photo'] = "";
177                 }
178
179                 if (!isset($gcontact['network'])) {
180                         $r = q(
181                                 "SELECT `network` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
182                                 dbesc(normalise_link($gcontact['url'])),
183                                 dbesc(NETWORK_STATUSNET)
184                         );
185                         if (DBM::is_result($r)) {
186                                 $gcontact['network'] = $r[0]["network"];
187                         }
188
189                         if (($gcontact['network'] == "") || ($gcontact['network'] == NETWORK_OSTATUS)) {
190                                 $r = q(
191                                         "SELECT `network`, `url` FROM `contact` WHERE `uid` = 0 AND `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
192                                         dbesc($gcontact['url']),
193                                         dbesc(normalise_link($gcontact['url'])),
194                                         dbesc(NETWORK_STATUSNET)
195                                 );
196                                 if (DBM::is_result($r)) {
197                                         $gcontact['network'] = $r[0]["network"];
198                                 }
199                         }
200                 }
201
202                 $gcontact['server_url'] = '';
203                 $gcontact['network'] = '';
204
205                 $x = q(
206                         "SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
207                         dbesc(normalise_link($gcontact['url']))
208                 );
209
210                 if (DBM::is_result($x)) {
211                         if (!isset($gcontact['network']) && ($x[0]["network"] != NETWORK_STATUSNET)) {
212                                 $gcontact['network'] = $x[0]["network"];
213                         }
214                         if ($gcontact['updated'] <= NULL_DATE) {
215                                 $gcontact['updated'] = $x[0]["updated"];
216                         }
217                         if (!isset($gcontact['server_url']) && (normalise_link($x[0]["server_url"]) != normalise_link($x[0]["url"]))) {
218                                 $gcontact['server_url'] = $x[0]["server_url"];
219                         }
220                         if (!isset($gcontact['addr'])) {
221                                 $gcontact['addr'] = $x[0]["addr"];
222                         }
223                 }
224
225                 if ((!isset($gcontact['network']) || !isset($gcontact['name']) || !isset($gcontact['addr']) || !isset($gcontact['photo']) || !isset($gcontact['server_url']) || $alternate)
226                         && PortableContact::reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)
227                 ) {
228                         $data = Probe::uri($gcontact['url']);
229
230                         if ($data["network"] == NETWORK_PHANTOM) {
231                                 throw new Exception('Probing for URL '.$gcontact['url'].' failed');
232                         }
233
234                         $orig_profile = $gcontact['url'];
235
236                         $gcontact["server_url"] = $data["baseurl"];
237
238                         $gcontact = array_merge($gcontact, $data);
239
240                         if ($alternate && ($gcontact['network'] == NETWORK_OSTATUS)) {
241                                 // Delete the old entry - if it exists
242                                 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
243                                 if (DBM::is_result($r)) {
244                                         q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
245                                         q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
246                                 }
247                         }
248                 }
249
250                 if (!isset($gcontact['name']) || !isset($gcontact['photo'])) {
251                         throw new Exception('No name and photo for URL '.$gcontact['url']);
252                 }
253
254                 if (!in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA))) {
255                         throw new Exception('No federated network ('.$gcontact['network'].') detected for URL '.$gcontact['url']);
256                 }
257
258                 if (!isset($gcontact['server_url'])) {
259                         // We check the server url to be sure that it is a real one
260                         $server_url = PortableContact::detectServer($gcontact['url']);
261
262                         // We are now sure that it is a correct URL. So we use it in the future
263                         if ($server_url != "") {
264                                 $gcontact['server_url'] = $server_url;
265                         }
266                 }
267
268                 // The server URL doesn't seem to be valid, so we don't store it.
269                 if (!PortableContact::checkServer($gcontact['server_url'], $gcontact['network'])) {
270                         $gcontact['server_url'] = "";
271                 }
272
273                 return $gcontact;
274         }
275
276         public static function countCommonFriends($uid, $cid)
277         {
278                 $r = q(
279                         "SELECT count(*) as `total`
280                         FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
281                         WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
282                         ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR
283                         (`gcontact`.`updated` >= `gcontact`.`last_failure`))
284                         AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
285                         intval($cid),
286                         intval($uid),
287                         intval($uid),
288                         intval($cid)
289                 );
290
291                 // logger("countCommonFriends: $uid $cid {$r[0]['total']}");
292                 if (DBM::is_result($r)) {
293                         return $r[0]['total'];
294                 }
295                 return 0;
296         }
297
298         public static function countCommonFriendsZcid($uid, $zcid)
299         {
300                 $r = q(
301                         "SELECT count(*) as `total`
302                         FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
303                         where `glink`.`zcid` = %d
304                         and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
305                         intval($zcid),
306                         intval($uid)
307                 );
308
309                 if (DBM::is_result($r)) {
310                         return $r[0]['total'];
311                 }
312
313                 return 0;
314         }
315
316         public static function commonFriends($uid, $cid, $start = 0, $limit = 9999, $shuffle = false)
317         {
318                 if ($shuffle) {
319                         $sql_extra = " order by rand() ";
320                 } else {
321                         $sql_extra = " order by `gcontact`.`name` asc ";
322                 }
323
324                 $r = q(
325                         "SELECT `gcontact`.*, `contact`.`id` AS `cid`
326                         FROM `glink`
327                         INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
328                         INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
329                         WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
330                                 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
331                                 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
332                                 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
333                                 $sql_extra LIMIT %d, %d",
334                         intval($cid),
335                         intval($uid),
336                         intval($uid),
337                         intval($cid),
338                         intval($start),
339                         intval($limit)
340                 );
341
342                 /// @TODO Check all calling-findings of this function if they properly use DBM::is_result()
343                 return $r;
344         }
345
346         function commonFriendsZcid($uid, $zcid, $start = 0, $limit = 9999, $shuffle = false)
347         {
348                 if ($shuffle) {
349                         $sql_extra = " order by rand() ";
350                 } else {
351                         $sql_extra = " order by `gcontact`.`name` asc ";
352                 }
353
354                 $r = q(
355                         "SELECT `gcontact`.*
356                         FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
357                         where `glink`.`zcid` = %d
358                         and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
359                         $sql_extra limit %d, %d",
360                         intval($zcid),
361                         intval($uid),
362                         intval($start),
363                         intval($limit)
364                 );
365
366                 /// @TODO Check all calling-findings of this function if they properly use DBM::is_result()
367                 return $r;
368         }
369
370         public static function countAllFriends($uid, $cid)
371         {
372                 $r = q(
373                         "SELECT count(*) as `total`
374                         FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
375                         where `glink`.`cid` = %d and `glink`.`uid` = %d AND
376                         ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
377                         intval($cid),
378                         intval($uid)
379                 );
380
381                 if (DBM::is_result($r)) {
382                         return $r[0]['total'];
383                 }
384                 
385                 return 0;
386         }
387
388
389         public static function allFriends($uid, $cid, $start = 0, $limit = 80)
390         {
391                 $r = q(
392                         "SELECT `gcontact`.*, `contact`.`id` AS `cid`
393                         FROM `glink`
394                         INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
395                         LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
396                         WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
397                         ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
398                         ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
399                         intval($uid),
400                         intval($cid),
401                         intval($uid),
402                         intval($start),
403                         intval($limit)
404                 );
405
406                 /// @TODO Check all calling-findings of this function if they properly use DBM::is_result()
407                 return $r;
408         }
409
410         public static function suggestionQuery($uid, $start = 0, $limit = 80)
411         {
412                 if (!$uid) {
413                         return array();
414                 }
415
416                 /*
417                 * Uncommented because the result of the queries are to big to store it in the cache.
418                 * We need to decide if we want to change the db column type or if we want to delete it.
419                 */
420                 //$list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
421                 //if (!is_null($list)) {
422                 //      return $list;
423                 //}
424
425                 $network = array(NETWORK_DFRN);
426
427                 if (Config::get('system', 'diaspora_enabled')) {
428                         $network[] = NETWORK_DIASPORA;
429                 }
430
431                 if (!Config::get('system', 'ostatus_disabled')) {
432                         $network[] = NETWORK_OSTATUS;
433                 }
434
435                 $sql_network = implode("', '", $network);
436                 $sql_network = "'".$sql_network."'";
437
438                 /// @todo This query is really slow
439                 // By now we cache the data for five minutes
440                 $r = q(
441                         "SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
442                         INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
443                         where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
444                         AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
445                         AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
446                         AND `gcontact`.`updated` >= '%s'
447                         AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
448                         AND `gcontact`.`network` IN (%s)
449                         GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
450                         intval($uid),
451                         intval($uid),
452                         intval($uid),
453                         intval($uid),
454                         dbesc(NULL_DATE),
455                         $sql_network,
456                         intval($start),
457                         intval($limit)
458                 );
459
460                 if (DBM::is_result($r) && count($r) >= ($limit -1)) {
461                         /*
462                         * Uncommented because the result of the queries are to big to store it in the cache.
463                         * We need to decide if we want to change the db column type or if we want to delete it.
464                         */
465                         //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, CACHE_FIVE_MINUTES);
466
467                         return $r;
468                 }
469
470                 $r2 = q(
471                         "SELECT gcontact.* FROM gcontact
472                         INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
473                         WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
474                         AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
475                         AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
476                         AND `gcontact`.`updated` >= '%s'
477                         AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
478                         AND `gcontact`.`network` IN (%s)
479                         ORDER BY rand() LIMIT %d, %d",
480                         intval($uid),
481                         intval($uid),
482                         intval($uid),
483                         dbesc(NULL_DATE),
484                         $sql_network,
485                         intval($start),
486                         intval($limit)
487                 );
488
489                 $list = array();
490                 foreach ($r2 as $suggestion) {
491                         $list[$suggestion["nurl"]] = $suggestion;
492                 }
493
494                 foreach ($r as $suggestion) {
495                         $list[$suggestion["nurl"]] = $suggestion;
496                 }
497
498                 while (sizeof($list) > ($limit)) {
499                         array_pop($list);
500                 }
501
502                 /*
503                 * Uncommented because the result of the queries are to big to store it in the cache.
504                 * We need to decide if we want to change the db column type or if we want to delete it.
505                 */
506                 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, CACHE_FIVE_MINUTES);
507                 return $list;
508         }
509
510         public static function updateSuggestions()
511         {
512                 $a = get_app();
513
514                 $done = array();
515
516                 /// @TODO Check if it is really neccessary to poll the own server
517                 PortableContact::loadWorker(0, 0, 0, System::baseUrl() . '/poco');
518
519                 $done[] = System::baseUrl() . '/poco';
520
521                 if (strlen(Config::get('system', 'directory'))) {
522                         $x = fetch_url(get_server()."/pubsites");
523                         if ($x) {
524                                 $j = json_decode($x);
525                                 if ($j->entries) {
526                                         foreach ($j->entries as $entry) {
527                                                 PortableContact::checkServer($entry->url);
528
529                                                 $url = $entry->url . '/poco';
530                                                 if (! in_array($url, $done)) {
531                                                         PortableContact::loadWorker(0, 0, 0, $entry->url . '/poco');
532                                                 }
533                                         }
534                                 }
535                         }
536                 }
537
538                 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
539                 $r = q(
540                         "SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
541                         dbesc(NETWORK_DFRN),
542                         dbesc(NETWORK_DIASPORA)
543                 );
544
545                 if (DBM::is_result($r)) {
546                         foreach ($r as $rr) {
547                                 $base = substr($rr['poco'], 0, strrpos($rr['poco'], '/'));
548                                 if (! in_array($base, $done)) {
549                                         PortableContact::loadWorker(0, 0, 0, $base);
550                                 }
551                         }
552                 }
553         }
554
555         /**
556          * @brief Removes unwanted parts from a contact url
557          *
558          * @param string $url Contact url
559          *
560          * @return string Contact url with the wanted parts
561          */
562         public static function cleanContactUrl($url)
563         {
564                 $parts = parse_url($url);
565
566                 if (!isset($parts["scheme"]) || !isset($parts["host"])) {
567                         return $url;
568                 }
569
570                 $new_url = $parts["scheme"]."://".$parts["host"];
571
572                 if (isset($parts["port"])) {
573                         $new_url .= ":".$parts["port"];
574                 }
575
576                 if (isset($parts["path"])) {
577                         $new_url .= $parts["path"];
578                 }
579
580                 if ($new_url != $url) {
581                         logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".System::callstack(), LOGGER_DEBUG);
582                 }
583
584                 return $new_url;
585         }
586
587         /**
588          * @brief Replace alternate OStatus user format with the primary one
589          *
590          * @param arr $contact contact array (called by reference)
591          */
592         public static function fixAlternateContactAddress(&$contact)
593         {
594                 if (($contact["network"] == NETWORK_OSTATUS) && PortableContact::alternateOStatusUrl($contact["url"])) {
595                         $data = Probe::uri($contact["url"]);
596                         if ($contact["network"] == NETWORK_OSTATUS) {
597                                 logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
598                                 $contact["url"] = $data["url"];
599                                 $contact["addr"] = $data["addr"];
600                                 $contact["alias"] = $data["alias"];
601                                 $contact["server_url"] = $data["baseurl"];
602                         }
603                 }
604         }
605
606         /**
607          * @brief Fetch the gcontact id, add an entry if not existed
608          *
609          * @param arr $contact contact array
610          *
611          * @return bool|int Returns false if not found, integer if contact was found
612          */
613         public static function getId($contact)
614         {
615                 $gcontact_id = 0;
616                 $doprobing = false;
617
618                 if (in_array($contact["network"], array(NETWORK_PHANTOM))) {
619                         logger("Invalid network for contact url ".$contact["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
620                         return false;
621                 }
622
623                 if ($contact["network"] == NETWORK_STATUSNET) {
624                         $contact["network"] = NETWORK_OSTATUS;
625                 }
626
627                 // All new contacts are hidden by default
628                 if (!isset($contact["hide"])) {
629                         $contact["hide"] = true;
630                 }
631
632                 // Replace alternate OStatus user format with the primary one
633                 self::fixAlternateContactAddress($contact);
634
635                 // Remove unwanted parts from the contact url (e.g. "?zrl=...")
636                 if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))) {
637                         $contact["url"] = self::cleanContactUrl($contact["url"]);
638                 }
639
640                 dba::lock('gcontact');
641                 $r = q(
642                         "SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
643                         dbesc(normalise_link($contact["url"]))
644                 );
645
646                 if (DBM::is_result($r)) {
647                         $gcontact_id = $r[0]["id"];
648
649                         // Update every 90 days
650                         if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
651                                 $last_failure_str = $r[0]["last_failure"];
652                                 $last_failure = strtotime($r[0]["last_failure"]);
653                                 $last_contact_str = $r[0]["last_contact"];
654                                 $last_contact = strtotime($r[0]["last_contact"]);
655                                 $doprobing = (((time() - $last_contact) > (90 * 86400)) && ((time() - $last_failure) > (90 * 86400)));
656                         }
657                 } else {
658                         q(
659                                 "INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
660                                 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
661                                 dbesc($contact["name"]),
662                                 dbesc($contact["nick"]),
663                                 dbesc($contact["addr"]),
664                                 dbesc($contact["network"]),
665                                 dbesc($contact["url"]),
666                                 dbesc(normalise_link($contact["url"])),
667                                 dbesc($contact["photo"]),
668                                 dbesc(datetime_convert()),
669                                 dbesc(datetime_convert()),
670                                 dbesc($contact["location"]),
671                                 dbesc($contact["about"]),
672                                 intval($contact["hide"]),
673                                 intval($contact["generation"])
674                         );
675
676                         $r = q(
677                                 "SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
678                                 dbesc(normalise_link($contact["url"]))
679                         );
680
681                         if (DBM::is_result($r)) {
682                                 $gcontact_id = $r[0]["id"];
683
684                                 $doprobing = in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""));
685                         }
686                 }
687                 dba::unlock();
688
689                 if ($doprobing) {
690                         logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
691                         Worker::add(PRIORITY_LOW, 'GProbe', $contact["url"]);
692                 }
693
694                 return $gcontact_id;
695         }
696
697         /**
698          * @brief Updates the gcontact table from a given array
699          *
700          * @param arr $contact contact array
701          *
702          * @return bool|int Returns false if not found, integer if contact was found
703          */
704         public static function update($contact)
705         {
706                 // Check for invalid "contact-type" value
707                 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
708                         $contact['contact-type'] = 0;
709                 }
710
711                 /// @todo update contact table as well
712
713                 $gcontact_id = self::getId($contact);
714
715                 if (!$gcontact_id) {
716                         return false;
717                 }
718
719                 $r = q(
720                         "SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
721                                 `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
722                         FROM `gcontact` WHERE `id` = %d LIMIT 1",
723                         intval($gcontact_id)
724                 );
725
726                 // Get all field names
727                 $fields = array();
728                 foreach ($r[0] as $field => $data) {
729                         $fields[$field] = $data;
730                 }
731
732                 unset($fields["url"]);
733                 unset($fields["updated"]);
734                 unset($fields["hide"]);
735
736                 // Bugfix: We had an error in the storing of keywords which lead to the "0"
737                 // This value is still transmitted via poco.
738                 if ($contact["keywords"] == "0") {
739                         unset($contact["keywords"]);
740                 }
741
742                 if ($r[0]["keywords"] == "0") {
743                         $r[0]["keywords"] = "";
744                 }
745
746                 // assign all unassigned fields from the database entry
747                 foreach ($fields as $field => $data) {
748                         if (!isset($contact[$field]) || ($contact[$field] == "")) {
749                                 $contact[$field] = $r[0][$field];
750                         }
751                 }
752
753                 if (!isset($contact["hide"])) {
754                         $contact["hide"] = $r[0]["hide"];
755                 }
756
757                 $fields["hide"] = $r[0]["hide"];
758
759                 if ($contact["network"] == NETWORK_STATUSNET) {
760                         $contact["network"] = NETWORK_OSTATUS;
761                 }
762
763                 // Replace alternate OStatus user format with the primary one
764                 self::fixAlternateContactAddress($contact);
765
766                 if (!isset($contact["updated"])) {
767                         $contact["updated"] = DBM::date();
768                 }
769
770                 if ($contact["network"] == NETWORK_TWITTER) {
771                         $contact["server_url"] = 'http://twitter.com';
772                 }
773
774                 if ($contact["server_url"] == "") {
775                         $data = Probe::uri($contact["url"]);
776                         if ($data["network"] != NETWORK_PHANTOM) {
777                                 $contact["server_url"] = $data['baseurl'];
778                         }
779                 } else {
780                         $contact["server_url"] = normalise_link($contact["server_url"]);
781                 }
782
783                 if (($contact["addr"] == "") && ($contact["server_url"] != "") && ($contact["nick"] != "")) {
784                         $hostname = str_replace("http://", "", $contact["server_url"]);
785                         $contact["addr"] = $contact["nick"]."@".$hostname;
786                 }
787
788                 // Check if any field changed
789                 $update = false;
790                 unset($fields["generation"]);
791
792                 if ((($contact["generation"] > 0) && ($contact["generation"] <= $r[0]["generation"])) || ($r[0]["generation"] == 0)) {
793                         foreach ($fields as $field => $data) {
794                                 if ($contact[$field] != $r[0][$field]) {
795                                         logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
796                                         $update = true;
797                                 }
798                         }
799
800                         if ($contact["generation"] < $r[0]["generation"]) {
801                                 logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
802                                 $update = true;
803                         }
804                 }
805
806                 if ($update) {
807                         logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG);
808                         $condition = array('`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)',
809                                         normalise_link($contact["url"]), $contact["generation"]);
810                         $contact["updated"] = DBM::date($contact["updated"]);
811
812                         $updated = array('photo' => $contact['photo'], 'name' => $contact['name'],
813                                         'nick' => $contact['nick'], 'addr' => $contact['addr'],
814                                         'network' => $contact['network'], 'birthday' => $contact['birthday'],
815                                         'gender' => $contact['gender'], 'keywords' => $contact['keywords'],
816                                         'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
817                                         'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
818                                         'notify' => $contact['notify'], 'url' => $contact['url'],
819                                         'location' => $contact['location'], 'about' => $contact['about'],
820                                         'generation' => $contact['generation'], 'updated' => $contact['updated'],
821                                         'server_url' => $contact['server_url'], 'connect' => $contact['connect']);
822
823                         dba::update('gcontact', $updated, $condition, $fields);
824
825                         // Now update the contact entry with the user id "0" as well.
826                         // This is used for the shadow copies of public items.
827                         $r = q(
828                                 "SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
829                                 dbesc(normalise_link($contact["url"]))
830                         );
831
832                         if (DBM::is_result($r)) {
833                                 logger("Update public contact ".$r[0]["id"], LOGGER_DEBUG);
834
835                                 update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
836
837                                 $fields = array('name', 'nick', 'addr',
838                                                 'network', 'bd', 'gender',
839                                                 'keywords', 'alias', 'contact-type',
840                                                 'url', 'location', 'about');
841                                 $old_contact = dba::select('contact', $fields, array('id' => $r[0]["id"]), array('limit' => 1));
842
843                                 // Update it with the current values
844                                 $fields = array('name' => $contact['name'], 'nick' => $contact['nick'],
845                                                 'addr' => $contact['addr'], 'network' => $contact['network'],
846                                                 'bd' => $contact['birthday'], 'gender' => $contact['gender'],
847                                                 'keywords' => $contact['keywords'], 'alias' => $contact['alias'],
848                                                 'contact-type' => $contact['contact-type'], 'url' => $contact['url'],
849                                                 'location' => $contact['location'], 'about' => $contact['about']);
850
851                                 dba::update('contact', $fields, array('id' => $r[0]["id"]), $old_contact);
852                         }
853                 }
854
855                 return $gcontact_id;
856         }
857
858         /**
859          * @brief Updates the gcontact entry from probe
860          *
861          * @param str $url profile link
862          */
863         public static function updateFromProbe($url)
864         {
865                 $data = Probe::uri($url);
866
867                 if (in_array($data["network"], array(NETWORK_PHANTOM))) {
868                         logger("Invalid network for contact url ".$data["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
869                         return;
870                 }
871
872                 $data["server_url"] = $data["baseurl"];
873
874                 self::update($data);
875         }
876
877         /**
878          * @brief Update the gcontact entry for a given user id
879          *
880          * @param int $uid User ID
881          */
882         public static function updateForUser($uid)
883         {
884                 $r = q(
885                         "SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
886                                 `profile`.`name`, `profile`.`about`, `profile`.`gender`,
887                                 `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
888                                 `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
889                                 `contact`.`notify`, `contact`.`url`, `contact`.`addr`
890                         FROM `profile`
891                                 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
892                                 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
893                         WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
894                         intval($uid)
895                 );
896
897                 $location = formatted_location(
898                         array("locality" => $r[0]["locality"], "region" => $r[0]["region"], "country-name" => $r[0]["country-name"])
899                 );
900
901                 // The "addr" field was added in 3.4.3 so it can be empty for older users
902                 if ($r[0]["addr"] != "") {
903                         $addr = $r[0]["nickname"].'@'.str_replace(array("http://", "https://"), "", System::baseUrl());
904                 } else {
905                         $addr = $r[0]["addr"];
906                 }
907
908                 $gcontact = array("name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
909                                 "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
910                                 "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
911                                 "notify" => $r[0]["notify"], "url" => $r[0]["url"],
912                                 "hide" => ($r[0]["hidewall"] || !$r[0]["net-publish"]),
913                                 "nick" => $r[0]["nickname"], "addr" => $addr,
914                                 "connect" => $addr, "server_url" => System::baseUrl(),
915                                 "generation" => 1, "network" => NETWORK_DFRN);
916
917                 self::update($gcontact);
918         }
919
920         /**
921          * @brief Fetches users of given GNU Social server
922          *
923          * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
924          *
925          * @param str $server Server address
926          */
927         public static function fetchGsUsers($server)
928         {
929                 logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
930
931                 $url = $server."/main/statistics";
932
933                 $result = z_fetch_url($url);
934                 if (!$result["success"]) {
935                         return false;
936                 }
937
938                 $statistics = json_decode($result["body"]);
939
940                 if (is_object($statistics->config)) {
941                         if ($statistics->config->instance_with_ssl) {
942                                 $server = "https://";
943                         } else {
944                                 $server = "http://";
945                         }
946
947                         $server .= $statistics->config->instance_address;
948
949                         $hostname = $statistics->config->instance_address;
950                 } else {
951                         /// @TODO is_object() above means here no object, still $statistics is being used as object
952                         if ($statistics->instance_with_ssl) {
953                                 $server = "https://";
954                         } else {
955                                 $server = "http://";
956                         }
957
958                         $server .= $statistics->instance_address;
959
960                         $hostname = $statistics->instance_address;
961                 }
962
963                 if (is_object($statistics->users)) {
964                         foreach ($statistics->users as $nick => $user) {
965                                 $profile_url = $server."/".$user->nickname;
966
967                                 $contact = array("url" => $profile_url,
968                                                 "name" => $user->fullname,
969                                                 "addr" => $user->nickname."@".$hostname,
970                                                 "nick" => $user->nickname,
971                                                 "about" => $user->bio,
972                                                 "network" => NETWORK_OSTATUS,
973                                                 "photo" => System::baseUrl()."/images/person-175.jpg");
974                                 self::getId($contact);
975                         }
976                 }
977         }
978
979         /**
980          * @brief Asking GNU Social server on a regular base for their user data
981          *
982          */
983         public static function discoverGsUsers()
984         {
985                 $requery_days = intval(Config::get("system", "poco_requery_days"));
986
987                 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
988
989                 $r = q(
990                         "SELECT `nurl`, `url` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `network` = '%s' AND `last_poco_query` < '%s' ORDER BY RAND() LIMIT 5",
991                         dbesc(NETWORK_OSTATUS),
992                         dbesc($last_update)
993                 );
994
995                 if (!DBM::is_result($r)) {
996                         return;
997                 }
998
999                 foreach ($r as $server) {
1000                         self::fetchGsUsers($server["url"]);
1001                         q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1002                 }
1003         }
1004 }