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