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