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