]> git.mxchange.org Git - friendica-addons.git/blob - statusnet/statusnet.php
Upgrade phpunit version in PHP-CI
[friendica-addons.git] / statusnet / statusnet.php
1 <?php
2
3 /**
4  * Name: GNU Social Connector
5  * Description: Bidirectional (posting, relaying and reading) connector for GNU Social.
6  * Version: 1.0.5
7  * Author: Tobias Diekershoff <https://f.diekershoff.de/profile/tobias>
8  * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
9  *
10  * Copyright (c) 2011-2013 Tobias Diekershoff, Michael Vogel
11  * All rights reserved.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions are met:
15  *    * Redistributions of source code must retain the above copyright notice,
16  *     this list of conditions and the following disclaimer.
17  *    * Redistributions in binary form must reproduce the above
18  *    * copyright notice, this list of conditions and the following disclaimer in
19  *      the documentation and/or other materials provided with the distribution.
20  *    * Neither the name of the <organization> nor the names of its contributors
21  *      may be used to endorse or promote products derived from this software
22  *      without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
26  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
27  * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT,
28  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
32  * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
33  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  *
35  */
36 define('STATUSNET_DEFAULT_POLL_INTERVAL', 5); // given in minutes
37
38 require_once __DIR__ . DIRECTORY_SEPARATOR . 'library' . DIRECTORY_SEPARATOR . 'statusnetoauth.php';
39
40 use CodebirdSN\CodebirdSN;
41 use Friendica\App;
42 use Friendica\Content\Text\Plaintext;
43 use Friendica\Core\Hook;
44 use Friendica\Core\Logger;
45 use Friendica\Core\Renderer;
46 use Friendica\Core\System;
47 use Friendica\Database\DBA;
48 use Friendica\DI;
49 use Friendica\Model\Item;
50 use Friendica\Model\Post;
51 use Friendica\Model\User;
52
53 function statusnet_install()
54 {
55         //  we need some hooks, for the configuration and for sending tweets
56         Hook::register('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
57         Hook::register('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
58         Hook::register('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
59         Hook::register('hook_fork', 'addon/statusnet/statusnet.php', 'statusnet_hook_fork');
60         Hook::register('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
61         Hook::register('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
62         Logger::notice('installed GNU Social');
63 }
64
65 function statusnet_jot_nets(array &$jotnets_fields)
66 {
67         if (!DI::userSession()->getLocalUserId()) {
68                 return;
69         }
70
71         if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'post')) {
72                 $jotnets_fields[] = [
73                         'type' => 'checkbox',
74                         'field' => [
75                                 'statusnet_enable',
76                                 DI::l10n()->t('Post to GNU Social'),
77                                 DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'post_by_default')
78                         ]
79                 ];
80         }
81 }
82
83 function statusnet_settings_post($post)
84 {
85         if (!DI::userSession()->getLocalUserId()) {
86                 return;
87         }
88         // don't check GNU Social settings if GNU Social submit button is not clicked
89         if (empty($_POST['statusnet-submit']) && empty($_POST['statusnet-disconnect'])) {
90                 return;
91         }
92
93         if (!empty($_POST['statusnet-disconnect'])) {
94                 /*               * *
95                  * if the GNU Social-disconnect button is clicked, clear the GNU Social configuration
96                  */
97                 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'statusnet', 'consumerkey');
98                 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'statusnet', 'consumersecret');
99                 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'statusnet', 'post');
100                 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'statusnet', 'post_by_default');
101                 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'statusnet', 'oauthtoken');
102                 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'statusnet', 'oauthsecret');
103                 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'statusnet', 'baseapi');
104         } else {
105                 if (isset($_POST['statusnet-preconf-apiurl'])) {
106                         /*                       * *
107                          * If the user used one of the preconfigured GNU Social server credentials
108                          * use them. All the data are available in the global config.
109                          * Check the API Url never the less and blame the admin if it's not working ^^
110                          */
111                         $globalsn = DI::config()->get('statusnet', 'sites');
112                         foreach ($globalsn as $asn) {
113                                 if ($asn['apiurl'] == $_POST['statusnet-preconf-apiurl']) {
114                                         $apibase = $asn['apiurl'];
115                                         $c = DI::httpClient()->fetch($apibase . 'statusnet/version.xml');
116                                         if (strlen($c) > 0) {
117                                                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'consumerkey', $asn['consumerkey']);
118                                                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'consumersecret', $asn['consumersecret']);
119                                                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'baseapi', $asn['apiurl']);
120                                                 //DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'application_name', $asn['applicationname'] );
121                                         } else {
122                                                 DI::sysmsg()->addNotice(DI::l10n()->t('Please contact your site administrator.<br />The provided API URL is not valid.') . '<br />' . $asn['apiurl']);
123                                         }
124                                 }
125                         }
126                 } else {
127                         if (isset($_POST['statusnet-consumersecret'])) {
128                                 //  check if we can reach the API of the GNU Social server
129                                 //  we'll check the API Version for that, if we don't get one we'll try to fix the path but will
130                                 //  resign quickly after this one try to fix the path ;-)
131                                 $apibase = $_POST['statusnet-baseapi'];
132                                 $c = DI::httpClient()->fetch($apibase . 'statusnet/version.xml');
133                                 if (strlen($c) > 0) {
134                                         //  ok the API path is correct, let's save the settings
135                                         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
136                                         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
137                                         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'baseapi', $apibase);
138                                         //DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'application_name', $_POST['statusnet-applicationname'] );
139                                 } else {
140                                         //  the API path is not correct, maybe missing trailing / ?
141                                         $apibase = $apibase . '/';
142                                         $c = DI::httpClient()->fetch($apibase . 'statusnet/version.xml');
143                                         if (strlen($c) > 0) {
144                                                 //  ok the API path is now correct, let's save the settings
145                                                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
146                                                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
147                                                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'baseapi', $apibase);
148                                         } else {
149                                                 //  still not the correct API base, let's do noting
150                                                 DI::sysmsg()->addNotice(DI::l10n()->t('We could not contact the GNU Social API with the Path you entered.'));
151                                         }
152                                 }
153                         } else {
154                                 if (isset($_POST['statusnet-pin'])) {
155                                         //  if the user supplied us with a PIN from GNU Social, let the magic of OAuth happen
156                                         $api = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'baseapi');
157                                         $ckey = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'consumerkey');
158                                         $csecret = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'consumersecret');
159                                         //  the token and secret for which the PIN was generated were hidden in the settings
160                                         //  form as token and token2, we need a new connection to GNU Social using these token
161                                         //  and secret to request a Access Token with the PIN
162                                         $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']);
163                                         $token = $connection->getAccessToken($_POST['statusnet-pin']);
164                                         //  ok, now that we have the Access Token, save them in the user config
165                                         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'oauthtoken', $token['oauth_token']);
166                                         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'oauthsecret', $token['oauth_token_secret']);
167                                         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'post', 1);
168                                         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'post_taglinks', 1);
169                                         //  reload the Addon Settings page, if we don't do it see Bug #42
170                                 } else {
171                                         //  if no PIN is supplied in the POST variables, the user has changed the setting
172                                         //  to post a dent for every new __public__ posting to the wall
173                                         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'post', intval($_POST['statusnet-enable']));
174                                         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'post_by_default', intval($_POST['statusnet-default']));
175                                 }
176                         }
177                 }
178         }
179 }
180
181 function statusnet_settings(array &$data)
182 {
183         if (!DI::userSession()->getLocalUserId()) {
184                 return;
185         }
186
187         DI::page()->registerStylesheet(__DIR__ . '/statusnet.css', 'all');
188
189         /*       * *
190          * 1) Check that we have a base api url and a consumer key & secret
191          * 2) If no OAuthtoken & stuff is present, generate button to get some
192          *    allow the user to cancel the connection process at this step
193          * 3) Checkbox for "Send public notices (respect size limitation)
194          */
195         $baseapi     = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'baseapi');
196         $ckey        = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'consumerkey');
197         $csecret     = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'consumersecret');
198         $otoken      = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'oauthtoken');
199         $osecret     = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'oauthsecret');
200         $enabled     = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'post', false);
201         $def_enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'post_by_default', false);
202
203         // Radio button list to select existing application credentials
204         $sites = array_map(function ($site) {
205                 return ['statusnet-preconf-apiurl', $site['sitename'], $site['apiurl']];
206         }, DI::config()->get('statusnet', 'sites', []));
207
208         $submit = ['statusnet-submit' => DI::l10n()->t('Save Settings')];
209
210         if ($ckey && $csecret) {
211                 if ($otoken && $osecret) {
212                         /*                       * *
213                          *  we have an OAuth key / secret pair for the user
214                          *  so let's give a chance to disable the postings to GNU Social
215                          */
216                         $connection = new StatusNetOAuth($baseapi, $ckey, $csecret, $otoken, $osecret);
217                         $account    = $connection->get('account/verify_credentials');
218
219                         if (!empty($account)) {
220                                 $connected_account = DI::l10n()->t('Currently connected to: <a href="%s" target="_statusnet">%s</a>', $account->statusnet_profile_url, $account->screen_name);
221                         }
222
223                         $user = User::getById(DI::userSession()->getLocalUserId());
224                         if ($user['hidewall']) {
225                                 $privacy_warning = DI::l10n()->t('<strong>Note</strong>: Due your privacy settings (<em>Hide your profile details from unknown viewers?</em>) the link potentially included in public postings relayed to GNU Social will lead the visitor to a blank page informing the visitor that the access to your profile has been restricted.');
226                         }
227
228                         $submit['statusnet-disconnect'] = DI::l10n()->t('Clear OAuth configuration');
229                 } else {
230                         /*                       * *
231                          * the user has not yet connected the account to GNU Social
232                          * get a temporary OAuth key/secret pair and display a button with
233                          * which the user can request a PIN to connect the account to a
234                          * account at GNU Social
235                          */
236                         $connection    = new StatusNetOAuth($baseapi, $ckey, $csecret);
237                         $request_token = $connection->getRequestToken('oob');
238                         $authorize_url = $connection->getAuthorizeURL($request_token['oauth_token'], false);
239
240                         $submit['statusnet-disconnect'] = DI::l10n()->t('Cancel GNU Social Connection');
241                 }
242         }
243
244         $t    = Renderer::getMarkupTemplate('connector_settings.tpl', 'addon/statusnet/');
245         $html = Renderer::replaceMacros($t, [
246                 '$l10n' => [
247                         'global_title'      => DI::l10n()->t('Globally Available GNU Social OAuthKeys'),
248                         'global_info'       => DI::l10n()->t(DI::l10n()->t('There are preconfigured OAuth key pairs for some GNU Social servers available. If you are using one of them, please use these credentials. If not feel free to connect to any other GNU Social instance (see below).')),
249                         'credentials_title' => DI::l10n()->t('Provide your own OAuth Credentials'),
250                         'credentials_info'  => DI::l10n()->t('No consumer key pair for GNU Social found. Register your Friendica Account as a desktop application on your GNU Social account, copy the consumer key pair here and enter the API base root.<br />Before you register your own OAuth key pair ask the administrator if there is already a key pair for this Friendica installation at your favorite GNU Social installation.'),
251                         'oauth_info'        => DI::l10n()->t('To connect to your GNU Social account click the button below to get a security code from GNU Social which you have to copy into the input box below and submit the form. Only your <strong>public</strong> posts will be posted to GNU Social.'),
252                         'oauth_alt'         => DI::l10n()->t('Log in with GNU Social'),
253                         'oauth_cancel'      => DI::l10n()->t('Cancel Connection Process'),
254                         'oauth_api'         => DI::l10n()->t('Current GNU Social API is: %s', $baseapi),
255                         'connected_account' => $connected_account ?? '',
256                         'privacy_warning'   => $privacy_warning ?? '',
257                 ],
258
259                 '$ckey'    => $ckey,
260                 '$csecret' => $csecret,
261                 '$otoken'  => $otoken,
262                 '$osecret' => $osecret,
263                 '$sites'   => $sites,
264
265                 '$authorize_url' => $authorize_url ?? '',
266                 '$request_token' => $request_token ?? null,
267                 '$account'       => $account ?? null,
268
269                 '$authenticate_url' => DI::baseUrl() . '/statusnet/connect',
270
271                 '$consumerkey'    => ['statusnet-consumerkey', DI::l10n()->t('OAuth Consumer Key'), '', '', false, ' size="35'],
272                 '$consumersecret' => ['statusnet-consumersecret', DI::l10n()->t('OAuth Consumer Secret'), '', '', false, ' size="35'],
273
274                 '$baseapi' => ['statusnet-baseapi', DI::l10n()->t('Base API Path (remember the trailing /)'), '', '', false, ' size="35'],
275                 '$pin'     => ['statusnet-pin', DI::l10n()->t('Copy the security code from GNU Social here')],
276
277                 '$enable'      => ['statusnet-enabled', DI::l10n()->t('Allow posting to GNU Social'), $enabled, DI::l10n()->t('If enabled all your <strong>public</strong> postings can be posted to the associated GNU Social account. You can choose to do so by default (here) or for every posting separately in the posting options when writing the entry.')],
278                 '$default'     => ['statusnet-default', DI::l10n()->t('Post to GNU Social by default'), $def_enabled],
279         ]);
280
281         $data = [
282                 'connector' => 'statusnet',
283                 'title'     => DI::l10n()->t('GNU Social Import/Export/Mirror'),
284                 'image'     => 'images/gnusocial.png',
285                 'enabled'   => $enabled,
286                 'html'      => $html,
287                 'submit'    => $submit,
288         ];
289 }
290
291 function statusnet_hook_fork(array &$b)
292 {
293         if ($b['name'] != 'notifier_normal') {
294                 return;
295         }
296
297         $post = $b['data'];
298
299         if ($post['deleted'] || ($post['created'] !== $post['edited']) || strpos($post['postopts'] ?? '', 'statusnet') === false || ($post['parent'] != $post['id']) || $post['private']) {
300                 $b['execute'] = false;
301                 return;
302         }
303 }
304
305 function statusnet_post_local(array &$b)
306 {
307         if ($b['edit']) {
308                 return;
309         }
310
311         if (!DI::userSession()->getLocalUserId() || (DI::userSession()->getLocalUserId() != $b['uid'])) {
312                 return;
313         }
314
315         $statusnet_post = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'post');
316         $statusnet_enable = (($statusnet_post && !empty($_REQUEST['statusnet_enable'])) ? intval($_REQUEST['statusnet_enable']) : 0);
317
318         // if API is used, default to the chosen settings
319         if ($b['api_source'] && intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'post_by_default'))) {
320                 $statusnet_enable = 1;
321         }
322
323         if (!$statusnet_enable) {
324                 return;
325         }
326
327         if (strlen($b['postopts'])) {
328                 $b['postopts'] .= ',';
329         }
330
331         $b['postopts'] .= 'statusnet';
332 }
333
334 function statusnet_post_hook(array &$b)
335 {
336         /**
337          * Post to GNU Social
338          */
339         if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) {
340                 return;
341         }
342
343         $b['body'] = Post\Media::addAttachmentsToBody($b['uri-id'], DI::contentItem()->addSharedPost($b));
344
345         $api = DI::pConfig()->get($b['uid'], 'statusnet', 'baseapi');
346         $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
347
348         if ($b['private'] || !strstr($b['postopts'], 'statusnet')) {
349                 return;
350         }
351
352         // Dont't post if the post doesn't belong to us.
353         // This is a check for group postings
354         $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
355         if ($b['contact-id'] != $self['id']) {
356                 return;
357         }
358
359         Logger::notice('GNU Socialpost invoked');
360
361         DI::pConfig()->load($b['uid'], 'statusnet');
362
363         $api     = DI::pConfig()->get($b['uid'], 'statusnet', 'baseapi');
364         $ckey    = DI::pConfig()->get($b['uid'], 'statusnet', 'consumerkey');
365         $csecret = DI::pConfig()->get($b['uid'], 'statusnet', 'consumersecret');
366         $otoken  = DI::pConfig()->get($b['uid'], 'statusnet', 'oauthtoken');
367         $osecret = DI::pConfig()->get($b['uid'], 'statusnet', 'oauthsecret');
368
369         if ($ckey && $csecret && $otoken && $osecret) {
370                 $dent = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
371                 $max_char = $dent->get_maxlength(); // max. length for a dent
372
373                 DI::pConfig()->set($b['uid'], 'statusnet', 'max_char', $max_char);
374
375                 $tempfile = '';
376                 $msgarr = Plaintext::getPost($b, $max_char, true, 7);
377                 $msg = $msgarr['text'];
378
379                 if (($msg == '') && isset($msgarr['title']))
380                         $msg = Plaintext::shorten($msgarr['title'], $max_char - 50, $b['uid']);
381
382                 $image = '';
383
384                 if (isset($msgarr['url']) && ($msgarr['type'] != 'photo')) {
385                         $msg .= " \n" . $msgarr['url'];
386                 } elseif (isset($msgarr['image']) && ($msgarr['type'] != 'video')) {
387                         $image = $msgarr['image'];
388                 }
389
390                 if ($image != '') {
391                         $img_str = DI::httpClient()->fetch($image);
392                         $tempfile = tempnam(System::getTempPath(), 'cache');
393                         file_put_contents($tempfile, $img_str);
394                         $postdata = ['status' => $msg, 'media[]' => $tempfile];
395                 } else {
396                         $postdata = ['status' => $msg];
397                 }
398
399                 // and now send it :-)
400                 if (strlen($msg)) {
401                         // New code that is able to post pictures
402                         require_once __DIR__ . DIRECTORY_SEPARATOR . 'library' . DIRECTORY_SEPARATOR . 'codebirdsn.php';
403                         $cb = CodebirdSN::getInstance();
404                         $cb->setAPIEndpoint($api);
405                         $cb->setConsumerKey($ckey, $csecret);
406                         $cb->setToken($otoken, $osecret);
407                         $result = $cb->statuses_update($postdata);
408                         //$result = $dent->post('statuses/update', $postdata);
409                         Logger::info('statusnet_post send, result: ' . print_r($result, true) .
410                                 "\nmessage: " . $msg . "\nOriginal post: " . print_r($b, true) . "\nPost Data: " . print_r($postdata, true));
411
412                         if (!empty($result->source)) {
413                                 DI::pConfig()->set($b['uid'], 'statusnet', 'application_name', strip_tags($result->source));
414                         }
415
416                         if (!empty($result->error)) {
417                                 Logger::notice('Send to GNU Social failed: "' . $result->error . '"');
418                         } elseif ($iscomment) {
419                                 Logger::notice('statusnet_post: Update extid ' . $result->id . ' for post id ' . $b['id']);
420                                 Item::update(['extid' => $hostname . '::' . $result->id, 'body' => $result->text], ['id' => $b['id']]);
421                         }
422                 }
423                 if ($tempfile != '') {
424                         unlink($tempfile);
425                 }
426         }
427 }
428
429 function statusnet_addon_admin_post()
430 {
431         $sites = [];
432
433         foreach ($_POST['sitename'] as $id => $sitename) {
434                 $sitename = trim($sitename);
435                 $apiurl = trim($_POST['apiurl'][$id]);
436                 if (!(substr($apiurl, -1) == '/')) {
437                         $apiurl = $apiurl . '/';
438                 }
439                 $secret = trim($_POST['secret'][$id]);
440                 $key = trim($_POST['key'][$id]);
441                 //$applicationname = (!empty($_POST['applicationname']) ? Strings::escapeTags(trim($_POST['applicationname'][$id])):'');
442                 if ($sitename != '' &&
443                         $apiurl != '' &&
444                         $secret != '' &&
445                         $key != '' &&
446                         empty($_POST['delete'][$id])) {
447
448                         $sites[] = [
449                                 'sitename' => $sitename,
450                                 'apiurl' => $apiurl,
451                                 'consumersecret' => $secret,
452                                 'consumerkey' => $key,
453                                 //'applicationname' => $applicationname
454                         ];
455                 }
456         }
457
458         $sites = DI::config()->set('statusnet', 'sites', $sites);
459 }
460
461 function statusnet_addon_admin(string &$o)
462 {
463         $sites = DI::config()->get('statusnet', 'sites');
464         $sitesform = [];
465         if (is_array($sites)) {
466                 foreach ($sites as $id => $s) {
467                         $sitesform[] = [
468                                 'sitename' => ["sitename[$id]", "Site name", $s['sitename'], ""],
469                                 'apiurl' => ["apiurl[$id]", "Api url", $s['apiurl'], DI::l10n()->t("Base API Path \x28remember the trailing /\x29")],
470                                 'secret' => ["secret[$id]", "Secret", $s['consumersecret'], ""],
471                                 'key' => ["key[$id]", "Key", $s['consumerkey'], ""],
472                                 //'applicationname' => Array("applicationname[$id]", "Application name", $s['applicationname'], ""),
473                                 'delete' => ["delete[$id]", "Delete", False, "Check to delete this preset"],
474                         ];
475                 }
476         }
477         /* empty form to add new site */
478         $id = count($sitesform);
479         $sitesform[] = [
480                 'sitename' => ["sitename[$id]", DI::l10n()->t("Site name"), "", ""],
481                 'apiurl' => ["apiurl[$id]", "Api url", "", DI::l10n()->t("Base API Path \x28remember the trailing /\x29")],
482                 'secret' => ["secret[$id]", DI::l10n()->t("Consumer Secret"), "", ""],
483                 'key' => ["key[$id]", DI::l10n()->t("Consumer Key"), "", ""],
484                 //'applicationname' => Array("applicationname[$id]", DI::l10n()->t("Application name"), "", ""),
485         ];
486
487         $t = Renderer::getMarkupTemplate('admin.tpl', 'addon/statusnet/');
488         $o = Renderer::replaceMacros($t, [
489                 '$submit' => DI::l10n()->t('Save Settings'),
490                 '$sites' => $sitesform,
491         ]);
492 }