User.php 38 KB

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