]> git.mxchange.org Git - friendica.git/blob - include/diaspora2.php
e8ed80ee8047836fd4d72bc706cc64145187576a
[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/api.php");
15
16 class xml {
17         function from_array($array, &$xml) {
18
19                 if (!is_object($xml)) {
20                         foreach($array as $key => $value) {
21                                 $root = new SimpleXMLElement('<'.$key.'/>');
22                                 array_to_xml($value, $root);
23
24                                 $dom = dom_import_simplexml($root)->ownerDocument;
25                                 $dom->formatOutput = true;
26                                 return $dom->saveXML();
27                         }
28                 }
29
30                 foreach($array as $key => $value) {
31                         if (!is_array($value) AND !is_numeric($key))
32                                 $xml->addChild($key, $value);
33                         elseif (is_array($value))
34                                 array_to_xml($value, $xml->addChild($key));
35                 }
36         }
37
38         function copy(&$source, &$target, $elementname) {
39                 if (count($source->children()) == 0)
40                         $target->addChild($elementname, $source);
41                 else {
42                         $child = $target->addChild($elementname);
43                         foreach ($source->children() AS $childfield => $childentry)
44                                 self::copy($childentry, $child, $childfield);
45                 }
46         }
47 }
48 /**
49  * @brief This class contain functions to create and send Diaspora XML files
50  *
51  */
52 class diaspora {
53
54         public static function dispatch_public($msg) {
55
56                 $enabled = intval(get_config("system", "diaspora_enabled"));
57                 if (!$enabled) {
58                         logger("diaspora is disabled");
59                         return false;
60                 }
61
62                 // Use a dummy importer to import the data for the public copy
63                 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
64                 $item_id = self::dispatch($importer,$msg);
65
66                 // Now distribute it to the followers
67                 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
68                         (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
69                         AND NOT `account_expired` AND NOT `account_removed`",
70                         dbesc(NETWORK_DIASPORA),
71                         dbesc($msg["author"])
72                 );
73                 if(count($r)) {
74                         foreach($r as $rr) {
75                                 logger("delivering to: ".$rr["username"]);
76                                 self::dispatch($rr,$msg);
77                         }
78                 } else
79                         logger("No subscribers for ".$msg["author"]." ".print_r($msg, true));
80
81                 return $item_id;
82         }
83
84         public static function dispatch($importer, $msg) {
85
86                 // The sender is the handle of the contact that sent the message.
87                 // This will often be different with relayed messages (for example "like" and "comment")
88                 $sender = $msg["author"];
89
90                 if (!diaspora::valid_posting($msg, $fields)) {
91                         logger("Invalid posting");
92                         return false;
93                 }
94
95                 $type = $fields->getName();
96
97                 switch ($type) {
98                         case "account_deletion":
99                                 return true;
100                                 //return self::import_account_deletion($importer, $fields);
101
102                         case "comment":
103                                 return true;
104                                 //return self::import_comment($importer, $sender, $fields);
105
106                         case "conversation":
107                                 return self::import_conversation($importer, $fields);
108
109                         case "like":
110                                 return true;
111                                 //return self::import_like($importer, $sender, $fields);
112
113                         case "message":
114                                 return true;
115                                 //return self::import_message($importer, $fields);
116
117                         case "participation": // Not implemented
118                                 return self::import_participation($importer, $fields);
119
120                         case "photo":
121                                 return self::import_photo($importer, $fields);
122
123                         case "poll_participation": // Not implemented
124                                 return self::import_poll_participation($importer, $fields);
125
126                         case "profile":
127                                 return true;
128                                 //return self::import_profile($importer, $fields);
129
130                         case "request":
131                                 return self::import_request($importer, $fields);
132
133                         case "reshare":
134                                 return true;
135                                 //return self::import_reshare($importer, $fields);
136
137                         case "retraction":
138                                 return self::import_retraction($importer, $fields);
139
140                         case "status_message":
141                                 return true;
142                                 //return self::import_status_message($importer, $fields, $msg, $data2);
143
144                         default:
145                                 logger("Unknown message type ".$type);
146                                 return false;
147                 }
148
149                 return true;
150         }
151
152         /**
153          * @brief Checks if a posting is valid and fetches the data fields.
154          *
155          * This function does not only check the signature.
156          * It also does the conversion between the old and the new diaspora format.
157          *
158          * @param array $msg Array with the XML, the sender handle and the sender signature
159          * @param object $fields SimpleXML object that contains the posting when it is valid
160          *
161          * @return bool Is the posting valid?
162          */
163         private function valid_posting($msg, &$fields) {
164
165                 $data = parse_xml_string($msg["message"], false);
166
167                 if (!is_object($data))
168                         return false;
169
170                 $first_child = $data->getName();
171
172                 // Is this the new or the old version?
173                 if ($data->getName() == "XML") {
174                         $oldXML = true;
175                         foreach ($data->post->children() as $child)
176                                 $element = $child;
177                 } else {
178                         $oldXML = false;
179                         $element = $data;
180                 }
181
182                 $type = $element->getName();
183
184                 // All retractions are handled identically from now on.
185                 // In the new version there will only be "retraction".
186                 if (in_array($type, array("signed_retraction", "relayable_retraction")))
187                         $type = "retraction";
188
189                 $fields = new SimpleXMLElement("<".$type."/>");
190
191                 $signed_data = "";
192
193                 foreach ($element->children() AS $fieldname => $entry) {
194                         if ($oldXML) {
195                                 // Translation for the old XML structure
196                                 if ($fieldname == "diaspora_handle")
197                                         $fieldname = "author";
198
199                                 if ($fieldname == "participant_handles")
200                                         $fieldname = "participants";
201
202                                 if (in_array($type, array("like", "participation"))) {
203                                         if ($fieldname == "target_type")
204                                                 $fieldname = "parent_type";
205                                 }
206
207                                 if ($fieldname == "sender_handle")
208                                         $fieldname = "author";
209
210                                 if ($fieldname == "recipient_handle")
211                                         $fieldname = "recipient";
212
213                                 if ($fieldname == "root_diaspora_id")
214                                         $fieldname = "root_author";
215
216                                 if ($type == "retraction") {
217                                         if ($fieldname == "post_guid")
218                                                 $fieldname = "target_guid";
219
220                                         if ($fieldname == "type")
221                                                 $fieldname = "target_type";
222                                 }
223                         }
224
225                         if ($fieldname == "author_signature")
226                                 $author_signature = base64_decode($entry);
227                         elseif ($fieldname == "parent_author_signature")
228                                 $parent_author_signature = base64_decode($entry);
229                         elseif ($fieldname != "target_author_signature") {
230                                 if ($signed_data != "") {
231                                         $signed_data .= ";";
232                                         $signed_data_parent .= ";";
233                                 }
234
235                                 $signed_data .= $entry;
236                         }
237                         if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")))
238                                 xml::copy($entry, $fields, $fieldname);
239                 }
240
241                 // This is something that shouldn't happen at all.
242                 if (in_array($type, array("status_message", "reshare", "profile")))
243                         if ($msg["author"] != $fields->author) {
244                                 logger("Message handle is not the same as envelope sender. Quitting this message.");
245                                 return false;
246                         }
247
248                 // Only some message types have signatures. So we quit here for the other types.
249                 if (!in_array($type, array("comment", "conversation", "message", "like")))
250                         return true;
251
252                 // No author_signature? This is a must, so we quit.
253                 if (!isset($author_signature))
254                         return false;
255
256                 if (isset($parent_author_signature)) {
257                         $key = self::get_key($msg["author"]);
258
259                         if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256"))
260                                 return false;
261                 }
262
263                 $key = self::get_key($fields->author);
264
265                 return rsa_verify($signed_data, $author_signature, $key, "sha256");
266         }
267
268         private function get_key($handle) {
269                 logger("Fetching diaspora key for: ".$handle);
270
271                 $r = self::get_person_by_handle($handle);
272                 if($r)
273                         return $r["pubkey"];
274
275                 return "";
276         }
277
278         private function get_person_by_handle($handle) {
279
280                 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
281                         dbesc(NETWORK_DIASPORA),
282                         dbesc($handle)
283                 );
284                 if (count($r)) {
285                         $person = $r[0];
286                         logger("In cache ".print_r($r,true), LOGGER_DEBUG);
287
288                         // update record occasionally so it doesn't get stale
289                         $d = strtotime($person["updated"]." +00:00");
290                         if ($d < strtotime("now - 14 days"))
291                                 $update = true;
292                 }
293
294                 if (!$person OR $update) {
295                         logger("create or refresh", LOGGER_DEBUG);
296                         $r = probe_url($handle, PROBE_DIASPORA);
297
298                         // Note that Friendica contacts will return a "Diaspora person"
299                         // if Diaspora connectivity is enabled on their server
300                         if (count($r) AND ($r["network"] === NETWORK_DIASPORA)) {
301                                 self::add_fcontact($r, $update);
302                                 $person = $r;
303                         }
304                 }
305                 return $person;
306         }
307
308         private function add_fcontact($arr, $update = false) {
309                 /// @todo Remove this function from include/network.php
310
311                 if($update) {
312                         $r = q("UPDATE `fcontact` SET
313                                         `name` = '%s',
314                                         `photo` = '%s',
315                                         `request` = '%s',
316                                         `nick` = '%s',
317                                         `addr` = '%s',
318                                         `batch` = '%s',
319                                         `notify` = '%s',
320                                         `poll` = '%s',
321                                         `confirm` = '%s',
322                                         `alias` = '%s',
323                                         `pubkey` = '%s',
324                                         `updated` = '%s'
325                                 WHERE `url` = '%s' AND `network` = '%s'",
326                                         dbesc($arr["name"]),
327                                         dbesc($arr["photo"]),
328                                         dbesc($arr["request"]),
329                                         dbesc($arr["nick"]),
330                                         dbesc($arr["addr"]),
331                                         dbesc($arr["batch"]),
332                                         dbesc($arr["notify"]),
333                                         dbesc($arr["poll"]),
334                                         dbesc($arr["confirm"]),
335                                         dbesc($arr["alias"]),
336                                         dbesc($arr["pubkey"]),
337                                         dbesc(datetime_convert()),
338                                         dbesc($arr["url"]),
339                                         dbesc($arr["network"])
340                                 );
341                 } else {
342                         $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`,
343                                         `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
344                                 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
345                                         dbesc($arr["url"]),
346                                         dbesc($arr["name"]),
347                                         dbesc($arr["photo"]),
348                                         dbesc($arr["request"]),
349                                         dbesc($arr["nick"]),
350                                         dbesc($arr["addr"]),
351                                         dbesc($arr["batch"]),
352                                         dbesc($arr["notify"]),
353                                         dbesc($arr["poll"]),
354                                         dbesc($arr["confirm"]),
355                                         dbesc($arr["network"]),
356                                         dbesc($arr["alias"]),
357                                         dbesc($arr["pubkey"]),
358                                         dbesc(datetime_convert())
359                                 );
360                 }
361
362                 return $r;
363         }
364
365         private function get_contact_by_handle($uid, $handle) {
366                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
367                         intval($uid),
368                         dbesc($handle)
369                 );
370
371                 if ($r AND count($r))
372                         return $r[0];
373
374                 $handle_parts = explode("@", $handle);
375                 $nurl_sql = '%%://' . $handle_parts[1] . '%%/profile/' . $handle_parts[0];
376                 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
377                         dbesc(NETWORK_DFRN),
378                         intval($uid),
379                         dbesc($nurl_sql)
380                 );
381                 if($r AND count($r))
382                         return $r[0];
383
384                 return false;
385         }
386
387         private function post_allow($importer, $contact, $is_comment = false) {
388
389                 // perhaps we were already sharing with this person. Now they're sharing with us.
390                 // That makes us friends.
391                 // Normally this should have handled by getting a request - but this could get lost
392                 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
393                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
394                                 intval(CONTACT_IS_FRIEND),
395                                 intval($contact["id"]),
396                                 intval($importer["uid"])
397                         );
398                         $contact["rel"] = CONTACT_IS_FRIEND;
399                         logger("defining user ".$contact["nick"]." as friend");
400                 }
401
402                 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
403                         return false;
404                 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
405                         return true;
406                 if($contact["rel"] == CONTACT_IS_FOLLOWER)
407                         if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
408                                 return true;
409
410                 // Messages for the global users are always accepted
411                 if ($importer["uid"] == 0)
412                         return true;
413
414                 return false;
415         }
416
417         private function get_allowed_contact_by_handle($importer, $handle, $is_comment = false) {
418                 $contact = self::get_contact_by_handle($importer["uid"], $handle);
419                 if (!$contact) {
420                         logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
421                         return false;
422                 }
423
424                 if (!self::post_allow($importer, $contact, false)) {
425                         logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
426                         return false;
427                 }
428                 return $contact;
429         }
430
431         private function message_exists($uid, $guid) {
432                 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
433                         intval($uid),
434                         dbesc($guid)
435                 );
436
437                 if(count($r)) {
438                         logger("message ".$guid." already exists for user ".$uid);
439                         return false;
440                 }
441
442                 return true;
443         }
444
445         private function fetch_guid($item) {
446                 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
447                         function ($match) use ($item){
448                                 return(self::fetch_guid_sub($match, $item));
449                         },$item["body"]);
450         }
451
452         private function fetch_guid_sub($match, $item) {
453                 if (!self::store_by_guid($match[1], $item["author-link"]))
454                         self::store_by_guid($match[1], $item["owner-link"]);
455         }
456
457         private function store_by_guid($guid, $server, $uid = 0) {
458                 $serverparts = parse_url($server);
459                 $server = $serverparts["scheme"]."://".$serverparts["host"];
460
461                 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
462
463                 $msg = self::fetch_message($guid, $server);
464
465                 if (!$msg)
466                         return false;
467
468                 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
469
470                 // Now call the dispatcher
471                 return self::dispatch_public($msg);
472         }
473
474         private function fetch_message($guid, $server, $level = 0) {
475
476                 if ($level > 5)
477                         return false;
478
479                 // This will not work if the server is not a Diaspora server
480                 $source_url = $server."/p/".$guid.".xml";
481                 $x = fetch_url($source_url);
482                 if(!$x)
483                         return false;
484
485                 /// @todo - should maybe solved by the dispatcher
486                 $source_xml = parse_xml_string($x, false);
487
488                 if (!is_object($source_xml))
489                         return false;
490
491                 if ($source_xml->post->reshare) {
492                         // Reshare of a reshare - old Diaspora version
493                         return self::fetch_message($source_xml->post->reshare->root_guid, $server, ++$level);
494                 } elseif ($source_xml->getName() == "reshare") {
495                         // Reshare of a reshare - new Diaspora version
496                         return self::fetch_message($source_xml->root_guid, $server, ++$level);
497                 }
498
499                 // Fetch the author - for the old and the new Diaspora version
500                 if ($source_xml->post->status_message->diaspora_handle)
501                         $author = (string)$source_xml->post->status_message->diaspora_handle;
502                 elseif ($source_xml->author)
503                         $author = (string)$source_xml->author;
504
505                 if (!$author)
506                         return false;
507
508                 $msg = array("message" => $x, "author" => $author);
509
510                 // We don't really need this, but until the work is unfinished we better will keep this
511                 $msg["key"] = self::get_key($msg["author"]);
512
513                 return $msg;
514         }
515
516         private function fetch_parent_item($uid, $guid, $author, $contact) {
517                 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
518                                 `author-name`, `author-link`, `author-avatar`,
519                                 `owner-name`, `owner-link`, `owner-avatar`
520                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
521                         intval($uid), dbesc($guid));
522
523                 if(!count($r)) {
524                         $result = self::store_by_guid($guid, $contact["url"], $uid);
525
526                         if (!$result) {
527                                 $person = self::get_person_by_handle($author);
528                                 $result = self::store_by_guid($guid, $person["url"], $uid);
529                         }
530
531                         if ($result) {
532                                 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
533
534                                 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
535                                                 `author-name`, `author-link`, `author-avatar`,
536                                                 `owner-name`, `owner-link`, `owner-avatar`
537                                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
538                                         intval($uid), dbesc($guid));
539                         }
540                 }
541
542                 if (!count($r)) {
543                         logger("parent item not found: parent: ".$guid." item: ".$guid);
544                         return false;
545                 } else
546                         return $r[0];
547         }
548
549         private function get_author_contact_by_url($contact, $person, $uid) {
550
551                 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
552                         dbesc(normalise_link($person["url"])), intval($uid));
553                 if ($r) {
554                         $cid = $r[0]["id"];
555                         $network = $r[0]["network"];
556                 } else {
557                         $cid = $contact["id"];
558                         $network = NETWORK_DIASPORA;
559                 }
560
561                 return (array("cid" => $cid, "network" => $network));
562         }
563
564         public static function is_redmatrix($url) {
565                 return(strstr($url, "/channel/"));
566         }
567
568         private function plink($addr, $guid) {
569                 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
570
571                 // Fallback
572                 if (!$r)
573                         return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
574
575                 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
576                 // So we try another way as well.
577                 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
578                 if ($s)
579                         $r[0]["network"] = $s[0]["network"];
580
581                 if ($r[0]["network"] == NETWORK_DFRN)
582                         return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
583
584                 if (self::is_redmatrix($r[0]["url"]))
585                         return $r[0]["url"]."/?f=&mid=".$guid;
586
587                 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
588         }
589
590         private function import_account_deletion($importer, $data) {
591                 $author = notags(unxmlify($data->author));
592
593                 $contact = self::get_contact_by_handle($importer["uid"], $author);
594                 if (!$contact) {
595                         logger("cannot find contact for author: ".$author);
596                         return false;
597                 }
598
599                 // We now remove the contact
600                 contact_remove($contact["id"]);
601                 return true;
602         }
603
604         private function import_comment($importer, $sender, $data) {
605                 $guid = notags(unxmlify($data->guid));
606                 $parent_guid = notags(unxmlify($data->parent_guid));
607                 $text = unxmlify($data->text);
608                 $author = notags(unxmlify($data->author));
609
610                 $contact = self::get_allowed_contact_by_handle($importer, $sender, true);
611                 if (!$contact)
612                         return false;
613
614                 if (self::message_exists($importer["uid"], $guid))
615                         return false;
616
617                 $parent_item = self::fetch_parent_item($importer["uid"], $parent_guid, $author, $contact);
618                 if (!$parent_item)
619                         return false;
620
621                 $person = self::get_person_by_handle($author);
622                 if (!is_array($person)) {
623                         logger("unable to find author details");
624                         return false;
625                 }
626
627                 // Fetch the contact id - if we know this contact
628                 $author_contact = self::get_author_contact_by_url($contact, $person, $importer["uid"]);
629
630                 $datarray = array();
631
632                 $datarray["uid"] = $importer["uid"];
633                 $datarray["contact-id"] = $author_contact["cid"];
634                 $datarray["network"]  = $author_contact["network"];
635
636                 $datarray["author-name"] = $person["name"];
637                 $datarray["author-link"] = $person["url"];
638                 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
639
640                 $datarray["owner-name"] = $contact["name"];
641                 $datarray["owner-link"] = $contact["url"];
642                 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
643
644                 $datarray["guid"] = $guid;
645                 $datarray["uri"] = $author.":".$guid;
646
647                 $datarray["type"] = "remote-comment";
648                 $datarray["verb"] = ACTIVITY_POST;
649                 $datarray["gravity"] = GRAVITY_COMMENT;
650                 $datarray["parent-uri"] = $parent_item["uri"];
651
652                 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
653                 $datarray["object"] = json_encode($data);
654
655                 $datarray["body"] = diaspora2bb($text);
656
657                 self::fetch_guid($datarray);
658
659                 $message_id = item_store($datarray);
660                 // print_r($datarray);
661
662                 // If we are the origin of the parent we store the original data and notify our followers
663                 if($message_id AND $parent_item["origin"]) {
664
665                         // Formerly we stored the signed text, the signature and the author in different fields.
666                         // The new Diaspora protocol can have variable fields. We now store the data in correct order in a single field.
667                         q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
668                                 intval($message_id),
669                                 dbesc(json_encode($data))
670                         );
671
672                         // notify others
673                         proc_run("php", "include/notifier.php", "comment-import", $message_id);
674                 }
675
676                 return $message_id;
677         }
678
679         private function import_conversation($importer, $data) {
680                 print_r($data);
681                 die();
682 /*
683         $guid = notags(unxmlify($xml->guid));
684         $subject = notags(unxmlify($xml->subject));
685         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
686         $participant_handles = notags(unxmlify($xml->participant_handles));
687         $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
688
689         $parent_uri = $diaspora_handle . ':' . $guid;
690
691         $messages = $xml->message;
692
693         if(! count($messages)) {
694                 logger('diaspora_conversation: empty conversation');
695                 return;
696         }
697
698                 $contact = self::get_allowed_contact_by_handle($importer, $sender, true)
699                 if (!$contact)
700                         return false;
701
702         $conversation = null;
703
704         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
705                 intval($importer['uid']),
706                 dbesc($guid)
707         );
708         if(count($c))
709                 $conversation = $c[0];
710         else {
711                 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
712                         intval($importer['uid']),
713                         dbesc($guid),
714                         dbesc($diaspora_handle),
715                         dbesc(datetime_convert('UTC','UTC',$created_at)),
716                         dbesc(datetime_convert()),
717                         dbesc($subject),
718                         dbesc($participant_handles)
719                 );
720                 if($r)
721                         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
722                 intval($importer['uid']),
723             dbesc($guid)
724         );
725             if(count($c))
726             $conversation = $c[0];
727         }
728         if(! $conversation) {
729                 logger('diaspora_conversation: unable to create conversation.');
730                 return;
731         }
732
733         foreach($messages as $mesg) {
734
735                 $reply = 0;
736
737                 $msg_guid = notags(unxmlify($mesg->guid));
738                 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
739                 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
740                 $msg_author_signature = notags(unxmlify($mesg->author_signature));
741                 $msg_text = unxmlify($mesg->text);
742                 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
743                 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
744                 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
745                 if($msg_conversation_guid != $guid) {
746                         logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
747                         continue;
748                 }
749
750                 $body = diaspora2bb($msg_text);
751                 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
752
753                 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
754
755                 $author_signature = base64_decode($msg_author_signature);
756
757                 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
758                         $person = $contact;
759                         $key = $msg['key'];
760                 }
761                 else {
762                         $person = find_diaspora_person_by_handle($msg_diaspora_handle); 
763
764                         if(is_array($person) && x($person,'pubkey'))
765                                 $key = $person['pubkey'];
766                         else {
767                                 logger('diaspora_conversation: unable to find author details');
768                                 continue;
769                         }
770                 }
771
772                 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
773                         logger('diaspora_conversation: verification failed.');
774                         continue;
775                 }
776
777                 if($msg_parent_author_signature) {
778                         $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
779
780                         $parent_author_signature = base64_decode($msg_parent_author_signature);
781
782                         $key = $msg['key'];
783
784                         if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
785                                 logger('diaspora_conversation: owner verification failed.');
786                                 continue;
787                         }
788                 }
789
790                 $r = q("select id from mail where `uri` = '%s' limit 1",
791                         dbesc($message_id)
792                 );
793                 if(count($r)) {
794                         logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
795                         continue;
796                 }
797
798                 q("insert into mail ( `uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`) values ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
799                         intval($importer['uid']),
800                         dbesc($msg_guid),
801                         intval($conversation['id']),
802                         dbesc($person['name']),
803                         dbesc($person['photo']),
804                         dbesc($person['url']),
805                         intval($contact['id']),
806                         dbesc($subject),
807                         dbesc($body),
808                         0,
809                         0,
810                         dbesc($message_id),
811                         dbesc($parent_uri),
812                         dbesc($msg_created_at)
813                 );
814
815                 q("update conv set updated = '%s' where id = %d",
816                         dbesc(datetime_convert()),
817                         intval($conversation['id'])
818                 );
819
820                 notification(array(
821                         'type' => NOTIFY_MAIL,
822                         'notify_flags' => $importer['notify-flags'],
823                         'language' => $importer['language'],
824                         'to_name' => $importer['username'],
825                         'to_email' => $importer['email'],
826                         'uid' =>$importer['uid'],
827                         'item' => array('subject' => $subject, 'body' => $body),
828                         'source_name' => $person['name'],
829                         'source_link' => $person['url'],
830                         'source_photo' => $person['thumb'],
831                         'verb' => ACTIVITY_POST,
832                         'otype' => 'mail'
833                 ));
834         }
835 */
836                 return true;
837         }
838
839         private function construct_like_body($contact, $parent_item, $guid) {
840                 $bodyverb = t('%1$s likes %2$s\'s %3$s');
841
842                 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
843                 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
844                 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
845
846                 return sprintf($bodyverb, $ulink, $alink, $plink);
847         }
848
849         private function construct_like_object($importer, $parent_item) {
850                 $objtype = ACTIVITY_OBJ_NOTE;
851                 $link = xmlify('<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />'."\n") ;
852                 $parent_body = $parent_item["body"];
853
854                 $obj = <<< EOT
855
856                 <object>
857                         <type>$objtype</type>
858                         <local>1</local>
859                         <id>{$parent_item["uri"]}</id>
860                         <link>$link</link>
861                         <title></title>
862                         <content>$parent_body</content>
863                 </object>
864 EOT;
865
866                 return $obj;
867         }
868
869         private function import_like($importer, $sender, $data) {
870                 $positive = notags(unxmlify($data->positive));
871                 $guid = notags(unxmlify($data->guid));
872                 $parent_type = notags(unxmlify($data->parent_type));
873                 $parent_guid = notags(unxmlify($data->parent_guid));
874                 $author = notags(unxmlify($data->author));
875
876                 // likes on comments aren't supported by Diaspora - only on posts
877                 if ($parent_type !== "Post")
878                         return false;
879
880                 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
881                 if ($positive === "false") {
882                         return false;
883                 }
884
885                 $contact = self::get_allowed_contact_by_handle($importer, $sender, true);
886                 if (!$contact)
887                         return false;
888
889                 if (self::message_exists($importer["uid"], $guid))
890                         return false;
891
892                 $parent_item = self::fetch_parent_item($importer["uid"], $parent_guid, $author, $contact);
893                 if (!$parent_item)
894                         return false;
895
896                 $person = self::get_person_by_handle($author);
897                 if (!is_array($person)) {
898                         logger("unable to find author details");
899                         return false;
900                 }
901
902                 // Fetch the contact id - if we know this contact
903                 $author_contact = self::get_author_contact_by_url($contact, $person, $importer["uid"]);
904
905                 $datarray = array();
906
907                 $datarray["uid"] = $importer["uid"];
908                 $datarray["contact-id"] = $author_contact["cid"];
909                 $datarray["network"]  = $author_contact["network"];
910
911                 $datarray["author-name"] = $person["name"];
912                 $datarray["author-link"] = $person["url"];
913                 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
914
915                 $datarray["owner-name"] = $contact["name"];
916                 $datarray["owner-link"] = $contact["url"];
917                 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
918
919                 $datarray["guid"] = $guid;
920                 $datarray["uri"] = $author.":".$guid;
921
922                 $datarray["type"] = "activity";
923                 $datarray["verb"] = ACTIVITY_LIKE;
924                 $datarray["gravity"] = GRAVITY_LIKE;
925                 $datarray["parent-uri"] = $parent_item["uri"];
926
927                 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
928                 $datarray["object"] = self::construct_like_object($importer, $parent_item);
929
930                 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
931
932                 $message_id = item_store($datarray);
933                 //print_r($datarray);
934
935                 // If we are the origin of the parent we store the original data and notify our followers
936                 if($message_id AND $parent_item["origin"]) {
937
938                         // Formerly we stored the signed text, the signature and the author in different fields.
939                         // The new Diaspora protocol can have variable fields. We now store the data in correct order in a single field.
940                         q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
941                                 intval($message_id),
942                                 dbesc(json_encode($data))
943                         );
944
945                         // notify others
946                         proc_run("php", "include/notifier.php", "comment-import", $message_id);
947                 }
948
949                 return $message_id;
950         }
951
952         private function import_message($importer, $data) {
953                 $guid = notags(unxmlify($data->guid));
954                 $parent_guid = notags(unxmlify($data->parent_guid));
955                 $text = unxmlify($data->text);
956                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
957                 $author = notags(unxmlify($data->author));
958                 $conversation_guid = notags(unxmlify($data->conversation_guid));
959
960                 $parent_uri = $author.":".$parent_guid;
961
962                 $contact = self::get_allowed_contact_by_handle($importer, $author, true);
963                 if (!$contact)
964                         return false;
965
966                 $conversation = null;
967
968                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
969                         intval($importer["uid"]),
970                         dbesc($conversation_guid)
971                 );
972                 if(count($c))
973                         $conversation = $c[0];
974                 else {
975                         logger("conversation not available.");
976                         return false;
977                 }
978
979                 $reply = 0;
980
981                 $body = diaspora2bb($text);
982                 $message_id = $author.":".$guid;
983
984                 $person = self::get_person_by_handle($author);
985                 if (!$person) {
986                         logger("unable to find author details");
987                         return false;
988                 }
989
990                 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
991                         dbesc($message_id),
992                         intval($importer["uid"])
993                 );
994                 if(count($r)) {
995                         logger("duplicate message already delivered.", LOGGER_DEBUG);
996                         return false;
997                 }
998
999                 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1000                                 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1001                         intval($importer["uid"]),
1002                         dbesc($guid),
1003                         intval($conversation["id"]),
1004                         dbesc($person["name"]),
1005                         dbesc($person["photo"]),
1006                         dbesc($person["url"]),
1007                         intval($contact["id"]),
1008                         dbesc($conversation["subject"]),
1009                         dbesc($body),
1010                         0,
1011                         1,
1012                         dbesc($message_id),
1013                         dbesc($parent_uri),
1014                         dbesc($created_at)
1015                 );
1016
1017                 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1018                         dbesc(datetime_convert()),
1019                         intval($conversation["id"])
1020                 );
1021
1022                 return true;
1023         }
1024
1025         private function import_participation($importer, $data) {
1026                 // I'm not sure if we can fully support this message type
1027                 return true;
1028         }
1029
1030         private function import_photo($importer, $data) {
1031                 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1032                 return true;
1033         }
1034
1035         private function import_poll_participation($importer, $data) {
1036                 // We don't support polls by now
1037                 return true;
1038         }
1039
1040         private function import_profile($importer, $data) {
1041                 $author = notags(unxmlify($data->author));
1042
1043                 $contact = self::get_contact_by_handle($importer["uid"], $author);
1044                 if (!$contact)
1045                         return;
1046
1047                 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1048                 $image_url = unxmlify($data->image_url);
1049                 $birthday = unxmlify($data->birthday);
1050                 $location = diaspora2bb(unxmlify($data->location));
1051                 $about = diaspora2bb(unxmlify($data->bio));
1052                 $gender = unxmlify($data->gender);
1053                 $searchable = (unxmlify($data->searchable) == "true");
1054                 $nsfw = (unxmlify($data->nsfw) == "true");
1055                 $tags = unxmlify($data->tag_string);
1056
1057                 $tags = explode("#", $tags);
1058
1059                 $keywords = array();
1060                 foreach ($tags as $tag) {
1061                         $tag = trim(strtolower($tag));
1062                         if ($tag != "")
1063                                 $keywords[] = $tag;
1064                 }
1065
1066                 $keywords = implode(", ", $keywords);
1067
1068                 $handle_parts = explode("@", $author);
1069                 $nick = $handle_parts[0];
1070
1071                 if($name === "")
1072                         $name = $handle_parts[0];
1073
1074                 if( preg_match("|^https?://|", $image_url) === 0)
1075                         $image_url = "http://".$handle_parts[1].$image_url;
1076
1077                 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1078
1079                 // Generic birthday. We don't know the timezone. The year is irrelevant.
1080
1081                 $birthday = str_replace("1000", "1901", $birthday);
1082
1083                 if ($birthday != "")
1084                         $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1085
1086                 // this is to prevent multiple birthday notifications in a single year
1087                 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1088
1089                 if(substr($birthday,5) === substr($contact["bd"],5))
1090                         $birthday = $contact["bd"];
1091
1092                 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1093                                 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1094                         dbesc($name),
1095                         dbesc($nick),
1096                         dbesc($author),
1097                         dbesc(datetime_convert()),
1098                         dbesc($birthday),
1099                         dbesc($location),
1100                         dbesc($about),
1101                         dbesc($keywords),
1102                         dbesc($gender),
1103                         intval($contact["id"]),
1104                         intval($importer["uid"])
1105                 );
1106
1107                 if ($searchable) {
1108                         poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1109                                 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1110                 }
1111
1112                 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1113                                         "photo" => $image_url, "name" => $name, "location" => $location,
1114                                         "about" => $about, "birthday" => $birthday, "gender" => $gender,
1115                                         "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1116                                         "hide" => !$searchable, "nsfw" => $nsfw);
1117
1118                 update_gcontact($gcontact);
1119
1120                 return true;
1121         }
1122
1123         private function import_request($importer, $data) {
1124 print_r($data);
1125 /*
1126         $author = unxmlify($xml->author);
1127         $recipient = unxmlify($xml->recipient);
1128
1129         if (!$author || !$recipient)
1130                 return;
1131
1132         $contact = self::get_contact_by_handle($importer["uid"],$author);
1133
1134         if($contact) {
1135
1136                 // perhaps we were already sharing with this person. Now they're sharing with us.
1137                 // That makes us friends.
1138
1139                 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1140                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1141                                 intval(CONTACT_IS_FRIEND),
1142                                 intval($contact["id"]),
1143                                 intval($importer["uid"])
1144                         );
1145                 }
1146                 // send notification
1147
1148                 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1149                         intval($importer["uid"])
1150                 );
1151
1152                 if((count($r)) && (!$r[0]["hide-friends"]) && (!$contact["hidden"]) && intval(get_pconfig($importer["uid"],'system','post_newfriend'))) {
1153
1154                         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1155                                 intval($importer["uid"])
1156                         );
1157
1158                         // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1159
1160                         if(count($self) && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1161
1162                                 $arr = array();
1163                                 $arr["uri"] = $arr["parent-uri"] = item_new_uri(App::get_hostname(), $importer["uid"]);
1164                                 $arr["uid"] = $importer["uid"];
1165                                 $arr["contact-id"] = $self[0]["id"];
1166                                 $arr["wall"] = 1;
1167                                 $arr["type"] = 'wall';
1168                                 $arr["gravity"] = 0;
1169                                 $arr["origin"] = 1;
1170                                 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1171                                 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1172                                 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1173                                 $arr["verb"] = ACTIVITY_FRIEND;
1174                                 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1175
1176                                 $A = '[url=' . $self[0]["url"] . "]' . $self[0]["name"] . '[/url]';
1177                                 $B = '[url=' . $contact["url"] . "]' . $contact["name"] . '[/url]';
1178                                 $BPhoto = '[url=' . $contact["url"] . "]' . '[img]' . $contact["thumb"] . '[/img][/url]';
1179                                 $arr["body"] =  sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
1180
1181                                 $arr["object"] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact["name"] . '</title>'
1182                                         . '<id>' . $contact["url"] . '/' . $contact["name"] . '</id>';
1183                                 $arr["object"] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact["url"] . '" />' . "\n")
1184 ;
1185                                 $arr["object"] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact["thumb"] . '" />' . "\n");
1186                                 $arr["object"] .= '</link></object>' . "\n";
1187                                 $arr["last-child"] = 1;
1188
1189                                 $arr["allow_cid"] = $user[0]["allow_cid"];
1190                                 $arr["allow_gid"] = $user[0]["allow_gid"];
1191                                 $arr["deny_cid"]  = $user[0]["deny_cid"];
1192                                 $arr["deny_gid"]  = $user[0]["deny_gid"];
1193
1194                                 $i = item_store($arr);
1195                                 if($i)
1196                                 proc_run('php',"include/notifier.php","activity","$i");
1197
1198                         }
1199
1200                 }
1201
1202                 return;
1203         }
1204
1205         $ret = self::get_person_by_handle($author);
1206
1207
1208         if((! count($ret)) || ($ret["network"] != NETWORK_DIASPORA)) {
1209                 logger('diaspora_request: Cannot resolve diaspora handle ' . $author . ' for ' . $recipient);
1210                 return;
1211         }
1212
1213         $batch = (($ret["batch"]) ? $ret["batch"] : implode('/', array_slice(explode('/',$ret["url"]),0,3)) . '/receive/public');
1214
1215
1216
1217         $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1218                 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
1219                 intval($importer["uid"]),
1220                 dbesc($ret["network"]),
1221                 dbesc($ret["addr"]),
1222                 datetime_convert(),
1223                 dbesc($ret["url"]),
1224                 dbesc(normalise_link($ret["url"])),
1225                 dbesc($batch),
1226                 dbesc($ret["name"]),
1227                 dbesc($ret["nick"]),
1228                 dbesc($ret["photo"]),
1229                 dbesc($ret["pubkey"]),
1230                 dbesc($ret["notify"]),
1231                 dbesc($ret["poll"]),
1232                 1,
1233                 2
1234         );
1235
1236         // find the contact record we just created
1237
1238         $contact_record = diaspora_get_contact_by_handle($importer["uid"],$author);
1239
1240         if(! $contact_record) {
1241                 logger('diaspora_request: unable to locate newly created contact record.');
1242                 return;
1243         }
1244
1245         $g = q("select def_gid from user where uid = %d limit 1",
1246                 intval($importer["uid"])
1247         );
1248         if($g && intval($g[0]["def_gid"])) {
1249                 group_add_member($importer["uid"],'',$contact_record["id"],$g[0]["def_gid"]);
1250         }
1251
1252         if($importer["page-flags"] == PAGE_NORMAL) {
1253
1254                 $hash = random_string() . (string) time();   // Generate a confirm_key
1255
1256                 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
1257                         VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
1258                         intval($importer["uid"]),
1259                         intval($contact_record["id"]),
1260                         0,
1261                         0,
1262                         dbesc( t('Sharing notification from Diaspora network')),
1263                         dbesc($hash),
1264                         dbesc(datetime_convert())
1265                 );
1266         }
1267         else {
1268
1269                 // automatic friend approval
1270
1271                 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1272
1273                 // technically they are sharing with us (CONTACT_IS_SHARING),
1274                 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1275                 // we are going to change the relationship and make them a follower.
1276
1277                 if($importer["page-flags"] == PAGE_FREELOVE)
1278                         $new_relation = CONTACT_IS_FRIEND;
1279                 else
1280                         $new_relation = CONTACT_IS_FOLLOWER;
1281
1282                 $r = q("UPDATE `contact` SET `rel` = %d,
1283                         `name-date` = '%s',
1284                         `uri-date` = '%s',
1285                         `blocked` = 0,
1286                         `pending` = 0,
1287                         `writable` = 1
1288                         WHERE `id` = %d
1289                         ",
1290                         intval($new_relation),
1291                         dbesc(datetime_convert()),
1292                         dbesc(datetime_convert()),
1293                         intval($contact_record["id"])
1294                 );
1295
1296                 $u = q("select * from user where uid = %d limit 1",intval($importer["uid"]));
1297                 if($u)
1298                         $ret = diaspora_share($u[0],$contact_record);
1299         }
1300 */
1301                 return true;
1302         }
1303
1304         private function get_original_item($guid, $orig_author, $author) {
1305
1306                 // Do we already have this item?
1307                 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1308                                 `author-name`, `author-link`, `author-avatar`
1309                                 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1310                         dbesc($guid));
1311
1312                 if(count($r)) {
1313                         logger("reshared message ".$guid." already exists on system.");
1314
1315                         // Maybe it is already a reshared item?
1316                         // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1317                         if (api_share_as_retweet($r[0]))
1318                                 $r = array();
1319                         else
1320                                 return $r[0];
1321                 }
1322
1323                 if (!count($r)) {
1324                         $server = 'https://'.substr($orig_author,strpos($orig_author,'@')+1);
1325                         logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1326                         $item_id = self::store_by_guid($guid, $server);
1327
1328                         if (!$item_id) {
1329                                 $server = 'https://'.substr($author,strpos($author,'@')+1);
1330                                 logger("2nd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1331                                 $item = self::store_by_guid($guid, $server);
1332                         }
1333                         if (!$item_id) {
1334                                 $server = 'http://'.substr($orig_author,strpos($orig_author,'@')+1);
1335                                 logger("3rd try: reshared message ".$guid." will be fetched from original server: ".$server);
1336                                 $item = self::store_by_guid($guid, $server);
1337                         }
1338                         if (!$item_id) {
1339                                 $server = 'http://'.substr($author,strpos($author,'@')+1);
1340                                 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1341                                 $item = self::store_by_guid($guid, $server);
1342                         }
1343
1344                         if ($item_id) {
1345                                 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1346                                                 `author-name`, `author-link`, `author-avatar`
1347                                         FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1348                                         intval($item_id));
1349
1350                                 if ($r)
1351                                         return $r[0];
1352
1353                         }
1354                 }
1355                 return false;
1356         }
1357
1358         private function import_reshare($importer, $data) {
1359                 $root_author = notags(unxmlify($data->root_author));
1360                 $root_guid = notags(unxmlify($data->root_guid));
1361                 $guid = notags(unxmlify($data->guid));
1362                 $author = notags(unxmlify($data->author));
1363                 $public = notags(unxmlify($data->public));
1364                 $created_at = notags(unxmlify($data->created_at));
1365
1366                 $contact = self::get_allowed_contact_by_handle($importer, $author, false);
1367                 if (!$contact)
1368                         return false;
1369
1370 //              if (self::message_exists($importer["uid"], $guid))
1371 //                      return false;
1372
1373                 $original_item = self::get_original_item($root_guid, $root_author, $author);
1374                 if (!$original_item)
1375                         return false;
1376
1377                 $datarray = array();
1378
1379                 $datarray["uid"] = $importer["uid"];
1380                 $datarray["contact-id"] = $contact["id"];
1381                 $datarray["network"]  = NETWORK_DIASPORA;
1382
1383                 $datarray["author-name"] = $contact["name"];
1384                 $datarray["author-link"] = $contact["url"];
1385                 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1386
1387                 $datarray["owner-name"] = $datarray["author-name"];
1388                 $datarray["owner-link"] = $datarray["author-link"];
1389                 $datarray["owner-avatar"] = $datarray["author-avatar"];
1390
1391                 $datarray["guid"] = $guid;
1392                 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1393
1394                 $datarray["verb"] = ACTIVITY_POST;
1395                 $datarray["gravity"] = GRAVITY_PARENT;
1396
1397                 $datarray["object"] = json_encode($data);
1398
1399                 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
1400                                         $original_item["guid"], $original_item["created"], $original_item["uri"]);
1401                 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
1402
1403                 $datarray["tag"] = $original_item["tag"];
1404                 $datarray["app"]  = $original_item["app"];
1405
1406                 $datarray["plink"] = self::plink($author, $guid);
1407                 $datarray["private"] = (($public == "false") ? 1 : 0);
1408                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1409
1410                 $datarray["object-type"] = $original_item["object-type"];
1411
1412                 self::fetch_guid($datarray);
1413                 //$message_id = item_store($datarray);
1414                 print_r($datarray);
1415
1416                 return $message_id;
1417         }
1418
1419         private function import_retraction($importer, $data) {
1420                 return true;
1421         }
1422
1423         private function import_status_message($importer, $data) {
1424
1425                 $raw_message = unxmlify($data->raw_message);
1426                 $guid = notags(unxmlify($data->guid));
1427                 $author = notags(unxmlify($data->author));
1428                 $public = notags(unxmlify($data->public));
1429                 $created_at = notags(unxmlify($data->created_at));
1430                 $provider_display_name = notags(unxmlify($data->provider_display_name));
1431
1432                 $contact = self::get_allowed_contact_by_handle($importer, $author, false);
1433                 if (!$contact)
1434                         return false;
1435
1436                 if (self::message_exists($importer["uid"], $guid))
1437                         return false;
1438
1439                 /// @todo enable support for polls
1440                 // if ($data->poll) {
1441                 //      print_r($data->poll);
1442                 //      die("poll!\n");
1443                 // }
1444
1445                 $address = array();
1446                 if ($data->location)
1447                         foreach ($data->location->children() AS $fieldname => $data)
1448                                 $address[$fieldname] = notags(unxmlify($data));
1449
1450                 $body = diaspora2bb($raw_message);
1451
1452                 if ($data->photo)
1453                         for ($i = 0; $i < count($data->photo); $i++)
1454                                 $body = "[img]".$data->photo[$i]->remote_photo_path.$data->photo[$i]->remote_photo_name."[/img]\n".$body;
1455
1456                 $datarray = array();
1457
1458                 if($data->photo->remote_photo_path AND $data->photo->remote_photo_name)
1459                         $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
1460                 else {
1461                         $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1462                         // Add OEmbed and other information to the body
1463                         if (!self::is_redmatrix($contact["url"]))
1464                                 $body = add_page_info_to_body($body, false, true);
1465                 }
1466
1467                 $str_tags = "";
1468
1469                 $cnt = preg_match_all("/@\[url=(.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER);
1470                 if($cnt) {
1471                         foreach($matches as $mtch) {
1472                                 if(strlen($str_tags))
1473                                         $str_tags .= ",";
1474                                 $str_tags .= "@[url=".$mtch[1]."[/url]";
1475                         }
1476                 }
1477
1478                 $datarray["uid"] = $importer["uid"];
1479                 $datarray["contact-id"] = $contact["id"];
1480                 $datarray["network"] = NETWORK_DIASPORA;
1481
1482                 $datarray["author-name"] = $contact["name"];
1483                 $datarray["author-link"] = $contact["url"];
1484                 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1485
1486                 $datarray["owner-name"] = $datarray["author-name"];
1487                 $datarray["owner-link"] = $datarray["author-link"];
1488                 $datarray["owner-avatar"] = $datarray["author-avatar"];
1489
1490                 $datarray["guid"] = $guid;
1491                 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1492
1493                 $datarray["verb"] = ACTIVITY_POST;
1494                 $datarray["gravity"] = GRAVITY_PARENT;
1495
1496                 $datarray["object"] = json_encode($data);
1497
1498                 $datarray["body"] = $body;
1499
1500                 $datarray["tag"] = $str_tags;
1501                 if ($provider_display_name != "")
1502                         $datarray["app"] = $provider_display_name;
1503
1504                 $datarray["plink"] = self::plink($author, $guid);
1505                 $datarray["private"] = (($public == "false") ? 1 : 0);
1506                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1507
1508                 if (isset($address["address"]))
1509                         $datarray["location"] = $address["address"];
1510
1511                 if (isset($address["lat"]) AND isset($address["lng"]))
1512                         $datarray["coord"] = $address["lat"]." ".$address["lng"];
1513
1514                 self::fetch_guid($datarray);
1515                 //$message_id = item_store($datarray);
1516                 print_r($datarray);
1517
1518                 logger("Stored item with message id ".$message_id, LOGGER_DEBUG);
1519
1520                 return $message_id;
1521         }
1522 }
1523 ?>