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