]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
870466497d1091526540790519136c343da8237a
[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 comment retraction on diaspora post
16  * - send like retraction on own 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  *
34  * Should work:
35  * - receive account deletion
36  * - send share
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) {
614                 $handle = False;
615
616                 logger("contact id is ".$contact_id, LOGGER_DEBUG);
617
618                 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
619                        intval($contact_id)
620                 );
621                 if($r) {
622                         $contact = $r[0];
623
624                         logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
625
626                         if($contact['addr'] != "")
627                                 $handle = $contact['addr'];
628                         elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
629                                 $baseurl_start = strpos($contact['url'],'://') + 3;
630                                 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
631                                 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
632                                 $handle = $contact['nick'].'@'.$baseurl;
633                         }
634                 }
635
636                 return $handle;
637         }
638
639         private function contact_by_handle($uid, $handle) {
640                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
641                         intval($uid),
642                         dbesc($handle)
643                 );
644
645                 if ($r)
646                         return $r[0];
647
648                 $handle_parts = explode("@", $handle);
649                 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
650                 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
651                         dbesc(NETWORK_DFRN),
652                         intval($uid),
653                         dbesc($nurl_sql)
654                 );
655                 if($r)
656                         return $r[0];
657
658                 return false;
659         }
660
661         private function post_allow($importer, $contact, $is_comment = false) {
662
663                 // perhaps we were already sharing with this person. Now they're sharing with us.
664                 // That makes us friends.
665                 // Normally this should have handled by getting a request - but this could get lost
666                 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
667                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
668                                 intval(CONTACT_IS_FRIEND),
669                                 intval($contact["id"]),
670                                 intval($importer["uid"])
671                         );
672                         $contact["rel"] = CONTACT_IS_FRIEND;
673                         logger("defining user ".$contact["nick"]." as friend");
674                 }
675
676                 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
677                         return false;
678                 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
679                         return true;
680                 if($contact["rel"] == CONTACT_IS_FOLLOWER)
681                         if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
682                                 return true;
683
684                 // Messages for the global users are always accepted
685                 if ($importer["uid"] == 0)
686                         return true;
687
688                 return false;
689         }
690
691         private function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
692                 $contact = self::contact_by_handle($importer["uid"], $handle);
693                 if (!$contact) {
694                         logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
695                         return false;
696                 }
697
698                 if (!self::post_allow($importer, $contact, $is_comment)) {
699                         logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
700                         return false;
701                 }
702                 return $contact;
703         }
704
705         private function message_exists($uid, $guid) {
706                 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
707                         intval($uid),
708                         dbesc($guid)
709                 );
710
711                 if($r) {
712                         logger("message ".$guid." already exists for user ".$uid);
713                         return true;
714                 }
715
716                 return false;
717         }
718
719         private function fetch_guid($item) {
720                 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
721                         function ($match) use ($item){
722                                 return(self::fetch_guid_sub($match, $item));
723                         },$item["body"]);
724         }
725
726         private function fetch_guid_sub($match, $item) {
727                 if (!self::store_by_guid($match[1], $item["author-link"]))
728                         self::store_by_guid($match[1], $item["owner-link"]);
729         }
730
731         private function store_by_guid($guid, $server, $uid = 0) {
732                 $serverparts = parse_url($server);
733                 $server = $serverparts["scheme"]."://".$serverparts["host"];
734
735                 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
736
737                 $msg = self::message($guid, $server);
738
739                 if (!$msg)
740                         return false;
741
742                 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
743
744                 // Now call the dispatcher
745                 return self::dispatch_public($msg);
746         }
747
748         private function message($guid, $server, $level = 0) {
749
750                 if ($level > 5)
751                         return false;
752
753                 // This will work for Diaspora and newer Friendica servers
754                 $source_url = $server."/p/".$guid.".xml";
755                 $x = fetch_url($source_url);
756                 if(!$x)
757                         return false;
758
759                 $source_xml = parse_xml_string($x, false);
760
761                 if (!is_object($source_xml))
762                         return false;
763
764                 if ($source_xml->post->reshare) {
765                         // Reshare of a reshare - old Diaspora version
766                         return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
767                 } elseif ($source_xml->getName() == "reshare") {
768                         // Reshare of a reshare - new Diaspora version
769                         return self::message($source_xml->root_guid, $server, ++$level);
770                 }
771
772                 $author = "";
773
774                 // Fetch the author - for the old and the new Diaspora version
775                 if ($source_xml->post->status_message->diaspora_handle)
776                         $author = (string)$source_xml->post->status_message->diaspora_handle;
777                 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
778                         $author = (string)$source_xml->author;
779
780                 // If this isn't a "status_message" then quit
781                 if (!$author)
782                         return false;
783
784                 $msg = array("message" => $x, "author" => $author);
785
786                 $msg["key"] = self::key($msg["author"]);
787
788                 return $msg;
789         }
790
791         private function parent_item($uid, $guid, $author, $contact) {
792                 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
793                                 `author-name`, `author-link`, `author-avatar`,
794                                 `owner-name`, `owner-link`, `owner-avatar`
795                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
796                         intval($uid), dbesc($guid));
797
798                 if(!$r) {
799                         $result = self::store_by_guid($guid, $contact["url"], $uid);
800
801                         if (!$result) {
802                                 $person = self::person_by_handle($author);
803                                 $result = self::store_by_guid($guid, $person["url"], $uid);
804                         }
805
806                         if ($result) {
807                                 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
808
809                                 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
810                                                 `author-name`, `author-link`, `author-avatar`,
811                                                 `owner-name`, `owner-link`, `owner-avatar`
812                                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
813                                         intval($uid), dbesc($guid));
814                         }
815                 }
816
817                 if (!$r) {
818                         logger("parent item not found: parent: ".$guid." - user: ".$uid);
819                         return false;
820                 } else {
821                         logger("parent item found: parent: ".$guid." - user: ".$uid);
822                         return $r[0];
823                 }
824         }
825
826         private function author_contact_by_url($contact, $person, $uid) {
827
828                 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
829                         dbesc(normalise_link($person["url"])), intval($uid));
830                 if ($r) {
831                         $cid = $r[0]["id"];
832                         $network = $r[0]["network"];
833                 } else {
834                         $cid = $contact["id"];
835                         $network = NETWORK_DIASPORA;
836                 }
837
838                 return (array("cid" => $cid, "network" => $network));
839         }
840
841         public static function is_redmatrix($url) {
842                 return(strstr($url, "/channel/"));
843         }
844
845         private function plink($addr, $guid) {
846                 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
847
848                 // Fallback
849                 if (!$r)
850                         return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
851
852                 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
853                 // So we try another way as well.
854                 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
855                 if ($s)
856                         $r[0]["network"] = $s[0]["network"];
857
858                 if ($r[0]["network"] == NETWORK_DFRN)
859                         return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
860
861                 if (self::is_redmatrix($r[0]["url"]))
862                         return $r[0]["url"]."/?f=&mid=".$guid;
863
864                 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
865         }
866
867         private function receive_account_deletion($importer, $data) {
868                 $author = notags(unxmlify($data->author));
869
870                 $contact = self::contact_by_handle($importer["uid"], $author);
871                 if (!$contact) {
872                         logger("cannot find contact for author: ".$author);
873                         return false;
874                 }
875
876                 // We now remove the contact
877                 contact_remove($contact["id"]);
878                 return true;
879         }
880
881         private function receive_comment($importer, $sender, $data, $xml) {
882                 $guid = notags(unxmlify($data->guid));
883                 $parent_guid = notags(unxmlify($data->parent_guid));
884                 $text = unxmlify($data->text);
885                 $author = notags(unxmlify($data->author));
886
887                 $contact = self::allowed_contact_by_handle($importer, $sender, true);
888                 if (!$contact)
889                         return false;
890
891                 if (self::message_exists($importer["uid"], $guid))
892                         return false;
893
894                 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
895                 if (!$parent_item)
896                         return false;
897
898                 $person = self::person_by_handle($author);
899                 if (!is_array($person)) {
900                         logger("unable to find author details");
901                         return false;
902                 }
903
904                 // Fetch the contact id - if we know this contact
905                 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
906
907                 $datarray = array();
908
909                 $datarray["uid"] = $importer["uid"];
910                 $datarray["contact-id"] = $author_contact["cid"];
911                 $datarray["network"]  = $author_contact["network"];
912
913                 $datarray["author-name"] = $person["name"];
914                 $datarray["author-link"] = $person["url"];
915                 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
916
917                 $datarray["owner-name"] = $contact["name"];
918                 $datarray["owner-link"] = $contact["url"];
919                 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
920
921                 $datarray["guid"] = $guid;
922                 $datarray["uri"] = $author.":".$guid;
923
924                 $datarray["type"] = "remote-comment";
925                 $datarray["verb"] = ACTIVITY_POST;
926                 $datarray["gravity"] = GRAVITY_COMMENT;
927                 $datarray["parent-uri"] = $parent_item["uri"];
928
929                 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
930                 $datarray["object"] = $xml;
931
932                 $datarray["body"] = diaspora2bb($text);
933
934                 self::fetch_guid($datarray);
935
936                 $message_id = item_store($datarray);
937
938                 if ($message_id)
939                         logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
940
941                 // If we are the origin of the parent we store the original data and notify our followers
942                 if($message_id AND $parent_item["origin"]) {
943
944                         // Formerly we stored the signed text, the signature and the author in different fields.
945                         // We now store the raw data so that we are more flexible.
946                         q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
947                                 intval($message_id),
948                                 dbesc(json_encode($data))
949                         );
950
951                         // notify others
952                         proc_run("php", "include/notifier.php", "comment-import", $message_id);
953                 }
954
955                 return $message_id;
956         }
957
958         private function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
959                 $guid = notags(unxmlify($data->guid));
960                 $subject = notags(unxmlify($data->subject));
961                 $author = notags(unxmlify($data->author));
962
963                 $reply = 0;
964
965                 $msg_guid = notags(unxmlify($mesg->guid));
966                 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
967                 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
968                 $msg_author_signature = notags(unxmlify($mesg->author_signature));
969                 $msg_text = unxmlify($mesg->text);
970                 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
971
972                 // "diaspora_handle" is the element name from the old version
973                 // "author" is the element name from the new version
974                 if ($mesg->author)
975                         $msg_author = notags(unxmlify($mesg->author));
976                 elseif ($mesg->diaspora_handle)
977                         $msg_author = notags(unxmlify($mesg->diaspora_handle));
978                 else
979                         return false;
980
981                 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
982
983                 if($msg_conversation_guid != $guid) {
984                         logger("message conversation guid does not belong to the current conversation.");
985                         return false;
986                 }
987
988                 $body = diaspora2bb($msg_text);
989                 $message_uri = $msg_author.":".$msg_guid;
990
991                 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
992
993                 $author_signature = base64_decode($msg_author_signature);
994
995                 if(strcasecmp($msg_author,$msg["author"]) == 0) {
996                         $person = $contact;
997                         $key = $msg["key"];
998                 } else {
999                         $person = self::person_by_handle($msg_author);
1000
1001                         if (is_array($person) && x($person, "pubkey"))
1002                                 $key = $person["pubkey"];
1003                         else {
1004                                 logger("unable to find author details");
1005                                         return false;
1006                         }
1007                 }
1008
1009                 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
1010                         logger("verification failed.");
1011                         return false;
1012                 }
1013
1014                 if($msg_parent_author_signature) {
1015                         $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1016
1017                         $parent_author_signature = base64_decode($msg_parent_author_signature);
1018
1019                         $key = $msg["key"];
1020
1021                         if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
1022                                 logger("owner verification failed.");
1023                                 return false;
1024                         }
1025                 }
1026
1027                 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
1028                         dbesc($message_uri)
1029                 );
1030                 if($r) {
1031                         logger("duplicate message already delivered.", LOGGER_DEBUG);
1032                         return false;
1033                 }
1034
1035                 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1036                         VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1037                         intval($importer["uid"]),
1038                         dbesc($msg_guid),
1039                         intval($conversation["id"]),
1040                         dbesc($person["name"]),
1041                         dbesc($person["photo"]),
1042                         dbesc($person["url"]),
1043                         intval($contact["id"]),
1044                         dbesc($subject),
1045                         dbesc($body),
1046                         0,
1047                         0,
1048                         dbesc($message_uri),
1049                         dbesc($author.":".$guid),
1050                         dbesc($msg_created_at)
1051                 );
1052
1053                 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1054                         dbesc(datetime_convert()),
1055                         intval($conversation["id"])
1056                 );
1057
1058                 notification(array(
1059                         "type" => NOTIFY_MAIL,
1060                         "notify_flags" => $importer["notify-flags"],
1061                         "language" => $importer["language"],
1062                         "to_name" => $importer["username"],
1063                         "to_email" => $importer["email"],
1064                         "uid" =>$importer["uid"],
1065                         "item" => array("subject" => $subject, "body" => $body),
1066                         "source_name" => $person["name"],
1067                         "source_link" => $person["url"],
1068                         "source_photo" => $person["thumb"],
1069                         "verb" => ACTIVITY_POST,
1070                         "otype" => "mail"
1071                 ));
1072         }
1073
1074         private function receive_conversation($importer, $msg, $data) {
1075                 $guid = notags(unxmlify($data->guid));
1076                 $subject = notags(unxmlify($data->subject));
1077                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1078                 $author = notags(unxmlify($data->author));
1079                 $participants = notags(unxmlify($data->participants));
1080
1081                 $messages = $data->message;
1082
1083                 if (!count($messages)) {
1084                         logger("empty conversation");
1085                         return false;
1086                 }
1087
1088                 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1089                 if (!$contact)
1090                         return false;
1091
1092                 $conversation = null;
1093
1094                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1095                         intval($importer["uid"]),
1096                         dbesc($guid)
1097                 );
1098                 if($c)
1099                         $conversation = $c[0];
1100                 else {
1101                         $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1102                                 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1103                                 intval($importer["uid"]),
1104                                 dbesc($guid),
1105                                 dbesc($author),
1106                                 dbesc(datetime_convert("UTC", "UTC", $created_at)),
1107                                 dbesc(datetime_convert()),
1108                                 dbesc($subject),
1109                                 dbesc($participants)
1110                         );
1111                         if($r)
1112                                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1113                                         intval($importer["uid"]),
1114                                         dbesc($guid)
1115                                 );
1116
1117                         if($c)
1118                                 $conversation = $c[0];
1119                 }
1120                 if (!$conversation) {
1121                         logger("unable to create conversation.");
1122                         return;
1123                 }
1124
1125                 foreach($messages as $mesg)
1126                         self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1127
1128                 return true;
1129         }
1130
1131         private function construct_like_body($contact, $parent_item, $guid) {
1132                 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1133
1134                 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1135                 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1136                 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1137
1138                 return sprintf($bodyverb, $ulink, $alink, $plink);
1139         }
1140
1141         private function construct_like_object($importer, $parent_item) {
1142                 $objtype = ACTIVITY_OBJ_NOTE;
1143                 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1144                 $parent_body = $parent_item["body"];
1145
1146                 $xmldata = array("object" => array("type" => $objtype,
1147                                                 "local" => "1",
1148                                                 "id" => $parent_item["uri"],
1149                                                 "link" => $link,
1150                                                 "title" => "",
1151                                                 "content" => $parent_body));
1152
1153                 return xml::from_array($xmldata, $xml, true);
1154         }
1155
1156         private function receive_like($importer, $sender, $data) {
1157                 $positive = notags(unxmlify($data->positive));
1158                 $guid = notags(unxmlify($data->guid));
1159                 $parent_type = notags(unxmlify($data->parent_type));
1160                 $parent_guid = notags(unxmlify($data->parent_guid));
1161                 $author = notags(unxmlify($data->author));
1162
1163                 // likes on comments aren't supported by Diaspora - only on posts
1164                 // But maybe this will be supported in the future, so we will accept it.
1165                 if (!in_array($parent_type, array("Post", "Comment")))
1166                         return false;
1167
1168                 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1169                 if (!$contact)
1170                         return false;
1171
1172                 if (self::message_exists($importer["uid"], $guid))
1173                         return false;
1174
1175                 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1176                 if (!$parent_item)
1177                         return false;
1178
1179                 $person = self::person_by_handle($author);
1180                 if (!is_array($person)) {
1181                         logger("unable to find author details");
1182                         return false;
1183                 }
1184
1185                 // Fetch the contact id - if we know this contact
1186                 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1187
1188                 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1189                 // We would accept this anyhow.
1190                 if ($positive === "true")
1191                         $verb = ACTIVITY_LIKE;
1192                 else
1193                         $verb = ACTIVITY_DISLIKE;
1194
1195                 $datarray = array();
1196
1197                 $datarray["uid"] = $importer["uid"];
1198                 $datarray["contact-id"] = $author_contact["cid"];
1199                 $datarray["network"]  = $author_contact["network"];
1200
1201                 $datarray["author-name"] = $person["name"];
1202                 $datarray["author-link"] = $person["url"];
1203                 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1204
1205                 $datarray["owner-name"] = $contact["name"];
1206                 $datarray["owner-link"] = $contact["url"];
1207                 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1208
1209                 $datarray["guid"] = $guid;
1210                 $datarray["uri"] = $author.":".$guid;
1211
1212                 $datarray["type"] = "activity";
1213                 $datarray["verb"] = $verb;
1214                 $datarray["gravity"] = GRAVITY_LIKE;
1215                 $datarray["parent-uri"] = $parent_item["uri"];
1216
1217                 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1218                 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1219
1220                 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1221
1222                 $message_id = item_store($datarray);
1223
1224                 if ($message_id)
1225                         logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1226
1227                 // If we are the origin of the parent we store the original data and notify our followers
1228                 if($message_id AND $parent_item["origin"]) {
1229
1230                         // Formerly we stored the signed text, the signature and the author in different fields.
1231                         // We now store the raw data so that we are more flexible.
1232                         q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1233                                 intval($message_id),
1234                                 dbesc(json_encode($data))
1235                         );
1236
1237                         // notify others
1238                         proc_run("php", "include/notifier.php", "comment-import", $message_id);
1239                 }
1240
1241                 return $message_id;
1242         }
1243
1244         private function receive_message($importer, $data) {
1245                 $guid = notags(unxmlify($data->guid));
1246                 $parent_guid = notags(unxmlify($data->parent_guid));
1247                 $text = unxmlify($data->text);
1248                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1249                 $author = notags(unxmlify($data->author));
1250                 $conversation_guid = notags(unxmlify($data->conversation_guid));
1251
1252                 $contact = self::allowed_contact_by_handle($importer, $author, true);
1253                 if (!$contact)
1254                         return false;
1255
1256                 $conversation = null;
1257
1258                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1259                         intval($importer["uid"]),
1260                         dbesc($conversation_guid)
1261                 );
1262                 if($c)
1263                         $conversation = $c[0];
1264                 else {
1265                         logger("conversation not available.");
1266                         return false;
1267                 }
1268
1269                 $reply = 0;
1270
1271                 $body = diaspora2bb($text);
1272                 $message_uri = $author.":".$guid;
1273
1274                 $person = self::person_by_handle($author);
1275                 if (!$person) {
1276                         logger("unable to find author details");
1277                         return false;
1278                 }
1279
1280                 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1281                         dbesc($message_uri),
1282                         intval($importer["uid"])
1283                 );
1284                 if($r) {
1285                         logger("duplicate message already delivered.", LOGGER_DEBUG);
1286                         return false;
1287                 }
1288
1289                 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1290                                 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1291                         intval($importer["uid"]),
1292                         dbesc($guid),
1293                         intval($conversation["id"]),
1294                         dbesc($person["name"]),
1295                         dbesc($person["photo"]),
1296                         dbesc($person["url"]),
1297                         intval($contact["id"]),
1298                         dbesc($conversation["subject"]),
1299                         dbesc($body),
1300                         0,
1301                         1,
1302                         dbesc($message_uri),
1303                         dbesc($author.":".$parent_guid),
1304                         dbesc($created_at)
1305                 );
1306
1307                 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1308                         dbesc(datetime_convert()),
1309                         intval($conversation["id"])
1310                 );
1311
1312                 return true;
1313         }
1314
1315         private function receive_participation($importer, $data) {
1316                 // I'm not sure if we can fully support this message type
1317                 return true;
1318         }
1319
1320         private function receive_photo($importer, $data) {
1321                 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1322                 return true;
1323         }
1324
1325         private function receive_poll_participation($importer, $data) {
1326                 // We don't support polls by now
1327                 return true;
1328         }
1329
1330         private function receive_profile($importer, $data) {
1331                 $author = notags(unxmlify($data->author));
1332
1333                 $contact = self::contact_by_handle($importer["uid"], $author);
1334                 if (!$contact)
1335                         return;
1336
1337                 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1338                 $image_url = unxmlify($data->image_url);
1339                 $birthday = unxmlify($data->birthday);
1340                 $location = diaspora2bb(unxmlify($data->location));
1341                 $about = diaspora2bb(unxmlify($data->bio));
1342                 $gender = unxmlify($data->gender);
1343                 $searchable = (unxmlify($data->searchable) == "true");
1344                 $nsfw = (unxmlify($data->nsfw) == "true");
1345                 $tags = unxmlify($data->tag_string);
1346
1347                 $tags = explode("#", $tags);
1348
1349                 $keywords = array();
1350                 foreach ($tags as $tag) {
1351                         $tag = trim(strtolower($tag));
1352                         if ($tag != "")
1353                                 $keywords[] = $tag;
1354                 }
1355
1356                 $keywords = implode(", ", $keywords);
1357
1358                 $handle_parts = explode("@", $author);
1359                 $nick = $handle_parts[0];
1360
1361                 if($name === "")
1362                         $name = $handle_parts[0];
1363
1364                 if( preg_match("|^https?://|", $image_url) === 0)
1365                         $image_url = "http://".$handle_parts[1].$image_url;
1366
1367                 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1368
1369                 // Generic birthday. We don't know the timezone. The year is irrelevant.
1370
1371                 $birthday = str_replace("1000", "1901", $birthday);
1372
1373                 if ($birthday != "")
1374                         $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1375
1376                 // this is to prevent multiple birthday notifications in a single year
1377                 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1378
1379                 if(substr($birthday,5) === substr($contact["bd"],5))
1380                         $birthday = $contact["bd"];
1381
1382                 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1383                                 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1384                         dbesc($name),
1385                         dbesc($nick),
1386                         dbesc($author),
1387                         dbesc(datetime_convert()),
1388                         dbesc($birthday),
1389                         dbesc($location),
1390                         dbesc($about),
1391                         dbesc($keywords),
1392                         dbesc($gender),
1393                         intval($contact["id"]),
1394                         intval($importer["uid"])
1395                 );
1396
1397                 if ($searchable) {
1398                         poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1399                                 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1400                 }
1401
1402                 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1403                                         "photo" => $image_url, "name" => $name, "location" => $location,
1404                                         "about" => $about, "birthday" => $birthday, "gender" => $gender,
1405                                         "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1406                                         "hide" => !$searchable, "nsfw" => $nsfw);
1407
1408                 update_gcontact($gcontact);
1409
1410                 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1411
1412                 return true;
1413         }
1414
1415         private function receive_request_make_friend($importer, $contact) {
1416
1417                 $a = get_app();
1418
1419                 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1420                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1421                                 intval(CONTACT_IS_FRIEND),
1422                                 intval($contact["id"]),
1423                                 intval($importer["uid"])
1424                         );
1425                 }
1426                 // send notification
1427
1428                 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1429                         intval($importer["uid"])
1430                 );
1431
1432                 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1433
1434                         $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1435                                 intval($importer["uid"])
1436                         );
1437
1438                         // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1439
1440                         if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1441
1442                                 $arr = array();
1443                                 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1444                                 $arr["uid"] = $importer["uid"];
1445                                 $arr["contact-id"] = $self[0]["id"];
1446                                 $arr["wall"] = 1;
1447                                 $arr["type"] = 'wall';
1448                                 $arr["gravity"] = 0;
1449                                 $arr["origin"] = 1;
1450                                 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1451                                 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1452                                 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1453                                 $arr["verb"] = ACTIVITY_FRIEND;
1454                                 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1455
1456                                 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1457                                 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1458                                 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1459                                 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1460
1461                                 $arr["object"] = "<object><type>".ACTIVITY_OBJ_PERSON."</type><title>".$contact["name"]."</title>"
1462                                         ."<id>".$contact["url"]."/".$contact["name"]."</id>";
1463                                 $arr["object"] .= "<link>".xmlify('<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n");
1464                                 $arr["object"] .= xmlify('<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n");
1465                                 $arr["object"] .= "</link></object>\n";
1466                                 $arr["last-child"] = 1;
1467
1468                                 $arr["allow_cid"] = $user[0]["allow_cid"];
1469                                 $arr["allow_gid"] = $user[0]["allow_gid"];
1470                                 $arr["deny_cid"]  = $user[0]["deny_cid"];
1471                                 $arr["deny_gid"]  = $user[0]["deny_gid"];
1472
1473                                 $i = item_store($arr);
1474                                 if($i)
1475                                         proc_run("php", "include/notifier.php", "activity", $i);
1476
1477                         }
1478
1479                 }
1480         }
1481
1482         private function receive_request($importer, $data) {
1483                 $author = unxmlify($data->author);
1484                 $recipient = unxmlify($data->recipient);
1485
1486                 if (!$author || !$recipient)
1487                         return;
1488
1489                 $contact = self::contact_by_handle($importer["uid"],$author);
1490
1491                 if($contact) {
1492
1493                         // perhaps we were already sharing with this person. Now they're sharing with us.
1494                         // That makes us friends.
1495
1496                         self::receive_request_make_friend($importer, $contact);
1497                         return true;
1498                 }
1499
1500                 $ret = self::person_by_handle($author);
1501
1502                 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
1503                         logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
1504                         return false;
1505                 }
1506
1507                 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
1508
1509                 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1510                         VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
1511                         intval($importer["uid"]),
1512                         dbesc($ret["network"]),
1513                         dbesc($ret["addr"]),
1514                         datetime_convert(),
1515                         dbesc($ret["url"]),
1516                         dbesc(normalise_link($ret["url"])),
1517                         dbesc($batch),
1518                         dbesc($ret["name"]),
1519                         dbesc($ret["nick"]),
1520                         dbesc($ret["photo"]),
1521                         dbesc($ret["pubkey"]),
1522                         dbesc($ret["notify"]),
1523                         dbesc($ret["poll"]),
1524                         1,
1525                         2
1526                 );
1527
1528                 // find the contact record we just created
1529
1530                 $contact_record = self::contact_by_handle($importer["uid"],$author);
1531
1532                 if (!$contact_record) {
1533                         logger("unable to locate newly created contact record.");
1534                         return;
1535                 }
1536
1537                 $g = q("SELECT `def_gid` FROM `user` WHERE `uid` = %d LIMIT 1",
1538                         intval($importer["uid"])
1539                 );
1540
1541                 if($g && intval($g[0]["def_gid"]))
1542                         group_add_member($importer["uid"], "", $contact_record["id"], $g[0]["def_gid"]);
1543
1544                 if($importer["page-flags"] == PAGE_NORMAL) {
1545
1546                         $hash = random_string().(string)time();   // Generate a confirm_key
1547
1548                         $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
1549                                 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
1550                                 intval($importer["uid"]),
1551                                 intval($contact_record["id"]),
1552                                 0,
1553                                 0,
1554                                 dbesc(t("Sharing notification from Diaspora network")),
1555                                 dbesc($hash),
1556                                 dbesc(datetime_convert())
1557                         );
1558                 } else {
1559
1560                         // automatic friend approval
1561
1562                         update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1563
1564                         // technically they are sharing with us (CONTACT_IS_SHARING),
1565                         // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1566                         // we are going to change the relationship and make them a follower.
1567
1568                         if($importer["page-flags"] == PAGE_FREELOVE)
1569                                 $new_relation = CONTACT_IS_FRIEND;
1570                         else
1571                                 $new_relation = CONTACT_IS_FOLLOWER;
1572
1573                         $r = q("UPDATE `contact` SET `rel` = %d,
1574                                 `name-date` = '%s',
1575                                 `uri-date` = '%s',
1576                                 `blocked` = 0,
1577                                 `pending` = 0,
1578                                 `writable` = 1
1579                                 WHERE `id` = %d
1580                                 ",
1581                                 intval($new_relation),
1582                                 dbesc(datetime_convert()),
1583                                 dbesc(datetime_convert()),
1584                                 intval($contact_record["id"])
1585                         );
1586
1587                         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1588                         if($u)
1589                                 $ret = self::send_share($u[0], $contact_record);
1590                 }
1591
1592                 return true;
1593         }
1594
1595         private function original_item($guid, $orig_author, $author) {
1596
1597                 // Do we already have this item?
1598                 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1599                                 `author-name`, `author-link`, `author-avatar`
1600                                 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1601                         dbesc($guid));
1602
1603                 if($r) {
1604                         logger("reshared message ".$guid." already exists on system.");
1605
1606                         // Maybe it is already a reshared item?
1607                         // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1608                         if (self::is_reshare($r[0]["body"], false))
1609                                 $r = array();
1610                         else
1611                                 return $r[0];
1612                 }
1613
1614                 if (!$r) {
1615                         $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
1616                         logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1617                         $item_id = self::store_by_guid($guid, $server);
1618
1619                         if (!$item_id) {
1620                                 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
1621                                 logger("2nd try: reshared message ".$guid." will be fetched from original server: ".$server);
1622                                 $item_id = self::store_by_guid($guid, $server);
1623                         }
1624
1625                         // Deactivated by now since there is a risk that someone could manipulate postings through this method
1626 /*                      if (!$item_id) {
1627                                 $server = "https://".substr($author, strpos($author, "@") + 1);
1628                                 logger("3rd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1629                                 $item_id = self::store_by_guid($guid, $server);
1630                         }
1631                         if (!$item_id) {
1632                                 $server = "http://".substr($author, strpos($author, "@") + 1);
1633                                 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1634                                 $item_id = self::store_by_guid($guid, $server);
1635                         }
1636 */
1637                         if ($item_id) {
1638                                 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1639                                                 `author-name`, `author-link`, `author-avatar`
1640                                         FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1641                                         intval($item_id));
1642
1643                                 if ($r)
1644                                         return $r[0];
1645
1646                         }
1647                 }
1648                 return false;
1649         }
1650
1651         private function receive_reshare($importer, $data, $xml) {
1652                 $root_author = notags(unxmlify($data->root_author));
1653                 $root_guid = notags(unxmlify($data->root_guid));
1654                 $guid = notags(unxmlify($data->guid));
1655                 $author = notags(unxmlify($data->author));
1656                 $public = notags(unxmlify($data->public));
1657                 $created_at = notags(unxmlify($data->created_at));
1658
1659                 $contact = self::allowed_contact_by_handle($importer, $author, false);
1660                 if (!$contact)
1661                         return false;
1662
1663                 if (self::message_exists($importer["uid"], $guid))
1664                         return false;
1665
1666                 $original_item = self::original_item($root_guid, $root_author, $author);
1667                 if (!$original_item)
1668                         return false;
1669
1670                 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
1671
1672                 $datarray = array();
1673
1674                 $datarray["uid"] = $importer["uid"];
1675                 $datarray["contact-id"] = $contact["id"];
1676                 $datarray["network"]  = NETWORK_DIASPORA;
1677
1678                 $datarray["author-name"] = $contact["name"];
1679                 $datarray["author-link"] = $contact["url"];
1680                 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1681
1682                 $datarray["owner-name"] = $datarray["author-name"];
1683                 $datarray["owner-link"] = $datarray["author-link"];
1684                 $datarray["owner-avatar"] = $datarray["author-avatar"];
1685
1686                 $datarray["guid"] = $guid;
1687                 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1688
1689                 $datarray["verb"] = ACTIVITY_POST;
1690                 $datarray["gravity"] = GRAVITY_PARENT;
1691
1692                 $datarray["object"] = $xml;
1693
1694                 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
1695                                         $original_item["guid"], $original_item["created"], $orig_url);
1696                 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
1697
1698                 $datarray["tag"] = $original_item["tag"];
1699                 $datarray["app"]  = $original_item["app"];
1700
1701                 $datarray["plink"] = self::plink($author, $guid);
1702                 $datarray["private"] = (($public == "false") ? 1 : 0);
1703                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1704
1705                 $datarray["object-type"] = $original_item["object-type"];
1706
1707                 self::fetch_guid($datarray);
1708                 $message_id = item_store($datarray);
1709
1710                 if ($message_id)
1711                         logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1712
1713                 return $message_id;
1714         }
1715
1716         private function item_retraction($importer, $contact, $data) {
1717                 $target_type = notags(unxmlify($data->target_type));
1718                 $target_guid = notags(unxmlify($data->target_guid));
1719                 $author = notags(unxmlify($data->author));
1720
1721                 $person = self::person_by_handle($author);
1722                 if (!is_array($person)) {
1723                         logger("unable to find author detail for ".$author);
1724                         return false;
1725                 }
1726
1727                 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
1728                         dbesc($target_guid),
1729                         intval($importer["uid"])
1730                 );
1731                 if (!$r)
1732                         return false;
1733
1734                 // Only delete it if the author really fits
1735                 if (!link_compare($r[0]["author-link"], $person["url"])) {
1736                         logger("Item author ".$r[0]["author-link"]." doesn't fit to expected contact ".$person["url"], LOGGER_DEBUG);
1737                         return false;
1738                 }
1739
1740                 // Check if the sender is the thread owner
1741                 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
1742                         intval($r[0]["parent"]));
1743
1744                 // Only delete it if the parent author really fits
1745                 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
1746                         logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
1747                         return false;
1748                 }
1749
1750                 // 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
1751                 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
1752                         dbesc(datetime_convert()),
1753                         dbesc(datetime_convert()),
1754                         intval($r[0]["id"])
1755                 );
1756                 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
1757
1758                 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
1759
1760                 // Now check if the retraction needs to be relayed by us
1761                 if($p[0]["origin"]) {
1762
1763                         // Formerly we stored the signed text, the signature and the author in different fields.
1764                         // We now store the raw data so that we are more flexible.
1765                         q("INSERT INTO `sign` (`retract_iid`,`signed_text`) VALUES (%d,'%s')",
1766                                 intval($r[0]["id"]),
1767                                 dbesc(json_encode($data))
1768                         );
1769                         $s = q("select * from sign where retract_iid = %d", intval($r[0]["id"]));
1770                         logger("Stored signatur for item ".$r[0]["id"]." - ".print_r($s, true), LOGGER_DEBUG);
1771
1772                         // notify others
1773                         proc_run("php", "include/notifier.php", "drop", $r[0]["id"]);
1774                 }
1775         }
1776
1777         private function receive_retraction($importer, $sender, $data) {
1778                 $target_type = notags(unxmlify($data->target_type));
1779
1780                 $contact = self::contact_by_handle($importer["uid"], $sender);
1781                 if (!$contact) {
1782                         logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
1783                         return false;
1784                 }
1785
1786                 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
1787
1788                 switch ($target_type) {
1789                         case "Comment":
1790                         case "Like":
1791                         case "Post": // "Post" will be supported in a future version
1792                         case "Reshare":
1793                         case "StatusMessage":
1794                                 return self::item_retraction($importer, $contact, $data);;
1795
1796                         case "Person":
1797                                 /// @todo What should we do with an "unshare"?
1798                                 // Removing the contact isn't correct since we still can read the public items
1799                                 //contact_remove($contact["id"]);
1800                                 return true;
1801
1802                         default:
1803                                 logger("Unknown target type ".$target_type);
1804                                 return false;
1805                 }
1806                 return true;
1807         }
1808
1809         private function receive_status_message($importer, $data, $xml) {
1810
1811                 $raw_message = unxmlify($data->raw_message);
1812                 $guid = notags(unxmlify($data->guid));
1813                 $author = notags(unxmlify($data->author));
1814                 $public = notags(unxmlify($data->public));
1815                 $created_at = notags(unxmlify($data->created_at));
1816                 $provider_display_name = notags(unxmlify($data->provider_display_name));
1817
1818                 /// @todo enable support for polls
1819                 //if ($data->poll) {
1820                 //      foreach ($data->poll AS $poll)
1821                 //              print_r($poll);
1822                 //      die("poll!\n");
1823                 //}
1824                 $contact = self::allowed_contact_by_handle($importer, $author, false);
1825                 if (!$contact)
1826                         return false;
1827
1828                 if (self::message_exists($importer["uid"], $guid))
1829                         return false;
1830
1831                 $address = array();
1832                 if ($data->location)
1833                         foreach ($data->location->children() AS $fieldname => $data)
1834                                 $address[$fieldname] = notags(unxmlify($data));
1835
1836                 $body = diaspora2bb($raw_message);
1837
1838                 $datarray = array();
1839
1840                 if ($data->photo) {
1841                         foreach ($data->photo AS $photo)
1842                                 $body = "[img]".unxmlify($photo->remote_photo_path).
1843                                         unxmlify($photo->remote_photo_name)."[/img]\n".$body;
1844
1845                         $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
1846                 } else {
1847                         $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1848
1849                         // Add OEmbed and other information to the body
1850                         if (!self::is_redmatrix($contact["url"]))
1851                                 $body = add_page_info_to_body($body, false, true);
1852                 }
1853
1854                 $datarray["uid"] = $importer["uid"];
1855                 $datarray["contact-id"] = $contact["id"];
1856                 $datarray["network"] = NETWORK_DIASPORA;
1857
1858                 $datarray["author-name"] = $contact["name"];
1859                 $datarray["author-link"] = $contact["url"];
1860                 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1861
1862                 $datarray["owner-name"] = $datarray["author-name"];
1863                 $datarray["owner-link"] = $datarray["author-link"];
1864                 $datarray["owner-avatar"] = $datarray["author-avatar"];
1865
1866                 $datarray["guid"] = $guid;
1867                 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1868
1869                 $datarray["verb"] = ACTIVITY_POST;
1870                 $datarray["gravity"] = GRAVITY_PARENT;
1871
1872                 $datarray["object"] = $xml;
1873
1874                 $datarray["body"] = $body;
1875
1876                 if ($provider_display_name != "")
1877                         $datarray["app"] = $provider_display_name;
1878
1879                 $datarray["plink"] = self::plink($author, $guid);
1880                 $datarray["private"] = (($public == "false") ? 1 : 0);
1881                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1882
1883                 if (isset($address["address"]))
1884                         $datarray["location"] = $address["address"];
1885
1886                 if (isset($address["lat"]) AND isset($address["lng"]))
1887                         $datarray["coord"] = $address["lat"]." ".$address["lng"];
1888
1889                 self::fetch_guid($datarray);
1890                 $message_id = item_store($datarray);
1891
1892                 if ($message_id)
1893                         logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1894
1895                 return $message_id;
1896         }
1897
1898         /******************************************************************************************
1899          * Here are all the functions that are needed to transmit data with the Diaspora protocol *
1900          ******************************************************************************************/
1901
1902         private function my_handle($me) {
1903                 if ($contact["addr"] != "")
1904                         return $contact["addr"];
1905
1906                 // Normally we should have a filled "addr" field - but in the past this wasn't the case
1907                 // So - just in case - we build the the address here.
1908                 return $me["nickname"]."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
1909         }
1910
1911         private function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
1912
1913                 logger("Message: ".$msg, LOGGER_DATA);
1914
1915                 $handle = self::my_handle($user);
1916
1917                 $b64url_data = base64url_encode($msg);
1918
1919                 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1920
1921                 $type = "application/xml";
1922                 $encoding = "base64url";
1923                 $alg = "RSA-SHA256";
1924
1925                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1926
1927                 $signature = rsa_sign($signable_data,$prvkey);
1928                 $sig = base64url_encode($signature);
1929
1930                 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
1931                                                 "me:env" => array("me:encoding" => "base64url",
1932                                                                 "me:alg" => "RSA-SHA256",
1933                                                                 "me:data" => $data,
1934                                                                 "@attributes" => array("type" => "application/xml"),
1935                                                                 "me:sig" => $sig)));
1936
1937                 $namespaces = array("" => "https://joindiaspora.com/protocol",
1938                                 "me" => "http://salmon-protocol.org/ns/magic-env");
1939
1940                 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
1941
1942                 logger("magic_env: ".$magic_env, LOGGER_DATA);
1943                 return $magic_env;
1944         }
1945
1946         private function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
1947
1948                 logger("Message: ".$msg, LOGGER_DATA);
1949
1950                 // without a public key nothing will work
1951
1952                 if (!$pubkey) {
1953                         logger("pubkey missing: contact id: ".$contact["id"]);
1954                         return false;
1955                 }
1956
1957                 $inner_aes_key = random_string(32);
1958                 $b_inner_aes_key = base64_encode($inner_aes_key);
1959                 $inner_iv = random_string(16);
1960                 $b_inner_iv = base64_encode($inner_iv);
1961
1962                 $outer_aes_key = random_string(32);
1963                 $b_outer_aes_key = base64_encode($outer_aes_key);
1964                 $outer_iv = random_string(16);
1965                 $b_outer_iv = base64_encode($outer_iv);
1966
1967                 $handle = self::my_handle($user);
1968
1969                 $padded_data = pkcs5_pad($msg,16);
1970                 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
1971
1972                 $b64_data = base64_encode($inner_encrypted);
1973
1974
1975                 $b64url_data = base64url_encode($b64_data);
1976                 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1977
1978                 $type = "application/xml";
1979                 $encoding = "base64url";
1980                 $alg = "RSA-SHA256";
1981
1982                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1983
1984                 $signature = rsa_sign($signable_data,$prvkey);
1985                 $sig = base64url_encode($signature);
1986
1987                 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
1988                                                         "aes_key" => $b_inner_aes_key,
1989                                                         "author_id" => $handle));
1990
1991                 $decrypted_header = xml::from_array($xmldata, $xml, true);
1992                 $decrypted_header = pkcs5_pad($decrypted_header,16);
1993
1994                 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
1995
1996                 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
1997
1998                 $encrypted_outer_key_bundle = "";
1999                 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2000
2001                 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2002
2003                 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2004
2005                 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2006                                                                 "ciphertext" => base64_encode($ciphertext)));
2007                 $cipher_json = base64_encode($encrypted_header_json_object);
2008
2009                 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2010                                                 "me:env" => array("me:encoding" => "base64url",
2011                                                                 "me:alg" => "RSA-SHA256",
2012                                                                 "me:data" => $data,
2013                                                                 "@attributes" => array("type" => "application/xml"),
2014                                                                 "me:sig" => $sig)));
2015
2016                 $namespaces = array("" => "https://joindiaspora.com/protocol",
2017                                 "me" => "http://salmon-protocol.org/ns/magic-env");
2018
2019                 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2020
2021                 logger("magic_env: ".$magic_env, LOGGER_DATA);
2022                 return $magic_env;
2023         }
2024
2025         private function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2026
2027                 if ($public)
2028                         $magic_env =  self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2029                 else
2030                         $magic_env =  self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2031
2032                 // The data that will be transmitted is double encoded via "urlencode", strange ...
2033                 $slap = "xml=".urlencode(urlencode($magic_env));
2034                 return $slap;
2035         }
2036
2037         private function signature($owner, $message) {
2038                 $sigmsg = $message;
2039                 unset($sigmsg["author_signature"]);
2040                 unset($sigmsg["parent_author_signature"]);
2041
2042                 $signed_text = implode(";", $sigmsg);
2043
2044                 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2045         }
2046
2047         public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2048
2049                 $a = get_app();
2050
2051                 $enabled = intval(get_config("system", "diaspora_enabled"));
2052                 if(!$enabled)
2053                         return 200;
2054
2055                 $logid = random_string(4);
2056                 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2057                 if (!$dest_url) {
2058                         logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2059                         return 0;
2060                 }
2061
2062                 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2063
2064                 if (!$queue_run && was_recently_delayed($contact["id"])) {
2065                         $return_code = 0;
2066                 } else {
2067                         if (!intval(get_config("system", "diaspora_test"))) {
2068                                 post_url($dest_url."/", $slap);
2069                                 $return_code = $a->get_curl_code();
2070                         } else {
2071                                 logger("test_mode");
2072                                 return 200;
2073                         }
2074                 }
2075
2076                 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2077
2078                 if(!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2079                         logger("queue message");
2080
2081                         $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2082                                 intval($contact["id"]),
2083                                 dbesc(NETWORK_DIASPORA),
2084                                 dbesc($slap),
2085                                 intval($public_batch)
2086                         );
2087                         if($r) {
2088                                 logger("add_to_queue ignored - identical item already in queue");
2089                         } else {
2090                                 // queue message for redelivery
2091                                 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2092                         }
2093                 }
2094
2095                 return(($return_code) ? $return_code : (-1));
2096         }
2097
2098
2099         private function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2100
2101                 $data = array("XML" => array("post" => array($type => $message)));
2102
2103                 $msg = xml::from_array($data, $xml);
2104
2105                 logger('message: '.$msg, LOGGER_DATA);
2106                 logger('send guid '.$guid, LOGGER_DEBUG);
2107
2108                 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2109
2110                 if ($spool) {
2111                         add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2112                         return true;
2113                 } else
2114                         $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2115
2116                 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2117
2118                 return $return_code;
2119         }
2120
2121         public static function send_share($owner,$contact) {
2122
2123                 $message = array("sender_handle" => self::my_handle($owner),
2124                                 "recipient_handle" => $contact["addr"]);
2125
2126                 return self::build_and_transmit($owner, $contact, "request", $message);
2127         }
2128
2129         public static function send_unshare($owner,$contact) {
2130
2131                 $message = array("post_guid" => $owner["guid"],
2132                                 "diaspora_handle" => self::my_handle($owner),
2133                                 "type" => "Person");
2134
2135                 return self::build_and_transmit($owner, $contact, "retraction", $message);
2136         }
2137
2138         public static function is_reshare($body, $complete = true) {
2139                 $body = trim($body);
2140
2141                 // Skip if it isn't a pure repeated messages
2142                 // Does it start with a share?
2143                 if (strpos($body, "[share") > 0)
2144                         return(false);
2145
2146                 // Does it end with a share?
2147                 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2148                         return(false);
2149
2150                 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2151                 // Skip if there is no shared message in there
2152                 if ($body == $attributes)
2153                         return(false);
2154
2155                 // If we don't do the complete check we quit here
2156                 if (!$complete)
2157                         return true;
2158
2159                 $guid = "";
2160                 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2161                 if ($matches[1] != "")
2162                         $guid = $matches[1];
2163
2164                 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2165                 if ($matches[1] != "")
2166                         $guid = $matches[1];
2167
2168                 if ($guid != "") {
2169                         $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2170                                 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2171                         if ($r) {
2172                                 $ret= array();
2173                                 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2174                                 $ret["root_guid"] = $guid;
2175                                 return($ret);
2176                         }
2177                 }
2178
2179                 $profile = "";
2180                 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2181                 if ($matches[1] != "")
2182                         $profile = $matches[1];
2183
2184                 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2185                 if ($matches[1] != "")
2186                         $profile = $matches[1];
2187
2188                 $ret= array();
2189
2190                 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2191                 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2192                         return(false);
2193
2194                 $link = "";
2195                 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2196                 if ($matches[1] != "")
2197                         $link = $matches[1];
2198
2199                 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2200                 if ($matches[1] != "")
2201                         $link = $matches[1];
2202
2203                 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2204                 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2205                         return(false);
2206                 return($ret);
2207         }
2208
2209         public static function send_status($item, $owner, $contact, $public_batch = false) {
2210
2211                 $myaddr = self::my_handle($owner);
2212
2213                 $public = (($item["private"]) ? "false" : "true");
2214
2215                 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2216
2217                 // Detect a share element and do a reshare
2218                 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
2219                         $message = array("root_diaspora_id" => $ret["root_handle"],
2220                                         "root_guid" => $ret["root_guid"],
2221                                         "guid" => $item["guid"],
2222                                         "diaspora_handle" => $myaddr,
2223                                         "public" => $public,
2224                                         "created_at" => $created,
2225                                         "provider_display_name" => $item["app"]);
2226
2227                         $type = "reshare";
2228                 } else {
2229                         $title = $item["title"];
2230                         $body = $item["body"];
2231
2232                         // convert to markdown
2233                         $body = html_entity_decode(bb2diaspora($body));
2234
2235                         // Adding the title
2236                         if(strlen($title))
2237                                 $body = "## ".html_entity_decode($title)."\n\n".$body;
2238
2239                         if ($item["attach"]) {
2240                                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
2241                                 if(cnt) {
2242                                         $body .= "\n".t("Attachments:")."\n";
2243                                         foreach($matches as $mtch)
2244                                                 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
2245                                 }
2246                         }
2247
2248                         $location = array();
2249
2250                         if ($item["location"] != "")
2251                                 $location["address"] = $item["location"];
2252
2253                         if ($item["coord"] != "") {
2254                                 $coord = explode(" ", $item["coord"]);
2255                                 $location["lat"] = $coord[0];
2256                                 $location["lng"] = $coord[1];
2257                         }
2258
2259                         $message = array("raw_message" => $body,
2260                                         "location" => $location,
2261                                         "guid" => $item["guid"],
2262                                         "diaspora_handle" => $myaddr,
2263                                         "public" => $public,
2264                                         "created_at" => $created,
2265                                         "provider_display_name" => $item["app"]);
2266
2267                         if (count($location) == 0)
2268                                 unset($message["location"]);
2269
2270                         $type = "status_message";
2271                 }
2272
2273                 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2274         }
2275
2276         private function construct_like($item, $owner) {
2277
2278                 $myaddr = self::my_handle($owner);
2279
2280                 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
2281                         dbesc($item["thr-parent"]));
2282                 if(!$p)
2283                         return false;
2284
2285                 $parent = $p[0];
2286
2287                 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
2288                 $positive = "true";
2289
2290                 return(array("positive" => $positive,
2291                                 "guid" => $item["guid"],
2292                                 "target_type" => $target_type,
2293                                 "parent_guid" => $parent["guid"],
2294                                 "author_signature" => $authorsig,
2295                                 "diaspora_handle" => $myaddr));
2296         }
2297
2298         private function construct_comment($item, $owner) {
2299
2300                 $myaddr = self::my_handle($owner);
2301
2302                 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2303                         intval($item["parent"]),
2304                         intval($item["parent"])
2305                 );
2306
2307                 if (!$p)
2308                         return false;
2309
2310                 $parent = $p[0];
2311
2312                 $text = html_entity_decode(bb2diaspora($item["body"]));
2313
2314                 return(array("guid" => $item["guid"],
2315                                 "parent_guid" => $parent["guid"],
2316                                 "author_signature" => "",
2317                                 "text" => $text,
2318                                 "diaspora_handle" => $myaddr));
2319         }
2320
2321         public static function send_followup($item,$owner,$contact,$public_batch = false) {
2322
2323                 if($item['verb'] === ACTIVITY_LIKE) {
2324                         $message = self::construct_like($item, $owner);
2325                         $type = "like";
2326                 } else {
2327                         $message = self::construct_comment($item, $owner);
2328                         $type = "comment";
2329                 }
2330
2331                 if (!$message)
2332                         return false;
2333
2334                 $message["author_signature"] = self::signature($owner, $message);
2335
2336                 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2337         }
2338
2339         private function message_from_signatur($item, $signature) {
2340
2341                 // Split the signed text
2342                 $signed_parts = explode(";", $signature['signed_text']);
2343
2344                 if ($item["deleted"])
2345                         $message = array("parent_author_signature" => "",
2346                                         "target_guid" => $signed_parts[0],
2347                                         "target_type" => $signed_parts[1],
2348                                         "sender_handle" => $signature['signer'],
2349                                         "target_author_signature" => $signature['signature']);
2350                 elseif ($item['verb'] === ACTIVITY_LIKE)
2351                         $message = array("positive" => $signed_parts[0],
2352                                         "guid" => $signed_parts[1],
2353                                         "target_type" => $signed_parts[2],
2354                                         "parent_guid" => $signed_parts[3],
2355                                         "parent_author_signature" => "",
2356                                         "author_signature" => $signature['signature'],
2357                                         "diaspora_handle" => $signed_parts[4]);
2358                 else {
2359                         // Remove the comment guid
2360                         $guid = array_shift($signed_parts);
2361
2362                         // Remove the parent guid
2363                         $parent_guid = array_shift($signed_parts);
2364
2365                         // Remove the handle
2366                         $handle = array_pop($signed_parts);
2367
2368                         // Glue the parts together
2369                         $text = implode(";", $signed_parts);
2370
2371                         $message = array("guid" => $guid,
2372                                         "parent_guid" => $parent_guid,
2373                                         "parent_author_signature" => "",
2374                                         "author_signature" => $signature['signature'],
2375                                         "text" => implode(";", $signed_parts),
2376                                         "diaspora_handle" => $handle);
2377                 }
2378                 return $message;
2379         }
2380
2381         public static function send_relay($item, $owner, $contact, $public_batch = false) {
2382
2383                 if ($item["deleted"]) {
2384                         $sql_sign_id = "retract_iid";
2385                         $type = "relayable_retraction";
2386                 } elseif ($item['verb'] === ACTIVITY_LIKE) {
2387                         $sql_sign_id = "iid";
2388                         $type = "like";
2389                 } else {
2390                         $sql_sign_id = "iid";
2391                         $type = "comment";
2392                 }
2393
2394                 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2395
2396                 // fetch the original signature
2397
2398                 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `".$sql_sign_id."` = %d LIMIT 1",
2399                         intval($item["id"]));
2400
2401                 if (!$r) {
2402                         if ($item["deleted"])
2403                                 return self::send_retraction($item, $owner, $contact, $public_batch);
2404
2405                         logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2406                         return false;
2407                 }
2408
2409                 $signature = $r[0];
2410
2411                 // Old way - is used by the internal Friendica functions
2412                 /// @todo Change all signatur storing functions to the new format
2413                 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
2414                         $message = self::message_from_signatur($item, $signature);
2415                 else {// New way
2416                         $msg = json_decode($signature['signed_text'], true);
2417
2418                         $message = array();
2419                         if (is_array($msg)) {
2420                                 foreach ($msg AS $field => $data) {
2421                                         if (!$item["deleted"]) {
2422                                                 if ($field == "author")
2423                                                         $field = "diaspora_handle";
2424                                                 if ($field == "parent_type")
2425                                                         $field = "target_type";
2426                                         }
2427
2428                                         $message[$field] = $data;
2429                                 }
2430                         } else
2431                                 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
2432                 }
2433
2434                 if ($item["deleted"]) {
2435                         $signed_text = $message["target_guid"].';'.$message["target_type"];
2436                         $message["parent_author_signature"] = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2437                 } else
2438                         $message["parent_author_signature"] = self::signature($owner, $message);
2439
2440                 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
2441
2442                 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2443         }
2444
2445         public static function send_retraction($item, $owner, $contact, $public_batch = false) {
2446
2447                 /// @todo Fetch handle from every contact (via gcontact)
2448                 $itemaddr = self::handle_from_contact($item["contact-id"]);
2449
2450                 $myaddr = self::my_handle($owner);
2451
2452                 // Check whether the retraction is for a top-level post or whether it's a relayable
2453                 if ($item["uri"] !== $item["parent-uri"]) {
2454                         $msg_type = "relayable_retraction";
2455                         $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
2456                 } else {
2457                         $msg_type = "signed_retraction";
2458                         $target_type = "StatusMessage";
2459                 }
2460
2461                 $signed_text = $item["guid"].";".$target_type;
2462
2463                 $message = array("target_guid" => $item['guid'],
2464                                 "target_type" => $target_type,
2465                                 "sender_handle" => $itemaddr,
2466                                 "target_author_signature" => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
2467
2468                 if ($itemaddr != $myaddr) {
2469                         $message["parent_author_signature"] = $message["target_author_signature"];
2470                         unset($message["target_author_signature"]);
2471                 }
2472
2473                 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
2474
2475                 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
2476         }
2477
2478         public static function send_mail($item, $owner, $contact) {
2479
2480                 $myaddr = self::my_handle($owner);
2481
2482                 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2483                         intval($item["convid"]),
2484                         intval($item["uid"])
2485                 );
2486
2487                 if (!$r) {
2488                         logger("conversation not found.");
2489                         return;
2490                 }
2491                 $cnv = $r[0];
2492
2493                 $conv = array(
2494                         "guid" => $cnv["guid"],
2495                         "subject" => $cnv["subject"],
2496                         "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2497                         "diaspora_handle" => $cnv["creator"],
2498                         "participant_handles" => $cnv["recips"]
2499                 );
2500
2501                 $body = bb2diaspora($item["body"]);
2502                 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2503
2504                 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
2505                 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2506
2507                 $msg = array(
2508                         "guid" => $item["guid"],
2509                         "parent_guid" => $cnv["guid"],
2510                         "parent_author_signature" => $sig,
2511                         "author_signature" => $sig,
2512                         "text" => $body,
2513                         "created_at" => $created,
2514                         "diaspora_handle" => $myaddr,
2515                         "conversation_guid" => $cnv["guid"]
2516                 );
2517
2518                 if ($item["reply"]) {
2519                         $message = $msg;
2520                         $type = "message";
2521                 } else {
2522                         $message = array("guid" => $cnv["guid"],
2523                                         "subject" => $cnv["subject"],
2524                                         "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2525                                         "message" => $msg,
2526                                         "diaspora_handle" => $cnv["creator"],
2527                                         "participant_handles" => $cnv["recips"]);
2528
2529                         $type = "conversation";
2530                 }
2531
2532                 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
2533         }
2534
2535         public static function send_profile($uid) {
2536
2537                 if (!$uid)
2538                         return;
2539
2540                 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
2541                         AND `uid` = %d AND `rel` != %d",
2542                         dbesc(NETWORK_DIASPORA),
2543                         intval($uid),
2544                         intval(CONTACT_IS_SHARING)
2545                 );
2546                 if (!$recips)
2547                         return;
2548
2549                 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
2550                         FROM `profile`
2551                         INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
2552                         INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
2553                         WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
2554                         intval($uid)
2555                 );
2556
2557                 if (!$r)
2558                         return;
2559
2560                 $profile = $r[0];
2561
2562                 $handle = $profile["addr"];
2563                 $first = ((strpos($profile['name'],' ')
2564                         ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
2565                 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
2566                 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
2567                 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
2568                 $small = App::get_baseurl().'/photo/custom/50/'  .$profile['uid'].'.jpg';
2569                 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
2570
2571                 if ($searchable === 'true') {
2572                         $dob = '1000-00-00';
2573
2574                         if (($profile['dob']) && ($profile['dob'] != '0000-00-00'))
2575                                 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
2576
2577                         $about = $profile['about'];
2578                         $about = strip_tags(bbcode($about));
2579
2580                         $location = formatted_location($profile);
2581                         $tags = '';
2582                         if ($profile['pub_keywords']) {
2583                                 $kw = str_replace(',',' ',$profile['pub_keywords']);
2584                                 $kw = str_replace('  ',' ',$kw);
2585                                 $arr = explode(' ',$profile['pub_keywords']);
2586                                 if (count($arr)) {
2587                                         for($x = 0; $x < 5; $x ++) {
2588                                                 if (trim($arr[$x]))
2589                                                         $tags .= '#'. trim($arr[$x]) .' ';
2590                                         }
2591                                 }
2592                         }
2593                         $tags = trim($tags);
2594                 }
2595
2596                 $message = array("diaspora_handle" => $handle,
2597                                 "first_name" => $first,
2598                                 "last_name" => $last,
2599                                 "image_url" => $large,
2600                                 "image_url_medium" => $medium,
2601                                 "image_url_small" => $small,
2602                                 "birthday" => $dob,
2603                                 "gender" => $profile['gender'],
2604                                 "bio" => $about,
2605                                 "location" => $location,
2606                                 "searchable" => $searchable,
2607                                 "tag_string" => $tags);
2608
2609                 foreach($recips as $recip)
2610                         self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
2611         }
2612 }
2613 ?>