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