]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
99288b773cdaed1da8dfc7d8803101ec789b5e49
[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 require_once('include/lock.php');
9
10 function diaspora_dispatch_public($msg) {
11
12         $enabled = intval(get_config('system','diaspora_enabled'));
13         if(! $enabled) {
14                 logger('mod-diaspora: disabled');
15                 return;
16         }
17
18         $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
19                 ( SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s' )
20                 AND `account_expired` = 0 AND `account_removed` = 0 ",
21                 dbesc(NETWORK_DIASPORA),
22                 dbesc($msg['author'])
23         );
24         if(count($r)) {
25                 foreach($r as $rr) {
26                         logger('diaspora_public: delivering to: ' . $rr['username']);
27                         diaspora_dispatch($rr,$msg);
28                 }
29         }
30         else
31                 logger('diaspora_public: no subscribers');
32 }
33
34
35
36 function diaspora_dispatch($importer,$msg,$attempt=1) {
37
38         $ret = 0;
39
40         $enabled = intval(get_config('system','diaspora_enabled'));
41         if(! $enabled) {
42                 logger('mod-diaspora: disabled');
43                 return;
44         }
45
46         // php doesn't like dashes in variable names
47
48         $msg['message'] = str_replace(
49                         array('<activity_streams-photo>','</activity_streams-photo>'),
50                         array('<asphoto>','</asphoto>'),
51                         $msg['message']);
52
53
54         $parsed_xml = parse_xml_string($msg['message'],false);
55
56         $xmlbase = $parsed_xml->post;
57
58         logger('diaspora_dispatch: ' . print_r($xmlbase,true), LOGGER_DEBUG);
59
60
61         if($xmlbase->request) {
62                 $ret = diaspora_request($importer,$xmlbase->request);
63         }
64         elseif($xmlbase->status_message) {
65                 $ret = diaspora_post($importer,$xmlbase->status_message,$msg);
66         }
67         elseif($xmlbase->profile) {
68                 $ret = diaspora_profile($importer,$xmlbase->profile,$msg);
69         }
70         elseif($xmlbase->comment) {
71                 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
72         }
73         elseif($xmlbase->like) {
74                 $ret = diaspora_like($importer,$xmlbase->like,$msg);
75         }
76         elseif($xmlbase->asphoto) {
77                 $ret = diaspora_asphoto($importer,$xmlbase->asphoto,$msg);
78         }
79         elseif($xmlbase->reshare) {
80                 $ret = diaspora_reshare($importer,$xmlbase->reshare,$msg);
81         }
82         elseif($xmlbase->retraction) {
83                 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
84         }
85         elseif($xmlbase->signed_retraction) {
86                 $ret = diaspora_signed_retraction($importer,$xmlbase->signed_retraction,$msg);
87         }
88         elseif($xmlbase->relayable_retraction) {
89                 $ret = diaspora_signed_retraction($importer,$xmlbase->relayable_retraction,$msg);
90         }
91         elseif($xmlbase->photo) {
92                 $ret = diaspora_photo($importer,$xmlbase->photo,$msg,$attempt);
93         }
94         elseif($xmlbase->conversation) {
95                 $ret = diaspora_conversation($importer,$xmlbase->conversation,$msg);
96         }
97         elseif($xmlbase->message) {
98                 $ret = diaspora_message($importer,$xmlbase->message,$msg);
99         }
100         else {
101                 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
102         }
103         return $ret;
104 }
105
106 function diaspora_handle_from_contact($contact_id) {
107         $handle = False;
108
109         logger("diaspora_handle_from_contact: contact id is " . $contact_id, LOGGER_DEBUG);
110
111         $r = q("SELECT network, addr, self, url, nick FROM contact WHERE id = %d",
112                intval($contact_id)
113         );
114         if($r) {
115                 $contact = $r[0];
116
117                 logger("diaspora_handle_from_contact: contact 'self' = " . $contact['self'] . " 'url' = " . $contact['url'], LOGGER_DEBUG);
118
119                 if($contact['network'] === NETWORK_DIASPORA) {
120                         $handle = $contact['addr'];
121
122 //                      logger("diaspora_handle_from_contact: contact id is a Diaspora person, handle = " . $handle, LOGGER_DEBUG);
123                 }
124                 elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
125                         $baseurl_start = strpos($contact['url'],'://') + 3;
126                         $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
127                         $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
128                         $handle = $contact['nick'] . '@' . $baseurl;
129
130 //                      logger("diaspora_handle_from_contact: contact id is a DFRN person, handle = " . $handle, LOGGER_DEBUG);
131                 }
132         }
133
134         return $handle;
135 }
136
137 function diaspora_get_contact_by_handle($uid,$handle) {
138         $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
139                 dbesc(NETWORK_DIASPORA),
140                 intval($uid),
141                 dbesc($handle)
142         );
143         if($r && count($r))
144                 return $r[0];
145
146         $handle_parts = explode("@", $handle);
147         $nurl_sql = '%%://' . $handle_parts[1] . '%%/profile/' . $handle_parts[0];
148         $r = q("SELECT * FROM contact WHERE network = '%s' AND uid = %d AND nurl LIKE '%s' LIMIT 1",
149                dbesc(NETWORK_DFRN),
150                intval($uid),
151                dbesc($nurl_sql)
152         );
153         if($r && count($r))
154                 return $r[0];
155
156         return false;
157 }
158
159 function find_diaspora_person_by_handle($handle) {
160
161         $person = false;
162         $update = false;
163         $got_lock = false;
164
165         $endlessloop = 0;
166         $maxloops = 10;
167
168         do {
169                 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
170                         dbesc(NETWORK_DIASPORA),
171                         dbesc($handle)
172                 );
173                 if(count($r)) {
174                         $person = $r[0];
175                         logger('find_diaspora_person_by handle: in cache ' . print_r($r,true), LOGGER_DEBUG);
176
177                         // update record occasionally so it doesn't get stale
178                         $d = strtotime($person['updated'] . ' +00:00');
179                         if($d < strtotime('now - 14 days'))
180                                 $update = true;
181                 }
182
183
184                 // FETCHING PERSON INFORMATION FROM REMOTE SERVER
185                 //
186                 // If the person isn't in our 'fcontact' table, or if he/she is but
187                 // his/her information hasn't been updated for more than 14 days, then
188                 // we want to fetch the person's information from the remote server.
189                 //
190                 // Note that $person isn't changed by this block of code unless the
191                 // person's information has been successfully fetched from the remote
192                 // server. So if $person was 'false' to begin with (because he/she wasn't
193                 // in the local cache), it'll stay false, and if $person held the local
194                 // cache information to begin with, it'll keep that information. That way
195                 // if there's a problem with the remote fetch, we can at least use our
196                 // cached information--it's better than nothing.
197
198                 if((! $person) || ($update))  {
199                         // Lock the function to prevent race conditions if multiple items
200                         // come in at the same time from a person who doesn't exist in
201                         // fcontact
202                         //
203                         // Don't loop forever. On the last loop, try to create the contact
204                         // whether the function is locked or not. Maybe the locking thread
205                         // has died or something. At any rate, a duplicate in 'fcontact'
206                         // is a much smaller problem than a deadlocked thread
207                         $got_lock = lock_function('find_diaspora_person_by_handle', false);
208                         if(($endlessloop + 1) >= $maxloops)
209                                 $got_lock = true;
210
211                         if($got_lock) {
212                                 logger('find_diaspora_person_by_handle: create or refresh', LOGGER_DEBUG);
213                                 require_once('include/Scrape.php');
214                                 $r = probe_url($handle, PROBE_DIASPORA);
215
216                                 // Note that Friendica contacts can return a "Diaspora person"
217                                 // if Diaspora connectivity is enabled on their server
218                                 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
219                                         add_fcontact($r,$update);
220                                         $person = ($r);
221                                 }
222
223                                 unlock_function('find_diaspora_person_by_handle');
224                         }
225                         else {
226                                 logger('find_diaspora_person_by_handle: couldn\'t lock function', LOGGER_DEBUG);
227                                 if(! $person)
228                                         block_on_function_lock('find_diaspora_person_by_handle');
229                         }
230                 }
231         } while((! $person) && (! $got_lock) && (++$endlessloop < $maxloops));
232         // We need to try again if the person wasn't in 'fcontact' but the function was locked.
233         // The fact that the function was locked may mean that another process was creating the
234         // person's record. It could also mean another process was creating or updating an unrelated
235         // person.
236         //
237         // At any rate, we need to keep trying until we've either got the person or had a chance to
238         // try to fetch his/her remote information. But we don't want to block on locking the
239         // function, because if the other process is creating the record, then when we acquire the lock
240         // we'll dive right into creating another, duplicate record. We DO want to at least wait
241         // until the lock is released, so we don't flood the database with requests.
242         //
243         // If the person was in the 'fcontact' table, don't try again. It's not worth the time, since
244         // we do have some information for the person
245
246         return $person;
247 }
248
249
250 function get_diaspora_key($uri) {
251         logger('Fetching diaspora key for: ' . $uri);
252
253         $r = find_diaspora_person_by_handle($uri);
254         if($r)
255                 return $r['pubkey'];
256         return '';
257 }
258
259
260 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
261         $a = get_app();
262
263         logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
264
265
266         $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
267
268 //      $b64_data = base64_encode($msg);
269 //      $b64url_data = base64url_encode($b64_data);
270
271         $b64url_data = base64url_encode($msg);
272
273         $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
274
275         $type = 'application/xml';
276         $encoding = 'base64url';
277         $alg = 'RSA-SHA256';
278
279         $signable_data = $data  . '.' . base64url_encode($type) . '.'
280                 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
281
282         $signature = rsa_sign($signable_data,$prvkey);
283         $sig = base64url_encode($signature);
284
285 $magic_env = <<< EOT
286 <?xml version='1.0' encoding='UTF-8'?>
287 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
288   <header>
289     <author_id>$handle</author_id>
290   </header>
291   <me:env>
292     <me:encoding>base64url</me:encoding>
293     <me:alg>RSA-SHA256</me:alg>
294     <me:data type="application/xml">$data</me:data>
295     <me:sig>$sig</me:sig>
296   </me:env>
297 </diaspora>
298 EOT;
299
300         logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
301         return $magic_env;
302
303 }
304
305
306
307
308 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
309         $a = get_app();
310
311         if($public)
312                 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
313
314         logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
315
316         // without a public key nothing will work
317
318         if(! $pubkey) {
319                 logger('diaspora_msg_build: pubkey missing: contact id: ' . $contact['id']);
320                 return '';
321         }
322
323         $inner_aes_key = random_string(32);
324         $b_inner_aes_key = base64_encode($inner_aes_key);
325         $inner_iv = random_string(16);
326         $b_inner_iv = base64_encode($inner_iv);
327
328         $outer_aes_key = random_string(32);
329         $b_outer_aes_key = base64_encode($outer_aes_key);
330         $outer_iv = random_string(16);
331         $b_outer_iv = base64_encode($outer_iv);
332
333         $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
334
335         $padded_data = pkcs5_pad($msg,16);
336         $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
337
338         $b64_data = base64_encode($inner_encrypted);
339
340
341         $b64url_data = base64url_encode($b64_data);
342         $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
343
344         $type = 'application/xml';
345         $encoding = 'base64url';
346         $alg = 'RSA-SHA256';
347
348         $signable_data = $data  . '.' . base64url_encode($type) . '.'
349                 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
350
351         $signature = rsa_sign($signable_data,$prvkey);
352         $sig = base64url_encode($signature);
353
354 $decrypted_header = <<< EOT
355 <decrypted_header>
356   <iv>$b_inner_iv</iv>
357   <aes_key>$b_inner_aes_key</aes_key>
358   <author_id>$handle</author_id>
359 </decrypted_header>
360 EOT;
361
362         $decrypted_header = pkcs5_pad($decrypted_header,16);
363
364         $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
365
366         $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
367
368         $encrypted_outer_key_bundle = '';
369         openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
370
371         $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
372
373         logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
374
375         $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle), 
376                 'ciphertext' => base64_encode($ciphertext)));
377         $cipher_json = base64_encode($encrypted_header_json_object);
378
379         $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
380
381 $magic_env = <<< EOT
382 <?xml version='1.0' encoding='UTF-8'?>
383 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
384   $encrypted_header
385   <me:env>
386     <me:encoding>base64url</me:encoding>
387     <me:alg>RSA-SHA256</me:alg>
388     <me:data type="application/xml">$data</me:data>
389     <me:sig>$sig</me:sig>
390   </me:env>
391 </diaspora>
392 EOT;
393
394         logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
395         return $magic_env;
396
397 }
398
399 /**
400  *
401  * diaspora_decode($importer,$xml)
402  *   array $importer -> from user table
403  *   string $xml -> urldecoded Diaspora salmon 
404  *
405  * Returns array
406  * 'message' -> decoded Diaspora XML message
407  * 'author' -> author diaspora handle
408  * 'key' -> author public key (converted to pkcs#8)
409  *
410  * Author and key are used elsewhere to save a lookup for verifying replies and likes
411  */
412
413
414 function diaspora_decode($importer,$xml) {
415
416         $public = false;
417         $basedom = parse_xml_string($xml);
418
419         $children = $basedom->children('https://joindiaspora.com/protocol');
420
421         if($children->header) {
422                 $public = true;
423                 $author_link = str_replace('acct:','',$children->header->author_id);
424         }
425         else {
426
427                 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
428
429                 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
430                 $ciphertext = base64_decode($encrypted_header->ciphertext);
431
432                 $outer_key_bundle = '';
433                 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
434
435                 $j_outer_key_bundle = json_decode($outer_key_bundle);
436
437                 $outer_iv = base64_decode($j_outer_key_bundle->iv);
438                 $outer_key = base64_decode($j_outer_key_bundle->key);
439
440                 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
441
442
443                 $decrypted = pkcs5_unpad($decrypted);
444
445                 /**
446                  * $decrypted now contains something like
447                  *
448                  *  <decrypted_header>
449                  *     <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
450                  *     <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
451
452 ***** OBSOLETE
453
454                  *     <author>
455                  *       <name>Ryan Hughes</name>
456                  *       <uri>acct:galaxor@diaspora.pirateship.org</uri>
457                  *     </author>
458
459 ***** CURRENT
460
461                  *     <author_id>galaxor@diaspora.priateship.org</author_id>
462
463 ***** END DIFFS
464
465                  *  </decrypted_header>
466                  */
467
468                 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
469                 $idom = parse_xml_string($decrypted,false);
470
471                 $inner_iv = base64_decode($idom->iv);
472                 $inner_aes_key = base64_decode($idom->aes_key);
473
474                 $author_link = str_replace('acct:','',$idom->author_id);
475
476         }
477
478         $dom = $basedom->children(NAMESPACE_SALMON_ME);
479
480         // figure out where in the DOM tree our data is hiding
481
482         if($dom->provenance->data)
483                 $base = $dom->provenance;
484         elseif($dom->env->data)
485                 $base = $dom->env;
486         elseif($dom->data)
487                 $base = $dom;
488
489         if(! $base) {
490                 logger('mod-diaspora: unable to locate salmon data in xml ');
491                 http_status_exit(400);
492         }
493
494
495         // Stash the signature away for now. We have to find their key or it won't be good for anything.
496         $signature = base64url_decode($base->sig);
497
498         // unpack the  data
499
500         // strip whitespace so our data element will return to one big base64 blob
501         $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
502
503
504         // stash away some other stuff for later
505
506         $type = $base->data[0]->attributes()->type[0];
507         $keyhash = $base->sig[0]->attributes()->keyhash[0];
508         $encoding = $base->encoding;
509         $alg = $base->alg;
510
511
512         $signed_data = $data  . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
513
514
515         // decode the data
516         $data = base64url_decode($data);
517
518
519         if($public) {
520                 $inner_decrypted = $data;
521         }
522         else {
523
524                 // Decode the encrypted blob
525
526                 $inner_encrypted = base64_decode($data);
527                 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
528                 $inner_decrypted = pkcs5_unpad($inner_decrypted);
529         }
530
531         if(! $author_link) {
532                 logger('mod-diaspora: Could not retrieve author URI.');
533                 http_status_exit(400);
534         }
535
536         // Once we have the author URI, go to the web and try to find their public key
537         // (first this will look it up locally if it is in the fcontact cache)
538         // This will also convert diaspora public key from pkcs#1 to pkcs#8
539
540         logger('mod-diaspora: Fetching key for ' . $author_link );
541         $key = get_diaspora_key($author_link);
542
543         if(! $key) {
544                 logger('mod-diaspora: Could not retrieve author key.');
545                 http_status_exit(400);
546         }
547
548         $verify = rsa_verify($signed_data,$signature,$key);
549
550         if(! $verify) {
551                 logger('mod-diaspora: Message did not verify. Discarding.');
552                 http_status_exit(400);
553         }
554
555         logger('mod-diaspora: Message verified.');
556
557         return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
558
559 }
560
561
562 function diaspora_request($importer,$xml) {
563
564         $a = get_app();
565
566         $sender_handle = unxmlify($xml->sender_handle);
567         $recipient_handle = unxmlify($xml->recipient_handle);
568
569         if(! $sender_handle || ! $recipient_handle)
570                 return;
571
572         $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
573
574         if($contact) {
575
576                 // perhaps we were already sharing with this person. Now they're sharing with us.
577                 // That makes us friends.
578
579                 if($contact['rel'] == CONTACT_IS_FOLLOWER && $importer['page-flags'] != PAGE_COMMUNITY) {
580                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
581                                 intval(CONTACT_IS_FRIEND),
582                                 intval($contact['id']),
583                                 intval($importer['uid'])
584                         );
585                 }
586                 // send notification
587
588                 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
589                         intval($importer['uid'])
590                 );
591
592                 if((count($r)) && (! $r[0]['hide-friends']) && (! $contact['hidden'])) {
593                         require_once('include/items.php');
594
595                         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
596                                 intval($importer['uid'])
597                         );
598
599                         // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
600
601                         if(count($self) && $contact['rel'] == CONTACT_IS_FOLLOWER) {
602
603                                 $arr = array();
604                                 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']); 
605                                 $arr['uid'] = $importer['uid'];
606                                 $arr['contact-id'] = $self[0]['id'];
607                                 $arr['wall'] = 1;
608                                 $arr['type'] = 'wall';
609                                 $arr['gravity'] = 0;
610                                 $arr['origin'] = 1;
611                                 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
612                                 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
613                                 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
614                                 $arr['verb'] = ACTIVITY_FRIEND;
615                                 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
616
617                                 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
618                                 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
619                                 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
620                                 $arr['body'] =  sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
621
622                                 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
623                                         . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
624                                 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
625                                 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
626                                 $arr['object'] .= '</link></object>' . "\n";
627                                 $arr['last-child'] = 1;
628
629                                 $arr['allow_cid'] = $user[0]['allow_cid'];
630                                 $arr['allow_gid'] = $user[0]['allow_gid'];
631                                 $arr['deny_cid']  = $user[0]['deny_cid'];
632                                 $arr['deny_gid']  = $user[0]['deny_gid'];
633
634                                 $i = item_store($arr);
635                                 if($i)
636                                 proc_run('php',"include/notifier.php","activity","$i");
637
638                         }
639
640                 }
641
642                 return;
643         }
644
645         $ret = find_diaspora_person_by_handle($sender_handle);
646
647
648         if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
649                 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
650                 return;
651         }
652
653         $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
654
655
656
657         $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
658                 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
659                 intval($importer['uid']),
660                 dbesc($ret['network']),
661                 dbesc($ret['addr']),
662                 datetime_convert(),
663                 dbesc($ret['url']),
664                 dbesc(normalise_link($ret['url'])),
665                 dbesc($batch),
666                 dbesc($ret['name']),
667                 dbesc($ret['nick']),
668                 dbesc($ret['photo']),
669                 dbesc($ret['pubkey']),
670                 dbesc($ret['notify']),
671                 dbesc($ret['poll']),
672                 1,
673                 2
674         );
675
676         // find the contact record we just created
677
678         $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
679
680         if(! $contact_record) {
681                 logger('diaspora_request: unable to locate newly created contact record.');
682                 return;
683         }
684
685         $g = q("select def_gid from user where uid = %d limit 1",
686                 intval($importer['uid'])
687         );
688         if($g && intval($g[0]['def_gid'])) {
689                 require_once('include/group.php');
690                 group_add_member($importer['uid'],'',$contact_record['id'],$g[0]['def_gid']);
691         }
692
693         if($importer['page-flags'] == PAGE_NORMAL) {
694
695                 $hash = random_string() . (string) time();   // Generate a confirm_key
696
697                 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
698                         VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
699                         intval($importer['uid']),
700                         intval($contact_record['id']),
701                         0,
702                         0,
703                         dbesc( t('Sharing notification from Diaspora network')),
704                         dbesc($hash),
705                         dbesc(datetime_convert())
706                 );
707         }
708         else {
709
710                 // automatic friend approval
711
712                 require_once('include/Photo.php');
713
714                 $photos = import_profile_photo($contact_record['photo'],$importer['uid'],$contact_record['id']);
715
716                 // technically they are sharing with us (CONTACT_IS_SHARING),
717                 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
718                 // we are going to change the relationship and make them a follower.
719
720                 if($importer['page-flags'] == PAGE_FREELOVE)
721                         $new_relation = CONTACT_IS_FRIEND;
722                 else
723                         $new_relation = CONTACT_IS_FOLLOWER;
724
725                 $r = q("UPDATE `contact` SET 
726                         `photo` = '%s', 
727                         `thumb` = '%s',
728                         `micro` = '%s', 
729                         `rel` = %d, 
730                         `name-date` = '%s', 
731                         `uri-date` = '%s', 
732                         `avatar-date` = '%s', 
733                         `blocked` = 0, 
734                         `pending` = 0
735                         WHERE `id` = %d
736                         ",
737                         dbesc($photos[0]),
738                         dbesc($photos[1]),
739                         dbesc($photos[2]),
740                         intval($new_relation),
741                         dbesc(datetime_convert()),
742                         dbesc(datetime_convert()),
743                         dbesc(datetime_convert()),
744                         intval($contact_record['id'])
745                 );
746
747                 $u = q("select * from user where uid = %d limit 1",intval($importer['uid']));
748                 if($u)
749                         $ret = diaspora_share($u[0],$contact_record);
750         }
751
752         return;
753 }
754
755 function diaspora_post_allow($importer,$contact) {
756
757         // perhaps we were already sharing with this person. Now they're sharing with us.
758         // That makes us friends.
759         // Normally this should have handled by getting a request - but this could get lost
760         if($contact['rel'] == CONTACT_IS_FOLLOWER && $importer['page-flags'] != PAGE_COMMUNITY) {
761                 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
762                         intval(CONTACT_IS_FRIEND),
763                         intval($contact['id']),
764                         intval($importer['uid'])
765                 );
766                 $contact['rel'] = CONTACT_IS_FRIEND;
767                 logger('diaspora_post_allow: defining user '.$contact["nick"].' as friend');
768         }
769
770         if(($contact['blocked']) || ($contact['readonly']) || ($contact['archive']))
771                 return false;
772         if($contact['rel'] == CONTACT_IS_SHARING || $contact['rel'] == CONTACT_IS_FRIEND)
773                 return true;
774         if($contact['rel'] == CONTACT_IS_FOLLOWER)
775                 if($importer['page-flags'] == PAGE_COMMUNITY)
776                         return true;
777         return false;
778 }
779
780
781 function diaspora_post($importer,$xml,$msg) {
782
783         $a = get_app();
784         $guid = notags(unxmlify($xml->guid));
785         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
786
787         if($diaspora_handle != $msg['author']) {
788                 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
789                 return 202;
790         }
791
792         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
793         if(! $contact)
794                 return;
795
796         if(! diaspora_post_allow($importer,$contact)) {
797                 logger('diaspora_post: Ignoring this author.');
798                 return 202;
799         }
800
801         $message_id = $diaspora_handle . ':' . $guid;
802         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
803                 intval($importer['uid']),
804                 dbesc($message_id),
805                 dbesc($guid)
806         );
807         if(count($r)) {
808                 logger('diaspora_post: message exists: ' . $guid);
809                 return;
810         }
811
812         // allocate a guid on our system - we aren't fixing any collisions.
813         // we're ignoring them
814
815         $g = q("select * from guid where guid = '%s' limit 1",
816                 dbesc($guid)
817         );
818         if(! count($g)) {
819                 q("insert into guid ( guid ) values ( '%s' )",
820                         dbesc($guid)
821                 );
822         }
823
824         $created = unxmlify($xml->created_at);
825         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
826
827         $body = diaspora2bb($xml->raw_message);
828
829         // Add OEmbed and other information to the body
830         $body = add_page_info_to_body($body, false, true);
831
832         $datarray = array();
833
834         $str_tags = '';
835
836         $tags = get_tags($body);
837
838         if(count($tags)) {
839                 foreach($tags as $tag) {
840                         if(strpos($tag,'#') === 0) {
841                                 if(strpos($tag,'[url='))
842                                         continue;
843
844                                 // don't link tags that are already embedded in links
845
846                                 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
847                                         continue;
848                                 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
849                                         continue;
850
851                                 $basetag = str_replace('_',' ',substr($tag,1));
852                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
853                                 if(strlen($str_tags))
854                                         $str_tags .= ',';
855                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
856                                 continue;
857                         }
858                 }
859         }
860
861         $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
862         if($cnt) {
863                 foreach($matches as $mtch) {
864                         if(strlen($str_tags))
865                                 $str_tags .= ',';
866                         $str_tags .= '@[url=' . $mtch[1] . '[/url]';
867                 }
868         }
869
870         $plink = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1).'/posts/'.$guid;
871
872         $datarray['uid'] = $importer['uid'];
873         $datarray['contact-id'] = $contact['id'];
874         $datarray['wall'] = 0;
875         $datarray['network'] = NETWORK_DIASPORA;
876         $datarray['verb'] = ACTIVITY_POST;
877         $datarray['guid'] = $guid;
878         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
879         $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
880         $datarray['private'] = $private;
881         $datarray['parent'] = 0;
882         $datarray['plink'] = $plink;
883         $datarray['owner-name'] = $contact['name'];
884         $datarray['owner-link'] = $contact['url'];
885         //$datarray['owner-avatar'] = $contact['thumb'];
886         $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
887         $datarray['author-name'] = $contact['name'];
888         $datarray['author-link'] = $contact['url'];
889         $datarray['author-avatar'] = $contact['thumb'];
890         $datarray['body'] = $body;
891         $datarray['tag'] = $str_tags;
892         $datarray['app']  = 'Diaspora';
893
894         // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
895
896         $datarray['visible'] = ((strlen($body)) ? 1 : 0);
897
898         $message_id = item_store($datarray);
899
900         //if($message_id) {
901         //      q("update item set plink = '%s' where id = %d",
902         //              dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
903         //              intval($message_id)
904         //      );
905         //}
906
907         return;
908
909 }
910
911 function diaspora_reshare($importer,$xml,$msg) {
912
913         logger('diaspora_reshare: init: ' . print_r($xml,true));
914
915         $a = get_app();
916         $guid = notags(unxmlify($xml->guid));
917         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
918
919
920         if($diaspora_handle != $msg['author']) {
921                 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
922                 return 202;
923         }
924
925         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
926         if(! $contact)
927                 return;
928
929         if(! diaspora_post_allow($importer,$contact)) {
930                 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
931                 return 202;
932         }
933
934         $message_id = $diaspora_handle . ':' . $guid;
935         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
936                 intval($importer['uid']),
937                 dbesc($message_id),
938                 dbesc($guid)
939         );
940         if(count($r)) {
941                 logger('diaspora_reshare: message exists: ' . $guid);
942                 return;
943         }
944
945         $orig_author = notags(unxmlify($xml->root_diaspora_id));
946         $orig_guid = notags(unxmlify($xml->root_guid));
947
948         $source_url = 'https://' . substr($orig_author,strpos($orig_author,'@')+1) . '/p/' . $orig_guid . '.xml';
949         $orig_url = 'https://'.substr($orig_author,strpos($orig_author,'@')+1).'/posts/'.$orig_guid;
950         $x = fetch_url($source_url);
951         if(! $x)
952                 $x = fetch_url(str_replace('https://','http://',$source_url));
953         if(! $x) {
954                 logger('diaspora_reshare: unable to fetch source url ' . $source_url);
955                 return;
956         }
957         logger('diaspora_reshare: source: ' . $x);
958
959         $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
960         $source_xml = parse_xml_string($x,false);
961
962         if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
963                 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
964                 $body = scale_external_images($body,false);
965         }
966         elseif($source_xml->post->asphoto->image_url) {
967                 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
968                 $body = scale_external_images($body);
969         }
970         elseif($source_xml->post->status_message) {
971                 $body = diaspora2bb($source_xml->post->status_message->raw_message);
972
973                 // Checking for embedded pictures
974                 if($source_xml->post->status_message->photo->remote_photo_path AND
975                         $source_xml->post->status_message->photo->remote_photo_name) {
976
977                         $remote_photo_path = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_path));
978                         $remote_photo_name = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_name));
979
980                         $body = '[img]'.$remote_photo_path.$remote_photo_name.'[/img]'."\n".$body;
981
982                         logger('diaspora_reshare: embedded picture link found: '.$body, LOGGER_DEBUG);
983                 }
984
985                 $body = scale_external_images($body);
986
987                 // Add OEmbed and other information to the body
988                 $body = add_page_info_to_body($body, false, true);
989         }
990         else {
991                 // Maybe it is a reshare of a photo that will be delivered at a later time (testing)
992                 logger('diaspora_reshare: no reshare content found: ' . print_r($source_xml,true));
993                 $body = "";
994                 //return;
995         }
996
997         //if(! $body) {
998         //      logger('diaspora_reshare: empty body: source= ' . $x);
999         //      return;
1000         //}
1001
1002         $person = find_diaspora_person_by_handle($orig_author);
1003
1004         /*if(is_array($person) && x($person,'name') && x($person,'url'))
1005                 $details = '[url=' . $person['url'] . ']' . $person['name'] . '[/url]';
1006         else
1007                 $details = $orig_author;
1008
1009         $prefix = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8') . $details . "\n";*/
1010
1011
1012         // allocate a guid on our system - we aren't fixing any collisions.
1013         // we're ignoring them
1014
1015         $g = q("select * from guid where guid = '%s' limit 1",
1016                 dbesc($guid)
1017         );
1018         if(! count($g)) {
1019                 q("insert into guid ( guid ) values ( '%s' )",
1020                         dbesc($guid)
1021                 );
1022         }
1023
1024         $created = unxmlify($xml->created_at);
1025         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1026
1027         $datarray = array();
1028
1029         $str_tags = '';
1030
1031         $tags = get_tags($body);
1032
1033         if(count($tags)) {
1034                 foreach($tags as $tag) {
1035                         if(strpos($tag,'#') === 0) {
1036                                 if(strpos($tag,'[url='))
1037                                         continue;
1038
1039                                 // don't link tags that are already embedded in links
1040
1041                                 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
1042                                         continue;
1043                                 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
1044                                         continue;
1045
1046
1047                                 $basetag = str_replace('_',' ',substr($tag,1));
1048                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
1049                                 if(strlen($str_tags))
1050                                         $str_tags .= ',';
1051                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1052                                 continue;
1053                         }
1054                 }
1055         }
1056
1057         $plink = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1).'/posts/'.$guid;
1058
1059         $datarray['uid'] = $importer['uid'];
1060         $datarray['contact-id'] = $contact['id'];
1061         $datarray['wall'] = 0;
1062         $datarray['network']  = NETWORK_DIASPORA;
1063         $datarray['guid'] = $guid;
1064         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1065         $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1066         $datarray['private'] = $private;
1067         $datarray['parent'] = 0;
1068         $datarray['plink'] = $plink;
1069         $datarray['owner-name'] = $contact['name'];
1070         $datarray['owner-link'] = $contact['url'];
1071         $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1072         if (!intval(get_config('system','wall-to-wall_share'))) {
1073                 $prefix = "[share author='".str_replace(array("'", "[", "]"), array("&#x27;", "&#x5B;", "&#x5D;"),$person['name']).
1074                                 "' profile='".$person['url'].
1075                                 "' avatar='".((x($person,'thumb')) ? $person['thumb'] : $person['photo']).
1076                                 "' link='".str_replace(array("'", "[", "]"), array("&#x27;", "&#x5B;", "&#x5D;"),$orig_url)."']";
1077                 $datarray['author-name'] = $contact['name'];
1078                 $datarray['author-link'] = $contact['url'];
1079                 $datarray['author-avatar'] = $contact['thumb'];
1080                 $datarray['body'] = $prefix.$body."[/share]";
1081         } else {
1082                 // Let reshared messages look like wall-to-wall posts
1083                 $datarray['author-name'] = $person['name'];
1084                 $datarray['author-link'] = $person['url'];
1085                 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1086                 $datarray['body'] = $body;
1087         }
1088
1089         $datarray['tag'] = $str_tags;
1090         $datarray['app']  = 'Diaspora';
1091
1092         // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible. (testing)
1093         $datarray['visible'] = ((strlen($body)) ? 1 : 0);
1094
1095         $message_id = item_store($datarray);
1096
1097         //if($message_id) {
1098         //      q("update item set plink = '%s' where id = %d",
1099         //              dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1100         //              intval($message_id)
1101         //      );
1102         //}
1103
1104         return;
1105
1106 }
1107
1108
1109 function diaspora_asphoto($importer,$xml,$msg) {
1110         logger('diaspora_asphoto called');
1111
1112         $a = get_app();
1113         $guid = notags(unxmlify($xml->guid));
1114         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1115
1116         if($diaspora_handle != $msg['author']) {
1117                 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1118                 return 202;
1119         }
1120
1121         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1122         if(! $contact)
1123                 return;
1124
1125         if(! diaspora_post_allow($importer,$contact)) {
1126                 logger('diaspora_asphoto: Ignoring this author.');
1127                 return 202;
1128         }
1129
1130         $message_id = $diaspora_handle . ':' . $guid;
1131         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
1132                 intval($importer['uid']),
1133                 dbesc($message_id),
1134                 dbesc($guid)
1135         );
1136         if(count($r)) {
1137                 logger('diaspora_asphoto: message exists: ' . $guid);
1138                 return;
1139         }
1140
1141         // allocate a guid on our system - we aren't fixing any collisions.
1142         // we're ignoring them
1143
1144         $g = q("select * from guid where guid = '%s' limit 1",
1145                 dbesc($guid)
1146         );
1147         if(! count($g)) {
1148                 q("insert into guid ( guid ) values ( '%s' )",
1149                         dbesc($guid)
1150                 );
1151         }
1152
1153         $created = unxmlify($xml->created_at);
1154         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1155
1156         if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
1157                 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
1158                 $body = scale_external_images($body,false);
1159         }
1160         elseif($xml->image_url) {
1161                 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
1162                 $body = scale_external_images($body);
1163         }
1164         else {
1165                 logger('diaspora_asphoto: no photo url found.');
1166                 return;
1167         }
1168
1169         $plink = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1).'/posts/'.$guid;
1170
1171         $datarray = array();
1172
1173         $datarray['uid'] = $importer['uid'];
1174         $datarray['contact-id'] = $contact['id'];
1175         $datarray['wall'] = 0;
1176         $datarray['network']  = NETWORK_DIASPORA;
1177         $datarray['guid'] = $guid;
1178         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1179         $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1180         $datarray['private'] = $private;
1181         $datarray['parent'] = 0;
1182         $datarray['plink'] = $plink;
1183         $datarray['owner-name'] = $contact['name'];
1184         $datarray['owner-link'] = $contact['url'];
1185         //$datarray['owner-avatar'] = $contact['thumb'];
1186         $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1187         $datarray['author-name'] = $contact['name'];
1188         $datarray['author-link'] = $contact['url'];
1189         $datarray['author-avatar'] = $contact['thumb'];
1190         $datarray['body'] = $body;
1191
1192         $datarray['app']  = 'Diaspora/Cubbi.es';
1193
1194         $message_id = item_store($datarray);
1195
1196         //if($message_id) {
1197         //      q("update item set plink = '%s' where id = %d",
1198         //              dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1199         //              intval($message_id)
1200         //      );
1201         //}
1202
1203         return;
1204
1205 }
1206
1207
1208
1209
1210
1211
1212 function diaspora_comment($importer,$xml,$msg) {
1213
1214         $a = get_app();
1215         $guid = notags(unxmlify($xml->guid));
1216         $parent_guid = notags(unxmlify($xml->parent_guid));
1217         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1218         $target_type = notags(unxmlify($xml->target_type));
1219         $text = unxmlify($xml->text);
1220         $author_signature = notags(unxmlify($xml->author_signature));
1221
1222         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1223
1224         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1225         if(! $contact) {
1226                 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
1227                 return;
1228         }
1229
1230         if(! diaspora_post_allow($importer,$contact)) {
1231                 logger('diaspora_comment: Ignoring this author.');
1232                 return 202;
1233         }
1234
1235         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1236                 intval($importer['uid']),
1237                 dbesc($guid)
1238         );
1239         if(count($r)) {
1240                 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
1241                 return;
1242         }
1243
1244         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1245                 intval($importer['uid']),
1246                 dbesc($parent_guid)
1247         );
1248         if(! count($r)) {
1249                 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1250                 return;
1251         }
1252         $parent_item = $r[0];
1253
1254
1255         /* How Diaspora performs comment signature checking:
1256
1257            - If an item has been sent by the comment author to the top-level post owner to relay on
1258              to the rest of the contacts on the top-level post, the top-level post owner should check
1259              the author_signature, then create a parent_author_signature before relaying the comment on
1260            - If an item has been relayed on by the top-level post owner, the contacts who receive it
1261              check only the parent_author_signature. Basically, they trust that the top-level post
1262              owner has already verified the authenticity of anything he/she sends out
1263            - In either case, the signature that get checked is the signature created by the person
1264              who sent the salmon
1265         */
1266
1267         $signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1268         $key = $msg['key'];
1269
1270         if($parent_author_signature) {
1271                 // If a parent_author_signature exists, then we've received the comment
1272                 // relayed from the top-level post owner. There's no need to check the
1273                 // author_signature if the parent_author_signature is valid
1274
1275                 $parent_author_signature = base64_decode($parent_author_signature);
1276
1277                 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1278                         logger('diaspora_comment: top-level owner verification failed.');
1279                         return;
1280                 }
1281         }
1282         else {
1283                 // If there's no parent_author_signature, then we've received the comment
1284                 // from the comment creator. In that case, the person is commenting on
1285                 // our post, so he/she must be a contact of ours and his/her public key
1286                 // should be in $msg['key']
1287
1288                 $author_signature = base64_decode($author_signature);
1289
1290                 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1291                         logger('diaspora_comment: comment author verification failed.');
1292                         return;
1293                 }
1294         }
1295
1296         // Phew! Everything checks out. Now create an item.
1297
1298         // Find the original comment author information.
1299         // We need this to make sure we display the comment author
1300         // information (name and avatar) correctly.
1301         if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1302                 $person = $contact;
1303         else {
1304                 $person = find_diaspora_person_by_handle($diaspora_handle);
1305
1306                 if(! is_array($person)) {
1307                         logger('diaspora_comment: unable to find author details');
1308                         return;
1309                 }
1310         }
1311
1312         $body = diaspora2bb($text);
1313         $message_id = $diaspora_handle . ':' . $guid;
1314
1315         $datarray = array();
1316
1317         $str_tags = '';
1318
1319         $tags = get_tags($body);
1320
1321         if(count($tags)) {
1322                 foreach($tags as $tag) {
1323                         if(strpos($tag,'#') === 0) {
1324                                 if(strpos($tag,'[url='))
1325                                         continue;
1326
1327                                 // don't link tags that are already embedded in links
1328
1329                                 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
1330                                         continue;
1331                                 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
1332                                         continue;
1333
1334
1335                                 $basetag = str_replace('_',' ',substr($tag,1));
1336                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
1337                                 if(strlen($str_tags))
1338                                         $str_tags .= ',';
1339                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1340                                 continue;
1341                         }
1342                 }
1343         }
1344
1345         $datarray['uid'] = $importer['uid'];
1346         $datarray['contact-id'] = $contact['id'];
1347         $datarray['type'] = 'remote-comment';
1348         $datarray['wall'] = $parent_item['wall'];
1349         $datarray['network']  = NETWORK_DIASPORA;
1350         $datarray['verb'] = ACTIVITY_POST;
1351         $datarray['gravity'] = GRAVITY_COMMENT;
1352         $datarray['guid'] = $guid;
1353         $datarray['uri'] = $message_id;
1354         $datarray['parent-uri'] = $parent_item['uri'];
1355
1356         // No timestamps for comments? OK, we'll the use current time.
1357         $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert();
1358         $datarray['private'] = $parent_item['private'];
1359
1360         $datarray['owner-name'] = $parent_item['owner-name'];
1361         $datarray['owner-link'] = $parent_item['owner-link'];
1362         $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1363
1364         $datarray['author-name'] = $person['name'];
1365         $datarray['author-link'] = $person['url'];
1366         $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1367         $datarray['body'] = $body;
1368         $datarray['tag'] = $str_tags;
1369
1370         // We can't be certain what the original app is if the message is relayed.
1371         if(($parent_item['origin']) && (! $parent_author_signature))
1372                 $datarray['app']  = 'Diaspora';
1373
1374         $message_id = item_store($datarray);
1375
1376         //if($message_id) {
1377                 //q("update item set plink = '%s' where id = %d",
1378                 //      //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1379                 //      dbesc($a->get_baseurl().'/display/'.$datarray['guid']),
1380                 //      intval($message_id)
1381                 //);
1382         //}
1383
1384         if(($parent_item['origin']) && (! $parent_author_signature)) {
1385                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1386                         intval($message_id),
1387                         dbesc($signed_data),
1388                         dbesc(base64_encode($author_signature)),
1389                         dbesc($diaspora_handle)
1390                 );
1391
1392                 // if the message isn't already being relayed, notify others
1393                 // the existence of parent_author_signature means the parent_author or owner
1394                 // is already relaying.
1395
1396                 proc_run('php','include/notifier.php','comment-import',$message_id);
1397         }
1398
1399         $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0 ",
1400                 dbesc($parent_item['uri']),
1401                 intval($importer['uid'])
1402         );
1403
1404         if(count($myconv)) {
1405                 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
1406
1407                 foreach($myconv as $conv) {
1408
1409                         // now if we find a match, it means we're in this conversation
1410
1411                         if(! link_compare($conv['author-link'],$importer_url))
1412                                 continue;
1413
1414                         require_once('include/enotify.php');
1415
1416                         $conv_parent = $conv['parent'];
1417
1418                         notification(array(
1419                                 'type'         => NOTIFY_COMMENT,
1420                                 'notify_flags' => $importer['notify-flags'],
1421                                 'language'     => $importer['language'],
1422                                 'to_name'      => $importer['username'],
1423                                 'to_email'     => $importer['email'],
1424                                 'uid'          => $importer['uid'],
1425                                 'item'         => $datarray,
1426                                 'link'             => $a->get_baseurl().'/display/'.urlencode($datarray['guid']),
1427                                 'source_name'  => $datarray['author-name'],
1428                                 'source_link'  => $datarray['author-link'],
1429                                 'source_photo' => $datarray['author-avatar'],
1430                                 'verb'         => ACTIVITY_POST,
1431                                 'otype'        => 'item',
1432                                 'parent'       => $conv_parent,
1433                                 'parent_uri'   => $parent_uri
1434                         ));
1435
1436                         // only send one notification
1437                         break;
1438                 }
1439         }
1440         return;
1441 }
1442
1443
1444
1445
1446 function diaspora_conversation($importer,$xml,$msg) {
1447
1448         $a = get_app();
1449
1450         $guid = notags(unxmlify($xml->guid));
1451         $subject = notags(unxmlify($xml->subject));
1452         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1453         $participant_handles = notags(unxmlify($xml->participant_handles));
1454         $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1455
1456         $parent_uri = $diaspora_handle . ':' . $guid;
1457  
1458         $messages = $xml->message;
1459
1460         if(! count($messages)) {
1461                 logger('diaspora_conversation: empty conversation');
1462                 return;
1463         }
1464
1465         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1466         if(! $contact) {
1467                 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1468                 return;
1469         }
1470
1471         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
1472                 logger('diaspora_conversation: Ignoring this author.');
1473                 return 202;
1474         }
1475
1476         $conversation = null;
1477
1478         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1479                 intval($importer['uid']),
1480                 dbesc($guid)
1481         );
1482         if(count($c))
1483                 $conversation = $c[0];
1484         else {
1485                 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1486                         intval($importer['uid']),
1487                         dbesc($guid),
1488                         dbesc($diaspora_handle),
1489                         dbesc(datetime_convert('UTC','UTC',$created_at)),
1490                         dbesc(datetime_convert()),
1491                         dbesc($subject),
1492                         dbesc($participant_handles)
1493                 );
1494                 if($r)
1495                         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1496                 intval($importer['uid']),
1497             dbesc($guid)
1498         );
1499             if(count($c))
1500             $conversation = $c[0];
1501         }
1502         if(! $conversation) {
1503                 logger('diaspora_conversation: unable to create conversation.');
1504                 return;
1505         }
1506
1507         foreach($messages as $mesg) {
1508
1509                 $reply = 0;
1510
1511                 $msg_guid = notags(unxmlify($mesg->guid));
1512                 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1513                 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1514                 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1515                 $msg_text = unxmlify($mesg->text);
1516                 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1517                 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1518                 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1519                 if($msg_conversation_guid != $guid) {
1520                         logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1521                         continue;
1522                 }
1523
1524                 $body = diaspora2bb($msg_text);
1525                 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1526
1527                 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1528
1529                 $author_signature = base64_decode($msg_author_signature);
1530
1531                 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1532                         $person = $contact;
1533                         $key = $msg['key'];
1534                 }
1535                 else {
1536                         $person = find_diaspora_person_by_handle($msg_diaspora_handle); 
1537
1538                         if(is_array($person) && x($person,'pubkey'))
1539                                 $key = $person['pubkey'];
1540                         else {
1541                                 logger('diaspora_conversation: unable to find author details');
1542                                 continue;
1543                         }
1544                 }
1545
1546                 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1547                         logger('diaspora_conversation: verification failed.');
1548                         continue;
1549                 }
1550
1551                 if($msg_parent_author_signature) {
1552                         $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1553
1554                         $parent_author_signature = base64_decode($msg_parent_author_signature);
1555
1556                         $key = $msg['key'];
1557
1558                         if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1559                                 logger('diaspora_conversation: owner verification failed.');
1560                                 continue;
1561                         }
1562                 }
1563
1564                 $r = q("select id from mail where `uri` = '%s' limit 1",
1565                         dbesc($message_id)
1566                 );
1567                 if(count($r)) {
1568                         logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1569                         continue;
1570                 }
1571
1572                 q("insert into mail ( `uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`) values ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1573                         intval($importer['uid']),
1574                         dbesc($msg_guid),
1575                         intval($conversation['id']),
1576                         dbesc($person['name']),
1577                         dbesc($person['photo']),
1578                         dbesc($person['url']),
1579                         intval($contact['id']),  
1580                         dbesc($subject),
1581                         dbesc($body),
1582                         0,
1583                         0,
1584                         dbesc($message_id),
1585                         dbesc($parent_uri),
1586                         dbesc($msg_created_at)
1587                 );
1588
1589                 q("update conv set updated = '%s' where id = %d",
1590                         dbesc(datetime_convert()),
1591                         intval($conversation['id'])
1592                 );
1593
1594                 require_once('include/enotify.php');
1595                 notification(array(
1596                         'type' => NOTIFY_MAIL,
1597                         'notify_flags' => $importer['notify-flags'],
1598                         'language' => $importer['language'],
1599                         'to_name' => $importer['username'],
1600                         'to_email' => $importer['email'],
1601                         'uid' =>$importer['importer_uid'],
1602                         'item' => array('subject' => $subject, 'body' => $body),
1603                         'source_name' => $person['name'],
1604                         'source_link' => $person['url'],
1605                         'source_photo' => $person['thumb'],
1606                         'verb' => ACTIVITY_POST,
1607                         'otype' => 'mail'
1608                 ));
1609         }
1610
1611         return;
1612 }
1613
1614 function diaspora_message($importer,$xml,$msg) {
1615
1616         $a = get_app();
1617
1618         $msg_guid = notags(unxmlify($xml->guid));
1619         $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1620         $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1621         $msg_author_signature = notags(unxmlify($xml->author_signature));
1622         $msg_text = unxmlify($xml->text);
1623         $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1624         $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1625         $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1626
1627         $parent_uri = $diaspora_handle . ':' . $msg_parent_guid;
1628  
1629         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1630         if(! $contact) {
1631                 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1632                 return;
1633         }
1634
1635         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
1636                 logger('diaspora_message: Ignoring this author.');
1637                 return 202;
1638         }
1639
1640         $conversation = null;
1641
1642         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1643                 intval($importer['uid']),
1644                 dbesc($msg_conversation_guid)
1645         );
1646         if(count($c))
1647                 $conversation = $c[0];
1648         else {
1649                 logger('diaspora_message: conversation not available.');
1650                 return;
1651         }
1652
1653         $reply = 0;
1654
1655         $body = diaspora2bb($msg_text);
1656         $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1657
1658         $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1659
1660
1661         $author_signature = base64_decode($msg_author_signature);
1662
1663         $person = find_diaspora_person_by_handle($msg_diaspora_handle); 
1664         if(is_array($person) && x($person,'pubkey'))
1665                 $key = $person['pubkey'];
1666         else {
1667                 logger('diaspora_message: unable to find author details');
1668                 return;
1669         }
1670
1671         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1672                 logger('diaspora_message: verification failed.');
1673                 return;
1674         }
1675
1676         $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1677                 dbesc($message_id),
1678                 intval($importer['uid'])
1679         );
1680         if(count($r)) {
1681                 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1682                 return;
1683         }
1684
1685         q("insert into mail ( `uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`) values ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1686                 intval($importer['uid']),
1687                 dbesc($msg_guid),
1688                 intval($conversation['id']),
1689                 dbesc($person['name']),
1690                 dbesc($person['photo']),
1691                 dbesc($person['url']),
1692                 intval($contact['id']),  
1693                 dbesc($conversation['subject']),
1694                 dbesc($body),
1695                 0,
1696                 1,
1697                 dbesc($message_id),
1698                 dbesc($parent_uri),
1699                 dbesc($msg_created_at)
1700         );
1701
1702         q("update conv set updated = '%s' where id = %d",
1703                 dbesc(datetime_convert()),
1704                 intval($conversation['id'])
1705         );
1706
1707         return;
1708 }
1709
1710
1711 function diaspora_photo($importer,$xml,$msg,$attempt=1) {
1712
1713         $a = get_app();
1714
1715         logger('diaspora_photo: init',LOGGER_DEBUG);
1716
1717         $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1718
1719         $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1720
1721         $status_message_guid = notags(unxmlify($xml->status_message_guid));
1722
1723         $guid = notags(unxmlify($xml->guid));
1724
1725         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1726
1727         $public = notags(unxmlify($xml->public));
1728
1729         $created_at = notags(unxmlify($xml_created_at));
1730
1731         logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1732
1733         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1734         if(! $contact) {
1735                 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1736                 return;
1737         }
1738
1739         if(! diaspora_post_allow($importer,$contact)) {
1740                 logger('diaspora_photo: Ignoring this author.');
1741                 return 202;
1742         }
1743
1744         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1745                 intval($importer['uid']),
1746                 dbesc($status_message_guid)
1747         );
1748         if(! count($r)) {
1749                 if($attempt <= 3) {
1750                         q("INSERT INTO dsprphotoq (uid, msg, attempt) VALUES (%d, '%s', %d)",
1751                            intval($importer['uid']),
1752                            dbesc(serialize($msg)),
1753                            intval($attempt + 1)
1754                         );
1755                 }
1756                 logger('diaspora_photo: attempt = ' . $attempt . '; status message not found: ' . $status_message_guid . ' for photo: ' . $guid);
1757                 return;
1758         }
1759
1760         $parent_item = $r[0];
1761
1762         $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1763
1764         $link_text = scale_external_images($link_text, true,
1765                                            array($remote_photo_name, 'scaled_full_' . $remote_photo_name));
1766
1767         if(strpos($parent_item['body'],$link_text) === false) {
1768                 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d",
1769                         dbesc($link_text . $parent_item['body']),
1770                         intval($parent_item['id']),
1771                         intval($parent_item['uid'])
1772                 );
1773         }
1774
1775         return;
1776 }
1777
1778
1779
1780
1781 function diaspora_like($importer,$xml,$msg) {
1782
1783         $a = get_app();
1784         $guid = notags(unxmlify($xml->guid));
1785         $parent_guid = notags(unxmlify($xml->parent_guid));
1786         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1787         $target_type = notags(unxmlify($xml->target_type));
1788         $positive = notags(unxmlify($xml->positive));
1789         $author_signature = notags(unxmlify($xml->author_signature));
1790
1791         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1792
1793         // likes on comments not supported here and likes on photos not supported by Diaspora
1794
1795 //      if($target_type !== 'Post')
1796 //              return;
1797
1798         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1799         if(! $contact) {
1800                 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1801                 return;
1802         }
1803
1804         if(! diaspora_post_allow($importer,$contact)) {
1805                 logger('diaspora_like: Ignoring this author.');
1806                 return 202;
1807         }
1808
1809         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1810                 intval($importer['uid']),
1811                 dbesc($parent_guid)
1812         );
1813         if(! count($r)) {
1814                 logger('diaspora_like: parent item not found: ' . $guid);
1815                 return;
1816         }
1817
1818         $parent_item = $r[0];
1819
1820         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1821                 intval($importer['uid']),
1822                 dbesc($guid)
1823         );
1824         if(count($r)) {
1825                 if($positive === 'true') {
1826                         logger('diaspora_like: duplicate like: ' . $guid);
1827                         return;
1828                 }
1829                 // Note: I don't think "Like" objects with positive = "false" are ever actually used
1830                 // It looks like "RelayableRetractions" are used for "unlike" instead
1831                 if($positive === 'false') {
1832                         logger('diaspora_like: received a like with positive set to "false"...ignoring');
1833 /*                      q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d",
1834                                 intval($r[0]['id']),
1835                                 intval($importer['uid'])
1836                         );*/
1837                         // FIXME--actually don't unless it turns out that Diaspora does indeed send out "false" likes
1838                         //  send notification via proc_run()
1839                         return;
1840                 }
1841         }
1842         // Note: I don't think "Like" objects with positive = "false" are ever actually used
1843         // It looks like "RelayableRetractions" are used for "unlike" instead
1844         if($positive === 'false') {
1845                 logger('diaspora_like: received a like with positive set to "false"');
1846                 logger('diaspora_like: unlike received with no corresponding like...ignoring');
1847                 return; 
1848         }
1849
1850
1851         /* How Diaspora performs "like" signature checking:
1852
1853            - If an item has been sent by the like author to the top-level post owner to relay on
1854              to the rest of the contacts on the top-level post, the top-level post owner should check
1855              the author_signature, then create a parent_author_signature before relaying the like on
1856            - If an item has been relayed on by the top-level post owner, the contacts who receive it
1857              check only the parent_author_signature. Basically, they trust that the top-level post
1858              owner has already verified the authenticity of anything he/she sends out
1859            - In either case, the signature that get checked is the signature created by the person
1860              who sent the salmon
1861         */
1862
1863         $signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1864         $key = $msg['key'];
1865
1866         if($parent_author_signature) {
1867                 // If a parent_author_signature exists, then we've received the like
1868                 // relayed from the top-level post owner. There's no need to check the
1869                 // author_signature if the parent_author_signature is valid
1870
1871                 $parent_author_signature = base64_decode($parent_author_signature);
1872
1873                 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1874                         if (intval(get_config('system','ignore_diaspora_like_signature')))
1875                                 logger('diaspora_like: top-level owner verification failed. Proceeding anyway.');
1876                         else {
1877                                 logger('diaspora_like: top-level owner verification failed.');
1878                                 return;
1879                         }
1880                 }
1881         }
1882         else {
1883                 // If there's no parent_author_signature, then we've received the like
1884                 // from the like creator. In that case, the person is "like"ing
1885                 // our post, so he/she must be a contact of ours and his/her public key
1886                 // should be in $msg['key']
1887
1888                 $author_signature = base64_decode($author_signature);
1889
1890                 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1891                         if (intval(get_config('system','ignore_diaspora_like_signature')))
1892                                 logger('diaspora_like: like creator verification failed. Proceeding anyway');
1893                         else {
1894                                 logger('diaspora_like: like creator verification failed.');
1895                                 return;
1896                         }
1897                 }
1898         }
1899
1900         // Phew! Everything checks out. Now create an item.
1901
1902         // Find the original comment author information.
1903         // We need this to make sure we display the comment author
1904         // information (name and avatar) correctly.
1905         if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1906                 $person = $contact;
1907         else {
1908                 $person = find_diaspora_person_by_handle($diaspora_handle);
1909
1910                 if(! is_array($person)) {
1911                         logger('diaspora_like: unable to find author details');
1912                         return;
1913                 }
1914         }
1915
1916         $uri = $diaspora_handle . ':' . $guid;
1917
1918         $activity = ACTIVITY_LIKE;
1919         $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
1920         $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE ); 
1921         $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
1922         $body = $parent_item['body'];
1923
1924         $obj = <<< EOT
1925
1926         <object>
1927                 <type>$objtype</type>
1928                 <local>1</local>
1929                 <id>{$parent_item['uri']}</id>
1930                 <link>$link</link>
1931                 <title></title>
1932                 <content>$body</content>
1933         </object>
1934 EOT;
1935         $bodyverb = t('%1$s likes %2$s\'s %3$s');
1936
1937         $arr = array();
1938
1939         $arr['uri'] = $uri;
1940         $arr['uid'] = $importer['uid'];
1941         $arr['guid'] = $guid;
1942         $arr['network']  = NETWORK_DIASPORA;
1943         $arr['contact-id'] = $contact['id'];
1944         $arr['type'] = 'activity';
1945         $arr['wall'] = $parent_item['wall'];
1946         $arr['gravity'] = GRAVITY_LIKE;
1947         $arr['parent'] = $parent_item['id'];
1948         $arr['parent-uri'] = $parent_item['uri'];
1949
1950         $arr['owner-name'] = $parent_item['name'];
1951         $arr['owner-link'] = $parent_item['url'];
1952         //$arr['owner-avatar'] = $parent_item['thumb'];
1953         $arr['owner-avatar'] = ((x($parent_item,'thumb')) ? $parent_item['thumb'] : $parent_item['photo']);
1954
1955         $arr['author-name'] = $person['name'];
1956         $arr['author-link'] = $person['url'];
1957         $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1958
1959         $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1960         $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1961         //$plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1962         $plink = '[url='.$a->get_baseurl().'/display/'.urlencode($guid).']'.$post_type.'[/url]';
1963         $arr['body'] =  sprintf( $bodyverb, $ulink, $alink, $plink );
1964
1965         $arr['app']  = 'Diaspora';
1966
1967         $arr['private'] = $parent_item['private'];
1968         $arr['verb'] = $activity;
1969         $arr['object-type'] = $objtype;
1970         $arr['object'] = $obj;
1971         $arr['visible'] = 1;
1972         $arr['unseen'] = 1;
1973         $arr['last-child'] = 0;
1974
1975         $message_id = item_store($arr);
1976
1977
1978         //if($message_id) {
1979         //      q("update item set plink = '%s' where id = %d",
1980         //              //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1981         //              dbesc($a->get_baseurl().'/display/'.$guid),
1982         //              intval($message_id)
1983         //      );
1984         //}
1985
1986         if(! $parent_author_signature) {
1987                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1988                         intval($message_id),
1989                         dbesc($signed_data),
1990                         dbesc(base64_encode($author_signature)),
1991                         dbesc($diaspora_handle)
1992                 );
1993         }
1994
1995         // if the message isn't already being relayed, notify others
1996         // the existence of parent_author_signature means the parent_author or owner
1997         // is already relaying. The parent_item['origin'] indicates the message was created on our system
1998
1999         if(($parent_item['origin']) && (! $parent_author_signature))
2000                 proc_run('php','include/notifier.php','comment-import',$message_id);
2001
2002         return;
2003 }
2004
2005 function diaspora_retraction($importer,$xml) {
2006
2007
2008         $guid = notags(unxmlify($xml->guid));
2009         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2010         $type = notags(unxmlify($xml->type));
2011
2012         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2013         if(! $contact)
2014                 return;
2015
2016         if($type === 'Person') {
2017                 require_once('include/Contact.php');
2018                 contact_remove($contact['id']);
2019         }
2020         elseif($type === 'Post') {
2021                 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2022                         dbesc('guid'),
2023                         intval($importer['uid'])
2024                 );
2025                 if(count($r)) {
2026                         if(link_compare($r[0]['author-link'],$contact['url'])) {
2027                                 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d",
2028                                         dbesc(datetime_convert()),
2029                                         intval($r[0]['id'])
2030                                 );
2031                                 delete_thread($r[0]['id']);
2032                         }
2033                 }
2034         }
2035
2036         return 202;
2037         // NOTREACHED
2038 }
2039
2040 function diaspora_signed_retraction($importer,$xml,$msg) {
2041
2042
2043         $guid = notags(unxmlify($xml->target_guid));
2044         $diaspora_handle = notags(unxmlify($xml->sender_handle));
2045         $type = notags(unxmlify($xml->target_type));
2046         $sig = notags(unxmlify($xml->target_author_signature));
2047
2048         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
2049
2050         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2051         if(! $contact) {
2052                 logger('diaspora_signed_retraction: no contact ' . $diaspora_handle . ' for ' . $importer['uid']);
2053                 return;
2054         }
2055
2056
2057         $signed_data = $guid . ';' . $type ;
2058         $key = $msg['key'];
2059
2060         /* How Diaspora performs relayable_retraction signature checking:
2061
2062            - If an item has been sent by the item author to the top-level post owner to relay on
2063              to the rest of the contacts on the top-level post, the top-level post owner checks
2064              the author_signature, then creates a parent_author_signature before relaying the item on
2065            - If an item has been relayed on by the top-level post owner, the contacts who receive it
2066              check only the parent_author_signature. Basically, they trust that the top-level post
2067              owner has already verified the authenticity of anything he/she sends out
2068            - In either case, the signature that get checked is the signature created by the person
2069              who sent the salmon
2070         */
2071
2072         if($parent_author_signature) {
2073
2074                 $parent_author_signature = base64_decode($parent_author_signature);
2075
2076                 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
2077                         logger('diaspora_signed_retraction: top-level post owner verification failed');
2078                         return;
2079                 }
2080
2081         }
2082         else {
2083
2084                 $sig_decode = base64_decode($sig);
2085
2086                 if(! rsa_verify($signed_data,$sig_decode,$key,'sha256')) {
2087                         logger('diaspora_signed_retraction: retraction owner verification failed.' . print_r($msg,true));
2088                         return;
2089                 }
2090         }
2091
2092         if($type === 'StatusMessage' || $type === 'Comment' || $type === 'Like') {
2093                 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2094                         dbesc($guid),
2095                         intval($importer['uid'])
2096                 );
2097                 if(count($r)) {
2098                         if(link_compare($r[0]['author-link'],$contact['url'])) {
2099                                 q("update item set `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' where `id` = %d",
2100                                         dbesc(datetime_convert()),
2101                                         dbesc(datetime_convert()),
2102                                         intval($r[0]['id'])
2103                                 );
2104                                 delete_thread($r[0]['id']);
2105
2106                                 // Now check if the retraction needs to be relayed by us
2107                                 //
2108                                 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2109                                 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2110                                 // The only item with `parent` and `id` as the parent id is the parent item.
2111                                 $p = q("select origin from item where parent = %d and id = %d limit 1",
2112                                         $r[0]['parent'],
2113                                         $r[0]['parent']
2114                                 );
2115                                 if(count($p)) {
2116                                         if(($p[0]['origin']) && (! $parent_author_signature)) {
2117                                                 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2118                                                         $r[0]['id'],
2119                                                         dbesc($signed_data),
2120                                                         dbesc($sig),
2121                                                         dbesc($diaspora_handle)
2122                                                 );
2123
2124                                                 // the existence of parent_author_signature would have meant the parent_author or owner
2125                                                 // is already relaying.
2126                                                 logger('diaspora_signed_retraction: relaying relayable_retraction');
2127
2128                                                 proc_run('php','include/notifier.php','drop',$r[0]['id']);
2129                                         }
2130                                 }
2131                         }
2132                 }
2133         }
2134         else
2135                 logger('diaspora_signed_retraction: unknown type: ' . $type);
2136
2137         return 202;
2138         // NOTREACHED
2139 }
2140
2141 function diaspora_profile($importer,$xml,$msg) {
2142
2143         $a = get_app();
2144         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2145
2146
2147         if($diaspora_handle != $msg['author']) {
2148                 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
2149                 return 202;
2150         }
2151
2152         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2153         if(! $contact)
2154                 return;
2155
2156         if($contact['blocked']) {
2157                 logger('diaspora_post: Ignoring this author.');
2158                 return 202;
2159         }
2160
2161         $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
2162         $image_url = unxmlify($xml->image_url);
2163         $birthday = unxmlify($xml->birthday);
2164
2165
2166         $handle_parts = explode("@", $diaspora_handle);
2167         if($name === '') {
2168                 $name = $handle_parts[0];
2169         }
2170         
2171          
2172         if( preg_match("|^https?://|", $image_url) === 0) {
2173                 $image_url = "http://" . $handle_parts[1] . $image_url;
2174         }
2175
2176 /*      $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE  `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
2177                 intval($importer['uid']),
2178                 intval($contact['id'])
2179         );
2180         $oldphotos = ((count($r)) ? $r : null);*/
2181
2182         require_once('include/Photo.php');
2183
2184         $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
2185         
2186         // Generic birthday. We don't know the timezone. The year is irrelevant. 
2187
2188         $birthday = str_replace('1000','1901',$birthday);
2189
2190         $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
2191
2192         // this is to prevent multiple birthday notifications in a single year
2193         // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2194
2195         if(substr($birthday,5) === substr($contact['bd'],5))
2196                 $birthday = $contact['bd'];
2197
2198         // TODO: update name on item['author-name'] if the name changed. See consume_feed()
2199         // Not doing this currently because D* protocol is scheduled for revision soon. 
2200
2201         $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",
2202                 dbesc($name),
2203                 dbesc(datetime_convert()),
2204                 dbesc($images[0]),
2205                 dbesc($images[1]),
2206                 dbesc($images[2]),
2207                 dbesc(datetime_convert()),
2208                 dbesc($birthday),
2209                 intval($contact['id']),
2210                 intval($importer['uid'])
2211         ); 
2212
2213 /*      if($r) {
2214                 if($oldphotos) {
2215                         foreach($oldphotos as $ph) {
2216                                 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
2217                                         intval($importer['uid']),
2218                                         intval($contact['id']),
2219                                         dbesc($ph['resource-id'])
2220                                 );
2221                         }
2222                 }
2223         }       */
2224
2225         return;
2226
2227 }
2228
2229 function diaspora_share($me,$contact) {
2230         $a = get_app();
2231         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2232         $theiraddr = $contact['addr'];
2233
2234         $tpl = get_markup_template('diaspora_share.tpl');
2235         $msg = replace_macros($tpl, array(
2236                 '$sender' => $myaddr,
2237                 '$recipient' => $theiraddr
2238         ));
2239
2240         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2241         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2242
2243         return(diaspora_transmit($owner,$contact,$slap, false));
2244 }
2245
2246 function diaspora_unshare($me,$contact) {
2247
2248         $a = get_app();
2249         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2250
2251         $tpl = get_markup_template('diaspora_retract.tpl');
2252         $msg = replace_macros($tpl, array(
2253                 '$guid'   => $me['guid'],
2254                 '$type'   => 'Person',
2255                 '$handle' => $myaddr
2256         ));
2257
2258         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2259         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2260
2261         return(diaspora_transmit($owner,$contact,$slap, false));
2262
2263 }
2264
2265
2266 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
2267
2268         $a = get_app();
2269         $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2270         $theiraddr = $contact['addr'];
2271
2272         $images = array();
2273
2274         $title = $item['title'];
2275         $body = $item['body'];
2276
2277 /*
2278         // We're trying to match Diaspora's split message/photo protocol but
2279         // all the photos are displayed on D* as links and not img's - even
2280         // though we're sending pretty much precisely what they send us when
2281         // doing the same operation.  
2282         // Commented out for now, we'll use bb2diaspora to convert photos to markdown
2283         // which seems to get through intact.
2284
2285         $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
2286         if($cnt) {
2287                 foreach($matches as $mtch) {
2288                         $detail = array();
2289                         $detail['str'] = $mtch[0];
2290                         $detail['path'] = dirname($mtch[1]) . '/';
2291                         $detail['file'] = basename($mtch[1]);
2292                         $detail['guid'] = $item['guid'];
2293                         $detail['handle'] = $myaddr;
2294                         $images[] = $detail;
2295                         $body = str_replace($detail['str'],$mtch[1],$body);
2296                 }
2297         }
2298 */
2299
2300         //if(strlen($title))
2301         //      $body = "[b]".html_entity_decode($title)."[/b]\n\n".$body;
2302
2303         // convert to markdown
2304         $body = xmlify(html_entity_decode(bb2diaspora($body)));
2305         //$body = bb2diaspora($body);
2306
2307         // Adding the title
2308         if(strlen($title))
2309                 $body = "## ".html_entity_decode($title)."\n\n".$body;
2310
2311         if($item['attach']) {
2312                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
2313                 if(cnt) {
2314                         $body .= "\n" . t('Attachments:') . "\n";
2315                         foreach($matches as $mtch) {
2316                                 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
2317                         }
2318                 }
2319         }
2320
2321
2322         $public = (($item['private']) ? 'false' : 'true');
2323
2324         require_once('include/datetime.php');
2325         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2326
2327         // Detect a share element and do a reshare
2328         // see: https://github.com/Raven24/diaspora-federation/blob/master/lib/diaspora-federation/entities/reshare.rb
2329         if (!$item['private'] AND ($ret = diaspora_is_reshare($item["body"]))) {
2330                 $tpl = get_markup_template('diaspora_reshare.tpl');
2331                 $msg = replace_macros($tpl, array(
2332                         '$root_handle' => xmlify($ret['root_handle']),
2333                         '$root_guid' => $ret['root_guid'],
2334                         '$guid' => $item['guid'],
2335                         '$handle' => xmlify($myaddr),
2336                         '$public' => $public,
2337                         '$created' => $created,
2338                         '$provider' => $item["app"]
2339                 ));
2340         } else {
2341                 $tpl = get_markup_template('diaspora_post.tpl');
2342                 $msg = replace_macros($tpl, array(
2343                         '$body' => $body,
2344                         '$guid' => $item['guid'],
2345                         '$handle' => xmlify($myaddr),
2346                         '$public' => $public,
2347                         '$created' => $created,
2348                         '$provider' => $item["app"]
2349                 ));
2350         }
2351
2352         logger('diaspora_send_status: '.$owner['username'].' -> '.$contact['name'].' base message: '.$msg, LOGGER_DATA);
2353
2354         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2355         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2356
2357         $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
2358
2359         logger('diaspora_send_status: guid: '.$item['guid'].' result '.$return_code, LOGGER_DEBUG);
2360
2361         if(count($images)) {
2362                 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
2363         }
2364
2365         return $return_code;
2366 }
2367
2368 function diaspora_is_reshare($body) {
2369         $body = trim($body);
2370
2371         // Skip if it isn't a pure repeated messages
2372         // Does it start with a share?
2373         if (strpos($body, "[share") > 0)
2374                 return(false);
2375
2376         // Does it end with a share?
2377         if (strlen($body) > (strrpos($body, "[/share]") + 8))
2378                 return(false);
2379
2380         $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2381         // Skip if there is no shared message in there
2382         if ($body == $attributes)
2383                 return(false);
2384
2385         $profile = "";
2386         preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2387         if ($matches[1] != "")
2388                 $profile = $matches[1];
2389
2390         preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2391         if ($matches[1] != "")
2392                 $profile = $matches[1];
2393
2394         $ret= array();
2395
2396         $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2397         if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2398                 return(false);
2399
2400         $link = "";
2401         preg_match("/link='(.*?)'/ism", $attributes, $matches);
2402         if ($matches[1] != "")
2403                 $link = $matches[1];
2404
2405         preg_match('/link="(.*?)"/ism', $attributes, $matches);
2406         if ($matches[1] != "")
2407                 $link = $matches[1];
2408
2409         $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2410         if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2411                 return(false);
2412
2413         return($ret);
2414 }
2415
2416 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
2417         $a = get_app();
2418         if(! count($images))
2419                 return;
2420         $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
2421
2422         $tpl = get_markup_template('diaspora_photo.tpl');
2423         foreach($images as $image) {
2424                 if(! stristr($image['path'],$mysite))
2425                         continue;
2426                 $resource = str_replace('.jpg','',$image['file']);
2427                 $resource = substr($resource,0,strpos($resource,'-'));
2428
2429                 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
2430                         dbesc($resource),
2431                         intval($owner['uid'])
2432                 );
2433                 if(! count($r))
2434                         continue;
2435                 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
2436                 $msg = replace_macros($tpl,array(
2437                         '$path' => xmlify($image['path']),
2438                         '$filename' => xmlify($image['file']),
2439                         '$msg_guid' => xmlify($image['guid']),
2440                         '$guid' => xmlify($r[0]['guid']),
2441                         '$handle' => xmlify($image['handle']),
2442                         '$public' => xmlify($public),
2443                         '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
2444                 ));
2445
2446
2447                 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
2448                 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2449                 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2450
2451                 diaspora_transmit($owner,$contact,$slap,$public_batch);
2452         }
2453
2454 }
2455
2456 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
2457
2458         $a = get_app();
2459         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2460 //      $theiraddr = $contact['addr'];
2461
2462         // Diaspora doesn't support threaded comments, but some
2463         // versions of Diaspora (i.e. Diaspora-pistos) support
2464         // likes on comments
2465         if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2466                 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2467                         dbesc($item['thr-parent'])
2468                       );
2469         }
2470         else {
2471                 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2472                 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2473                 // The only item with `parent` and `id` as the parent id is the parent item.
2474                 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2475                         intval($item['parent']),
2476                         intval($item['parent'])
2477                 );
2478         }
2479         if(count($p))
2480                 $parent = $p[0];
2481         else
2482                 return;
2483
2484         if($item['verb'] === ACTIVITY_LIKE) {
2485                 $tpl = get_markup_template('diaspora_like.tpl');
2486                 $like = true;
2487                 $target_type = ( $parent['uri'] === $parent['parent-uri']  ? 'Post' : 'Comment');
2488 //              $target_type = (strpos($parent['type'], 'comment') ? 'Comment' : 'Post');
2489 //              $positive = (($item['deleted']) ? 'false' : 'true');
2490                 $positive = 'true';
2491
2492                 if(($item['deleted']))
2493                         logger('diaspora_send_followup: received deleted "like". Those should go to diaspora_send_retraction');
2494         }
2495         else {
2496                 $tpl = get_markup_template('diaspora_comment.tpl');
2497                 $like = false;
2498         }
2499
2500         $text = html_entity_decode(bb2diaspora($item['body']));
2501
2502         // sign it
2503
2504         if($like)
2505                 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $myaddr;
2506         else
2507                 $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $myaddr;
2508
2509         $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2510
2511         $msg = replace_macros($tpl,array(
2512                 '$guid' => xmlify($item['guid']),
2513                 '$parent_guid' => xmlify($parent['guid']),
2514                 '$target_type' =>xmlify($target_type),
2515                 '$authorsig' => xmlify($authorsig),
2516                 '$body' => xmlify($text),
2517                 '$positive' => xmlify($positive),
2518                 '$handle' => xmlify($myaddr)
2519         ));
2520
2521         logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2522
2523         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2524         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2525
2526         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2527 }
2528
2529
2530 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2531
2532
2533         $a = get_app();
2534         $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2535 //      $theiraddr = $contact['addr'];
2536
2537         $body = $item['body'];
2538         $text = html_entity_decode(bb2diaspora($body));
2539
2540         // Diaspora doesn't support threaded comments, but some
2541         // versions of Diaspora (i.e. Diaspora-pistos) support
2542         // likes on comments
2543         if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2544                 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2545                         dbesc($item['thr-parent'])
2546                       );
2547         }
2548         else {
2549                 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2550                 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2551                 // The only item with `parent` and `id` as the parent id is the parent item.
2552                 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2553                        intval($item['parent']),
2554                        intval($item['parent'])
2555                       );
2556         }
2557         if(count($p))
2558                 $parent = $p[0];
2559         else
2560                 return;
2561
2562         $like = false;
2563         $relay_retract = false;
2564         $sql_sign_id = 'iid';
2565         if( $item['deleted']) {
2566                 $relay_retract = true;
2567
2568                 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2569
2570                 $sql_sign_id = 'retract_iid';
2571                 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2572         }
2573         elseif($item['verb'] === ACTIVITY_LIKE) {
2574                 $like = true;
2575
2576                 $target_type = ( $parent['uri'] === $parent['parent-uri']  ? 'Post' : 'Comment');
2577 //              $positive = (($item['deleted']) ? 'false' : 'true');
2578                 $positive = 'true';
2579
2580                 $tpl = get_markup_template('diaspora_like_relay.tpl');
2581         }
2582         else { // item is a comment
2583                 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2584         }
2585
2586
2587         // fetch the original signature if the relayable was created by a Diaspora
2588         // or DFRN user. Relayables for other networks are not supported.
2589
2590 /*      $r = q("select * from sign where " . $sql_sign_id . " = %d limit 1",
2591                 intval($item['id'])
2592         );
2593         if(count($r)) { 
2594                 $orig_sign = $r[0];
2595                 $signed_text = $orig_sign['signed_text'];
2596                 $authorsig = $orig_sign['signature'];
2597                 $handle = $orig_sign['signer'];
2598         }
2599         else {
2600
2601                 // Author signature information (for likes, comments, and retractions of likes or comments,
2602                 // whether from Diaspora or Friendica) must be placed in the `sign` table before this 
2603                 // function is called
2604                 logger('diaspora_send_relay: original author signature not found, cannot send relayable');
2605                 return;
2606         }*/
2607
2608         /* Since the author signature is only checked by the parent, not by the relay recipients,
2609          * I think it may not be necessary for us to do so much work to preserve all the original
2610          * signatures. The important thing that Diaspora DOES need is the original creator's handle.
2611          * Let's just generate that and forget about all the original author signature stuff.
2612          *
2613          * Note: this might be more of an problem if we want to support likes on comments for older
2614          * versions of Diaspora (diaspora-pistos), but since there are a number of problems with
2615          * doing that, let's ignore it for now.
2616          *
2617          * Currently, only DFRN contacts are supported. StatusNet shouldn't be hard, but it hasn't
2618          * been done yet
2619          */
2620
2621         $handle = diaspora_handle_from_contact($item['contact-id']);
2622         if(! $handle)
2623                 return;
2624
2625
2626         if($relay_retract)
2627                 $sender_signed_text = $item['guid'] . ';' . $target_type;
2628         elseif($like)
2629                 $sender_signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle;
2630         else
2631                 $sender_signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle;
2632
2633         // Sign the relayable with the top-level owner's signature
2634         //
2635         // We'll use the $sender_signed_text that we just created, instead of the $signed_text
2636         // stored in the database, because that provides the best chance that Diaspora will
2637         // be able to reconstruct the signed text the same way we did. This is particularly a
2638         // concern for the comment, whose signed text includes the text of the comment. The
2639         // smallest change in the text of the comment, including removing whitespace, will
2640         // make the signature verification fail. Since we translate from BB code to Diaspora's
2641         // markup at the top of this function, which is AFTER we placed the original $signed_text
2642         // in the database, it's hazardous to trust the original $signed_text.
2643
2644         $parentauthorsig = base64_encode(rsa_sign($sender_signed_text,$owner['uprvkey'],'sha256'));
2645
2646         $msg = replace_macros($tpl,array(
2647                 '$guid' => xmlify($item['guid']),
2648                 '$parent_guid' => xmlify($parent['guid']),
2649                 '$target_type' =>xmlify($target_type),
2650                 '$authorsig' => xmlify($authorsig),
2651                 '$parentsig' => xmlify($parentauthorsig),
2652                 '$body' => xmlify($text),
2653                 '$positive' => xmlify($positive),
2654                 '$handle' => xmlify($handle)
2655         ));
2656
2657         logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DATA);
2658
2659
2660         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2661         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2662
2663         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2664
2665 }
2666
2667
2668
2669 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2670
2671         $a = get_app();
2672         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2673
2674         // Check whether the retraction is for a top-level post or whether it's a relayable
2675         if( $item['uri'] !== $item['parent-uri'] ) {
2676
2677                 $tpl = get_markup_template('diaspora_relay_retraction.tpl');
2678                 $target_type = (($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2679         }
2680         else {
2681                 
2682                 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2683                 $target_type = 'StatusMessage';
2684         }
2685
2686         $signed_text = $item['guid'] . ';' . $target_type;
2687
2688         $msg = replace_macros($tpl, array(
2689                 '$guid'   => xmlify($item['guid']),
2690                 '$type'   => xmlify($target_type),
2691                 '$handle' => xmlify($myaddr),
2692                 '$signature' => xmlify(base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')))
2693         ));
2694
2695         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2696         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2697
2698         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2699 }
2700
2701 function diaspora_send_mail($item,$owner,$contact) {
2702
2703         $a = get_app();
2704         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2705
2706         $r = q("select * from conv where id = %d and uid = %d limit 1",
2707                 intval($item['convid']),
2708                 intval($item['uid'])
2709         );
2710
2711         if(! count($r)) {
2712                 logger('diaspora_send_mail: conversation not found.');
2713                 return;
2714         }
2715         $cnv = $r[0];
2716
2717         $conv = array(
2718                 'guid' => xmlify($cnv['guid']),
2719                 'subject' => xmlify($cnv['subject']),
2720                 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
2721                 'diaspora_handle' => xmlify($cnv['creator']),
2722                 'participant_handles' => xmlify($cnv['recips'])
2723         );
2724
2725         $body = bb2diaspora($item['body']);
2726         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2727  
2728         $signed_text =  $item['guid'] . ';' . $cnv['guid'] . ';' . $body .  ';' 
2729                 . $created . ';' . $myaddr . ';' . $cnv['guid'];
2730
2731         $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2732
2733         $msg = array(
2734                 'guid' => xmlify($item['guid']),
2735                 'parent_guid' => xmlify($cnv['guid']),
2736                 'parent_author_signature' => (($item['reply']) ? null : xmlify($sig)),
2737                 'author_signature' => xmlify($sig),
2738                 'text' => xmlify($body),
2739                 'created_at' => xmlify($created),
2740                 'diaspora_handle' => xmlify($myaddr),
2741                 'conversation_guid' => xmlify($cnv['guid'])
2742         );
2743
2744         if($item['reply']) {
2745                 $tpl = get_markup_template('diaspora_message.tpl');
2746                 $xmsg = replace_macros($tpl, array('$msg' => $msg));
2747         }
2748         else {
2749                 $conv['messages'] = array($msg);
2750                 $tpl = get_markup_template('diaspora_conversation.tpl');
2751                 $xmsg = replace_macros($tpl, array('$conv' => $conv));
2752         }
2753
2754         logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
2755
2756         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
2757         //$slap = 'xml=' . urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false));
2758
2759         return(diaspora_transmit($owner,$contact,$slap,false));
2760
2761
2762 }
2763
2764 function diaspora_transmit($owner,$contact,$slap,$public_batch,$queue_run=false) {
2765
2766         $enabled = intval(get_config('system','diaspora_enabled'));
2767         if(! $enabled) {
2768                 return 200;
2769         }
2770
2771         $a = get_app();
2772         $logid = random_string(4);
2773         $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
2774         if(! $dest_url) {
2775                 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2776                 return 0;
2777         } 
2778
2779         logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
2780
2781         if( (! $queue_run) && (was_recently_delayed($contact['id'])) ) {
2782                 $return_code = 0;
2783         }
2784         else {
2785                 if (!intval(get_config('system','diaspora_test'))) {
2786                         post_url($dest_url . '/', $slap);
2787                         $return_code = $a->get_curl_code();
2788                 } else {
2789                         logger('diaspora_transmit: test_mode');
2790                         return 200;
2791                 }
2792         }
2793
2794         logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
2795
2796         if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
2797                 logger('diaspora_transmit: queue message');
2798
2799                 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
2800                         intval($contact['id']),
2801                         dbesc(NETWORK_DIASPORA),
2802                         dbesc($slap),
2803                         intval($public_batch)
2804                 );
2805                 if(count($r)) {
2806                         logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
2807                 }
2808                 else {
2809                         // queue message for redelivery
2810                         add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
2811                 }
2812         }
2813
2814
2815         return(($return_code) ? $return_code : (-1));
2816 }
2817
2818