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