]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
Added some documentation, script to generate a basic doxygen header
[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 
834          *
835          * @param string $guid message guid
836          * @param $server
837          * @param $level
838          *
839          * @return 
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 
886          *
887          * @param int $uid The user id
888          * @param string $guid message guid
889          * @param $author
890          * @param array $contact The contact that is checked
891          *
892          * @return 
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 
931          *
932          * @param array $contact The contact that is checked
933          * @param $person
934          * @param int $uid The user id
935          *
936          * @return 
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 $addr
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 
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 $msg
1110          * @param $mesg
1111          * @param $conversation
1112          *
1113          * @return 
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         }
1230
1231         /**
1232          * @brief 
1233          *
1234          * @param array $importer Array of the importer user
1235          * @param $msg
1236          * @param object $data The message object
1237          *
1238          * @return 
1239          */
1240         private function receive_conversation($importer, $msg, $data) {
1241                 $guid = notags(unxmlify($data->guid));
1242                 $subject = notags(unxmlify($data->subject));
1243                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1244                 $author = notags(unxmlify($data->author));
1245                 $participants = notags(unxmlify($data->participants));
1246
1247                 $messages = $data->message;
1248
1249                 if (!count($messages)) {
1250                         logger("empty conversation");
1251                         return false;
1252                 }
1253
1254                 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1255                 if (!$contact)
1256                         return false;
1257
1258                 $conversation = null;
1259
1260                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1261                         intval($importer["uid"]),
1262                         dbesc($guid)
1263                 );
1264                 if($c)
1265                         $conversation = $c[0];
1266                 else {
1267                         $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1268                                 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1269                                 intval($importer["uid"]),
1270                                 dbesc($guid),
1271                                 dbesc($author),
1272                                 dbesc(datetime_convert("UTC", "UTC", $created_at)),
1273                                 dbesc(datetime_convert()),
1274                                 dbesc($subject),
1275                                 dbesc($participants)
1276                         );
1277                         if($r)
1278                                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1279                                         intval($importer["uid"]),
1280                                         dbesc($guid)
1281                                 );
1282
1283                         if($c)
1284                                 $conversation = $c[0];
1285                 }
1286                 if (!$conversation) {
1287                         logger("unable to create conversation.");
1288                         return;
1289                 }
1290
1291                 foreach($messages as $mesg)
1292                         self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1293
1294                 return true;
1295         }
1296
1297         /**
1298          * @brief 
1299          *
1300          * @param array $contact The contact that is checked
1301          * @param $parent_item
1302          * @param string $guid message guid
1303          *
1304          * @return 
1305          */
1306         private function construct_like_body($contact, $parent_item, $guid) {
1307                 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1308
1309                 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1310                 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1311                 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1312
1313                 return sprintf($bodyverb, $ulink, $alink, $plink);
1314         }
1315
1316         /**
1317          * @brief 
1318          *
1319          * @param array $importer Array of the importer user
1320          * @param $parent_item
1321          *
1322          * @return 
1323          */
1324         private function construct_like_object($importer, $parent_item) {
1325                 $objtype = ACTIVITY_OBJ_NOTE;
1326                 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1327                 $parent_body = $parent_item["body"];
1328
1329                 $xmldata = array("object" => array("type" => $objtype,
1330                                                 "local" => "1",
1331                                                 "id" => $parent_item["uri"],
1332                                                 "link" => $link,
1333                                                 "title" => "",
1334                                                 "content" => $parent_body));
1335
1336                 return xml::from_array($xmldata, $xml, true);
1337         }
1338
1339         /**
1340          * @brief 
1341          *
1342          * @param array $importer Array of the importer user
1343          * @param string $sender The sender of the message
1344          * @param object $data The message object
1345          *
1346          * @return int The message id of the generated like or "false" if there was an error
1347          */
1348         private function receive_like($importer, $sender, $data) {
1349                 $positive = notags(unxmlify($data->positive));
1350                 $guid = notags(unxmlify($data->guid));
1351                 $parent_type = notags(unxmlify($data->parent_type));
1352                 $parent_guid = notags(unxmlify($data->parent_guid));
1353                 $author = notags(unxmlify($data->author));
1354
1355                 // likes on comments aren't supported by Diaspora - only on posts
1356                 // But maybe this will be supported in the future, so we will accept it.
1357                 if (!in_array($parent_type, array("Post", "Comment")))
1358                         return false;
1359
1360                 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1361                 if (!$contact)
1362                         return false;
1363
1364                 if (self::message_exists($importer["uid"], $guid))
1365                         return false;
1366
1367                 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1368                 if (!$parent_item)
1369                         return false;
1370
1371                 $person = self::person_by_handle($author);
1372                 if (!is_array($person)) {
1373                         logger("unable to find author details");
1374                         return false;
1375                 }
1376
1377                 // Fetch the contact id - if we know this contact
1378                 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1379
1380                 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1381                 // We would accept this anyhow.
1382                 if ($positive === "true")
1383                         $verb = ACTIVITY_LIKE;
1384                 else
1385                         $verb = ACTIVITY_DISLIKE;
1386
1387                 $datarray = array();
1388
1389                 $datarray["uid"] = $importer["uid"];
1390                 $datarray["contact-id"] = $author_contact["cid"];
1391                 $datarray["network"]  = $author_contact["network"];
1392
1393                 $datarray["author-name"] = $person["name"];
1394                 $datarray["author-link"] = $person["url"];
1395                 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1396
1397                 $datarray["owner-name"] = $contact["name"];
1398                 $datarray["owner-link"] = $contact["url"];
1399                 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1400
1401                 $datarray["guid"] = $guid;
1402                 $datarray["uri"] = $author.":".$guid;
1403
1404                 $datarray["type"] = "activity";
1405                 $datarray["verb"] = $verb;
1406                 $datarray["gravity"] = GRAVITY_LIKE;
1407                 $datarray["parent-uri"] = $parent_item["uri"];
1408
1409                 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1410                 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1411
1412                 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1413
1414                 $message_id = item_store($datarray);
1415
1416                 if ($message_id)
1417                         logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1418
1419                 // If we are the origin of the parent we store the original data and notify our followers
1420                 if($message_id AND $parent_item["origin"]) {
1421
1422                         // Formerly we stored the signed text, the signature and the author in different fields.
1423                         // We now store the raw data so that we are more flexible.
1424                         q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1425                                 intval($message_id),
1426                                 dbesc(json_encode($data))
1427                         );
1428
1429                         // notify others
1430                         proc_run("php", "include/notifier.php", "comment-import", $message_id);
1431                 }
1432
1433                 return $message_id;
1434         }
1435
1436         /**
1437          * @brief 
1438          *
1439          * @param array $importer Array of the importer user
1440          * @param object $data The message object
1441          *
1442          * @return 
1443          */
1444         private function receive_message($importer, $data) {
1445                 $guid = notags(unxmlify($data->guid));
1446                 $parent_guid = notags(unxmlify($data->parent_guid));
1447                 $text = unxmlify($data->text);
1448                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1449                 $author = notags(unxmlify($data->author));
1450                 $conversation_guid = notags(unxmlify($data->conversation_guid));
1451
1452                 $contact = self::allowed_contact_by_handle($importer, $author, true);
1453                 if (!$contact)
1454                         return false;
1455
1456                 $conversation = null;
1457
1458                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1459                         intval($importer["uid"]),
1460                         dbesc($conversation_guid)
1461                 );
1462                 if($c)
1463                         $conversation = $c[0];
1464                 else {
1465                         logger("conversation not available.");
1466                         return false;
1467                 }
1468
1469                 $reply = 0;
1470
1471                 $body = diaspora2bb($text);
1472                 $message_uri = $author.":".$guid;
1473
1474                 $person = self::person_by_handle($author);
1475                 if (!$person) {
1476                         logger("unable to find author details");
1477                         return false;
1478                 }
1479
1480                 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1481                         dbesc($message_uri),
1482                         intval($importer["uid"])
1483                 );
1484                 if($r) {
1485                         logger("duplicate message already delivered.", LOGGER_DEBUG);
1486                         return false;
1487                 }
1488
1489                 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1490                                 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1491                         intval($importer["uid"]),
1492                         dbesc($guid),
1493                         intval($conversation["id"]),
1494                         dbesc($person["name"]),
1495                         dbesc($person["photo"]),
1496                         dbesc($person["url"]),
1497                         intval($contact["id"]),
1498                         dbesc($conversation["subject"]),
1499                         dbesc($body),
1500                         0,
1501                         1,
1502                         dbesc($message_uri),
1503                         dbesc($author.":".$parent_guid),
1504                         dbesc($created_at)
1505                 );
1506
1507                 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1508                         dbesc(datetime_convert()),
1509                         intval($conversation["id"])
1510                 );
1511
1512                 return true;
1513         }
1514
1515         /**
1516          * @brief 
1517          *
1518          * @param array $importer Array of the importer user
1519          * @param object $data The message object
1520          *
1521          * @return bool always true
1522          */
1523         private function receive_participation($importer, $data) {
1524                 // I'm not sure if we can fully support this message type
1525                 return true;
1526         }
1527
1528         /**
1529          * @brief 
1530          *
1531          * @param array $importer Array of the importer user
1532          * @param object $data The message object
1533          *
1534          * @return 
1535          */
1536         private function receive_photo($importer, $data) {
1537                 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1538                 return true;
1539         }
1540
1541         /**
1542          * @brief 
1543          *
1544          * @param array $importer Array of the importer user
1545          * @param object $data The message object
1546          *
1547          * @return 
1548          */
1549         private function receive_poll_participation($importer, $data) {
1550                 // We don't support polls by now
1551                 return true;
1552         }
1553
1554         /**
1555          * @brief 
1556          *
1557          * @param array $importer Array of the importer user
1558          * @param object $data The message object
1559          *
1560          * @return 
1561          */
1562         private function receive_profile($importer, $data) {
1563                 $author = notags(unxmlify($data->author));
1564
1565                 $contact = self::contact_by_handle($importer["uid"], $author);
1566                 if (!$contact)
1567                         return false;
1568
1569                 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1570                 $image_url = unxmlify($data->image_url);
1571                 $birthday = unxmlify($data->birthday);
1572                 $location = diaspora2bb(unxmlify($data->location));
1573                 $about = diaspora2bb(unxmlify($data->bio));
1574                 $gender = unxmlify($data->gender);
1575                 $searchable = (unxmlify($data->searchable) == "true");
1576                 $nsfw = (unxmlify($data->nsfw) == "true");
1577                 $tags = unxmlify($data->tag_string);
1578
1579                 $tags = explode("#", $tags);
1580
1581                 $keywords = array();
1582                 foreach ($tags as $tag) {
1583                         $tag = trim(strtolower($tag));
1584                         if ($tag != "")
1585                                 $keywords[] = $tag;
1586                 }
1587
1588                 $keywords = implode(", ", $keywords);
1589
1590                 $handle_parts = explode("@", $author);
1591                 $nick = $handle_parts[0];
1592
1593                 if($name === "")
1594                         $name = $handle_parts[0];
1595
1596                 if( preg_match("|^https?://|", $image_url) === 0)
1597                         $image_url = "http://".$handle_parts[1].$image_url;
1598
1599                 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1600
1601                 // Generic birthday. We don't know the timezone. The year is irrelevant.
1602
1603                 $birthday = str_replace("1000", "1901", $birthday);
1604
1605                 if ($birthday != "")
1606                         $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1607
1608                 // this is to prevent multiple birthday notifications in a single year
1609                 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1610
1611                 if(substr($birthday,5) === substr($contact["bd"],5))
1612                         $birthday = $contact["bd"];
1613
1614                 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1615                                 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1616                         dbesc($name),
1617                         dbesc($nick),
1618                         dbesc($author),
1619                         dbesc(datetime_convert()),
1620                         dbesc($birthday),
1621                         dbesc($location),
1622                         dbesc($about),
1623                         dbesc($keywords),
1624                         dbesc($gender),
1625                         intval($contact["id"]),
1626                         intval($importer["uid"])
1627                 );
1628
1629                 if ($searchable) {
1630                         poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1631                                 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1632                 }
1633
1634                 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1635                                         "photo" => $image_url, "name" => $name, "location" => $location,
1636                                         "about" => $about, "birthday" => $birthday, "gender" => $gender,
1637                                         "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1638                                         "hide" => !$searchable, "nsfw" => $nsfw);
1639
1640                 update_gcontact($gcontact);
1641
1642                 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1643
1644                 return true;
1645         }
1646
1647         /**
1648          * @brief 
1649          *
1650          * @param array $importer Array of the importer user
1651          * @param array $contact The contact that is checked
1652          *
1653          * @return 
1654          */
1655         private function receive_request_make_friend($importer, $contact) {
1656
1657                 $a = get_app();
1658
1659                 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1660                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1661                                 intval(CONTACT_IS_FRIEND),
1662                                 intval($contact["id"]),
1663                                 intval($importer["uid"])
1664                         );
1665                 }
1666                 // send notification
1667
1668                 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1669                         intval($importer["uid"])
1670                 );
1671
1672                 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1673
1674                         $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1675                                 intval($importer["uid"])
1676                         );
1677
1678                         // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1679
1680                         if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1681
1682                                 $arr = array();
1683                                 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1684                                 $arr["uid"] = $importer["uid"];
1685                                 $arr["contact-id"] = $self[0]["id"];
1686                                 $arr["wall"] = 1;
1687                                 $arr["type"] = 'wall';
1688                                 $arr["gravity"] = 0;
1689                                 $arr["origin"] = 1;
1690                                 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1691                                 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1692                                 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1693                                 $arr["verb"] = ACTIVITY_FRIEND;
1694                                 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1695
1696                                 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1697                                 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1698                                 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1699                                 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1700
1701                                 $arr["object"] = "<object><type>".ACTIVITY_OBJ_PERSON."</type><title>".$contact["name"]."</title>"
1702                                         ."<id>".$contact["url"]."/".$contact["name"]."</id>";
1703                                 $arr["object"] .= "<link>".xmlify('<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n");
1704                                 $arr["object"] .= xmlify('<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n");
1705                                 $arr["object"] .= "</link></object>\n";
1706                                 $arr["last-child"] = 1;
1707
1708                                 $arr["allow_cid"] = $user[0]["allow_cid"];
1709                                 $arr["allow_gid"] = $user[0]["allow_gid"];
1710                                 $arr["deny_cid"]  = $user[0]["deny_cid"];
1711                                 $arr["deny_gid"]  = $user[0]["deny_gid"];
1712
1713                                 $i = item_store($arr);
1714                                 if($i)
1715                                         proc_run("php", "include/notifier.php", "activity", $i);
1716
1717                         }
1718
1719                 }
1720         }
1721
1722         /**
1723          * @brief 
1724          *
1725          * @param array $importer Array of the importer user
1726          * @param object $data The message object
1727          *
1728          * @return 
1729          */
1730         private function receive_request($importer, $data) {
1731                 $author = unxmlify($data->author);
1732                 $recipient = unxmlify($data->recipient);
1733
1734                 if (!$author || !$recipient)
1735                         return;
1736
1737                 $contact = self::contact_by_handle($importer["uid"],$author);
1738
1739                 if($contact) {
1740
1741                         // perhaps we were already sharing with this person. Now they're sharing with us.
1742                         // That makes us friends.
1743
1744                         self::receive_request_make_friend($importer, $contact);
1745                         return true;
1746                 }
1747
1748                 $ret = self::person_by_handle($author);
1749
1750                 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
1751                         logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
1752                         return false;
1753                 }
1754
1755                 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
1756
1757                 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1758                         VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
1759                         intval($importer["uid"]),
1760                         dbesc($ret["network"]),
1761                         dbesc($ret["addr"]),
1762                         datetime_convert(),
1763                         dbesc($ret["url"]),
1764                         dbesc(normalise_link($ret["url"])),
1765                         dbesc($batch),
1766                         dbesc($ret["name"]),
1767                         dbesc($ret["nick"]),
1768                         dbesc($ret["photo"]),
1769                         dbesc($ret["pubkey"]),
1770                         dbesc($ret["notify"]),
1771                         dbesc($ret["poll"]),
1772                         1,
1773                         2
1774                 );
1775
1776                 // find the contact record we just created
1777
1778                 $contact_record = self::contact_by_handle($importer["uid"],$author);
1779
1780                 if (!$contact_record) {
1781                         logger("unable to locate newly created contact record.");
1782                         return;
1783                 }
1784
1785                 $g = q("SELECT `def_gid` FROM `user` WHERE `uid` = %d LIMIT 1",
1786                         intval($importer["uid"])
1787                 );
1788
1789                 if($g && intval($g[0]["def_gid"]))
1790                         group_add_member($importer["uid"], "", $contact_record["id"], $g[0]["def_gid"]);
1791
1792                 if($importer["page-flags"] == PAGE_NORMAL) {
1793
1794                         $hash = random_string().(string)time();   // Generate a confirm_key
1795
1796                         $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
1797                                 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
1798                                 intval($importer["uid"]),
1799                                 intval($contact_record["id"]),
1800                                 0,
1801                                 0,
1802                                 dbesc(t("Sharing notification from Diaspora network")),
1803                                 dbesc($hash),
1804                                 dbesc(datetime_convert())
1805                         );
1806                 } else {
1807
1808                         // automatic friend approval
1809
1810                         update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1811
1812                         // technically they are sharing with us (CONTACT_IS_SHARING),
1813                         // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1814                         // we are going to change the relationship and make them a follower.
1815
1816                         if($importer["page-flags"] == PAGE_FREELOVE)
1817                                 $new_relation = CONTACT_IS_FRIEND;
1818                         else
1819                                 $new_relation = CONTACT_IS_FOLLOWER;
1820
1821                         $r = q("UPDATE `contact` SET `rel` = %d,
1822                                 `name-date` = '%s',
1823                                 `uri-date` = '%s',
1824                                 `blocked` = 0,
1825                                 `pending` = 0,
1826                                 `writable` = 1
1827                                 WHERE `id` = %d
1828                                 ",
1829                                 intval($new_relation),
1830                                 dbesc(datetime_convert()),
1831                                 dbesc(datetime_convert()),
1832                                 intval($contact_record["id"])
1833                         );
1834
1835                         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1836                         if($u)
1837                                 $ret = self::send_share($u[0], $contact_record);
1838                 }
1839
1840                 return true;
1841         }
1842
1843         /**
1844          * @brief 
1845          *
1846          * @param string $guid message guid
1847          * @param $orig_author
1848          * @param $author
1849          *
1850          * @return 
1851          */
1852         private function original_item($guid, $orig_author, $author) {
1853
1854                 // Do we already have this item?
1855                 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1856                                 `author-name`, `author-link`, `author-avatar`
1857                                 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1858                         dbesc($guid));
1859
1860                 if($r) {
1861                         logger("reshared message ".$guid." already exists on system.");
1862
1863                         // Maybe it is already a reshared item?
1864                         // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1865                         if (self::is_reshare($r[0]["body"], false))
1866                                 $r = array();
1867                         else
1868                                 return $r[0];
1869                 }
1870
1871                 if (!$r) {
1872                         $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
1873                         logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1874                         $item_id = self::store_by_guid($guid, $server);
1875
1876                         if (!$item_id) {
1877                                 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
1878                                 logger("2nd try: reshared message ".$guid." will be fetched from original server: ".$server);
1879                                 $item_id = self::store_by_guid($guid, $server);
1880                         }
1881
1882                         // Deactivated by now since there is a risk that someone could manipulate postings through this method
1883 /*                      if (!$item_id) {
1884                                 $server = "https://".substr($author, strpos($author, "@") + 1);
1885                                 logger("3rd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1886                                 $item_id = self::store_by_guid($guid, $server);
1887                         }
1888                         if (!$item_id) {
1889                                 $server = "http://".substr($author, strpos($author, "@") + 1);
1890                                 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1891                                 $item_id = self::store_by_guid($guid, $server);
1892                         }
1893 */
1894                         if ($item_id) {
1895                                 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1896                                                 `author-name`, `author-link`, `author-avatar`
1897                                         FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1898                                         intval($item_id));
1899
1900                                 if ($r)
1901                                         return $r[0];
1902
1903                         }
1904                 }
1905                 return false;
1906         }
1907
1908         /**
1909          * @brief 
1910          *
1911          * @param array $importer Array of the importer user
1912          * @param object $data The message object
1913          * @param string $xml The original XML of the message
1914          *
1915          * @return 
1916          */
1917         private function receive_reshare($importer, $data, $xml) {
1918                 $root_author = notags(unxmlify($data->root_author));
1919                 $root_guid = notags(unxmlify($data->root_guid));
1920                 $guid = notags(unxmlify($data->guid));
1921                 $author = notags(unxmlify($data->author));
1922                 $public = notags(unxmlify($data->public));
1923                 $created_at = notags(unxmlify($data->created_at));
1924
1925                 $contact = self::allowed_contact_by_handle($importer, $author, false);
1926                 if (!$contact)
1927                         return false;
1928
1929                 if (self::message_exists($importer["uid"], $guid))
1930                         return false;
1931
1932                 $original_item = self::original_item($root_guid, $root_author, $author);
1933                 if (!$original_item)
1934                         return false;
1935
1936                 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
1937
1938                 $datarray = array();
1939
1940                 $datarray["uid"] = $importer["uid"];
1941                 $datarray["contact-id"] = $contact["id"];
1942                 $datarray["network"]  = NETWORK_DIASPORA;
1943
1944                 $datarray["author-name"] = $contact["name"];
1945                 $datarray["author-link"] = $contact["url"];
1946                 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1947
1948                 $datarray["owner-name"] = $datarray["author-name"];
1949                 $datarray["owner-link"] = $datarray["author-link"];
1950                 $datarray["owner-avatar"] = $datarray["author-avatar"];
1951
1952                 $datarray["guid"] = $guid;
1953                 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1954
1955                 $datarray["verb"] = ACTIVITY_POST;
1956                 $datarray["gravity"] = GRAVITY_PARENT;
1957
1958                 $datarray["object"] = $xml;
1959
1960                 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
1961                                         $original_item["guid"], $original_item["created"], $orig_url);
1962                 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
1963
1964                 $datarray["tag"] = $original_item["tag"];
1965                 $datarray["app"]  = $original_item["app"];
1966
1967                 $datarray["plink"] = self::plink($author, $guid);
1968                 $datarray["private"] = (($public == "false") ? 1 : 0);
1969                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1970
1971                 $datarray["object-type"] = $original_item["object-type"];
1972
1973                 self::fetch_guid($datarray);
1974                 $message_id = item_store($datarray);
1975
1976                 if ($message_id)
1977                         logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1978
1979                 return $message_id;
1980         }
1981
1982         /**
1983          * @brief 
1984          *
1985          * @param array $importer Array of the importer user
1986          * @param array $contact The contact that is checked
1987          * @param object $data The message object
1988          *
1989          * @return 
1990          */
1991         private function item_retraction($importer, $contact, $data) {
1992                 $target_type = notags(unxmlify($data->target_type));
1993                 $target_guid = notags(unxmlify($data->target_guid));
1994                 $author = notags(unxmlify($data->author));
1995
1996                 $person = self::person_by_handle($author);
1997                 if (!is_array($person)) {
1998                         logger("unable to find author detail for ".$author);
1999                         return false;
2000                 }
2001
2002                 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2003                         dbesc($target_guid),
2004                         intval($importer["uid"])
2005                 );
2006                 if (!$r)
2007                         return false;
2008
2009                 // Only delete it if the author really fits
2010                 if (!link_compare($r[0]["author-link"], $person["url"])) {
2011                         logger("Item author ".$r[0]["author-link"]." doesn't fit to expected contact ".$person["url"], LOGGER_DEBUG);
2012                         return false;
2013                 }
2014
2015                 // Check if the sender is the thread owner
2016                 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2017                         intval($r[0]["parent"]));
2018
2019                 // Only delete it if the parent author really fits
2020                 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
2021                         logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2022                         return false;
2023                 }
2024
2025                 // 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
2026                 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
2027                         dbesc(datetime_convert()),
2028                         dbesc(datetime_convert()),
2029                         intval($r[0]["id"])
2030                 );
2031                 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2032
2033                 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2034
2035                 // Now check if the retraction needs to be relayed by us
2036                 if($p[0]["origin"]) {
2037                         // notify others
2038                         proc_run("php", "include/notifier.php", "drop", $r[0]["id"]);
2039                 }
2040         }
2041
2042         /**
2043          * @brief 
2044          *
2045          * @param array $importer Array of the importer user
2046          * @param string $sender The sender of the message
2047          * @param object $data The message object
2048          *
2049          * @return 
2050          */
2051         private function receive_retraction($importer, $sender, $data) {
2052                 $target_type = notags(unxmlify($data->target_type));
2053
2054                 $contact = self::contact_by_handle($importer["uid"], $sender);
2055                 if (!$contact) {
2056                         logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2057                         return false;
2058                 }
2059
2060                 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2061
2062                 switch ($target_type) {
2063                         case "Comment":
2064                         case "Like":
2065                         case "Post": // "Post" will be supported in a future version
2066                         case "Reshare":
2067                         case "StatusMessage":
2068                                 return self::item_retraction($importer, $contact, $data);;
2069
2070                         case "Person":
2071                                 /// @todo What should we do with an "unshare"?
2072                                 // Removing the contact isn't correct since we still can read the public items
2073                                 //contact_remove($contact["id"]);
2074                                 return true;
2075
2076                         default:
2077                                 logger("Unknown target type ".$target_type);
2078                                 return false;
2079                 }
2080                 return true;
2081         }
2082
2083         /**
2084          * @brief 
2085          *
2086          * @param array $importer Array of the importer user
2087          * @param object $data The message object
2088          * @param string $xml The original XML of the message
2089          *
2090          * @return 
2091          */
2092         private function receive_status_message($importer, $data, $xml) {
2093
2094                 $raw_message = unxmlify($data->raw_message);
2095                 $guid = notags(unxmlify($data->guid));
2096                 $author = notags(unxmlify($data->author));
2097                 $public = notags(unxmlify($data->public));
2098                 $created_at = notags(unxmlify($data->created_at));
2099                 $provider_display_name = notags(unxmlify($data->provider_display_name));
2100
2101                 /// @todo enable support for polls
2102                 //if ($data->poll) {
2103                 //      foreach ($data->poll AS $poll)
2104                 //              print_r($poll);
2105                 //      die("poll!\n");
2106                 //}
2107                 $contact = self::allowed_contact_by_handle($importer, $author, false);
2108                 if (!$contact)
2109                         return false;
2110
2111                 if (self::message_exists($importer["uid"], $guid))
2112                         return false;
2113
2114                 $address = array();
2115                 if ($data->location)
2116                         foreach ($data->location->children() AS $fieldname => $data)
2117                                 $address[$fieldname] = notags(unxmlify($data));
2118
2119                 $body = diaspora2bb($raw_message);
2120
2121                 $datarray = array();
2122
2123                 if ($data->photo) {
2124                         foreach ($data->photo AS $photo)
2125                                 $body = "[img]".unxmlify($photo->remote_photo_path).
2126                                         unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2127
2128                         $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
2129                 } else {
2130                         $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2131
2132                         // Add OEmbed and other information to the body
2133                         if (!self::is_redmatrix($contact["url"]))
2134                                 $body = add_page_info_to_body($body, false, true);
2135                 }
2136
2137                 $datarray["uid"] = $importer["uid"];
2138                 $datarray["contact-id"] = $contact["id"];
2139                 $datarray["network"] = NETWORK_DIASPORA;
2140
2141                 $datarray["author-name"] = $contact["name"];
2142                 $datarray["author-link"] = $contact["url"];
2143                 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2144
2145                 $datarray["owner-name"] = $datarray["author-name"];
2146                 $datarray["owner-link"] = $datarray["author-link"];
2147                 $datarray["owner-avatar"] = $datarray["author-avatar"];
2148
2149                 $datarray["guid"] = $guid;
2150                 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
2151
2152                 $datarray["verb"] = ACTIVITY_POST;
2153                 $datarray["gravity"] = GRAVITY_PARENT;
2154
2155                 $datarray["object"] = $xml;
2156
2157                 $datarray["body"] = $body;
2158
2159                 if ($provider_display_name != "")
2160                         $datarray["app"] = $provider_display_name;
2161
2162                 $datarray["plink"] = self::plink($author, $guid);
2163                 $datarray["private"] = (($public == "false") ? 1 : 0);
2164                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
2165
2166                 if (isset($address["address"]))
2167                         $datarray["location"] = $address["address"];
2168
2169                 if (isset($address["lat"]) AND isset($address["lng"]))
2170                         $datarray["coord"] = $address["lat"]." ".$address["lng"];
2171
2172                 self::fetch_guid($datarray);
2173                 $message_id = item_store($datarray);
2174
2175                 if ($message_id)
2176                         logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2177
2178                 return $message_id;
2179         }
2180
2181         /******************************************************************************************
2182          * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2183          ******************************************************************************************/
2184
2185         /**
2186          * @brief 
2187          *
2188          * @param $me
2189          *
2190          * @return 
2191          */
2192         private function my_handle($me) {
2193                 if ($contact["addr"] != "")
2194                         return $contact["addr"];
2195
2196                 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2197                 // So - just in case - we build the the address here.
2198                 return $me["nickname"]."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
2199         }
2200
2201         /**
2202          * @brief 
2203          *
2204          * @param $msg
2205          * @param $user
2206          * @param array $contact The contact that is checked
2207          * @param $prvkey
2208          * @param $pubkey
2209          *
2210          * @return 
2211          */
2212         private function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
2213
2214                 logger("Message: ".$msg, LOGGER_DATA);
2215
2216                 $handle = self::my_handle($user);
2217
2218                 $b64url_data = base64url_encode($msg);
2219
2220                 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2221
2222                 $type = "application/xml";
2223                 $encoding = "base64url";
2224                 $alg = "RSA-SHA256";
2225
2226                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2227
2228                 $signature = rsa_sign($signable_data,$prvkey);
2229                 $sig = base64url_encode($signature);
2230
2231                 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
2232                                                 "me:env" => array("me:encoding" => "base64url",
2233                                                                 "me:alg" => "RSA-SHA256",
2234                                                                 "me:data" => $data,
2235                                                                 "@attributes" => array("type" => "application/xml"),
2236                                                                 "me:sig" => $sig)));
2237
2238                 $namespaces = array("" => "https://joindiaspora.com/protocol",
2239                                 "me" => "http://salmon-protocol.org/ns/magic-env");
2240
2241                 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2242
2243                 logger("magic_env: ".$magic_env, LOGGER_DATA);
2244                 return $magic_env;
2245         }
2246
2247         /**
2248          * @brief 
2249          *
2250          * @param $msg
2251          * @param $user
2252          * @param array $contact The contact that is checked
2253          * @param $prvkey
2254          * @param $pubkey
2255          *
2256          * @return 
2257          */
2258         private function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
2259
2260                 logger("Message: ".$msg, LOGGER_DATA);
2261
2262                 // without a public key nothing will work
2263
2264                 if (!$pubkey) {
2265                         logger("pubkey missing: contact id: ".$contact["id"]);
2266                         return false;
2267                 }
2268
2269                 $inner_aes_key = random_string(32);
2270                 $b_inner_aes_key = base64_encode($inner_aes_key);
2271                 $inner_iv = random_string(16);
2272                 $b_inner_iv = base64_encode($inner_iv);
2273
2274                 $outer_aes_key = random_string(32);
2275                 $b_outer_aes_key = base64_encode($outer_aes_key);
2276                 $outer_iv = random_string(16);
2277                 $b_outer_iv = base64_encode($outer_iv);
2278
2279                 $handle = self::my_handle($user);
2280
2281                 $padded_data = pkcs5_pad($msg,16);
2282                 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
2283
2284                 $b64_data = base64_encode($inner_encrypted);
2285
2286
2287                 $b64url_data = base64url_encode($b64_data);
2288                 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2289
2290                 $type = "application/xml";
2291                 $encoding = "base64url";
2292                 $alg = "RSA-SHA256";
2293
2294                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2295
2296                 $signature = rsa_sign($signable_data,$prvkey);
2297                 $sig = base64url_encode($signature);
2298
2299                 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
2300                                                         "aes_key" => $b_inner_aes_key,
2301                                                         "author_id" => $handle));
2302
2303                 $decrypted_header = xml::from_array($xmldata, $xml, true);
2304                 $decrypted_header = pkcs5_pad($decrypted_header,16);
2305
2306                 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
2307
2308                 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
2309
2310                 $encrypted_outer_key_bundle = "";
2311                 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2312
2313                 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2314
2315                 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2316
2317                 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2318                                                                 "ciphertext" => base64_encode($ciphertext)));
2319                 $cipher_json = base64_encode($encrypted_header_json_object);
2320
2321                 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2322                                                 "me:env" => array("me:encoding" => "base64url",
2323                                                                 "me:alg" => "RSA-SHA256",
2324                                                                 "me:data" => $data,
2325                                                                 "@attributes" => array("type" => "application/xml"),
2326                                                                 "me:sig" => $sig)));
2327
2328                 $namespaces = array("" => "https://joindiaspora.com/protocol",
2329                                 "me" => "http://salmon-protocol.org/ns/magic-env");
2330
2331                 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2332
2333                 logger("magic_env: ".$magic_env, LOGGER_DATA);
2334                 return $magic_env;
2335         }
2336
2337         /**
2338          * @brief 
2339          *
2340          * @param $msg
2341          * @param $user
2342          * @param array $contact The contact that is checked
2343          * @param $prvkey
2344          * @param $pubkey
2345          * @param $public
2346          *
2347          * @return 
2348          */
2349         private function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2350
2351                 if ($public)
2352                         $magic_env =  self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2353                 else
2354                         $magic_env =  self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2355
2356                 // The data that will be transmitted is double encoded via "urlencode", strange ...
2357                 $slap = "xml=".urlencode(urlencode($magic_env));
2358                 return $slap;
2359         }
2360
2361         /**
2362          * @brief 
2363          *
2364          * @param array $owner the array of the item owner
2365          * @param $message
2366          *
2367          * @return 
2368          */
2369         private function signature($owner, $message) {
2370                 $sigmsg = $message;
2371                 unset($sigmsg["author_signature"]);
2372                 unset($sigmsg["parent_author_signature"]);
2373
2374                 $signed_text = implode(";", $sigmsg);
2375
2376                 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2377         }
2378
2379         /**
2380          * @brief 
2381          *
2382          * @param array $owner the array of the item owner
2383          * @param array $contact The contact that is checked
2384          * @param $slap
2385          * @param bool $public_batch Is it a public post?
2386          * @param $queue_run
2387          * @param string $guid message guid
2388          *
2389          * @return 
2390          */
2391         public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2392
2393                 $a = get_app();
2394
2395                 $enabled = intval(get_config("system", "diaspora_enabled"));
2396                 if(!$enabled)
2397                         return 200;
2398
2399                 $logid = random_string(4);
2400                 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2401                 if (!$dest_url) {
2402                         logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2403                         return 0;
2404                 }
2405
2406                 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2407
2408                 if (!$queue_run && was_recently_delayed($contact["id"])) {
2409                         $return_code = 0;
2410                 } else {
2411                         if (!intval(get_config("system", "diaspora_test"))) {
2412                                 post_url($dest_url."/", $slap);
2413                                 $return_code = $a->get_curl_code();
2414                         } else {
2415                                 logger("test_mode");
2416                                 return 200;
2417                         }
2418                 }
2419
2420                 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2421
2422                 if(!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2423                         logger("queue message");
2424
2425                         $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2426                                 intval($contact["id"]),
2427                                 dbesc(NETWORK_DIASPORA),
2428                                 dbesc($slap),
2429                                 intval($public_batch)
2430                         );
2431                         if($r) {
2432                                 logger("add_to_queue ignored - identical item already in queue");
2433                         } else {
2434                                 // queue message for redelivery
2435                                 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2436                         }
2437                 }
2438
2439                 return(($return_code) ? $return_code : (-1));
2440         }
2441
2442
2443         /**
2444          * @brief 
2445          *
2446          * @param array $owner the array of the item owner
2447          * @param array $contact The contact that is checked
2448          * @param $type
2449          * @param $message
2450          * @param bool $public_batch Is it a public post?
2451          * @param string $guid message guid
2452          * @param $spool
2453          *
2454          * @return 
2455          */
2456         private function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2457
2458                 $data = array("XML" => array("post" => array($type => $message)));
2459
2460                 $msg = xml::from_array($data, $xml);
2461
2462                 logger('message: '.$msg, LOGGER_DATA);
2463                 logger('send guid '.$guid, LOGGER_DEBUG);
2464
2465                 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2466
2467                 if ($spool) {
2468                         add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2469                         return true;
2470                 } else
2471                         $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2472
2473                 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2474
2475                 return $return_code;
2476         }
2477
2478         /**
2479          * @brief 
2480          *
2481          * @param array $owner the array of the item owner
2482          * @param array $contact The contact that is checked
2483          *
2484          * @return int The result of the transmission
2485          */
2486         public static function send_share($owner,$contact) {
2487
2488                 $message = array("sender_handle" => self::my_handle($owner),
2489                                 "recipient_handle" => $contact["addr"]);
2490
2491                 return self::build_and_transmit($owner, $contact, "request", $message);
2492         }
2493
2494         /**
2495          * @brief 
2496          *
2497          * @param array $owner the array of the item owner
2498          * @param array $contact The contact that is checked
2499          *
2500          * @return int The result of the transmission
2501          */
2502         public static function send_unshare($owner,$contact) {
2503
2504                 $message = array("post_guid" => $owner["guid"],
2505                                 "diaspora_handle" => self::my_handle($owner),
2506                                 "type" => "Person");
2507
2508                 return self::build_and_transmit($owner, $contact, "retraction", $message);
2509         }
2510
2511         /**
2512          * @brief 
2513          *
2514          * @param $body
2515          * @param $complete
2516          *
2517          * @return 
2518          */
2519         public static function is_reshare($body, $complete = true) {
2520                 $body = trim($body);
2521
2522                 // Skip if it isn't a pure repeated messages
2523                 // Does it start with a share?
2524                 if (strpos($body, "[share") > 0)
2525                         return(false);
2526
2527                 // Does it end with a share?
2528                 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2529                         return(false);
2530
2531                 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2532                 // Skip if there is no shared message in there
2533                 if ($body == $attributes)
2534                         return(false);
2535
2536                 // If we don't do the complete check we quit here
2537                 if (!$complete)
2538                         return true;
2539
2540                 $guid = "";
2541                 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2542                 if ($matches[1] != "")
2543                         $guid = $matches[1];
2544
2545                 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2546                 if ($matches[1] != "")
2547                         $guid = $matches[1];
2548
2549                 if ($guid != "") {
2550                         $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2551                                 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2552                         if ($r) {
2553                                 $ret= array();
2554                                 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2555                                 $ret["root_guid"] = $guid;
2556                                 return($ret);
2557                         }
2558                 }
2559
2560                 $profile = "";
2561                 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2562                 if ($matches[1] != "")
2563                         $profile = $matches[1];
2564
2565                 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2566                 if ($matches[1] != "")
2567                         $profile = $matches[1];
2568
2569                 $ret= array();
2570
2571                 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2572                 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2573                         return(false);
2574
2575                 $link = "";
2576                 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2577                 if ($matches[1] != "")
2578                         $link = $matches[1];
2579
2580                 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2581                 if ($matches[1] != "")
2582                         $link = $matches[1];
2583
2584                 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2585                 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2586                         return(false);
2587                 return($ret);
2588         }
2589
2590         /**
2591          * @brief 
2592          *
2593          * @param array $item The item that will be exported
2594          * @param array $owner the array of the item owner
2595          * @param array $contact The contact that is checked
2596          * @param bool $public_batch Is it a public post?
2597          *
2598          * @return int The result of the transmission
2599          */
2600         public static function send_status($item, $owner, $contact, $public_batch = false) {
2601
2602                 $myaddr = self::my_handle($owner);
2603
2604                 $public = (($item["private"]) ? "false" : "true");
2605
2606                 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2607
2608                 // Detect a share element and do a reshare
2609                 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
2610                         $message = array("root_diaspora_id" => $ret["root_handle"],
2611                                         "root_guid" => $ret["root_guid"],
2612                                         "guid" => $item["guid"],
2613                                         "diaspora_handle" => $myaddr,
2614                                         "public" => $public,
2615                                         "created_at" => $created,
2616                                         "provider_display_name" => $item["app"]);
2617
2618                         $type = "reshare";
2619                 } else {
2620                         $title = $item["title"];
2621                         $body = $item["body"];
2622
2623                         // convert to markdown
2624                         $body = html_entity_decode(bb2diaspora($body));
2625
2626                         // Adding the title
2627                         if(strlen($title))
2628                                 $body = "## ".html_entity_decode($title)."\n\n".$body;
2629
2630                         if ($item["attach"]) {
2631                                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
2632                                 if(cnt) {
2633                                         $body .= "\n".t("Attachments:")."\n";
2634                                         foreach($matches as $mtch)
2635                                                 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
2636                                 }
2637                         }
2638
2639                         $location = array();
2640
2641                         if ($item["location"] != "")
2642                                 $location["address"] = $item["location"];
2643
2644                         if ($item["coord"] != "") {
2645                                 $coord = explode(" ", $item["coord"]);
2646                                 $location["lat"] = $coord[0];
2647                                 $location["lng"] = $coord[1];
2648                         }
2649
2650                         $message = array("raw_message" => $body,
2651                                         "location" => $location,
2652                                         "guid" => $item["guid"],
2653                                         "diaspora_handle" => $myaddr,
2654                                         "public" => $public,
2655                                         "created_at" => $created,
2656                                         "provider_display_name" => $item["app"]);
2657
2658                         if (count($location) == 0)
2659                                 unset($message["location"]);
2660
2661                         $type = "status_message";
2662                 }
2663
2664                 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2665         }
2666
2667         /**
2668          * @brief 
2669          *
2670          * @param array $item The item that will be exported
2671          * @param array $owner the array of the item owner
2672          *
2673          * @return 
2674          */
2675         private function construct_like($item, $owner) {
2676
2677                 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
2678                         dbesc($item["thr-parent"]));
2679                 if(!$p)
2680                         return false;
2681
2682                 $parent = $p[0];
2683
2684                 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
2685                 $positive = "true";
2686
2687                 return(array("positive" => $positive,
2688                                 "guid" => $item["guid"],
2689                                 "target_type" => $target_type,
2690                                 "parent_guid" => $parent["guid"],
2691                                 "author_signature" => $authorsig,
2692                                 "diaspora_handle" => self::my_handle($owner)));
2693         }
2694
2695         /**
2696          * @brief 
2697          *
2698          * @param array $item The item that will be exported
2699          * @param array $owner the array of the item owner
2700          *
2701          * @return 
2702          */
2703         private function construct_comment($item, $owner) {
2704
2705                 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2706                         intval($item["parent"]),
2707                         intval($item["parent"])
2708                 );
2709
2710                 if (!$p)
2711                         return false;
2712
2713                 $parent = $p[0];
2714
2715                 $text = html_entity_decode(bb2diaspora($item["body"]));
2716
2717                 return(array("guid" => $item["guid"],
2718                                 "parent_guid" => $parent["guid"],
2719                                 "author_signature" => "",
2720                                 "text" => $text,
2721                                 "diaspora_handle" => self::my_handle($owner)));
2722         }
2723
2724         /**
2725          * @brief Send a like or a comment
2726          *
2727          * @param array $item The item that will be exported
2728          * @param array $owner the array of the item owner
2729          * @param array $contact The contact that is checked
2730          * @param bool $public_batch Is it a public post?
2731          *
2732          * @return int The result of the transmission
2733          */
2734         public static function send_followup($item,$owner,$contact,$public_batch = false) {
2735
2736                 if($item['verb'] === ACTIVITY_LIKE) {
2737                         $message = self::construct_like($item, $owner);
2738                         $type = "like";
2739                 } else {
2740                         $message = self::construct_comment($item, $owner);
2741                         $type = "comment";
2742                 }
2743
2744                 if (!$message)
2745                         return false;
2746
2747                 $message["author_signature"] = self::signature($owner, $message);
2748
2749                 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2750         }
2751
2752         /**
2753          * @brief 
2754          *
2755          * @param array $item The item that will be exported
2756          * @param $signature
2757          *
2758          * @return int The result of the transmission
2759          */
2760         private function message_from_signatur($item, $signature) {
2761
2762                 // Split the signed text
2763                 $signed_parts = explode(";", $signature['signed_text']);
2764
2765                 if ($item["deleted"])
2766                         $message = array("parent_author_signature" => "",
2767                                         "target_guid" => $signed_parts[0],
2768                                         "target_type" => $signed_parts[1],
2769                                         "sender_handle" => $signature['signer'],
2770                                         "target_author_signature" => $signature['signature']);
2771                 elseif ($item['verb'] === ACTIVITY_LIKE)
2772                         $message = array("positive" => $signed_parts[0],
2773                                         "guid" => $signed_parts[1],
2774                                         "target_type" => $signed_parts[2],
2775                                         "parent_guid" => $signed_parts[3],
2776                                         "parent_author_signature" => "",
2777                                         "author_signature" => $signature['signature'],
2778                                         "diaspora_handle" => $signed_parts[4]);
2779                 else {
2780                         // Remove the comment guid
2781                         $guid = array_shift($signed_parts);
2782
2783                         // Remove the parent guid
2784                         $parent_guid = array_shift($signed_parts);
2785
2786                         // Remove the handle
2787                         $handle = array_pop($signed_parts);
2788
2789                         // Glue the parts together
2790                         $text = implode(";", $signed_parts);
2791
2792                         $message = array("guid" => $guid,
2793                                         "parent_guid" => $parent_guid,
2794                                         "parent_author_signature" => "",
2795                                         "author_signature" => $signature['signature'],
2796                                         "text" => implode(";", $signed_parts),
2797                                         "diaspora_handle" => $handle);
2798                 }
2799                 return $message;
2800         }
2801
2802         /**
2803          * @brief 
2804          *
2805          * @param array $item The item that will be exported
2806          * @param array $owner the array of the item owner
2807          * @param array $contact The contact that is checked
2808          * @param bool $public_batch Is it a public post?
2809          *
2810          * @return int The result of the transmission
2811          */
2812         public static function send_relay($item, $owner, $contact, $public_batch = false) {
2813
2814                 if ($item["deleted"])
2815                         return self::send_retraction($item, $owner, $contact, $public_batch, true);
2816                 elseif ($item['verb'] === ACTIVITY_LIKE)
2817                         $type = "like";
2818                 else
2819                         $type = "comment";
2820
2821                 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2822
2823                 // fetch the original signature
2824
2825                 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
2826                         intval($item["id"]));
2827
2828                 if (!$r) {
2829                         logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2830                         return false;
2831                 }
2832
2833                 $signature = $r[0];
2834
2835                 // Old way - is used by the internal Friendica functions
2836                 /// @todo Change all signatur storing functions to the new format
2837                 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
2838                         $message = self::message_from_signatur($item, $signature);
2839                 else {// New way
2840                         $msg = json_decode($signature['signed_text'], true);
2841
2842                         $message = array();
2843                         if (is_array($msg)) {
2844                                 foreach ($msg AS $field => $data) {
2845                                         if (!$item["deleted"]) {
2846                                                 if ($field == "author")
2847                                                         $field = "diaspora_handle";
2848                                                 if ($field == "parent_type")
2849                                                         $field = "target_type";
2850                                         }
2851
2852                                         $message[$field] = $data;
2853                                 }
2854                         } else
2855                                 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
2856                 }
2857
2858                 $message["parent_author_signature"] = self::signature($owner, $message);
2859
2860                 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
2861
2862                 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2863         }
2864
2865         /**
2866          * @brief 
2867          *
2868          * @param array $item The item that will be exported
2869          * @param array $owner the array of the item owner
2870          * @param array $contact The contact that is checked
2871          * @param bool $public_batch Is it a public post?
2872          * @param $relay
2873          *
2874          * @return int The result of the transmission
2875          */
2876         public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
2877
2878                 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
2879
2880                 // Check whether the retraction is for a top-level post or whether it's a relayable
2881                 if ($item["uri"] !== $item["parent-uri"]) {
2882                         $msg_type = "relayable_retraction";
2883                         $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
2884                 } else {
2885                         $msg_type = "signed_retraction";
2886                         $target_type = "StatusMessage";
2887                 }
2888
2889                 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
2890                         $signature = "parent_author_signature";
2891                 else
2892                         $signature = "target_author_signature";
2893
2894                 $signed_text = $item["guid"].";".$target_type;
2895
2896                 $message = array("target_guid" => $item['guid'],
2897                                 "target_type" => $target_type,
2898                                 "sender_handle" => $itemaddr,
2899                                 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
2900
2901                 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
2902
2903                 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
2904         }
2905
2906         /**
2907          * @brief 
2908          *
2909          * @param array $item The item that will be exported
2910          * @param array $owner The owner
2911          * @param array $contact The contact that is checked
2912          *
2913          * @return int The result of the transmission
2914          */
2915         public static function send_mail($item, $owner, $contact) {
2916
2917                 $myaddr = self::my_handle($owner);
2918
2919                 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2920                         intval($item["convid"]),
2921                         intval($item["uid"])
2922                 );
2923
2924                 if (!$r) {
2925                         logger("conversation not found.");
2926                         return;
2927                 }
2928                 $cnv = $r[0];
2929
2930                 $conv = array(
2931                         "guid" => $cnv["guid"],
2932                         "subject" => $cnv["subject"],
2933                         "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2934                         "diaspora_handle" => $cnv["creator"],
2935                         "participant_handles" => $cnv["recips"]
2936                 );
2937
2938                 $body = bb2diaspora($item["body"]);
2939                 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2940
2941                 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
2942                 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2943
2944                 $msg = array(
2945                         "guid" => $item["guid"],
2946                         "parent_guid" => $cnv["guid"],
2947                         "parent_author_signature" => $sig,
2948                         "author_signature" => $sig,
2949                         "text" => $body,
2950                         "created_at" => $created,
2951                         "diaspora_handle" => $myaddr,
2952                         "conversation_guid" => $cnv["guid"]
2953                 );
2954
2955                 if ($item["reply"]) {
2956                         $message = $msg;
2957                         $type = "message";
2958                 } else {
2959                         $message = array("guid" => $cnv["guid"],
2960                                         "subject" => $cnv["subject"],
2961                                         "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2962                                         "message" => $msg,
2963                                         "diaspora_handle" => $cnv["creator"],
2964                                         "participant_handles" => $cnv["recips"]);
2965
2966                         $type = "conversation";
2967                 }
2968
2969                 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
2970         }
2971
2972         /**
2973          * @brief 
2974          *
2975          * @param int $uid The user id
2976          *
2977          * @return int The result of the transmission
2978          */
2979         public static function send_profile($uid) {
2980
2981                 if (!$uid)
2982                         return;
2983
2984                 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
2985                         AND `uid` = %d AND `rel` != %d",
2986                         dbesc(NETWORK_DIASPORA),
2987                         intval($uid),
2988                         intval(CONTACT_IS_SHARING)
2989                 );
2990                 if (!$recips)
2991                         return;
2992
2993                 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
2994                         FROM `profile`
2995                         INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
2996                         INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
2997                         WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
2998                         intval($uid)
2999                 );
3000
3001                 if (!$r)
3002                         return;
3003
3004                 $profile = $r[0];
3005
3006                 $handle = $profile["addr"];
3007                 $first = ((strpos($profile['name'],' ')
3008                         ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3009                 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3010                 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3011                 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3012                 $small = App::get_baseurl().'/photo/custom/50/'  .$profile['uid'].'.jpg';
3013                 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3014
3015                 if ($searchable === 'true') {
3016                         $dob = '1000-00-00';
3017
3018                         if (($profile['dob']) && ($profile['dob'] != '0000-00-00'))
3019                                 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3020
3021                         $about = $profile['about'];
3022                         $about = strip_tags(bbcode($about));
3023
3024                         $location = formatted_location($profile);
3025                         $tags = '';
3026                         if ($profile['pub_keywords']) {
3027                                 $kw = str_replace(',',' ',$profile['pub_keywords']);
3028                                 $kw = str_replace('  ',' ',$kw);
3029                                 $arr = explode(' ',$profile['pub_keywords']);
3030                                 if (count($arr)) {
3031                                         for($x = 0; $x < 5; $x ++) {
3032                                                 if (trim($arr[$x]))
3033                                                         $tags .= '#'. trim($arr[$x]) .' ';
3034                                         }
3035                                 }
3036                         }
3037                         $tags = trim($tags);
3038                 }
3039
3040                 $message = array("diaspora_handle" => $handle,
3041                                 "first_name" => $first,
3042                                 "last_name" => $last,
3043                                 "image_url" => $large,
3044                                 "image_url_medium" => $medium,
3045                                 "image_url_small" => $small,
3046                                 "birthday" => $dob,
3047                                 "gender" => $profile['gender'],
3048                                 "bio" => $about,
3049                                 "location" => $location,
3050                                 "searchable" => $searchable,
3051                                 "tag_string" => $tags);
3052
3053                 foreach($recips as $recip)
3054                         self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3055         }
3056 }
3057 ?>