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