1<?php
2/*
3 * vim:set softtabstop=4 shiftwidth=4 expandtab:
4 *
5 * LICENSE: GNU Affero General Public License, version 3 (AGPL-3.0-or-later)
6 * Copyright 2001 - 2020 Ampache.org
7 *
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU Affero General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 * GNU Affero General Public License for more details.
17 *
18 * You should have received a copy of the GNU Affero General Public License
19 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
20 *
21 */
22declare(strict_types=0);
23
24namespace Ampache\Plugin;
25
26use Ampache\Repository\Model\Preference;
27use Ampache\Repository\Model\User;
28use Ampache\Module\System\Core;
29use Exception;
30use Requests;
31
32class AmpacheGoogleMaps
33{
34    public $name        = 'GoogleMaps';
35    public $categories  = 'geolocation';
36    public $description = 'Show user\'s location with Google Maps';
37    public $url         = 'http://maps.google.com';
38    public $version     = '000001';
39    public $min_ampache = '370022';
40    public $max_ampache = '999999';
41
42    private $api_key;
43
44    /**
45     * Constructor
46     * This function does nothing...
47     */
48    public function __construct()
49    {
50        $this->description = T_("Show user's location with Google Maps");
51
52        return true;
53    } // constructor
54
55    /**
56     * install
57     * This is a required plugin function. It inserts our preferences
58     * into Ampache
59     */
60    public function install()
61    {
62        if (Preference::exists('gmaps_api_key')) {
63            return false;
64        }
65        Preference::insert('gmaps_api_key', T_('Google Maps API key'), '', 75, 'string', 'plugins', $this->name);
66
67        return true;
68    } // install
69
70    /**
71     * uninstall
72     * This is a required plugin function. It removes our preferences from
73     * the database returning it to its original form
74     */
75    public function uninstall()
76    {
77        Preference::delete('gmaps_api_key');
78
79        return true;
80    } // uninstall
81
82    /**
83     * upgrade
84     * This is a recommended plugin function
85     */
86    public function upgrade()
87    {
88        return true;
89    } // upgrade
90
91    /**
92     * @param $latitude
93     * @param $longitude
94     * @return string
95     */
96    public function get_location_name($latitude, $longitude)
97    {
98        $name = "";
99        try {
100            $url     = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" . $latitude . "," . $longitude . "&sensor=false";
101            $request = Requests::get($url, array(), Core::requests_options());
102
103            $place = json_decode($request->body, true);
104            if (count($place['results']) > 0) {
105                $name = $place['results'][0]['formatted_address'];
106            }
107        } catch (Exception $error) {
108            debug_event(self::class, 'Error getting location name: ' . $error->getMessage(), 1);
109        }
110
111        return $name;
112    }
113
114    /**
115     * @param $pts
116     * @return boolean
117     */
118    public function display_map($pts)
119    {
120        if (!$this->api_key) {
121            debug_event(self::class, 'Missing API key, display map plugin skipped.', 3);
122
123            return false;
124        }
125
126        echo '<script>' . "\n";
127        echo 'function map_ready() {' . "\n";
128        echo 'var mapOptions = {' . "\n";
129        if (count($pts) > 0) {
130            echo 'center: { lat: ' . $pts[0]['latitude'] . ', lng: ' . $pts[0]['longitude'] . ' }, ' . "\n";
131        } else {
132            // No geolocation data? Display `Paris` city.
133            echo 'center: { lat: 48.853, lng: 2.348 }, ' . "\n";
134        }
135        echo 'zoom: 11' . "\n";
136        echo '};' . "\n";
137        echo 'var map = new google.maps.Map(document.getElementById("map-canvas"), ' . "\n";
138        echo 'mapOptions);' . "\n";
139        echo 'var marker;' . "\n";
140        foreach ($pts as $pt) {
141            $ptdescr = T_("Hits") . ": " . $pt['hits'] . "\\n";
142            $ptdescr .= T_("Last activity") . ": " . date("r", $pt['last_date']);
143            if (!empty($pt['name'])) {
144                $ptdescr = $pt['name'] . "\\n" . $ptdescr;
145            }
146            echo 'marker = new google.maps.Marker({' . "\n";
147            echo 'position: { lat: ' . $pt['latitude'] . ', lng: ' . $pt['longitude'] . ' }, ' . "\n";
148            echo 'title:"' . $ptdescr . '"' . "\n";
149            echo '});' . "\n";
150            echo 'marker.setMap(map);' . "\n";
151        }
152        echo '}' . "\n";
153
154        echo 'function loadMapScript() {' . "\n";
155        echo 'var script = document.createElement("script");' . "\n";
156        echo 'script.src = "https://maps.googleapis.com/maps/api/js?key=' . $this->api_key . '&" + "callback=map_ready";' . "\n";
157        echo 'document.body.appendChild(script);' . "\n";
158        echo '}' . "\n";
159        echo 'loadMapScript();';
160
161        echo '</script>' . "\n";
162        echo '<div id="map-canvas" style="display: inline-block; height: 300px; width:680px; margin: 0; padding: 0;"></div>' . "\n";
163
164        return true;
165    }
166
167    /**
168     * load
169     * This loads up the data we need into this object, this stuff comes
170     * from the preferences.
171     * @param User $user
172     * @return boolean
173     */
174    public function load($user)
175    {
176        $user->set_preferences();
177        $data = $user->prefs;
178        // load system when nothing is given
179        if (!strlen(trim($data['gmaps_api_key']))) {
180            $data                  = array();
181            $data['gmaps_api_key'] = Preference::get_by_user(-1, 'gmaps_api_key');
182        }
183
184        if (strlen(trim($data['gmaps_api_key']))) {
185            $this->api_key = trim($data['gmaps_api_key']);
186        }
187
188        return true;
189    } // load
190}
191