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