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.
 
 
 
 
 
 

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