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