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