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