util.php 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383
  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. /* XXX: break up into separate modules (HTTP, user, files) */
  20. /**
  21. * Show a server error.
  22. */
  23. function common_server_error($msg, $code=500)
  24. {
  25. $err = new ServerErrorAction($msg, $code);
  26. $err->showPage();
  27. }
  28. /**
  29. * Show a user error.
  30. */
  31. function common_user_error($msg, $code=400)
  32. {
  33. $err = new ClientErrorAction($msg, $code);
  34. $err->showPage();
  35. }
  36. /**
  37. * This should only be used at setup; processes switching languages
  38. * to send text to other users should use common_switch_locale().
  39. *
  40. * @param string $language Locale language code (optional; empty uses
  41. * current user's preference or site default)
  42. * @return mixed success
  43. */
  44. function common_init_locale($language=null)
  45. {
  46. if(!$language) {
  47. $language = common_language();
  48. }
  49. putenv('LANGUAGE='.$language);
  50. putenv('LANG='.$language);
  51. $ok = setlocale(LC_ALL, $language . ".utf8",
  52. $language . ".UTF8",
  53. $language . ".utf-8",
  54. $language . ".UTF-8",
  55. $language);
  56. return $ok;
  57. }
  58. /**
  59. * Initialize locale and charset settings and gettext with our message catalog,
  60. * using the current user's language preference or the site default.
  61. *
  62. * This should generally only be run at framework initialization; code switching
  63. * languages at runtime should call common_switch_language().
  64. *
  65. * @access private
  66. */
  67. function common_init_language()
  68. {
  69. mb_internal_encoding('UTF-8');
  70. // Note that this setlocale() call may "fail" but this is harmless;
  71. // gettext will still select the right language.
  72. $language = common_language();
  73. $locale_set = common_init_locale($language);
  74. if (!$locale_set) {
  75. // The requested locale doesn't exist on the system.
  76. //
  77. // gettext seems very picky... We first need to setlocale()
  78. // to a locale which _does_ exist on the system, and _then_
  79. // we can set in another locale that may not be set up
  80. // (say, ga_ES for Galego/Galician) it seems to take it.
  81. //
  82. // For some reason C and POSIX which are guaranteed to work
  83. // don't do the job. en_US.UTF-8 should be there most of the
  84. // time, but not guaranteed.
  85. $ok = common_init_locale("en_US");
  86. if (!$ok && strtolower(substr(PHP_OS, 0, 3)) != 'win') {
  87. // Try to find a complete, working locale on Unix/Linux...
  88. // @fixme shelling out feels awfully inefficient
  89. // but I don't think there's a more standard way.
  90. $all = `locale -a`;
  91. foreach (explode("\n", $all) as $locale) {
  92. if (preg_match('/\.utf[-_]?8$/i', $locale)) {
  93. $ok = setlocale(LC_ALL, $locale);
  94. if ($ok) {
  95. break;
  96. }
  97. }
  98. }
  99. }
  100. if (!$ok) {
  101. common_log(LOG_ERR, "Unable to find a UTF-8 locale on this system; UI translations may not work.");
  102. }
  103. $locale_set = common_init_locale($language);
  104. }
  105. common_init_gettext();
  106. }
  107. /**
  108. * @access private
  109. */
  110. function common_init_gettext()
  111. {
  112. setlocale(LC_CTYPE, 'C');
  113. // So we do not have to make people install the gettext locales
  114. $path = common_config('site','locale_path');
  115. bindtextdomain("statusnet", $path);
  116. bind_textdomain_codeset("statusnet", "UTF-8");
  117. textdomain("statusnet");
  118. }
  119. /**
  120. * Switch locale during runtime, and poke gettext until it cries uncle.
  121. * Otherwise, sometimes it doesn't actually switch away from the old language.
  122. *
  123. * @param string $language code for locale ('en', 'fr', 'pt_BR' etc)
  124. */
  125. function common_switch_locale($language=null)
  126. {
  127. common_init_locale($language);
  128. setlocale(LC_CTYPE, 'C');
  129. // So we do not have to make people install the gettext locales
  130. $path = common_config('site','locale_path');
  131. bindtextdomain("statusnet", $path);
  132. bind_textdomain_codeset("statusnet", "UTF-8");
  133. textdomain("statusnet");
  134. }
  135. function common_timezone()
  136. {
  137. if (common_logged_in()) {
  138. $user = common_current_user();
  139. if ($user->timezone) {
  140. return $user->timezone;
  141. }
  142. }
  143. return common_config('site', 'timezone');
  144. }
  145. function common_valid_language($lang)
  146. {
  147. if ($lang) {
  148. // Validate -- we don't want to end up with a bogus code
  149. // left over from some old junk.
  150. foreach (common_config('site', 'languages') as $code => $info) {
  151. if ($info['lang'] == $lang) {
  152. return true;
  153. }
  154. }
  155. }
  156. return false;
  157. }
  158. function common_language()
  159. {
  160. // Allow ?uselang=xx override, very useful for debugging
  161. // and helping translators check usage and context.
  162. if (isset($_GET['uselang'])) {
  163. $uselang = strval($_GET['uselang']);
  164. if (common_valid_language($uselang)) {
  165. return $uselang;
  166. }
  167. }
  168. // If there is a user logged in and they've set a language preference
  169. // then return that one...
  170. if (_have_config() && common_logged_in()) {
  171. $user = common_current_user();
  172. if (common_valid_language($user->language)) {
  173. return $user->language;
  174. }
  175. }
  176. // Otherwise, find the best match for the languages requested by the
  177. // user's browser...
  178. if (common_config('site', 'langdetect')) {
  179. $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
  180. if (!empty($httplang)) {
  181. $language = client_prefered_language($httplang);
  182. if ($language)
  183. return $language;
  184. }
  185. }
  186. // Finally, if none of the above worked, use the site's default...
  187. return common_config('site', 'language');
  188. }
  189. /**
  190. * Salted, hashed passwords are stored in the DB.
  191. */
  192. function common_munge_password($password, $id, Profile $profile=null)
  193. {
  194. $hashed = null;
  195. if (Event::handle('StartHashPassword', array(&$hashed, $password, $profile))) {
  196. Event::handle('EndHashPassword', array(&$hashed, $password, $profile));
  197. }
  198. if (empty($hashed)) {
  199. throw new PasswordHashException();
  200. }
  201. return $hashed;
  202. }
  203. /**
  204. * Check if a username exists and has matching password.
  205. */
  206. function common_check_user($nickname, $password)
  207. {
  208. // empty nickname always unacceptable
  209. if (empty($nickname)) {
  210. return false;
  211. }
  212. $authenticatedUser = false;
  213. if (Event::handle('StartCheckPassword', array($nickname, $password, &$authenticatedUser))) {
  214. if (common_is_email($nickname)) {
  215. $user = User::getKV('email', common_canonical_email($nickname));
  216. } else {
  217. $user = User::getKV('nickname', Nickname::normalize($nickname));
  218. }
  219. if ($user instanceof User && !empty($password)) {
  220. if (0 == strcmp(common_munge_password($password, $user->id),
  221. $user->password)) {
  222. //internal checking passed
  223. $authenticatedUser = $user;
  224. }
  225. }
  226. }
  227. Event::handle('EndCheckPassword', array($nickname, $password, $authenticatedUser));
  228. return $authenticatedUser;
  229. }
  230. /**
  231. * Is the current user logged in?
  232. */
  233. function common_logged_in()
  234. {
  235. return (!is_null(common_current_user()));
  236. }
  237. function common_have_session()
  238. {
  239. return (0 != strcmp(session_id(), ''));
  240. }
  241. function common_ensure_session()
  242. {
  243. $c = null;
  244. if (array_key_exists(session_name(), $_COOKIE)) {
  245. $c = $_COOKIE[session_name()];
  246. }
  247. if (!common_have_session()) {
  248. if (common_config('sessions', 'handle')) {
  249. Session::setSaveHandler();
  250. }
  251. if (array_key_exists(session_name(), $_GET)) {
  252. $id = $_GET[session_name()];
  253. } else if (array_key_exists(session_name(), $_COOKIE)) {
  254. $id = $_COOKIE[session_name()];
  255. }
  256. if (isset($id)) {
  257. session_id($id);
  258. }
  259. @session_start();
  260. if (!isset($_SESSION['started'])) {
  261. $_SESSION['started'] = time();
  262. if (!empty($id)) {
  263. common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' .
  264. ' is set but started value is null');
  265. }
  266. }
  267. }
  268. }
  269. // Three kinds of arguments:
  270. // 1) a user object
  271. // 2) a nickname
  272. // 3) null to clear
  273. // Initialize to false; set to null if none found
  274. $_cur = false;
  275. function common_set_user($user)
  276. {
  277. global $_cur;
  278. if (is_null($user) && common_have_session()) {
  279. $_cur = null;
  280. unset($_SESSION['userid']);
  281. return true;
  282. } else if (is_string($user)) {
  283. $nickname = $user;
  284. $user = User::getKV('nickname', $nickname);
  285. } else if (!$user instanceof User) {
  286. return false;
  287. }
  288. if ($user) {
  289. if (Event::handle('StartSetUser', array(&$user))) {
  290. if (!empty($user)) {
  291. if (!$user->hasRight(Right::WEBLOGIN)) {
  292. // TRANS: Authorisation exception thrown when a user a not allowed to login.
  293. throw new AuthorizationException(_('Not allowed to log in.'));
  294. }
  295. common_ensure_session();
  296. $_SESSION['userid'] = $user->id;
  297. $_cur = $user;
  298. Event::handle('EndSetUser', array($user));
  299. return $_cur;
  300. }
  301. }
  302. }
  303. return false;
  304. }
  305. function common_set_cookie($key, $value, $expiration=0)
  306. {
  307. $path = common_config('site', 'path');
  308. $server = common_config('site', 'server');
  309. if ($path && ($path != '/')) {
  310. $cookiepath = '/' . $path . '/';
  311. } else {
  312. $cookiepath = '/';
  313. }
  314. return setcookie($key,
  315. $value,
  316. $expiration,
  317. $cookiepath,
  318. $server,
  319. common_config('site', 'ssl')=='always');
  320. }
  321. define('REMEMBERME', 'rememberme');
  322. define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
  323. function common_rememberme($user=null)
  324. {
  325. if (!$user) {
  326. $user = common_current_user();
  327. if (!$user) {
  328. return false;
  329. }
  330. }
  331. $rm = new Remember_me();
  332. $rm->code = common_random_hexstr(16);
  333. $rm->user_id = $user->id;
  334. // Wrap the insert in some good ol' fashioned transaction code
  335. $rm->query('BEGIN');
  336. $result = $rm->insert();
  337. if (!$result) {
  338. common_log_db_error($rm, 'INSERT', __FILE__);
  339. $rm->query('ROLLBACK');
  340. return false;
  341. }
  342. $rm->query('COMMIT');
  343. $cookieval = $rm->user_id . ':' . $rm->code;
  344. common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
  345. common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
  346. return true;
  347. }
  348. function common_remembered_user()
  349. {
  350. $user = null;
  351. $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
  352. if (!$packed) {
  353. return null;
  354. }
  355. list($id, $code) = explode(':', $packed);
  356. if (!$id || !$code) {
  357. common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
  358. common_forgetme();
  359. return null;
  360. }
  361. $rm = Remember_me::getKV('code', $code);
  362. if (!$rm) {
  363. common_log(LOG_WARNING, 'No such remember code: ' . $code);
  364. common_forgetme();
  365. return null;
  366. }
  367. if ($rm->user_id != $id) {
  368. common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
  369. common_forgetme();
  370. return null;
  371. }
  372. $user = User::getKV('id', $rm->user_id);
  373. if (!$user instanceof User) {
  374. common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
  375. common_forgetme();
  376. return null;
  377. }
  378. // successful!
  379. $result = $rm->delete();
  380. if (!$result) {
  381. common_log_db_error($rm, 'DELETE', __FILE__);
  382. common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
  383. common_forgetme();
  384. return null;
  385. }
  386. common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
  387. common_set_user($user);
  388. common_real_login(false);
  389. // We issue a new cookie, so they can log in
  390. // automatically again after this session
  391. common_rememberme($user);
  392. return $user;
  393. }
  394. /**
  395. * must be called with a valid user!
  396. */
  397. function common_forgetme()
  398. {
  399. common_set_cookie(REMEMBERME, '', 0);
  400. }
  401. /**
  402. * Who is the current user?
  403. */
  404. function common_current_user()
  405. {
  406. global $_cur;
  407. if (!_have_config()) {
  408. return null;
  409. }
  410. if ($_cur === false) {
  411. if (isset($_COOKIE[session_name()]) || isset($_GET[session_name()])
  412. || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
  413. common_ensure_session();
  414. $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
  415. if ($id) {
  416. $user = User::getKV('id', $id);
  417. if ($user instanceof User) {
  418. $_cur = $user;
  419. return $_cur;
  420. }
  421. }
  422. }
  423. // that didn't work; try to remember; will init $_cur to null on failure
  424. $_cur = common_remembered_user();
  425. if ($_cur) {
  426. // XXX: Is this necessary?
  427. $_SESSION['userid'] = $_cur->id;
  428. }
  429. }
  430. return $_cur;
  431. }
  432. /**
  433. * Logins that are 'remembered' aren't 'real' -- they're subject to
  434. * cookie-stealing. So, we don't let them do certain things. New reg,
  435. * OpenID, and password logins _are_ real.
  436. */
  437. function common_real_login($real=true)
  438. {
  439. common_ensure_session();
  440. $_SESSION['real_login'] = $real;
  441. }
  442. function common_is_real_login()
  443. {
  444. return common_logged_in() && $_SESSION['real_login'];
  445. }
  446. /**
  447. * Get a hash portion for HTTP caching Etags and such including
  448. * info on the current user's session. If login/logout state changes,
  449. * or we've changed accounts, or we've renamed the current user,
  450. * we'll get a new hash value.
  451. *
  452. * This should not be considered secure information.
  453. *
  454. * @param User $user (optional; uses common_current_user() if left out)
  455. * @return string
  456. */
  457. function common_user_cache_hash($user=false)
  458. {
  459. if ($user === false) {
  460. $user = common_current_user();
  461. }
  462. if ($user) {
  463. return crc32($user->id . ':' . $user->nickname);
  464. } else {
  465. return '0';
  466. }
  467. }
  468. /**
  469. * get canonical version of nickname for comparison
  470. *
  471. * @param string $nickname
  472. * @return string
  473. *
  474. * @throws NicknameException on invalid input
  475. * @deprecated call Nickname::normalize() directly.
  476. */
  477. function common_canonical_nickname($nickname)
  478. {
  479. return Nickname::normalize($nickname);
  480. }
  481. /**
  482. * get canonical version of email for comparison
  483. *
  484. * @fixme actually normalize
  485. * @fixme reject invalid input
  486. *
  487. * @param string $email
  488. * @return string
  489. */
  490. function common_canonical_email($email)
  491. {
  492. // XXX: canonicalize UTF-8
  493. // XXX: lcase the domain part
  494. return $email;
  495. }
  496. /**
  497. * Partial notice markup rendering step: build links to !group references.
  498. *
  499. * @param string $text partially rendered HTML
  500. * @param Notice $notice in whose context we're working
  501. * @return string partially rendered HTML
  502. */
  503. function common_render_content($text, Notice $notice)
  504. {
  505. $r = common_render_text($text);
  506. $r = common_linkify_mentions($r, $notice);
  507. return $r;
  508. }
  509. /**
  510. * Finds @-mentions within the partially-rendered text section and
  511. * turns them into live links.
  512. *
  513. * Should generally not be called except from common_render_content().
  514. *
  515. * @param string $text partially-rendered HTML
  516. * @param Notice $notice in-progress or complete Notice object for context
  517. * @return string partially-rendered HTML
  518. */
  519. function common_linkify_mentions($text, $notice)
  520. {
  521. $mentions = common_find_mentions($text, $notice);
  522. // We need to go through in reverse order by position,
  523. // so our positions stay valid despite our fudging with the
  524. // string!
  525. $points = array();
  526. foreach ($mentions as $mention)
  527. {
  528. $points[$mention['position']] = $mention;
  529. }
  530. krsort($points);
  531. foreach ($points as $position => $mention) {
  532. $linkText = common_linkify_mention($mention);
  533. $text = substr_replace($text, $linkText, $position, mb_strlen($mention['text']));
  534. }
  535. return $text;
  536. }
  537. function common_linkify_mention($mention)
  538. {
  539. $output = null;
  540. if (Event::handle('StartLinkifyMention', array($mention, &$output))) {
  541. $xs = new XMLStringer(false);
  542. $attrs = array('href' => $mention['url'],
  543. 'class' => 'h-card '.$mention['type']);
  544. if (!empty($mention['title'])) {
  545. $attrs['title'] = $mention['title'];
  546. }
  547. $xs->element('a', $attrs, $mention['text']);
  548. $output = $xs->getString();
  549. Event::handle('EndLinkifyMention', array($mention, &$output));
  550. }
  551. return $output;
  552. }
  553. /**
  554. * Find @-mentions in the given text, using the given notice object as context.
  555. * References will be resolved with common_relative_profile() against the user
  556. * who posted the notice.
  557. *
  558. * Note the return data format is internal, to be used for building links and
  559. * such. Should not be used directly; rather, call common_linkify_mentions().
  560. *
  561. * @param string $text
  562. * @param Notice $notice notice in whose context we're building links
  563. *
  564. * @return array
  565. *
  566. * @access private
  567. */
  568. function common_find_mentions($text, $notice)
  569. {
  570. try {
  571. $sender = Profile::getKV('id', $notice->profile_id);
  572. } catch (NoProfileException $e) {
  573. return array();
  574. }
  575. $mentions = array();
  576. if (Event::handle('StartFindMentions', array($sender, $text, &$mentions))) {
  577. // Get the context of the original notice, if any
  578. $origAuthor = null;
  579. $origNotice = null;
  580. $origMentions = array();
  581. // Is it a reply?
  582. if ($notice instanceof Notice) {
  583. try {
  584. $origNotice = $notice->getParent();
  585. $origAuthor = $origNotice->getProfile();
  586. $ids = $origNotice->getReplies();
  587. foreach ($ids as $id) {
  588. $repliedTo = Profile::getKV('id', $id);
  589. if ($repliedTo instanceof Profile) {
  590. $origMentions[$repliedTo->nickname] = $repliedTo;
  591. }
  592. }
  593. } catch (NoProfileException $e) {
  594. common_log(LOG_WARNING, sprintf('Notice %d author profile id %d does not exist', $origNotice->id, $origNotice->profile_id));
  595. } catch (ServerException $e) {
  596. // Probably just no parent. Should get a specific NoParentException
  597. } catch (Exception $e) {
  598. common_log(LOG_WARNING, __METHOD__ . ' got exception ' . get_class($e) . ' : ' . $e->getMessage());
  599. }
  600. }
  601. $matches = common_find_mentions_raw($text);
  602. foreach ($matches as $match) {
  603. try {
  604. $nickname = Nickname::normalize($match[0]);
  605. } catch (NicknameException $e) {
  606. // Bogus match? Drop it.
  607. continue;
  608. }
  609. // Try to get a profile for this nickname.
  610. // Start with conversation context, then go to
  611. // sender context.
  612. if ($origAuthor instanceof Profile && $origAuthor->nickname == $nickname) {
  613. $mentioned = $origAuthor;
  614. } else if (!empty($origMentions) &&
  615. array_key_exists($nickname, $origMentions)) {
  616. $mentioned = $origMentions[$nickname];
  617. } else {
  618. $mentioned = common_relative_profile($sender, $nickname);
  619. }
  620. if ($mentioned instanceof Profile) {
  621. $user = User::getKV('id', $mentioned->id);
  622. if ($user instanceof User) {
  623. $url = common_local_url('userbyid', array('id' => $user->id));
  624. } else {
  625. $url = $mentioned->profileurl;
  626. }
  627. $mention = array('mentioned' => array($mentioned),
  628. 'type' => 'mention',
  629. 'text' => $match[0],
  630. 'position' => $match[1],
  631. 'url' => $url);
  632. if (!empty($mentioned->fullname)) {
  633. $mention['title'] = $mentioned->fullname;
  634. }
  635. $mentions[] = $mention;
  636. }
  637. }
  638. // @#tag => mention of all subscriptions tagged 'tag'
  639. preg_match_all('/(?:^|[\s\.\,\:\;]+)@#([\pL\pN_\-\.]{1,64})/',
  640. $text, $hmatches, PREG_OFFSET_CAPTURE);
  641. foreach ($hmatches[1] as $hmatch) {
  642. $tag = common_canonical_tag($hmatch[0]);
  643. $plist = Profile_list::getByTaggerAndTag($sender->id, $tag);
  644. if (!$plist instanceof Profile_list || $plist->private) {
  645. continue;
  646. }
  647. $tagged = $sender->getTaggedSubscribers($tag);
  648. $url = common_local_url('showprofiletag',
  649. array('tagger' => $sender->nickname,
  650. 'tag' => $tag));
  651. $mentions[] = array('mentioned' => $tagged,
  652. 'type' => 'list',
  653. 'text' => $hmatch[0],
  654. 'position' => $hmatch[1],
  655. 'url' => $url);
  656. }
  657. preg_match_all('/(?:^|[\s\.\,\:\;]+)!(' . Nickname::DISPLAY_FMT . ')/',
  658. $text, $hmatches, PREG_OFFSET_CAPTURE);
  659. foreach ($hmatches[1] as $hmatch) {
  660. $nickname = Nickname::normalize($hmatch[0]);
  661. $group = User_group::getForNickname($nickname, $sender);
  662. if (!$group instanceof User_group || !$sender->isMember($group)) {
  663. continue;
  664. }
  665. $profile = $group->getProfile();
  666. $mentions[] = array('mentioned' => array($profile),
  667. 'type' => 'group',
  668. 'text' => $hmatch[0],
  669. 'position' => $hmatch[1],
  670. 'url' => $group->permalink(),
  671. 'title' => $group->getFancyName());
  672. }
  673. Event::handle('EndFindMentions', array($sender, $text, &$mentions));
  674. }
  675. return $mentions;
  676. }
  677. /**
  678. * Does the actual regex pulls to find @-mentions in text.
  679. * Should generally not be called directly; for use in common_find_mentions.
  680. *
  681. * @param string $text
  682. * @return array of PCRE match arrays
  683. */
  684. function common_find_mentions_raw($text)
  685. {
  686. $tmatches = array();
  687. preg_match_all('/^T (' . Nickname::DISPLAY_FMT . ') /',
  688. $text,
  689. $tmatches,
  690. PREG_OFFSET_CAPTURE);
  691. $atmatches = array();
  692. preg_match_all('/(?:^|\s+)@(' . Nickname::DISPLAY_FMT . ')\b/',
  693. $text,
  694. $atmatches,
  695. PREG_OFFSET_CAPTURE);
  696. $matches = array_merge($tmatches[1], $atmatches[1]);
  697. return $matches;
  698. }
  699. function common_render_text($text)
  700. {
  701. $r = nl2br(htmlspecialchars($text));
  702. $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
  703. $r = common_replace_urls_callback($r, 'common_linkify');
  704. $r = preg_replace_callback('/(^|\&quot\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/u',
  705. function ($m) { return "{$m[1]}#".common_tag_link($m[2]); }, $r);
  706. // XXX: machine tags
  707. return $r;
  708. }
  709. /**
  710. * Find links in the given text and pass them to the given callback function.
  711. *
  712. * @param string $text
  713. * @param function($text, $arg) $callback: return replacement text
  714. * @param mixed $arg: optional argument will be passed on to the callback
  715. */
  716. function common_replace_urls_callback($text, $callback, $arg = null) {
  717. // Start off with a regex
  718. $regex = '#'.
  719. '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
  720. '('.
  721. '(?:'.
  722. '(?:'. //Known protocols
  723. '(?:'.
  724. '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
  725. '|'.
  726. '(?:(?:mailto|aim|tel|xmpp):)'.
  727. ')'.
  728. '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
  729. '(?:'.
  730. '(?:'.
  731. '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
  732. ')|(?:'.
  733. '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
  734. ')'.
  735. ')'.
  736. ')'.
  737. '|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'. //IPv4
  738. '|(?:'. //IPv6
  739. '\[?(?:(?:(?:[0-9A-Fa-f]{1,4}:){7}(?:(?:[0-9A-Fa-f]{1,4})|:))|(?:(?:[0-9A-Fa-f]{1,4}:){6}(?::|(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})|(?::[0-9A-Fa-f]{1,4})))|(?:(?:[0-9A-Fa-f]{1,4}:){5}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:){4}(?::[0-9A-Fa-f]{1,4}){0,1}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:){3}(?::[0-9A-Fa-f]{1,4}){0,2}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:){2}(?::[0-9A-Fa-f]{1,4}){0,3}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:)(?::[0-9A-Fa-f]{1,4}){0,4}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?::(?::[0-9A-Fa-f]{1,4}){0,5}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})))\]?(?<!:)'.
  740. ')|(?:'. //DNS
  741. '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
  742. '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
  743. //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
  744. '(?:AC|AD|AE|AERO|AF|AG|AI|AL|AM|AN|AO|AQ|AR|ARPA|AS|ASIA|AT|AU|AW|AX|AZ|BA|BB|BD|BE|BF|BG|BH|BI|BIZ|BJ|BM|BN|BO|BR|BS|BT|BV|BW|BY|BZ|CA|CAT|CC|CD|CF|CG|CH|CI|CK|CL|CM|CN|CO|COM|COOP|CR|CU|CV|CX|CY|CZ|DE|DJ|DK|DM|DO|DZ|EC|EDU|EE|EG|ER|ES|ET|EU|FI|FJ|FK|FM|FO|FR|GA|GB|GD|GE|GF|GG|GH|GI|GL|GM|GN|GOV|GP|GQ|GR|GS|GT|GU|GW|GY|HK|HM|HN|HR|HT|HU|ID|IE|IL|IM|IN|INFO|INT|IO|IQ|IR|IS|IT|JE|JM|JO|JOBS|JP|KE|KG|KH|KI|KM|KN|KP|KR|KW|KY|KZ|LA|LB|LC|LI|LK|LR|LS|LT|LU|LV|LY|MA|MC|MD|ME|MG|MH|MIL|MK|ML|MM|MN|MO|MOBI|MP|MQ|MR|MS|MT|MU|MUSEUM|MV|MW|MX|MY|MZ|NA|NAME|NC|NE|NET|NF|NG|NI|NL|NO|NP|NR|NU|NZ|OM|ORG|PA|PE|PF|PG|PH|PK|PL|PM|PN|PR|PRO|PS|PT|PW|PY|QA|RE|RO|RS|RU|RW|SA|SB|SC|SD|SE|SG|SH|SI|SJ|SK|SL|SM|SN|SO|SR|ST|SU|SV|SY|SZ|TC|TD|TEL|TF|TG|TH|TJ|TK|TL|TM|TN|TO|TP|TR|TRAVEL|TT|TV|TW|TZ|UA|UG|UK|US|UY|UZ|VA|VC|VE|VG|VI|VN|VU|WF|WS|XN--0ZWM56D|测试|XN--11B5BS3A9AJ6G|परीक्षा|XN--80AKHBYKNJ4F|испытание|XN--9T4B11YI5A|테스트|XN--DEBA0AD|טעסט|XN--G6W251D|測試|XN--HGBK6AJ7F53BBA|آزمایشی|XN--HLCJ6AYA9ESC7A|பரிட்சை|XN--JXALPDLP|δοκιμή|XN--KGBECHTV|إختبار|XN--ZCKZAH|テスト|YE|YT|YU|ZA|ZM|ZONE|ZW|local|loc|onion)'.
  745. ')(?![\pN\pL\-\_])'.
  746. ')'.
  747. '(?:'.
  748. '(?:\:\d+)?'. //:port
  749. '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
  750. '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
  751. '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
  752. ')(?<![\?\.\,\#\,])'.
  753. ')'.
  754. '#ixu';
  755. //preg_match_all($regex,$text,$matches);
  756. //print_r($matches);
  757. return preg_replace_callback($regex, curry('callback_helper',$callback,$arg) ,$text);
  758. }
  759. /**
  760. * Intermediate callback for common_replace_links(), helps resolve some
  761. * ambiguous link forms before passing on to the final callback.
  762. *
  763. * @param array $matches
  764. * @param callable $callback
  765. * @param mixed $arg optional argument to pass on as second param to callback
  766. * @return string
  767. *
  768. * @access private
  769. */
  770. function callback_helper($matches, $callback, $arg=null) {
  771. $url=$matches[1];
  772. $left = strpos($matches[0],$url);
  773. $right = $left+strlen($url);
  774. $groupSymbolSets=array(
  775. array(
  776. 'left'=>'(',
  777. 'right'=>')'
  778. ),
  779. array(
  780. 'left'=>'[',
  781. 'right'=>']'
  782. ),
  783. array(
  784. 'left'=>'{',
  785. 'right'=>'}'
  786. ),
  787. array(
  788. 'left'=>'<',
  789. 'right'=>'>'
  790. )
  791. );
  792. $cannotEndWith=array('.','?',',','#');
  793. $original_url=$url;
  794. do{
  795. $original_url=$url;
  796. foreach($groupSymbolSets as $groupSymbolSet){
  797. if(substr($url,-1)==$groupSymbolSet['right']){
  798. $group_left_count = substr_count($url,$groupSymbolSet['left']);
  799. $group_right_count = substr_count($url,$groupSymbolSet['right']);
  800. if($group_left_count<$group_right_count){
  801. $right-=1;
  802. $url=substr($url,0,-1);
  803. }
  804. }
  805. }
  806. if(in_array(substr($url,-1),$cannotEndWith)){
  807. $right-=1;
  808. $url=substr($url,0,-1);
  809. }
  810. }while($original_url!=$url);
  811. $result = call_user_func_array($callback, array($url, $arg));
  812. return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
  813. }
  814. require_once INSTALLDIR . "/lib/curry.php";
  815. function common_linkify($url) {
  816. // It comes in special'd, so we unspecial it before passing to the stringifying
  817. // functions
  818. $url = htmlspecialchars_decode($url);
  819. if (strpos($url, '@') !== false && strpos($url, ':') === false && Validate::email($url)) {
  820. //url is an email address without the mailto: protocol
  821. $canon = "mailto:$url";
  822. $longurl = "mailto:$url";
  823. } else {
  824. $canon = File_redirection::_canonUrl($url);
  825. $longurl_data = File_redirection::where($canon, common_config('attachments', 'process_links'));
  826. if (is_array($longurl_data)) {
  827. $longurl = $longurl_data['url'];
  828. } elseif (is_string($longurl_data)) {
  829. $longurl = $longurl_data;
  830. } else {
  831. // Unable to reach the server to verify contents, etc
  832. // Just pass the link on through for now.
  833. common_log(LOG_ERR, "Can't linkify url '$url'");
  834. $longurl = $url;
  835. }
  836. }
  837. $attrs = array('href' => $canon, 'title' => $longurl);
  838. $is_attachment = false;
  839. $attachment_id = null;
  840. $has_thumb = false;
  841. // Check to see whether this is a known "attachment" URL.
  842. $f = File::getKV('url', $longurl);
  843. if (!$f instanceof File) {
  844. if (common_config('attachments', 'process_links')) {
  845. // XXX: this writes to the database. :<
  846. try {
  847. $f = File::processNew($longurl);
  848. } catch (ServerException $e) {
  849. $f = null;
  850. }
  851. }
  852. }
  853. if ($f instanceof File) {
  854. try {
  855. $enclosure = $f->getEnclosure();
  856. $is_attachment = true;
  857. $attachment_id = $f->id;
  858. $thumb = File_thumbnail::getKV('file_id', $f->id);
  859. $has_thumb = ($thumb instanceof File_thumbnail);
  860. } catch (ServerException $e) {
  861. // There was not enough metadata available
  862. }
  863. }
  864. // Add clippy
  865. if ($is_attachment) {
  866. $attrs['class'] = 'attachment';
  867. if ($has_thumb) {
  868. $attrs['class'] = 'attachment thumbnail';
  869. }
  870. $attrs['id'] = "attachment-{$attachment_id}";
  871. }
  872. // Whether to nofollow
  873. $nf = common_config('nofollow', 'external');
  874. if ($nf == 'never') {
  875. $attrs['rel'] = 'external';
  876. } else {
  877. $attrs['rel'] = 'nofollow external';
  878. }
  879. return XMLStringer::estring('a', $attrs, $url);
  880. }
  881. /**
  882. * Find and shorten links in a given chunk of text if it's longer than the
  883. * configured notice content limit (or unconditionally).
  884. *
  885. * Side effects: may save file and file_redirection records for referenced URLs.
  886. *
  887. * Pass the $user option or call $user->shortenLinks($text) to ensure the proper
  888. * user's options are used; otherwise the current web session user's setitngs
  889. * will be used or ur1.ca if there is no active web login.
  890. *
  891. * @param string $text
  892. * @param boolean $always (optional)
  893. * @param User $user (optional)
  894. *
  895. * @return string
  896. */
  897. function common_shorten_links($text, $always = false, User $user=null)
  898. {
  899. if ($user === null) {
  900. $user = common_current_user();
  901. }
  902. $maxLength = User_urlshortener_prefs::maxNoticeLength($user);
  903. if ($always || ($maxLength != -1 && mb_strlen($text) > $maxLength)) {
  904. return common_replace_urls_callback($text, array('File_redirection', 'forceShort'), $user);
  905. } else {
  906. return common_replace_urls_callback($text, array('File_redirection', 'makeShort'), $user);
  907. }
  908. }
  909. /**
  910. * Very basic stripping of invalid UTF-8 input text.
  911. *
  912. * @param string $str
  913. * @return mixed string or null if invalid input
  914. *
  915. * @todo ideally we should drop bad chars, and maybe do some of the checks
  916. * from common_xml_safe_str. But we can't strip newlines, etc.
  917. * @todo Unicode normalization might also be useful, but not needed now.
  918. */
  919. function common_validate_utf8($str)
  920. {
  921. // preg_replace will return NULL on invalid UTF-8 input.
  922. //
  923. // Note: empty regex //u also caused NULL return on some
  924. // production machines, but none of our test machines.
  925. //
  926. // This should be replaced with a more reliable check.
  927. return preg_replace('/\x00/u', '', $str);
  928. }
  929. /**
  930. * Make sure an arbitrary string is safe for output in XML as a single line.
  931. *
  932. * @param string $str
  933. * @return string
  934. */
  935. function common_xml_safe_str($str)
  936. {
  937. // Replace common eol and extra whitespace input chars
  938. $unWelcome = array(
  939. "\t", // tab
  940. "\n", // newline
  941. "\r", // cr
  942. "\0", // null byte eos
  943. "\x0B" // vertical tab
  944. );
  945. $replacement = array(
  946. ' ', // single space
  947. ' ',
  948. '', // nothing
  949. '',
  950. ' '
  951. );
  952. $str = str_replace($unWelcome, $replacement, $str);
  953. // Neutralize any additional control codes and UTF-16 surrogates
  954. // (Twitter uses '*')
  955. return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
  956. }
  957. function common_tag_link($tag)
  958. {
  959. $canonical = common_canonical_tag($tag);
  960. if (common_config('singleuser', 'enabled')) {
  961. // regular TagAction isn't set up in 1user mode
  962. $nickname = User::singleUserNickname();
  963. $url = common_local_url('showstream',
  964. array('nickname' => $nickname,
  965. 'tag' => $canonical));
  966. } else {
  967. $url = common_local_url('tag', array('tag' => $canonical));
  968. }
  969. $xs = new XMLStringer();
  970. $xs->elementStart('span', 'tag');
  971. $xs->element('a', array('href' => $url,
  972. 'rel' => 'tag'),
  973. $tag);
  974. $xs->elementEnd('span');
  975. return $xs->getString();
  976. }
  977. function common_canonical_tag($tag)
  978. {
  979. // only alphanum
  980. $tag = preg_replace('/[^\pL\pN]/u', '', $tag);
  981. $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
  982. $tag = substr($tag, 0, 64);
  983. return $tag;
  984. }
  985. function common_valid_profile_tag($str)
  986. {
  987. return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
  988. }
  989. /**
  990. * Resolve an ambiguous profile nickname reference, checking in following order:
  991. * - profiles that $sender subscribes to
  992. * - profiles that subscribe to $sender
  993. * - local user profiles
  994. *
  995. * WARNING: does not validate or normalize $nickname -- MUST BE PRE-VALIDATED
  996. * OR THERE MAY BE A RISK OF SQL INJECTION ATTACKS. THIS FUNCTION DOES NOT
  997. * ESCAPE SQL.
  998. *
  999. * @fixme validate input
  1000. * @fixme escape SQL
  1001. * @fixme fix or remove mystery third parameter
  1002. * @fixme is $sender a User or Profile?
  1003. *
  1004. * @param <type> $sender the user or profile in whose context we're looking
  1005. * @param string $nickname validated nickname of
  1006. * @param <type> $dt unused mystery parameter; in Notice reply-to handling a timestamp is passed.
  1007. *
  1008. * @return Profile or null
  1009. */
  1010. function common_relative_profile($sender, $nickname, $dt=null)
  1011. {
  1012. // Will throw exception on invalid input.
  1013. $nickname = Nickname::normalize($nickname);
  1014. // Try to find profiles this profile is subscribed to that have this nickname
  1015. $recipient = new Profile();
  1016. // XXX: use a join instead of a subquery
  1017. $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.intval($sender->id).' and subscribed = id)', 'AND');
  1018. $recipient->whereAdd("nickname = '" . $recipient->escape($nickname) . "'", 'AND');
  1019. if ($recipient->find(true)) {
  1020. // XXX: should probably differentiate between profiles with
  1021. // the same name by date of most recent update
  1022. return $recipient;
  1023. }
  1024. // Try to find profiles that listen to this profile and that have this nickname
  1025. $recipient = new Profile();
  1026. // XXX: use a join instead of a subquery
  1027. $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.intval($sender->id).' and subscriber = id)', 'AND');
  1028. $recipient->whereAdd("nickname = '" . $recipient->escape($nickname) . "'", 'AND');
  1029. if ($recipient->find(true)) {
  1030. // XXX: should probably differentiate between profiles with
  1031. // the same name by date of most recent update
  1032. return $recipient;
  1033. }
  1034. // If this is a local user, try to find a local user with that nickname.
  1035. $sender = User::getKV('id', $sender->id);
  1036. if ($sender instanceof User) {
  1037. $recipient_user = User::getKV('nickname', $nickname);
  1038. if ($recipient_user instanceof User) {
  1039. return $recipient_user->getProfile();
  1040. }
  1041. }
  1042. // Otherwise, no links. @messages from local users to remote users,
  1043. // or from remote users to other remote users, are just
  1044. // outside our ability to make intelligent guesses about
  1045. return null;
  1046. }
  1047. function common_local_url($action, $args=null, $params=null, $fragment=null, $addSession=true)
  1048. {
  1049. if (Event::handle('StartLocalURL', array(&$action, &$params, &$fragment, &$addSession, &$url))) {
  1050. $r = Router::get();
  1051. $path = $r->build($action, $args, $params, $fragment);
  1052. $ssl = common_config('site', 'ssl') === 'always'
  1053. || StatusNet::isHTTPS()
  1054. || common_is_sensitive($action);
  1055. if (common_config('site','fancy')) {
  1056. $url = common_path($path, $ssl, $addSession);
  1057. } else {
  1058. if (mb_strpos($path, '/index.php') === 0) {
  1059. $url = common_path($path, $ssl, $addSession);
  1060. } else {
  1061. $url = common_path('index.php/'.$path, $ssl, $addSession);
  1062. }
  1063. }
  1064. Event::handle('EndLocalURL', array(&$action, &$params, &$fragment, &$addSession, &$url));
  1065. }
  1066. return $url;
  1067. }
  1068. function common_is_sensitive($action)
  1069. {
  1070. static $sensitive = array(
  1071. 'login',
  1072. 'register',
  1073. 'passwordsettings',
  1074. 'api',
  1075. 'ApiOAuthRequestToken',
  1076. 'ApiOAuthAccessToken',
  1077. 'ApiOAuthAuthorize',
  1078. 'ApiOAuthPin',
  1079. 'showapplication'
  1080. );
  1081. $ssl = null;
  1082. if (Event::handle('SensitiveAction', array($action, &$ssl))) {
  1083. $ssl = in_array($action, $sensitive);
  1084. }
  1085. return $ssl;
  1086. }
  1087. function common_path($relative, $ssl=false, $addSession=true)
  1088. {
  1089. $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
  1090. if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
  1091. || StatusNet::isHTTPS()
  1092. || common_config('site', 'ssl') === 'always') {
  1093. $proto = 'https';
  1094. if (is_string(common_config('site', 'sslserver')) &&
  1095. mb_strlen(common_config('site', 'sslserver')) > 0) {
  1096. $serverpart = common_config('site', 'sslserver');
  1097. } else if (common_config('site', 'server')) {
  1098. $serverpart = common_config('site', 'server');
  1099. } else {
  1100. common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
  1101. }
  1102. } else {
  1103. $proto = 'http';
  1104. if (common_config('site', 'server')) {
  1105. $serverpart = common_config('site', 'server');
  1106. } else {
  1107. common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
  1108. }
  1109. }
  1110. if ($addSession) {
  1111. $relative = common_inject_session($relative, $serverpart);
  1112. }
  1113. return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
  1114. }
  1115. function common_inject_session($url, $serverpart = null)
  1116. {
  1117. if (!common_have_session()) {
  1118. return $url;
  1119. }
  1120. if (empty($serverpart)) {
  1121. $serverpart = parse_url($url, PHP_URL_HOST);
  1122. }
  1123. $currentServer = (array_key_exists('HTTP_HOST', $_SERVER)) ? $_SERVER['HTTP_HOST'] : null;
  1124. // Are we pointing to another server (like an SSL server?)
  1125. if (!empty($currentServer) && 0 != strcasecmp($currentServer, $serverpart)) {
  1126. // Pass the session ID as a GET parameter
  1127. $sesspart = session_name() . '=' . session_id();
  1128. $i = strpos($url, '?');
  1129. if ($i === false) { // no GET params, just append
  1130. $url .= '?' . $sesspart;
  1131. } else {
  1132. $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
  1133. }
  1134. }
  1135. return $url;
  1136. }
  1137. function common_date_string($dt)
  1138. {
  1139. // XXX: do some sexy date formatting
  1140. // return date(DATE_RFC822, $dt);
  1141. $t = strtotime($dt);
  1142. $now = time();
  1143. $diff = $now - $t;
  1144. if ($now < $t) { // that shouldn't happen!
  1145. return common_exact_date($dt);
  1146. } else if ($diff < 60) {
  1147. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1148. return _('a few seconds ago');
  1149. } else if ($diff < 92) {
  1150. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1151. return _('about a minute ago');
  1152. } else if ($diff < 3300) {
  1153. $minutes = round($diff/60);
  1154. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1155. return sprintf( _m('about one minute ago', 'about %d minutes ago', $minutes), $minutes);
  1156. } else if ($diff < 5400) {
  1157. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1158. return _('about an hour ago');
  1159. } else if ($diff < 22 * 3600) {
  1160. $hours = round($diff/3600);
  1161. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1162. return sprintf( _m('about one hour ago', 'about %d hours ago', $hours), $hours);
  1163. } else if ($diff < 37 * 3600) {
  1164. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1165. return _('about a day ago');
  1166. } else if ($diff < 24 * 24 * 3600) {
  1167. $days = round($diff/(24*3600));
  1168. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1169. return sprintf( _m('about one day ago', 'about %d days ago', $days), $days);
  1170. } else if ($diff < 46 * 24 * 3600) {
  1171. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1172. return _('about a month ago');
  1173. } else if ($diff < 330 * 24 * 3600) {
  1174. $months = round($diff/(30*24*3600));
  1175. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1176. return sprintf( _m('about one month ago', 'about %d months ago',$months), $months);
  1177. } else if ($diff < 480 * 24 * 3600) {
  1178. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1179. return _('about a year ago');
  1180. } else {
  1181. return common_exact_date($dt);
  1182. }
  1183. }
  1184. function common_exact_date($dt)
  1185. {
  1186. static $_utc;
  1187. static $_siteTz;
  1188. if (!$_utc) {
  1189. $_utc = new DateTimeZone('UTC');
  1190. $_siteTz = new DateTimeZone(common_timezone());
  1191. }
  1192. $dateStr = date('d F Y H:i:s', strtotime($dt));
  1193. $d = new DateTime($dateStr, $_utc);
  1194. $d->setTimezone($_siteTz);
  1195. // TRANS: Human-readable full date-time specification (formatting on http://php.net/date)
  1196. return $d->format(_('l, d-M-Y H:i:s T'));
  1197. }
  1198. function common_date_w3dtf($dt)
  1199. {
  1200. $dateStr = date('d F Y H:i:s', strtotime($dt));
  1201. $d = new DateTime($dateStr, new DateTimeZone('UTC'));
  1202. $d->setTimezone(new DateTimeZone(common_timezone()));
  1203. return $d->format(DATE_W3C);
  1204. }
  1205. function common_date_rfc2822($dt)
  1206. {
  1207. $dateStr = date('d F Y H:i:s', strtotime($dt));
  1208. $d = new DateTime($dateStr, new DateTimeZone('UTC'));
  1209. $d->setTimezone(new DateTimeZone(common_timezone()));
  1210. return $d->format('r');
  1211. }
  1212. function common_date_iso8601($dt)
  1213. {
  1214. $dateStr = date('d F Y H:i:s', strtotime($dt));
  1215. $d = new DateTime($dateStr, new DateTimeZone('UTC'));
  1216. $d->setTimezone(new DateTimeZone(common_timezone()));
  1217. return $d->format('c');
  1218. }
  1219. function common_sql_now()
  1220. {
  1221. return common_sql_date(time());
  1222. }
  1223. function common_sql_date($datetime)
  1224. {
  1225. return strftime('%Y-%m-%d %H:%M:%S', $datetime);
  1226. }
  1227. /**
  1228. * Return an SQL fragment to calculate an age-based weight from a given
  1229. * timestamp or datetime column.
  1230. *
  1231. * @param string $column name of field we're comparing against current time
  1232. * @param integer $dropoff divisor for age in seconds before exponentiation
  1233. * @return string SQL fragment
  1234. */
  1235. function common_sql_weight($column, $dropoff)
  1236. {
  1237. if (common_config('db', 'type') == 'pgsql') {
  1238. // PostgreSQL doesn't support timestampdiff function.
  1239. // @fixme will this use the right time zone?
  1240. // @fixme does this handle cross-year subtraction correctly?
  1241. return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
  1242. } else {
  1243. return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
  1244. }
  1245. }
  1246. function common_redirect($url, $code=307)
  1247. {
  1248. static $status = array(301 => "Moved Permanently",
  1249. 302 => "Found",
  1250. 303 => "See Other",
  1251. 307 => "Temporary Redirect");
  1252. header('HTTP/1.1 '.$code.' '.$status[$code]);
  1253. header("Location: $url");
  1254. header("Connection: close");
  1255. $xo = new XMLOutputter();
  1256. $xo->startXML('a',
  1257. '-//W3C//DTD XHTML 1.0 Strict//EN',
  1258. 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
  1259. $xo->element('a', array('href' => $url), $url);
  1260. $xo->endXML();
  1261. exit;
  1262. }
  1263. // Stick the notice on the queue
  1264. function common_enqueue_notice($notice)
  1265. {
  1266. static $localTransports = array('ping');
  1267. $transports = array();
  1268. if (common_config('sms', 'enabled')) {
  1269. $transports[] = 'sms';
  1270. }
  1271. if (Event::hasHandler('HandleQueuedNotice')) {
  1272. $transports[] = 'plugin';
  1273. }
  1274. // We can skip these for gatewayed notices.
  1275. if ($notice->isLocal()) {
  1276. $transports = array_merge($transports, $localTransports);
  1277. }
  1278. if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
  1279. $qm = QueueManager::get();
  1280. foreach ($transports as $transport)
  1281. {
  1282. $qm->enqueue($notice, $transport);
  1283. }
  1284. Event::handle('EndEnqueueNotice', array($notice, $transports));
  1285. }
  1286. return true;
  1287. }
  1288. function common_profile_url($nickname)
  1289. {
  1290. return common_local_url('showstream', array('nickname' => $nickname),
  1291. null, null, false);
  1292. }
  1293. /**
  1294. * Should make up a reasonable root URL
  1295. */
  1296. function common_root_url($ssl=false)
  1297. {
  1298. $url = common_path('', $ssl, false);
  1299. $i = strpos($url, '?');
  1300. if ($i !== false) {
  1301. $url = substr($url, 0, $i);
  1302. }
  1303. return $url;
  1304. }
  1305. /**
  1306. * returns $bytes bytes of random data as a hexadecimal string
  1307. */
  1308. function common_random_hexstr($bytes)
  1309. {
  1310. $str = @file_exists('/dev/urandom')
  1311. ? common_urandom($bytes)
  1312. : common_mtrand($bytes);
  1313. $hexstr = '';
  1314. for ($i = 0; $i < $bytes; $i++) {
  1315. $hexstr .= sprintf("%02x", ord($str[$i]));
  1316. }
  1317. return $hexstr;
  1318. }
  1319. function common_urandom($bytes)
  1320. {
  1321. $h = fopen('/dev/urandom', 'rb');
  1322. // should not block
  1323. $src = fread($h, $bytes);
  1324. fclose($h);
  1325. return $src;
  1326. }
  1327. function common_mtrand($bytes)
  1328. {
  1329. $str = '';
  1330. for ($i = 0; $i < $bytes; $i++) {
  1331. $str .= chr(mt_rand(0, 255));
  1332. }
  1333. return $str;
  1334. }
  1335. /**
  1336. * Record the given URL as the return destination for a future
  1337. * form submission, to be read by common_get_returnto().
  1338. *
  1339. * @param string $url
  1340. *
  1341. * @fixme as a session-global setting, this can allow multiple forms
  1342. * to conflict and overwrite each others' returnto destinations if
  1343. * the user has multiple tabs or windows open.
  1344. *
  1345. * Should refactor to index with a token or otherwise only pass the
  1346. * data along its intended path.
  1347. */
  1348. function common_set_returnto($url)
  1349. {
  1350. common_ensure_session();
  1351. $_SESSION['returnto'] = $url;
  1352. }
  1353. /**
  1354. * Fetch a return-destination URL previously recorded by
  1355. * common_set_returnto().
  1356. *
  1357. * @return mixed URL string or null
  1358. *
  1359. * @fixme as a session-global setting, this can allow multiple forms
  1360. * to conflict and overwrite each others' returnto destinations if
  1361. * the user has multiple tabs or windows open.
  1362. *
  1363. * Should refactor to index with a token or otherwise only pass the
  1364. * data along its intended path.
  1365. */
  1366. function common_get_returnto()
  1367. {
  1368. common_ensure_session();
  1369. return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
  1370. }
  1371. function common_timestamp()
  1372. {
  1373. return date('YmdHis');
  1374. }
  1375. function common_ensure_syslog()
  1376. {
  1377. static $initialized = false;
  1378. if (!$initialized) {
  1379. openlog(common_config('syslog', 'appname'), 0,
  1380. common_config('syslog', 'facility'));
  1381. $initialized = true;
  1382. }
  1383. }
  1384. function common_log_line($priority, $msg)
  1385. {
  1386. static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
  1387. 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
  1388. return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . PHP_EOL;
  1389. }
  1390. function common_request_id()
  1391. {
  1392. $pid = getmypid();
  1393. $server = common_config('site', 'server');
  1394. if (php_sapi_name() == 'cli') {
  1395. $script = basename($_SERVER['PHP_SELF']);
  1396. return "$server:$script:$pid";
  1397. } else {
  1398. static $req_id = null;
  1399. if (!isset($req_id)) {
  1400. $req_id = substr(md5(mt_rand()), 0, 8);
  1401. }
  1402. if (isset($_SERVER['REQUEST_URI'])) {
  1403. $url = $_SERVER['REQUEST_URI'];
  1404. }
  1405. $method = $_SERVER['REQUEST_METHOD'];
  1406. return "$server:$pid.$req_id $method $url";
  1407. }
  1408. }
  1409. function common_log($priority, $msg, $filename=null)
  1410. {
  1411. if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
  1412. $msg = (empty($filename)) ? $msg : basename($filename) . ' - ' . $msg;
  1413. $msg = '[' . common_request_id() . '] ' . $msg;
  1414. $logfile = common_config('site', 'logfile');
  1415. if ($logfile) {
  1416. $log = fopen($logfile, "a");
  1417. if ($log) {
  1418. $output = common_log_line($priority, $msg);
  1419. fwrite($log, $output);
  1420. fclose($log);
  1421. }
  1422. } else {
  1423. common_ensure_syslog();
  1424. syslog($priority, $msg);
  1425. }
  1426. Event::handle('EndLog', array($priority, $msg, $filename));
  1427. }
  1428. }
  1429. function common_debug($msg, $filename=null)
  1430. {
  1431. if ($filename) {
  1432. common_log(LOG_DEBUG, basename($filename).' - '.$msg);
  1433. } else {
  1434. common_log(LOG_DEBUG, $msg);
  1435. }
  1436. }
  1437. function common_log_db_error(&$object, $verb, $filename=null)
  1438. {
  1439. global $_PEAR;
  1440. $objstr = common_log_objstring($object);
  1441. $last_error = &$_PEAR->getStaticProperty('DB_DataObject','lastError');
  1442. if (is_object($last_error)) {
  1443. $msg = $last_error->message;
  1444. } else {
  1445. $msg = 'Unknown error (' . var_export($last_error, true) . ')';
  1446. }
  1447. common_log(LOG_ERR, $msg . '(' . $verb . ' on ' . $objstr . ')', $filename);
  1448. }
  1449. function common_log_objstring(&$object)
  1450. {
  1451. if (is_null($object)) {
  1452. return "null";
  1453. }
  1454. if (!($object instanceof DB_DataObject)) {
  1455. return "(unknown)";
  1456. }
  1457. $arr = $object->toArray();
  1458. $fields = array();
  1459. foreach ($arr as $k => $v) {
  1460. if (is_object($v)) {
  1461. $fields[] = "$k='".get_class($v)."'";
  1462. } else {
  1463. $fields[] = "$k='$v'";
  1464. }
  1465. }
  1466. $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
  1467. return $objstring;
  1468. }
  1469. function common_valid_http_url($url, $secure=false)
  1470. {
  1471. // If $secure is true, only allow https URLs to pass
  1472. // (if false, we use '?' in 'https?' to say the 's' is optional)
  1473. $regex = $secure ? '/^https$/' : '/^https?$/';
  1474. return filter_var($url, FILTER_VALIDATE_URL)
  1475. && preg_match($regex, parse_url($url, PHP_URL_SCHEME));
  1476. }
  1477. function common_valid_tag($tag)
  1478. {
  1479. if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
  1480. return (Validate::email($matches[1]) ||
  1481. preg_match('/^([\w-\.]+)$/', $matches[1]));
  1482. }
  1483. return false;
  1484. }
  1485. /**
  1486. * Determine if given domain or address literal is valid
  1487. * eg for use in JIDs and URLs. Does not check if the domain
  1488. * exists!
  1489. *
  1490. * @param string $domain
  1491. * @return boolean valid or not
  1492. */
  1493. function common_valid_domain($domain)
  1494. {
  1495. $octet = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])";
  1496. $ipv4 = "(?:$octet(?:\.$octet){3})";
  1497. if (preg_match("/^$ipv4$/u", $domain)) return true;
  1498. $group = "(?:[0-9a-f]{1,4})";
  1499. $ipv6 = "(?:\[($group(?::$group){0,7})?(::)?($group(?::$group){0,7})?\])"; // http://tools.ietf.org/html/rfc3513#section-2.2
  1500. if (preg_match("/^$ipv6$/ui", $domain, $matches)) {
  1501. $before = explode(":", $matches[1]);
  1502. $zeroes = $matches[2];
  1503. $after = explode(":", $matches[3]);
  1504. if ($zeroes) {
  1505. $min = 0;
  1506. $max = 7;
  1507. } else {
  1508. $min = 1;
  1509. $max = 8;
  1510. }
  1511. $explicit = count($before) + count($after);
  1512. if ($explicit < $min || $explicit > $max) {
  1513. return false;
  1514. }
  1515. return true;
  1516. }
  1517. try {
  1518. require_once "Net/IDNA.php";
  1519. $idn = Net_IDNA::getInstance();
  1520. $domain = $idn->encode($domain);
  1521. } catch (Exception $e) {
  1522. return false;
  1523. }
  1524. $subdomain = "(?:[a-z0-9][a-z0-9-]*)"; // @fixme
  1525. $fqdn = "(?:$subdomain(?:\.$subdomain)*\.?)";
  1526. return preg_match("/^$fqdn$/ui", $domain);
  1527. }
  1528. /* Following functions are copied from MediaWiki GlobalFunctions.php
  1529. * and written by Evan Prodromou. */
  1530. function common_accept_to_prefs($accept, $def = '*/*')
  1531. {
  1532. // No arg means accept anything (per HTTP spec)
  1533. if(!$accept) {
  1534. return array($def => 1);
  1535. }
  1536. $prefs = array();
  1537. $parts = explode(',', $accept);
  1538. foreach($parts as $part) {
  1539. // FIXME: doesn't deal with params like 'text/html; level=1'
  1540. @list($value, $qpart) = explode(';', trim($part));
  1541. $match = array();
  1542. if(!isset($qpart)) {
  1543. $prefs[$value] = 1;
  1544. } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
  1545. $prefs[$value] = $match[1];
  1546. }
  1547. }
  1548. return $prefs;
  1549. }
  1550. // Match by our supported file extensions
  1551. function common_supported_ext_to_mime($fileext)
  1552. {
  1553. // Accept a filename and take out the extension
  1554. if (strpos($fileext, '.') !== false) {
  1555. $fileext = substr(strrchr($fileext, '.'), 1);
  1556. }
  1557. $supported = common_config('attachments', 'supported');
  1558. foreach($supported as $type => $ext) {
  1559. if ($ext === $fileext) {
  1560. return $type;
  1561. }
  1562. }
  1563. throw new ServerException('Unsupported file extension');
  1564. }
  1565. // Match by our supported mime types
  1566. function common_supported_mime_to_ext($mimetype)
  1567. {
  1568. $supported = common_config('attachments', 'supported');
  1569. foreach($supported as $type => $ext) {
  1570. if ($mimetype === $type) {
  1571. return $ext;
  1572. }
  1573. }
  1574. throw new ServerException('Unsupported MIME type');
  1575. }
  1576. // The MIME "media" is the part before the slash (video in video/webm)
  1577. function common_get_mime_media($type)
  1578. {
  1579. $tmp = explode('/', $type);
  1580. return strtolower($tmp[0]);
  1581. }
  1582. function common_bare_mime($mimetype)
  1583. {
  1584. $mimetype = mb_strtolower($mimetype);
  1585. if ($semicolon = mb_strpos($mimetype, ';')) {
  1586. $mimetype = mb_substr($mimetype, 0, $semicolon);
  1587. }
  1588. return $mimetype;
  1589. }
  1590. function common_mime_type_match($type, $avail)
  1591. {
  1592. if(array_key_exists($type, $avail)) {
  1593. return $type;
  1594. } else {
  1595. $parts = explode('/', $type);
  1596. if(array_key_exists($parts[0] . '/*', $avail)) {
  1597. return $parts[0] . '/*';
  1598. } elseif(array_key_exists('*/*', $avail)) {
  1599. return '*/*';
  1600. } else {
  1601. return null;
  1602. }
  1603. }
  1604. }
  1605. function common_negotiate_type($cprefs, $sprefs)
  1606. {
  1607. $combine = array();
  1608. foreach(array_keys($sprefs) as $type) {
  1609. $parts = explode('/', $type);
  1610. if($parts[1] != '*') {
  1611. $ckey = common_mime_type_match($type, $cprefs);
  1612. if($ckey) {
  1613. $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
  1614. }
  1615. }
  1616. }
  1617. foreach(array_keys($cprefs) as $type) {
  1618. $parts = explode('/', $type);
  1619. if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
  1620. $skey = common_mime_type_match($type, $sprefs);
  1621. if($skey) {
  1622. $combine[$type] = $sprefs[$skey] * $cprefs[$type];
  1623. }
  1624. }
  1625. }
  1626. $bestq = 0;
  1627. $besttype = 'text/html';
  1628. foreach(array_keys($combine) as $type) {
  1629. if($combine[$type] > $bestq) {
  1630. $besttype = $type;
  1631. $bestq = $combine[$type];
  1632. }
  1633. }
  1634. if ('text/html' === $besttype) {
  1635. return "text/html; charset=utf-8";
  1636. }
  1637. return $besttype;
  1638. }
  1639. function common_config($main, $sub)
  1640. {
  1641. global $config;
  1642. return (array_key_exists($main, $config) &&
  1643. array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
  1644. }
  1645. function common_config_set($main, $sub, $value)
  1646. {
  1647. global $config;
  1648. if (!array_key_exists($main, $config)) {
  1649. $config[$main] = array();
  1650. }
  1651. $config[$main][$sub] = $value;
  1652. }
  1653. function common_config_append($main, $sub, $value)
  1654. {
  1655. global $config;
  1656. if (!array_key_exists($main, $config)) {
  1657. $config[$main] = array();
  1658. }
  1659. if (!array_key_exists($sub, $config[$main])) {
  1660. $config[$main][$sub] = array();
  1661. }
  1662. if (!is_array($config[$main][$sub])) {
  1663. $config[$main][$sub] = array($config[$main][$sub]);
  1664. }
  1665. array_push($config[$main][$sub], $value);
  1666. }
  1667. /**
  1668. * Pull arguments from a GET/POST/REQUEST array with first-level input checks:
  1669. * strips "magic quotes" slashes if necessary, and kills invalid UTF-8 strings.
  1670. *
  1671. * @param array $from
  1672. * @return array
  1673. */
  1674. function common_copy_args($from)
  1675. {
  1676. $to = array();
  1677. $strip = get_magic_quotes_gpc();
  1678. foreach ($from as $k => $v) {
  1679. if(is_array($v)) {
  1680. $to[$k] = common_copy_args($v);
  1681. } else {
  1682. if ($strip) {
  1683. $v = stripslashes($v);
  1684. }
  1685. $to[$k] = strval(common_validate_utf8($v));
  1686. }
  1687. }
  1688. return $to;
  1689. }
  1690. /**
  1691. * Neutralise the evil effects of magic_quotes_gpc in the current request.
  1692. * This is used before handing a request off to OAuthRequest::from_request.
  1693. * @fixme Doesn't consider vars other than _POST and _GET?
  1694. * @fixme Can't be undone and could corrupt data if run twice.
  1695. */
  1696. function common_remove_magic_from_request()
  1697. {
  1698. if(get_magic_quotes_gpc()) {
  1699. $_POST=array_map('stripslashes',$_POST);
  1700. $_GET=array_map('stripslashes',$_GET);
  1701. }
  1702. }
  1703. function common_user_uri(&$user)
  1704. {
  1705. return common_local_url('userbyid', array('id' => $user->id),
  1706. null, null, false);
  1707. }
  1708. // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
  1709. function common_confirmation_code($bits)
  1710. {
  1711. // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
  1712. static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
  1713. $chars = ceil($bits/5);
  1714. $code = '';
  1715. for ($i = 0; $i < $chars; $i++) {
  1716. // XXX: convert to string and back
  1717. $num = hexdec(common_random_hexstr(1));
  1718. // XXX: randomness is too precious to throw away almost
  1719. // 40% of the bits we get!
  1720. $code .= $codechars[$num%32];
  1721. }
  1722. return $code;
  1723. }
  1724. // convert markup to HTML
  1725. function common_markup_to_html($c, $args=null)
  1726. {
  1727. if ($c === null) {
  1728. return '';
  1729. }
  1730. if (is_null($args)) {
  1731. $args = array();
  1732. }
  1733. // XXX: not very efficient
  1734. foreach ($args as $name => $value) {
  1735. $c = preg_replace('/%%arg.'.$name.'%%/', $value, $c);
  1736. }
  1737. $c = preg_replace_callback('/%%user.(\w+)%%/', function ($m) { return common_user_property($m[1]); }, $c);
  1738. $c = preg_replace_callback('/%%action.(\w+)%%/', function ($m) { return common_local_url($m[1]); }, $c);
  1739. $c = preg_replace_callback('/%%doc.(\w+)%%/', function ($m) { return common_local_url('doc', array('title'=>$m[1])); }, $c);
  1740. $c = preg_replace_callback('/%%(\w+).(\w+)%%/', function ($m) { return common_config($m[1], $m[2]); }, $c);
  1741. return \Michelf\Markdown::defaultTransform($c);
  1742. }
  1743. function common_user_property($property)
  1744. {
  1745. $profile = Profile::current();
  1746. if (empty($profile)) {
  1747. return null;
  1748. }
  1749. switch ($property) {
  1750. case 'profileurl':
  1751. case 'nickname':
  1752. case 'fullname':
  1753. case 'location':
  1754. case 'bio':
  1755. return $profile->$property;
  1756. break;
  1757. case 'avatar':
  1758. try {
  1759. return $profile->getAvatar(AVATAR_STREAM_SIZE);
  1760. } catch (Exception $e) {
  1761. return null;
  1762. }
  1763. break;
  1764. case 'bestname':
  1765. return $profile->getBestName();
  1766. break;
  1767. default:
  1768. return null;
  1769. }
  1770. }
  1771. function common_profile_uri($profile)
  1772. {
  1773. $uri = null;
  1774. if (!empty($profile)) {
  1775. if (Event::handle('StartCommonProfileURI', array($profile, &$uri))) {
  1776. $user = User::getKV('id', $profile->id);
  1777. if ($user instanceof User) {
  1778. $uri = $user->getUri();
  1779. }
  1780. Event::handle('EndCommonProfileURI', array($profile, &$uri));
  1781. }
  1782. }
  1783. // XXX: this is a very bad profile!
  1784. return $uri;
  1785. }
  1786. function common_canonical_sms($sms)
  1787. {
  1788. // strip non-digits
  1789. preg_replace('/\D/', '', $sms);
  1790. return $sms;
  1791. }
  1792. function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
  1793. {
  1794. switch ($errno) {
  1795. case E_ERROR:
  1796. case E_COMPILE_ERROR:
  1797. case E_CORE_ERROR:
  1798. case E_USER_ERROR:
  1799. case E_PARSE:
  1800. case E_RECOVERABLE_ERROR:
  1801. common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
  1802. die();
  1803. break;
  1804. case E_WARNING:
  1805. case E_COMPILE_WARNING:
  1806. case E_CORE_WARNING:
  1807. case E_USER_WARNING:
  1808. common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
  1809. break;
  1810. case E_NOTICE:
  1811. case E_USER_NOTICE:
  1812. common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
  1813. break;
  1814. case E_STRICT:
  1815. case E_DEPRECATED:
  1816. case E_USER_DEPRECATED:
  1817. // XXX: config variable to log this stuff, too
  1818. break;
  1819. default:
  1820. common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
  1821. die();
  1822. break;
  1823. }
  1824. // FIXME: show error page if we're on the Web
  1825. /* Don't execute PHP internal error handler */
  1826. return true;
  1827. }
  1828. function common_session_token()
  1829. {
  1830. common_ensure_session();
  1831. if (!array_key_exists('token', $_SESSION)) {
  1832. $_SESSION['token'] = common_random_hexstr(64);
  1833. }
  1834. return $_SESSION['token'];
  1835. }
  1836. function common_license_terms($uri)
  1837. {
  1838. if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
  1839. return explode('-',$matches[1]);
  1840. }
  1841. return array($uri);
  1842. }
  1843. function common_compatible_license($from, $to)
  1844. {
  1845. $from_terms = common_license_terms($from);
  1846. // public domain and cc-by are compatible with everything
  1847. if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
  1848. return true;
  1849. }
  1850. $to_terms = common_license_terms($to);
  1851. // sa is compatible across versions. IANAL
  1852. if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
  1853. return count(array_diff($from_terms, $to_terms)) == 0;
  1854. }
  1855. // XXX: better compatibility check needed here!
  1856. // Should at least normalise URIs
  1857. return ($from == $to);
  1858. }
  1859. /**
  1860. * returns a quoted table name, if required according to config
  1861. */
  1862. function common_database_tablename($tablename)
  1863. {
  1864. if(common_config('db','quote_identifiers')) {
  1865. $tablename = '"'. $tablename .'"';
  1866. }
  1867. //table prefixes could be added here later
  1868. return $tablename;
  1869. }
  1870. /**
  1871. * Shorten a URL with the current user's configured shortening service,
  1872. * or ur1.ca if configured, or not at all if no shortening is set up.
  1873. *
  1874. * @param string $long_url original URL
  1875. * @param User $user to specify a particular user's options
  1876. * @param boolean $force Force shortening (used when notice is too long)
  1877. * @return string may return the original URL if shortening failed
  1878. *
  1879. * @fixme provide a way to specify a particular shortener
  1880. */
  1881. function common_shorten_url($long_url, User $user=null, $force = false)
  1882. {
  1883. $long_url = trim($long_url);
  1884. $user = common_current_user();
  1885. $maxUrlLength = User_urlshortener_prefs::maxUrlLength($user);
  1886. // $force forces shortening even if it's not strictly needed
  1887. // I doubt URL shortening is ever 'strictly' needed. - ESP
  1888. if (($maxUrlLength == -1 || mb_strlen($long_url) < $maxUrlLength) && !$force) {
  1889. return $long_url;
  1890. }
  1891. $shortenerName = User_urlshortener_prefs::urlShorteningService($user);
  1892. if (Event::handle('StartShortenUrl',
  1893. array($long_url, $shortenerName, &$shortenedUrl))) {
  1894. if ($shortenerName == 'internal') {
  1895. try {
  1896. $f = File::processNew($long_url);
  1897. $shortenedUrl = common_local_url('redirecturl', array('id' => $f->id));
  1898. if ((mb_strlen($shortenedUrl) < mb_strlen($long_url)) || $force) {
  1899. return $shortenedUrl;
  1900. } else {
  1901. return $long_url;
  1902. }
  1903. } catch (ServerException $e) {
  1904. return $long_url;
  1905. }
  1906. } else {
  1907. return $long_url;
  1908. }
  1909. } else {
  1910. //URL was shortened, so return the result
  1911. return trim($shortenedUrl);
  1912. }
  1913. }
  1914. /**
  1915. * @return mixed array($proxy, $ip) for web requests; proxy may be null
  1916. * null if not a web request
  1917. *
  1918. * @fixme X-Forwarded-For can be chained by multiple proxies;
  1919. we should parse the list and provide a cleaner array
  1920. * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
  1921. * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
  1922. * use function to get exact request headers from Apache if possible.
  1923. */
  1924. function common_client_ip()
  1925. {
  1926. if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
  1927. return null;
  1928. }
  1929. if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
  1930. if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
  1931. $proxy = $_SERVER['HTTP_CLIENT_IP'];
  1932. } else {
  1933. $proxy = $_SERVER['REMOTE_ADDR'];
  1934. }
  1935. $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  1936. } else {
  1937. $proxy = null;
  1938. if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
  1939. $ip = $_SERVER['HTTP_CLIENT_IP'];
  1940. } else {
  1941. $ip = $_SERVER['REMOTE_ADDR'];
  1942. }
  1943. }
  1944. return array($proxy, $ip);
  1945. }
  1946. function common_url_to_nickname($url)
  1947. {
  1948. static $bad = array('query', 'user', 'password', 'port', 'fragment');
  1949. $parts = parse_url($url);
  1950. // If any of these parts exist, this won't work
  1951. foreach ($bad as $badpart) {
  1952. if (array_key_exists($badpart, $parts)) {
  1953. return null;
  1954. }
  1955. }
  1956. // We just have host and/or path
  1957. // If it's just a host...
  1958. if (array_key_exists('host', $parts) &&
  1959. (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
  1960. {
  1961. $hostparts = explode('.', $parts['host']);
  1962. // Try to catch common idiom of nickname.service.tld
  1963. if ((count($hostparts) > 2) &&
  1964. (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
  1965. (strcmp($hostparts[0], 'www') != 0))
  1966. {
  1967. return common_nicknamize($hostparts[0]);
  1968. } else {
  1969. // Do the whole hostname
  1970. return common_nicknamize($parts['host']);
  1971. }
  1972. } else {
  1973. if (array_key_exists('path', $parts)) {
  1974. // Strip starting, ending slashes
  1975. $path = preg_replace('@/$@', '', $parts['path']);
  1976. $path = preg_replace('@^/@', '', $path);
  1977. $path = basename($path);
  1978. // Hack for MediaWiki user pages, in the form:
  1979. // http://example.com/wiki/User:Myname
  1980. // ('User' may be localized.)
  1981. if (strpos($path, ':')) {
  1982. $parts = array_filter(explode(':', $path));
  1983. $path = $parts[count($parts) - 1];
  1984. }
  1985. if ($path) {
  1986. return common_nicknamize($path);
  1987. }
  1988. }
  1989. }
  1990. return null;
  1991. }
  1992. function common_nicknamize($str)
  1993. {
  1994. try {
  1995. return Nickname::normalize($str);
  1996. } catch (NicknameException $e) {
  1997. return null;
  1998. }
  1999. }
  2000. function common_perf_counter($key, $val=null)
  2001. {
  2002. global $_perfCounters;
  2003. if (isset($_perfCounters)) {
  2004. if (common_config('site', 'logperf')) {
  2005. if (array_key_exists($key, $_perfCounters)) {
  2006. $_perfCounters[$key][] = $val;
  2007. } else {
  2008. $_perfCounters[$key] = array($val);
  2009. }
  2010. if (common_config('site', 'logperf_detail')) {
  2011. common_log(LOG_DEBUG, "PERF COUNTER HIT: $key $val");
  2012. }
  2013. }
  2014. }
  2015. }
  2016. function common_log_perf_counters()
  2017. {
  2018. if (common_config('site', 'logperf')) {
  2019. global $_startTime, $_perfCounters;
  2020. if (isset($_startTime)) {
  2021. $endTime = microtime(true);
  2022. $diff = round(($endTime - $_startTime) * 1000);
  2023. common_log(LOG_DEBUG, "PERF runtime: ${diff}ms");
  2024. }
  2025. $counters = $_perfCounters;
  2026. ksort($counters);
  2027. foreach ($counters as $key => $values) {
  2028. $count = count($values);
  2029. $unique = count(array_unique($values));
  2030. common_log(LOG_DEBUG, "PERF COUNTER: $key $count ($unique unique)");
  2031. }
  2032. }
  2033. }
  2034. function common_is_email($str)
  2035. {
  2036. return (strpos($str, '@') !== false);
  2037. }
  2038. function common_init_stats()
  2039. {
  2040. global $_mem, $_ts;
  2041. $_mem = memory_get_usage(true);
  2042. $_ts = microtime(true);
  2043. }
  2044. function common_log_delta($comment=null)
  2045. {
  2046. global $_mem, $_ts;
  2047. $mold = $_mem;
  2048. $told = $_ts;
  2049. $_mem = memory_get_usage(true);
  2050. $_ts = microtime(true);
  2051. $mtotal = $_mem - $mold;
  2052. $ttotal = $_ts - $told;
  2053. if (empty($comment)) {
  2054. $comment = 'Delta';
  2055. }
  2056. common_debug(sprintf("%s: %d %d", $comment, $mtotal, round($ttotal * 1000000)));
  2057. }
  2058. function common_strip_html($html, $trim=true, $save_whitespace=false)
  2059. {
  2060. if (!$save_whitespace) {
  2061. $html = preg_replace('/\s+/', ' ', $html);
  2062. }
  2063. $text = html_entity_decode(strip_tags($html), ENT_QUOTES, 'UTF-8');
  2064. return $trim ? trim($text) : $text;
  2065. }