User.php 38 KB

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