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