]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
ignore suggestions
[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`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
455                 VALUES ( %d, '%s', '%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(normalise_link($ret['url'])),
462                 dbesc($batch),
463                 dbesc($ret['name']),
464                 dbesc($ret['nick']),
465                 dbesc($ret['photo']),
466                 dbesc($ret['pubkey']),
467                 dbesc($ret['notify']),
468                 dbesc($ret['poll']),
469                 1,
470                 2
471         );
472                  
473         // find the contact record we just created
474
475         $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
476
477         $hash = random_string() . (string) time();   // Generate a confirm_key
478         
479         if($contact_record) {
480                 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
481                         VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
482                         intval($importer['uid']),
483                         intval($contact_record['id']),
484                         0,
485                         0,
486                         dbesc( t('Sharing notification from Diaspora network')),
487                         dbesc($hash),
488                         dbesc(datetime_convert())
489                 );
490         }
491
492         return;
493 }
494
495 function diaspora_post($importer,$xml) {
496
497         $a = get_app();
498         $guid = notags(unxmlify($xml->guid));
499         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
500
501         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
502         if(! $contact)
503                 return;
504
505         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
506                 logger('diaspora_post: Ignoring this author.');
507                 return 202;
508         }
509
510         $message_id = $diaspora_handle . ':' . $guid;
511         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
512                 intval($importer['uid']),
513                 dbesc($message_id),
514                 dbesc($guid)
515         );
516         if(count($r)) {
517                 logger('diaspora_post: message exists: ' . $guid);
518                 return;
519         }
520
521     // allocate a guid on our system - we aren't fixing any collisions.
522         // we're ignoring them
523
524         $g = q("select * from guid where guid = '%s' limit 1",
525                 dbesc($guid)
526         );
527         if(! count($g)) {
528                 q("insert into guid ( guid ) values ( '%s' )",
529                         dbesc($guid)
530                 );
531         }
532
533         $created = unxmlify($xml->created_at);
534         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
535
536         $body = diaspora2bb($xml->raw_message);
537
538         $datarray = array();
539
540         $str_tags = '';
541
542         $tags = get_tags($body);
543
544         if(count($tags)) {
545                 foreach($tags as $tag) {
546                         if(strpos($tag,'#') === 0) {
547                                 if(strpos($tag,'[url='))
548                                         continue;
549                                 $basetag = str_replace('_',' ',substr($tag,1));
550                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
551                                 if(strlen($str_tags))
552                                         $str_tags .= ',';
553                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
554                                 continue;
555                         }
556                 }
557         }
558         
559         $datarray['uid'] = $importer['uid'];
560         $datarray['contact-id'] = $contact['id'];
561         $datarray['wall'] = 0;
562         $datarray['guid'] = $guid;
563         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
564         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
565         $datarray['private'] = $private;
566         $datarray['parent'] = 0;
567         $datarray['owner-name'] = $contact['name'];
568         $datarray['owner-link'] = $contact['url'];
569         $datarray['owner-avatar'] = $contact['thumb'];
570         $datarray['author-name'] = $contact['name'];
571         $datarray['author-link'] = $contact['url'];
572         $datarray['author-avatar'] = $contact['thumb'];
573         $datarray['body'] = $body;
574         $datarray['tag'] = $str_tags;
575         $datarray['app']  = 'Diaspora';
576
577         // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
578
579         $datarray['visible'] = ((strlen($body)) ? 1 : 0);
580
581         $message_id = item_store($datarray);
582
583         if($message_id) {
584                 q("update item set plink = '%s' where id = %d limit 1",
585                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
586                         intval($message_id)
587                 );
588         }
589
590         return;
591
592 }
593
594 function diaspora_reshare($importer,$xml) {
595
596         logger('diaspora_reshare: init: ' . print_r($xml,true));
597
598         $a = get_app();
599         $guid = notags(unxmlify($xml->guid));
600         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
601
602
603         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
604         if(! $contact)
605                 return;
606
607         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
608                 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
609                 return 202;
610         }
611
612         $message_id = $diaspora_handle . ':' . $guid;
613         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
614                 intval($importer['uid']),
615                 dbesc($message_id),
616                 dbesc($guid)
617         );
618         if(count($r)) {
619                 logger('diaspora_reshare: message exists: ' . $guid);
620                 return;
621         }
622
623         $orig_author = notags(unxmlify($xml->root_diaspora_id));
624         $orig_guid = notags(unxmlify($xml->root_guid));
625
626         $source_url = 'https://' . substr($orig_author,strpos($orig_author,'@')+1) . '/p/' . $orig_guid . '.xml';
627         $x = fetch_url($source_url);
628         if(! $x)
629                 $x = fetch_url(str_replace('https://','http://',$source_url));
630         if(! $x) {
631                 logger('diaspora_reshare: unable to fetch source url ' . $source_url);
632                 return;
633         }
634         logger('diaspora_reshare: source: ' . $x);
635
636         $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
637         $source_xml = parse_xml_string($x,false);
638
639         if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
640                 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
641                 $body = scale_diaspora_images($body,false);
642         }
643         elseif($source_xml->post->asphoto->image_url) {
644                 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
645                 $body = scale_diaspora_images($body);
646         }
647         elseif($source_xml->post->status_message) {
648                 $body = diaspora2bb($source_xml->post->status_message->raw_message);
649                 $body = scale_diaspora_images($body);
650
651         }
652         else {
653                 logger('diaspora_reshare: no reshare content found: ' . print_r($source_xml,true));
654                 return;
655         }
656         if(! $body) {
657                 logger('diaspora_reshare: empty body: source= ' . $x);
658                 return;
659         }
660
661         $person = find_diaspora_person_by_handle($orig_author);
662
663         if(is_array($person) && x($person,'name') && x($person,'url'))
664                 $details = '[url=' . $person['url'] . ']' . $person['name'] . '[/url]';
665         else
666                 $details = $orig_author;
667         
668         $prefix = '&#x2672; ' . $details . "\n"; 
669
670
671     // allocate a guid on our system - we aren't fixing any collisions.
672         // we're ignoring them
673
674         $g = q("select * from guid where guid = '%s' limit 1",
675                 dbesc($guid)
676         );
677         if(! count($g)) {
678                 q("insert into guid ( guid ) values ( '%s' )",
679                         dbesc($guid)
680                 );
681         }
682
683         $created = unxmlify($xml->created_at);
684         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
685
686         $datarray = array();
687
688         $str_tags = '';
689
690         $tags = get_tags($body);
691
692         if(count($tags)) {
693                 foreach($tags as $tag) {
694                         if(strpos($tag,'#') === 0) {
695                                 if(strpos($tag,'[url='))
696                                         continue;
697                                 $basetag = str_replace('_',' ',substr($tag,1));
698                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
699                                 if(strlen($str_tags))
700                                         $str_tags .= ',';
701                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
702                                 continue;
703                         }
704                 }
705         }
706         
707         $datarray['uid'] = $importer['uid'];
708         $datarray['contact-id'] = $contact['id'];
709         $datarray['wall'] = 0;
710         $datarray['guid'] = $guid;
711         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
712         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
713         $datarray['private'] = $private;
714         $datarray['parent'] = 0;
715         $datarray['owner-name'] = $contact['name'];
716         $datarray['owner-link'] = $contact['url'];
717         $datarray['owner-avatar'] = $contact['thumb'];
718         $datarray['author-name'] = $contact['name'];
719         $datarray['author-link'] = $contact['url'];
720         $datarray['author-avatar'] = $contact['thumb'];
721         $datarray['body'] = $prefix . $body;
722         $datarray['tag'] = $str_tags;
723         $datarray['app']  = 'Diaspora';
724
725         $message_id = item_store($datarray);
726
727         if($message_id) {
728                 q("update item set plink = '%s' where id = %d limit 1",
729                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
730                         intval($message_id)
731                 );
732         }
733
734         return;
735
736 }
737
738
739 function diaspora_asphoto($importer,$xml) {
740         logger('diaspora_asphoto called');
741
742         $a = get_app();
743         $guid = notags(unxmlify($xml->guid));
744         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
745
746         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
747         if(! $contact)
748                 return;
749
750         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
751                 logger('diaspora_asphoto: Ignoring this author.');
752                 return 202;
753         }
754
755         $message_id = $diaspora_handle . ':' . $guid;
756         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
757                 intval($importer['uid']),
758                 dbesc($message_id),
759                 dbesc($guid)
760         );
761         if(count($r)) {
762                 logger('diaspora_asphoto: message exists: ' . $guid);
763                 return;
764         }
765
766     // allocate a guid on our system - we aren't fixing any collisions.
767         // we're ignoring them
768
769         $g = q("select * from guid where guid = '%s' limit 1",
770                 dbesc($guid)
771         );
772         if(! count($g)) {
773                 q("insert into guid ( guid ) values ( '%s' )",
774                         dbesc($guid)
775                 );
776         }
777
778         $created = unxmlify($xml->created_at);
779         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
780
781         if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
782                 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
783                 $body = scale_diaspora_images($body,false);
784         }
785         elseif($xml->image_url) {
786                 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
787                 $body = scale_diaspora_images($body);
788         }
789         else {
790                 logger('diaspora_asphoto: no photo url found.');
791                 return;
792         }
793
794         $datarray = array();
795
796         
797         $datarray['uid'] = $importer['uid'];
798         $datarray['contact-id'] = $contact['id'];
799         $datarray['wall'] = 0;
800         $datarray['guid'] = $guid;
801         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
802         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
803         $datarray['private'] = $private;
804         $datarray['parent'] = 0;
805         $datarray['owner-name'] = $contact['name'];
806         $datarray['owner-link'] = $contact['url'];
807         $datarray['owner-avatar'] = $contact['thumb'];
808         $datarray['author-name'] = $contact['name'];
809         $datarray['author-link'] = $contact['url'];
810         $datarray['author-avatar'] = $contact['thumb'];
811         $datarray['body'] = $body;
812         
813         $datarray['app']  = 'Diaspora/Cubbi.es';
814
815         $message_id = item_store($datarray);
816
817         if($message_id) {
818                 q("update item set plink = '%s' where id = %d limit 1",
819                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
820                         intval($message_id)
821                 );
822         }
823
824         return;
825
826 }
827
828
829
830
831
832
833 function diaspora_comment($importer,$xml,$msg) {
834
835         $a = get_app();
836         $guid = notags(unxmlify($xml->guid));
837         $parent_guid = notags(unxmlify($xml->parent_guid));
838         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
839         $target_type = notags(unxmlify($xml->target_type));
840         $text = unxmlify($xml->text);
841         $author_signature = notags(unxmlify($xml->author_signature));
842
843         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
844
845         $text = $xml->text;
846
847         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
848         if(! $contact) {
849                 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
850                 return;
851         }
852
853         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
854                 logger('diaspora_comment: Ignoring this author.');
855                 return 202;
856         }
857
858         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
859                 intval($importer['uid']),
860                 dbesc($guid)
861         );
862         if(count($r)) {
863                 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
864                 return;
865         }
866
867         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
868                 intval($importer['uid']),
869                 dbesc($parent_guid)
870         );
871         if(! count($r)) {
872                 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
873                 return;
874         }
875         $parent_item = $r[0];
876
877         $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
878
879         $author_signature = base64_decode($author_signature);
880
881         if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
882                 $person = $contact;
883                 $key = $msg['key'];
884         }
885         else {
886                 $person = find_diaspora_person_by_handle($diaspora_handle);     
887
888                 if(is_array($person) && x($person,'pubkey'))
889                         $key = $person['pubkey'];
890                 else {
891                         logger('diaspora_comment: unable to find author details');
892                         return;
893                 }
894         }
895
896         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
897                 logger('diaspora_comment: verification failed.');
898                 return;
899         }
900
901         if($parent_author_signature) {
902                 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
903
904                 $parent_author_signature = base64_decode($parent_author_signature);
905
906                 $key = $msg['key'];
907
908                 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
909                         logger('diaspora_comment: owner verification failed.');
910                         return;
911                 }
912         }
913
914         // Phew! Everything checks out. Now create an item.
915
916         $body = diaspora2bb($text);
917
918         $message_id = $diaspora_handle . ':' . $guid;
919
920         $datarray = array();
921
922         $str_tags = '';
923
924         $tags = get_tags($body);
925
926         if(count($tags)) {
927                 foreach($tags as $tag) {
928                         if(strpos($tag,'#') === 0) {
929                                 if(strpos($tag,'[url='))
930                                         continue;
931                                 $basetag = str_replace('_',' ',substr($tag,1));
932                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
933                                 if(strlen($str_tags))
934                                         $str_tags .= ',';
935                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
936                                 continue;
937                         }
938                 }
939         }
940
941         $datarray['uid'] = $importer['uid'];
942         $datarray['contact-id'] = $contact['id'];
943         $datarray['wall'] = $parent_item['wall'];
944         $datarray['gravity'] = GRAVITY_COMMENT;
945         $datarray['guid'] = $guid;
946         $datarray['uri'] = $message_id;
947         $datarray['parent-uri'] = $parent_item['uri'];
948
949         // No timestamps for comments? OK, we'll the use current time.
950         $datarray['created'] = $datarray['edited'] = datetime_convert();
951         $datarray['private'] = $parent_item['private'];
952
953         $datarray['owner-name'] = $parent_item['owner-name'];
954         $datarray['owner-link'] = $parent_item['owner-link'];
955         $datarray['owner-avatar'] = $parent_item['owner-avatar'];
956
957         $datarray['author-name'] = $person['name'];
958         $datarray['author-link'] = $person['url'];
959         $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
960         $datarray['body'] = $body;
961         $datarray['tag'] = $str_tags;
962
963         // We can't be certain what the original app is if the message is relayed.
964         if(($parent_item['origin']) && (! $parent_author_signature)) 
965                 $datarray['app']  = 'Diaspora';
966
967         $message_id = item_store($datarray);
968
969         if($message_id) {
970                 q("update item set plink = '%s' where id = %d limit 1",
971                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
972                         intval($message_id)
973                 );
974         }
975
976         if(($parent_item['origin']) && (! $parent_author_signature)) {
977                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
978                         intval($message_id),
979                         dbesc($author_signed_data),
980                         dbesc(base64_encode($author_signature)),
981                         dbesc($diaspora_handle)
982                 );
983
984                 // if the message isn't already being relayed, notify others
985                 // the existence of parent_author_signature means the parent_author or owner
986                 // is already relaying.
987
988                 proc_run('php','include/notifier.php','comment',$message_id);
989         }
990         return;
991 }
992
993 function diaspora_photo($importer,$xml,$msg) {
994
995         $a = get_app();
996         $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
997
998         $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
999
1000         $status_message_guid = notags(unxmlify($xml->status_message_guid));
1001
1002         $guid = notags(unxmlify($xml->guid));
1003
1004         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1005
1006         $public = notags(unxmlify($xml->public));
1007
1008         $created_at = notags(unxmlify($xml_created_at));
1009
1010
1011         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1012         if(! $contact)
1013                 return;
1014
1015         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
1016                 logger('diaspora_photo: Ignoring this author.');
1017                 return 202;
1018         }
1019
1020         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1021                 intval($importer['uid']),
1022                 dbesc($status_message_guid)
1023         );
1024         if(! count($r)) {
1025                 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1026                 return;
1027         }
1028         $parent_item = $r[0];
1029
1030         $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1031
1032         $link_text = scale_diaspora_images($link_text);
1033
1034         if(strpos($parent_item['body'],$link_text) === false) {
1035                 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d limit 1",
1036                         dbesc($link_text . $parent_item['body']),
1037                         intval($parent_item['id']),
1038                         intval($parent_item['uid'])
1039                 );
1040         }
1041
1042         return;
1043 }
1044
1045
1046
1047
1048 function diaspora_like($importer,$xml,$msg) {
1049
1050         $a = get_app();
1051         $guid = notags(unxmlify($xml->guid));
1052         $parent_guid = notags(unxmlify($xml->parent_guid));
1053         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1054         $target_type = notags(unxmlify($xml->target_type));
1055         $positive = notags(unxmlify($xml->positive));
1056         $author_signature = notags(unxmlify($xml->author_signature));
1057
1058         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1059
1060         // likes on comments not supported here and likes on photos not supported by Diaspora
1061
1062         if($target_type !== 'Post')
1063                 return;
1064
1065         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1066         if(! $contact) {
1067                 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1068                 return;
1069         }
1070
1071         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
1072                 logger('diaspora_like: Ignoring this author.');
1073                 return 202;
1074         }
1075
1076         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1077                 intval($importer['uid']),
1078                 dbesc($parent_guid)
1079         );
1080         if(! count($r)) {
1081                 logger('diaspora_like: parent item not found: ' . $guid);
1082                 return;
1083         }
1084
1085         $parent_item = $r[0];
1086
1087         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1088                 intval($importer['uid']),
1089                 dbesc($guid)
1090         );
1091         if(count($r)) {
1092                 if($positive === 'true') {
1093                         logger('diaspora_like: duplicate like: ' . $guid);
1094                         return;
1095                 } 
1096                 if($positive === 'false') {
1097                         q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
1098                                 intval($r[0]['id']),
1099                                 intval($importer['uid'])
1100                         );
1101                         // FIXME
1102                         //  send notification via proc_run()
1103                         return;
1104                 }
1105         }
1106         if($positive === 'false') {
1107                 logger('diaspora_like: unlike received with no corresponding like');
1108                 return; 
1109         }
1110
1111         $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1112
1113         $author_signature = base64_decode($author_signature);
1114
1115         if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1116                 $person = $contact;
1117                 $key = $msg['key'];
1118         }
1119         else {
1120                 $person = find_diaspora_person_by_handle($diaspora_handle);     
1121                 if(is_array($person) && x($person,'pubkey'))
1122                         $key = $person['pubkey'];
1123                 else {
1124                         logger('diaspora_like: unable to find author details');
1125                         return;
1126                 }
1127         }
1128
1129         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1130                 logger('diaspora_like: verification failed.');
1131                 return;
1132         }
1133
1134         if($parent_author_signature) {
1135
1136                 $owner_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1137
1138                 $parent_author_signature = base64_decode($parent_author_signature);
1139
1140                 $key = $msg['key'];
1141
1142                 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1143                         logger('diaspora_like: owner verification failed.');
1144                         return;
1145                 }
1146         }
1147
1148         // Phew! Everything checks out. Now create an item.
1149
1150         $uri = $diaspora_handle . ':' . $guid;
1151
1152         $activity = ACTIVITY_LIKE;
1153         $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
1154         $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE ); 
1155         $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
1156         $body = $parent_item['body'];
1157
1158         $obj = <<< EOT
1159
1160         <object>
1161                 <type>$objtype</type>
1162                 <local>1</local>
1163                 <id>{$parent_item['uri']}</id>
1164                 <link>$link</link>
1165                 <title></title>
1166                 <content>$body</content>
1167         </object>
1168 EOT;
1169         $bodyverb = t('%1$s likes %2$s\'s %3$s');
1170
1171         $arr = array();
1172
1173         $arr['uri'] = $uri;
1174         $arr['uid'] = $importer['uid'];
1175         $arr['guid'] = $guid;
1176         $arr['contact-id'] = $contact['id'];
1177         $arr['type'] = 'activity';
1178         $arr['wall'] = $parent_item['wall'];
1179         $arr['gravity'] = GRAVITY_LIKE;
1180         $arr['parent'] = $parent_item['id'];
1181         $arr['parent-uri'] = $parent_item['uri'];
1182
1183         $arr['owner-name'] = $parent_item['name'];
1184         $arr['owner-link'] = $parent_item['url'];
1185         $arr['owner-avatar'] = $parent_item['thumb'];
1186
1187         $arr['author-name'] = $person['name'];
1188         $arr['author-link'] = $person['url'];
1189         $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1190         
1191         $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1192         $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1193         $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1194         $arr['body'] =  sprintf( $bodyverb, $ulink, $alink, $plink );
1195
1196         $arr['app']  = 'Diaspora';
1197
1198         $arr['private'] = $parent_item['private'];
1199         $arr['verb'] = $activity;
1200         $arr['object-type'] = $objtype;
1201         $arr['object'] = $obj;
1202         $arr['visible'] = 1;
1203         $arr['unseen'] = 1;
1204         $arr['last-child'] = 0;
1205
1206         $message_id = item_store($arr);
1207
1208
1209         if($message_id) {
1210                 q("update item set plink = '%s' where id = %d limit 1",
1211                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1212                         intval($message_id)
1213                 );
1214         }
1215
1216         if(! $parent_author_signature) {
1217                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1218                         intval($message_id),
1219                         dbesc($author_signed_data),
1220                         dbesc(base64_encode($author_signature)),
1221                         dbesc($diaspora_handle)
1222                 );
1223         }
1224
1225         // if the message isn't already being relayed, notify others
1226         // the existence of parent_author_signature means the parent_author or owner
1227         // is already relaying. The parent_item['origin'] indicates the message was created on our system
1228
1229         if(($parent_item['origin']) && (! $parent_author_signature))
1230                 proc_run('php','include/notifier.php','comment',$message_id);
1231
1232         return;
1233 }
1234
1235 function diaspora_retraction($importer,$xml) {
1236
1237         $guid = notags(unxmlify($xml->guid));
1238         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1239         $type = notags(unxmlify($xml->type));
1240
1241         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1242         if(! $contact)
1243                 return;
1244
1245         if($type === 'Person') {
1246                 contact_remove($contact['id']);
1247         }
1248         elseif($type === 'Post') {
1249                 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1250                         dbesc('guid'),
1251                         intval($importer['uid'])
1252                 );
1253                 if(count($r)) {
1254                         if(link_compare($r[0]['author-link'],$contact['url'])) {
1255                                 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1256                                         dbesc(datetime_convert()),                      
1257                                         intval($r[0]['id'])
1258                                 );
1259                         }
1260                 }
1261         }
1262
1263         return 202;
1264         // NOTREACHED
1265 }
1266
1267 function diaspora_profile($importer,$xml) {
1268
1269         $a = get_app();
1270         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1271
1272         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1273         if(! $contact)
1274                 return;
1275
1276         if($contact['blocked']) {
1277                 logger('diaspora_post: Ignoring this author.');
1278                 return 202;
1279         }
1280
1281         $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
1282         $image_url = unxmlify($xml->image_url);
1283         $birthday = unxmlify($xml->birthday);
1284
1285         $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE  `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
1286                 intval($importer['uid']),
1287                 intval($contact['id'])
1288         );
1289         $oldphotos = ((count($r)) ? $r : null);
1290
1291         require_once('include/Photo.php');
1292
1293         $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
1294         
1295         // Generic birthday. We don't know the timezone. The year is irrelevant. 
1296
1297         $birthday = str_replace('1000','1901',$birthday);
1298
1299         $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
1300
1301         $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",
1302                 dbesc($name),
1303                 dbesc(datetime_convert()),
1304                 dbesc($images[0]),
1305                 dbesc($images[1]),
1306                 dbesc($images[2]),
1307                 dbesc(datetime_convert()),
1308                 dbesc($birthday),
1309                 intval($contact['id']),
1310                 intval($importer['uid'])
1311         ); 
1312
1313         if($r) {
1314                 if($oldphotos) {
1315                         foreach($oldphotos as $ph) {
1316                                 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
1317                                         intval($importer['uid']),
1318                                         intval($contact['id']),
1319                                         dbesc($ph['resource-id'])
1320                                 );
1321                         }
1322                 }
1323         }       
1324
1325         return;
1326
1327 }
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350 function diaspora_share($me,$contact) {
1351         $a = get_app();
1352         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1353         $theiraddr = $contact['addr'];
1354
1355         $tpl = get_markup_template('diaspora_share.tpl');
1356         $msg = replace_macros($tpl, array(
1357                 '$sender' => $myaddr,
1358                 '$recipient' => $theiraddr
1359         ));
1360
1361         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1362
1363         return(diaspora_transmit($owner,$contact,$slap, false));
1364 }
1365
1366 function diaspora_unshare($me,$contact) {
1367
1368         $a = get_app();
1369         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1370
1371         $tpl = get_markup_template('diaspora_retract.tpl');
1372         $msg = replace_macros($tpl, array(
1373                 '$guid'   => $me['guid'],
1374                 '$type'   => 'Person',
1375                 '$handle' => $myaddr
1376         ));
1377
1378         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1379
1380         return(diaspora_transmit($owner,$contact,$slap, false));
1381
1382 }
1383
1384
1385
1386 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
1387
1388         $a = get_app();
1389         $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1390         $theiraddr = $contact['addr'];
1391
1392         $images = array();
1393
1394         $body = $item['body'];
1395
1396 /*
1397         // We're trying to match Diaspora's split message/photo protocol but
1398         // all the photos are displayed on D* as links and not img's - even
1399         // though we're sending pretty much precisely what they send us when
1400         // doing the same operation.  
1401         // Commented out for now, we'll use bb2diaspora to convert photos to markdown
1402         // which seems to get through intact.
1403
1404         $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
1405         if($cnt) {
1406                 foreach($matches as $mtch) {
1407                         $detail = array();
1408                         $detail['str'] = $mtch[0];
1409                         $detail['path'] = dirname($mtch[1]) . '/';
1410                         $detail['file'] = basename($mtch[1]);
1411                         $detail['guid'] = $item['guid'];
1412                         $detail['handle'] = $myaddr;
1413                         $images[] = $detail;
1414                         $body = str_replace($detail['str'],$mtch[1],$body);
1415                 }
1416         }       
1417 */
1418
1419         $body = xmlify(html_entity_decode(bb2diaspora($body)));
1420
1421         if($item['attach']) {
1422                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
1423                 if(cnt) {
1424                         $body .= "\n" . t('Attachments:') . "\n";
1425                         foreach($matches as $mtch) {
1426                                 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
1427                         }
1428                 }
1429         }       
1430
1431
1432         $public = (($item['private']) ? 'false' : 'true');
1433
1434         require_once('include/datetime.php');
1435         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
1436
1437         $tpl = get_markup_template('diaspora_post.tpl');
1438         $msg = replace_macros($tpl, array(
1439                 '$body' => $body,
1440                 '$guid' => $item['guid'],
1441                 '$handle' => xmlify($myaddr),
1442                 '$public' => $public,
1443                 '$created' => $created
1444         ));
1445
1446         logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
1447
1448         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1449
1450         $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
1451
1452         if(count($images)) {
1453                 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
1454         }
1455
1456         return $return_code;
1457 }
1458
1459
1460 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
1461         $a = get_app();
1462         if(! count($images))
1463                 return;
1464         $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
1465
1466         $tpl = get_markup_template('diaspora_photo.tpl');
1467         foreach($images as $image) {
1468                 if(! stristr($image['path'],$mysite))
1469                         continue;
1470                 $resource = str_replace('.jpg','',$image['file']);
1471                 $resource = substr($resource,0,strpos($resource,'-'));
1472
1473                 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
1474                         dbesc($resource),
1475                         intval($owner['uid'])
1476                 );
1477                 if(! count($r))
1478                         continue;
1479                 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
1480                 $msg = replace_macros($tpl,array(               
1481                         '$path' => xmlify($image['path']),
1482                         '$filename' => xmlify($image['file']),
1483                         '$msg_guid' => xmlify($image['guid']),
1484                         '$guid' => xmlify($r[0]['guid']),
1485                         '$handle' => xmlify($image['handle']),
1486                         '$public' => xmlify($public),
1487                         '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
1488                 ));
1489
1490
1491                 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
1492                 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1493
1494                 diaspora_transmit($owner,$contact,$slap,$public_batch);
1495         }
1496
1497 }
1498
1499 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
1500
1501         $a = get_app();
1502         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1503         $theiraddr = $contact['addr'];
1504
1505         $p = q("select guid from item where parent = %d limit 1",
1506                 $item['parent']
1507         );
1508         if(count($p))
1509                 $parent_guid = $p[0]['guid'];
1510         else
1511                 return;
1512
1513         if($item['verb'] === ACTIVITY_LIKE) {
1514                 $tpl = get_markup_template('diaspora_like.tpl');
1515                 $like = true;
1516                 $target_type = 'Post';
1517                 $positive = (($item['deleted']) ? 'false' : 'true');
1518         }
1519         else {
1520                 $tpl = get_markup_template('diaspora_comment.tpl');
1521                 $like = false;
1522         }
1523
1524         $text = html_entity_decode(bb2diaspora($item['body']));
1525
1526         // sign it
1527
1528         if($like)
1529                 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1530         else
1531                 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1532
1533         $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1534
1535         $msg = replace_macros($tpl,array(
1536                 '$guid' => xmlify($item['guid']),
1537                 '$parent_guid' => xmlify($parent_guid),
1538                 '$target_type' =>xmlify($target_type),
1539                 '$authorsig' => xmlify($authorsig),
1540                 '$body' => xmlify($text),
1541                 '$positive' => xmlify($positive),
1542                 '$handle' => xmlify($myaddr)
1543         ));
1544
1545         logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
1546
1547         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1548
1549         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1550 }
1551
1552
1553 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
1554
1555
1556         $a = get_app();
1557         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1558         $theiraddr = $contact['addr'];
1559
1560
1561         $p = q("select guid from item where parent = %d limit 1",
1562                 $item['parent']
1563         );
1564         if(count($p))
1565                 $parent_guid = $p[0]['guid'];
1566         else
1567                 return;
1568
1569         if($item['verb'] === ACTIVITY_LIKE) {
1570                 $tpl = get_markup_template('diaspora_like_relay.tpl');
1571                 $like = true;
1572                 $target_type = 'Post';
1573                 $positive = (($item['deleted']) ? 'false' : 'true');
1574         }
1575         else {
1576                 $tpl = get_markup_template('diaspora_comment_relay.tpl');
1577                 $like = false;
1578         }
1579
1580         $body = $item['body'];
1581
1582         $text = html_entity_decode(bb2diaspora($body));
1583
1584         // fetch the original signature if somebody sent the post to us to relay
1585         // If we are relaying for a reply originating on our own account, there wasn't a 'send to relay'
1586         // action. It wasn't needed. In that case create the original signature and the 
1587         // owner (parent author) signature
1588         // comments from other networks will be relayed under our name, with a brief 
1589         // preamble to describe what's happening and noting the real author
1590
1591         $r = q("select * from sign where iid = %d limit 1",
1592                 intval($item['id'])
1593         );
1594         if(count($r)) { 
1595                 $orig_sign = $r[0];
1596                 $signed_text = $orig_sign['signed_text'];
1597                 $authorsig = $orig_sign['signature'];
1598                 $handle = $orig_sign['signer'];
1599         }
1600         else {
1601
1602                 $itemcontact = q("select * from contact where `id` = %d limit 1",
1603                         intval($item['contact-id'])
1604                 );
1605                 if(count($itemcontact)) {
1606                         if(! $itemcontact[0]['self']) {
1607                                 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
1608                                         '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',  
1609                                         network_to_name($itemcontact['network'])) . "\n";
1610                                 $body = $prefix . $body;
1611                         }
1612                 }
1613                 else {
1614
1615                         if($like)
1616                                 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1617                         else
1618                                 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1619
1620                         $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1621
1622                         q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1623                                 intval($item['id']),
1624                                 dbesc($signed_text),
1625                                 dbesc(base64_encode($authorsig)),
1626                                 dbesc($myaddr)
1627                         );
1628                         $handle = $myaddr;
1629                 }
1630         }
1631
1632         // sign it
1633
1634         $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1635
1636         $msg = replace_macros($tpl,array(
1637                 '$guid' => xmlify($item['guid']),
1638                 '$parent_guid' => xmlify($parent_guid),
1639                 '$target_type' =>xmlify($target_type),
1640                 '$authorsig' => xmlify($orig_sign['signature']),
1641                 '$parentsig' => xmlify($parentauthorsig),
1642                 '$body' => xmlify($text),
1643                 '$positive' => xmlify($positive),
1644                 '$handle' => xmlify($handle)
1645         ));
1646
1647         logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
1648
1649         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1650
1651         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1652
1653 }
1654
1655
1656
1657 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
1658
1659         $a = get_app();
1660         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1661
1662         $tpl = get_markup_template('diaspora_retract.tpl');
1663         $msg = replace_macros($tpl, array(
1664                 '$guid'   => $item['guid'],
1665                 '$type'   => 'Post',
1666                 '$handle' => $myaddr
1667         ));
1668
1669         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1670
1671         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1672 }
1673
1674
1675
1676 function diaspora_transmit($owner,$contact,$slap,$public_batch) {
1677
1678         $a = get_app();
1679         $logid = random_string(4);
1680         logger('diaspora_transmit: ' . $logid . ' ' . (($public_batch) ? $contact['batch'] : $contact['notify']));
1681         post_url((($public_batch) ? $contact['batch'] : $contact['notify']) . '/',$slap);
1682         $return_code = $a->get_curl_code();
1683         logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
1684
1685         if((! $return_code) || (($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
1686                 logger('diaspora_transmit: queue message');
1687                 // queue message for redelivery
1688                 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
1689         }
1690
1691
1692         return(($return_code) ? $return_code : (-1));
1693 }