]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
diaspora.php: Standards, standards everywhere
[friendica.git] / include / diaspora.php
1 <?php
2 /**
3  * @file include/diaspora.php
4  * @brief The implementation of the diaspora protocol
5  *
6  * The new protocol is described here: http://diaspora.github.io/diaspora_federation/index.html
7  * Currently this implementation here interprets the old and the new protocol and sends the old one.
8  * This will change in the future.
9  */
10
11 require_once("include/items.php");
12 require_once("include/bb2diaspora.php");
13 require_once("include/Scrape.php");
14 require_once("include/Contact.php");
15 require_once("include/Photo.php");
16 require_once("include/socgraph.php");
17 require_once("include/group.php");
18 require_once("include/xml.php");
19 require_once("include/datetime.php");
20 require_once("include/queue_fn.php");
21
22 /**
23  * @brief This class contain functions to create and send Diaspora XML files
24  *
25  */
26 class Diaspora {
27
28         /**
29          * @brief Return a list of relay servers
30          *
31          * This is an experimental Diaspora feature.
32          *
33          * @return array of relay servers
34          */
35         public static function relay_list() {
36
37                 $serverdata = get_config("system", "relay_server");
38                 if ($serverdata == "")
39                         return array();
40
41                 $relay = array();
42
43                 $servers = explode(",", $serverdata);
44
45                 foreach($servers AS $server) {
46                         $server = trim($server);
47                         $batch = $server."/receive/public";
48
49                         $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
50
51                         if (!$relais) {
52                                 $addr = "relay@".str_replace("http://", "", normalise_link($server));
53
54                                 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
55                                         VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
56                                         datetime_convert(),
57                                         dbesc($addr),
58                                         dbesc($addr),
59                                         dbesc($server),
60                                         dbesc(normalise_link($server)),
61                                         dbesc($batch),
62                                         dbesc(NETWORK_DIASPORA),
63                                         intval(CONTACT_IS_FOLLOWER),
64                                         dbesc(datetime_convert()),
65                                         dbesc(datetime_convert()),
66                                         dbesc(datetime_convert())
67                                 );
68
69                                 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
70                                 if ($relais)
71                                         $relay[] = $relais[0];
72                         } else
73                                 $relay[] = $relais[0];
74                 }
75
76                 return $relay;
77         }
78
79         /**
80          * @brief repairs a signature that was double encoded
81          *
82          * The function is unused at the moment. It was copied from the old implementation.
83          *
84          * @param string $signature The signature
85          * @param string $handle The handle of the signature owner
86          * @param integer $level This value is only set inside this function to avoid endless loops
87          *
88          * @return string the repaired signature
89          */
90         private function repair_signature($signature, $handle = "", $level = 1) {
91
92                 if ($signature == "")
93                         return ($signature);
94
95                 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
96                         $signature = base64_decode($signature);
97                         logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
98
99                         // Do a recursive call to be able to fix even multiple levels
100                         if ($level < 10)
101                                 $signature = self::repair_signature($signature, $handle, ++$level);
102                 }
103
104                 return($signature);
105         }
106
107         /**
108          * @brief verify the envelope and return the verified data
109          *
110          * @param string $envelope The magic envelope
111          *
112          * @return string verified data
113          */
114         private function verify_magic_envelope($envelope) {
115
116                 $basedom = parse_xml_string($envelope, false);
117
118                 if (!is_object($basedom)) {
119                         logger("Envelope is no XML file");
120                         return false;
121                 }
122
123                 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
124
125                 if (sizeof($children) == 0) {
126                         logger("XML has no children");
127                         return false;
128                 }
129
130                 $handle = "";
131
132                 $data = base64url_decode($children->data);
133                 $type = $children->data->attributes()->type[0];
134
135                 $encoding = $children->encoding;
136
137                 $alg = $children->alg;
138
139                 $sig = base64url_decode($children->sig);
140                 $key_id = $children->sig->attributes()->key_id[0];
141                 if ($key_id != "")
142                         $handle = base64url_decode($key_id);
143
144                 $b64url_data = base64url_encode($data);
145                 $msg = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
146
147                 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
148
149                 $key = self::key($handle);
150
151                 $verify = rsa_verify($signable_data, $sig, $key);
152                 if (!$verify) {
153                         logger('Message did not verify. Discarding.');
154                         return false;
155                 }
156
157                 return $data;
158         }
159
160         /**
161          * @brief: Decodes incoming Diaspora message
162          *
163          * @param array $importer Array of the importer user
164          * @param string $xml urldecoded Diaspora salmon
165          *
166          * @return array
167          * 'message' -> decoded Diaspora XML message
168          * 'author' -> author diaspora handle
169          * 'key' -> author public key (converted to pkcs#8)
170          */
171         public static function decode($importer, $xml) {
172
173                 $public = false;
174                 $basedom = parse_xml_string($xml);
175
176                 if (!is_object($basedom))
177                         return false;
178
179                 $children = $basedom->children('https://joindiaspora.com/protocol');
180
181                 if($children->header) {
182                         $public = true;
183                         $author_link = str_replace('acct:','',$children->header->author_id);
184                 } else {
185
186                         $encrypted_header = json_decode(base64_decode($children->encrypted_header));
187
188                         $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
189                         $ciphertext = base64_decode($encrypted_header->ciphertext);
190
191                         $outer_key_bundle = '';
192                         openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
193
194                         $j_outer_key_bundle = json_decode($outer_key_bundle);
195
196                         $outer_iv = base64_decode($j_outer_key_bundle->iv);
197                         $outer_key = base64_decode($j_outer_key_bundle->key);
198
199                         $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
200
201
202                         $decrypted = pkcs5_unpad($decrypted);
203
204                         logger('decrypted: '.$decrypted, LOGGER_DEBUG);
205                         $idom = parse_xml_string($decrypted,false);
206
207                         $inner_iv = base64_decode($idom->iv);
208                         $inner_aes_key = base64_decode($idom->aes_key);
209
210                         $author_link = str_replace('acct:','',$idom->author_id);
211                 }
212
213                 $dom = $basedom->children(NAMESPACE_SALMON_ME);
214
215                 // figure out where in the DOM tree our data is hiding
216
217                 if($dom->provenance->data)
218                         $base = $dom->provenance;
219                 elseif($dom->env->data)
220                         $base = $dom->env;
221                 elseif($dom->data)
222                         $base = $dom;
223
224                 if (!$base) {
225                         logger('unable to locate salmon data in xml');
226                         http_status_exit(400);
227                 }
228
229
230                 // Stash the signature away for now. We have to find their key or it won't be good for anything.
231                 $signature = base64url_decode($base->sig);
232
233                 // unpack the  data
234
235                 // strip whitespace so our data element will return to one big base64 blob
236                 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
237
238
239                 // stash away some other stuff for later
240
241                 $type = $base->data[0]->attributes()->type[0];
242                 $keyhash = $base->sig[0]->attributes()->keyhash[0];
243                 $encoding = $base->encoding;
244                 $alg = $base->alg;
245
246
247                 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
248
249
250                 // decode the data
251                 $data = base64url_decode($data);
252
253
254                 if($public)
255                         $inner_decrypted = $data;
256                 else {
257
258                         // Decode the encrypted blob
259
260                         $inner_encrypted = base64_decode($data);
261                         $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
262                         $inner_decrypted = pkcs5_unpad($inner_decrypted);
263                 }
264
265                 if (!$author_link) {
266                         logger('Could not retrieve author URI.');
267                         http_status_exit(400);
268                 }
269                 // Once we have the author URI, go to the web and try to find their public key
270                 // (first this will look it up locally if it is in the fcontact cache)
271                 // This will also convert diaspora public key from pkcs#1 to pkcs#8
272
273                 logger('Fetching key for '.$author_link);
274                 $key = self::key($author_link);
275
276                 if (!$key) {
277                         logger('Could not retrieve author key.');
278                         http_status_exit(400);
279                 }
280
281                 $verify = rsa_verify($signed_data,$signature,$key);
282
283                 if (!$verify) {
284                         logger('Message did not verify. Discarding.');
285                         http_status_exit(400);
286                 }
287
288                 logger('Message verified.');
289
290                 return array('message' => (string)$inner_decrypted,
291                                 'author' => unxmlify($author_link),
292                                 'key' => (string)$key);
293         }
294
295
296         /**
297          * @brief Dispatches public messages and find the fitting receivers
298          *
299          * @param array $msg The post that will be dispatched
300          *
301          * @return int The message id of the generated message, "true" or "false" if there was an error
302          */
303         public static function dispatch_public($msg) {
304
305                 $enabled = intval(get_config("system", "diaspora_enabled"));
306                 if (!$enabled) {
307                         logger("diaspora is disabled");
308                         return false;
309                 }
310
311                 // Use a dummy importer to import the data for the public copy
312                 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
313                 $message_id = self::dispatch($importer,$msg);
314
315                 // Now distribute it to the followers
316                 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
317                         (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
318                         AND NOT `account_expired` AND NOT `account_removed`",
319                         dbesc(NETWORK_DIASPORA),
320                         dbesc($msg["author"])
321                 );
322                 if($r) {
323                         foreach($r as $rr) {
324                                 logger("delivering to: ".$rr["username"]);
325                                 self::dispatch($rr,$msg);
326                         }
327                 } else
328                         logger("No subscribers for ".$msg["author"]." ".print_r($msg, true));
329
330                 return $message_id;
331         }
332
333         /**
334          * @brief Dispatches the different message types to the different functions
335          *
336          * @param array $importer Array of the importer user
337          * @param array $msg The post that will be dispatched
338          *
339          * @return int The message id of the generated message, "true" or "false" if there was an error
340          */
341         public static function dispatch($importer, $msg) {
342
343                 // The sender is the handle of the contact that sent the message.
344                 // This will often be different with relayed messages (for example "like" and "comment")
345                 $sender = $msg["author"];
346
347                 if (!self::valid_posting($msg, $fields)) {
348                         logger("Invalid posting");
349                         return false;
350                 }
351
352                 $type = $fields->getName();
353
354                 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
355
356                 switch ($type) {
357                         case "account_deletion":
358                                 return self::receive_account_deletion($importer, $fields);
359
360                         case "comment":
361                                 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
362
363                         case "contact":
364                                 return self::receive_contact_request($importer, $fields);
365
366                         case "conversation":
367                                 return self::receive_conversation($importer, $msg, $fields);
368
369                         case "like":
370                                 return self::receive_like($importer, $sender, $fields);
371
372                         case "message":
373                                 return self::receive_message($importer, $fields);
374
375                         case "participation": // Not implemented
376                                 return self::receive_participation($importer, $fields);
377
378                         case "photo": // Not implemented
379                                 return self::receive_photo($importer, $fields);
380
381                         case "poll_participation": // Not implemented
382                                 return self::receive_poll_participation($importer, $fields);
383
384                         case "profile":
385                                 return self::receive_profile($importer, $fields);
386
387                         case "reshare":
388                                 return self::receive_reshare($importer, $fields, $msg["message"]);
389
390                         case "retraction":
391                                 return self::receive_retraction($importer, $sender, $fields);
392
393                         case "status_message":
394                                 return self::receive_status_message($importer, $fields, $msg["message"]);
395
396                         default:
397                                 logger("Unknown message type ".$type);
398                                 return false;
399                 }
400
401                 return true;
402         }
403
404         /**
405          * @brief Checks if a posting is valid and fetches the data fields.
406          *
407          * This function does not only check the signature.
408          * It also does the conversion between the old and the new diaspora format.
409          *
410          * @param array $msg Array with the XML, the sender handle and the sender signature
411          * @param object $fields SimpleXML object that contains the posting when it is valid
412          *
413          * @return bool Is the posting valid?
414          */
415         private function valid_posting($msg, &$fields) {
416
417                 $data = parse_xml_string($msg["message"], false);
418
419                 if (!is_object($data)) {
420                         logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
421                         return false;
422                 }
423
424                 $first_child = $data->getName();
425
426                 // Is this the new or the old version?
427                 if ($data->getName() == "XML") {
428                         $oldXML = true;
429                         foreach ($data->post->children() as $child)
430                                 $element = $child;
431                 } else {
432                         $oldXML = false;
433                         $element = $data;
434                 }
435
436                 $type = $element->getName();
437                 $orig_type = $type;
438
439                 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
440
441                 // All retractions are handled identically from now on.
442                 // In the new version there will only be "retraction".
443                 if (in_array($type, array("signed_retraction", "relayable_retraction")))
444                         $type = "retraction";
445
446                 if ($type == "request")
447                         $type = "contact";
448
449                 $fields = new SimpleXMLElement("<".$type."/>");
450
451                 $signed_data = "";
452
453                 foreach ($element->children() AS $fieldname => $entry) {
454                         if ($oldXML) {
455                                 // Translation for the old XML structure
456                                 if ($fieldname == "diaspora_handle")
457                                         $fieldname = "author";
458
459                                 if ($fieldname == "participant_handles")
460                                         $fieldname = "participants";
461
462                                 if (in_array($type, array("like", "participation"))) {
463                                         if ($fieldname == "target_type")
464                                                 $fieldname = "parent_type";
465                                 }
466
467                                 if ($fieldname == "sender_handle")
468                                         $fieldname = "author";
469
470                                 if ($fieldname == "recipient_handle")
471                                         $fieldname = "recipient";
472
473                                 if ($fieldname == "root_diaspora_id")
474                                         $fieldname = "root_author";
475
476                                 if ($type == "retraction") {
477                                         if ($fieldname == "post_guid")
478                                                 $fieldname = "target_guid";
479
480                                         if ($fieldname == "type")
481                                                 $fieldname = "target_type";
482                                 }
483                         }
484
485                         if (($fieldname == "author_signature") AND ($entry != ""))
486                                 $author_signature = base64_decode($entry);
487                         elseif (($fieldname == "parent_author_signature") AND ($entry != ""))
488                                 $parent_author_signature = base64_decode($entry);
489                         elseif (!in_array($fieldname, array("author_signature", "parent_author_signature", "target_author_signature"))) {
490                                 if ($signed_data != "") {
491                                         $signed_data .= ";";
492                                         $signed_data_parent .= ";";
493                                 }
494
495                                 $signed_data .= $entry;
496                         }
497                         if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
498                                 ($orig_type == "relayable_retraction"))
499                                 xml::copy($entry, $fields, $fieldname);
500                 }
501
502                 // This is something that shouldn't happen at all.
503                 if (in_array($type, array("status_message", "reshare", "profile")))
504                         if ($msg["author"] != $fields->author) {
505                                 logger("Message handle is not the same as envelope sender. Quitting this message.");
506                                 return false;
507                         }
508
509                 // Only some message types have signatures. So we quit here for the other types.
510                 if (!in_array($type, array("comment", "message", "like")))
511                         return true;
512
513                 // No author_signature? This is a must, so we quit.
514                 if (!isset($author_signature)) {
515                         logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
516                         return false;
517                 }
518
519                 if (isset($parent_author_signature)) {
520                         $key = self::key($msg["author"]);
521
522                         if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256")) {
523                                 logger("No valid parent author signature for author ".$msg["author"]. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$parent_author_signature, LOGGER_DEBUG);
524                                 return false;
525                         }
526                 }
527
528                 $key = self::key($fields->author);
529
530                 if (!rsa_verify($signed_data, $author_signature, $key, "sha256")) {
531                         logger("No valid author signature for author ".$msg["author"]. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
532                         return false;
533                 } else
534                         return true;
535         }
536
537         /**
538          * @brief Fetches the public key for a given handle
539          *
540          * @param string $handle The handle
541          *
542          * @return string The public key
543          */
544         private function key($handle) {
545                 $handle = strval($handle);
546
547                 logger("Fetching diaspora key for: ".$handle);
548
549                 $r = self::person_by_handle($handle);
550                 if($r)
551                         return $r["pubkey"];
552
553                 return "";
554         }
555
556         /**
557          * @brief Fetches data for a given handle
558          *
559          * @param string $handle The handle
560          *
561          * @return array the queried data
562          */
563         private function person_by_handle($handle) {
564
565                 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
566                         dbesc(NETWORK_DIASPORA),
567                         dbesc($handle)
568                 );
569                 if ($r) {
570                         $person = $r[0];
571                         logger("In cache ".print_r($r,true), LOGGER_DEBUG);
572
573                         // update record occasionally so it doesn't get stale
574                         $d = strtotime($person["updated"]." +00:00");
575                         if ($d < strtotime("now - 14 days"))
576                                 $update = true;
577
578                         if ($person["guid"] == "")
579                                 $update = true;
580                 }
581
582                 if (!$person OR $update) {
583                         logger("create or refresh", LOGGER_DEBUG);
584                         $r = probe_url($handle, PROBE_DIASPORA);
585
586                         // Note that Friendica contacts will return a "Diaspora person"
587                         // if Diaspora connectivity is enabled on their server
588                         if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
589                                 self::add_fcontact($r, $update);
590                                 $person = $r;
591                         }
592                 }
593                 return $person;
594         }
595
596         /**
597          * @brief Updates the fcontact table
598          *
599          * @param array $arr The fcontact data
600          * @param bool $update Update or insert?
601          *
602          * @return string The id of the fcontact entry
603          */
604         private function add_fcontact($arr, $update = false) {
605
606                 if($update) {
607                         $r = q("UPDATE `fcontact` SET
608                                         `name` = '%s',
609                                         `photo` = '%s',
610                                         `request` = '%s',
611                                         `nick` = '%s',
612                                         `addr` = '%s',
613                                         `guid` = '%s',
614                                         `batch` = '%s',
615                                         `notify` = '%s',
616                                         `poll` = '%s',
617                                         `confirm` = '%s',
618                                         `alias` = '%s',
619                                         `pubkey` = '%s',
620                                         `updated` = '%s'
621                                 WHERE `url` = '%s' AND `network` = '%s'",
622                                         dbesc($arr["name"]),
623                                         dbesc($arr["photo"]),
624                                         dbesc($arr["request"]),
625                                         dbesc($arr["nick"]),
626                                         dbesc(strtolower($arr["addr"])),
627                                         dbesc($arr["guid"]),
628                                         dbesc($arr["batch"]),
629                                         dbesc($arr["notify"]),
630                                         dbesc($arr["poll"]),
631                                         dbesc($arr["confirm"]),
632                                         dbesc($arr["alias"]),
633                                         dbesc($arr["pubkey"]),
634                                         dbesc(datetime_convert()),
635                                         dbesc($arr["url"]),
636                                         dbesc($arr["network"])
637                                 );
638                 } else {
639                         $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
640                                         `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
641                                 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
642                                         dbesc($arr["url"]),
643                                         dbesc($arr["name"]),
644                                         dbesc($arr["photo"]),
645                                         dbesc($arr["request"]),
646                                         dbesc($arr["nick"]),
647                                         dbesc($arr["addr"]),
648                                         dbesc($arr["guid"]),
649                                         dbesc($arr["batch"]),
650                                         dbesc($arr["notify"]),
651                                         dbesc($arr["poll"]),
652                                         dbesc($arr["confirm"]),
653                                         dbesc($arr["network"]),
654                                         dbesc($arr["alias"]),
655                                         dbesc($arr["pubkey"]),
656                                         dbesc(datetime_convert())
657                                 );
658                 }
659
660                 return $r;
661         }
662
663         /**
664          * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
665          *
666          * @param int $contact_id The id in the contact table
667          * @param int $gcontact_id The id in the gcontact table
668          *
669          * @return string the handle
670          */
671         public static function handle_from_contact($contact_id, $gcontact_id = 0) {
672                 $handle = false;
673
674                 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
675
676                 if ($gcontact_id != 0) {
677                         $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
678                                 intval($gcontact_id));
679
680                         if (dbm::is_result($r)) {
681                                 return strtolower($r[0]["addr"]);
682                         }
683                 }
684
685                 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
686                         intval($contact_id));
687
688                 if (dbm::is_result($r)) {
689                         $contact = $r[0];
690
691                         logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
692
693                         if ($contact['addr'] != "") {
694                                 $handle = $contact['addr'];
695                         } else {
696                                 $baseurl_start = strpos($contact['url'],'://') + 3;
697                                 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
698                                 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
699                                 $handle = $contact['nick'].'@'.$baseurl;
700                         }
701                 }
702
703                 return strtolower($handle);
704         }
705
706         /**
707          * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
708          * fcontact guid
709          *
710          * @param mixed $fcontact_guid Hexadecimal string guid
711          *
712          * @return string the contact url or null
713          */
714         public static function url_from_fcontact_guid($fcontact_guid) {
715                 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
716
717                 $r = q("SELECT `url` FROM `fcontact` WHERE `guid` = '%s' AND `network` = 'dspr' AND `url` != ''",
718                         $fcontact_guid);
719
720                 if (dbm::is_result($r)) {
721                         return $r[0]['url'];
722                 }
723
724                 return null;
725         }
726
727         /**
728          * @brief Get a contact id for a given handle
729          *
730          * @param int $uid The user id
731          * @param string $handle The handle in the format user@domain.tld
732          *
733          * @return The contact id
734          */
735         private function contact_by_handle($uid, $handle) {
736                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
737                         intval($uid),
738                         dbesc($handle)
739                 );
740
741                 if ($r)
742                         return $r[0];
743
744                 $handle_parts = explode("@", $handle);
745                 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
746                 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
747                         dbesc(NETWORK_DFRN),
748                         intval($uid),
749                         dbesc($nurl_sql)
750                 );
751                 if($r)
752                         return $r[0];
753
754                 return false;
755         }
756
757         /**
758          * @brief Check if posting is allowed for this contact
759          *
760          * @param array $importer Array of the importer user
761          * @param array $contact The contact that is checked
762          * @param bool $is_comment Is the check for a comment?
763          *
764          * @return bool is the contact allowed to post?
765          */
766         private function post_allow($importer, $contact, $is_comment = false) {
767
768                 // perhaps we were already sharing with this person. Now they're sharing with us.
769                 // That makes us friends.
770                 // Normally this should have handled by getting a request - but this could get lost
771                 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
772                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
773                                 intval(CONTACT_IS_FRIEND),
774                                 intval($contact["id"]),
775                                 intval($importer["uid"])
776                         );
777                         $contact["rel"] = CONTACT_IS_FRIEND;
778                         logger("defining user ".$contact["nick"]." as friend");
779                 }
780
781                 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
782                         return false;
783                 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
784                         return true;
785                 if($contact["rel"] == CONTACT_IS_FOLLOWER)
786                         if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
787                                 return true;
788
789                 // Messages for the global users are always accepted
790                 if ($importer["uid"] == 0)
791                         return true;
792
793                 return false;
794         }
795
796         /**
797          * @brief Fetches the contact id for a handle and checks if posting is allowed
798          *
799          * @param array $importer Array of the importer user
800          * @param string $handle The checked handle in the format user@domain.tld
801          * @param bool $is_comment Is the check for a comment?
802          *
803          * @return array The contact data
804          */
805         private function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
806                 $contact = self::contact_by_handle($importer["uid"], $handle);
807                 if (!$contact) {
808                         logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
809                         return false;
810                 }
811
812                 if (!self::post_allow($importer, $contact, $is_comment)) {
813                         logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
814                         return false;
815                 }
816                 return $contact;
817         }
818
819         /**
820          * @brief Does the message already exists on the system?
821          *
822          * @param int $uid The user id
823          * @param string $guid The guid of the message
824          *
825          * @return int|bool message id if the message already was stored into the system - or false.
826          */
827         private function message_exists($uid, $guid) {
828                 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
829                         intval($uid),
830                         dbesc($guid)
831                 );
832
833                 if($r) {
834                         logger("message ".$guid." already exists for user ".$uid);
835                         return $r[0]["id"];
836                 }
837
838                 return false;
839         }
840
841         /**
842          * @brief Checks for links to posts in a message
843          *
844          * @param array $item The item array
845          */
846         private function fetch_guid($item) {
847                 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
848                         function ($match) use ($item){
849                                 return(self::fetch_guid_sub($match, $item));
850                         },$item["body"]);
851         }
852
853         /**
854          * @brief Checks for relative /people/* links in an item body to match local
855          * contacts or prepends the remote host taken from the author link.
856          *
857          * @param string $body The item body to replace links from
858          * @param string $author_link The author link for missing local contact fallback
859          *
860          * @return the replaced string
861          */
862         public function replace_people_guid($body, $author_link) {
863                 $return = preg_replace_callback("&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
864                         function ($match) use ($author_link) {
865                                 // $match
866                                 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
867                                 // 1 => '0123456789abcdef'
868                                 // 2 => 'Foo Bar'
869                                 $handle = self::url_from_fcontact_guid($match[1]);
870
871                                 if ($handle) {
872                                         $return = '@[url='.$handle.']'.$match[2].'[/url]';
873                                 }else {
874                                         // No local match, restoring absolute remote URL from author scheme and host
875                                         $author_url = parse_url($author_link);
876                                         $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
877                                 }
878
879                                 return $return;
880                         }, $body);
881
882                 return $return;
883         }
884
885         /**
886          * @brief sub function of "fetch_guid" which checks for links in messages
887          *
888          * @param array $match array containing a link that has to be checked for a message link
889          * @param array $item The item array
890          */
891         private function fetch_guid_sub($match, $item) {
892                 if (!self::store_by_guid($match[1], $item["author-link"]))
893                         self::store_by_guid($match[1], $item["owner-link"]);
894         }
895
896         /**
897          * @brief Fetches an item with a given guid from a given server
898          *
899          * @param string $guid the message guid
900          * @param string $server The server address
901          * @param int $uid The user id of the user
902          *
903          * @return int the message id of the stored message or false
904          */
905         private function store_by_guid($guid, $server, $uid = 0) {
906                 $serverparts = parse_url($server);
907                 $server = $serverparts["scheme"]."://".$serverparts["host"];
908
909                 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
910
911                 $msg = self::message($guid, $server);
912
913                 if (!$msg)
914                         return false;
915
916                 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
917
918                 // Now call the dispatcher
919                 return self::dispatch_public($msg);
920         }
921
922         /**
923          * @brief Fetches a message from a server
924          *
925          * @param string $guid message guid
926          * @param string $server The url of the server
927          * @param int $level Endless loop prevention
928          *
929          * @return array
930          *      'message' => The message XML
931          *      'author' => The author handle
932          *      'key' => The public key of the author
933          */
934         private function message($guid, $server, $level = 0) {
935
936                 if ($level > 5)
937                         return false;
938
939                 // This will work for new Diaspora servers and Friendica servers from 3.5
940                 $source_url = $server."/fetch/post/".$guid;
941                 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
942
943                 $envelope = fetch_url($source_url);
944                 if($envelope) {
945                         logger("Envelope was fetched.", LOGGER_DEBUG);
946                         $x = self::verify_magic_envelope($envelope);
947                         if (!$x)
948                                 logger("Envelope could not be verified.", LOGGER_DEBUG);
949                         else
950                                 logger("Envelope was verified.", LOGGER_DEBUG);
951                 } else
952                         $x = false;
953
954                 // This will work for older Diaspora and Friendica servers
955                 if (!$x) {
956                         $source_url = $server."/p/".$guid.".xml";
957                         logger("Fetch post from ".$source_url, LOGGER_DEBUG);
958
959                         $x = fetch_url($source_url);
960                         if(!$x)
961                                 return false;
962                 }
963
964                 $source_xml = parse_xml_string($x, false);
965
966                 if (!is_object($source_xml))
967                         return false;
968
969                 if ($source_xml->post->reshare) {
970                         // Reshare of a reshare - old Diaspora version
971                         logger("Message is a reshare", LOGGER_DEBUG);
972                         return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
973                 } elseif ($source_xml->getName() == "reshare") {
974                         // Reshare of a reshare - new Diaspora version
975                         logger("Message is a new reshare", LOGGER_DEBUG);
976                         return self::message($source_xml->root_guid, $server, ++$level);
977                 }
978
979                 $author = "";
980
981                 // Fetch the author - for the old and the new Diaspora version
982                 if ($source_xml->post->status_message->diaspora_handle)
983                         $author = (string)$source_xml->post->status_message->diaspora_handle;
984                 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
985                         $author = (string)$source_xml->author;
986
987                 // If this isn't a "status_message" then quit
988                 if (!$author) {
989                         logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
990                         return false;
991                 }
992
993                 $msg = array("message" => $x, "author" => $author);
994
995                 $msg["key"] = self::key($msg["author"]);
996
997                 return $msg;
998         }
999
1000         /**
1001          * @brief Fetches the item record of a given guid
1002          *
1003          * @param int $uid The user id
1004          * @param string $guid message guid
1005          * @param string $author The handle of the item
1006          * @param array $contact The contact of the item owner
1007          *
1008          * @return array the item record
1009          */
1010         private function parent_item($uid, $guid, $author, $contact) {
1011                 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1012                                 `author-name`, `author-link`, `author-avatar`,
1013                                 `owner-name`, `owner-link`, `owner-avatar`
1014                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1015                         intval($uid), dbesc($guid));
1016
1017                 if(!$r) {
1018                         $result = self::store_by_guid($guid, $contact["url"], $uid);
1019
1020                         if (!$result) {
1021                                 $person = self::person_by_handle($author);
1022                                 $result = self::store_by_guid($guid, $person["url"], $uid);
1023                         }
1024
1025                         if ($result) {
1026                                 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1027
1028                                 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1029                                                 `author-name`, `author-link`, `author-avatar`,
1030                                                 `owner-name`, `owner-link`, `owner-avatar`
1031                                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1032                                         intval($uid), dbesc($guid));
1033                         }
1034                 }
1035
1036                 if (!$r) {
1037                         logger("parent item not found: parent: ".$guid." - user: ".$uid);
1038                         return false;
1039                 } else {
1040                         logger("parent item found: parent: ".$guid." - user: ".$uid);
1041                         return $r[0];
1042                 }
1043         }
1044
1045         /**
1046          * @brief returns contact details
1047          *
1048          * @param array $contact The default contact if the person isn't found
1049          * @param array $person The record of the person
1050          * @param int $uid The user id
1051          *
1052          * @return array
1053          *      'cid' => contact id
1054          *      'network' => network type
1055          */
1056         private function author_contact_by_url($contact, $person, $uid) {
1057
1058                 $r = q("SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1059                         dbesc(normalise_link($person["url"])), intval($uid));
1060                 if ($r) {
1061                         $cid = $r[0]["id"];
1062                         $network = $r[0]["network"];
1063
1064                         // We are receiving content from a user that is about to be terminated
1065                         // This means the user is vital, so we remove a possible termination date.
1066                         unmark_for_death($contact);
1067                 } else {
1068                         $cid = $contact["id"];
1069                         $network = NETWORK_DIASPORA;
1070                 }
1071
1072                 return array("cid" => $cid, "network" => $network);
1073         }
1074
1075         /**
1076          * @brief Is the profile a hubzilla profile?
1077          *
1078          * @param string $url The profile link
1079          *
1080          * @return bool is it a hubzilla server?
1081          */
1082         public static function is_redmatrix($url) {
1083                 return(strstr($url, "/channel/"));
1084         }
1085
1086         /**
1087          * @brief Generate a post link with a given handle and message guid
1088          *
1089          * @param string $addr The user handle
1090          * @param string $guid message guid
1091          *
1092          * @return string the post link
1093          */
1094         private function plink($addr, $guid) {
1095                 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1096
1097                 // Fallback
1098                 if (!$r)
1099                         return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1100
1101                 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1102                 // So we try another way as well.
1103                 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1104                 if ($s)
1105                         $r[0]["network"] = $s[0]["network"];
1106
1107                 if ($r[0]["network"] == NETWORK_DFRN)
1108                         return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
1109
1110                 if (self::is_redmatrix($r[0]["url"]))
1111                         return $r[0]["url"]."/?f=&mid=".$guid;
1112
1113                 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1114         }
1115
1116         /**
1117          * @brief Processes an account deletion
1118          *
1119          * @param array $importer Array of the importer user
1120          * @param object $data The message object
1121          *
1122          * @return bool Success
1123          */
1124         private function receive_account_deletion($importer, $data) {
1125
1126                 /// @todo Account deletion should remove the contact from the global contacts as well
1127
1128                 $author = notags(unxmlify($data->author));
1129
1130                 $contact = self::contact_by_handle($importer["uid"], $author);
1131                 if (!$contact) {
1132                         logger("cannot find contact for author: ".$author);
1133                         return false;
1134                 }
1135
1136                 // We now remove the contact
1137                 contact_remove($contact["id"]);
1138                 return true;
1139         }
1140
1141         /**
1142          * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1143          *
1144          * @param string $author Author handle
1145          * @param string $guid Message guid
1146          *
1147          * @return string The constructed uri or the one from our database
1148          */
1149         private function get_uri_from_guid($author, $guid) {
1150
1151                 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1152                 if ($r)
1153                         return $r[0]["uri"];
1154                 else
1155                         return $author.":".$guid;
1156         }
1157
1158         /**
1159          * @brief Processes an incoming comment
1160          *
1161          * @param array $importer Array of the importer user
1162          * @param string $sender The sender of the message
1163          * @param object $data The message object
1164          * @param string $xml The original XML of the message
1165          *
1166          * @return int The message id of the generated comment or "false" if there was an error
1167          */
1168         private function receive_comment($importer, $sender, $data, $xml) {
1169                 $guid = notags(unxmlify($data->guid));
1170                 $parent_guid = notags(unxmlify($data->parent_guid));
1171                 $text = unxmlify($data->text);
1172                 $author = notags(unxmlify($data->author));
1173
1174                 if (isset($data->created_at)) {
1175                         $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1176                 } else {
1177                         $created_at = datetime_convert();
1178                 }
1179
1180                 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1181                 if (!$contact) {
1182                         return false;
1183                 }
1184
1185                 $message_id = self::message_exists($importer["uid"], $guid);
1186                 if ($message_id) {
1187                         return $message_id;
1188                 }
1189
1190                 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1191                 if (!$parent_item) {
1192                         return false;
1193                 }
1194
1195                 $person = self::person_by_handle($author);
1196                 if (!is_array($person)) {
1197                         logger("unable to find author details");
1198                         return false;
1199                 }
1200
1201                 // Fetch the contact id - if we know this contact
1202                 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1203
1204                 $datarray = array();
1205
1206                 $datarray["uid"] = $importer["uid"];
1207                 $datarray["contact-id"] = $author_contact["cid"];
1208                 $datarray["network"]  = $author_contact["network"];
1209
1210                 $datarray["author-name"] = $person["name"];
1211                 $datarray["author-link"] = $person["url"];
1212                 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1213
1214                 $datarray["owner-name"] = $contact["name"];
1215                 $datarray["owner-link"] = $contact["url"];
1216                 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1217
1218                 $datarray["guid"] = $guid;
1219                 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1220
1221                 $datarray["type"] = "remote-comment";
1222                 $datarray["verb"] = ACTIVITY_POST;
1223                 $datarray["gravity"] = GRAVITY_COMMENT;
1224                 $datarray["parent-uri"] = $parent_item["uri"];
1225
1226                 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1227                 $datarray["object"] = $xml;
1228
1229                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1230
1231                 $body = diaspora2bb($text);
1232
1233                 $datarray["body"] = self::replace_people_guid($body, $person["url"]);
1234
1235                 self::fetch_guid($datarray);
1236
1237                 $message_id = item_store($datarray);
1238
1239                 if ($message_id) {
1240                         logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1241                 }
1242
1243                 // If we are the origin of the parent we store the original data and notify our followers
1244                 if($message_id AND $parent_item["origin"]) {
1245
1246                         // Formerly we stored the signed text, the signature and the author in different fields.
1247                         // We now store the raw data so that we are more flexible.
1248                         q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1249                                 intval($message_id),
1250                                 dbesc(json_encode($data))
1251                         );
1252
1253                         // notify others
1254                         proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1255                 }
1256
1257                 return $message_id;
1258         }
1259
1260         /**
1261          * @brief processes and stores private messages
1262          *
1263          * @param array $importer Array of the importer user
1264          * @param array $contact The contact of the message
1265          * @param object $data The message object
1266          * @param array $msg Array of the processed message, author handle and key
1267          * @param object $mesg The private message
1268          * @param array $conversation The conversation record to which this message belongs
1269          *
1270          * @return bool "true" if it was successful
1271          */
1272         private function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1273                 $guid = notags(unxmlify($data->guid));
1274                 $subject = notags(unxmlify($data->subject));
1275                 $author = notags(unxmlify($data->author));
1276
1277                 $msg_guid = notags(unxmlify($mesg->guid));
1278                 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1279                 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1280                 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1281                 $msg_text = unxmlify($mesg->text);
1282                 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1283
1284                 // "diaspora_handle" is the element name from the old version
1285                 // "author" is the element name from the new version
1286                 if ($mesg->author) {
1287                         $msg_author = notags(unxmlify($mesg->author));
1288                 } elseif ($mesg->diaspora_handle) {
1289                         $msg_author = notags(unxmlify($mesg->diaspora_handle));
1290                 } else {
1291                         return false;
1292                 }
1293
1294                 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1295
1296                 if ($msg_conversation_guid != $guid) {
1297                         logger("message conversation guid does not belong to the current conversation.");
1298                         return false;
1299                 }
1300
1301                 $body = diaspora2bb($msg_text);
1302                 $message_uri = $msg_author.":".$msg_guid;
1303
1304                 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1305
1306                 $author_signature = base64_decode($msg_author_signature);
1307
1308                 if (strcasecmp($msg_author,$msg["author"]) == 0) {
1309                         $person = $contact;
1310                         $key = $msg["key"];
1311                 } else {
1312                         $person = self::person_by_handle($msg_author);
1313
1314                         if (is_array($person) && x($person, "pubkey")) {
1315                                 $key = $person["pubkey"];
1316                         } else {
1317                                 logger("unable to find author details");
1318                                         return false;
1319                         }
1320                 }
1321
1322                 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
1323                         logger("verification failed.");
1324                         return false;
1325                 }
1326
1327                 if ($msg_parent_author_signature) {
1328                         $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1329
1330                         $parent_author_signature = base64_decode($msg_parent_author_signature);
1331
1332                         $key = $msg["key"];
1333
1334                         if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
1335                                 logger("owner verification failed.");
1336                                 return false;
1337                         }
1338                 }
1339
1340                 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
1341                         dbesc($message_uri)
1342                 );
1343                 if (dbm::is_result($r)) {
1344                         logger("duplicate message already delivered.", LOGGER_DEBUG);
1345                         return false;
1346                 }
1347
1348                 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1349                         VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1350                         intval($importer["uid"]),
1351                         dbesc($msg_guid),
1352                         intval($conversation["id"]),
1353                         dbesc($person["name"]),
1354                         dbesc($person["photo"]),
1355                         dbesc($person["url"]),
1356                         intval($contact["id"]),
1357                         dbesc($subject),
1358                         dbesc($body),
1359                         0,
1360                         0,
1361                         dbesc($message_uri),
1362                         dbesc($author.":".$guid),
1363                         dbesc($msg_created_at)
1364                 );
1365
1366                 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1367                         dbesc(datetime_convert()),
1368                         intval($conversation["id"])
1369                 );
1370
1371                 notification(array(
1372                         "type" => NOTIFY_MAIL,
1373                         "notify_flags" => $importer["notify-flags"],
1374                         "language" => $importer["language"],
1375                         "to_name" => $importer["username"],
1376                         "to_email" => $importer["email"],
1377                         "uid" =>$importer["uid"],
1378                         "item" => array("subject" => $subject, "body" => $body),
1379                         "source_name" => $person["name"],
1380                         "source_link" => $person["url"],
1381                         "source_photo" => $person["thumb"],
1382                         "verb" => ACTIVITY_POST,
1383                         "otype" => "mail"
1384                 ));
1385                 return true;
1386         }
1387
1388         /**
1389          * @brief Processes new private messages (answers to private messages are processed elsewhere)
1390          *
1391          * @param array $importer Array of the importer user
1392          * @param array $msg Array of the processed message, author handle and key
1393          * @param object $data The message object
1394          *
1395          * @return bool Success
1396          */
1397         private function receive_conversation($importer, $msg, $data) {
1398                 $guid = notags(unxmlify($data->guid));
1399                 $subject = notags(unxmlify($data->subject));
1400                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1401                 $author = notags(unxmlify($data->author));
1402                 $participants = notags(unxmlify($data->participants));
1403
1404                 $messages = $data->message;
1405
1406                 if (!count($messages)) {
1407                         logger("empty conversation");
1408                         return false;
1409                 }
1410
1411                 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1412                 if (!$contact)
1413                         return false;
1414
1415                 $conversation = null;
1416
1417                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1418                         intval($importer["uid"]),
1419                         dbesc($guid)
1420                 );
1421                 if($c)
1422                         $conversation = $c[0];
1423                 else {
1424                         $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1425                                 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1426                                 intval($importer["uid"]),
1427                                 dbesc($guid),
1428                                 dbesc($author),
1429                                 dbesc($created_at),
1430                                 dbesc(datetime_convert()),
1431                                 dbesc($subject),
1432                                 dbesc($participants)
1433                         );
1434                         if($r)
1435                                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1436                                         intval($importer["uid"]),
1437                                         dbesc($guid)
1438                                 );
1439
1440                         if($c)
1441                                 $conversation = $c[0];
1442                 }
1443                 if (!$conversation) {
1444                         logger("unable to create conversation.");
1445                         return;
1446                 }
1447
1448                 foreach($messages as $mesg)
1449                         self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1450
1451                 return true;
1452         }
1453
1454         /**
1455          * @brief Creates the body for a "like" message
1456          *
1457          * @param array $contact The contact that send us the "like"
1458          * @param array $parent_item The item array of the parent item
1459          * @param string $guid message guid
1460          *
1461          * @return string the body
1462          */
1463         private function construct_like_body($contact, $parent_item, $guid) {
1464                 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1465
1466                 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1467                 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1468                 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1469
1470                 return sprintf($bodyverb, $ulink, $alink, $plink);
1471         }
1472
1473         /**
1474          * @brief Creates a XML object for a "like"
1475          *
1476          * @param array $importer Array of the importer user
1477          * @param array $parent_item The item array of the parent item
1478          *
1479          * @return string The XML
1480          */
1481         private function construct_like_object($importer, $parent_item) {
1482                 $objtype = ACTIVITY_OBJ_NOTE;
1483                 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1484                 $parent_body = $parent_item["body"];
1485
1486                 $xmldata = array("object" => array("type" => $objtype,
1487                                                 "local" => "1",
1488                                                 "id" => $parent_item["uri"],
1489                                                 "link" => $link,
1490                                                 "title" => "",
1491                                                 "content" => $parent_body));
1492
1493                 return xml::from_array($xmldata, $xml, true);
1494         }
1495
1496         /**
1497          * @brief Processes "like" messages
1498          *
1499          * @param array $importer Array of the importer user
1500          * @param string $sender The sender of the message
1501          * @param object $data The message object
1502          *
1503          * @return int The message id of the generated like or "false" if there was an error
1504          */
1505         private function receive_like($importer, $sender, $data) {
1506                 $positive = notags(unxmlify($data->positive));
1507                 $guid = notags(unxmlify($data->guid));
1508                 $parent_type = notags(unxmlify($data->parent_type));
1509                 $parent_guid = notags(unxmlify($data->parent_guid));
1510                 $author = notags(unxmlify($data->author));
1511
1512                 // likes on comments aren't supported by Diaspora - only on posts
1513                 // But maybe this will be supported in the future, so we will accept it.
1514                 if (!in_array($parent_type, array("Post", "Comment")))
1515                         return false;
1516
1517                 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1518                 if (!$contact)
1519                         return false;
1520
1521                 $message_id = self::message_exists($importer["uid"], $guid);
1522                 if ($message_id)
1523                         return $message_id;
1524
1525                 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1526                 if (!$parent_item)
1527                         return false;
1528
1529                 $person = self::person_by_handle($author);
1530                 if (!is_array($person)) {
1531                         logger("unable to find author details");
1532                         return false;
1533                 }
1534
1535                 // Fetch the contact id - if we know this contact
1536                 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1537
1538                 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1539                 // We would accept this anyhow.
1540                 if ($positive == "true")
1541                         $verb = ACTIVITY_LIKE;
1542                 else
1543                         $verb = ACTIVITY_DISLIKE;
1544
1545                 $datarray = array();
1546
1547                 $datarray["uid"] = $importer["uid"];
1548                 $datarray["contact-id"] = $author_contact["cid"];
1549                 $datarray["network"]  = $author_contact["network"];
1550
1551                 $datarray["author-name"] = $person["name"];
1552                 $datarray["author-link"] = $person["url"];
1553                 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1554
1555                 $datarray["owner-name"] = $contact["name"];
1556                 $datarray["owner-link"] = $contact["url"];
1557                 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1558
1559                 $datarray["guid"] = $guid;
1560                 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1561
1562                 $datarray["type"] = "activity";
1563                 $datarray["verb"] = $verb;
1564                 $datarray["gravity"] = GRAVITY_LIKE;
1565                 $datarray["parent-uri"] = $parent_item["uri"];
1566
1567                 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1568                 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1569
1570                 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1571
1572                 $message_id = item_store($datarray);
1573
1574                 if ($message_id)
1575                         logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1576
1577                 // If we are the origin of the parent we store the original data and notify our followers
1578                 if($message_id AND $parent_item["origin"]) {
1579
1580                         // Formerly we stored the signed text, the signature and the author in different fields.
1581                         // We now store the raw data so that we are more flexible.
1582                         q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1583                                 intval($message_id),
1584                                 dbesc(json_encode($data))
1585                         );
1586
1587                         // notify others
1588                         proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1589                 }
1590
1591                 return $message_id;
1592         }
1593
1594         /**
1595          * @brief Processes private messages
1596          *
1597          * @param array $importer Array of the importer user
1598          * @param object $data The message object
1599          *
1600          * @return bool Success?
1601          */
1602         private function receive_message($importer, $data) {
1603                 $guid = notags(unxmlify($data->guid));
1604                 $parent_guid = notags(unxmlify($data->parent_guid));
1605                 $text = unxmlify($data->text);
1606                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1607                 $author = notags(unxmlify($data->author));
1608                 $conversation_guid = notags(unxmlify($data->conversation_guid));
1609
1610                 $contact = self::allowed_contact_by_handle($importer, $author, true);
1611                 if (!$contact) {
1612                         return false;
1613                 }
1614
1615                 $conversation = null;
1616
1617                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1618                         intval($importer["uid"]),
1619                         dbesc($conversation_guid)
1620                 );
1621                 if ($c) {
1622                         $conversation = $c[0];
1623                 } else {
1624                         logger("conversation not available.");
1625                         return false;
1626                 }
1627
1628                 $message_uri = $author.":".$guid;
1629
1630                 $person = self::person_by_handle($author);
1631                 if (!$person) {
1632                         logger("unable to find author details");
1633                         return false;
1634                 }
1635
1636                 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1637                         dbesc($message_uri),
1638                         intval($importer["uid"])
1639                 );
1640                 if (dbm::is_result($r)) {
1641                         logger("duplicate message already delivered.", LOGGER_DEBUG);
1642                         return false;
1643                 }
1644
1645                 $body = diaspora2bb($text);
1646
1647                 $body = self::replace_people_guid($body, $person["url"]);
1648
1649                 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1650                                 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1651                         intval($importer["uid"]),
1652                         dbesc($guid),
1653                         intval($conversation["id"]),
1654                         dbesc($person["name"]),
1655                         dbesc($person["photo"]),
1656                         dbesc($person["url"]),
1657                         intval($contact["id"]),
1658                         dbesc($conversation["subject"]),
1659                         dbesc($body),
1660                         0,
1661                         1,
1662                         dbesc($message_uri),
1663                         dbesc($author.":".$parent_guid),
1664                         dbesc($created_at)
1665                 );
1666
1667                 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1668                         dbesc(datetime_convert()),
1669                         intval($conversation["id"])
1670                 );
1671
1672                 return true;
1673         }
1674
1675         /**
1676          * @brief Processes participations - unsupported by now
1677          *
1678          * @param array $importer Array of the importer user
1679          * @param object $data The message object
1680          *
1681          * @return bool always true
1682          */
1683         private function receive_participation($importer, $data) {
1684                 // I'm not sure if we can fully support this message type
1685                 return true;
1686         }
1687
1688         /**
1689          * @brief Processes photos - unneeded
1690          *
1691          * @param array $importer Array of the importer user
1692          * @param object $data The message object
1693          *
1694          * @return bool always true
1695          */
1696         private function receive_photo($importer, $data) {
1697                 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1698                 return true;
1699         }
1700
1701         /**
1702          * @brief Processes poll participations - unssupported
1703          *
1704          * @param array $importer Array of the importer user
1705          * @param object $data The message object
1706          *
1707          * @return bool always true
1708          */
1709         private function receive_poll_participation($importer, $data) {
1710                 // We don't support polls by now
1711                 return true;
1712         }
1713
1714         /**
1715          * @brief Processes incoming profile updates
1716          *
1717          * @param array $importer Array of the importer user
1718          * @param object $data The message object
1719          *
1720          * @return bool Success
1721          */
1722         private function receive_profile($importer, $data) {
1723                 $author = strtolower(notags(unxmlify($data->author)));
1724
1725                 $contact = self::contact_by_handle($importer["uid"], $author);
1726                 if (!$contact)
1727                         return false;
1728
1729                 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1730                 $image_url = unxmlify($data->image_url);
1731                 $birthday = unxmlify($data->birthday);
1732                 $location = diaspora2bb(unxmlify($data->location));
1733                 $about = diaspora2bb(unxmlify($data->bio));
1734                 $gender = unxmlify($data->gender);
1735                 $searchable = (unxmlify($data->searchable) == "true");
1736                 $nsfw = (unxmlify($data->nsfw) == "true");
1737                 $tags = unxmlify($data->tag_string);
1738
1739                 $tags = explode("#", $tags);
1740
1741                 $keywords = array();
1742                 foreach ($tags as $tag) {
1743                         $tag = trim(strtolower($tag));
1744                         if ($tag != "")
1745                                 $keywords[] = $tag;
1746                 }
1747
1748                 $keywords = implode(", ", $keywords);
1749
1750                 $handle_parts = explode("@", $author);
1751                 $nick = $handle_parts[0];
1752
1753                 if($name === "")
1754                         $name = $handle_parts[0];
1755
1756                 if( preg_match("|^https?://|", $image_url) === 0)
1757                         $image_url = "http://".$handle_parts[1].$image_url;
1758
1759                 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1760
1761                 // Generic birthday. We don't know the timezone. The year is irrelevant.
1762
1763                 $birthday = str_replace("1000", "1901", $birthday);
1764
1765                 if ($birthday != "")
1766                         $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1767
1768                 // this is to prevent multiple birthday notifications in a single year
1769                 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1770
1771                 if(substr($birthday,5) === substr($contact["bd"],5))
1772                         $birthday = $contact["bd"];
1773
1774                 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1775                                 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1776                         dbesc($name),
1777                         dbesc($nick),
1778                         dbesc($author),
1779                         dbesc(datetime_convert()),
1780                         dbesc($birthday),
1781                         dbesc($location),
1782                         dbesc($about),
1783                         dbesc($keywords),
1784                         dbesc($gender),
1785                         intval($contact["id"]),
1786                         intval($importer["uid"])
1787                 );
1788
1789                 if ($searchable) {
1790                         poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1791                                 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1792                 }
1793
1794                 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1795                                         "photo" => $image_url, "name" => $name, "location" => $location,
1796                                         "about" => $about, "birthday" => $birthday, "gender" => $gender,
1797                                         "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1798                                         "hide" => !$searchable, "nsfw" => $nsfw);
1799
1800                 update_gcontact($gcontact);
1801
1802                 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1803
1804                 return true;
1805         }
1806
1807         /**
1808          * @brief Processes incoming friend requests
1809          *
1810          * @param array $importer Array of the importer user
1811          * @param array $contact The contact that send the request
1812          */
1813         private function receive_request_make_friend($importer, $contact) {
1814
1815                 $a = get_app();
1816
1817                 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1818                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1819                                 intval(CONTACT_IS_FRIEND),
1820                                 intval($contact["id"]),
1821                                 intval($importer["uid"])
1822                         );
1823                 }
1824                 // send notification
1825
1826                 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1827                         intval($importer["uid"])
1828                 );
1829
1830                 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1831
1832                         $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1833                                 intval($importer["uid"])
1834                         );
1835
1836                         // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1837
1838                         if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1839
1840                                 $arr = array();
1841                                 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1842                                 $arr["uid"] = $importer["uid"];
1843                                 $arr["contact-id"] = $self[0]["id"];
1844                                 $arr["wall"] = 1;
1845                                 $arr["type"] = 'wall';
1846                                 $arr["gravity"] = 0;
1847                                 $arr["origin"] = 1;
1848                                 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1849                                 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1850                                 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1851                                 $arr["verb"] = ACTIVITY_FRIEND;
1852                                 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1853
1854                                 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1855                                 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1856                                 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1857                                 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1858
1859                                 $arr["object"] = self::construct_new_friend_object($contact);
1860
1861                                 $arr["last-child"] = 1;
1862
1863                                 $arr["allow_cid"] = $user[0]["allow_cid"];
1864                                 $arr["allow_gid"] = $user[0]["allow_gid"];
1865                                 $arr["deny_cid"]  = $user[0]["deny_cid"];
1866                                 $arr["deny_gid"]  = $user[0]["deny_gid"];
1867
1868                                 $i = item_store($arr);
1869                                 if($i)
1870                                         proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
1871                         }
1872                 }
1873         }
1874
1875         /**
1876          * @brief Creates a XML object for a "new friend" message
1877          *
1878          * @param array $contact Array of the contact
1879          *
1880          * @return string The XML
1881          */
1882         private function construct_new_friend_object($contact) {
1883                 $objtype = ACTIVITY_OBJ_PERSON;
1884                 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
1885                         '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
1886
1887                 $xmldata = array("object" => array("type" => $objtype,
1888                                                 "title" => $contact["name"],
1889                                                 "id" => $contact["url"]."/".$contact["name"],
1890                                                 "link" => $link));
1891
1892                 return xml::from_array($xmldata, $xml, true);
1893         }
1894
1895         /**
1896          * @brief Processes incoming sharing notification
1897          *
1898          * @param array $importer Array of the importer user
1899          * @param object $data The message object
1900          *
1901          * @return bool Success
1902          */
1903         private function receive_contact_request($importer, $data) {
1904                 $author = unxmlify($data->author);
1905                 $recipient = unxmlify($data->recipient);
1906
1907                 if (!$author || !$recipient)
1908                         return false;
1909
1910                 // the current protocol version doesn't know these fields
1911                 // That means that we will assume their existance
1912                 if (isset($data->following))
1913                         $following = (unxmlify($data->following) == "true");
1914                 else
1915                         $following = true;
1916
1917                 if (isset($data->sharing))
1918                         $sharing = (unxmlify($data->sharing) == "true");
1919                 else
1920                         $sharing = true;
1921
1922                 $contact = self::contact_by_handle($importer["uid"],$author);
1923
1924                 // perhaps we were already sharing with this person. Now they're sharing with us.
1925                 // That makes us friends.
1926                 if ($contact) {
1927                         if ($following AND $sharing) {
1928                                 logger("Author ".$author." (Contact ".$contact["id"].") wants to have a bidirectional conection.", LOGGER_DEBUG);
1929                                 self::receive_request_make_friend($importer, $contact);
1930
1931                                 // refetch the contact array
1932                                 $contact = self::contact_by_handle($importer["uid"],$author);
1933
1934                                 // If we are now friends, we are sending a share message.
1935                                 // Normally we needn't to do so, but the first message could have been vanished.
1936                                 if (in_array($contact["rel"], array(CONTACT_IS_FRIEND, CONTACT_IS_FOLLOWER))) {
1937                                         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1938                                         if($u) {
1939                                                 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
1940                                                 $ret = self::send_share($u[0], $contact);
1941                                         }
1942                                 }
1943                                 return true;
1944                         } else { /// @todo Handle all possible variations of adding and retracting of permissions
1945                                 logger("Author ".$author." (Contact ".$contact["id"].") wants to change the relationship: Following: ".$following." - sharing: ".$sharing. "(By now unsupported)", LOGGER_DEBUG);
1946                                 return false;
1947                         }
1948                 }
1949
1950                 if (!$following AND $sharing AND in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
1951                         logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
1952                         return false;
1953                 } elseif (!$following AND !$sharing) {
1954                         logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
1955                         return false;
1956                 } elseif (!$following AND $sharing) {
1957                         logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
1958                 } elseif ($following AND $sharing) {
1959                         logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
1960                 } elseif ($following AND !$sharing) {
1961                         logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
1962                 }
1963
1964                 $ret = self::person_by_handle($author);
1965
1966                 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
1967                         logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
1968                         return false;
1969                 }
1970
1971                 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
1972
1973                 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1974                         VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
1975                         intval($importer["uid"]),
1976                         dbesc($ret["network"]),
1977                         dbesc($ret["addr"]),
1978                         datetime_convert(),
1979                         dbesc($ret["url"]),
1980                         dbesc(normalise_link($ret["url"])),
1981                         dbesc($batch),
1982                         dbesc($ret["name"]),
1983                         dbesc($ret["nick"]),
1984                         dbesc($ret["photo"]),
1985                         dbesc($ret["pubkey"]),
1986                         dbesc($ret["notify"]),
1987                         dbesc($ret["poll"]),
1988                         1,
1989                         2
1990                 );
1991
1992                 // find the contact record we just created
1993
1994                 $contact_record = self::contact_by_handle($importer["uid"],$author);
1995
1996                 if (!$contact_record) {
1997                         logger("unable to locate newly created contact record.");
1998                         return;
1999                 }
2000
2001                 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2002
2003                 $def_gid = get_default_group($importer['uid'], $ret["network"]);
2004
2005                 if(intval($def_gid))
2006                         group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
2007
2008                 update_contact_avatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2009
2010                 if($importer["page-flags"] == PAGE_NORMAL) {
2011
2012                         logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2013
2014                         $hash = random_string().(string)time();   // Generate a confirm_key
2015
2016                         $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2017                                 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2018                                 intval($importer["uid"]),
2019                                 intval($contact_record["id"]),
2020                                 0,
2021                                 0,
2022                                 dbesc(t("Sharing notification from Diaspora network")),
2023                                 dbesc($hash),
2024                                 dbesc(datetime_convert())
2025                         );
2026                 } else {
2027
2028                         // automatic friend approval
2029
2030                         logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2031
2032                         update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
2033
2034                         // technically they are sharing with us (CONTACT_IS_SHARING),
2035                         // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2036                         // we are going to change the relationship and make them a follower.
2037
2038                         if (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing AND $following)
2039                                 $new_relation = CONTACT_IS_FRIEND;
2040                         elseif (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing)
2041                                 $new_relation = CONTACT_IS_SHARING;
2042                         else
2043                                 $new_relation = CONTACT_IS_FOLLOWER;
2044
2045                         $r = q("UPDATE `contact` SET `rel` = %d,
2046                                 `name-date` = '%s',
2047                                 `uri-date` = '%s',
2048                                 `blocked` = 0,
2049                                 `pending` = 0,
2050                                 `writable` = 1
2051                                 WHERE `id` = %d
2052                                 ",
2053                                 intval($new_relation),
2054                                 dbesc(datetime_convert()),
2055                                 dbesc(datetime_convert()),
2056                                 intval($contact_record["id"])
2057                         );
2058
2059                         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2060                         if($u) {
2061                                 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2062                                 $ret = self::send_share($u[0], $contact_record);
2063
2064                                 // Send the profile data, maybe it weren't transmitted before
2065                                 self::send_profile($importer["uid"], array($contact_record));
2066                         }
2067                 }
2068
2069                 return true;
2070         }
2071
2072         /**
2073          * @brief Fetches a message with a given guid
2074          *
2075          * @param string $guid message guid
2076          * @param string $orig_author handle of the original post
2077          * @param string $author handle of the sharer
2078          *
2079          * @return array The fetched item
2080          */
2081         private function original_item($guid, $orig_author, $author) {
2082
2083                 // Do we already have this item?
2084                 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2085                                 `author-name`, `author-link`, `author-avatar`
2086                                 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2087                         dbesc($guid));
2088
2089                 if (dbm::is_result($r)) {
2090                         logger("reshared message ".$guid." already exists on system.");
2091
2092                         // Maybe it is already a reshared item?
2093                         // Then refetch the content, if it is a reshare from a reshare.
2094                         // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2095                         if (self::is_reshare($r[0]["body"], true)) {
2096                                 $r = array();
2097                         } elseif (self::is_reshare($r[0]["body"], false)) {
2098                                 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2099
2100                                 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2101
2102                                 // Add OEmbed and other information to the body
2103                                 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2104
2105                                 return $r[0];
2106                         } else {
2107                                 return $r[0];
2108                         }
2109                 }
2110
2111                 if (!dbm::is_result($r)) {
2112                         $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2113                         logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2114                         $item_id = self::store_by_guid($guid, $server);
2115
2116                         if (!$item_id) {
2117                                 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2118                                 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2119                                 $item_id = self::store_by_guid($guid, $server);
2120                         }
2121
2122                         if ($item_id) {
2123                                 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2124                                                 `author-name`, `author-link`, `author-avatar`
2125                                         FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2126                                         intval($item_id));
2127
2128                                 if (dbm::is_result($r)) {
2129                                         // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2130                                         if (self::is_reshare($r[0]["body"], false)) {
2131                                                 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2132                                                 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2133                                         }
2134
2135                                         return $r[0];
2136                                 }
2137
2138                         }
2139                 }
2140                 return false;
2141         }
2142
2143         /**
2144          * @brief Processes a reshare message
2145          *
2146          * @param array $importer Array of the importer user
2147          * @param object $data The message object
2148          * @param string $xml The original XML of the message
2149          *
2150          * @return int the message id
2151          */
2152         private function receive_reshare($importer, $data, $xml) {
2153                 $root_author = notags(unxmlify($data->root_author));
2154                 $root_guid = notags(unxmlify($data->root_guid));
2155                 $guid = notags(unxmlify($data->guid));
2156                 $author = notags(unxmlify($data->author));
2157                 $public = notags(unxmlify($data->public));
2158                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2159
2160                 $contact = self::allowed_contact_by_handle($importer, $author, false);
2161                 if (!$contact)
2162                         return false;
2163
2164                 $message_id = self::message_exists($importer["uid"], $guid);
2165                 if ($message_id)
2166                         return $message_id;
2167
2168                 $original_item = self::original_item($root_guid, $root_author, $author);
2169                 if (!$original_item)
2170                         return false;
2171
2172                 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
2173
2174                 $datarray = array();
2175
2176                 $datarray["uid"] = $importer["uid"];
2177                 $datarray["contact-id"] = $contact["id"];
2178                 $datarray["network"]  = NETWORK_DIASPORA;
2179
2180                 $datarray["author-name"] = $contact["name"];
2181                 $datarray["author-link"] = $contact["url"];
2182                 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2183
2184                 $datarray["owner-name"] = $datarray["author-name"];
2185                 $datarray["owner-link"] = $datarray["author-link"];
2186                 $datarray["owner-avatar"] = $datarray["author-avatar"];
2187
2188                 $datarray["guid"] = $guid;
2189                 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2190
2191                 $datarray["verb"] = ACTIVITY_POST;
2192                 $datarray["gravity"] = GRAVITY_PARENT;
2193
2194                 $datarray["object"] = $xml;
2195
2196                 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
2197                                         $original_item["guid"], $original_item["created"], $orig_url);
2198                 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2199
2200                 $datarray["tag"] = $original_item["tag"];
2201                 $datarray["app"]  = $original_item["app"];
2202
2203                 $datarray["plink"] = self::plink($author, $guid);
2204                 $datarray["private"] = (($public == "false") ? 1 : 0);
2205                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2206
2207                 $datarray["object-type"] = $original_item["object-type"];
2208
2209                 self::fetch_guid($datarray);
2210                 $message_id = item_store($datarray);
2211
2212                 if ($message_id)
2213                         logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2214
2215                 return $message_id;
2216         }
2217
2218         /**
2219          * @brief Processes retractions
2220          *
2221          * @param array $importer Array of the importer user
2222          * @param array $contact The contact of the item owner
2223          * @param object $data The message object
2224          *
2225          * @return bool success
2226          */
2227         private function item_retraction($importer, $contact, $data) {
2228                 $target_type = notags(unxmlify($data->target_type));
2229                 $target_guid = notags(unxmlify($data->target_guid));
2230                 $author = notags(unxmlify($data->author));
2231
2232                 $person = self::person_by_handle($author);
2233                 if (!is_array($person)) {
2234                         logger("unable to find author detail for ".$author);
2235                         return false;
2236                 }
2237
2238                 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2239                         dbesc($target_guid),
2240                         intval($importer["uid"])
2241                 );
2242                 if (!$r)
2243                         return false;
2244
2245                 // Check if the sender is the thread owner
2246                 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2247                         intval($r[0]["parent"]));
2248
2249                 // Only delete it if the parent author really fits
2250                 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
2251                         logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2252                         return false;
2253                 }
2254
2255                 // 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
2256                 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
2257                         dbesc(datetime_convert()),
2258                         dbesc(datetime_convert()),
2259                         intval($r[0]["id"])
2260                 );
2261                 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2262
2263                 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2264
2265                 // Now check if the retraction needs to be relayed by us
2266                 if($p[0]["origin"]) {
2267                         // notify others
2268                         proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $r[0]["id"]);
2269                 }
2270
2271                 return true;
2272         }
2273
2274         /**
2275          * @brief Receives retraction messages
2276          *
2277          * @param array $importer Array of the importer user
2278          * @param string $sender The sender of the message
2279          * @param object $data The message object
2280          *
2281          * @return bool Success
2282          */
2283         private function receive_retraction($importer, $sender, $data) {
2284                 $target_type = notags(unxmlify($data->target_type));
2285
2286                 $contact = self::contact_by_handle($importer["uid"], $sender);
2287                 if (!$contact) {
2288                         logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2289                         return false;
2290                 }
2291
2292                 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2293
2294                 switch ($target_type) {
2295                         case "Comment":
2296                         case "Like":
2297                         case "Post": // "Post" will be supported in a future version
2298                         case "Reshare":
2299                         case "StatusMessage":
2300                                 return self::item_retraction($importer, $contact, $data);;
2301
2302                         case "Contact":
2303                         case "Person":
2304                                 /// @todo What should we do with an "unshare"?
2305                                 // Removing the contact isn't correct since we still can read the public items
2306                                 contact_remove($contact["id"]);
2307                                 return true;
2308
2309                         default:
2310                                 logger("Unknown target type ".$target_type);
2311                                 return false;
2312                 }
2313                 return true;
2314         }
2315
2316         /**
2317          * @brief Receives status messages
2318          *
2319          * @param array $importer Array of the importer user
2320          * @param object $data The message object
2321          * @param string $xml The original XML of the message
2322          *
2323          * @return int The message id of the newly created item
2324          */
2325         private function receive_status_message($importer, $data, $xml) {
2326                 $raw_message = unxmlify($data->raw_message);
2327                 $guid = notags(unxmlify($data->guid));
2328                 $author = notags(unxmlify($data->author));
2329                 $public = notags(unxmlify($data->public));
2330                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2331                 $provider_display_name = notags(unxmlify($data->provider_display_name));
2332
2333                 /// @todo enable support for polls
2334                 //if ($data->poll) {
2335                 //      foreach ($data->poll AS $poll)
2336                 //              print_r($poll);
2337                 //      die("poll!\n");
2338                 //}
2339                 $contact = self::allowed_contact_by_handle($importer, $author, false);
2340                 if (!$contact) {
2341                         return false;
2342                 }
2343
2344                 $message_id = self::message_exists($importer["uid"], $guid);
2345                 if ($message_id) {
2346                         return $message_id;
2347                 }
2348
2349                 $address = array();
2350                 if ($data->location) {
2351                         foreach ($data->location->children() AS $fieldname => $data) {
2352                                 $address[$fieldname] = notags(unxmlify($data));
2353                         }
2354                 }
2355
2356                 $body = diaspora2bb($raw_message);
2357
2358                 $datarray = array();
2359
2360                 // Attach embedded pictures to the body
2361                 if ($data->photo) {
2362                         foreach ($data->photo AS $photo) {
2363                                 $body = "[img]".unxmlify($photo->remote_photo_path).
2364                                         unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2365                         }
2366
2367                         $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
2368                 } else {
2369                         $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2370
2371                         // Add OEmbed and other information to the body
2372                         if (!self::is_redmatrix($contact["url"])) {
2373                                 $body = add_page_info_to_body($body, false, true);
2374                         }
2375                 }
2376
2377                 $datarray["uid"] = $importer["uid"];
2378                 $datarray["contact-id"] = $contact["id"];
2379                 $datarray["network"] = NETWORK_DIASPORA;
2380
2381                 $datarray["author-name"] = $contact["name"];
2382                 $datarray["author-link"] = $contact["url"];
2383                 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2384
2385                 $datarray["owner-name"] = $datarray["author-name"];
2386                 $datarray["owner-link"] = $datarray["author-link"];
2387                 $datarray["owner-avatar"] = $datarray["author-avatar"];
2388
2389                 $datarray["guid"] = $guid;
2390                 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2391
2392                 $datarray["verb"] = ACTIVITY_POST;
2393                 $datarray["gravity"] = GRAVITY_PARENT;
2394
2395                 $datarray["object"] = $xml;
2396
2397                 $datarray["body"] = self::replace_people_guid($body, $contact["url"]);
2398
2399                 if ($provider_display_name != "") {
2400                         $datarray["app"] = $provider_display_name;
2401                 }
2402
2403                 $datarray["plink"] = self::plink($author, $guid);
2404                 $datarray["private"] = (($public == "false") ? 1 : 0);
2405                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2406
2407                 if (isset($address["address"])) {
2408                         $datarray["location"] = $address["address"];
2409                 }
2410
2411                 if (isset($address["lat"]) AND isset($address["lng"])) {
2412                         $datarray["coord"] = $address["lat"]." ".$address["lng"];
2413                 }
2414
2415                 self::fetch_guid($datarray);
2416                 $message_id = item_store($datarray);
2417
2418                 if ($message_id) {
2419                         logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2420                 }
2421
2422                 return $message_id;
2423         }
2424
2425         /* ************************************************************************************** *
2426          * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2427          * ************************************************************************************** */
2428
2429         /**
2430          * @brief returnes the handle of a contact
2431          *
2432          * @param array $me contact array
2433          *
2434          * @return string the handle in the format user@domain.tld
2435          */
2436         private function my_handle($contact) {
2437                 if ($contact["addr"] != "")
2438                         return $contact["addr"];
2439
2440                 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2441                 // So - just in case - we build the the address here.
2442                 if ($contact["nickname"] != "")
2443                         $nick = $contact["nickname"];
2444                 else
2445                         $nick = $contact["nick"];
2446
2447                 return $nick."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
2448         }
2449
2450         /**
2451          * @brief Creates the envelope for the "fetch" endpoint
2452          *
2453          * @param string $msg The message that is to be transmitted
2454          * @param array $user The record of the sender
2455          *
2456          * @return string The envelope
2457          */
2458
2459         public static function build_magic_envelope($msg, $user) {
2460
2461                 $b64url_data = base64url_encode($msg);
2462                 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2463
2464                 $key_id = base64url_encode(self::my_handle($user));
2465                 $type = "application/xml";
2466                 $encoding = "base64url";
2467                 $alg = "RSA-SHA256";
2468                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2469                 $signature = rsa_sign($signable_data, $user["prvkey"]);
2470                 $sig = base64url_encode($signature);
2471
2472                 $xmldata = array("me:env" => array("me:data" => $data,
2473                                                         "@attributes" => array("type" => $type),
2474                                                         "me:encoding" => $encoding,
2475                                                         "me:alg" => $alg,
2476                                                         "me:sig" => $sig,
2477                                                         "@attributes2" => array("key_id" => $key_id)));
2478
2479                 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
2480
2481                 return xml::from_array($xmldata, $xml, false, $namespaces);
2482         }
2483
2484         /**
2485          * @brief Creates the envelope for a public message
2486          *
2487          * @param string $msg The message that is to be transmitted
2488          * @param array $user The record of the sender
2489          * @param array $contact Target of the communication
2490          * @param string $prvkey The private key of the sender
2491          * @param string $pubkey The public key of the receiver
2492          *
2493          * @return string The envelope
2494          */
2495         private function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
2496
2497                 logger("Message: ".$msg, LOGGER_DATA);
2498
2499                 $handle = self::my_handle($user);
2500
2501                 $b64url_data = base64url_encode($msg);
2502
2503                 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2504
2505                 $type = "application/xml";
2506                 $encoding = "base64url";
2507                 $alg = "RSA-SHA256";
2508
2509                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2510
2511                 $signature = rsa_sign($signable_data,$prvkey);
2512                 $sig = base64url_encode($signature);
2513
2514                 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
2515                                                         "me:env" => array("me:encoding" => $encoding,
2516                                                         "me:alg" => $alg,
2517                                                         "me:data" => $data,
2518                                                         "@attributes" => array("type" => $type),
2519                                                         "me:sig" => $sig)));
2520
2521                 $namespaces = array("" => "https://joindiaspora.com/protocol",
2522                                 "me" => "http://salmon-protocol.org/ns/magic-env");
2523
2524                 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2525
2526                 logger("magic_env: ".$magic_env, LOGGER_DATA);
2527                 return $magic_env;
2528         }
2529
2530         /**
2531          * @brief Creates the envelope for a private message
2532          *
2533          * @param string $msg The message that is to be transmitted
2534          * @param array $user The record of the sender
2535          * @param array $contact Target of the communication
2536          * @param string $prvkey The private key of the sender
2537          * @param string $pubkey The public key of the receiver
2538          *
2539          * @return string The envelope
2540          */
2541         private function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
2542
2543                 logger("Message: ".$msg, LOGGER_DATA);
2544
2545                 // without a public key nothing will work
2546
2547                 if (!$pubkey) {
2548                         logger("pubkey missing: contact id: ".$contact["id"]);
2549                         return false;
2550                 }
2551
2552                 $inner_aes_key = random_string(32);
2553                 $b_inner_aes_key = base64_encode($inner_aes_key);
2554                 $inner_iv = random_string(16);
2555                 $b_inner_iv = base64_encode($inner_iv);
2556
2557                 $outer_aes_key = random_string(32);
2558                 $b_outer_aes_key = base64_encode($outer_aes_key);
2559                 $outer_iv = random_string(16);
2560                 $b_outer_iv = base64_encode($outer_iv);
2561
2562                 $handle = self::my_handle($user);
2563
2564                 $padded_data = pkcs5_pad($msg,16);
2565                 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
2566
2567                 $b64_data = base64_encode($inner_encrypted);
2568
2569
2570                 $b64url_data = base64url_encode($b64_data);
2571                 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2572
2573                 $type = "application/xml";
2574                 $encoding = "base64url";
2575                 $alg = "RSA-SHA256";
2576
2577                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2578
2579                 $signature = rsa_sign($signable_data,$prvkey);
2580                 $sig = base64url_encode($signature);
2581
2582                 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
2583                                                         "aes_key" => $b_inner_aes_key,
2584                                                         "author_id" => $handle));
2585
2586                 $decrypted_header = xml::from_array($xmldata, $xml, true);
2587                 $decrypted_header = pkcs5_pad($decrypted_header,16);
2588
2589                 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
2590
2591                 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
2592
2593                 $encrypted_outer_key_bundle = "";
2594                 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2595
2596                 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2597
2598                 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2599
2600                 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2601                                                                 "ciphertext" => base64_encode($ciphertext)));
2602                 $cipher_json = base64_encode($encrypted_header_json_object);
2603
2604                 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2605                                                 "me:env" => array("me:encoding" => $encoding,
2606                                                                 "me:alg" => $alg,
2607                                                                 "me:data" => $data,
2608                                                                 "@attributes" => array("type" => $type),
2609                                                                 "me:sig" => $sig)));
2610
2611                 $namespaces = array("" => "https://joindiaspora.com/protocol",
2612                                 "me" => "http://salmon-protocol.org/ns/magic-env");
2613
2614                 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2615
2616                 logger("magic_env: ".$magic_env, LOGGER_DATA);
2617                 return $magic_env;
2618         }
2619
2620         /**
2621          * @brief Create the envelope for a message
2622          *
2623          * @param string $msg The message that is to be transmitted
2624          * @param array $user The record of the sender
2625          * @param array $contact Target of the communication
2626          * @param string $prvkey The private key of the sender
2627          * @param string $pubkey The public key of the receiver
2628          * @param bool $public Is the message public?
2629          *
2630          * @return string The message that will be transmitted to other servers
2631          */
2632         private function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2633
2634                 if ($public)
2635                         $magic_env =  self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2636                 else
2637                         $magic_env =  self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2638
2639                 // The data that will be transmitted is double encoded via "urlencode", strange ...
2640                 $slap = "xml=".urlencode(urlencode($magic_env));
2641                 return $slap;
2642         }
2643
2644         /**
2645          * @brief Creates a signature for a message
2646          *
2647          * @param array $owner the array of the owner of the message
2648          * @param array $message The message that is to be signed
2649          *
2650          * @return string The signature
2651          */
2652         private function signature($owner, $message) {
2653                 $sigmsg = $message;
2654                 unset($sigmsg["author_signature"]);
2655                 unset($sigmsg["parent_author_signature"]);
2656
2657                 $signed_text = implode(";", $sigmsg);
2658
2659                 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2660         }
2661
2662         /**
2663          * @brief Transmit a message to a target server
2664          *
2665          * @param array $owner the array of the item owner
2666          * @param array $contact Target of the communication
2667          * @param string $slap The message that is to be transmitted
2668          * @param bool $public_batch Is it a public post?
2669          * @param bool $queue_run Is the transmission called from the queue?
2670          * @param string $guid message guid
2671          *
2672          * @return int Result of the transmission
2673          */
2674         public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2675
2676                 $a = get_app();
2677
2678                 $enabled = intval(get_config("system", "diaspora_enabled"));
2679                 if(!$enabled)
2680                         return 200;
2681
2682                 $logid = random_string(4);
2683                 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2684                 if (!$dest_url) {
2685                         logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2686                         return 0;
2687                 }
2688
2689                 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2690
2691                 if (!$queue_run && was_recently_delayed($contact["id"])) {
2692                         $return_code = 0;
2693                 } else {
2694                         if (!intval(get_config("system", "diaspora_test"))) {
2695                                 post_url($dest_url."/", $slap);
2696                                 $return_code = $a->get_curl_code();
2697                         } else {
2698                                 logger("test_mode");
2699                                 return 200;
2700                         }
2701                 }
2702
2703                 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2704
2705                 if(!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2706                         logger("queue message");
2707
2708                         $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2709                                 intval($contact["id"]),
2710                                 dbesc(NETWORK_DIASPORA),
2711                                 dbesc($slap),
2712                                 intval($public_batch)
2713                         );
2714                         if($r) {
2715                                 logger("add_to_queue ignored - identical item already in queue");
2716                         } else {
2717                                 // queue message for redelivery
2718                                 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2719
2720                                 // The message could not be delivered. We mark the contact as "dead"
2721                                 mark_for_death($contact);
2722                         }
2723                 } elseif (($return_code >= 200) AND ($return_code <= 299)) {
2724                         // We successfully delivered a message, the contact is alive
2725                         unmark_for_death($contact);
2726                 }
2727
2728                 return(($return_code) ? $return_code : (-1));
2729         }
2730
2731
2732         /**
2733          * @brief Build the post xml
2734          *
2735          * @param string $type The message type
2736          * @param array $message The message data
2737          *
2738          * @return string The post XML
2739          */
2740         public static function build_post_xml($type, $message) {
2741
2742                 $data = array("XML" => array("post" => array($type => $message)));
2743                 return xml::from_array($data, $xml);
2744         }
2745
2746         /**
2747          * @brief Builds and transmit messages
2748          *
2749          * @param array $owner the array of the item owner
2750          * @param array $contact Target of the communication
2751          * @param string $type The message type
2752          * @param array $message The message data
2753          * @param bool $public_batch Is it a public post?
2754          * @param string $guid message guid
2755          * @param bool $spool Should the transmission be spooled or transmitted?
2756          *
2757          * @return int Result of the transmission
2758          */
2759         private function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2760
2761                 $msg = self::build_post_xml($type, $message);
2762
2763                 logger('message: '.$msg, LOGGER_DATA);
2764                 logger('send guid '.$guid, LOGGER_DEBUG);
2765
2766                 // Fallback if the private key wasn't transmitted in the expected field
2767                 if ($owner['uprvkey'] == "")
2768                         $owner['uprvkey'] = $owner['prvkey'];
2769
2770                 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2771
2772                 if ($spool) {
2773                         add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2774                         return true;
2775                 } else
2776                         $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2777
2778                 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2779
2780                 return $return_code;
2781         }
2782
2783         /**
2784          * @brief Sends a "share" message
2785          *
2786          * @param array $owner the array of the item owner
2787          * @param array $contact Target of the communication
2788          *
2789          * @return int The result of the transmission
2790          */
2791         public static function send_share($owner,$contact) {
2792
2793                 $message = array("sender_handle" => self::my_handle($owner),
2794                                 "recipient_handle" => $contact["addr"]);
2795
2796                 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
2797
2798                 return self::build_and_transmit($owner, $contact, "request", $message);
2799         }
2800
2801         /**
2802          * @brief sends an "unshare"
2803          *
2804          * @param array $owner the array of the item owner
2805          * @param array $contact Target of the communication
2806          *
2807          * @return int The result of the transmission
2808          */
2809         public static function send_unshare($owner,$contact) {
2810
2811                 $message = array("post_guid" => $owner["guid"],
2812                                 "diaspora_handle" => self::my_handle($owner),
2813                                 "type" => "Person");
2814
2815                 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
2816
2817                 return self::build_and_transmit($owner, $contact, "retraction", $message);
2818         }
2819
2820         /**
2821          * @brief Checks a message body if it is a reshare
2822          *
2823          * @param string $body The message body that is to be check
2824          * @param bool $complete Should it be a complete check or a simple check?
2825          *
2826          * @return array|bool Reshare details or "false" if no reshare
2827          */
2828         public static function is_reshare($body, $complete = true) {
2829                 $body = trim($body);
2830
2831                 // Skip if it isn't a pure repeated messages
2832                 // Does it start with a share?
2833                 if ((strpos($body, "[share") > 0) AND $complete)
2834                         return(false);
2835
2836                 // Does it end with a share?
2837                 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2838                         return(false);
2839
2840                 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2841                 // Skip if there is no shared message in there
2842                 if ($body == $attributes)
2843                         return(false);
2844
2845                 // If we don't do the complete check we quit here
2846                 if (!$complete)
2847                         return true;
2848
2849                 $guid = "";
2850                 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2851                 if ($matches[1] != "")
2852                         $guid = $matches[1];
2853
2854                 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2855                 if ($matches[1] != "")
2856                         $guid = $matches[1];
2857
2858                 if ($guid != "") {
2859                         $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2860                                 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2861                         if ($r) {
2862                                 $ret= array();
2863                                 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2864                                 $ret["root_guid"] = $guid;
2865                                 return($ret);
2866                         }
2867                 }
2868
2869                 $profile = "";
2870                 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2871                 if ($matches[1] != "")
2872                         $profile = $matches[1];
2873
2874                 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2875                 if ($matches[1] != "")
2876                         $profile = $matches[1];
2877
2878                 $ret= array();
2879
2880                 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2881                 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2882                         return(false);
2883
2884                 $link = "";
2885                 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2886                 if ($matches[1] != "")
2887                         $link = $matches[1];
2888
2889                 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2890                 if ($matches[1] != "")
2891                         $link = $matches[1];
2892
2893                 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2894                 if (($ret["root_guid"] == $link) OR (trim($ret["root_guid"]) == ""))
2895                         return(false);
2896
2897                 return($ret);
2898         }
2899
2900         /**
2901          * @brief Create a post (status message or reshare)
2902          *
2903          * @param array $item The item that will be exported
2904          * @param array $owner the array of the item owner
2905          *
2906          * @return array
2907          * 'type' -> Message type ("status_message" or "reshare")
2908          * 'message' -> Array of XML elements of the status
2909          */
2910         public static function build_status($item, $owner) {
2911
2912                 $myaddr = self::my_handle($owner);
2913
2914                 $public = (($item["private"]) ? "false" : "true");
2915
2916                 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2917
2918                 // Detect a share element and do a reshare
2919                 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
2920                         $message = array("root_diaspora_id" => $ret["root_handle"],
2921                                         "root_guid" => $ret["root_guid"],
2922                                         "guid" => $item["guid"],
2923                                         "diaspora_handle" => $myaddr,
2924                                         "public" => $public,
2925                                         "created_at" => $created,
2926                                         "provider_display_name" => $item["app"]);
2927
2928                         $type = "reshare";
2929                 } else {
2930                         $title = $item["title"];
2931                         $body = $item["body"];
2932
2933                         // convert to markdown
2934                         $body = html_entity_decode(bb2diaspora($body));
2935
2936                         // Adding the title
2937                         if(strlen($title))
2938                                 $body = "## ".html_entity_decode($title)."\n\n".$body;
2939
2940                         if ($item["attach"]) {
2941                                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
2942                                 if(cnt) {
2943                                         $body .= "\n".t("Attachments:")."\n";
2944                                         foreach($matches as $mtch)
2945                                                 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
2946                                 }
2947                         }
2948
2949                         $location = array();
2950
2951                         if ($item["location"] != "")
2952                                 $location["address"] = $item["location"];
2953
2954                         if ($item["coord"] != "") {
2955                                 $coord = explode(" ", $item["coord"]);
2956                                 $location["lat"] = $coord[0];
2957                                 $location["lng"] = $coord[1];
2958                         }
2959
2960                         $message = array("raw_message" => $body,
2961                                         "location" => $location,
2962                                         "guid" => $item["guid"],
2963                                         "diaspora_handle" => $myaddr,
2964                                         "public" => $public,
2965                                         "created_at" => $created,
2966                                         "provider_display_name" => $item["app"]);
2967
2968                         // Diaspora rejects messages when they contain a location without "lat" or "lng"
2969                         if (!isset($location["lat"]) OR !isset($location["lng"])) {
2970                                 unset($message["location"]);
2971                         }
2972
2973                         $type = "status_message";
2974                 }
2975                 return array("type" => $type, "message" => $message);
2976         }
2977
2978         /**
2979          * @brief Sends a post
2980          *
2981          * @param array $item The item that will be exported
2982          * @param array $owner the array of the item owner
2983          * @param array $contact Target of the communication
2984          * @param bool $public_batch Is it a public post?
2985          *
2986          * @return int The result of the transmission
2987          */
2988         public static function send_status($item, $owner, $contact, $public_batch = false) {
2989
2990                 $status = self::build_status($item, $owner);
2991
2992                 return self::build_and_transmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
2993         }
2994
2995         /**
2996          * @brief Creates a "like" object
2997          *
2998          * @param array $item The item that will be exported
2999          * @param array $owner the array of the item owner
3000          *
3001          * @return array The data for a "like"
3002          */
3003         private function construct_like($item, $owner) {
3004
3005                 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3006                         dbesc($item["thr-parent"]));
3007                 if(!$p)
3008                         return false;
3009
3010                 $parent = $p[0];
3011
3012                 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3013                 $positive = "true";
3014
3015                 return(array("positive" => $positive,
3016                                 "guid" => $item["guid"],
3017                                 "target_type" => $target_type,
3018                                 "parent_guid" => $parent["guid"],
3019                                 "author_signature" => "",
3020                                 "diaspora_handle" => self::my_handle($owner)));
3021         }
3022
3023         /**
3024          * @brief Creates the object for a comment
3025          *
3026          * @param array $item The item that will be exported
3027          * @param array $owner the array of the item owner
3028          *
3029          * @return array The data for a comment
3030          */
3031         private function construct_comment($item, $owner) {
3032
3033                 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3034                         intval($item["parent"]),
3035                         intval($item["parent"])
3036                 );
3037
3038                 if (!$p)
3039                         return false;
3040
3041                 $parent = $p[0];
3042
3043                 $text = html_entity_decode(bb2diaspora($item["body"]));
3044
3045                 return(array("guid" => $item["guid"],
3046                                 "parent_guid" => $parent["guid"],
3047                                 "author_signature" => "",
3048                                 "text" => $text,
3049                                 "diaspora_handle" => self::my_handle($owner)));
3050         }
3051
3052         /**
3053          * @brief Send a like or a comment
3054          *
3055          * @param array $item The item that will be exported
3056          * @param array $owner the array of the item owner
3057          * @param array $contact Target of the communication
3058          * @param bool $public_batch Is it a public post?
3059          *
3060          * @return int The result of the transmission
3061          */
3062         public static function send_followup($item,$owner,$contact,$public_batch = false) {
3063
3064                 if($item['verb'] === ACTIVITY_LIKE) {
3065                         $message = self::construct_like($item, $owner);
3066                         $type = "like";
3067                 } else {
3068                         $message = self::construct_comment($item, $owner);
3069                         $type = "comment";
3070                 }
3071
3072                 if (!$message)
3073                         return false;
3074
3075                 $message["author_signature"] = self::signature($owner, $message);
3076
3077                 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3078         }
3079
3080         /**
3081          * @brief Creates a message from a signature record entry
3082          *
3083          * @param array $item The item that will be exported
3084          * @param array $signature The entry of the "sign" record
3085          *
3086          * @return string The message
3087          */
3088         private function message_from_signature($item, $signature) {
3089
3090                 // Split the signed text
3091                 $signed_parts = explode(";", $signature['signed_text']);
3092
3093                 if ($item["deleted"])
3094                         $message = array("parent_author_signature" => "",
3095                                         "target_guid" => $signed_parts[0],
3096                                         "target_type" => $signed_parts[1],
3097                                         "sender_handle" => $signature['signer'],
3098                                         "target_author_signature" => $signature['signature']);
3099                 elseif ($item['verb'] === ACTIVITY_LIKE)
3100                         $message = array("positive" => $signed_parts[0],
3101                                         "guid" => $signed_parts[1],
3102                                         "target_type" => $signed_parts[2],
3103                                         "parent_guid" => $signed_parts[3],
3104                                         "parent_author_signature" => "",
3105                                         "author_signature" => $signature['signature'],
3106                                         "diaspora_handle" => $signed_parts[4]);
3107                 else {
3108                         // Remove the comment guid
3109                         $guid = array_shift($signed_parts);
3110
3111                         // Remove the parent guid
3112                         $parent_guid = array_shift($signed_parts);
3113
3114                         // Remove the handle
3115                         $handle = array_pop($signed_parts);
3116
3117                         // Glue the parts together
3118                         $text = implode(";", $signed_parts);
3119
3120                         $message = array("guid" => $guid,
3121                                         "parent_guid" => $parent_guid,
3122                                         "parent_author_signature" => "",
3123                                         "author_signature" => $signature['signature'],
3124                                         "text" => implode(";", $signed_parts),
3125                                         "diaspora_handle" => $handle);
3126                 }
3127                 return $message;
3128         }
3129
3130         /**
3131          * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3132          *
3133          * @param array $item The item that will be exported
3134          * @param array $owner the array of the item owner
3135          * @param array $contact Target of the communication
3136          * @param bool $public_batch Is it a public post?
3137          *
3138          * @return int The result of the transmission
3139          */
3140         public static function send_relay($item, $owner, $contact, $public_batch = false) {
3141
3142                 if ($item["deleted"])
3143                         return self::send_retraction($item, $owner, $contact, $public_batch, true);
3144                 elseif ($item['verb'] === ACTIVITY_LIKE)
3145                         $type = "like";
3146                 else
3147                         $type = "comment";
3148
3149                 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3150
3151                 // fetch the original signature
3152
3153                 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3154                         intval($item["id"]));
3155
3156                 if (!$r) {
3157                         logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3158                         return false;
3159                 }
3160
3161                 $signature = $r[0];
3162
3163                 // Old way - is used by the internal Friendica functions
3164                 /// @todo Change all signatur storing functions to the new format
3165                 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
3166                         $message = self::message_from_signature($item, $signature);
3167                 else {// New way
3168                         $msg = json_decode($signature['signed_text'], true);
3169
3170                         $message = array();
3171                         if (is_array($msg)) {
3172                                 foreach ($msg AS $field => $data) {
3173                                         if (!$item["deleted"]) {
3174                                                 if ($field == "author")
3175                                                         $field = "diaspora_handle";
3176                                                 if ($field == "parent_type")
3177                                                         $field = "target_type";
3178                                         }
3179
3180                                         $message[$field] = $data;
3181                                 }
3182                         } else
3183                                 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3184                 }
3185
3186                 $message["parent_author_signature"] = self::signature($owner, $message);
3187
3188                 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3189
3190                 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3191         }
3192
3193         /**
3194          * @brief Sends a retraction (deletion) of a message, like or comment
3195          *
3196          * @param array $item The item that will be exported
3197          * @param array $owner the array of the item owner
3198          * @param array $contact Target of the communication
3199          * @param bool $public_batch Is it a public post?
3200          * @param bool $relay Is the retraction transmitted from a relay?
3201          *
3202          * @return int The result of the transmission
3203          */
3204         public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
3205
3206                 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
3207
3208                 // Check whether the retraction is for a top-level post or whether it's a relayable
3209                 if ($item["uri"] !== $item["parent-uri"]) {
3210                         $msg_type = "relayable_retraction";
3211                         $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
3212                 } else {
3213                         $msg_type = "signed_retraction";
3214                         $target_type = "StatusMessage";
3215                 }
3216
3217                 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
3218                         $signature = "parent_author_signature";
3219                 else
3220                         $signature = "target_author_signature";
3221
3222                 $signed_text = $item["guid"].";".$target_type;
3223
3224                 $message = array("target_guid" => $item['guid'],
3225                                 "target_type" => $target_type,
3226                                 "sender_handle" => $itemaddr,
3227                                 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
3228
3229                 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3230
3231                 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3232         }
3233
3234         /**
3235          * @brief Sends a mail
3236          *
3237          * @param array $item The item that will be exported
3238          * @param array $owner The owner
3239          * @param array $contact Target of the communication
3240          *
3241          * @return int The result of the transmission
3242          */
3243         public static function send_mail($item, $owner, $contact) {
3244
3245                 $myaddr = self::my_handle($owner);
3246
3247                 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3248                         intval($item["convid"]),
3249                         intval($item["uid"])
3250                 );
3251
3252                 if (!$r) {
3253                         logger("conversation not found.");
3254                         return;
3255                 }
3256                 $cnv = $r[0];
3257
3258                 $conv = array(
3259                         "guid" => $cnv["guid"],
3260                         "subject" => $cnv["subject"],
3261                         "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
3262                         "diaspora_handle" => $cnv["creator"],
3263                         "participant_handles" => $cnv["recips"]
3264                 );
3265
3266                 $body = bb2diaspora($item["body"]);
3267                 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
3268
3269                 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
3270                 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3271
3272                 $msg = array(
3273                         "guid" => $item["guid"],
3274                         "parent_guid" => $cnv["guid"],
3275                         "parent_author_signature" => $sig,
3276                         "author_signature" => $sig,
3277                         "text" => $body,
3278                         "created_at" => $created,
3279                         "diaspora_handle" => $myaddr,
3280                         "conversation_guid" => $cnv["guid"]
3281                 );
3282
3283                 if ($item["reply"]) {
3284                         $message = $msg;
3285                         $type = "message";
3286                 } else {
3287                         $message = array("guid" => $cnv["guid"],
3288                                         "subject" => $cnv["subject"],
3289                                         "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
3290                                         "message" => $msg,
3291                                         "diaspora_handle" => $cnv["creator"],
3292                                         "participant_handles" => $cnv["recips"]);
3293
3294                         $type = "conversation";
3295                 }
3296
3297                 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3298         }
3299
3300         /**
3301          * @brief Sends profile data
3302          *
3303          * @param int $uid The user id
3304          */
3305         public static function send_profile($uid, $recips = false) {
3306
3307                 if (!$uid)
3308                         return;
3309
3310                 if (!$recips)
3311                         $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3312                                 AND `uid` = %d AND `rel` != %d",
3313                                 dbesc(NETWORK_DIASPORA),
3314                                 intval($uid),
3315                                 intval(CONTACT_IS_SHARING)
3316                         );
3317                 if (!$recips)
3318                         return;
3319
3320                 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3321                         FROM `profile`
3322                         INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3323                         INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3324                         WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3325                         intval($uid)
3326                 );
3327
3328                 if (!$r)
3329                         return;
3330
3331                 $profile = $r[0];
3332
3333                 $handle = $profile["addr"];
3334                 $first = ((strpos($profile['name'],' ')
3335                         ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3336                 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3337                 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3338                 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3339                 $small = App::get_baseurl().'/photo/custom/50/'  .$profile['uid'].'.jpg';
3340                 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3341
3342                 if ($searchable === 'true') {
3343                         $dob = '1000-00-00';
3344
3345                         if (($profile['dob']) && ($profile['dob'] != '0000-00-00'))
3346                                 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3347
3348                         $about = $profile['about'];
3349                         $about = strip_tags(bbcode($about));
3350
3351                         $location = formatted_location($profile);
3352                         $tags = '';
3353                         if ($profile['pub_keywords']) {
3354                                 $kw = str_replace(',',' ',$profile['pub_keywords']);
3355                                 $kw = str_replace('  ',' ',$kw);
3356                                 $arr = explode(' ',$profile['pub_keywords']);
3357                                 if (count($arr)) {
3358                                         for($x = 0; $x < 5; $x ++) {
3359                                                 if (trim($arr[$x]))
3360                                                         $tags .= '#'. trim($arr[$x]) .' ';
3361                                         }
3362                                 }
3363                         }
3364                         $tags = trim($tags);
3365                 }
3366
3367                 $message = array("diaspora_handle" => $handle,
3368                                 "first_name" => $first,
3369                                 "last_name" => $last,
3370                                 "image_url" => $large,
3371                                 "image_url_medium" => $medium,
3372                                 "image_url_small" => $small,
3373                                 "birthday" => $dob,
3374                                 "gender" => $profile['gender'],
3375                                 "bio" => $about,
3376                                 "location" => $location,
3377                                 "searchable" => $searchable,
3378                                 "tag_string" => $tags);
3379
3380                 foreach($recips as $recip) {
3381                         logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
3382                         self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3383                 }
3384         }
3385
3386         /**
3387          * @brief Stores the signature for likes that are created on our system
3388          *
3389          * @param array $contact The contact array of the "like"
3390          * @param int $post_id The post id of the "like"
3391          *
3392          * @return bool Success
3393          */
3394         public static function store_like_signature($contact, $post_id) {
3395
3396                 // Is the contact the owner? Then fetch the private key
3397                 if (!$contact['self'] OR ($contact['uid'] == 0)) {
3398                         logger("No owner post, so not storing signature", LOGGER_DEBUG);
3399                         return false;
3400                 }
3401
3402                 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3403                 if(!$r)
3404                         return false;
3405
3406                 $contact["uprvkey"] = $r[0]['prvkey'];
3407
3408                 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3409                 if (!$r)
3410                         return false;
3411
3412                 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE)))
3413                         return false;
3414
3415                 $message = self::construct_like($r[0], $contact);
3416                 $message["author_signature"] = self::signature($contact, $message);
3417
3418                 // In the future we will store the signature more flexible to support new fields.
3419                 // Right now we cannot change this since old Friendica versions (prior to 3.5) can only handle this format.
3420                 // (We are transmitting this data here via DFRN)
3421
3422                 $signed_text = $message["positive"].";".$message["guid"].";".$message["target_type"].";".
3423                                 $message["parent_guid"].";".$message["diaspora_handle"];
3424
3425                 q("INSERT INTO `sign` (`iid`,`signed_text`,`signature`,`signer`) VALUES (%d,'%s','%s','%s')",
3426                         intval($post_id),
3427                         dbesc($signed_text),
3428                         dbesc($message["author_signature"]),
3429                         dbesc($message["diaspora_handle"])
3430                 );
3431
3432                 // This here will replace the lines above, once Diaspora changed its protocol
3433                 //q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3434                 //      intval($message_id),
3435                 //      dbesc(json_encode($message))
3436                 //);
3437
3438                 logger('Stored diaspora like signature');
3439                 return true;
3440         }
3441
3442         /**
3443          * @brief Stores the signature for comments that are created on our system
3444          *
3445          * @param array $item The item array of the comment
3446          * @param array $contact The contact array of the item owner
3447          * @param string $uprvkey The private key of the sender
3448          * @param int $message_id The message id of the comment
3449          *
3450          * @return bool Success
3451          */
3452         public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3453
3454                 if ($uprvkey == "") {
3455                         logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3456                         return false;
3457                 }
3458
3459                 $contact["uprvkey"] = $uprvkey;
3460
3461                 $message = self::construct_comment($item, $contact);
3462                 $message["author_signature"] = self::signature($contact, $message);
3463
3464                 // In the future we will store the signature more flexible to support new fields.
3465                 // Right now we cannot change this since old Friendica versions (prior to 3.5) can only handle this format.
3466                 // (We are transmitting this data here via DFRN)
3467                 $signed_text = $message["guid"].";".$message["parent_guid"].";".
3468                                 $message["text"].";".$message["diaspora_handle"];
3469
3470                 q("INSERT INTO `sign` (`iid`,`signed_text`,`signature`,`signer`) VALUES (%d,'%s','%s','%s')",
3471                         intval($message_id),
3472                         dbesc($signed_text),
3473                         dbesc($message["author_signature"]),
3474                         dbesc($message["diaspora_handle"])
3475                 );
3476
3477                 // This here will replace the lines above, once Diaspora changed its protocol
3478                 //q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3479                 //      intval($message_id),
3480                 //      dbesc(json_encode($message))
3481                 //);
3482
3483                 logger('Stored diaspora comment signature');
3484                 return true;
3485         }
3486 }
3487 ?>