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.
 
 
 
 
 
 

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