]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
9cef21ceb3408789b255c5616f4d12aa1fcd39fc
[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 $msg) {
1119
1120                 $reply = 0;
1121
1122                 $msg_guid = notags(unxmlify($msg->guid));
1123                 $msg_parent_guid = notags(unxmlify($msg->parent_guid));
1124                 $msg_parent_author_signature = notags(unxmlify($msg->parent_author_signature));
1125                 $msg_author_signature = notags(unxmlify($msg->author_signature));
1126                 $msg_text = unxmlify($msg->text);
1127                 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($msg->created_at)));
1128                 $msg_diaspora_handle = notags(unxmlify($msg->diaspora_handle));
1129                 $msg_conversation_guid = notags(unxmlify($msg->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                 $person = find_diaspora_person_by_handle($msg_diaspora_handle); 
1144                 if(is_array($person) && x($person,'pubkey'))
1145                         $key = $person['pubkey'];
1146                 else {
1147                         logger('diaspora_conversation: unable to find author details');
1148                         continue;
1149                 }
1150
1151                 $r = q("select id from mail where `uri` = '%s' limit 1",
1152                         dbesc($message_id)
1153                 );
1154                 if(count($r)) {
1155                         logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1156                         continue;
1157                 }
1158
1159                 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')",
1160                         intval($importer['uid']),
1161                         dbesc($msg_guid),
1162                         intval($conversation['id']),
1163                         dbesc($person['name']),
1164                         dbesc($person['photo']),
1165                         dbesc($person['url']),
1166                         intval($contact['id']),  
1167                         dbesc($subject),
1168                         dbesc($body),
1169                         0,
1170                         intval($reply),
1171                         dbesc($message_id),
1172                         dbesc($parent_uri),
1173                         dbesc($msg_created_at)
1174                 );                      
1175
1176         }       
1177
1178
1179 /*
1180         $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1181
1182         $author_signature = base64_decode($author_signature);
1183
1184         if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1185                 $person = $contact;
1186                 $key = $msg['key'];
1187         }
1188         else {
1189                 $person = find_diaspora_person_by_handle($diaspora_handle);     
1190
1191                 if(is_array($person) && x($person,'pubkey'))
1192                         $key = $person['pubkey'];
1193                 else {
1194                         logger('diaspora_comment: unable to find author details');
1195                         return;
1196                 }
1197         }
1198
1199         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1200                 logger('diaspora_comment: verification failed.');
1201                 return;
1202         }
1203
1204         if($parent_author_signature) {
1205                 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1206
1207                 $parent_author_signature = base64_decode($parent_author_signature);
1208
1209                 $key = $msg['key'];
1210
1211                 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1212                         logger('diaspora_comment: owner verification failed.');
1213                         return;
1214                 }
1215         }
1216
1217         // Phew! Everything checks out. Now create an item.
1218
1219         $body = diaspora2bb($text);
1220
1221         $message_id = $diaspora_handle . ':' . $guid;
1222
1223         $datarray = array();
1224
1225         $str_tags = '';
1226
1227         $tags = get_tags($body);
1228
1229         if(count($tags)) {
1230                 foreach($tags as $tag) {
1231                         if(strpos($tag,'#') === 0) {
1232                                 if(strpos($tag,'[url='))
1233                                         continue;
1234                                 $basetag = str_replace('_',' ',substr($tag,1));
1235                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
1236                                 if(strlen($str_tags))
1237                                         $str_tags .= ',';
1238                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1239                                 continue;
1240                         }
1241                 }
1242         }
1243
1244 */
1245
1246         return;
1247 }
1248
1249
1250
1251
1252
1253
1254 function diaspora_photo($importer,$xml,$msg) {
1255
1256         $a = get_app();
1257         $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1258
1259         $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1260
1261         $status_message_guid = notags(unxmlify($xml->status_message_guid));
1262
1263         $guid = notags(unxmlify($xml->guid));
1264
1265         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1266
1267         $public = notags(unxmlify($xml->public));
1268
1269         $created_at = notags(unxmlify($xml_created_at));
1270
1271
1272         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1273         if(! $contact)
1274                 return;
1275
1276         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
1277                 logger('diaspora_photo: Ignoring this author.');
1278                 return 202;
1279         }
1280
1281         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1282                 intval($importer['uid']),
1283                 dbesc($status_message_guid)
1284         );
1285         if(! count($r)) {
1286                 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1287                 return;
1288         }
1289         $parent_item = $r[0];
1290
1291         $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1292
1293         $link_text = scale_diaspora_images($link_text);
1294
1295         if(strpos($parent_item['body'],$link_text) === false) {
1296                 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d limit 1",
1297                         dbesc($link_text . $parent_item['body']),
1298                         intval($parent_item['id']),
1299                         intval($parent_item['uid'])
1300                 );
1301         }
1302
1303         return;
1304 }
1305
1306
1307
1308
1309 function diaspora_like($importer,$xml,$msg) {
1310
1311         $a = get_app();
1312         $guid = notags(unxmlify($xml->guid));
1313         $parent_guid = notags(unxmlify($xml->parent_guid));
1314         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1315         $target_type = notags(unxmlify($xml->target_type));
1316         $positive = notags(unxmlify($xml->positive));
1317         $author_signature = notags(unxmlify($xml->author_signature));
1318
1319         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1320
1321         // likes on comments not supported here and likes on photos not supported by Diaspora
1322
1323         if($target_type !== 'Post')
1324                 return;
1325
1326         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1327         if(! $contact) {
1328                 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1329                 return;
1330         }
1331
1332         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
1333                 logger('diaspora_like: Ignoring this author.');
1334                 return 202;
1335         }
1336
1337         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1338                 intval($importer['uid']),
1339                 dbesc($parent_guid)
1340         );
1341         if(! count($r)) {
1342                 logger('diaspora_like: parent item not found: ' . $guid);
1343                 return;
1344         }
1345
1346         $parent_item = $r[0];
1347
1348         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1349                 intval($importer['uid']),
1350                 dbesc($guid)
1351         );
1352         if(count($r)) {
1353                 if($positive === 'true') {
1354                         logger('diaspora_like: duplicate like: ' . $guid);
1355                         return;
1356                 } 
1357                 if($positive === 'false') {
1358                         q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
1359                                 intval($r[0]['id']),
1360                                 intval($importer['uid'])
1361                         );
1362                         // FIXME
1363                         //  send notification via proc_run()
1364                         return;
1365                 }
1366         }
1367         if($positive === 'false') {
1368                 logger('diaspora_like: unlike received with no corresponding like');
1369                 return; 
1370         }
1371
1372         $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1373
1374         $author_signature = base64_decode($author_signature);
1375
1376         if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1377                 $person = $contact;
1378                 $key = $msg['key'];
1379         }
1380         else {
1381                 $person = find_diaspora_person_by_handle($diaspora_handle);     
1382                 if(is_array($person) && x($person,'pubkey'))
1383                         $key = $person['pubkey'];
1384                 else {
1385                         logger('diaspora_like: unable to find author details');
1386                         return;
1387                 }
1388         }
1389
1390         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1391                 logger('diaspora_like: verification failed.');
1392                 return;
1393         }
1394
1395         if($parent_author_signature) {
1396
1397                 $owner_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1398
1399                 $parent_author_signature = base64_decode($parent_author_signature);
1400
1401                 $key = $msg['key'];
1402
1403                 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1404                         logger('diaspora_like: owner verification failed.');
1405                         return;
1406                 }
1407         }
1408
1409         // Phew! Everything checks out. Now create an item.
1410
1411         $uri = $diaspora_handle . ':' . $guid;
1412
1413         $activity = ACTIVITY_LIKE;
1414         $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
1415         $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE ); 
1416         $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
1417         $body = $parent_item['body'];
1418
1419         $obj = <<< EOT
1420
1421         <object>
1422                 <type>$objtype</type>
1423                 <local>1</local>
1424                 <id>{$parent_item['uri']}</id>
1425                 <link>$link</link>
1426                 <title></title>
1427                 <content>$body</content>
1428         </object>
1429 EOT;
1430         $bodyverb = t('%1$s likes %2$s\'s %3$s');
1431
1432         $arr = array();
1433
1434         $arr['uri'] = $uri;
1435         $arr['uid'] = $importer['uid'];
1436         $arr['guid'] = $guid;
1437         $arr['contact-id'] = $contact['id'];
1438         $arr['type'] = 'activity';
1439         $arr['wall'] = $parent_item['wall'];
1440         $arr['gravity'] = GRAVITY_LIKE;
1441         $arr['parent'] = $parent_item['id'];
1442         $arr['parent-uri'] = $parent_item['uri'];
1443
1444         $arr['owner-name'] = $parent_item['name'];
1445         $arr['owner-link'] = $parent_item['url'];
1446         $arr['owner-avatar'] = $parent_item['thumb'];
1447
1448         $arr['author-name'] = $person['name'];
1449         $arr['author-link'] = $person['url'];
1450         $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1451         
1452         $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1453         $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1454         $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1455         $arr['body'] =  sprintf( $bodyverb, $ulink, $alink, $plink );
1456
1457         $arr['app']  = 'Diaspora';
1458
1459         $arr['private'] = $parent_item['private'];
1460         $arr['verb'] = $activity;
1461         $arr['object-type'] = $objtype;
1462         $arr['object'] = $obj;
1463         $arr['visible'] = 1;
1464         $arr['unseen'] = 1;
1465         $arr['last-child'] = 0;
1466
1467         $message_id = item_store($arr);
1468
1469
1470         if($message_id) {
1471                 q("update item set plink = '%s' where id = %d limit 1",
1472                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1473                         intval($message_id)
1474                 );
1475         }
1476
1477         if(! $parent_author_signature) {
1478                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1479                         intval($message_id),
1480                         dbesc($author_signed_data),
1481                         dbesc(base64_encode($author_signature)),
1482                         dbesc($diaspora_handle)
1483                 );
1484         }
1485
1486         // if the message isn't already being relayed, notify others
1487         // the existence of parent_author_signature means the parent_author or owner
1488         // is already relaying. The parent_item['origin'] indicates the message was created on our system
1489
1490         if(($parent_item['origin']) && (! $parent_author_signature))
1491                 proc_run('php','include/notifier.php','comment',$message_id);
1492
1493         return;
1494 }
1495
1496 function diaspora_retraction($importer,$xml) {
1497
1498         $guid = notags(unxmlify($xml->guid));
1499         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1500         $type = notags(unxmlify($xml->type));
1501
1502         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1503         if(! $contact)
1504                 return;
1505
1506         if($type === 'Person') {
1507                 require_once('include/Contact.php');
1508                 contact_remove($contact['id']);
1509         }
1510         elseif($type === 'Post') {
1511                 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1512                         dbesc('guid'),
1513                         intval($importer['uid'])
1514                 );
1515                 if(count($r)) {
1516                         if(link_compare($r[0]['author-link'],$contact['url'])) {
1517                                 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1518                                         dbesc(datetime_convert()),                      
1519                                         intval($r[0]['id'])
1520                                 );
1521                         }
1522                 }
1523         }
1524
1525         return 202;
1526         // NOTREACHED
1527 }
1528
1529 function diaspora_signed_retraction($importer,$xml) {
1530
1531         $guid = notags(unxmlify($xml->target_guid));
1532         $diaspora_handle = notags(unxmlify($xml->sender_handle));
1533         $type = notags(unxmlify($xml->target_type));
1534         $sig = notags(unxmlify($xml->target_author_signature));
1535
1536         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1537         if(! $contact)
1538                 return;
1539
1540         // this may not yet work for comments. Need to see how the relaying works
1541         // and figure out who signs it.
1542
1543
1544         $signed_data = $guid . ';' . $type ;
1545
1546         $sig = base64_decode($sig);
1547
1548         $key = $msg['key'];
1549
1550         if(! rsa_verify($signed_data,$sig,$key,'sha256')) {
1551                 logger('diaspora_signed_retraction: owner verification failed.' . print_r($msg,true));
1552                 return;
1553         }
1554
1555         if($type === 'StatusMessage') {
1556                 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1557                         dbesc('guid'),
1558                         intval($importer['uid'])
1559                 );
1560                 if(count($r)) {
1561                         if(link_compare($r[0]['author-link'],$contact['url'])) {
1562                                 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1563                                         dbesc(datetime_convert()),                      
1564                                         intval($r[0]['id'])
1565                                 );
1566                         }
1567                 }
1568         }
1569
1570         return 202;
1571         // NOTREACHED
1572 }
1573
1574 function diaspora_profile($importer,$xml) {
1575
1576         $a = get_app();
1577         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1578
1579         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1580         if(! $contact)
1581                 return;
1582
1583         if($contact['blocked']) {
1584                 logger('diaspora_post: Ignoring this author.');
1585                 return 202;
1586         }
1587
1588         $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
1589         $image_url = unxmlify($xml->image_url);
1590         $birthday = unxmlify($xml->birthday);
1591
1592         $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE  `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
1593                 intval($importer['uid']),
1594                 intval($contact['id'])
1595         );
1596         $oldphotos = ((count($r)) ? $r : null);
1597
1598         require_once('include/Photo.php');
1599
1600         $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
1601         
1602         // Generic birthday. We don't know the timezone. The year is irrelevant. 
1603
1604         $birthday = str_replace('1000','1901',$birthday);
1605
1606         $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
1607
1608         $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",
1609                 dbesc($name),
1610                 dbesc(datetime_convert()),
1611                 dbesc($images[0]),
1612                 dbesc($images[1]),
1613                 dbesc($images[2]),
1614                 dbesc(datetime_convert()),
1615                 dbesc($birthday),
1616                 intval($contact['id']),
1617                 intval($importer['uid'])
1618         ); 
1619
1620         if($r) {
1621                 if($oldphotos) {
1622                         foreach($oldphotos as $ph) {
1623                                 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
1624                                         intval($importer['uid']),
1625                                         intval($contact['id']),
1626                                         dbesc($ph['resource-id'])
1627                                 );
1628                         }
1629                 }
1630         }       
1631
1632         return;
1633
1634 }
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657 function diaspora_share($me,$contact) {
1658         $a = get_app();
1659         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1660         $theiraddr = $contact['addr'];
1661
1662         $tpl = get_markup_template('diaspora_share.tpl');
1663         $msg = replace_macros($tpl, array(
1664                 '$sender' => $myaddr,
1665                 '$recipient' => $theiraddr
1666         ));
1667
1668         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1669
1670         return(diaspora_transmit($owner,$contact,$slap, false));
1671 }
1672
1673 function diaspora_unshare($me,$contact) {
1674
1675         $a = get_app();
1676         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1677
1678         $tpl = get_markup_template('diaspora_retract.tpl');
1679         $msg = replace_macros($tpl, array(
1680                 '$guid'   => $me['guid'],
1681                 '$type'   => 'Person',
1682                 '$handle' => $myaddr
1683         ));
1684
1685         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1686
1687         return(diaspora_transmit($owner,$contact,$slap, false));
1688
1689 }
1690
1691
1692
1693 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
1694
1695         $a = get_app();
1696         $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1697         $theiraddr = $contact['addr'];
1698
1699         $images = array();
1700
1701         $body = $item['body'];
1702
1703 /*
1704         // We're trying to match Diaspora's split message/photo protocol but
1705         // all the photos are displayed on D* as links and not img's - even
1706         // though we're sending pretty much precisely what they send us when
1707         // doing the same operation.  
1708         // Commented out for now, we'll use bb2diaspora to convert photos to markdown
1709         // which seems to get through intact.
1710
1711         $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
1712         if($cnt) {
1713                 foreach($matches as $mtch) {
1714                         $detail = array();
1715                         $detail['str'] = $mtch[0];
1716                         $detail['path'] = dirname($mtch[1]) . '/';
1717                         $detail['file'] = basename($mtch[1]);
1718                         $detail['guid'] = $item['guid'];
1719                         $detail['handle'] = $myaddr;
1720                         $images[] = $detail;
1721                         $body = str_replace($detail['str'],$mtch[1],$body);
1722                 }
1723         }       
1724 */
1725
1726         $body = xmlify(html_entity_decode(bb2diaspora($body)));
1727
1728         if($item['attach']) {
1729                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
1730                 if(cnt) {
1731                         $body .= "\n" . t('Attachments:') . "\n";
1732                         foreach($matches as $mtch) {
1733                                 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
1734                         }
1735                 }
1736         }       
1737
1738
1739         $public = (($item['private']) ? 'false' : 'true');
1740
1741         require_once('include/datetime.php');
1742         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
1743
1744         $tpl = get_markup_template('diaspora_post.tpl');
1745         $msg = replace_macros($tpl, array(
1746                 '$body' => $body,
1747                 '$guid' => $item['guid'],
1748                 '$handle' => xmlify($myaddr),
1749                 '$public' => $public,
1750                 '$created' => $created
1751         ));
1752
1753         logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
1754
1755         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1756
1757         $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
1758
1759         if(count($images)) {
1760                 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
1761         }
1762
1763         return $return_code;
1764 }
1765
1766
1767 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
1768         $a = get_app();
1769         if(! count($images))
1770                 return;
1771         $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
1772
1773         $tpl = get_markup_template('diaspora_photo.tpl');
1774         foreach($images as $image) {
1775                 if(! stristr($image['path'],$mysite))
1776                         continue;
1777                 $resource = str_replace('.jpg','',$image['file']);
1778                 $resource = substr($resource,0,strpos($resource,'-'));
1779
1780                 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
1781                         dbesc($resource),
1782                         intval($owner['uid'])
1783                 );
1784                 if(! count($r))
1785                         continue;
1786                 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
1787                 $msg = replace_macros($tpl,array(               
1788                         '$path' => xmlify($image['path']),
1789                         '$filename' => xmlify($image['file']),
1790                         '$msg_guid' => xmlify($image['guid']),
1791                         '$guid' => xmlify($r[0]['guid']),
1792                         '$handle' => xmlify($image['handle']),
1793                         '$public' => xmlify($public),
1794                         '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
1795                 ));
1796
1797
1798                 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
1799                 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1800
1801                 diaspora_transmit($owner,$contact,$slap,$public_batch);
1802         }
1803
1804 }
1805
1806 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
1807
1808         $a = get_app();
1809         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1810         $theiraddr = $contact['addr'];
1811
1812         $p = q("select guid from item where parent = %d limit 1",
1813                 $item['parent']
1814         );
1815         if(count($p))
1816                 $parent_guid = $p[0]['guid'];
1817         else
1818                 return;
1819
1820         if($item['verb'] === ACTIVITY_LIKE) {
1821                 $tpl = get_markup_template('diaspora_like.tpl');
1822                 $like = true;
1823                 $target_type = 'Post';
1824                 $positive = (($item['deleted']) ? 'false' : 'true');
1825         }
1826         else {
1827                 $tpl = get_markup_template('diaspora_comment.tpl');
1828                 $like = false;
1829         }
1830
1831         $text = html_entity_decode(bb2diaspora($item['body']));
1832
1833         // sign it
1834
1835         if($like)
1836                 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1837         else
1838                 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1839
1840         $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1841
1842         $msg = replace_macros($tpl,array(
1843                 '$guid' => xmlify($item['guid']),
1844                 '$parent_guid' => xmlify($parent_guid),
1845                 '$target_type' =>xmlify($target_type),
1846                 '$authorsig' => xmlify($authorsig),
1847                 '$body' => xmlify($text),
1848                 '$positive' => xmlify($positive),
1849                 '$handle' => xmlify($myaddr)
1850         ));
1851
1852         logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
1853
1854         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1855
1856         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1857 }
1858
1859
1860 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
1861
1862
1863         $a = get_app();
1864         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1865         $theiraddr = $contact['addr'];
1866
1867
1868         $p = q("select guid from item where parent = %d limit 1",
1869                 $item['parent']
1870         );
1871         if(count($p))
1872                 $parent_guid = $p[0]['guid'];
1873         else
1874                 return;
1875
1876         if($item['verb'] === ACTIVITY_LIKE) {
1877                 $tpl = get_markup_template('diaspora_like_relay.tpl');
1878                 $like = true;
1879                 $target_type = 'Post';
1880                 $positive = (($item['deleted']) ? 'false' : 'true');
1881         }
1882         else {
1883                 $tpl = get_markup_template('diaspora_comment_relay.tpl');
1884                 $like = false;
1885         }
1886
1887         $body = $item['body'];
1888
1889         $text = html_entity_decode(bb2diaspora($body));
1890
1891         // fetch the original signature if somebody sent the post to us to relay
1892         // If we are relaying for a reply originating on our own account, there wasn't a 'send to relay'
1893         // action. It wasn't needed. In that case create the original signature and the 
1894         // owner (parent author) signature
1895         // comments from other networks will be relayed under our name, with a brief 
1896         // preamble to describe what's happening and noting the real author
1897
1898         $r = q("select * from sign where iid = %d limit 1",
1899                 intval($item['id'])
1900         );
1901         if(count($r)) { 
1902                 $orig_sign = $r[0];
1903                 $signed_text = $orig_sign['signed_text'];
1904                 $authorsig = $orig_sign['signature'];
1905                 $handle = $orig_sign['signer'];
1906         }
1907         else {
1908
1909                 $itemcontact = q("select * from contact where `id` = %d limit 1",
1910                         intval($item['contact-id'])
1911                 );
1912                 if(count($itemcontact)) {
1913                         if(! $itemcontact[0]['self']) {
1914                                 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
1915                                         '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',  
1916                                         network_to_name($itemcontact['network'])) . "\n";
1917                                 $body = $prefix . $body;
1918                         }
1919                 }
1920                 else {
1921
1922                         if($like)
1923                                 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1924                         else
1925                                 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1926
1927                         $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1928
1929                         q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1930                                 intval($item['id']),
1931                                 dbesc($signed_text),
1932                                 dbesc(base64_encode($authorsig)),
1933                                 dbesc($myaddr)
1934                         );
1935                         $handle = $myaddr;
1936                 }
1937         }
1938
1939         // sign it
1940
1941         $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1942
1943         $msg = replace_macros($tpl,array(
1944                 '$guid' => xmlify($item['guid']),
1945                 '$parent_guid' => xmlify($parent_guid),
1946                 '$target_type' =>xmlify($target_type),
1947                 '$authorsig' => xmlify($orig_sign['signature']),
1948                 '$parentsig' => xmlify($parentauthorsig),
1949                 '$body' => xmlify($text),
1950                 '$positive' => xmlify($positive),
1951                 '$handle' => xmlify($handle)
1952         ));
1953
1954         logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
1955
1956         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1957
1958         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1959
1960 }
1961
1962
1963
1964 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
1965
1966         $a = get_app();
1967         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1968
1969         $signed_text = $item['guid'] . ';' . 'StatusMessage';
1970
1971         $tpl = get_markup_template('diaspora_signed_retract.tpl');
1972         $msg = replace_macros($tpl, array(
1973                 '$guid'   => $item['guid'],
1974                 '$type'   => 'StatusMessage',
1975                 '$handle' => $myaddr,
1976                 '$signature' => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'))
1977         ));
1978
1979         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1980
1981         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1982 }
1983
1984
1985
1986 function diaspora_transmit($owner,$contact,$slap,$public_batch) {
1987
1988         $a = get_app();
1989         $logid = random_string(4);
1990         $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
1991         if(! $dest_url) {
1992                 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
1993                 return 0;
1994         } 
1995
1996         logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
1997
1998         post_url($dest_url . '/', $slap);
1999
2000         $return_code = $a->get_curl_code();
2001         logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
2002
2003         if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
2004                 logger('diaspora_transmit: queue message');
2005
2006                 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
2007                         intval($contact['id']),
2008                         dbesc(NETWORK_DIASPORA),
2009                         dbesc($slap),
2010                         intval($public_batch)
2011                 );
2012                 if(count($r)) {
2013                         logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
2014                 }
2015                 else {
2016                         // queue message for redelivery
2017                         add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
2018                 }
2019         }
2020
2021
2022         return(($return_code) ? $return_code : (-1));
2023 }