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