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.
 
 
 
 
 
 

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