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