Profile.php 57 KB

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