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