Profile.php 57 KB

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