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