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