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