util.php 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594
  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, 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->getProfile()), $user->password)) {
  221. //internal checking passed
  222. $authenticatedUser = $user;
  223. }
  224. }
  225. }
  226. Event::handle('EndCheckPassword', array($nickname, $password, $authenticatedUser));
  227. return $authenticatedUser;
  228. }
  229. /**
  230. * Is the current user logged in?
  231. */
  232. function common_logged_in()
  233. {
  234. return (!is_null(common_current_user()));
  235. }
  236. function common_local_referer()
  237. {
  238. return parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST) === common_config('site', 'server');
  239. }
  240. function common_have_session()
  241. {
  242. return (0 != strcmp(session_id(), ''));
  243. }
  244. function common_ensure_session()
  245. {
  246. $c = null;
  247. if (array_key_exists(session_name(), $_COOKIE)) {
  248. $c = $_COOKIE[session_name()];
  249. }
  250. if (!common_have_session()) {
  251. if (common_config('sessions', 'handle')) {
  252. Session::setSaveHandler();
  253. }
  254. if (array_key_exists(session_name(), $_GET)) {
  255. $id = $_GET[session_name()];
  256. } else if (array_key_exists(session_name(), $_COOKIE)) {
  257. $id = $_COOKIE[session_name()];
  258. }
  259. if (isset($id)) {
  260. session_id($id);
  261. }
  262. @session_start();
  263. if (!isset($_SESSION['started'])) {
  264. $_SESSION['started'] = time();
  265. if (!empty($id)) {
  266. common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' .
  267. ' is set but started value is null');
  268. }
  269. }
  270. }
  271. }
  272. // Three kinds of arguments:
  273. // 1) a user object
  274. // 2) a nickname
  275. // 3) null to clear
  276. // Initialize to false; set to null if none found
  277. $_cur = false;
  278. function common_set_user($user)
  279. {
  280. global $_cur;
  281. if (is_null($user) && common_have_session()) {
  282. $_cur = null;
  283. unset($_SESSION['userid']);
  284. return true;
  285. } else if (is_string($user)) {
  286. $nickname = $user;
  287. $user = User::getKV('nickname', $nickname);
  288. } else if (!$user instanceof User) {
  289. return false;
  290. }
  291. if ($user) {
  292. if (Event::handle('StartSetUser', array(&$user))) {
  293. if (!empty($user)) {
  294. if (!$user->hasRight(Right::WEBLOGIN)) {
  295. // TRANS: Authorisation exception thrown when a user a not allowed to login.
  296. throw new AuthorizationException(_('Not allowed to log in.'));
  297. }
  298. common_ensure_session();
  299. $_SESSION['userid'] = $user->id;
  300. $_cur = $user;
  301. Event::handle('EndSetUser', array($user));
  302. return $_cur;
  303. }
  304. }
  305. }
  306. return false;
  307. }
  308. function common_set_cookie($key, $value, $expiration=0)
  309. {
  310. $path = common_config('site', 'path');
  311. $server = common_config('site', 'server');
  312. if ($path && ($path != '/')) {
  313. $cookiepath = '/' . $path . '/';
  314. } else {
  315. $cookiepath = '/';
  316. }
  317. return setcookie($key,
  318. $value,
  319. $expiration,
  320. $cookiepath,
  321. $server,
  322. GNUsocial::useHTTPS());
  323. }
  324. define('REMEMBERME', 'rememberme');
  325. define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
  326. function common_rememberme($user=null)
  327. {
  328. if (!$user) {
  329. $user = common_current_user();
  330. if (!$user) {
  331. return false;
  332. }
  333. }
  334. $rm = new Remember_me();
  335. $rm->code = common_random_hexstr(16);
  336. $rm->user_id = $user->id;
  337. // Wrap the insert in some good ol' fashioned transaction code
  338. $rm->query('BEGIN');
  339. $result = $rm->insert();
  340. if (!$result) {
  341. common_log_db_error($rm, 'INSERT', __FILE__);
  342. $rm->query('ROLLBACK');
  343. return false;
  344. }
  345. $rm->query('COMMIT');
  346. $cookieval = $rm->user_id . ':' . $rm->code;
  347. common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
  348. common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
  349. return true;
  350. }
  351. function common_remembered_user()
  352. {
  353. $user = null;
  354. $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
  355. if (!$packed) {
  356. return null;
  357. }
  358. list($id, $code) = explode(':', $packed);
  359. if (!$id || !$code) {
  360. common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
  361. common_forgetme();
  362. return null;
  363. }
  364. $rm = Remember_me::getKV('code', $code);
  365. if (!$rm) {
  366. common_log(LOG_WARNING, 'No such remember code: ' . $code);
  367. common_forgetme();
  368. return null;
  369. }
  370. if ($rm->user_id != $id) {
  371. common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
  372. common_forgetme();
  373. return null;
  374. }
  375. $user = User::getKV('id', $rm->user_id);
  376. if (!$user instanceof User) {
  377. common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
  378. common_forgetme();
  379. return null;
  380. }
  381. // successful!
  382. $result = $rm->delete();
  383. if (!$result) {
  384. common_log_db_error($rm, 'DELETE', __FILE__);
  385. common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
  386. common_forgetme();
  387. return null;
  388. }
  389. common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
  390. common_set_user($user);
  391. common_real_login(false);
  392. // We issue a new cookie, so they can log in
  393. // automatically again after this session
  394. common_rememberme($user);
  395. return $user;
  396. }
  397. /**
  398. * must be called with a valid user!
  399. */
  400. function common_forgetme()
  401. {
  402. common_set_cookie(REMEMBERME, '', 0);
  403. }
  404. /**
  405. * Who is the current user?
  406. */
  407. function common_current_user()
  408. {
  409. global $_cur;
  410. if (!_have_config()) {
  411. return null;
  412. }
  413. if ($_cur === false) {
  414. if (isset($_COOKIE[session_name()]) || isset($_GET[session_name()])
  415. || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
  416. common_ensure_session();
  417. $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
  418. if ($id) {
  419. $user = User::getKV('id', $id);
  420. if ($user instanceof User) {
  421. $_cur = $user;
  422. return $_cur;
  423. }
  424. }
  425. }
  426. // that didn't work; try to remember; will init $_cur to null on failure
  427. $_cur = common_remembered_user();
  428. if ($_cur) {
  429. // XXX: Is this necessary?
  430. $_SESSION['userid'] = $_cur->id;
  431. }
  432. }
  433. return $_cur;
  434. }
  435. /**
  436. * Logins that are 'remembered' aren't 'real' -- they're subject to
  437. * cookie-stealing. So, we don't let them do certain things. New reg,
  438. * OpenID, and password logins _are_ real.
  439. */
  440. function common_real_login($real=true)
  441. {
  442. common_ensure_session();
  443. $_SESSION['real_login'] = $real;
  444. }
  445. function common_is_real_login()
  446. {
  447. return common_logged_in() && $_SESSION['real_login'];
  448. }
  449. /**
  450. * Get a hash portion for HTTP caching Etags and such including
  451. * info on the current user's session. If login/logout state changes,
  452. * or we've changed accounts, or we've renamed the current user,
  453. * we'll get a new hash value.
  454. *
  455. * This should not be considered secure information.
  456. *
  457. * @param User $user (optional; uses common_current_user() if left out)
  458. * @return string
  459. */
  460. function common_user_cache_hash($user=false)
  461. {
  462. if ($user === false) {
  463. $user = common_current_user();
  464. }
  465. if ($user) {
  466. return crc32($user->id . ':' . $user->nickname);
  467. } else {
  468. return '0';
  469. }
  470. }
  471. /**
  472. * get canonical version of nickname for comparison
  473. *
  474. * @param string $nickname
  475. * @return string
  476. *
  477. * @throws NicknameException on invalid input
  478. * @deprecated call Nickname::normalize() directly.
  479. */
  480. function common_canonical_nickname($nickname)
  481. {
  482. return Nickname::normalize($nickname);
  483. }
  484. /**
  485. * get canonical version of email for comparison
  486. *
  487. * @fixme actually normalize
  488. * @fixme reject invalid input
  489. *
  490. * @param string $email
  491. * @return string
  492. */
  493. function common_canonical_email($email)
  494. {
  495. // XXX: canonicalize UTF-8
  496. // XXX: lcase the domain part
  497. return $email;
  498. }
  499. function common_purify($html)
  500. {
  501. require_once INSTALLDIR.'/extlib/HTMLPurifier/HTMLPurifier.auto.php';
  502. $cfg = HTMLPurifier_Config::createDefault();
  503. $cfg->set('Attr.AllowedRel', ['bookmark', 'directory', 'enclosure', 'home', 'license', 'nofollow', 'payment', 'tag']); // http://microformats.org/wiki/rel
  504. $cfg->set('HTML.ForbiddenAttributes', array('style')); // id, on* etc. are already filtered by default
  505. $cfg->set('URI.AllowedSchemes', array_fill_keys(common_url_schemes(), true));
  506. // Remove more elements than what the default filter removes, default in GNU social are remotely
  507. // linked resources such as img, video, audio
  508. $forbiddenElements = array();
  509. foreach (common_config('htmlfilter') as $tag=>$filter) {
  510. if ($filter === true) {
  511. $forbiddenElements[] = $tag;
  512. }
  513. }
  514. $cfg->set('HTML.ForbiddenElements', $forbiddenElements);
  515. $html = common_remove_unicode_formatting($html);
  516. $purifier = new HTMLPurifier($cfg);
  517. $purified = $purifier->purify($html);
  518. Event::handle('EndCommonPurify', array(&$purified, $html));
  519. return $purified;
  520. }
  521. function common_remove_unicode_formatting($text)
  522. {
  523. // Strip Unicode text formatting/direction codes
  524. // this is pretty dangerous for visualisation of text and can be used for mischief
  525. return preg_replace('/[\\x{200b}-\\x{200f}\\x{202a}-\\x{202e}]/u', '', $text);
  526. }
  527. /**
  528. * Partial notice markup rendering step: build links to !group references.
  529. *
  530. * @param string $text partially rendered HTML
  531. * @param Profile $author the Profile that is composing the current notice
  532. * @param Notice $parent the Notice this is sent in reply to, if any
  533. * @return string partially rendered HTML
  534. */
  535. function common_render_content($text, Profile $author, Notice $parent=null)
  536. {
  537. $text = common_render_text($text);
  538. $text = common_linkify_mentions($text, $author, $parent);
  539. return $text;
  540. }
  541. /**
  542. * Finds @-mentions within the partially-rendered text section and
  543. * turns them into live links.
  544. *
  545. * Should generally not be called except from common_render_content().
  546. *
  547. * @param string $text partially-rendered HTML
  548. * @param Profile $author the Profile that is composing the current notice
  549. * @param Notice $parent the Notice this is sent in reply to, if any
  550. * @return string partially-rendered HTML
  551. */
  552. function common_linkify_mentions($text, Profile $author, Notice $parent=null)
  553. {
  554. $mentions = common_find_mentions($text, $author, $parent);
  555. // We need to go through in reverse order by position,
  556. // so our positions stay valid despite our fudging with the
  557. // string!
  558. $points = array();
  559. foreach ($mentions as $mention)
  560. {
  561. $points[$mention['position']] = $mention;
  562. }
  563. krsort($points);
  564. foreach ($points as $position => $mention) {
  565. $linkText = common_linkify_mention($mention);
  566. $text = substr_replace($text, $linkText, $position, $mention['length']);
  567. }
  568. return $text;
  569. }
  570. function common_linkify_mention(array $mention)
  571. {
  572. $output = null;
  573. if (Event::handle('StartLinkifyMention', array($mention, &$output))) {
  574. $xs = new XMLStringer(false);
  575. $attrs = array('href' => $mention['url'],
  576. 'class' => 'h-card '.$mention['type']);
  577. if (!empty($mention['title'])) {
  578. $attrs['title'] = $mention['title'];
  579. }
  580. $xs->element('a', $attrs, $mention['text']);
  581. $output = $xs->getString();
  582. Event::handle('EndLinkifyMention', array($mention, &$output));
  583. }
  584. return $output;
  585. }
  586. function common_get_attentions($text, Profile $sender, Notice $parent=null)
  587. {
  588. $mentions = common_find_mentions($text, $sender, $parent);
  589. $atts = array();
  590. foreach ($mentions as $mention) {
  591. foreach ($mention['mentioned'] as $mentioned) {
  592. $atts[$mentioned->getUri()] = $mentioned->getObjectType();
  593. }
  594. }
  595. if ($parent instanceof Notice) {
  596. $parentAuthor = $parent->getProfile();
  597. // afaik groups can't be authors
  598. $atts[$parentAuthor->getUri()] = ActivityObject::PERSON;
  599. }
  600. return $atts;
  601. }
  602. /**
  603. * Find @-mentions in the given text, using the given notice object as context.
  604. * References will be resolved with common_relative_profile() against the user
  605. * who posted the notice.
  606. *
  607. * Note the return data format is internal, to be used for building links and
  608. * such. Should not be used directly; rather, call common_linkify_mentions().
  609. *
  610. * @param string $text
  611. * @param Profile $sender the Profile that is sending the current text
  612. * @param Notice $parent the Notice this text is in reply to, if any
  613. *
  614. * @return array
  615. *
  616. * @access private
  617. */
  618. function common_find_mentions($text, Profile $sender, Notice $parent=null)
  619. {
  620. $mentions = array();
  621. if (Event::handle('StartFindMentions', array($sender, $text, &$mentions))) {
  622. // Get the context of the original notice, if any
  623. $origMentions = array();
  624. // Does it have a parent notice for context?
  625. if ($parent instanceof Notice) {
  626. foreach ($parent->getAttentionProfiles() as $repliedTo) {
  627. if (!$repliedTo->isPerson()) {
  628. continue;
  629. }
  630. $origMentions[$repliedTo->id] = $repliedTo;
  631. }
  632. }
  633. $matches = common_find_mentions_raw($text);
  634. foreach ($matches as $match) {
  635. try {
  636. $nickname = Nickname::normalize($match[0]);
  637. } catch (NicknameException $e) {
  638. // Bogus match? Drop it.
  639. continue;
  640. }
  641. // primarily mention the profiles mentioned in the parent
  642. $mention_found_in_origMentions = false;
  643. foreach($origMentions as $origMentionsId=>$origMention) {
  644. if($origMention->getNickname() == $nickname) {
  645. $mention_found_in_origMentions = $origMention;
  646. // don't mention same twice! the parent might have mentioned
  647. // two users with same nickname on different instances
  648. unset($origMentions[$origMentionsId]);
  649. break;
  650. }
  651. }
  652. // Try to get a profile for this nickname.
  653. // Start with parents mentions, then go to parents sender context
  654. if ($mention_found_in_origMentions) {
  655. $mentioned = $mention_found_in_origMentions;
  656. } else if ($parent instanceof Notice && $parent->getProfile()->getNickname() === $nickname) {
  657. $mentioned = $parent->getProfile();
  658. } else {
  659. // sets to null if no match
  660. $mentioned = common_relative_profile($sender, $nickname);
  661. }
  662. if ($mentioned instanceof Profile) {
  663. try {
  664. $url = $mentioned->getUri(); // prefer the URI as URL, if it is one.
  665. if (!common_valid_http_url($url)) {
  666. $url = $mentioned->getUrl();
  667. }
  668. } catch (InvalidUrlException $e) {
  669. $url = common_local_url('userbyid', array('id' => $mentioned->getID()));
  670. }
  671. $mention = array('mentioned' => array($mentioned),
  672. 'type' => 'mention',
  673. 'text' => $match[0],
  674. 'position' => $match[1],
  675. 'length' => mb_strlen($match[0]),
  676. 'title' => $mentioned->getFullname(),
  677. 'url' => $url);
  678. $mentions[] = $mention;
  679. }
  680. }
  681. // @#tag => mention of all subscriptions tagged 'tag'
  682. preg_match_all('/(?:^|[\s\.\,\:\;]+)@#([\pL\pN_\-\.]{1,64})/',
  683. $text, $hmatches, PREG_OFFSET_CAPTURE);
  684. foreach ($hmatches[1] as $hmatch) {
  685. $tag = common_canonical_tag($hmatch[0]);
  686. $plist = Profile_list::getByTaggerAndTag($sender->getID(), $tag);
  687. if (!$plist instanceof Profile_list || $plist->private) {
  688. continue;
  689. }
  690. $tagged = $sender->getTaggedSubscribers($tag);
  691. $url = common_local_url('showprofiletag',
  692. array('nickname' => $sender->getNickname(),
  693. 'tag' => $tag));
  694. $mentions[] = array('mentioned' => $tagged,
  695. 'type' => 'list',
  696. 'text' => $hmatch[0],
  697. 'position' => $hmatch[1],
  698. 'length' => mb_strlen($hmatch[0]),
  699. 'url' => $url);
  700. }
  701. preg_match_all('/(?:^|[\s\.\,\:\;]+)!(' . Nickname::DISPLAY_FMT . ')/',
  702. $text, $hmatches, PREG_OFFSET_CAPTURE);
  703. foreach ($hmatches[1] as $hmatch) {
  704. $nickname = Nickname::normalize($hmatch[0]);
  705. $group = User_group::getForNickname($nickname, $sender);
  706. if (!$group instanceof User_group || !$sender->isMember($group)) {
  707. continue;
  708. }
  709. $profile = $group->getProfile();
  710. $mentions[] = array('mentioned' => array($profile),
  711. 'type' => 'group',
  712. 'text' => $hmatch[0],
  713. 'position' => $hmatch[1],
  714. 'length' => mb_strlen($hmatch[0]),
  715. 'url' => $group->permalink(),
  716. 'title' => $group->getFancyName());
  717. }
  718. Event::handle('EndFindMentions', array($sender, $text, &$mentions));
  719. }
  720. return $mentions;
  721. }
  722. /**
  723. * Does the actual regex pulls to find @-mentions in text.
  724. * Should generally not be called directly; for use in common_find_mentions.
  725. *
  726. * @param string $text
  727. * @return array of PCRE match arrays
  728. */
  729. function common_find_mentions_raw($text)
  730. {
  731. $tmatches = array();
  732. preg_match_all('/^T (' . Nickname::DISPLAY_FMT . ') /',
  733. $text,
  734. $tmatches,
  735. PREG_OFFSET_CAPTURE);
  736. $atmatches = array();
  737. // the regexp's "(?!\@)" makes sure it doesn't matches the single "@remote" in "@remote@server.com"
  738. preg_match_all('/(?:^|\s+)@(' . Nickname::DISPLAY_FMT . ')\b(?!\@)/',
  739. $text,
  740. $atmatches,
  741. PREG_OFFSET_CAPTURE);
  742. $matches = array_merge($tmatches[1], $atmatches[1]);
  743. return $matches;
  744. }
  745. function common_render_text($text)
  746. {
  747. $text = common_remove_unicode_formatting($text);
  748. $text = nl2br(htmlspecialchars($text));
  749. $text = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $text);
  750. $text = common_replace_urls_callback($text, 'common_linkify');
  751. $text = preg_replace_callback('/(^|\&quot\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/u',
  752. function ($m) { return "{$m[1]}#".common_tag_link($m[2]); }, $text);
  753. // XXX: machine tags
  754. return $text;
  755. }
  756. define('_URL_SCHEME_COLON_DOUBLE_SLASH', 1);
  757. define('_URL_SCHEME_SINGLE_COLON', 2);
  758. define('_URL_SCHEME_NO_DOMAIN', 4);
  759. define('_URL_SCHEME_COLON_COORDINATES', 8);
  760. function common_url_schemes($filter=null)
  761. {
  762. // TODO: move these to $config
  763. $schemes = [
  764. 'http' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  765. 'https' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  766. 'ftp' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  767. 'ftps' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  768. 'mms' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  769. 'rtsp' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  770. 'gopher' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  771. 'news' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  772. 'nntp' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  773. 'telnet' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  774. 'wais' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  775. 'file' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  776. 'prospero' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  777. 'webcal' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  778. 'irc' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  779. 'ircs' => _URL_SCHEME_COLON_DOUBLE_SLASH,
  780. 'aim' => _URL_SCHEME_SINGLE_COLON,
  781. 'bitcoin' => _URL_SCHEME_SINGLE_COLON,
  782. 'fax' => _URL_SCHEME_SINGLE_COLON,
  783. 'jabber' => _URL_SCHEME_SINGLE_COLON,
  784. 'mailto' => _URL_SCHEME_SINGLE_COLON,
  785. 'tel' => _URL_SCHEME_SINGLE_COLON,
  786. 'xmpp' => _URL_SCHEME_SINGLE_COLON,
  787. 'magnet' => _URL_SCHEME_NO_DOMAIN,
  788. 'geo' => _URL_SCHEME_COLON_COORDINATES,
  789. ];
  790. return array_keys(
  791. array_filter($schemes,
  792. function ($scheme) use ($filter) {
  793. return is_null($filter) || ($scheme & $filter);
  794. })
  795. );
  796. }
  797. /**
  798. * Find links in the given text and pass them to the given callback function.
  799. *
  800. * @param string $text
  801. * @param function($text, $arg) $callback: return replacement text
  802. * @param mixed $arg: optional argument will be passed on to the callback
  803. */
  804. function common_replace_urls_callback($text, $callback, $arg = null) {
  805. $geouri_labeltext_regex = '\pN\pL\-';
  806. $geouri_mark_regex = '\-\_\.\!\~\*\\\'\(\)'; // the \\\' is really pretty
  807. $geouri_unreserved_regex = '\pN\pL' . $geouri_mark_regex;
  808. $geouri_punreserved_regex = '\[\]\:\&\+\$';
  809. $geouri_pctencoded_regex = '(?:\%[0-9a-fA-F][0-9a-fA-F])';
  810. $geouri_paramchar_regex = $geouri_unreserved_regex . $geouri_punreserved_regex; //FIXME: add $geouri_pctencoded_regex here so it works
  811. // Start off with a regex
  812. $regex = '#'.
  813. '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
  814. '('.
  815. '(?:'.
  816. '(?:'. //Known protocols
  817. '(?:'.
  818. '(?:(?:' . implode('|', common_url_schemes(_URL_SCHEME_COLON_DOUBLE_SLASH)) . ')://)'.
  819. '|'.
  820. '(?:(?:' . implode('|', common_url_schemes(_URL_SCHEME_SINGLE_COLON)) . '):)'.
  821. ')'.
  822. '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
  823. '(?:'.
  824. '(?:'.
  825. '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
  826. ')|(?:'.
  827. '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
  828. ')'.
  829. ')'.
  830. ')'.
  831. '|(?:'.
  832. '(?:' . implode('|', common_url_schemes(_URL_SCHEME_COLON_COORDINATES)) . '):'.
  833. // There's an order that must be followed here too, if ;crs= is used, it must precede ;u=
  834. // Also 'crsp' (;crs=$crsp) must match $geouri_labeltext_regex
  835. // Also 'uval' (;u=$uval) must be a pnum: \-?[0-9]+
  836. '(?:'.
  837. '(?:[0-9]+(?:\.[0-9]+)?(?:\,[0-9]+(?:\.[0-9]+)?){1,2})'. // 1(.23)?(,4(.56)){1,2}
  838. '(?:\;(?:['.$geouri_labeltext_regex.']+)(?:\=['.$geouri_paramchar_regex.']+)*)*'.
  839. ')'.
  840. ')'.
  841. // URLs without domain name, like magnet:?xt=...
  842. '|(?:(?:' . implode('|', common_url_schemes(_URL_SCHEME_NO_DOMAIN)) . '):(?=\?))'. // zero-length lookahead requires ? after :
  843. (common_config('linkify', 'bare_ipv4') // Convert IPv4 addresses to hyperlinks
  844. ? '|(?:(?: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]?)'
  845. : '').
  846. (common_config('linkify', 'bare_ipv6') // Convert IPv6 addresses to hyperlinks
  847. ? '|(?:'. //IPv6
  848. '\[?(?:(?:(?:[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})))\]?(?<!:)'.
  849. ')'
  850. : '').
  851. (common_config('linkify', 'bare_domains')
  852. ? '|(?:'. //DNS
  853. '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
  854. '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
  855. //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
  856. '(?: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)'.
  857. ')(?![\pN\pL\-\_])'
  858. : '') . // if common_config('linkify', 'bare_domains') is false, don't add anything here
  859. ')'.
  860. '(?:'.
  861. '(?:\:\d+)?'. //:port
  862. '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
  863. '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
  864. '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
  865. ')(?<![\?\.\,\#\,])'.
  866. ')'.
  867. '#ixu';
  868. //preg_match_all($regex,$text,$matches);
  869. //print_r($matches);
  870. return preg_replace_callback($regex, curry('callback_helper',$callback,$arg) ,$text);
  871. }
  872. /**
  873. * Intermediate callback for common_replace_links(), helps resolve some
  874. * ambiguous link forms before passing on to the final callback.
  875. *
  876. * @param array $matches
  877. * @param callable $callback
  878. * @param mixed $arg optional argument to pass on as second param to callback
  879. * @return string
  880. *
  881. * @access private
  882. */
  883. function callback_helper($matches, $callback, $arg=null) {
  884. $url=$matches[1];
  885. $left = strpos($matches[0],$url);
  886. $right = $left+strlen($url);
  887. $groupSymbolSets=array(
  888. array(
  889. 'left'=>'(',
  890. 'right'=>')'
  891. ),
  892. array(
  893. 'left'=>'[',
  894. 'right'=>']'
  895. ),
  896. array(
  897. 'left'=>'{',
  898. 'right'=>'}'
  899. ),
  900. array(
  901. 'left'=>'<',
  902. 'right'=>'>'
  903. )
  904. );
  905. $cannotEndWith=array('.','?',',','#');
  906. $original_url=$url;
  907. do{
  908. $original_url=$url;
  909. foreach($groupSymbolSets as $groupSymbolSet){
  910. if(substr($url,-1)==$groupSymbolSet['right']){
  911. $group_left_count = substr_count($url,$groupSymbolSet['left']);
  912. $group_right_count = substr_count($url,$groupSymbolSet['right']);
  913. if($group_left_count<$group_right_count){
  914. $right-=1;
  915. $url=substr($url,0,-1);
  916. }
  917. }
  918. }
  919. if(in_array(substr($url,-1),$cannotEndWith)){
  920. $right-=1;
  921. $url=substr($url,0,-1);
  922. }
  923. }while($original_url!=$url);
  924. $result = call_user_func_array($callback, array($url, $arg));
  925. return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
  926. }
  927. require_once INSTALLDIR . "/lib/curry.php";
  928. function common_linkify($url) {
  929. // It comes in special'd, so we unspecial it before passing to the stringifying
  930. // functions
  931. $url = htmlspecialchars_decode($url);
  932. if (strpos($url, '@') !== false && strpos($url, ':') === false && Validate::email($url)) {
  933. //url is an email address without the mailto: protocol
  934. $canon = "mailto:$url";
  935. $longurl = "mailto:$url";
  936. } else {
  937. $canon = File_redirection::_canonUrl($url);
  938. $longurl_data = File_redirection::where($canon, common_config('attachments', 'process_links'));
  939. if(isset($longurl_data->redir_url)) {
  940. $longurl = $longurl_data->redir_url;
  941. } else {
  942. // e.g. local files
  943. $longurl = $longurl_data->url;
  944. }
  945. }
  946. $attrs = array('href' => $longurl, 'title' => $longurl);
  947. $is_attachment = false;
  948. $attachment_id = null;
  949. $has_thumb = false;
  950. // Check to see whether this is a known "attachment" URL.
  951. try {
  952. $f = File::getByUrl($longurl);
  953. } catch (NoResultException $e) {
  954. if (common_config('attachments', 'process_links')) {
  955. // XXX: this writes to the database. :<
  956. try {
  957. $f = File::processNew($longurl);
  958. } catch (ServerException $e) {
  959. $f = null;
  960. }
  961. }
  962. }
  963. if ($f instanceof File) {
  964. try {
  965. $enclosure = $f->getEnclosure();
  966. $is_attachment = true;
  967. $attachment_id = $f->id;
  968. $thumb = File_thumbnail::getKV('file_id', $f->id);
  969. $has_thumb = ($thumb instanceof File_thumbnail);
  970. } catch (ServerException $e) {
  971. // There was not enough metadata available
  972. }
  973. }
  974. // Add clippy
  975. if ($is_attachment) {
  976. $attrs['class'] = 'attachment';
  977. if ($has_thumb) {
  978. $attrs['class'] = 'attachment thumbnail';
  979. }
  980. $attrs['id'] = "attachment-{$attachment_id}";
  981. }
  982. // Whether to nofollow
  983. $nf = common_config('nofollow', 'external');
  984. if ($nf == 'never') {
  985. $attrs['rel'] = 'external';
  986. } else {
  987. $attrs['rel'] = 'nofollow external';
  988. }
  989. return XMLStringer::estring('a', $attrs, $url);
  990. }
  991. /**
  992. * Find and shorten links in a given chunk of text if it's longer than the
  993. * configured notice content limit (or unconditionally).
  994. *
  995. * Side effects: may save file and file_redirection records for referenced URLs.
  996. *
  997. * Pass the $user option or call $user->shortenLinks($text) to ensure the proper
  998. * user's options are used; otherwise the current web session user's setitngs
  999. * will be used or ur1.ca if there is no active web login.
  1000. *
  1001. * @param string $text
  1002. * @param boolean $always (optional)
  1003. * @param User $user (optional)
  1004. *
  1005. * @return string
  1006. */
  1007. function common_shorten_links($text, $always = false, User $user=null)
  1008. {
  1009. if ($user === null) {
  1010. $user = common_current_user();
  1011. }
  1012. $maxLength = User_urlshortener_prefs::maxNoticeLength($user);
  1013. if ($always || ($maxLength != -1 && mb_strlen($text) > $maxLength)) {
  1014. return common_replace_urls_callback($text, array('File_redirection', 'forceShort'), $user);
  1015. } else {
  1016. return common_replace_urls_callback($text, array('File_redirection', 'makeShort'), $user);
  1017. }
  1018. }
  1019. /**
  1020. * Very basic stripping of invalid UTF-8 input text.
  1021. *
  1022. * @param string $str
  1023. * @return mixed string or null if invalid input
  1024. *
  1025. * @todo ideally we should drop bad chars, and maybe do some of the checks
  1026. * from common_xml_safe_str. But we can't strip newlines, etc.
  1027. * @todo Unicode normalization might also be useful, but not needed now.
  1028. */
  1029. function common_validate_utf8($str)
  1030. {
  1031. // preg_replace will return NULL on invalid UTF-8 input.
  1032. //
  1033. // Note: empty regex //u also caused NULL return on some
  1034. // production machines, but none of our test machines.
  1035. //
  1036. // This should be replaced with a more reliable check.
  1037. return preg_replace('/\x00/u', '', $str);
  1038. }
  1039. /**
  1040. * Make sure an arbitrary string is safe for output in XML as a single line.
  1041. *
  1042. * @param string $str
  1043. * @return string
  1044. */
  1045. function common_xml_safe_str($str)
  1046. {
  1047. // Replace common eol and extra whitespace input chars
  1048. $unWelcome = array(
  1049. "\t", // tab
  1050. "\n", // newline
  1051. "\r", // cr
  1052. "\0", // null byte eos
  1053. "\x0B" // vertical tab
  1054. );
  1055. $replacement = array(
  1056. ' ', // single space
  1057. ' ',
  1058. '', // nothing
  1059. '',
  1060. ' '
  1061. );
  1062. $str = str_replace($unWelcome, $replacement, $str);
  1063. // Neutralize any additional control codes and UTF-16 surrogates
  1064. // (Twitter uses '*')
  1065. return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
  1066. }
  1067. function common_slugify($str)
  1068. {
  1069. // php5-intl is highly recommended...
  1070. if (!function_exists('transliterator_transliterate')) {
  1071. $str = preg_replace('/[^\pL\pN]/u', '', $str);
  1072. $str = mb_convert_case($str, MB_CASE_LOWER, 'UTF-8');
  1073. $str = substr($str, 0, 64);
  1074. return $str;
  1075. }
  1076. $str = transliterator_transliterate(
  1077. 'Any-Latin;' . // any charset to latin compatible
  1078. 'NFD;' . // decompose
  1079. '[:Nonspacing Mark:] Remove;' . // remove nonspacing marks (accents etc.)
  1080. 'NFC;' . // composite again
  1081. '[:Punctuation:] Remove;' . // remove punctuation (.,¿? etc.)
  1082. 'Lower();' . // turn into lowercase
  1083. 'Latin-ASCII;', // get ASCII equivalents (ð to d for example)
  1084. $str);
  1085. return preg_replace('/[^\pL\pN]/', '', $str);
  1086. }
  1087. function common_tag_link($tag)
  1088. {
  1089. $canonical = common_canonical_tag($tag);
  1090. if (common_config('singleuser', 'enabled')) {
  1091. // regular TagAction isn't set up in 1user mode
  1092. $nickname = User::singleUserNickname();
  1093. $url = common_local_url('showstream',
  1094. array('nickname' => $nickname,
  1095. 'tag' => $canonical));
  1096. } else {
  1097. $url = common_local_url('tag', array('tag' => $canonical));
  1098. }
  1099. $xs = new XMLStringer();
  1100. $xs->elementStart('span', 'tag');
  1101. $xs->element('a', array('href' => $url,
  1102. 'rel' => 'tag'),
  1103. $tag);
  1104. $xs->elementEnd('span');
  1105. return $xs->getString();
  1106. }
  1107. function common_canonical_tag($tag)
  1108. {
  1109. $tag = common_slugify($tag);
  1110. $tag = substr($tag, 0, 64);
  1111. return $tag;
  1112. }
  1113. function common_valid_profile_tag($str)
  1114. {
  1115. return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
  1116. }
  1117. /**
  1118. * Resolve an ambiguous profile nickname reference, checking in following order:
  1119. * - profiles that $sender subscribes to
  1120. * - profiles that subscribe to $sender
  1121. * - local user profiles
  1122. *
  1123. * WARNING: does not validate or normalize $nickname -- MUST BE PRE-VALIDATED
  1124. * OR THERE MAY BE A RISK OF SQL INJECTION ATTACKS. THIS FUNCTION DOES NOT
  1125. * ESCAPE SQL.
  1126. *
  1127. * @fixme validate input
  1128. * @fixme escape SQL
  1129. * @fixme fix or remove mystery third parameter
  1130. * @fixme is $sender a User or Profile?
  1131. *
  1132. * @param <type> $sender the user or profile in whose context we're looking
  1133. * @param string $nickname validated nickname of
  1134. * @param <type> $dt unused mystery parameter; in Notice reply-to handling a timestamp is passed.
  1135. *
  1136. * @return Profile or null
  1137. */
  1138. function common_relative_profile($sender, $nickname, $dt=null)
  1139. {
  1140. // Will throw exception on invalid input.
  1141. $nickname = Nickname::normalize($nickname);
  1142. // Try to find profiles this profile is subscribed to that have this nickname
  1143. $recipient = new Profile();
  1144. // XXX: use a join instead of a subquery
  1145. $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.intval($sender->id).' and subscribed = id)', 'AND');
  1146. $recipient->whereAdd("nickname = '" . $recipient->escape($nickname) . "'", 'AND');
  1147. if ($recipient->find(true)) {
  1148. // XXX: should probably differentiate between profiles with
  1149. // the same name by date of most recent update
  1150. return $recipient;
  1151. }
  1152. // Try to find profiles that listen to this profile and that have this nickname
  1153. $recipient = new Profile();
  1154. // XXX: use a join instead of a subquery
  1155. $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.intval($sender->id).' and subscriber = id)', 'AND');
  1156. $recipient->whereAdd("nickname = '" . $recipient->escape($nickname) . "'", 'AND');
  1157. if ($recipient->find(true)) {
  1158. // XXX: should probably differentiate between profiles with
  1159. // the same name by date of most recent update
  1160. return $recipient;
  1161. }
  1162. // If this is a local user, try to find a local user with that nickname.
  1163. $sender = User::getKV('id', $sender->id);
  1164. if ($sender instanceof User) {
  1165. $recipient_user = User::getKV('nickname', $nickname);
  1166. if ($recipient_user instanceof User) {
  1167. return $recipient_user->getProfile();
  1168. }
  1169. }
  1170. // Otherwise, no links. @messages from local users to remote users,
  1171. // or from remote users to other remote users, are just
  1172. // outside our ability to make intelligent guesses about
  1173. return null;
  1174. }
  1175. function common_local_url($action, $args=null, $params=null, $fragment=null, $addSession=true)
  1176. {
  1177. if (Event::handle('StartLocalURL', array(&$action, &$params, &$fragment, &$addSession, &$url))) {
  1178. $r = Router::get();
  1179. $path = $r->build($action, $args, $params, $fragment);
  1180. $ssl = GNUsocial::useHTTPS();
  1181. if (common_config('site','fancy')) {
  1182. $url = common_path($path, $ssl, $addSession);
  1183. } else {
  1184. if (mb_strpos($path, '/index.php') === 0) {
  1185. $url = common_path($path, $ssl, $addSession);
  1186. } else {
  1187. $url = common_path('index.php/'.$path, $ssl, $addSession);
  1188. }
  1189. }
  1190. Event::handle('EndLocalURL', array(&$action, &$params, &$fragment, &$addSession, &$url));
  1191. }
  1192. return $url;
  1193. }
  1194. function common_path($relative, $ssl=false, $addSession=true)
  1195. {
  1196. $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
  1197. if ($ssl && GNUsocial::useHTTPS()) {
  1198. $proto = 'https';
  1199. if (is_string(common_config('site', 'sslserver')) &&
  1200. mb_strlen(common_config('site', 'sslserver')) > 0) {
  1201. $serverpart = common_config('site', 'sslserver');
  1202. } else if (common_config('site', 'server')) {
  1203. $serverpart = common_config('site', 'server');
  1204. } else {
  1205. common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
  1206. }
  1207. } else {
  1208. $proto = 'http';
  1209. if (common_config('site', 'server')) {
  1210. $serverpart = common_config('site', 'server');
  1211. } else {
  1212. common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
  1213. }
  1214. }
  1215. if ($addSession) {
  1216. $relative = common_inject_session($relative, $serverpart);
  1217. }
  1218. return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
  1219. }
  1220. // FIXME: Maybe this should also be able to handle non-fancy URLs with index.php?p=...
  1221. function common_fake_local_fancy_url($url)
  1222. {
  1223. /**
  1224. * This is a hacky fix to make URIs generated with "index.php/" match against
  1225. * locally stored URIs without that. So for example if the remote site is looking
  1226. * up the webfinger for some user and for some reason knows about https://some.example/user/1
  1227. * but we locally store and report only https://some.example/index.php/user/1 then they would
  1228. * dismiss the profile for not having an identified alias.
  1229. *
  1230. * There are various live instances where these issues occur, for various reasons.
  1231. * Most of them being users fiddling with configuration while already having
  1232. * started federating (distributing the URI to other servers) or maybe manually
  1233. * editing the local database.
  1234. */
  1235. if (!preg_match(
  1236. // [1] protocol part, we can only rewrite http/https anyway.
  1237. '/^(https?:\/\/)' .
  1238. // [2] site name.
  1239. // FIXME: Dunno how this acts if we're aliasing ourselves with a .onion domain etc.
  1240. '('.preg_quote(common_config('site', 'server'), '/').')' .
  1241. // [3] site path, or if that is empty just '/' (to retain the /)
  1242. '('.preg_quote(common_config('site', 'path') ?: '/', '/').')' .
  1243. // [4] + [5] extract index.php (+ possible leading double /) and the rest of the URL separately.
  1244. '(\/?index\.php\/)(.*)$/', $url, $matches)) {
  1245. // if preg_match failed to match
  1246. throw new Exception('No known change could be made to the URL.');
  1247. }
  1248. // now reconstruct the URL with everything except the "index.php/" part
  1249. $fancy_url = '';
  1250. foreach ([1,2,3,5] as $idx) {
  1251. $fancy_url .= $matches[$idx];
  1252. }
  1253. return $fancy_url;
  1254. }
  1255. // FIXME: Maybe this should also be able to handle non-fancy URLs with index.php?p=...
  1256. function common_fake_local_nonfancy_url($url)
  1257. {
  1258. /**
  1259. * This is a hacky fix to make URIs NOT generated with "index.php/" match against
  1260. * locally stored URIs WITH that. The reverse from the above.
  1261. *
  1262. * It will also "repair" index.php URLs with multiple / prepended. Like https://some.example///index.php/user/1
  1263. */
  1264. if (!preg_match(
  1265. // [1] protocol part, we can only rewrite http/https anyway.
  1266. '/^(https?:\/\/)' .
  1267. // [2] site name.
  1268. // FIXME: Dunno how this acts if we're aliasing ourselves with a .onion domain etc.
  1269. '('.preg_quote(common_config('site', 'server'), '/').')' .
  1270. // [3] site path, or if that is empty just '/' (to retain the /)
  1271. '('.preg_quote(common_config('site', 'path') ?: '/', '/').')' .
  1272. // [4] should be empty (might contain one or more / and then maybe also index.php). Will be overwritten.
  1273. // [5] will have the extracted actual URL part (besides site path)
  1274. '((?!index.php\/)\/*(?:index.php\/)?)(.*)$/', $url, $matches)) {
  1275. // if preg_match failed to match
  1276. throw new Exception('No known change could be made to the URL.');
  1277. }
  1278. $matches[4] = 'index.php/'; // inject the index.php/ rewritethingy
  1279. // remove the first element, which is the full matching string
  1280. array_shift($matches);
  1281. return implode($matches);
  1282. }
  1283. function common_inject_session($url, $serverpart = null)
  1284. {
  1285. if (!common_have_session()) {
  1286. return $url;
  1287. }
  1288. if (empty($serverpart)) {
  1289. $serverpart = parse_url($url, PHP_URL_HOST);
  1290. }
  1291. $currentServer = (array_key_exists('HTTP_HOST', $_SERVER)) ? $_SERVER['HTTP_HOST'] : null;
  1292. // Are we pointing to another server (like an SSL server?)
  1293. if (!empty($currentServer) && 0 != strcasecmp($currentServer, $serverpart)) {
  1294. // Pass the session ID as a GET parameter
  1295. $sesspart = session_name() . '=' . session_id();
  1296. $i = strpos($url, '?');
  1297. if ($i === false) { // no GET params, just append
  1298. $url .= '?' . $sesspart;
  1299. } else {
  1300. $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
  1301. }
  1302. }
  1303. return $url;
  1304. }
  1305. function common_date_string($dt)
  1306. {
  1307. // XXX: do some sexy date formatting
  1308. // return date(DATE_RFC822, $dt);
  1309. $t = strtotime($dt);
  1310. $now = time();
  1311. $diff = $now - $t;
  1312. if ($now < $t) { // that shouldn't happen!
  1313. return common_exact_date($dt);
  1314. } else if ($diff < 60) {
  1315. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1316. return _('a few seconds ago');
  1317. } else if ($diff < 92) {
  1318. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1319. return _('about a minute ago');
  1320. } else if ($diff < 3300) {
  1321. $minutes = round($diff/60);
  1322. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1323. return sprintf( _m('about one minute ago', 'about %d minutes ago', $minutes), $minutes);
  1324. } else if ($diff < 5400) {
  1325. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1326. return _('about an hour ago');
  1327. } else if ($diff < 22 * 3600) {
  1328. $hours = round($diff/3600);
  1329. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1330. return sprintf( _m('about one hour ago', 'about %d hours ago', $hours), $hours);
  1331. } else if ($diff < 37 * 3600) {
  1332. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1333. return _('about a day ago');
  1334. } else if ($diff < 24 * 24 * 3600) {
  1335. $days = round($diff/(24*3600));
  1336. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1337. return sprintf( _m('about one day ago', 'about %d days ago', $days), $days);
  1338. } else if ($diff < 46 * 24 * 3600) {
  1339. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1340. return _('about a month ago');
  1341. } else if ($diff < 330 * 24 * 3600) {
  1342. $months = round($diff/(30*24*3600));
  1343. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1344. return sprintf( _m('about one month ago', 'about %d months ago',$months), $months);
  1345. } else if ($diff < 480 * 24 * 3600) {
  1346. // TRANS: Used in notices to indicate when the notice was made compared to now.
  1347. return _('about a year ago');
  1348. } else {
  1349. return common_exact_date($dt);
  1350. }
  1351. }
  1352. function common_exact_date($dt)
  1353. {
  1354. static $_utc;
  1355. static $_siteTz;
  1356. if (!$_utc) {
  1357. $_utc = new DateTimeZone('UTC');
  1358. $_siteTz = new DateTimeZone(common_timezone());
  1359. }
  1360. $dateStr = date('d F Y H:i:s', strtotime($dt));
  1361. $d = new DateTime($dateStr, $_utc);
  1362. $d->setTimezone($_siteTz);
  1363. // TRANS: Human-readable full date-time specification (formatting on http://php.net/date)
  1364. return $d->format(_('l, d-M-Y H:i:s T'));
  1365. }
  1366. function common_date_w3dtf($dt)
  1367. {
  1368. $dateStr = date('d F Y H:i:s', strtotime($dt));
  1369. $d = new DateTime($dateStr, new DateTimeZone('UTC'));
  1370. $d->setTimezone(new DateTimeZone(common_timezone()));
  1371. return $d->format(DATE_W3C);
  1372. }
  1373. function common_date_rfc2822($dt)
  1374. {
  1375. $dateStr = date('d F Y H:i:s', strtotime($dt));
  1376. $d = new DateTime($dateStr, new DateTimeZone('UTC'));
  1377. $d->setTimezone(new DateTimeZone(common_timezone()));
  1378. return $d->format('r');
  1379. }
  1380. function common_date_iso8601($dt)
  1381. {
  1382. $dateStr = date('d F Y H:i:s', strtotime($dt));
  1383. $d = new DateTime($dateStr, new DateTimeZone('UTC'));
  1384. $d->setTimezone(new DateTimeZone(common_timezone()));
  1385. return $d->format('c');
  1386. }
  1387. function common_sql_now()
  1388. {
  1389. return common_sql_date(time());
  1390. }
  1391. function common_sql_date($datetime)
  1392. {
  1393. return strftime('%Y-%m-%d %H:%M:%S', $datetime);
  1394. }
  1395. /**
  1396. * Return an SQL fragment to calculate an age-based weight from a given
  1397. * timestamp or datetime column.
  1398. *
  1399. * @param string $column name of field we're comparing against current time
  1400. * @param integer $dropoff divisor for age in seconds before exponentiation
  1401. * @return string SQL fragment
  1402. */
  1403. function common_sql_weight($column, $dropoff)
  1404. {
  1405. if (common_config('db', 'type') == 'pgsql') {
  1406. // PostgreSQL doesn't support timestampdiff function.
  1407. // @fixme will this use the right time zone?
  1408. // @fixme does this handle cross-year subtraction correctly?
  1409. return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
  1410. } else {
  1411. return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
  1412. }
  1413. }
  1414. function common_redirect($url, $code=307)
  1415. {
  1416. static $status = array(301 => "Moved Permanently",
  1417. 302 => "Found",
  1418. 303 => "See Other",
  1419. 307 => "Temporary Redirect");
  1420. header('HTTP/1.1 '.$code.' '.$status[$code]);
  1421. header("Location: $url");
  1422. header("Connection: close");
  1423. $xo = new XMLOutputter();
  1424. $xo->startXML('a',
  1425. '-//W3C//DTD XHTML 1.0 Strict//EN',
  1426. 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
  1427. $xo->element('a', array('href' => $url), $url);
  1428. $xo->endXML();
  1429. exit;
  1430. }
  1431. // Stick the notice on the queue
  1432. function common_enqueue_notice($notice)
  1433. {
  1434. static $localTransports = array('ping');
  1435. $transports = array();
  1436. if (common_config('sms', 'enabled')) {
  1437. $transports[] = 'sms';
  1438. }
  1439. if (Event::hasHandler('HandleQueuedNotice')) {
  1440. $transports[] = 'plugin';
  1441. }
  1442. // We can skip these for gatewayed notices.
  1443. if ($notice->isLocal()) {
  1444. $transports = array_merge($transports, $localTransports);
  1445. }
  1446. if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
  1447. $qm = QueueManager::get();
  1448. foreach ($transports as $transport)
  1449. {
  1450. $qm->enqueue($notice, $transport);
  1451. }
  1452. Event::handle('EndEnqueueNotice', array($notice, $transports));
  1453. }
  1454. return true;
  1455. }
  1456. function common_profile_url($nickname)
  1457. {
  1458. return common_local_url('showstream', array('nickname' => $nickname),
  1459. null, null, false);
  1460. }
  1461. /**
  1462. * Should make up a reasonable root URL
  1463. */
  1464. function common_root_url($ssl=false)
  1465. {
  1466. $url = common_path('', $ssl, false);
  1467. $i = strpos($url, '?');
  1468. if ($i !== false) {
  1469. $url = substr($url, 0, $i);
  1470. }
  1471. return $url;
  1472. }
  1473. /**
  1474. * returns $bytes bytes of raw random data
  1475. */
  1476. function common_random_rawstr($bytes)
  1477. {
  1478. $rawstr = @file_exists('/dev/urandom')
  1479. ? common_urandom($bytes)
  1480. : common_mtrand($bytes);
  1481. return $rawstr;
  1482. }
  1483. /**
  1484. * returns $bytes bytes of random data as a hexadecimal string
  1485. */
  1486. function common_random_hexstr($bytes)
  1487. {
  1488. $str = common_random_rawstr($bytes);
  1489. $hexstr = '';
  1490. for ($i = 0; $i < $bytes; $i++) {
  1491. $hexstr .= sprintf("%02x", ord($str[$i]));
  1492. }
  1493. return $hexstr;
  1494. }
  1495. function common_urandom($bytes)
  1496. {
  1497. $h = fopen('/dev/urandom', 'rb');
  1498. // should not block
  1499. $src = fread($h, $bytes);
  1500. fclose($h);
  1501. return $src;
  1502. }
  1503. function common_mtrand($bytes)
  1504. {
  1505. $str = '';
  1506. for ($i = 0; $i < $bytes; $i++) {
  1507. $str .= chr(mt_rand(0, 255));
  1508. }
  1509. return $str;
  1510. }
  1511. /**
  1512. * Record the given URL as the return destination for a future
  1513. * form submission, to be read by common_get_returnto().
  1514. *
  1515. * @param string $url
  1516. *
  1517. * @fixme as a session-global setting, this can allow multiple forms
  1518. * to conflict and overwrite each others' returnto destinations if
  1519. * the user has multiple tabs or windows open.
  1520. *
  1521. * Should refactor to index with a token or otherwise only pass the
  1522. * data along its intended path.
  1523. */
  1524. function common_set_returnto($url)
  1525. {
  1526. common_ensure_session();
  1527. $_SESSION['returnto'] = $url;
  1528. }
  1529. /**
  1530. * Fetch a return-destination URL previously recorded by
  1531. * common_set_returnto().
  1532. *
  1533. * @return mixed URL string or null
  1534. *
  1535. * @fixme as a session-global setting, this can allow multiple forms
  1536. * to conflict and overwrite each others' returnto destinations if
  1537. * the user has multiple tabs or windows open.
  1538. *
  1539. * Should refactor to index with a token or otherwise only pass the
  1540. * data along its intended path.
  1541. */
  1542. function common_get_returnto()
  1543. {
  1544. common_ensure_session();
  1545. return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
  1546. }
  1547. function common_timestamp()
  1548. {
  1549. return date('YmdHis');
  1550. }
  1551. function common_ensure_syslog()
  1552. {
  1553. static $initialized = false;
  1554. if (!$initialized) {
  1555. openlog(common_config('syslog', 'appname'), 0,
  1556. common_config('syslog', 'facility'));
  1557. $initialized = true;
  1558. }
  1559. }
  1560. function common_log_line($priority, $msg)
  1561. {
  1562. static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
  1563. 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
  1564. return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . PHP_EOL;
  1565. }
  1566. function common_request_id()
  1567. {
  1568. $pid = getmypid();
  1569. $server = common_config('site', 'server');
  1570. if (php_sapi_name() == 'cli') {
  1571. $script = basename($_SERVER['PHP_SELF']);
  1572. return "$server:$script:$pid";
  1573. } else {
  1574. static $req_id = null;
  1575. if (!isset($req_id)) {
  1576. $req_id = substr(md5(mt_rand()), 0, 8);
  1577. }
  1578. if (isset($_SERVER['REQUEST_URI'])) {
  1579. $url = $_SERVER['REQUEST_URI'];
  1580. }
  1581. $method = $_SERVER['REQUEST_METHOD'];
  1582. return "$server:$pid.$req_id $method $url";
  1583. }
  1584. }
  1585. function common_log($priority, $msg, $filename=null)
  1586. {
  1587. if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
  1588. $msg = (empty($filename)) ? $msg : basename($filename) . ' - ' . $msg;
  1589. $msg = '[' . common_request_id() . '] ' . $msg;
  1590. $logfile = common_config('site', 'logfile');
  1591. if ($logfile) {
  1592. $log = fopen($logfile, "a");
  1593. if ($log) {
  1594. $output = common_log_line($priority, $msg);
  1595. fwrite($log, $output);
  1596. fclose($log);
  1597. }
  1598. } else {
  1599. common_ensure_syslog();
  1600. syslog($priority, $msg);
  1601. }
  1602. Event::handle('EndLog', array($priority, $msg, $filename));
  1603. }
  1604. }
  1605. function common_debug($msg, $filename=null)
  1606. {
  1607. if ($filename) {
  1608. common_log(LOG_DEBUG, basename($filename).' - '.$msg);
  1609. } else {
  1610. common_log(LOG_DEBUG, $msg);
  1611. }
  1612. }
  1613. function common_log_db_error(&$object, $verb, $filename=null)
  1614. {
  1615. global $_PEAR;
  1616. $objstr = common_log_objstring($object);
  1617. $last_error = &$_PEAR->getStaticProperty('DB_DataObject','lastError');
  1618. if (is_object($last_error)) {
  1619. $msg = $last_error->message;
  1620. } else {
  1621. $msg = 'Unknown error (' . var_export($last_error, true) . ')';
  1622. }
  1623. common_log(LOG_ERR, $msg . '(' . $verb . ' on ' . $objstr . ')', $filename);
  1624. }
  1625. function common_log_objstring(&$object)
  1626. {
  1627. if (is_null($object)) {
  1628. return "null";
  1629. }
  1630. if (!($object instanceof DB_DataObject)) {
  1631. return "(unknown)";
  1632. }
  1633. $arr = $object->toArray();
  1634. $fields = array();
  1635. foreach ($arr as $k => $v) {
  1636. if (is_object($v)) {
  1637. $fields[] = "$k='".get_class($v)."'";
  1638. } else {
  1639. $fields[] = "$k='$v'";
  1640. }
  1641. }
  1642. $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
  1643. return $objstring;
  1644. }
  1645. function common_valid_http_url($url, $secure=false)
  1646. {
  1647. // If $secure is true, only allow https URLs to pass
  1648. // (if false, we use '?' in 'https?' to say the 's' is optional)
  1649. $regex = $secure ? '/^https$/' : '/^https?$/';
  1650. return filter_var($url, FILTER_VALIDATE_URL)
  1651. && preg_match($regex, parse_url($url, PHP_URL_SCHEME));
  1652. }
  1653. function common_valid_tag($tag)
  1654. {
  1655. if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
  1656. return (Validate::email($matches[1]) ||
  1657. preg_match('/^([\w-\.]+)$/', $matches[1]));
  1658. }
  1659. return false;
  1660. }
  1661. /**
  1662. * Determine if given domain or address literal is valid
  1663. * eg for use in JIDs and URLs. Does not check if the domain
  1664. * exists!
  1665. *
  1666. * @param string $domain
  1667. * @return boolean valid or not
  1668. */
  1669. function common_valid_domain($domain)
  1670. {
  1671. $octet = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])";
  1672. $ipv4 = "(?:$octet(?:\.$octet){3})";
  1673. if (preg_match("/^$ipv4$/u", $domain)) return true;
  1674. $group = "(?:[0-9a-f]{1,4})";
  1675. $ipv6 = "(?:\[($group(?::$group){0,7})?(::)?($group(?::$group){0,7})?\])"; // http://tools.ietf.org/html/rfc3513#section-2.2
  1676. if (preg_match("/^$ipv6$/ui", $domain, $matches)) {
  1677. $before = explode(":", $matches[1]);
  1678. $zeroes = $matches[2];
  1679. $after = explode(":", $matches[3]);
  1680. if ($zeroes) {
  1681. $min = 0;
  1682. $max = 7;
  1683. } else {
  1684. $min = 1;
  1685. $max = 8;
  1686. }
  1687. $explicit = count($before) + count($after);
  1688. if ($explicit < $min || $explicit > $max) {
  1689. return false;
  1690. }
  1691. return true;
  1692. }
  1693. try {
  1694. require_once "Net/IDNA.php";
  1695. $idn = Net_IDNA::getInstance();
  1696. $domain = $idn->encode($domain);
  1697. } catch (Exception $e) {
  1698. return false;
  1699. }
  1700. $subdomain = "(?:[a-z0-9][a-z0-9-]*)"; // @fixme
  1701. $fqdn = "(?:$subdomain(?:\.$subdomain)*\.?)";
  1702. return preg_match("/^$fqdn$/ui", $domain);
  1703. }
  1704. /* Following functions are copied from MediaWiki GlobalFunctions.php
  1705. * and written by Evan Prodromou. */
  1706. function common_accept_to_prefs($accept, $def = '*/*')
  1707. {
  1708. // No arg means accept anything (per HTTP spec)
  1709. if(!$accept) {
  1710. return array($def => 1);
  1711. }
  1712. $prefs = array();
  1713. $parts = explode(',', $accept);
  1714. foreach($parts as $part) {
  1715. // FIXME: doesn't deal with params like 'text/html; level=1'
  1716. @list($value, $qpart) = explode(';', trim($part));
  1717. $match = array();
  1718. if(!isset($qpart)) {
  1719. $prefs[$value] = 1;
  1720. } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
  1721. $prefs[$value] = $match[1];
  1722. }
  1723. }
  1724. return $prefs;
  1725. }
  1726. // Match by our supported file extensions
  1727. function common_supported_ext_to_mime($fileext)
  1728. {
  1729. // Accept a filename and take out the extension
  1730. if (strpos($fileext, '.') !== false) {
  1731. $fileext = substr(strrchr($fileext, '.'), 1);
  1732. }
  1733. $supported = common_config('attachments', 'supported');
  1734. if ($supported === true) {
  1735. throw new ServerException('Supported extension but unknown mimetype relation.');
  1736. }
  1737. foreach($supported as $type => $ext) {
  1738. if ($ext === $fileext) {
  1739. return $type;
  1740. }
  1741. }
  1742. throw new ServerException('Unsupported file extension');
  1743. }
  1744. // Match by our supported mime types
  1745. function common_supported_mime_to_ext($mimetype)
  1746. {
  1747. $supported = common_config('attachments', 'supported');
  1748. if ($supported === true) {
  1749. throw new ServerException('Supported mimetype but unknown extension relation.');
  1750. }
  1751. foreach($supported as $type => $ext) {
  1752. if ($mimetype === $type) {
  1753. return $ext;
  1754. }
  1755. }
  1756. throw new ServerException('Unsupported MIME type');
  1757. }
  1758. // The MIME "media" is the part before the slash (video in video/webm)
  1759. function common_get_mime_media($type)
  1760. {
  1761. $tmp = explode('/', $type);
  1762. return strtolower($tmp[0]);
  1763. }
  1764. // Get only the mimetype and not additional info (separated from bare mime with semi-colon)
  1765. function common_bare_mime($mimetype)
  1766. {
  1767. $mimetype = mb_strtolower($mimetype);
  1768. if ($semicolon = mb_strpos($mimetype, ';')) {
  1769. $mimetype = mb_substr($mimetype, 0, $semicolon);
  1770. }
  1771. return $mimetype;
  1772. }
  1773. function common_mime_type_match($type, $avail)
  1774. {
  1775. if(array_key_exists($type, $avail)) {
  1776. return $type;
  1777. } else {
  1778. $parts = explode('/', $type);
  1779. if(array_key_exists($parts[0] . '/*', $avail)) {
  1780. return $parts[0] . '/*';
  1781. } elseif(array_key_exists('*/*', $avail)) {
  1782. return '*/*';
  1783. } else {
  1784. return null;
  1785. }
  1786. }
  1787. }
  1788. function common_negotiate_type($cprefs, $sprefs)
  1789. {
  1790. $combine = array();
  1791. foreach(array_keys($sprefs) as $type) {
  1792. $parts = explode('/', $type);
  1793. if($parts[1] != '*') {
  1794. $ckey = common_mime_type_match($type, $cprefs);
  1795. if($ckey) {
  1796. $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
  1797. }
  1798. }
  1799. }
  1800. foreach(array_keys($cprefs) as $type) {
  1801. $parts = explode('/', $type);
  1802. if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
  1803. $skey = common_mime_type_match($type, $sprefs);
  1804. if($skey) {
  1805. $combine[$type] = $sprefs[$skey] * $cprefs[$type];
  1806. }
  1807. }
  1808. }
  1809. $bestq = 0;
  1810. $besttype = 'text/html';
  1811. foreach(array_keys($combine) as $type) {
  1812. if($combine[$type] > $bestq) {
  1813. $besttype = $type;
  1814. $bestq = $combine[$type];
  1815. }
  1816. }
  1817. if ('text/html' === $besttype) {
  1818. return "text/html; charset=utf-8";
  1819. }
  1820. return $besttype;
  1821. }
  1822. function common_config($main, $sub=null)
  1823. {
  1824. global $config;
  1825. if (is_null($sub)) {
  1826. // Return the config category array
  1827. return array_key_exists($main, $config) ? $config[$main] : array();
  1828. }
  1829. // Return the config value
  1830. return (array_key_exists($main, $config) &&
  1831. array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
  1832. }
  1833. function common_config_set($main, $sub, $value)
  1834. {
  1835. global $config;
  1836. if (!array_key_exists($main, $config)) {
  1837. $config[$main] = array();
  1838. }
  1839. $config[$main][$sub] = $value;
  1840. }
  1841. function common_config_append($main, $sub, $value)
  1842. {
  1843. global $config;
  1844. if (!array_key_exists($main, $config)) {
  1845. $config[$main] = array();
  1846. }
  1847. if (!array_key_exists($sub, $config[$main])) {
  1848. $config[$main][$sub] = array();
  1849. }
  1850. if (!is_array($config[$main][$sub])) {
  1851. $config[$main][$sub] = array($config[$main][$sub]);
  1852. }
  1853. array_push($config[$main][$sub], $value);
  1854. }
  1855. /**
  1856. * Pull arguments from a GET/POST/REQUEST array with first-level input checks:
  1857. * strips "magic quotes" slashes if necessary, and kills invalid UTF-8 strings.
  1858. *
  1859. * @param array $from
  1860. * @return array
  1861. */
  1862. function common_copy_args($from)
  1863. {
  1864. $to = array();
  1865. $strip = get_magic_quotes_gpc();
  1866. foreach ($from as $k => $v) {
  1867. if(is_array($v)) {
  1868. $to[$k] = common_copy_args($v);
  1869. } else {
  1870. if ($strip) {
  1871. $v = stripslashes($v);
  1872. }
  1873. $to[$k] = strval(common_validate_utf8($v));
  1874. }
  1875. }
  1876. return $to;
  1877. }
  1878. /**
  1879. * Neutralise the evil effects of magic_quotes_gpc in the current request.
  1880. * This is used before handing a request off to OAuthRequest::from_request.
  1881. * @fixme Doesn't consider vars other than _POST and _GET?
  1882. * @fixme Can't be undone and could corrupt data if run twice.
  1883. */
  1884. function common_remove_magic_from_request()
  1885. {
  1886. if(get_magic_quotes_gpc()) {
  1887. $_POST=array_map('stripslashes',$_POST);
  1888. $_GET=array_map('stripslashes',$_GET);
  1889. }
  1890. }
  1891. function common_user_uri(&$user)
  1892. {
  1893. return common_local_url('userbyid', array('id' => $user->id),
  1894. null, null, false);
  1895. }
  1896. // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
  1897. function common_confirmation_code($bits)
  1898. {
  1899. // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
  1900. static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
  1901. $chars = ceil($bits/5);
  1902. $code = '';
  1903. for ($i = 0; $i < $chars; $i++) {
  1904. // XXX: convert to string and back
  1905. $num = hexdec(common_random_hexstr(1));
  1906. // XXX: randomness is too precious to throw away almost
  1907. // 40% of the bits we get!
  1908. $code .= $codechars[$num%32];
  1909. }
  1910. return $code;
  1911. }
  1912. // convert markup to HTML
  1913. function common_markup_to_html($c, $args=null)
  1914. {
  1915. if ($c === null) {
  1916. return '';
  1917. }
  1918. if (is_null($args)) {
  1919. $args = array();
  1920. }
  1921. // XXX: not very efficient
  1922. foreach ($args as $name => $value) {
  1923. $c = preg_replace('/%%arg.'.$name.'%%/', $value, $c);
  1924. }
  1925. $c = preg_replace_callback('/%%user.(\w+)%%/', function ($m) { return common_user_property($m[1]); }, $c);
  1926. $c = preg_replace_callback('/%%action.(\w+)%%/', function ($m) { return common_local_url($m[1]); }, $c);
  1927. $c = preg_replace_callback('/%%doc.(\w+)%%/', function ($m) { return common_local_url('doc', array('title'=>$m[1])); }, $c);
  1928. $c = preg_replace_callback('/%%(\w+).(\w+)%%/', function ($m) { return common_config($m[1], $m[2]); }, $c);
  1929. return \Michelf\Markdown::defaultTransform($c);
  1930. }
  1931. function common_user_property($property)
  1932. {
  1933. $profile = Profile::current();
  1934. if (empty($profile)) {
  1935. return null;
  1936. }
  1937. switch ($property) {
  1938. case 'profileurl':
  1939. case 'nickname':
  1940. case 'fullname':
  1941. case 'location':
  1942. case 'bio':
  1943. return $profile->$property;
  1944. break;
  1945. case 'avatar':
  1946. try {
  1947. return $profile->getAvatar(AVATAR_STREAM_SIZE);
  1948. } catch (Exception $e) {
  1949. return null;
  1950. }
  1951. break;
  1952. case 'bestname':
  1953. return $profile->getBestName();
  1954. break;
  1955. default:
  1956. return null;
  1957. }
  1958. }
  1959. function common_profile_uri($profile)
  1960. {
  1961. $uri = null;
  1962. if (!empty($profile)) {
  1963. if (Event::handle('StartCommonProfileURI', array($profile, &$uri))) {
  1964. $user = User::getKV('id', $profile->id);
  1965. if ($user instanceof User) {
  1966. $uri = $user->getUri();
  1967. }
  1968. Event::handle('EndCommonProfileURI', array($profile, &$uri));
  1969. }
  1970. }
  1971. // XXX: this is a very bad profile!
  1972. return $uri;
  1973. }
  1974. function common_canonical_sms($sms)
  1975. {
  1976. // strip non-digits
  1977. preg_replace('/\D/', '', $sms);
  1978. return $sms;
  1979. }
  1980. function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
  1981. {
  1982. switch ($errno) {
  1983. case E_ERROR:
  1984. case E_COMPILE_ERROR:
  1985. case E_CORE_ERROR:
  1986. case E_USER_ERROR:
  1987. case E_PARSE:
  1988. case E_RECOVERABLE_ERROR:
  1989. common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
  1990. die();
  1991. break;
  1992. case E_WARNING:
  1993. case E_COMPILE_WARNING:
  1994. case E_CORE_WARNING:
  1995. case E_USER_WARNING:
  1996. common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
  1997. break;
  1998. case E_NOTICE:
  1999. case E_USER_NOTICE:
  2000. common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
  2001. break;
  2002. case E_STRICT:
  2003. case E_DEPRECATED:
  2004. case E_USER_DEPRECATED:
  2005. // XXX: config variable to log this stuff, too
  2006. break;
  2007. default:
  2008. common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
  2009. die();
  2010. break;
  2011. }
  2012. // FIXME: show error page if we're on the Web
  2013. /* Don't execute PHP internal error handler */
  2014. return true;
  2015. }
  2016. function common_session_token()
  2017. {
  2018. common_ensure_session();
  2019. if (!array_key_exists('token', $_SESSION)) {
  2020. $_SESSION['token'] = common_random_hexstr(64);
  2021. }
  2022. return $_SESSION['token'];
  2023. }
  2024. function common_license_terms($uri)
  2025. {
  2026. if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
  2027. return explode('-',$matches[1]);
  2028. }
  2029. return array($uri);
  2030. }
  2031. function common_compatible_license($from, $to)
  2032. {
  2033. $from_terms = common_license_terms($from);
  2034. // public domain and cc-by are compatible with everything
  2035. if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
  2036. return true;
  2037. }
  2038. $to_terms = common_license_terms($to);
  2039. // sa is compatible across versions. IANAL
  2040. if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
  2041. return count(array_diff($from_terms, $to_terms)) == 0;
  2042. }
  2043. // XXX: better compatibility check needed here!
  2044. // Should at least normalise URIs
  2045. return ($from == $to);
  2046. }
  2047. /**
  2048. * returns a quoted table name, if required according to config
  2049. */
  2050. function common_database_tablename($tablename)
  2051. {
  2052. if(common_config('db','quote_identifiers')) {
  2053. $tablename = '"'. $tablename .'"';
  2054. }
  2055. //table prefixes could be added here later
  2056. return $tablename;
  2057. }
  2058. /**
  2059. * Shorten a URL with the current user's configured shortening service,
  2060. * or ur1.ca if configured, or not at all if no shortening is set up.
  2061. *
  2062. * @param string $long_url original URL
  2063. * @param User $user to specify a particular user's options
  2064. * @param boolean $force Force shortening (used when notice is too long)
  2065. * @return string may return the original URL if shortening failed
  2066. *
  2067. * @fixme provide a way to specify a particular shortener
  2068. */
  2069. function common_shorten_url($long_url, User $user=null, $force = false)
  2070. {
  2071. $long_url = trim($long_url);
  2072. $user = common_current_user();
  2073. $maxUrlLength = User_urlshortener_prefs::maxUrlLength($user);
  2074. // $force forces shortening even if it's not strictly needed
  2075. // I doubt URL shortening is ever 'strictly' needed. - ESP
  2076. if (($maxUrlLength == -1 || mb_strlen($long_url) < $maxUrlLength) && !$force) {
  2077. return $long_url;
  2078. }
  2079. $shortenerName = User_urlshortener_prefs::urlShorteningService($user);
  2080. if (Event::handle('StartShortenUrl',
  2081. array($long_url, $shortenerName, &$shortenedUrl))) {
  2082. if ($shortenerName == 'internal') {
  2083. try {
  2084. $f = File::processNew($long_url);
  2085. $shortenedUrl = common_local_url('redirecturl', array('id' => $f->id));
  2086. if ((mb_strlen($shortenedUrl) < mb_strlen($long_url)) || $force) {
  2087. return $shortenedUrl;
  2088. } else {
  2089. return $long_url;
  2090. }
  2091. } catch (ServerException $e) {
  2092. return $long_url;
  2093. }
  2094. } else {
  2095. return $long_url;
  2096. }
  2097. } else {
  2098. //URL was shortened, so return the result
  2099. return trim($shortenedUrl);
  2100. }
  2101. }
  2102. /**
  2103. * @return mixed array($proxy, $ip) for web requests; proxy may be null
  2104. * null if not a web request
  2105. *
  2106. * @fixme X-Forwarded-For can be chained by multiple proxies;
  2107. we should parse the list and provide a cleaner array
  2108. * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
  2109. * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
  2110. * use function to get exact request headers from Apache if possible.
  2111. */
  2112. function common_client_ip()
  2113. {
  2114. if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
  2115. return null;
  2116. }
  2117. if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
  2118. if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
  2119. $proxy = $_SERVER['HTTP_CLIENT_IP'];
  2120. } else {
  2121. $proxy = $_SERVER['REMOTE_ADDR'];
  2122. }
  2123. $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  2124. } else {
  2125. $proxy = null;
  2126. if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
  2127. $ip = $_SERVER['HTTP_CLIENT_IP'];
  2128. } else {
  2129. $ip = $_SERVER['REMOTE_ADDR'];
  2130. }
  2131. }
  2132. return array($proxy, $ip);
  2133. }
  2134. function common_url_to_nickname($url)
  2135. {
  2136. static $bad = array('query', 'user', 'password', 'port', 'fragment');
  2137. $parts = parse_url($url);
  2138. // If any of these parts exist, this won't work
  2139. foreach ($bad as $badpart) {
  2140. if (array_key_exists($badpart, $parts)) {
  2141. return null;
  2142. }
  2143. }
  2144. // We just have host and/or path
  2145. // If it's just a host...
  2146. if (array_key_exists('host', $parts) &&
  2147. (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
  2148. {
  2149. $hostparts = explode('.', $parts['host']);
  2150. // Try to catch common idiom of nickname.service.tld
  2151. if ((count($hostparts) > 2) &&
  2152. (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
  2153. (strcmp($hostparts[0], 'www') != 0))
  2154. {
  2155. return common_nicknamize($hostparts[0]);
  2156. } else {
  2157. // Do the whole hostname
  2158. return common_nicknamize($parts['host']);
  2159. }
  2160. } else {
  2161. if (array_key_exists('path', $parts)) {
  2162. // Strip starting, ending slashes
  2163. $path = preg_replace('@/$@', '', $parts['path']);
  2164. $path = preg_replace('@^/@', '', $path);
  2165. $path = basename($path);
  2166. // Hack for MediaWiki user pages, in the form:
  2167. // http://example.com/wiki/User:Myname
  2168. // ('User' may be localized.)
  2169. if (strpos($path, ':')) {
  2170. $parts = array_filter(explode(':', $path));
  2171. $path = $parts[count($parts) - 1];
  2172. }
  2173. if ($path) {
  2174. return common_nicknamize($path);
  2175. }
  2176. }
  2177. }
  2178. return null;
  2179. }
  2180. function common_nicknamize($str)
  2181. {
  2182. try {
  2183. return Nickname::normalize($str);
  2184. } catch (NicknameException $e) {
  2185. return null;
  2186. }
  2187. }
  2188. function common_perf_counter($key, $val=null)
  2189. {
  2190. global $_perfCounters;
  2191. if (isset($_perfCounters)) {
  2192. if (common_config('site', 'logperf')) {
  2193. if (array_key_exists($key, $_perfCounters)) {
  2194. $_perfCounters[$key][] = $val;
  2195. } else {
  2196. $_perfCounters[$key] = array($val);
  2197. }
  2198. if (common_config('site', 'logperf_detail')) {
  2199. common_log(LOG_DEBUG, "PERF COUNTER HIT: $key $val");
  2200. }
  2201. }
  2202. }
  2203. }
  2204. function common_log_perf_counters()
  2205. {
  2206. if (common_config('site', 'logperf')) {
  2207. global $_startTime, $_perfCounters;
  2208. if (isset($_startTime)) {
  2209. $endTime = microtime(true);
  2210. $diff = round(($endTime - $_startTime) * 1000);
  2211. common_log(LOG_DEBUG, "PERF runtime: ${diff}ms");
  2212. }
  2213. $counters = $_perfCounters;
  2214. ksort($counters);
  2215. foreach ($counters as $key => $values) {
  2216. $count = count($values);
  2217. $unique = count(array_unique($values));
  2218. common_log(LOG_DEBUG, "PERF COUNTER: $key $count ($unique unique)");
  2219. }
  2220. }
  2221. }
  2222. function common_is_email($str)
  2223. {
  2224. return (strpos($str, '@') !== false);
  2225. }
  2226. function common_init_stats()
  2227. {
  2228. global $_mem, $_ts;
  2229. $_mem = memory_get_usage(true);
  2230. $_ts = microtime(true);
  2231. }
  2232. function common_log_delta($comment=null)
  2233. {
  2234. global $_mem, $_ts;
  2235. $mold = $_mem;
  2236. $told = $_ts;
  2237. $_mem = memory_get_usage(true);
  2238. $_ts = microtime(true);
  2239. $mtotal = $_mem - $mold;
  2240. $ttotal = $_ts - $told;
  2241. if (empty($comment)) {
  2242. $comment = 'Delta';
  2243. }
  2244. common_debug(sprintf("%s: %d %d", $comment, $mtotal, round($ttotal * 1000000)));
  2245. }
  2246. function common_strip_html($html, $trim=true, $save_whitespace=false)
  2247. {
  2248. if (!$save_whitespace) {
  2249. $html = preg_replace('/\s+/', ' ', $html);
  2250. }
  2251. $text = html_entity_decode(strip_tags($html), ENT_QUOTES, 'UTF-8');
  2252. return $trim ? trim($text) : $text;
  2253. }
  2254. function html_sprintf()
  2255. {
  2256. $args = func_get_args();
  2257. for ($i=1; $i<count($args); $i++) {
  2258. $args[$i] = htmlspecialchars($args[$i]);
  2259. }
  2260. return call_user_func_array('sprintf', $args);
  2261. }
  2262. function _ve($var)
  2263. {
  2264. return var_export($var, true);
  2265. }