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