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