Profile.php 59 KB

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