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