]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
c888959d716499909c439e6edb28ea84f88aa330
[friendica.git] / include / diaspora.php
1 <?php
2 /**
3  * @file include/diaspora.php
4  * @brief The implementation of the diaspora protocol
5  *
6  * Checklist:
7  *
8  * Checked:
9  * - send status
10  * - send comment
11  * - send like
12  * - send mail
13  * - send status retraction
14  * - send comment retraction on own post
15  * - send like retraction on own post
16  * - send comment retraction on diaspora post
17  * - send like retraction on diaspora post
18  * - receive status
19  * - receive reshare
20  * - receive comment
21  * - receive like
22  * - receive connect request
23  * - receive profile data
24  * - receive mail
25  * - receive comment retraction
26  * - receive like retraction
27  * - relay comment
28  * - relay like
29  * - relay comment retraction from diaspora
30  * - relay comment retraction from friendica
31  * - relay like retraction from diaspora
32  * - relay like retraction from friendica
33  * - send share
34  *
35  * Should work:
36  * - receive account deletion
37  * - send unshare
38  *
39  * Unchecked:
40  */
41
42 require_once("include/items.php");
43 require_once("include/bb2diaspora.php");
44 require_once("include/Scrape.php");
45 require_once("include/Contact.php");
46 require_once("include/Photo.php");
47 require_once("include/socgraph.php");
48 require_once("include/group.php");
49 require_once("include/xml.php");
50 require_once("include/datetime.php");
51 require_once("include/queue_fn.php");
52
53 /**
54  * @brief This class contain functions to create and send Diaspora XML files
55  *
56  */
57 class diaspora {
58
59         public static function relay_list() {
60
61                 $serverdata = get_config("system", "relay_server");
62                 if ($serverdata == "")
63                         return array();
64
65                 $relay = array();
66
67                 $servers = explode(",", $serverdata);
68
69                 foreach($servers AS $server) {
70                         $server = trim($server);
71                         $batch = $server."/receive/public";
72
73                         $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
74
75                         if (!$relais) {
76                                 $addr = "relay@".str_replace("http://", "", normalise_link($server));
77
78                                 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
79                                         VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
80                                         datetime_convert(),
81                                         dbesc($addr),
82                                         dbesc($addr),
83                                         dbesc($server),
84                                         dbesc(normalise_link($server)),
85                                         dbesc($batch),
86                                         dbesc(NETWORK_DIASPORA),
87                                         intval(CONTACT_IS_FOLLOWER),
88                                         dbesc(datetime_convert()),
89                                         dbesc(datetime_convert()),
90                                         dbesc(datetime_convert())
91                                 );
92
93                                 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
94                                 if ($relais)
95                                         $relay[] = $relais[0];
96                         } else
97                                 $relay[] = $relais[0];
98                 }
99
100                 return $relay;
101         }
102
103         function repair_signature($signature, $handle = "", $level = 1) {
104
105                 if ($signature == "")
106                         return ($signature);
107
108                 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
109                         $signature = base64_decode($signature);
110                         logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
111
112                         // Do a recursive call to be able to fix even multiple levels
113                         if ($level < 10)
114                                 $signature = self::repair_signature($signature, $handle, ++$level);
115                 }
116
117                 return($signature);
118         }
119
120         /**
121          * @brief: Decodes incoming Diaspora message
122          *
123          * @param array $importer from user table
124          * @param string $xml urldecoded Diaspora salmon
125          *
126          * @return array
127          * 'message' -> decoded Diaspora XML message
128          * 'author' -> author diaspora handle
129          * 'key' -> author public key (converted to pkcs#8)
130          */
131         function decode($importer, $xml) {
132
133                 $public = false;
134                 $basedom = parse_xml_string($xml);
135
136                 if (!is_object($basedom))
137                         return false;
138
139                 $children = $basedom->children('https://joindiaspora.com/protocol');
140
141                 if($children->header) {
142                         $public = true;
143                         $author_link = str_replace('acct:','',$children->header->author_id);
144                 } else {
145
146                         $encrypted_header = json_decode(base64_decode($children->encrypted_header));
147
148                         $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
149                         $ciphertext = base64_decode($encrypted_header->ciphertext);
150
151                         $outer_key_bundle = '';
152                         openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
153
154                         $j_outer_key_bundle = json_decode($outer_key_bundle);
155
156                         $outer_iv = base64_decode($j_outer_key_bundle->iv);
157                         $outer_key = base64_decode($j_outer_key_bundle->key);
158
159                         $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
160
161
162                         $decrypted = pkcs5_unpad($decrypted);
163
164                         /**
165                          * $decrypted now contains something like
166                          *
167                          *  <decrypted_header>
168                          *     <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
169                          *     <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
170                          *     <author_id>galaxor@diaspora.priateship.org</author_id>
171                          *  </decrypted_header>
172                          */
173
174                         logger('decrypted: '.$decrypted, LOGGER_DEBUG);
175                         $idom = parse_xml_string($decrypted,false);
176
177                         $inner_iv = base64_decode($idom->iv);
178                         $inner_aes_key = base64_decode($idom->aes_key);
179
180                         $author_link = str_replace('acct:','',$idom->author_id);
181                 }
182
183                 $dom = $basedom->children(NAMESPACE_SALMON_ME);
184
185                 // figure out where in the DOM tree our data is hiding
186
187                 if($dom->provenance->data)
188                         $base = $dom->provenance;
189                 elseif($dom->env->data)
190                         $base = $dom->env;
191                 elseif($dom->data)
192                         $base = $dom;
193
194                 if (!$base) {
195                         logger('unable to locate salmon data in xml');
196                         http_status_exit(400);
197                 }
198
199
200                 // Stash the signature away for now. We have to find their key or it won't be good for anything.
201                 $signature = base64url_decode($base->sig);
202
203                 // unpack the  data
204
205                 // strip whitespace so our data element will return to one big base64 blob
206                 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
207
208
209                 // stash away some other stuff for later
210
211                 $type = $base->data[0]->attributes()->type[0];
212                 $keyhash = $base->sig[0]->attributes()->keyhash[0];
213                 $encoding = $base->encoding;
214                 $alg = $base->alg;
215
216
217                 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
218
219
220                 // decode the data
221                 $data = base64url_decode($data);
222
223
224                 if($public)
225                         $inner_decrypted = $data;
226                 else {
227
228                         // Decode the encrypted blob
229
230                         $inner_encrypted = base64_decode($data);
231                         $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
232                         $inner_decrypted = pkcs5_unpad($inner_decrypted);
233                 }
234
235                 if (!$author_link) {
236                         logger('Could not retrieve author URI.');
237                         http_status_exit(400);
238                 }
239                 // Once we have the author URI, go to the web and try to find their public key
240                 // (first this will look it up locally if it is in the fcontact cache)
241                 // This will also convert diaspora public key from pkcs#1 to pkcs#8
242
243                 logger('Fetching key for '.$author_link);
244                 $key = self::key($author_link);
245
246                 if (!$key) {
247                         logger('Could not retrieve author key.');
248                         http_status_exit(400);
249                 }
250
251                 $verify = rsa_verify($signed_data,$signature,$key);
252
253                 if (!$verify) {
254                         logger('Message did not verify. Discarding.');
255                         http_status_exit(400);
256                 }
257
258                 logger('Message verified.');
259
260                 return array('message' => (string)$inner_decrypted,
261                                 'author' => unxmlify($author_link),
262                                 'key' => (string)$key);
263
264         }
265
266
267         /**
268          * @brief Dispatches public messages and find the fitting receivers
269          *
270          * @param array $msg The post that will be dispatched
271          *
272          * @return bool Was the message accepted?
273          */
274         public static function dispatch_public($msg) {
275
276                 $enabled = intval(get_config("system", "diaspora_enabled"));
277                 if (!$enabled) {
278                         logger("diaspora is disabled");
279                         return false;
280                 }
281
282                 // Use a dummy importer to import the data for the public copy
283                 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
284                 $item_id = self::dispatch($importer,$msg);
285
286                 // Now distribute it to the followers
287                 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
288                         (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
289                         AND NOT `account_expired` AND NOT `account_removed`",
290                         dbesc(NETWORK_DIASPORA),
291                         dbesc($msg["author"])
292                 );
293                 if($r) {
294                         foreach($r as $rr) {
295                                 logger("delivering to: ".$rr["username"]);
296                                 self::dispatch($rr,$msg);
297                         }
298                 } else
299                         logger("No subscribers for ".$msg["author"]." ".print_r($msg, true));
300
301                 return $item_id;
302         }
303
304         /**
305          * @brief Dispatches the different message types to the different functions
306          *
307          * @param array $importer Array of the importer user
308          * @param array $msg The post that will be dispatched
309          *
310          * @return bool Was the message accepted?
311          */
312         public static function dispatch($importer, $msg) {
313
314                 // The sender is the handle of the contact that sent the message.
315                 // This will often be different with relayed messages (for example "like" and "comment")
316                 $sender = $msg["author"];
317
318                 if (!diaspora::valid_posting($msg, $fields)) {
319                         logger("Invalid posting");
320                         return false;
321                 }
322
323                 $type = $fields->getName();
324
325                 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
326
327                 switch ($type) {
328                         case "account_deletion":
329                                 return self::receive_account_deletion($importer, $fields);
330
331                         case "comment":
332                                 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
333
334                         case "conversation":
335                                 return self::receive_conversation($importer, $msg, $fields);
336
337                         case "like":
338                                 return self::receive_like($importer, $sender, $fields);
339
340                         case "message":
341                                 return self::receive_message($importer, $fields);
342
343                         case "participation": // Not implemented
344                                 return self::receive_participation($importer, $fields);
345
346                         case "photo": // Not implemented
347                                 return self::receive_photo($importer, $fields);
348
349                         case "poll_participation": // Not implemented
350                                 return self::receive_poll_participation($importer, $fields);
351
352                         case "profile":
353                                 return self::receive_profile($importer, $fields);
354
355                         case "request":
356                                 return self::receive_request($importer, $fields);
357
358                         case "reshare":
359                                 return self::receive_reshare($importer, $fields, $msg["message"]);
360
361                         case "retraction":
362                                 return self::receive_retraction($importer, $sender, $fields);
363
364                         case "status_message":
365                                 return self::receive_status_message($importer, $fields, $msg["message"]);
366
367                         default:
368                                 logger("Unknown message type ".$type);
369                                 return false;
370                 }
371
372                 return true;
373         }
374
375         /**
376          * @brief Checks if a posting is valid and fetches the data fields.
377          *
378          * This function does not only check the signature.
379          * It also does the conversion between the old and the new diaspora format.
380          *
381          * @param array $msg Array with the XML, the sender handle and the sender signature
382          * @param object $fields SimpleXML object that contains the posting when it is valid
383          *
384          * @return bool Is the posting valid?
385          */
386         private function valid_posting($msg, &$fields) {
387
388                 $data = parse_xml_string($msg["message"], false);
389
390                 if (!is_object($data))
391                         return false;
392
393                 $first_child = $data->getName();
394
395                 // Is this the new or the old version?
396                 if ($data->getName() == "XML") {
397                         $oldXML = true;
398                         foreach ($data->post->children() as $child)
399                                 $element = $child;
400                 } else {
401                         $oldXML = false;
402                         $element = $data;
403                 }
404
405                 $type = $element->getName();
406                 $orig_type = $type;
407
408                 // All retractions are handled identically from now on.
409                 // In the new version there will only be "retraction".
410                 if (in_array($type, array("signed_retraction", "relayable_retraction")))
411                         $type = "retraction";
412
413                 $fields = new SimpleXMLElement("<".$type."/>");
414
415                 $signed_data = "";
416
417                 foreach ($element->children() AS $fieldname => $entry) {
418                         if ($oldXML) {
419                                 // Translation for the old XML structure
420                                 if ($fieldname == "diaspora_handle")
421                                         $fieldname = "author";
422
423                                 if ($fieldname == "participant_handles")
424                                         $fieldname = "participants";
425
426                                 if (in_array($type, array("like", "participation"))) {
427                                         if ($fieldname == "target_type")
428                                                 $fieldname = "parent_type";
429                                 }
430
431                                 if ($fieldname == "sender_handle")
432                                         $fieldname = "author";
433
434                                 if ($fieldname == "recipient_handle")
435                                         $fieldname = "recipient";
436
437                                 if ($fieldname == "root_diaspora_id")
438                                         $fieldname = "root_author";
439
440                                 if ($type == "retraction") {
441                                         if ($fieldname == "post_guid")
442                                                 $fieldname = "target_guid";
443
444                                         if ($fieldname == "type")
445                                                 $fieldname = "target_type";
446                                 }
447                         }
448
449                         if ($fieldname == "author_signature")
450                                 $author_signature = base64_decode($entry);
451                         elseif ($fieldname == "parent_author_signature")
452                                 $parent_author_signature = base64_decode($entry);
453                         elseif ($fieldname != "target_author_signature") {
454                                 if ($signed_data != "") {
455                                         $signed_data .= ";";
456                                         $signed_data_parent .= ";";
457                                 }
458
459                                 $signed_data .= $entry;
460                         }
461                         if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
462                                 ($orig_type == "relayable_retraction"))
463                                 xml::copy($entry, $fields, $fieldname);
464                 }
465
466                 // This is something that shouldn't happen at all.
467                 if (in_array($type, array("status_message", "reshare", "profile")))
468                         if ($msg["author"] != $fields->author) {
469                                 logger("Message handle is not the same as envelope sender. Quitting this message.");
470                                 return false;
471                         }
472
473                 // Only some message types have signatures. So we quit here for the other types.
474                 if (!in_array($type, array("comment", "message", "like")))
475                         return true;
476
477                 // No author_signature? This is a must, so we quit.
478                 if (!isset($author_signature))
479                         return false;
480
481                 if (isset($parent_author_signature)) {
482                         $key = self::key($msg["author"]);
483
484                         if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256"))
485                                 return false;
486                 }
487
488                 $key = self::key($fields->author);
489
490                 return rsa_verify($signed_data, $author_signature, $key, "sha256");
491         }
492
493         /**
494          * @brief Fetches the public key for a given handle
495          *
496          * @param string $handle The handle
497          *
498          * @return string The public key
499          */
500         private function key($handle) {
501                 $handle = strval($handle);
502
503                 logger("Fetching diaspora key for: ".$handle);
504
505                 $r = self::person_by_handle($handle);
506                 if($r)
507                         return $r["pubkey"];
508
509                 return "";
510         }
511
512         /**
513          * @brief Fetches data for a given handle
514          *
515          * @param string $handle The handle
516          *
517          * @return array the queried data
518          */
519         private function person_by_handle($handle) {
520
521                 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
522                         dbesc(NETWORK_DIASPORA),
523                         dbesc($handle)
524                 );
525                 if ($r) {
526                         $person = $r[0];
527                         logger("In cache ".print_r($r,true), LOGGER_DEBUG);
528
529                         // update record occasionally so it doesn't get stale
530                         $d = strtotime($person["updated"]." +00:00");
531                         if ($d < strtotime("now - 14 days"))
532                                 $update = true;
533                 }
534
535                 if (!$person OR $update) {
536                         logger("create or refresh", LOGGER_DEBUG);
537                         $r = probe_url($handle, PROBE_DIASPORA);
538
539                         // Note that Friendica contacts will return a "Diaspora person"
540                         // if Diaspora connectivity is enabled on their server
541                         if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
542                                 self::add_fcontact($r, $update);
543                                 $person = $r;
544                         }
545                 }
546                 return $person;
547         }
548
549         /**
550          * @brief Updates the fcontact table
551          *
552          * @param array $arr The fcontact data
553          * @param bool $update Update or insert?
554          *
555          * @return string The id of the fcontact entry
556          */
557         private function add_fcontact($arr, $update = false) {
558
559                 if($update) {
560                         $r = q("UPDATE `fcontact` SET
561                                         `name` = '%s',
562                                         `photo` = '%s',
563                                         `request` = '%s',
564                                         `nick` = '%s',
565                                         `addr` = '%s',
566                                         `batch` = '%s',
567                                         `notify` = '%s',
568                                         `poll` = '%s',
569                                         `confirm` = '%s',
570                                         `alias` = '%s',
571                                         `pubkey` = '%s',
572                                         `updated` = '%s'
573                                 WHERE `url` = '%s' AND `network` = '%s'",
574                                         dbesc($arr["name"]),
575                                         dbesc($arr["photo"]),
576                                         dbesc($arr["request"]),
577                                         dbesc($arr["nick"]),
578                                         dbesc($arr["addr"]),
579                                         dbesc($arr["batch"]),
580                                         dbesc($arr["notify"]),
581                                         dbesc($arr["poll"]),
582                                         dbesc($arr["confirm"]),
583                                         dbesc($arr["alias"]),
584                                         dbesc($arr["pubkey"]),
585                                         dbesc(datetime_convert()),
586                                         dbesc($arr["url"]),
587                                         dbesc($arr["network"])
588                                 );
589                 } else {
590                         $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`,
591                                         `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
592                                 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
593                                         dbesc($arr["url"]),
594                                         dbesc($arr["name"]),
595                                         dbesc($arr["photo"]),
596                                         dbesc($arr["request"]),
597                                         dbesc($arr["nick"]),
598                                         dbesc($arr["addr"]),
599                                         dbesc($arr["batch"]),
600                                         dbesc($arr["notify"]),
601                                         dbesc($arr["poll"]),
602                                         dbesc($arr["confirm"]),
603                                         dbesc($arr["network"]),
604                                         dbesc($arr["alias"]),
605                                         dbesc($arr["pubkey"]),
606                                         dbesc(datetime_convert())
607                                 );
608                 }
609
610                 return $r;
611         }
612
613         public static function handle_from_contact($contact_id, $gcontact_id = 0) {
614                 $handle = False;
615
616                 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
617
618                 if ($gcontact_id != 0) {
619                         $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
620                                 intval($gcontact_id));
621                         if ($r)
622                                 return $r[0]["addr"];
623                 }
624
625                 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
626                         intval($contact_id));
627                 if ($r) {
628                         $contact = $r[0];
629
630                         logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
631
632                         if($contact['addr'] != "")
633                                 $handle = $contact['addr'];
634                         elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
635                                 $baseurl_start = strpos($contact['url'],'://') + 3;
636                                 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
637                                 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
638                                 $handle = $contact['nick'].'@'.$baseurl;
639                         }
640                 }
641
642                 return $handle;
643         }
644
645         private function contact_by_handle($uid, $handle) {
646                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
647                         intval($uid),
648                         dbesc($handle)
649                 );
650
651                 if ($r)
652                         return $r[0];
653
654                 $handle_parts = explode("@", $handle);
655                 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
656                 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
657                         dbesc(NETWORK_DFRN),
658                         intval($uid),
659                         dbesc($nurl_sql)
660                 );
661                 if($r)
662                         return $r[0];
663
664                 return false;
665         }
666
667         private function post_allow($importer, $contact, $is_comment = false) {
668
669                 // perhaps we were already sharing with this person. Now they're sharing with us.
670                 // That makes us friends.
671                 // Normally this should have handled by getting a request - but this could get lost
672                 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
673                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
674                                 intval(CONTACT_IS_FRIEND),
675                                 intval($contact["id"]),
676                                 intval($importer["uid"])
677                         );
678                         $contact["rel"] = CONTACT_IS_FRIEND;
679                         logger("defining user ".$contact["nick"]." as friend");
680                 }
681
682                 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
683                         return false;
684                 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
685                         return true;
686                 if($contact["rel"] == CONTACT_IS_FOLLOWER)
687                         if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
688                                 return true;
689
690                 // Messages for the global users are always accepted
691                 if ($importer["uid"] == 0)
692                         return true;
693
694                 return false;
695         }
696
697         private function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
698                 $contact = self::contact_by_handle($importer["uid"], $handle);
699                 if (!$contact) {
700                         logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
701                         return false;
702                 }
703
704                 if (!self::post_allow($importer, $contact, $is_comment)) {
705                         logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
706                         return false;
707                 }
708                 return $contact;
709         }
710
711         private function message_exists($uid, $guid) {
712                 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
713                         intval($uid),
714                         dbesc($guid)
715                 );
716
717                 if($r) {
718                         logger("message ".$guid." already exists for user ".$uid);
719                         return true;
720                 }
721
722                 return false;
723         }
724
725         private function fetch_guid($item) {
726                 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
727                         function ($match) use ($item){
728                                 return(self::fetch_guid_sub($match, $item));
729                         },$item["body"]);
730         }
731
732         private function fetch_guid_sub($match, $item) {
733                 if (!self::store_by_guid($match[1], $item["author-link"]))
734                         self::store_by_guid($match[1], $item["owner-link"]);
735         }
736
737         private function store_by_guid($guid, $server, $uid = 0) {
738                 $serverparts = parse_url($server);
739                 $server = $serverparts["scheme"]."://".$serverparts["host"];
740
741                 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
742
743                 $msg = self::message($guid, $server);
744
745                 if (!$msg)
746                         return false;
747
748                 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
749
750                 // Now call the dispatcher
751                 return self::dispatch_public($msg);
752         }
753
754         private function message($guid, $server, $level = 0) {
755
756                 if ($level > 5)
757                         return false;
758
759                 // This will work for Diaspora and newer Friendica servers
760                 $source_url = $server."/p/".$guid.".xml";
761                 $x = fetch_url($source_url);
762                 if(!$x)
763                         return false;
764
765                 $source_xml = parse_xml_string($x, false);
766
767                 if (!is_object($source_xml))
768                         return false;
769
770                 if ($source_xml->post->reshare) {
771                         // Reshare of a reshare - old Diaspora version
772                         return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
773                 } elseif ($source_xml->getName() == "reshare") {
774                         // Reshare of a reshare - new Diaspora version
775                         return self::message($source_xml->root_guid, $server, ++$level);
776                 }
777
778                 $author = "";
779
780                 // Fetch the author - for the old and the new Diaspora version
781                 if ($source_xml->post->status_message->diaspora_handle)
782                         $author = (string)$source_xml->post->status_message->diaspora_handle;
783                 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
784                         $author = (string)$source_xml->author;
785
786                 // If this isn't a "status_message" then quit
787                 if (!$author)
788                         return false;
789
790                 $msg = array("message" => $x, "author" => $author);
791
792                 $msg["key"] = self::key($msg["author"]);
793
794                 return $msg;
795         }
796
797         private function parent_item($uid, $guid, $author, $contact) {
798                 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
799                                 `author-name`, `author-link`, `author-avatar`,
800                                 `owner-name`, `owner-link`, `owner-avatar`
801                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
802                         intval($uid), dbesc($guid));
803
804                 if(!$r) {
805                         $result = self::store_by_guid($guid, $contact["url"], $uid);
806
807                         if (!$result) {
808                                 $person = self::person_by_handle($author);
809                                 $result = self::store_by_guid($guid, $person["url"], $uid);
810                         }
811
812                         if ($result) {
813                                 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
814
815                                 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
816                                                 `author-name`, `author-link`, `author-avatar`,
817                                                 `owner-name`, `owner-link`, `owner-avatar`
818                                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
819                                         intval($uid), dbesc($guid));
820                         }
821                 }
822
823                 if (!$r) {
824                         logger("parent item not found: parent: ".$guid." - user: ".$uid);
825                         return false;
826                 } else {
827                         logger("parent item found: parent: ".$guid." - user: ".$uid);
828                         return $r[0];
829                 }
830         }
831
832         private function author_contact_by_url($contact, $person, $uid) {
833
834                 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
835                         dbesc(normalise_link($person["url"])), intval($uid));
836                 if ($r) {
837                         $cid = $r[0]["id"];
838                         $network = $r[0]["network"];
839                 } else {
840                         $cid = $contact["id"];
841                         $network = NETWORK_DIASPORA;
842                 }
843
844                 return (array("cid" => $cid, "network" => $network));
845         }
846
847         public static function is_redmatrix($url) {
848                 return(strstr($url, "/channel/"));
849         }
850
851         private function plink($addr, $guid) {
852                 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
853
854                 // Fallback
855                 if (!$r)
856                         return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
857
858                 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
859                 // So we try another way as well.
860                 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
861                 if ($s)
862                         $r[0]["network"] = $s[0]["network"];
863
864                 if ($r[0]["network"] == NETWORK_DFRN)
865                         return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
866
867                 if (self::is_redmatrix($r[0]["url"]))
868                         return $r[0]["url"]."/?f=&mid=".$guid;
869
870                 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
871         }
872
873         private function receive_account_deletion($importer, $data) {
874                 $author = notags(unxmlify($data->author));
875
876                 $contact = self::contact_by_handle($importer["uid"], $author);
877                 if (!$contact) {
878                         logger("cannot find contact for author: ".$author);
879                         return false;
880                 }
881
882                 // We now remove the contact
883                 contact_remove($contact["id"]);
884                 return true;
885         }
886
887         private function receive_comment($importer, $sender, $data, $xml) {
888                 $guid = notags(unxmlify($data->guid));
889                 $parent_guid = notags(unxmlify($data->parent_guid));
890                 $text = unxmlify($data->text);
891                 $author = notags(unxmlify($data->author));
892
893                 $contact = self::allowed_contact_by_handle($importer, $sender, true);
894                 if (!$contact)
895                         return false;
896
897                 if (self::message_exists($importer["uid"], $guid))
898                         return false;
899
900                 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
901                 if (!$parent_item)
902                         return false;
903
904                 $person = self::person_by_handle($author);
905                 if (!is_array($person)) {
906                         logger("unable to find author details");
907                         return false;
908                 }
909
910                 // Fetch the contact id - if we know this contact
911                 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
912
913                 $datarray = array();
914
915                 $datarray["uid"] = $importer["uid"];
916                 $datarray["contact-id"] = $author_contact["cid"];
917                 $datarray["network"]  = $author_contact["network"];
918
919                 $datarray["author-name"] = $person["name"];
920                 $datarray["author-link"] = $person["url"];
921                 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
922
923                 $datarray["owner-name"] = $contact["name"];
924                 $datarray["owner-link"] = $contact["url"];
925                 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
926
927                 $datarray["guid"] = $guid;
928                 $datarray["uri"] = $author.":".$guid;
929
930                 $datarray["type"] = "remote-comment";
931                 $datarray["verb"] = ACTIVITY_POST;
932                 $datarray["gravity"] = GRAVITY_COMMENT;
933                 $datarray["parent-uri"] = $parent_item["uri"];
934
935                 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
936                 $datarray["object"] = $xml;
937
938                 $datarray["body"] = diaspora2bb($text);
939
940                 self::fetch_guid($datarray);
941
942                 $message_id = item_store($datarray);
943
944                 if ($message_id)
945                         logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
946
947                 // If we are the origin of the parent we store the original data and notify our followers
948                 if($message_id AND $parent_item["origin"]) {
949
950                         // Formerly we stored the signed text, the signature and the author in different fields.
951                         // We now store the raw data so that we are more flexible.
952                         q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
953                                 intval($message_id),
954                                 dbesc(json_encode($data))
955                         );
956
957                         // notify others
958                         proc_run("php", "include/notifier.php", "comment-import", $message_id);
959                 }
960
961                 return $message_id;
962         }
963
964         private function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
965                 $guid = notags(unxmlify($data->guid));
966                 $subject = notags(unxmlify($data->subject));
967                 $author = notags(unxmlify($data->author));
968
969                 $reply = 0;
970
971                 $msg_guid = notags(unxmlify($mesg->guid));
972                 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
973                 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
974                 $msg_author_signature = notags(unxmlify($mesg->author_signature));
975                 $msg_text = unxmlify($mesg->text);
976                 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
977
978                 // "diaspora_handle" is the element name from the old version
979                 // "author" is the element name from the new version
980                 if ($mesg->author)
981                         $msg_author = notags(unxmlify($mesg->author));
982                 elseif ($mesg->diaspora_handle)
983                         $msg_author = notags(unxmlify($mesg->diaspora_handle));
984                 else
985                         return false;
986
987                 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
988
989                 if($msg_conversation_guid != $guid) {
990                         logger("message conversation guid does not belong to the current conversation.");
991                         return false;
992                 }
993
994                 $body = diaspora2bb($msg_text);
995                 $message_uri = $msg_author.":".$msg_guid;
996
997                 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
998
999                 $author_signature = base64_decode($msg_author_signature);
1000
1001                 if(strcasecmp($msg_author,$msg["author"]) == 0) {
1002                         $person = $contact;
1003                         $key = $msg["key"];
1004                 } else {
1005                         $person = self::person_by_handle($msg_author);
1006
1007                         if (is_array($person) && x($person, "pubkey"))
1008                                 $key = $person["pubkey"];
1009                         else {
1010                                 logger("unable to find author details");
1011                                         return false;
1012                         }
1013                 }
1014
1015                 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
1016                         logger("verification failed.");
1017                         return false;
1018                 }
1019
1020                 if($msg_parent_author_signature) {
1021                         $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1022
1023                         $parent_author_signature = base64_decode($msg_parent_author_signature);
1024
1025                         $key = $msg["key"];
1026
1027                         if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
1028                                 logger("owner verification failed.");
1029                                 return false;
1030                         }
1031                 }
1032
1033                 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
1034                         dbesc($message_uri)
1035                 );
1036                 if($r) {
1037                         logger("duplicate message already delivered.", LOGGER_DEBUG);
1038                         return false;
1039                 }
1040
1041                 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1042                         VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1043                         intval($importer["uid"]),
1044                         dbesc($msg_guid),
1045                         intval($conversation["id"]),
1046                         dbesc($person["name"]),
1047                         dbesc($person["photo"]),
1048                         dbesc($person["url"]),
1049                         intval($contact["id"]),
1050                         dbesc($subject),
1051                         dbesc($body),
1052                         0,
1053                         0,
1054                         dbesc($message_uri),
1055                         dbesc($author.":".$guid),
1056                         dbesc($msg_created_at)
1057                 );
1058
1059                 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1060                         dbesc(datetime_convert()),
1061                         intval($conversation["id"])
1062                 );
1063
1064                 notification(array(
1065                         "type" => NOTIFY_MAIL,
1066                         "notify_flags" => $importer["notify-flags"],
1067                         "language" => $importer["language"],
1068                         "to_name" => $importer["username"],
1069                         "to_email" => $importer["email"],
1070                         "uid" =>$importer["uid"],
1071                         "item" => array("subject" => $subject, "body" => $body),
1072                         "source_name" => $person["name"],
1073                         "source_link" => $person["url"],
1074                         "source_photo" => $person["thumb"],
1075                         "verb" => ACTIVITY_POST,
1076                         "otype" => "mail"
1077                 ));
1078         }
1079
1080         private function receive_conversation($importer, $msg, $data) {
1081                 $guid = notags(unxmlify($data->guid));
1082                 $subject = notags(unxmlify($data->subject));
1083                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1084                 $author = notags(unxmlify($data->author));
1085                 $participants = notags(unxmlify($data->participants));
1086
1087                 $messages = $data->message;
1088
1089                 if (!count($messages)) {
1090                         logger("empty conversation");
1091                         return false;
1092                 }
1093
1094                 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1095                 if (!$contact)
1096                         return false;
1097
1098                 $conversation = null;
1099
1100                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1101                         intval($importer["uid"]),
1102                         dbesc($guid)
1103                 );
1104                 if($c)
1105                         $conversation = $c[0];
1106                 else {
1107                         $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1108                                 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1109                                 intval($importer["uid"]),
1110                                 dbesc($guid),
1111                                 dbesc($author),
1112                                 dbesc(datetime_convert("UTC", "UTC", $created_at)),
1113                                 dbesc(datetime_convert()),
1114                                 dbesc($subject),
1115                                 dbesc($participants)
1116                         );
1117                         if($r)
1118                                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1119                                         intval($importer["uid"]),
1120                                         dbesc($guid)
1121                                 );
1122
1123                         if($c)
1124                                 $conversation = $c[0];
1125                 }
1126                 if (!$conversation) {
1127                         logger("unable to create conversation.");
1128                         return;
1129                 }
1130
1131                 foreach($messages as $mesg)
1132                         self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1133
1134                 return true;
1135         }
1136
1137         private function construct_like_body($contact, $parent_item, $guid) {
1138                 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1139
1140                 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1141                 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1142                 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1143
1144                 return sprintf($bodyverb, $ulink, $alink, $plink);
1145         }
1146
1147         private function construct_like_object($importer, $parent_item) {
1148                 $objtype = ACTIVITY_OBJ_NOTE;
1149                 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1150                 $parent_body = $parent_item["body"];
1151
1152                 $xmldata = array("object" => array("type" => $objtype,
1153                                                 "local" => "1",
1154                                                 "id" => $parent_item["uri"],
1155                                                 "link" => $link,
1156                                                 "title" => "",
1157                                                 "content" => $parent_body));
1158
1159                 return xml::from_array($xmldata, $xml, true);
1160         }
1161
1162         private function receive_like($importer, $sender, $data) {
1163                 $positive = notags(unxmlify($data->positive));
1164                 $guid = notags(unxmlify($data->guid));
1165                 $parent_type = notags(unxmlify($data->parent_type));
1166                 $parent_guid = notags(unxmlify($data->parent_guid));
1167                 $author = notags(unxmlify($data->author));
1168
1169                 // likes on comments aren't supported by Diaspora - only on posts
1170                 // But maybe this will be supported in the future, so we will accept it.
1171                 if (!in_array($parent_type, array("Post", "Comment")))
1172                         return false;
1173
1174                 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1175                 if (!$contact)
1176                         return false;
1177
1178                 if (self::message_exists($importer["uid"], $guid))
1179                         return false;
1180
1181                 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1182                 if (!$parent_item)
1183                         return false;
1184
1185                 $person = self::person_by_handle($author);
1186                 if (!is_array($person)) {
1187                         logger("unable to find author details");
1188                         return false;
1189                 }
1190
1191                 // Fetch the contact id - if we know this contact
1192                 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1193
1194                 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1195                 // We would accept this anyhow.
1196                 if ($positive === "true")
1197                         $verb = ACTIVITY_LIKE;
1198                 else
1199                         $verb = ACTIVITY_DISLIKE;
1200
1201                 $datarray = array();
1202
1203                 $datarray["uid"] = $importer["uid"];
1204                 $datarray["contact-id"] = $author_contact["cid"];
1205                 $datarray["network"]  = $author_contact["network"];
1206
1207                 $datarray["author-name"] = $person["name"];
1208                 $datarray["author-link"] = $person["url"];
1209                 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1210
1211                 $datarray["owner-name"] = $contact["name"];
1212                 $datarray["owner-link"] = $contact["url"];
1213                 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1214
1215                 $datarray["guid"] = $guid;
1216                 $datarray["uri"] = $author.":".$guid;
1217
1218                 $datarray["type"] = "activity";
1219                 $datarray["verb"] = $verb;
1220                 $datarray["gravity"] = GRAVITY_LIKE;
1221                 $datarray["parent-uri"] = $parent_item["uri"];
1222
1223                 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1224                 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1225
1226                 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1227
1228                 $message_id = item_store($datarray);
1229
1230                 if ($message_id)
1231                         logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1232
1233                 // If we are the origin of the parent we store the original data and notify our followers
1234                 if($message_id AND $parent_item["origin"]) {
1235
1236                         // Formerly we stored the signed text, the signature and the author in different fields.
1237                         // We now store the raw data so that we are more flexible.
1238                         q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1239                                 intval($message_id),
1240                                 dbesc(json_encode($data))
1241                         );
1242
1243                         // notify others
1244                         proc_run("php", "include/notifier.php", "comment-import", $message_id);
1245                 }
1246
1247                 return $message_id;
1248         }
1249
1250         private function receive_message($importer, $data) {
1251                 $guid = notags(unxmlify($data->guid));
1252                 $parent_guid = notags(unxmlify($data->parent_guid));
1253                 $text = unxmlify($data->text);
1254                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1255                 $author = notags(unxmlify($data->author));
1256                 $conversation_guid = notags(unxmlify($data->conversation_guid));
1257
1258                 $contact = self::allowed_contact_by_handle($importer, $author, true);
1259                 if (!$contact)
1260                         return false;
1261
1262                 $conversation = null;
1263
1264                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1265                         intval($importer["uid"]),
1266                         dbesc($conversation_guid)
1267                 );
1268                 if($c)
1269                         $conversation = $c[0];
1270                 else {
1271                         logger("conversation not available.");
1272                         return false;
1273                 }
1274
1275                 $reply = 0;
1276
1277                 $body = diaspora2bb($text);
1278                 $message_uri = $author.":".$guid;
1279
1280                 $person = self::person_by_handle($author);
1281                 if (!$person) {
1282                         logger("unable to find author details");
1283                         return false;
1284                 }
1285
1286                 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1287                         dbesc($message_uri),
1288                         intval($importer["uid"])
1289                 );
1290                 if($r) {
1291                         logger("duplicate message already delivered.", LOGGER_DEBUG);
1292                         return false;
1293                 }
1294
1295                 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1296                                 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1297                         intval($importer["uid"]),
1298                         dbesc($guid),
1299                         intval($conversation["id"]),
1300                         dbesc($person["name"]),
1301                         dbesc($person["photo"]),
1302                         dbesc($person["url"]),
1303                         intval($contact["id"]),
1304                         dbesc($conversation["subject"]),
1305                         dbesc($body),
1306                         0,
1307                         1,
1308                         dbesc($message_uri),
1309                         dbesc($author.":".$parent_guid),
1310                         dbesc($created_at)
1311                 );
1312
1313                 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1314                         dbesc(datetime_convert()),
1315                         intval($conversation["id"])
1316                 );
1317
1318                 return true;
1319         }
1320
1321         private function receive_participation($importer, $data) {
1322                 // I'm not sure if we can fully support this message type
1323                 return true;
1324         }
1325
1326         private function receive_photo($importer, $data) {
1327                 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1328                 return true;
1329         }
1330
1331         private function receive_poll_participation($importer, $data) {
1332                 // We don't support polls by now
1333                 return true;
1334         }
1335
1336         private function receive_profile($importer, $data) {
1337                 $author = notags(unxmlify($data->author));
1338
1339                 $contact = self::contact_by_handle($importer["uid"], $author);
1340                 if (!$contact)
1341                         return;
1342
1343                 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1344                 $image_url = unxmlify($data->image_url);
1345                 $birthday = unxmlify($data->birthday);
1346                 $location = diaspora2bb(unxmlify($data->location));
1347                 $about = diaspora2bb(unxmlify($data->bio));
1348                 $gender = unxmlify($data->gender);
1349                 $searchable = (unxmlify($data->searchable) == "true");
1350                 $nsfw = (unxmlify($data->nsfw) == "true");
1351                 $tags = unxmlify($data->tag_string);
1352
1353                 $tags = explode("#", $tags);
1354
1355                 $keywords = array();
1356                 foreach ($tags as $tag) {
1357                         $tag = trim(strtolower($tag));
1358                         if ($tag != "")
1359                                 $keywords[] = $tag;
1360                 }
1361
1362                 $keywords = implode(", ", $keywords);
1363
1364                 $handle_parts = explode("@", $author);
1365                 $nick = $handle_parts[0];
1366
1367                 if($name === "")
1368                         $name = $handle_parts[0];
1369
1370                 if( preg_match("|^https?://|", $image_url) === 0)
1371                         $image_url = "http://".$handle_parts[1].$image_url;
1372
1373                 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1374
1375                 // Generic birthday. We don't know the timezone. The year is irrelevant.
1376
1377                 $birthday = str_replace("1000", "1901", $birthday);
1378
1379                 if ($birthday != "")
1380                         $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1381
1382                 // this is to prevent multiple birthday notifications in a single year
1383                 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1384
1385                 if(substr($birthday,5) === substr($contact["bd"],5))
1386                         $birthday = $contact["bd"];
1387
1388                 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1389                                 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1390                         dbesc($name),
1391                         dbesc($nick),
1392                         dbesc($author),
1393                         dbesc(datetime_convert()),
1394                         dbesc($birthday),
1395                         dbesc($location),
1396                         dbesc($about),
1397                         dbesc($keywords),
1398                         dbesc($gender),
1399                         intval($contact["id"]),
1400                         intval($importer["uid"])
1401                 );
1402
1403                 if ($searchable) {
1404                         poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1405                                 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1406                 }
1407
1408                 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1409                                         "photo" => $image_url, "name" => $name, "location" => $location,
1410                                         "about" => $about, "birthday" => $birthday, "gender" => $gender,
1411                                         "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1412                                         "hide" => !$searchable, "nsfw" => $nsfw);
1413
1414                 update_gcontact($gcontact);
1415
1416                 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1417
1418                 return true;
1419         }
1420
1421         private function receive_request_make_friend($importer, $contact) {
1422
1423                 $a = get_app();
1424
1425                 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1426                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1427                                 intval(CONTACT_IS_FRIEND),
1428                                 intval($contact["id"]),
1429                                 intval($importer["uid"])
1430                         );
1431                 }
1432                 // send notification
1433
1434                 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1435                         intval($importer["uid"])
1436                 );
1437
1438                 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1439
1440                         $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1441                                 intval($importer["uid"])
1442                         );
1443
1444                         // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1445
1446                         if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1447
1448                                 $arr = array();
1449                                 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1450                                 $arr["uid"] = $importer["uid"];
1451                                 $arr["contact-id"] = $self[0]["id"];
1452                                 $arr["wall"] = 1;
1453                                 $arr["type"] = 'wall';
1454                                 $arr["gravity"] = 0;
1455                                 $arr["origin"] = 1;
1456                                 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1457                                 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1458                                 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1459                                 $arr["verb"] = ACTIVITY_FRIEND;
1460                                 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1461
1462                                 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1463                                 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1464                                 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1465                                 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1466
1467                                 $arr["object"] = "<object><type>".ACTIVITY_OBJ_PERSON."</type><title>".$contact["name"]."</title>"
1468                                         ."<id>".$contact["url"]."/".$contact["name"]."</id>";
1469                                 $arr["object"] .= "<link>".xmlify('<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n");
1470                                 $arr["object"] .= xmlify('<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n");
1471                                 $arr["object"] .= "</link></object>\n";
1472                                 $arr["last-child"] = 1;
1473
1474                                 $arr["allow_cid"] = $user[0]["allow_cid"];
1475                                 $arr["allow_gid"] = $user[0]["allow_gid"];
1476                                 $arr["deny_cid"]  = $user[0]["deny_cid"];
1477                                 $arr["deny_gid"]  = $user[0]["deny_gid"];
1478
1479                                 $i = item_store($arr);
1480                                 if($i)
1481                                         proc_run("php", "include/notifier.php", "activity", $i);
1482
1483                         }
1484
1485                 }
1486         }
1487
1488         private function receive_request($importer, $data) {
1489                 $author = unxmlify($data->author);
1490                 $recipient = unxmlify($data->recipient);
1491
1492                 if (!$author || !$recipient)
1493                         return;
1494
1495                 $contact = self::contact_by_handle($importer["uid"],$author);
1496
1497                 if($contact) {
1498
1499                         // perhaps we were already sharing with this person. Now they're sharing with us.
1500                         // That makes us friends.
1501
1502                         self::receive_request_make_friend($importer, $contact);
1503                         return true;
1504                 }
1505
1506                 $ret = self::person_by_handle($author);
1507
1508                 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
1509                         logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
1510                         return false;
1511                 }
1512
1513                 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
1514
1515                 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1516                         VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
1517                         intval($importer["uid"]),
1518                         dbesc($ret["network"]),
1519                         dbesc($ret["addr"]),
1520                         datetime_convert(),
1521                         dbesc($ret["url"]),
1522                         dbesc(normalise_link($ret["url"])),
1523                         dbesc($batch),
1524                         dbesc($ret["name"]),
1525                         dbesc($ret["nick"]),
1526                         dbesc($ret["photo"]),
1527                         dbesc($ret["pubkey"]),
1528                         dbesc($ret["notify"]),
1529                         dbesc($ret["poll"]),
1530                         1,
1531                         2
1532                 );
1533
1534                 // find the contact record we just created
1535
1536                 $contact_record = self::contact_by_handle($importer["uid"],$author);
1537
1538                 if (!$contact_record) {
1539                         logger("unable to locate newly created contact record.");
1540                         return;
1541                 }
1542
1543                 $g = q("SELECT `def_gid` FROM `user` WHERE `uid` = %d LIMIT 1",
1544                         intval($importer["uid"])
1545                 );
1546
1547                 if($g && intval($g[0]["def_gid"]))
1548                         group_add_member($importer["uid"], "", $contact_record["id"], $g[0]["def_gid"]);
1549
1550                 if($importer["page-flags"] == PAGE_NORMAL) {
1551
1552                         $hash = random_string().(string)time();   // Generate a confirm_key
1553
1554                         $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
1555                                 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
1556                                 intval($importer["uid"]),
1557                                 intval($contact_record["id"]),
1558                                 0,
1559                                 0,
1560                                 dbesc(t("Sharing notification from Diaspora network")),
1561                                 dbesc($hash),
1562                                 dbesc(datetime_convert())
1563                         );
1564                 } else {
1565
1566                         // automatic friend approval
1567
1568                         update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1569
1570                         // technically they are sharing with us (CONTACT_IS_SHARING),
1571                         // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1572                         // we are going to change the relationship and make them a follower.
1573
1574                         if($importer["page-flags"] == PAGE_FREELOVE)
1575                                 $new_relation = CONTACT_IS_FRIEND;
1576                         else
1577                                 $new_relation = CONTACT_IS_FOLLOWER;
1578
1579                         $r = q("UPDATE `contact` SET `rel` = %d,
1580                                 `name-date` = '%s',
1581                                 `uri-date` = '%s',
1582                                 `blocked` = 0,
1583                                 `pending` = 0,
1584                                 `writable` = 1
1585                                 WHERE `id` = %d
1586                                 ",
1587                                 intval($new_relation),
1588                                 dbesc(datetime_convert()),
1589                                 dbesc(datetime_convert()),
1590                                 intval($contact_record["id"])
1591                         );
1592
1593                         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1594                         if($u)
1595                                 $ret = self::send_share($u[0], $contact_record);
1596                 }
1597
1598                 return true;
1599         }
1600
1601         private function original_item($guid, $orig_author, $author) {
1602
1603                 // Do we already have this item?
1604                 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1605                                 `author-name`, `author-link`, `author-avatar`
1606                                 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1607                         dbesc($guid));
1608
1609                 if($r) {
1610                         logger("reshared message ".$guid." already exists on system.");
1611
1612                         // Maybe it is already a reshared item?
1613                         // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1614                         if (self::is_reshare($r[0]["body"], false))
1615                                 $r = array();
1616                         else
1617                                 return $r[0];
1618                 }
1619
1620                 if (!$r) {
1621                         $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
1622                         logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1623                         $item_id = self::store_by_guid($guid, $server);
1624
1625                         if (!$item_id) {
1626                                 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
1627                                 logger("2nd try: reshared message ".$guid." will be fetched from original server: ".$server);
1628                                 $item_id = self::store_by_guid($guid, $server);
1629                         }
1630
1631                         // Deactivated by now since there is a risk that someone could manipulate postings through this method
1632 /*                      if (!$item_id) {
1633                                 $server = "https://".substr($author, strpos($author, "@") + 1);
1634                                 logger("3rd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1635                                 $item_id = self::store_by_guid($guid, $server);
1636                         }
1637                         if (!$item_id) {
1638                                 $server = "http://".substr($author, strpos($author, "@") + 1);
1639                                 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1640                                 $item_id = self::store_by_guid($guid, $server);
1641                         }
1642 */
1643                         if ($item_id) {
1644                                 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1645                                                 `author-name`, `author-link`, `author-avatar`
1646                                         FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1647                                         intval($item_id));
1648
1649                                 if ($r)
1650                                         return $r[0];
1651
1652                         }
1653                 }
1654                 return false;
1655         }
1656
1657         private function receive_reshare($importer, $data, $xml) {
1658                 $root_author = notags(unxmlify($data->root_author));
1659                 $root_guid = notags(unxmlify($data->root_guid));
1660                 $guid = notags(unxmlify($data->guid));
1661                 $author = notags(unxmlify($data->author));
1662                 $public = notags(unxmlify($data->public));
1663                 $created_at = notags(unxmlify($data->created_at));
1664
1665                 $contact = self::allowed_contact_by_handle($importer, $author, false);
1666                 if (!$contact)
1667                         return false;
1668
1669                 if (self::message_exists($importer["uid"], $guid))
1670                         return false;
1671
1672                 $original_item = self::original_item($root_guid, $root_author, $author);
1673                 if (!$original_item)
1674                         return false;
1675
1676                 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
1677
1678                 $datarray = array();
1679
1680                 $datarray["uid"] = $importer["uid"];
1681                 $datarray["contact-id"] = $contact["id"];
1682                 $datarray["network"]  = NETWORK_DIASPORA;
1683
1684                 $datarray["author-name"] = $contact["name"];
1685                 $datarray["author-link"] = $contact["url"];
1686                 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1687
1688                 $datarray["owner-name"] = $datarray["author-name"];
1689                 $datarray["owner-link"] = $datarray["author-link"];
1690                 $datarray["owner-avatar"] = $datarray["author-avatar"];
1691
1692                 $datarray["guid"] = $guid;
1693                 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1694
1695                 $datarray["verb"] = ACTIVITY_POST;
1696                 $datarray["gravity"] = GRAVITY_PARENT;
1697
1698                 $datarray["object"] = $xml;
1699
1700                 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
1701                                         $original_item["guid"], $original_item["created"], $orig_url);
1702                 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
1703
1704                 $datarray["tag"] = $original_item["tag"];
1705                 $datarray["app"]  = $original_item["app"];
1706
1707                 $datarray["plink"] = self::plink($author, $guid);
1708                 $datarray["private"] = (($public == "false") ? 1 : 0);
1709                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1710
1711                 $datarray["object-type"] = $original_item["object-type"];
1712
1713                 self::fetch_guid($datarray);
1714                 $message_id = item_store($datarray);
1715
1716                 if ($message_id)
1717                         logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1718
1719                 return $message_id;
1720         }
1721
1722         private function item_retraction($importer, $contact, $data) {
1723                 $target_type = notags(unxmlify($data->target_type));
1724                 $target_guid = notags(unxmlify($data->target_guid));
1725                 $author = notags(unxmlify($data->author));
1726
1727                 $person = self::person_by_handle($author);
1728                 if (!is_array($person)) {
1729                         logger("unable to find author detail for ".$author);
1730                         return false;
1731                 }
1732
1733                 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
1734                         dbesc($target_guid),
1735                         intval($importer["uid"])
1736                 );
1737                 if (!$r)
1738                         return false;
1739
1740                 // Only delete it if the author really fits
1741                 if (!link_compare($r[0]["author-link"], $person["url"])) {
1742                         logger("Item author ".$r[0]["author-link"]." doesn't fit to expected contact ".$person["url"], LOGGER_DEBUG);
1743                         return false;
1744                 }
1745
1746                 // Check if the sender is the thread owner
1747                 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
1748                         intval($r[0]["parent"]));
1749
1750                 // Only delete it if the parent author really fits
1751                 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
1752                         logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
1753                         return false;
1754                 }
1755
1756                 // Currently we don't have a central deletion function that we could use in this case. The function "item_drop" doesn't work for that case
1757                 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
1758                         dbesc(datetime_convert()),
1759                         dbesc(datetime_convert()),
1760                         intval($r[0]["id"])
1761                 );
1762                 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
1763
1764                 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
1765
1766                 // Now check if the retraction needs to be relayed by us
1767                 if($p[0]["origin"]) {
1768                         // notify others
1769                         proc_run("php", "include/notifier.php", "drop", $r[0]["id"]);
1770                 }
1771         }
1772
1773         private function receive_retraction($importer, $sender, $data) {
1774                 $target_type = notags(unxmlify($data->target_type));
1775
1776                 $contact = self::contact_by_handle($importer["uid"], $sender);
1777                 if (!$contact) {
1778                         logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
1779                         return false;
1780                 }
1781
1782                 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
1783
1784                 switch ($target_type) {
1785                         case "Comment":
1786                         case "Like":
1787                         case "Post": // "Post" will be supported in a future version
1788                         case "Reshare":
1789                         case "StatusMessage":
1790                                 return self::item_retraction($importer, $contact, $data);;
1791
1792                         case "Person":
1793                                 /// @todo What should we do with an "unshare"?
1794                                 // Removing the contact isn't correct since we still can read the public items
1795                                 //contact_remove($contact["id"]);
1796                                 return true;
1797
1798                         default:
1799                                 logger("Unknown target type ".$target_type);
1800                                 return false;
1801                 }
1802                 return true;
1803         }
1804
1805         private function receive_status_message($importer, $data, $xml) {
1806
1807                 $raw_message = unxmlify($data->raw_message);
1808                 $guid = notags(unxmlify($data->guid));
1809                 $author = notags(unxmlify($data->author));
1810                 $public = notags(unxmlify($data->public));
1811                 $created_at = notags(unxmlify($data->created_at));
1812                 $provider_display_name = notags(unxmlify($data->provider_display_name));
1813
1814                 /// @todo enable support for polls
1815                 //if ($data->poll) {
1816                 //      foreach ($data->poll AS $poll)
1817                 //              print_r($poll);
1818                 //      die("poll!\n");
1819                 //}
1820                 $contact = self::allowed_contact_by_handle($importer, $author, false);
1821                 if (!$contact)
1822                         return false;
1823
1824                 if (self::message_exists($importer["uid"], $guid))
1825                         return false;
1826
1827                 $address = array();
1828                 if ($data->location)
1829                         foreach ($data->location->children() AS $fieldname => $data)
1830                                 $address[$fieldname] = notags(unxmlify($data));
1831
1832                 $body = diaspora2bb($raw_message);
1833
1834                 $datarray = array();
1835
1836                 if ($data->photo) {
1837                         foreach ($data->photo AS $photo)
1838                                 $body = "[img]".unxmlify($photo->remote_photo_path).
1839                                         unxmlify($photo->remote_photo_name)."[/img]\n".$body;
1840
1841                         $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
1842                 } else {
1843                         $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1844
1845                         // Add OEmbed and other information to the body
1846                         if (!self::is_redmatrix($contact["url"]))
1847                                 $body = add_page_info_to_body($body, false, true);
1848                 }
1849
1850                 $datarray["uid"] = $importer["uid"];
1851                 $datarray["contact-id"] = $contact["id"];
1852                 $datarray["network"] = NETWORK_DIASPORA;
1853
1854                 $datarray["author-name"] = $contact["name"];
1855                 $datarray["author-link"] = $contact["url"];
1856                 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1857
1858                 $datarray["owner-name"] = $datarray["author-name"];
1859                 $datarray["owner-link"] = $datarray["author-link"];
1860                 $datarray["owner-avatar"] = $datarray["author-avatar"];
1861
1862                 $datarray["guid"] = $guid;
1863                 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1864
1865                 $datarray["verb"] = ACTIVITY_POST;
1866                 $datarray["gravity"] = GRAVITY_PARENT;
1867
1868                 $datarray["object"] = $xml;
1869
1870                 $datarray["body"] = $body;
1871
1872                 if ($provider_display_name != "")
1873                         $datarray["app"] = $provider_display_name;
1874
1875                 $datarray["plink"] = self::plink($author, $guid);
1876                 $datarray["private"] = (($public == "false") ? 1 : 0);
1877                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1878
1879                 if (isset($address["address"]))
1880                         $datarray["location"] = $address["address"];
1881
1882                 if (isset($address["lat"]) AND isset($address["lng"]))
1883                         $datarray["coord"] = $address["lat"]." ".$address["lng"];
1884
1885                 self::fetch_guid($datarray);
1886                 $message_id = item_store($datarray);
1887
1888                 if ($message_id)
1889                         logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1890
1891                 return $message_id;
1892         }
1893
1894         /******************************************************************************************
1895          * Here are all the functions that are needed to transmit data with the Diaspora protocol *
1896          ******************************************************************************************/
1897
1898         private function my_handle($me) {
1899                 if ($contact["addr"] != "")
1900                         return $contact["addr"];
1901
1902                 // Normally we should have a filled "addr" field - but in the past this wasn't the case
1903                 // So - just in case - we build the the address here.
1904                 return $me["nickname"]."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
1905         }
1906
1907         private function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
1908
1909                 logger("Message: ".$msg, LOGGER_DATA);
1910
1911                 $handle = self::my_handle($user);
1912
1913                 $b64url_data = base64url_encode($msg);
1914
1915                 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1916
1917                 $type = "application/xml";
1918                 $encoding = "base64url";
1919                 $alg = "RSA-SHA256";
1920
1921                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1922
1923                 $signature = rsa_sign($signable_data,$prvkey);
1924                 $sig = base64url_encode($signature);
1925
1926                 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
1927                                                 "me:env" => array("me:encoding" => "base64url",
1928                                                                 "me:alg" => "RSA-SHA256",
1929                                                                 "me:data" => $data,
1930                                                                 "@attributes" => array("type" => "application/xml"),
1931                                                                 "me:sig" => $sig)));
1932
1933                 $namespaces = array("" => "https://joindiaspora.com/protocol",
1934                                 "me" => "http://salmon-protocol.org/ns/magic-env");
1935
1936                 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
1937
1938                 logger("magic_env: ".$magic_env, LOGGER_DATA);
1939                 return $magic_env;
1940         }
1941
1942         private function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
1943
1944                 logger("Message: ".$msg, LOGGER_DATA);
1945
1946                 // without a public key nothing will work
1947
1948                 if (!$pubkey) {
1949                         logger("pubkey missing: contact id: ".$contact["id"]);
1950                         return false;
1951                 }
1952
1953                 $inner_aes_key = random_string(32);
1954                 $b_inner_aes_key = base64_encode($inner_aes_key);
1955                 $inner_iv = random_string(16);
1956                 $b_inner_iv = base64_encode($inner_iv);
1957
1958                 $outer_aes_key = random_string(32);
1959                 $b_outer_aes_key = base64_encode($outer_aes_key);
1960                 $outer_iv = random_string(16);
1961                 $b_outer_iv = base64_encode($outer_iv);
1962
1963                 $handle = self::my_handle($user);
1964
1965                 $padded_data = pkcs5_pad($msg,16);
1966                 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
1967
1968                 $b64_data = base64_encode($inner_encrypted);
1969
1970
1971                 $b64url_data = base64url_encode($b64_data);
1972                 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1973
1974                 $type = "application/xml";
1975                 $encoding = "base64url";
1976                 $alg = "RSA-SHA256";
1977
1978                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1979
1980                 $signature = rsa_sign($signable_data,$prvkey);
1981                 $sig = base64url_encode($signature);
1982
1983                 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
1984                                                         "aes_key" => $b_inner_aes_key,
1985                                                         "author_id" => $handle));
1986
1987                 $decrypted_header = xml::from_array($xmldata, $xml, true);
1988                 $decrypted_header = pkcs5_pad($decrypted_header,16);
1989
1990                 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
1991
1992                 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
1993
1994                 $encrypted_outer_key_bundle = "";
1995                 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
1996
1997                 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
1998
1999                 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2000
2001                 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2002                                                                 "ciphertext" => base64_encode($ciphertext)));
2003                 $cipher_json = base64_encode($encrypted_header_json_object);
2004
2005                 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2006                                                 "me:env" => array("me:encoding" => "base64url",
2007                                                                 "me:alg" => "RSA-SHA256",
2008                                                                 "me:data" => $data,
2009                                                                 "@attributes" => array("type" => "application/xml"),
2010                                                                 "me:sig" => $sig)));
2011
2012                 $namespaces = array("" => "https://joindiaspora.com/protocol",
2013                                 "me" => "http://salmon-protocol.org/ns/magic-env");
2014
2015                 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2016
2017                 logger("magic_env: ".$magic_env, LOGGER_DATA);
2018                 return $magic_env;
2019         }
2020
2021         private function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2022
2023                 if ($public)
2024                         $magic_env =  self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2025                 else
2026                         $magic_env =  self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2027
2028                 // The data that will be transmitted is double encoded via "urlencode", strange ...
2029                 $slap = "xml=".urlencode(urlencode($magic_env));
2030                 return $slap;
2031         }
2032
2033         private function signature($owner, $message) {
2034                 $sigmsg = $message;
2035                 unset($sigmsg["author_signature"]);
2036                 unset($sigmsg["parent_author_signature"]);
2037
2038                 $signed_text = implode(";", $sigmsg);
2039
2040                 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2041         }
2042
2043         public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2044
2045                 $a = get_app();
2046
2047                 $enabled = intval(get_config("system", "diaspora_enabled"));
2048                 if(!$enabled)
2049                         return 200;
2050
2051                 $logid = random_string(4);
2052                 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2053                 if (!$dest_url) {
2054                         logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2055                         return 0;
2056                 }
2057
2058                 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2059
2060                 if (!$queue_run && was_recently_delayed($contact["id"])) {
2061                         $return_code = 0;
2062                 } else {
2063                         if (!intval(get_config("system", "diaspora_test"))) {
2064                                 post_url($dest_url."/", $slap);
2065                                 $return_code = $a->get_curl_code();
2066                         } else {
2067                                 logger("test_mode");
2068                                 return 200;
2069                         }
2070                 }
2071
2072                 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2073
2074                 if(!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2075                         logger("queue message");
2076
2077                         $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2078                                 intval($contact["id"]),
2079                                 dbesc(NETWORK_DIASPORA),
2080                                 dbesc($slap),
2081                                 intval($public_batch)
2082                         );
2083                         if($r) {
2084                                 logger("add_to_queue ignored - identical item already in queue");
2085                         } else {
2086                                 // queue message for redelivery
2087                                 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2088                         }
2089                 }
2090
2091                 return(($return_code) ? $return_code : (-1));
2092         }
2093
2094
2095         private function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2096
2097                 $data = array("XML" => array("post" => array($type => $message)));
2098
2099                 $msg = xml::from_array($data, $xml);
2100
2101                 logger('message: '.$msg, LOGGER_DATA);
2102                 logger('send guid '.$guid, LOGGER_DEBUG);
2103
2104                 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2105
2106                 if ($spool) {
2107                         add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2108                         return true;
2109                 } else
2110                         $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2111
2112                 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2113
2114                 return $return_code;
2115         }
2116
2117         public static function send_share($owner,$contact) {
2118
2119                 $message = array("sender_handle" => self::my_handle($owner),
2120                                 "recipient_handle" => $contact["addr"]);
2121
2122                 return self::build_and_transmit($owner, $contact, "request", $message);
2123         }
2124
2125         public static function send_unshare($owner,$contact) {
2126
2127                 $message = array("post_guid" => $owner["guid"],
2128                                 "diaspora_handle" => self::my_handle($owner),
2129                                 "type" => "Person");
2130
2131                 return self::build_and_transmit($owner, $contact, "retraction", $message);
2132         }
2133
2134         public static function is_reshare($body, $complete = true) {
2135                 $body = trim($body);
2136
2137                 // Skip if it isn't a pure repeated messages
2138                 // Does it start with a share?
2139                 if (strpos($body, "[share") > 0)
2140                         return(false);
2141
2142                 // Does it end with a share?
2143                 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2144                         return(false);
2145
2146                 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2147                 // Skip if there is no shared message in there
2148                 if ($body == $attributes)
2149                         return(false);
2150
2151                 // If we don't do the complete check we quit here
2152                 if (!$complete)
2153                         return true;
2154
2155                 $guid = "";
2156                 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2157                 if ($matches[1] != "")
2158                         $guid = $matches[1];
2159
2160                 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2161                 if ($matches[1] != "")
2162                         $guid = $matches[1];
2163
2164                 if ($guid != "") {
2165                         $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2166                                 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2167                         if ($r) {
2168                                 $ret= array();
2169                                 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2170                                 $ret["root_guid"] = $guid;
2171                                 return($ret);
2172                         }
2173                 }
2174
2175                 $profile = "";
2176                 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2177                 if ($matches[1] != "")
2178                         $profile = $matches[1];
2179
2180                 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2181                 if ($matches[1] != "")
2182                         $profile = $matches[1];
2183
2184                 $ret= array();
2185
2186                 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2187                 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2188                         return(false);
2189
2190                 $link = "";
2191                 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2192                 if ($matches[1] != "")
2193                         $link = $matches[1];
2194
2195                 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2196                 if ($matches[1] != "")
2197                         $link = $matches[1];
2198
2199                 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2200                 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2201                         return(false);
2202                 return($ret);
2203         }
2204
2205         public static function send_status($item, $owner, $contact, $public_batch = false) {
2206
2207                 $myaddr = self::my_handle($owner);
2208
2209                 $public = (($item["private"]) ? "false" : "true");
2210
2211                 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2212
2213                 // Detect a share element and do a reshare
2214                 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
2215                         $message = array("root_diaspora_id" => $ret["root_handle"],
2216                                         "root_guid" => $ret["root_guid"],
2217                                         "guid" => $item["guid"],
2218                                         "diaspora_handle" => $myaddr,
2219                                         "public" => $public,
2220                                         "created_at" => $created,
2221                                         "provider_display_name" => $item["app"]);
2222
2223                         $type = "reshare";
2224                 } else {
2225                         $title = $item["title"];
2226                         $body = $item["body"];
2227
2228                         // convert to markdown
2229                         $body = html_entity_decode(bb2diaspora($body));
2230
2231                         // Adding the title
2232                         if(strlen($title))
2233                                 $body = "## ".html_entity_decode($title)."\n\n".$body;
2234
2235                         if ($item["attach"]) {
2236                                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
2237                                 if(cnt) {
2238                                         $body .= "\n".t("Attachments:")."\n";
2239                                         foreach($matches as $mtch)
2240                                                 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
2241                                 }
2242                         }
2243
2244                         $location = array();
2245
2246                         if ($item["location"] != "")
2247                                 $location["address"] = $item["location"];
2248
2249                         if ($item["coord"] != "") {
2250                                 $coord = explode(" ", $item["coord"]);
2251                                 $location["lat"] = $coord[0];
2252                                 $location["lng"] = $coord[1];
2253                         }
2254
2255                         $message = array("raw_message" => $body,
2256                                         "location" => $location,
2257                                         "guid" => $item["guid"],
2258                                         "diaspora_handle" => $myaddr,
2259                                         "public" => $public,
2260                                         "created_at" => $created,
2261                                         "provider_display_name" => $item["app"]);
2262
2263                         if (count($location) == 0)
2264                                 unset($message["location"]);
2265
2266                         $type = "status_message";
2267                 }
2268
2269                 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2270         }
2271
2272         private function construct_like($item, $owner) {
2273
2274                 $myaddr = self::my_handle($owner);
2275
2276                 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
2277                         dbesc($item["thr-parent"]));
2278                 if(!$p)
2279                         return false;
2280
2281                 $parent = $p[0];
2282
2283                 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
2284                 $positive = "true";
2285
2286                 return(array("positive" => $positive,
2287                                 "guid" => $item["guid"],
2288                                 "target_type" => $target_type,
2289                                 "parent_guid" => $parent["guid"],
2290                                 "author_signature" => $authorsig,
2291                                 "diaspora_handle" => $myaddr));
2292         }
2293
2294         private function construct_comment($item, $owner) {
2295
2296                 $myaddr = self::my_handle($owner);
2297
2298                 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2299                         intval($item["parent"]),
2300                         intval($item["parent"])
2301                 );
2302
2303                 if (!$p)
2304                         return false;
2305
2306                 $parent = $p[0];
2307
2308                 $text = html_entity_decode(bb2diaspora($item["body"]));
2309
2310                 return(array("guid" => $item["guid"],
2311                                 "parent_guid" => $parent["guid"],
2312                                 "author_signature" => "",
2313                                 "text" => $text,
2314                                 "diaspora_handle" => $myaddr));
2315         }
2316
2317         public static function send_followup($item,$owner,$contact,$public_batch = false) {
2318
2319                 if($item['verb'] === ACTIVITY_LIKE) {
2320                         $message = self::construct_like($item, $owner);
2321                         $type = "like";
2322                 } else {
2323                         $message = self::construct_comment($item, $owner);
2324                         $type = "comment";
2325                 }
2326
2327                 if (!$message)
2328                         return false;
2329
2330                 $message["author_signature"] = self::signature($owner, $message);
2331
2332                 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2333         }
2334
2335         private function message_from_signatur($item, $signature) {
2336
2337                 // Split the signed text
2338                 $signed_parts = explode(";", $signature['signed_text']);
2339
2340                 if ($item["deleted"])
2341                         $message = array("parent_author_signature" => "",
2342                                         "target_guid" => $signed_parts[0],
2343                                         "target_type" => $signed_parts[1],
2344                                         "sender_handle" => $signature['signer'],
2345                                         "target_author_signature" => $signature['signature']);
2346                 elseif ($item['verb'] === ACTIVITY_LIKE)
2347                         $message = array("positive" => $signed_parts[0],
2348                                         "guid" => $signed_parts[1],
2349                                         "target_type" => $signed_parts[2],
2350                                         "parent_guid" => $signed_parts[3],
2351                                         "parent_author_signature" => "",
2352                                         "author_signature" => $signature['signature'],
2353                                         "diaspora_handle" => $signed_parts[4]);
2354                 else {
2355                         // Remove the comment guid
2356                         $guid = array_shift($signed_parts);
2357
2358                         // Remove the parent guid
2359                         $parent_guid = array_shift($signed_parts);
2360
2361                         // Remove the handle
2362                         $handle = array_pop($signed_parts);
2363
2364                         // Glue the parts together
2365                         $text = implode(";", $signed_parts);
2366
2367                         $message = array("guid" => $guid,
2368                                         "parent_guid" => $parent_guid,
2369                                         "parent_author_signature" => "",
2370                                         "author_signature" => $signature['signature'],
2371                                         "text" => implode(";", $signed_parts),
2372                                         "diaspora_handle" => $handle);
2373                 }
2374                 return $message;
2375         }
2376
2377         public static function send_relay($item, $owner, $contact, $public_batch = false) {
2378
2379                 if ($item["deleted"])
2380                         return self::send_retraction($item, $owner, $contact, $public_batch, true);
2381                 elseif ($item['verb'] === ACTIVITY_LIKE)
2382                         $type = "like";
2383                 else
2384                         $type = "comment";
2385
2386                 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2387
2388                 // fetch the original signature
2389
2390                 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
2391                         intval($item["id"]));
2392
2393                 if (!$r) {
2394                         logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2395                         return false;
2396                 }
2397
2398                 $signature = $r[0];
2399
2400                 // Old way - is used by the internal Friendica functions
2401                 /// @todo Change all signatur storing functions to the new format
2402                 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
2403                         $message = self::message_from_signatur($item, $signature);
2404                 else {// New way
2405                         $msg = json_decode($signature['signed_text'], true);
2406
2407                         $message = array();
2408                         if (is_array($msg)) {
2409                                 foreach ($msg AS $field => $data) {
2410                                         if (!$item["deleted"]) {
2411                                                 if ($field == "author")
2412                                                         $field = "diaspora_handle";
2413                                                 if ($field == "parent_type")
2414                                                         $field = "target_type";
2415                                         }
2416
2417                                         $message[$field] = $data;
2418                                 }
2419                         } else
2420                                 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
2421                 }
2422
2423                 $message["parent_author_signature"] = self::signature($owner, $message);
2424
2425                 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
2426
2427                 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2428         }
2429
2430         public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
2431
2432                 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
2433                 //$myaddr = self::my_handle($owner);
2434
2435                 // Check whether the retraction is for a top-level post or whether it's a relayable
2436                 if ($item["uri"] !== $item["parent-uri"]) {
2437                         $msg_type = "relayable_retraction";
2438                         $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
2439                 } else {
2440                         $msg_type = "signed_retraction";
2441                         $target_type = "StatusMessage";
2442                 }
2443
2444                 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
2445                         $signature = "parent_author_signature";
2446                 else
2447                         $signature = "target_author_signature";
2448
2449                 $signed_text = $item["guid"].";".$target_type;
2450
2451                 $message = array("target_guid" => $item['guid'],
2452                                 "target_type" => $target_type,
2453                                 "sender_handle" => $itemaddr,
2454                                 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
2455
2456                 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
2457
2458                 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
2459         }
2460
2461         public static function send_mail($item, $owner, $contact) {
2462
2463                 $myaddr = self::my_handle($owner);
2464
2465                 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2466                         intval($item["convid"]),
2467                         intval($item["uid"])
2468                 );
2469
2470                 if (!$r) {
2471                         logger("conversation not found.");
2472                         return;
2473                 }
2474                 $cnv = $r[0];
2475
2476                 $conv = array(
2477                         "guid" => $cnv["guid"],
2478                         "subject" => $cnv["subject"],
2479                         "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2480                         "diaspora_handle" => $cnv["creator"],
2481                         "participant_handles" => $cnv["recips"]
2482                 );
2483
2484                 $body = bb2diaspora($item["body"]);
2485                 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2486
2487                 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
2488                 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2489
2490                 $msg = array(
2491                         "guid" => $item["guid"],
2492                         "parent_guid" => $cnv["guid"],
2493                         "parent_author_signature" => $sig,
2494                         "author_signature" => $sig,
2495                         "text" => $body,
2496                         "created_at" => $created,
2497                         "diaspora_handle" => $myaddr,
2498                         "conversation_guid" => $cnv["guid"]
2499                 );
2500
2501                 if ($item["reply"]) {
2502                         $message = $msg;
2503                         $type = "message";
2504                 } else {
2505                         $message = array("guid" => $cnv["guid"],
2506                                         "subject" => $cnv["subject"],
2507                                         "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2508                                         "message" => $msg,
2509                                         "diaspora_handle" => $cnv["creator"],
2510                                         "participant_handles" => $cnv["recips"]);
2511
2512                         $type = "conversation";
2513                 }
2514
2515                 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
2516         }
2517
2518         public static function send_profile($uid) {
2519
2520                 if (!$uid)
2521                         return;
2522
2523                 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
2524                         AND `uid` = %d AND `rel` != %d",
2525                         dbesc(NETWORK_DIASPORA),
2526                         intval($uid),
2527                         intval(CONTACT_IS_SHARING)
2528                 );
2529                 if (!$recips)
2530                         return;
2531
2532                 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
2533                         FROM `profile`
2534                         INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
2535                         INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
2536                         WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
2537                         intval($uid)
2538                 );
2539
2540                 if (!$r)
2541                         return;
2542
2543                 $profile = $r[0];
2544
2545                 $handle = $profile["addr"];
2546                 $first = ((strpos($profile['name'],' ')
2547                         ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
2548                 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
2549                 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
2550                 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
2551                 $small = App::get_baseurl().'/photo/custom/50/'  .$profile['uid'].'.jpg';
2552                 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
2553
2554                 if ($searchable === 'true') {
2555                         $dob = '1000-00-00';
2556
2557                         if (($profile['dob']) && ($profile['dob'] != '0000-00-00'))
2558                                 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
2559
2560                         $about = $profile['about'];
2561                         $about = strip_tags(bbcode($about));
2562
2563                         $location = formatted_location($profile);
2564                         $tags = '';
2565                         if ($profile['pub_keywords']) {
2566                                 $kw = str_replace(',',' ',$profile['pub_keywords']);
2567                                 $kw = str_replace('  ',' ',$kw);
2568                                 $arr = explode(' ',$profile['pub_keywords']);
2569                                 if (count($arr)) {
2570                                         for($x = 0; $x < 5; $x ++) {
2571                                                 if (trim($arr[$x]))
2572                                                         $tags .= '#'. trim($arr[$x]) .' ';
2573                                         }
2574                                 }
2575                         }
2576                         $tags = trim($tags);
2577                 }
2578
2579                 $message = array("diaspora_handle" => $handle,
2580                                 "first_name" => $first,
2581                                 "last_name" => $last,
2582                                 "image_url" => $large,
2583                                 "image_url_medium" => $medium,
2584                                 "image_url_small" => $small,
2585                                 "birthday" => $dob,
2586                                 "gender" => $profile['gender'],
2587                                 "bio" => $about,
2588                                 "location" => $location,
2589                                 "searchable" => $searchable,
2590                                 "tag_string" => $tags);
2591
2592                 foreach($recips as $recip)
2593                         self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
2594         }
2595 }
2596 ?>