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