Merge pull request #947 from nupplaphil/task/di_l10n
[friendica-addons.git/.git] / diaspora / diaspora.php
1 <?php
2
3 /**
4  * Name: Diaspora Post Connector
5  * Description: Post to Diaspora
6  * Version: 0.2
7  * Author: Michael Vogel <heluecht@pirati.ca>
8  */
9
10 require_once 'addon/diaspora/Diaspora_Connection.php';
11
12 use Friendica\App;
13 use Friendica\Content\Text\BBCode;
14 use Friendica\Core\Hook;
15 use Friendica\Core\Logger;
16 use Friendica\Database\DBA;
17 use Friendica\Core\Worker;
18 use Friendica\DI;
19
20 function diaspora_install()
21 {
22         Hook::register('hook_fork',               'addon/diaspora/diaspora.php', 'diaspora_hook_fork');
23         Hook::register('post_local',              'addon/diaspora/diaspora.php', 'diaspora_post_local');
24         Hook::register('notifier_normal',         'addon/diaspora/diaspora.php', 'diaspora_send');
25         Hook::register('jot_networks',            'addon/diaspora/diaspora.php', 'diaspora_jot_nets');
26         Hook::register('connector_settings',      'addon/diaspora/diaspora.php', 'diaspora_settings');
27         Hook::register('connector_settings_post', 'addon/diaspora/diaspora.php', 'diaspora_settings_post');
28 }
29
30 function diaspora_uninstall()
31 {
32         Hook::unregister('hook_fork',               'addon/diaspora/diaspora.php', 'diaspora_hook_fork');
33         Hook::unregister('post_local',              'addon/diaspora/diaspora.php', 'diaspora_post_local');
34         Hook::unregister('notifier_normal',         'addon/diaspora/diaspora.php', 'diaspora_send');
35         Hook::unregister('jot_networks',            'addon/diaspora/diaspora.php', 'diaspora_jot_nets');
36         Hook::unregister('connector_settings',      'addon/diaspora/diaspora.php', 'diaspora_settings');
37         Hook::unregister('connector_settings_post', 'addon/diaspora/diaspora.php', 'diaspora_settings_post');
38 }
39
40 function diaspora_jot_nets(App $a, array &$jotnets_fields)
41 {
42         if (!local_user()) {
43                 return;
44         }
45
46         if (DI::pConfig()->get(local_user(), 'diaspora', 'post')) {
47                 $jotnets_fields[] = [
48                         'type' => 'checkbox',
49                         'field' => [
50                                 'diaspora_enable',
51                                 DI::l10n()->t('Post to Diaspora'),
52                                 DI::pConfig()->get(local_user(), 'diaspora', 'post_by_default')
53                         ]
54                 ];
55         }
56 }
57
58 function diaspora_settings(App $a, &$s)
59 {
60         if (! local_user()) {
61                 return;
62         }
63
64         /* Add our stylesheet to the page so we can make our settings look nice */
65
66         DI::page()['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . DI::baseUrl()->get() . '/addon/diaspora/diaspora.css' . '" media="all" />' . "\r\n";
67
68         /* Get the current state of our config variables */
69
70         $enabled = DI::pConfig()->get(local_user(),'diaspora','post');
71         $checked = (($enabled) ? ' checked="checked" ' : '');
72         $css = (($enabled) ? '' : '-disabled');
73
74         $def_enabled = DI::pConfig()->get(local_user(),'diaspora','post_by_default');
75
76         $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
77
78         $handle = DI::pConfig()->get(local_user(), 'diaspora', 'handle');
79         $password = DI::pConfig()->get(local_user(), 'diaspora', 'password');
80         $aspect = DI::pConfig()->get(local_user(),'diaspora','aspect');
81
82         $status = "";
83
84         $r = q("SELECT `addr` FROM `contact` WHERE `self` AND `uid` = %d", intval(local_user()));
85
86         if (DBA::isResult($r)) {
87                 $status = DI::l10n()->t("Please remember: You can always be reached from Diaspora with your Friendica handle %s. ", $r[0]['addr']);
88                 $status .= DI::l10n()->t('This connector is only meant if you still want to use your old Diaspora account for some time. ');
89                 $status .= DI::l10n()->t('However, it is preferred that you tell your Diaspora contacts the new handle %s instead.', $r[0]['addr']);
90         }
91
92         $aspects = false;
93
94         if ($handle && $password) {
95                 $conn = new Diaspora_Connection($handle, $password);
96                 $conn->logIn();
97                 $aspects = $conn->getAspects();
98
99                 if (!$aspects) {
100                         $status = DI::l10n()->t("Can't login to your Diaspora account. Please check handle (in the format user@domain.tld) and password.");
101                 }
102         }
103
104         /* Add some HTML to the existing form */
105
106         $s .= '<span id="settings_diaspora_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_diaspora_expanded\'); openClose(\'settings_diaspora_inflated\');">';
107         $s .= '<img class="connector'.$css.'" src="images/diaspora-logo.png" /><h3 class="connector">'. DI::l10n()->t('Diaspora Export').'</h3>';
108         $s .= '</span>';
109         $s .= '<div id="settings_diaspora_expanded" class="settings-block" style="display: none;">';
110         $s .= '<span class="fakelink" onclick="openClose(\'settings_diaspora_expanded\'); openClose(\'settings_diaspora_inflated\');">';
111         $s .= '<img class="connector'.$css.'" src="images/diaspora-logo.png" /><h3 class="connector">'. DI::l10n()->t('Diaspora Export').'</h3>';
112         $s .= '</span>';
113
114         if ($status) {
115                 $s .= '<div id="diaspora-status-wrapper"><strong>';
116                 $s .= $status;
117                 $s .= '</strong></div><div class="clear"></div>';
118         }
119
120         $s .= '<div id="diaspora-enable-wrapper">';
121         $s .= '<label id="diaspora-enable-label" for="diaspora-checkbox">' . DI::l10n()->t('Enable Diaspora Post Addon') . '</label>';
122         $s .= '<input id="diaspora-checkbox" type="checkbox" name="diaspora" value="1" ' . $checked . '/>';
123         $s .= '</div><div class="clear"></div>';
124
125         $s .= '<div id="diaspora-username-wrapper">';
126         $s .= '<label id="diaspora-username-label" for="diaspora-username">' . DI::l10n()->t('Diaspora handle') . '</label>';
127         $s .= '<input id="diaspora-username" type="text" name="handle" value="' . $handle . '" />';
128         $s .= '</div><div class="clear"></div>';
129
130         $s .= '<div id="diaspora-password-wrapper">';
131         $s .= '<label id="diaspora-password-label" for="diaspora-password">' . DI::l10n()->t('Diaspora password') . '</label>';
132         $s .= '<input id="diaspora-password" type="password" name="password" value="' . $password . '" />';
133         $s .= '</div><div class="clear"></div>';
134
135         if ($aspects) {
136                 $single_aspect =  new stdClass();
137                 $single_aspect->id = 'all_aspects';
138                 $single_aspect->name = DI::l10n()->t('All aspects');
139                 $aspects[] = $single_aspect;
140
141                 $single_aspect =  new stdClass();
142                 $single_aspect->id = 'public';
143                 $single_aspect->name = DI::l10n()->t('Public');
144                 $aspects[] = $single_aspect;
145
146                 $s .= '<label id="diaspora-aspect-label" for="diaspora-aspect">' . DI::l10n()->t('Post to aspect:') . '</label>';
147                 $s .= '<select name="aspect" id="diaspora-aspect">';
148                 foreach($aspects as $single_aspect) {
149                         if ($single_aspect->id == $aspect)
150                                 $s .= "<option value='".$single_aspect->id."' selected>".$single_aspect->name."</option>";
151                         else
152                                 $s .= "<option value='".$single_aspect->id."'>".$single_aspect->name."</option>";
153                 }
154
155                 $s .= "</select>";
156                 $s .= '<div class="clear"></div>';
157         }
158
159         $s .= '<div id="diaspora-bydefault-wrapper">';
160         $s .= '<label id="diaspora-bydefault-label" for="diaspora-bydefault">' . DI::l10n()->t('Post to Diaspora by default') . '</label>';
161         $s .= '<input id="diaspora-bydefault" type="checkbox" name="diaspora_bydefault" value="1" ' . $def_checked . '/>';
162         $s .= '</div><div class="clear"></div>';
163
164         /* provide a submit button */
165
166         $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="diaspora-submit" name="diaspora-submit" class="settings-submit" value="' . DI::l10n()->t('Save Settings') . '" /></div></div>';
167
168 }
169
170
171 function diaspora_settings_post(App $a, &$b)
172 {
173         if (!empty($_POST['diaspora-submit'])) {
174                 DI::pConfig()->set(local_user(),'diaspora', 'post'           , intval($_POST['diaspora']));
175                 DI::pConfig()->set(local_user(),'diaspora', 'post_by_default', intval($_POST['diaspora_bydefault']));
176                 DI::pConfig()->set(local_user(),'diaspora', 'handle'         , trim($_POST['handle']));
177                 DI::pConfig()->set(local_user(),'diaspora', 'password'       , trim($_POST['password']));
178                 DI::pConfig()->set(local_user(),'diaspora', 'aspect'         , trim($_POST['aspect']));
179         }
180 }
181
182 function diaspora_hook_fork(&$a, &$b)
183 {
184         if ($b['name'] != 'notifier_normal') {
185                 return;
186         }
187
188         $post = $b['data'];
189
190         if ($post['deleted'] || $post['private'] || ($post['created'] !== $post['edited']) ||
191                 !strstr($post['postopts'], 'diaspora') || ($post['parent'] != $post['id'])) {
192                 $b['execute'] = false;
193                 return;
194         }
195 }
196
197 function diaspora_post_local(App $a, array &$b)
198 {
199         if ($b['edit']) {
200                 return;
201         }
202
203         if (!local_user() || (local_user() != $b['uid'])) {
204                 return;
205         }
206
207         if ($b['private'] || $b['parent']) {
208                 return;
209         }
210
211         $diaspora_post   = intval(DI::pConfig()->get(local_user(),'diaspora','post'));
212
213         $diaspora_enable = (($diaspora_post && !empty($_REQUEST['diaspora_enable'])) ? intval($_REQUEST['diaspora_enable']) : 0);
214
215         if ($b['api_source'] && intval(DI::pConfig()->get(local_user(),'diaspora','post_by_default'))) {
216                 $diaspora_enable = 1;
217         }
218
219         if (!$diaspora_enable) {
220                 return;
221         }
222
223         if (strlen($b['postopts'])) {
224                 $b['postopts'] .= ',';
225         }
226
227         $b['postopts'] .= 'diaspora';
228 }
229
230 function diaspora_send(App $a, array &$b)
231 {
232         $hostname = DI::baseUrl()->getHostname();
233
234         Logger::log('diaspora_send: invoked');
235
236         if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) {
237                 return;
238         }
239
240         if (!strstr($b['postopts'],'diaspora')) {
241                 return;
242         }
243
244         if ($b['parent'] != $b['id']) {
245                 return;
246         }
247
248         // Dont't post if the post doesn't belong to us.
249         // This is a check for forum postings
250         $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
251
252         if ($b['contact-id'] != $self['id']) {
253                 return;
254         }
255
256         Logger::log('diaspora_send: prepare posting', Logger::DEBUG);
257
258         $handle = DI::pConfig()->get($b['uid'],'diaspora','handle');
259         $password = DI::pConfig()->get($b['uid'],'diaspora','password');
260         $aspect = DI::pConfig()->get($b['uid'],'diaspora','aspect');
261
262         if ($handle && $password) {
263                 Logger::log('diaspora_send: all values seem to be okay', Logger::DEBUG);
264
265                 $tag_arr = [];
266                 $tags = '';
267                 $x = preg_match_all('/\#\[(.*?)\](.*?)\[/',$b['tag'],$matches,PREG_SET_ORDER);
268
269                 if ($x) {
270                         foreach ($matches as $mtch) {
271                                 $tag_arr[] = $mtch[2];
272                         }
273                 }
274
275                 if (count($tag_arr)) {
276                         $tags = implode(',',$tag_arr);
277                 }
278
279                 $title = $b['title'];
280                 $body = $b['body'];
281                 // Insert a newline before and after a quote
282                 $body = str_ireplace("[quote", "\n\n[quote", $body);
283                 $body = str_ireplace("[/quote]", "[/quote]\n\n", $body);
284
285                 // Removal of tags and mentions
286                 // #-tags
287                 $body = preg_replace('/#\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '#$2', $body);
288                 // @-mentions
289                 $body = preg_replace('/@\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '@$2', $body);
290
291                 // remove multiple newlines
292                 do {
293                         $oldbody = $body;
294                         $body = str_replace("\n\n\n", "\n\n", $body);
295                 } while ($oldbody != $body);
296
297                 // convert to markdown
298                 $body = BBCode::toMarkdown($body);
299
300                 // Adding the title
301                 if (strlen($title)) {
302                         $body = "## ".html_entity_decode($title)."\n\n".$body;
303                 }
304
305                 require_once "addon/diaspora/diasphp.php";
306
307                 try {
308                         Logger::log('diaspora_send: prepare', Logger::DEBUG);
309                         $conn = new Diaspora_Connection($handle, $password);
310                         Logger::log('diaspora_send: try to log in '.$handle, Logger::DEBUG);
311                         $conn->logIn();
312                         Logger::log('diaspora_send: try to send '.$body, Logger::DEBUG);
313
314                         $conn->provider = $hostname;
315                         $conn->postStatusMessage($body, $aspect);
316
317                         Logger::log('diaspora_send: success');
318                 } catch (Exception $e) {
319                         Logger::log("diaspora_send: Error submitting the post: " . $e->getMessage());
320
321                         Logger::log('diaspora_send: requeueing '.$b['uid'], Logger::DEBUG);
322
323                         Worker::defer();
324                 }
325         }
326 }