util.php 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780
  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('START TRANSACTION');
  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, $defancy = false)
  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') && !$defancy) {
  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') !== 'mysql') {
  1454. $expr = sprintf(
  1455. '(((EXTRACT(DAY %1$s) * 24 + EXTRACT(HOUR %1$s)) * 60 + '
  1456. . 'EXTRACT(MINUTE %1$s)) * 60 + EXTRACT(SECOND %1$s))',
  1457. "FROM ({$column} - CURRENT_TIMESTAMP)"
  1458. );
  1459. } else {
  1460. $expr = "timestampdiff(SECOND, CURRENT_TIMESTAMP, {$column})";
  1461. }
  1462. return "SUM(EXP({$expr} / {$dropoff}))";
  1463. }
  1464. function common_redirect($url, $code=307)
  1465. {
  1466. static $status = [301 => "Moved Permanently",
  1467. 302 => "Found",
  1468. 303 => "See Other",
  1469. 307 => "Temporary Redirect"];
  1470. header('HTTP/1.1 '.$code.' '.$status[$code]);
  1471. header("Location: $url");
  1472. header("Connection: close");
  1473. $xo = new XMLOutputter();
  1474. $xo->startXML(
  1475. 'a',
  1476. '-//W3C//DTD XHTML 1.0 Strict//EN',
  1477. 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'
  1478. );
  1479. $xo->element('a', ['href' => $url], $url);
  1480. $xo->endXML();
  1481. exit;
  1482. }
  1483. // Stick the notice on the queue
  1484. function common_enqueue_notice($notice)
  1485. {
  1486. static $localTransports = ['ping'];
  1487. $transports = [];
  1488. if (common_config('sms', 'enabled')) {
  1489. $transports[] = 'sms';
  1490. }
  1491. if (Event::hasHandler('HandleQueuedNotice')) {
  1492. $transports[] = 'Module';
  1493. }
  1494. // We can skip these for gatewayed notices.
  1495. if ($notice->isLocal()) {
  1496. $transports = array_merge($transports, $localTransports);
  1497. }
  1498. if (Event::handle('StartEnqueueNotice', [$notice, &$transports])) {
  1499. $qm = QueueManager::get();
  1500. foreach ($transports as $transport) {
  1501. $qm->enqueue($notice, $transport);
  1502. }
  1503. Event::handle('EndEnqueueNotice', [$notice, $transports]);
  1504. }
  1505. return true;
  1506. }
  1507. function common_profile_url($nickname)
  1508. {
  1509. return common_local_url(
  1510. 'showstream',
  1511. ['nickname' => $nickname],
  1512. null,
  1513. null,
  1514. false
  1515. );
  1516. }
  1517. /**
  1518. * Should make up a reasonable root URL
  1519. *
  1520. * @param bool $tls true or false to force TLS scheme, null to use server configuration
  1521. */
  1522. function common_root_url($tls=null)
  1523. {
  1524. if (is_null($tls)) {
  1525. $tls = GNUsocial::useHTTPS();
  1526. }
  1527. $url = common_path('', $tls, false);
  1528. $i = strpos($url, '?');
  1529. if ($i !== false) {
  1530. $url = substr($url, 0, $i);
  1531. }
  1532. return $url;
  1533. }
  1534. /**
  1535. * returns $bytes bytes of raw random data
  1536. */
  1537. function common_random_rawstr($bytes)
  1538. {
  1539. $rawstr = @file_exists('/dev/urandom')
  1540. ? common_urandom($bytes)
  1541. : common_mtrand($bytes);
  1542. return $rawstr;
  1543. }
  1544. /**
  1545. * returns $bytes bytes of random data as a hexadecimal string
  1546. */
  1547. function common_random_hexstr($bytes)
  1548. {
  1549. return bin2hex(random_bytes($bytes));
  1550. }
  1551. function common_urandom($bytes)
  1552. {
  1553. $h = fopen('/dev/urandom', 'rb');
  1554. // should not block
  1555. $src = fread($h, $bytes);
  1556. fclose($h);
  1557. return $src;
  1558. }
  1559. function common_mtrand($bytes)
  1560. {
  1561. $str = '';
  1562. for ($i = 0; $i < $bytes; $i++) {
  1563. $str .= chr(mt_rand(0, 255));
  1564. }
  1565. return $str;
  1566. }
  1567. /**
  1568. * Record the given URL as the return destination for a future
  1569. * form submission, to be read by common_get_returnto().
  1570. *
  1571. * @param string $url
  1572. *
  1573. * @fixme as a session-global setting, this can allow multiple forms
  1574. * to conflict and overwrite each others' returnto destinations if
  1575. * the user has multiple tabs or windows open.
  1576. *
  1577. * Should refactor to index with a token or otherwise only pass the
  1578. * data along its intended path.
  1579. */
  1580. function common_set_returnto($url)
  1581. {
  1582. common_ensure_session();
  1583. $_SESSION['returnto'] = $url;
  1584. }
  1585. /**
  1586. * Fetch a return-destination URL previously recorded by
  1587. * common_set_returnto().
  1588. *
  1589. * @return mixed URL string or null
  1590. *
  1591. * @fixme as a session-global setting, this can allow multiple forms
  1592. * to conflict and overwrite each others' returnto destinations if
  1593. * the user has multiple tabs or windows open.
  1594. *
  1595. * Should refactor to index with a token or otherwise only pass the
  1596. * data along its intended path.
  1597. */
  1598. function common_get_returnto()
  1599. {
  1600. common_ensure_session();
  1601. return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
  1602. }
  1603. function common_timestamp()
  1604. {
  1605. return date('YmdHis');
  1606. }
  1607. function common_ensure_syslog()
  1608. {
  1609. static $initialized = false;
  1610. if (!$initialized) {
  1611. openlog(
  1612. common_config('syslog', 'appname'),
  1613. 0,
  1614. common_config('syslog', 'facility')
  1615. );
  1616. $initialized = true;
  1617. }
  1618. }
  1619. function common_log_line($priority, $msg)
  1620. {
  1621. static $syslog_priorities = ['LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
  1622. 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG'];
  1623. return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . PHP_EOL;
  1624. }
  1625. function common_request_id()
  1626. {
  1627. $pid = getmypid();
  1628. $server = common_config('site', 'server');
  1629. if (php_sapi_name() == 'cli') {
  1630. $script = basename($_SERVER['PHP_SELF']);
  1631. return "$server:$script:$pid";
  1632. } else {
  1633. static $req_id = null;
  1634. if (!isset($req_id)) {
  1635. $req_id = substr(md5(mt_rand()), 0, 8);
  1636. }
  1637. if (isset($_SERVER['REQUEST_URI'])) {
  1638. $url = $_SERVER['REQUEST_URI'];
  1639. }
  1640. $method = $_SERVER['REQUEST_METHOD'];
  1641. return "$server:$pid.$req_id $method $url";
  1642. }
  1643. }
  1644. function common_log($priority, $msg, $filename=null)
  1645. {
  1646. // Don't write LOG_DEBUG if that's not wanted
  1647. if ($priority === LOG_DEBUG && !common_config('site', 'logdebug')) {
  1648. return;
  1649. }
  1650. if (Event::handle('StartLog', [&$priority, &$msg, &$filename])) {
  1651. $msg = (empty($filename)) ? $msg : basename($filename) . ' - ' . $msg;
  1652. $msg = '[' . common_request_id() . '] ' . $msg;
  1653. $logfile = common_config('site', 'logfile');
  1654. if ($logfile) {
  1655. $log = fopen($logfile, "a");
  1656. if ($log) {
  1657. $output = common_log_line($priority, $msg);
  1658. fwrite($log, $output);
  1659. fclose($log);
  1660. }
  1661. } else {
  1662. common_ensure_syslog();
  1663. syslog($priority, $msg);
  1664. }
  1665. Event::handle('EndLog', [$priority, $msg, $filename]);
  1666. }
  1667. }
  1668. function common_debug($msg, $filename=null)
  1669. {
  1670. if ($filename) {
  1671. common_log(LOG_DEBUG, basename($filename).' - '.$msg);
  1672. } else {
  1673. common_log(LOG_DEBUG, $msg);
  1674. }
  1675. }
  1676. function common_log_db_error(&$object, $verb, $filename=null)
  1677. {
  1678. global $_PEAR;
  1679. $objstr = common_log_objstring($object);
  1680. $last_error = &$_PEAR->getStaticProperty('DB_DataObject', 'lastError');
  1681. if (is_object($last_error)) {
  1682. $msg = $last_error->message;
  1683. } else {
  1684. $msg = 'Unknown error (' . var_export($last_error, true) . ')';
  1685. }
  1686. common_log(LOG_ERR, $msg . '(' . $verb . ' on ' . $objstr . ')', $filename);
  1687. }
  1688. function common_log_objstring(&$object)
  1689. {
  1690. if (is_null($object)) {
  1691. return "null";
  1692. }
  1693. if (!($object instanceof DB_DataObject)) {
  1694. return "(unknown)";
  1695. }
  1696. $arr = $object->toArray();
  1697. $fields = [];
  1698. foreach ($arr as $k => $v) {
  1699. if (is_object($v)) {
  1700. $fields[] = "$k='".get_class($v)."'";
  1701. } else {
  1702. $fields[] = "$k='$v'";
  1703. }
  1704. }
  1705. $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
  1706. return $objstring;
  1707. }
  1708. function common_valid_http_url($url, $secure=false)
  1709. {
  1710. if (empty($url)) {
  1711. return false;
  1712. }
  1713. // If $secure is true, only allow https URLs to pass
  1714. // (if false, we use '?' in 'https?' to say the 's' is optional)
  1715. $regex = $secure ? '/^https$/' : '/^https?$/';
  1716. return filter_var($url, FILTER_VALIDATE_URL)
  1717. && preg_match($regex, parse_url($url, PHP_URL_SCHEME));
  1718. }
  1719. function common_valid_tag($tag)
  1720. {
  1721. if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
  1722. return (Validate::email($matches[1]) ||
  1723. preg_match('/^([\w-\.]+)$/', $matches[1]));
  1724. }
  1725. return false;
  1726. }
  1727. /**
  1728. * Determine if given domain or address literal is valid
  1729. * eg for use in JIDs and URLs. Does not check if the domain
  1730. * exists!
  1731. *
  1732. * @param string $domain
  1733. * @return boolean valid or not
  1734. */
  1735. function common_valid_domain($domain)
  1736. {
  1737. $octet = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])";
  1738. $ipv4 = "(?:$octet(?:\.$octet){3})";
  1739. if (preg_match("/^$ipv4$/u", $domain)) {
  1740. return true;
  1741. }
  1742. $group = "(?:[0-9a-f]{1,4})";
  1743. $ipv6 = "(?:\[($group(?::$group){0,7})?(::)?($group(?::$group){0,7})?\])"; // http://tools.ietf.org/html/rfc3513#section-2.2
  1744. if (preg_match("/^$ipv6$/ui", $domain, $matches)) {
  1745. $before = explode(":", $matches[1]);
  1746. $zeroes = $matches[2];
  1747. $after = explode(":", $matches[3]);
  1748. if ($zeroes) {
  1749. $min = 0;
  1750. $max = 7;
  1751. } else {
  1752. $min = 1;
  1753. $max = 8;
  1754. }
  1755. $explicit = count($before) + count($after);
  1756. if ($explicit < $min || $explicit > $max) {
  1757. return false;
  1758. }
  1759. return true;
  1760. }
  1761. try {
  1762. require_once "Net/IDNA2.php";
  1763. $idn = Net_IDNA2::getInstance();
  1764. $domain = $idn->encode($domain);
  1765. } catch (Exception $e) {
  1766. return false;
  1767. }
  1768. $subdomain = "(?:[a-z0-9][a-z0-9-]*)"; // @fixme
  1769. $fqdn = "(?:$subdomain(?:\.$subdomain)*\.?)";
  1770. return preg_match("/^$fqdn$/ui", $domain);
  1771. }
  1772. /* Following functions are copied from MediaWiki GlobalFunctions.php
  1773. * and written by Evan Prodromou. */
  1774. function common_accept_to_prefs($accept, $def = '*/*')
  1775. {
  1776. // No arg means accept anything (per HTTP spec)
  1777. if (!$accept) {
  1778. return [$def => 1];
  1779. }
  1780. $prefs = [];
  1781. $parts = explode(',', $accept);
  1782. foreach ($parts as $part) {
  1783. // FIXME: doesn't deal with params like 'text/html; level=1'
  1784. @list($value, $qpart) = explode(';', trim($part));
  1785. $match = [];
  1786. if (!isset($qpart)) {
  1787. $prefs[$value] = 1;
  1788. } elseif (preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
  1789. $prefs[$value] = $match[1];
  1790. }
  1791. }
  1792. return $prefs;
  1793. }
  1794. // Match by our supported file extensions
  1795. function common_supported_filename_to_mime($filename)
  1796. {
  1797. // Accept a filename and take out the extension
  1798. if (strpos($filename, '.') === false) {
  1799. throw new ServerException(sprintf('No extension on filename: %1$s', _ve($filename)));
  1800. }
  1801. $fileext = substr(strrchr($filename, '.'), 1);
  1802. return common_supported_ext_to_mime($fileext);
  1803. }
  1804. function common_supported_ext_to_mime($fileext)
  1805. {
  1806. $supported = common_config('attachments', 'supported');
  1807. if ($supported === true) {
  1808. // FIXME: Should we just accept the extension straight off when supported === true?
  1809. throw new UnknownExtensionMimeException($fileext);
  1810. }
  1811. foreach ($supported as $type => $ext) {
  1812. if ($ext === $fileext) {
  1813. return $type;
  1814. }
  1815. }
  1816. throw new ServerException('Unsupported file extension');
  1817. }
  1818. // Match by our supported mime types
  1819. function common_supported_mime_to_ext($mimetype)
  1820. {
  1821. $supported = common_config('attachments', 'supported');
  1822. if (is_array($supported)) {
  1823. foreach ($supported as $type => $ext) {
  1824. if ($mimetype === $type) {
  1825. return $ext;
  1826. }
  1827. }
  1828. }
  1829. throw new UnknownMimeExtensionException($mimetype);
  1830. }
  1831. // The MIME "media" is the part before the slash (video in video/webm)
  1832. function common_get_mime_media($type)
  1833. {
  1834. $tmp = explode('/', $type);
  1835. return strtolower($tmp[0]);
  1836. }
  1837. // Get only the mimetype and not additional info (separated from bare mime with semi-colon)
  1838. function common_bare_mime($mimetype)
  1839. {
  1840. $mimetype = mb_strtolower($mimetype);
  1841. if ($semicolon = mb_strpos($mimetype, ';')) {
  1842. $mimetype = mb_substr($mimetype, 0, $semicolon);
  1843. }
  1844. return trim($mimetype);
  1845. }
  1846. function common_mime_type_match($type, $avail)
  1847. {
  1848. if (array_key_exists($type, $avail)) {
  1849. return $type;
  1850. } else {
  1851. $parts = explode('/', $type);
  1852. if (array_key_exists($parts[0] . '/*', $avail)) {
  1853. return $parts[0] . '/*';
  1854. } elseif (array_key_exists('*/*', $avail)) {
  1855. return '*/*';
  1856. } else {
  1857. return null;
  1858. }
  1859. }
  1860. }
  1861. function common_negotiate_type($cprefs, $sprefs)
  1862. {
  1863. $combine = [];
  1864. foreach (array_keys($sprefs) as $type) {
  1865. $parts = explode('/', $type);
  1866. if (isset($parts[1]) && $parts[1] != '*') {
  1867. $ckey = common_mime_type_match($type, $cprefs);
  1868. if ($ckey) {
  1869. $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
  1870. }
  1871. }
  1872. }
  1873. foreach (array_keys($cprefs) as $type) {
  1874. $parts = explode('/', $type);
  1875. if (isset($parts[1]) && $parts[1] != '*' && !array_key_exists($type, $sprefs)) {
  1876. $skey = common_mime_type_match($type, $sprefs);
  1877. if ($skey) {
  1878. $combine[$type] = $sprefs[$skey] * $cprefs[$type];
  1879. }
  1880. }
  1881. }
  1882. $bestq = 0;
  1883. $besttype = 'text/html';
  1884. foreach (array_keys($combine) as $type) {
  1885. if ($combine[$type] > $bestq) {
  1886. $besttype = $type;
  1887. $bestq = $combine[$type];
  1888. }
  1889. }
  1890. if ('text/html' === $besttype) {
  1891. return "text/html; charset=utf-8";
  1892. }
  1893. return $besttype;
  1894. }
  1895. function common_config($main, $sub=null)
  1896. {
  1897. global $config;
  1898. if (is_null($config)) {
  1899. throw new ServerException('common_config was invoked before config.php was read');
  1900. }
  1901. if (is_null($sub)) {
  1902. // Return the config category array
  1903. return array_key_exists($main, $config) ? $config[$main] : [];
  1904. }
  1905. // Return the config value
  1906. return (array_key_exists($main, $config) &&
  1907. array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
  1908. }
  1909. function common_config_set($main, $sub, $value)
  1910. {
  1911. global $config;
  1912. if (!array_key_exists($main, $config)) {
  1913. $config[$main] = [];
  1914. }
  1915. $config[$main][$sub] = $value;
  1916. }
  1917. function common_config_append($main, $sub, $value)
  1918. {
  1919. global $config;
  1920. if (!array_key_exists($main, $config)) {
  1921. $config[$main] = [];
  1922. }
  1923. if (!array_key_exists($sub, $config[$main])) {
  1924. $config[$main][$sub] = [];
  1925. }
  1926. if (!is_array($config[$main][$sub])) {
  1927. $config[$main][$sub] = [$config[$main][$sub]];
  1928. }
  1929. array_push($config[$main][$sub], $value);
  1930. }
  1931. /**
  1932. * Pull arguments from a GET/POST/REQUEST array with first-level input checks:
  1933. * strips "magic quotes" slashes if necessary, and kills invalid UTF-8 strings.
  1934. *
  1935. * @param array $from
  1936. * @return array
  1937. */
  1938. function common_copy_args($from)
  1939. {
  1940. $to = [];
  1941. $strip = get_magic_quotes_gpc();
  1942. foreach ($from as $k => $v) {
  1943. if (is_array($v)) {
  1944. $to[$k] = common_copy_args($v);
  1945. } else {
  1946. if ($strip) {
  1947. $v = stripslashes($v);
  1948. }
  1949. $to[$k] = strval(common_validate_utf8($v));
  1950. }
  1951. }
  1952. return $to;
  1953. }
  1954. /**
  1955. * Neutralise the evil effects of magic_quotes_gpc in the current request.
  1956. * This is used before handing a request off to OAuthRequest::from_request.
  1957. * @fixme Doesn't consider vars other than _POST and _GET?
  1958. * @fixme Can't be undone and could corrupt data if run twice.
  1959. */
  1960. function common_remove_magic_from_request()
  1961. {
  1962. if (get_magic_quotes_gpc()) {
  1963. $_POST=array_map('stripslashes', $_POST);
  1964. $_GET=array_map('stripslashes', $_GET);
  1965. }
  1966. }
  1967. function common_user_uri(&$user)
  1968. {
  1969. return common_local_url(
  1970. 'userbyid',
  1971. ['id' => $user->id],
  1972. null,
  1973. null,
  1974. false,
  1975. true
  1976. );
  1977. }
  1978. /**
  1979. * Generates cryptographically secure pseudo-random strings out of a allowed chars string
  1980. *
  1981. * @param $bits int strength of the confirmation code
  1982. * @param $codechars allowed characters to be used in the confirmation code, by default we use 36 upper case
  1983. * alphanums and remove lookalikes (0, O, 1, I) = 32 chars = 5 bits to make it easy for the user to type in
  1984. * @return string confirmation_code of length $bits/5
  1985. */
  1986. function common_confirmation_code($bits, $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ')
  1987. {
  1988. $chars = ceil($bits/5);
  1989. $codechars_length = strlen($codechars)-1;
  1990. $code = '';
  1991. for ($i = 0; $i < $chars; ++$i) {
  1992. $random_char = $codechars[random_int(0, $codechars_length)];
  1993. $code .= $random_char;
  1994. }
  1995. return $code;
  1996. }
  1997. // convert markup to HTML
  1998. function common_markup_to_html($c, $args=null)
  1999. {
  2000. if ($c === null) {
  2001. return '';
  2002. }
  2003. if (is_null($args)) {
  2004. $args = [];
  2005. }
  2006. // XXX: not very efficient
  2007. foreach ($args as $name => $value) {
  2008. $c = preg_replace('/%%arg.'.$name.'%%/', $value, $c);
  2009. }
  2010. $c = preg_replace_callback('/%%user.(\w+)%%/', function ($m) {
  2011. return common_user_property($m[1]);
  2012. }, $c);
  2013. $c = preg_replace_callback('/%%action.(\w+)%%/', function ($m) {
  2014. return common_local_url($m[1]);
  2015. }, $c);
  2016. $c = preg_replace_callback('/%%doc.(\w+)%%/', function ($m) {
  2017. return common_local_url('doc', ['title'=>$m[1]]);
  2018. }, $c);
  2019. $c = preg_replace_callback('/%%(\w+).(\w+)%%/', function ($m) {
  2020. return common_config($m[1], $m[2]);
  2021. }, $c);
  2022. return \Michelf\Markdown::defaultTransform($c);
  2023. }
  2024. function common_user_property($property)
  2025. {
  2026. $profile = Profile::current();
  2027. if (empty($profile)) {
  2028. return null;
  2029. }
  2030. switch ($property) {
  2031. case 'profileurl':
  2032. case 'nickname':
  2033. case 'fullname':
  2034. case 'location':
  2035. case 'bio':
  2036. return $profile->$property;
  2037. break;
  2038. case 'avatar':
  2039. try {
  2040. return $profile->getAvatar(AVATAR_STREAM_SIZE);
  2041. } catch (Exception $e) {
  2042. return null;
  2043. }
  2044. break;
  2045. case 'bestname':
  2046. return $profile->getBestName();
  2047. break;
  2048. default:
  2049. return null;
  2050. }
  2051. }
  2052. function common_profile_uri($profile)
  2053. {
  2054. $uri = null;
  2055. if (!empty($profile)) {
  2056. if (Event::handle('StartCommonProfileURI', [$profile, &$uri])) {
  2057. $user = User::getKV('id', $profile->id);
  2058. if ($user instanceof User) {
  2059. $uri = $user->getUri();
  2060. } // FIXME: might be a remote profile, by this function name, I would guess it would be fine to call this
  2061. // On the other hand, there's Profile->getUri
  2062. Event::handle('EndCommonProfileURI', [$profile, &$uri]);
  2063. }
  2064. }
  2065. // XXX: this is a very bad profile!
  2066. return $uri;
  2067. }
  2068. function common_canonical_sms($sms)
  2069. {
  2070. // strip non-digits
  2071. preg_replace('/\D/', '', $sms);
  2072. return $sms;
  2073. }
  2074. function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
  2075. {
  2076. switch ($errno) {
  2077. case E_ERROR:
  2078. case E_COMPILE_ERROR:
  2079. case E_CORE_ERROR:
  2080. case E_USER_ERROR:
  2081. case E_PARSE:
  2082. case E_RECOVERABLE_ERROR:
  2083. common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
  2084. die();
  2085. break;
  2086. case E_WARNING:
  2087. case E_COMPILE_WARNING:
  2088. case E_CORE_WARNING:
  2089. case E_USER_WARNING:
  2090. common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
  2091. break;
  2092. case E_NOTICE:
  2093. case E_USER_NOTICE:
  2094. common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
  2095. break;
  2096. case E_STRICT:
  2097. case E_DEPRECATED:
  2098. case E_USER_DEPRECATED:
  2099. // XXX: config variable to log this stuff, too
  2100. break;
  2101. default:
  2102. common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
  2103. die();
  2104. break;
  2105. }
  2106. // FIXME: show error page if we're on the Web
  2107. /* Don't execute PHP internal error handler */
  2108. return true;
  2109. }
  2110. function common_session_token()
  2111. {
  2112. common_ensure_session();
  2113. if (!array_key_exists('token', $_SESSION)) {
  2114. $_SESSION['token'] = common_random_hexstr(64);
  2115. }
  2116. return $_SESSION['token'];
  2117. }
  2118. function common_license_terms($uri)
  2119. {
  2120. if (preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
  2121. return explode('-', $matches[1]);
  2122. }
  2123. return [$uri];
  2124. }
  2125. function common_compatible_license($from, $to)
  2126. {
  2127. $from_terms = common_license_terms($from);
  2128. // public domain and cc-by are compatible with everything
  2129. if (count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
  2130. return true;
  2131. }
  2132. $to_terms = common_license_terms($to);
  2133. // sa is compatible across versions. IANAL
  2134. if (in_array('sa', $from_terms) || in_array('sa', $to_terms)) {
  2135. return count(array_diff($from_terms, $to_terms)) == 0;
  2136. }
  2137. // XXX: better compatibility check needed here!
  2138. // Should at least normalise URIs
  2139. return ($from == $to);
  2140. }
  2141. /**
  2142. * returns a quoted table name
  2143. */
  2144. function common_database_tablename($tablename)
  2145. {
  2146. $schema = Schema::get();
  2147. // table prefixes could be added here later
  2148. return $schema->quoteIdentifier($tablename);
  2149. }
  2150. /**
  2151. * Shorten a URL with the current user's configured shortening service,
  2152. * or ur1.ca if configured, or not at all if no shortening is set up.
  2153. *
  2154. * @param string $long_url original URL
  2155. * @param User $user to specify a particular user's options
  2156. * @param boolean $force Force shortening (used when notice is too long)
  2157. * @return string may return the original URL if shortening failed
  2158. *
  2159. * @fixme provide a way to specify a particular shortener
  2160. */
  2161. function common_shorten_url($long_url, User $user=null, $force = false)
  2162. {
  2163. $long_url = trim($long_url);
  2164. $user = common_current_user();
  2165. $maxUrlLength = User_urlshortener_prefs::maxUrlLength($user);
  2166. // $force forces shortening even if it's not strictly needed
  2167. // I doubt URL shortening is ever 'strictly' needed. - ESP
  2168. if (($maxUrlLength == -1 || mb_strlen($long_url) < $maxUrlLength) && !$force) {
  2169. return $long_url;
  2170. }
  2171. $shortenerName = User_urlshortener_prefs::urlShorteningService($user);
  2172. if (Event::handle(
  2173. 'StartShortenUrl',
  2174. [$long_url, $shortenerName, &$shortenedUrl]
  2175. )) {
  2176. if ($shortenerName == 'internal') {
  2177. try {
  2178. $f = File::processNew($long_url);
  2179. $shortenedUrl = common_local_url('redirecturl', ['id' => $f->id]);
  2180. if ((mb_strlen($shortenedUrl) < mb_strlen($long_url)) || $force) {
  2181. return $shortenedUrl;
  2182. } else {
  2183. return $long_url;
  2184. }
  2185. } catch (ServerException $e) {
  2186. return $long_url;
  2187. }
  2188. } else {
  2189. return $long_url;
  2190. }
  2191. } else {
  2192. //URL was shortened, so return the result
  2193. return trim($shortenedUrl);
  2194. }
  2195. }
  2196. /**
  2197. * @return mixed array($proxy, $ip) for web requests; proxy may be null
  2198. * null if not a web request
  2199. *
  2200. * @fixme X-Forwarded-For can be chained by multiple proxies;
  2201. we should parse the list and provide a cleaner array
  2202. * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
  2203. * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
  2204. * use function to get exact request headers from Apache if possible.
  2205. */
  2206. function common_client_ip()
  2207. {
  2208. if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
  2209. return null;
  2210. }
  2211. if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
  2212. if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
  2213. $proxy = $_SERVER['HTTP_CLIENT_IP'];
  2214. } else {
  2215. $proxy = $_SERVER['REMOTE_ADDR'];
  2216. }
  2217. $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  2218. } else {
  2219. $proxy = null;
  2220. if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
  2221. $ip = $_SERVER['HTTP_CLIENT_IP'];
  2222. } else {
  2223. $ip = $_SERVER['REMOTE_ADDR'];
  2224. }
  2225. }
  2226. return [$proxy, $ip];
  2227. }
  2228. function common_url_to_nickname($url)
  2229. {
  2230. static $bad = ['query', 'user', 'password', 'port', 'fragment'];
  2231. $parts = parse_url($url);
  2232. // If any of these parts exist, this won't work
  2233. foreach ($bad as $badpart) {
  2234. if (array_key_exists($badpart, $parts)) {
  2235. return null;
  2236. }
  2237. }
  2238. // We just have host and/or path
  2239. // If it's just a host...
  2240. if (array_key_exists('host', $parts) &&
  2241. (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0)) {
  2242. $hostparts = explode('.', $parts['host']);
  2243. // Try to catch common idiom of nickname.service.tld
  2244. if ((count($hostparts) > 2) &&
  2245. (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
  2246. (strcmp($hostparts[0], 'www') != 0)) {
  2247. return common_nicknamize($hostparts[0]);
  2248. } else {
  2249. // Do the whole hostname
  2250. return common_nicknamize($parts['host']);
  2251. }
  2252. } else {
  2253. if (array_key_exists('path', $parts)) {
  2254. // Strip starting, ending slashes
  2255. $path = preg_replace('@/$@', '', $parts['path']);
  2256. $path = preg_replace('@^/@', '', $path);
  2257. $path = basename($path);
  2258. // Hack for MediaWiki user pages, in the form:
  2259. // http://example.com/wiki/User:Myname
  2260. // ('User' may be localized.)
  2261. if (strpos($path, ':')) {
  2262. $parts = array_filter(explode(':', $path));
  2263. $path = $parts[count($parts) - 1];
  2264. }
  2265. if ($path) {
  2266. return common_nicknamize($path);
  2267. }
  2268. }
  2269. }
  2270. return null;
  2271. }
  2272. function common_nicknamize($str)
  2273. {
  2274. try {
  2275. return Nickname::normalize($str);
  2276. } catch (NicknameException $e) {
  2277. return null;
  2278. }
  2279. }
  2280. function common_perf_counter($key, $val=null)
  2281. {
  2282. global $_perfCounters;
  2283. if (isset($_perfCounters)) {
  2284. if (common_config('site', 'logperf')) {
  2285. if (array_key_exists($key, $_perfCounters)) {
  2286. $_perfCounters[$key][] = $val;
  2287. } else {
  2288. $_perfCounters[$key] = [$val];
  2289. }
  2290. if (common_config('site', 'logperf_detail')) {
  2291. common_log(LOG_DEBUG, "PERF COUNTER HIT: $key $val");
  2292. }
  2293. }
  2294. }
  2295. }
  2296. function common_log_perf_counters()
  2297. {
  2298. if (common_config('site', 'logperf')) {
  2299. global $_startCpuTime, $_perfCounters;
  2300. if (isset($_startCpuTime)) {
  2301. $end_cpu_time = hrtime(true);
  2302. $diff = round(($end_cpu_time - $_startCpuTime) / 1000000);
  2303. common_log(LOG_DEBUG, "PERF runtime: ${diff}ms");
  2304. }
  2305. $counters = $_perfCounters;
  2306. ksort($counters);
  2307. foreach ($counters as $key => $values) {
  2308. $count = count($values);
  2309. $unique = count(array_unique($values));
  2310. common_log(LOG_DEBUG, "PERF COUNTER: $key $count ($unique unique)");
  2311. }
  2312. }
  2313. }
  2314. function common_is_email($str)
  2315. {
  2316. return (strpos($str, '@') !== false);
  2317. }
  2318. function common_init_stats()
  2319. {
  2320. global $_mem, $_ts;
  2321. $_mem = memory_get_usage(true);
  2322. $_ts = microtime(true);
  2323. }
  2324. function common_log_delta($comment=null)
  2325. {
  2326. global $_mem, $_ts;
  2327. $mold = $_mem;
  2328. $told = $_ts;
  2329. $_mem = memory_get_usage(true);
  2330. $_ts = microtime(true);
  2331. $mtotal = $_mem - $mold;
  2332. $ttotal = $_ts - $told;
  2333. if (empty($comment)) {
  2334. $comment = 'Delta';
  2335. }
  2336. common_debug(sprintf("%s: %d %d", $comment, $mtotal, round($ttotal * 1000000)));
  2337. }
  2338. function common_strip_html($html, $trim=true, $save_whitespace=false)
  2339. {
  2340. // first replace <br /> with \n
  2341. $html = preg_replace('/\<(\s*)?br(\s*)?\/?(\s*)?\>/i', "\n", $html);
  2342. // then, unless explicitly avoided, remove excessive whitespace
  2343. if (!$save_whitespace) {
  2344. $html = preg_replace('/\s+/', ' ', $html);
  2345. }
  2346. $text = html_entity_decode(strip_tags($html), ENT_QUOTES, 'UTF-8');
  2347. return $trim ? trim($text) : $text;
  2348. }
  2349. /**
  2350. * An internal helper function that converts a $size from php.ini for
  2351. * file size limit from the 'human-readable' shorthand into a int. If
  2352. * $size is empty (the value is not set in php.ini), returns a default
  2353. * value (5000000)
  2354. *
  2355. * @param string|bool $size
  2356. * @return int the php.ini upload limit in machine-readable format
  2357. */
  2358. function _common_size_str_to_int($size): int
  2359. {
  2360. // `memory_limit` can be -1 and `post_max_size` can be 0
  2361. // for unlimited. Consistency.
  2362. if (empty($size) || $size === '-1' || $size === '0') {
  2363. return 5000000;
  2364. }
  2365. $suffix = substr($size, -1);
  2366. $size = substr($size, 0, -1);
  2367. switch (strtoupper($suffix)) {
  2368. case 'P':
  2369. $size *= 1024;
  2370. // no break
  2371. case 'T':
  2372. $size *= 1024;
  2373. // no break
  2374. case 'G':
  2375. $size *= 1024;
  2376. // no break
  2377. case 'M':
  2378. $size *= 1024;
  2379. // no break
  2380. case 'K':
  2381. $size *= 1024;
  2382. break;
  2383. }
  2384. return $size;
  2385. }
  2386. /**
  2387. * Uses `_common_size_str_to_int()` to find the smallest value for uploads in php.ini
  2388. *
  2389. * @return int
  2390. */
  2391. function common_get_preferred_php_upload_limit(): int
  2392. {
  2393. return min(
  2394. _common_size_str_to_int(ini_get('post_max_size')),
  2395. _common_size_str_to_int(ini_get('upload_max_filesize')),
  2396. _common_size_str_to_int(ini_get('memory_limit'))
  2397. );
  2398. }
  2399. /**
  2400. * Include $filepath in the response, for viewing and downloading.
  2401. *
  2402. * @throws ServerException
  2403. */
  2404. function common_send_file(string $filepath, string $mimetype, string $filename, string $disposition = 'inline'): void
  2405. {
  2406. if (is_string(common_config('site', 'x-static-delivery'))) {
  2407. $tmp = explode(INSTALLDIR, $filepath);
  2408. $relative_path = end($tmp);
  2409. common_debug("Using Static Delivery with header: '" .
  2410. common_config('site', 'x-static-delivery') . ": {$relative_path}'");
  2411. header(common_config('site', 'x-static-delivery') . ": {$relative_path}");
  2412. } else {
  2413. header("Content-Description: File Transfer");
  2414. header("Content-Type: {$mimetype}");
  2415. header("Content-Disposition: {$disposition}; filename=\"{$filename}\"");
  2416. header('Expires: 0');
  2417. header('Content-Transfer-Encoding: binary');
  2418. $filesize = filesize($filepath);
  2419. if (file_exists($filepath)) {
  2420. http_response_code(200);
  2421. header("Content-Length: {$filesize}");
  2422. // header('Cache-Control: private, no-transform, no-store, must-revalidate');
  2423. $ret = @readfile($filepath);
  2424. } elseif ($ret === false) {
  2425. http_response_code(404);
  2426. common_log(LOG_ERR, "Couldn't read file at {$filepath}.");
  2427. } elseif ($ret !== $filesize) {
  2428. http_response_code(500);
  2429. common_log(LOG_ERR, "The lengths of the file as recorded on the DB (or on disk) for the file " .
  2430. "{$filepath} differ from what was sent to the user ({$filesize} vs {$ret}).");
  2431. }
  2432. }
  2433. }
  2434. function html_sprintf()
  2435. {
  2436. $args = func_get_args();
  2437. for ($i=1; $i<count($args); $i++) {
  2438. $args[$i] = htmlspecialchars($args[$i]);
  2439. }
  2440. return call_user_func_array('sprintf', $args);
  2441. }
  2442. function _ve($var)
  2443. {
  2444. return var_export($var, true);
  2445. }