]> 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         $def_gid = get_default_group($importer['uid'], $ret["network"]);
741         if (intval($def_gid)) {
742                 require_once('include/group.php');
743                 group_add_member($importer['uid'], '', $contact_record['id'], $def_gid);
744         }
745
746         if($importer['page-flags'] == PAGE_NORMAL) {
747
748                 $hash = random_string() . (string) time();   // Generate a confirm_key
749
750                 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
751                         VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
752                         intval($importer['uid']),
753                         intval($contact_record['id']),
754                         0,
755                         0,
756                         dbesc( t('Sharing notification from Diaspora network')),
757                         dbesc($hash),
758                         dbesc(datetime_convert())
759                 );
760         }
761         else {
762
763                 // automatic friend approval
764
765                 require_once('include/Photo.php');
766
767                 update_contact_avatar($contact_record['photo'],$importer['uid'],$contact_record['id']);
768
769                 // technically they are sharing with us (CONTACT_IS_SHARING),
770                 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
771                 // we are going to change the relationship and make them a follower.
772
773                 if($importer['page-flags'] == PAGE_FREELOVE)
774                         $new_relation = CONTACT_IS_FRIEND;
775                 else
776                         $new_relation = CONTACT_IS_FOLLOWER;
777
778                 $r = q("UPDATE `contact` SET `rel` = %d,
779                         `name-date` = '%s',
780                         `uri-date` = '%s',
781                         `blocked` = 0,
782                         `pending` = 0,
783                         `writable` = 1
784                         WHERE `id` = %d
785                         ",
786                         intval($new_relation),
787                         dbesc(datetime_convert()),
788                         dbesc(datetime_convert()),
789                         intval($contact_record['id'])
790                 );
791
792                 $u = q("select * from user where uid = %d limit 1",intval($importer['uid']));
793                 if($u)
794                         $ret = diaspora_share($u[0],$contact_record);
795         }
796
797         return;
798 }
799
800 function diaspora_post_allow($importer,$contact, $is_comment = false) {
801
802         // perhaps we were already sharing with this person. Now they're sharing with us.
803         // That makes us friends.
804         // Normally this should have handled by getting a request - but this could get lost
805         if($contact['rel'] == CONTACT_IS_FOLLOWER && in_array($importer['page-flags'], array(PAGE_FREELOVE))) {
806                 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
807                         intval(CONTACT_IS_FRIEND),
808                         intval($contact['id']),
809                         intval($importer['uid'])
810                 );
811                 $contact['rel'] = CONTACT_IS_FRIEND;
812                 logger('diaspora_post_allow: defining user '.$contact["nick"].' as friend');
813         }
814
815         if(($contact['blocked']) || ($contact['readonly']) || ($contact['archive']))
816                 return false;
817         if($contact['rel'] == CONTACT_IS_SHARING || $contact['rel'] == CONTACT_IS_FRIEND)
818                 return true;
819         if($contact['rel'] == CONTACT_IS_FOLLOWER)
820                 if(($importer['page-flags'] == PAGE_COMMUNITY) OR $is_comment)
821                         return true;
822
823         // Messages for the global users are always accepted
824         if ($importer['uid'] == 0)
825                 return true;
826
827         return false;
828 }
829
830 function diaspora_is_redmatrix($url) {
831         return(strstr($url, "/channel/"));
832 }
833
834 function diaspora_plink($addr, $guid) {
835         $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
836
837         // Fallback
838         if (!$r)
839                 return 'https://'.substr($addr,strpos($addr,'@')+1).'/posts/'.$guid;
840
841         // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
842         // So we try another way as well.
843         $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
844         if ($s)
845                 $r[0]["network"] = $s[0]["network"];
846
847         if ($r[0]["network"] == NETWORK_DFRN)
848                 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
849
850         if (diaspora_is_redmatrix($r[0]["url"]))
851                 return $r[0]["url"]."/?f=&mid=".$guid;
852
853         return 'https://'.substr($addr,strpos($addr,'@')+1).'/posts/'.$guid;
854 }
855
856 function diaspora_repair_signature($signature, $handle = "", $level = 1) {
857
858         if ($signature == "")
859                 return($signature);
860
861         if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
862                 $signature = base64_decode($signature);
863                 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
864
865                 // Do a recursive call to be able to fix even multiple levels
866                 if ($level < 10)
867                         $signature = diaspora_repair_signature($signature, $handle, ++$level);
868         }
869
870         return($signature);
871 }
872
873 function diaspora_post($importer,$xml,$msg) {
874
875         $a = get_app();
876         $guid = notags(unxmlify($xml->guid));
877         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
878
879         if($diaspora_handle != $msg['author']) {
880                 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
881                 return 202;
882         }
883
884         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
885         if(! $contact) {
886                 logger('diaspora_post: A Contact for handle '.$diaspora_handle.' and user '.$importer['uid'].' was not found');
887                 return 203;
888         }
889
890         if(! diaspora_post_allow($importer,$contact, false)) {
891                 logger('diaspora_post: Ignoring this author.');
892                 return 202;
893         }
894
895         $message_id = $diaspora_handle . ':' . $guid;
896         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
897                 intval($importer['uid']),
898                 dbesc($guid)
899         );
900         if(count($r)) {
901                 logger('diaspora_post: message exists: ' . $guid);
902                 return 208;
903         }
904
905         $created = unxmlify($xml->created_at);
906         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
907
908         $body = diaspora2bb($xml->raw_message);
909
910         $datarray = array();
911
912         $datarray["object"] = json_encode($xml);
913
914         if($xml->photo->remote_photo_path AND $xml->photo->remote_photo_name)
915                 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
916         else {
917                 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
918                 // Add OEmbed and other information to the body
919                 if (!diaspora_is_redmatrix($contact['url']))
920                         $body = add_page_info_to_body($body, false, true);
921         }
922
923         $str_tags = '';
924
925         $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
926         if($cnt) {
927                 foreach($matches as $mtch) {
928                         if(strlen($str_tags))
929                                 $str_tags .= ',';
930                         $str_tags .= '@[url=' . $mtch[1] . '[/url]';
931                 }
932         }
933
934         $plink = diaspora_plink($diaspora_handle, $guid);
935
936         $datarray['uid'] = $importer['uid'];
937         $datarray['contact-id'] = $contact['id'];
938         $datarray['wall'] = 0;
939         $datarray['network'] = NETWORK_DIASPORA;
940         $datarray['verb'] = ACTIVITY_POST;
941         $datarray['guid'] = $guid;
942         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
943         $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
944         $datarray['private'] = $private;
945         $datarray['parent'] = 0;
946         $datarray['plink'] = $plink;
947         $datarray['owner-name'] = $contact['name'];
948         $datarray['owner-link'] = $contact['url'];
949         //$datarray['owner-avatar'] = $contact['thumb'];
950         $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
951         $datarray['author-name'] = $contact['name'];
952         $datarray['author-link'] = $contact['url'];
953         $datarray['author-avatar'] = $contact['thumb'];
954         $datarray['body'] = $body;
955         $datarray['tag'] = $str_tags;
956         if ($xml->provider_display_name)
957                 $datarray["app"] = unxmlify($xml->provider_display_name);
958         else
959                 $datarray['app']  = 'Diaspora';
960
961         // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
962
963         $datarray['visible'] = ((strlen($body)) ? 1 : 0);
964
965         DiasporaFetchGuid($datarray);
966         $message_id = item_store($datarray);
967
968         logger("Stored item with message id ".$message_id, LOGGER_DEBUG);
969
970         return 201;
971
972 }
973
974 function DiasporaFetchGuid($item) {
975         preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
976                 function ($match) use ($item){
977                         return(DiasporaFetchGuidSub($match, $item));
978                 },$item["body"]);
979 }
980
981 function DiasporaFetchGuidSub($match, $item) {
982         $a = get_app();
983
984         if (!diaspora_store_by_guid($match[1], $item["author-link"]))
985                 diaspora_store_by_guid($match[1], $item["owner-link"]);
986 }
987
988 function diaspora_store_by_guid($guid, $server, $uid = 0) {
989         require_once("include/Contact.php");
990
991         $serverparts = parse_url($server);
992         $server = $serverparts["scheme"]."://".$serverparts["host"];
993
994         logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
995
996         $item = diaspora_fetch_message($guid, $server);
997
998         if (!$item)
999                 return false;
1000
1001         logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1002
1003         $body = $item["body"];
1004         $str_tags = $item["tag"];
1005         $app = $item["app"];
1006         $created = $item["created"];
1007         $author = $item["author"];
1008         $guid = $item["guid"];
1009         $private = $item["private"];
1010         $object = $item["object"];
1011         $objecttype = $item["object-type"];
1012
1013         $message_id = $author.':'.$guid;
1014         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1015                 intval($uid),
1016                 dbesc($guid)
1017         );
1018         if(count($r))
1019                 return $r[0]["id"];
1020
1021         $person = find_diaspora_person_by_handle($author);
1022
1023         $contact_id = get_contact($person['url'], $uid);
1024
1025         $contacts = q("SELECT * FROM `contact` WHERE `id` = %d", intval($contact_id));
1026         $importers = q("SELECT * FROM `user` WHERE `uid` = %d", intval($uid));
1027
1028         if ($contacts AND $importers)
1029                 if(!diaspora_post_allow($importers[0],$contacts[0], false)) {
1030                         logger('Ignoring author '.$person['url'].' for uid '.$uid);
1031                         return false;
1032                 } else
1033                         logger('Author '.$person['url'].' is allowed for uid '.$uid);
1034
1035         $datarray = array();
1036         $datarray['uid'] = $uid;
1037         $datarray['contact-id'] = $contact_id;
1038         $datarray['wall'] = 0;
1039         $datarray['network']  = NETWORK_DIASPORA;
1040         $datarray['guid'] = $guid;
1041         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1042         $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1043         $datarray['private'] = $private;
1044         $datarray['parent'] = 0;
1045         $datarray['plink'] = diaspora_plink($author, $guid);
1046         $datarray['author-name'] = $person['name'];
1047         $datarray['author-link'] = $person['url'];
1048         $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1049         $datarray['owner-name'] = $datarray['author-name'];
1050         $datarray['owner-link'] = $datarray['author-link'];
1051         $datarray['owner-avatar'] = $datarray['author-avatar'];
1052         $datarray['body'] = $body;
1053         $datarray['tag'] = $str_tags;
1054         $datarray['app']  = $app;
1055         $datarray['visible'] = ((strlen($body)) ? 1 : 0);
1056         $datarray['object'] = $object;
1057         $datarray['object-type'] = $objecttype;
1058
1059         if ($datarray['contact-id'] == 0)
1060                 return false;
1061
1062         DiasporaFetchGuid($datarray);
1063         $message_id = item_store($datarray);
1064
1065         /// @TODO
1066         /// Looking if there is some subscribe mechanism in Diaspora to get all comments for this post
1067
1068         return $message_id;
1069 }
1070
1071 function diaspora_fetch_message($guid, $server, $level = 0) {
1072
1073         if ($level > 5)
1074                 return false;
1075
1076         $a = get_app();
1077
1078         // This will not work if the server is not a Diaspora server
1079         $source_url = $server.'/p/'.$guid.'.xml';
1080         $x = fetch_url($source_url);
1081         if(!$x)
1082                 return false;
1083
1084         $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
1085         $source_xml = parse_xml_string($x,false);
1086
1087         $item = array();
1088         $item["app"] = 'Diaspora';
1089         $item["guid"] = $guid;
1090         $body = "";
1091
1092         if ($source_xml->post->status_message->created_at)
1093                 $item["created"] = unxmlify($source_xml->post->status_message->created_at);
1094
1095         if ($source_xml->post->status_message->provider_display_name)
1096                 $item["app"] = unxmlify($source_xml->post->status_message->provider_display_name);
1097
1098         if ($source_xml->post->status_message->diaspora_handle)
1099                 $item["author"] = unxmlify($source_xml->post->status_message->diaspora_handle);
1100
1101         if ($source_xml->post->status_message->guid)
1102                 $item["guid"] = unxmlify($source_xml->post->status_message->guid);
1103
1104         $item["private"] = (unxmlify($source_xml->post->status_message->public) == 'false');
1105         $item["object"] = json_encode($source_xml->post);
1106
1107         if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
1108                 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1109                 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
1110                 $body = scale_external_images($body,false);
1111         } elseif($source_xml->post->asphoto->image_url) {
1112                 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1113                 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
1114                 $body = scale_external_images($body);
1115         } elseif($source_xml->post->status_message) {
1116                 $body = diaspora2bb($source_xml->post->status_message->raw_message);
1117
1118                 // Checking for embedded pictures
1119                 if($source_xml->post->status_message->photo->remote_photo_path AND
1120                         $source_xml->post->status_message->photo->remote_photo_name) {
1121
1122                         $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1123
1124                         $remote_photo_path = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_path));
1125                         $remote_photo_name = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_name));
1126
1127                         $body = '[img]'.$remote_photo_path.$remote_photo_name.'[/img]'."\n".$body;
1128
1129                         logger('embedded picture link found: '.$body, LOGGER_DEBUG);
1130                 } else
1131                         $item["object-type"] = ACTIVITY_OBJ_NOTE;
1132
1133                 $body = scale_external_images($body);
1134
1135                 // Add OEmbed and other information to the body
1136                 /// @TODO It could be a repeated redmatrix item
1137                 /// Then we shouldn't add further data to it
1138                 if ($item["object-type"] == ACTIVITY_OBJ_NOTE)
1139                         $body = add_page_info_to_body($body, false, true);
1140
1141         } elseif($source_xml->post->reshare) {
1142                 // Reshare of a reshare
1143                 return diaspora_fetch_message($source_xml->post->reshare->root_guid, $server, ++$level);
1144         } else {
1145                 // Maybe it is a reshare of a photo that will be delivered at a later time (testing)
1146                 logger('no content found: '.print_r($source_xml,true));
1147                 return false;
1148         }
1149
1150         if (trim($body) == "")
1151                 return false;
1152
1153         $item["tag"] = '';
1154         $item["body"] = $body;
1155
1156         return $item;
1157 }
1158
1159 function diaspora_reshare($importer,$xml,$msg) {
1160
1161         logger('diaspora_reshare: init: ' . print_r($xml,true));
1162
1163         $a = get_app();
1164         $guid = notags(unxmlify($xml->guid));
1165         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1166
1167
1168         if($diaspora_handle != $msg['author']) {
1169                 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1170                 return 202;
1171         }
1172
1173         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1174         if(! $contact)
1175                 return;
1176
1177         if(! diaspora_post_allow($importer,$contact, false)) {
1178                 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
1179                 return 202;
1180         }
1181
1182         $message_id = $diaspora_handle . ':' . $guid;
1183         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1184                 intval($importer['uid']),
1185                 dbesc($guid)
1186         );
1187         if(count($r)) {
1188                 logger('diaspora_reshare: message exists: ' . $guid);
1189                 return;
1190         }
1191
1192         $orig_author = notags(unxmlify($xml->root_diaspora_id));
1193         $orig_guid = notags(unxmlify($xml->root_guid));
1194         $orig_url = $a->get_baseurl()."/display/".$orig_guid;
1195
1196         $create_original_post = false;
1197
1198         // Do we already have this item?
1199         $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",
1200                 dbesc($orig_guid),
1201                 dbesc(NETWORK_DIASPORA)
1202         );
1203         if(count($r)) {
1204                 logger('reshared message '.$orig_guid." reshared by ".$guid.' already exists on system.');
1205
1206                 // Maybe it is already a reshared item?
1207                 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1208                 require_once('include/api.php');
1209                 if (api_share_as_retweet($r[0]))
1210                         $r = array();
1211                 else {
1212                         $body = $r[0]["body"];
1213                         $str_tags = $r[0]["tag"];
1214                         $app = $r[0]["app"];
1215                         $orig_created = $r[0]["created"];
1216                         $orig_plink = $r[0]["plink"];
1217                         $orig_uri = $r[0]["uri"];
1218                         $object = $r[0]["object"];
1219                         $objecttype = $r[0]["object-type"];
1220                 }
1221         }
1222
1223         if (!count($r)) {
1224                 $body = "";
1225                 $str_tags = "";
1226                 $app = "";
1227
1228                 $server = 'https://'.substr($orig_author,strpos($orig_author,'@')+1);
1229                 logger('1st try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1230                 $item = diaspora_fetch_message($orig_guid, $server);
1231
1232                 if (!$item) {
1233                         $server = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1234                         logger('2nd try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1235                         $item = diaspora_fetch_message($orig_guid, $server);
1236                 }
1237                 if (!$item) {
1238                         $server = 'http://'.substr($orig_author,strpos($orig_author,'@')+1);
1239                         logger('3rd try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1240                         $item = diaspora_fetch_message($orig_guid, $server);
1241                 }
1242                 if (!$item) {
1243                         $server = 'http://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1244                         logger('4th try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1245                         $item = diaspora_fetch_message($orig_guid, $server);
1246                 }
1247
1248                 if ($item) {
1249                         $body = $item["body"];
1250                         $str_tags = $item["tag"];
1251                         $app = $item["app"];
1252                         $orig_created = $item["created"];
1253                         $orig_author = $item["author"];
1254                         $orig_guid = $item["guid"];
1255                         $orig_plink = diaspora_plink($orig_author, $orig_guid);
1256                         $orig_uri = $orig_author.':'.$orig_guid;
1257                         $create_original_post = ($body != "");
1258                         $object = $item["object"];
1259                         $objecttype = $item["object-type"];
1260                 }
1261         }
1262
1263         $plink = diaspora_plink($diaspora_handle, $guid);
1264
1265         $person = find_diaspora_person_by_handle($orig_author);
1266
1267         $created = unxmlify($xml->created_at);
1268         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1269
1270         $datarray = array();
1271
1272         $datarray['uid'] = $importer['uid'];
1273         $datarray['contact-id'] = $contact['id'];
1274         $datarray['wall'] = 0;
1275         $datarray['network']  = NETWORK_DIASPORA;
1276         $datarray['guid'] = $guid;
1277         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1278         $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1279         $datarray['private'] = $private;
1280         $datarray['parent'] = 0;
1281         $datarray['plink'] = $plink;
1282         $datarray['owner-name'] = $contact['name'];
1283         $datarray['owner-link'] = $contact['url'];
1284         $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1285         if (!intval(get_config('system','wall-to-wall_share'))) {
1286                 $prefix = share_header($person['name'], $person['url'], ((x($person,'thumb')) ? $person['thumb'] : $person['photo']), $orig_guid, $orig_created, $orig_url);
1287
1288                 $datarray['author-name'] = $contact['name'];
1289                 $datarray['author-link'] = $contact['url'];
1290                 $datarray['author-avatar'] = $contact['thumb'];
1291                 $datarray['body'] = $prefix.$body."[/share]";
1292         } else {
1293                 // Let reshared messages look like wall-to-wall posts
1294                 $datarray['author-name'] = $person['name'];
1295                 $datarray['author-link'] = $person['url'];
1296                 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1297                 $datarray['body'] = $body;
1298         }
1299
1300         $datarray["object"] = json_encode($xml);
1301         $datarray['object-type'] = $objecttype;
1302
1303         $datarray['tag'] = $str_tags;
1304         $datarray['app']  = $app;
1305
1306         // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible. (testing)
1307         $datarray['visible'] = ((strlen($body)) ? 1 : 0);
1308
1309         // Store the original item of a reshare
1310         if ($create_original_post) {
1311                 require_once("include/Contact.php");
1312
1313                 $datarray2 = $datarray;
1314
1315                 $datarray2['uid'] = 0;
1316                 $datarray2['contact-id'] = get_contact($person['url'], 0);
1317                 $datarray2['guid'] = $orig_guid;
1318                 $datarray2['uri'] = $datarray2['parent-uri'] = $orig_uri;
1319                 $datarray2['changed'] = $datarray2['created'] = $datarray2['edited'] = $datarray2['commented'] = $datarray2['received'] = datetime_convert('UTC','UTC',$orig_created);
1320                 $datarray2['parent'] = 0;
1321                 $datarray2['plink'] = $orig_plink;
1322
1323                 $datarray2['author-name'] = $person['name'];
1324                 $datarray2['author-link'] = $person['url'];
1325                 $datarray2['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1326                 $datarray2['owner-name'] = $datarray2['author-name'];
1327                 $datarray2['owner-link'] = $datarray2['author-link'];
1328                 $datarray2['owner-avatar'] = $datarray2['author-avatar'];
1329                 $datarray2['body'] = $body;
1330                 $datarray2["object"] = $object;
1331
1332                 DiasporaFetchGuid($datarray2);
1333                 $message_id = item_store($datarray2);
1334
1335                 logger("Store original item ".$orig_guid." under message id ".$message_id);
1336         }
1337
1338         DiasporaFetchGuid($datarray);
1339         $message_id = item_store($datarray);
1340
1341         return;
1342
1343 }
1344
1345
1346 function diaspora_asphoto($importer,$xml,$msg) {
1347         logger('diaspora_asphoto called');
1348
1349         $a = get_app();
1350         $guid = notags(unxmlify($xml->guid));
1351         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1352
1353         if($diaspora_handle != $msg['author']) {
1354                 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1355                 return 202;
1356         }
1357
1358         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1359         if(! $contact)
1360                 return;
1361
1362         if(! diaspora_post_allow($importer,$contact, false)) {
1363                 logger('diaspora_asphoto: Ignoring this author.');
1364                 return 202;
1365         }
1366
1367         $message_id = $diaspora_handle . ':' . $guid;
1368         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1369                 intval($importer['uid']),
1370                 dbesc($guid)
1371         );
1372         if(count($r)) {
1373                 logger('diaspora_asphoto: message exists: ' . $guid);
1374                 return;
1375         }
1376
1377         $created = unxmlify($xml->created_at);
1378         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1379
1380         if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
1381                 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
1382                 $body = scale_external_images($body,false);
1383         }
1384         elseif($xml->image_url) {
1385                 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
1386                 $body = scale_external_images($body);
1387         }
1388         else {
1389                 logger('diaspora_asphoto: no photo url found.');
1390                 return;
1391         }
1392
1393         $plink = diaspora_plink($diaspora_handle, $guid);
1394
1395         $datarray = array();
1396
1397         $datarray['uid'] = $importer['uid'];
1398         $datarray['contact-id'] = $contact['id'];
1399         $datarray['wall'] = 0;
1400         $datarray['network']  = NETWORK_DIASPORA;
1401         $datarray['guid'] = $guid;
1402         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1403         $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1404         $datarray['private'] = $private;
1405         $datarray['parent'] = 0;
1406         $datarray['plink'] = $plink;
1407         $datarray['owner-name'] = $contact['name'];
1408         $datarray['owner-link'] = $contact['url'];
1409         //$datarray['owner-avatar'] = $contact['thumb'];
1410         $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1411         $datarray['author-name'] = $contact['name'];
1412         $datarray['author-link'] = $contact['url'];
1413         $datarray['author-avatar'] = $contact['thumb'];
1414         $datarray['body'] = $body;
1415         $datarray["object"] = json_encode($xml);
1416         $datarray['object-type'] = ACTIVITY_OBJ_PHOTO;
1417
1418         $datarray['app']  = 'Diaspora/Cubbi.es';
1419
1420         DiasporaFetchGuid($datarray);
1421         $message_id = item_store($datarray);
1422
1423         //if($message_id) {
1424         //      q("update item set plink = '%s' where id = %d",
1425         //              dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1426         //              intval($message_id)
1427         //      );
1428         //}
1429
1430         return;
1431
1432 }
1433
1434 function diaspora_comment($importer,$xml,$msg) {
1435
1436         $a = get_app();
1437         $guid = notags(unxmlify($xml->guid));
1438         $parent_guid = notags(unxmlify($xml->parent_guid));
1439         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1440         $target_type = notags(unxmlify($xml->target_type));
1441         $text = unxmlify($xml->text);
1442         $author_signature = notags(unxmlify($xml->author_signature));
1443
1444         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1445
1446         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1447         if(! $contact) {
1448                 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
1449                 return;
1450         }
1451
1452         if(! diaspora_post_allow($importer,$contact, true)) {
1453                 logger('diaspora_comment: Ignoring this author.');
1454                 return 202;
1455         }
1456
1457         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1458                 intval($importer['uid']),
1459                 dbesc($guid)
1460         );
1461         if(count($r)) {
1462                 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
1463                 return;
1464         }
1465
1466         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1467                 intval($importer['uid']),
1468                 dbesc($parent_guid)
1469         );
1470
1471         if(!count($r)) {
1472                 $result = diaspora_store_by_guid($parent_guid, $contact['url'], $importer['uid']);
1473
1474                 if (!$result) {
1475                         $person = find_diaspora_person_by_handle($diaspora_handle);
1476                         $result = diaspora_store_by_guid($parent_guid, $person['url'], $importer['uid']);
1477                 }
1478
1479                 if ($result) {
1480                         logger("Fetched missing item ".$parent_guid." - result: ".$result, LOGGER_DEBUG);
1481
1482                         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1483                                 intval($importer['uid']),
1484                                 dbesc($parent_guid)
1485                         );
1486                 }
1487         }
1488
1489         if(! count($r)) {
1490                 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1491                 return;
1492         }
1493         $parent_item = $r[0];
1494
1495
1496         /* How Diaspora performs comment signature checking:
1497
1498            - If an item has been sent by the comment author to the top-level post owner to relay on
1499              to the rest of the contacts on the top-level post, the top-level post owner should check
1500              the author_signature, then create a parent_author_signature before relaying the comment on
1501            - If an item has been relayed on by the top-level post owner, the contacts who receive it
1502              check only the parent_author_signature. Basically, they trust that the top-level post
1503              owner has already verified the authenticity of anything he/she sends out
1504            - In either case, the signature that get checked is the signature created by the person
1505              who sent the salmon
1506         */
1507
1508         $signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1509         $key = $msg['key'];
1510
1511         if($parent_author_signature) {
1512                 // If a parent_author_signature exists, then we've received the comment
1513                 // relayed from the top-level post owner. There's no need to check the
1514                 // author_signature if the parent_author_signature is valid
1515
1516                 $parent_author_signature = base64_decode($parent_author_signature);
1517
1518                 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1519                         logger('diaspora_comment: top-level owner verification failed.');
1520                         return;
1521                 }
1522         }
1523         else {
1524                 // If there's no parent_author_signature, then we've received the comment
1525                 // from the comment creator. In that case, the person is commenting on
1526                 // our post, so he/she must be a contact of ours and his/her public key
1527                 // should be in $msg['key']
1528
1529                 $author_signature = base64_decode($author_signature);
1530
1531                 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1532                         logger('diaspora_comment: comment author verification failed.');
1533                         return;
1534                 }
1535         }
1536
1537         // Phew! Everything checks out. Now create an item.
1538
1539         // Find the original comment author information.
1540         // We need this to make sure we display the comment author
1541         // information (name and avatar) correctly.
1542         if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1543                 $person = $contact;
1544         else {
1545                 $person = find_diaspora_person_by_handle($diaspora_handle);
1546
1547                 if(! is_array($person)) {
1548                         logger('diaspora_comment: unable to find author details');
1549                         return;
1550                 }
1551         }
1552
1553         // Fetch the contact id - if we know this contact
1554         $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1555                 dbesc(normalise_link($person['url'])), intval($importer['uid']));
1556         if ($r) {
1557                 $cid = $r[0]['id'];
1558                 $network = $r[0]['network'];
1559         } else {
1560                 $cid = $contact['id'];
1561                 $network = NETWORK_DIASPORA;
1562         }
1563
1564         $body = diaspora2bb($text);
1565         $message_id = $diaspora_handle . ':' . $guid;
1566
1567         $datarray = array();
1568
1569         $datarray['uid'] = $importer['uid'];
1570         $datarray['contact-id'] = $cid;
1571         $datarray['type'] = 'remote-comment';
1572         $datarray['wall'] = $parent_item['wall'];
1573         $datarray['network']  = $network;
1574         $datarray['verb'] = ACTIVITY_POST;
1575         $datarray['gravity'] = GRAVITY_COMMENT;
1576         $datarray['guid'] = $guid;
1577         $datarray['uri'] = $message_id;
1578         $datarray['parent-uri'] = $parent_item['uri'];
1579
1580         // No timestamps for comments? OK, we'll the use current time.
1581         $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert();
1582         $datarray['private'] = $parent_item['private'];
1583
1584         $datarray['owner-name'] = $parent_item['owner-name'];
1585         $datarray['owner-link'] = $parent_item['owner-link'];
1586         $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1587
1588         $datarray['author-name'] = $person['name'];
1589         $datarray['author-link'] = $person['url'];
1590         $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1591         $datarray['body'] = $body;
1592         $datarray["object"] = json_encode($xml);
1593         $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1594
1595         // We can't be certain what the original app is if the message is relayed.
1596         if(($parent_item['origin']) && (! $parent_author_signature))
1597                 $datarray['app']  = 'Diaspora';
1598
1599         DiasporaFetchGuid($datarray);
1600         $message_id = item_store($datarray);
1601
1602         $datarray['id'] = $message_id;
1603
1604         //if($message_id) {
1605                 //q("update item set plink = '%s' where id = %d",
1606                 //      //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1607                 //      dbesc($a->get_baseurl().'/display/'.$datarray['guid']),
1608                 //      intval($message_id)
1609                 //);
1610         //}
1611
1612         // If we are the origin of the parent we store the original signature and notify our followers
1613         if($parent_item['origin']) {
1614                 $author_signature_base64 = base64_encode($author_signature);
1615                 $author_signature_base64 = diaspora_repair_signature($author_signature_base64, $diaspora_handle);
1616
1617                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1618                         intval($message_id),
1619                         dbesc($signed_data),
1620                         dbesc($author_signature_base64),
1621                         dbesc($diaspora_handle)
1622                 );
1623
1624                 // notify others
1625                 proc_run('php','include/notifier.php','comment-import',$message_id);
1626         }
1627
1628         return;
1629 }
1630
1631
1632
1633
1634 function diaspora_conversation($importer,$xml,$msg) {
1635
1636         $a = get_app();
1637
1638         $guid = notags(unxmlify($xml->guid));
1639         $subject = notags(unxmlify($xml->subject));
1640         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1641         $participant_handles = notags(unxmlify($xml->participant_handles));
1642         $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1643
1644         $parent_uri = $diaspora_handle . ':' . $guid;
1645
1646         $messages = $xml->message;
1647
1648         if(! count($messages)) {
1649                 logger('diaspora_conversation: empty conversation');
1650                 return;
1651         }
1652
1653         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1654         if(! $contact) {
1655                 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1656                 return;
1657         }
1658
1659         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1660                 logger('diaspora_conversation: Ignoring this author.');
1661                 return 202;
1662         }
1663
1664         $conversation = null;
1665
1666         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1667                 intval($importer['uid']),
1668                 dbesc($guid)
1669         );
1670         if(count($c))
1671                 $conversation = $c[0];
1672         else {
1673                 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1674                         intval($importer['uid']),
1675                         dbesc($guid),
1676                         dbesc($diaspora_handle),
1677                         dbesc(datetime_convert('UTC','UTC',$created_at)),
1678                         dbesc(datetime_convert()),
1679                         dbesc($subject),
1680                         dbesc($participant_handles)
1681                 );
1682                 if($r)
1683                         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1684                 intval($importer['uid']),
1685             dbesc($guid)
1686         );
1687             if(count($c))
1688             $conversation = $c[0];
1689         }
1690         if(! $conversation) {
1691                 logger('diaspora_conversation: unable to create conversation.');
1692                 return;
1693         }
1694
1695         foreach($messages as $mesg) {
1696
1697                 $reply = 0;
1698
1699                 $msg_guid = notags(unxmlify($mesg->guid));
1700                 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1701                 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1702                 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1703                 $msg_text = unxmlify($mesg->text);
1704                 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1705                 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1706                 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1707                 if($msg_conversation_guid != $guid) {
1708                         logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1709                         continue;
1710                 }
1711
1712                 $body = diaspora2bb($msg_text);
1713                 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1714
1715                 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1716
1717                 $author_signature = base64_decode($msg_author_signature);
1718
1719                 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1720                         $person = $contact;
1721                         $key = $msg['key'];
1722                 }
1723                 else {
1724                         $person = find_diaspora_person_by_handle($msg_diaspora_handle); 
1725
1726                         if(is_array($person) && x($person,'pubkey'))
1727                                 $key = $person['pubkey'];
1728                         else {
1729                                 logger('diaspora_conversation: unable to find author details');
1730                                 continue;
1731                         }
1732                 }
1733
1734                 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1735                         logger('diaspora_conversation: verification failed.');
1736                         continue;
1737                 }
1738
1739                 if($msg_parent_author_signature) {
1740                         $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1741
1742                         $parent_author_signature = base64_decode($msg_parent_author_signature);
1743
1744                         $key = $msg['key'];
1745
1746                         if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1747                                 logger('diaspora_conversation: owner verification failed.');
1748                                 continue;
1749                         }
1750                 }
1751
1752                 $r = q("select id from mail where `uri` = '%s' limit 1",
1753                         dbesc($message_id)
1754                 );
1755                 if(count($r)) {
1756                         logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1757                         continue;
1758                 }
1759
1760                 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')",
1761                         intval($importer['uid']),
1762                         dbesc($msg_guid),
1763                         intval($conversation['id']),
1764                         dbesc($person['name']),
1765                         dbesc($person['photo']),
1766                         dbesc($person['url']),
1767                         intval($contact['id']),
1768                         dbesc($subject),
1769                         dbesc($body),
1770                         0,
1771                         0,
1772                         dbesc($message_id),
1773                         dbesc($parent_uri),
1774                         dbesc($msg_created_at)
1775                 );
1776
1777                 q("update conv set updated = '%s' where id = %d",
1778                         dbesc(datetime_convert()),
1779                         intval($conversation['id'])
1780                 );
1781
1782                 notification(array(
1783                         'type' => NOTIFY_MAIL,
1784                         'notify_flags' => $importer['notify-flags'],
1785                         'language' => $importer['language'],
1786                         'to_name' => $importer['username'],
1787                         'to_email' => $importer['email'],
1788                         'uid' =>$importer['uid'],
1789                         'item' => array('subject' => $subject, 'body' => $body),
1790                         'source_name' => $person['name'],
1791                         'source_link' => $person['url'],
1792                         'source_photo' => $person['thumb'],
1793                         'verb' => ACTIVITY_POST,
1794                         'otype' => 'mail'
1795                 ));
1796         }
1797
1798         return;
1799 }
1800
1801 function diaspora_message($importer,$xml,$msg) {
1802
1803         $a = get_app();
1804
1805         $msg_guid = notags(unxmlify($xml->guid));
1806         $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1807         $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1808         $msg_author_signature = notags(unxmlify($xml->author_signature));
1809         $msg_text = unxmlify($xml->text);
1810         $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1811         $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1812         $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1813
1814         $parent_uri = $msg_diaspora_handle . ':' . $msg_parent_guid;
1815
1816         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1817         if(! $contact) {
1818                 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1819                 return;
1820         }
1821
1822         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1823                 logger('diaspora_message: Ignoring this author.');
1824                 return 202;
1825         }
1826
1827         $conversation = null;
1828
1829         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1830                 intval($importer['uid']),
1831                 dbesc($msg_conversation_guid)
1832         );
1833         if(count($c))
1834                 $conversation = $c[0];
1835         else {
1836                 logger('diaspora_message: conversation not available.');
1837                 return;
1838         }
1839
1840         $reply = 0;
1841
1842         $body = diaspora2bb($msg_text);
1843         $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1844
1845         $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1846
1847
1848         $author_signature = base64_decode($msg_author_signature);
1849
1850         $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1851         if(is_array($person) && x($person,'pubkey'))
1852                 $key = $person['pubkey'];
1853         else {
1854                 logger('diaspora_message: unable to find author details');
1855                 return;
1856         }
1857
1858         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1859                 logger('diaspora_message: verification failed.');
1860                 return;
1861         }
1862
1863         $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1864                 dbesc($message_id),
1865                 intval($importer['uid'])
1866         );
1867         if(count($r)) {
1868                 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1869                 return;
1870         }
1871
1872         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')",
1873                 intval($importer['uid']),
1874                 dbesc($msg_guid),
1875                 intval($conversation['id']),
1876                 dbesc($person['name']),
1877                 dbesc($person['photo']),
1878                 dbesc($person['url']),
1879                 intval($contact['id']),
1880                 dbesc($conversation['subject']),
1881                 dbesc($body),
1882                 0,
1883                 1,
1884                 dbesc($message_id),
1885                 dbesc($parent_uri),
1886                 dbesc($msg_created_at)
1887         );
1888
1889         q("update conv set updated = '%s' where id = %d",
1890                 dbesc(datetime_convert()),
1891                 intval($conversation['id'])
1892         );
1893
1894         return;
1895 }
1896
1897 function diaspora_participation($importer,$xml) {
1898         logger("Unsupported message type 'participation' ".print_r($xml, true));
1899 }
1900
1901 function diaspora_photo($importer,$xml,$msg,$attempt=1) {
1902
1903         $a = get_app();
1904
1905         logger('diaspora_photo: init',LOGGER_DEBUG);
1906
1907         $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1908
1909         $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1910
1911         $status_message_guid = notags(unxmlify($xml->status_message_guid));
1912
1913         $guid = notags(unxmlify($xml->guid));
1914
1915         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1916
1917         $public = notags(unxmlify($xml->public));
1918
1919         $created_at = notags(unxmlify($xml_created_at));
1920
1921         logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1922
1923         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1924         if(! $contact) {
1925                 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1926                 return;
1927         }
1928
1929         if(! diaspora_post_allow($importer,$contact, false)) {
1930                 logger('diaspora_photo: Ignoring this author.');
1931                 return 202;
1932         }
1933
1934         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1935                 intval($importer['uid']),
1936                 dbesc($status_message_guid)
1937         );
1938
1939 /*      deactivated by now since it can lead to multiplicated pictures in posts.
1940         if(!count($r)) {
1941                 $result = diaspora_store_by_guid($status_message_guid, $contact['url'], $importer['uid']);
1942
1943                 if (!$result) {
1944                         $person = find_diaspora_person_by_handle($diaspora_handle);
1945                         $result = diaspora_store_by_guid($status_message_guid, $person['url'], $importer['uid']);
1946                 }
1947
1948                 if ($result) {
1949                         logger("Fetched missing item ".$status_message_guid." - result: ".$result, LOGGER_DEBUG);
1950
1951                         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1952                                 intval($importer['uid']),
1953                                 dbesc($status_message_guid)
1954                         );
1955                 }
1956         }
1957 */
1958         if(!count($r)) {
1959                 if($attempt <= 3) {
1960                         q("INSERT INTO dsprphotoq (uid, msg, attempt) VALUES (%d, '%s', %d)",
1961                            intval($importer['uid']),
1962                            dbesc(serialize($msg)),
1963                            intval($attempt + 1)
1964                         );
1965                 }
1966
1967                 logger('diaspora_photo: attempt = ' . $attempt . '; status message not found: ' . $status_message_guid . ' for photo: ' . $guid);
1968                 return;
1969         }
1970
1971         $parent_item = $r[0];
1972
1973         $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1974
1975         $link_text = scale_external_images($link_text, true,
1976                                            array($remote_photo_name, 'scaled_full_' . $remote_photo_name));
1977
1978         if(strpos($parent_item['body'],$link_text) === false) {
1979
1980                 $parent_item['body'] = $link_text . $parent_item['body'];
1981
1982                 $r = q("UPDATE `item` SET `body` = '%s', `visible` = 1 WHERE `id` = %d AND `uid` = %d",
1983                         dbesc($parent_item['body']),
1984                         intval($parent_item['id']),
1985                         intval($parent_item['uid'])
1986                 );
1987                 put_item_in_cache($parent_item, true);
1988                 update_thread($parent_item['id']);
1989         }
1990
1991         return;
1992 }
1993
1994
1995
1996
1997 function diaspora_like($importer,$xml,$msg) {
1998
1999         $a = get_app();
2000         $guid = notags(unxmlify($xml->guid));
2001         $parent_guid = notags(unxmlify($xml->parent_guid));
2002         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2003         $target_type = notags(unxmlify($xml->target_type));
2004         $positive = notags(unxmlify($xml->positive));
2005         $author_signature = notags(unxmlify($xml->author_signature));
2006
2007         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
2008
2009         // likes on comments not supported here and likes on photos not supported by Diaspora
2010
2011 //      if($target_type !== 'Post')
2012 //              return;
2013
2014         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
2015         if(! $contact) {
2016                 logger('diaspora_like: cannot find contact: ' . $msg['author']);
2017                 return;
2018         }
2019
2020         if(! diaspora_post_allow($importer,$contact, false)) {
2021                 logger('diaspora_like: Ignoring this author.');
2022                 return 202;
2023         }
2024
2025         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2026                 intval($importer['uid']),
2027                 dbesc($parent_guid)
2028         );
2029
2030         if(!count($r)) {
2031                 $result = diaspora_store_by_guid($parent_guid, $contact['url'], $importer['uid']);
2032
2033                 if (!$result) {
2034                         $person = find_diaspora_person_by_handle($diaspora_handle);
2035                         $result = diaspora_store_by_guid($parent_guid, $person['url'], $importer['uid']);
2036                 }
2037
2038                 if ($result) {
2039                         logger("Fetched missing item ".$parent_guid." - result: ".$result, LOGGER_DEBUG);
2040
2041                         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2042                                 intval($importer['uid']),
2043                                 dbesc($parent_guid)
2044                         );
2045                 }
2046         }
2047
2048         if(! count($r)) {
2049                 logger('diaspora_like: parent item not found: ' . $guid);
2050                 return;
2051         }
2052
2053         $parent_item = $r[0];
2054
2055         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2056                 intval($importer['uid']),
2057                 dbesc($guid)
2058         );
2059         if(count($r)) {
2060                 if($positive === 'true') {
2061                         logger('diaspora_like: duplicate like: ' . $guid);
2062                         return;
2063                 }
2064                 // Note: I don't think "Like" objects with positive = "false" are ever actually used
2065                 // It looks like "RelayableRetractions" are used for "unlike" instead
2066                 if($positive === 'false') {
2067                         logger('diaspora_like: received a like with positive set to "false"...ignoring');
2068 /*                      q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d",
2069                                 intval($r[0]['id']),
2070                                 intval($importer['uid'])
2071                         );*/
2072                         // FIXME--actually don't unless it turns out that Diaspora does indeed send out "false" likes
2073                         //  send notification via proc_run()
2074                         return;
2075                 }
2076         }
2077         // Note: I don't think "Like" objects with positive = "false" are ever actually used
2078         // It looks like "RelayableRetractions" are used for "unlike" instead
2079         if($positive === 'false') {
2080                 logger('diaspora_like: received a like with positive set to "false"');
2081                 logger('diaspora_like: unlike received with no corresponding like...ignoring');
2082                 return;
2083         }
2084
2085
2086         /* How Diaspora performs "like" signature checking:
2087
2088            - If an item has been sent by the like author to the top-level post owner to relay on
2089              to the rest of the contacts on the top-level post, the top-level post owner should check
2090              the author_signature, then create a parent_author_signature before relaying the like on
2091            - If an item has been relayed on by the top-level post owner, the contacts who receive it
2092              check only the parent_author_signature. Basically, they trust that the top-level post
2093              owner has already verified the authenticity of anything he/she sends out
2094            - In either case, the signature that get checked is the signature created by the person
2095              who sent the salmon
2096         */
2097
2098         // Diaspora has changed the way they are signing the likes.
2099         // Just to make sure that we don't miss any likes we will check the old and the current way.
2100         $old_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
2101
2102         $signed_data = $positive . ';' . $guid . ';' . $target_type . ';' . $parent_guid . ';' . $diaspora_handle;
2103
2104         $key = $msg['key'];
2105
2106         if ($parent_author_signature) {
2107                 // If a parent_author_signature exists, then we've received the like
2108                 // relayed from the top-level post owner. There's no need to check the
2109                 // author_signature if the parent_author_signature is valid
2110
2111                 $parent_author_signature = base64_decode($parent_author_signature);
2112
2113                 if (!rsa_verify($signed_data,$parent_author_signature,$key,'sha256') AND
2114                         !rsa_verify($old_signed_data,$parent_author_signature,$key,'sha256')) {
2115
2116                         logger('diaspora_like: top-level owner verification failed.');
2117                         return;
2118                 }
2119         } else {
2120                 // If there's no parent_author_signature, then we've received the like
2121                 // from the like creator. In that case, the person is "like"ing
2122                 // our post, so he/she must be a contact of ours and his/her public key
2123                 // should be in $msg['key']
2124
2125                 $author_signature = base64_decode($author_signature);
2126
2127                 if (!rsa_verify($signed_data,$author_signature,$key,'sha256') AND
2128                         !rsa_verify($old_signed_data,$author_signature,$key,'sha256')) {
2129
2130                         logger('diaspora_like: like creator verification failed.');
2131                         return;
2132                 }
2133         }
2134
2135         // Phew! Everything checks out. Now create an item.
2136
2137         // Find the original comment author information.
2138         // We need this to make sure we display the comment author
2139         // information (name and avatar) correctly.
2140         if(strcasecmp($diaspora_handle,$msg['author']) == 0)
2141                 $person = $contact;
2142         else {
2143                 $person = find_diaspora_person_by_handle($diaspora_handle);
2144
2145                 if(! is_array($person)) {
2146                         logger('diaspora_like: unable to find author details');
2147                         return;
2148                 }
2149         }
2150
2151         $uri = $diaspora_handle . ':' . $guid;
2152
2153         $activity = ACTIVITY_LIKE;
2154         $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
2155         $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
2156         $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
2157         $body = $parent_item['body'];
2158
2159         $obj = <<< EOT
2160
2161         <object>
2162                 <type>$objtype</type>
2163                 <local>1</local>
2164                 <id>{$parent_item['uri']}</id>
2165                 <link>$link</link>
2166                 <title></title>
2167                 <content>$body</content>
2168         </object>
2169 EOT;
2170         $bodyverb = t('%1$s likes %2$s\'s %3$s');
2171
2172         // Fetch the contact id - if we know this contact
2173         $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
2174                 dbesc(normalise_link($person['url'])), intval($importer['uid']));
2175         if ($r) {
2176                 $cid = $r[0]['id'];
2177                 $network = $r[0]['network'];
2178         } else {
2179                 $cid = $contact['id'];
2180                 $network = NETWORK_DIASPORA;
2181         }
2182
2183         $arr = array();
2184
2185         $arr['uri'] = $uri;
2186         $arr['uid'] = $importer['uid'];
2187         $arr['guid'] = $guid;
2188         $arr['network']  = $network;
2189         $arr['contact-id'] = $cid;
2190         $arr['type'] = 'activity';
2191         $arr['wall'] = $parent_item['wall'];
2192         $arr['gravity'] = GRAVITY_LIKE;
2193         $arr['parent'] = $parent_item['id'];
2194         $arr['parent-uri'] = $parent_item['uri'];
2195
2196         $arr['owner-name'] = $parent_item['name'];
2197         $arr['owner-link'] = $parent_item['url'];
2198         //$arr['owner-avatar'] = $parent_item['thumb'];
2199         $arr['owner-avatar'] = ((x($parent_item,'thumb')) ? $parent_item['thumb'] : $parent_item['photo']);
2200
2201         $arr['author-name'] = $person['name'];
2202         $arr['author-link'] = $person['url'];
2203         $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
2204
2205         $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
2206         $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
2207         //$plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
2208         $plink = '[url='.$a->get_baseurl().'/display/'.urlencode($guid).']'.$post_type.'[/url]';
2209         $arr['body'] =  sprintf( $bodyverb, $ulink, $alink, $plink );
2210
2211         $arr['app']  = 'Diaspora';
2212
2213         $arr['private'] = $parent_item['private'];
2214         $arr['verb'] = $activity;
2215         $arr['object-type'] = $objtype;
2216         $arr['object'] = $obj;
2217         $arr['visible'] = 1;
2218         $arr['unseen'] = 1;
2219         $arr['last-child'] = 0;
2220
2221         $message_id = item_store($arr);
2222
2223
2224         //if($message_id) {
2225         //      q("update item set plink = '%s' where id = %d",
2226         //              //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
2227         //              dbesc($a->get_baseurl().'/display/'.$guid),
2228         //              intval($message_id)
2229         //      );
2230         //}
2231
2232         // If we are the origin of the parent we store the original signature and notify our followers
2233         if($parent_item['origin']) {
2234                 $author_signature_base64 = base64_encode($author_signature);
2235                 $author_signature_base64 = diaspora_repair_signature($author_signature_base64, $diaspora_handle);
2236
2237                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2238                         intval($message_id),
2239                         dbesc($signed_data),
2240                         dbesc($author_signature_base64),
2241                         dbesc($diaspora_handle)
2242                 );
2243
2244                 // notify others
2245                 proc_run('php','include/notifier.php','comment-import',$message_id);
2246         }
2247
2248         return;
2249 }
2250
2251 function diaspora_retraction($importer,$xml) {
2252
2253
2254         $guid = notags(unxmlify($xml->guid));
2255         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2256         $type = notags(unxmlify($xml->type));
2257
2258         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2259         if(! $contact)
2260                 return;
2261
2262         if($type === 'Person') {
2263                 require_once('include/Contact.php');
2264                 contact_remove($contact['id']);
2265         } elseif($type === 'StatusMessage') {
2266                 $guid = notags(unxmlify($xml->post_guid));
2267
2268                 $r = q("SELECT * FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2269                         dbesc($guid),
2270                         intval($importer['uid'])
2271                 );
2272                 if(count($r)) {
2273                         if(link_compare($r[0]['author-link'],$contact['url'])) {
2274                                 q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d",
2275                                         dbesc(datetime_convert()),
2276                                         intval($r[0]['id'])
2277                                 );
2278                                 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2279                         }
2280                 }
2281         } elseif($type === 'Post') {
2282                 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2283                         dbesc('guid'),
2284                         intval($importer['uid'])
2285                 );
2286                 if(count($r)) {
2287                         if(link_compare($r[0]['author-link'],$contact['url'])) {
2288                                 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d",
2289                                         dbesc(datetime_convert()),
2290                                         intval($r[0]['id'])
2291                                 );
2292                                 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2293                         }
2294                 }
2295         }
2296
2297         return 202;
2298         // NOTREACHED
2299 }
2300
2301 function diaspora_signed_retraction($importer,$xml,$msg) {
2302
2303
2304         $guid = notags(unxmlify($xml->target_guid));
2305         $diaspora_handle = notags(unxmlify($xml->sender_handle));
2306         $type = notags(unxmlify($xml->target_type));
2307         $sig = notags(unxmlify($xml->target_author_signature));
2308
2309         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
2310
2311         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2312         if(! $contact) {
2313                 logger('diaspora_signed_retraction: no contact ' . $diaspora_handle . ' for ' . $importer['uid']);
2314                 return;
2315         }
2316
2317
2318         $signed_data = $guid . ';' . $type ;
2319         $key = $msg['key'];
2320
2321         /* How Diaspora performs relayable_retraction signature checking:
2322
2323            - If an item has been sent by the item author to the top-level post owner to relay on
2324              to the rest of the contacts on the top-level post, the top-level post owner checks
2325              the author_signature, then creates a parent_author_signature before relaying the item on
2326            - If an item has been relayed on by the top-level post owner, the contacts who receive it
2327              check only the parent_author_signature. Basically, they trust that the top-level post
2328              owner has already verified the authenticity of anything he/she sends out
2329            - In either case, the signature that get checked is the signature created by the person
2330              who sent the salmon
2331         */
2332
2333         if($parent_author_signature) {
2334
2335                 $parent_author_signature = base64_decode($parent_author_signature);
2336
2337                 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
2338                         logger('diaspora_signed_retraction: top-level post owner verification failed');
2339                         return;
2340                 }
2341
2342         } else {
2343
2344                 $sig_decode = base64_decode($sig);
2345
2346                 if(! rsa_verify($signed_data,$sig_decode,$key,'sha256')) {
2347                         logger('diaspora_signed_retraction: retraction owner verification failed.' . print_r($msg,true));
2348                         return;
2349                 }
2350         }
2351
2352         if($type === 'StatusMessage' || $type === 'Comment' || $type === 'Like') {
2353                 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2354                         dbesc($guid),
2355                         intval($importer['uid'])
2356                 );
2357                 if(count($r)) {
2358                         if(link_compare($r[0]['author-link'],$contact['url'])) {
2359                                 q("update item set `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' where `id` = %d",
2360                                         dbesc(datetime_convert()),
2361                                         dbesc(datetime_convert()),
2362                                         intval($r[0]['id'])
2363                                 );
2364                                 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2365
2366                                 // Now check if the retraction needs to be relayed by us
2367                                 //
2368                                 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2369                                 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2370                                 // The only item with `parent` and `id` as the parent id is the parent item.
2371                                 $p = q("SELECT `origin` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2372                                         intval($r[0]['parent']),
2373                                         intval($r[0]['parent'])
2374                                 );
2375                                 if(count($p)) {
2376                                         if($p[0]['origin']) {
2377                                                 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2378                                                         $r[0]['id'],
2379                                                         dbesc($signed_data),
2380                                                         dbesc($sig),
2381                                                         dbesc($diaspora_handle)
2382                                                 );
2383
2384                                                 // the existence of parent_author_signature would have meant the parent_author or owner
2385                                                 // is already relaying.
2386                                                 logger('diaspora_signed_retraction: relaying relayable_retraction');
2387
2388                                                 proc_run('php','include/notifier.php','drop',$r[0]['id']);
2389                                         }
2390                                 }
2391                         }
2392                 }
2393         }
2394         else
2395                 logger('diaspora_signed_retraction: unknown type: ' . $type);
2396
2397         return 202;
2398         // NOTREACHED
2399 }
2400
2401 function diaspora_profile($importer,$xml,$msg) {
2402
2403         $a = get_app();
2404         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2405
2406
2407         if($diaspora_handle != $msg['author']) {
2408                 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
2409                 return 202;
2410         }
2411
2412         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2413         if(! $contact)
2414                 return;
2415
2416         //if($contact['blocked']) {
2417         //      logger('diaspora_post: Ignoring this author.');
2418         //      return 202;
2419         //}
2420
2421         $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
2422         $image_url = unxmlify($xml->image_url);
2423         $birthday = unxmlify($xml->birthday);
2424         $location = diaspora2bb(unxmlify($xml->location));
2425         $about = diaspora2bb(unxmlify($xml->bio));
2426         $gender = unxmlify($xml->gender);
2427         $searchable = (unxmlify($xml->searchable) == "true");
2428         $nsfw = (unxmlify($xml->nsfw) == "true");
2429         $tags = unxmlify($xml->tag_string);
2430
2431         $tags = explode("#", $tags);
2432
2433         $keywords = array();
2434         foreach ($tags as $tag) {
2435                 $tag = trim(strtolower($tag));
2436                 if ($tag != "")
2437                         $keywords[] = $tag;
2438         }
2439
2440         $keywords = implode(", ", $keywords);
2441
2442         $handle_parts = explode("@", $diaspora_handle);
2443         $nick = $handle_parts[0];
2444
2445         if($name === '') {
2446                 $name = $handle_parts[0];
2447         }
2448
2449         if( preg_match("|^https?://|", $image_url) === 0) {
2450                 $image_url = "http://" . $handle_parts[1] . $image_url;
2451         }
2452
2453 /*      $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE  `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
2454                 intval($importer['uid']),
2455                 intval($contact['id'])
2456         );
2457         $oldphotos = ((count($r)) ? $r : null);*/
2458
2459         require_once('include/Photo.php');
2460
2461         update_contact_avatar($image_url,$importer['uid'],$contact['id']);
2462
2463         // Generic birthday. We don't know the timezone. The year is irrelevant.
2464
2465         $birthday = str_replace('1000','1901',$birthday);
2466
2467         if ($birthday != "")
2468                 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
2469
2470         // this is to prevent multiple birthday notifications in a single year
2471         // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2472
2473         if(substr($birthday,5) === substr($contact['bd'],5))
2474                 $birthday = $contact['bd'];
2475
2476         /// @TODO Update name on item['author-name'] if the name changed. See consume_feed()
2477         /// (Not doing this currently because D* protocol is scheduled for revision soon).
2478
2479         $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
2480                         `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2481                 dbesc($name),
2482                 dbesc($nick),
2483                 dbesc($diaspora_handle),
2484                 dbesc(datetime_convert()),
2485                 dbesc($birthday),
2486                 dbesc($location),
2487                 dbesc($about),
2488                 dbesc($keywords),
2489                 dbesc($gender),
2490                 intval($contact['id']),
2491                 intval($importer['uid'])
2492         );
2493
2494         if ($searchable) {
2495                 require_once('include/socgraph.php');
2496                 poco_check($contact['url'], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
2497                         datetime_convert(), 2, $contact['id'], $importer['uid']);
2498         }
2499
2500         update_gcontact(array("url" => $contact['url'], "network" => NETWORK_DIASPORA, "generation" => 2,
2501                                 "photo" => $image_url, "name" => $name, "location" => $location,
2502                                 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2503                                 "addr" => $diaspora_handle, "nick" => $nick, "keywords" => $keywords,
2504                                 "hide" => !$searchable, "nsfw" => $nsfw));
2505
2506 /*      if($r) {
2507                 if($oldphotos) {
2508                         foreach($oldphotos as $ph) {
2509                                 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
2510                                         intval($importer['uid']),
2511                                         intval($contact['id']),
2512                                         dbesc($ph['resource-id'])
2513                                 );
2514                         }
2515                 }
2516         }       */
2517
2518         return;
2519
2520 }
2521
2522 function diaspora_share($me,$contact) {
2523         $a = get_app();
2524         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2525         $theiraddr = $contact['addr'];
2526
2527         $tpl = get_markup_template('diaspora_share.tpl');
2528         $msg = replace_macros($tpl, array(
2529                 '$sender' => $myaddr,
2530                 '$recipient' => $theiraddr
2531         ));
2532
2533         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2534         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2535
2536         return(diaspora_transmit($owner,$contact,$slap, false));
2537 }
2538
2539 function diaspora_unshare($me,$contact) {
2540
2541         $a = get_app();
2542         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2543
2544         $tpl = get_markup_template('diaspora_retract.tpl');
2545         $msg = replace_macros($tpl, array(
2546                 '$guid'   => $me['guid'],
2547                 '$type'   => 'Person',
2548                 '$handle' => $myaddr
2549         ));
2550
2551         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2552         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2553
2554         return(diaspora_transmit($owner,$contact,$slap, false));
2555
2556 }
2557
2558
2559 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
2560
2561         $a = get_app();
2562         $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2563         $theiraddr = $contact['addr'];
2564
2565         $images = array();
2566
2567         $title = $item['title'];
2568         $body = $item['body'];
2569
2570 /*
2571         // We're trying to match Diaspora's split message/photo protocol but
2572         // all the photos are displayed on D* as links and not img's - even
2573         // though we're sending pretty much precisely what they send us when
2574         // doing the same operation.  
2575         // Commented out for now, we'll use bb2diaspora to convert photos to markdown
2576         // which seems to get through intact.
2577
2578         $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
2579         if($cnt) {
2580                 foreach($matches as $mtch) {
2581                         $detail = array();
2582                         $detail['str'] = $mtch[0];
2583                         $detail['path'] = dirname($mtch[1]) . '/';
2584                         $detail['file'] = basename($mtch[1]);
2585                         $detail['guid'] = $item['guid'];
2586                         $detail['handle'] = $myaddr;
2587                         $images[] = $detail;
2588                         $body = str_replace($detail['str'],$mtch[1],$body);
2589                 }
2590         }
2591 */
2592
2593         //if(strlen($title))
2594         //      $body = "[b]".html_entity_decode($title)."[/b]\n\n".$body;
2595
2596         // convert to markdown
2597         $body = xmlify(html_entity_decode(bb2diaspora($body)));
2598         //$body = bb2diaspora($body);
2599
2600         // Adding the title
2601         if(strlen($title))
2602                 $body = "## ".html_entity_decode($title)."\n\n".$body;
2603
2604         if($item['attach']) {
2605                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
2606                 if(cnt) {
2607                         $body .= "\n" . t('Attachments:') . "\n";
2608                         foreach($matches as $mtch) {
2609                                 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
2610                         }
2611                 }
2612         }
2613
2614
2615         $public = (($item['private']) ? 'false' : 'true');
2616
2617         require_once('include/datetime.php');
2618         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2619
2620         // Detect a share element and do a reshare
2621         // see: https://github.com/Raven24/diaspora-federation/blob/master/lib/diaspora-federation/entities/reshare.rb
2622         if (!$item['private'] AND ($ret = diaspora_is_reshare($item["body"]))) {
2623                 $tpl = get_markup_template('diaspora_reshare.tpl');
2624                 $msg = replace_macros($tpl, array(
2625                         '$root_handle' => xmlify($ret['root_handle']),
2626                         '$root_guid' => $ret['root_guid'],
2627                         '$guid' => $item['guid'],
2628                         '$handle' => xmlify($myaddr),
2629                         '$public' => $public,
2630                         '$created' => $created,
2631                         '$provider' => $item["app"]
2632                 ));
2633         } else {
2634                 $tpl = get_markup_template('diaspora_post.tpl');
2635                 $msg = replace_macros($tpl, array(
2636                         '$body' => $body,
2637                         '$guid' => $item['guid'],
2638                         '$handle' => xmlify($myaddr),
2639                         '$public' => $public,
2640                         '$created' => $created,
2641                         '$provider' => $item["app"]
2642                 ));
2643         }
2644
2645         logger('diaspora_send_status: '.$owner['username'].' -> '.$contact['name'].' base message: '.$msg, LOGGER_DATA);
2646         logger('send guid '.$item['guid'], LOGGER_DEBUG);
2647
2648         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2649         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2650
2651         $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch,false,$item['guid']);
2652
2653         logger('diaspora_send_status: guid: '.$item['guid'].' result '.$return_code, LOGGER_DEBUG);
2654
2655         if(count($images)) {
2656                 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
2657         }
2658
2659         return $return_code;
2660 }
2661
2662 function diaspora_is_reshare($body) {
2663         $body = trim($body);
2664
2665         // Skip if it isn't a pure repeated messages
2666         // Does it start with a share?
2667         if (strpos($body, "[share") > 0)
2668                 return(false);
2669
2670         // Does it end with a share?
2671         if (strlen($body) > (strrpos($body, "[/share]") + 8))
2672                 return(false);
2673
2674         $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2675         // Skip if there is no shared message in there
2676         if ($body == $attributes)
2677                 return(false);
2678
2679         $guid = "";
2680         preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2681         if ($matches[1] != "")
2682                 $guid = $matches[1];
2683
2684         preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2685         if ($matches[1] != "")
2686                 $guid = $matches[1];
2687
2688         if ($guid != "") {
2689                 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2690                         dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2691                 if ($r) {
2692                         $ret= array();
2693                         $ret["root_handle"] = diaspora_handle_from_contact($r[0]["contact-id"]);
2694                         $ret["root_guid"] = $guid;
2695                         return($ret);
2696                 }
2697         }
2698
2699         $profile = "";
2700         preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2701         if ($matches[1] != "")
2702                 $profile = $matches[1];
2703
2704         preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2705         if ($matches[1] != "")
2706                 $profile = $matches[1];
2707
2708         $ret= array();
2709
2710         $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2711         if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2712                 return(false);
2713
2714         $link = "";
2715         preg_match("/link='(.*?)'/ism", $attributes, $matches);
2716         if ($matches[1] != "")
2717                 $link = $matches[1];
2718
2719         preg_match('/link="(.*?)"/ism', $attributes, $matches);
2720         if ($matches[1] != "")
2721                 $link = $matches[1];
2722
2723         $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2724         if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2725                 return(false);
2726
2727         return($ret);
2728 }
2729
2730 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
2731         $a = get_app();
2732         if(! count($images))
2733                 return;
2734         $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
2735
2736         $tpl = get_markup_template('diaspora_photo.tpl');
2737         foreach($images as $image) {
2738                 if(! stristr($image['path'],$mysite))
2739                         continue;
2740                 $resource = str_replace('.jpg','',$image['file']);
2741                 $resource = substr($resource,0,strpos($resource,'-'));
2742
2743                 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
2744                         dbesc($resource),
2745                         intval($owner['uid'])
2746                 );
2747                 if(! count($r))
2748                         continue;
2749                 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
2750                 $msg = replace_macros($tpl,array(
2751                         '$path' => xmlify($image['path']),
2752                         '$filename' => xmlify($image['file']),
2753                         '$msg_guid' => xmlify($image['guid']),
2754                         '$guid' => xmlify($r[0]['guid']),
2755                         '$handle' => xmlify($image['handle']),
2756                         '$public' => xmlify($public),
2757                         '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
2758                 ));
2759
2760
2761                 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
2762                 logger('send guid '.$r[0]['guid'], LOGGER_DEBUG);
2763
2764                 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2765                 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2766
2767                 diaspora_transmit($owner,$contact,$slap,$public_batch,false,$r[0]['guid']);
2768         }
2769
2770 }
2771
2772 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
2773
2774         $a = get_app();
2775         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2776 //      $theiraddr = $contact['addr'];
2777
2778         // Diaspora doesn't support threaded comments, but some
2779         // versions of Diaspora (i.e. Diaspora-pistos) support
2780         // likes on comments
2781         if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2782                 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2783                         dbesc($item['thr-parent'])
2784                       );
2785         }
2786         else {
2787                 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2788                 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2789                 // The only item with `parent` and `id` as the parent id is the parent item.
2790                 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2791                         intval($item['parent']),
2792                         intval($item['parent'])
2793                 );
2794         }
2795         if(count($p))
2796                 $parent = $p[0];
2797         else
2798                 return;
2799
2800         if($item['verb'] === ACTIVITY_LIKE) {
2801                 $tpl = get_markup_template('diaspora_like.tpl');
2802                 $like = true;
2803                 $target_type = ( $parent['uri'] === $parent['parent-uri']  ? 'Post' : 'Comment');
2804 //              $target_type = (strpos($parent['type'], 'comment') ? 'Comment' : 'Post');
2805 //              $positive = (($item['deleted']) ? 'false' : 'true');
2806                 $positive = 'true';
2807
2808                 if(($item['deleted']))
2809                         logger('diaspora_send_followup: received deleted "like". Those should go to diaspora_send_retraction');
2810         }
2811         else {
2812                 $tpl = get_markup_template('diaspora_comment.tpl');
2813                 $like = false;
2814         }
2815
2816         $text = html_entity_decode(bb2diaspora($item['body']));
2817
2818         // sign it
2819
2820         if($like)
2821                 $signed_text =  $positive . ';' . $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $myaddr;
2822         else
2823                 $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $myaddr;
2824
2825         $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2826
2827         $msg = replace_macros($tpl,array(
2828                 '$guid' => xmlify($item['guid']),
2829                 '$parent_guid' => xmlify($parent['guid']),
2830                 '$target_type' =>xmlify($target_type),
2831                 '$authorsig' => xmlify($authorsig),
2832                 '$body' => xmlify($text),
2833                 '$positive' => xmlify($positive),
2834                 '$handle' => xmlify($myaddr)
2835         ));
2836
2837         logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2838         logger('send guid '.$item['guid'], LOGGER_DEBUG);
2839
2840         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2841         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2842
2843         return(diaspora_transmit($owner,$contact,$slap,$public_batch,false,$item['guid']));
2844 }
2845
2846
2847 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2848
2849
2850         $a = get_app();
2851         $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2852 //      $theiraddr = $contact['addr'];
2853
2854         // Diaspora doesn't support threaded comments, but some
2855         // versions of Diaspora (i.e. Diaspora-pistos) support
2856         // likes on comments
2857         if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2858                 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2859                         dbesc($item['thr-parent'])
2860                       );
2861         }
2862         else {
2863                 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2864                 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2865                 // The only item with `parent` and `id` as the parent id is the parent item.
2866                 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2867                        intval($item['parent']),
2868                        intval($item['parent'])
2869                       );
2870         }
2871         if(count($p))
2872                 $parent = $p[0];
2873         else
2874                 return;
2875
2876         $like = false;
2877         $relay_retract = false;
2878         $sql_sign_id = 'iid';
2879         if( $item['deleted']) {
2880                 $relay_retract = true;
2881
2882                 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2883
2884                 $sql_sign_id = 'retract_iid';
2885                 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2886         }
2887         elseif($item['verb'] === ACTIVITY_LIKE) {
2888                 $like = true;
2889
2890                 $target_type = ( $parent['uri'] === $parent['parent-uri']  ? 'Post' : 'Comment');
2891 //              $positive = (($item['deleted']) ? 'false' : 'true');
2892                 $positive = 'true';
2893
2894                 $tpl = get_markup_template('diaspora_like_relay.tpl');
2895         }
2896         else { // item is a comment
2897                 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2898         }
2899
2900
2901         // fetch the original signature if the relayable was created by a Diaspora
2902         // or DFRN user. Relayables for other networks are not supported.
2903
2904         $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE " . $sql_sign_id . " = %d LIMIT 1",
2905                 intval($item['id'])
2906         );
2907         if(count($r)) {
2908                 $orig_sign = $r[0];
2909                 $signed_text = $orig_sign['signed_text'];
2910                 $authorsig = $orig_sign['signature'];
2911                 $handle = $orig_sign['signer'];
2912
2913                 // Split the signed text
2914                 $signed_parts = explode(";", $signed_text);
2915
2916                 // Remove the parent guid
2917                 array_shift($signed_parts);
2918
2919                 // Remove the comment guid
2920                 array_shift($signed_parts);
2921
2922                 // Remove the handle
2923                 array_pop($signed_parts);
2924
2925                 // Glue the parts together
2926                 $text = implode(";", $signed_parts);
2927         }
2928         else {
2929                 // This part is meant for cases where we don't have the signatur. (Which shouldn't happen with posts from Diaspora and Friendica)
2930                 // This means that the comment won't be accepted by newer Diaspora servers
2931
2932                 $body = $item['body'];
2933                 $text = html_entity_decode(bb2diaspora($body));
2934
2935                 $handle = diaspora_handle_from_contact($item['contact-id']);
2936                 if(! $handle)
2937                         return;
2938
2939                 if($relay_retract)
2940                         $signed_text = $item['guid'] . ';' . $target_type;
2941                 elseif($like)
2942                         $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle;
2943                 else
2944                         $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle;
2945
2946                 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2947         }
2948
2949         // Sign the relayable with the top-level owner's signature
2950         $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2951
2952         $msg = replace_macros($tpl,array(
2953                 '$guid' => xmlify($item['guid']),
2954                 '$parent_guid' => xmlify($parent['guid']),
2955                 '$target_type' =>xmlify($target_type),
2956                 '$authorsig' => xmlify($authorsig),
2957                 '$parentsig' => xmlify($parentauthorsig),
2958                 '$body' => xmlify($text),
2959                 '$positive' => xmlify($positive),
2960                 '$handle' => xmlify($handle)
2961         ));
2962
2963         logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DATA);
2964         logger('send guid '.$item['guid'], LOGGER_DEBUG);
2965
2966         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2967         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2968
2969         return(diaspora_transmit($owner,$contact,$slap,$public_batch,false,$item['guid']));
2970
2971 }
2972
2973
2974
2975 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2976
2977         $a = get_app();
2978         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2979
2980         // Check whether the retraction is for a top-level post or whether it's a relayable
2981         if( $item['uri'] !== $item['parent-uri'] ) {
2982
2983                 $tpl = get_markup_template('diaspora_relay_retraction.tpl');
2984                 $target_type = (($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2985         }
2986         else {
2987
2988                 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2989                 $target_type = 'StatusMessage';
2990         }
2991
2992         $signed_text = $item['guid'] . ';' . $target_type;
2993
2994         $msg = replace_macros($tpl, array(
2995                 '$guid'   => xmlify($item['guid']),
2996                 '$type'   => xmlify($target_type),
2997                 '$handle' => xmlify($myaddr),
2998                 '$signature' => xmlify(base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')))
2999         ));
3000
3001         logger('send guid '.$item['guid'], LOGGER_DEBUG);
3002
3003         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
3004         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
3005
3006         return(diaspora_transmit($owner,$contact,$slap,$public_batch,false,$item['guid']));
3007 }
3008
3009 function diaspora_send_mail($item,$owner,$contact) {
3010
3011         $a = get_app();
3012         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
3013
3014         $r = q("select * from conv where id = %d and uid = %d limit 1",
3015                 intval($item['convid']),
3016                 intval($item['uid'])
3017         );
3018
3019         if(! count($r)) {
3020                 logger('diaspora_send_mail: conversation not found.');
3021                 return;
3022         }
3023         $cnv = $r[0];
3024
3025         $conv = array(
3026                 'guid' => xmlify($cnv['guid']),
3027                 'subject' => xmlify($cnv['subject']),
3028                 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
3029                 'diaspora_handle' => xmlify($cnv['creator']),
3030                 'participant_handles' => xmlify($cnv['recips'])
3031         );
3032
3033         $body = bb2diaspora($item['body']);
3034         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
3035
3036         $signed_text =  $item['guid'] . ';' . $cnv['guid'] . ';' . $body .  ';'
3037                 . $created . ';' . $myaddr . ';' . $cnv['guid'];
3038
3039         $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
3040
3041         $msg = array(
3042                 'guid' => xmlify($item['guid']),
3043                 'parent_guid' => xmlify($cnv['guid']),
3044                 'parent_author_signature' => xmlify($sig),
3045                 'author_signature' => xmlify($sig),
3046                 'text' => xmlify($body),
3047                 'created_at' => xmlify($created),
3048                 'diaspora_handle' => xmlify($myaddr),
3049                 'conversation_guid' => xmlify($cnv['guid'])
3050         );
3051
3052         if($item['reply']) {
3053                 $tpl = get_markup_template('diaspora_message.tpl');
3054                 $xmsg = replace_macros($tpl, array('$msg' => $msg));
3055         }
3056         else {
3057                 $conv['messages'] = array($msg);
3058                 $tpl = get_markup_template('diaspora_conversation.tpl');
3059                 $xmsg = replace_macros($tpl, array('$conv' => $conv));
3060         }
3061
3062         logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
3063         logger('send guid '.$item['guid'], LOGGER_DEBUG);
3064
3065         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
3066         //$slap = 'xml=' . urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false));
3067
3068         return(diaspora_transmit($owner,$contact,$slap,false,false,$item['guid']));
3069
3070
3071 }
3072
3073 function diaspora_transmit($owner,$contact,$slap,$public_batch,$queue_run=false,$guid = "") {
3074
3075         $enabled = intval(get_config('system','diaspora_enabled'));
3076         if(! $enabled) {
3077                 return 200;
3078         }
3079
3080         $a = get_app();
3081         $logid = random_string(4);
3082         $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
3083         if(! $dest_url) {
3084                 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
3085                 return 0;
3086         }
3087
3088         logger('diaspora_transmit: '.$logid.'-'.$guid.' '.$dest_url);
3089
3090         if( (! $queue_run) && (was_recently_delayed($contact['id'])) ) {
3091                 $return_code = 0;
3092         }
3093         else {
3094                 if (!intval(get_config('system','diaspora_test'))) {
3095                         post_url($dest_url . '/', $slap);
3096                         $return_code = $a->get_curl_code();
3097                 } else {
3098                         logger('diaspora_transmit: test_mode');
3099                         return 200;
3100                 }
3101         }
3102
3103         logger('diaspora_transmit: '.$logid.'-'.$guid.' returns: '.$return_code);
3104
3105         if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
3106                 logger('diaspora_transmit: queue message');
3107
3108                 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
3109                         intval($contact['id']),
3110                         dbesc(NETWORK_DIASPORA),
3111                         dbesc($slap),
3112                         intval($public_batch)
3113                 );
3114                 if(count($r)) {
3115                         logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
3116                 }
3117                 else {
3118                         // queue message for redelivery
3119                         add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
3120                 }
3121         }
3122
3123
3124         return(($return_code) ? $return_code : (-1));
3125 }
3126
3127 function diaspora_fetch_relay() {
3128
3129         $serverdata = get_config("system", "relay_server");
3130         if ($serverdata == "")
3131                 return array();
3132
3133         $relay = array();
3134
3135         $servers = explode(",", $serverdata);
3136
3137         foreach($servers AS $server) {
3138                 $server = trim($server);
3139                 $batch = $server."/receive/public";
3140
3141                 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
3142
3143                 if (!$relais) {
3144                         $addr = "relay@".str_replace("http://", "", normalise_link($server));
3145
3146                         $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
3147                                 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
3148                                 datetime_convert(),
3149                                 dbesc($addr),
3150                                 dbesc($addr),
3151                                 dbesc($server),
3152                                 dbesc(normalise_link($server)),
3153                                 dbesc($batch),
3154                                 dbesc(NETWORK_DIASPORA),
3155                                 intval(CONTACT_IS_FOLLOWER),
3156                                 dbesc(datetime_convert()),
3157                                 dbesc(datetime_convert()),
3158                                 dbesc(datetime_convert())
3159                         );
3160
3161                         $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
3162                         if ($relais)
3163                                 $relay[] = $relais[0];
3164                 } else
3165                         $relay[] = $relais[0];
3166         }
3167
3168         return $relay;
3169 }