Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

boot.php 52KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942
  1. <?php
  2. require_once('include/config.php');
  3. require_once('include/network.php');
  4. require_once('include/plugin.php');
  5. require_once('include/text.php');
  6. require_once('include/datetime.php');
  7. require_once('include/pgettext.php');
  8. require_once('include/nav.php');
  9. require_once('include/cache.php');
  10. require_once('library/Mobile_Detect/Mobile_Detect.php');
  11. require_once('include/features.php');
  12. require_once('include/identity.php');
  13. require_once('update.php');
  14. require_once('include/dbstructure.php');
  15. define ( 'FRIENDICA_PLATFORM', 'Friendica');
  16. define ( 'FRIENDICA_CODENAME', 'Lily of the valley');
  17. define ( 'FRIENDICA_VERSION', '3.4.3-dev' );
  18. define ( 'DFRN_PROTOCOL_VERSION', '2.23' );
  19. define ( 'DB_UPDATE_VERSION', 1191 );
  20. define ( 'EOL', "<br />\r\n" );
  21. define ( 'ATOM_TIME', 'Y-m-d\TH:i:s\Z' );
  22. /**
  23. *
  24. * Image storage quality. Lower numbers save space at cost of image detail.
  25. * For ease of upgrade, please do not change here. Change jpeg quality with
  26. * $a->config['system']['jpeg_quality'] = n;
  27. * in .htconfig.php, where n is netween 1 and 100, and with very poor results
  28. * below about 50
  29. *
  30. */
  31. define ( 'JPEG_QUALITY', 100 );
  32. /**
  33. * $a->config['system']['png_quality'] from 0 (uncompressed) to 9
  34. */
  35. define ( 'PNG_QUALITY', 8 );
  36. /**
  37. *
  38. * An alternate way of limiting picture upload sizes. Specify the maximum pixel
  39. * length that pictures are allowed to be (for non-square pictures, it will apply
  40. * to the longest side). Pictures longer than this length will be resized to be
  41. * this length (on the longest side, the other side will be scaled appropriately).
  42. * Modify this value using
  43. *
  44. * $a->config['system']['max_image_length'] = n;
  45. *
  46. * in .htconfig.php
  47. *
  48. * If you don't want to set a maximum length, set to -1. The default value is
  49. * defined by 'MAX_IMAGE_LENGTH' below.
  50. *
  51. */
  52. define ( 'MAX_IMAGE_LENGTH', -1 );
  53. /**
  54. * Not yet used
  55. */
  56. define ( 'DEFAULT_DB_ENGINE', 'MyISAM' );
  57. /**
  58. * SSL redirection policies
  59. */
  60. define ( 'SSL_POLICY_NONE', 0 );
  61. define ( 'SSL_POLICY_FULL', 1 );
  62. define ( 'SSL_POLICY_SELFSIGN', 2 );
  63. /**
  64. * log levels
  65. */
  66. define ( 'LOGGER_NORMAL', 0 );
  67. define ( 'LOGGER_TRACE', 1 );
  68. define ( 'LOGGER_DEBUG', 2 );
  69. define ( 'LOGGER_DATA', 3 );
  70. define ( 'LOGGER_ALL', 4 );
  71. /**
  72. * cache levels
  73. */
  74. define ( 'CACHE_MONTH', 0 );
  75. define ( 'CACHE_WEEK', 1 );
  76. define ( 'CACHE_DAY', 2 );
  77. define ( 'CACHE_HOUR', 3 );
  78. /**
  79. * registration policies
  80. */
  81. define ( 'REGISTER_CLOSED', 0 );
  82. define ( 'REGISTER_APPROVE', 1 );
  83. define ( 'REGISTER_OPEN', 2 );
  84. /**
  85. * relationship types
  86. */
  87. define ( 'CONTACT_IS_FOLLOWER', 1);
  88. define ( 'CONTACT_IS_SHARING', 2);
  89. define ( 'CONTACT_IS_FRIEND', 3);
  90. /**
  91. * DB update return values
  92. */
  93. define ( 'UPDATE_SUCCESS', 0);
  94. define ( 'UPDATE_FAILED', 1);
  95. /**
  96. *
  97. * page/profile types
  98. *
  99. * PAGE_NORMAL is a typical personal profile account
  100. * PAGE_SOAPBOX automatically approves all friend requests as CONTACT_IS_SHARING, (readonly)
  101. * PAGE_COMMUNITY automatically approves all friend requests as CONTACT_IS_SHARING, but with
  102. * write access to wall and comments (no email and not included in page owner's ACL lists)
  103. * PAGE_FREELOVE automatically approves all friend requests as full friends (CONTACT_IS_FRIEND).
  104. *
  105. */
  106. define ( 'PAGE_NORMAL', 0 );
  107. define ( 'PAGE_SOAPBOX', 1 );
  108. define ( 'PAGE_COMMUNITY', 2 );
  109. define ( 'PAGE_FREELOVE', 3 );
  110. define ( 'PAGE_BLOG', 4 );
  111. define ( 'PAGE_PRVGROUP', 5 );
  112. // Type of the community page
  113. define ( 'CP_NO_COMMUNITY_PAGE', -1 );
  114. define ( 'CP_USERS_ON_SERVER', 0 );
  115. define ( 'CP_GLOBAL_COMMUNITY', 1 );
  116. /**
  117. * Network and protocol family types
  118. */
  119. define ( 'NETWORK_DFRN', 'dfrn'); // Friendica, Mistpark, other DFRN implementations
  120. define ( 'NETWORK_ZOT', 'zot!'); // Zot!
  121. define ( 'NETWORK_OSTATUS', 'stat'); // status.net, identi.ca, GNU-social, other OStatus implementations
  122. define ( 'NETWORK_FEED', 'feed'); // RSS/Atom feeds with no known "post/notify" protocol
  123. define ( 'NETWORK_DIASPORA', 'dspr'); // Diaspora
  124. define ( 'NETWORK_MAIL', 'mail'); // IMAP/POP
  125. define ( 'NETWORK_MAIL2', 'mai2'); // extended IMAP/POP
  126. define ( 'NETWORK_FACEBOOK', 'face'); // Facebook API
  127. define ( 'NETWORK_LINKEDIN', 'lnkd'); // LinkedIn
  128. define ( 'NETWORK_XMPP', 'xmpp'); // XMPP
  129. define ( 'NETWORK_MYSPACE', 'mysp'); // MySpace
  130. define ( 'NETWORK_GPLUS', 'goog'); // Google+
  131. define ( 'NETWORK_PUMPIO', 'pump'); // pump.io
  132. define ( 'NETWORK_TWITTER', 'twit'); // Twitter
  133. define ( 'NETWORK_DIASPORA2', 'dspc'); // Diaspora connector
  134. define ( 'NETWORK_STATUSNET', 'stac'); // Statusnet connector
  135. define ( 'NETWORK_APPNET', 'apdn'); // app.net
  136. define ( 'NETWORK_NEWS', 'nntp'); // Network News Transfer Protocol
  137. define ( 'NETWORK_ICALENDAR', 'ical'); // iCalendar
  138. define ( 'NETWORK_PHANTOM', 'unkn'); // Place holder
  139. /**
  140. * These numbers are used in stored permissions
  141. * and existing allocations MUST NEVER BE CHANGED
  142. * OR RE-ASSIGNED! You may only add to them.
  143. */
  144. $netgroup_ids = array(
  145. NETWORK_DFRN => (-1),
  146. NETWORK_ZOT => (-2),
  147. NETWORK_OSTATUS => (-3),
  148. NETWORK_FEED => (-4),
  149. NETWORK_DIASPORA => (-5),
  150. NETWORK_MAIL => (-6),
  151. NETWORK_MAIL2 => (-7),
  152. NETWORK_FACEBOOK => (-8),
  153. NETWORK_LINKEDIN => (-9),
  154. NETWORK_XMPP => (-10),
  155. NETWORK_MYSPACE => (-11),
  156. NETWORK_GPLUS => (-12),
  157. NETWORK_PUMPIO => (-13),
  158. NETWORK_TWITTER => (-14),
  159. NETWORK_DIASPORA2 => (-15),
  160. NETWORK_STATUSNET => (-16),
  161. NETWORK_APPNET => (-17),
  162. NETWORK_NEWS => (-18),
  163. NETWORK_ICALENDAR => (-19),
  164. NETWORK_PHANTOM => (-127),
  165. );
  166. /**
  167. * Maximum number of "people who like (or don't like) this" that we will list by name
  168. */
  169. define ( 'MAX_LIKERS', 75);
  170. /**
  171. * Communication timeout
  172. */
  173. define ( 'ZCURL_TIMEOUT' , (-1));
  174. /**
  175. * email notification options
  176. */
  177. define ( 'NOTIFY_INTRO', 0x0001 );
  178. define ( 'NOTIFY_CONFIRM', 0x0002 );
  179. define ( 'NOTIFY_WALL', 0x0004 );
  180. define ( 'NOTIFY_COMMENT', 0x0008 );
  181. define ( 'NOTIFY_MAIL', 0x0010 );
  182. define ( 'NOTIFY_SUGGEST', 0x0020 );
  183. define ( 'NOTIFY_PROFILE', 0x0040 );
  184. define ( 'NOTIFY_TAGSELF', 0x0080 );
  185. define ( 'NOTIFY_TAGSHARE', 0x0100 );
  186. define ( 'NOTIFY_POKE', 0x0200 );
  187. define ( 'NOTIFY_SHARE', 0x0400 );
  188. define ( 'NOTIFY_SYSTEM', 0x8000 );
  189. /**
  190. * Tag/term types
  191. */
  192. define ( 'TERM_UNKNOWN', 0 );
  193. define ( 'TERM_HASHTAG', 1 );
  194. define ( 'TERM_MENTION', 2 );
  195. define ( 'TERM_CATEGORY', 3 );
  196. define ( 'TERM_PCATEGORY', 4 );
  197. define ( 'TERM_FILE', 5 );
  198. define ( 'TERM_SAVEDSEARCH', 6 );
  199. define ( 'TERM_CONVERSATION', 7 );
  200. define ( 'TERM_OBJ_POST', 1 );
  201. define ( 'TERM_OBJ_PHOTO', 2 );
  202. /**
  203. * various namespaces we may need to parse
  204. */
  205. define ( 'NAMESPACE_ZOT', 'http://purl.org/zot' );
  206. define ( 'NAMESPACE_DFRN' , 'http://purl.org/macgirvin/dfrn/1.0' );
  207. define ( 'NAMESPACE_THREAD' , 'http://purl.org/syndication/thread/1.0' );
  208. define ( 'NAMESPACE_TOMB' , 'http://purl.org/atompub/tombstones/1.0' );
  209. define ( 'NAMESPACE_ACTIVITY', 'http://activitystrea.ms/spec/1.0/' );
  210. define ( 'NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/' );
  211. define ( 'NAMESPACE_MEDIA', 'http://purl.org/syndication/atommedia' );
  212. define ( 'NAMESPACE_SALMON_ME', 'http://salmon-protocol.org/ns/magic-env' );
  213. define ( 'NAMESPACE_OSTATUSSUB', 'http://ostatus.org/schema/1.0/subscribe' );
  214. define ( 'NAMESPACE_GEORSS', 'http://www.georss.org/georss' );
  215. define ( 'NAMESPACE_POCO', 'http://portablecontacts.net/spec/1.0' );
  216. define ( 'NAMESPACE_FEED', 'http://schemas.google.com/g/2010#updates-from' );
  217. define ( 'NAMESPACE_OSTATUS', 'http://ostatus.org/schema/1.0' );
  218. define ( 'NAMESPACE_STATUSNET', 'http://status.net/schema/api/1/' );
  219. define ( 'NAMESPACE_ATOM1', 'http://www.w3.org/2005/Atom' );
  220. /**
  221. * activity stream defines
  222. */
  223. define ( 'ACTIVITY_LIKE', NAMESPACE_ACTIVITY_SCHEMA . 'like' );
  224. define ( 'ACTIVITY_DISLIKE', NAMESPACE_DFRN . '/dislike' );
  225. define ( 'ACTIVITY_ATTEND', NAMESPACE_ZOT . '/activity/attendyes' );
  226. define ( 'ACTIVITY_ATTENDNO', NAMESPACE_ZOT . '/activity/attendno' );
  227. define ( 'ACTIVITY_ATTENDMAYBE', NAMESPACE_ZOT . '/activity/attendmaybe' );
  228. define ( 'ACTIVITY_OBJ_HEART', NAMESPACE_DFRN . '/heart' );
  229. define ( 'ACTIVITY_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'make-friend' );
  230. define ( 'ACTIVITY_REQ_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'request-friend' );
  231. define ( 'ACTIVITY_UNFRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'remove-friend' );
  232. define ( 'ACTIVITY_FOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'follow' );
  233. define ( 'ACTIVITY_UNFOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'stop-following' );
  234. define ( 'ACTIVITY_JOIN', NAMESPACE_ACTIVITY_SCHEMA . 'join' );
  235. define ( 'ACTIVITY_POST', NAMESPACE_ACTIVITY_SCHEMA . 'post' );
  236. define ( 'ACTIVITY_UPDATE', NAMESPACE_ACTIVITY_SCHEMA . 'update' );
  237. define ( 'ACTIVITY_TAG', NAMESPACE_ACTIVITY_SCHEMA . 'tag' );
  238. define ( 'ACTIVITY_FAVORITE', NAMESPACE_ACTIVITY_SCHEMA . 'favorite' );
  239. define ( 'ACTIVITY_SHARE', NAMESPACE_ACTIVITY_SCHEMA . 'share' );
  240. define ( 'ACTIVITY_POKE', NAMESPACE_ZOT . '/activity/poke' );
  241. define ( 'ACTIVITY_MOOD', NAMESPACE_ZOT . '/activity/mood' );
  242. define ( 'ACTIVITY_OBJ_BOOKMARK', NAMESPACE_ACTIVITY_SCHEMA . 'bookmark' );
  243. define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
  244. define ( 'ACTIVITY_OBJ_NOTE', NAMESPACE_ACTIVITY_SCHEMA . 'note' );
  245. define ( 'ACTIVITY_OBJ_PERSON', NAMESPACE_ACTIVITY_SCHEMA . 'person' );
  246. define ( 'ACTIVITY_OBJ_IMAGE', NAMESPACE_ACTIVITY_SCHEMA . 'image' );
  247. define ( 'ACTIVITY_OBJ_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
  248. define ( 'ACTIVITY_OBJ_VIDEO', NAMESPACE_ACTIVITY_SCHEMA . 'video' );
  249. define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
  250. define ( 'ACTIVITY_OBJ_ALBUM', NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
  251. define ( 'ACTIVITY_OBJ_EVENT', NAMESPACE_ACTIVITY_SCHEMA . 'event' );
  252. define ( 'ACTIVITY_OBJ_GROUP', NAMESPACE_ACTIVITY_SCHEMA . 'group' );
  253. define ( 'ACTIVITY_OBJ_TAGTERM', NAMESPACE_DFRN . '/tagterm' );
  254. define ( 'ACTIVITY_OBJ_PROFILE', NAMESPACE_DFRN . '/profile' );
  255. define ( 'ACTIVITY_OBJ_QUESTION', 'http://activityschema.org/object/question' );
  256. /**
  257. * item weight for query ordering
  258. */
  259. define ( 'GRAVITY_PARENT', 0);
  260. define ( 'GRAVITY_LIKE', 3);
  261. define ( 'GRAVITY_COMMENT', 6);
  262. /**
  263. *
  264. * Reverse the effect of magic_quotes_gpc if it is enabled.
  265. * Please disable magic_quotes_gpc so we don't have to do this.
  266. * See http://php.net/manual/en/security.magicquotes.disabling.php
  267. *
  268. */
  269. function startup() {
  270. error_reporting(E_ERROR | E_WARNING | E_PARSE);
  271. set_time_limit(0);
  272. // This has to be quite large to deal with embedded private photos
  273. ini_set('pcre.backtrack_limit', 500000);
  274. if (get_magic_quotes_gpc()) {
  275. $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
  276. while (list($key, $val) = each($process)) {
  277. foreach ($val as $k => $v) {
  278. unset($process[$key][$k]);
  279. if (is_array($v)) {
  280. $process[$key][stripslashes($k)] = $v;
  281. $process[] = &$process[$key][stripslashes($k)];
  282. } else {
  283. $process[$key][stripslashes($k)] = stripslashes($v);
  284. }
  285. }
  286. }
  287. unset($process);
  288. }
  289. }
  290. /**
  291. *
  292. * class: App
  293. *
  294. * Our main application structure for the life of this page
  295. * Primarily deals with the URL that got us here
  296. * and tries to make some sense of it, and
  297. * stores our page contents and config storage
  298. * and anything else that might need to be passed around
  299. * before we spit the page out.
  300. *
  301. */
  302. if(! class_exists('App')) {
  303. class App {
  304. public $module_loaded = false;
  305. public $query_string;
  306. public $config;
  307. public $page;
  308. public $profile;
  309. public $profile_uid;
  310. public $user;
  311. public $cid;
  312. public $contact;
  313. public $contacts;
  314. public $page_contact;
  315. public $content;
  316. public $data = array();
  317. public $error = false;
  318. public $cmd;
  319. public $argv;
  320. public $argc;
  321. public $module;
  322. public $pager;
  323. public $strings;
  324. public $path;
  325. public $hooks;
  326. public $timezone;
  327. public $interactive = true;
  328. public $plugins;
  329. public $apps = array();
  330. public $identities;
  331. public $is_mobile;
  332. public $is_tablet;
  333. public $is_friendica_app;
  334. public $performance = array();
  335. public $nav_sel;
  336. public $category;
  337. // Allow themes to control internal parameters
  338. // by changing App values in theme.php
  339. public $sourcename = '';
  340. public $videowidth = 425;
  341. public $videoheight = 350;
  342. public $force_max_items = 0;
  343. public $theme_thread_allow = true;
  344. public $theme_events_in_profile = true;
  345. // An array for all theme-controllable parameters
  346. // Mostly unimplemented yet. Only options 'stylesheet' and
  347. // beyond are used.
  348. public $theme = array(
  349. 'sourcename' => '',
  350. 'videowidth' => 425,
  351. 'videoheight' => 350,
  352. 'force_max_items' => 0,
  353. 'thread_allow' => true,
  354. 'stylesheet' => '',
  355. 'template_engine' => 'smarty3',
  356. );
  357. // array of registered template engines ('name'=>'class name')
  358. public $template_engines = array();
  359. // array of instanced template engines ('name'=>'instance')
  360. public $template_engine_instance = array();
  361. private $ldelim = array(
  362. 'internal' => '',
  363. 'smarty3' => '{{'
  364. );
  365. private $rdelim = array(
  366. 'internal' => '',
  367. 'smarty3' => '}}'
  368. );
  369. private $scheme;
  370. private $hostname;
  371. private $baseurl;
  372. private $db;
  373. private $curl_code;
  374. private $curl_content_type;
  375. private $curl_headers;
  376. private $cached_profile_image;
  377. private $cached_profile_picdate;
  378. function __construct() {
  379. global $default_timezone;
  380. $hostname = "";
  381. if (file_exists(".htpreconfig.php"))
  382. @include(".htpreconfig.php");
  383. $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
  384. date_default_timezone_set($this->timezone);
  385. $this->performance["start"] = microtime(true);
  386. $this->performance["database"] = 0;
  387. $this->performance["network"] = 0;
  388. $this->performance["file"] = 0;
  389. $this->performance["rendering"] = 0;
  390. $this->performance["parser"] = 0;
  391. $this->performance["marktime"] = 0;
  392. $this->performance["markstart"] = microtime(true);
  393. $this->config = array();
  394. $this->page = array();
  395. $this->pager= array();
  396. $this->query_string = '';
  397. startup();
  398. set_include_path(
  399. 'include' . PATH_SEPARATOR
  400. . 'library' . PATH_SEPARATOR
  401. . 'library/phpsec' . PATH_SEPARATOR
  402. . 'library/langdet' . PATH_SEPARATOR
  403. . '.' );
  404. $this->scheme = 'http';
  405. if(x($_SERVER,'HTTPS') && $_SERVER['HTTPS'])
  406. $this->scheme = 'https';
  407. elseif(x($_SERVER,'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443))
  408. $this->scheme = 'https';
  409. if(x($_SERVER,'SERVER_NAME')) {
  410. $this->hostname = $_SERVER['SERVER_NAME'];
  411. // See bug 437 - this didn't work so disabling it
  412. //if(stristr($this->hostname,'xn--')) {
  413. // PHP or webserver may have converted idn to punycode, so
  414. // convert punycode back to utf-8
  415. // require_once('library/simplepie/idn/idna_convert.class.php');
  416. // $x = new idna_convert();
  417. // $this->hostname = $x->decode($_SERVER['SERVER_NAME']);
  418. //}
  419. if(x($_SERVER,'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443)
  420. $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
  421. /**
  422. * Figure out if we are running at the top of a domain
  423. * or in a sub-directory and adjust accordingly
  424. */
  425. $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
  426. if(isset($path) && strlen($path) && ($path != $this->path))
  427. $this->path = $path;
  428. }
  429. if ($hostname != "")
  430. $this->hostname = $hostname;
  431. if (is_array($_SERVER["argv"]) && $_SERVER["argc"]>1 && substr(end($_SERVER["argv"]), 0, 4)=="http" ) {
  432. $this->set_baseurl(array_pop($_SERVER["argv"]) );
  433. $_SERVER["argc"] --;
  434. }
  435. #set_include_path("include/$this->hostname" . PATH_SEPARATOR . get_include_path());
  436. if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,9) === "pagename=") {
  437. $this->query_string = substr($_SERVER['QUERY_STRING'],9);
  438. // removing trailing / - maybe a nginx problem
  439. if (substr($this->query_string, 0, 1) == "/")
  440. $this->query_string = substr($this->query_string, 1);
  441. } elseif((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
  442. $this->query_string = substr($_SERVER['QUERY_STRING'],2);
  443. // removing trailing / - maybe a nginx problem
  444. if (substr($this->query_string, 0, 1) == "/")
  445. $this->query_string = substr($this->query_string, 1);
  446. }
  447. if (x($_GET,'pagename'))
  448. $this->cmd = trim($_GET['pagename'],'/\\');
  449. elseif (x($_GET,'q'))
  450. $this->cmd = trim($_GET['q'],'/\\');
  451. // fix query_string
  452. $this->query_string = str_replace($this->cmd."&",$this->cmd."?", $this->query_string);
  453. // unix style "homedir"
  454. if(substr($this->cmd,0,1) === '~')
  455. $this->cmd = 'profile/' . substr($this->cmd,1);
  456. // Diaspora style profile url
  457. if(substr($this->cmd,0,2) === 'u/')
  458. $this->cmd = 'profile/' . substr($this->cmd,2);
  459. /**
  460. *
  461. * Break the URL path into C style argc/argv style arguments for our
  462. * modules. Given "http://example.com/module/arg1/arg2", $this->argc
  463. * will be 3 (integer) and $this->argv will contain:
  464. * [0] => 'module'
  465. * [1] => 'arg1'
  466. * [2] => 'arg2'
  467. *
  468. *
  469. * There will always be one argument. If provided a naked domain
  470. * URL, $this->argv[0] is set to "home".
  471. *
  472. */
  473. $this->argv = explode('/',$this->cmd);
  474. $this->argc = count($this->argv);
  475. if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
  476. $this->module = str_replace(".", "_", $this->argv[0]);
  477. $this->module = str_replace("-", "_", $this->module);
  478. }
  479. else {
  480. $this->argc = 1;
  481. $this->argv = array('home');
  482. $this->module = 'home';
  483. }
  484. /**
  485. * See if there is any page number information, and initialise
  486. * pagination
  487. */
  488. $this->pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
  489. $this->pager['itemspage'] = 50;
  490. $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
  491. if($this->pager['start'] < 0)
  492. $this->pager['start'] = 0;
  493. $this->pager['total'] = 0;
  494. /**
  495. * Detect mobile devices
  496. */
  497. $mobile_detect = new Mobile_Detect();
  498. $this->is_mobile = $mobile_detect->isMobile();
  499. $this->is_tablet = $mobile_detect->isTablet();
  500. // Friendica-Client
  501. $this->is_friendica_app = ($_SERVER['HTTP_USER_AGENT'] == "Apache-HttpClient/UNAVAILABLE (java 1.4)");
  502. /**
  503. * register template engines
  504. */
  505. $dc = get_declared_classes();
  506. foreach ($dc as $k) {
  507. if (in_array("ITemplateEngine", class_implements($k))){
  508. $this->register_template_engine($k);
  509. }
  510. }
  511. }
  512. function get_basepath() {
  513. $basepath = get_config("system", "basepath");
  514. if ($basepath == "")
  515. $basepath = $_SERVER["DOCUMENT_ROOT"];
  516. if ($basepath == "")
  517. $basepath = $_SERVER["PWD"];
  518. return($basepath);
  519. }
  520. function get_scheme() {
  521. return($this->scheme);
  522. }
  523. function get_baseurl($ssl = false) {
  524. $scheme = $this->scheme;
  525. if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
  526. if(intval($this->config['system']['ssl_policy']) === intval(SSL_POLICY_FULL))
  527. $scheme = 'https';
  528. // Basically, we have $ssl = true on any links which can only be seen by a logged in user
  529. // (and also the login link). Anything seen by an outsider will have it turned off.
  530. if($this->config['system']['ssl_policy'] == SSL_POLICY_SELFSIGN) {
  531. if($ssl)
  532. $scheme = 'https';
  533. else
  534. $scheme = 'http';
  535. }
  536. }
  537. if (get_config('config','hostname') != "")
  538. $this->hostname = get_config('config','hostname');
  539. $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
  540. return $this->baseurl;
  541. }
  542. function set_baseurl($url) {
  543. $parsed = @parse_url($url);
  544. $this->baseurl = $url;
  545. if($parsed) {
  546. $this->scheme = $parsed['scheme'];
  547. $hostname = $parsed['host'];
  548. if(x($parsed,'port'))
  549. $hostname .= ':' . $parsed['port'];
  550. if(x($parsed,'path'))
  551. $this->path = trim($parsed['path'],'\\/');
  552. if (file_exists(".htpreconfig.php"))
  553. @include(".htpreconfig.php");
  554. if (get_config('config','hostname') != "")
  555. $this->hostname = get_config('config','hostname');
  556. if (!isset($this->hostname) OR ($this->hostname == ""))
  557. $this->hostname = $hostname;
  558. }
  559. }
  560. function get_hostname() {
  561. if (get_config('config','hostname') != "")
  562. $this->hostname = get_config('config','hostname');
  563. return $this->hostname;
  564. }
  565. function set_hostname($h) {
  566. $this->hostname = $h;
  567. }
  568. function set_path($p) {
  569. $this->path = trim(trim($p),'/');
  570. }
  571. function get_path() {
  572. return $this->path;
  573. }
  574. function set_pager_total($n) {
  575. $this->pager['total'] = intval($n);
  576. }
  577. function set_pager_itemspage($n) {
  578. $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
  579. $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
  580. }
  581. function set_pager_page($n) {
  582. $this->pager['page'] = $n;
  583. $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
  584. }
  585. function init_pagehead() {
  586. $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
  587. if($interval < 10000)
  588. $interval = 40000;
  589. // compose the page title from the sitename and the
  590. // current module called
  591. if (!$this->module=='')
  592. {
  593. $this->page['title'] = $this->config['sitename'].' ('.$this->module.')';
  594. } else {
  595. $this->page['title'] = $this->config['sitename'];
  596. }
  597. /* put the head template at the beginning of page['htmlhead']
  598. * since the code added by the modules frequently depends on it
  599. * being first
  600. */
  601. if(!isset($this->page['htmlhead']))
  602. $this->page['htmlhead'] = '';
  603. // If we're using Smarty, then doing replace_macros() will replace
  604. // any unrecognized variables with a blank string. Since we delay
  605. // replacing $stylesheet until later, we need to replace it now
  606. // with another variable name
  607. if($this->theme['template_engine'] === 'smarty3')
  608. $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
  609. else
  610. $stylesheet = '$stylesheet';
  611. $shortcut_icon = get_config("system", "shortcut_icon");
  612. if ($shortcut_icon == "")
  613. $shortcut_icon = $this->get_baseurl()."/images/friendica-32.png";
  614. $touch_icon = get_config("system", "touch_icon");
  615. if ($touch_icon == "")
  616. $touch_icon = $this->get_baseurl()."/images/friendica-128.png";
  617. $tpl = get_markup_template('head.tpl');
  618. $this->page['htmlhead'] = replace_macros($tpl,array(
  619. '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
  620. '$local_user' => local_user(),
  621. '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
  622. '$delitem' => t('Delete this item?'),
  623. '$comment' => t('Comment'),
  624. '$showmore' => t('show more'),
  625. '$showfewer' => t('show fewer'),
  626. '$update_interval' => $interval,
  627. '$shortcut_icon' => $shortcut_icon,
  628. '$touch_icon' => $touch_icon,
  629. '$stylesheet' => $stylesheet
  630. )) . $this->page['htmlhead'];
  631. }
  632. function init_page_end() {
  633. if(!isset($this->page['end']))
  634. $this->page['end'] = '';
  635. $tpl = get_markup_template('end.tpl');
  636. $this->page['end'] = replace_macros($tpl,array(
  637. '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
  638. )) . $this->page['end'];
  639. }
  640. function set_curl_code($code) {
  641. $this->curl_code = $code;
  642. }
  643. function get_curl_code() {
  644. return $this->curl_code;
  645. }
  646. function set_curl_content_type($content_type) {
  647. $this->curl_content_type = $content_type;
  648. }
  649. function get_curl_content_type() {
  650. return $this->curl_content_type;
  651. }
  652. function set_curl_headers($headers) {
  653. $this->curl_headers = $headers;
  654. }
  655. function get_curl_headers() {
  656. return $this->curl_headers;
  657. }
  658. function get_cached_avatar_image($avatar_image){
  659. if($this->cached_profile_image[$avatar_image])
  660. return $this->cached_profile_image[$avatar_image];
  661. $path_parts = explode("/",$avatar_image);
  662. $common_filename = $path_parts[count($path_parts)-1];
  663. if($this->cached_profile_picdate[$common_filename]){
  664. $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
  665. } else {
  666. $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like '%%/%s'",
  667. $common_filename);
  668. if(! count($r)){
  669. $this->cached_profile_image[$avatar_image] = $avatar_image;
  670. } else {
  671. $this->cached_profile_picdate[$common_filename] = "?rev=".urlencode($r[0]['picdate']);
  672. $this->cached_profile_image[$avatar_image] = $avatar_image.$this->cached_profile_picdate[$common_filename];
  673. }
  674. }
  675. return $this->cached_profile_image[$avatar_image];
  676. }
  677. /**
  678. * register template engine class
  679. * if $name is "", is used class static property $class::$name
  680. * @param string $class
  681. * @param string $name
  682. */
  683. function register_template_engine($class, $name = '') {
  684. if ($name===""){
  685. $v = get_class_vars( $class );
  686. if(x($v,"name")) $name = $v['name'];
  687. }
  688. if ($name===""){
  689. echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
  690. killme();
  691. }
  692. $this->template_engines[$name] = $class;
  693. }
  694. /**
  695. * return template engine instance. If $name is not defined,
  696. * return engine defined by theme, or default
  697. *
  698. * @param strin $name Template engine name
  699. * @return object Template Engine instance
  700. */
  701. function template_engine($name = ''){
  702. if ($name!=="") {
  703. $template_engine = $name;
  704. } else {
  705. $template_engine = 'smarty3';
  706. if (x($this->theme, 'template_engine')) {
  707. $template_engine = $this->theme['template_engine'];
  708. }
  709. }
  710. if (isset($this->template_engines[$template_engine])){
  711. if(isset($this->template_engine_instance[$template_engine])){
  712. return $this->template_engine_instance[$template_engine];
  713. } else {
  714. $class = $this->template_engines[$template_engine];
  715. $obj = new $class;
  716. $this->template_engine_instance[$template_engine] = $obj;
  717. return $obj;
  718. }
  719. }
  720. echo "template engine <tt>$template_engine</tt> is not registered!\n"; killme();
  721. }
  722. function get_template_engine() {
  723. return $this->theme['template_engine'];
  724. }
  725. function set_template_engine($engine = 'smarty3') {
  726. $this->theme['template_engine'] = $engine;
  727. /*
  728. $this->theme['template_engine'] = 'smarty3';
  729. switch($engine) {
  730. case 'smarty3':
  731. if(is_writable('view/smarty3/'))
  732. $this->theme['template_engine'] = 'smarty3';
  733. break;
  734. default:
  735. break;
  736. }
  737. */
  738. }
  739. function get_template_ldelim($engine = 'smarty3') {
  740. return $this->ldelim[$engine];
  741. }
  742. function get_template_rdelim($engine = 'smarty3') {
  743. return $this->rdelim[$engine];
  744. }
  745. function save_timestamp($stamp, $value) {
  746. $duration = (float)(microtime(true)-$stamp);
  747. $this->performance[$value] += (float)$duration;
  748. $this->performance["marktime"] += (float)$duration;
  749. }
  750. function mark_timestamp($mark) {
  751. //$this->performance["markstart"] -= microtime(true) - $this->performance["marktime"];
  752. $this->performance["markstart"] = microtime(true) - $this->performance["markstart"] - $this->performance["marktime"];
  753. }
  754. function get_useragent() {
  755. return(FRIENDICA_PLATFORM." '".FRIENDICA_CODENAME."' ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION."; ".$this->get_baseurl());
  756. }
  757. function is_friendica_app() {
  758. return($this->is_friendica_app);
  759. }
  760. }
  761. }
  762. // retrieve the App structure
  763. // useful in functions which require it but don't get it passed to them
  764. if(! function_exists('get_app')) {
  765. function get_app() {
  766. global $a;
  767. return $a;
  768. }
  769. };
  770. // Multi-purpose function to check variable state.
  771. // Usage: x($var) or $x($array,'key')
  772. // returns false if variable/key is not set
  773. // if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
  774. // e.g. x('') or x(0) returns 0;
  775. if(! function_exists('x')) {
  776. function x($s,$k = NULL) {
  777. if($k != NULL) {
  778. if((is_array($s)) && (array_key_exists($k,$s))) {
  779. if($s[$k])
  780. return (int) 1;
  781. return (int) 0;
  782. }
  783. return false;
  784. }
  785. else {
  786. if(isset($s)) {
  787. if($s) {
  788. return (int) 1;
  789. }
  790. return (int) 0;
  791. }
  792. return false;
  793. }
  794. }
  795. }
  796. // called from db initialisation if db is dead.
  797. if(! function_exists('system_unavailable')) {
  798. function system_unavailable() {
  799. include('system_unavailable.php');
  800. system_down();
  801. killme();
  802. }
  803. }
  804. function clean_urls() {
  805. global $a;
  806. // if($a->config['system']['clean_urls'])
  807. return true;
  808. // return false;
  809. }
  810. function z_path() {
  811. global $a;
  812. $base = $a->get_baseurl();
  813. if(! clean_urls())
  814. $base .= '/?q=';
  815. return $base;
  816. }
  817. function z_root() {
  818. global $a;
  819. return $a->get_baseurl();
  820. }
  821. function absurl($path) {
  822. if(strpos($path,'/') === 0)
  823. return z_path() . $path;
  824. return $path;
  825. }
  826. function is_ajax() {
  827. return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
  828. }
  829. function check_db() {
  830. $build = get_config('system','build');
  831. if(! x($build)) {
  832. set_config('system','build',DB_UPDATE_VERSION);
  833. $build = DB_UPDATE_VERSION;
  834. }
  835. if($build != DB_UPDATE_VERSION)
  836. proc_run('php', 'include/dbupdate.php');
  837. }
  838. // Sets the base url for use in cmdline programs which don't have
  839. // $_SERVER variables
  840. if(! function_exists('check_url')) {
  841. function check_url(&$a) {
  842. $url = get_config('system','url');
  843. // if the url isn't set or the stored url is radically different
  844. // than the currently visited url, store the current value accordingly.
  845. // "Radically different" ignores common variations such as http vs https
  846. // and www.example.com vs example.com.
  847. // We will only change the url to an ip address if there is no existing setting
  848. if(! x($url))
  849. $url = set_config('system','url',$a->get_baseurl());
  850. if((! link_compare($url,$a->get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
  851. $url = set_config('system','url',$a->get_baseurl());
  852. return;
  853. }
  854. }
  855. // Automatic database updates
  856. if(! function_exists('update_db')) {
  857. function update_db(&$a) {
  858. $build = get_config('system','build');
  859. if(! x($build))
  860. $build = set_config('system','build',DB_UPDATE_VERSION);
  861. if($build != DB_UPDATE_VERSION) {
  862. $stored = intval($build);
  863. $current = intval(DB_UPDATE_VERSION);
  864. if($stored < $current) {
  865. load_config('database');
  866. // We're reporting a different version than what is currently installed.
  867. // Run any existing update scripts to bring the database up to current.
  868. // make sure that boot.php and update.php are the same release, we might be
  869. // updating right this very second and the correct version of the update.php
  870. // file may not be here yet. This can happen on a very busy site.
  871. if(DB_UPDATE_VERSION == UPDATE_VERSION) {
  872. // Compare the current structure with the defined structure
  873. $t = get_config('database','dbupdate_'.DB_UPDATE_VERSION);
  874. if($t !== false)
  875. return;
  876. set_config('database','dbupdate_'.DB_UPDATE_VERSION, time());
  877. // run old update routine (wich could modify the schema and
  878. // conflits with new routine)
  879. for ($x = $stored; $x < NEW_UPDATE_ROUTINE_VERSION; $x++) {
  880. $r = run_update_function($x);
  881. if (!$r) break;
  882. }
  883. if ($stored < NEW_UPDATE_ROUTINE_VERSION) $stored = NEW_UPDATE_ROUTINE_VERSION;
  884. // run new update routine
  885. // it update the structure in one call
  886. $retval = update_structure(false, true);
  887. if($retval) {
  888. update_fail(
  889. DB_UPDATE_VERSION,
  890. $retval
  891. );
  892. return;
  893. } else {
  894. set_config('database','dbupdate_'.DB_UPDATE_VERSION, 'success');
  895. }
  896. // run any left update_nnnn functions in update.php
  897. for($x = $stored; $x < $current; $x ++) {
  898. $r = run_update_function($x);
  899. if (!$r) break;
  900. }
  901. }
  902. }
  903. }
  904. return;
  905. }
  906. }
  907. if(!function_exists('run_update_function')){
  908. function run_update_function($x) {
  909. if(function_exists('update_' . $x)) {
  910. // There could be a lot of processes running or about to run.
  911. // We want exactly one process to run the update command.
  912. // So store the fact that we're taking responsibility
  913. // after first checking to see if somebody else already has.
  914. // If the update fails or times-out completely you may need to
  915. // delete the config entry to try again.
  916. $t = get_config('database','update_' . $x);
  917. if($t !== false)
  918. return false;
  919. set_config('database','update_' . $x, time());
  920. // call the specific update
  921. $func = 'update_' . $x;
  922. $retval = $func();
  923. if($retval) {
  924. //send the administrator an e-mail
  925. update_fail(
  926. $x,
  927. sprintf(t('Update %s failed. See error logs.'), $x)
  928. );
  929. return false;
  930. } else {
  931. set_config('database','update_' . $x, 'success');
  932. set_config('system','build', $x + 1);
  933. return true;
  934. }
  935. } else {
  936. set_config('database','update_' . $x, 'success');
  937. set_config('system','build', $x + 1);
  938. return true;
  939. }
  940. return true;
  941. }
  942. }
  943. if(! function_exists('check_plugins')) {
  944. function check_plugins(&$a) {
  945. /**
  946. *
  947. * Synchronise plugins:
  948. *
  949. * $a->config['system']['addon'] contains a comma-separated list of names
  950. * of plugins/addons which are used on this system.
  951. * Go through the database list of already installed addons, and if we have
  952. * an entry, but it isn't in the config list, call the uninstall procedure
  953. * and mark it uninstalled in the database (for now we'll remove it).
  954. * Then go through the config list and if we have a plugin that isn't installed,
  955. * call the install procedure and add it to the database.
  956. *
  957. */
  958. $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
  959. if(count($r))
  960. $installed = $r;
  961. else
  962. $installed = array();
  963. $plugins = get_config('system','addon');
  964. $plugins_arr = array();
  965. if($plugins)
  966. $plugins_arr = explode(',',str_replace(' ', '',$plugins));
  967. $a->plugins = $plugins_arr;
  968. $installed_arr = array();
  969. if(count($installed)) {
  970. foreach($installed as $i) {
  971. if(! in_array($i['name'],$plugins_arr)) {
  972. uninstall_plugin($i['name']);
  973. }
  974. else {
  975. $installed_arr[] = $i['name'];
  976. }
  977. }
  978. }
  979. if(count($plugins_arr)) {
  980. foreach($plugins_arr as $p) {
  981. if(! in_array($p,$installed_arr)) {
  982. install_plugin($p);
  983. }
  984. }
  985. }
  986. load_hooks();
  987. return;
  988. }
  989. }
  990. function get_guid($size=16, $prefix = "") {
  991. if ($prefix == "") {
  992. $a = get_app();
  993. $prefix = hash("crc32", $a->get_hostname());
  994. }
  995. while (strlen($prefix) < ($size - 13))
  996. $prefix .= mt_rand();
  997. if ($size >= 24) {
  998. $prefix = substr($prefix, 0, $size - 22);
  999. return(str_replace(".", "", uniqid($prefix, true)));
  1000. } else {
  1001. $prefix = substr($prefix, 0, $size - 13);
  1002. return(uniqid($prefix));
  1003. }
  1004. }
  1005. // wrapper for adding a login box. If $register == true provide a registration
  1006. // link. This will most always depend on the value of $a->config['register_policy'].
  1007. // returns the complete html for inserting into the page
  1008. if(! function_exists('login')) {
  1009. function login($register = false, $hiddens=false) {
  1010. $a = get_app();
  1011. $o = "";
  1012. $reg = false;
  1013. if ($register) {
  1014. $reg = array(
  1015. 'title' => t('Create a New Account'),
  1016. 'desc' => t('Register')
  1017. );
  1018. }
  1019. $noid = get_config('system','no_openid');
  1020. $dest_url = $a->get_baseurl(true) . '/' . $a->query_string;
  1021. if(local_user()) {
  1022. $tpl = get_markup_template("logout.tpl");
  1023. }
  1024. else {
  1025. $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
  1026. '$baseurl' => $a->get_baseurl(true)
  1027. ));
  1028. $tpl = get_markup_template("login.tpl");
  1029. $_SESSION['return_url'] = $a->query_string;
  1030. $a->module = 'login';
  1031. }
  1032. $o .= replace_macros($tpl, array(
  1033. '$dest_url' => $dest_url,
  1034. '$logout' => t('Logout'),
  1035. '$login' => t('Login'),
  1036. '$lname' => array('username', t('Nickname or Email address: ') , '', ''),
  1037. '$lpassword' => array('password', t('Password: '), '', ''),
  1038. '$lremember' => array('remember', t('Remember me'), 0, ''),
  1039. '$openid' => !$noid,
  1040. '$lopenid' => array('openid_url', t('Or login using OpenID: '),'',''),
  1041. '$hiddens' => $hiddens,
  1042. '$register' => $reg,
  1043. '$lostpass' => t('Forgot your password?'),
  1044. '$lostlink' => t('Password Reset'),
  1045. '$tostitle' => t('Website Terms of Service'),
  1046. '$toslink' => t('terms of service'),
  1047. '$privacytitle' => t('Website Privacy Policy'),
  1048. '$privacylink' => t('privacy policy'),
  1049. ));
  1050. call_hooks('login_hook',$o);
  1051. return $o;
  1052. }
  1053. }
  1054. // Used to end the current process, after saving session state.
  1055. if(! function_exists('killme')) {
  1056. function killme() {
  1057. session_write_close();
  1058. exit;
  1059. }
  1060. }
  1061. // redirect to another URL and terminate this process.
  1062. if(! function_exists('goaway')) {
  1063. function goaway($s) {
  1064. header("Location: $s");
  1065. killme();
  1066. }
  1067. }
  1068. // Returns the uid of locally logged in user or false.
  1069. if(! function_exists('local_user')) {
  1070. function local_user() {
  1071. if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
  1072. return intval($_SESSION['uid']);
  1073. return false;
  1074. }
  1075. }
  1076. // Returns contact id of authenticated site visitor or false
  1077. if(! function_exists('remote_user')) {
  1078. function remote_user() {
  1079. if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
  1080. return intval($_SESSION['visitor_id']);
  1081. return false;
  1082. }
  1083. }
  1084. // contents of $s are displayed prominently on the page the next time
  1085. // a page is loaded. Usually used for errors or alerts.
  1086. if(! function_exists('notice')) {
  1087. /**
  1088. * Show an error message to user.
  1089. *
  1090. * This function save text in session, to be shown to the user at next page load
  1091. *
  1092. * @param string $s - Text of notice
  1093. */
  1094. function notice($s) {
  1095. $a = get_app();
  1096. if(! x($_SESSION,'sysmsg')) $_SESSION['sysmsg'] = array();
  1097. if($a->interactive)
  1098. $_SESSION['sysmsg'][] = $s;
  1099. }
  1100. }
  1101. if(! function_exists('info')) {
  1102. /**
  1103. * Show an info message to user.
  1104. *
  1105. * This function save text in session, to be shown to the user at next page load
  1106. *
  1107. * @param string $s - Text of notice
  1108. */
  1109. function info($s) {
  1110. $a = get_app();
  1111. if (local_user() AND get_pconfig(local_user(),'system','ignore_info'))
  1112. return;
  1113. if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
  1114. if($a->interactive)
  1115. $_SESSION['sysmsg_info'][] = $s;
  1116. }
  1117. }
  1118. // wrapper around config to limit the text length of an incoming message
  1119. if(! function_exists('get_max_import_size')) {
  1120. function get_max_import_size() {
  1121. global $a;
  1122. return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
  1123. }
  1124. }
  1125. /**
  1126. *
  1127. * Wrap calls to proc_close(proc_open()) and call hook
  1128. * so plugins can take part in process :)
  1129. *
  1130. * args:
  1131. * $cmd program to run
  1132. * next args are passed as $cmd command line
  1133. *
  1134. * e.g.: proc_run("ls","-la","/tmp");
  1135. *
  1136. * $cmd and string args are surrounded with ""
  1137. */
  1138. if(! function_exists('proc_run')) {
  1139. function proc_run($cmd){
  1140. $a = get_app();
  1141. $args = func_get_args();
  1142. $newargs = array();
  1143. if(! count($args))
  1144. return;
  1145. // expand any arrays
  1146. foreach($args as $arg) {
  1147. if(is_array($arg)) {
  1148. foreach($arg as $n) {
  1149. $newargs[] = $n;
  1150. }
  1151. }
  1152. else
  1153. $newargs[] = $arg;
  1154. }
  1155. $args = $newargs;
  1156. $arr = array('args' => $args, 'run_cmd' => true);
  1157. call_hooks("proc_run", $arr);
  1158. if(! $arr['run_cmd'])
  1159. return;
  1160. if(count($args) && $args[0] === 'php') {
  1161. if (get_config("system", "worker")) {
  1162. $argv = $args;
  1163. array_shift($argv);
  1164. $parameters = json_encode($argv);
  1165. $found = q("SELECT `id` FROM `workerqueue` WHERE `parameter` = '%s'",
  1166. dbesc($parameters));
  1167. if (!$found)
  1168. q("INSERT INTO `workerqueue` (`parameter`, `created`, `priority`)
  1169. VALUES ('%s', '%s', %d)",
  1170. dbesc($parameters),
  1171. dbesc(datetime_convert()),
  1172. intval(0));
  1173. // Should we quit and wait for the poller to be called as a cronjob?
  1174. if (get_config("system", "worker_dont_fork"))
  1175. return;
  1176. // Checking number of workers
  1177. $workers = q("SELECT COUNT(*) AS `workers` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
  1178. // Get number of allowed number of worker threads
  1179. $queues = intval(get_config("system", "worker_queues"));
  1180. if ($queues == 0)
  1181. $queues = 4;
  1182. // If there are already enough workers running, don't fork another one
  1183. if ($workers[0]["workers"] >= $queues)
  1184. return;
  1185. // Now call the poller to execute the jobs that we just added to the queue
  1186. $args = array("php", "include/poller.php", "no_cron");
  1187. }
  1188. $args[0] = ((x($a->config,'php_path')) && (strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
  1189. }
  1190. // add baseurl to args. cli scripts can't construct it
  1191. $args[] = $a->get_baseurl();
  1192. for($x = 0; $x < count($args); $x ++)
  1193. $args[$x] = escapeshellarg($args[$x]);
  1194. $cmdline = implode($args," ");
  1195. if(get_config('system','proc_windows'))
  1196. proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
  1197. else
  1198. proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
  1199. }
  1200. }
  1201. if(! function_exists('current_theme')) {
  1202. function current_theme(){
  1203. $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
  1204. $a = get_app();
  1205. $page_theme = null;
  1206. // Find the theme that belongs to the user whose stuff we are looking at
  1207. if($a->profile_uid && ($a->profile_uid != local_user())) {
  1208. $r = q("select theme from user where uid = %d limit 1",
  1209. intval($a->profile_uid)
  1210. );
  1211. if($r)
  1212. $page_theme = $r[0]['theme'];
  1213. }
  1214. // Allow folks to over-rule user themes and always use their own on their own site.
  1215. // This works only if the user is on the same server
  1216. if($page_theme && local_user() && (local_user() != $a->profile_uid)) {
  1217. if(get_pconfig(local_user(),'system','always_my_theme'))
  1218. $page_theme = null;
  1219. }
  1220. // $mobile_detect = new Mobile_Detect();
  1221. // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
  1222. $is_mobile = $a->is_mobile || $a->is_tablet;
  1223. $standard_system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
  1224. $standard_theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $standard_system_theme);
  1225. if($is_mobile) {
  1226. if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
  1227. $system_theme = $standard_system_theme;
  1228. $theme_name = $standard_theme_name;
  1229. }
  1230. else {
  1231. $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : $standard_system_theme);
  1232. $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
  1233. if($theme_name === '---') {
  1234. // user has selected to have the mobile theme be the same as the normal one
  1235. $system_theme = $standard_system_theme;
  1236. $theme_name = $standard_theme_name;
  1237. if($page_theme)
  1238. $theme_name = $page_theme;
  1239. }
  1240. }
  1241. }
  1242. else {
  1243. $system_theme = $standard_system_theme;
  1244. $theme_name = $standard_theme_name;
  1245. if($page_theme)
  1246. $theme_name = $page_theme;
  1247. }
  1248. if($theme_name &&
  1249. (file_exists('view/theme/' . $theme_name . '/style.css') ||
  1250. file_exists('view/theme/' . $theme_name . '/style.php')))
  1251. return($theme_name);
  1252. foreach($app_base_themes as $t) {
  1253. if(file_exists('view/theme/' . $t . '/style.css')||
  1254. file_exists('view/theme/' . $t . '/style.php'))
  1255. return($t);
  1256. }
  1257. $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
  1258. if(count($fallback))
  1259. return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
  1260. }
  1261. }
  1262. /*
  1263. * Return full URL to theme which is currently in effect.
  1264. * Provide a sane default if nothing is chosen or the specified theme does not exist.
  1265. */
  1266. if(! function_exists('current_theme_url')) {
  1267. function current_theme_url() {
  1268. global $a;
  1269. $t = current_theme();
  1270. $opts = (($a->profile_uid) ? '?f=&puid=' . $a->profile_uid : '');
  1271. if (file_exists('view/theme/' . $t . '/style.php'))
  1272. return($a->get_baseurl() . '/view/theme/' . $t . '/style.pcss' . $opts);
  1273. return($a->get_baseurl() . '/view/theme/' . $t . '/style.css');
  1274. }
  1275. }
  1276. if(! function_exists('feed_birthday')) {
  1277. function feed_birthday($uid,$tz) {
  1278. /**
  1279. *
  1280. * Determine the next birthday, but only if the birthday is published
  1281. * in the default profile. We _could_ also look for a private profile that the
  1282. * recipient can see, but somebody could get mad at us if they start getting
  1283. * public birthday greetings when they haven't made this info public.
  1284. *
  1285. * Assuming we are able to publish this info, we are then going to convert
  1286. * the start time from the owner's timezone to UTC.
  1287. *
  1288. * This will potentially solve the problem found with some social networks
  1289. * where birthdays are converted to the viewer's timezone and salutations from
  1290. * elsewhere in the world show up on the wrong day. We will convert it to the
  1291. * viewer's timezone also, but first we are going to convert it from the birthday
  1292. * person's timezone to GMT - so the viewer may find the birthday starting at
  1293. * 6:00PM the day before, but that will correspond to midnight to the birthday person.
  1294. *
  1295. */
  1296. $birthday = '';
  1297. if(! strlen($tz))
  1298. $tz = 'UTC';
  1299. $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
  1300. intval($uid)
  1301. );
  1302. if($p && count($p)) {
  1303. $tmp_dob = substr($p[0]['dob'],5);
  1304. if(intval($tmp_dob)) {
  1305. $y = datetime_convert($tz,$tz,'now','Y');
  1306. $bd = $y . '-' . $tmp_dob . ' 00:00';
  1307. $t_dob = strtotime($bd);
  1308. $now = strtotime(datetime_convert($tz,$tz,'now'));
  1309. if($t_dob < $now)
  1310. $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
  1311. $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
  1312. }
  1313. }
  1314. return $birthday;
  1315. }
  1316. }
  1317. if(! function_exists('is_site_admin')) {
  1318. function is_site_admin() {
  1319. $a = get_app();
  1320. $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
  1321. //if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
  1322. if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && in_array($a->user['email'], $adminlist))
  1323. return true;
  1324. return false;
  1325. }
  1326. }
  1327. if(! function_exists('load_contact_links')) {
  1328. function load_contact_links($uid) {
  1329. $a = get_app();
  1330. $ret = array();
  1331. if(! $uid || x($a->contacts,'empty'))
  1332. return;
  1333. $r = q("SELECT `id`,`network`,`url`,`thumb`, `rel` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `thumb` != ''",
  1334. intval($uid)
  1335. );
  1336. if(count($r)) {
  1337. foreach($r as $rr){
  1338. $url = normalise_link($rr['url']);
  1339. $ret[$url] = $rr;
  1340. }
  1341. } else
  1342. $ret['empty'] = true;
  1343. $a->contacts = $ret;
  1344. return;
  1345. }
  1346. }
  1347. /**
  1348. * returns querystring as string from a mapped array
  1349. *
  1350. * @param params Array
  1351. * @return string
  1352. */
  1353. function build_querystring($params, $name=null) {
  1354. $ret = "";
  1355. foreach($params as $key=>$val) {
  1356. if(is_array($val)) {
  1357. if($name==null) {
  1358. $ret .= build_querystring($val, $key);
  1359. } else {
  1360. $ret .= build_querystring($val, $name."[$key]");
  1361. }
  1362. } else {
  1363. $val = urlencode($val);
  1364. if($name!=null) {
  1365. $ret.=$name."[$key]"."=$val&";
  1366. } else {
  1367. $ret.= "$key=$val&";
  1368. }
  1369. }
  1370. }
  1371. return $ret;
  1372. }
  1373. function explode_querystring($query) {
  1374. $arg_st = strpos($query, '?');
  1375. if($arg_st !== false) {
  1376. $base = substr($query, 0, $arg_st);
  1377. $arg_st += 1;
  1378. } else {
  1379. $base = '';
  1380. $arg_st = 0;
  1381. }
  1382. $args = explode('&', substr($query, $arg_st));
  1383. foreach($args as $k=>$arg) {
  1384. if($arg === '')
  1385. unset($args[$k]);
  1386. }
  1387. $args = array_values($args);
  1388. if(!$base) {
  1389. $base = $args[0];
  1390. unset($args[0]);
  1391. $args = array_values($args);
  1392. }
  1393. return array(
  1394. 'base' => $base,
  1395. 'args' => $args,
  1396. );
  1397. }
  1398. /**
  1399. * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
  1400. *
  1401. * Taken from http://webcheatsheet.com/php/get_current_page_url.php
  1402. */
  1403. function curPageURL() {
  1404. $pageURL = 'http';
  1405. if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
  1406. $pageURL .= "://";
  1407. if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
  1408. $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
  1409. } else {
  1410. $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
  1411. }
  1412. return $pageURL;
  1413. }
  1414. function random_digits($digits) {
  1415. $rn = '';
  1416. for($i = 0; $i < $digits; $i++) {
  1417. $rn .= rand(0,9);
  1418. }
  1419. return $rn;
  1420. }
  1421. function get_server() {
  1422. $server = get_config("system", "directory");
  1423. if ($server == "")
  1424. $server = "http://dir.friendi.ca";
  1425. return($server);
  1426. }
  1427. function get_cachefile($file, $writemode = true) {
  1428. $cache = get_itemcachepath();
  1429. if ((! $cache) || (! is_dir($cache)))
  1430. return("");
  1431. $subfolder = $cache."/".substr($file, 0, 2);
  1432. $cachepath = $subfolder."/".$file;
  1433. if ($writemode) {
  1434. if (!is_dir($subfolder)) {
  1435. mkdir($subfolder);
  1436. chmod($subfolder, 0777);
  1437. }
  1438. }
  1439. return($cachepath);
  1440. }
  1441. function clear_cache($basepath = "", $path = "") {
  1442. if ($path == "") {
  1443. $basepath = get_itemcachepath();
  1444. $path = $basepath;
  1445. }
  1446. if (($path == "") OR (!is_dir($path)))
  1447. return;
  1448. if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
  1449. return;
  1450. $cachetime = (int)get_config('system','itemcache_duration');
  1451. if ($cachetime == 0)
  1452. $cachetime = 86400;
  1453. if (is_writable($path)){
  1454. if ($dh = opendir($path)) {
  1455. while (($file = readdir($dh)) !== false) {
  1456. $fullpath = $path."/".$file;
  1457. if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
  1458. clear_cache($basepath, $fullpath);
  1459. if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
  1460. unlink($fullpath);
  1461. }
  1462. closedir($dh);
  1463. }
  1464. }
  1465. }
  1466. function get_itemcachepath() {
  1467. // Checking, if the cache is deactivated
  1468. $cachetime = (int)get_config('system','itemcache_duration');
  1469. if ($cachetime < 0)
  1470. return "";
  1471. $itemcache = get_config('system','itemcache');
  1472. if (($itemcache != "") AND is_dir($itemcache) AND is_writable($itemcache))
  1473. return($itemcache);
  1474. $temppath = get_temppath();
  1475. if ($temppath != "") {
  1476. $itemcache = $temppath."/itemcache";
  1477. if(!file_exists($itemcache) && !is_dir($itemcache)) {
  1478. mkdir($itemcache);
  1479. }
  1480. if (is_dir($itemcache) AND is_writable($itemcache)) {
  1481. set_config("system", "itemcache", $itemcache);
  1482. return($itemcache);
  1483. }
  1484. }
  1485. return "";
  1486. }
  1487. function get_lockpath() {
  1488. $lockpath = get_config('system','lockpath');
  1489. if (($lockpath != "") AND is_dir($lockpath) AND is_writable($lockpath))
  1490. return($lockpath);
  1491. $temppath = get_temppath();
  1492. if ($temppath != "") {
  1493. $lockpath = $temppath."/lock";
  1494. if (!is_dir($lockpath))
  1495. mkdir($lockpath);
  1496. elseif (!is_writable($lockpath))
  1497. $lockpath = $temppath;
  1498. if (is_dir($lockpath) AND is_writable($lockpath)) {
  1499. set_config("system", "lockpath", $lockpath);
  1500. return($lockpath);
  1501. }
  1502. }
  1503. return "";
  1504. }
  1505. function get_temppath() {
  1506. $a = get_app();
  1507. $temppath = get_config("system","temppath");
  1508. if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath))
  1509. return($temppath);
  1510. $temppath = sys_get_temp_dir();
  1511. if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath)) {
  1512. $temppath .= "/".$a->get_hostname();
  1513. if (!is_dir($temppath))
  1514. mkdir($temppath);
  1515. if (is_dir($temppath) AND is_writable($temppath)) {
  1516. set_config("system", "temppath", $temppath);
  1517. return($temppath);
  1518. }
  1519. }
  1520. return("");
  1521. }
  1522. function set_template_engine(&$a, $engine = 'internal') {
  1523. // This function is no longer necessary, but keep it as a wrapper to the class method
  1524. // to avoid breaking themes again unnecessarily
  1525. $a->set_template_engine($engine);
  1526. }
  1527. if(!function_exists('exif_imagetype')) {
  1528. function exif_imagetype($file) {
  1529. $size = getimagesize($file);
  1530. return($size[2]);
  1531. }
  1532. }
  1533. function validate_include(&$file) {
  1534. $orig_file = $file;
  1535. $file = realpath($file);
  1536. if (strpos($file, getcwd()) !== 0)
  1537. return false;
  1538. $file = str_replace(getcwd()."/", "", $file, $count);
  1539. if ($count != 1)
  1540. return false;
  1541. if ($orig_file !== $file)
  1542. return false;
  1543. $valid = false;
  1544. if (strpos($file, "include/") === 0)
  1545. $valid = true;
  1546. if (strpos($file, "addon/") === 0)
  1547. $valid = true;
  1548. if (!$valid)
  1549. return false;
  1550. return true;
  1551. }