util.php 85 KB

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