Profile.php 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872
  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' => 191, 'not null' => true, 'description' => 'nickname or username', 'collate' => 'utf8_general_ci'),
  46. 'fullname' => array('type' => 'text', 'description' => 'display name', 'collate' => 'utf8_general_ci'),
  47. 'profileurl' => array('type' => 'text', 'description' => 'URL, cached so we dont regenerate'),
  48. 'homepage' => array('type' => 'text', 'description' => 'identifying URL', 'collate' => 'utf8_general_ci'),
  49. 'bio' => array('type' => 'text', 'description' => 'descriptive biography', 'collate' => 'utf8_general_ci'),
  50. 'location' => array('type' => 'text', 'description' => 'physical location', 'collate' => 'utf8_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_created_id_idx' => array('nickname', 'created', 'id'),
  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, group_id 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, profile_tag.tagged 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. $lists->joinAdd(['id', 'profile_tag_subscription:profile_tag_id']);
  484. if (common_config('db', 'type') !== 'mysql') {
  485. $lists->selectAdd(sprintf(
  486. '((EXTRACT(DAY %1$s) * 24 + EXTRACT(HOUR %1$s)) * 60 + ' .
  487. 'EXTRACT(MINUTE %1$s)) * 60 + FLOOR(EXTRACT(SECOND %1$s)) AS "cursor"',
  488. "FROM (profile_tag_subscription.created - TIMESTAMP '1970-01-01 00:00:00')"
  489. ));
  490. } else {
  491. $lists->selectAdd("timestampdiff(SECOND, '1970-01-01', profile_tag_subscription.created) AS `cursor`");
  492. }
  493. $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
  494. if ($since > 0) {
  495. $lists->whereAdd('cursor > ' . $since);
  496. }
  497. if ($upto > 0) {
  498. $lists->whereAdd('cursor <= ' . $upto);
  499. }
  500. if ($offset >= 0 && !is_null($limit)) {
  501. $lists->limit($offset, $limit);
  502. }
  503. $lists->orderBy('profile_tag_subscription.created DESC, profile_list.id DESC');
  504. $lists->find();
  505. return $lists;
  506. }
  507. /**
  508. * Request to join the given group.
  509. * May throw exceptions on failure.
  510. *
  511. * @param User_group $group
  512. * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
  513. */
  514. public function joinGroup(User_group $group)
  515. {
  516. $join = null;
  517. if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
  518. $join = Group_join_queue::saveNew($this, $group);
  519. } else {
  520. if (Event::handle('StartJoinGroup', array($group, $this))) {
  521. $join = Group_member::join($group->id, $this->id);
  522. self::blow('profile:groups:%d', $this->id);
  523. self::blow('group:member_ids:%d', $group->id);
  524. self::blow('group:member_count:%d', $group->id);
  525. Event::handle('EndJoinGroup', array($group, $this));
  526. }
  527. }
  528. if ($join) {
  529. // Send any applicable notifications...
  530. $join->notify();
  531. }
  532. return $join;
  533. }
  534. /**
  535. * Leave a group that this profile is a member of.
  536. *
  537. * @param User_group $group
  538. */
  539. public function leaveGroup(User_group $group)
  540. {
  541. if (Event::handle('StartLeaveGroup', array($group, $this))) {
  542. Group_member::leave($group->id, $this->id);
  543. self::blow('profile:groups:%d', $this->id);
  544. self::blow('group:member_ids:%d', $group->id);
  545. self::blow('group:member_count:%d', $group->id);
  546. Event::handle('EndLeaveGroup', array($group, $this));
  547. }
  548. }
  549. public function avatarUrl($size = AVATAR_PROFILE_SIZE)
  550. {
  551. return Avatar::urlByProfile($this, $size);
  552. }
  553. public function getSubscribed($offset = 0, $limit = null)
  554. {
  555. $subs = Subscription::getSubscribedIDs($this->id, $offset, $limit);
  556. try {
  557. $profiles = Profile::multiGet('id', $subs);
  558. } catch (NoResultException $e) {
  559. return $e->obj;
  560. }
  561. return $profiles;
  562. }
  563. public function getSubscribers($offset = 0, $limit = null)
  564. {
  565. $subs = Subscription::getSubscriberIDs($this->id, $offset, $limit);
  566. try {
  567. $profiles = Profile::multiGet('id', $subs);
  568. } catch (NoResultException $e) {
  569. return $e->obj;
  570. }
  571. return $profiles;
  572. }
  573. public function getTaggedSubscribers($tag, $offset = 0, $limit = null)
  574. {
  575. $profile = new Profile();
  576. $qry = <<<END
  577. SELECT profile.*
  578. FROM profile
  579. INNER JOIN subscription ON profile.id = subscription.subscriber
  580. INNER JOIN profile_tag
  581. ON profile_tag.tagged = subscription.subscriber
  582. AND profile_tag.tagger = subscription.subscribed
  583. WHERE subscription.subscribed = {$this->getID()}
  584. AND profile_tag.tag = '{$profile->escape($tag)}'
  585. AND subscription.subscribed <> subscription.subscriber
  586. ORDER BY subscription.created DESC, subscription.subscriber DESC
  587. END;
  588. if ($offset) {
  589. $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
  590. }
  591. $cnt = $profile->query($qry);
  592. return $profile;
  593. }
  594. public function getTaggedSubscriptions($tag, $offset = 0, $limit = null)
  595. {
  596. $profile = new Profile();
  597. $qry = <<<END
  598. SELECT profile.*
  599. FROM profile
  600. INNER JOIN subscription ON profile.id = subscription.subscribed
  601. INNER JOIN profile_tag
  602. ON profile_tag.tagged = subscription.subscribed
  603. AND profile_tag.tagger = subscription.subscriber
  604. WHERE subscription.subscriber = {$this->getID()}
  605. AND profile_tag.tag = '{$profile->escape($tag)}'
  606. AND subscription.subscribed <> subscription.subscriber
  607. ORDER BY subscription.created DESC, subscription.subscribed DESC
  608. END;
  609. if ($offset) {
  610. $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
  611. }
  612. $profile->query($qry);
  613. return $profile;
  614. }
  615. /**
  616. * Get pending subscribers, who have not yet been approved.
  617. *
  618. * @param int $offset
  619. * @param int $limit
  620. * @return Profile
  621. */
  622. public function getRequests($offset = 0, $limit = null)
  623. {
  624. // FIXME: mysql only
  625. $subqueue = new Profile();
  626. $subqueue->joinAdd(array('id', 'subscription_queue:subscriber'));
  627. $subqueue->whereAdd(sprintf('subscription_queue.subscribed = %d', $this->getID()));
  628. $subqueue->limit($offset, $limit);
  629. $subqueue->orderBy(
  630. 'subscription_queue.created DESC, subscription_queue.subscriber DESC'
  631. );
  632. if (!$subqueue->find()) {
  633. throw new NoResultException($subqueue);
  634. }
  635. return $subqueue;
  636. }
  637. public function subscriptionCount()
  638. {
  639. $c = Cache::instance();
  640. if (!empty($c)) {
  641. $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
  642. if (is_integer($cnt)) {
  643. return (int) $cnt;
  644. }
  645. }
  646. $sub = new Subscription();
  647. $sub->subscriber = $this->id;
  648. $cnt = (int) $sub->count('distinct subscribed');
  649. // Local users are subscribed to themselves
  650. if ($this->isLocal()) {
  651. $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
  652. }
  653. if (!empty($c)) {
  654. $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
  655. }
  656. return $cnt;
  657. }
  658. public function subscriberCount()
  659. {
  660. $c = Cache::instance();
  661. if (!empty($c)) {
  662. $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
  663. if (is_integer($cnt)) {
  664. return (int) $cnt;
  665. }
  666. }
  667. $sub = new Subscription();
  668. $sub->subscribed = $this->id;
  669. $sub->whereAdd('subscriber <> subscribed');
  670. $cnt = (int) $sub->count('DISTINCT subscriber');
  671. if (!empty($c)) {
  672. $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
  673. }
  674. return $cnt;
  675. }
  676. /**
  677. * Is this profile subscribed to another profile?
  678. *
  679. * @param Profile $other
  680. * @return boolean
  681. */
  682. public function isSubscribed(Profile $other)
  683. {
  684. return Subscription::exists($this, $other);
  685. }
  686. public function readableBy(Profile $other = null)
  687. {
  688. // If it's not a private stream, it's readable by anyone
  689. if (!$this->isPrivateStream()) {
  690. return true;
  691. }
  692. // If it's a private stream, $other must be a subscriber to $this
  693. return is_null($other) ? false : $other->isSubscribed($this);
  694. }
  695. public function requiresSubscriptionApproval(Profile $other = null): bool
  696. {
  697. if (!$this->isLocal()) {
  698. // We don't know for remote users, and we'll always be able to send
  699. // the request. Whether it'll work immediately or require moderation
  700. // can be determined in another function.
  701. return false;
  702. }
  703. // Assume that profiles _we_ subscribe to are permitted. Could be made configurable.
  704. if (!is_null($other) && $this->isSubscribed($other)) {
  705. return false;
  706. }
  707. // If the local user either has a private stream (implies the following)
  708. // or user has a moderation policy for new subscriptions, return true.
  709. return $this->isPrivateStream() || $this->getUser()->subscribe_policy === User::SUBSCRIBE_POLICY_MODERATE;
  710. }
  711. /**
  712. * Check if a pending subscription request is outstanding for this...
  713. *
  714. * @param Profile $other
  715. * @return boolean
  716. */
  717. public function hasPendingSubscription(Profile $other)
  718. {
  719. return Subscription_queue::exists($this, $other);
  720. }
  721. /**
  722. * Are these two profiles subscribed to each other?
  723. *
  724. * @param Profile $other
  725. * @return boolean
  726. */
  727. public function mutuallySubscribed(Profile $other)
  728. {
  729. return $this->isSubscribed($other) &&
  730. $other->isSubscribed($this);
  731. }
  732. public function noticeCount()
  733. {
  734. $c = Cache::instance();
  735. if (!empty($c)) {
  736. $cnt = $c->get(Cache::key('profile:notice_count:'.$this->getID()));
  737. if (is_integer($cnt)) {
  738. return (int) $cnt;
  739. }
  740. }
  741. $notices = new Notice();
  742. $notices->profile_id = $this->getID();
  743. $notices->verb = ActivityVerb::POST;
  744. $cnt = (int) $notices->count('id'); // Not sure if I imagine this, but 'id' was faster than the defaulting 'uri'?
  745. if (!empty($c)) {
  746. $c->set(Cache::key('profile:notice_count:'.$this->getID()), $cnt);
  747. }
  748. return $cnt;
  749. }
  750. public function blowSubscriberCount()
  751. {
  752. $c = Cache::instance();
  753. if (!empty($c)) {
  754. $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
  755. }
  756. }
  757. public function blowSubscriptionCount()
  758. {
  759. $c = Cache::instance();
  760. if (!empty($c)) {
  761. $c->delete(Cache::key('profile:subscription_count:'.$this->id));
  762. }
  763. }
  764. public function blowNoticeCount()
  765. {
  766. $c = Cache::instance();
  767. if (!empty($c)) {
  768. $c->delete(Cache::key('profile:notice_count:'.$this->id));
  769. }
  770. }
  771. public static function maxBio()
  772. {
  773. $biolimit = common_config('profile', 'biolimit');
  774. // null => use global limit (distinct from 0!)
  775. if (is_null($biolimit)) {
  776. $biolimit = common_config('site', 'textlimit');
  777. }
  778. return $biolimit;
  779. }
  780. public static function bioTooLong($bio)
  781. {
  782. $biolimit = self::maxBio();
  783. return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
  784. }
  785. public function update($dataObject = false)
  786. {
  787. if (is_object($dataObject) && $this->nickname != $dataObject->nickname) {
  788. try {
  789. $local = $this->getUser();
  790. common_debug("Updating User ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
  791. $origuser = clone($local);
  792. $local->nickname = $this->nickname;
  793. // updateWithKeys throws exception on failure.
  794. $local->updateWithKeys($origuser);
  795. // Clear the site owner, in case nickname changed
  796. if ($local->hasRole(Profile_role::OWNER)) {
  797. User::blow('user:site_owner');
  798. }
  799. } catch (NoSuchUserException $e) {
  800. // Nevermind...
  801. }
  802. }
  803. return parent::update($dataObject);
  804. }
  805. public function getRelSelf()
  806. {
  807. return ['href' => $this->getUrl(),
  808. 'text' => common_config('site', 'name'),
  809. 'image' => Avatar::urlByProfile($this)];
  810. }
  811. // All the known rel="me", used for the IndieWeb audience
  812. public function getRelMes()
  813. {
  814. $relMes = array();
  815. try {
  816. $relMes[] = $this->getRelSelf();
  817. } catch (InvalidUrlException $e) {
  818. // no valid profile URL available
  819. }
  820. if (common_valid_http_url($this->getHomepage())) {
  821. $relMes[] = ['href' => $this->getHomepage(),
  822. 'text' => _('Homepage'),
  823. 'image' => null];
  824. }
  825. Event::handle('OtherAccountProfiles', array($this, &$relMes));
  826. return $relMes;
  827. }
  828. public function delete($useWhere = false)
  829. {
  830. $this->_deleteNotices();
  831. $this->_deleteSubscriptions();
  832. $this->_deleteTags();
  833. $this->_deleteBlocks();
  834. $this->_deleteAttentions();
  835. Avatar::deleteFromProfile($this, true);
  836. $this->grantRole(Profile_role::DELETED);
  837. $localuser = User::getKV('id', $this->id);
  838. if ($localuser instanceof User) {
  839. $localuser->delete();
  840. }
  841. // Warning: delete() will run on the batch objects,
  842. // not on individual objects.
  843. $related = [
  844. 'Reply',
  845. 'Group_member',
  846. 'Profile_role',
  847. ];
  848. Event::handle('ProfileDeleteRelated', array($this, &$related));
  849. foreach ($related as $cls) {
  850. $inst = new $cls();
  851. $inst->profile_id = $this->id;
  852. $inst->delete();
  853. }
  854. return parent::delete($useWhere);
  855. }
  856. public function _deleteNotices()
  857. {
  858. $notice = new Notice();
  859. $notice->profile_id = $this->id;
  860. if ($notice->find()) {
  861. while ($notice->fetch()) {
  862. $other = clone($notice);
  863. $other->delete();
  864. }
  865. }
  866. }
  867. public function _deleteSubscriptions()
  868. {
  869. $sub = new Subscription();
  870. $sub->subscriber = $this->getID();
  871. $sub->find();
  872. while ($sub->fetch()) {
  873. try {
  874. $other = $sub->getSubscribed();
  875. if (!$other->sameAs($this)) {
  876. Subscription::cancel($this, $other);
  877. }
  878. } catch (NoResultException $e) {
  879. // Profile not found
  880. common_log(LOG_INFO, 'Subscribed profile id=='.$sub->subscribed.' not found when deleting profile id=='.$this->getID().', ignoring...');
  881. } catch (ServerException $e) {
  882. // Subscription cancel failed
  883. common_log(LOG_INFO, 'Subscribed profile id=='.$other->getID().' could not be reached for unsubscription notice when deleting profile id=='.$this->getID().', ignoring...');
  884. }
  885. }
  886. $sub = new Subscription();
  887. $sub->subscribed = $this->getID();
  888. $sub->find();
  889. while ($sub->fetch()) {
  890. try {
  891. $other = $sub->getSubscriber();
  892. common_log(LOG_INFO, 'Subscriber profile id=='.$sub->subscribed.' not found when deleting profile id=='.$this->getID().', ignoring...');
  893. if (!$other->sameAs($this)) {
  894. Subscription::cancel($other, $this);
  895. }
  896. } catch (NoResultException $e) {
  897. // Profile not found
  898. common_log(LOG_INFO, 'Subscribed profile id=='.$sub->subscribed.' not found when deleting profile id=='.$this->getID().', ignoring...');
  899. } catch (ServerException $e) {
  900. // Subscription cancel failed
  901. common_log(LOG_INFO, 'Subscriber profile id=='.$other->getID().' could not be reached for unsubscription notice when deleting profile id=='.$this->getID().', ignoring...');
  902. }
  903. }
  904. // Finally delete self-subscription
  905. $self = new Subscription();
  906. $self->subscriber = $this->getID();
  907. $self->subscribed = $this->getID();
  908. $self->delete();
  909. }
  910. public function _deleteTags()
  911. {
  912. $tag = new Profile_tag();
  913. $tag->tagged = $this->id;
  914. $tag->delete();
  915. }
  916. public function _deleteBlocks()
  917. {
  918. $block = new Profile_block();
  919. $block->blocked = $this->id;
  920. $block->delete();
  921. $block = new Group_block();
  922. $block->blocked = $this->id;
  923. $block->delete();
  924. }
  925. public function _deleteAttentions()
  926. {
  927. $att = new Attention();
  928. $att->profile_id = $this->getID();
  929. if ($att->find()) {
  930. while ($att->fetch()) {
  931. // Can't do delete() on the object directly since it won't remove all of it
  932. $other = clone($att);
  933. $other->delete();
  934. }
  935. }
  936. }
  937. // XXX: identical to Notice::getLocation.
  938. public function getLocation()
  939. {
  940. $location = null;
  941. if (!empty($this->location_id) && !empty($this->location_ns)) {
  942. $location = Location::fromId($this->location_id, $this->location_ns);
  943. }
  944. if (is_null($location)) { // no ID, or Location::fromId() failed
  945. if (!empty($this->lat) && !empty($this->lon)) {
  946. $location = Location::fromLatLon($this->lat, $this->lon);
  947. }
  948. }
  949. if (is_null($location)) { // still haven't found it!
  950. if (!empty($this->location)) {
  951. $location = Location::fromName($this->location);
  952. }
  953. }
  954. return $location;
  955. }
  956. public function shareLocation()
  957. {
  958. $cfg = common_config('location', 'share');
  959. if ($cfg == 'always') {
  960. return true;
  961. } elseif ($cfg == 'never') {
  962. return false;
  963. } else { // user
  964. $share = common_config('location', 'sharedefault');
  965. // Check if user has a personal setting for this
  966. $prefs = User_location_prefs::getKV('user_id', $this->id);
  967. if (!empty($prefs)) {
  968. $share = $prefs->share_location;
  969. $prefs->free();
  970. }
  971. return $share;
  972. }
  973. }
  974. public function hasRole($name)
  975. {
  976. $has_role = false;
  977. if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
  978. $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
  979. 'role' => $name));
  980. $has_role = !empty($role);
  981. Event::handle('EndHasRole', array($this, $name, $has_role));
  982. }
  983. return $has_role;
  984. }
  985. public function grantRole($name)
  986. {
  987. if (Event::handle('StartGrantRole', array($this, $name))) {
  988. $role = new Profile_role();
  989. $role->profile_id = $this->id;
  990. $role->role = $name;
  991. $role->created = common_sql_now();
  992. $result = $role->update();
  993. if ($result === 0 || $result === false) {
  994. $result = $role->insert();
  995. }
  996. if (!$result) {
  997. throw new Exception("Can't save role '$name' for profile '{$this->id}'");
  998. }
  999. if ($name == 'owner') {
  1000. User::blow('user:site_owner');
  1001. }
  1002. Event::handle('EndGrantRole', array($this, $name));
  1003. }
  1004. return $result;
  1005. }
  1006. public function revokeRole($name)
  1007. {
  1008. if (Event::handle('StartRevokeRole', array($this, $name))) {
  1009. $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
  1010. 'role' => $name));
  1011. if (empty($role)) {
  1012. // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
  1013. // TRANS: %1$s is the role name, %2$s is the user ID (number).
  1014. throw new Exception(sprintf(
  1015. _('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),
  1016. $name,
  1017. $this->id
  1018. ));
  1019. }
  1020. $result = $role->delete();
  1021. if (!$result) {
  1022. common_log_db_error($role, 'DELETE', __FILE__);
  1023. // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
  1024. // TRANS: %1$s is the role name, %2$s is the user ID (number).
  1025. throw new Exception(sprintf(
  1026. _('Cannot revoke role "%1$s" for user #%2$d; database error.'),
  1027. $name,
  1028. $this->id
  1029. ));
  1030. }
  1031. if ($name == 'owner') {
  1032. User::blow('user:site_owner');
  1033. }
  1034. Event::handle('EndRevokeRole', array($this, $name));
  1035. return true;
  1036. }
  1037. }
  1038. public function isSandboxed()
  1039. {
  1040. return $this->hasRole(Profile_role::SANDBOXED);
  1041. }
  1042. public function isSilenced()
  1043. {
  1044. return $this->hasRole(Profile_role::SILENCED);
  1045. }
  1046. public function sandbox()
  1047. {
  1048. $this->grantRole(Profile_role::SANDBOXED);
  1049. }
  1050. public function unsandbox()
  1051. {
  1052. $this->revokeRole(Profile_role::SANDBOXED);
  1053. }
  1054. public function silence()
  1055. {
  1056. $this->grantRole(Profile_role::SILENCED);
  1057. if (common_config('notice', 'hidespam')) {
  1058. $this->flushVisibility();
  1059. }
  1060. }
  1061. public function silenceAs(Profile $actor)
  1062. {
  1063. if (!$actor->hasRight(Right::SILENCEUSER)) {
  1064. throw new AuthorizationException(_('You cannot silence users on this site.'));
  1065. }
  1066. // Only administrators can silence other privileged users (such as others who have the right to silence).
  1067. if ($this->isPrivileged() && !$actor->hasRole(Profile_role::ADMINISTRATOR)) {
  1068. throw new AuthorizationException(_('You cannot silence other privileged users.'));
  1069. }
  1070. if ($this->isSilenced()) {
  1071. // TRANS: Client error displayed trying to silence an already silenced user.
  1072. throw new AlreadyFulfilledException(_('User is already silenced.'));
  1073. }
  1074. return $this->silence();
  1075. }
  1076. public function unsilence()
  1077. {
  1078. $this->revokeRole(Profile_role::SILENCED);
  1079. if (common_config('notice', 'hidespam')) {
  1080. $this->flushVisibility();
  1081. }
  1082. }
  1083. public function unsilenceAs(Profile $actor)
  1084. {
  1085. if (!$actor->hasRight(Right::SILENCEUSER)) {
  1086. // TRANS: Client error displayed trying to unsilence a user when the user does not have the right.
  1087. throw new AuthorizationException(_('You cannot unsilence users on this site.'));
  1088. }
  1089. if (!$this->isSilenced()) {
  1090. // TRANS: Client error displayed trying to unsilence a user when the target user has not been silenced.
  1091. throw new AlreadyFulfilledException(_('User is not silenced.'));
  1092. }
  1093. return $this->unsilence();
  1094. }
  1095. public function flushVisibility()
  1096. {
  1097. // Get all notices
  1098. $stream = new ProfileNoticeStream($this, $this);
  1099. $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
  1100. foreach ($ids as $id) {
  1101. self::blow('notice:in-scope-for:%d:null', $id);
  1102. }
  1103. }
  1104. public function isPrivileged()
  1105. {
  1106. // TODO: An Event::handle so plugins can report if users are privileged.
  1107. // The ModHelper is the only one I care about when coding this, and that
  1108. // can be tested with Right::SILENCEUSER which I do below:
  1109. switch (true) {
  1110. case $this->hasRight(Right::SILENCEUSER):
  1111. case $this->hasRole(Profile_role::MODERATOR):
  1112. case $this->hasRole(Profile_role::ADMINISTRATOR):
  1113. case $this->hasRole(Profile_role::OWNER):
  1114. return true;
  1115. }
  1116. return false;
  1117. }
  1118. /**
  1119. * Does this user have the right to do X?
  1120. *
  1121. * With our role-based authorization, this is merely a lookup for whether the user
  1122. * has a particular role. The implementation currently uses a switch statement
  1123. * to determine if the user has the pre-defined role to exercise the right. Future
  1124. * implementations may allow per-site roles, and different mappings of roles to rights.
  1125. *
  1126. * @param $right string Name of the right, usually a constant in class Right
  1127. * @return boolean whether the user has the right in question
  1128. */
  1129. public function hasRight($right)
  1130. {
  1131. $result = false;
  1132. if ($this->hasRole(Profile_role::DELETED)) {
  1133. return false;
  1134. }
  1135. if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
  1136. switch ($right) {
  1137. case Right::DELETEOTHERSNOTICE:
  1138. case Right::MAKEGROUPADMIN:
  1139. case Right::SANDBOXUSER:
  1140. case Right::SILENCEUSER:
  1141. case Right::DELETEUSER:
  1142. case Right::DELETEGROUP:
  1143. case Right::TRAINSPAM:
  1144. case Right::REVIEWSPAM:
  1145. $result = $this->hasRole(Profile_role::MODERATOR);
  1146. break;
  1147. case Right::CONFIGURESITE:
  1148. $result = $this->hasRole(Profile_role::ADMINISTRATOR);
  1149. break;
  1150. case Right::GRANTROLE:
  1151. case Right::REVOKEROLE:
  1152. $result = $this->hasRole(Profile_role::OWNER);
  1153. break;
  1154. case Right::NEWNOTICE:
  1155. case Right::NEWMESSAGE:
  1156. case Right::SUBSCRIBE:
  1157. case Right::CREATEGROUP:
  1158. $result = !$this->isSilenced();
  1159. break;
  1160. case Right::PUBLICNOTICE:
  1161. case Right::EMAILONREPLY:
  1162. case Right::EMAILONSUBSCRIBE:
  1163. case Right::EMAILONFAVE:
  1164. $result = !$this->isSandboxed() && !$this->isSilenced();
  1165. break;
  1166. case Right::WEBLOGIN:
  1167. $result = !$this->isSilenced();
  1168. break;
  1169. case Right::API:
  1170. $result = !$this->isSilenced();
  1171. break;
  1172. case Right::BACKUPACCOUNT:
  1173. $result = common_config('profile', 'backup');
  1174. break;
  1175. case Right::RESTOREACCOUNT:
  1176. $result = common_config('profile', 'restore');
  1177. break;
  1178. case Right::DELETEACCOUNT:
  1179. $result = common_config('profile', 'delete');
  1180. break;
  1181. case Right::MOVEACCOUNT:
  1182. $result = common_config('profile', 'move');
  1183. break;
  1184. default:
  1185. $result = false;
  1186. break;
  1187. }
  1188. }
  1189. return $result;
  1190. }
  1191. // FIXME: Can't put Notice typing here due to ArrayWrapper
  1192. public function hasRepeated($notice)
  1193. {
  1194. // XXX: not really a pkey, but should work
  1195. $notice = Notice::pkeyGet(array('profile_id' => $this->getID(),
  1196. 'repeat_of' => $notice->getID(),
  1197. 'verb' => ActivityVerb::SHARE));
  1198. return !empty($notice);
  1199. }
  1200. /**
  1201. * Returns an XML string fragment with limited profile information
  1202. * as an Atom <author> element.
  1203. *
  1204. * Assumes that Atom has been previously set up as the base namespace.
  1205. *
  1206. * @param Profile $cur the current authenticated user
  1207. *
  1208. * @return string
  1209. */
  1210. public function asAtomAuthor($cur = null)
  1211. {
  1212. $xs = new XMLStringer(true);
  1213. $xs->elementStart('author');
  1214. $xs->element('name', null, $this->nickname);
  1215. $xs->element('uri', null, $this->getUri());
  1216. if ($cur != null) {
  1217. $attrs = [];
  1218. $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
  1219. $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
  1220. $xs->element('statusnet:profile_info', $attrs, null);
  1221. }
  1222. $xs->elementEnd('author');
  1223. return $xs->getString();
  1224. }
  1225. /**
  1226. * Extra profile info for atom entries
  1227. *
  1228. * Clients use some extra profile info in the atom stream.
  1229. * This gives it to them.
  1230. *
  1231. * @param Profile $scoped The currently logged in/scoped profile
  1232. *
  1233. * @return array representation of <statusnet:profile_info> element or null
  1234. */
  1235. public function profileInfo(Profile $scoped = null)
  1236. {
  1237. $profileInfoAttr = array('local_id' => $this->id);
  1238. if ($scoped instanceof Profile) {
  1239. // Whether the current user is a subscribed to this profile
  1240. $profileInfoAttr['following'] = $scoped->isSubscribed($this) ? 'true' : 'false';
  1241. // Whether the current user is has blocked this profile
  1242. $profileInfoAttr['blocking'] = $scoped->hasBlocked($this) ? 'true' : 'false';
  1243. }
  1244. return array('statusnet:profile_info', $profileInfoAttr, null);
  1245. }
  1246. /**
  1247. * Returns an XML string fragment with profile information as an
  1248. * Activity Streams <activity:actor> element.
  1249. *
  1250. * Assumes that 'activity' namespace has been previously defined.
  1251. *
  1252. * @return string
  1253. */
  1254. public function asActivityActor()
  1255. {
  1256. return $this->asActivityNoun('actor');
  1257. }
  1258. /**
  1259. * Returns an XML string fragment with profile information as an
  1260. * Activity Streams noun object with the given element type.
  1261. *
  1262. * Assumes that 'activity', 'georss', and 'poco' namespace has been
  1263. * previously defined.
  1264. *
  1265. * @param string $element one of 'actor', 'subject', 'object', 'target'
  1266. *
  1267. * @return string
  1268. */
  1269. public function asActivityNoun($element)
  1270. {
  1271. $noun = $this->asActivityObject();
  1272. return $noun->asString('activity:' . $element);
  1273. }
  1274. public function asActivityObject()
  1275. {
  1276. $object = new ActivityObject();
  1277. if (Event::handle('StartActivityObjectFromProfile', array($this, &$object))) {
  1278. $object->type = $this->getObjectType();
  1279. $object->id = $this->getUri();
  1280. $object->title = $this->getBestName();
  1281. $object->link = $this->getUrl();
  1282. $object->summary = $this->getDescription();
  1283. try {
  1284. $avatar = Avatar::getUploaded($this);
  1285. $object->avatarLinks[] = AvatarLink::fromAvatar($avatar);
  1286. } catch (NoAvatarException $e) {
  1287. // Could not find an original avatar to link
  1288. }
  1289. $sizes = array(
  1290. AVATAR_PROFILE_SIZE,
  1291. AVATAR_STREAM_SIZE,
  1292. AVATAR_MINI_SIZE
  1293. );
  1294. foreach ($sizes as $size) {
  1295. $alink = null;
  1296. try {
  1297. $avatar = Avatar::byProfile($this, $size);
  1298. $alink = AvatarLink::fromAvatar($avatar);
  1299. } catch (NoAvatarException $e) {
  1300. $alink = new AvatarLink();
  1301. $alink->type = 'image/png';
  1302. $alink->height = $size;
  1303. $alink->width = $size;
  1304. $alink->url = Avatar::defaultImage($size);
  1305. }
  1306. $object->avatarLinks[] = $alink;
  1307. }
  1308. if (isset($this->lat) && isset($this->lon)) {
  1309. $object->geopoint = (float)$this->lat
  1310. . ' ' . (float)$this->lon;
  1311. }
  1312. $object->poco = PoCo::fromProfile($this);
  1313. if ($this->isLocal()) {
  1314. $object->extra[] = array('followers', array('url' => common_local_url('subscribers', array('nickname' => $this->getNickname()))));
  1315. }
  1316. Event::handle('EndActivityObjectFromProfile', array($this, &$object));
  1317. }
  1318. return $object;
  1319. }
  1320. /**
  1321. * Returns the profile's canonical url, not necessarily a uri/unique id
  1322. *
  1323. * @return string $profileurl
  1324. */
  1325. public function getUrl()
  1326. {
  1327. $url = null;
  1328. if ($this->isGroup()) {
  1329. // FIXME: Get rid of this event, it fills no real purpose, data should be in Profile->profileurl (replaces User_group->mainpage)
  1330. if (Event::handle('StartUserGroupHomeUrl', array($this->getGroup(), &$url))) {
  1331. $url = $this->getGroup()->isLocal()
  1332. ? common_local_url('showgroup', array('nickname' => $this->getNickname()))
  1333. : $this->profileurl;
  1334. }
  1335. Event::handle('EndUserGroupHomeUrl', array($this->getGroup(), $url));
  1336. } elseif ($this->isLocal()) {
  1337. $url = common_local_url('showstream', array('nickname' => $this->getNickname()));
  1338. } else {
  1339. $url = $this->profileurl;
  1340. }
  1341. if (empty($url) ||
  1342. !filter_var($url, FILTER_VALIDATE_URL)) {
  1343. throw new InvalidUrlException($url);
  1344. }
  1345. return $url;
  1346. }
  1347. public function getHtmlTitle()
  1348. {
  1349. try {
  1350. return $this->getAcctUri(false);
  1351. } catch (ProfileNoAcctUriException $e) {
  1352. return $this->getNickname();
  1353. }
  1354. }
  1355. public function getNickname()
  1356. {
  1357. return $this->nickname;
  1358. }
  1359. public function getFullname()
  1360. {
  1361. return $this->fullname;
  1362. }
  1363. public function getHomepage()
  1364. {
  1365. return $this->homepage;
  1366. }
  1367. public function getDescription()
  1368. {
  1369. return $this->bio;
  1370. }
  1371. /**
  1372. * Returns the best URI for a profile. Plugins may override.
  1373. *
  1374. * @return string $uri
  1375. */
  1376. public function getUri()
  1377. {
  1378. $uri = null;
  1379. // give plugins a chance to set the URI
  1380. if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
  1381. // check for a local user first
  1382. $user = User::getKV('id', $this->id);
  1383. if ($user instanceof User) {
  1384. $uri = $user->getUri();
  1385. } else {
  1386. $group = User_group::getKV('profile_id', $this->id);
  1387. if ($group instanceof User_group) {
  1388. $uri = $group->getUri();
  1389. }
  1390. }
  1391. Event::handle('EndGetProfileUri', array($this, &$uri));
  1392. }
  1393. return $uri;
  1394. }
  1395. /**
  1396. * Returns an assumed acct: URI for a profile. Plugins are required.
  1397. *
  1398. * @return string $uri
  1399. */
  1400. public function getAcctUri($scheme=true)
  1401. {
  1402. $acct = null;
  1403. if (Event::handle('StartGetProfileAcctUri', array($this, &$acct))) {
  1404. Event::handle('EndGetProfileAcctUri', array($this, &$acct));
  1405. }
  1406. if ($acct === null) {
  1407. throw new ProfileNoAcctUriException($this);
  1408. }
  1409. if (parse_url($acct, PHP_URL_SCHEME) !== 'acct') {
  1410. throw new ServerException('Acct URI does not have acct: scheme');
  1411. }
  1412. // if we don't return the scheme, just remove the 'acct:' in the beginning
  1413. return $scheme ? $acct : mb_substr($acct, 5);
  1414. }
  1415. public function hasBlocked(Profile $other)
  1416. {
  1417. $block = Profile_block::exists($this, $other);
  1418. return !empty($block);
  1419. }
  1420. public function getAtomFeed()
  1421. {
  1422. $feed = null;
  1423. if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
  1424. if ($this->isLocal()) {
  1425. $feed = common_local_url('ApiTimelineUser', array('id' => $this->getID(),
  1426. 'format' => 'atom'));
  1427. }
  1428. Event::handle('EndProfileGetAtomFeed', array($this, $feed));
  1429. }
  1430. return $feed;
  1431. }
  1432. public function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
  1433. {
  1434. // TRANS: Exception thrown when trying view "repeated to me".
  1435. throw new Exception(_('Not implemented since inbox change.'));
  1436. }
  1437. /*
  1438. * Get a Profile object by URI. Will call external plugins for help
  1439. * using the event StartGetProfileFromURI.
  1440. *
  1441. * @param string $uri A unique identifier for a resource (profile/group/whatever)
  1442. */
  1443. public static function fromUri($uri)
  1444. {
  1445. $profile = null;
  1446. if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
  1447. // Get a local user when plugin lookup (like OStatus) fails
  1448. $user = User::getKV('uri', $uri);
  1449. if ($user instanceof User) {
  1450. $profile = $user->getProfile();
  1451. } else {
  1452. $group = User_group::getKV('uri', $uri);
  1453. if ($group instanceof User_group) {
  1454. $profile = $group->getProfile();
  1455. }
  1456. }
  1457. Event::handle('EndGetProfileFromURI', array($uri, $profile));
  1458. }
  1459. if (!$profile instanceof Profile) {
  1460. throw new UnknownUriException($uri);
  1461. }
  1462. return $profile;
  1463. }
  1464. public function canRead(Notice $notice)
  1465. {
  1466. if ($notice->scope & Notice::SITE_SCOPE) {
  1467. $user = $this->getUser();
  1468. if (empty($user)) {
  1469. return false;
  1470. }
  1471. }
  1472. if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
  1473. $replies = $notice->getReplies();
  1474. if (!in_array($this->id, $replies)) {
  1475. $groups = $notice->getGroups();
  1476. $foundOne = false;
  1477. foreach ($groups as $group) {
  1478. if ($this->isMember($group)) {
  1479. $foundOne = true;
  1480. break;
  1481. }
  1482. }
  1483. if (!$foundOne) {
  1484. return false;
  1485. }
  1486. }
  1487. }
  1488. if ($notice->scope & Notice::FOLLOWER_SCOPE) {
  1489. $author = $notice->getProfile();
  1490. if (!Subscription::exists($this, $author)) {
  1491. return false;
  1492. }
  1493. }
  1494. return true;
  1495. }
  1496. public static function current()
  1497. {
  1498. $user = common_current_user();
  1499. if (empty($user)) {
  1500. $profile = null;
  1501. } else {
  1502. $profile = $user->getProfile();
  1503. }
  1504. return $profile;
  1505. }
  1506. public static function ensureCurrent()
  1507. {
  1508. $profile = self::current();
  1509. if (!$profile instanceof Profile) {
  1510. throw new AuthorizationException('A currently scoped profile is required.');
  1511. }
  1512. return $profile;
  1513. }
  1514. /**
  1515. * Magic function called at serialize() time.
  1516. *
  1517. * We use this to drop a couple process-specific references
  1518. * from DB_DataObject which can cause trouble in future
  1519. * processes.
  1520. *
  1521. * @return array of variable names to include in serialization.
  1522. */
  1523. public function __sleep()
  1524. {
  1525. $vars = parent::__sleep();
  1526. $skip = array('_user', '_group');
  1527. return array_diff($vars, $skip);
  1528. }
  1529. public function getProfile()
  1530. {
  1531. return $this;
  1532. }
  1533. /**
  1534. * Test whether the given profile is the same as the current class,
  1535. * for testing identities.
  1536. *
  1537. * @param Profile $other The other profile, usually from Action's $this->scoped
  1538. *
  1539. * @return boolean
  1540. */
  1541. public function sameAs(Profile $other=null)
  1542. {
  1543. if (is_null($other)) {
  1544. // In case $this->scoped is null or something, i.e. not a current/legitimate profile.
  1545. return false;
  1546. }
  1547. return $this->getID() === $other->getID();
  1548. }
  1549. /**
  1550. * This will perform shortenLinks with the connected User object.
  1551. *
  1552. * Won't work on remote profiles or groups, so expect a
  1553. * NoSuchUserException if you don't know it's a local User.
  1554. *
  1555. * @param string $text String to shorten
  1556. * @param boolean $always Disrespect minimum length etc.
  1557. *
  1558. * @return string link-shortened $text
  1559. */
  1560. public function shortenLinks($text, $always=false)
  1561. {
  1562. return $this->getUser()->shortenLinks($text, $always);
  1563. }
  1564. public function isPrivateStream(): bool
  1565. {
  1566. // We only know of public remote users as of yet...
  1567. if (!$this->isLocal()) {
  1568. return false;
  1569. }
  1570. $private_stream = $this->getUser()->private_stream;
  1571. return !is_null($private_stream) && $private_stream;
  1572. }
  1573. public function delPref($namespace, $topic)
  1574. {
  1575. return Profile_prefs::setData($this, $namespace, $topic, null);
  1576. }
  1577. public function getPref($namespace, $topic, $default = null)
  1578. {
  1579. // If you want an exception to be thrown, call Profile_prefs::getData directly
  1580. try {
  1581. return Profile_prefs::getData($this, $namespace, $topic, $default);
  1582. } catch (NoResultException $e) {
  1583. return null;
  1584. }
  1585. }
  1586. // The same as getPref but will fall back to common_config value for the same namespace/topic
  1587. public function getConfigPref($namespace, $topic)
  1588. {
  1589. return Profile_prefs::getConfigData($this, $namespace, $topic);
  1590. }
  1591. public function setPref($namespace, $topic, $data)
  1592. {
  1593. return Profile_prefs::setData($this, $namespace, $topic, $data);
  1594. }
  1595. public function getConnectedApps($offset=0, $limit=null)
  1596. {
  1597. return $this->getUser()->getConnectedApps($offset, $limit);
  1598. }
  1599. }