Merge pull request #1024 from hoergen/develop
[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\Core\Renderer;
17 use Friendica\Core\Session;
18 use Friendica\Database\DBA;
19 use Friendica\Core\Worker;
20 use Friendica\DI;
21
22 function diaspora_install()
23 {
24         Hook::register('hook_fork',               'addon/diaspora/diaspora.php', 'diaspora_hook_fork');
25         Hook::register('post_local',              'addon/diaspora/diaspora.php', 'diaspora_post_local');
26         Hook::register('notifier_normal',         'addon/diaspora/diaspora.php', 'diaspora_send');
27         Hook::register('jot_networks',            'addon/diaspora/diaspora.php', 'diaspora_jot_nets');
28         Hook::register('connector_settings',      'addon/diaspora/diaspora.php', 'diaspora_settings');
29         Hook::register('connector_settings_post', 'addon/diaspora/diaspora.php', 'diaspora_settings_post');
30 }
31
32 function diaspora_jot_nets(App $a, array &$jotnets_fields)
33 {
34         if (!local_user()) {
35                 return;
36         }
37
38         if (DI::pConfig()->get(local_user(), 'diaspora', 'post')) {
39                 $jotnets_fields[] = [
40                         'type' => 'checkbox',
41                         'field' => [
42                                 'diaspora_enable',
43                                 DI::l10n()->t('Post to Diaspora'),
44                                 DI::pConfig()->get(local_user(), 'diaspora', 'post_by_default')
45                         ]
46                 ];
47         }
48 }
49
50 function diaspora_settings(App $a, &$s)
51 {
52         if (! local_user()) {
53                 return;
54         }
55
56         /* Get the current state of our config variables */
57
58         $enabled = DI::pConfig()->get(local_user(),'diaspora','post');
59         $def_enabled = DI::pConfig()->get(local_user(),'diaspora','post_by_default');
60
61         $handle = DI::pConfig()->get(local_user(), 'diaspora', 'handle');
62         $password = DI::pConfig()->get(local_user(), 'diaspora', 'password');
63         $aspect = DI::pConfig()->get(local_user(),'diaspora','aspect');
64
65         $info = '';
66         $error = '';
67         if (Session::get('my_address')) {
68                 $info = DI::l10n()->t('Please remember: You can always be reached from Diaspora with your Friendica handle <strong>%s</strong>. ', Session::get('my_address'));
69                 $info .= DI::l10n()->t('This connector is only meant if you still want to use your old Diaspora account for some time. ');
70                 $info .= DI::l10n()->t('However, it is preferred that you tell your Diaspora contacts the new handle <strong>%s</strong> instead.', Session::get('my_address'));
71         }
72
73         $aspect_select = '';
74         if ($handle && $password) {
75                 $conn = new Diaspora_Connection($handle, $password);
76                 $conn->logIn();
77                 $rawAspects = $conn->getAspects();
78                 if ($rawAspects) {
79                         $availableAspects = [
80                                 'all_aspects' => DI::l10n()->t('All aspects'),
81                                 'public' => DI::l10n()->t('Public'),
82                         ];
83                         foreach ($rawAspects as $rawAspect) {
84                                 $availableAspects[$rawAspect->id] = $rawAspect->name;
85                         }
86
87                         $aspect_select = ['aspect', DI::l10n()->t('Post to aspect:'), $aspect, '', $availableAspects];
88                         $info = DI::l10n()->t('Connected with your Diaspora account <strong>%s</strong>', $handle);
89                 } else {
90                         $info = '';
91                         $error = DI::l10n()->t("Can't login to your Diaspora account. Please check handle (in the format user@domain.tld) and password.");
92                 }
93         }
94
95         DI::page()->registerStylesheet('addon/diaspora/diaspora.css');
96
97         $t = Renderer::getMarkupTemplate('settings.tpl', 'addon/diaspora/');
98         $s .= Renderer::replaceMacros($t, [
99                 '$header'           => DI::l10n()->t('Diaspora Export'),
100                 '$info_header'      => DI::l10n()->t('Information'),
101                 '$error_header'     => DI::l10n()->t('Error'),
102                 '$submit'           => DI::l10n()->t('Save Settings'),
103                 '$info'             => $info,
104                 '$error'            => $error,
105                 '$enabled'          => $enabled,
106                 '$enabled_checkbox' => ['enabled', DI::l10n()->t('Enable Diaspora Post Addon'), $enabled],
107                 '$handle'           => ['handle', DI::l10n()->t('Diaspora handle'), $handle, null, null, 'placeholder="user@domain.tld"'],
108                 '$password'         => ['password', DI::l10n()->t('Diaspora password'), '', DI::l10n()->t('Privacy notice: Your Diaspora password will be stored unencrypted to authenticate you with your Diaspora pod. This means your Friendica node administrator can have access to it.')],
109                 '$aspect_select'    => $aspect_select,
110                 '$post_by_default'  => ['post_by_default', DI::l10n()->t('Post to Diaspora by default'), $def_enabled],
111         ]);
112 }
113
114
115 function diaspora_settings_post(App $a, &$b)
116 {
117         if (!empty($_POST['diaspora-submit'])) {
118                 DI::pConfig()->set(local_user(),'diaspora', 'post'           , intval($_POST['enabled']));
119                 if (intval($_POST['enabled'])) {
120                         if (isset($_POST['handle'])) {
121                                 DI::pConfig()->set(local_user(),'diaspora', 'handle'         , trim($_POST['handle']));
122                                 DI::pConfig()->set(local_user(),'diaspora', 'password'       , trim($_POST['password']));
123                         }
124                         if (!empty($_POST['aspect'])) {
125                                 DI::pConfig()->set(local_user(),'diaspora', 'aspect'         , trim($_POST['aspect']));
126                                 DI::pConfig()->set(local_user(),'diaspora', 'post_by_default', intval($_POST['post_by_default']));
127                         }
128                 } else {
129                         DI::pConfig()->delete(local_user(), 'diaspora', 'password');
130                 }
131         }
132 }
133
134 function diaspora_hook_fork(&$a, &$b)
135 {
136         if ($b['name'] != 'notifier_normal') {
137                 return;
138         }
139
140         $post = $b['data'];
141
142         if ($post['deleted'] || $post['private'] || ($post['created'] !== $post['edited']) ||
143                 !strstr($post['postopts'], 'diaspora') || ($post['parent'] != $post['id'])) {
144                 $b['execute'] = false;
145                 return;
146         }
147 }
148
149 function diaspora_post_local(App $a, array &$b)
150 {
151         if ($b['edit']) {
152                 return;
153         }
154
155         if (!local_user() || (local_user() != $b['uid'])) {
156                 return;
157         }
158
159         if ($b['private'] || $b['parent']) {
160                 return;
161         }
162
163         $diaspora_post   = intval(DI::pConfig()->get(local_user(),'diaspora','post'));
164
165         $diaspora_enable = (($diaspora_post && !empty($_REQUEST['diaspora_enable'])) ? intval($_REQUEST['diaspora_enable']) : 0);
166
167         if ($b['api_source'] && intval(DI::pConfig()->get(local_user(),'diaspora','post_by_default'))) {
168                 $diaspora_enable = 1;
169         }
170
171         if (!$diaspora_enable) {
172                 return;
173         }
174
175         if (strlen($b['postopts'])) {
176                 $b['postopts'] .= ',';
177         }
178
179         $b['postopts'] .= 'diaspora';
180 }
181
182 function diaspora_send(App $a, array &$b)
183 {
184         $hostname = DI::baseUrl()->getHostname();
185
186         Logger::log('diaspora_send: invoked');
187
188         if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) {
189                 return;
190         }
191
192         if (!strstr($b['postopts'],'diaspora')) {
193                 return;
194         }
195
196         if ($b['parent'] != $b['id']) {
197                 return;
198         }
199
200         // Dont't post if the post doesn't belong to us.
201         // This is a check for forum postings
202         $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
203
204         if ($b['contact-id'] != $self['id']) {
205                 return;
206         }
207
208         Logger::log('diaspora_send: prepare posting', Logger::DEBUG);
209
210         $handle = DI::pConfig()->get($b['uid'],'diaspora','handle');
211         $password = DI::pConfig()->get($b['uid'],'diaspora','password');
212         $aspect = DI::pConfig()->get($b['uid'],'diaspora','aspect');
213
214         if ($handle && $password) {
215                 Logger::log('diaspora_send: all values seem to be okay', Logger::DEBUG);
216
217                 $title = $b['title'];
218                 $body = $b['body'];
219                 // Insert a newline before and after a quote
220                 $body = str_ireplace("[quote", "\n\n[quote", $body);
221                 $body = str_ireplace("[/quote]", "[/quote]\n\n", $body);
222
223                 // Removal of tags and mentions
224                 // #-tags
225                 $body = preg_replace('/#\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '#$2', $body);
226                 // @-mentions
227                 $body = preg_replace('/@\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '@$2', $body);
228
229                 // remove multiple newlines
230                 do {
231                         $oldbody = $body;
232                         $body = str_replace("\n\n\n", "\n\n", $body);
233                 } while ($oldbody != $body);
234
235                 // convert to markdown
236                 $body = BBCode::toMarkdown($body);
237
238                 // Adding the title
239                 if (strlen($title)) {
240                         $body = "## ".html_entity_decode($title)."\n\n".$body;
241                 }
242
243                 require_once "addon/diaspora/diasphp.php";
244
245                 try {
246                         Logger::log('diaspora_send: prepare', Logger::DEBUG);
247                         $conn = new Diaspora_Connection($handle, $password);
248                         Logger::log('diaspora_send: try to log in '.$handle, Logger::DEBUG);
249                         $conn->logIn();
250                         Logger::log('diaspora_send: try to send '.$body, Logger::DEBUG);
251
252                         $conn->provider = $hostname;
253                         $conn->postStatusMessage($body, $aspect);
254
255                         Logger::log('diaspora_send: success');
256                 } catch (Exception $e) {
257                         Logger::log("diaspora_send: Error submitting the post: " . $e->getMessage());
258
259                         Logger::log('diaspora_send: requeueing '.$b['uid'], Logger::DEBUG);
260
261                         Worker::defer();
262                 }
263         }
264 }