]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
Merge branch 'pull'
[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
9
10 function diaspora_dispatch_public($msg) {
11
12         $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN ( SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s' ) AND `account_expired` = 0 ",
13                 dbesc(NETWORK_DIASPORA),
14                 dbesc($msg['author'])
15         );
16         if(count($r)) {
17                 foreach($r as $rr) {
18                         logger('diaspora_public: delivering to: ' . $rr['username']);
19                         diaspora_dispatch($rr,$msg);
20                 }
21         }
22         else
23                 logger('diaspora_public: no subscribers');
24 }
25
26
27
28 function diaspora_dispatch($importer,$msg) {
29
30         $ret = 0;
31
32         // php doesn't like dashes in variable names
33
34         $msg['message'] = str_replace(
35                         array('<activity_streams-photo>','</activity_streams-photo>'),
36                         array('<asphoto>','</asphoto>'),
37                         $msg['message']);
38
39
40         $parsed_xml = parse_xml_string($msg['message'],false);
41
42         $xmlbase = $parsed_xml->post;
43
44         if($xmlbase->request) {
45                 $ret = diaspora_request($importer,$xmlbase->request);
46         }
47         elseif($xmlbase->status_message) {
48                 $ret = diaspora_post($importer,$xmlbase->status_message);
49         }
50         elseif($xmlbase->profile) {
51                 $ret = diaspora_profile($importer,$xmlbase->profile);
52         }
53         elseif($xmlbase->comment) {
54                 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
55         }
56         elseif($xmlbase->like) {
57                 $ret = diaspora_like($importer,$xmlbase->like,$msg);
58         }
59         elseif($xmlbase->asphoto) {
60                 $ret = diaspora_asphoto($importer,$xmlbase->asphoto);
61         }
62         elseif($xmlbase->reshare) {
63                 $ret = diaspora_reshare($importer,$xmlbase->reshare);
64         }
65         elseif($xmlbase->retraction) {
66                 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
67         }
68         elseif($xmlbase->signed_retraction) {
69                 $ret = diaspora_signed_retraction($importer,$xmlbase->retraction,$msg);
70         }
71         elseif($xmlbase->photo) {
72                 $ret = diaspora_photo($importer,$xmlbase->photo,$msg);
73         }
74         elseif($xmlbase->conversation) {
75                 $ret = diaspora_conversation($importer,$xmlbase->conversation,$msg);
76         }
77         else {
78                 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
79         }
80         return $ret;
81 }
82
83 function diaspora_get_contact_by_handle($uid,$handle) {
84         $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
85                 dbesc(NETWORK_DIASPORA),
86                 intval($uid),
87                 dbesc($handle)
88         );
89         if($r && count($r))
90                 return $r[0];
91         return false;
92 }
93
94 function find_diaspora_person_by_handle($handle) {
95         $update = false;
96         $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
97                 dbesc(NETWORK_DIASPORA),
98                 dbesc($handle)
99         );
100         if(count($r)) {
101                 logger('find_diaspora_person_by handle: in cache ' . print_r($r,true), LOGGER_DEBUG);
102                 // update record occasionally so it doesn't get stale
103                 $d = strtotime($r[0]['updated'] . ' +00:00');
104                 if($d > strtotime('now - 14 days'))
105                         return $r[0];
106                 $update = true;
107         }
108         logger('find_diaspora_person_by_handle: refresh',LOGGER_DEBUG);
109         require_once('include/Scrape.php');
110         $r = probe_url($handle, PROBE_DIASPORA);
111         if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
112                 add_fcontact($r,$update);
113                 return ($r);
114         }
115         return false;
116 }
117
118
119 function get_diaspora_key($uri) {
120         logger('Fetching diaspora key for: ' . $uri);
121
122         $r = find_diaspora_person_by_handle($uri);
123         if($r)
124                 return $r['pubkey'];
125         return '';
126 }
127
128
129 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
130         $a = get_app();
131
132         logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
133
134         
135         $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
136
137 //      $b64_data = base64_encode($msg);
138 //      $b64url_data = base64url_encode($b64_data);
139
140         $b64url_data = base64url_encode($msg);
141
142         $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
143
144         $type = 'application/xml';
145         $encoding = 'base64url';
146         $alg = 'RSA-SHA256';
147
148         $signable_data = $data  . '.' . base64url_encode($type) . '.' 
149                 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
150
151         $signature = rsa_sign($signable_data,$prvkey);
152         $sig = base64url_encode($signature);
153
154 $magic_env = <<< EOT
155 <?xml version='1.0' encoding='UTF-8'?>
156 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
157   <header>
158     <author_id>$handle</author_id>
159   </header>
160   <me:env>
161     <me:encoding>base64url</me:encoding>
162     <me:alg>RSA-SHA256</me:alg>
163     <me:data type="application/xml">$data</me:data>
164     <me:sig>$sig</me:sig>
165   </me:env>
166 </diaspora>
167 EOT;
168
169         logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
170         return $magic_env;
171
172 }
173
174
175
176
177 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
178         $a = get_app();
179
180         if($public)
181                 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
182
183         logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
184
185         $inner_aes_key = random_string(32);
186         $b_inner_aes_key = base64_encode($inner_aes_key);
187         $inner_iv = random_string(16);
188         $b_inner_iv = base64_encode($inner_iv);
189
190         $outer_aes_key = random_string(32);
191         $b_outer_aes_key = base64_encode($outer_aes_key);
192         $outer_iv = random_string(16);
193         $b_outer_iv = base64_encode($outer_iv);
194         
195         $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
196
197         $padded_data = pkcs5_pad($msg,16);
198         $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
199
200         $b64_data = base64_encode($inner_encrypted);
201
202
203         $b64url_data = base64url_encode($b64_data);
204         $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
205
206         $type = 'application/xml';
207         $encoding = 'base64url';
208         $alg = 'RSA-SHA256';
209
210         $signable_data = $data  . '.' . base64url_encode($type) . '.' 
211                 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
212
213         $signature = rsa_sign($signable_data,$prvkey);
214         $sig = base64url_encode($signature);
215
216 $decrypted_header = <<< EOT
217 <decrypted_header>
218   <iv>$b_inner_iv</iv>
219   <aes_key>$b_inner_aes_key</aes_key>
220   <author_id>$handle</author_id>
221 </decrypted_header>
222 EOT;
223
224         $decrypted_header = pkcs5_pad($decrypted_header,16);
225
226         $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
227
228         $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
229
230         $encrypted_outer_key_bundle = '';
231         openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
232
233         $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
234
235         logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
236
237         $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle), 
238                 'ciphertext' => base64_encode($ciphertext)));
239         $cipher_json = base64_encode($encrypted_header_json_object);
240
241         $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
242
243 $magic_env = <<< EOT
244 <?xml version='1.0' encoding='UTF-8'?>
245 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
246   $encrypted_header
247   <me:env>
248     <me:encoding>base64url</me:encoding>
249     <me:alg>RSA-SHA256</me:alg>
250     <me:data type="application/xml">$data</me:data>
251     <me:sig>$sig</me:sig>
252   </me:env>
253 </diaspora>
254 EOT;
255
256         logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
257         return $magic_env;
258
259 }
260
261 /**
262  *
263  * diaspora_decode($importer,$xml)
264  *   array $importer -> from user table
265  *   string $xml -> urldecoded Diaspora salmon 
266  *
267  * Returns array
268  * 'message' -> decoded Diaspora XML message
269  * 'author' -> author diaspora handle
270  * 'key' -> author public key (converted to pkcs#8)
271  *
272  * Author and key are used elsewhere to save a lookup for verifying replies and likes
273  */
274
275
276 function diaspora_decode($importer,$xml) {
277
278         $public = false;
279         $basedom = parse_xml_string($xml);
280
281         $children = $basedom->children('https://joindiaspora.com/protocol');
282
283         if($children->header) {
284                 $public = true;
285                 $author_link = str_replace('acct:','',$children->header->author_id);
286         }
287         else {
288
289                 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
290         
291                 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
292                 $ciphertext = base64_decode($encrypted_header->ciphertext);
293
294                 $outer_key_bundle = '';
295                 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
296
297                 $j_outer_key_bundle = json_decode($outer_key_bundle);
298
299                 $outer_iv = base64_decode($j_outer_key_bundle->iv);
300                 $outer_key = base64_decode($j_outer_key_bundle->key);
301
302                 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
303
304
305                 $decrypted = pkcs5_unpad($decrypted);
306
307                 /**
308                  * $decrypted now contains something like
309                  *
310                  *  <decrypted_header>
311                  *     <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
312                  *     <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
313
314 ***** OBSOLETE
315
316                  *     <author>
317                  *       <name>Ryan Hughes</name>
318                  *       <uri>acct:galaxor@diaspora.pirateship.org</uri>
319                  *     </author>
320
321 ***** CURRENT
322
323                  *     <author_id>galaxor@diaspora.priateship.org</author_id>
324
325 ***** END DIFFS
326
327                  *  </decrypted_header>
328                  */
329
330                 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
331                 $idom = parse_xml_string($decrypted,false);
332
333                 $inner_iv = base64_decode($idom->iv);
334                 $inner_aes_key = base64_decode($idom->aes_key);
335
336                 $author_link = str_replace('acct:','',$idom->author_id);
337
338         }
339
340         $dom = $basedom->children(NAMESPACE_SALMON_ME);
341
342         // figure out where in the DOM tree our data is hiding
343
344         if($dom->provenance->data)
345                 $base = $dom->provenance;
346         elseif($dom->env->data)
347                 $base = $dom->env;
348         elseif($dom->data)
349                 $base = $dom;
350         
351         if(! $base) {
352                 logger('mod-diaspora: unable to locate salmon data in xml ');
353                 http_status_exit(400);
354         }
355
356
357         // Stash the signature away for now. We have to find their key or it won't be good for anything.
358         $signature = base64url_decode($base->sig);
359
360         // unpack the  data
361
362         // strip whitespace so our data element will return to one big base64 blob
363         $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
364
365
366         // stash away some other stuff for later
367
368         $type = $base->data[0]->attributes()->type[0];
369         $keyhash = $base->sig[0]->attributes()->keyhash[0];
370         $encoding = $base->encoding;
371         $alg = $base->alg;
372
373
374         $signed_data = $data  . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
375
376
377         // decode the data
378         $data = base64url_decode($data);
379
380
381         if($public) {
382                 $inner_decrypted = $data;
383         }
384         else {
385
386                 // Decode the encrypted blob
387
388                 $inner_encrypted = base64_decode($data);
389                 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
390                 $inner_decrypted = pkcs5_unpad($inner_decrypted);
391         }
392
393         if(! $author_link) {
394                 logger('mod-diaspora: Could not retrieve author URI.');
395                 http_status_exit(400);
396         }
397
398         // Once we have the author URI, go to the web and try to find their public key
399         // (first this will look it up locally if it is in the fcontact cache)
400         // This will also convert diaspora public key from pkcs#1 to pkcs#8
401
402         logger('mod-diaspora: Fetching key for ' . $author_link );
403         $key = get_diaspora_key($author_link);
404
405         if(! $key) {
406                 logger('mod-diaspora: Could not retrieve author key.');
407                 http_status_exit(400);
408         }
409
410         $verify = rsa_verify($signed_data,$signature,$key);
411
412         if(! $verify) {
413                 logger('mod-diaspora: Message did not verify. Discarding.');
414                 http_status_exit(400);
415         }
416
417         logger('mod-diaspora: Message verified.');
418
419         return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
420
421 }
422
423         
424 function diaspora_request($importer,$xml) {
425
426         $a = get_app();
427
428         $sender_handle = unxmlify($xml->sender_handle);
429         $recipient_handle = unxmlify($xml->recipient_handle);
430
431         if(! $sender_handle || ! $recipient_handle)
432                 return;
433          
434         $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
435
436         if($contact) {
437
438                 // perhaps we were already sharing with this person. Now they're sharing with us.
439                 // That makes us friends.
440
441                 if($contact['rel'] == CONTACT_IS_FOLLOWER) {
442                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
443                                 intval(CONTACT_IS_FRIEND),
444                                 intval($contact['id']),
445                                 intval($importer['uid'])
446                         );
447                 }
448                 // send notification
449
450                 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
451                         intval($importer['uid'])
452                 );
453
454                 if((count($r)) && ($r[0]['hide-friends'] == 0)) {
455                         require_once('include/items.php');
456
457                         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
458                                 intval($importer['uid'])
459                         );
460
461                         // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
462
463                         if(count($self) && $contact['rel'] == CONTACT_IS_FOLLOWER) {
464
465                                 $arr = array();
466                                 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']); 
467                                 $arr['uid'] = $importer['uid'];
468                                 $arr['contact-id'] = $self[0]['id'];
469                                 $arr['wall'] = 1;
470                                 $arr['type'] = 'wall';
471                                 $arr['gravity'] = 0;
472                                 $arr['origin'] = 1;
473                                 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
474                                 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
475                                 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
476                                 $arr['verb'] = ACTIVITY_FRIEND;
477                                 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
478                                 
479                                 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
480                                 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
481                                 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
482                                 $arr['body'] =  sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
483
484                                 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
485                                         . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
486                                 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
487                                 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
488                                 $arr['object'] .= '</link></object>' . "\n";
489                                 $arr['last-child'] = 1;
490
491                                 $arr['allow_cid'] = $user[0]['allow_cid'];
492                                 $arr['allow_gid'] = $user[0]['allow_gid'];
493                                 $arr['deny_cid']  = $user[0]['deny_cid'];
494                                 $arr['deny_gid']  = $user[0]['deny_gid'];
495
496                                 $i = item_store($arr);
497                                 if($i)
498                                 proc_run('php',"include/notifier.php","activity","$i");
499
500                         }
501
502                 }
503
504                 return;
505         }
506         
507         $ret = find_diaspora_person_by_handle($sender_handle);
508
509
510         if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
511                 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
512                 return;
513         }
514
515         $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
516
517         $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
518                 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
519                 intval($importer['uid']),
520                 dbesc($ret['network']),
521                 dbesc($ret['addr']),
522                 datetime_convert(),
523                 dbesc($ret['url']),
524                 dbesc(normalise_link($ret['url'])),
525                 dbesc($batch),
526                 dbesc($ret['name']),
527                 dbesc($ret['nick']),
528                 dbesc($ret['photo']),
529                 dbesc($ret['pubkey']),
530                 dbesc($ret['notify']),
531                 dbesc($ret['poll']),
532                 1,
533                 2
534         );
535                  
536         // find the contact record we just created
537
538         $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
539
540         $hash = random_string() . (string) time();   // Generate a confirm_key
541         
542         if($contact_record) {
543                 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
544                         VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
545                         intval($importer['uid']),
546                         intval($contact_record['id']),
547                         0,
548                         0,
549                         dbesc( t('Sharing notification from Diaspora network')),
550                         dbesc($hash),
551                         dbesc(datetime_convert())
552                 );
553         }
554
555         return;
556 }
557
558 function diaspora_post($importer,$xml) {
559
560         $a = get_app();
561         $guid = notags(unxmlify($xml->guid));
562         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
563
564         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
565         if(! $contact)
566                 return;
567
568         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
569                 logger('diaspora_post: Ignoring this author.');
570                 return 202;
571         }
572
573         $message_id = $diaspora_handle . ':' . $guid;
574         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
575                 intval($importer['uid']),
576                 dbesc($message_id),
577                 dbesc($guid)
578         );
579         if(count($r)) {
580                 logger('diaspora_post: message exists: ' . $guid);
581                 return;
582         }
583
584     // allocate a guid on our system - we aren't fixing any collisions.
585         // we're ignoring them
586
587         $g = q("select * from guid where guid = '%s' limit 1",
588                 dbesc($guid)
589         );
590         if(! count($g)) {
591                 q("insert into guid ( guid ) values ( '%s' )",
592                         dbesc($guid)
593                 );
594         }
595
596         $created = unxmlify($xml->created_at);
597         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
598
599         $body = diaspora2bb($xml->raw_message);
600
601         $datarray = array();
602
603         $str_tags = '';
604
605         $tags = get_tags($body);
606
607         if(count($tags)) {
608                 foreach($tags as $tag) {
609                         if(strpos($tag,'#') === 0) {
610                                 if(strpos($tag,'[url='))
611                                         continue;
612                                 $basetag = str_replace('_',' ',substr($tag,1));
613                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
614                                 if(strlen($str_tags))
615                                         $str_tags .= ',';
616                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
617                                 continue;
618                         }
619                 }
620         }
621         
622         $datarray['uid'] = $importer['uid'];
623         $datarray['contact-id'] = $contact['id'];
624         $datarray['wall'] = 0;
625         $datarray['guid'] = $guid;
626         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
627         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
628         $datarray['private'] = $private;
629         $datarray['parent'] = 0;
630         $datarray['owner-name'] = $contact['name'];
631         $datarray['owner-link'] = $contact['url'];
632         $datarray['owner-avatar'] = $contact['thumb'];
633         $datarray['author-name'] = $contact['name'];
634         $datarray['author-link'] = $contact['url'];
635         $datarray['author-avatar'] = $contact['thumb'];
636         $datarray['body'] = $body;
637         $datarray['tag'] = $str_tags;
638         $datarray['app']  = 'Diaspora';
639
640         // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
641
642         $datarray['visible'] = ((strlen($body)) ? 1 : 0);
643
644         $message_id = item_store($datarray);
645
646         if($message_id) {
647                 q("update item set plink = '%s' where id = %d limit 1",
648                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
649                         intval($message_id)
650                 );
651         }
652
653         return;
654
655 }
656
657 function diaspora_reshare($importer,$xml) {
658
659         logger('diaspora_reshare: init: ' . print_r($xml,true));
660
661         $a = get_app();
662         $guid = notags(unxmlify($xml->guid));
663         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
664
665
666         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
667         if(! $contact)
668                 return;
669
670         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
671                 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
672                 return 202;
673         }
674
675         $message_id = $diaspora_handle . ':' . $guid;
676         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
677                 intval($importer['uid']),
678                 dbesc($message_id),
679                 dbesc($guid)
680         );
681         if(count($r)) {
682                 logger('diaspora_reshare: message exists: ' . $guid);
683                 return;
684         }
685
686         $orig_author = notags(unxmlify($xml->root_diaspora_id));
687         $orig_guid = notags(unxmlify($xml->root_guid));
688
689         $source_url = 'https://' . substr($orig_author,strpos($orig_author,'@')+1) . '/p/' . $orig_guid . '.xml';
690         $x = fetch_url($source_url);
691         if(! $x)
692                 $x = fetch_url(str_replace('https://','http://',$source_url));
693         if(! $x) {
694                 logger('diaspora_reshare: unable to fetch source url ' . $source_url);
695                 return;
696         }
697         logger('diaspora_reshare: source: ' . $x);
698
699         $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
700         $source_xml = parse_xml_string($x,false);
701
702         if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
703                 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
704                 $body = scale_diaspora_images($body,false);
705         }
706         elseif($source_xml->post->asphoto->image_url) {
707                 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
708                 $body = scale_diaspora_images($body);
709         }
710         elseif($source_xml->post->status_message) {
711                 $body = diaspora2bb($source_xml->post->status_message->raw_message);
712                 $body = scale_diaspora_images($body);
713
714         }
715         else {
716                 logger('diaspora_reshare: no reshare content found: ' . print_r($source_xml,true));
717                 return;
718         }
719         if(! $body) {
720                 logger('diaspora_reshare: empty body: source= ' . $x);
721                 return;
722         }
723
724         $person = find_diaspora_person_by_handle($orig_author);
725
726         if(is_array($person) && x($person,'name') && x($person,'url'))
727                 $details = '[url=' . $person['url'] . ']' . $person['name'] . '[/url]';
728         else
729                 $details = $orig_author;
730         
731         $prefix = '&#x2672; ' . $details . "\n"; 
732
733
734     // allocate a guid on our system - we aren't fixing any collisions.
735         // we're ignoring them
736
737         $g = q("select * from guid where guid = '%s' limit 1",
738                 dbesc($guid)
739         );
740         if(! count($g)) {
741                 q("insert into guid ( guid ) values ( '%s' )",
742                         dbesc($guid)
743                 );
744         }
745
746         $created = unxmlify($xml->created_at);
747         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
748
749         $datarray = array();
750
751         $str_tags = '';
752
753         $tags = get_tags($body);
754
755         if(count($tags)) {
756                 foreach($tags as $tag) {
757                         if(strpos($tag,'#') === 0) {
758                                 if(strpos($tag,'[url='))
759                                         continue;
760                                 $basetag = str_replace('_',' ',substr($tag,1));
761                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
762                                 if(strlen($str_tags))
763                                         $str_tags .= ',';
764                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
765                                 continue;
766                         }
767                 }
768         }
769         
770         $datarray['uid'] = $importer['uid'];
771         $datarray['contact-id'] = $contact['id'];
772         $datarray['wall'] = 0;
773         $datarray['guid'] = $guid;
774         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
775         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
776         $datarray['private'] = $private;
777         $datarray['parent'] = 0;
778         $datarray['owner-name'] = $contact['name'];
779         $datarray['owner-link'] = $contact['url'];
780         $datarray['owner-avatar'] = $contact['thumb'];
781         $datarray['author-name'] = $contact['name'];
782         $datarray['author-link'] = $contact['url'];
783         $datarray['author-avatar'] = $contact['thumb'];
784         $datarray['body'] = $prefix . $body;
785         $datarray['tag'] = $str_tags;
786         $datarray['app']  = 'Diaspora';
787
788         $message_id = item_store($datarray);
789
790         if($message_id) {
791                 q("update item set plink = '%s' where id = %d limit 1",
792                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
793                         intval($message_id)
794                 );
795         }
796
797         return;
798
799 }
800
801
802 function diaspora_asphoto($importer,$xml) {
803         logger('diaspora_asphoto called');
804
805         $a = get_app();
806         $guid = notags(unxmlify($xml->guid));
807         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
808
809         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
810         if(! $contact)
811                 return;
812
813         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
814                 logger('diaspora_asphoto: Ignoring this author.');
815                 return 202;
816         }
817
818         $message_id = $diaspora_handle . ':' . $guid;
819         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
820                 intval($importer['uid']),
821                 dbesc($message_id),
822                 dbesc($guid)
823         );
824         if(count($r)) {
825                 logger('diaspora_asphoto: message exists: ' . $guid);
826                 return;
827         }
828
829     // allocate a guid on our system - we aren't fixing any collisions.
830         // we're ignoring them
831
832         $g = q("select * from guid where guid = '%s' limit 1",
833                 dbesc($guid)
834         );
835         if(! count($g)) {
836                 q("insert into guid ( guid ) values ( '%s' )",
837                         dbesc($guid)
838                 );
839         }
840
841         $created = unxmlify($xml->created_at);
842         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
843
844         if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
845                 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
846                 $body = scale_diaspora_images($body,false);
847         }
848         elseif($xml->image_url) {
849                 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
850                 $body = scale_diaspora_images($body);
851         }
852         else {
853                 logger('diaspora_asphoto: no photo url found.');
854                 return;
855         }
856
857         $datarray = array();
858
859         
860         $datarray['uid'] = $importer['uid'];
861         $datarray['contact-id'] = $contact['id'];
862         $datarray['wall'] = 0;
863         $datarray['guid'] = $guid;
864         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
865         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
866         $datarray['private'] = $private;
867         $datarray['parent'] = 0;
868         $datarray['owner-name'] = $contact['name'];
869         $datarray['owner-link'] = $contact['url'];
870         $datarray['owner-avatar'] = $contact['thumb'];
871         $datarray['author-name'] = $contact['name'];
872         $datarray['author-link'] = $contact['url'];
873         $datarray['author-avatar'] = $contact['thumb'];
874         $datarray['body'] = $body;
875         
876         $datarray['app']  = 'Diaspora/Cubbi.es';
877
878         $message_id = item_store($datarray);
879
880         if($message_id) {
881                 q("update item set plink = '%s' where id = %d limit 1",
882                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
883                         intval($message_id)
884                 );
885         }
886
887         return;
888
889 }
890
891
892
893
894
895
896 function diaspora_comment($importer,$xml,$msg) {
897
898         $a = get_app();
899         $guid = notags(unxmlify($xml->guid));
900         $parent_guid = notags(unxmlify($xml->parent_guid));
901         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
902         $target_type = notags(unxmlify($xml->target_type));
903         $text = unxmlify($xml->text);
904         $author_signature = notags(unxmlify($xml->author_signature));
905
906         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
907
908         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
909         if(! $contact) {
910                 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
911                 return;
912         }
913
914         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
915                 logger('diaspora_comment: Ignoring this author.');
916                 return 202;
917         }
918
919         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
920                 intval($importer['uid']),
921                 dbesc($guid)
922         );
923         if(count($r)) {
924                 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
925                 return;
926         }
927
928         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
929                 intval($importer['uid']),
930                 dbesc($parent_guid)
931         );
932         if(! count($r)) {
933                 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
934                 return;
935         }
936         $parent_item = $r[0];
937
938         $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
939
940         $author_signature = base64_decode($author_signature);
941
942         if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
943                 $person = $contact;
944                 $key = $msg['key'];
945         }
946         else {
947                 $person = find_diaspora_person_by_handle($diaspora_handle);     
948
949                 if(is_array($person) && x($person,'pubkey'))
950                         $key = $person['pubkey'];
951                 else {
952                         logger('diaspora_comment: unable to find author details');
953                         return;
954                 }
955         }
956
957         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
958                 logger('diaspora_comment: verification failed.');
959                 return;
960         }
961
962         if($parent_author_signature) {
963                 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
964
965                 $parent_author_signature = base64_decode($parent_author_signature);
966
967                 $key = $msg['key'];
968
969                 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
970                         logger('diaspora_comment: owner verification failed.');
971                         return;
972                 }
973         }
974
975         // Phew! Everything checks out. Now create an item.
976
977         $body = diaspora2bb($text);
978
979         $message_id = $diaspora_handle . ':' . $guid;
980
981         $datarray = array();
982
983         $str_tags = '';
984
985         $tags = get_tags($body);
986
987         if(count($tags)) {
988                 foreach($tags as $tag) {
989                         if(strpos($tag,'#') === 0) {
990                                 if(strpos($tag,'[url='))
991                                         continue;
992                                 $basetag = str_replace('_',' ',substr($tag,1));
993                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
994                                 if(strlen($str_tags))
995                                         $str_tags .= ',';
996                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
997                                 continue;
998                         }
999                 }
1000         }
1001
1002         $datarray['uid'] = $importer['uid'];
1003         $datarray['contact-id'] = $contact['id'];
1004         $datarray['wall'] = $parent_item['wall'];
1005         $datarray['gravity'] = GRAVITY_COMMENT;
1006         $datarray['guid'] = $guid;
1007         $datarray['uri'] = $message_id;
1008         $datarray['parent-uri'] = $parent_item['uri'];
1009
1010         // No timestamps for comments? OK, we'll the use current time.
1011         $datarray['created'] = $datarray['edited'] = datetime_convert();
1012         $datarray['private'] = $parent_item['private'];
1013
1014         $datarray['owner-name'] = $parent_item['owner-name'];
1015         $datarray['owner-link'] = $parent_item['owner-link'];
1016         $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1017
1018         $datarray['author-name'] = $person['name'];
1019         $datarray['author-link'] = $person['url'];
1020         $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1021         $datarray['body'] = $body;
1022         $datarray['tag'] = $str_tags;
1023
1024         // We can't be certain what the original app is if the message is relayed.
1025         if(($parent_item['origin']) && (! $parent_author_signature)) 
1026                 $datarray['app']  = 'Diaspora';
1027
1028         $message_id = item_store($datarray);
1029
1030         if($message_id) {
1031                 q("update item set plink = '%s' where id = %d limit 1",
1032                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1033                         intval($message_id)
1034                 );
1035         }
1036
1037         if(($parent_item['origin']) && (! $parent_author_signature)) {
1038                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1039                         intval($message_id),
1040                         dbesc($author_signed_data),
1041                         dbesc(base64_encode($author_signature)),
1042                         dbesc($diaspora_handle)
1043                 );
1044
1045                 // if the message isn't already being relayed, notify others
1046                 // the existence of parent_author_signature means the parent_author or owner
1047                 // is already relaying.
1048
1049                 proc_run('php','include/notifier.php','comment',$message_id);
1050         }
1051         return;
1052 }
1053
1054
1055
1056
1057 function diaspora_conversation($importer,$xml,$msg) {
1058
1059         $a = get_app();
1060
1061         $guid = notags(unxmlify($xml->guid));
1062         $subject = notags(unxmlify($xml->subject));
1063         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1064         $participant_handles = notags(unxmlify($xml->participant_handles));
1065         $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1066
1067         $parent_uri = $diaspora_handle . ':' . $guid;
1068  
1069         $messages = $xml->message;
1070
1071         if(! count($messages)) {
1072                 logger('diaspora_conversation: empty conversation');
1073                 return;
1074         }
1075
1076         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1077         if(! $contact) {
1078                 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1079                 return;
1080         }
1081
1082         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
1083                 logger('diaspora_conversation: Ignoring this author.');
1084                 return 202;
1085         }
1086
1087         $conversation = null;
1088
1089         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1090                 intval($importer['uid']),
1091                 dbesc($guid)
1092         );
1093         if(count($c))
1094                 $conversation = $c[0];
1095         else {
1096                 $r = q("insert into conv (uid,guid,recips) values('%d, '%s', '%s') ",
1097                         intval($importer['uid']),
1098                         dbesc($guid),
1099                         dbesc($participant_handles)
1100                 );
1101                 if($r)
1102                         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1103                 intval($importer['uid']),
1104             dbesc($guid)
1105         );
1106             if(count($c))
1107             $conversation = $c[0];
1108         }
1109         if(! $conversation) {
1110                 logger('diaspora_conversation: unable to create conversation.');
1111                 return;
1112         }
1113
1114
1115         foreach($messages as $msg) {
1116
1117                 $reply = 0;
1118
1119                 $msg_guid = notags(unxmlify($msg->guid));
1120                 $msg_parent_guid = notags(unxmlify($msg->parent_guid));
1121                 $msg_parent_author_signature = notags(unxmlify($msg->parent_author_signature));
1122                 $msg_author_signature = notags(unxmlify($msg->author_signature));
1123                 $msg_text = unxmlify($msg->text);
1124                 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($msg->created_at)));
1125                 $msg_diaspora_handle = notags(unxmlify($msg->diaspora_handle));
1126                 $msg_conversation_guid = notags(unxmlify($msg->conversation_guid));
1127                 if($msg_conversation_guid != $guid) {
1128                         logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1129                         continue;
1130                 }
1131
1132                 // Is this right?
1133
1134                 if($msg_parent_guid != $guid)
1135                         $reply = 1;
1136                         
1137                 $body = diaspora2bb($msg_text);
1138                 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1139
1140                 $person = find_diaspora_person_by_handle($msg_diaspora_handle); 
1141                 if(is_array($person) && x($person,'pubkey'))
1142                         $key = $person['pubkey'];
1143                 else {
1144                         logger('diaspora_conversation: unable to find author details');
1145                         continue;
1146                 }
1147
1148                 $r = q("select id from mail where `uri` = '%s' limit 1",
1149                         dbesc($message_id)
1150                 );
1151                 if(count($r)) {
1152                         logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1153                         continue;
1154                 }
1155
1156                 q("insert into mail ( `uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`replied`,`uri`,`parent-uri`,`created`) values ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1157                         intval($importer['uid']),
1158                         dbesc($msg_guid),
1159                         intval($conversation['id']),
1160                         dbesc($person['name']),
1161                         dbesc($person['photo']),
1162                         dbesc($person['url']),
1163                         intval($contact['id']),  
1164                         dbesc($subject),
1165                         dbesc($body),
1166                         0,
1167                         intval($reply),
1168                         dbesc($message_id),
1169                         dbesc($parent_uri),
1170                         dbesc($msg_created_at)
1171                 );                      
1172
1173         }       
1174
1175
1176 /*
1177         $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1178
1179         $author_signature = base64_decode($author_signature);
1180
1181         if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1182                 $person = $contact;
1183                 $key = $msg['key'];
1184         }
1185         else {
1186                 $person = find_diaspora_person_by_handle($diaspora_handle);     
1187
1188                 if(is_array($person) && x($person,'pubkey'))
1189                         $key = $person['pubkey'];
1190                 else {
1191                         logger('diaspora_comment: unable to find author details');
1192                         return;
1193                 }
1194         }
1195
1196         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1197                 logger('diaspora_comment: verification failed.');
1198                 return;
1199         }
1200
1201         if($parent_author_signature) {
1202                 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1203
1204                 $parent_author_signature = base64_decode($parent_author_signature);
1205
1206                 $key = $msg['key'];
1207
1208                 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1209                         logger('diaspora_comment: owner verification failed.');
1210                         return;
1211                 }
1212         }
1213
1214         // Phew! Everything checks out. Now create an item.
1215
1216         $body = diaspora2bb($text);
1217
1218         $message_id = $diaspora_handle . ':' . $guid;
1219
1220         $datarray = array();
1221
1222         $str_tags = '';
1223
1224         $tags = get_tags($body);
1225
1226         if(count($tags)) {
1227                 foreach($tags as $tag) {
1228                         if(strpos($tag,'#') === 0) {
1229                                 if(strpos($tag,'[url='))
1230                                         continue;
1231                                 $basetag = str_replace('_',' ',substr($tag,1));
1232                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
1233                                 if(strlen($str_tags))
1234                                         $str_tags .= ',';
1235                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1236                                 continue;
1237                         }
1238                 }
1239         }
1240
1241 */
1242
1243         return;
1244 }
1245
1246
1247
1248
1249
1250
1251 function diaspora_photo($importer,$xml,$msg) {
1252
1253         $a = get_app();
1254         $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1255
1256         $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1257
1258         $status_message_guid = notags(unxmlify($xml->status_message_guid));
1259
1260         $guid = notags(unxmlify($xml->guid));
1261
1262         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1263
1264         $public = notags(unxmlify($xml->public));
1265
1266         $created_at = notags(unxmlify($xml_created_at));
1267
1268
1269         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1270         if(! $contact)
1271                 return;
1272
1273         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
1274                 logger('diaspora_photo: Ignoring this author.');
1275                 return 202;
1276         }
1277
1278         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1279                 intval($importer['uid']),
1280                 dbesc($status_message_guid)
1281         );
1282         if(! count($r)) {
1283                 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1284                 return;
1285         }
1286         $parent_item = $r[0];
1287
1288         $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1289
1290         $link_text = scale_diaspora_images($link_text);
1291
1292         if(strpos($parent_item['body'],$link_text) === false) {
1293                 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d limit 1",
1294                         dbesc($link_text . $parent_item['body']),
1295                         intval($parent_item['id']),
1296                         intval($parent_item['uid'])
1297                 );
1298         }
1299
1300         return;
1301 }
1302
1303
1304
1305
1306 function diaspora_like($importer,$xml,$msg) {
1307
1308         $a = get_app();
1309         $guid = notags(unxmlify($xml->guid));
1310         $parent_guid = notags(unxmlify($xml->parent_guid));
1311         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1312         $target_type = notags(unxmlify($xml->target_type));
1313         $positive = notags(unxmlify($xml->positive));
1314         $author_signature = notags(unxmlify($xml->author_signature));
1315
1316         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1317
1318         // likes on comments not supported here and likes on photos not supported by Diaspora
1319
1320         if($target_type !== 'Post')
1321                 return;
1322
1323         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1324         if(! $contact) {
1325                 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1326                 return;
1327         }
1328
1329         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
1330                 logger('diaspora_like: Ignoring this author.');
1331                 return 202;
1332         }
1333
1334         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1335                 intval($importer['uid']),
1336                 dbesc($parent_guid)
1337         );
1338         if(! count($r)) {
1339                 logger('diaspora_like: parent item not found: ' . $guid);
1340                 return;
1341         }
1342
1343         $parent_item = $r[0];
1344
1345         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1346                 intval($importer['uid']),
1347                 dbesc($guid)
1348         );
1349         if(count($r)) {
1350                 if($positive === 'true') {
1351                         logger('diaspora_like: duplicate like: ' . $guid);
1352                         return;
1353                 } 
1354                 if($positive === 'false') {
1355                         q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
1356                                 intval($r[0]['id']),
1357                                 intval($importer['uid'])
1358                         );
1359                         // FIXME
1360                         //  send notification via proc_run()
1361                         return;
1362                 }
1363         }
1364         if($positive === 'false') {
1365                 logger('diaspora_like: unlike received with no corresponding like');
1366                 return; 
1367         }
1368
1369         $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1370
1371         $author_signature = base64_decode($author_signature);
1372
1373         if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1374                 $person = $contact;
1375                 $key = $msg['key'];
1376         }
1377         else {
1378                 $person = find_diaspora_person_by_handle($diaspora_handle);     
1379                 if(is_array($person) && x($person,'pubkey'))
1380                         $key = $person['pubkey'];
1381                 else {
1382                         logger('diaspora_like: unable to find author details');
1383                         return;
1384                 }
1385         }
1386
1387         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1388                 logger('diaspora_like: verification failed.');
1389                 return;
1390         }
1391
1392         if($parent_author_signature) {
1393
1394                 $owner_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1395
1396                 $parent_author_signature = base64_decode($parent_author_signature);
1397
1398                 $key = $msg['key'];
1399
1400                 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1401                         logger('diaspora_like: owner verification failed.');
1402                         return;
1403                 }
1404         }
1405
1406         // Phew! Everything checks out. Now create an item.
1407
1408         $uri = $diaspora_handle . ':' . $guid;
1409
1410         $activity = ACTIVITY_LIKE;
1411         $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
1412         $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE ); 
1413         $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
1414         $body = $parent_item['body'];
1415
1416         $obj = <<< EOT
1417
1418         <object>
1419                 <type>$objtype</type>
1420                 <local>1</local>
1421                 <id>{$parent_item['uri']}</id>
1422                 <link>$link</link>
1423                 <title></title>
1424                 <content>$body</content>
1425         </object>
1426 EOT;
1427         $bodyverb = t('%1$s likes %2$s\'s %3$s');
1428
1429         $arr = array();
1430
1431         $arr['uri'] = $uri;
1432         $arr['uid'] = $importer['uid'];
1433         $arr['guid'] = $guid;
1434         $arr['contact-id'] = $contact['id'];
1435         $arr['type'] = 'activity';
1436         $arr['wall'] = $parent_item['wall'];
1437         $arr['gravity'] = GRAVITY_LIKE;
1438         $arr['parent'] = $parent_item['id'];
1439         $arr['parent-uri'] = $parent_item['uri'];
1440
1441         $arr['owner-name'] = $parent_item['name'];
1442         $arr['owner-link'] = $parent_item['url'];
1443         $arr['owner-avatar'] = $parent_item['thumb'];
1444
1445         $arr['author-name'] = $person['name'];
1446         $arr['author-link'] = $person['url'];
1447         $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1448         
1449         $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1450         $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1451         $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1452         $arr['body'] =  sprintf( $bodyverb, $ulink, $alink, $plink );
1453
1454         $arr['app']  = 'Diaspora';
1455
1456         $arr['private'] = $parent_item['private'];
1457         $arr['verb'] = $activity;
1458         $arr['object-type'] = $objtype;
1459         $arr['object'] = $obj;
1460         $arr['visible'] = 1;
1461         $arr['unseen'] = 1;
1462         $arr['last-child'] = 0;
1463
1464         $message_id = item_store($arr);
1465
1466
1467         if($message_id) {
1468                 q("update item set plink = '%s' where id = %d limit 1",
1469                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1470                         intval($message_id)
1471                 );
1472         }
1473
1474         if(! $parent_author_signature) {
1475                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1476                         intval($message_id),
1477                         dbesc($author_signed_data),
1478                         dbesc(base64_encode($author_signature)),
1479                         dbesc($diaspora_handle)
1480                 );
1481         }
1482
1483         // if the message isn't already being relayed, notify others
1484         // the existence of parent_author_signature means the parent_author or owner
1485         // is already relaying. The parent_item['origin'] indicates the message was created on our system
1486
1487         if(($parent_item['origin']) && (! $parent_author_signature))
1488                 proc_run('php','include/notifier.php','comment',$message_id);
1489
1490         return;
1491 }
1492
1493 function diaspora_retraction($importer,$xml) {
1494
1495         $guid = notags(unxmlify($xml->guid));
1496         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1497         $type = notags(unxmlify($xml->type));
1498
1499         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1500         if(! $contact)
1501                 return;
1502
1503         if($type === 'Person') {
1504                 require_once('include/Contact.php');
1505                 contact_remove($contact['id']);
1506         }
1507         elseif($type === 'Post') {
1508                 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1509                         dbesc('guid'),
1510                         intval($importer['uid'])
1511                 );
1512                 if(count($r)) {
1513                         if(link_compare($r[0]['author-link'],$contact['url'])) {
1514                                 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1515                                         dbesc(datetime_convert()),                      
1516                                         intval($r[0]['id'])
1517                                 );
1518                         }
1519                 }
1520         }
1521
1522         return 202;
1523         // NOTREACHED
1524 }
1525
1526 function diaspora_signed_retraction($importer,$xml) {
1527
1528         $guid = notags(unxmlify($xml->target_guid));
1529         $diaspora_handle = notags(unxmlify($xml->sender_handle));
1530         $type = notags(unxmlify($xml->target_type));
1531         $sig = notags(unxmlify($xml->target_author_signature));
1532
1533         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1534         if(! $contact)
1535                 return;
1536
1537         // this may not yet work for comments. Need to see how the relaying works
1538         // and figure out who signs it.
1539
1540
1541         $signed_data = $guid . ';' . $type ;
1542
1543         $sig = base64_decode($sig);
1544
1545         $key = $msg['key'];
1546
1547         if(! rsa_verify($signed_data,$sig,$key,'sha256')) {
1548                 logger('diaspora_signed_retraction: owner verification failed.' . print_r($msg,true));
1549                 return;
1550         }
1551
1552         if($type === 'StatusMessage') {
1553                 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1554                         dbesc('guid'),
1555                         intval($importer['uid'])
1556                 );
1557                 if(count($r)) {
1558                         if(link_compare($r[0]['author-link'],$contact['url'])) {
1559                                 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1560                                         dbesc(datetime_convert()),                      
1561                                         intval($r[0]['id'])
1562                                 );
1563                         }
1564                 }
1565         }
1566
1567         return 202;
1568         // NOTREACHED
1569 }
1570
1571 function diaspora_profile($importer,$xml) {
1572
1573         $a = get_app();
1574         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1575
1576         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1577         if(! $contact)
1578                 return;
1579
1580         if($contact['blocked']) {
1581                 logger('diaspora_post: Ignoring this author.');
1582                 return 202;
1583         }
1584
1585         $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
1586         $image_url = unxmlify($xml->image_url);
1587         $birthday = unxmlify($xml->birthday);
1588
1589         $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE  `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
1590                 intval($importer['uid']),
1591                 intval($contact['id'])
1592         );
1593         $oldphotos = ((count($r)) ? $r : null);
1594
1595         require_once('include/Photo.php');
1596
1597         $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
1598         
1599         // Generic birthday. We don't know the timezone. The year is irrelevant. 
1600
1601         $birthday = str_replace('1000','1901',$birthday);
1602
1603         $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
1604
1605         $r = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s', `avatar-date` = '%s' , `bd` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
1606                 dbesc($name),
1607                 dbesc(datetime_convert()),
1608                 dbesc($images[0]),
1609                 dbesc($images[1]),
1610                 dbesc($images[2]),
1611                 dbesc(datetime_convert()),
1612                 dbesc($birthday),
1613                 intval($contact['id']),
1614                 intval($importer['uid'])
1615         ); 
1616
1617         if($r) {
1618                 if($oldphotos) {
1619                         foreach($oldphotos as $ph) {
1620                                 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
1621                                         intval($importer['uid']),
1622                                         intval($contact['id']),
1623                                         dbesc($ph['resource-id'])
1624                                 );
1625                         }
1626                 }
1627         }       
1628
1629         return;
1630
1631 }
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654 function diaspora_share($me,$contact) {
1655         $a = get_app();
1656         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1657         $theiraddr = $contact['addr'];
1658
1659         $tpl = get_markup_template('diaspora_share.tpl');
1660         $msg = replace_macros($tpl, array(
1661                 '$sender' => $myaddr,
1662                 '$recipient' => $theiraddr
1663         ));
1664
1665         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1666
1667         return(diaspora_transmit($owner,$contact,$slap, false));
1668 }
1669
1670 function diaspora_unshare($me,$contact) {
1671
1672         $a = get_app();
1673         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1674
1675         $tpl = get_markup_template('diaspora_retract.tpl');
1676         $msg = replace_macros($tpl, array(
1677                 '$guid'   => $me['guid'],
1678                 '$type'   => 'Person',
1679                 '$handle' => $myaddr
1680         ));
1681
1682         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1683
1684         return(diaspora_transmit($owner,$contact,$slap, false));
1685
1686 }
1687
1688
1689
1690 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
1691
1692         $a = get_app();
1693         $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1694         $theiraddr = $contact['addr'];
1695
1696         $images = array();
1697
1698         $body = $item['body'];
1699
1700 /*
1701         // We're trying to match Diaspora's split message/photo protocol but
1702         // all the photos are displayed on D* as links and not img's - even
1703         // though we're sending pretty much precisely what they send us when
1704         // doing the same operation.  
1705         // Commented out for now, we'll use bb2diaspora to convert photos to markdown
1706         // which seems to get through intact.
1707
1708         $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
1709         if($cnt) {
1710                 foreach($matches as $mtch) {
1711                         $detail = array();
1712                         $detail['str'] = $mtch[0];
1713                         $detail['path'] = dirname($mtch[1]) . '/';
1714                         $detail['file'] = basename($mtch[1]);
1715                         $detail['guid'] = $item['guid'];
1716                         $detail['handle'] = $myaddr;
1717                         $images[] = $detail;
1718                         $body = str_replace($detail['str'],$mtch[1],$body);
1719                 }
1720         }       
1721 */
1722
1723         $body = xmlify(html_entity_decode(bb2diaspora($body)));
1724
1725         if($item['attach']) {
1726                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
1727                 if(cnt) {
1728                         $body .= "\n" . t('Attachments:') . "\n";
1729                         foreach($matches as $mtch) {
1730                                 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
1731                         }
1732                 }
1733         }       
1734
1735
1736         $public = (($item['private']) ? 'false' : 'true');
1737
1738         require_once('include/datetime.php');
1739         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
1740
1741         $tpl = get_markup_template('diaspora_post.tpl');
1742         $msg = replace_macros($tpl, array(
1743                 '$body' => $body,
1744                 '$guid' => $item['guid'],
1745                 '$handle' => xmlify($myaddr),
1746                 '$public' => $public,
1747                 '$created' => $created
1748         ));
1749
1750         logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
1751
1752         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1753
1754         $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
1755
1756         if(count($images)) {
1757                 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
1758         }
1759
1760         return $return_code;
1761 }
1762
1763
1764 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
1765         $a = get_app();
1766         if(! count($images))
1767                 return;
1768         $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
1769
1770         $tpl = get_markup_template('diaspora_photo.tpl');
1771         foreach($images as $image) {
1772                 if(! stristr($image['path'],$mysite))
1773                         continue;
1774                 $resource = str_replace('.jpg','',$image['file']);
1775                 $resource = substr($resource,0,strpos($resource,'-'));
1776
1777                 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
1778                         dbesc($resource),
1779                         intval($owner['uid'])
1780                 );
1781                 if(! count($r))
1782                         continue;
1783                 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
1784                 $msg = replace_macros($tpl,array(               
1785                         '$path' => xmlify($image['path']),
1786                         '$filename' => xmlify($image['file']),
1787                         '$msg_guid' => xmlify($image['guid']),
1788                         '$guid' => xmlify($r[0]['guid']),
1789                         '$handle' => xmlify($image['handle']),
1790                         '$public' => xmlify($public),
1791                         '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
1792                 ));
1793
1794
1795                 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
1796                 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1797
1798                 diaspora_transmit($owner,$contact,$slap,$public_batch);
1799         }
1800
1801 }
1802
1803 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
1804
1805         $a = get_app();
1806         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1807         $theiraddr = $contact['addr'];
1808
1809         $p = q("select guid from item where parent = %d limit 1",
1810                 $item['parent']
1811         );
1812         if(count($p))
1813                 $parent_guid = $p[0]['guid'];
1814         else
1815                 return;
1816
1817         if($item['verb'] === ACTIVITY_LIKE) {
1818                 $tpl = get_markup_template('diaspora_like.tpl');
1819                 $like = true;
1820                 $target_type = 'Post';
1821                 $positive = (($item['deleted']) ? 'false' : 'true');
1822         }
1823         else {
1824                 $tpl = get_markup_template('diaspora_comment.tpl');
1825                 $like = false;
1826         }
1827
1828         $text = html_entity_decode(bb2diaspora($item['body']));
1829
1830         // sign it
1831
1832         if($like)
1833                 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1834         else
1835                 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1836
1837         $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1838
1839         $msg = replace_macros($tpl,array(
1840                 '$guid' => xmlify($item['guid']),
1841                 '$parent_guid' => xmlify($parent_guid),
1842                 '$target_type' =>xmlify($target_type),
1843                 '$authorsig' => xmlify($authorsig),
1844                 '$body' => xmlify($text),
1845                 '$positive' => xmlify($positive),
1846                 '$handle' => xmlify($myaddr)
1847         ));
1848
1849         logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
1850
1851         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1852
1853         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1854 }
1855
1856
1857 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
1858
1859
1860         $a = get_app();
1861         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1862         $theiraddr = $contact['addr'];
1863
1864
1865         $p = q("select guid from item where parent = %d limit 1",
1866                 $item['parent']
1867         );
1868         if(count($p))
1869                 $parent_guid = $p[0]['guid'];
1870         else
1871                 return;
1872
1873         if($item['verb'] === ACTIVITY_LIKE) {
1874                 $tpl = get_markup_template('diaspora_like_relay.tpl');
1875                 $like = true;
1876                 $target_type = 'Post';
1877                 $positive = (($item['deleted']) ? 'false' : 'true');
1878         }
1879         else {
1880                 $tpl = get_markup_template('diaspora_comment_relay.tpl');
1881                 $like = false;
1882         }
1883
1884         $body = $item['body'];
1885
1886         $text = html_entity_decode(bb2diaspora($body));
1887
1888         // fetch the original signature if somebody sent the post to us to relay
1889         // If we are relaying for a reply originating on our own account, there wasn't a 'send to relay'
1890         // action. It wasn't needed. In that case create the original signature and the 
1891         // owner (parent author) signature
1892         // comments from other networks will be relayed under our name, with a brief 
1893         // preamble to describe what's happening and noting the real author
1894
1895         $r = q("select * from sign where iid = %d limit 1",
1896                 intval($item['id'])
1897         );
1898         if(count($r)) { 
1899                 $orig_sign = $r[0];
1900                 $signed_text = $orig_sign['signed_text'];
1901                 $authorsig = $orig_sign['signature'];
1902                 $handle = $orig_sign['signer'];
1903         }
1904         else {
1905
1906                 $itemcontact = q("select * from contact where `id` = %d limit 1",
1907                         intval($item['contact-id'])
1908                 );
1909                 if(count($itemcontact)) {
1910                         if(! $itemcontact[0]['self']) {
1911                                 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
1912                                         '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',  
1913                                         network_to_name($itemcontact['network'])) . "\n";
1914                                 $body = $prefix . $body;
1915                         }
1916                 }
1917                 else {
1918
1919                         if($like)
1920                                 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1921                         else
1922                                 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1923
1924                         $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1925
1926                         q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1927                                 intval($item['id']),
1928                                 dbesc($signed_text),
1929                                 dbesc(base64_encode($authorsig)),
1930                                 dbesc($myaddr)
1931                         );
1932                         $handle = $myaddr;
1933                 }
1934         }
1935
1936         // sign it
1937
1938         $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1939
1940         $msg = replace_macros($tpl,array(
1941                 '$guid' => xmlify($item['guid']),
1942                 '$parent_guid' => xmlify($parent_guid),
1943                 '$target_type' =>xmlify($target_type),
1944                 '$authorsig' => xmlify($orig_sign['signature']),
1945                 '$parentsig' => xmlify($parentauthorsig),
1946                 '$body' => xmlify($text),
1947                 '$positive' => xmlify($positive),
1948                 '$handle' => xmlify($handle)
1949         ));
1950
1951         logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
1952
1953         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1954
1955         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1956
1957 }
1958
1959
1960
1961 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
1962
1963         $a = get_app();
1964         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1965
1966         $signed_text = $item['guid'] . ';' . 'StatusMessage';
1967
1968         $tpl = get_markup_template('diaspora_signed_retract.tpl');
1969         $msg = replace_macros($tpl, array(
1970                 '$guid'   => $item['guid'],
1971                 '$type'   => 'StatusMessage',
1972                 '$handle' => $myaddr,
1973                 '$signature' => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'))
1974         ));
1975
1976         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1977
1978         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1979 }
1980
1981
1982
1983 function diaspora_transmit($owner,$contact,$slap,$public_batch) {
1984
1985         $a = get_app();
1986         $logid = random_string(4);
1987         $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
1988         if(! $dest_url) {
1989                 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
1990                 return 0;
1991         } 
1992
1993         logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
1994
1995         post_url($dest_url . '/', $slap);
1996
1997         $return_code = $a->get_curl_code();
1998         logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
1999
2000         if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
2001                 logger('diaspora_transmit: queue message');
2002
2003                 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
2004                         intval($contact['id']),
2005                         dbesc(NETWORK_DIASPORA),
2006                         dbesc($slap),
2007                         intval($public_batch)
2008                 );
2009                 if(count($r)) {
2010                         logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
2011                 }
2012                 else {
2013                         // queue message for redelivery
2014                         add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
2015                 }
2016         }
2017
2018
2019         return(($return_code) ? $return_code : (-1));
2020 }