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