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