]> git.mxchange.org Git - friendica.git/blob - include/diaspora2.php
Some code cleaning, changes to the xml generation
[friendica.git] / include / diaspora2.php
1 <?php
2 /**
3  * @file include/diaspora.php
4  * @brief The implementation of the diaspora protocol
5  */
6
7 require_once("include/items.php");
8 require_once("include/bb2diaspora.php");
9 require_once("include/Scrape.php");
10 require_once("include/Contact.php");
11 require_once("include/Photo.php");
12 require_once("include/socgraph.php");
13 require_once("include/group.php");
14 require_once("include/xml.php");
15 require_once("include/datetime.php");
16
17 /**
18  * @brief This class contain functions to create and send Diaspora XML files
19  *
20  */
21 class diaspora {
22
23         public static function relay_list() {
24
25                 $serverdata = get_config("system", "relay_server");
26                 if ($serverdata == "")
27                         return array();
28
29                 $relay = array();
30
31                 $servers = explode(",", $serverdata);
32
33                 foreach($servers AS $server) {
34                         $server = trim($server);
35                         $batch = $server."/receive/public";
36
37                         $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
38
39                         if (!$relais) {
40                                 $addr = "relay@".str_replace("http://", "", normalise_link($server));
41
42                                 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
43                                         VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
44                                         datetime_convert(),
45                                         dbesc($addr),
46                                         dbesc($addr),
47                                         dbesc($server),
48                                         dbesc(normalise_link($server)),
49                                         dbesc($batch),
50                                         dbesc(NETWORK_DIASPORA),
51                                         intval(CONTACT_IS_FOLLOWER),
52                                         dbesc(datetime_convert()),
53                                         dbesc(datetime_convert()),
54                                         dbesc(datetime_convert())
55                                 );
56
57                                 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
58                                 if ($relais)
59                                         $relay[] = $relais[0];
60                         } else
61                                 $relay[] = $relais[0];
62                 }
63
64                 return $relay;
65         }
66
67         /**
68          * @brief Dispatches public messages and find the fitting receivers
69          *
70          * @param array $msg The post that will be dispatched
71          *
72          * @return bool Was the message accepted?
73          */
74         public static function dispatch_public($msg) {
75
76                 $enabled = intval(get_config("system", "diaspora_enabled"));
77                 if (!$enabled) {
78                         logger("diaspora is disabled");
79                         return false;
80                 }
81
82                 // Use a dummy importer to import the data for the public copy
83                 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
84                 $item_id = self::dispatch($importer,$msg);
85
86                 // Now distribute it to the followers
87                 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
88                         (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
89                         AND NOT `account_expired` AND NOT `account_removed`",
90                         dbesc(NETWORK_DIASPORA),
91                         dbesc($msg["author"])
92                 );
93                 if($r) {
94                         foreach($r as $rr) {
95                                 logger("delivering to: ".$rr["username"]);
96                                 self::dispatch($rr,$msg);
97                         }
98                 } else
99                         logger("No subscribers for ".$msg["author"]." ".print_r($msg, true));
100
101                 return $item_id;
102         }
103
104         /**
105          * @brief Dispatches the different message types to the different functions
106          *
107          * @param array $importer Array of the importer user
108          * @param array $msg The post that will be dispatched
109          *
110          * @return bool Was the message accepted?
111          */
112         public static function dispatch($importer, $msg) {
113
114                 // The sender is the handle of the contact that sent the message.
115                 // This will often be different with relayed messages (for example "like" and "comment")
116                 $sender = $msg["author"];
117
118                 if (!diaspora::valid_posting($msg, $fields)) {
119                         logger("Invalid posting");
120                         return false;
121                 }
122
123                 $type = $fields->getName();
124
125                 switch ($type) {
126                         case "account_deletion":
127                                 return self::receive_account_deletion($importer, $fields);
128
129                         case "comment":
130                                 return self::receive_comment($importer, $sender, $fields);
131
132                         case "conversation":
133                                 return self::receive_conversation($importer, $msg, $fields);
134
135                         case "like":
136                                 return self::receive_like($importer, $sender, $fields);
137
138                         case "message":
139                                 return self::receive_message($importer, $fields);
140
141                         case "participation": // Not implemented
142                                 return self::receive_participation($importer, $fields);
143
144                         case "photo": // Not implemented
145                                 return self::receive_photo($importer, $fields);
146
147                         case "poll_participation": // Not implemented
148                                 return self::receive_poll_participation($importer, $fields);
149
150                         case "profile":
151                                 return self::receive_profile($importer, $fields);
152
153                         case "request":
154                                 return self::receive_request($importer, $fields);
155
156                         case "reshare":
157                                 return self::receive_reshare($importer, $fields);
158
159                         case "retraction":
160                                 return self::receive_retraction($importer, $sender, $fields);
161
162                         case "status_message":
163                                 return self::receive_status_message($importer, $fields);
164
165                         default:
166                                 logger("Unknown message type ".$type);
167                                 return false;
168                 }
169
170                 return true;
171         }
172
173         /**
174          * @brief Checks if a posting is valid and fetches the data fields.
175          *
176          * This function does not only check the signature.
177          * It also does the conversion between the old and the new diaspora format.
178          *
179          * @param array $msg Array with the XML, the sender handle and the sender signature
180          * @param object $fields SimpleXML object that contains the posting when it is valid
181          *
182          * @return bool Is the posting valid?
183          */
184         private function valid_posting($msg, &$fields) {
185
186                 $data = parse_xml_string($msg["message"], false);
187
188                 if (!is_object($data))
189                         return false;
190
191                 $first_child = $data->getName();
192
193                 // Is this the new or the old version?
194                 if ($data->getName() == "XML") {
195                         $oldXML = true;
196                         foreach ($data->post->children() as $child)
197                                 $element = $child;
198                 } else {
199                         $oldXML = false;
200                         $element = $data;
201                 }
202
203                 $type = $element->getName();
204                 $orig_type = $type;
205
206                 // All retractions are handled identically from now on.
207                 // In the new version there will only be "retraction".
208                 if (in_array($type, array("signed_retraction", "relayable_retraction")))
209                         $type = "retraction";
210
211                 $fields = new SimpleXMLElement("<".$type."/>");
212
213                 $signed_data = "";
214
215                 foreach ($element->children() AS $fieldname => $entry) {
216                         if ($oldXML) {
217                                 // Translation for the old XML structure
218                                 if ($fieldname == "diaspora_handle")
219                                         $fieldname = "author";
220
221                                 if ($fieldname == "participant_handles")
222                                         $fieldname = "participants";
223
224                                 if (in_array($type, array("like", "participation"))) {
225                                         if ($fieldname == "target_type")
226                                                 $fieldname = "parent_type";
227                                 }
228
229                                 if ($fieldname == "sender_handle")
230                                         $fieldname = "author";
231
232                                 if ($fieldname == "recipient_handle")
233                                         $fieldname = "recipient";
234
235                                 if ($fieldname == "root_diaspora_id")
236                                         $fieldname = "root_author";
237
238                                 if ($type == "retraction") {
239                                         if ($fieldname == "post_guid")
240                                                 $fieldname = "target_guid";
241
242                                         if ($fieldname == "type")
243                                                 $fieldname = "target_type";
244                                 }
245                         }
246
247                         if ($fieldname == "author_signature")
248                                 $author_signature = base64_decode($entry);
249                         elseif ($fieldname == "parent_author_signature")
250                                 $parent_author_signature = base64_decode($entry);
251                         elseif ($fieldname != "target_author_signature") {
252                                 if ($signed_data != "") {
253                                         $signed_data .= ";";
254                                         $signed_data_parent .= ";";
255                                 }
256
257                                 $signed_data .= $entry;
258                         }
259                         if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
260                                 ($orig_type == "relayable_retraction"))
261                                 xml::copy($entry, $fields, $fieldname);
262                 }
263
264                 // This is something that shouldn't happen at all.
265                 if (in_array($type, array("status_message", "reshare", "profile")))
266                         if ($msg["author"] != $fields->author) {
267                                 logger("Message handle is not the same as envelope sender. Quitting this message.");
268                                 return false;
269                         }
270
271                 // Only some message types have signatures. So we quit here for the other types.
272                 if (!in_array($type, array("comment", "message", "like")))
273                         return true;
274
275                 // No author_signature? This is a must, so we quit.
276                 if (!isset($author_signature))
277                         return false;
278
279                 if (isset($parent_author_signature)) {
280                         $key = self::key($msg["author"]);
281
282                         if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256"))
283                                 return false;
284                 }
285
286                 $key = self::key($fields->author);
287
288                 return rsa_verify($signed_data, $author_signature, $key, "sha256");
289         }
290
291         /**
292          * @brief Fetches the public key for a given handle
293          *
294          * @param string $handle The handle
295          *
296          * @return string The public key
297          */
298         private function key($handle) {
299                 logger("Fetching diaspora key for: ".$handle);
300
301                 $r = self::person_by_handle($handle);
302                 if($r)
303                         return $r["pubkey"];
304
305                 return "";
306         }
307
308         /**
309          * @brief Fetches data for a given handle
310          *
311          * @param string $handle The handle
312          *
313          * @return array the queried data
314          */
315         private function person_by_handle($handle) {
316
317                 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
318                         dbesc(NETWORK_DIASPORA),
319                         dbesc($handle)
320                 );
321                 if ($r) {
322                         $person = $r[0];
323                         logger("In cache ".print_r($r,true), LOGGER_DEBUG);
324
325                         // update record occasionally so it doesn't get stale
326                         $d = strtotime($person["updated"]." +00:00");
327                         if ($d < strtotime("now - 14 days"))
328                                 $update = true;
329                 }
330
331                 if (!$person OR $update) {
332                         logger("create or refresh", LOGGER_DEBUG);
333                         $r = probe_url($handle, PROBE_DIASPORA);
334
335                         // Note that Friendica contacts will return a "Diaspora person"
336                         // if Diaspora connectivity is enabled on their server
337                         if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
338                                 self::add_fcontact($r, $update);
339                                 $person = $r;
340                         }
341                 }
342                 return $person;
343         }
344
345         /**
346          * @brief Updates the fcontact table
347          *
348          * @param array $arr The fcontact data
349          * @param bool $update Update or insert?
350          *
351          * @return string The id of the fcontact entry
352          */
353         private function add_fcontact($arr, $update = false) {
354                 /// @todo Remove this function from include/network.php
355
356                 if($update) {
357                         $r = q("UPDATE `fcontact` SET
358                                         `name` = '%s',
359                                         `photo` = '%s',
360                                         `request` = '%s',
361                                         `nick` = '%s',
362                                         `addr` = '%s',
363                                         `batch` = '%s',
364                                         `notify` = '%s',
365                                         `poll` = '%s',
366                                         `confirm` = '%s',
367                                         `alias` = '%s',
368                                         `pubkey` = '%s',
369                                         `updated` = '%s'
370                                 WHERE `url` = '%s' AND `network` = '%s'",
371                                         dbesc($arr["name"]),
372                                         dbesc($arr["photo"]),
373                                         dbesc($arr["request"]),
374                                         dbesc($arr["nick"]),
375                                         dbesc($arr["addr"]),
376                                         dbesc($arr["batch"]),
377                                         dbesc($arr["notify"]),
378                                         dbesc($arr["poll"]),
379                                         dbesc($arr["confirm"]),
380                                         dbesc($arr["alias"]),
381                                         dbesc($arr["pubkey"]),
382                                         dbesc(datetime_convert()),
383                                         dbesc($arr["url"]),
384                                         dbesc($arr["network"])
385                                 );
386                 } else {
387                         $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`,
388                                         `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
389                                 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
390                                         dbesc($arr["url"]),
391                                         dbesc($arr["name"]),
392                                         dbesc($arr["photo"]),
393                                         dbesc($arr["request"]),
394                                         dbesc($arr["nick"]),
395                                         dbesc($arr["addr"]),
396                                         dbesc($arr["batch"]),
397                                         dbesc($arr["notify"]),
398                                         dbesc($arr["poll"]),
399                                         dbesc($arr["confirm"]),
400                                         dbesc($arr["network"]),
401                                         dbesc($arr["alias"]),
402                                         dbesc($arr["pubkey"]),
403                                         dbesc(datetime_convert())
404                                 );
405                 }
406
407                 return $r;
408         }
409
410         public static function handle_from_contact($contact_id) {
411                 $handle = False;
412
413                 logger("contact id is ".$contact_id, LOGGER_DEBUG);
414
415                 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
416                        intval($contact_id)
417                 );
418                 if($r) {
419                         $contact = $r[0];
420
421                         logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
422
423                         if($contact['addr'] != "")
424                                 $handle = $contact['addr'];
425                         elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
426                                 $baseurl_start = strpos($contact['url'],'://') + 3;
427                                 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
428                                 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
429                                 $handle = $contact['nick'].'@'.$baseurl;
430                         }
431                 }
432
433                 return $handle;
434         }
435
436         private function contact_by_handle($uid, $handle) {
437                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
438                         intval($uid),
439                         dbesc($handle)
440                 );
441
442                 if ($r)
443                         return $r[0];
444
445                 $handle_parts = explode("@", $handle);
446                 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
447                 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
448                         dbesc(NETWORK_DFRN),
449                         intval($uid),
450                         dbesc($nurl_sql)
451                 );
452                 if($r)
453                         return $r[0];
454
455                 return false;
456         }
457
458         private function post_allow($importer, $contact, $is_comment = false) {
459
460                 // perhaps we were already sharing with this person. Now they're sharing with us.
461                 // That makes us friends.
462                 // Normally this should have handled by getting a request - but this could get lost
463                 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
464                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
465                                 intval(CONTACT_IS_FRIEND),
466                                 intval($contact["id"]),
467                                 intval($importer["uid"])
468                         );
469                         $contact["rel"] = CONTACT_IS_FRIEND;
470                         logger("defining user ".$contact["nick"]." as friend");
471                 }
472
473                 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
474                         return false;
475                 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
476                         return true;
477                 if($contact["rel"] == CONTACT_IS_FOLLOWER)
478                         if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
479                                 return true;
480
481                 // Messages for the global users are always accepted
482                 if ($importer["uid"] == 0)
483                         return true;
484
485                 return false;
486         }
487
488         private function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
489                 $contact = self::contact_by_handle($importer["uid"], $handle);
490                 if (!$contact) {
491                         logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
492                         return false;
493                 }
494
495                 if (!self::post_allow($importer, $contact, false)) {
496                         logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
497                         return false;
498                 }
499                 return $contact;
500         }
501
502         private function message_exists($uid, $guid) {
503                 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
504                         intval($uid),
505                         dbesc($guid)
506                 );
507
508                 if($r) {
509                         logger("message ".$guid." already exists for user ".$uid);
510                         return false;
511                 }
512
513                 return true;
514         }
515
516         private function fetch_guid($item) {
517                 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
518                         function ($match) use ($item){
519                                 return(self::fetch_guid_sub($match, $item));
520                         },$item["body"]);
521         }
522
523         private function fetch_guid_sub($match, $item) {
524                 if (!self::store_by_guid($match[1], $item["author-link"]))
525                         self::store_by_guid($match[1], $item["owner-link"]);
526         }
527
528         private function store_by_guid($guid, $server, $uid = 0) {
529                 $serverparts = parse_url($server);
530                 $server = $serverparts["scheme"]."://".$serverparts["host"];
531
532                 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
533
534                 $msg = self::message($guid, $server);
535
536                 if (!$msg)
537                         return false;
538
539                 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
540
541                 // Now call the dispatcher
542                 return self::dispatch_public($msg);
543         }
544
545         private function message($guid, $server, $level = 0) {
546
547                 if ($level > 5)
548                         return false;
549
550                 // This will work for Diaspora and newer Friendica servers
551                 $source_url = $server."/p/".$guid.".xml";
552                 $x = fetch_url($source_url);
553                 if(!$x)
554                         return false;
555
556                 $source_xml = parse_xml_string($x, false);
557
558                 if (!is_object($source_xml))
559                         return false;
560
561                 if ($source_xml->post->reshare) {
562                         // Reshare of a reshare - old Diaspora version
563                         return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
564                 } elseif ($source_xml->getName() == "reshare") {
565                         // Reshare of a reshare - new Diaspora version
566                         return self::message($source_xml->root_guid, $server, ++$level);
567                 }
568
569                 $author = "";
570
571                 // Fetch the author - for the old and the new Diaspora version
572                 if ($source_xml->post->status_message->diaspora_handle)
573                         $author = (string)$source_xml->post->status_message->diaspora_handle;
574                 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
575                         $author = (string)$source_xml->author;
576
577                 // If this isn't a "status_message" then quit
578                 if (!$author)
579                         return false;
580
581                 $msg = array("message" => $x, "author" => $author);
582
583                 $msg["key"] = self::key($msg["author"]);
584
585                 return $msg;
586         }
587
588         private function parent_item($uid, $guid, $author, $contact) {
589                 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
590                                 `author-name`, `author-link`, `author-avatar`,
591                                 `owner-name`, `owner-link`, `owner-avatar`
592                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
593                         intval($uid), dbesc($guid));
594
595                 if(!$r) {
596                         $result = self::store_by_guid($guid, $contact["url"], $uid);
597
598                         if (!$result) {
599                                 $person = self::person_by_handle($author);
600                                 $result = self::store_by_guid($guid, $person["url"], $uid);
601                         }
602
603                         if ($result) {
604                                 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
605
606                                 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
607                                                 `author-name`, `author-link`, `author-avatar`,
608                                                 `owner-name`, `owner-link`, `owner-avatar`
609                                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
610                                         intval($uid), dbesc($guid));
611                         }
612                 }
613
614                 if (!$r) {
615                         logger("parent item not found: parent: ".$guid." item: ".$guid);
616                         return false;
617                 } else
618                         return $r[0];
619         }
620
621         private function author_contact_by_url($contact, $person, $uid) {
622
623                 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
624                         dbesc(normalise_link($person["url"])), intval($uid));
625                 if ($r) {
626                         $cid = $r[0]["id"];
627                         $network = $r[0]["network"];
628                 } else {
629                         $cid = $contact["id"];
630                         $network = NETWORK_DIASPORA;
631                 }
632
633                 return (array("cid" => $cid, "network" => $network));
634         }
635
636         public static function is_redmatrix($url) {
637                 return(strstr($url, "/channel/"));
638         }
639
640         private function plink($addr, $guid) {
641                 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
642
643                 // Fallback
644                 if (!$r)
645                         return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
646
647                 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
648                 // So we try another way as well.
649                 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
650                 if ($s)
651                         $r[0]["network"] = $s[0]["network"];
652
653                 if ($r[0]["network"] == NETWORK_DFRN)
654                         return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
655
656                 if (self::is_redmatrix($r[0]["url"]))
657                         return $r[0]["url"]."/?f=&mid=".$guid;
658
659                 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
660         }
661
662         private function receive_account_deletion($importer, $data) {
663                 $author = notags(unxmlify($data->author));
664
665                 $contact = self::contact_by_handle($importer["uid"], $author);
666                 if (!$contact) {
667                         logger("cannot find contact for author: ".$author);
668                         return false;
669                 }
670
671                 // We now remove the contact
672                 contact_remove($contact["id"]);
673                 return true;
674         }
675
676         private function receive_comment($importer, $sender, $data) {
677                 $guid = notags(unxmlify($data->guid));
678                 $parent_guid = notags(unxmlify($data->parent_guid));
679                 $text = unxmlify($data->text);
680                 $author = notags(unxmlify($data->author));
681
682                 $contact = self::allowed_contact_by_handle($importer, $sender, true);
683                 if (!$contact)
684                         return false;
685
686                 if (self::message_exists($importer["uid"], $guid))
687                         return false;
688
689                 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
690                 if (!$parent_item)
691                         return false;
692
693                 $person = self::person_by_handle($author);
694                 if (!is_array($person)) {
695                         logger("unable to find author details");
696                         return false;
697                 }
698
699                 // Fetch the contact id - if we know this contact
700                 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
701
702                 $datarray = array();
703
704                 $datarray["uid"] = $importer["uid"];
705                 $datarray["contact-id"] = $author_contact["cid"];
706                 $datarray["network"]  = $author_contact["network"];
707
708                 $datarray["author-name"] = $person["name"];
709                 $datarray["author-link"] = $person["url"];
710                 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
711
712                 $datarray["owner-name"] = $contact["name"];
713                 $datarray["owner-link"] = $contact["url"];
714                 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
715
716                 $datarray["guid"] = $guid;
717                 $datarray["uri"] = $author.":".$guid;
718
719                 $datarray["type"] = "remote-comment";
720                 $datarray["verb"] = ACTIVITY_POST;
721                 $datarray["gravity"] = GRAVITY_COMMENT;
722                 $datarray["parent-uri"] = $parent_item["uri"];
723
724                 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
725                 $datarray["object"] = json_encode($data);
726
727                 $datarray["body"] = diaspora2bb($text);
728
729                 self::fetch_guid($datarray);
730
731                 $message_id = item_store($datarray);
732                 // print_r($datarray);
733
734                 // If we are the origin of the parent we store the original data and notify our followers
735                 if($message_id AND $parent_item["origin"]) {
736
737                         // Formerly we stored the signed text, the signature and the author in different fields.
738                         // We now store the raw data so that we are more flexible.
739                         q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
740                                 intval($message_id),
741                                 dbesc(json_encode($data))
742                         );
743
744                         // notify others
745                         proc_run("php", "include/notifier.php", "comment-import", $message_id);
746                 }
747
748                 return $message_id;
749         }
750
751         private function receive_conversation_message($importer, $contact, $data, $msg, $mesg) {
752                 $guid = notags(unxmlify($data->guid));
753                 $subject = notags(unxmlify($data->subject));
754                 $author = notags(unxmlify($data->author));
755
756                 $reply = 0;
757
758                 $msg_guid = notags(unxmlify($mesg->guid));
759                 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
760                 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
761                 $msg_author_signature = notags(unxmlify($mesg->author_signature));
762                 $msg_text = unxmlify($mesg->text);
763                 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
764
765                 // "diaspora_handle" is the element name from the old version
766                 // "author" is the element name from the new version
767                 if ($mesg->author)
768                         $msg_author = notags(unxmlify($mesg->author));
769                 elseif ($mesg->diaspora_handle)
770                         $msg_author = notags(unxmlify($mesg->diaspora_handle));
771                 else
772                         return false;
773
774                 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
775
776                 if($msg_conversation_guid != $guid) {
777                         logger("message conversation guid does not belong to the current conversation.");
778                         return false;
779                 }
780
781                 $body = diaspora2bb($msg_text);
782                 $message_uri = $msg_author.":".$msg_guid;
783
784                 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
785
786                 $author_signature = base64_decode($msg_author_signature);
787
788                 if(strcasecmp($msg_author,$msg["author"]) == 0) {
789                         $person = $contact;
790                         $key = $msg["key"];
791                 } else {
792                         $person = self::person_by_handle($msg_author);
793
794                         if (is_array($person) && x($person, "pubkey"))
795                                 $key = $person["pubkey"];
796                         else {
797                                 logger("unable to find author details");
798                                         return false;
799                         }
800                 }
801
802                 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
803                         logger("verification failed.");
804                         return false;
805                 }
806
807                 if($msg_parent_author_signature) {
808                         $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
809
810                         $parent_author_signature = base64_decode($msg_parent_author_signature);
811
812                         $key = $msg["key"];
813
814                         if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
815                                 logger("owner verification failed.");
816                                 return false;
817                         }
818                 }
819
820                 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
821                         dbesc($message_uri)
822                 );
823                 if($r) {
824                         logger("duplicate message already delivered.", LOGGER_DEBUG);
825                         return false;
826                 }
827
828                 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
829                         VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
830                         intval($importer["uid"]),
831                         dbesc($msg_guid),
832                         intval($conversation["id"]),
833                         dbesc($person["name"]),
834                         dbesc($person["photo"]),
835                         dbesc($person["url"]),
836                         intval($contact["id"]),
837                         dbesc($subject),
838                         dbesc($body),
839                         0,
840                         0,
841                         dbesc($message_uri),
842                         dbesc($author.":".$guid),
843                         dbesc($msg_created_at)
844                 );
845
846                 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
847                         dbesc(datetime_convert()),
848                         intval($conversation["id"])
849                 );
850
851                 notification(array(
852                         "type" => NOTIFY_MAIL,
853                         "notify_flags" => $importer["notify-flags"],
854                         "language" => $importer["language"],
855                         "to_name" => $importer["username"],
856                         "to_email" => $importer["email"],
857                         "uid" =>$importer["uid"],
858                         "item" => array("subject" => $subject, "body" => $body),
859                         "source_name" => $person["name"],
860                         "source_link" => $person["url"],
861                         "source_photo" => $person["thumb"],
862                         "verb" => ACTIVITY_POST,
863                         "otype" => "mail"
864                 ));
865         }
866
867         private function receive_conversation($importer, $msg, $data) {
868                 $guid = notags(unxmlify($data->guid));
869                 $subject = notags(unxmlify($data->subject));
870                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
871                 $author = notags(unxmlify($data->author));
872                 $participants = notags(unxmlify($data->participants));
873
874                 $messages = $data->message;
875
876                 if (!count($messages)) {
877                         logger("empty conversation");
878                         return false;
879                 }
880
881                 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
882                 if (!$contact)
883                         return false;
884
885                 $conversation = null;
886
887                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
888                         intval($importer["uid"]),
889                         dbesc($guid)
890                 );
891                 if($c)
892                         $conversation = $c[0];
893                 else {
894                         $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
895                                 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
896                                 intval($importer["uid"]),
897                                 dbesc($guid),
898                                 dbesc($author),
899                                 dbesc(datetime_convert("UTC", "UTC", $created_at)),
900                                 dbesc(datetime_convert()),
901                                 dbesc($subject),
902                                 dbesc($participants)
903                         );
904                         if($r)
905                                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
906                                         intval($importer["uid"]),
907                                         dbesc($guid)
908                                 );
909
910                         if($c)
911                                 $conversation = $c[0];
912                 }
913                 if (!$conversation) {
914                         logger("unable to create conversation.");
915                         return;
916                 }
917
918                 foreach($messages as $mesg)
919                         self::receive_conversation_message($importer, $contact, $data, $msg, $mesg);
920
921                 return true;
922         }
923
924         private function construct_like_body($contact, $parent_item, $guid) {
925                 $bodyverb = t('%1$s likes %2$s\'s %3$s');
926
927                 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
928                 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
929                 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
930
931                 return sprintf($bodyverb, $ulink, $alink, $plink);
932         }
933
934         private function construct_like_object($importer, $parent_item) {
935                 $objtype = ACTIVITY_OBJ_NOTE;
936                 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
937                 $parent_body = $parent_item["body"];
938
939                 $xmldata = array("object" => array("type" => $objtype,
940                                                 "local" => "1",
941                                                 "id" => $parent_item["uri"],
942                                                 "link" => $link,
943                                                 "title" => "",
944                                                 "content" => $parent_body));
945
946                 return xml::from_array($xmldata, $xml, true);
947         }
948
949         private function receive_like($importer, $sender, $data) {
950                 $positive = notags(unxmlify($data->positive));
951                 $guid = notags(unxmlify($data->guid));
952                 $parent_type = notags(unxmlify($data->parent_type));
953                 $parent_guid = notags(unxmlify($data->parent_guid));
954                 $author = notags(unxmlify($data->author));
955
956                 // likes on comments aren't supported by Diaspora - only on posts
957                 // But maybe this will be supported in the future, so we will accept it.
958                 if (!in_array($parent_type, array("Post", "Comment")))
959                         return false;
960
961                 $contact = self::allowed_contact_by_handle($importer, $sender, true);
962                 if (!$contact)
963                         return false;
964
965                 if (self::message_exists($importer["uid"], $guid))
966                         return false;
967
968                 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
969                 if (!$parent_item)
970                         return false;
971
972                 $person = self::person_by_handle($author);
973                 if (!is_array($person)) {
974                         logger("unable to find author details");
975                         return false;
976                 }
977
978                 // Fetch the contact id - if we know this contact
979                 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
980
981                 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
982                 // We would accept this anyhow.
983                 if ($positive === "true")
984                         $verb = ACTIVITY_LIKE;
985                 else
986                         $verb = ACTIVITY_DISLIKE;
987
988                 $datarray = array();
989
990                 $datarray["uid"] = $importer["uid"];
991                 $datarray["contact-id"] = $author_contact["cid"];
992                 $datarray["network"]  = $author_contact["network"];
993
994                 $datarray["author-name"] = $person["name"];
995                 $datarray["author-link"] = $person["url"];
996                 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
997
998                 $datarray["owner-name"] = $contact["name"];
999                 $datarray["owner-link"] = $contact["url"];
1000                 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1001
1002                 $datarray["guid"] = $guid;
1003                 $datarray["uri"] = $author.":".$guid;
1004
1005                 $datarray["type"] = "activity";
1006                 $datarray["verb"] = $verb;
1007                 $datarray["gravity"] = GRAVITY_LIKE;
1008                 $datarray["parent-uri"] = $parent_item["uri"];
1009
1010                 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1011                 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1012
1013                 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1014
1015                 $message_id = item_store($datarray);
1016                 // print_r($datarray);
1017
1018                 // If we are the origin of the parent we store the original data and notify our followers
1019                 if($message_id AND $parent_item["origin"]) {
1020
1021                         // Formerly we stored the signed text, the signature and the author in different fields.
1022                         // We now store the raw data so that we are more flexible.
1023                         q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1024                                 intval($message_id),
1025                                 dbesc(json_encode($data))
1026                         );
1027
1028                         // notify others
1029                         proc_run("php", "include/notifier.php", "comment-import", $message_id);
1030                 }
1031
1032                 return $message_id;
1033         }
1034
1035         private function receive_message($importer, $data) {
1036                 $guid = notags(unxmlify($data->guid));
1037                 $parent_guid = notags(unxmlify($data->parent_guid));
1038                 $text = unxmlify($data->text);
1039                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1040                 $author = notags(unxmlify($data->author));
1041                 $conversation_guid = notags(unxmlify($data->conversation_guid));
1042
1043                 $contact = self::allowed_contact_by_handle($importer, $author, true);
1044                 if (!$contact)
1045                         return false;
1046
1047                 $conversation = null;
1048
1049                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1050                         intval($importer["uid"]),
1051                         dbesc($conversation_guid)
1052                 );
1053                 if($c)
1054                         $conversation = $c[0];
1055                 else {
1056                         logger("conversation not available.");
1057                         return false;
1058                 }
1059
1060                 $reply = 0;
1061
1062                 $body = diaspora2bb($text);
1063                 $message_uri = $author.":".$guid;
1064
1065                 $person = self::person_by_handle($author);
1066                 if (!$person) {
1067                         logger("unable to find author details");
1068                         return false;
1069                 }
1070
1071                 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1072                         dbesc($message_uri),
1073                         intval($importer["uid"])
1074                 );
1075                 if($r) {
1076                         logger("duplicate message already delivered.", LOGGER_DEBUG);
1077                         return false;
1078                 }
1079
1080                 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1081                                 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1082                         intval($importer["uid"]),
1083                         dbesc($guid),
1084                         intval($conversation["id"]),
1085                         dbesc($person["name"]),
1086                         dbesc($person["photo"]),
1087                         dbesc($person["url"]),
1088                         intval($contact["id"]),
1089                         dbesc($conversation["subject"]),
1090                         dbesc($body),
1091                         0,
1092                         1,
1093                         dbesc($message_uri),
1094                         dbesc($author.":".$parent_guid),
1095                         dbesc($created_at)
1096                 );
1097
1098                 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1099                         dbesc(datetime_convert()),
1100                         intval($conversation["id"])
1101                 );
1102
1103                 return true;
1104         }
1105
1106         private function receive_participation($importer, $data) {
1107                 // I'm not sure if we can fully support this message type
1108                 return true;
1109         }
1110
1111         private function receive_photo($importer, $data) {
1112                 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1113                 return true;
1114         }
1115
1116         private function receive_poll_participation($importer, $data) {
1117                 // We don't support polls by now
1118                 return true;
1119         }
1120
1121         private function receive_profile($importer, $data) {
1122                 $author = notags(unxmlify($data->author));
1123
1124                 $contact = self::contact_by_handle($importer["uid"], $author);
1125                 if (!$contact)
1126                         return;
1127
1128                 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1129                 $image_url = unxmlify($data->image_url);
1130                 $birthday = unxmlify($data->birthday);
1131                 $location = diaspora2bb(unxmlify($data->location));
1132                 $about = diaspora2bb(unxmlify($data->bio));
1133                 $gender = unxmlify($data->gender);
1134                 $searchable = (unxmlify($data->searchable) == "true");
1135                 $nsfw = (unxmlify($data->nsfw) == "true");
1136                 $tags = unxmlify($data->tag_string);
1137
1138                 $tags = explode("#", $tags);
1139
1140                 $keywords = array();
1141                 foreach ($tags as $tag) {
1142                         $tag = trim(strtolower($tag));
1143                         if ($tag != "")
1144                                 $keywords[] = $tag;
1145                 }
1146
1147                 $keywords = implode(", ", $keywords);
1148
1149                 $handle_parts = explode("@", $author);
1150                 $nick = $handle_parts[0];
1151
1152                 if($name === "")
1153                         $name = $handle_parts[0];
1154
1155                 if( preg_match("|^https?://|", $image_url) === 0)
1156                         $image_url = "http://".$handle_parts[1].$image_url;
1157
1158                 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1159
1160                 // Generic birthday. We don't know the timezone. The year is irrelevant.
1161
1162                 $birthday = str_replace("1000", "1901", $birthday);
1163
1164                 if ($birthday != "")
1165                         $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1166
1167                 // this is to prevent multiple birthday notifications in a single year
1168                 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1169
1170                 if(substr($birthday,5) === substr($contact["bd"],5))
1171                         $birthday = $contact["bd"];
1172
1173                 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1174                                 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1175                         dbesc($name),
1176                         dbesc($nick),
1177                         dbesc($author),
1178                         dbesc(datetime_convert()),
1179                         dbesc($birthday),
1180                         dbesc($location),
1181                         dbesc($about),
1182                         dbesc($keywords),
1183                         dbesc($gender),
1184                         intval($contact["id"]),
1185                         intval($importer["uid"])
1186                 );
1187
1188                 if ($searchable) {
1189                         poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1190                                 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1191                 }
1192
1193                 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1194                                         "photo" => $image_url, "name" => $name, "location" => $location,
1195                                         "about" => $about, "birthday" => $birthday, "gender" => $gender,
1196                                         "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1197                                         "hide" => !$searchable, "nsfw" => $nsfw);
1198
1199                 update_gcontact($gcontact);
1200
1201                 return true;
1202         }
1203
1204         private function receive_request_make_friend($importer, $contact) {
1205
1206                 $a = get_app();
1207
1208                 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1209                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1210                                 intval(CONTACT_IS_FRIEND),
1211                                 intval($contact["id"]),
1212                                 intval($importer["uid"])
1213                         );
1214                 }
1215                 // send notification
1216
1217                 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1218                         intval($importer["uid"])
1219                 );
1220
1221                 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1222
1223                         $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1224                                 intval($importer["uid"])
1225                         );
1226
1227                         // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1228
1229                         if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1230
1231                                 $arr = array();
1232                                 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1233                                 $arr["uid"] = $importer["uid"];
1234                                 $arr["contact-id"] = $self[0]["id"];
1235                                 $arr["wall"] = 1;
1236                                 $arr["type"] = 'wall';
1237                                 $arr["gravity"] = 0;
1238                                 $arr["origin"] = 1;
1239                                 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1240                                 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1241                                 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1242                                 $arr["verb"] = ACTIVITY_FRIEND;
1243                                 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1244
1245                                 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1246                                 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1247                                 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1248                                 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1249
1250                                 $arr["object"] = "<object><type>".ACTIVITY_OBJ_PERSON."</type><title>".$contact["name"]."</title>"
1251                                         ."<id>".$contact["url"]."/".$contact["name"]."</id>";
1252                                 $arr["object"] .= "<link>".xmlify('<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n");
1253                                 $arr["object"] .= xmlify('<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n");
1254                                 $arr["object"] .= "</link></object>\n";
1255                                 $arr["last-child"] = 1;
1256
1257                                 $arr["allow_cid"] = $user[0]["allow_cid"];
1258                                 $arr["allow_gid"] = $user[0]["allow_gid"];
1259                                 $arr["deny_cid"]  = $user[0]["deny_cid"];
1260                                 $arr["deny_gid"]  = $user[0]["deny_gid"];
1261
1262                                 $i = item_store($arr);
1263                                 if($i)
1264                                         proc_run("php", "include/notifier.php", "activity", $i);
1265
1266                         }
1267
1268                 }
1269         }
1270
1271         private function receive_request($importer, $data) {
1272                 $author = unxmlify($data->author);
1273                 $recipient = unxmlify($data->recipient);
1274
1275                 if (!$author || !$recipient)
1276                         return;
1277
1278                 $contact = self::contact_by_handle($importer["uid"],$author);
1279
1280                 if($contact) {
1281
1282                         // perhaps we were already sharing with this person. Now they're sharing with us.
1283                         // That makes us friends.
1284
1285                         self::receive_request_make_friend($importer, $contact);
1286                         return true;
1287                 }
1288
1289                 $ret = self::person_by_handle($author);
1290
1291                 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
1292                         logger("Cannot resolve diaspora handle ".$author ." for ".$recipient);
1293                         return false;
1294                 }
1295
1296                 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
1297
1298                 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1299                         VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
1300                         intval($importer["uid"]),
1301                         dbesc($ret["network"]),
1302                         dbesc($ret["addr"]),
1303                         datetime_convert(),
1304                         dbesc($ret["url"]),
1305                         dbesc(normalise_link($ret["url"])),
1306                         dbesc($batch),
1307                         dbesc($ret["name"]),
1308                         dbesc($ret["nick"]),
1309                         dbesc($ret["photo"]),
1310                         dbesc($ret["pubkey"]),
1311                         dbesc($ret["notify"]),
1312                         dbesc($ret["poll"]),
1313                         1,
1314                         2
1315                 );
1316
1317                 // find the contact record we just created
1318
1319                 $contact_record = self::contact_by_handle($importer["uid"],$author);
1320
1321                 if (!$contact_record) {
1322                         logger("unable to locate newly created contact record.");
1323                         return;
1324                 }
1325
1326                 $g = q("SELECT `def_gid` FROM `user` WHERE `uid` = %d LIMIT 1",
1327                         intval($importer["uid"])
1328                 );
1329
1330                 if($g && intval($g[0]["def_gid"]))
1331                         group_add_member($importer["uid"], "", $contact_record["id"], $g[0]["def_gid"]);
1332
1333                 if($importer["page-flags"] == PAGE_NORMAL) {
1334
1335                         $hash = random_string().(string)time();   // Generate a confirm_key
1336
1337                         $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
1338                                 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
1339                                 intval($importer["uid"]),
1340                                 intval($contact_record["id"]),
1341                                 0,
1342                                 0,
1343                                 dbesc(t("Sharing notification from Diaspora network")),
1344                                 dbesc($hash),
1345                                 dbesc(datetime_convert())
1346                         );
1347                 } else {
1348
1349                         // automatic friend approval
1350
1351                         update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1352
1353                         // technically they are sharing with us (CONTACT_IS_SHARING),
1354                         // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1355                         // we are going to change the relationship and make them a follower.
1356
1357                         if($importer["page-flags"] == PAGE_FREELOVE)
1358                                 $new_relation = CONTACT_IS_FRIEND;
1359                         else
1360                                 $new_relation = CONTACT_IS_FOLLOWER;
1361
1362                         $r = q("UPDATE `contact` SET `rel` = %d,
1363                                 `name-date` = '%s',
1364                                 `uri-date` = '%s',
1365                                 `blocked` = 0,
1366                                 `pending` = 0,
1367                                 `writable` = 1
1368                                 WHERE `id` = %d
1369                                 ",
1370                                 intval($new_relation),
1371                                 dbesc(datetime_convert()),
1372                                 dbesc(datetime_convert()),
1373                                 intval($contact_record["id"])
1374                         );
1375
1376                         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1377                         if($u)
1378                                 $ret = self::send_share($u[0], $contact_record);
1379                 }
1380
1381                 return true;
1382         }
1383
1384         private function original_item($guid, $orig_author, $author) {
1385
1386                 // Do we already have this item?
1387                 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1388                                 `author-name`, `author-link`, `author-avatar`
1389                                 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1390                         dbesc($guid));
1391
1392                 if($r) {
1393                         logger("reshared message ".$guid." already exists on system.");
1394
1395                         // Maybe it is already a reshared item?
1396                         // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1397                         if (self::is_reshare($r[0]["body"]))
1398                                 $r = array();
1399                         else
1400                                 return $r[0];
1401                 }
1402
1403                 if (!$r) {
1404                         $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
1405                         logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1406                         $item_id = self::store_by_guid($guid, $server);
1407
1408                         if (!$item_id) {
1409                                 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
1410                                 logger("2nd try: reshared message ".$guid." will be fetched from original server: ".$server);
1411                                 $item_id = self::store_by_guid($guid, $server);
1412                         }
1413
1414                         // Deactivated by now since there is a risk that someone could manipulate postings through this method
1415 /*                      if (!$item_id) {
1416                                 $server = "https://".substr($author, strpos($author, "@") + 1);
1417                                 logger("3rd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1418                                 $item_id = self::store_by_guid($guid, $server);
1419                         }
1420                         if (!$item_id) {
1421                                 $server = "http://".substr($author, strpos($author, "@") + 1);
1422                                 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1423                                 $item_id = self::store_by_guid($guid, $server);
1424                         }
1425 */
1426                         if ($item_id) {
1427                                 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1428                                                 `author-name`, `author-link`, `author-avatar`
1429                                         FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1430                                         intval($item_id));
1431
1432                                 if ($r)
1433                                         return $r[0];
1434
1435                         }
1436                 }
1437                 return false;
1438         }
1439
1440         private function receive_reshare($importer, $data) {
1441                 $root_author = notags(unxmlify($data->root_author));
1442                 $root_guid = notags(unxmlify($data->root_guid));
1443                 $guid = notags(unxmlify($data->guid));
1444                 $author = notags(unxmlify($data->author));
1445                 $public = notags(unxmlify($data->public));
1446                 $created_at = notags(unxmlify($data->created_at));
1447
1448                 $contact = self::allowed_contact_by_handle($importer, $author, false);
1449                 if (!$contact)
1450                         return false;
1451
1452                 if (self::message_exists($importer["uid"], $guid))
1453                         return false;
1454
1455                 $original_item = self::original_item($root_guid, $root_author, $author);
1456                 if (!$original_item)
1457                         return false;
1458
1459                 $datarray = array();
1460
1461                 $datarray["uid"] = $importer["uid"];
1462                 $datarray["contact-id"] = $contact["id"];
1463                 $datarray["network"]  = NETWORK_DIASPORA;
1464
1465                 $datarray["author-name"] = $contact["name"];
1466                 $datarray["author-link"] = $contact["url"];
1467                 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1468
1469                 $datarray["owner-name"] = $datarray["author-name"];
1470                 $datarray["owner-link"] = $datarray["author-link"];
1471                 $datarray["owner-avatar"] = $datarray["author-avatar"];
1472
1473                 $datarray["guid"] = $guid;
1474                 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1475
1476                 $datarray["verb"] = ACTIVITY_POST;
1477                 $datarray["gravity"] = GRAVITY_PARENT;
1478
1479                 $datarray["object"] = json_encode($data);
1480
1481                 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
1482                                         $original_item["guid"], $original_item["created"], $original_item["uri"]);
1483                 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
1484
1485                 $datarray["tag"] = $original_item["tag"];
1486                 $datarray["app"]  = $original_item["app"];
1487
1488                 $datarray["plink"] = self::plink($author, $guid);
1489                 $datarray["private"] = (($public == "false") ? 1 : 0);
1490                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1491
1492                 $datarray["object-type"] = $original_item["object-type"];
1493
1494                 self::fetch_guid($datarray);
1495                 $message_id = item_store($datarray);
1496                 // print_r($datarray);
1497
1498                 return $message_id;
1499         }
1500
1501         private function item_retraction($importer, $contact, $data) {
1502                 $target_type = notags(unxmlify($data->target_type));
1503                 $target_guid = notags(unxmlify($data->target_guid));
1504                 $author = notags(unxmlify($data->author));
1505
1506                 $person = self::person_by_handle($author);
1507                 if (!is_array($person)) {
1508                         logger("unable to find author detail for ".$author);
1509                         return false;
1510                 }
1511
1512                 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
1513                         dbesc($target_guid),
1514                         intval($importer["uid"])
1515                 );
1516                 if (!$r)
1517                         return false;
1518
1519                 // Only delete it if the author really fits
1520                 if (!link_compare($r[0]["author-link"],$person["url"]))
1521                         return false;
1522
1523                 // Check if the sender is the thread owner
1524                 $p = q("SELECT `author-link`, `origin` FROM `item` WHERE `id` = %d",
1525                         intval($r[0]["parent"]));
1526
1527                 // Only delete it if the parent author really fits
1528                 if (!link_compare($p[0]["author-link"], $contact["url"]))
1529                         return false;
1530
1531                 // 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
1532                 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
1533                         dbesc(datetime_convert()),
1534                         dbesc(datetime_convert()),
1535                         intval($r[0]["id"])
1536                 );
1537                 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
1538
1539                 // Now check if the retraction needs to be relayed by us
1540                 if($p[0]["origin"]) {
1541
1542                         // Formerly we stored the signed text, the signature and the author in different fields.
1543                         // We now store the raw data so that we are more flexible.
1544                         q("INSERT INTO `sign` (`retract_iid`,`signed_text`) VALUES (%d,'%s')",
1545                                 intval($r[0]["id"]),
1546                                 dbesc(json_encode($data))
1547                         );
1548
1549                         // notify others
1550                         proc_run("php", "include/notifier.php", "drop", $r[0]["id"]);
1551                 }
1552         }
1553
1554         private function receive_retraction($importer, $sender, $data) {
1555                 $target_type = notags(unxmlify($data->target_type));
1556
1557                 $contact = self::contact_by_handle($importer["uid"], $sender);
1558                 if (!$contact) {
1559                         logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
1560                         return false;
1561                 }
1562
1563                 switch ($target_type) {
1564                         case "Comment":
1565                         case "Like":
1566                         case "Post": // "Post" will be supported in a future version
1567                         case "Reshare":
1568                         case "StatusMessage":
1569                                 return self::item_retraction($importer, $contact, $data);;
1570
1571                         case "Person":
1572                                 /// @todo What should we do with an "unshare"?
1573                                 // Removing the contact isn't correct since we still can read the public items
1574                                 //contact_remove($contact["id"]);
1575                                 return true;
1576
1577                         default:
1578                                 logger("Unknown target type ".$target_type);
1579                                 return false;
1580                 }
1581                 return true;
1582         }
1583
1584         private function receive_status_message($importer, $data) {
1585
1586                 $raw_message = unxmlify($data->raw_message);
1587                 $guid = notags(unxmlify($data->guid));
1588                 $author = notags(unxmlify($data->author));
1589                 $public = notags(unxmlify($data->public));
1590                 $created_at = notags(unxmlify($data->created_at));
1591                 $provider_display_name = notags(unxmlify($data->provider_display_name));
1592
1593                 /// @todo enable support for polls
1594                 //if ($data->poll) {
1595                 //      foreach ($data->poll AS $poll)
1596                 //              print_r($poll);
1597                 //      die("poll!\n");
1598                 //}
1599                 $contact = self::allowed_contact_by_handle($importer, $author, false);
1600                 if (!$contact)
1601                         return false;
1602
1603                 if (self::message_exists($importer["uid"], $guid))
1604                         return false;
1605
1606                 $address = array();
1607                 if ($data->location)
1608                         foreach ($data->location->children() AS $fieldname => $data)
1609                                 $address[$fieldname] = notags(unxmlify($data));
1610
1611                 $body = diaspora2bb($raw_message);
1612
1613                 $datarray = array();
1614
1615                 if ($data->photo) {
1616                         foreach ($data->photo AS $photo)
1617                                 $body = "[img]".$photo->remote_photo_path.$photo->remote_photo_name."[/img]\n".$body;
1618
1619                         $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
1620                 } else {
1621                         $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1622
1623                         // Add OEmbed and other information to the body
1624                         if (!self::is_redmatrix($contact["url"]))
1625                                 $body = add_page_info_to_body($body, false, true);
1626                 }
1627
1628                 $datarray["uid"] = $importer["uid"];
1629                 $datarray["contact-id"] = $contact["id"];
1630                 $datarray["network"] = NETWORK_DIASPORA;
1631
1632                 $datarray["author-name"] = $contact["name"];
1633                 $datarray["author-link"] = $contact["url"];
1634                 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1635
1636                 $datarray["owner-name"] = $datarray["author-name"];
1637                 $datarray["owner-link"] = $datarray["author-link"];
1638                 $datarray["owner-avatar"] = $datarray["author-avatar"];
1639
1640                 $datarray["guid"] = $guid;
1641                 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1642
1643                 $datarray["verb"] = ACTIVITY_POST;
1644                 $datarray["gravity"] = GRAVITY_PARENT;
1645
1646                 $datarray["object"] = json_encode($data);
1647
1648                 $datarray["body"] = $body;
1649
1650                 if ($provider_display_name != "")
1651                         $datarray["app"] = $provider_display_name;
1652
1653                 $datarray["plink"] = self::plink($author, $guid);
1654                 $datarray["private"] = (($public == "false") ? 1 : 0);
1655                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1656
1657                 if (isset($address["address"]))
1658                         $datarray["location"] = $address["address"];
1659
1660                 if (isset($address["lat"]) AND isset($address["lng"]))
1661                         $datarray["coord"] = $address["lat"]." ".$address["lng"];
1662
1663                 self::fetch_guid($datarray);
1664                 $message_id = item_store($datarray);
1665                 // print_r($datarray);
1666
1667                 logger("Stored item with message id ".$message_id, LOGGER_DEBUG);
1668
1669                 return $message_id;
1670         }
1671
1672         /*******************************************************************************************
1673          * Here come all the functions that are needed to transmit data with the Diaspora protocol *
1674          *******************************************************************************************/
1675
1676         private function my_handle($me) {
1677                 if ($contact["addr"] != "")
1678                         return $contact["addr"];
1679
1680                 // Normally we should have a filled "addr" field - but in the past this wasn't the case
1681                 // So - just in case - we build the the address here.
1682                 return $me["nickname"]."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
1683         }
1684
1685         private function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
1686
1687                 logger("Message: ".$msg, LOGGER_DATA);
1688
1689                 $handle = self::my_handle($user);
1690
1691                 $b64url_data = base64url_encode($msg);
1692
1693                 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1694
1695                 $type = "application/xml";
1696                 $encoding = "base64url";
1697                 $alg = "RSA-SHA256";
1698
1699                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1700
1701                 $signature = rsa_sign($signable_data,$prvkey);
1702                 $sig = base64url_encode($signature);
1703
1704 $magic_env = <<< EOT
1705 <?xml version='1.0' encoding='UTF-8'?>
1706 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
1707   <header>
1708     <author_id>$handle</author_id>
1709   </header>
1710   <me:env>
1711     <me:encoding>base64url</me:encoding>
1712     <me:alg>RSA-SHA256</me:alg>
1713     <me:data type="application/xml">$data</me:data>
1714     <me:sig>$sig</me:sig>
1715   </me:env>
1716 </diaspora>
1717 EOT;
1718 die($magic_env."\n");
1719                 logger("magic_env: ".$magic_env, LOGGER_DATA);
1720                 return $magic_env;
1721         }
1722
1723         private function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
1724
1725                 logger("Message: ".$msg, LOGGER_DATA);
1726
1727                 // without a public key nothing will work
1728
1729                 if (!$pubkey) {
1730                         logger("pubkey missing: contact id: ".$contact["id"]);
1731                         return false;
1732                 }
1733
1734                 $inner_aes_key = random_string(32);
1735                 $b_inner_aes_key = base64_encode($inner_aes_key);
1736                 $inner_iv = random_string(16);
1737                 $b_inner_iv = base64_encode($inner_iv);
1738
1739                 $outer_aes_key = random_string(32);
1740                 $b_outer_aes_key = base64_encode($outer_aes_key);
1741                 $outer_iv = random_string(16);
1742                 $b_outer_iv = base64_encode($outer_iv);
1743
1744                 $handle = self::my_handle($user);
1745
1746                 $padded_data = pkcs5_pad($msg,16);
1747                 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
1748
1749                 $b64_data = base64_encode($inner_encrypted);
1750
1751
1752                 $b64url_data = base64url_encode($b64_data);
1753                 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1754
1755                 $type = "application/xml";
1756                 $encoding = "base64url";
1757                 $alg = "RSA-SHA256";
1758
1759                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1760
1761                 $signature = rsa_sign($signable_data,$prvkey);
1762                 $sig = base64url_encode($signature);
1763
1764                 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
1765                                                         "aes_key" => $b_inner_aes_key,
1766                                                         "author_id" => $handle));
1767
1768                 $decrypted_header = xml::from_array($xmldata, $xml, true);
1769                 $decrypted_header = pkcs5_pad($decrypted_header,16);
1770
1771                 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
1772
1773                 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
1774
1775                 $encrypted_outer_key_bundle = "";
1776                 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
1777
1778                 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
1779
1780                 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
1781
1782                 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
1783                                                                 "ciphertext" => base64_encode($ciphertext)));
1784                 $cipher_json = base64_encode($encrypted_header_json_object);
1785
1786                 $xml = nul;
1787                 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
1788                                                 "me:env" => array("me:encoding" => "base64url",
1789                                                                 "me:alg" => "RSA-SHA256",
1790                                                                 "me:data" => $data,
1791                                                                 "me:sig" => $sig)));
1792                 $encrypted_header = xml::from_array($xmldata, $xml, true);
1793 echo $encrypted_header."\n";
1794
1795                 $encrypted_header = "<encrypted_header>".$cipher_json."</encrypted_header>";
1796
1797 $magic_env = <<< EOT
1798 <?xml version='1.0' encoding='UTF-8'?>
1799 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
1800   $encrypted_header
1801   <me:env>
1802     <me:encoding>base64url</me:encoding>
1803     <me:alg>RSA-SHA256</me:alg>
1804     <me:data type="application/xml">$data</me:data>
1805     <me:sig>$sig</me:sig>
1806   </me:env>
1807 </diaspora>
1808 EOT;
1809 die($magic_env."\n");
1810
1811                 logger("magic_env: ".$magic_env, LOGGER_DATA);
1812                 return $magic_env;
1813         }
1814
1815         private function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
1816
1817                 if ($public)
1818                         $magic_env =  self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
1819                 else
1820                         $magic_env =  self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
1821
1822                 // The data that will be transmitted is double encoded via "urlencode", strange ...
1823                 $slap = "xml=".urlencode(urlencode($magic_env));
1824                 return $slap;
1825         }
1826
1827         private function signature($owner, $message) {
1828                 $sigmsg = $message;
1829                 unset($sigmsg["author_signature"]);
1830                 unset($sigmsg["parent_author_signature"]);
1831
1832                 $signed_text = implode(";", $sigmsg);
1833
1834                 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
1835         }
1836
1837         public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
1838
1839                 $a = get_app();
1840
1841                 $enabled = intval(get_config("system", "diaspora_enabled"));
1842                 if(!$enabled)
1843                         return 200;
1844
1845                 $logid = random_string(4);
1846                 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
1847                 if (!$dest_url) {
1848                         logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
1849                         return 0;
1850                 }
1851
1852                 logger("transmit: ".$logid."-".$guid." ".$dest_url);
1853
1854                 if (!$queue_run && was_recently_delayed($contact["id"])) {
1855                         $return_code = 0;
1856                 } else {
1857                         if (!intval(get_config("system", "diaspora_test"))) {
1858                                 post_url($dest_url."/", $slap);
1859                                 $return_code = $a->get_curl_code();
1860                         } else {
1861                                 logger("test_mode");
1862                                 return 200;
1863                         }
1864                 }
1865
1866                 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
1867
1868                 if(!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
1869                         logger("queue message");
1870
1871                         $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
1872                                 intval($contact["id"]),
1873                                 dbesc(NETWORK_DIASPORA),
1874                                 dbesc($slap),
1875                                 intval($public_batch)
1876                         );
1877                         if(count($r)) {
1878                                 logger("add_to_queue ignored - identical item already in queue");
1879                         } else {
1880                                 // queue message for redelivery
1881                                 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
1882                         }
1883                 }
1884
1885                 return(($return_code) ? $return_code : (-1));
1886         }
1887
1888
1889         private function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "") {
1890
1891                 $data = array("XML" => array("post" => array($type => $message)));
1892
1893                 $msg = xml::from_array($data, $xml);
1894
1895                 logger('message: '.$msg, LOGGER_DATA);
1896                 logger('send guid '.$guid, LOGGER_DEBUG);
1897
1898                 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
1899 die($slap);
1900                 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
1901
1902                 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
1903
1904                 return $return_code;
1905         }
1906
1907         public static function send_share($owner,$contact) {
1908
1909                 $message = array("sender_handle" => self::my_handle($owner),
1910                                 "recipient_handle" => $contact["addr"]);
1911
1912                 return self::build_and_transmit($owner, $contact, "request", $message);
1913         }
1914
1915         public static function send_unshare($owner,$contact) {
1916
1917                 $message = array("post_guid" => $owner["guid"],
1918                                 "diaspora_handle" => self::my_handle($owner),
1919                                 "type" => "Person");
1920
1921                 return self::build_and_transmit($owner, $contact, "retraction", $message);
1922         }
1923
1924         private function is_reshare($body) {
1925                 $body = trim($body);
1926
1927                 // Skip if it isn't a pure repeated messages
1928                 // Does it start with a share?
1929                 if (strpos($body, "[share") > 0)
1930                         return(false);
1931
1932                 // Does it end with a share?
1933                 if (strlen($body) > (strrpos($body, "[/share]") + 8))
1934                         return(false);
1935
1936                 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1937                 // Skip if there is no shared message in there
1938                 if ($body == $attributes)
1939                         return(false);
1940
1941                 $guid = "";
1942                 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1943                 if ($matches[1] != "")
1944                         $guid = $matches[1];
1945
1946                 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1947                 if ($matches[1] != "")
1948                         $guid = $matches[1];
1949
1950                 if ($guid != "") {
1951                         $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
1952                                 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
1953                         if ($r) {
1954                                 $ret= array();
1955                                 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
1956                                 $ret["root_guid"] = $guid;
1957                                 return($ret);
1958                         }
1959                 }
1960
1961                 $profile = "";
1962                 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
1963                 if ($matches[1] != "")
1964                         $profile = $matches[1];
1965
1966                 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
1967                 if ($matches[1] != "")
1968                         $profile = $matches[1];
1969
1970                 $ret= array();
1971
1972                 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
1973                 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
1974                         return(false);
1975
1976                 $link = "";
1977                 preg_match("/link='(.*?)'/ism", $attributes, $matches);
1978                 if ($matches[1] != "")
1979                         $link = $matches[1];
1980
1981                 preg_match('/link="(.*?)"/ism', $attributes, $matches);
1982                 if ($matches[1] != "")
1983                         $link = $matches[1];
1984
1985                 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
1986                 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
1987                         return(false);
1988                 return($ret);
1989         }
1990
1991         public static function send_status($item, $owner, $contact, $public_batch = false) {
1992
1993                 $myaddr = self::my_handle($owner);
1994
1995                 $public = (($item["private"]) ? "false" : "true");
1996
1997                 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
1998
1999                 // Detect a share element and do a reshare
2000                 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
2001                         $message = array("root_diaspora_id" => $ret["root_handle"],
2002                                         "root_guid" => $ret["root_guid"],
2003                                         "guid" => $item["guid"],
2004                                         "diaspora_handle" => $myaddr,
2005                                         "public" => $public,
2006                                         "created_at" => $created,
2007                                         "provider_display_name" => $item["app"]);
2008
2009                         $type = "reshare";
2010                 } else {
2011                         $title = $item["title"];
2012                         $body = $item["body"];
2013
2014                         // convert to markdown
2015                         $body = html_entity_decode(bb2diaspora($body));
2016
2017                         // Adding the title
2018                         if(strlen($title))
2019                                 $body = "## ".html_entity_decode($title)."\n\n".$body;
2020
2021                         if ($item["attach"]) {
2022                                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
2023                                 if(cnt) {
2024                                         $body .= "\n".t("Attachments:")."\n";
2025                                         foreach($matches as $mtch)
2026                                                 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
2027                                 }
2028                         }
2029
2030                         $location = array();
2031
2032                         if ($item["location"] != "")
2033                                 $location["address"] = $item["location"];
2034
2035                         if ($item["coord"] != "") {
2036                                 $coord = explode(" ", $item["coord"]);
2037                                 $location["lat"] = $coord[0];
2038                                 $location["lng"] = $coord[1];
2039                         }
2040
2041                         $message = array("raw_message" => $body,
2042                                         "location" => $location,
2043                                         "guid" => $item["guid"],
2044                                         "diaspora_handle" => $myaddr,
2045                                         "public" => $public,
2046                                         "created_at" => $created,
2047                                         "provider_display_name" => $item["app"]);
2048
2049                         if (count($location) == 0)
2050                                 unset($message["location"]);
2051
2052                         $type = "status_message";
2053                 }
2054
2055                 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2056         }
2057
2058         private function construct_like($item, $owner) {
2059
2060                 $myaddr = self::my_handle($owner);
2061
2062                 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
2063                         dbesc($item["thr-parent"]));
2064                 if(!$p)
2065                         return false;
2066
2067                 $parent = $p[0];
2068
2069                 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
2070                 $positive = "true";
2071
2072                 return(array("positive" => $positive,
2073                                 "guid" => $item["guid"],
2074                                 "target_type" => $target_type,
2075                                 "parent_guid" => $parent["guid"],
2076                                 "author_signature" => $authorsig,
2077                                 "diaspora_handle" => $myaddr));
2078         }
2079
2080         private function construct_comment($item, $owner) {
2081
2082                 $myaddr = self::my_handle($owner);
2083
2084                 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2085                         intval($item["parent"]),
2086                         intval($item["parent"])
2087                 );
2088
2089                 if (!$p)
2090                         return false;
2091
2092                 $parent = $p[0];
2093
2094                 $text = html_entity_decode(bb2diaspora($item["body"]));
2095
2096                 return(array("guid" => $item["guid"],
2097                                 "parent_guid" => $parent["guid"],
2098                                 "author_signature" => "",
2099                                 "text" => $text,
2100                                 "diaspora_handle" => $myaddr));
2101         }
2102
2103         public static function send_followup($item,$owner,$contact,$public_batch = false) {
2104
2105                 if($item['verb'] === ACTIVITY_LIKE) {
2106                         $message = self::construct_like($item, $owner);
2107                         $type = "like";
2108                 } else {
2109                         $message = self::construct_comment($item, $owner);
2110                         $type = "comment";
2111                 }
2112
2113                 if (!$message)
2114                         return false;
2115
2116                 $message["author_signature"] = self::signature($owner, $message);
2117
2118                 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2119         }
2120
2121         function send_relay($item, $owner, $contact, $public_batch = false) {
2122
2123                 if ($item["deleted"]) {
2124                         $sql_sign_id = "retract_iid";
2125                         $type = "relayable_retraction";
2126                 } elseif ($item['verb'] === ACTIVITY_LIKE) {
2127                         $sql_sign_id = "iid";
2128                         $type = "like";
2129                 } else {
2130                         $sql_sign_id = "iid";
2131                         $type = "comment";
2132                 }
2133
2134                 // fetch the original signature if the relayable was created by a Diaspora
2135                 // or DFRN user.
2136
2137                 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `".$sql_sign_id."` = %d LIMIT 1",
2138                         intval($item["id"])
2139                 );
2140
2141                 if (!$r)
2142                         return self::send_followup($item, $owner, $contact, $public_batch);
2143
2144                 $orig_sign = $r[0];
2145
2146                 // Old way - is used by the internal Friendica functions
2147                 /// @todo Change all signatur storing functions to the new format
2148                 if ($orig_sign['signed_text'] AND $orig_sign['signature'] AND $orig_sign['signer']) {
2149
2150                         // Split the signed text
2151                         $signed_parts = explode(";", $orig_sign['signed_text']);
2152
2153                         if ($item["deleted"])
2154                                 $message = array("parent_author_signature" => "",
2155                                                 "target_guid" => $signed_parts[0],
2156                                                 "target_type" => $signed_parts[1],
2157                                                 "sender_handle" => $orig_sign['signer'],
2158                                                 "target_author_signature" => $orig_sign['signature']);
2159                         elseif ($item['verb'] === ACTIVITY_LIKE)
2160                                 $message = array("positive" => $signed_parts[0],
2161                                                 "guid" => $signed_parts[1],
2162                                                 "target_type" => $signed_parts[2],
2163                                                 "parent_guid" => $signed_parts[3],
2164                                                 "parent_author_signature" => "",
2165                                                 "author_signature" => $orig_sign['signature'],
2166                                                 "diaspora_handle" => $signed_parts[4]);
2167                         else {
2168                                 // Remove the comment guid
2169                                 $guid = array_shift($signed_parts);
2170
2171                                 // Remove the parent guid
2172                                 $parent_guid = array_shift($signed_parts);
2173
2174                                 // Remove the handle
2175                                 $handle = array_pop($signed_parts);
2176
2177                                 // Glue the parts together
2178                                 $text = implode(";", $signed_parts);
2179
2180                                 $message = array("guid" => $guid,
2181                                                 "parent_guid" => $parent_guid,
2182                                                 "parent_author_signature" => "",
2183                                                 "author_signature" => $orig_sign['signature'],
2184                                                 "text" => implode(";", $signed_parts),
2185                                                 "diaspora_handle" => $handle);
2186                         }
2187                 } else { // New way
2188                         $message = json_decode($orig_sign['signed_text']);
2189                 }
2190
2191                 if ($item["deleted"]) {
2192                         $signed_text = $message["target_guid"].';'.$message["target_type"];
2193                         $message["parent_author_signature"] = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2194                 } else
2195                         $message["parent_author_signature"] = self::signature($owner, $message);
2196
2197                 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2198         }
2199
2200         public static function send_retraction($item, $owner, $contact, $public_batch = false) {
2201
2202                 $myaddr = self::my_handle($owner);
2203
2204                 // Check whether the retraction is for a top-level post or whether it's a relayable
2205                 if ($item["uri"] !== $item["parent-uri"]) {
2206                         $msg_type = "relayable_retraction";
2207                         $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
2208                 } else {
2209                         $msg_type = "signed_retraction";
2210                         $target_type = "StatusMessage";
2211                 }
2212
2213                 $signed_text = $item["guid"].";".$target_type;
2214
2215                 $message = array("target_guid" => $item['guid'],
2216                                 "target_type" => $target_type,
2217                                 "sender_handle" => $myaddr,
2218                                 "target_author_signature" => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
2219
2220                 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
2221         }
2222
2223         public static function send_mail($item, $owner, $contact) {
2224
2225                 $myaddr = self::my_handle($owner);
2226
2227                 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2228                         intval($item["convid"]),
2229                         intval($item["uid"])
2230                 );
2231
2232                 if (!count($r)) {
2233                         logger("conversation not found.");
2234                         return;
2235                 }
2236                 $cnv = $r[0];
2237
2238                 $conv = array(
2239                         "guid" => $cnv["guid"],
2240                         "subject" => $cnv["subject"],
2241                         "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2242                         "diaspora_handle" => $cnv["creator"],
2243                         "participant_handles" => $cnv["recips"]
2244                 );
2245
2246                 $body = bb2diaspora($item["body"]);
2247                 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2248
2249                 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
2250                 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2251
2252                 $msg = array(
2253                         "guid" => $item["guid"],
2254                         "parent_guid" => $cnv["guid"],
2255                         "parent_author_signature" => $sig,
2256                         "author_signature" => $sig,
2257                         "text" => $body,
2258                         "created_at" => $created,
2259                         "diaspora_handle" => $myaddr,
2260                         "conversation_guid" => $cnv["guid"]
2261                 );
2262
2263                 if ($item["reply"]) {
2264                         $message = $msg;
2265                         $type = "message";
2266                 } else {
2267                         $message = array("guid" => $cnv["guid"],
2268                                         "subject" => $cnv["subject"],
2269                                         "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2270                                         "message" => $msg,
2271                                         "diaspora_handle" => $cnv["creator"],
2272                                         "participant_handles" => $cnv["recips"]);
2273
2274                         $type = "conversation";
2275                 }
2276
2277                 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
2278         }
2279 }
2280 ?>