util.php 82 KB

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