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