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