User.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. <?php
  2. /* GNU FM -- a free network service for sharing your music listening habits
  3. Copyright (C) 2009 Free Software Foundation, Inc
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU Affero General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Affero General Public License for more details.
  12. You should have received a copy of the GNU Affero General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. require_once($install_path . '/database.php');
  16. require_once($install_path . '/data/sanitize.php');
  17. require_once($install_path . '/utils/human-time.php');
  18. require_once($install_path . '/data/Server.php');
  19. require_once($install_path . '/data/Tag.php');
  20. /**
  21. * Represents User data
  22. *
  23. * General attributes are accessible as public variables.
  24. *
  25. */
  26. class User {
  27. public $name, $email, $fullname, $bio, $location, $homepage, $error, $userlevel;
  28. public $id, $acctid, $avatar_uri, $location_uri, $webid_uri, $laconica_profile, $journal_rss;
  29. public $password, $has_identica, $created, $modified, $uniqueid, $anticommercial, $receive_emails;
  30. public $remote = false;
  31. /**
  32. * User constructor
  33. *
  34. * @param string $name The name of the user to load
  35. * @param array $data User data as row returned from Users database table
  36. */
  37. function __construct($name, $data = null) {
  38. global $base_url;
  39. $base = preg_replace('#/$#', '', $base_url);
  40. if (is_array($data)) {
  41. $row = $data;
  42. } else {
  43. global $adodb;
  44. $query = 'SELECT * FROM Users WHERE active = 1 AND lower(username) = lower(' . $adodb->qstr($name) . ') LIMIT 1';
  45. $adodb->SetFetchMode(ADODB_FETCH_ASSOC);
  46. $row = $adodb->CacheGetRow(7200, $query);
  47. if (!$row) {
  48. throw new Exception('EUSER', 22);
  49. }
  50. }
  51. if (is_array($row)) {
  52. $this->name = $row['username'];
  53. $this->password = $row['password'];
  54. $this->email = $row['email'];
  55. $this->fullname = $row['fullname'];
  56. $this->homepage = $row['homepage'];
  57. $this->bio = $row['bio'];
  58. $this->location = $row['location'];
  59. $this->location_uri = $row['location_uri'];
  60. $this->userlevel = $row['userlevel'];
  61. $this->id = $row['webid_uri'];
  62. $this->webid_uri = $row['webid_uri'];
  63. $this->avatar_uri = $row['avatar_uri'];
  64. $this->laconica_profile = $row['laconica_profile'];
  65. $this->journal_rss = $row['journal_rss'];
  66. $this->acctid = $this->getURL() . '#acct';
  67. $this->created = $row['created'];
  68. $this->modified = $row['modified'];
  69. $this->uniqueid = $row['uniqueid'];
  70. $this->anticommercial = $row['anticommercial'];
  71. $this->receive_emails = $row['receive_emails'];
  72. $this->has_identica = preg_match('#^http://identi\.ca/#i', $this->laconica_profile);
  73. if (!preg_match('/\:/', $this->id)) {
  74. $this->id = $this->getURL() . '#me';
  75. }
  76. }
  77. }
  78. /**
  79. * Create User object from user id
  80. *
  81. * @param int $uid User id
  82. * @return User User object, or false in case of failure
  83. */
  84. public static function new_from_uniqueid_number($uid) {
  85. global $adodb;
  86. $query = sprintf('SELECT * FROM Users WHERE uniqueid = %d', (int)$uid);
  87. $adodb->SetFetchMode(ADODB_FETCH_ASSOC);
  88. $row = $adodb->CacheGetRow(7200, $query);
  89. if ($row) {
  90. try {
  91. return new User($row['username'], $row);
  92. } catch (Exception $e) {
  93. return false;
  94. }
  95. } else {
  96. return false;
  97. }
  98. }
  99. /**
  100. * Save user data to database
  101. *
  102. * @return int 1 on success
  103. */
  104. function save() {
  105. global $adodb;
  106. // It appears we just discard this data, but this is here for a reason!
  107. // getLocationDetails will fill in latitude,longitude details into the Places table in the database
  108. // if it's not already there. This is important as the location_uri field is a foreign key.
  109. if (!empty($this->location_uri)) {
  110. $dummy = Server::getLocationDetails($this->location_uri);
  111. }
  112. $q = sprintf('UPDATE Users SET '
  113. . 'email=%s, ' # Send a confirmation email first??
  114. . 'password=%s, '
  115. . 'fullname=%s, '
  116. . 'homepage=%s, '
  117. . 'bio=%s, '
  118. . 'location=%s, '
  119. . 'userlevel=%d, '
  120. . 'webid_uri=%s, '
  121. . 'location_uri=%s, '
  122. . 'avatar_uri=%s, '
  123. . 'laconica_profile=%s, '
  124. . 'journal_rss=%s, '
  125. . 'anticommercial=%d, '
  126. . 'receive_emails=%d, '
  127. . 'modified=%d '
  128. . 'WHERE username=%s'
  129. , $adodb->qstr($this->email)
  130. , $adodb->qstr($this->password)
  131. , $adodb->qstr($this->fullname)
  132. , $adodb->qstr($this->homepage)
  133. , $adodb->qstr($this->bio)
  134. , $adodb->qstr($this->location)
  135. , $this->userlevel
  136. , $adodb->qstr($this->id)
  137. , (empty($this->location_uri) ? 'NULL' : $adodb->qstr($this->location_uri))
  138. , $adodb->qstr($this->avatar_uri)
  139. , $adodb->qstr($this->laconica_profile)
  140. , $adodb->qstr($this->journal_rss)
  141. , (int)($this->anticommercial)
  142. , (int)($this->receive_emails)
  143. , time()
  144. , $adodb->qstr($this->name));
  145. try {
  146. $res = $adodb->Execute($q);
  147. } catch (Exception $e) {
  148. header('Content-Type: text/plain');
  149. exit;
  150. }
  151. $query = 'SELECT * FROM Users WHERE lower(username) = lower(' . $adodb->qstr($this->name) . ') LIMIT 1';
  152. $adodb->CacheFlush($query);
  153. return 1;
  154. }
  155. /**
  156. * Get a user's scrobbles ordered by time
  157. *
  158. * @param int $number The number of scrobbles to return
  159. * @param int $offset The position of the first scrobble to return
  160. * @param int $from Only return scrobbles with time higher than this timestamp
  161. * @param int $to Only return scrobbles with time lower than this timestamp
  162. * @return array An array of scrobbles with human time
  163. */
  164. function getScrobbles($number, $offset = 0, $from = false, $to = false) {
  165. $data = Server::getRecentScrobbles($number, $this->uniqueid, $offset, $from, $to);
  166. if ($data == null) {
  167. return array();
  168. }
  169. return $data;
  170. }
  171. /**
  172. * Retrieve a user's avatar via the gravatar service
  173. *
  174. * @param int $size The desired size of the avatar (between 1 and 512 pixels)
  175. * @return string A URL to the user's avatar image
  176. */
  177. function getAvatar($size = 64) {
  178. if (!empty($this->avatar_uri)) {
  179. return $this->avatar_uri;
  180. }
  181. return 'https://www.gravatar.com/avatar/' . md5(strtolower($this->email)) . '?s=' . $size . '&d=monsterid';
  182. }
  183. /**
  184. * Retrieves the URL to the user's page
  185. *
  186. * @param string $component Type of user page, profile|stats|recent-tracks|station
  187. * @return string URL to the user's page
  188. */
  189. function getURL($component = 'profile', $params = false) {
  190. return Server::getUserURL($this->name, $component, $params);
  191. }
  192. /**
  193. * Get a user's now-playing tracks
  194. *
  195. * @param int $number Amount of tracks to retrieve
  196. * @return array An array of nowplaying data or null in case of failure
  197. */
  198. function getNowPlaying($number) {
  199. return Server::getNowPlaying($number, $this->name);
  200. }
  201. /**
  202. * Log in to the gnukebox server
  203. *
  204. * @return array A string containing the session key to be used for scrobbling
  205. */
  206. function getScrobbleSession() {
  207. return Server::getScrobbleSession($this->uniqueid);
  208. }
  209. /**
  210. * Log in to the radio server
  211. *
  212. * @param string $station The station to be played
  213. * @return array A string containing the session key to be used for streaming
  214. */
  215. function getRadioSession($station) {
  216. return Server::getRadioSession($station, $this->name);
  217. }
  218. /**
  219. * Log in to the web services
  220. *
  221. * @return array A string containing the web session key
  222. */
  223. function getWebServiceSession() {
  224. return Server::getWebServiceSession($this->name);
  225. }
  226. /**
  227. * Get this user's top artists
  228. *
  229. * @param int $limit The number of artists to return
  230. * @param int $offset Skip this number of rows before returning artists
  231. * @param bool $streamable Only return streamable artists
  232. * @param int $begin Only use scrobbles with time higher than this timestamp
  233. * @param int $end Only use scrobbles with time lower than this timestamp
  234. * @param int $cache Caching period in seconds
  235. * @return array An array of artists ((artist, freq, artisturl) ..) or empty array in case of failure
  236. */
  237. function getTopArtists($limit = 20, $offset = 0, $streamable = False, $begin = null, $end = null, $cache = 600) {
  238. return Server::getTopArtists($limit, $offset, $streamable, $begin, $end, $this->uniqueid, $cache);
  239. }
  240. /**
  241. * Get this user's top tracks
  242. *
  243. * @param int $limit The number of tracks to return
  244. * @param int $offset Skip this number of rows before returning tracks
  245. * @param bool $streamable Only return streamable tracks
  246. * @param int $begin Only use scrobbles with time higher than this timestamp
  247. * @param int $end Only use scrobbles with time lower than this timestamp
  248. * @param int $cache Caching period in seconds
  249. * @return array An array of tracks ((artist, track, freq, listeners, artisturl, trackurl) ..) or empty array in case of failure
  250. */
  251. function getTopTracks($limit = 20, $offset = 0, $streamable = False, $begin = null, $end = null, $cache = 600) {
  252. return Server::getTopTracks($limit, $offset, $streamable, $begin, $end, null, $this->uniqueid, $cache);
  253. }
  254. /**
  255. * Get this user's total number of tracks scrobbled
  256. *
  257. * @param int $since Timestamp to start counting tracks from
  258. * @return int Number of tracks scrobbled
  259. */
  260. public function getTotalTracks($since = null) {
  261. global $adodb;
  262. if ($since) {
  263. $query = 'SELECT COUNT(*) FROM Scrobbles WHERE userid = ' . ($this->uniqueid) . ' AND time > ' . (int)($since);
  264. } else {
  265. $query = 'SELECT scrobble_count FROM User_Stats WHERE userid = ' . ($this->uniqueid);
  266. }
  267. try {
  268. $tracks = $adodb->CacheGetOne(200, $query);
  269. } catch (Exception $e) {
  270. $tracks = 0;
  271. }
  272. return $tracks;
  273. }
  274. /**
  275. * Get a user's top tags, ordered by tag count
  276. *
  277. * @param int $limit The number of tags to return (default is 10)
  278. * @param int $offset The position of the first tag to return (default is 0)
  279. * @param int $cache Caching period of query in seconds (default is 600)
  280. * @return An array of tag details ((tag, freq) .. )
  281. */
  282. function getTopTags($limit=10, $offset=0, $cache=600) {
  283. return Tag::_getTagData($cache, $limit, $offset, $this->uniqueid);
  284. }
  285. /**
  286. * Get artists, albums, or tracks tagged with tag by user
  287. *
  288. * @param string $tag Items are tagged by this tag
  289. * @param string $taggingtype Type of tags to return (artist|album|track)
  290. * @param int $limit The number of items to return (default is 10)
  291. * @param int $offset The position of the first item to return (default is 0)
  292. * @param int $cache Caching period of query in seconds (default is 600)
  293. * @param bool $streamable Show only content by streamable artists (default is False)
  294. * @return array Item details ((artist, .. , freq) .. )
  295. */
  296. function getPersonalTags($tag, $taggingtype, $limit=10, $offset=0, $cache=600, $streamable=False) {
  297. if(isset($tag) and isset($taggingtype)) {
  298. return Tag::_getTagData($cache, $limit, $offset, $this->uniqueid, null, null, null, $tag, $taggingtype, $streamable);
  299. }
  300. }
  301. /**
  302. * Get a user's tags for a specific artist
  303. *
  304. * @param string $artist The name of the artist to fetch tags for
  305. * @param int $limit The number of tags to return (default is 10)
  306. * @param int $offset The position of the first tag to return (default is 0)
  307. * @param int $cache Caching period of query in seconds (default is 600)
  308. * @return An array of tag details ((tag, freq) .. )
  309. */
  310. function getTagsForArtist($artist, $limit=10, $offset=0, $cache=0) {
  311. if(isset($artist)) {
  312. $artistobj = new Artist($artist);
  313. return $artistobj->getTags($this->uniqueid, $limit, $offset, $cache);
  314. }
  315. }
  316. /**
  317. * Get tag count for tag and user
  318. *
  319. * @param string $tag The tag to show user's tag count for
  320. * @param int $cache Caching period of query in seconds (default is 600)
  321. * @return An array of tag details ((tag, freq) .. )
  322. */
  323. function getTagInfo($tag, $cache=600) {
  324. if(isset($tag)) {
  325. return Tag::_getTagData($cache, 1, 0, $this->uniqueid, null, null, null, $tag);
  326. }
  327. }
  328. /**
  329. * Retrieves a list of user's loved tracks
  330. *
  331. * @param int $limit The number of tracks to return
  332. * @param int $offset Skip this number of rows before returning tracks
  333. * @param bool $streamable Only return streamable tracks
  334. * @param int $artist Only return results from this artist
  335. * @param int $cache Caching period in seconds
  336. * @return array Track details ((artist, track, time, freq, artisturl, trackurl) ..) or empty array in case of failure
  337. */
  338. function getLovedTracks($limit = 20, $offset = 0, $streamable = False, $artist = null, $cache = 600) {
  339. return Server::getLovedTracks($limit, $offset, $streamable, $artist, $this->uniqueid, $cache);
  340. }
  341. /**
  342. * Retrieves a list of user's loved artists
  343. *
  344. * @param int $limit The number of artists to return
  345. * @param int $offset Skip this number of rows before returning artists
  346. * @param bool $streamable Only return streamable artists
  347. * @param int $cache Caching period in seconds
  348. * @return array An array of artists ((artist, freq, artisturl) ..) or empty array in case of failure
  349. */
  350. function getLovedArtists($limit = 20, $offset = 0, $streamable = False, $cache = 600) {
  351. return Server::getLovedArtists($limit, $offset, $streamable, $this->uniqueid, $cache);
  352. }
  353. /**
  354. * Retrieves a list of user's banned tracks
  355. *
  356. * @todo Rewrite this function like $user->getLovedTracks()
  357. *
  358. * @param int $limit The number of tracks to return
  359. * @param int $offset Skip this number of rows before returning tracks
  360. * @return array Track details ((userid, track, artist, time) ..) or empty array in case of failure
  361. */
  362. function getBannedTracks($limit = 50, $offset = 0) {
  363. global $adodb;
  364. $res = $adodb->CacheGetAll(600, 'SELECT * FROM Banned_Tracks WHERE '
  365. . ' userid = ' . $this->uniqueid . ' ORDER BY time DESC'
  366. . ' LIMIT ' . $limit . ' OFFSET ' . $offset);
  367. return $res;
  368. }
  369. /**
  370. * Get details of any connections this user has setup to other services.
  371. *
  372. * @return array An array of service connection details
  373. */
  374. function getConnections() {
  375. global $adodb;
  376. $res = $adodb->GetAll('SELECT * FROM Service_Connections WHERE '
  377. . ' userid = ' . $this->uniqueid);
  378. return $res;
  379. }
  380. /**
  381. * Get artists recommended for this user
  382. *
  383. * @param int $limit The number of artists to return (defaults to 10)
  384. * @param bool $random Pick artists at random
  385. * @return array An array of artist details
  386. */
  387. function getRecommended($limit = 10, $random = false) {
  388. global $adodb;
  389. $loved = $this->getLovedTracks(50);
  390. $artists = array();
  391. for ($i = 0; $i < min($limit, count($loved) - 1); $i++) {
  392. if ($random) {
  393. $n = rand(0, count($loved) - 1);
  394. } else {
  395. $n = $i;
  396. }
  397. $artists[] = $loved[$n]['artist'];
  398. }
  399. $recommendedArtists = array();
  400. foreach ($artists as $artist_name) {
  401. try {
  402. $artist = new Artist($artist_name);
  403. } catch (Exception $e) {
  404. continue;
  405. }
  406. $similar = $artist->getSimilar(5);
  407. foreach ($similar as $sa) {
  408. if (!array_key_exists($sa['artist'], $recommendedArtists)) {
  409. $recommendedArtists[$sa['artist']] = $sa;
  410. }
  411. }
  412. }
  413. $limit = min($limit, count($recommendedArtists) - 1);
  414. if ($random) {
  415. $randomArtists = array();
  416. $keys = array_keys($recommendedArtists);
  417. for ($i = 0; $i < $limit; $i++) {
  418. $randomArtists[] = $recommendedArtists[$keys[rand(0, count($recommendedArtists) - 1)]];
  419. }
  420. return $randomArtists;
  421. } else {
  422. return array_slice($recommendedArtists, 0, $limit);
  423. }
  424. }
  425. /**
  426. * Determines whether a user has permission to manage an artist
  427. *
  428. * @param string $artist The name of the artist to check
  429. * @return bool Boolean indicating whether this user can edit the artist or not.
  430. */
  431. function manages($artist) {
  432. global $adodb;
  433. if ($this->userlevel >= 2) {
  434. // Let admins edit all artists
  435. return true;
  436. }
  437. $res = $adodb->GetOne('SELECT COUNT(*) FROM Manages WHERE '
  438. . ' userid = ' . $this->uniqueid
  439. . ' AND artist = ' . $adodb->qstr($artist)
  440. . ' AND authorised = 1');
  441. return $res != 0;
  442. }
  443. /**
  444. * Checks whether this user has any loved tracks
  445. *
  446. * @return bool Boolean indicating whether this user has marked any tracks as being loved in the past.
  447. */
  448. function hasLoved() {
  449. global $adodb;
  450. $res = $adodb->GetOne('SELECT COUNT(*) FROM Loved_Tracks WHERE '
  451. . ' userid = ' . $this->uniqueid);
  452. return $res != 0;
  453. }
  454. /**
  455. * Find the neighbours of this user based on the number of loved artists shared between them and other users.
  456. *
  457. * @param int The number of neighbours to return (defaults to 10).
  458. * @return array An array of userids, User objects and the number of loved artists shared with this user.
  459. */
  460. function getNeighbours($limit=10) {
  461. global $adodb;
  462. if (!$this->hasLoved()) {
  463. return array();
  464. }
  465. $res = $adodb->CacheGetAll(7200, 'SELECT Loved_Tracks.userid AS userid, count(Loved_Tracks.userid) AS shared_artists FROM Loved_Tracks INNER JOIN (SELECT DISTINCT(artist) AS artist FROM Loved_Tracks WHERE userid=' . $this->uniqueid . ') AS Loved_Artists ON Loved_Tracks.artist = Loved_Artists.artist WHERE userid != ' . $this->uniqueid . ' GROUP BY Loved_Tracks.userid ORDER BY shared_artists DESC LIMIT ' . $limit);
  466. foreach ($res as &$neighbour) {
  467. $neighbour['user'] = User::new_from_uniqueid_number($neighbour['userid']);
  468. }
  469. return $res;
  470. }
  471. }