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