]> git.mxchange.org Git - friendica-addons.git/blob - statusnet/statusnet.php
4ae7b86b2f6968736e0c86131d2eb80eb61560a5
[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(App $a, 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(App $a, $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(App $a, 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()->get() . '/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(App $a, array &$b)
292 {
293         if ($b['name'] != 'notifier_normal') {
294                 return;
295         }
296
297         $post = $b['data'];
298
299         // Deleting and editing is not supported by the addon
300         if ($post['deleted'] || ($post['created'] !== $post['edited'])) {
301                 $b['execute'] = false;
302                 return;
303         }
304
305         if ($post['app'] == 'StatusNet') {
306                 $b['execute'] = false;
307                 return;
308         }
309
310         // Comments are never exported when we don't import the GNU Social timeline
311         if (strpos($post['postopts'] ?? '', 'statusnet') === false || ($post['parent'] != $post['id']) || $post['private']) {
312                 $b['execute'] = false;
313                 return;
314         }
315 }
316
317 function statusnet_post_local(App $a, array &$b)
318 {
319         if ($b['edit']) {
320                 return;
321         }
322
323         if (!DI::userSession()->getLocalUserId() || (DI::userSession()->getLocalUserId() != $b['uid'])) {
324                 return;
325         }
326
327         $statusnet_post = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'post');
328         $statusnet_enable = (($statusnet_post && !empty($_REQUEST['statusnet_enable'])) ? intval($_REQUEST['statusnet_enable']) : 0);
329
330         // if API is used, default to the chosen settings
331         if ($b['api_source'] && intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'post_by_default'))) {
332                 $statusnet_enable = 1;
333         }
334
335         if (!$statusnet_enable) {
336                 return;
337         }
338
339         if (strlen($b['postopts'])) {
340                 $b['postopts'] .= ',';
341         }
342
343         $b['postopts'] .= 'statusnet';
344 }
345
346 function statusnet_post_hook(App $a, array &$b)
347 {
348         /**
349          * Post to GNU Social
350          */
351         if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) {
352                 return;
353         }
354
355         $b['body'] = Post\Media::addAttachmentsToBody($b['uri-id'], DI::contentItem()->addSharedPost($b));
356
357         $api = DI::pConfig()->get($b['uid'], 'statusnet', 'baseapi');
358         $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
359
360         if ($b['private'] || !strstr($b['postopts'], 'statusnet')) {
361                 return;
362         }
363
364         // Dont't post if the post doesn't belong to us.
365         // This is a check for forum postings
366         $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
367         if ($b['contact-id'] != $self['id']) {
368                 return;
369         }
370
371         Logger::notice('GNU Socialpost invoked');
372
373         DI::pConfig()->load($b['uid'], 'statusnet');
374
375         $api     = DI::pConfig()->get($b['uid'], 'statusnet', 'baseapi');
376         $ckey    = DI::pConfig()->get($b['uid'], 'statusnet', 'consumerkey');
377         $csecret = DI::pConfig()->get($b['uid'], 'statusnet', 'consumersecret');
378         $otoken  = DI::pConfig()->get($b['uid'], 'statusnet', 'oauthtoken');
379         $osecret = DI::pConfig()->get($b['uid'], 'statusnet', 'oauthsecret');
380
381         if ($ckey && $csecret && $otoken && $osecret) {
382                 $dent = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
383                 $max_char = $dent->get_maxlength(); // max. length for a dent
384
385                 DI::pConfig()->set($b['uid'], 'statusnet', 'max_char', $max_char);
386
387                 $tempfile = '';
388                 $msgarr = Plaintext::getPost($b, $max_char, true, 7);
389                 $msg = $msgarr['text'];
390
391                 if (($msg == '') && isset($msgarr['title']))
392                         $msg = Plaintext::shorten($msgarr['title'], $max_char - 50, $b['uid']);
393
394                 $image = '';
395
396                 if (isset($msgarr['url']) && ($msgarr['type'] != 'photo')) {
397                         $msg .= " \n" . $msgarr['url'];
398                 } elseif (isset($msgarr['image']) && ($msgarr['type'] != 'video')) {
399                         $image = $msgarr['image'];
400                 }
401
402                 if ($image != '') {
403                         $img_str = DI::httpClient()->fetch($image);
404                         $tempfile = tempnam(System::getTempPath(), 'cache');
405                         file_put_contents($tempfile, $img_str);
406                         $postdata = ['status' => $msg, 'media[]' => $tempfile];
407                 } else {
408                         $postdata = ['status' => $msg];
409                 }
410
411                 // and now send it :-)
412                 if (strlen($msg)) {
413                         // New code that is able to post pictures
414                         require_once __DIR__ . DIRECTORY_SEPARATOR . 'library' . DIRECTORY_SEPARATOR . 'codebirdsn.php';
415                         $cb = CodebirdSN::getInstance();
416                         $cb->setAPIEndpoint($api);
417                         $cb->setConsumerKey($ckey, $csecret);
418                         $cb->setToken($otoken, $osecret);
419                         $result = $cb->statuses_update($postdata);
420                         //$result = $dent->post('statuses/update', $postdata);
421                         Logger::info('statusnet_post send, result: ' . print_r($result, true) .
422                                 "\nmessage: " . $msg . "\nOriginal post: " . print_r($b, true) . "\nPost Data: " . print_r($postdata, true));
423
424                         if (!empty($result->source)) {
425                                 DI::pConfig()->set($b['uid'], 'statusnet', 'application_name', strip_tags($result->source));
426                         }
427
428                         if (!empty($result->error)) {
429                                 Logger::notice('Send to GNU Social failed: "' . $result->error . '"');
430                         } elseif ($iscomment) {
431                                 Logger::notice('statusnet_post: Update extid ' . $result->id . ' for post id ' . $b['id']);
432                                 Item::update(['extid' => $hostname . '::' . $result->id, 'body' => $result->text], ['id' => $b['id']]);
433                         }
434                 }
435                 if ($tempfile != '') {
436                         unlink($tempfile);
437                 }
438         }
439 }
440
441 function statusnet_addon_admin_post(App $a)
442 {
443         $sites = [];
444
445         foreach ($_POST['sitename'] as $id => $sitename) {
446                 $sitename = trim($sitename);
447                 $apiurl = trim($_POST['apiurl'][$id]);
448                 if (!(substr($apiurl, -1) == '/')) {
449                         $apiurl = $apiurl . '/';
450                 }
451                 $secret = trim($_POST['secret'][$id]);
452                 $key = trim($_POST['key'][$id]);
453                 //$applicationname = (!empty($_POST['applicationname']) ? Strings::escapeTags(trim($_POST['applicationname'][$id])):'');
454                 if ($sitename != '' &&
455                         $apiurl != '' &&
456                         $secret != '' &&
457                         $key != '' &&
458                         empty($_POST['delete'][$id])) {
459
460                         $sites[] = [
461                                 'sitename' => $sitename,
462                                 'apiurl' => $apiurl,
463                                 'consumersecret' => $secret,
464                                 'consumerkey' => $key,
465                                 //'applicationname' => $applicationname
466                         ];
467                 }
468         }
469
470         $sites = DI::config()->set('statusnet', 'sites', $sites);
471 }
472
473 function statusnet_addon_admin(App $a, string &$o)
474 {
475         $sites = DI::config()->get('statusnet', 'sites');
476         $sitesform = [];
477         if (is_array($sites)) {
478                 foreach ($sites as $id => $s) {
479                         $sitesform[] = [
480                                 'sitename' => ["sitename[$id]", "Site name", $s['sitename'], ""],
481                                 'apiurl' => ["apiurl[$id]", "Api url", $s['apiurl'], DI::l10n()->t("Base API Path \x28remember the trailing /\x29")],
482                                 'secret' => ["secret[$id]", "Secret", $s['consumersecret'], ""],
483                                 'key' => ["key[$id]", "Key", $s['consumerkey'], ""],
484                                 //'applicationname' => Array("applicationname[$id]", "Application name", $s['applicationname'], ""),
485                                 'delete' => ["delete[$id]", "Delete", False, "Check to delete this preset"],
486                         ];
487                 }
488         }
489         /* empty form to add new site */
490         $id = count($sitesform);
491         $sitesform[] = [
492                 'sitename' => ["sitename[$id]", DI::l10n()->t("Site name"), "", ""],
493                 'apiurl' => ["apiurl[$id]", "Api url", "", DI::l10n()->t("Base API Path \x28remember the trailing /\x29")],
494                 'secret' => ["secret[$id]", DI::l10n()->t("Consumer Secret"), "", ""],
495                 'key' => ["key[$id]", DI::l10n()->t("Consumer Key"), "", ""],
496                 //'applicationname' => Array("applicationname[$id]", DI::l10n()->t("Application name"), "", ""),
497         ];
498
499         $t = Renderer::getMarkupTemplate('admin.tpl', 'addon/statusnet/');
500         $o = Renderer::replaceMacros($t, [
501                 '$submit' => DI::l10n()->t('Save Settings'),
502                 '$sites' => $sitesform,
503         ]);
504 }