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