Profile.php 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898
  1. <?php
  2. // This file is part of GNU social - https://www.gnu.org/software/social
  3. //
  4. // GNU social is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // GNU social is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * Table Definition for profile
  18. *
  19. * @copyright 2008-2011 StatusNet, Inc.
  20. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  21. */
  22. defined('GNUSOCIAL') || die();
  23. class Profile extends Managed_DataObject
  24. {
  25. public $is_mariadb;
  26. public $group_id;
  27. public $profile_id;
  28. public $is_admin;
  29. public $uri;
  30. protected $password;
  31. protected $email;
  32. protected $incomingemail;
  33. protected $emailnotifysub;
  34. protected $emailnotifyfav;
  35. protected $emailnotifynudge;
  36. protected $emailnotifymsg;
  37. protected $emailnotifyattn;
  38. protected $language;
  39. protected $timezone;
  40. protected $emailpost;
  41. protected $sms;
  42. protected $carrier;
  43. protected $smsnotify;
  44. protected $smsreplies;
  45. protected $smsemail;
  46. protected $autosubscribe;
  47. protected $subscribe_policy;
  48. protected $urlshorteningservice;
  49. protected $private_stream;
  50. public $__table = 'profile'; // table name
  51. public $id; // int(4) primary_key not_null
  52. public $nickname; // varchar(64) multiple_key not_null
  53. public $fullname; // text()
  54. public $profileurl; // text()
  55. public $homepage; // text()
  56. public $bio; // text() multiple_key
  57. public $location; // text()
  58. public $lat; // decimal(10,7)
  59. public $lon; // decimal(10,7)
  60. public $location_id; // int(4)
  61. public $location_ns; // int(4)
  62. public $created; // datetime()
  63. public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
  64. public static function schemaDef()
  65. {
  66. $def = array(
  67. 'description' => 'local and remote users have profiles',
  68. 'fields' => array(
  69. 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
  70. 'nickname' => array('type' => 'varchar', 'length' => 191, 'not null' => true, 'description' => 'nickname or username', 'collate' => 'utf8_general_ci'),
  71. 'fullname' => array('type' => 'text', 'description' => 'display name', 'collate' => 'utf8_general_ci'),
  72. 'profileurl' => array('type' => 'text', 'description' => 'URL, cached so we dont regenerate'),
  73. 'homepage' => array('type' => 'text', 'description' => 'identifying URL', 'collate' => 'utf8_general_ci'),
  74. 'bio' => array('type' => 'text', 'description' => 'descriptive biography', 'collate' => 'utf8_general_ci'),
  75. 'location' => array('type' => 'text', 'description' => 'physical location', 'collate' => 'utf8_general_ci'),
  76. 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
  77. 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
  78. 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
  79. 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
  80. 'created' => array('type' => 'datetime', 'description' => 'date this record was created'),
  81. 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
  82. ),
  83. 'primary key' => array('id'),
  84. 'indexes' => array(
  85. 'profile_nickname_created_id_idx' => array('nickname', 'created', 'id'),
  86. ),
  87. 'fulltext indexes' => array(
  88. 'profile_fulltext_idx' => array('nickname', 'fullname', 'location', 'bio', 'homepage'),
  89. ),
  90. );
  91. return $def;
  92. }
  93. public static function getByEmail($email)
  94. {
  95. // in the future, profiles should have emails stored...
  96. $user = User::getKV('email', $email);
  97. if (!($user instanceof User)) {
  98. throw new NoSuchUserException(array('email'=>$email));
  99. }
  100. return $user->getProfile();
  101. }
  102. protected $_user = array();
  103. public function getUser()
  104. {
  105. if (!isset($this->_user[$this->id])) {
  106. $cur_user = common_current_user();
  107. if (($cur_user instanceof User) && $cur_user->sameAs($this)) {
  108. $user = $cur_user;
  109. } else {
  110. $user = User::getKV('id', $this->id);
  111. if (!$user instanceof User) {
  112. throw new NoSuchUserException(array('id'=>$this->id));
  113. }
  114. }
  115. $this->_user[$this->id] = $user;
  116. }
  117. return $this->_user[$this->id];
  118. }
  119. protected $_group = array();
  120. public function getGroup()
  121. {
  122. if (!isset($this->_group[$this->id])) {
  123. $group = User_group::getKV('profile_id', $this->id);
  124. if (!$group instanceof User_group) {
  125. throw new NoSuchGroupException(array('profile_id'=>$this->id));
  126. }
  127. $this->_group[$this->id] = $group;
  128. }
  129. return $this->_group[$this->id];
  130. }
  131. public function isGroup()
  132. {
  133. try {
  134. $this->getGroup();
  135. return true;
  136. } catch (NoSuchGroupException $e) {
  137. return false;
  138. }
  139. }
  140. public function isPerson()
  141. {
  142. // Maybe other things than PERSON and GROUP can have Profiles in the future?
  143. return !$this->isGroup();
  144. }
  145. public function isLocal()
  146. {
  147. try {
  148. $this->getUser();
  149. } catch (NoSuchUserException $e) {
  150. return false;
  151. }
  152. return true;
  153. }
  154. // Returns false if the user has no password (which will always
  155. // be the case for remote users). This can be the case for OpenID
  156. // logins or other mechanisms which don't store a password hash.
  157. public function hasPassword()
  158. {
  159. try {
  160. return $this->getUser()->hasPassword();
  161. } catch (NoSuchUserException $e) {
  162. return false;
  163. }
  164. }
  165. public function getObjectType()
  166. {
  167. // FIXME: More types... like peopletags and whatever
  168. if ($this->isGroup()) {
  169. return ActivityObject::GROUP;
  170. } else {
  171. return ActivityObject::PERSON;
  172. }
  173. }
  174. public function getAvatar($width, $height=null)
  175. {
  176. return Avatar::byProfile($this, $width, $height);
  177. }
  178. public function setOriginal($filename)
  179. {
  180. if ($this->isGroup()) {
  181. // Until Group avatars are handled just like profile avatars.
  182. return $this->getGroup()->setOriginal($filename);
  183. }
  184. $imagefile = new ImageFile(Avatar::path($filename));
  185. $avatar = new Avatar();
  186. $avatar->profile_id = $this->id;
  187. $avatar->width = $imagefile->width;
  188. $avatar->height = $imagefile->height;
  189. $avatar->mediatype = image_type_to_mime_type($imagefile->type);
  190. $avatar->filename = $filename;
  191. $avatar->original = true;
  192. $avatar->created = common_sql_now();
  193. // XXX: start a transaction here
  194. if (!Avatar::deleteFromProfile($this, true) || !$avatar->insert()) {
  195. // If we can't delete the old avatars, let's abort right here.
  196. @unlink(Avatar::path($filename));
  197. return null;
  198. }
  199. return $avatar;
  200. }
  201. /**
  202. * Gets either the full name (if filled) or the nickname.
  203. *
  204. * @return string
  205. */
  206. public function getBestName()
  207. {
  208. return ($this->fullname) ? $this->fullname : $this->nickname;
  209. }
  210. /**
  211. * Takes the currently scoped profile into account to give a name
  212. * to list in notice streams. Preferences may differ between profiles.
  213. */
  214. public function getStreamName()
  215. {
  216. $user = common_current_user();
  217. if ($user instanceof User && $user->streamNicknames()) {
  218. return $this->nickname;
  219. }
  220. return $this->getBestName();
  221. }
  222. /**
  223. * Gets the full name (if filled) with acct URI, URL, or URI as a
  224. * parenthetical (in that order, for each not found). If no full
  225. * name is found only the second part is returned, without ()s.
  226. *
  227. * @return string
  228. */
  229. public function getFancyName()
  230. {
  231. $uri = null;
  232. try {
  233. $uri = $this->getAcctUri(false);
  234. } catch (ProfileNoAcctUriException $e) {
  235. try {
  236. $uri = $this->getUrl();
  237. } catch (InvalidUrlException $e) {
  238. $uri = $this->getUri();
  239. }
  240. }
  241. if (mb_strlen($this->getFullname() ?? "") > 0) {
  242. // TRANS: The "fancy name": Full name of a profile or group (%1$s) followed by some URI (%2$s) in parentheses.
  243. return sprintf(_m('FANCYNAME', '%1$s (%2$s)'), $this->getFullname(), $uri);
  244. } else {
  245. return $uri;
  246. }
  247. }
  248. /**
  249. * Get the most recent notice posted by this user, if any.
  250. *
  251. * @return mixed Notice or null
  252. */
  253. public function getCurrentNotice(Profile $scoped = null)
  254. {
  255. try {
  256. $notice = $this->getNotices(0, 1, 0, 0, $scoped);
  257. if ($notice->fetch()) {
  258. if ($notice instanceof ArrayWrapper) {
  259. // hack for things trying to work with single notices
  260. // ...but this shouldn't happen anymore I think. Keeping it for safety...
  261. return $notice->_items[0];
  262. }
  263. return $notice;
  264. }
  265. } catch (PrivateStreamException $e) {
  266. // Maybe we should let this through if it's handled well upstream
  267. return null;
  268. }
  269. return null;
  270. }
  271. public function getReplies($offset = 0, $limit = NOTICES_PER_PAGE, $since_id = 0, $before_id = 0)
  272. {
  273. return Reply::stream($this->getID(), $offset, $limit, $since_id, $before_id);
  274. }
  275. public function getTaggedNotices($tag, $offset = 0, $limit = NOTICES_PER_PAGE, $since_id = 0, $max_id = 0)
  276. {
  277. //FIXME: Get Profile::current() some other way to avoid possible
  278. // confusion between current session profile and background processing.
  279. $stream = new TaggedProfileNoticeStream($this, $tag, Profile::current());
  280. return $stream->getNotices($offset, $limit, $since_id, $max_id);
  281. }
  282. public function getNotices($offset = 0, $limit = NOTICES_PER_PAGE, $since_id = 0, $max_id = 0, Profile $scoped = null)
  283. {
  284. $stream = new ProfileNoticeStream($this, $scoped);
  285. return $stream->getNotices($offset, $limit, $since_id, $max_id);
  286. }
  287. public function isMember(User_group $group)
  288. {
  289. $groups = $this->getGroups(0, null);
  290. while ($groups instanceof User_group && $groups->fetch()) {
  291. if ($groups->id == $group->id) {
  292. return true;
  293. }
  294. }
  295. return false;
  296. }
  297. public function isAdmin(User_group $group)
  298. {
  299. $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
  300. 'group_id' => $group->id));
  301. return (!empty($gm) && $gm->is_admin);
  302. }
  303. public function isPendingMember($group)
  304. {
  305. $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
  306. 'group_id' => $group->id));
  307. return !empty($request);
  308. }
  309. public function getGroups($offset = 0, $limit = PROFILES_PER_PAGE)
  310. {
  311. $ids = array();
  312. $keypart = sprintf('profile:groups:%d', $this->id);
  313. $idstring = self::cacheGet($keypart);
  314. if ($idstring !== false) {
  315. $ids = explode(',', $idstring);
  316. } else {
  317. $gm = new Group_member();
  318. $gm->profile_id = $this->id;
  319. $gm->orderBy('created DESC, group_id DESC');
  320. if ($gm->find()) {
  321. while ($gm->fetch()) {
  322. $ids[] = $gm->group_id;
  323. }
  324. }
  325. self::cacheSet($keypart, implode(',', $ids));
  326. }
  327. if (!is_null($offset) && !is_null($limit)) {
  328. $ids = array_slice($ids, $offset, $limit);
  329. }
  330. try {
  331. return User_group::multiGet('id', $ids);
  332. } catch (NoResultException $e) {
  333. return null; // throw exception when we handle it everywhere
  334. }
  335. }
  336. public function getGroupCount()
  337. {
  338. $groups = $this->getGroups(0, null);
  339. return $groups instanceof User_group
  340. ? $groups->N
  341. : 0;
  342. }
  343. public function isTagged($peopletag)
  344. {
  345. $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
  346. 'tagged' => $this->id,
  347. 'tag' => $peopletag->tag));
  348. return !empty($tag);
  349. }
  350. public function canTag($tagged)
  351. {
  352. if (empty($tagged)) {
  353. return false;
  354. }
  355. if ($tagged->id == $this->id) {
  356. return true;
  357. }
  358. $all = common_config('peopletag', 'allow_tagging', 'all');
  359. $local = common_config('peopletag', 'allow_tagging', 'local');
  360. $remote = common_config('peopletag', 'allow_tagging', 'remote');
  361. $subs = common_config('peopletag', 'allow_tagging', 'subs');
  362. if ($all) {
  363. return true;
  364. }
  365. $tagged_user = $tagged->getUser();
  366. if (!empty($tagged_user)) {
  367. if ($local) {
  368. return true;
  369. }
  370. } elseif ($subs) {
  371. return (Subscription::exists($this, $tagged) ||
  372. Subscription::exists($tagged, $this));
  373. } elseif ($remote) {
  374. return true;
  375. }
  376. return false;
  377. }
  378. public function getLists(Profile $scoped = null, $offset = 0, $limit = null, $since_id = 0, $max_id = 0)
  379. {
  380. $ids = array();
  381. $keypart = sprintf('profile:lists:%d', $this->id);
  382. $idstr = self::cacheGet($keypart);
  383. if ($idstr !== false) {
  384. $ids = explode(',', $idstr);
  385. } else {
  386. $list = new Profile_list();
  387. $list->selectAdd();
  388. $list->selectAdd('id');
  389. $list->tagger = $this->id;
  390. $list->selectAdd('id as "cursor"');
  391. if ($since_id > 0) {
  392. $list->whereAdd('id > ' . $since_id);
  393. }
  394. if ($max_id > 0) {
  395. $list->whereAdd('id <= ' . $max_id);
  396. }
  397. if ($offset >= 0 && !is_null($limit)) {
  398. $list->limit($offset, $limit);
  399. }
  400. $list->orderBy('id DESC');
  401. if ($list->find()) {
  402. while ($list->fetch()) {
  403. $ids[] = $list->id;
  404. }
  405. }
  406. self::cacheSet($keypart, implode(',', $ids));
  407. }
  408. $showPrivate = $this->sameAs($scoped);
  409. $lists = array();
  410. foreach ($ids as $id) {
  411. $list = Profile_list::getKV('id', $id);
  412. if (!empty($list) &&
  413. ($showPrivate || !$list->private)) {
  414. if (!isset($list->cursor)) {
  415. $list->cursor = $list->id;
  416. }
  417. $lists[] = $list;
  418. }
  419. }
  420. return new ArrayWrapper($lists);
  421. }
  422. /**
  423. * Get tags that other people put on this profile, in reverse-chron order
  424. *
  425. * @param Profile $scoped User we are requesting as
  426. * @param int $offset Offset from latest
  427. * @param int $limit Max number to get
  428. * @param datetime $since_id max date
  429. * @param datetime $max_id min date
  430. *
  431. * @return Profile_list resulting lists
  432. */
  433. public function getOtherTags(Profile $scoped = null, int $offset = 0, ?int $limit = null, int $since = 0, int $upto = 0)
  434. {
  435. $list = new Profile_list();
  436. if (common_config('db', 'type') !== 'mysql') {
  437. $cursor = sprintf(
  438. '((EXTRACT(DAY %1$s) * 24 + EXTRACT(HOUR %1$s)) * 60 + ' .
  439. 'EXTRACT(MINUTE %1$s)) * 60 + FLOOR(EXTRACT(SECOND %1$s)) AS "cursor"',
  440. "FROM (profile_tag.modified - TIMESTAMP '1970-01-01 00:00:00')"
  441. );
  442. } else {
  443. // The SQL/Foundation conforming implementation above doesn't work on MariaDB/MySQL
  444. $cursor = "timestampdiff(SECOND, '1970-01-01', profile_tag.modified) AS `cursor`";
  445. }
  446. $qry = sprintf(
  447. 'SELECT profile_list.*, ' . $cursor . ' ' .
  448. 'FROM profile_tag INNER JOIN profile_list ' .
  449. 'ON (profile_tag.tagger = profile_list.tagger ' .
  450. ' AND profile_tag.tag = profile_list.tag) ' .
  451. 'WHERE profile_tag.tagged = %d ',
  452. $this->id
  453. );
  454. if (!is_null($scoped)) {
  455. $qry .= sprintf(
  456. 'AND ( profile_list.private IS NOT TRUE ' .
  457. 'OR ( profile_list.tagger = %d AND ' .
  458. 'profile_list.private IS TRUE ) )',
  459. $scoped->getID()
  460. );
  461. } else {
  462. $qry .= 'AND profile_list.private IS NOT TRUE ';
  463. }
  464. if ($since > 0) {
  465. $qry .= 'AND cursor > ' . $since . ' ';
  466. }
  467. if ($upto > 0) {
  468. $qry .= 'AND cursor < ' . $upto . ' ';
  469. }
  470. $qry .= 'ORDER BY profile_tag.modified DESC, profile_tag.tagged DESC ';
  471. if ($offset >= 0 && !is_null($limit)) {
  472. $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
  473. }
  474. $list->query($qry);
  475. return $list;
  476. }
  477. public function getPrivateTags($offset = 0, $limit = null, $since_id = 0, $max_id = 0)
  478. {
  479. $tags = new Profile_list();
  480. $tags->private = true;
  481. $tags->tagger = $this->id;
  482. if ($since_id > 0) {
  483. $tags->whereAdd('id > ' . $since_id);
  484. }
  485. if ($max_id > 0) {
  486. $tags->whereAdd('id <= ' . $max_id);
  487. }
  488. if ($offset >= 0 && !is_null($limit)) {
  489. $tags->limit($offset, $limit);
  490. }
  491. $tags->orderBy('id DESC');
  492. $tags->find();
  493. return $tags;
  494. }
  495. public function hasLocalTags()
  496. {
  497. $tags = new Profile_tag();
  498. $tags->joinAdd(array('tagger', 'user:id'));
  499. $tags->whereAdd('tagged = ' . $this->id);
  500. $tags->whereAdd('tagger <> ' . $this->id);
  501. $tags->limit(0, 1);
  502. $tags->fetch();
  503. return ($tags->N == 0) ? false : true;
  504. }
  505. public function getTagSubscriptions(int $offset = 0, ?int $limit = null, int $since = 0, int $upto = 0)
  506. {
  507. $lists = new Profile_list();
  508. $lists->joinAdd(['id', 'profile_tag_subscription:profile_tag_id']);
  509. if (common_config('db', 'type') !== 'mysql') {
  510. $lists->selectAdd(sprintf(
  511. '((EXTRACT(DAY %1$s) * 24 + EXTRACT(HOUR %1$s)) * 60 + ' .
  512. 'EXTRACT(MINUTE %1$s)) * 60 + FLOOR(EXTRACT(SECOND %1$s)) AS "cursor"',
  513. "FROM (profile_tag_subscription.created - TIMESTAMP '1970-01-01 00:00:00')"
  514. ));
  515. } else {
  516. $lists->selectAdd("timestampdiff(SECOND, '1970-01-01', profile_tag_subscription.created) AS `cursor`");
  517. }
  518. $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
  519. if ($since > 0) {
  520. $lists->whereAdd('cursor > ' . $since);
  521. }
  522. if ($upto > 0) {
  523. $lists->whereAdd('cursor <= ' . $upto);
  524. }
  525. if ($offset >= 0 && !is_null($limit)) {
  526. $lists->limit($offset, $limit);
  527. }
  528. $lists->orderBy('profile_tag_subscription.created DESC, profile_list.id DESC');
  529. $lists->find();
  530. return $lists;
  531. }
  532. /**
  533. * Request to join the given group.
  534. * May throw exceptions on failure.
  535. *
  536. * @param User_group $group
  537. * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
  538. */
  539. public function joinGroup(User_group $group)
  540. {
  541. $join = null;
  542. if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
  543. $join = Group_join_queue::saveNew($this, $group);
  544. } else {
  545. if (Event::handle('StartJoinGroup', array($group, $this))) {
  546. $join = Group_member::join($group->id, $this->id);
  547. self::blow('profile:groups:%d', $this->id);
  548. self::blow('group:member_ids:%d', $group->id);
  549. self::blow('group:member_count:%d', $group->id);
  550. Event::handle('EndJoinGroup', array($group, $this));
  551. }
  552. }
  553. if ($join) {
  554. // Send any applicable notifications...
  555. $join->notify();
  556. }
  557. return $join;
  558. }
  559. /**
  560. * Leave a group that this profile is a member of.
  561. *
  562. * @param User_group $group
  563. */
  564. public function leaveGroup(User_group $group)
  565. {
  566. if (Event::handle('StartLeaveGroup', array($group, $this))) {
  567. Group_member::leave($group->id, $this->id);
  568. self::blow('profile:groups:%d', $this->id);
  569. self::blow('group:member_ids:%d', $group->id);
  570. self::blow('group:member_count:%d', $group->id);
  571. Event::handle('EndLeaveGroup', array($group, $this));
  572. }
  573. }
  574. public function avatarUrl($size = AVATAR_PROFILE_SIZE)
  575. {
  576. return Avatar::urlByProfile($this, $size);
  577. }
  578. public function getSubscribed($offset = 0, $limit = null)
  579. {
  580. $subs = Subscription::getSubscribedIDs($this->id, $offset, $limit);
  581. try {
  582. $profiles = Profile::multiGet('id', $subs);
  583. } catch (NoResultException $e) {
  584. return $e->obj;
  585. }
  586. return $profiles;
  587. }
  588. public function getSubscribers($offset = 0, $limit = null)
  589. {
  590. $subs = Subscription::getSubscriberIDs($this->id, $offset, $limit);
  591. try {
  592. $profiles = Profile::multiGet('id', $subs);
  593. } catch (NoResultException $e) {
  594. return $e->obj;
  595. }
  596. return $profiles;
  597. }
  598. public function getTaggedSubscribers($tag, $offset = 0, $limit = null)
  599. {
  600. $profile = new Profile();
  601. $qry = <<<END
  602. SELECT profile.*
  603. FROM profile
  604. INNER JOIN subscription ON profile.id = subscription.subscriber
  605. INNER JOIN profile_tag
  606. ON profile_tag.tagged = subscription.subscriber
  607. AND profile_tag.tagger = subscription.subscribed
  608. WHERE subscription.subscribed = {$this->getID()}
  609. AND profile_tag.tag = '{$profile->escape($tag)}'
  610. AND subscription.subscribed <> subscription.subscriber
  611. ORDER BY subscription.created DESC, subscription.subscriber DESC
  612. END;
  613. if ($offset) {
  614. $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
  615. }
  616. $cnt = $profile->query($qry);
  617. return $profile;
  618. }
  619. public function getTaggedSubscriptions($tag, $offset = 0, $limit = null)
  620. {
  621. $profile = new Profile();
  622. $qry = <<<END
  623. SELECT profile.*
  624. FROM profile
  625. INNER JOIN subscription ON profile.id = subscription.subscribed
  626. INNER JOIN profile_tag
  627. ON profile_tag.tagged = subscription.subscribed
  628. AND profile_tag.tagger = subscription.subscriber
  629. WHERE subscription.subscriber = {$this->getID()}
  630. AND profile_tag.tag = '{$profile->escape($tag)}'
  631. AND subscription.subscribed <> subscription.subscriber
  632. ORDER BY subscription.created DESC, subscription.subscribed DESC
  633. END;
  634. if ($offset) {
  635. $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
  636. }
  637. $profile->query($qry);
  638. return $profile;
  639. }
  640. /**
  641. * Get pending subscribers, who have not yet been approved.
  642. *
  643. * @param int $offset
  644. * @param int $limit
  645. * @return Profile
  646. */
  647. public function getRequests($offset = 0, $limit = null)
  648. {
  649. // FIXME: mysql only
  650. $subqueue = new Profile();
  651. $subqueue->joinAdd(array('id', 'subscription_queue:subscriber'));
  652. $subqueue->whereAdd(sprintf('subscription_queue.subscribed = %d', $this->getID()));
  653. $subqueue->limit($offset, $limit);
  654. $subqueue->orderBy(
  655. 'subscription_queue.created DESC, subscription_queue.subscriber DESC'
  656. );
  657. if (!$subqueue->find()) {
  658. throw new NoResultException($subqueue);
  659. }
  660. return $subqueue;
  661. }
  662. public function subscriptionCount()
  663. {
  664. $c = Cache::instance();
  665. if (!empty($c)) {
  666. $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
  667. if (is_integer($cnt)) {
  668. return (int) $cnt;
  669. }
  670. }
  671. $sub = new Subscription();
  672. $sub->subscriber = $this->id;
  673. $cnt = (int) $sub->count('distinct subscribed');
  674. // Local users are subscribed to themselves
  675. if ($this->isLocal()) {
  676. $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
  677. }
  678. if (!empty($c)) {
  679. $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
  680. }
  681. return $cnt;
  682. }
  683. public function subscriberCount()
  684. {
  685. $c = Cache::instance();
  686. if (!empty($c)) {
  687. $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
  688. if (is_integer($cnt)) {
  689. return (int) $cnt;
  690. }
  691. }
  692. $sub = new Subscription();
  693. $sub->subscribed = $this->id;
  694. $sub->whereAdd('subscriber <> subscribed');
  695. $cnt = (int) $sub->count('DISTINCT subscriber');
  696. if (!empty($c)) {
  697. $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
  698. }
  699. return $cnt;
  700. }
  701. /**
  702. * Is this profile subscribed to another profile?
  703. *
  704. * @param Profile $other
  705. * @return boolean
  706. */
  707. public function isSubscribed(Profile $other)
  708. {
  709. return Subscription::exists($this, $other);
  710. }
  711. public function readableBy(Profile $other = null)
  712. {
  713. // If it's not a private stream, it's readable by anyone
  714. if (!$this->isPrivateStream()) {
  715. return true;
  716. }
  717. // If it's a private stream, $other must be a subscriber to $this
  718. return is_null($other) ? false : $other->isSubscribed($this);
  719. }
  720. public function requiresSubscriptionApproval(Profile $other = null): bool
  721. {
  722. if (!$this->isLocal()) {
  723. // We don't know for remote users, and we'll always be able to send
  724. // the request. Whether it'll work immediately or require moderation
  725. // can be determined in another function.
  726. return false;
  727. }
  728. // Assume that profiles _we_ subscribe to are permitted. Could be made configurable.
  729. if (!is_null($other) && $this->isSubscribed($other)) {
  730. return false;
  731. }
  732. // If the local user either has a private stream (implies the following)
  733. // or user has a moderation policy for new subscriptions, return true.
  734. return $this->isPrivateStream() || $this->getUser()->subscribe_policy === User::SUBSCRIBE_POLICY_MODERATE;
  735. }
  736. /**
  737. * Check if a pending subscription request is outstanding for this...
  738. *
  739. * @param Profile $other
  740. * @return boolean
  741. */
  742. public function hasPendingSubscription(Profile $other)
  743. {
  744. return Subscription_queue::exists($this, $other);
  745. }
  746. /**
  747. * Are these two profiles subscribed to each other?
  748. *
  749. * @param Profile $other
  750. * @return boolean
  751. */
  752. public function mutuallySubscribed(Profile $other)
  753. {
  754. return $this->isSubscribed($other) &&
  755. $other->isSubscribed($this);
  756. }
  757. public function noticeCount()
  758. {
  759. $c = Cache::instance();
  760. if (!empty($c)) {
  761. $cnt = $c->get(Cache::key('profile:notice_count:'.$this->getID()));
  762. if (is_integer($cnt)) {
  763. return (int) $cnt;
  764. }
  765. }
  766. $notices = new Notice();
  767. $notices->profile_id = $this->getID();
  768. $notices->verb = ActivityVerb::POST;
  769. $cnt = (int) $notices->count('id'); // Not sure if I imagine this, but 'id' was faster than the defaulting 'uri'?
  770. if (!empty($c)) {
  771. $c->set(Cache::key('profile:notice_count:'.$this->getID()), $cnt);
  772. }
  773. return $cnt;
  774. }
  775. public function blowSubscriberCount()
  776. {
  777. $c = Cache::instance();
  778. if (!empty($c)) {
  779. $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
  780. }
  781. }
  782. public function blowSubscriptionCount()
  783. {
  784. $c = Cache::instance();
  785. if (!empty($c)) {
  786. $c->delete(Cache::key('profile:subscription_count:'.$this->id));
  787. }
  788. }
  789. public function blowNoticeCount()
  790. {
  791. $c = Cache::instance();
  792. if (!empty($c)) {
  793. $c->delete(Cache::key('profile:notice_count:'.$this->id));
  794. }
  795. }
  796. public static function maxBio()
  797. {
  798. $biolimit = common_config('profile', 'biolimit');
  799. // null => use global limit (distinct from 0!)
  800. if (is_null($biolimit)) {
  801. $biolimit = common_config('site', 'textlimit');
  802. }
  803. return $biolimit;
  804. }
  805. public static function bioTooLong($bio)
  806. {
  807. $biolimit = self::maxBio();
  808. return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
  809. }
  810. public function update($dataObject = false)
  811. {
  812. if (is_object($dataObject) && $this->nickname != $dataObject->nickname) {
  813. try {
  814. $local = $this->getUser();
  815. common_debug("Updating User ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
  816. $origuser = clone($local);
  817. $local->nickname = $this->nickname;
  818. // updateWithKeys throws exception on failure.
  819. $local->updateWithKeys($origuser);
  820. // Clear the site owner, in case nickname changed
  821. if ($local->hasRole(Profile_role::OWNER)) {
  822. User::blow('user:site_owner');
  823. }
  824. } catch (NoSuchUserException $e) {
  825. // Nevermind...
  826. }
  827. }
  828. return parent::update($dataObject);
  829. }
  830. public function getRelSelf()
  831. {
  832. return ['href' => $this->getUrl(),
  833. 'text' => common_config('site', 'name'),
  834. 'image' => Avatar::urlByProfile($this)];
  835. }
  836. // All the known rel="me", used for the IndieWeb audience
  837. public function getRelMes()
  838. {
  839. $relMes = array();
  840. try {
  841. $relMes[] = $this->getRelSelf();
  842. } catch (InvalidUrlException $e) {
  843. // no valid profile URL available
  844. }
  845. if (common_valid_http_url($this->getHomepage())) {
  846. $relMes[] = ['href' => $this->getHomepage(),
  847. 'text' => _('Homepage'),
  848. 'image' => null];
  849. }
  850. Event::handle('OtherAccountProfiles', array($this, &$relMes));
  851. return $relMes;
  852. }
  853. public function delete($useWhere = false)
  854. {
  855. $this->_deleteNotices();
  856. $this->_deleteSubscriptions();
  857. $this->_deleteTags();
  858. $this->_deleteBlocks();
  859. $this->_deleteAttentions();
  860. Avatar::deleteFromProfile($this, true);
  861. $this->grantRole(Profile_role::DELETED);
  862. $localuser = User::getKV('id', $this->id);
  863. if ($localuser instanceof User) {
  864. $localuser->delete();
  865. }
  866. // Warning: delete() will run on the batch objects,
  867. // not on individual objects.
  868. $related = [
  869. 'Reply',
  870. 'Group_member',
  871. 'Profile_role',
  872. ];
  873. Event::handle('ProfileDeleteRelated', array($this, &$related));
  874. foreach ($related as $cls) {
  875. $inst = new $cls();
  876. $inst->profile_id = $this->id;
  877. $inst->delete();
  878. }
  879. return parent::delete($useWhere);
  880. }
  881. public function _deleteNotices()
  882. {
  883. $notice = new Notice();
  884. $notice->profile_id = $this->id;
  885. if ($notice->find()) {
  886. while ($notice->fetch()) {
  887. $other = clone($notice);
  888. $other->delete();
  889. }
  890. }
  891. }
  892. public function _deleteSubscriptions()
  893. {
  894. $sub = new Subscription();
  895. $sub->subscriber = $this->getID();
  896. $sub->find();
  897. while ($sub->fetch()) {
  898. try {
  899. $other = $sub->getSubscribed();
  900. if (!$other->sameAs($this)) {
  901. Subscription::cancel($this, $other);
  902. }
  903. } catch (NoResultException $e) {
  904. // Profile not found
  905. common_log(LOG_INFO, 'Subscribed profile id=='.$sub->subscribed.' not found when deleting profile id=='.$this->getID().', ignoring...');
  906. } catch (ServerException $e) {
  907. // Subscription cancel failed
  908. common_log(LOG_INFO, 'Subscribed profile id=='.$other->getID().' could not be reached for unsubscription notice when deleting profile id=='.$this->getID().', ignoring...');
  909. }
  910. }
  911. $sub = new Subscription();
  912. $sub->subscribed = $this->getID();
  913. $sub->find();
  914. while ($sub->fetch()) {
  915. try {
  916. $other = $sub->getSubscriber();
  917. common_log(LOG_INFO, 'Subscriber profile id=='.$sub->subscribed.' not found when deleting profile id=='.$this->getID().', ignoring...');
  918. if (!$other->sameAs($this)) {
  919. Subscription::cancel($other, $this);
  920. }
  921. } catch (NoResultException $e) {
  922. // Profile not found
  923. common_log(LOG_INFO, 'Subscribed profile id=='.$sub->subscribed.' not found when deleting profile id=='.$this->getID().', ignoring...');
  924. } catch (ServerException $e) {
  925. // Subscription cancel failed
  926. common_log(LOG_INFO, 'Subscriber profile id=='.$other->getID().' could not be reached for unsubscription notice when deleting profile id=='.$this->getID().', ignoring...');
  927. }
  928. }
  929. // Finally delete self-subscription
  930. $self = new Subscription();
  931. $self->subscriber = $this->getID();
  932. $self->subscribed = $this->getID();
  933. $self->delete();
  934. }
  935. public function _deleteTags()
  936. {
  937. $tag = new Profile_tag();
  938. $tag->tagged = $this->id;
  939. $tag->delete();
  940. }
  941. public function _deleteBlocks()
  942. {
  943. $block = new Profile_block();
  944. $block->blocked = $this->id;
  945. $block->delete();
  946. $block = new Group_block();
  947. $block->blocked = $this->id;
  948. $block->delete();
  949. }
  950. public function _deleteAttentions()
  951. {
  952. $att = new Attention();
  953. $att->profile_id = $this->getID();
  954. if ($att->find()) {
  955. while ($att->fetch()) {
  956. // Can't do delete() on the object directly since it won't remove all of it
  957. $other = clone($att);
  958. $other->delete();
  959. }
  960. }
  961. }
  962. // XXX: identical to Notice::getLocation.
  963. public function getLocation()
  964. {
  965. $location = null;
  966. if (!empty($this->location_id) && !empty($this->location_ns)) {
  967. $location = Location::fromId($this->location_id, $this->location_ns);
  968. }
  969. if (is_null($location)) { // no ID, or Location::fromId() failed
  970. if (!empty($this->lat) && !empty($this->lon)) {
  971. $location = Location::fromLatLon($this->lat, $this->lon);
  972. }
  973. }
  974. if (is_null($location)) { // still haven't found it!
  975. if (!empty($this->location)) {
  976. $location = Location::fromName($this->location);
  977. }
  978. }
  979. return $location;
  980. }
  981. public function shareLocation()
  982. {
  983. $cfg = common_config('location', 'share');
  984. if ($cfg == 'always') {
  985. return true;
  986. } elseif ($cfg == 'never') {
  987. return false;
  988. } else { // user
  989. $share = common_config('location', 'sharedefault');
  990. // Check if user has a personal setting for this
  991. $prefs = User_location_prefs::getKV('user_id', $this->id);
  992. if (!empty($prefs)) {
  993. $share = $prefs->share_location;
  994. $prefs->free();
  995. }
  996. return $share;
  997. }
  998. }
  999. public function hasRole($name)
  1000. {
  1001. $has_role = false;
  1002. if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
  1003. $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
  1004. 'role' => $name));
  1005. $has_role = !empty($role);
  1006. Event::handle('EndHasRole', array($this, $name, $has_role));
  1007. }
  1008. return $has_role;
  1009. }
  1010. public function grantRole($name)
  1011. {
  1012. if (Event::handle('StartGrantRole', array($this, $name))) {
  1013. $role = new Profile_role();
  1014. $role->profile_id = $this->id;
  1015. $role->role = $name;
  1016. $role->created = common_sql_now();
  1017. $result = $role->update();
  1018. if ($result === 0 || $result === false) {
  1019. $result = $role->insert();
  1020. }
  1021. if (!$result) {
  1022. throw new Exception("Can't save role '$name' for profile '{$this->id}'");
  1023. }
  1024. if ($name == 'owner') {
  1025. User::blow('user:site_owner');
  1026. }
  1027. Event::handle('EndGrantRole', array($this, $name));
  1028. }
  1029. return $result;
  1030. }
  1031. public function revokeRole($name)
  1032. {
  1033. if (Event::handle('StartRevokeRole', array($this, $name))) {
  1034. $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
  1035. 'role' => $name));
  1036. if (empty($role)) {
  1037. // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
  1038. // TRANS: %1$s is the role name, %2$s is the user ID (number).
  1039. throw new Exception(sprintf(
  1040. _('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),
  1041. $name,
  1042. $this->id
  1043. ));
  1044. }
  1045. $result = $role->delete();
  1046. if (!$result) {
  1047. common_log_db_error($role, 'DELETE', __FILE__);
  1048. // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
  1049. // TRANS: %1$s is the role name, %2$s is the user ID (number).
  1050. throw new Exception(sprintf(
  1051. _('Cannot revoke role "%1$s" for user #%2$d; database error.'),
  1052. $name,
  1053. $this->id
  1054. ));
  1055. }
  1056. if ($name == 'owner') {
  1057. User::blow('user:site_owner');
  1058. }
  1059. Event::handle('EndRevokeRole', array($this, $name));
  1060. return true;
  1061. }
  1062. }
  1063. public function isSandboxed()
  1064. {
  1065. return $this->hasRole(Profile_role::SANDBOXED);
  1066. }
  1067. public function isSilenced()
  1068. {
  1069. return $this->hasRole(Profile_role::SILENCED);
  1070. }
  1071. public function sandbox()
  1072. {
  1073. $this->grantRole(Profile_role::SANDBOXED);
  1074. }
  1075. public function unsandbox()
  1076. {
  1077. $this->revokeRole(Profile_role::SANDBOXED);
  1078. }
  1079. public function silence()
  1080. {
  1081. $this->grantRole(Profile_role::SILENCED);
  1082. if (common_config('notice', 'hidespam')) {
  1083. $this->flushVisibility();
  1084. }
  1085. }
  1086. public function silenceAs(Profile $actor)
  1087. {
  1088. if (!$actor->hasRight(Right::SILENCEUSER)) {
  1089. throw new AuthorizationException(_('You cannot silence users on this site.'));
  1090. }
  1091. // Only administrators can silence other privileged users (such as others who have the right to silence).
  1092. if ($this->isPrivileged() && !$actor->hasRole(Profile_role::ADMINISTRATOR)) {
  1093. throw new AuthorizationException(_('You cannot silence other privileged users.'));
  1094. }
  1095. if ($this->isSilenced()) {
  1096. // TRANS: Client error displayed trying to silence an already silenced user.
  1097. throw new AlreadyFulfilledException(_('User is already silenced.'));
  1098. }
  1099. return $this->silence();
  1100. }
  1101. public function unsilence()
  1102. {
  1103. $this->revokeRole(Profile_role::SILENCED);
  1104. if (common_config('notice', 'hidespam')) {
  1105. $this->flushVisibility();
  1106. }
  1107. }
  1108. public function unsilenceAs(Profile $actor)
  1109. {
  1110. if (!$actor->hasRight(Right::SILENCEUSER)) {
  1111. // TRANS: Client error displayed trying to unsilence a user when the user does not have the right.
  1112. throw new AuthorizationException(_('You cannot unsilence users on this site.'));
  1113. }
  1114. if (!$this->isSilenced()) {
  1115. // TRANS: Client error displayed trying to unsilence a user when the target user has not been silenced.
  1116. throw new AlreadyFulfilledException(_('User is not silenced.'));
  1117. }
  1118. return $this->unsilence();
  1119. }
  1120. public function flushVisibility()
  1121. {
  1122. // Get all notices
  1123. $stream = new ProfileNoticeStream($this, $this);
  1124. $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
  1125. foreach ($ids as $id) {
  1126. self::blow('notice:in-scope-for:%d:null', $id);
  1127. }
  1128. }
  1129. public function isPrivileged()
  1130. {
  1131. // TODO: An Event::handle so plugins can report if users are privileged.
  1132. // The ModHelper is the only one I care about when coding this, and that
  1133. // can be tested with Right::SILENCEUSER which I do below:
  1134. switch (true) {
  1135. case $this->hasRight(Right::SILENCEUSER):
  1136. case $this->hasRole(Profile_role::MODERATOR):
  1137. case $this->hasRole(Profile_role::ADMINISTRATOR):
  1138. case $this->hasRole(Profile_role::OWNER):
  1139. return true;
  1140. }
  1141. return false;
  1142. }
  1143. /**
  1144. * Does this user have the right to do X?
  1145. *
  1146. * With our role-based authorization, this is merely a lookup for whether the user
  1147. * has a particular role. The implementation currently uses a switch statement
  1148. * to determine if the user has the pre-defined role to exercise the right. Future
  1149. * implementations may allow per-site roles, and different mappings of roles to rights.
  1150. *
  1151. * @param $right string Name of the right, usually a constant in class Right
  1152. * @return boolean whether the user has the right in question
  1153. */
  1154. public function hasRight($right)
  1155. {
  1156. $result = false;
  1157. if ($this->hasRole(Profile_role::DELETED)) {
  1158. return false;
  1159. }
  1160. if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
  1161. switch ($right) {
  1162. case Right::DELETEOTHERSNOTICE:
  1163. case Right::MAKEGROUPADMIN:
  1164. case Right::SANDBOXUSER:
  1165. case Right::SILENCEUSER:
  1166. case Right::DELETEUSER:
  1167. case Right::DELETEGROUP:
  1168. case Right::TRAINSPAM:
  1169. case Right::REVIEWSPAM:
  1170. $result = $this->hasRole(Profile_role::MODERATOR);
  1171. break;
  1172. case Right::CONFIGURESITE:
  1173. $result = $this->hasRole(Profile_role::ADMINISTRATOR);
  1174. break;
  1175. case Right::GRANTROLE:
  1176. case Right::REVOKEROLE:
  1177. $result = $this->hasRole(Profile_role::OWNER);
  1178. break;
  1179. case Right::NEWNOTICE:
  1180. case Right::NEWMESSAGE:
  1181. case Right::SUBSCRIBE:
  1182. case Right::CREATEGROUP:
  1183. $result = !$this->isSilenced();
  1184. break;
  1185. case Right::PUBLICNOTICE:
  1186. case Right::EMAILONREPLY:
  1187. case Right::EMAILONSUBSCRIBE:
  1188. case Right::EMAILONFAVE:
  1189. $result = !$this->isSandboxed() && !$this->isSilenced();
  1190. break;
  1191. case Right::WEBLOGIN:
  1192. $result = !$this->isSilenced();
  1193. break;
  1194. case Right::API:
  1195. $result = !$this->isSilenced();
  1196. break;
  1197. case Right::BACKUPACCOUNT:
  1198. $result = common_config('profile', 'backup');
  1199. break;
  1200. case Right::RESTOREACCOUNT:
  1201. $result = common_config('profile', 'restore');
  1202. break;
  1203. case Right::DELETEACCOUNT:
  1204. $result = common_config('profile', 'delete');
  1205. break;
  1206. case Right::MOVEACCOUNT:
  1207. $result = common_config('profile', 'move');
  1208. break;
  1209. default:
  1210. $result = false;
  1211. break;
  1212. }
  1213. }
  1214. return $result;
  1215. }
  1216. // FIXME: Can't put Notice typing here due to ArrayWrapper
  1217. public function hasRepeated($notice)
  1218. {
  1219. // XXX: not really a pkey, but should work
  1220. $notice = Notice::pkeyGet(array('profile_id' => $this->getID(),
  1221. 'repeat_of' => $notice->getID(),
  1222. 'verb' => ActivityVerb::SHARE));
  1223. return !empty($notice);
  1224. }
  1225. /**
  1226. * Returns an XML string fragment with limited profile information
  1227. * as an Atom <author> element.
  1228. *
  1229. * Assumes that Atom has been previously set up as the base namespace.
  1230. *
  1231. * @param Profile $cur the current authenticated user
  1232. *
  1233. * @return string
  1234. */
  1235. public function asAtomAuthor($cur = null)
  1236. {
  1237. $xs = new XMLStringer(true);
  1238. $xs->elementStart('author');
  1239. $xs->element('name', null, $this->nickname);
  1240. $xs->element('uri', null, $this->getUri());
  1241. if ($cur != null) {
  1242. $attrs = [];
  1243. $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
  1244. $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
  1245. $xs->element('statusnet:profile_info', $attrs, null);
  1246. }
  1247. $xs->elementEnd('author');
  1248. return $xs->getString();
  1249. }
  1250. /**
  1251. * Extra profile info for atom entries
  1252. *
  1253. * Clients use some extra profile info in the atom stream.
  1254. * This gives it to them.
  1255. *
  1256. * @param Profile $scoped The currently logged in/scoped profile
  1257. *
  1258. * @return array representation of <statusnet:profile_info> element or null
  1259. */
  1260. public function profileInfo(Profile $scoped = null)
  1261. {
  1262. $profileInfoAttr = array('local_id' => $this->id);
  1263. if ($scoped instanceof Profile) {
  1264. // Whether the current user is a subscribed to this profile
  1265. $profileInfoAttr['following'] = $scoped->isSubscribed($this) ? 'true' : 'false';
  1266. // Whether the current user is has blocked this profile
  1267. $profileInfoAttr['blocking'] = $scoped->hasBlocked($this) ? 'true' : 'false';
  1268. }
  1269. return array('statusnet:profile_info', $profileInfoAttr, null);
  1270. }
  1271. /**
  1272. * Returns an XML string fragment with profile information as an
  1273. * Activity Streams <activity:actor> element.
  1274. *
  1275. * Assumes that 'activity' namespace has been previously defined.
  1276. *
  1277. * @return string
  1278. */
  1279. public function asActivityActor()
  1280. {
  1281. return $this->asActivityNoun('actor');
  1282. }
  1283. /**
  1284. * Returns an XML string fragment with profile information as an
  1285. * Activity Streams noun object with the given element type.
  1286. *
  1287. * Assumes that 'activity', 'georss', and 'poco' namespace has been
  1288. * previously defined.
  1289. *
  1290. * @param string $element one of 'actor', 'subject', 'object', 'target'
  1291. *
  1292. * @return string
  1293. */
  1294. public function asActivityNoun($element)
  1295. {
  1296. $noun = $this->asActivityObject();
  1297. return $noun->asString('activity:' . $element);
  1298. }
  1299. public function asActivityObject()
  1300. {
  1301. $object = new ActivityObject();
  1302. if (Event::handle('StartActivityObjectFromProfile', array($this, &$object))) {
  1303. $object->type = $this->getObjectType();
  1304. $object->id = $this->getUri();
  1305. $object->title = $this->getBestName();
  1306. $object->link = $this->getUrl();
  1307. $object->summary = $this->getDescription();
  1308. try {
  1309. $avatar = Avatar::getUploaded($this);
  1310. $object->avatarLinks[] = AvatarLink::fromAvatar($avatar);
  1311. } catch (NoAvatarException $e) {
  1312. // Could not find an original avatar to link
  1313. }
  1314. $sizes = array(
  1315. AVATAR_PROFILE_SIZE,
  1316. AVATAR_STREAM_SIZE,
  1317. AVATAR_MINI_SIZE
  1318. );
  1319. foreach ($sizes as $size) {
  1320. $alink = null;
  1321. try {
  1322. $avatar = Avatar::byProfile($this, $size);
  1323. $alink = AvatarLink::fromAvatar($avatar);
  1324. } catch (NoAvatarException $e) {
  1325. $alink = new AvatarLink();
  1326. $alink->type = 'image/png';
  1327. $alink->height = $size;
  1328. $alink->width = $size;
  1329. $alink->url = Avatar::defaultImage($size);
  1330. }
  1331. $object->avatarLinks[] = $alink;
  1332. }
  1333. if (isset($this->lat) && isset($this->lon)) {
  1334. $object->geopoint = (float)$this->lat
  1335. . ' ' . (float)$this->lon;
  1336. }
  1337. $object->poco = PoCo::fromProfile($this);
  1338. if ($this->isLocal()) {
  1339. $object->extra[] = array('followers', array('url' => common_local_url('subscribers', array('nickname' => $this->getNickname()))));
  1340. }
  1341. Event::handle('EndActivityObjectFromProfile', array($this, &$object));
  1342. }
  1343. return $object;
  1344. }
  1345. /**
  1346. * Returns the profile's canonical url, not necessarily a uri/unique id
  1347. *
  1348. * @return string $profileurl
  1349. */
  1350. public function getUrl()
  1351. {
  1352. $url = null;
  1353. if ($this->isGroup()) {
  1354. // FIXME: Get rid of this event, it fills no real purpose, data should be in Profile->profileurl (replaces User_group->mainpage)
  1355. if (Event::handle('StartUserGroupHomeUrl', array($this->getGroup(), &$url))) {
  1356. $url = $this->getGroup()->isLocal()
  1357. ? common_local_url('showgroup', array('nickname' => $this->getNickname()))
  1358. : $this->profileurl;
  1359. }
  1360. Event::handle('EndUserGroupHomeUrl', array($this->getGroup(), $url));
  1361. } elseif ($this->isLocal()) {
  1362. $url = common_local_url('showstream', array('nickname' => $this->getNickname()));
  1363. } else {
  1364. $url = $this->profileurl;
  1365. }
  1366. if (empty($url) ||
  1367. !filter_var($url, FILTER_VALIDATE_URL)) {
  1368. throw new InvalidUrlException($url);
  1369. }
  1370. return $url;
  1371. }
  1372. public function getHtmlTitle()
  1373. {
  1374. try {
  1375. return $this->getAcctUri(false);
  1376. } catch (ProfileNoAcctUriException $e) {
  1377. return $this->getNickname();
  1378. }
  1379. }
  1380. public function getNickname()
  1381. {
  1382. return $this->nickname;
  1383. }
  1384. public function getFullname()
  1385. {
  1386. return $this->fullname;
  1387. }
  1388. public function getHomepage()
  1389. {
  1390. return $this->homepage;
  1391. }
  1392. public function getDescription()
  1393. {
  1394. return $this->bio;
  1395. }
  1396. /**
  1397. * Returns the best URI for a profile. Plugins may override.
  1398. *
  1399. * @return string $uri
  1400. */
  1401. public function getUri()
  1402. {
  1403. $uri = null;
  1404. // give plugins a chance to set the URI
  1405. if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
  1406. // check for a local user first
  1407. $user = User::getKV('id', $this->id);
  1408. if ($user instanceof User) {
  1409. $uri = $user->getUri();
  1410. } else {
  1411. $group = User_group::getKV('profile_id', $this->id);
  1412. if ($group instanceof User_group) {
  1413. $uri = $group->getUri();
  1414. }
  1415. }
  1416. Event::handle('EndGetProfileUri', array($this, &$uri));
  1417. }
  1418. return $uri;
  1419. }
  1420. /**
  1421. * Returns an assumed acct: URI for a profile. Plugins are required.
  1422. *
  1423. * @return string $uri
  1424. */
  1425. public function getAcctUri($scheme=true)
  1426. {
  1427. $acct = null;
  1428. if (Event::handle('StartGetProfileAcctUri', array($this, &$acct))) {
  1429. Event::handle('EndGetProfileAcctUri', array($this, &$acct));
  1430. }
  1431. if ($acct === null) {
  1432. throw new ProfileNoAcctUriException($this);
  1433. }
  1434. if (parse_url($acct, PHP_URL_SCHEME) !== 'acct') {
  1435. throw new ServerException('Acct URI does not have acct: scheme');
  1436. }
  1437. // if we don't return the scheme, just remove the 'acct:' in the beginning
  1438. return $scheme ? $acct : mb_substr($acct, 5);
  1439. }
  1440. public function hasBlocked(Profile $other)
  1441. {
  1442. $block = Profile_block::exists($this, $other);
  1443. return !empty($block);
  1444. }
  1445. public function getAtomFeed()
  1446. {
  1447. $feed = null;
  1448. if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
  1449. if ($this->isLocal()) {
  1450. $feed = common_local_url('ApiTimelineUser', array('id' => $this->getID(),
  1451. 'format' => 'atom'));
  1452. }
  1453. Event::handle('EndProfileGetAtomFeed', array($this, $feed));
  1454. }
  1455. return $feed;
  1456. }
  1457. public function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
  1458. {
  1459. // TRANS: Exception thrown when trying view "repeated to me".
  1460. throw new Exception(_('Not implemented since inbox change.'));
  1461. }
  1462. /*
  1463. * Get a Profile object by URI. Will call external plugins for help
  1464. * using the event StartGetProfileFromURI.
  1465. *
  1466. * @param string $uri A unique identifier for a resource (profile/group/whatever)
  1467. */
  1468. public static function fromUri($uri)
  1469. {
  1470. $profile = null;
  1471. if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
  1472. // Get a local user when plugin lookup (like OStatus) fails
  1473. $user = User::getKV('uri', $uri);
  1474. if ($user instanceof User) {
  1475. $profile = $user->getProfile();
  1476. } else {
  1477. $group = User_group::getKV('uri', $uri);
  1478. if ($group instanceof User_group) {
  1479. $profile = $group->getProfile();
  1480. }
  1481. }
  1482. Event::handle('EndGetProfileFromURI', array($uri, $profile));
  1483. }
  1484. if (!$profile instanceof Profile) {
  1485. throw new UnknownUriException($uri);
  1486. }
  1487. return $profile;
  1488. }
  1489. public function canRead(Notice $notice)
  1490. {
  1491. if ($notice->scope & Notice::SITE_SCOPE) {
  1492. $user = $this->getUser();
  1493. if (empty($user)) {
  1494. return false;
  1495. }
  1496. }
  1497. if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
  1498. $replies = $notice->getReplies();
  1499. if (!in_array($this->id, $replies)) {
  1500. $groups = $notice->getGroups();
  1501. $foundOne = false;
  1502. foreach ($groups as $group) {
  1503. if ($this->isMember($group)) {
  1504. $foundOne = true;
  1505. break;
  1506. }
  1507. }
  1508. if (!$foundOne) {
  1509. return false;
  1510. }
  1511. }
  1512. }
  1513. if ($notice->scope & Notice::FOLLOWER_SCOPE) {
  1514. $author = $notice->getProfile();
  1515. if (!Subscription::exists($this, $author)) {
  1516. return false;
  1517. }
  1518. }
  1519. return true;
  1520. }
  1521. public static function current()
  1522. {
  1523. $user = common_current_user();
  1524. if (empty($user)) {
  1525. $profile = null;
  1526. } else {
  1527. $profile = $user->getProfile();
  1528. }
  1529. return $profile;
  1530. }
  1531. public static function ensureCurrent()
  1532. {
  1533. $profile = self::current();
  1534. if (!$profile instanceof Profile) {
  1535. throw new AuthorizationException('A currently scoped profile is required.');
  1536. }
  1537. return $profile;
  1538. }
  1539. /**
  1540. * Magic function called at serialize() time.
  1541. *
  1542. * We use this to drop a couple process-specific references
  1543. * from DB_DataObject which can cause trouble in future
  1544. * processes.
  1545. *
  1546. * @return array of variable names to include in serialization.
  1547. */
  1548. public function __sleep()
  1549. {
  1550. $vars = parent::__sleep();
  1551. $skip = array('_user', '_group');
  1552. return array_diff($vars, $skip);
  1553. }
  1554. public function getProfile()
  1555. {
  1556. return $this;
  1557. }
  1558. /**
  1559. * Test whether the given profile is the same as the current class,
  1560. * for testing identities.
  1561. *
  1562. * @param Profile $other The other profile, usually from Action's $this->scoped
  1563. *
  1564. * @return boolean
  1565. */
  1566. public function sameAs(Profile $other=null)
  1567. {
  1568. if (is_null($other)) {
  1569. // In case $this->scoped is null or something, i.e. not a current/legitimate profile.
  1570. return false;
  1571. }
  1572. return $this->getID() === $other->getID();
  1573. }
  1574. /**
  1575. * This will perform shortenLinks with the connected User object.
  1576. *
  1577. * Won't work on remote profiles or groups, so expect a
  1578. * NoSuchUserException if you don't know it's a local User.
  1579. *
  1580. * @param string $text String to shorten
  1581. * @param boolean $always Disrespect minimum length etc.
  1582. *
  1583. * @return string link-shortened $text
  1584. */
  1585. public function shortenLinks($text, $always=false)
  1586. {
  1587. return $this->getUser()->shortenLinks($text, $always);
  1588. }
  1589. public function isPrivateStream(): bool
  1590. {
  1591. // We only know of public remote users as of yet...
  1592. if (!$this->isLocal()) {
  1593. return false;
  1594. }
  1595. $private_stream = $this->getUser()->private_stream;
  1596. return !is_null($private_stream) && $private_stream;
  1597. }
  1598. public function delPref($namespace, $topic)
  1599. {
  1600. return Profile_prefs::setData($this, $namespace, $topic, null);
  1601. }
  1602. public function getPref($namespace, $topic, $default = null)
  1603. {
  1604. // If you want an exception to be thrown, call Profile_prefs::getData directly
  1605. try {
  1606. return Profile_prefs::getData($this, $namespace, $topic, $default);
  1607. } catch (NoResultException $e) {
  1608. return null;
  1609. }
  1610. }
  1611. // The same as getPref but will fall back to common_config value for the same namespace/topic
  1612. public function getConfigPref($namespace, $topic)
  1613. {
  1614. return Profile_prefs::getConfigData($this, $namespace, $topic);
  1615. }
  1616. public function setPref($namespace, $topic, $data)
  1617. {
  1618. return Profile_prefs::setData($this, $namespace, $topic, $data);
  1619. }
  1620. public function getConnectedApps($offset=0, $limit=null)
  1621. {
  1622. return $this->getUser()->getConnectedApps($offset, $limit);
  1623. }
  1624. }