aboutsummaryrefslogtreecommitdiffstats
path: root/unshorturl/unshorturl.php
blob: 7c4574388a89f75f0a7150c84867a4e55bd71de5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php

/**
 * Name: UnshortURL
 * Description: Expand shortened URLs into their proper URLs
 * Version: 0.1.0
 * Author: Harald Eilertsen <https://hub.volse.no/channel/harald>
 * Maintainer: Harald Eilertsen <https://hub.volse.no/channel/harald>
 *
 * SPDX-FileCopyrightText: 2021 Harald Eilertsen <haraldei@anduin.net>
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

use Zotlabs\Lib\Apps;
use Zotlabs\Extend\Hook;

function unshorturl_install() {
    Hook::register('feature_settings', 'addon/unshorturl/unshorturl.php', 'unshorturl_feature_settings', 1);
    Hook::register('prepare_body', 'addon/unshorturl/unshorturl.php', 'unshorturl_prepare_body', 1);
}

function unshorturl_uninstall() {
    Hook::unregister('feature_settings', 'addon/unshorturl/unshorturl.php', 'unshorturl_feature_settings');
    Hook::unregister('prepare_body', 'addon/unshorturl/unshorturl.php', 'unshorturl_prepare_body');
}

function unshorturl_feature_settings(&$a, &$html) {
  $html =
      '<div class="settings-block">'
        . '<h3>UnshortURL</h3>'
        . '<p>Expand shortened URL\'s into their full representation.</p>'
        . '<div class="clear"></div>'
        . '</div>';
}

function unshorturl_get_long_url($shorturl) {
    $ch = curl_init($shorturl);
    curl_setopt_array($ch, [
        CURLOPT_HEADER => true,
        CURLOPT_NOBODY => true,
        CURLOPT_RETURNTRANSFER => true
    ]);
    $res = curl_exec($ch);

    if ($res !== false) {
        $matches = [];
        if (preg_match('/^(?:L|l)ocation: (.*)$/m', $res, $matches)) {
            return $matches[1];
        }
    }

    return false;
}

function unshorturl_prepare_body(&$body) {
    if (!local_channel() || !Apps::addon_app_installed(local_channel(), 'unshorturl')) {
        return;
    }

    $matches = [];
    $num_matches = preg_match_all('/https?:\/\/(bit\.ly|dlvr\.it|t\.co)\/\w+/', $body['html'], $matches);
    if ($num_matches > 0) {
        $matches = array_unique($matches);
        foreach ($matches as $links) {
            foreach($links as $l) {
                $longurl = unshorturl_get_long_url($l);
                if ($longurl) {
                    $body['html'] = str_replace($l, $longurl, $body['html']);
                }
            }
        }
    }
}