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