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