User.php 38 KB

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