Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
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.
 
 
 
 
 
 

2370 lines
65 KiB

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