Profile.php 55 KB

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