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