User.php 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  1. <?php
  2. // This file is part of GNU social - https://www.gnu.org/software/social
  3. //
  4. // GNU social 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. //
  9. // GNU social is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  16. defined('GNUSOCIAL') || die();
  17. /**
  18. * Table Definition for user
  19. */
  20. class User extends Managed_DataObject
  21. {
  22. const SUBSCRIBE_POLICY_OPEN = 0;
  23. const SUBSCRIBE_POLICY_MODERATE = 1;
  24. ###START_AUTOCODE
  25. /* the code below is auto generated do not remove the above tag */
  26. public $__table = 'user'; // table name
  27. public $id; // int(4) primary_key not_null
  28. public $nickname; // varchar(64) unique_key
  29. public $password; // varchar(191) not 255 because utf8mb4 takes more space
  30. public $email; // varchar(191) unique_key not 255 because utf8mb4 takes more space
  31. public $incomingemail; // varchar(191) unique_key not 255 because utf8mb4 takes more space
  32. public $emailnotifysub; // bool default_true
  33. public $emailnotifyfav; // tinyint(1) default_null
  34. public $emailnotifynudge; // bool default_true
  35. public $emailnotifymsg; // bool default_true
  36. public $emailnotifyattn; // bool default_true
  37. public $language; // varchar(50)
  38. public $timezone; // varchar(50)
  39. public $emailpost; // bool default_true
  40. public $sms; // varchar(64) unique_key
  41. public $carrier; // int(4)
  42. public $smsnotify; // bool default_false
  43. public $smsreplies; // bool default_false
  44. public $smsemail; // varchar(191) not 255 because utf8mb4 takes more space
  45. public $uri; // varchar(191) unique_key not 255 because utf8mb4 takes more space
  46. public $autosubscribe; // bool default_false
  47. public $subscribe_policy; // tinyint(1)
  48. public $urlshorteningservice; // varchar(50) default_ur1.ca
  49. public $private_stream; // bool default_false
  50. public $created; // datetime()
  51. public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
  52. /* the code above is auto generated do not remove the tag below */
  53. ###END_AUTOCODE
  54. public static function schemaDef()
  55. {
  56. return array(
  57. 'description' => 'local users',
  58. 'fields' => array(
  59. 'id' => array('type' => 'int', 'not null' => true, 'description' => 'foreign key to profile table'),
  60. 'nickname' => array('type' => 'varchar', 'length' => 64, 'description' => 'nickname or username, duped in profile'),
  61. 'password' => array('type' => 'varchar', 'length' => 191, 'description' => 'salted password, can be null for OpenID users'),
  62. 'email' => array('type' => 'varchar', 'length' => 191, 'description' => 'email address for password recovery etc.'),
  63. 'incomingemail' => array('type' => 'varchar', 'length' => 191, 'description' => 'email address for post-by-email'),
  64. 'emailnotifysub' => array('type' => 'bool', 'default' => true, 'description' => 'Notify by email of subscriptions'),
  65. 'emailnotifyfav' => array('type' => 'int', 'size' => 'tiny', 'default' => null, 'description' => 'Notify by email of favorites'),
  66. 'emailnotifynudge' => array('type' => 'bool', 'default' => true, 'description' => 'Notify by email of nudges'),
  67. 'emailnotifymsg' => array('type' => 'bool', 'default' => true, 'description' => 'Notify by email of direct messages'),
  68. 'emailnotifyattn' => array('type' => 'bool', 'default' => true, 'description' => 'Notify by email of @-replies'),
  69. 'language' => array('type' => 'varchar', 'length' => 50, 'description' => 'preferred language'),
  70. 'timezone' => array('type' => 'varchar', 'length' => 50, 'description' => 'timezone'),
  71. 'emailpost' => array('type' => 'bool', 'default' => true, 'description' => 'Post by email'),
  72. 'sms' => array('type' => 'varchar', 'length' => 64, 'description' => 'sms phone number'),
  73. 'carrier' => array('type' => 'int', 'description' => 'foreign key to sms_carrier'),
  74. 'smsnotify' => array('type' => 'bool', 'default' => false, 'description' => 'whether to send notices to SMS'),
  75. 'smsreplies' => array('type' => 'bool', 'default' => false, 'description' => 'whether to send notices to SMS on replies'),
  76. 'smsemail' => array('type' => 'varchar', 'length' => 191, 'description' => 'built from sms and carrier'),
  77. 'uri' => array('type' => 'varchar', 'length' => 191, 'description' => 'universally unique identifier, usually a tag URI'),
  78. 'autosubscribe' => array('type' => 'bool', 'default' => false, 'description' => 'automatically subscribe to users who subscribe to us'),
  79. 'subscribe_policy' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => '0 = anybody can subscribe; 1 = require approval'),
  80. 'urlshorteningservice' => array('type' => 'varchar', 'length' => 50, 'default' => 'internal', 'description' => 'service to use for auto-shortening URLs'),
  81. 'private_stream' => array('type' => 'bool', 'default' => false, 'description' => 'whether to limit all notices to followers only'),
  82. 'created' => array('type' => 'datetime', 'description' => 'date this record was created'),
  83. 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
  84. ),
  85. 'primary key' => array('id'),
  86. 'unique keys' => array(
  87. 'user_nickname_key' => array('nickname'),
  88. 'user_email_key' => array('email'),
  89. 'user_incomingemail_key' => array('incomingemail'),
  90. 'user_sms_key' => array('sms'),
  91. 'user_uri_key' => array('uri'),
  92. ),
  93. 'foreign keys' => array(
  94. 'user_id_fkey' => array('profile', array('id' => 'id')),
  95. 'user_carrier_fkey' => array('sms_carrier', array('carrier' => 'id')),
  96. ),
  97. 'indexes' => array(
  98. 'user_created_idx' => array('created'),
  99. 'user_smsemail_idx' => array('smsemail'),
  100. ),
  101. );
  102. }
  103. protected $_profile = array();
  104. /**
  105. * @return Profile
  106. *
  107. * @throws UserNoProfileException if user has no profile
  108. */
  109. public function getProfile()
  110. {
  111. if (!isset($this->_profile[$this->id])) {
  112. $profile = Profile::getKV('id', $this->id);
  113. if (!$profile instanceof Profile) {
  114. throw new UserNoProfileException($this);
  115. }
  116. $this->_profile[$this->id] = $profile;
  117. }
  118. return $this->_profile[$this->id];
  119. }
  120. public function sameAs(Profile $other)
  121. {
  122. return $this->getProfile()->sameAs($other);
  123. }
  124. public function getUri()
  125. {
  126. return $this->uri;
  127. }
  128. public function getNickname()
  129. {
  130. return $this->getProfile()->getNickname();
  131. }
  132. public static function getByNickname($nickname)
  133. {
  134. $user = User::getKV('nickname', $nickname);
  135. if (!$user instanceof User) {
  136. throw new NoSuchUserException(array('nickname' => $nickname));
  137. }
  138. return $user;
  139. }
  140. public function isSubscribed(Profile $other)
  141. {
  142. return $this->getProfile()->isSubscribed($other);
  143. }
  144. public function hasPendingSubscription(Profile $other)
  145. {
  146. return $this->getProfile()->hasPendingSubscription($other);
  147. }
  148. /**
  149. * Get the most recent notice posted by this user, if any.
  150. *
  151. * @return mixed Notice or null
  152. */
  153. public function getCurrentNotice()
  154. {
  155. return $this->getProfile()->getCurrentNotice();
  156. }
  157. public function getCarrier()
  158. {
  159. return Sms_carrier::getKV('id', $this->carrier);
  160. }
  161. public function hasBlocked(Profile $other)
  162. {
  163. return $this->getProfile()->hasBlocked($other);
  164. }
  165. /**
  166. * Register a new user account and profile and set up default subscriptions.
  167. * If a new-user welcome message is configured, this will be sent.
  168. *
  169. * @param array $fields associative array of optional properties
  170. * string 'bio'
  171. * string 'email'
  172. * bool 'email_confirmed' pass true to mark email as pre-confirmed
  173. * string 'fullname'
  174. * string 'homepage'
  175. * string 'location' informal string description of geolocation
  176. * float 'lat' decimal latitude for geolocation
  177. * float 'lon' decimal longitude for geolocation
  178. * int 'location_id' geoname identifier
  179. * int 'location_ns' geoname namespace to interpret location_id
  180. * string 'nickname' REQUIRED
  181. * string 'password' (may be missing for eg OpenID registrations)
  182. * string 'code' invite code
  183. * ?string 'uri' permalink to notice; defaults to local notice URL
  184. * @return User object
  185. * @throws Exception on failure
  186. */
  187. public static function register(array $fields, $accept_email_fail = false)
  188. {
  189. // MAGICALLY put fields into current scope
  190. extract($fields);
  191. $profile = new Profile();
  192. if (!empty($email)) {
  193. $email = common_canonical_email($email);
  194. }
  195. // Normalize _and_ check whether it is in use. Throw NicknameException on failure.
  196. $profile->nickname = Nickname::normalize($nickname, true);
  197. $profile->profileurl = common_profile_url($profile->nickname);
  198. if (!empty($fullname)) {
  199. $profile->fullname = $fullname;
  200. }
  201. if (!empty($homepage)) {
  202. $profile->homepage = $homepage;
  203. }
  204. if (!empty($bio)) {
  205. $profile->bio = $bio;
  206. }
  207. if (!empty($location)) {
  208. $profile->location = $location;
  209. $loc = Location::fromName($location);
  210. if (!empty($loc)) {
  211. $profile->lat = $loc->lat;
  212. $profile->lon = $loc->lon;
  213. $profile->location_id = $loc->location_id;
  214. $profile->location_ns = $loc->location_ns;
  215. }
  216. }
  217. $profile->created = common_sql_now();
  218. $user = new User();
  219. $user->nickname = $profile->nickname;
  220. $invite = null;
  221. // Users who respond to invite email have proven their ownership of that address
  222. if (!empty($code)) {
  223. $invite = Invitation::getKV($code);
  224. if ($invite instanceof Invitation && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
  225. $user->email = $invite->address;
  226. }
  227. }
  228. if (isset($email_confirmed) && $email_confirmed) {
  229. $user->email = $email;
  230. }
  231. // Set default-on options here, otherwise they'll be disabled
  232. // initially for sites using caching, since the initial encache
  233. // doesn't know about the defaults in the database.
  234. $user->emailnotifysub = true;
  235. $user->emailnotifynudge = true;
  236. $user->emailnotifymsg = true;
  237. $user->emailnotifyattn = true;
  238. $user->emailpost = true;
  239. $user->created = common_sql_now();
  240. if (Event::handle('StartUserRegister', array($profile))) {
  241. $profile->query('START TRANSACTION');
  242. $id = $profile->insert();
  243. if ($id === false) {
  244. common_log_db_error($profile, 'INSERT', __FILE__);
  245. $profile->query('ROLLBACK');
  246. // TRANS: Profile data could not be inserted for some reason.
  247. throw new ServerException(_m('Could not insert profile data for new user.'));
  248. }
  249. // Necessary because id has been known to be reissued.
  250. if ($profile->hasRole(Profile_role::DELETED)) {
  251. $profile->revokeRole(Profile_role::DELETED);
  252. }
  253. $user->id = $id;
  254. if (!empty($uri)) {
  255. $user->uri = $uri;
  256. } else {
  257. $user->uri = common_user_uri($user);
  258. }
  259. if (!empty($password)) { // may not have a password for OpenID users
  260. $user->password = common_munge_password($password);
  261. }
  262. $result = $user->insert();
  263. if ($result === false) {
  264. common_log_db_error($user, 'INSERT', __FILE__);
  265. $profile->query('ROLLBACK');
  266. // TRANS: User data could not be inserted for some reason.
  267. throw new ServerException(_m('Could not insert user data for new user.'));
  268. }
  269. // Everyone is subscribed to themself
  270. $subscription = new Subscription();
  271. $subscription->subscriber = $user->id;
  272. $subscription->subscribed = $user->id;
  273. $subscription->created = $user->created;
  274. $result = $subscription->insert();
  275. if (!$result) {
  276. common_log_db_error($subscription, 'INSERT', __FILE__);
  277. $profile->query('ROLLBACK');
  278. // TRANS: Subscription data could not be inserted for some reason.
  279. throw new ServerException(_m('Could not insert subscription data for new user.'));
  280. }
  281. // Mark that this invite was converted
  282. if (!empty($invite)) {
  283. $invite->convert($user);
  284. }
  285. if (!empty($email) && empty($user->email)) {
  286. // The actual email will be sent further down, after the database COMMIT
  287. $confirm = new Confirm_address();
  288. $confirm->code = common_confirmation_code(128);
  289. $confirm->user_id = $user->id;
  290. $confirm->address = $email;
  291. $confirm->address_type = 'email';
  292. $result = $confirm->insert();
  293. if ($result===false) {
  294. common_log_db_error($confirm, 'INSERT', __FILE__);
  295. $profile->query('ROLLBACK');
  296. // TRANS: Email confirmation data could not be inserted for some reason.
  297. throw new ServerException(_m('Could not insert email confirmation data for new user.'));
  298. }
  299. }
  300. if (!empty($code) && $user->email) {
  301. $user->emailChanged();
  302. }
  303. // Default system subscription
  304. $defnick = common_config('newuser', 'default');
  305. if (!empty($defnick)) {
  306. $defuser = User::getKV('nickname', $defnick);
  307. if (empty($defuser)) {
  308. common_log(
  309. LOG_WARNING,
  310. sprintf('Default user %s does not exist.', $defnick),
  311. __FILE__
  312. );
  313. } else {
  314. Subscription::ensureStart($profile, $defuser->getProfile());
  315. }
  316. }
  317. $profile->query('COMMIT');
  318. if (!empty($email) && empty($user->email)) {
  319. try {
  320. $confirm->sendConfirmation();
  321. } catch (EmailException $e) {
  322. common_log(LOG_ERR, "Could not send user registration email for user id=={$profile->getID()}: {$e->getMessage()}");
  323. if (!$accept_email_fail) {
  324. throw $e;
  325. }
  326. }
  327. }
  328. // Welcome message
  329. $welcome = common_config('newuser', 'welcome');
  330. if (!empty($welcome)) {
  331. $welcomeuser = User::getKV('nickname', $welcome);
  332. if (empty($welcomeuser)) {
  333. common_log(
  334. LOG_WARNING,
  335. sprintf('Welcome user %s does not exist.', $defnick),
  336. __FILE__
  337. );
  338. } else {
  339. $notice = Notice::saveNew(
  340. $welcomeuser->id,
  341. // TRANS: Notice given on user registration.
  342. // TRANS: %1$s is the sitename, $2$s is the registering user's nickname.
  343. sprintf(
  344. _('Welcome to %1$s, @%2$s!'),
  345. common_config('site', 'name'),
  346. $profile->getNickname()
  347. ),
  348. 'system'
  349. );
  350. }
  351. }
  352. Event::handle('EndUserRegister', array($profile));
  353. }
  354. if (!$user instanceof User || empty($user->id)) {
  355. throw new ServerException('User could not be registered. Probably an event hook that failed.');
  356. }
  357. return $user;
  358. }
  359. // Things we do when the email changes
  360. public function emailChanged()
  361. {
  362. $invites = new Invitation();
  363. $invites->address = $this->email;
  364. $invites->address_type = 'email';
  365. if ($invites->find()) {
  366. while ($invites->fetch()) {
  367. try {
  368. $other = Profile::getByID($invites->user_id);
  369. Subscription::start($other, $this->getProfile());
  370. } catch (NoResultException $e) {
  371. // profile did not exist
  372. } catch (AlreadyFulfilledException $e) {
  373. // already subscribed to this profile
  374. } catch (Exception $e) {
  375. common_log(LOG_ERR, 'On-invitation-completion subscription failed when subscribing '._ve($invites->user_id).' to '.$this->getProfile()->getID().': '._ve($e->getMessage()));
  376. }
  377. }
  378. }
  379. }
  380. public function mutuallySubscribed(Profile $other)
  381. {
  382. return $this->getProfile()->mutuallySubscribed($other);
  383. }
  384. public function mutuallySubscribedUsers()
  385. {
  386. $user = new User();
  387. // 3-way join; probably should get cached
  388. $user->query(sprintf(
  389. 'SELECT %1$s.* ' .
  390. 'FROM subscription AS sub1 INNER JOIN %1$s ON sub1.subscribed = %1$s.id ' .
  391. 'INNER JOIN subscription AS sub2 ON %1$s.id = sub2.subscriber ' .
  392. 'WHERE sub1.subscriber = %2$d AND sub2.subscribed = %2$d ' .
  393. 'ORDER BY %1$s.nickname',
  394. $user->escapedTableName(),
  395. $this->id
  396. ));
  397. return $user;
  398. }
  399. public function getReplies($offset = 0, $limit = NOTICES_PER_PAGE, $since_id = 0, $before_id = 0)
  400. {
  401. return $this->getProfile()->getReplies($offset, $limit, $since_id, $before_id);
  402. }
  403. public function getTaggedNotices($tag, $offset = 0, $limit = NOTICES_PER_PAGE, $since_id = 0, $before_id = 0)
  404. {
  405. return $this->getProfile()->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id);
  406. }
  407. public function getNotices($offset = 0, $limit = NOTICES_PER_PAGE, $since_id = 0, $before_id = 0)
  408. {
  409. return $this->getProfile()->getNotices($offset, $limit, $since_id, $before_id);
  410. }
  411. public function block(Profile $other)
  412. {
  413. // Add a new block record
  414. // no blocking (and thus unsubbing from) yourself
  415. if ($this->id == $other->id) {
  416. common_log(
  417. LOG_WARNING,
  418. sprintf(
  419. "Profile ID %d (%s) tried to block themself.",
  420. $this->id,
  421. $this->nickname
  422. )
  423. );
  424. return false;
  425. }
  426. $block = new Profile_block();
  427. $block->query('START TRANSACTION');
  428. $block->blocker = $this->id;
  429. $block->blocked = $other->id;
  430. $result = $block->insert();
  431. if (!$result) {
  432. common_log_db_error($block, 'INSERT', __FILE__);
  433. return false;
  434. }
  435. $self = $this->getProfile();
  436. if (Subscription::exists($other, $self)) {
  437. Subscription::cancel($other, $self);
  438. }
  439. if (Subscription::exists($self, $other)) {
  440. Subscription::cancel($self, $other);
  441. }
  442. $block->query('COMMIT');
  443. return true;
  444. }
  445. public function unblock(Profile $other)
  446. {
  447. // Get the block record
  448. $block = Profile_block::exists($this->getProfile(), $other);
  449. if (!$block) {
  450. return false;
  451. }
  452. $result = $block->delete();
  453. if (!$result) {
  454. common_log_db_error($block, 'DELETE', __FILE__);
  455. return false;
  456. }
  457. return true;
  458. }
  459. public function isMember(User_group $group)
  460. {
  461. return $this->getProfile()->isMember($group);
  462. }
  463. public function isAdmin(User_group $group)
  464. {
  465. return $this->getProfile()->isAdmin($group);
  466. }
  467. public function getGroups($offset = 0, $limit = null)
  468. {
  469. return $this->getProfile()->getGroups($offset, $limit);
  470. }
  471. /**
  472. * Request to join the given group.
  473. * May throw exceptions on failure.
  474. *
  475. * @param User_group $group
  476. * @return Group_member
  477. */
  478. public function joinGroup(User_group $group)
  479. {
  480. return $this->getProfile()->joinGroup($group);
  481. }
  482. /**
  483. * Leave a group that this user is a member of.
  484. *
  485. * @param User_group $group
  486. */
  487. public function leaveGroup(User_group $group)
  488. {
  489. return $this->getProfile()->leaveGroup($group);
  490. }
  491. public function getSubscribed($offset = 0, $limit = null)
  492. {
  493. return $this->getProfile()->getSubscribed($offset, $limit);
  494. }
  495. public function getSubscribers($offset = 0, $limit = null)
  496. {
  497. return $this->getProfile()->getSubscribers($offset, $limit);
  498. }
  499. public function getTaggedSubscribers($tag, $offset = 0, $limit = null)
  500. {
  501. return $this->getProfile()->getTaggedSubscribers($tag, $offset, $limit);
  502. }
  503. public function getTaggedSubscriptions($tag, $offset = 0, $limit = null)
  504. {
  505. return $this->getProfile()->getTaggedSubscriptions($tag, $offset, $limit);
  506. }
  507. public function hasRight($right)
  508. {
  509. return $this->getProfile()->hasRight($right);
  510. }
  511. public function delete($useWhere = false)
  512. {
  513. if (empty($this->id)) {
  514. common_log(LOG_WARNING, "Ambiguous User->delete(); skipping related tables.");
  515. return parent::delete($useWhere);
  516. }
  517. try {
  518. if (!$this->hasRole(Profile_role::DELETED)) {
  519. $profile = $this->getProfile();
  520. $profile->delete();
  521. }
  522. } catch (UserNoProfileException $unp) {
  523. common_log(LOG_INFO, "User {$this->nickname} has no profile; continuing deletion.");
  524. }
  525. $related = array(
  526. 'Confirm_address',
  527. 'Remember_me',
  528. 'Foreign_link',
  529. 'Invitation',
  530. );
  531. Event::handle('UserDeleteRelated', array($this, &$related));
  532. foreach ($related as $cls) {
  533. $inst = new $cls();
  534. $inst->user_id = $this->id;
  535. $inst->delete();
  536. }
  537. $this->_deleteTags();
  538. $this->_deleteBlocks();
  539. return parent::delete($useWhere);
  540. }
  541. public function _deleteTags()
  542. {
  543. $tag = new Profile_tag();
  544. $tag->tagger = $this->id;
  545. $tag->delete();
  546. }
  547. public function _deleteBlocks()
  548. {
  549. $block = new Profile_block();
  550. $block->blocker = $this->id;
  551. $block->delete();
  552. // XXX delete group block? Reset blocker?
  553. }
  554. public function hasRole($name)
  555. {
  556. return $this->getProfile()->hasRole($name);
  557. }
  558. public function grantRole($name)
  559. {
  560. return $this->getProfile()->grantRole($name);
  561. }
  562. public function revokeRole($name)
  563. {
  564. return $this->getProfile()->revokeRole($name);
  565. }
  566. public function isSandboxed()
  567. {
  568. return $this->getProfile()->isSandboxed();
  569. }
  570. public function isSilenced()
  571. {
  572. return $this->getProfile()->isSilenced();
  573. }
  574. public function receivesEmailNotifications()
  575. {
  576. // We could do this in one large if statement, but that's not as easy to read
  577. // Don't send notifications if we don't know the user's email address or it is
  578. // explicitly undesired by the user's own settings.
  579. if (empty($this->email) || !$this->emailnotifyattn) {
  580. return false;
  581. }
  582. // Don't send notifications to a user who is sandboxed or silenced
  583. if ($this->isSandboxed() || $this->isSilenced()) {
  584. return false;
  585. }
  586. return true;
  587. }
  588. public function repeatedByMe($offset = 0, $limit = 20, $since_id = null, $max_id = null)
  589. {
  590. // FIXME: Use another way to get Profile::current() since we
  591. // want to avoid confusion between session user and queue processing.
  592. $stream = new RepeatedByMeNoticeStream($this->getProfile(), Profile::current());
  593. return $stream->getNotices($offset, $limit, $since_id, $max_id);
  594. }
  595. public function repeatsOfMe($offset = 0, $limit = 20, $since_id = null, $max_id = null)
  596. {
  597. // FIXME: Use another way to get Profile::current() since we
  598. // want to avoid confusion between session user and queue processing.
  599. $stream = new RepeatsOfMeNoticeStream($this->getProfile(), Profile::current());
  600. return $stream->getNotices($offset, $limit, $since_id, $max_id);
  601. }
  602. public function repeatedToMe($offset = 0, $limit = 20, $since_id = null, $max_id = null)
  603. {
  604. return $this->getProfile()->repeatedToMe($offset, $limit, $since_id, $max_id);
  605. }
  606. public static function siteOwner()
  607. {
  608. $owner = self::cacheGet('user:site_owner');
  609. if ($owner === false) { // cache miss
  610. $pr = new Profile_role();
  611. $pr->role = Profile_role::OWNER;
  612. $pr->orderBy('created');
  613. $pr->limit(1);
  614. if (!$pr->find(true)) {
  615. throw new NoResultException($pr);
  616. }
  617. $owner = User::getKV('id', $pr->profile_id);
  618. self::cacheSet('user:site_owner', $owner);
  619. }
  620. if ($owner instanceof User) {
  621. return $owner;
  622. }
  623. throw new ServerException(_('No site owner configured.'));
  624. }
  625. /**
  626. * Pull the primary site account to use in single-user mode.
  627. * If a valid user nickname is listed in 'singleuser':'nickname'
  628. * in the config, this will be used; otherwise the site owner
  629. * account is taken by default.
  630. *
  631. * @return User
  632. * @throws ServerException if no valid single user account is present
  633. * @throws ServerException if called when not in single-user mode
  634. */
  635. public static function singleUser()
  636. {
  637. if (!common_config('singleuser', 'enabled')) {
  638. // TRANS: Server exception.
  639. throw new ServerException(_('Single-user mode code called when not enabled.'));
  640. }
  641. if ($nickname = common_config('singleuser', 'nickname')) {
  642. $user = User::getKV('nickname', $nickname);
  643. if ($user instanceof User) {
  644. return $user;
  645. }
  646. }
  647. // If there was no nickname or no user by that nickname,
  648. // try the site owner. Throws exception if not configured.
  649. return User::siteOwner();
  650. }
  651. /**
  652. * This is kind of a hack for using external setup code that's trying to
  653. * build single-user sites.
  654. *
  655. * Will still return a username if the config singleuser/nickname is set
  656. * even if the account doesn't exist, which normally indicates that the
  657. * site is horribly misconfigured.
  658. *
  659. * At the moment, we need to let it through so that router setup can
  660. * complete, otherwise we won't be able to create the account.
  661. *
  662. * This will be easier when we can more easily create the account and
  663. * *then* switch the site to 1user mode without jumping through hoops.
  664. *
  665. * @return string
  666. * @throws ServerException if no valid single user account is present
  667. * @throws ServerException if called when not in single-user mode
  668. */
  669. public static function singleUserNickname()
  670. {
  671. try {
  672. $user = User::singleUser();
  673. return $user->nickname;
  674. } catch (Exception $e) {
  675. if (common_config('singleuser', 'enabled') && common_config('singleuser', 'nickname')) {
  676. common_log(LOG_WARNING, "Warning: code attempting to pull single-user nickname when the account does not exist. If this is not setup time, this is probably a bug.");
  677. return common_config('singleuser', 'nickname');
  678. }
  679. throw $e;
  680. }
  681. }
  682. /**
  683. * Find and shorten links in the given text using this user's URL shortening
  684. * settings.
  685. *
  686. * By default, links will be left untouched if the text is shorter than the
  687. * configured maximum notice length. Pass true for the $always parameter
  688. * to force all links to be shortened regardless.
  689. *
  690. * Side effects: may save file and file_redirection records for referenced URLs.
  691. *
  692. * @param string $text
  693. * @param boolean $always
  694. * @return string
  695. */
  696. public function shortenLinks($text, $always=false)
  697. {
  698. return common_shorten_links($text, $always, $this);
  699. }
  700. /*
  701. * Get a list of OAuth client applications that have access to this
  702. * user's account.
  703. */
  704. public function getConnectedApps($offset = 0, $limit = null)
  705. {
  706. $qry =
  707. 'SELECT u.* ' .
  708. 'FROM oauth_application_user AS u, oauth_application AS a ' .
  709. 'WHERE u.profile_id = %d ' .
  710. 'AND a.id = u.application_id ' .
  711. 'AND u.access_type > 0 ' .
  712. 'ORDER BY u.created DESC ';
  713. if ($offset > 0) {
  714. $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
  715. }
  716. $apps = new Oauth_application_user();
  717. $cnt = $apps->query(sprintf($qry, $this->id));
  718. return $apps;
  719. }
  720. /**
  721. * Magic function called at serialize() time.
  722. *
  723. * We use this to drop a couple process-specific references
  724. * from DB_DataObject which can cause trouble in future
  725. * processes.
  726. *
  727. * @return array of variable names to include in serialization.
  728. */
  729. public function __sleep()
  730. {
  731. $vars = parent::__sleep();
  732. $skip = array('_profile');
  733. return array_diff($vars, $skip);
  734. }
  735. public static function recoverPassword($nore)
  736. {
  737. require_once INSTALLDIR . '/lib/util/mail.php';
  738. // $confirm_email will be used as a fallback if our user doesn't have a confirmed email
  739. $confirm_email = null;
  740. if (common_is_email($nore)) {
  741. $user = User::getKV('email', common_canonical_email($nore));
  742. // See if it's an unconfirmed email address
  743. if (!$user instanceof User) {
  744. // Warning: it may actually be legit to have multiple folks
  745. // who have claimed, but not yet confirmed, the same address.
  746. // We'll only send to the first one that comes up.
  747. $confirm_email = new Confirm_address();
  748. $confirm_email->address = common_canonical_email($nore);
  749. $confirm_email->address_type = 'email';
  750. if ($confirm_email->find(true)) {
  751. $user = User::getKV('id', $confirm_email->user_id);
  752. }
  753. }
  754. // No luck finding anyone by that email address.
  755. if (!$user instanceof User) {
  756. if (common_config('site', 'fakeaddressrecovery')) {
  757. // Return without actually doing anything! We fake address recovery
  758. // to avoid revealing which email addresses are registered with the site.
  759. return;
  760. }
  761. // TRANS: Information on password recovery form if no known e-mail address was specified.
  762. throw new ClientException(_('No user with that email address exists here.'));
  763. }
  764. } else {
  765. // This might throw a NicknameException on bad nicknames
  766. $user = User::getKV('nickname', common_canonical_nickname($nore));
  767. if (!$user instanceof User) {
  768. // TRANS: Information on password recovery form if no known username was specified.
  769. throw new ClientException(_('No user with that nickname exists here.'));
  770. }
  771. }
  772. // Try to get an unconfirmed email address if they used a user name
  773. if (empty($user->email) && $confirm_email === null) {
  774. $confirm_email = new Confirm_address();
  775. $confirm_email->user_id = $user->id;
  776. $confirm_email->address_type = 'email';
  777. $confirm_email->find();
  778. if (!$confirm_email->fetch()) {
  779. // Nothing found, so let's reset it to null
  780. $confirm_email = null;
  781. }
  782. }
  783. if (empty($user->email) && !$confirm_email instanceof Confirm_address) {
  784. // TRANS: Client error displayed on password recovery form if a user does not have a registered e-mail address.
  785. throw new ClientException(_('No registered email address for that user.'));
  786. }
  787. // Success! We have a valid user and a confirmed or unconfirmed email address
  788. $confirm = new Confirm_address();
  789. $confirm->code = common_confirmation_code(128);
  790. $confirm->address_type = 'recover';
  791. $confirm->user_id = $user->id;
  792. $confirm->address = $user->email ?: $confirm_email->address;
  793. if (!$confirm->insert()) {
  794. common_log_db_error($confirm, 'INSERT', __FILE__);
  795. // TRANS: Server error displayed if e-mail address confirmation fails in the database on the password recovery form.
  796. throw new ServerException(_('Error saving address confirmation.'));
  797. }
  798. // @todo FIXME: needs i18n.
  799. $body = "Hey, $user->nickname.";
  800. $body .= "\n\n";
  801. $body .= 'Someone just asked for a new password ' .
  802. 'for this account on ' . common_config('site', 'name') . '.';
  803. $body .= "\n\n";
  804. $body .= 'If it was you, and you want to confirm, use the URL below:';
  805. $body .= "\n\n";
  806. $body .= "\t" . common_local_url(
  807. 'recoverpassword',
  808. ['code' => $confirm->code]
  809. );
  810. $body .= "\n\n";
  811. $body .= 'If not, just ignore this message.';
  812. $body .= "\n\n";
  813. $body .= 'Thanks for your time, ';
  814. $body .= "\n";
  815. $body .= common_config('site', 'name');
  816. $body .= "\n";
  817. $headers = _mail_prepare_headers('recoverpassword', $user->nickname, $user->nickname);
  818. // TRANS: Subject for password recovery e-mail.
  819. mail_to_user($user, _('Password recovery requested'), $body, $headers, $confirm->address);
  820. }
  821. public function streamModeOnly()
  822. {
  823. if (common_config('oldschool', 'enabled')) {
  824. $osp = Old_school_prefs::getKV('user_id', $this->id);
  825. if (!empty($osp)) {
  826. return $osp->stream_mode_only;
  827. }
  828. }
  829. return false;
  830. }
  831. public function streamNicknames()
  832. {
  833. if (common_config('oldschool', 'enabled')) {
  834. $osp = Old_school_prefs::getKV('user_id', $this->id);
  835. if (!empty($osp)) {
  836. return $osp->stream_nicknames;
  837. }
  838. }
  839. return false;
  840. }
  841. public function registrationActivity()
  842. {
  843. $profile = $this->getProfile();
  844. $service = new ActivityObject();
  845. $service->type = ActivityObject::SERVICE;
  846. $service->title = common_config('site', 'name');
  847. $service->link = common_root_url();
  848. $service->id = $service->link;
  849. $act = new Activity();
  850. $act->actor = $profile->asActivityObject();
  851. $act->verb = ActivityVerb::JOIN;
  852. $act->objects[] = $service;
  853. $act->id = TagURI::mint(
  854. 'user:register:%d',
  855. $this->id
  856. );
  857. $act->time = strtotime($this->created);
  858. $act->title = _("Register");
  859. $act->content = sprintf(
  860. _('%1$s joined %2$s.'),
  861. $profile->getBestName(),
  862. $service->title
  863. );
  864. return $act;
  865. }
  866. public function isPrivateStream()
  867. {
  868. return $this->getProfile()->isPrivateStream();
  869. }
  870. public function hasPassword()
  871. {
  872. return !empty($this->password);
  873. }
  874. public function setPassword($password)
  875. {
  876. $orig = clone($this);
  877. $this->password = common_munge_password($password, $this->getProfile());
  878. if ($this->validate() !== true) {
  879. // TRANS: Form validation error on page where to change password.
  880. throw new ServerException(_('Error saving user; invalid.'));
  881. }
  882. if (!$this->update($orig)) {
  883. common_log_db_error($this, 'UPDATE', __FILE__);
  884. // TRANS: Server error displayed on page where to change password when password change
  885. // TRANS: could not be made because of a server error.
  886. throw new ServerException(_('Cannot save new password.'));
  887. }
  888. }
  889. public function delPref($namespace, $topic)
  890. {
  891. return $this->getProfile()->delPref($namespace, $topic);
  892. }
  893. public function getPref($namespace, $topic, $default=null)
  894. {
  895. return $this->getProfile()->getPref($namespace, $topic, $default);
  896. }
  897. public function getConfigPref($namespace, $topic)
  898. {
  899. return $this->getProfile()->getConfigPref($namespace, $topic);
  900. }
  901. public function setPref($namespace, $topic, $data)
  902. {
  903. return $this->getProfile()->setPref($namespace, $topic, $data);
  904. }
  905. }