Update t() calls
[friendica-addons.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\Core\Addon;
13 use Friendica\Core\L10n;
14 use Friendica\Core\PConfig;
15 use Friendica\Database\DBM;
16 use Friendica\Model\Queue;
17
18 function diaspora_install() {
19         Addon::registerHook('post_local',           'addon/diaspora/diaspora.php', 'diaspora_post_local');
20         Addon::registerHook('notifier_normal',      'addon/diaspora/diaspora.php', 'diaspora_send');
21         Addon::registerHook('jot_networks',         'addon/diaspora/diaspora.php', 'diaspora_jot_nets');
22         Addon::registerHook('connector_settings',      'addon/diaspora/diaspora.php', 'diaspora_settings');
23         Addon::registerHook('connector_settings_post', 'addon/diaspora/diaspora.php', 'diaspora_settings_post');
24         Addon::registerHook('queue_predeliver', 'addon/diaspora/diaspora.php', 'diaspora_queue_hook');
25 }
26 function diaspora_uninstall() {
27         Addon::unregisterHook('post_local',       'addon/diaspora/diaspora.php', 'diaspora_post_local');
28         Addon::unregisterHook('notifier_normal',  'addon/diaspora/diaspora.php', 'diaspora_send');
29         Addon::unregisterHook('jot_networks',     'addon/diaspora/diaspora.php', 'diaspora_jot_nets');
30         Addon::unregisterHook('connector_settings',      'addon/diaspora/diaspora.php', 'diaspora_settings');
31         Addon::unregisterHook('connector_settings_post', 'addon/diaspora/diaspora.php', 'diaspora_settings_post');
32         Addon::unregisterHook('queue_predeliver', 'addon/diaspora/diaspora.php', 'diaspora_queue_hook');
33 }
34
35
36 function diaspora_jot_nets(&$a,&$b) {
37     if(! local_user())
38         return;
39
40     $diaspora_post = PConfig::get(local_user(),'diaspora','post');
41     if(intval($diaspora_post) == 1) {
42         $diaspora_defpost = PConfig::get(local_user(),'diaspora','post_by_default');
43         $selected = ((intval($diaspora_defpost) == 1) ? ' checked="checked" ' : '');
44         $b .= '<div class="profile-jot-net"><input type="checkbox" name="diaspora_enable"' . $selected . ' value="1" /> '
45             . L10n::t('Post to Diaspora') . '</div>';
46     }
47 }
48
49 function diaspora_queue_hook(&$a,&$b) {
50         $hostname = $a->get_hostname();
51
52         $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
53                 dbesc(NETWORK_DIASPORA2)
54         );
55         if(! count($qi))
56                 return;
57
58         foreach($qi as $x) {
59                 if($x['network'] !== NETWORK_DIASPORA2)
60                         continue;
61
62                 logger('diaspora_queue: run');
63
64                 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid`
65                         WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
66                         intval($x['cid'])
67                 );
68                 if(! count($r))
69                         continue;
70
71                 $userdata = $r[0];
72
73                 $handle = PConfig::get($userdata['uid'],'diaspora','handle');
74                 $password = PConfig::get($userdata['uid'],'diaspora','password');
75                 $aspect = PConfig::get($userdata['uid'],'diaspora','aspect');
76
77                 $success = false;
78
79                 if ($handle && $password) {
80                         logger('diaspora_queue: able to post for user '.$handle);
81
82                         $z = unserialize($x['content']);
83
84                         $post = $z['post'];
85
86                         logger('diaspora_queue: post: '.$post, LOGGER_DATA);
87
88                         try {
89                                 logger('diaspora_queue: prepare', LOGGER_DEBUG);
90                                 $conn = new Diaspora_Connection($handle, $password);
91                                 logger('diaspora_queue: try to log in '.$handle, LOGGER_DEBUG);
92                                 $conn->logIn();
93                                 logger('diaspora_queue: try to send '.$body, LOGGER_DEBUG);
94                                 $conn->provider = $hostname;
95                                 $conn->postStatusMessage($post, $aspect);
96
97                                 logger('diaspora_queue: send '.$userdata['uid'].' success', LOGGER_DEBUG);
98
99                                 $success = true;
100
101                                 Queue::removeItem($x['id']);
102                         } catch (Exception $e) {
103                                 logger("diaspora_queue: Send ".$userdata['uid']." failed: ".$e->getMessage(), LOGGER_DEBUG);
104                         }
105                 } else {
106                         logger('diaspora_queue: send '.$userdata['uid'].' missing username or password', LOGGER_DEBUG);
107                 }
108
109                 if (!$success) {
110                         logger('diaspora_queue: delayed');
111                         Queue::updateTime($x['id']);
112                 }
113         }
114 }
115
116 function diaspora_settings(&$a,&$s) {
117
118         if(! local_user())
119                 return;
120
121         /* Add our stylesheet to the page so we can make our settings look nice */
122
123         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/diaspora/diaspora.css' . '" media="all" />' . "\r\n";
124
125         /* Get the current state of our config variables */
126
127         $enabled = PConfig::get(local_user(),'diaspora','post');
128         $checked = (($enabled) ? ' checked="checked" ' : '');
129         $css = (($enabled) ? '' : '-disabled');
130
131         $def_enabled = PConfig::get(local_user(),'diaspora','post_by_default');
132
133         $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
134
135         $handle = PConfig::get(local_user(), 'diaspora', 'handle');
136         $password = PConfig::get(local_user(), 'diaspora', 'password');
137         $aspect = PConfig::get(local_user(),'diaspora','aspect');
138
139         $status = "";
140
141         $r = q("SELECT `addr` FROM `contact` WHERE `self` AND `uid` = %d", intval(local_user()));
142         if (DBM::is_result($r)) {
143                 $status = sprintf(L10n::t("Please remember: You can always be reached from Diaspora with your Friendica handle %s. "), $r[0]['addr']);
144                 $status .= L10n::t('This connector is only meant if you still want to use your old Diaspora account for some time. ');
145                 $status .= sprintf(L10n::t('However, it is preferred that you tell your Diaspora contacts the new handle %s instead.'), $r[0]['addr']);
146         }
147
148         $aspects = false;
149
150         if ($handle && $password) {
151                 $conn = new Diaspora_Connection($handle, $password);
152                 $conn->logIn();
153                 $aspects = $conn->getAspects();
154                 if (!$aspects) {
155                         $status = L10n::t("Can't login to your Diaspora account. Please check handle (in the format user@domain.tld) and password.");
156                 }
157         }
158
159         /* Add some HTML to the existing form */
160
161         $s .= '<span id="settings_diaspora_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_diaspora_expanded\'); openClose(\'settings_diaspora_inflated\');">';
162         $s .= '<img class="connector'.$css.'" src="images/diaspora-logo.png" /><h3 class="connector">'. L10n::t('Diaspora Export').'</h3>';
163         $s .= '</span>';
164         $s .= '<div id="settings_diaspora_expanded" class="settings-block" style="display: none;">';
165         $s .= '<span class="fakelink" onclick="openClose(\'settings_diaspora_expanded\'); openClose(\'settings_diaspora_inflated\');">';
166         $s .= '<img class="connector'.$css.'" src="images/diaspora-logo.png" /><h3 class="connector">'. L10n::t('Diaspora Export').'</h3>';
167         $s .= '</span>';
168
169         if ($status) {
170                 $s .= '<div id="diaspora-status-wrapper"><strong>';
171                 $s .= $status;
172                 $s .= '</strong></div><div class="clear"></div>';
173         }
174
175         $s .= '<div id="diaspora-enable-wrapper">';
176         $s .= '<label id="diaspora-enable-label" for="diaspora-checkbox">' . L10n::t('Enable Diaspora Post Addon') . '</label>';
177         $s .= '<input id="diaspora-checkbox" type="checkbox" name="diaspora" value="1" ' . $checked . '/>';
178         $s .= '</div><div class="clear"></div>';
179
180         $s .= '<div id="diaspora-username-wrapper">';
181         $s .= '<label id="diaspora-username-label" for="diaspora-username">' . L10n::t('Diaspora handle') . '</label>';
182         $s .= '<input id="diaspora-username" type="text" name="handle" value="' . $handle . '" />';
183         $s .= '</div><div class="clear"></div>';
184
185         $s .= '<div id="diaspora-password-wrapper">';
186         $s .= '<label id="diaspora-password-label" for="diaspora-password">' . L10n::t('Diaspora password') . '</label>';
187         $s .= '<input id="diaspora-password" type="password" name="password" value="' . $password . '" />';
188         $s .= '</div><div class="clear"></div>';
189
190         if ($aspects) {
191                 $single_aspect =  new stdClass();
192                 $single_aspect->id = 'all_aspects';
193                 $single_aspect->name = L10n::t('All aspects');
194                 $aspects[] = $single_aspect;
195
196                 $single_aspect =  new stdClass();
197                 $single_aspect->id = 'public';
198                 $single_aspect->name = L10n::t('Public');
199                 $aspects[] = $single_aspect;
200
201                 $s .= '<label id="diaspora-aspect-label" for="diaspora-aspect">' . L10n::t('Post to aspect:') . '</label>';
202                 $s .= '<select name="aspect" id="diaspora-aspect">';
203                 foreach($aspects as $single_aspect) {
204                         if ($single_aspect->id == $aspect)
205                                 $s .= "<option value='".$single_aspect->id."' selected>".$single_aspect->name."</option>";
206                         else
207                                 $s .= "<option value='".$single_aspect->id."'>".$single_aspect->name."</option>";
208                 }
209
210                 $s .= "</select>";
211                 $s .= '<div class="clear"></div>';
212         }
213
214         $s .= '<div id="diaspora-bydefault-wrapper">';
215         $s .= '<label id="diaspora-bydefault-label" for="diaspora-bydefault">' . L10n::t('Post to Diaspora by default') . '</label>';
216         $s .= '<input id="diaspora-bydefault" type="checkbox" name="diaspora_bydefault" value="1" ' . $def_checked . '/>';
217         $s .= '</div><div class="clear"></div>';
218
219         /* provide a submit button */
220
221         $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="diaspora-submit" name="diaspora-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div></div>';
222
223 }
224
225
226 function diaspora_settings_post(&$a,&$b) {
227
228         if(x($_POST,'diaspora-submit')) {
229
230                 PConfig::set(local_user(),'diaspora','post',intval($_POST['diaspora']));
231                 PConfig::set(local_user(),'diaspora','post_by_default',intval($_POST['diaspora_bydefault']));
232                 PConfig::set(local_user(),'diaspora','handle',trim($_POST['handle']));
233                 PConfig::set(local_user(),'diaspora','password',trim($_POST['password']));
234                 PConfig::set(local_user(),'diaspora','aspect',trim($_POST['aspect']));
235         }
236
237 }
238
239 function diaspora_post_local(&$a,&$b) {
240
241         if ($b['edit']) {
242                 return;
243         }
244
245         if (!local_user() || (local_user() != $b['uid'])) {
246                 return;
247         }
248
249         if ($b['private'] || $b['parent']) {
250                 return;
251         }
252
253         $diaspora_post   = intval(PConfig::get(local_user(),'diaspora','post'));
254
255         $diaspora_enable = (($diaspora_post && x($_REQUEST,'diaspora_enable')) ? intval($_REQUEST['diaspora_enable']) : 0);
256
257         if ($b['api_source'] && intval(PConfig::get(local_user(),'diaspora','post_by_default'))) {
258                 $diaspora_enable = 1;
259         }
260
261         if (!$diaspora_enable) {
262                 return;
263         }
264
265         if (strlen($b['postopts'])) {
266                 $b['postopts'] .= ',';
267         }
268
269         $b['postopts'] .= 'diaspora';
270 }
271
272
273
274
275 function diaspora_send(&$a,&$b) {
276         $hostname = $a->get_hostname();
277
278         logger('diaspora_send: invoked');
279
280         if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) {
281                 return;
282         }
283
284         if(! strstr($b['postopts'],'diaspora')) {
285                 return;
286         }
287
288         if($b['parent'] != $b['id']) {
289                 return;
290         }
291
292         // Dont't post if the post doesn't belong to us.
293         // This is a check for forum postings
294         $self = dba::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
295         if ($b['contact-id'] != $self['id']) {
296                 return;
297         }
298
299         logger('diaspora_send: prepare posting', LOGGER_DEBUG);
300
301         $handle = PConfig::get($b['uid'],'diaspora','handle');
302         $password = PConfig::get($b['uid'],'diaspora','password');
303         $aspect = PConfig::get($b['uid'],'diaspora','aspect');
304
305         if ($handle && $password) {
306
307                 logger('diaspora_send: all values seem to be okay', LOGGER_DEBUG);
308
309                 require_once('include/bb2diaspora.php');
310                 $tag_arr = [];
311                 $tags = '';
312                 $x = preg_match_all('/\#\[(.*?)\](.*?)\[/',$b['tag'],$matches,PREG_SET_ORDER);
313
314                 if($x) {
315                         foreach($matches as $mtch) {
316                                 $tag_arr[] = $mtch[2];
317                         }
318                 }
319                 if(count($tag_arr))
320                         $tags = implode(',',$tag_arr);
321
322                 $title = $b['title'];
323                 $body = $b['body'];
324                 // Insert a newline before and after a quote
325                 $body = str_ireplace("[quote", "\n\n[quote", $body);
326                 $body = str_ireplace("[/quote]", "[/quote]\n\n", $body);
327
328                 // Removal of tags and mentions
329                 // #-tags
330                 $body = preg_replace('/#\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '#$2', $body);
331                 // @-mentions
332                 $body = preg_replace('/@\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '@$2', $body);
333
334                 // remove multiple newlines
335                 do {
336                         $oldbody = $body;
337                         $body = str_replace("\n\n\n", "\n\n", $body);
338                 } while ($oldbody != $body);
339
340                 // convert to markdown
341                 $body = bb2diaspora($body, false, true);
342
343                 // Adding the title
344                 if(strlen($title))
345                         $body = "## ".html_entity_decode($title)."\n\n".$body;
346
347                 require_once("addon/diaspora/diasphp.php");
348
349                 try {
350                         logger('diaspora_send: prepare', LOGGER_DEBUG);
351                         $conn = new Diaspora_Connection($handle, $password);
352                         logger('diaspora_send: try to log in '.$handle, LOGGER_DEBUG);
353                         $conn->logIn();
354                         logger('diaspora_send: try to send '.$body, LOGGER_DEBUG);
355
356                         $conn->provider = $hostname;
357                         $conn->postStatusMessage($body, $aspect);
358
359                         logger('diaspora_send: success');
360                 } catch (Exception $e) {
361                         logger("diaspora_send: Error submitting the post: " . $e->getMessage());
362
363                         logger('diaspora_send: requeueing '.$b['uid'], LOGGER_DEBUG);
364
365                         $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
366                         if (count($r))
367                                 $a->contact = $r[0]["id"];
368
369                         $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $body]);
370                         
371                         Queue::add($a->contact, NETWORK_DIASPORA2, $s);
372                         notice(L10n::t('Diaspora post failed. Queued for retry.').EOL);
373                 }
374         }
375 }