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