Profile.php 59 KB

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