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