Merge branch 'develop' into 1703-worker-splitting

This commit is contained in:
Michael Vogel 2017-03-21 17:08:07 +01:00 committed by GitHub
commit 4ebebe96fe
181 changed files with 3486 additions and 4306 deletions

309
boot.php
View file

@ -711,6 +711,7 @@ class App {
// fix query_string // fix query_string
$this->query_string = str_replace($this->cmd."&",$this->cmd."?", $this->query_string); $this->query_string = str_replace($this->cmd."&",$this->cmd."?", $this->query_string);
// unix style "homedir" // unix style "homedir"
if (substr($this->cmd,0,1) === '~') { if (substr($this->cmd,0,1) === '~') {
@ -744,7 +745,8 @@ class App {
if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) { if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
$this->module = str_replace(".", "_", $this->argv[0]); $this->module = str_replace(".", "_", $this->argv[0]);
$this->module = str_replace("-", "_", $this->module); $this->module = str_replace("-", "_", $this->module);
} else { }
else {
$this->argc = 1; $this->argc = 1;
$this->argv = array('home'); $this->argv = array('home');
$this->module = 'home'; $this->module = 'home';
@ -758,9 +760,8 @@ class App {
$this->pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1); $this->pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
$this->pager['itemspage'] = 50; $this->pager['itemspage'] = 50;
$this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage']; $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
if ($this->pager['start'] < 0) { if($this->pager['start'] < 0)
$this->pager['start'] = 0; $this->pager['start'] = 0;
}
$this->pager['total'] = 0; $this->pager['total'] = 0;
/* /*
@ -792,17 +793,14 @@ class App {
$basepath = get_config("system", "basepath"); $basepath = get_config("system", "basepath");
if ($basepath == "") { if ($basepath == "")
$basepath = dirname(__FILE__); $basepath = dirname(__FILE__);
}
if ($basepath == "") { if ($basepath == "")
$basepath = $_SERVER["DOCUMENT_ROOT"]; $basepath = $_SERVER["DOCUMENT_ROOT"];
}
if ($basepath == "") { if ($basepath == "")
$basepath = $_SERVER["PWD"]; $basepath = $_SERVER["PWD"];
}
return($basepath); return($basepath);
} }
@ -878,7 +876,7 @@ class App {
} }
if (file_exists(".htpreconfig.php")) { if (file_exists(".htpreconfig.php")) {
include(".htpreconfig.php"); @include(".htpreconfig.php");
} }
if (get_config('config', 'hostname') != '') { if (get_config('config', 'hostname') != '') {
@ -892,9 +890,8 @@ class App {
} }
function get_hostname() { function get_hostname() {
if (get_config('config','hostname') != "") { if (get_config('config','hostname') != "")
$this->hostname = get_config('config','hostname'); $this->hostname = get_config('config','hostname');
}
return $this->hostname; return $this->hostname;
} }
@ -929,17 +926,16 @@ class App {
$interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000); $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
// If the update is "deactivated" set it to the highest integer number (~24 days) // If the update is "deactivated" set it to the highest integer number (~24 days)
if ($interval < 0) { if ($interval < 0)
$interval = 2147483647; $interval = 2147483647;
}
if ($interval < 10000) { if($interval < 10000)
$interval = 40000; $interval = 40000;
}
// compose the page title from the sitename and the // compose the page title from the sitename and the
// current module called // current module called
if (!$this->module=='') { if (!$this->module=='')
{
$this->page['title'] = $this->config['sitename'].' ('.$this->module.')'; $this->page['title'] = $this->config['sitename'].' ('.$this->module.')';
} else { } else {
$this->page['title'] = $this->config['sitename']; $this->page['title'] = $this->config['sitename'];
@ -949,29 +945,25 @@ class App {
* since the code added by the modules frequently depends on it * since the code added by the modules frequently depends on it
* being first * being first
*/ */
if (!isset($this->page['htmlhead'])) { if(!isset($this->page['htmlhead']))
$this->page['htmlhead'] = ''; $this->page['htmlhead'] = '';
}
// If we're using Smarty, then doing replace_macros() will replace // If we're using Smarty, then doing replace_macros() will replace
// any unrecognized variables with a blank string. Since we delay // any unrecognized variables with a blank string. Since we delay
// replacing $stylesheet until later, we need to replace it now // replacing $stylesheet until later, we need to replace it now
// with another variable name // with another variable name
if ($this->theme['template_engine'] === 'smarty3') { if($this->theme['template_engine'] === 'smarty3')
$stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3'); $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
} else { else
$stylesheet = '$stylesheet'; $stylesheet = '$stylesheet';
}
$shortcut_icon = get_config("system", "shortcut_icon"); $shortcut_icon = get_config("system", "shortcut_icon");
if ($shortcut_icon == "") { if ($shortcut_icon == "")
$shortcut_icon = "images/friendica-32.png"; $shortcut_icon = "images/friendica-32.png";
}
$touch_icon = get_config("system", "touch_icon"); $touch_icon = get_config("system", "touch_icon");
if ($touch_icon == "") { if ($touch_icon == "")
$touch_icon = "images/friendica-128.png"; $touch_icon = "images/friendica-128.png";
}
// get data wich is needed for infinite scroll on the network page // get data wich is needed for infinite scroll on the network page
$invinite_scroll = infinite_scroll_data($this->module); $invinite_scroll = infinite_scroll_data($this->module);
@ -993,9 +985,8 @@ class App {
} }
function init_page_end() { function init_page_end() {
if (!isset($this->page['end'])) { if(!isset($this->page['end']))
$this->page['end'] = ''; $this->page['end'] = '';
}
$tpl = get_markup_template('end.tpl'); $tpl = get_markup_template('end.tpl');
$this->page['end'] = replace_macros($tpl,array( $this->page['end'] = replace_macros($tpl,array(
'$baseurl' => $this->get_baseurl() // FIXME for z_path!!!! '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
@ -1168,9 +1159,8 @@ class App {
} }
function save_timestamp($stamp, $value) { function save_timestamp($stamp, $value) {
if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) { if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler'])
return; return;
}
$duration = (float)(microtime(true)-$stamp); $duration = (float)(microtime(true)-$stamp);
@ -1252,9 +1242,8 @@ class App {
array_shift($trace); array_shift($trace);
$callstack = array(); $callstack = array();
foreach ($trace AS $func) { foreach ($trace AS $func)
$callstack[] = $func["function"]; $callstack[] = $func["function"];
}
return implode(", ", $callstack); return implode(", ", $callstack);
} }
@ -1276,34 +1265,32 @@ class App {
* @return bool Is it a known backend? * @return bool Is it a known backend?
*/ */
function is_backend() { function is_backend() {
static $backend = array( $backend = array();
"_well_known", $backend[] = "_well_known";
"api", $backend[] = "api";
"dfrn_notify", $backend[] = "dfrn_notify";
"fetch", $backend[] = "fetch";
"hcard", $backend[] = "hcard";
"hostxrd", $backend[] = "hostxrd";
"nodeinfo", $backend[] = "nodeinfo";
"noscrape", $backend[] = "noscrape";
"p", $backend[] = "p";
"poco", $backend[] = "poco";
"post", $backend[] = "post";
"proxy", $backend[] = "proxy";
"pubsub", $backend[] = "pubsub";
"pubsubhubbub", $backend[] = "pubsubhubbub";
"receive", $backend[] = "receive";
"rsd_xml", $backend[] = "rsd_xml";
"salmon", $backend[] = "salmon";
"statistics_json", $backend[] = "statistics_json";
"xrd", $backend[] = "xrd";
);
if (in_array($this->module, $backend)) { if (in_array($this->module, $backend))
return(true); return(true);
} else { else
return($this->backend); return($this->backend);
} }
}
/** /**
* @brief Checks if the maximum number of database processes is reached * @brief Checks if the maximum number of database processes is reached
@ -1315,16 +1302,14 @@ class App {
if ($this->is_backend()) { if ($this->is_backend()) {
$process = "backend"; $process = "backend";
$max_processes = get_config('system', 'max_processes_backend'); $max_processes = get_config('system', 'max_processes_backend');
if (intval($max_processes) == 0) { if (intval($max_processes) == 0)
$max_processes = 5; $max_processes = 5;
}
} else { } else {
$process = "frontend"; $process = "frontend";
$max_processes = get_config('system', 'max_processes_frontend'); $max_processes = get_config('system', 'max_processes_frontend');
if (intval($max_processes) == 0) { if (intval($max_processes) == 0)
$max_processes = 20; $max_processes = 20;
} }
}
$processlist = dbm::processlist(); $processlist = dbm::processlist();
if ($processlist["list"] != "") { if ($processlist["list"] != "") {
@ -1348,16 +1333,14 @@ class App {
if ($this->is_backend()) { if ($this->is_backend()) {
$process = "backend"; $process = "backend";
$maxsysload = intval(get_config('system', 'maxloadavg')); $maxsysload = intval(get_config('system', 'maxloadavg'));
if ($maxsysload < 1) { if ($maxsysload < 1)
$maxsysload = 50; $maxsysload = 50;
}
} else { } else {
$process = "frontend"; $process = "frontend";
$maxsysload = intval(get_config('system','maxloadavg_frontend')); $maxsysload = intval(get_config('system','maxloadavg_frontend'));
if ($maxsysload < 1) { if ($maxsysload < 1)
$maxsysload = 50; $maxsysload = 50;
} }
}
$load = current_load(); $load = current_load();
if ($load) { if ($load) {
@ -1392,17 +1375,16 @@ class App {
// add baseurl to args. cli scripts can't construct it // add baseurl to args. cli scripts can't construct it
$args[] = $this->get_baseurl(); $args[] = $this->get_baseurl();
for ($x = 0; $x < count($args); $x ++) { for($x = 0; $x < count($args); $x ++)
$args[$x] = escapeshellarg($args[$x]); $args[$x] = escapeshellarg($args[$x]);
}
$cmdline = implode($args," "); $cmdline = implode($args," ");
if (get_config('system','proc_windows')) { if(get_config('system','proc_windows'))
proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__))); proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
} else { else
proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__))); proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
}
} }
/** /**
@ -1481,13 +1463,13 @@ function get_app() {
function x($s,$k = NULL) { function x($s,$k = NULL) {
if($k != NULL) { if($k != NULL) {
if((is_array($s)) && (array_key_exists($k,$s))) { if((is_array($s)) && (array_key_exists($k,$s))) {
if ($s[$k]) { if($s[$k])
return (int) 1; return (int) 1;
}
return (int) 0; return (int) 0;
} }
return false; return false;
} else { }
else {
if(isset($s)) { if(isset($s)) {
if($s) { if($s) {
return (int) 1; return (int) 1;
@ -1517,9 +1499,8 @@ function clean_urls() {
function z_path() { function z_path() {
$base = App::get_baseurl(); $base = App::get_baseurl();
if (! clean_urls()) { if(! clean_urls())
$base .= '/?q='; $base .= '/?q=';
}
return $base; return $base;
} }
@ -1544,9 +1525,8 @@ function z_root() {
* @return string * @return string
*/ */
function absurl($path) { function absurl($path) {
if (strpos($path,'/') === 0) { if(strpos($path,'/') === 0)
return z_path() . $path; return z_path() . $path;
}
return $path; return $path;
} }
@ -1566,9 +1546,8 @@ function check_db() {
set_config('system','build',DB_UPDATE_VERSION); set_config('system','build',DB_UPDATE_VERSION);
$build = DB_UPDATE_VERSION; $build = DB_UPDATE_VERSION;
} }
if ($build != DB_UPDATE_VERSION) { if($build != DB_UPDATE_VERSION)
proc_run(PRIORITY_CRITICAL, 'include/dbupdate.php'); proc_run(PRIORITY_CRITICAL, 'include/dbupdate.php');
}
} }
@ -1587,12 +1566,10 @@ function check_url(App $a) {
// and www.example.com vs example.com. // and www.example.com vs example.com.
// We will only change the url to an ip address if there is no existing setting // We will only change the url to an ip address if there is no existing setting
if (! x($url)) { if(! x($url))
$url = set_config('system','url',App::get_baseurl()); $url = set_config('system','url',App::get_baseurl());
} if((! link_compare($url,App::get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
if ((! link_compare($url,App::get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname))) {
$url = set_config('system','url',App::get_baseurl()); $url = set_config('system','url',App::get_baseurl());
}
return; return;
} }
@ -1603,9 +1580,8 @@ function check_url(App $a) {
*/ */
function update_db(App $a) { function update_db(App $a) {
$build = get_config('system','build'); $build = get_config('system','build');
if (! x($build)) { if(! x($build))
$build = set_config('system','build',DB_UPDATE_VERSION); $build = set_config('system','build',DB_UPDATE_VERSION);
}
if($build != DB_UPDATE_VERSION) { if($build != DB_UPDATE_VERSION) {
$stored = intval($build); $stored = intval($build);
@ -1624,9 +1600,8 @@ function update_db(App $a) {
// Compare the current structure with the defined structure // Compare the current structure with the defined structure
$t = get_config('database','dbupdate_'.DB_UPDATE_VERSION); $t = get_config('database','dbupdate_'.DB_UPDATE_VERSION);
if ($t !== false) { if($t !== false)
return; return;
}
set_config('database','dbupdate_'.DB_UPDATE_VERSION, time()); set_config('database','dbupdate_'.DB_UPDATE_VERSION, time());
@ -1634,13 +1609,10 @@ function update_db(App $a) {
// conflits with new routine) // conflits with new routine)
for ($x = $stored; $x < NEW_UPDATE_ROUTINE_VERSION; $x++) { for ($x = $stored; $x < NEW_UPDATE_ROUTINE_VERSION; $x++) {
$r = run_update_function($x); $r = run_update_function($x);
if (!$r) { if (!$r) break;
break;
}
}
if ($stored < NEW_UPDATE_ROUTINE_VERSION) {
$stored = NEW_UPDATE_ROUTINE_VERSION;
} }
if ($stored < NEW_UPDATE_ROUTINE_VERSION) $stored = NEW_UPDATE_ROUTINE_VERSION;
// run new update routine // run new update routine
// it update the structure in one call // it update the structure in one call
@ -1658,9 +1630,7 @@ function update_db(App $a) {
// run any left update_nnnn functions in update.php // run any left update_nnnn functions in update.php
for($x = $stored; $x < $current; $x ++) { for($x = $stored; $x < $current; $x ++) {
$r = run_update_function($x); $r = run_update_function($x);
if (!$r) { if (!$r) break;
break;
}
} }
} }
} }
@ -1681,9 +1651,8 @@ function run_update_function($x) {
// delete the config entry to try again. // delete the config entry to try again.
$t = get_config('database','update_' . $x); $t = get_config('database','update_' . $x);
if ($t !== false) { if($t !== false)
return false; return false;
}
set_config('database','update_' . $x, time()); set_config('database','update_' . $x, time());
// call the specific update // call the specific update
@ -1728,18 +1697,16 @@ function run_update_function($x) {
function check_plugins(App $a) { function check_plugins(App $a) {
$r = q("SELECT * FROM `addon` WHERE `installed` = 1"); $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
if (dbm::is_result($r)) { if (dbm::is_result($r))
$installed = $r; $installed = $r;
} else { else
$installed = array(); $installed = array();
}
$plugins = get_config('system','addon'); $plugins = get_config('system','addon');
$plugins_arr = array(); $plugins_arr = array();
if ($plugins) { if($plugins)
$plugins_arr = explode(',',str_replace(' ', '',$plugins)); $plugins_arr = explode(',',str_replace(' ', '',$plugins));
}
$a->plugins = $plugins_arr; $a->plugins = $plugins_arr;
@ -1749,7 +1716,8 @@ function check_plugins(App $a) {
foreach($installed as $i) { foreach($installed as $i) {
if(! in_array($i['name'],$plugins_arr)) { if(! in_array($i['name'],$plugins_arr)) {
uninstall_plugin($i['name']); uninstall_plugin($i['name']);
} else { }
else {
$installed_arr[] = $i['name']; $installed_arr[] = $i['name'];
} }
} }
@ -1819,7 +1787,8 @@ function login($register = false, $hiddens=false) {
if(local_user()) { if(local_user()) {
$tpl = get_markup_template("logout.tpl"); $tpl = get_markup_template("logout.tpl");
} else { }
else {
$a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array( $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
'$baseurl' => $a->get_baseurl(true) '$baseurl' => $a->get_baseurl(true)
)); ));
@ -1867,9 +1836,8 @@ function login($register = false, $hiddens=false) {
*/ */
function killme() { function killme() {
if (!get_app()->is_backend()) { if (!get_app()->is_backend())
session_write_close(); session_write_close();
}
exit; exit;
} }
@ -1878,9 +1846,8 @@ function killme() {
* @brief Redirect to another URL and terminate this process. * @brief Redirect to another URL and terminate this process.
*/ */
function goaway($s) { function goaway($s) {
if (!strstr(normalise_link($s), "http://")) { if (!strstr(normalise_link($s), "http://"))
$s = App::get_baseurl()."/".$s; $s = App::get_baseurl()."/".$s;
}
header("Location: $s"); header("Location: $s");
killme(); killme();
@ -1928,9 +1895,8 @@ function public_contact() {
* @return int|bool visitor_id or false * @return int|bool visitor_id or false
*/ */
function remote_user() { function remote_user() {
if ((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id'))) { if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
return intval($_SESSION['visitor_id']); return intval($_SESSION['visitor_id']);
}
return false; return false;
} }
@ -1943,13 +1909,10 @@ function remote_user() {
*/ */
function notice($s) { function notice($s) {
$a = get_app(); $a = get_app();
if (! x($_SESSION,'sysmsg')) { if(! x($_SESSION,'sysmsg')) $_SESSION['sysmsg'] = array();
$_SESSION['sysmsg'] = array(); if($a->interactive)
}
if ($a->interactive) {
$_SESSION['sysmsg'][] = $s; $_SESSION['sysmsg'][] = $s;
} }
}
/** /**
* @brief Show an info message to user. * @brief Show an info message to user.
@ -1961,17 +1924,13 @@ function notice($s) {
function info($s) { function info($s) {
$a = get_app(); $a = get_app();
if (local_user() AND get_pconfig(local_user(),'system','ignore_info')) { if (local_user() AND get_pconfig(local_user(),'system','ignore_info'))
return; return;
}
if (! x($_SESSION,'sysmsg_info')) { if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
$_SESSION['sysmsg_info'] = array(); if($a->interactive)
}
if ($a->interactive) {
$_SESSION['sysmsg_info'][] = $s; $_SESSION['sysmsg_info'][] = $s;
} }
}
/** /**
@ -2032,9 +1991,8 @@ function proc_run($cmd){
$arr = array('args' => $args, 'run_cmd' => true); $arr = array('args' => $args, 'run_cmd' => true);
call_hooks("proc_run", $arr); call_hooks("proc_run", $arr);
if (!$arr['run_cmd'] OR !count($args)) { if (!$arr['run_cmd'] OR !count($args))
return; return;
}
$priority = PRIORITY_MEDIUM; $priority = PRIORITY_MEDIUM;
$dont_fork = get_config("system", "worker_dont_fork"); $dont_fork = get_config("system", "worker_dont_fork");
@ -2057,13 +2015,12 @@ function proc_run($cmd){
$found = q("SELECT `id` FROM `workerqueue` WHERE `parameter` = '%s'", $found = q("SELECT `id` FROM `workerqueue` WHERE `parameter` = '%s'",
dbesc($parameters)); dbesc($parameters));
if (!dbm::is_result($found)) { if (!$found)
q("INSERT INTO `workerqueue` (`parameter`, `created`, `priority`) q("INSERT INTO `workerqueue` (`parameter`, `created`, `priority`)
VALUES ('%s', '%s', %d)", VALUES ('%s', '%s', %d)",
dbesc($parameters), dbesc($parameters),
dbesc(datetime_convert()), dbesc(datetime_convert()),
intval($priority)); intval($priority));
}
// Should we quit and wait for the poller to be called as a cronjob? // Should we quit and wait for the poller to be called as a cronjob?
if ($dont_fork) { if ($dont_fork) {
@ -2076,14 +2033,12 @@ function proc_run($cmd){
// Get number of allowed number of worker threads // Get number of allowed number of worker threads
$queues = intval(get_config("system", "worker_queues")); $queues = intval(get_config("system", "worker_queues"));
if ($queues == 0) { if ($queues == 0)
$queues = 4; $queues = 4;
}
// If there are already enough workers running, don't fork another one // If there are already enough workers running, don't fork another one
if ($workers[0]["workers"] >= $queues) { if ($workers[0]["workers"] >= $queues)
return; return;
}
// Now call the poller to execute the jobs that we just added to the queue // Now call the poller to execute the jobs that we just added to the queue
$args = array("include/poller.php", "no_cron"); $args = array("include/poller.php", "no_cron");
@ -2104,19 +2059,17 @@ function current_theme(){
$r = q("select theme from user where uid = %d limit 1", $r = q("select theme from user where uid = %d limit 1",
intval($a->profile_uid) intval($a->profile_uid)
); );
if (dbm::is_result($r)) { if (dbm::is_result($r))
$page_theme = $r[0]['theme']; $page_theme = $r[0]['theme'];
} }
}
// Allow folks to over-rule user themes and always use their own on their own site. // Allow folks to over-rule user themes and always use their own on their own site.
// This works only if the user is on the same server // This works only if the user is on the same server
if($page_theme && local_user() && (local_user() != $a->profile_uid)) { if($page_theme && local_user() && (local_user() != $a->profile_uid)) {
if (get_pconfig(local_user(),'system','always_my_theme')) { if(get_pconfig(local_user(),'system','always_my_theme'))
$page_theme = null; $page_theme = null;
} }
}
// $mobile_detect = new Mobile_Detect(); // $mobile_detect = new Mobile_Detect();
// $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet(); // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
@ -2141,39 +2094,33 @@ function current_theme(){
$system_theme = $standard_system_theme; $system_theme = $standard_system_theme;
$theme_name = $standard_theme_name; $theme_name = $standard_theme_name;
if ($page_theme) { if($page_theme)
$theme_name = $page_theme; $theme_name = $page_theme;
} }
} }
} }
} else { else {
$system_theme = $standard_system_theme; $system_theme = $standard_system_theme;
$theme_name = $standard_theme_name; $theme_name = $standard_theme_name;
if ($page_theme) { if($page_theme)
$theme_name = $page_theme; $theme_name = $page_theme;
} }
}
if($theme_name && if($theme_name &&
(file_exists('view/theme/' . $theme_name . '/style.css') || (file_exists('view/theme/' . $theme_name . '/style.css') ||
file_exists('view/theme/' . $theme_name . '/style.php'))) { file_exists('view/theme/' . $theme_name . '/style.php')))
return($theme_name); return($theme_name);
}
foreach($app_base_themes as $t) { foreach($app_base_themes as $t) {
if(file_exists('view/theme/' . $t . '/style.css')|| if(file_exists('view/theme/' . $t . '/style.css')||
file_exists('view/theme/' . $t . '/style.php')) { file_exists('view/theme/' . $t . '/style.php'))
return($t); return($t);
} }
}
$fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php')); $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
if (count($fallback)) { if(count($fallback))
return (str_replace('view/theme/','', substr($fallback[0],0,-10))); return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
}
/// @TODO No final return statement?
} }
@ -2190,9 +2137,8 @@ function current_theme_url() {
$t = current_theme(); $t = current_theme();
$opts = (($a->profile_uid) ? '?f=&puid=' . $a->profile_uid : ''); $opts = (($a->profile_uid) ? '?f=&puid=' . $a->profile_uid : '');
if (file_exists('view/theme/' . $t . '/style.php')) { if (file_exists('view/theme/' . $t . '/style.php'))
return('view/theme/'.$t.'/style.pcss'.$opts); return('view/theme/'.$t.'/style.pcss'.$opts);
}
return('view/theme/'.$t.'/style.css'); return('view/theme/'.$t.'/style.css');
} }
@ -2221,9 +2167,8 @@ function feed_birthday($uid,$tz) {
$birthday = ''; $birthday = '';
if (! strlen($tz)) { if(! strlen($tz))
$tz = 'UTC'; $tz = 'UTC';
}
$p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1", $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
intval($uid) intval($uid)
@ -2236,9 +2181,8 @@ function feed_birthday($uid,$tz) {
$bd = $y . '-' . $tmp_dob . ' 00:00'; $bd = $y . '-' . $tmp_dob . ' 00:00';
$t_dob = strtotime($bd); $t_dob = strtotime($bd);
$now = strtotime(datetime_convert($tz,$tz,'now')); $now = strtotime(datetime_convert($tz,$tz,'now'));
if ($t_dob < $now) { if($t_dob < $now)
$bd = $y + 1 . '-' . $tmp_dob . ' 00:00'; $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
}
$birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME); $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
} }
} }
@ -2303,10 +2247,9 @@ function explode_querystring($query) {
$args = explode('&', substr($query, $arg_st)); $args = explode('&', substr($query, $arg_st));
foreach($args as $k=>$arg) { foreach($args as $k=>$arg) {
if ($arg === '') { if($arg === '')
unset($args[$k]); unset($args[$k]);
} }
}
$args = array_values($args); $args = array_values($args);
if(!$base) { if(!$base) {
@ -2328,9 +2271,7 @@ function explode_querystring($query) {
*/ */
function curPageURL() { function curPageURL() {
$pageURL = 'http'; $pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") { if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "s";
}
$pageURL .= "://"; $pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") { if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]; $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
@ -2351,9 +2292,8 @@ function random_digits($digits) {
function get_server() { function get_server() {
$server = get_config("system", "directory"); $server = get_config("system", "directory");
if ($server == "") { if ($server == "")
$server = "http://dir.friendi.ca"; $server = "http://dir.friendi.ca";
}
return($server); return($server);
} }
@ -2361,9 +2301,8 @@ function get_server() {
function get_cachefile($file, $writemode = true) { function get_cachefile($file, $writemode = true) {
$cache = get_itemcachepath(); $cache = get_itemcachepath();
if ((! $cache) || (! is_dir($cache))) { if ((! $cache) || (! is_dir($cache)))
return(""); return("");
}
$subfolder = $cache."/".substr($file, 0, 2); $subfolder = $cache."/".substr($file, 0, 2);
@ -2385,30 +2324,25 @@ function clear_cache($basepath = "", $path = "") {
$path = $basepath; $path = $basepath;
} }
if (($path == "") OR (!is_dir($path))) { if (($path == "") OR (!is_dir($path)))
return; return;
}
if (substr(realpath($path), 0, strlen($basepath)) != $basepath) { if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
return; return;
}
$cachetime = (int)get_config('system','itemcache_duration'); $cachetime = (int)get_config('system','itemcache_duration');
if ($cachetime == 0) { if ($cachetime == 0)
$cachetime = 86400; $cachetime = 86400;
}
if (is_writable($path)){ if (is_writable($path)){
if ($dh = opendir($path)) { if ($dh = opendir($path)) {
while (($file = readdir($dh)) !== false) { while (($file = readdir($dh)) !== false) {
$fullpath = $path."/".$file; $fullpath = $path."/".$file;
if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != "..")) { if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
clear_cache($basepath, $fullpath); clear_cache($basepath, $fullpath);
} if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime))) {
unlink($fullpath); unlink($fullpath);
} }
}
closedir($dh); closedir($dh);
} }
} }
@ -2417,9 +2351,8 @@ function clear_cache($basepath = "", $path = "") {
function get_itemcachepath() { function get_itemcachepath() {
// Checking, if the cache is deactivated // Checking, if the cache is deactivated
$cachetime = (int)get_config('system','itemcache_duration'); $cachetime = (int)get_config('system','itemcache_duration');
if ($cachetime < 0) { if ($cachetime < 0)
return ""; return "";
}
$itemcache = get_config('system','itemcache'); $itemcache = get_config('system','itemcache');
if (($itemcache != "") AND App::directory_usable($itemcache)) { if (($itemcache != "") AND App::directory_usable($itemcache)) {
@ -2534,42 +2467,37 @@ function validate_include(&$file) {
$file = realpath($file); $file = realpath($file);
if (strpos($file, getcwd()) !== 0) { if (strpos($file, getcwd()) !== 0)
return false; return false;
}
$file = str_replace(getcwd()."/", "", $file, $count); $file = str_replace(getcwd()."/", "", $file, $count);
if ($count != 1) { if ($count != 1)
return false; return false;
}
if ($orig_file !== $file) { if ($orig_file !== $file)
return false; return false;
}
$valid = false; $valid = false;
if (strpos($file, "include/") === 0) { if (strpos($file, "include/") === 0)
$valid = true; $valid = true;
}
if (strpos($file, "addon/") === 0) { if (strpos($file, "addon/") === 0)
$valid = true; $valid = true;
}
// Simply return flag if (!$valid)
return ($valid); return false;
return true;
} }
function current_load() { function current_load() {
if (!function_exists('sys_getloadavg')) { if (!function_exists('sys_getloadavg'))
return false; return false;
}
$load_arr = sys_getloadavg(); $load_arr = sys_getloadavg();
if (!is_array($load_arr)) { if (!is_array($load_arr))
return false; return false;
}
return max($load_arr[0], $load_arr[1]); return max($load_arr[0], $load_arr[1]);
} }
@ -2590,9 +2518,8 @@ function argc() {
* @return string Value of the argv key * @return string Value of the argv key
*/ */
function argv($x) { function argv($x) {
if (array_key_exists($x,get_app()->argv)) { if(array_key_exists($x,get_app()->argv))
return get_app()->argv[$x]; return get_app()->argv[$x];
}
return ''; return '';
} }

View file

@ -122,13 +122,11 @@ function terminate_friendship($user,$self,$contact) {
// This provides for the possibility that their database is temporarily messed // This provides for the possibility that their database is temporarily messed
// up or some other transient event and that there's a possibility we could recover from it. // up or some other transient event and that there's a possibility we could recover from it.
function mark_for_death(array $contact) { function mark_for_death($contact) {
if ($contact['archive']) { if($contact['archive'])
return; return;
}
/// @TODO Comparison of strings this way may lead to bugs/incompatibility, better switch to DateTime
if ($contact['term-date'] <= NULL_DATE) { if ($contact['term-date'] <= NULL_DATE) {
q("UPDATE `contact` SET `term-date` = '%s' WHERE `id` = %d", q("UPDATE `contact` SET `term-date` = '%s' WHERE `id` = %d",
dbesc(datetime_convert()), dbesc(datetime_convert()),

View file

@ -33,11 +33,10 @@ class DirSearch {
$ostatus = NETWORK_DFRN; $ostatus = NETWORK_DFRN;
// check if we search only communities or every contact // check if we search only communities or every contact
if ($mode === "community") { if($mode === "community")
$extra_sql = " AND `community`"; $extra_sql = " AND `community`";
} else { else
$extra_sql = ""; $extra_sql = "";
}
$search .= "%"; $search .= "%";

View file

@ -154,16 +154,12 @@ class ForumManager {
foreach($contacts as $contact) { foreach($contacts as $contact) {
$forumlist .= micropro($contact,false,'forumlist-profile-advanced'); $forumlist .= micropro($contact,false,'forumlist-profile-advanced');
$total_shown ++; $total_shown ++;
if($total_shown == $show_total)
if ($total_shown == $show_total) {
break; break;
} }
}
if (count($contacts) > 0) { if(count($contacts) > 0)
$o .= $forumlist; $o .= $forumlist;
}
return $o; return $o;
} }

View file

@ -1133,17 +1133,15 @@ class Probe {
$password = ''; $password = '';
openssl_private_decrypt(hex2bin($r[0]['pass']), $password,$x[0]['prvkey']); openssl_private_decrypt(hex2bin($r[0]['pass']), $password,$x[0]['prvkey']);
$mbox = email_connect($mailbox,$r[0]['user'], $password); $mbox = email_connect($mailbox,$r[0]['user'], $password);
if (!$mbox) { if(!mbox)
return false; return false;
} }
}
$msgs = email_poll($mbox, $uri); $msgs = email_poll($mbox, $uri);
logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG); logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
if (!count($msgs)) { if (!count($msgs))
return false; return false;
}
$data = array(); $data = array();
@ -1159,11 +1157,10 @@ class Probe {
$data["poll"] = 'email '.random_string(); $data["poll"] = 'email '.random_string();
$x = email_msg_meta($mbox, $msgs[0]); $x = email_msg_meta($mbox, $msgs[0]);
if (stristr($x[0]->from, $uri)) { if(stristr($x[0]->from, $uri))
$adr = imap_rfc822_parse_adrlist($x[0]->from, ''); $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
} elseif (stristr($x[0]->to, $uri)) { elseif(stristr($x[0]->to, $uri))
$adr = imap_rfc822_parse_adrlist($x[0]->to, ''); $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
}
if(isset($adr)) { if(isset($adr)) {
foreach($adr as $feadr) { foreach($adr as $feadr) {
if((strcasecmp($feadr->mailbox, $data["name"]) == 0) if((strcasecmp($feadr->mailbox, $data["name"]) == 0)
@ -1172,13 +1169,11 @@ class Probe {
$personal = imap_mime_header_decode($feadr->personal); $personal = imap_mime_header_decode($feadr->personal);
$data["name"] = ""; $data["name"] = "";
foreach ($personal as $perspart) { foreach($personal as $perspart)
if ($perspart->charset != "default") { if ($perspart->charset != "default")
$data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text); $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
} else { else
$data["name"] .= $perspart->text; $data["name"] .= $perspart->text;
}
}
$data["name"] = notags($data["name"]); $data["name"] = notags($data["name"]);
} }

View file

@ -170,13 +170,11 @@ class Smilies {
* @todo: Rework because it doesn't work correctly * @todo: Rework because it doesn't work correctly
*/ */
private function preg_heart($x) { private function preg_heart($x) {
if (strlen($x[1]) == 1) { if(strlen($x[1]) == 1)
return $x[0]; return $x[0];
}
$t = ''; $t = '';
for ($cnt = 0; $cnt < strlen($x[1]); $cnt ++) { for($cnt = 0; $cnt < strlen($x[1]); $cnt ++)
$t .= '<img class="smiley" src="' . app::get_baseurl() . '/images/smiley-heart.gif" alt="&lt;3" />'; $t .= '<img class="smiley" src="' . app::get_baseurl() . '/images/smiley-heart.gif" alt="&lt;3" />';
}
$r = str_replace($x[0],$t,$x[0]); $r = str_replace($x[0],$t,$x[0]);
return $r; return $r;
} }

View file

@ -121,9 +121,8 @@ function contact_selector($selname, $selclass, $preselected = false, $options) {
$sql_extra .= sprintf(" AND `id` != %d ", intval($x['exclude'])); $sql_extra .= sprintf(" AND `id` != %d ", intval($x['exclude']));
if(is_array($x['networks']) && count($x['networks'])) { if(is_array($x['networks']) && count($x['networks'])) {
for ($y = 0; $y < count($x['networks']) ; $y ++) { for($y = 0; $y < count($x['networks']) ; $y ++)
$x['networks'][$y] = "'" . dbesc($x['networks'][$y]) . "'"; $x['networks'][$y] = "'" . dbesc($x['networks'][$y]) . "'";
}
$str_nets = implode(',',$x['networks']); $str_nets = implode(',',$x['networks']);
$sql_extra .= " AND `network` IN ( $str_nets ) "; $sql_extra .= " AND `network` IN ( $str_nets ) ";
} }

View file

@ -219,20 +219,17 @@ function bb_find_open_close($s, $open, $close, $occurance = 1) {
$start_pos = -1; $start_pos = -1;
for($i = 1; $i <= $occurance; $i++) { for($i = 1; $i <= $occurance; $i++) {
if ( $start_pos !== false) { if( $start_pos !== false)
$start_pos = strpos($s, $open, $start_pos + 1); $start_pos = strpos($s, $open, $start_pos + 1);
} }
}
if ( $start_pos === false) { if( $start_pos === false)
return false; return false;
}
$end_pos = strpos($s, $close, $start_pos); $end_pos = strpos($s, $close, $start_pos);
if ( $end_pos === false) { if( $end_pos === false)
return false; return false;
}
$res = array( 'start' => $start_pos, 'end' => $end_pos ); $res = array( 'start' => $start_pos, 'end' => $end_pos );
@ -246,10 +243,9 @@ function get_bb_tag_pos($s, $name, $occurance = 1) {
$start_open = -1; $start_open = -1;
for($i = 1; $i <= $occurance; $i++) { for($i = 1; $i <= $occurance; $i++) {
if ( $start_open !== false) { if( $start_open !== false)
$start_open = strpos($s, '[' . $name, $start_open + 1); // allow [name= type tags $start_open = strpos($s, '[' . $name, $start_open + 1); // allow [name= type tags
} }
}
if( $start_open === false) if( $start_open === false)
return false; return false;

View file

@ -173,7 +173,6 @@ function categories_widget($baseurl,$selected = '') {
$matches = false; $matches = false;
$terms = array(); $terms = array();
$cnt = preg_match_all('/<(.*?)>/',$saved,$matches,PREG_SET_ORDER); $cnt = preg_match_all('/<(.*?)>/',$saved,$matches,PREG_SET_ORDER);
if($cnt) { if($cnt) {
foreach($matches as $mtch) { foreach($matches as $mtch) {
$unescaped = xmlify(file_tag_decode($mtch[1])); $unescaped = xmlify(file_tag_decode($mtch[1]));
@ -216,9 +215,9 @@ function common_friends_visitor_widget($profile_uid) {
dbesc(normalise_link(get_my_url())), dbesc(normalise_link(get_my_url())),
intval($profile_uid) intval($profile_uid)
); );
if (dbm::is_result($r)) { if (dbm::is_result($r))
$cid = $r[0]['id']; $cid = $r[0]['id'];
} else { else {
$r = q("select id from gcontact where nurl = '%s' limit 1", $r = q("select id from gcontact where nurl = '%s' limit 1",
dbesc(normalise_link(get_my_url())) dbesc(normalise_link(get_my_url()))
); );
@ -228,26 +227,22 @@ function common_friends_visitor_widget($profile_uid) {
} }
} }
if ($cid == 0 && $zcid == 0) { if($cid == 0 && $zcid == 0)
return; return;
}
require_once('include/socgraph.php'); require_once('include/socgraph.php');
if ($cid) { if($cid)
$t = count_common_friends($profile_uid,$cid); $t = count_common_friends($profile_uid,$cid);
} else { else
$t = count_common_friends_zcid($profile_uid,$zcid); $t = count_common_friends_zcid($profile_uid,$zcid);
} if(! $t)
if (! $t) {
return; return;
}
if ($cid) { if($cid)
$r = common_friends($profile_uid,$cid,0,5,true); $r = common_friends($profile_uid,$cid,0,5,true);
} else { else
$r = common_friends_zcid($profile_uid,$zcid,0,5,true); $r = common_friends_zcid($profile_uid,$zcid,0,5,true);
}
return replace_macros(get_markup_template('remote_friends_common.tpl'), array( return replace_macros(get_markup_template('remote_friends_common.tpl'), array(
'$desc' => sprintf( tt("%d contact in common", "%d contacts in common", $t), $t), '$desc' => sprintf( tt("%d contact in common", "%d contacts in common", $t), $t),

View file

@ -309,11 +309,10 @@ function localize_item(&$item){
$matches = null; $matches = null;
if(preg_match_all('/@\[url=(.*?)\]/is',$item['body'],$matches,PREG_SET_ORDER)) { if(preg_match_all('/@\[url=(.*?)\]/is',$item['body'],$matches,PREG_SET_ORDER)) {
foreach($matches as $mtch) { foreach($matches as $mtch) {
if (! strpos($mtch[1],'zrl=')) { if(! strpos($mtch[1],'zrl='))
$item['body'] = str_replace($mtch[0],'@[url=' . zrl($mtch[1]). ']',$item['body']); $item['body'] = str_replace($mtch[0],'@[url=' . zrl($mtch[1]). ']',$item['body']);
} }
} }
}
// add zrl's to public images // add zrl's to public images
$photo_pattern = "/\[url=(.*?)\/photos\/(.*?)\/image\/(.*?)\]\[img(.*?)\]h(.*?)\[\/img\]\[\/url\]/is"; $photo_pattern = "/\[url=(.*?)\/photos\/(.*?)\/image\/(.*?)\]\[img(.*?)\]h(.*?)\[\/img\]\[\/url\]/is";
@ -485,10 +484,9 @@ function conversation(App $a, $items, $mode, $update, $preview = false) {
$str_blocked = get_pconfig(local_user(),'system','blocked'); $str_blocked = get_pconfig(local_user(),'system','blocked');
if($str_blocked) { if($str_blocked) {
$arr_blocked = explode(',',$str_blocked); $arr_blocked = explode(',',$str_blocked);
for ($x = 0; $x < count($arr_blocked); $x ++) { for($x = 0; $x < count($arr_blocked); $x ++)
$arr_blocked[$x] = trim($arr_blocked[$x]); $arr_blocked[$x] = trim($arr_blocked[$x]);
} }
}
} }
@ -1361,23 +1359,18 @@ function conv_sort($arr,$order) {
$arr = $newarr; $arr = $newarr;
foreach ($arr as $x) { foreach($arr as $x)
if ($x['id'] == $x['parent']) { if($x['id'] == $x['parent'])
$parents[] = $x; $parents[] = $x;
}
}
if (stristr($order,'created')) { if(stristr($order,'created'))
usort($parents,'sort_thr_created'); usort($parents,'sort_thr_created');
} elseif (stristr($order,'commented')) { elseif(stristr($order,'commented'))
usort($parents,'sort_thr_commented'); usort($parents,'sort_thr_commented');
}
if (count($parents)) { if(count($parents))
foreach($parents as $i=>$_x) { foreach($parents as $i=>$_x)
$parents[$i]['children'] = get_item_children($arr, $_x); $parents[$i]['children'] = get_item_children($arr, $_x);
}
}
/*foreach($arr as $x) { /*foreach($arr as $x) {
if($x['id'] != $x['parent']) { if($x['id'] != $x['parent']) {
@ -1425,11 +1418,9 @@ function sort_thr_commented($a,$b) {
} }
function find_thread_parent_index($arr,$x) { function find_thread_parent_index($arr,$x) {
foreach ($arr as $k => $v) { foreach($arr as $k => $v)
if ($v['id'] == $x['parent']) { if($v['id'] == $x['parent'])
return $k; return $k;
}
}
return false; return false;
} }
@ -1452,7 +1443,8 @@ function get_responses($conv_responses,$response_verbs,$ob,$item) {
$ret[$v]['list_part'] = array_slice($ret[$v]['list'], 0, MAX_LIKERS); $ret[$v]['list_part'] = array_slice($ret[$v]['list'], 0, MAX_LIKERS);
array_push($ret[$v]['list_part'], '<a href="#" data-toggle="modal" data-target="#' . $v . 'Modal-' array_push($ret[$v]['list_part'], '<a href="#" data-toggle="modal" data-target="#' . $v . 'Modal-'
. (($ob) ? $ob->get_id() : $item['id']) . '"><b>' . t('View all') . '</b></a>'); . (($ob) ? $ob->get_id() : $item['id']) . '"><b>' . t('View all') . '</b></a>');
} else { }
else {
$ret[$v]['list_part'] = ''; $ret[$v]['list_part'] = '';
} }
$ret[$v]['button'] = get_response_button_text($v,$ret[$v]['count']); $ret[$v]['button'] = get_response_button_text($v,$ret[$v]['count']);
@ -1461,10 +1453,9 @@ function get_responses($conv_responses,$response_verbs,$ob,$item) {
$count = 0; $count = 0;
foreach($ret as $key) { foreach($ret as $key) {
if ($key['count'] == true) { if ($key['count'] == true)
$count++; $count++;
} }
}
$ret['count'] = $count; $ret['count'] = $count;
return $ret; return $ret;

View file

@ -8,21 +8,19 @@ function cronhooks_run(&$argv, &$argc){
require_once('include/datetime.php'); require_once('include/datetime.php');
if (($argc == 2) AND is_array($a->hooks) AND array_key_exists("cron", $a->hooks)) { if (($argc == 2) AND is_array($a->hooks) AND array_key_exists("cron", $a->hooks)) {
foreach ($a->hooks["cron"] as $hook) { foreach ($a->hooks["cron"] as $hook)
if ($hook[1] == $argv[1]) { if ($hook[1] == $argv[1]) {
logger("Calling cron hook '".$hook[1]."'", LOGGER_DEBUG); logger("Calling cron hook '".$hook[1]."'", LOGGER_DEBUG);
call_single_hook($a, $name, $hook, $data); call_single_hook($a, $name, $hook, $data);
} }
}
return; return;
} }
$last = get_config('system', 'last_cronhook'); $last = get_config('system', 'last_cronhook');
$poll_interval = intval(get_config('system','cronhook_interval')); $poll_interval = intval(get_config('system','cronhook_interval'));
if (! $poll_interval) { if(! $poll_interval)
$poll_interval = 9; $poll_interval = 9;
}
if($last) { if($last) {
$next = $last + ($poll_interval * 60); $next = $last + ($poll_interval * 60);

View file

@ -48,12 +48,12 @@ function select_timezone($current = 'America/Los_Angeles') {
$continent = $ex[0]; $continent = $ex[0];
$o .= '<optgroup label="' . t($continent) . '">'; $o .= '<optgroup label="' . t($continent) . '">';
} }
if (count($ex) > 2) { if(count($ex) > 2)
$city = substr($value,strpos($value,'/')+1); $city = substr($value,strpos($value,'/')+1);
} else { else
$city = $ex[1]; $city = $ex[1];
} }
} else { else {
$city = $ex[0]; $city = $ex[0];
if($continent != t('Miscellaneous')) { if($continent != t('Miscellaneous')) {
$o .= '</optgroup>'; $o .= '</optgroup>';
@ -486,12 +486,10 @@ function cal($y = 0,$m = 0, $links = false, $class='') {
$thisyear = datetime_convert('UTC',date_default_timezone_get(),'now','Y'); $thisyear = datetime_convert('UTC',date_default_timezone_get(),'now','Y');
$thismonth = datetime_convert('UTC',date_default_timezone_get(),'now','m'); $thismonth = datetime_convert('UTC',date_default_timezone_get(),'now','m');
if (! $y) { if(! $y)
$y = $thisyear; $y = $thisyear;
} if(! $m)
if (! $m) {
$m = intval($thismonth); $m = intval($thismonth);
}
$dn = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'); $dn = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
$f = get_first_dim($y,$m); $f = get_first_dim($y,$m);
@ -500,33 +498,29 @@ function cal($y = 0,$m = 0, $links = false, $class='') {
$dow = 0; $dow = 0;
$started = false; $started = false;
if (($y == $thisyear) && ($m == $thismonth)) { if(($y == $thisyear) && ($m == $thismonth))
$tddate = intval(datetime_convert('UTC',date_default_timezone_get(),'now','j')); $tddate = intval(datetime_convert('UTC',date_default_timezone_get(),'now','j'));
}
$str_month = day_translate($mtab[$m]); $str_month = day_translate($mtab[$m]);
$o = '<table class="calendar' . $class . '">'; $o = '<table class="calendar' . $class . '">';
$o .= "<caption>$str_month $y</caption><tr>"; $o .= "<caption>$str_month $y</caption><tr>";
for ($a = 0; $a < 7; $a ++) { for($a = 0; $a < 7; $a ++)
$o .= '<th>' . mb_substr(day_translate($dn[$a]),0,3,'UTF-8') . '</th>'; $o .= '<th>' . mb_substr(day_translate($dn[$a]),0,3,'UTF-8') . '</th>';
}
$o .= '</tr><tr>'; $o .= '</tr><tr>';
while($d <= $l) { while($d <= $l) {
if (($dow == $f) && (! $started)) { if(($dow == $f) && (! $started))
$started = true; $started = true;
}
$today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : ''); $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
$o .= "<td $today>"; $o .= "<td $today>";
$day = str_replace(' ','&nbsp;',sprintf('%2.2d', $d)); $day = str_replace(' ','&nbsp;',sprintf('%2.2d', $d));
if($started) { if($started) {
if (is_array($links) && isset($links[$d])) { if(is_array($links) && isset($links[$d]))
$o .= "<a href=\"{$links[$d]}\">$day</a>"; $o .= "<a href=\"{$links[$d]}\">$day</a>";
} else { else
$o .= $day; $o .= $day;
}
$d ++; $d ++;
} else { } else {
@ -540,11 +534,9 @@ function cal($y = 0,$m = 0, $links = false, $class='') {
$o .= '</tr><tr>'; $o .= '</tr><tr>';
} }
} }
if ($dow) { if($dow)
for ($a = $dow; $a < 7; $a ++) { for($a = $dow; $a < 7; $a ++)
$o .= '<td>&nbsp;</td>'; $o .= '<td>&nbsp;</td>';
}
}
$o .= '</tr></table>'."\r\n"; $o .= '</tr></table>'."\r\n";

View file

@ -41,7 +41,6 @@ class dfrn {
* @param array $owner Owner record * @param array $owner Owner record
* *
* @return string DFRN entries * @return string DFRN entries
* @todo Add type-hints
*/ */
public static function entries($items,$owner) { public static function entries($items,$owner) {
@ -50,9 +49,8 @@ class dfrn {
$root = self::add_header($doc, $owner, "dfrn:owner", "", false); $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
if (! count($items)) { if(! count($items))
return trim($doc->saveXML()); return trim($doc->saveXML());
}
foreach($items as $item) { foreach($items as $item) {
$entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]); $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
@ -86,17 +84,14 @@ class dfrn {
if($public_feed && $a->argc > 2) { if($public_feed && $a->argc > 2) {
for($x = 2; $x < $a->argc; $x++) { for($x = 2; $x < $a->argc; $x++) {
if ($a->argv[$x] == 'converse') { if($a->argv[$x] == 'converse')
$converse = true; $converse = true;
} if($a->argv[$x] == 'starred')
if ($a->argv[$x] == 'starred') {
$starred = true; $starred = true;
} if($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1]))
if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
$category = $a->argv[$x+1]; $category = $a->argv[$x+1];
} }
} }
}
@ -157,9 +152,8 @@ class dfrn {
for($x = 0; $x < count($groups); $x ++) for($x = 0; $x < count($groups); $x ++)
$groups[$x] = '<' . intval($groups[$x]) . '>' ; $groups[$x] = '<' . intval($groups[$x]) . '>' ;
$gs = implode('|', $groups); $gs = implode('|', $groups);
} else { } else
$gs = '<<>>' ; // Impossible to match $gs = '<<>>' ; // Impossible to match
}
$sql_extra = sprintf(" $sql_extra = sprintf("
AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' ) AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
@ -174,15 +168,13 @@ class dfrn {
); );
} }
if ($public_feed) { if($public_feed)
$sort = 'DESC'; $sort = 'DESC';
} else { else
$sort = 'ASC'; $sort = 'ASC';
}
if (! strlen($last_update)) { if(! strlen($last_update))
$last_update = 'now -30 days'; $last_update = 'now -30 days';
}
if(isset($category)) { if(isset($category)) {
$sql_post_table = sprintf("INNER JOIN (SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d ORDER BY `tid` DESC) AS `term` ON `item`.`id` = `term`.`oid` ", $sql_post_table = sprintf("INNER JOIN (SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d ORDER BY `tid` DESC) AS `term` ON `item`.`id` = `term`.`oid` ",
@ -191,10 +183,9 @@ class dfrn {
} }
if($public_feed) { if($public_feed) {
if (! $converse) { if(! $converse)
$sql_extra .= " AND `contact`.`self` = 1 "; $sql_extra .= " AND `contact`.`self` = 1 ";
} }
}
$check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s'); $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
@ -216,11 +207,6 @@ class dfrn {
dbesc($sort) dbesc($sort)
); );
if (!dbm::is_result($r)) {
logger("Query failed to execute, no result returned in " . __FUNCTION__);
killme();
}
// Will check further below if this actually returned results. // Will check further below if this actually returned results.
// We will provide an empty feed if that is the case. // We will provide an empty feed if that is the case.
@ -231,15 +217,13 @@ class dfrn {
$alternatelink = $owner['url']; $alternatelink = $owner['url'];
if (isset($category)) { if(isset($category))
$alternatelink .= "/category/".$category; $alternatelink .= "/category/".$category;
}
if ($public_feed) { if ($public_feed)
$author = "dfrn:owner"; $author = "dfrn:owner";
} else { else
$author = "author"; $author = "author";
}
$root = self::add_header($doc, $owner, $author, $alternatelink, true); $root = self::add_header($doc, $owner, $author, $alternatelink, true);
@ -257,21 +241,18 @@ class dfrn {
foreach($items as $item) { foreach($items as $item) {
// prevent private email from leaking. // prevent private email from leaking.
if ($item['network'] == NETWORK_MAIL) { if($item['network'] == NETWORK_MAIL)
continue; continue;
}
// public feeds get html, our own nodes use bbcode // public feeds get html, our own nodes use bbcode
if($public_feed) { if($public_feed) {
$type = 'html'; $type = 'html';
// catch any email that's in a public conversation and make sure it doesn't leak // catch any email that's in a public conversation and make sure it doesn't leak
if ($item['private']) { if($item['private'])
continue; continue;
} } else
} else {
$type = 'text'; $type = 'text';
}
$entry = self::entry($doc, $type, $item, $owner, true); $entry = self::entry($doc, $type, $item, $owner, true);
$root->appendChild($entry); $root->appendChild($entry);
@ -292,7 +273,6 @@ class dfrn {
* @param array $owner Owner record * @param array $owner Owner record
* *
* @return string DFRN mail * @return string DFRN mail
* @todo Add type-hints
*/ */
public static function mail($item, $owner) { public static function mail($item, $owner) {
$doc = new DOMDocument('1.0', 'utf-8'); $doc = new DOMDocument('1.0', 'utf-8');
@ -327,7 +307,6 @@ class dfrn {
* @param array $owner Owner record * @param array $owner Owner record
* *
* @return string DFRN suggestions * @return string DFRN suggestions
* @todo Add type-hints
*/ */
public static function fsuggest($item, $owner) { public static function fsuggest($item, $owner) {
$doc = new DOMDocument('1.0', 'utf-8'); $doc = new DOMDocument('1.0', 'utf-8');
@ -355,7 +334,6 @@ class dfrn {
* @param int $uid User ID * @param int $uid User ID
* *
* @return string DFRN relocations * @return string DFRN relocations
* @todo Add type-hints
*/ */
public static function relocate($owner, $uid) { public static function relocate($owner, $uid) {
@ -372,9 +350,8 @@ class dfrn {
$photos = array(); $photos = array();
$ext = Photo::supportedTypes(); $ext = Photo::supportedTypes();
foreach ($rp as $p) { foreach($rp as $p)
$photos[$p['scale']] = app::get_baseurl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']]; $photos[$p['scale']] = app::get_baseurl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
}
unset($rp, $ext); unset($rp, $ext);
@ -413,13 +390,11 @@ class dfrn {
* @param bool $public Is it a header for public posts? * @param bool $public Is it a header for public posts?
* *
* @return object XML root object * @return object XML root object
* @todo Add type-hints
*/ */
private static function add_header($doc, $owner, $authorelement, $alternatelink = "", $public = false) { private static function add_header($doc, $owner, $authorelement, $alternatelink = "", $public = false) {
if ($alternatelink == "") { if ($alternatelink == "")
$alternatelink = $owner['url']; $alternatelink = $owner['url'];
}
$root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed'); $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
$doc->appendChild($root); $doc->appendChild($root);
@ -462,9 +437,8 @@ class dfrn {
} }
// For backward compatibility we keep this element // For backward compatibility we keep this element
if ($owner['page-flags'] == PAGE_COMMUNITY) { if ($owner['page-flags'] == PAGE_COMMUNITY)
xml::add_element($doc, $root, "dfrn:community", 1); xml::add_element($doc, $root, "dfrn:community", 1);
}
// The former element is replaced by this one // The former element is replaced by this one
xml::add_element($doc, $root, "dfrn:account_type", $owner["account-type"]); xml::add_element($doc, $root, "dfrn:account_type", $owner["account-type"]);
@ -487,7 +461,6 @@ class dfrn {
* @param string $authorelement Element name for the author * @param string $authorelement Element name for the author
* *
* @return object XML author object * @return object XML author object
* @todo Add type-hints
*/ */
private static function add_author($doc, $owner, $authorelement, $public) { private static function add_author($doc, $owner, $authorelement, $public) {
@ -495,11 +468,10 @@ class dfrn {
$r = q("SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid` $r = q("SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d", WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
intval($owner['uid'])); intval($owner['uid']));
if (dbm::is_result($r)) { if ($r)
$hidewall = true; $hidewall = true;
} else { else
$hidewall = false; $hidewall = false;
}
$author = $doc->createElement($authorelement); $author = $doc->createElement($authorelement);
@ -507,11 +479,10 @@ class dfrn {
$uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME); $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
$picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME); $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
$attributes = array(); if (!$public OR !$hidewall)
if (!$public OR !$hidewall) {
$attributes = array("dfrn:updated" => $namdate); $attributes = array("dfrn:updated" => $namdate);
} else
$attributes = array();
xml::add_element($doc, $author, "name", $owner["name"], $attributes); xml::add_element($doc, $author, "name", $owner["name"], $attributes);
xml::add_element($doc, $author, "uri", app::get_baseurl().'/profile/'.$owner["nickname"], $attributes); xml::add_element($doc, $author, "uri", app::get_baseurl().'/profile/'.$owner["nickname"], $attributes);
@ -520,23 +491,20 @@ class dfrn {
$attributes = array("rel" => "photo", "type" => "image/jpeg", $attributes = array("rel" => "photo", "type" => "image/jpeg",
"media:width" => 175, "media:height" => 175, "href" => $owner['photo']); "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
if (!$public OR !$hidewall) { if (!$public OR !$hidewall)
$attributes["dfrn:updated"] = $picdate; $attributes["dfrn:updated"] = $picdate;
}
xml::add_element($doc, $author, "link", "", $attributes); xml::add_element($doc, $author, "link", "", $attributes);
$attributes["rel"] = "avatar"; $attributes["rel"] = "avatar";
xml::add_element($doc, $author, "link", "", $attributes); xml::add_element($doc, $author, "link", "", $attributes);
if ($hidewall) { if ($hidewall)
xml::add_element($doc, $author, "dfrn:hide", "true"); xml::add_element($doc, $author, "dfrn:hide", "true");
}
// The following fields will only be generated if the data isn't meant for a public feed // The following fields will only be generated if the data isn't meant for a public feed
if ($public) { if ($public)
return $author; return $author;
}
$birthday = feed_birthday($owner['uid'], $owner['timezone']); $birthday = feed_birthday($owner['uid'], $owner['timezone']);
@ -551,7 +519,7 @@ class dfrn {
INNER JOIN `user` ON `user`.`uid` = `profile`.`uid` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d", WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
intval($owner['uid'])); intval($owner['uid']));
if (dbm::is_result($r)) { if ($r) {
$profile = $r[0]; $profile = $r[0];
xml::add_element($doc, $author, "poco:displayName", $profile["name"]); xml::add_element($doc, $author, "poco:displayName", $profile["name"]);
@ -579,9 +547,8 @@ class dfrn {
if (trim($profile["pub_keywords"]) != "") { if (trim($profile["pub_keywords"]) != "") {
$keywords = explode(",", $profile["pub_keywords"]); $keywords = explode(",", $profile["pub_keywords"]);
foreach ($keywords AS $keyword) { foreach ($keywords AS $keyword)
xml::add_element($doc, $author, "poco:tags", trim($keyword)); xml::add_element($doc, $author, "poco:tags", trim($keyword));
}
} }
@ -598,17 +565,14 @@ class dfrn {
xml::add_element($doc, $element, "poco:formatted", formatted_location($profile)); xml::add_element($doc, $element, "poco:formatted", formatted_location($profile));
if (trim($profile["locality"]) != "") { if (trim($profile["locality"]) != "")
xml::add_element($doc, $element, "poco:locality", $profile["locality"]); xml::add_element($doc, $element, "poco:locality", $profile["locality"]);
}
if (trim($profile["region"]) != "") { if (trim($profile["region"]) != "")
xml::add_element($doc, $element, "poco:region", $profile["region"]); xml::add_element($doc, $element, "poco:region", $profile["region"]);
}
if (trim($profile["country-name"]) != "") { if (trim($profile["country-name"]) != "")
xml::add_element($doc, $element, "poco:country", $profile["country-name"]); xml::add_element($doc, $element, "poco:country", $profile["country-name"]);
}
$author->appendChild($element); $author->appendChild($element);
} }
@ -626,7 +590,6 @@ class dfrn {
* @param array $items Item elements * @param array $items Item elements
* *
* @return object XML author object * @return object XML author object
* @todo Add type-hints
*/ */
private static function add_entry_author($doc, $element, $contact_url, $item) { private static function add_entry_author($doc, $element, $contact_url, $item) {
@ -667,7 +630,6 @@ class dfrn {
* @param string $activity activity value * @param string $activity activity value
* *
* @return object XML activity object * @return object XML activity object
* @todo Add type-hints
*/ */
private static function create_activity($doc, $element, $activity) { private static function create_activity($doc, $element, $activity) {
@ -675,24 +637,18 @@ class dfrn {
$entry = $doc->createElement($element); $entry = $doc->createElement($element);
$r = parse_xml_string($activity, false); $r = parse_xml_string($activity, false);
if (!$r) { if(!$r)
return false; return false;
} if($r->type)
if ($r->type) {
xml::add_element($doc, $entry, "activity:object-type", $r->type); xml::add_element($doc, $entry, "activity:object-type", $r->type);
} if($r->id)
if ($r->id) {
xml::add_element($doc, $entry, "id", $r->id); xml::add_element($doc, $entry, "id", $r->id);
} if($r->title)
if ($r->title) {
xml::add_element($doc, $entry, "title", $r->title); xml::add_element($doc, $entry, "title", $r->title);
}
if($r->link) { if($r->link) {
if(substr($r->link,0,1) == '<') { if(substr($r->link,0,1) == '<') {
if (strstr($r->link,'&') && (! strstr($r->link,'&amp;'))) { if(strstr($r->link,'&') && (! strstr($r->link,'&amp;')))
$r->link = str_replace('&','&amp;', $r->link); $r->link = str_replace('&','&amp;', $r->link);
}
$r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link); $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
@ -701,9 +657,8 @@ class dfrn {
if (is_object($data)) { if (is_object($data)) {
foreach ($data->link AS $link) { foreach ($data->link AS $link) {
$attributes = array(); $attributes = array();
foreach ($link->attributes() AS $parameter => $value) { foreach ($link->attributes() AS $parameter => $value)
$attributes[$parameter] = $value; $attributes[$parameter] = $value;
}
xml::add_element($doc, $entry, "link", "", $attributes); xml::add_element($doc, $entry, "link", "", $attributes);
} }
} }
@ -712,9 +667,8 @@ class dfrn {
xml::add_element($doc, $entry, "link", "", $attributes); xml::add_element($doc, $entry, "link", "", $attributes);
} }
} }
if ($r->content) { if($r->content)
xml::add_element($doc, $entry, "content", bbcode($r->content), array("type" => "html")); xml::add_element($doc, $entry, "content", bbcode($r->content), array("type" => "html"));
}
return $entry; return $entry;
} }
@ -730,7 +684,6 @@ class dfrn {
* @param array $item Item element * @param array $item Item element
* *
* @return object XML attachment object * @return object XML attachment object
* @todo Add type-hints
*/ */
private static function get_attachment($doc, $root, $item) { private static function get_attachment($doc, $root, $item) {
$arr = explode('[/attach],',$item['attach']); $arr = explode('[/attach],',$item['attach']);
@ -743,13 +696,11 @@ class dfrn {
"href" => $matches[1], "href" => $matches[1],
"type" => $matches[3]); "type" => $matches[3]);
if (intval($matches[2])) { if(intval($matches[2]))
$attributes["length"] = intval($matches[2]); $attributes["length"] = intval($matches[2]);
}
if (trim($matches[4]) != "") { if(trim($matches[4]) != "")
$attributes["title"] = trim($matches[4]); $attributes["title"] = trim($matches[4]);
}
xml::add_element($doc, $root, "link", "", $attributes); xml::add_element($doc, $root, "link", "", $attributes);
} }
@ -768,15 +719,13 @@ class dfrn {
* @param int $cid Contact ID of the recipient * @param int $cid Contact ID of the recipient
* *
* @return object XML entry object * @return object XML entry object
* @todo Add type-hints
*/ */
private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0) { private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0) {
$mentioned = array(); $mentioned = array();
if (!$item['parent']) { if(!$item['parent'])
return; return;
}
if($item['deleted']) { if($item['deleted']) {
$attributes = array("ref" => $item['uri'], "when" => datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)); $attributes = array("ref" => $item['uri'], "when" => datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME));
@ -785,11 +734,10 @@ class dfrn {
$entry = $doc->createElement("entry"); $entry = $doc->createElement("entry");
if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) { if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
$body = fix_private_photos($item['body'],$owner['uid'],$item,$cid); $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
} else { else
$body = $item['body']; $body = $item['body'];
}
// Remove the abstract element. It is only locally important. // Remove the abstract element. It is only locally important.
$body = remove_abstract($body); $body = remove_abstract($body);
@ -797,9 +745,8 @@ class dfrn {
if ($type == 'html') { if ($type == 'html') {
$htmlbody = $body; $htmlbody = $body;
if ($item['title'] != "") { if ($item['title'] != "")
$htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody; $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
}
$htmlbody = bbcode($htmlbody, false, false, 7); $htmlbody = bbcode($htmlbody, false, false, 7);
} }
@ -838,33 +785,26 @@ class dfrn {
// "comment-allow" is some old fashioned stuff for old Friendica versions. // "comment-allow" is some old fashioned stuff for old Friendica versions.
// It is included in the rewritten code for completeness // It is included in the rewritten code for completeness
if ($comment) { if ($comment)
xml::add_element($doc, $entry, "dfrn:comment-allow", intval($item['last-child'])); xml::add_element($doc, $entry, "dfrn:comment-allow", intval($item['last-child']));
}
if ($item['location']) { if($item['location'])
xml::add_element($doc, $entry, "dfrn:location", $item['location']); xml::add_element($doc, $entry, "dfrn:location", $item['location']);
}
if ($item['coord']) { if($item['coord'])
xml::add_element($doc, $entry, "georss:point", $item['coord']); xml::add_element($doc, $entry, "georss:point", $item['coord']);
}
if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) { if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
xml::add_element($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1)); xml::add_element($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
}
if ($item['extid']) { if($item['extid'])
xml::add_element($doc, $entry, "dfrn:extid", $item['extid']); xml::add_element($doc, $entry, "dfrn:extid", $item['extid']);
}
if ($item['bookmark']) { if($item['bookmark'])
xml::add_element($doc, $entry, "dfrn:bookmark", "true"); xml::add_element($doc, $entry, "dfrn:bookmark", "true");
}
if ($item['app']) { if($item['app'])
xml::add_element($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app'])); xml::add_element($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app']));
}
xml::add_element($doc, $entry, "dfrn:diaspora_guid", $item["guid"]); xml::add_element($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
@ -877,62 +817,47 @@ class dfrn {
xml::add_element($doc, $entry, "activity:verb", construct_verb($item)); xml::add_element($doc, $entry, "activity:verb", construct_verb($item));
if ($item['object-type'] != "") { if ($item['object-type'] != "")
xml::add_element($doc, $entry, "activity:object-type", $item['object-type']); xml::add_element($doc, $entry, "activity:object-type", $item['object-type']);
} elseif ($item['id'] == $item['parent']) { elseif ($item['id'] == $item['parent'])
xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE); xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
} else { else
xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT); xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
}
$actobj = self::create_activity($doc, "activity:object", $item['object']); $actobj = self::create_activity($doc, "activity:object", $item['object']);
if ($actobj) { if ($actobj)
$entry->appendChild($actobj); $entry->appendChild($actobj);
}
$actarg = self::create_activity($doc, "activity:target", $item['target']); $actarg = self::create_activity($doc, "activity:target", $item['target']);
if ($actarg) { if ($actarg)
$entry->appendChild($actarg); $entry->appendChild($actarg);
}
$tags = item_getfeedtags($item); $tags = item_getfeedtags($item);
if(count($tags)) { if(count($tags)) {
foreach ($tags as $t) { foreach($tags as $t)
if (($type != 'html') OR ($t[0] != "@")) { if (($type != 'html') OR ($t[0] != "@"))
xml::add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2])); xml::add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]));
} }
}
}
if (count($tags)) { if(count($tags))
foreach ($tags as $t) { foreach($tags as $t)
if ($t[0] == "@") { if ($t[0] == "@")
$mentioned[$t[1]] = $t[1]; $mentioned[$t[1]] = $t[1];
}
}
}
foreach ($mentioned AS $mention) { foreach ($mentioned AS $mention) {
$r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'", $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
intval($owner["uid"]), intval($owner["uid"]),
dbesc(normalise_link($mention))); dbesc(normalise_link($mention)));
if ($r[0]["forum"] OR $r[0]["prv"])
if (!dbm::is_result($r)) {
/// @TODO Maybe some logging?
killme();
}
if ($r[0]["forum"] OR $r[0]["prv"]) {
xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned", xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
"ostatus:object-type" => ACTIVITY_OBJ_GROUP, "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
"href" => $mention)); "href" => $mention));
} else { else
xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned", xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
"ostatus:object-type" => ACTIVITY_OBJ_PERSON, "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
"href" => $mention)); "href" => $mention));
} }
}
self::get_attachment($doc, $entry, $item); self::get_attachment($doc, $entry, $item);
@ -948,7 +873,6 @@ class dfrn {
* @param bool $dissolve (to be documented) * @param bool $dissolve (to be documented)
* *
* @return int Deliver status. -1 means an error. * @return int Deliver status. -1 means an error.
* @todo Add array type-hint for $owner, $contact
*/ */
public static function deliver($owner,$contact,$atom, $dissolve = false) { public static function deliver($owner,$contact,$atom, $dissolve = false) {
@ -956,20 +880,16 @@ class dfrn {
$idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']); $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
if ($contact['duplex'] && $contact['dfrn-id']) { if($contact['duplex'] && $contact['dfrn-id'])
$idtosend = '0:' . $orig_id; $idtosend = '0:' . $orig_id;
} if($contact['duplex'] && $contact['issued-id'])
if ($contact['duplex'] && $contact['issued-id']) {
$idtosend = '1:' . $orig_id; $idtosend = '1:' . $orig_id;
}
$rino = get_config('system','rino_encrypt'); $rino = get_config('system','rino_encrypt');
$rino = intval($rino); $rino = intval($rino);
// use RINO1 if mcrypt isn't installed and RINO2 was selected // use RINO1 if mcrypt isn't installed and RINO2 was selected
if ($rino == 2 and !function_exists('mcrypt_create_iv')) { if ($rino==2 and !function_exists('mcrypt_create_iv')) $rino=1;
$rino = 1;
}
logger("Local rino version: ". $rino, LOGGER_DEBUG); logger("Local rino version: ". $rino, LOGGER_DEBUG);
@ -1008,9 +928,8 @@ class dfrn {
logger('dfrn_deliver: ' . $xml, LOGGER_DATA); logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
if (! $xml) { if(! $xml)
return 3; return 3;
}
if(strpos($xml,'<?xml') === false) { if(strpos($xml,'<?xml') === false) {
logger('dfrn_deliver: no valid XML returned'); logger('dfrn_deliver: no valid XML returned');
@ -1020,9 +939,8 @@ class dfrn {
$res = parse_xml_string($xml); $res = parse_xml_string($xml);
if ((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id))) { if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
return (($res->status) ? $res->status : 3); return (($res->status) ? $res->status : 3);
}
$postvars = array(); $postvars = array();
$sent_dfrn_id = hex2bin((string) $res->dfrn_id); $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
@ -1034,9 +952,8 @@ class dfrn {
logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG); logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
if ($owner['page-flags'] == PAGE_PRVGROUP) { if($owner['page-flags'] == PAGE_PRVGROUP)
$page = 2; $page = 2;
}
$final_dfrn_id = ''; $final_dfrn_id = '';
@ -1063,9 +980,8 @@ class dfrn {
$final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.')); $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
if (strpos($final_dfrn_id,':') == 1) { if(strpos($final_dfrn_id,':') == 1)
$final_dfrn_id = substr($final_dfrn_id,2); $final_dfrn_id = substr($final_dfrn_id,2);
}
if($final_dfrn_id != $orig_id) { if($final_dfrn_id != $orig_id) {
logger('dfrn_deliver: wrong dfrn_id.'); logger('dfrn_deliver: wrong dfrn_id.');
@ -1075,9 +991,8 @@ class dfrn {
$postvars['dfrn_id'] = $idtosend; $postvars['dfrn_id'] = $idtosend;
$postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION; $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
if ($dissolve) { if($dissolve)
$postvars['dissolve'] = '1'; $postvars['dissolve'] = '1';
}
if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) { if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
@ -1090,9 +1005,8 @@ class dfrn {
$postvars['ssl_policy'] = $ssl_policy; $postvars['ssl_policy'] = $ssl_policy;
if ($page) { if($page)
$postvars['page'] = $page; $postvars['page'] = $page;
}
if($rino>0 && $rino_remote_version>0 && (! $dissolve)) { if($rino>0 && $rino_remote_version>0 && (! $dissolve)) {
@ -1133,25 +1047,23 @@ class dfrn {
$postvars['rino'] = $rino_remote_version; $postvars['rino'] = $rino_remote_version;
$postvars['data'] = bin2hex($data); $postvars['data'] = bin2hex($data);
//logger('rino: sent key = ' . $key, LOGGER_DEBUG); #logger('rino: sent key = ' . $key, LOGGER_DEBUG);
if($dfrn_version >= 2.1) { if($dfrn_version >= 2.1) {
if(($contact['duplex'] && strlen($contact['pubkey'])) if(($contact['duplex'] && strlen($contact['pubkey']))
|| ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
|| ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) { || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey'])))
openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']); openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
} else { else
openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']); openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
}
} else { } else {
if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) { if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY))
openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']); openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
} else { else
openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']); openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
}
} }
@ -1182,7 +1094,6 @@ class dfrn {
return 3; return 3;
} }
/// @TODO Really compare with > here? Maybe DateTime (which allows such comparison again) is much safer/correcter
if ($contact['term-date'] > NULL_DATE) { if ($contact['term-date'] > NULL_DATE) {
logger("dfrn_deliver: $url back from the dead - removing mark for death"); logger("dfrn_deliver: $url back from the dead - removing mark for death");
require_once('include/Contact.php'); require_once('include/Contact.php');
@ -1199,7 +1110,7 @@ class dfrn {
* *
* @param array $contact Contact record * @param array $contact Contact record
* @param string $birthday Birthday of the contact * @param string $birthday Birthday of the contact
* @todo Add array type-hint for $contact *
*/ */
private static function birthday_event($contact, $birthday) { private static function birthday_event($contact, $birthday) {
@ -1243,7 +1154,6 @@ class dfrn {
* @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
* *
* @return Returns an array with relevant data of the author * @return Returns an array with relevant data of the author
* @todo Find good type-hints for all parameter
*/ */
private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "") { private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "") {
@ -1255,15 +1165,13 @@ class dfrn {
`name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type` `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'", FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
intval($importer["uid"]), dbesc(normalise_link($author["link"])), dbesc(NETWORK_STATUSNET)); intval($importer["uid"]), dbesc(normalise_link($author["link"])), dbesc(NETWORK_STATUSNET));
if ($r) {
if (dbm::is_result($r)) {
$contact = $r[0]; $contact = $r[0];
$author["contact-id"] = $r[0]["id"]; $author["contact-id"] = $r[0]["id"];
$author["network"] = $r[0]["network"]; $author["network"] = $r[0]["network"];
} else { } else {
if (!$onlyfetch) { if (!$onlyfetch)
logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG); logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
}
$author["contact-id"] = $importer["id"]; $author["contact-id"] = $importer["id"];
$author["network"] = $importer["network"]; $author["network"] = $importer["network"];
@ -1278,77 +1186,62 @@ class dfrn {
$href = ""; $href = "";
$width = 0; $width = 0;
foreach($avatar->attributes AS $attributes) { foreach($avatar->attributes AS $attributes) {
/// @TODO Rewrite these similar if () to one switch if ($attributes->name == "href")
if ($attributes->name == "href") {
$href = $attributes->textContent; $href = $attributes->textContent;
} if ($attributes->name == "width")
if ($attributes->name == "width") {
$width = $attributes->textContent; $width = $attributes->textContent;
} if ($attributes->name == "updated")
if ($attributes->name == "updated") {
$contact["avatar-date"] = $attributes->textContent; $contact["avatar-date"] = $attributes->textContent;
} }
} if (($width > 0) AND ($href != ""))
if (($width > 0) AND ($href != "")) {
$avatarlist[$width] = $href; $avatarlist[$width] = $href;
} }
}
if (count($avatarlist) > 0) { if (count($avatarlist) > 0) {
krsort($avatarlist); krsort($avatarlist);
$author["avatar"] = current($avatarlist); $author["avatar"] = current($avatarlist);
} }
if (dbm::is_result($r) AND !$onlyfetch) { if ($r AND !$onlyfetch) {
logger("Check if contact details for contact ".$r[0]["id"]." (".$r[0]["nick"].") have to be updated.", LOGGER_DEBUG); logger("Check if contact details for contact ".$r[0]["id"]." (".$r[0]["nick"].") have to be updated.", LOGGER_DEBUG);
$poco = array("url" => $contact["url"]); $poco = array("url" => $contact["url"]);
// When was the last change to name or uri? // When was the last change to name or uri?
$name_element = $xpath->query($element."/atom:name", $context)->item(0); $name_element = $xpath->query($element."/atom:name", $context)->item(0);
foreach ($name_element->attributes AS $attributes) { foreach($name_element->attributes AS $attributes)
if ($attributes->name == "updated") { if ($attributes->name == "updated")
$poco["name-date"] = $attributes->textContent; $poco["name-date"] = $attributes->textContent;
}
}
$link_element = $xpath->query($element."/atom:link", $context)->item(0); $link_element = $xpath->query($element."/atom:link", $context)->item(0);
foreach ($link_element->attributes AS $attributes) { foreach($link_element->attributes AS $attributes)
if ($attributes->name == "updated") { if ($attributes->name == "updated")
$poco["uri-date"] = $attributes->textContent; $poco["uri-date"] = $attributes->textContent;
}
}
// Update contact data // Update contact data
$value = $xpath->evaluate($element."/dfrn:handle/text()", $context)->item(0)->nodeValue; $value = $xpath->evaluate($element."/dfrn:handle/text()", $context)->item(0)->nodeValue;
if ($value != "") { if ($value != "")
$poco["addr"] = $value; $poco["addr"] = $value;
}
$value = $xpath->evaluate($element."/poco:displayName/text()", $context)->item(0)->nodeValue; $value = $xpath->evaluate($element."/poco:displayName/text()", $context)->item(0)->nodeValue;
if ($value != "") { if ($value != "")
$poco["name"] = $value; $poco["name"] = $value;
}
$value = $xpath->evaluate($element."/poco:preferredUsername/text()", $context)->item(0)->nodeValue; $value = $xpath->evaluate($element."/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
if ($value != "") { if ($value != "")
$poco["nick"] = $value; $poco["nick"] = $value;
}
$value = $xpath->evaluate($element."/poco:note/text()", $context)->item(0)->nodeValue; $value = $xpath->evaluate($element."/poco:note/text()", $context)->item(0)->nodeValue;
if ($value != "") { if ($value != "")
$poco["about"] = $value; $poco["about"] = $value;
}
$value = $xpath->evaluate($element."/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue; $value = $xpath->evaluate($element."/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
if ($value != "") { if ($value != "")
$poco["location"] = $value; $poco["location"] = $value;
}
/// @todo Only search for elements with "poco:type" = "xmpp" /// @todo Only search for elements with "poco:type" = "xmpp"
$value = $xpath->evaluate($element."/poco:ims/poco:value/text()", $context)->item(0)->nodeValue; $value = $xpath->evaluate($element."/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
if ($value != "") { if ($value != "")
$poco["xmpp"] = $value; $poco["xmpp"] = $value;
}
/// @todo Add support for the following fields that we don't support by now in the contact table: /// @todo Add support for the following fields that we don't support by now in the contact table:
/// - poco:utcOffset /// - poco:utcOffset
@ -1364,20 +1257,17 @@ class dfrn {
// If the contact isn't searchable then set the contact to "hidden". // If the contact isn't searchable then set the contact to "hidden".
// Problem: This can be manually overridden by the user. // Problem: This can be manually overridden by the user.
if ($hide) { if ($hide)
$contact["hidden"] = true; $contact["hidden"] = true;
}
// Save the keywords into the contact table // Save the keywords into the contact table
$tags = array(); $tags = array();
$tagelements = $xpath->evaluate($element."/poco:tags/text()", $context); $tagelements = $xpath->evaluate($element."/poco:tags/text()", $context);
foreach ($tagelements AS $tag) { foreach($tagelements AS $tag)
$tags[$tag->nodeValue] = $tag->nodeValue; $tags[$tag->nodeValue] = $tag->nodeValue;
}
if (count($tags)) { if (count($tags))
$poco["keywords"] = implode(", ", $tags); $poco["keywords"] = implode(", ", $tags);
}
// "dfrn:birthday" contains the birthday converted to UTC // "dfrn:birthday" contains the birthday converted to UTC
$old_bdyear = $contact["bdyear"]; $old_bdyear = $contact["bdyear"];
@ -1407,15 +1297,13 @@ class dfrn {
$contact = array_merge($contact, $poco); $contact = array_merge($contact, $poco);
if ($old_bdyear != $contact["bdyear"]) { if ($old_bdyear != $contact["bdyear"])
self::birthday_event($contact, $birthday); self::birthday_event($contact, $birthday);
}
// Get all field names // Get all field names
$fields = array(); $fields = array();
foreach ($r[0] AS $field => $data) { foreach ($r[0] AS $field => $data)
$fields[$field] = $data; $fields[$field] = $data;
}
unset($fields["id"]); unset($fields["id"]);
unset($fields["uid"]); unset($fields["uid"]);
@ -1426,19 +1314,17 @@ class dfrn {
// Update check for this field has to be done differently // Update check for this field has to be done differently
$datefields = array("name-date", "uri-date"); $datefields = array("name-date", "uri-date");
foreach ($datefields AS $field) { foreach ($datefields AS $field)
if (strtotime($contact[$field]) > strtotime($r[0][$field])) { if (strtotime($contact[$field]) > strtotime($r[0][$field])) {
logger("Difference for contact ".$contact["id"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG); logger("Difference for contact ".$contact["id"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
$update = true; $update = true;
} }
}
foreach ($fields AS $field => $data) { foreach ($fields AS $field => $data)
if ($contact[$field] != $r[0][$field]) { if ($contact[$field] != $r[0][$field]) {
logger("Difference for contact ".$contact["id"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG); logger("Difference for contact ".$contact["id"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
$update = true; $update = true;
} }
}
if ($update) { if ($update) {
logger("Update contact data for contact ".$contact["id"]." (".$contact["nick"].")", LOGGER_DEBUG); logger("Update contact data for contact ".$contact["id"]." (".$contact["nick"].")", LOGGER_DEBUG);
@ -1480,12 +1366,10 @@ class dfrn {
* @param text $element element name * @param text $element element name
* *
* @return string XML string * @return string XML string
* @todo Find good type-hints for all parameter
*/ */
private static function transform_activity($xpath, $activity, $element) { private static function transform_activity($xpath, $activity, $element) {
if (!is_object($activity)) { if (!is_object($activity))
return ""; return "";
}
$obj_doc = new DOMDocument("1.0", "utf-8"); $obj_doc = new DOMDocument("1.0", "utf-8");
$obj_doc->formatOutput = true; $obj_doc->formatOutput = true;
@ -1496,26 +1380,21 @@ class dfrn {
xml::add_element($obj_doc, $obj_element, "type", $activity_type); xml::add_element($obj_doc, $obj_element, "type", $activity_type);
$id = $xpath->query("atom:id", $activity)->item(0); $id = $xpath->query("atom:id", $activity)->item(0);
if (is_object($id)) { if (is_object($id))
$obj_element->appendChild($obj_doc->importNode($id, true)); $obj_element->appendChild($obj_doc->importNode($id, true));
}
$title = $xpath->query("atom:title", $activity)->item(0); $title = $xpath->query("atom:title", $activity)->item(0);
if (is_object($title)) { if (is_object($title))
$obj_element->appendChild($obj_doc->importNode($title, true)); $obj_element->appendChild($obj_doc->importNode($title, true));
}
$links = $xpath->query("atom:link", $activity); $links = $xpath->query("atom:link", $activity);
if (is_object($links)) { if (is_object($links))
foreach ($links AS $link) { foreach ($links AS $link)
$obj_element->appendChild($obj_doc->importNode($link, true)); $obj_element->appendChild($obj_doc->importNode($link, true));
}
}
$content = $xpath->query("atom:content", $activity)->item(0); $content = $xpath->query("atom:content", $activity)->item(0);
if (is_object($content)) { if (is_object($content))
$obj_element->appendChild($obj_doc->importNode($content, true)); $obj_element->appendChild($obj_doc->importNode($content, true));
}
$obj_doc->appendChild($obj_element); $obj_doc->appendChild($obj_element);
@ -1532,13 +1411,11 @@ class dfrn {
* @param object $xpath XPath object * @param object $xpath XPath object
* @param object $mail mail elements * @param object $mail mail elements
* @param array $importer Record of the importer user mixed with contact of the content * @param array $importer Record of the importer user mixed with contact of the content
* @todo Find good type-hints for all parameter
*/ */
private static function process_mail($xpath, $mail, $importer) { private static function process_mail($xpath, $mail, $importer) {
logger("Processing mails"); logger("Processing mails");
/// @TODO Rewrite this to one statement
$msg = array(); $msg = array();
$msg["uid"] = $importer["importer_uid"]; $msg["uid"] = $importer["importer_uid"];
$msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue; $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
@ -1558,7 +1435,7 @@ class dfrn {
$r = dbq("INSERT INTO `mail` (`".implode("`, `", array_keys($msg))."`) VALUES (".implode(", ", array_values($msg)).")"); $r = dbq("INSERT INTO `mail` (`".implode("`, `", array_keys($msg))."`) VALUES (".implode(", ", array_values($msg)).")");
// send notifications. // send notifications.
/// @TODO Arange this mess
$notif_params = array( $notif_params = array(
"type" => NOTIFY_MAIL, "type" => NOTIFY_MAIL,
"notify_flags" => $importer["notify-flags"], "notify_flags" => $importer["notify-flags"],
@ -1585,14 +1462,12 @@ class dfrn {
* @param object $xpath XPath object * @param object $xpath XPath object
* @param object $suggestion suggestion elements * @param object $suggestion suggestion elements
* @param array $importer Record of the importer user mixed with contact of the content * @param array $importer Record of the importer user mixed with contact of the content
* @todo Find good type-hints for all parameter
*/ */
private static function process_suggestion($xpath, $suggestion, $importer) { private static function process_suggestion($xpath, $suggestion, $importer) {
$a = get_app(); $a = get_app();
logger("Processing suggestions"); logger("Processing suggestions");
/// @TODO Rewrite this to one statement
$suggest = array(); $suggest = array();
$suggest["uid"] = $importer["importer_uid"]; $suggest["uid"] = $importer["importer_uid"];
$suggest["cid"] = $importer["id"]; $suggest["cid"] = $importer["id"];
@ -1609,11 +1484,8 @@ class dfrn {
dbesc(normalise_link($suggest["url"])), dbesc(normalise_link($suggest["url"])),
intval($suggest["uid"]) intval($suggest["uid"])
); );
if (dbm::is_result($r))
if (dbm::is_result($r)) {
// Has already friend matching description
return false; return false;
}
// Do we already have an fcontact record for this person? // Do we already have an fcontact record for this person?
@ -1631,11 +1503,9 @@ class dfrn {
intval($suggest["uid"]), intval($suggest["uid"]),
intval($fid) intval($fid)
); );
/// @TODO Really abort on valid result??? Maybe missed ! here? if (dbm::is_result($r))
if (dbm::is_result($r)) {
return false; return false;
} }
}
if(!$fid) if(!$fid)
$r = q("INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')", $r = q("INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
dbesc($suggest["name"]), dbesc($suggest["name"]),
@ -1648,12 +1518,11 @@ class dfrn {
dbesc($suggest["name"]), dbesc($suggest["name"]),
dbesc($suggest["request"]) dbesc($suggest["request"])
); );
if (dbm::is_result($r)) { if (dbm::is_result($r))
$fid = $r[0]["id"]; $fid = $r[0]["id"];
} else { else
// database record did not get created. Quietly give up. // database record did not get created. Quietly give up.
killme(); return false;
}
$hash = random_string(); $hash = random_string();
@ -1695,13 +1564,11 @@ class dfrn {
* @param object $xpath XPath object * @param object $xpath XPath object
* @param object $relocation relocation elements * @param object $relocation relocation elements
* @param array $importer Record of the importer user mixed with contact of the content * @param array $importer Record of the importer user mixed with contact of the content
* @todo Find good type-hints for all parameter
*/ */
private static function process_relocation($xpath, $relocation, $importer) { private static function process_relocation($xpath, $relocation, $importer) {
logger("Processing relocations"); logger("Processing relocations");
/// @TODO Rewrite this to one statement
$relocate = array(); $relocate = array();
$relocate["uid"] = $importer["importer_uid"]; $relocate["uid"] = $importer["importer_uid"];
$relocate["cid"] = $importer["id"]; $relocate["cid"] = $importer["id"];
@ -1718,23 +1585,18 @@ class dfrn {
$relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue; $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
$relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue; $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
if (($relocate["avatar"] == "") AND ($relocate["photo"] != "")) { if (($relocate["avatar"] == "") AND ($relocate["photo"] != ""))
$relocate["avatar"] = $relocate["photo"]; $relocate["avatar"] = $relocate["photo"];
}
if ($relocate["addr"] == "") { if ($relocate["addr"] == "")
$relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]); $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
}
// update contact // update contact
$r = q("SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;", $r = q("SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
intval($importer["id"]), intval($importer["id"]),
intval($importer["importer_uid"])); intval($importer["importer_uid"]));
if (!$r)
if (!dbm::is_result($r)) { return false;
/// @todo Don't die quietly
killme();
}
$old = $r[0]; $old = $r[0];
@ -1790,9 +1652,8 @@ class dfrn {
update_contact_avatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true); update_contact_avatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
if ($x === false) { if ($x === false)
return false; return false;
}
// update items // update items
/// @todo This is an extreme performance killer /// @todo This is an extreme performance killer
@ -1807,17 +1668,15 @@ class dfrn {
$n, dbesc($f[0]), $n, dbesc($f[0]),
intval($importer["importer_uid"])); intval($importer["importer_uid"]));
if (dbm::is_result($r)) { if ($r) {
$x = q("UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d", $x = q("UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
$n, dbesc($f[1]), $n, dbesc($f[1]),
$n, dbesc($f[0]), $n, dbesc($f[0]),
intval($importer["importer_uid"])); intval($importer["importer_uid"]));
if ($x === false)
if ($x === false) {
return false; return false;
} }
} }
}
/// @TODO /// @TODO
/// merge with current record, current contents have priority /// merge with current record, current contents have priority
@ -1858,10 +1717,9 @@ class dfrn {
$changed = true; $changed = true;
if ($entrytype == DFRN_REPLY_RC) { if ($entrytype == DFRN_REPLY_RC)
proc_run(PRIORITY_HIGH, "include/notifier.php","comment-import", $current["id"]); proc_run(PRIORITY_HIGH, "include/notifier.php","comment-import", $current["id"]);
} }
}
// update last-child if it changes // update last-child if it changes
if($item["last-child"] AND ($item["last-child"] != $current["last-child"])) { if($item["last-child"] AND ($item["last-child"] != $current["last-child"])) {
@ -1896,9 +1754,8 @@ class dfrn {
$sql_extra = ""; $sql_extra = "";
$community = true; $community = true;
logger("possible community action"); logger("possible community action");
} else { } else
$sql_extra = " AND `contact`.`self` AND `item`.`wall` "; $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
}
// was the top-level post for this action written by somebody on this site? // was the top-level post for this action written by somebody on this site?
// Specifically, the recipient? // Specifically, the recipient?
@ -1922,10 +1779,9 @@ class dfrn {
dbesc($r[0]["parent-uri"]), dbesc($r[0]["parent-uri"]),
intval($importer["importer_uid"]) intval($importer["importer_uid"])
); );
if (dbm::is_result($r)) { if (dbm::is_result($r))
$is_a_remote_action = true; $is_a_remote_action = true;
} }
}
// Does this have the characteristics of a community or private group action? // Does this have the characteristics of a community or private group action?
// If it's an action to a wall post on a community/prvgroup page it's a // If it's an action to a wall post on a community/prvgroup page it's a
@ -1939,15 +1795,13 @@ class dfrn {
} }
} }
if ($is_a_remote_action) { if ($is_a_remote_action)
return DFRN_REPLY_RC; return DFRN_REPLY_RC;
} else { else
return DFRN_REPLY; return DFRN_REPLY;
}
} else { } else
return DFRN_TOP_LEVEL; return DFRN_TOP_LEVEL;
}
} }
@ -1960,9 +1814,8 @@ class dfrn {
*/ */
private static function do_poke($item, $importer, $posted_id) { private static function do_poke($item, $importer, $posted_id) {
$verb = urldecode(substr($item["verb"],strpos($item["verb"], "#")+1)); $verb = urldecode(substr($item["verb"],strpos($item["verb"], "#")+1));
if (!$verb) { if(!$verb)
return; return;
}
$xo = parse_xml_string($item["object"],false); $xo = parse_xml_string($item["object"],false);
if(($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) { if(($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
@ -2064,9 +1917,8 @@ class dfrn {
dbesc($item["verb"]), dbesc($item["verb"]),
dbesc($item["parent-uri"]) dbesc($item["parent-uri"])
); );
if (dbm::is_result($r)) { if (dbm::is_result($r))
return false; return false;
}
$r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1", $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
intval($item["uid"]), intval($item["uid"]),
@ -2074,12 +1926,10 @@ class dfrn {
dbesc($item["verb"]), dbesc($item["verb"]),
dbesc($item["parent-uri"]) dbesc($item["parent-uri"])
); );
if (dbm::is_result($r)) { if (dbm::is_result($r))
return false; return false;
} } else
} else {
$is_like = false; $is_like = false;
}
if(($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) { if(($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
@ -2092,9 +1942,8 @@ class dfrn {
intval($importer["importer_uid"]) intval($importer["importer_uid"])
); );
if (!dbm::is_result($r)) { if (!dbm::is_result($r))
killme(); return false;
}
// extract tag, if not duplicate, add to parent item // extract tag, if not duplicate, add to parent item
if($xo->content) { if($xo->content) {
@ -2117,7 +1966,6 @@ class dfrn {
* *
* @param object $links link elements * @param object $links link elements
* @param array $item the item record * @param array $item the item record
* @todo Add type-hints
*/ */
private static function parse_links($links, &$item) { private static function parse_links($links, &$item) {
$rel = ""; $rel = "";
@ -2127,23 +1975,17 @@ class dfrn {
$title = ""; $title = "";
foreach ($links AS $link) { foreach ($links AS $link) {
foreach($link->attributes AS $attributes) { foreach($link->attributes AS $attributes) {
/// @TODO Rewrite these repeated (same) if () statements to a switch() if ($attributes->name == "href")
if ($attributes->name == "href") {
$href = $attributes->textContent; $href = $attributes->textContent;
} if ($attributes->name == "rel")
if ($attributes->name == "rel") {
$rel = $attributes->textContent; $rel = $attributes->textContent;
} if ($attributes->name == "type")
if ($attributes->name == "type") {
$type = $attributes->textContent; $type = $attributes->textContent;
} if ($attributes->name == "length")
if ($attributes->name == "length") {
$length = $attributes->textContent; $length = $attributes->textContent;
} if ($attributes->name == "title")
if ($attributes->name == "title") {
$title = $attributes->textContent; $title = $attributes->textContent;
} }
}
if (($rel != "") AND ($href != "")) if (($rel != "") AND ($href != ""))
switch($rel) { switch($rel) {
case "alternate": case "alternate":
@ -2151,9 +1993,8 @@ class dfrn {
break; break;
case "enclosure": case "enclosure":
$enclosure = $href; $enclosure = $href;
if (strlen($item["attach"])) { if(strlen($item["attach"]))
$item["attach"] .= ","; $item["attach"] .= ",";
}
$item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'" title="'.$title.'"[/attach]'; $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'" title="'.$title.'"[/attach]';
break; break;
@ -2168,7 +2009,6 @@ class dfrn {
* @param object $xpath XPath object * @param object $xpath XPath object
* @param object $entry entry elements * @param object $entry entry elements
* @param array $importer Record of the importer user mixed with contact of the content * @param array $importer Record of the importer user mixed with contact of the content
* @todo Add type-hints
*/ */
private static function process_entry($header, $xpath, $entry, $importer) { private static function process_entry($header, $xpath, $entry, $importer) {
@ -2248,50 +2088,44 @@ class dfrn {
$item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue; $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
$georsspoint = $xpath->query("georss:point", $entry); $georsspoint = $xpath->query("georss:point", $entry);
if ($georsspoint) { if ($georsspoint)
$item["coord"] = $georsspoint->item(0)->nodeValue; $item["coord"] = $georsspoint->item(0)->nodeValue;
}
$item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue; $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
$item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue; $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") { if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true")
$item["bookmark"] = true; $item["bookmark"] = true;
}
$notice_info = $xpath->query("statusnet:notice_info", $entry); $notice_info = $xpath->query("statusnet:notice_info", $entry);
if ($notice_info AND ($notice_info->length > 0)) { if ($notice_info AND ($notice_info->length > 0)) {
foreach($notice_info->item(0)->attributes AS $attributes) { foreach($notice_info->item(0)->attributes AS $attributes) {
if ($attributes->name == "source") { if ($attributes->name == "source")
$item["app"] = strip_tags($attributes->textContent); $item["app"] = strip_tags($attributes->textContent);
} }
} }
}
$item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue; $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
// We store the data from "dfrn:diaspora_signature" in a different table, this is done in "item_store" // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "item_store"
$dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue); $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
if ($dsprsig != "") { if ($dsprsig != "")
$item["dsprsig"] = $dsprsig; $item["dsprsig"] = $dsprsig;
}
$item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue; $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") { if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "")
$item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue; $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
}
$object = $xpath->query("activity:object", $entry)->item(0); $object = $xpath->query("activity:object", $entry)->item(0);
$item["object"] = self::transform_activity($xpath, $object, "object"); $item["object"] = self::transform_activity($xpath, $object, "object");
if (trim($item["object"]) != "") { if (trim($item["object"]) != "") {
$r = parse_xml_string($item["object"], false); $r = parse_xml_string($item["object"], false);
if (isset($r->type)) { if (isset($r->type))
$item["object-type"] = $r->type; $item["object-type"] = $r->type;
} }
}
$target = $xpath->query("activity:target", $entry)->item(0); $target = $xpath->query("activity:target", $entry)->item(0);
$item["target"] = self::transform_activity($xpath, $target, "target"); $item["target"] = self::transform_activity($xpath, $target, "target");
@ -2302,14 +2136,12 @@ class dfrn {
$term = ""; $term = "";
$scheme = ""; $scheme = "";
foreach($category->attributes AS $attributes) { foreach($category->attributes AS $attributes) {
if ($attributes->name == "term") { if ($attributes->name == "term")
$term = $attributes->textContent; $term = $attributes->textContent;
}
if ($attributes->name == "scheme") { if ($attributes->name == "scheme")
$scheme = $attributes->textContent; $scheme = $attributes->textContent;
} }
}
if (($term != "") AND ($scheme != "")) { if (($term != "") AND ($scheme != "")) {
$parts = explode(":", $scheme); $parts = explode(":", $scheme);
@ -2317,9 +2149,8 @@ class dfrn {
$termhash = array_shift($parts); $termhash = array_shift($parts);
$termurl = implode(":", $parts); $termurl = implode(":", $parts);
if (strlen($item["tag"])) { if(strlen($item["tag"]))
$item["tag"] .= ","; $item["tag"] .= ",";
}
$item["tag"] .= $termhash."[url=".$termurl."]".$term."[/url]"; $item["tag"] .= $termhash."[url=".$termurl."]".$term."[/url]";
} }
@ -2330,46 +2161,37 @@ class dfrn {
$enclosure = ""; $enclosure = "";
$links = $xpath->query("atom:link", $entry); $links = $xpath->query("atom:link", $entry);
if ($links) { if ($links)
self::parse_links($links, $item); self::parse_links($links, $item);
}
// Is it a reply or a top level posting? // Is it a reply or a top level posting?
$item["parent-uri"] = $item["uri"]; $item["parent-uri"] = $item["uri"];
$inreplyto = $xpath->query("thr:in-reply-to", $entry); $inreplyto = $xpath->query("thr:in-reply-to", $entry);
if (is_object($inreplyto->item(0))) { if (is_object($inreplyto->item(0)))
foreach ($inreplyto->item(0)->attributes AS $attributes) { foreach($inreplyto->item(0)->attributes AS $attributes)
if ($attributes->name == "ref") { if ($attributes->name == "ref")
$item["parent-uri"] = $attributes->textContent; $item["parent-uri"] = $attributes->textContent;
}
}
}
// Get the type of the item (Top level post, reply or remote reply) // Get the type of the item (Top level post, reply or remote reply)
$entrytype = self::get_entry_type($importer, $item); $entrytype = self::get_entry_type($importer, $item);
// Now assign the rest of the values that depend on the type of the message // Now assign the rest of the values that depend on the type of the message
if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) { if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
if (!isset($item["object-type"])) { if (!isset($item["object-type"]))
$item["object-type"] = ACTIVITY_OBJ_COMMENT; $item["object-type"] = ACTIVITY_OBJ_COMMENT;
}
if ($item["contact-id"] != $owner["contact-id"]) { if ($item["contact-id"] != $owner["contact-id"])
$item["contact-id"] = $owner["contact-id"]; $item["contact-id"] = $owner["contact-id"];
}
if (($item["network"] != $owner["network"]) AND ($owner["network"] != "")) { if (($item["network"] != $owner["network"]) AND ($owner["network"] != ""))
$item["network"] = $owner["network"]; $item["network"] = $owner["network"];
}
if ($item["contact-id"] != $author["contact-id"]) { if ($item["contact-id"] != $author["contact-id"])
$item["contact-id"] = $author["contact-id"]; $item["contact-id"] = $author["contact-id"];
}
if (($item["network"] != $author["network"]) AND ($author["network"] != "")) { if (($item["network"] != $author["network"]) AND ($author["network"] != ""))
$item["network"] = $author["network"]; $item["network"] = $author["network"];
}
// This code was taken from the old DFRN code // This code was taken from the old DFRN code
// When activated, forums don't work. // When activated, forums don't work.
@ -2385,9 +2207,8 @@ class dfrn {
$item["type"] = "remote-comment"; $item["type"] = "remote-comment";
$item["wall"] = 1; $item["wall"] = 1;
} elseif ($entrytype == DFRN_TOP_LEVEL) { } elseif ($entrytype == DFRN_TOP_LEVEL) {
if (!isset($item["object-type"])) { if (!isset($item["object-type"]))
$item["object-type"] = ACTIVITY_OBJ_NOTE; $item["object-type"] = ACTIVITY_OBJ_NOTE;
}
// Is it an event? // Is it an event?
if ($item["object-type"] == ACTIVITY_OBJ_EVENT) { if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
@ -2406,9 +2227,8 @@ class dfrn {
dbesc($item["uri"]), dbesc($item["uri"]),
intval($importer["uid"]) intval($importer["uid"])
); );
if (dbm::is_result($r)) { if (dbm::is_result($r))
$ev["id"] = $r[0]["id"]; $ev["id"] = $r[0]["id"];
}
$event_id = event_store($ev); $event_id = event_store($ev);
logger("Event ".$event_id." was stored", LOGGER_DEBUG); logger("Event ".$event_id." was stored", LOGGER_DEBUG);
@ -2426,9 +2246,8 @@ class dfrn {
if (dbm::is_result($current)) { if (dbm::is_result($current)) {
if (self::update_content($r[0], $item, $importer, $entrytype)) if (self::update_content($r[0], $item, $importer, $entrytype))
logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG); logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
} else { else
logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG); logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
}
return; return;
} }
@ -2514,22 +2333,18 @@ class dfrn {
logger("Processing deletions"); logger("Processing deletions");
foreach($deletion->attributes AS $attributes) { foreach($deletion->attributes AS $attributes) {
if ($attributes->name == "ref") { if ($attributes->name == "ref")
$uri = $attributes->textContent; $uri = $attributes->textContent;
} if ($attributes->name == "when")
if ($attributes->name == "when") {
$when = $attributes->textContent; $when = $attributes->textContent;
} }
} if ($when)
if ($when) {
$when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s"); $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
} else { else
$when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s"); $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
}
if (!$uri OR !$importer["id"]) { if (!$uri OR !$importer["id"])
return false; return false;
}
/// @todo Only select the used fields /// @todo Only select the used fields
$r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id` $r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
@ -2547,11 +2362,10 @@ class dfrn {
$entrytype = self::get_entry_type($importer, $item); $entrytype = self::get_entry_type($importer, $item);
if (!$item["deleted"]) { if(!$item["deleted"])
logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG); logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
} else { else
return; return;
}
if($item["object-type"] == ACTIVITY_OBJ_EVENT) { if($item["object-type"] == ACTIVITY_OBJ_EVENT) {
logger("Deleting event ".$item["event-id"], LOGGER_DEBUG); logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
@ -2576,19 +2390,16 @@ class dfrn {
$author_remove = (($item["origin"] && $item["self"]) ? true : false); $author_remove = (($item["origin"] && $item["self"]) ? true : false);
$author_copy = (($item["origin"]) ? true : false); $author_copy = (($item["origin"]) ? true : false);
if ($owner_remove && $author_copy) { if($owner_remove && $author_copy)
return; return;
}
if($author_remove || $owner_remove) { if($author_remove || $owner_remove) {
$tags = explode(',',$i[0]["tag"]); $tags = explode(',',$i[0]["tag"]);
$newtags = array(); $newtags = array();
if(count($tags)) { if(count($tags)) {
foreach ($tags as $tag) { foreach($tags as $tag)
if (trim($tag) !== trim($xo->body)) { if(trim($tag) !== trim($xo->body))
$newtags[] = trim($tag); $newtags[] = trim($tag);
} }
}
}
q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d", q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
dbesc(implode(',',$newtags)), dbesc(implode(',',$newtags)),
intval($i[0]["id"]) intval($i[0]["id"])
@ -2697,14 +2508,12 @@ class dfrn {
// Update the contact table if the data has changed // Update the contact table if the data has changed
// The "atom:author" is only present in feeds // The "atom:author" is only present in feeds
if ($xpath->query("/atom:feed/atom:author")->length > 0) { if ($xpath->query("/atom:feed/atom:author")->length > 0)
self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml); self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
}
// Only the "dfrn:owner" in the head section contains all data // Only the "dfrn:owner" in the head section contains all data
if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) { if ($xpath->query("/atom:feed/dfrn:owner")->length > 0)
self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml); self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
}
logger("Import DFRN message for user ".$importer["uid"]." from contact ".$importer["id"], LOGGER_DEBUG); logger("Import DFRN message for user ".$importer["uid"]." from contact ".$importer["id"], LOGGER_DEBUG);
@ -2712,50 +2521,43 @@ class dfrn {
if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) { if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
$accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()", $context)->item(0)->nodeValue); $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()", $context)->item(0)->nodeValue);
if ($accounttype != $importer["contact-type"]) { if ($accounttype != $importer["contact-type"])
q("UPDATE `contact` SET `contact-type` = %d WHERE `id` = %d", q("UPDATE `contact` SET `contact-type` = %d WHERE `id` = %d",
intval($accounttype), intval($accounttype),
intval($importer["id"]) intval($importer["id"])
); );
} }
}
// is it a public forum? Private forums aren't supported with this method // is it a public forum? Private forums aren't supported with this method
// This is deprecated since 3.5.1 // This is deprecated since 3.5.1
$forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()", $context)->item(0)->nodeValue); $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()", $context)->item(0)->nodeValue);
if ($forum != $importer["forum"]) { if ($forum != $importer["forum"])
q("UPDATE `contact` SET `forum` = %d WHERE `forum` != %d AND `id` = %d", q("UPDATE `contact` SET `forum` = %d WHERE `forum` != %d AND `id` = %d",
intval($forum), intval($forum), intval($forum), intval($forum),
intval($importer["id"]) intval($importer["id"])
); );
}
$mails = $xpath->query("/atom:feed/dfrn:mail"); $mails = $xpath->query("/atom:feed/dfrn:mail");
foreach ($mails AS $mail) { foreach ($mails AS $mail)
self::process_mail($xpath, $mail, $importer); self::process_mail($xpath, $mail, $importer);
}
$suggestions = $xpath->query("/atom:feed/dfrn:suggest"); $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
foreach ($suggestions AS $suggestion) { foreach ($suggestions AS $suggestion)
self::process_suggestion($xpath, $suggestion, $importer); self::process_suggestion($xpath, $suggestion, $importer);
}
$relocations = $xpath->query("/atom:feed/dfrn:relocate"); $relocations = $xpath->query("/atom:feed/dfrn:relocate");
foreach ($relocations AS $relocation) { foreach ($relocations AS $relocation)
self::process_relocation($xpath, $relocation, $importer); self::process_relocation($xpath, $relocation, $importer);
}
$deletions = $xpath->query("/atom:feed/at:deleted-entry"); $deletions = $xpath->query("/atom:feed/at:deleted-entry");
foreach ($deletions AS $deletion) { foreach ($deletions AS $deletion)
self::process_deletion($xpath, $deletion, $importer); self::process_deletion($xpath, $deletion, $importer);
}
if (!$sort_by_date) { if (!$sort_by_date) {
$entries = $xpath->query("/atom:feed/atom:entry"); $entries = $xpath->query("/atom:feed/atom:entry");
foreach ($entries AS $entry) { foreach ($entries AS $entry)
self::process_entry($header, $xpath, $entry, $importer); self::process_entry($header, $xpath, $entry, $importer);
}
} else { } else {
$newentries = array(); $newentries = array();
$entries = $xpath->query("/atom:feed/atom:entry"); $entries = $xpath->query("/atom:feed/atom:entry");
@ -2767,10 +2569,9 @@ class dfrn {
// Now sort after the publishing date // Now sort after the publishing date
ksort($newentries); ksort($newentries);
foreach ($newentries AS $entry) { foreach ($newentries AS $entry)
self::process_entry($header, $xpath, $entry, $importer); self::process_entry($header, $xpath, $entry, $importer);
} }
}
logger("Import done for user ".$importer["uid"]." from contact ".$importer["id"], LOGGER_DEBUG); logger("Import done for user ".$importer["uid"]." from contact ".$importer["id"], LOGGER_DEBUG);
} }
} }

View file

@ -3632,20 +3632,17 @@ class Diaspora {
} }
$r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid'])); $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
if (!dbm::is_result($r)) { if(!$r)
return false; return false;
}
$contact["uprvkey"] = $r[0]['prvkey']; $contact["uprvkey"] = $r[0]['prvkey'];
$r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id)); $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
if (!dbm::is_result($r)) { if (!$r)
return false; return false;
}
if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) { if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE)))
return false; return false;
}
$message = self::construct_like($r[0], $contact); $message = self::construct_like($r[0], $contact);
$message["author_signature"] = self::signature($contact, $message); $message["author_signature"] = self::signature($contact, $message);

View file

@ -207,7 +207,7 @@ function discover_directory($search) {
foreach($j->results as $jj) { foreach($j->results as $jj) {
// Check if the contact already exists // Check if the contact already exists
$exists = q("SELECT `id`, `last_contact`, `last_failure`, `updated` FROM `gcontact` WHERE `nurl` = '%s'", normalise_link($jj->url)); $exists = q("SELECT `id`, `last_contact`, `last_failure`, `updated` FROM `gcontact` WHERE `nurl` = '%s'", normalise_link($jj->url));
if (dbm::is_result($exists)) { if ($exists) {
logger("Profile ".$jj->url." already exists (".$search.")", LOGGER_DEBUG); logger("Profile ".$jj->url." already exists (".$search.")", LOGGER_DEBUG);
if (($exists[0]["last_contact"] < $exists[0]["last_failure"]) AND if (($exists[0]["last_contact"] < $exists[0]["last_failure"]) AND
@ -260,13 +260,11 @@ function gs_search_user($search) {
if (!$result["success"]) { if (!$result["success"]) {
return false; return false;
} }
$contacts = json_decode($result["body"]); $contacts = json_decode($result["body"]);
if ($contacts->status == 'ERROR') { if ($contacts->status == 'ERROR') {
return false; return false;
} }
foreach($contacts->data AS $user) { foreach($contacts->data AS $user) {
$contact = probe_url($user->site_address."/".$user->name); $contact = probe_url($user->site_address."/".$user->name);
if ($contact["network"] != NETWORK_PHANTOM) { if ($contact["network"] != NETWORK_PHANTOM) {

View file

@ -411,12 +411,10 @@ function notification($params) {
$hash = random_string(); $hash = random_string();
$r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1", $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1",
dbesc($hash)); dbesc($hash));
if (dbm::is_result($r)) { if (dbm::is_result($r))
$dups = true; $dups = true;
}
} while($dups == true); } while($dups == true);
/// @TODO One statement is enough
$datarray = array(); $datarray = array();
$datarray['hash'] = $hash; $datarray['hash'] = $hash;
$datarray['name'] = $params['source_name']; $datarray['name'] = $params['source_name'];

View file

@ -11,13 +11,12 @@ function expire_run(&$argv, &$argc){
// physically remove anything that has been deleted for more than two months // physically remove anything that has been deleted for more than two months
$r = q("DELETE FROM `item` WHERE `deleted` = 1 AND `changed` < UTC_TIMESTAMP() - INTERVAL 60 DAY"); $r = q("delete from item where deleted = 1 and changed < UTC_TIMESTAMP() - INTERVAL 60 DAY");
// make this optional as it could have a performance impact on large sites // make this optional as it could have a performance impact on large sites
if (intval(get_config('system','optimize_items'))) { if(intval(get_config('system','optimize_items')))
q("OPTIMIZE TABLE `item`"); q("optimize table item");
}
logger('expire: start'); logger('expire: start');

View file

@ -289,9 +289,8 @@ function feed_import($xml,$importer,&$contact, &$hub, $simulate = false) {
$type = $attributes->textContent; $type = $attributes->textContent;
} }
} }
if (strlen($item["attach"])) { if(strlen($item["attach"]))
$item["attach"] .= ','; $item["attach"] .= ',';
}
$attachments[] = array("link" => $href, "type" => $type, "length" => $length); $attachments[] = array("link" => $href, "type" => $type, "length" => $length);

View file

@ -347,10 +347,9 @@ function groups_containing($uid,$c) {
$ret = array(); $ret = array();
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
foreach ($r as $rr) { foreach($r as $rr)
$ret[] = $rr['gid']; $ret[] = $rr['gid'];
} }
}
return $ret; return $ret;
} }

View file

@ -878,20 +878,16 @@ function zrl_init(App $a) {
} }
function zrl($s,$force = false) { function zrl($s,$force = false) {
if (! strlen($s)) { if(! strlen($s))
return $s; return $s;
} if((! strpos($s,'/profile/')) && (! $force))
if ((! strpos($s,'/profile/')) && (! $force)) {
return $s; return $s;
} if($force && substr($s,-1,1) !== '/')
if ($force && substr($s,-1,1) !== '/') {
$s = $s . '/'; $s = $s . '/';
}
$achar = strpos($s,'?') ? '&' : '?'; $achar = strpos($s,'?') ? '&' : '?';
$mine = get_my_url(); $mine = get_my_url();
if ($mine and ! link_compare($mine,$s)) { if($mine and ! link_compare($mine,$s))
return $s . $achar . 'zrl=' . urlencode($mine); return $s . $achar . 'zrl=' . urlencode($mine);
}
return $s; return $s;
} }
@ -912,10 +908,9 @@ function zrl($s,$force = false) {
function get_theme_uid() { function get_theme_uid() {
$uid = (($_REQUEST['puid']) ? intval($_REQUEST['puid']) : 0); $uid = (($_REQUEST['puid']) ? intval($_REQUEST['puid']) : 0);
if(local_user()) { if(local_user()) {
if ((get_pconfig(local_user(),'system','always_my_theme')) || (! $uid)) { if((get_pconfig(local_user(),'system','always_my_theme')) || (! $uid))
return local_user(); return local_user();
} }
}
return $uid; return $uid;
} }

View file

@ -57,9 +57,8 @@ function block_on_function_lock($fn_name, $wait_sec = 2, $timeout = 30) {
dbesc($fn_name) dbesc($fn_name)
); );
if (dbm::is_result($r) && $r[0]['locked']) { if (dbm::is_result($r) && $r[0]['locked'])
sleep($wait_sec); sleep($wait_sec);
}
} while(dbm::is_result($r) && $r[0]['locked'] && ((time() - $start) < $timeout)); } while(dbm::is_result($r) && $r[0]['locked'] && ((time() - $start) < $timeout));

View file

@ -497,15 +497,14 @@ function allowed_url($url) {
*/ */
function allowed_email($email) { function allowed_email($email) {
$domain = strtolower(substr($email,strpos($email,'@') + 1)); $domain = strtolower(substr($email,strpos($email,'@') + 1));
if (! $domain) { if(! $domain)
return false; return false;
}
$str_allowed = get_config('system','allowed_email'); $str_allowed = get_config('system','allowed_email');
if (! $str_allowed) { if(! $str_allowed)
return true; return true;
}
$found = false; $found = false;

View file

@ -316,9 +316,7 @@ function oembed_html2bbcode($text) {
$xattr = "@rel='oembed'";//oe_build_xpath("rel","oembed"); $xattr = "@rel='oembed'";//oe_build_xpath("rel","oembed");
foreach($entries as $e) { foreach($entries as $e) {
$href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue; $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
if (!is_null($href)) { if(!is_null($href)) $e->parentNode->replaceChild(new DOMText("[embed]".$href."[/embed]"), $e);
$e->parentNode->replaceChild(new DOMText("[embed]".$href."[/embed]"), $e);
}
} }
return oe_get_inner_html( $dom->getElementsByTagName("body")->item(0) ); return oe_get_inner_html( $dom->getElementsByTagName("body")->item(0) );
} else { } else {

View file

@ -61,7 +61,7 @@ function onepoll_run(&$argv, &$argc){
intval($contact_id) intval($contact_id)
); );
if (! dbm::is_result($contacts)) { if (! count($contacts)) {
return; return;
} }
@ -437,19 +437,17 @@ function onepoll_run(&$argv, &$argc){
if ($raw_refs) { if ($raw_refs) {
$refs_arr = explode(' ', $raw_refs); $refs_arr = explode(' ', $raw_refs);
if (count($refs_arr)) { if (count($refs_arr)) {
for ($x = 0; $x < count($refs_arr); $x ++) { for($x = 0; $x < count($refs_arr); $x ++)
$refs_arr[$x] = "'" . msgid2iri(str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x]))) . "'"; $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x]))) . "'";
} }
}
$qstr = implode(',',$refs_arr); $qstr = implode(',',$refs_arr);
$r = q("SELECT `uri` , `parent-uri` FROM `item` USE INDEX (`uid_uri`) WHERE `uri` IN ($qstr) AND `uid` = %d LIMIT 1", $r = q("SELECT `uri` , `parent-uri` FROM `item` USE INDEX (`uid_uri`) WHERE `uri` IN ($qstr) AND `uid` = %d LIMIT 1",
intval($importer_uid) intval($importer_uid)
); );
if (dbm::is_result($r)) { if (dbm::is_result($r))
$datarray['parent-uri'] = $r[0]['parent-uri']; // Set the parent as the top-level item $datarray['parent-uri'] = $r[0]['parent-uri']; // Set the parent as the top-level item
// $datarray['parent-uri'] = $r[0]['uri']; // $datarray['parent-uri'] = $r[0]['uri'];
} }
}
// Decoding the header // Decoding the header
$subject = imap_mime_header_decode($meta->subject); $subject = imap_mime_header_decode($meta->subject);

View file

@ -37,11 +37,9 @@ class ostatus {
* @param bool $onlyfetch Only fetch the header without updating the contact entries * @param bool $onlyfetch Only fetch the header without updating the contact entries
* *
* @return array Array of author related entries for the item * @return array Array of author related entries for the item
* @todo Add type-hints
*/ */
private function fetchauthor($xpath, $context, $importer, &$contact, $onlyfetch) { private function fetchauthor($xpath, $context, $importer, &$contact, $onlyfetch) {
/// @TODO One statment is enough ...
$author = array(); $author = array();
$author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue; $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
$author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue; $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
@ -49,24 +47,19 @@ class ostatus {
$aliaslink = $author["author-link"]; $aliaslink = $author["author-link"];
$alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes; $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
if (is_object($alternate)) { if (is_object($alternate))
/// @TODO foreach () may only later work on objects that have iterator interface implemented, please check this foreach($alternate AS $attributes)
foreach ($alternate AS $attributes) { if ($attributes->name == "href")
if ($attributes->name == "href") {
$author["author-link"] = $attributes->textContent; $author["author-link"] = $attributes->textContent;
}
}
}
$r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` IN ('%s', '%s') AND `network` != '%s'", $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` IN ('%s', '%s') AND `network` != '%s'",
intval($importer["uid"]), dbesc(normalise_link($author["author-link"])), intval($importer["uid"]), dbesc(normalise_link($author["author-link"])),
dbesc(normalise_link($aliaslink)), dbesc(NETWORK_STATUSNET)); dbesc(normalise_link($aliaslink)), dbesc(NETWORK_STATUSNET));
if (dbm::is_result($r)) { if ($r) {
$contact = $r[0]; $contact = $r[0];
$author["contact-id"] = $r[0]["id"]; $author["contact-id"] = $r[0]["id"];
} else { } else
$author["contact-id"] = $contact["id"]; $author["contact-id"] = $contact["id"];
}
$avatarlist = array(); $avatarlist = array();
$avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context); $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
@ -74,33 +67,29 @@ class ostatus {
$href = ""; $href = "";
$width = 0; $width = 0;
foreach($avatar->attributes AS $attributes) { foreach($avatar->attributes AS $attributes) {
if ($attributes->name == "href") { if ($attributes->name == "href")
$href = $attributes->textContent; $href = $attributes->textContent;
} if ($attributes->name == "width")
if ($attributes->name == "width") {
$width = $attributes->textContent; $width = $attributes->textContent;
} }
} if (($width > 0) AND ($href != ""))
if (($width > 0) AND ($href != "")) {
$avatarlist[$width] = $href; $avatarlist[$width] = $href;
} }
}
if (count($avatarlist) > 0) { if (count($avatarlist) > 0) {
krsort($avatarlist); krsort($avatarlist);
$author["author-avatar"] = current($avatarlist); $author["author-avatar"] = current($avatarlist);
} }
$displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue; $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
if ($displayname != "") { if ($displayname != "")
$author["author-name"] = $displayname; $author["author-name"] = $displayname;
}
$author["owner-name"] = $author["author-name"]; $author["owner-name"] = $author["author-name"];
$author["owner-link"] = $author["author-link"]; $author["owner-link"] = $author["author-link"];
$author["owner-avatar"] = $author["author-avatar"]; $author["owner-avatar"] = $author["author-avatar"];
// Only update the contacts if it is an OStatus contact // Only update the contacts if it is an OStatus contact
if (dbm::is_result($r) AND !$onlyfetch AND ($contact["network"] == NETWORK_OSTATUS)) { if ($r AND !$onlyfetch AND ($contact["network"] == NETWORK_OSTATUS)) {
// Update contact data // Update contact data
@ -115,29 +104,24 @@ class ostatus {
// $contact["poll"] = $value; // $contact["poll"] = $value;
$value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue; $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
if ($value != "") { if ($value != "")
$contact["alias"] = $value; $contact["alias"] = $value;
}
$value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue; $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
if ($value != "") { if ($value != "")
$contact["name"] = $value; $contact["name"] = $value;
}
$value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue; $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
if ($value != "") { if ($value != "")
$contact["nick"] = $value; $contact["nick"] = $value;
}
$value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue; $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
if ($value != "") { if ($value != "")
$contact["about"] = html2bbcode($value); $contact["about"] = html2bbcode($value);
}
$value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue; $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
if ($value != "") { if ($value != "")
$contact["location"] = $value; $contact["location"] = $value;
}
if (($contact["name"] != $r[0]["name"]) OR ($contact["nick"] != $r[0]["nick"]) OR ($contact["about"] != $r[0]["about"]) OR if (($contact["name"] != $r[0]["name"]) OR ($contact["nick"] != $r[0]["nick"]) OR ($contact["about"] != $r[0]["about"]) OR
($contact["alias"] != $r[0]["alias"]) OR ($contact["location"] != $r[0]["location"])) { ($contact["alias"] != $r[0]["alias"]) OR ($contact["location"] != $r[0]["location"])) {
@ -192,16 +176,14 @@ class ostatus {
* @param array $importer user record of the importing user * @param array $importer user record of the importing user
* *
* @return array Array of author related entries for the item * @return array Array of author related entries for the item
* @todo add type-hints
*/ */
public static function salmon_author($xml, $importer) { public static function salmon_author($xml, $importer) {
if ($xml == "") { if ($xml == "")
return; return;
}
$doc = new DOMDocument(); $doc = new DOMDocument();
$doc->loadXML($xml); @$doc->loadXML($xml);
$xpath = new DomXPath($doc); $xpath = new DomXPath($doc);
$xpath->registerNamespace('atom', NAMESPACE_ATOM1); $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
@ -229,22 +211,20 @@ class ostatus {
* @param array $importer user record of the importing user * @param array $importer user record of the importing user
* @param $contact * @param $contact
* @param array $hub Called by reference, returns the fetched hub data * @param array $hub Called by reference, returns the fetched hub data
* @todo Add missing-type hint + determine type for $contact
*/ */
public static function import($xml,$importer,&$contact, &$hub) { public static function import($xml,$importer,&$contact, &$hub) {
/// @todo this function is too long. It has to be split in many parts /// @todo this function is too long. It has to be split in many parts
logger("Import OStatus message", LOGGER_DEBUG); logger("Import OStatus message", LOGGER_DEBUG);
if ($xml == "") { if ($xml == "")
return; return;
}
//$tempfile = tempnam(get_temppath(), "import"); //$tempfile = tempnam(get_temppath(), "import");
//file_put_contents($tempfile, $xml); //file_put_contents($tempfile, $xml);
$doc = new DOMDocument(); $doc = new DOMDocument();
$doc->loadXML($xml); @$doc->loadXML($xml);
$xpath = new DomXPath($doc); $xpath = new DomXPath($doc);
$xpath->registerNamespace('atom', NAMESPACE_ATOM1); $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
@ -258,16 +238,13 @@ class ostatus {
$gub = ""; $gub = "";
$hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes; $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
if (is_object($hub_attributes)) { if (is_object($hub_attributes))
foreach ($hub_attributes AS $hub_attribute) { foreach($hub_attributes AS $hub_attribute)
if ($hub_attribute->name == "href") { if ($hub_attribute->name == "href") {
$hub = $hub_attribute->textContent; $hub = $hub_attribute->textContent;
logger("Found hub ".$hub, LOGGER_DEBUG); logger("Found hub ".$hub, LOGGER_DEBUG);
} }
}
}
/// @TODO One statement is enough ...
$header = array(); $header = array();
$header["uid"] = $importer["uid"]; $header["uid"] = $importer["uid"];
$header["network"] = NETWORK_OSTATUS; $header["network"] = NETWORK_OSTATUS;
@ -280,11 +257,10 @@ class ostatus {
// depending on that, the first node is different // depending on that, the first node is different
$first_child = $doc->firstChild->tagName; $first_child = $doc->firstChild->tagName;
if ($first_child == "feed") { if ($first_child == "feed")
$entries = $xpath->query('/atom:feed/atom:entry'); $entries = $xpath->query('/atom:feed/atom:entry');
} else { else
$entries = $xpath->query('/atom:entry'); $entries = $xpath->query('/atom:entry');
}
$conversation = ""; $conversation = "";
$conversationlist = array(); $conversationlist = array();
@ -301,18 +277,16 @@ class ostatus {
$mention = false; $mention = false;
// fetch the author // fetch the author
if ($first_child == "feed") { if ($first_child == "feed")
$author = self::fetchauthor($xpath, $doc->firstChild, $importer, $contact, false); $author = self::fetchauthor($xpath, $doc->firstChild, $importer, $contact, false);
} else { else
$author = self::fetchauthor($xpath, $entry, $importer, $contact, false); $author = self::fetchauthor($xpath, $entry, $importer, $contact, false);
}
$value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue; $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
if ($value != "") { if ($value != "")
$nickname = $value; $nickname = $value;
} else { else
$nickname = $author["author-name"]; $nickname = $author["author-name"];
}
$item = array_merge($header, $author); $item = array_merge($header, $author);
@ -321,7 +295,7 @@ class ostatus {
$r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'", $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
intval($importer["uid"]), dbesc($item["uri"])); intval($importer["uid"]), dbesc($item["uri"]));
if (dbm::is_result($r)) { if ($r) {
logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$r[0]["id"], LOGGER_DEBUG); logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$r[0]["id"], LOGGER_DEBUG);
continue; continue;
} }
@ -332,9 +306,8 @@ class ostatus {
if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) OR ($item["object-type"] == ACTIVITY_OBJ_EVENT)) { if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) OR ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
$item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue; $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
$item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue; $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
} elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) { } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION)
$item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue; $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
}
$item["object"] = $xml; $item["object"] = $xml;
$item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue; $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
@ -379,9 +352,8 @@ class ostatus {
} }
// http://activitystrea.ms/schema/1.0/rsvp-yes // http://activitystrea.ms/schema/1.0/rsvp-yes
if (!in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE))) { if (!in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE)))
logger("Unhandled verb ".$item["verb"]." ".print_r($item, true)); logger("Unhandled verb ".$item["verb"]." ".print_r($item, true));
}
$item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue; $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
$item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue; $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
@ -392,14 +364,12 @@ class ostatus {
$inreplyto = $xpath->query('thr:in-reply-to', $entry); $inreplyto = $xpath->query('thr:in-reply-to', $entry);
if (is_object($inreplyto->item(0))) { if (is_object($inreplyto->item(0))) {
foreach($inreplyto->item(0)->attributes AS $attributes) { foreach($inreplyto->item(0)->attributes AS $attributes) {
if ($attributes->name == "ref") { if ($attributes->name == "ref")
$item["parent-uri"] = $attributes->textContent; $item["parent-uri"] = $attributes->textContent;
} if ($attributes->name == "href")
if ($attributes->name == "href") {
$related = $attributes->textContent; $related = $attributes->textContent;
} }
} }
}
$georsspoint = $xpath->query('georss:point', $entry); $georsspoint = $xpath->query('georss:point', $entry);
if ($georsspoint) if ($georsspoint)
@ -441,7 +411,7 @@ class ostatus {
if ($attributes->name == "title") if ($attributes->name == "title")
$title = $attributes->textContent; $title = $attributes->textContent;
} }
if (($rel != "") AND ($href != "")) { if (($rel != "") AND ($href != ""))
switch($rel) { switch($rel) {
case "alternate": case "alternate":
$item["plink"] = $href; $item["plink"] = $href;
@ -480,7 +450,6 @@ class ostatus {
} }
} }
} }
}
$local_id = ""; $local_id = "";
$repeat_of = ""; $repeat_of = "";
@ -488,17 +457,14 @@ class ostatus {
$notice_info = $xpath->query('statusnet:notice_info', $entry); $notice_info = $xpath->query('statusnet:notice_info', $entry);
if ($notice_info AND ($notice_info->length > 0)) { if ($notice_info AND ($notice_info->length > 0)) {
foreach($notice_info->item(0)->attributes AS $attributes) { foreach($notice_info->item(0)->attributes AS $attributes) {
if ($attributes->name == "source") { if ($attributes->name == "source")
$item["app"] = strip_tags($attributes->textContent); $item["app"] = strip_tags($attributes->textContent);
} if ($attributes->name == "local_id")
if ($attributes->name == "local_id") {
$local_id = $attributes->textContent; $local_id = $attributes->textContent;
} if ($attributes->name == "repeat_of")
if ($attributes->name == "repeat_of") {
$repeat_of = $attributes->textContent; $repeat_of = $attributes->textContent;
} }
} }
}
// Is it a repeated post? // Is it a repeated post?
if (($repeat_of != "") OR ($item["verb"] == ACTIVITY_SHARE)) { if (($repeat_of != "") OR ($item["verb"] == ACTIVITY_SHARE)) {
@ -507,32 +473,24 @@ class ostatus {
if (is_object($activityobjects)) { if (is_object($activityobjects)) {
$orig_uri = $xpath->query("activity:object/atom:id", $activityobjects)->item(0)->nodeValue; $orig_uri = $xpath->query("activity:object/atom:id", $activityobjects)->item(0)->nodeValue;
if (!isset($orig_uri)) { if (!isset($orig_uri))
$orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue; $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
}
$orig_links = $xpath->query("activity:object/atom:link[@rel='alternate']", $activityobjects); $orig_links = $xpath->query("activity:object/atom:link[@rel='alternate']", $activityobjects);
if ($orig_links AND ($orig_links->length > 0)) { if ($orig_links AND ($orig_links->length > 0))
foreach ($orig_links->item(0)->attributes AS $attributes) { foreach($orig_links->item(0)->attributes AS $attributes)
if ($attributes->name == "href") { if ($attributes->name == "href")
$orig_link = $attributes->textContent; $orig_link = $attributes->textContent;
}
}
}
if (!isset($orig_link)) { if (!isset($orig_link))
$orig_link = $xpath->query("atom:link[@rel='alternate']", $activityobjects)->item(0)->nodeValue; $orig_link = $xpath->query("atom:link[@rel='alternate']", $activityobjects)->item(0)->nodeValue;
}
if (!isset($orig_link)) { if (!isset($orig_link))
$orig_link = self::convert_href($orig_uri); $orig_link = self::convert_href($orig_uri);
}
$orig_body = $xpath->query('activity:object/atom:content/text()', $activityobjects)->item(0)->nodeValue; $orig_body = $xpath->query('activity:object/atom:content/text()', $activityobjects)->item(0)->nodeValue;
if (!isset($orig_body))
if (!isset($orig_body)) {
$orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue; $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
}
$orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue; $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
$orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue; $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
@ -553,12 +511,10 @@ class ostatus {
$item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue; $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
$item["object-type"] = $xpath->query('activity:object/activity:object-type/text()', $activityobjects)->item(0)->nodeValue; $item["object-type"] = $xpath->query('activity:object/activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
if (!isset($item["object-type"]))
if (!isset($item["object-type"])) {
$item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue; $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
} }
} }
}
//if ($enclosure != "") //if ($enclosure != "")
// $item["body"] .= add_page_info($enclosure); // $item["body"] .= add_page_info($enclosure);
@ -584,14 +540,12 @@ class ostatus {
intval($importer["uid"]), dbesc($item["parent-uri"])); intval($importer["uid"]), dbesc($item["parent-uri"]));
} }
} }
if ($r) {
if (dbm::is_result($r)) {
$item["type"] = 'remote-comment'; $item["type"] = 'remote-comment';
$item["gravity"] = GRAVITY_COMMENT; $item["gravity"] = GRAVITY_COMMENT;
} }
} else { } else
$item["parent-uri"] = $item["uri"]; $item["parent-uri"] = $item["uri"];
}
$item_id = self::completion($conversation, $importer["uid"], $item, $self); $item_id = self::completion($conversation, $importer["uid"], $item, $self);
@ -614,26 +568,22 @@ class ostatus {
public static function convert_href($href) { public static function convert_href($href) {
$elements = explode(":",$href); $elements = explode(":",$href);
if ((count($elements) <= 2) OR ($elements[0] != "tag")) { if ((count($elements) <= 2) OR ($elements[0] != "tag"))
return $href; return $href;
}
$server = explode(",", $elements[1]); $server = explode(",", $elements[1]);
$conversation = explode("=", $elements[2]); $conversation = explode("=", $elements[2]);
if ((count($elements) == 4) AND ($elements[2] == "post")) { if ((count($elements) == 4) AND ($elements[2] == "post"))
return "http://".$server[0]."/notice/".$elements[3]; return "http://".$server[0]."/notice/".$elements[3];
}
if ((count($conversation) != 2) OR ($conversation[1] =="")) { if ((count($conversation) != 2) OR ($conversation[1] ==""))
return $href; return $href;
}
if ($elements[3] == "objectType=thread") { if ($elements[3] == "objectType=thread")
return "http://".$server[0]."/conversation/".$conversation[1]; return "http://".$server[0]."/conversation/".$conversation[1];
} else { else
return "http://".$server[0]."/notice/".$conversation[1]; return "http://".$server[0]."/notice/".$conversation[1];
}
return $href; return $href;
} }
@ -706,53 +656,42 @@ class ostatus {
* @brief Updates the gcontact table with actor data from the conversation * @brief Updates the gcontact table with actor data from the conversation
* *
* @param object $actor The actor object that contains the contact data * @param object $actor The actor object that contains the contact data
* @todo Add type-hint
*/ */
private function conv_fetch_actor($actor) { private function conv_fetch_actor($actor) {
// We set the generation to "3" since the data here is not as reliable as the data we get on other occasions // We set the generation to "3" since the data here is not as reliable as the data we get on other occasions
$contact = array("network" => NETWORK_OSTATUS, "generation" => 3); $contact = array("network" => NETWORK_OSTATUS, "generation" => 3);
if (isset($actor->url)) { if (isset($actor->url))
$contact["url"] = $actor->url; $contact["url"] = $actor->url;
}
if (isset($actor->displayName)) { if (isset($actor->displayName))
$contact["name"] = $actor->displayName; $contact["name"] = $actor->displayName;
}
if (isset($actor->portablecontacts_net->displayName)) { if (isset($actor->portablecontacts_net->displayName))
$contact["name"] = $actor->portablecontacts_net->displayName; $contact["name"] = $actor->portablecontacts_net->displayName;
}
if (isset($actor->portablecontacts_net->preferredUsername)) { if (isset($actor->portablecontacts_net->preferredUsername))
$contact["nick"] = $actor->portablecontacts_net->preferredUsername; $contact["nick"] = $actor->portablecontacts_net->preferredUsername;
}
if (isset($actor->id)) { if (isset($actor->id))
$contact["alias"] = $actor->id; $contact["alias"] = $actor->id;
}
if (isset($actor->summary)) { if (isset($actor->summary))
$contact["about"] = $actor->summary; $contact["about"] = $actor->summary;
}
if (isset($actor->portablecontacts_net->note)) { if (isset($actor->portablecontacts_net->note))
$contact["about"] = $actor->portablecontacts_net->note; $contact["about"] = $actor->portablecontacts_net->note;
}
if (isset($actor->portablecontacts_net->addresses->formatted)) { if (isset($actor->portablecontacts_net->addresses->formatted))
$contact["location"] = $actor->portablecontacts_net->addresses->formatted; $contact["location"] = $actor->portablecontacts_net->addresses->formatted;
}
if (isset($actor->image->url)) { if (isset($actor->image->url))
$contact["photo"] = $actor->image->url; $contact["photo"] = $actor->image->url;
}
if (isset($actor->image->width)) { if (isset($actor->image->width))
$avatarwidth = $actor->image->width; $avatarwidth = $actor->image->width;
}
if (is_array($actor->status_net->avatarLinks)) if (is_array($actor->status_net->avatarLinks))
foreach ($actor->status_net->avatarLinks AS $avatar) { foreach ($actor->status_net->avatarLinks AS $avatar) {
@ -779,26 +718,22 @@ class ostatus {
if ($conversation_id != "") { if ($conversation_id != "") {
$elements = explode(":", $conversation_id); $elements = explode(":", $conversation_id);
if ((count($elements) <= 2) OR ($elements[0] != "tag")) { if ((count($elements) <= 2) OR ($elements[0] != "tag"))
return $conversation_id; return $conversation_id;
} }
}
if ($self == "") { if ($self == "")
return ""; return "";
}
$json = str_replace(".atom", ".json", $self); $json = str_replace(".atom", ".json", $self);
$raw = fetch_url($json); $raw = fetch_url($json);
if ($raw == "") { if ($raw == "")
return ""; return "";
}
$data = json_decode($raw); $data = json_decode($raw);
if (!is_object($data)) { if (!is_object($data))
return ""; return "";
}
$conversation_id = $data->statusnet_conversation_id; $conversation_id = $data->statusnet_conversation_id;
@ -824,12 +759,11 @@ class ostatus {
$contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'", $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
$uid, normalise_link($actor), NETWORK_STATUSNET); $uid, normalise_link($actor), NETWORK_STATUSNET);
if (!dbm::is_result($contact)) { if (!$contact)
$contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `alias` IN ('%s', '%s') AND `network` != '%s'", $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `alias` IN ('%s', '%s') AND `network` != '%s'",
$uid, $actor, normalise_link($actor), NETWORK_STATUSNET); $uid, $actor, normalise_link($actor), NETWORK_STATUSNET);
}
if (dbm::is_result($contact)) { if ($contact) {
logger("Found contact for url ".$actor, LOGGER_DEBUG); logger("Found contact for url ".$actor, LOGGER_DEBUG);
$details["contact_id"] = $contact[0]["id"]; $details["contact_id"] = $contact[0]["id"];
$details["network"] = $contact[0]["network"]; $details["network"] = $contact[0]["network"];
@ -861,7 +795,6 @@ class ostatus {
* @param array $item Data of the item that is to be posted * @param array $item Data of the item that is to be posted
* *
* @return integer The item id of the posted item array * @return integer The item id of the posted item array
* @todo Add type-hints
*/ */
private function completion($conversation_url, $uid, $item = array(), $self = "") { private function completion($conversation_url, $uid, $item = array(), $self = "") {
@ -894,9 +827,9 @@ class ostatus {
(SELECT `oid` FROM `term` WHERE `uid` = %d AND `otype` = %d AND `type` = %d AND `url` = '%s'))", (SELECT `oid` FROM `term` WHERE `uid` = %d AND `otype` = %d AND `type` = %d AND `url` = '%s'))",
intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url)); intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
*/ */
if (dbm::is_result($parents)) { if ($parents)
$parent = $parents[0]; $parent = $parents[0];
} elseif (count($item) > 0) { elseif (count($item) > 0) {
$parent = $item; $parent = $item;
$parent["type"] = "remote"; $parent["type"] = "remote";
$parent["verb"] = ACTIVITY_POST; $parent["verb"] = ACTIVITY_POST;
@ -904,11 +837,9 @@ class ostatus {
} else { } else {
// Preset the parent // Preset the parent
$r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid`=%d", $uid); $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid`=%d", $uid);
if (!dbm::is_result($r)) { if (!$r)
return(-2); return(-2);
}
/// @TODO one statement is enough ...
$parent = array(); $parent = array();
$parent["id"] = 0; $parent["id"] = 0;
$parent["parent"] = 0; $parent["parent"] = 0;
@ -935,24 +866,20 @@ class ostatus {
} elseif (!$conv_arr["success"] AND (substr($conv, 0, 8) == "https://")) { } elseif (!$conv_arr["success"] AND (substr($conv, 0, 8) == "https://")) {
$conv = str_replace("https://", "http://", $conv); $conv = str_replace("https://", "http://", $conv);
$conv_as = fetch_url($conv."?page=".$pageno); $conv_as = fetch_url($conv."?page=".$pageno);
} else { } else
$conv_as = $conv_arr["body"]; $conv_as = $conv_arr["body"];
}
$conv_as = str_replace(',"statusnet:notice_info":', ',"statusnet_notice_info":', $conv_as); $conv_as = str_replace(',"statusnet:notice_info":', ',"statusnet_notice_info":', $conv_as);
$conv_as = json_decode($conv_as); $conv_as = json_decode($conv_as);
$no_of_items = sizeof($items); $no_of_items = sizeof($items);
if (is_array($conv_as->items)) { if (@is_array($conv_as->items))
foreach ($conv_as->items AS $single_item) { foreach ($conv_as->items AS $single_item)
$items[$single_item->id] = $single_item; $items[$single_item->id] = $single_item;
}
}
if ($no_of_items == sizeof($items)) { if ($no_of_items == sizeof($items))
break; break;
}
$pageno++; $pageno++;
@ -970,20 +897,13 @@ class ostatus {
} }
return($item_stored); return($item_stored);
} else { } else
return(-3); return(-3);
} }
}
$items = array_reverse($items); $items = array_reverse($items);
$r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self`", intval($uid)); $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self`", intval($uid));
if (!dbm::is_result($r)) {
logger("Failed query, uid=" . intval($uid) ." in " . __FUNCTION__);
killme();
}
$importer = $r[0]; $importer = $r[0];
$new_parent = true; $new_parent = true;
@ -999,18 +919,15 @@ class ostatus {
$mention = false; $mention = false;
if (isset($single_conv->object->id)) { if (isset($single_conv->object->id))
$single_conv->id = $single_conv->object->id; $single_conv->id = $single_conv->object->id;
}
$plink = self::convert_href($single_conv->id); $plink = self::convert_href($single_conv->id);
if (isset($single_conv->object->url)) { if (isset($single_conv->object->url))
$plink = self::convert_href($single_conv->object->url); $plink = self::convert_href($single_conv->object->url);
}
if (!isset($single_conv->id)) { if (@!$single_conv->id)
continue; continue;
}
logger("Got id ".$single_conv->id, LOGGER_DEBUG); logger("Got id ".$single_conv->id, LOGGER_DEBUG);
@ -1029,7 +946,7 @@ class ostatus {
(SELECT `parent` FROM `item` (SELECT `parent` FROM `item`
WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s')) LIMIT 1", WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s')) LIMIT 1",
intval($uid), dbesc($first_id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN)); intval($uid), dbesc($first_id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
if (dbm::is_result($new_parents)) { if ($new_parents) {
if ($new_parents[0]["parent"] == $parent["parent"]) { if ($new_parents[0]["parent"] == $parent["parent"]) {
// Option 2: This post is already present inside our thread - but not as thread starter // Option 2: This post is already present inside our thread - but not as thread starter
logger("Option 2: uri present in our thread: ".$first_id, LOGGER_DEBUG); logger("Option 2: uri present in our thread: ".$first_id, LOGGER_DEBUG);
@ -1060,19 +977,17 @@ class ostatus {
if (isset($single_conv->context->inReplyTo->id)) { if (isset($single_conv->context->inReplyTo->id)) {
$parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1", $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
intval($uid), dbesc($single_conv->context->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN)); intval($uid), dbesc($single_conv->context->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
if (dbm::is_result($parent_exists)) { if ($parent_exists)
$parent_uri = $single_conv->context->inReplyTo->id; $parent_uri = $single_conv->context->inReplyTo->id;
} }
}
// This is the current way // This is the current way
if (isset($single_conv->object->inReplyTo->id)) { if (isset($single_conv->object->inReplyTo->id)) {
$parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1", $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
intval($uid), dbesc($single_conv->object->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN)); intval($uid), dbesc($single_conv->object->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
if (dbm::is_result($parent_exists)) { if ($parent_exists)
$parent_uri = $single_conv->object->inReplyTo->id; $parent_uri = $single_conv->object->inReplyTo->id;
} }
}
$message_exists = q("SELECT `id`, `parent`, `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1", $message_exists = q("SELECT `id`, `parent`, `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
intval($uid), dbesc($single_conv->id), intval($uid), dbesc($single_conv->id),
@ -1118,18 +1033,14 @@ class ostatus {
continue; continue;
} }
if (is_array($single_conv->to)) { if (is_array($single_conv->to))
foreach ($single_conv->to AS $to) { foreach($single_conv->to AS $to)
if ($importer["nurl"] == normalise_link($to->id)) { if ($importer["nurl"] == normalise_link($to->id))
$mention = true; $mention = true;
}
}
}
$actor = $single_conv->actor->id; $actor = $single_conv->actor->id;
if (isset($single_conv->actor->url)) { if (isset($single_conv->actor->url))
$actor = $single_conv->actor->url; $actor = $single_conv->actor->url;
}
$details = self::get_actor_details($actor, $uid, $parent["contact-id"]); $details = self::get_actor_details($actor, $uid, $parent["contact-id"]);
@ -1139,7 +1050,6 @@ class ostatus {
continue; continue;
} }
/// @TODO One statment is okay (until if () )
$arr = array(); $arr = array();
$arr["network"] = $details["network"]; $arr["network"] = $details["network"];
$arr["uri"] = $single_conv->id; $arr["uri"] = $single_conv->id;
@ -1150,13 +1060,10 @@ class ostatus {
$arr["created"] = $single_conv->published; $arr["created"] = $single_conv->published;
$arr["edited"] = $single_conv->published; $arr["edited"] = $single_conv->published;
$arr["owner-name"] = $single_conv->actor->displayName; $arr["owner-name"] = $single_conv->actor->displayName;
if ($arr["owner-name"] == '')
if ($arr["owner-name"] == '') {
$arr["owner-name"] = $single_conv->actor->contact->displayName; $arr["owner-name"] = $single_conv->actor->contact->displayName;
} if ($arr["owner-name"] == '')
if ($arr["owner-name"] == '') {
$arr["owner-name"] = $single_conv->actor->portablecontacts_net->displayName; $arr["owner-name"] = $single_conv->actor->portablecontacts_net->displayName;
}
$arr["owner-link"] = $actor; $arr["owner-link"] = $actor;
$arr["owner-avatar"] = $single_conv->actor->image->url; $arr["owner-avatar"] = $single_conv->actor->image->url;
@ -1165,17 +1072,17 @@ class ostatus {
$arr["author-avatar"] = $single_conv->actor->image->url; $arr["author-avatar"] = $single_conv->actor->image->url;
$arr["body"] = add_page_info_to_body(html2bbcode($single_conv->content)); $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->content));
if (isset($single_conv->status_net->notice_info->source)) { if (isset($single_conv->status_net->notice_info->source))
$arr["app"] = strip_tags($single_conv->status_net->notice_info->source); $arr["app"] = strip_tags($single_conv->status_net->notice_info->source);
} elseif (isset($single_conv->statusnet->notice_info->source)) { elseif (isset($single_conv->statusnet->notice_info->source))
$arr["app"] = strip_tags($single_conv->statusnet->notice_info->source); $arr["app"] = strip_tags($single_conv->statusnet->notice_info->source);
} elseif (isset($single_conv->statusnet_notice_info->source)) { elseif (isset($single_conv->statusnet_notice_info->source))
$arr["app"] = strip_tags($single_conv->statusnet_notice_info->source); $arr["app"] = strip_tags($single_conv->statusnet_notice_info->source);
} elseif (isset($single_conv->provider->displayName)) { elseif (isset($single_conv->provider->displayName))
$arr["app"] = $single_conv->provider->displayName; $arr["app"] = $single_conv->provider->displayName;
} else { else
$arr["app"] = "OStatus"; $arr["app"] = "OStatus";
}
$arr["object"] = json_encode($single_conv); $arr["object"] = json_encode($single_conv);
$arr["verb"] = $parent["verb"]; $arr["verb"] = $parent["verb"];
@ -1185,31 +1092,27 @@ class ostatus {
// Is it a reshared item? // Is it a reshared item?
if (isset($single_conv->verb) AND ($single_conv->verb == "share") AND isset($single_conv->object)) { if (isset($single_conv->verb) AND ($single_conv->verb == "share") AND isset($single_conv->object)) {
if (is_array($single_conv->object)) { if (is_array($single_conv->object))
$single_conv->object = $single_conv->object[0]; $single_conv->object = $single_conv->object[0];
}
logger("Found reshared item ".$single_conv->object->id); logger("Found reshared item ".$single_conv->object->id);
// $single_conv->object->context->conversation; // $single_conv->object->context->conversation;
if (isset($single_conv->object->object->id)) { if (isset($single_conv->object->object->id))
$arr["uri"] = $single_conv->object->object->id; $arr["uri"] = $single_conv->object->object->id;
} else { else
$arr["uri"] = $single_conv->object->id; $arr["uri"] = $single_conv->object->id;
}
if (isset($single_conv->object->object->url)) { if (isset($single_conv->object->object->url))
$plink = self::convert_href($single_conv->object->object->url); $plink = self::convert_href($single_conv->object->object->url);
} else { else
$plink = self::convert_href($single_conv->object->url); $plink = self::convert_href($single_conv->object->url);
}
if (isset($single_conv->object->object->content)) { if (isset($single_conv->object->object->content))
$arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->object->content)); $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->object->content));
} else { else
$arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content)); $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content));
}
$arr["plink"] = $plink; $arr["plink"] = $plink;
@ -1217,9 +1120,8 @@ class ostatus {
$arr["edited"] = $single_conv->object->published; $arr["edited"] = $single_conv->object->published;
$arr["author-name"] = $single_conv->object->actor->displayName; $arr["author-name"] = $single_conv->object->actor->displayName;
if ($arr["owner-name"] == '') { if ($arr["owner-name"] == '')
$arr["author-name"] = $single_conv->object->actor->contact->displayName; $arr["author-name"] = $single_conv->object->actor->contact->displayName;
}
$arr["author-link"] = $single_conv->object->actor->url; $arr["author-link"] = $single_conv->object->actor->url;
$arr["author-avatar"] = $single_conv->object->actor->image->url; $arr["author-avatar"] = $single_conv->object->actor->image->url;
@ -1231,24 +1133,20 @@ class ostatus {
$arr["coord"] = trim($single_conv->object->location->lat." ".$single_conv->object->location->lon); $arr["coord"] = trim($single_conv->object->location->lat." ".$single_conv->object->location->lon);
} }
if ($arr["location"] == "") { if ($arr["location"] == "")
unset($arr["location"]); unset($arr["location"]);
}
if ($arr["coord"] == "") { if ($arr["coord"] == "")
unset($arr["coord"]); unset($arr["coord"]);
}
// Copy fields from given item array // Copy fields from given item array
if (isset($item["uri"]) AND (($item["uri"] == $arr["uri"]) OR ($item["uri"] == $single_conv->id))) { if (isset($item["uri"]) AND (($item["uri"] == $arr["uri"]) OR ($item["uri"] == $single_conv->id))) {
$copy_fields = array("owner-name", "owner-link", "owner-avatar", "author-name", "author-link", "author-avatar", $copy_fields = array("owner-name", "owner-link", "owner-avatar", "author-name", "author-link", "author-avatar",
"gravity", "body", "object-type", "object", "verb", "created", "edited", "coord", "tag", "gravity", "body", "object-type", "object", "verb", "created", "edited", "coord", "tag",
"title", "attach", "app", "type", "location", "contact-id", "uri"); "title", "attach", "app", "type", "location", "contact-id", "uri");
foreach ($copy_fields AS $field) { foreach ($copy_fields AS $field)
if (isset($item[$field])) { if (isset($item[$field]))
$arr[$field] = $item[$field]; $arr[$field] = $item[$field];
}
}
} }
@ -1274,11 +1172,10 @@ class ostatus {
logger('setting new parent to id '.$newitem); logger('setting new parent to id '.$newitem);
$new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1", $new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
intval($uid), intval($newitem)); intval($uid), intval($newitem));
if (dbm::is_result($new_parents)) { if ($new_parents)
$parent = $new_parents[0]; $parent = $new_parents[0];
} }
} }
}
if (($item_stored < 0) AND (count($item) > 0)) { if (($item_stored < 0) AND (count($item) > 0)) {
@ -1311,18 +1208,15 @@ class ostatus {
$conversation_url = self::convert_href($conversation_url); $conversation_url = self::convert_href($conversation_url);
$messages = q("SELECT `uid`, `parent`, `created`, `received`, `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid)); $messages = q("SELECT `uid`, `parent`, `created`, `received`, `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
if (!$messages)
if (!dbm::is_result($messages)) {
return; return;
}
$message = $messages[0]; $message = $messages[0];
// Store conversation url if not done before // Store conversation url if not done before
$conversation = q("SELECT `url` FROM `term` WHERE `uid` = %d AND `oid` = %d AND `otype` = %d AND `type` = %d", $conversation = q("SELECT `url` FROM `term` WHERE `uid` = %d AND `oid` = %d AND `otype` = %d AND `type` = %d",
intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION)); intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION));
if (!dbm::is_result($conversation)) { if (!$conversation) {
$r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `created`, `received`, `guid`) VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s')", $r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `created`, `received`, `guid`) VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s')",
intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION),
dbesc($message["created"]), dbesc($conversation_url), dbesc($message["created"]), dbesc($message["received"]), dbesc($message["guid"])); dbesc($message["created"]), dbesc($conversation_url), dbesc($message["created"]), dbesc($message["received"]), dbesc($message["guid"]));
@ -1336,38 +1230,32 @@ class ostatus {
* @param array $item The item array of thw post * @param array $item The item array of thw post
* *
* @return string The guid if the post is a reshare * @return string The guid if the post is a reshare
* @todo Add type-hints
*/ */
private function get_reshared_guid($item) { private function get_reshared_guid($item) {
$body = trim($item["body"]); $body = trim($item["body"]);
// Skip if it isn't a pure repeated messages // Skip if it isn't a pure repeated messages
// Does it start with a share? // Does it start with a share?
if (strpos($body, "[share") > 0) { if (strpos($body, "[share") > 0)
return(""); return("");
}
// Does it end with a share? // Does it end with a share?
if (strlen($body) > (strrpos($body, "[/share]") + 8)) { if (strlen($body) > (strrpos($body, "[/share]") + 8))
return(""); return("");
}
$attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body); $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
// Skip if there is no shared message in there // Skip if there is no shared message in there
if ($body == $attributes) { if ($body == $attributes)
return(false); return(false);
}
$guid = ""; $guid = "";
preg_match("/guid='(.*?)'/ism", $attributes, $matches); preg_match("/guid='(.*?)'/ism", $attributes, $matches);
if ($matches[1] != "") { if ($matches[1] != "")
$guid = $matches[1]; $guid = $matches[1];
}
preg_match('/guid="(.*?)"/ism', $attributes, $matches); preg_match('/guid="(.*?)"/ism', $attributes, $matches);
if ($matches[1] != "") { if ($matches[1] != "")
$guid = $matches[1]; $guid = $matches[1];
}
return $guid; return $guid;
} }
@ -1383,11 +1271,10 @@ class ostatus {
$siteinfo = get_attached_data($body); $siteinfo = get_attached_data($body);
if (($siteinfo["type"] == "photo")) { if (($siteinfo["type"] == "photo")) {
if (isset($siteinfo["preview"])) { if (isset($siteinfo["preview"]))
$preview = $siteinfo["preview"]; $preview = $siteinfo["preview"];
} else { else
$preview = $siteinfo["image"]; $preview = $siteinfo["image"];
}
// Is it a remote picture? Then make a smaller preview here // Is it a remote picture? Then make a smaller preview here
$preview = proxy_url($preview, false, PROXY_SIZE_SMALL); $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
@ -1396,11 +1283,10 @@ class ostatus {
$preview = str_replace(array("-0.jpg", "-0.png"), array("-2.jpg", "-2.png"), $preview); $preview = str_replace(array("-0.jpg", "-0.png"), array("-2.jpg", "-2.png"), $preview);
$preview = str_replace(array("-1.jpg", "-1.png"), array("-2.jpg", "-2.png"), $preview); $preview = str_replace(array("-1.jpg", "-1.png"), array("-2.jpg", "-2.png"), $preview);
if (isset($siteinfo["url"])) { if (isset($siteinfo["url"]))
$url = $siteinfo["url"]; $url = $siteinfo["url"];
} else { else
$url = $siteinfo["image"]; $url = $siteinfo["image"];
}
$body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]"; $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
} }
@ -1415,7 +1301,6 @@ class ostatus {
* @param array $owner Contact data of the poster * @param array $owner Contact data of the poster
* *
* @return object header root element * @return object header root element
* @todo Add type-hints
*/ */
private function add_header($doc, $owner) { private function add_header($doc, $owner) {
@ -1475,7 +1360,6 @@ class ostatus {
* *
* @param object $doc XML document * @param object $doc XML document
* @param object $root XML root element where the hub links are added * @param object $root XML root element where the hub links are added
* @todo Add type-hints
*/ */
public static function hublinks($doc, $root) { public static function hublinks($doc, $root) {
$hub = get_config('system','huburl'); $hub = get_config('system','huburl');
@ -1486,12 +1370,10 @@ class ostatus {
if(count($hubs)) { if(count($hubs)) {
foreach($hubs as $h) { foreach($hubs as $h) {
$h = trim($h); $h = trim($h);
if (! strlen($h)) { if(! strlen($h))
continue; continue;
} if ($h === '[internal]')
if ($h === '[internal]') {
$h = App::get_baseurl() . '/pubsubhubbub'; $h = App::get_baseurl() . '/pubsubhubbub';
}
xml::add_element($doc, $root, "link", "", array("href" => $h, "rel" => "hub")); xml::add_element($doc, $root, "link", "", array("href" => $h, "rel" => "hub"));
} }
} }
@ -1504,7 +1386,6 @@ class ostatus {
* @param object $doc XML document * @param object $doc XML document
* @param object $root XML root element where the hub links are added * @param object $root XML root element where the hub links are added
* @param array $item Data of the item that is to be posted * @param array $item Data of the item that is to be posted
* @todo Add type-hints
*/ */
private function get_attachment($doc, $root, $item) { private function get_attachment($doc, $root, $item) {
$o = ""; $o = "";
@ -1557,13 +1438,11 @@ class ostatus {
"href" => $matches[1], "href" => $matches[1],
"type" => $matches[3]); "type" => $matches[3]);
if (intval($matches[2])) { if(intval($matches[2]))
$attributes["length"] = intval($matches[2]); $attributes["length"] = intval($matches[2]);
}
if (trim($matches[4]) != "") { if(trim($matches[4]) != "")
$attributes["title"] = trim($matches[4]); $attributes["title"] = trim($matches[4]);
}
xml::add_element($doc, $root, "link", "", $attributes); xml::add_element($doc, $root, "link", "", $attributes);
} }
@ -1578,15 +1457,12 @@ class ostatus {
* @param array $owner Contact data of the poster * @param array $owner Contact data of the poster
* *
* @return object author element * @return object author element
* @todo Add type-hints
*/ */
private function add_author($doc, $owner) { private function add_author($doc, $owner) {
$profile = null;
$r = q("SELECT `homepage` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"])); $r = q("SELECT `homepage` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
if (dbm::is_result($r)) { if ($r)
$profile = $r[0]; $profile = $r[0];
}
$author = $doc->createElement("author"); $author = $doc->createElement("author");
xml::add_element($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON); xml::add_element($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
@ -1654,12 +1530,10 @@ class ostatus {
* @param array $item Data of the item that is to be posted * @param array $item Data of the item that is to be posted
* *
* @return string activity * @return string activity
* @todo Add type-hints
*/ */
function construct_verb($item) { function construct_verb($item) {
if ($item['verb']) { if ($item['verb'])
return $item['verb']; return $item['verb'];
}
return ACTIVITY_POST; return ACTIVITY_POST;
} }
@ -1669,12 +1543,10 @@ class ostatus {
* @param array $item Data of the item that is to be posted * @param array $item Data of the item that is to be posted
* *
* @return string Object type * @return string Object type
* @todo Add type-hints
*/ */
function construct_objecttype($item) { function construct_objecttype($item) {
if (in_array($item['object-type'], array(ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT))) { if (in_array($item['object-type'], array(ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT)))
return $item['object-type']; return $item['object-type'];
};
return ACTIVITY_OBJ_NOTE; return ACTIVITY_OBJ_NOTE;
} }
@ -1712,7 +1584,6 @@ class ostatus {
* @param array $contact Array of the contact that is added * @param array $contact Array of the contact that is added
* *
* @return object Source element * @return object Source element
* @todo Add type-hints
*/ */
private function source_entry($doc, $contact) { private function source_entry($doc, $contact) {
$source = $doc->createElement("source"); $source = $doc->createElement("source");
@ -1737,41 +1608,39 @@ class ostatus {
* @param array $owner Contact data of the poster * @param array $owner Contact data of the poster
* *
* @return array Contact array * @return array Contact array
* @todo Add array type-hint for $owner
*/ */
private function contact_entry($url, $owner) { private function contact_entry($url, $owner) {
$r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1", $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
dbesc(normalise_link($url)), intval($owner["uid"])); dbesc(normalise_link($url)), intval($owner["uid"]));
if (dbm::is_result($r)) { if ($r) {
$contact = $r[0]; $contact = $r[0];
$contact["uid"] = -1; $contact["uid"] = -1;
} else { }
if (!$r) {
$r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1", $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
dbesc(normalise_link($url))); dbesc(normalise_link($url)));
if (dbm::is_result($r)) { if ($r) {
$contact = $r[0]; $contact = $r[0];
$contact["uid"] = -1; $contact["uid"] = -1;
$contact["success_update"] = $contact["updated"]; $contact["success_update"] = $contact["updated"];
} }
} }
if (!dbm::is_result($r)) { if (!$r)
$contact = $owner; $contact = owner;
}
if (!isset($contact["poll"])) { if (!isset($contact["poll"])) {
$data = probe_url($url); $data = probe_url($url);
$contact["poll"] = $data["poll"]; $contact["poll"] = $data["poll"];
if (!$contact["alias"]) { if (!$contact["alias"])
$contact["alias"] = $data["alias"]; $contact["alias"] = $data["alias"];
} }
}
if (!isset($contact["alias"])) { if (!isset($contact["alias"]))
$contact["alias"] = $contact["url"]; $contact["alias"] = $contact["url"];
}
return $contact; return $contact;
} }
@ -1786,7 +1655,6 @@ class ostatus {
* @param bool $toplevel Is it for en entry element (false) or a feed entry (true)? * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
* *
* @return object Entry element * @return object Entry element
* @todo Add type-hints
*/ */
private function reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel) { private function reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel) {
@ -1799,12 +1667,10 @@ class ostatus {
$r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1", $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
intval($owner["uid"]), dbesc($repeated_guid), intval($owner["uid"]), dbesc($repeated_guid),
dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS)); dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
if ($r)
if (!dbm::is_result($r)) {
return false;
}
$repeated_item = $r[0]; $repeated_item = $r[0];
else
return false;
$contact = self::contact_entry($repeated_item['author-link'], $owner); $contact = self::contact_entry($repeated_item['author-link'], $owner);
@ -1855,7 +1721,6 @@ class ostatus {
* @param bool $toplevel Is it for en entry element (false) or a feed entry (true)? * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
* *
* @return object Entry element with "like" * @return object Entry element with "like"
* @todo Add type-hints
*/ */
private function like_entry($doc, $item, $owner, $toplevel) { private function like_entry($doc, $item, $owner, $toplevel) {
@ -1893,7 +1758,6 @@ class ostatus {
* @param array $contact Contact data of the target * @param array $contact Contact data of the target
* *
* @return object author element * @return object author element
* @todo Add type-hints
*/ */
private function add_person_object($doc, $owner, $contact) { private function add_person_object($doc, $owner, $contact) {
@ -1940,7 +1804,6 @@ class ostatus {
* @param bool $toplevel Is it for en entry element (false) or a feed entry (true)? * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
* *
* @return object Entry element * @return object Entry element
* @todo Add type-hints
*/ */
private function follow_entry($doc, $item, $owner, $toplevel) { private function follow_entry($doc, $item, $owner, $toplevel) {
@ -2003,7 +1866,6 @@ class ostatus {
* @param bool $toplevel Is it for en entry element (false) or a feed entry (true)? * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
* *
* @return object Entry element * @return object Entry element
* @todo Add type-hints
*/ */
private function note_entry($doc, $item, $owner, $toplevel) { private function note_entry($doc, $item, $owner, $toplevel) {
@ -2031,7 +1893,6 @@ class ostatus {
* @param bool $toplevel Is it for en entry element (false) or a feed entry (true)? * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
* *
* @return string The title for the element * @return string The title for the element
* @todo Add type-hints
*/ */
private function entry_header($doc, &$entry, $owner, $toplevel) { private function entry_header($doc, &$entry, $owner, $toplevel) {
/// @todo Check if this title stuff is really needed (I guess not) /// @todo Check if this title stuff is really needed (I guess not)
@ -2067,22 +1928,19 @@ class ostatus {
* @param string $title Title for the post * @param string $title Title for the post
* @param string $verb The activity verb * @param string $verb The activity verb
* @param bool $complete Add the "status_net" element? * @param bool $complete Add the "status_net" element?
* @todo Add type-hints
*/ */
private function entry_content($doc, $entry, $item, $owner, $title, $verb = "", $complete = true) { private function entry_content($doc, $entry, $item, $owner, $title, $verb = "", $complete = true) {
if ($verb == "") { if ($verb == "")
$verb = self::construct_verb($item); $verb = self::construct_verb($item);
}
xml::add_element($doc, $entry, "id", $item["uri"]); xml::add_element($doc, $entry, "id", $item["uri"]);
xml::add_element($doc, $entry, "title", $title); xml::add_element($doc, $entry, "title", $title);
$body = self::format_picture_post($item['body']); $body = self::format_picture_post($item['body']);
if ($item['title'] != "") { if ($item['title'] != "")
$body = "[b]".$item['title']."[/b]\n\n".$body; $body = "[b]".$item['title']."[/b]\n\n".$body;
}
$body = bbcode($body, false, false, 7); $body = bbcode($body, false, false, 7);
@ -2108,7 +1966,6 @@ class ostatus {
* @param array $item Data of the item that is to be posted * @param array $item Data of the item that is to be posted
* @param array $owner Contact data of the poster * @param array $owner Contact data of the poster
* @param $complete * @param $complete
* @todo Add type-hints
*/ */
private function entry_footer($doc, $entry, $item, $owner, $complete = true) { private function entry_footer($doc, $entry, $item, $owner, $complete = true) {
@ -2135,7 +1992,7 @@ class ostatus {
$thrparent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `uid` = %d AND `uri` = '%s'", $thrparent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
intval($owner["uid"]), intval($owner["uid"]),
dbesc($parent_item)); dbesc($parent_item));
if (dbm::is_result($thrparent)) { if ($thrparent) {
$mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"]; $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
$mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"]; $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
} }
@ -2149,13 +2006,10 @@ class ostatus {
$tags = item_getfeedtags($item); $tags = item_getfeedtags($item);
if (count($tags)) { if(count($tags))
foreach ($tags as $t) { foreach($tags as $t)
if ($t[0] == "@") { if ($t[0] == "@")
$mentioned[$t[1]] = $t[1]; $mentioned[$t[1]] = $t[1];
}
}
}
// Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS) // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
$newmentions = array(); $newmentions = array();
@ -2169,16 +2023,15 @@ class ostatus {
$r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'", $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
intval($owner["uid"]), intval($owner["uid"]),
dbesc(normalise_link($mention))); dbesc(normalise_link($mention)));
if ($r[0]["forum"] OR $r[0]["prv"]) { if ($r[0]["forum"] OR $r[0]["prv"])
xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned", xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
"ostatus:object-type" => ACTIVITY_OBJ_GROUP, "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
"href" => $mention)); "href" => $mention));
} else { else
xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned", xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
"ostatus:object-type" => ACTIVITY_OBJ_PERSON, "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
"href" => $mention)); "href" => $mention));
} }
}
if (!$item["private"]) { if (!$item["private"]) {
xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:attention", xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:attention",
@ -2188,13 +2041,10 @@ class ostatus {
"href" => "http://activityschema.org/collection/public")); "href" => "http://activityschema.org/collection/public"));
} }
if (count($tags)) { if(count($tags))
foreach ($tags as $t) { foreach($tags as $t)
if ($t[0] != "@") { if ($t[0] != "@")
xml::add_element($doc, $entry, "category", "", array("term" => $t[2])); xml::add_element($doc, $entry, "category", "", array("term" => $t[2]));
}
}
}
self::get_attachment($doc, $entry, $item); self::get_attachment($doc, $entry, $item);

View file

@ -524,14 +524,12 @@ function service_class_fetch($uid,$property) {
function upgrade_link($bbcode = false) { function upgrade_link($bbcode = false) {
$l = get_config('service_class','upgrade_link'); $l = get_config('service_class','upgrade_link');
if (! $l) { if(! $l)
return ''; return '';
} if($bbcode)
if ($bbcode) {
$t = sprintf('[url=%s]' . t('Click here to upgrade.') . '[/url]', $l); $t = sprintf('[url=%s]' . t('Click here to upgrade.') . '[/url]', $l);
} else { else
$t = sprintf('<a href="%s">' . t('Click here to upgrade.') . '</div>', $l); $t = sprintf('<a href="%s">' . t('Click here to upgrade.') . '</div>', $l);
}
return $t; return $t;
} }
@ -558,15 +556,13 @@ function upgrade_bool_message($bbcode = false) {
*/ */
function theme_include($file, $root = '') { function theme_include($file, $root = '') {
// Make sure $root ends with a slash / if it's not blank // Make sure $root ends with a slash / if it's not blank
if ($root !== '' && $root[strlen($root)-1] !== '/') { if($root !== '' && $root[strlen($root)-1] !== '/')
$root = $root . '/'; $root = $root . '/';
}
$theme_info = $a->theme_info; $theme_info = $a->theme_info;
if (is_array($theme_info) AND array_key_exists('extends',$theme_info)) { if(is_array($theme_info) AND array_key_exists('extends',$theme_info))
$parent = $theme_info['extends']; $parent = $theme_info['extends'];
} else { else
$parent = 'NOPATH'; $parent = 'NOPATH';
}
$theme = current_theme(); $theme = current_theme();
$thname = $theme; $thname = $theme;
$ext = substr($file,strrpos($file,'.')+1); $ext = substr($file,strrpos($file,'.')+1);
@ -577,11 +573,10 @@ function theme_include($file, $root = '') {
); );
foreach($paths as $p) { foreach($paths as $p) {
// strpos() is faster than strstr when checking if one string is in another (http://php.net/manual/en/function.strstr.php) // strpos() is faster than strstr when checking if one string is in another (http://php.net/manual/en/function.strstr.php)
if (strpos($p,'NOPATH') !== false) { if(strpos($p,'NOPATH') !== false)
continue; continue;
} elseif (file_exists($p)) { if(file_exists($p))
return $p; return $p;
} }
}
return ''; return '';
} }

View file

@ -364,7 +364,7 @@ function poller_kill_stale_workers() {
return; return;
} }
foreach ($r AS $pid) foreach ($r AS $pid) {
if (!posix_kill($pid["pid"], 0)) { if (!posix_kill($pid["pid"], 0)) {
q("UPDATE `workerqueue` SET `executed` = '%s', `pid` = 0 WHERE `pid` = %d", q("UPDATE `workerqueue` SET `executed` = '%s', `pid` = 0 WHERE `pid` = %d",
dbesc(NULL_DATE), intval($pid["pid"])); dbesc(NULL_DATE), intval($pid["pid"]));
@ -372,9 +372,8 @@ function poller_kill_stale_workers() {
// Kill long running processes // Kill long running processes
// Check if the priority is in a valid range // Check if the priority is in a valid range
if (!in_array($pid["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE))) { if (!in_array($pid["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE)))
$pid["priority"] = PRIORITY_MEDIUM; $pid["priority"] = PRIORITY_MEDIUM;
}
// Define the maximum durations // Define the maximum durations
$max_duration_defaults = array(PRIORITY_CRITICAL => 360, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 360); $max_duration_defaults = array(PRIORITY_CRITICAL => 360, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 360);

View file

@ -28,11 +28,9 @@ function handle_pubsubhubbub($id) {
global $a; global $a;
$r = q("SELECT * FROM `push_subscriber` WHERE `id` = %d", intval($id)); $r = q("SELECT * FROM `push_subscriber` WHERE `id` = %d", intval($id));
if (!$r)
if (!dbm::is_result($r)) {
return; return;
} else
$rr = $r[0]; $rr = $r[0];
logger("Generate feed of user ".$rr['nickname']." to ".$rr['callback_url']." - last updated ".$rr['last_update'], LOGGER_DEBUG); logger("Generate feed of user ".$rr['nickname']." to ".$rr['callback_url']." - last updated ".$rr['last_update'], LOGGER_DEBUG);
@ -67,10 +65,8 @@ function handle_pubsubhubbub($id) {
// increment this until some upper limit where we give up // increment this until some upper limit where we give up
$new_push = intval($rr['push']) + 1; $new_push = intval($rr['push']) + 1;
if ($new_push > 30) { if ($new_push > 30) // OK, let's give up
// OK, let's give up
$new_push = 0; $new_push = 0;
}
q("UPDATE `push_subscriber` SET `push` = %d WHERE id = %d", q("UPDATE `push_subscriber` SET `push` = %d WHERE id = %d",
$new_push, $new_push,

View file

@ -49,14 +49,12 @@ function was_recently_delayed($cid) {
function add_to_queue($cid,$network,$msg,$batch = false) { function add_to_queue($cid,$network,$msg,$batch = false) {
$max_queue = get_config('system','max_contact_queue'); $max_queue = get_config('system','max_contact_queue');
if ($max_queue < 1) { if($max_queue < 1)
$max_queue = 500; $max_queue = 500;
}
$batch_queue = get_config('system','max_batch_queue'); $batch_queue = get_config('system','max_batch_queue');
if ($batch_queue < 1) { if($batch_queue < 1)
$batch_queue = 1000; $batch_queue = 1000;
}
$r = q("SELECT COUNT(*) AS `total` FROM `queue` INNER JOIN `contact` ON `queue`.`cid` = `contact`.`id` $r = q("SELECT COUNT(*) AS `total` FROM `queue` INNER JOIN `contact` ON `queue`.`cid` = `contact`.`id`
WHERE `queue`.`cid` = %d AND `contact`.`self` = 0 ", WHERE `queue`.`cid` = %d AND `contact`.`self` = 0 ",
@ -66,7 +64,8 @@ function add_to_queue($cid,$network,$msg,$batch = false) {
if($batch && ($r[0]['total'] > $batch_queue)) { if($batch && ($r[0]['total'] > $batch_queue)) {
logger('add_to_queue: too many queued items for batch server ' . $cid . ' - discarding message'); logger('add_to_queue: too many queued items for batch server ' . $cid . ' - discarding message');
return; return;
} elseif ((! $batch) && ($r[0]['total'] > $max_queue)) { }
elseif((! $batch) && ($r[0]['total'] > $max_queue)) {
logger('add_to_queue: too many queued items for contact ' . $cid . ' - discarding message'); logger('add_to_queue: too many queued items for contact ' . $cid . ' - discarding message');
return; return;
} }

View file

@ -16,7 +16,8 @@ function get_salmon_key($uri,$keyhash) {
$ret[] = $a['@attributes']['href']; $ret[] = $a['@attributes']['href'];
} }
} }
} else { }
else {
return ''; return '';
} }
@ -68,9 +69,8 @@ function slapper($owner,$url,$slap) {
// does contact have a salmon endpoint? // does contact have a salmon endpoint?
if (! strlen($url)) { if(! strlen($url))
return; return;
}
if(! $owner['sprvkey']) { if(! $owner['sprvkey']) {
@ -169,12 +169,10 @@ function slapper($owner,$url,$slap) {
} }
} }
logger('slapper for '.$url.' returned ' . $return_code); logger('slapper for '.$url.' returned ' . $return_code);
if (! $return_code) { if(! $return_code)
return(-1); return(-1);
} if(($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))
if (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after'))) {
return(-1); return(-1);
}
return ((($return_code >= 200) && ($return_code < 300)) ? 0 : 1); return ((($return_code >= 200) && ($return_code < 300)) ? 0 : 1);
} }

View file

@ -55,25 +55,21 @@ function authenticate_success($user_record, $login_initial = false, $interactive
$a->user = $user_record; $a->user = $user_record;
if($interactive) { if($interactive) {
/// @TODO Comparison of strings this way may lead to bugs/incompatiblities
if ($a->user['login_date'] <= NULL_DATE) { if ($a->user['login_date'] <= NULL_DATE) {
$_SESSION['return_url'] = 'profile_photo/new'; $_SESSION['return_url'] = 'profile_photo/new';
$a->module = 'profile_photo'; $a->module = 'profile_photo';
info( t("Welcome ") . $a->user['username'] . EOL); info( t("Welcome ") . $a->user['username'] . EOL);
info( t('Please upload a profile photo.') . EOL); info( t('Please upload a profile photo.') . EOL);
} else {
info( t("Welcome back ") . $a->user['username'] . EOL);
} }
else
info( t("Welcome back ") . $a->user['username'] . EOL);
} }
$member_since = strtotime($a->user['register_date']); $member_since = strtotime($a->user['register_date']);
if(time() < ($member_since + ( 60 * 60 * 24 * 14)))
if (time() < ($member_since + ( 60 * 60 * 24 * 14))) {
$_SESSION['new_member'] = true; $_SESSION['new_member'] = true;
} else { else
$_SESSION['new_member'] = false; $_SESSION['new_member'] = false;
}
if(strlen($a->user['timezone'])) { if(strlen($a->user['timezone'])) {
date_default_timezone_set($a->user['timezone']); date_default_timezone_set($a->user['timezone']);
$a->timezone = $a->user['timezone']; $a->timezone = $a->user['timezone'];
@ -362,10 +358,9 @@ function item_permissions_sql($owner_id,$remote_verified = false,$groups = null)
$gs = '<<>>'; // should be impossible to match $gs = '<<>>'; // should be impossible to match
if(is_array($groups) && count($groups)) { if(is_array($groups) && count($groups)) {
foreach ($groups as $g) { foreach($groups as $g)
$gs .= '|<' . intval($g) . '>'; $gs .= '|<' . intval($g) . '>';
} }
}
$sql = sprintf( $sql = sprintf(
/*" AND ( private = 0 OR ( private in (1,2) AND wall = 1 AND ( allow_cid = '' OR allow_cid REGEXP '<%d>' ) /*" AND ( private = 0 OR ( private in (1,2) AND wall = 1 AND ( allow_cid = '' OR allow_cid REGEXP '<%d>' )

View file

@ -1664,22 +1664,20 @@ function poco_discover_federation() {
} }
} }
/* // Currently disabled, since the service isn't available anymore.
* Currently disabled, since the service isn't available anymore. // It is not removed since I hope that there will be a successor.
* It is not removed since I hope that there will be a successor. // Discover GNU Social Servers.
* Discover GNU Social Servers. //if (!get_config('system','ostatus_disabled')) {
if (!get_config('system','ostatus_disabled')) { // $serverdata = "http://gstools.org/api/get_open_instances/";
$serverdata = "http://gstools.org/api/get_open_instances/";
$result = z_fetch_url($serverdata); // $result = z_fetch_url($serverdata);
if ($result["success"]) { // if ($result["success"]) {
$servers = json_decode($result["body"]); // $servers = json_decode($result["body"]);
foreach($servers->data AS $server) // foreach($servers->data AS $server)
poco_check_server($server->instance_address); // poco_check_server($server->instance_address);
} // }
} //}
*/
set_config('poco','last_federation_discovery', time()); set_config('poco','last_federation_discovery', time());
} }

View file

@ -105,11 +105,10 @@ function create_tags_from_itemuri($itemuri, $uid) {
$messages = q("SELECT `id` FROM `item` WHERE uri ='%s' AND uid=%d", dbesc($itemuri), intval($uid)); $messages = q("SELECT `id` FROM `item` WHERE uri ='%s' AND uid=%d", dbesc($itemuri), intval($uid));
if(count($messages)) { if(count($messages)) {
foreach ($messages as $message) { foreach ($messages as $message)
create_tags_from_item($message["id"]); create_tags_from_item($message["id"]);
} }
} }
}
function update_items() { function update_items() {
global $db; global $db;

View file

@ -53,9 +53,8 @@ class Template implements ITemplateEngine {
private function _get_var($name, $retNoKey = false) { private function _get_var($name, $retNoKey = false) {
$keys = array_map('trim', explode(".", $name)); $keys = array_map('trim', explode(".", $name));
if ($retNoKey && !array_key_exists($keys[0], $this->r)) { if ($retNoKey && !array_key_exists($keys[0], $this->r))
return KEY_NOT_EXISTS; return KEY_NOT_EXISTS;
}
$val = $this->r; $val = $this->r;
foreach ($keys as $k) { foreach ($keys as $k) {
$val = (isset($val[$k]) ? $val[$k] : null); $val = (isset($val[$k]) ? $val[$k] : null);
@ -74,16 +73,14 @@ class Template implements ITemplateEngine {
if (strpos($args[2], "==") > 0) { if (strpos($args[2], "==") > 0) {
list($a, $b) = array_map("trim", explode("==", $args[2])); list($a, $b) = array_map("trim", explode("==", $args[2]));
$a = $this->_get_var($a); $a = $this->_get_var($a);
if ($b[0] == "$") { if ($b[0] == "$")
$b = $this->_get_var($b); $b = $this->_get_var($b);
}
$val = ($a == $b); $val = ($a == $b);
} else if (strpos($args[2], "!=") > 0) { } else if (strpos($args[2], "!=") > 0) {
list($a, $b) = array_map("trim", explode("!=", $args[2])); list($a, $b) = array_map("trim", explode("!=", $args[2]));
$a = $this->_get_var($a); $a = $this->_get_var($a);
if ($b[0] == "$") { if ($b[0] == "$")
$b = $this->_get_var($b); $b = $this->_get_var($b);
}
$val = ($a != $b); $val = ($a != $b);
} else { } else {
$val = $this->_get_var($args[2]); $val = $this->_get_var($args[2]);
@ -112,16 +109,14 @@ class Template implements ITemplateEngine {
//$vals = $this->r[$m[0]]; //$vals = $this->r[$m[0]];
$vals = $this->_get_var($m[0]); $vals = $this->_get_var($m[0]);
$ret = ""; $ret = "";
if (!is_array($vals)) { if (!is_array($vals))
return $ret; return $ret;
}
foreach ($vals as $k => $v) { foreach ($vals as $k => $v) {
$this->_push_stack(); $this->_push_stack();
$r = $this->r; $r = $this->r;
$r[$varname] = $v; $r[$varname] = $v;
if ($keyname != '') { if ($keyname != '')
$r[$keyname] = (($k === 0) ? '0' : $k); $r[$keyname] = (($k === 0) ? '0' : $k);
}
$ret .= $this->replace($args[3], $r); $ret .= $this->replace($args[3], $r);
$this->_pop_stack(); $this->_pop_stack();
} }
@ -141,9 +136,8 @@ class Template implements ITemplateEngine {
$newctx = null; $newctx = null;
} }
if ($tplfile[0] == "$") { if ($tplfile[0] == "$")
$tplfile = $this->_get_var($tplfile); $tplfile = $this->_get_var($tplfile);
}
$this->_push_stack(); $this->_push_stack();
$r = $this->r; $r = $this->r;

View file

@ -421,11 +421,10 @@ function expand_acl($s) {
$t = str_replace('<','',$s); $t = str_replace('<','',$s);
$a = explode('>',$t); $a = explode('>',$t);
foreach($a as $aa) { foreach($a as $aa) {
if (intval($aa)) { if(intval($aa))
$ret[] = intval($aa); $ret[] = intval($aa);
} }
} }
}
return $ret; return $ret;
}} }}

View file

@ -174,34 +174,29 @@ function add_shadow_entry($itemid) {
function update_thread_uri($itemuri, $uid) { function update_thread_uri($itemuri, $uid) {
$messages = q("SELECT `id` FROM `item` WHERE uri ='%s' AND uid=%d", dbesc($itemuri), intval($uid)); $messages = q("SELECT `id` FROM `item` WHERE uri ='%s' AND uid=%d", dbesc($itemuri), intval($uid));
if (dbm::is_result($messages)) { if (dbm::is_result($messages))
foreach ($messages as $message) { foreach ($messages as $message)
update_thread($message["id"]); update_thread($message["id"]);
} }
}
}
function update_thread($itemid, $setmention = false) { function update_thread($itemid, $setmention = false) {
$items = q("SELECT `uid`, `guid`, `title`, `body`, `created`, `edited`, `commented`, `received`, `changed`, `wall`, `private`, `pubmail`, `moderated`, `visible`, `spam`, `starred`, `bookmark`, `contact-id`, `gcontact-id`, $items = q("SELECT `uid`, `guid`, `title`, `body`, `created`, `edited`, `commented`, `received`, `changed`, `wall`, `private`, `pubmail`, `moderated`, `visible`, `spam`, `starred`, `bookmark`, `contact-id`, `gcontact-id`,
`deleted`, `origin`, `forum_mode`, `network`, `rendered-html`, `rendered-hash` FROM `item` WHERE `id` = %d AND (`parent` = %d OR `parent` = 0) LIMIT 1", intval($itemid), intval($itemid)); `deleted`, `origin`, `forum_mode`, `network`, `rendered-html`, `rendered-hash` FROM `item` WHERE `id` = %d AND (`parent` = %d OR `parent` = 0) LIMIT 1", intval($itemid), intval($itemid));
if (!dbm::is_result($items)) { if (!dbm::is_result($items))
return; return;
}
$item = $items[0]; $item = $items[0];
if ($setmention) { if ($setmention)
$item["mention"] = 1; $item["mention"] = 1;
}
$sql = ""; $sql = "";
foreach ($item AS $field => $data) foreach ($item AS $field => $data)
if (!in_array($field, array("guid", "title", "body", "rendered-html", "rendered-hash"))) { if (!in_array($field, array("guid", "title", "body", "rendered-html", "rendered-hash"))) {
if ($sql != "") { if ($sql != "")
$sql .= ", "; $sql .= ", ";
}
$sql .= "`".$field."` = '".dbesc($data)."'"; $sql .= "`".$field."` = '".dbesc($data)."'";
} }
@ -213,9 +208,8 @@ function update_thread($itemid, $setmention = false) {
// Updating a shadow item entry // Updating a shadow item entry
$items = q("SELECT `id` FROM `item` WHERE `guid` = '%s' AND `uid` = 0 LIMIT 1", dbesc($item["guid"])); $items = q("SELECT `id` FROM `item` WHERE `guid` = '%s' AND `uid` = 0 LIMIT 1", dbesc($item["guid"]));
if (!dbm::is_result($items)) { if (!$items)
return; return;
}
$result = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `rendered-html` = '%s', `rendered-hash` = '%s' WHERE `id` = %d", $result = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `rendered-html` = '%s', `rendered-hash` = '%s' WHERE `id` = %d",
dbesc($item["title"]), dbesc($item["title"]),
@ -230,12 +224,10 @@ function update_thread($itemid, $setmention = false) {
function delete_thread_uri($itemuri, $uid) { function delete_thread_uri($itemuri, $uid) {
$messages = q("SELECT `id` FROM `item` WHERE uri ='%s' AND uid=%d", dbesc($itemuri), intval($uid)); $messages = q("SELECT `id` FROM `item` WHERE uri ='%s' AND uid=%d", dbesc($itemuri), intval($uid));
if (dbm::is_result($messages)) { if(count($messages))
foreach ($messages as $message) { foreach ($messages as $message)
delete_thread($message["id"], $itemuri); delete_thread($message["id"], $itemuri);
} }
}
}
function delete_thread($itemid, $itemuri = "") { function delete_thread($itemid, $itemuri = "") {
$item = q("SELECT `uid` FROM `thread` WHERE `iid` = %d", intval($itemid)); $item = q("SELECT `uid` FROM `thread` WHERE `iid` = %d", intval($itemid));

View file

@ -21,41 +21,35 @@ function update_gcontact_run(&$argv, &$argc){
$r = q("SELECT * FROM `gcontact` WHERE `id` = %d", intval($contact_id)); $r = q("SELECT * FROM `gcontact` WHERE `id` = %d", intval($contact_id));
if (!dbm::is_result($r)) { if (!$r)
return; return;
}
if (!in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))) } if (!in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS)))
return; return;
}
$data = probe_url($r[0]["url"]); $data = probe_url($r[0]["url"]);
if (!in_array($data["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))) { if (!in_array($data["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))) {
if ($r[0]["server_url"] != "") { if ($r[0]["server_url"] != "")
poco_check_server($r[0]["server_url"], $r[0]["network"]); poco_check_server($r[0]["server_url"], $r[0]["network"]);
}
q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `id` = %d", q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `id` = %d",
dbesc(datetime_convert()), intval($contact_id)); dbesc(datetime_convert()), intval($contact_id));
return; return;
} }
if (($data["name"] == "") AND ($r[0]['name'] != "")) { if (($data["name"] == "") AND ($r[0]['name'] != ""))
$data["name"] = $r[0]['name']; $data["name"] = $r[0]['name'];
}
if (($data["nick"] == "") AND ($r[0]['nick'] != "")) { if (($data["nick"] == "") AND ($r[0]['nick'] != ""))
$data["nick"] = $r[0]['nick']; $data["nick"] = $r[0]['nick'];
}
if (($data["addr"] == "") AND ($r[0]['addr'] != "")) { if (($data["addr"] == "") AND ($r[0]['addr'] != ""))
$data["addr"] = $r[0]['addr']; $data["addr"] = $r[0]['addr'];
}
if (($data["photo"] == "") AND ($r[0]['photo'] != "")) { if (($data["photo"] == "") AND ($r[0]['photo'] != ""))
$data["photo"] = $r[0]['photo']; $data["photo"] = $r[0]['photo'];
}
q("UPDATE `gcontact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `photo` = '%s' q("UPDATE `gcontact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `photo` = '%s'
WHERE `id` = %d", WHERE `id` = %d",

View file

@ -28,17 +28,17 @@ $a->backend = false;
/** /**
* *
* Load the configuration file which contains our DB credentials. * Load the configuration file which contains our DB credentials.
* Ignore errors. If the file doesn't exist or is empty, we are running in * Ignore errors. If the file doesn't exist or is empty, we are running in installation mode.
* installation mode.
* *
*/ */
$install = ((file_exists('.htconfig.php') && filesize('.htconfig.php')) ? false : true); $install = ((file_exists('.htconfig.php') && filesize('.htconfig.php')) ? false : true);
// Only load config if found, don't surpress errors @include(".htconfig.php");
if (!$install) {
include(".htconfig.php");
}
/** /**
* *
@ -233,14 +233,12 @@ if (strlen($a->module)) {
*/ */
// Compatibility with the Android Diaspora client // Compatibility with the Android Diaspora client
if ($a->module == "stream") { if ($a->module == "stream")
$a->module = "network"; $a->module = "network";
}
// Compatibility with the Firefox App // Compatibility with the Firefox App
if (($a->module == "users") AND ($a->cmd == "users/sign_in")) { if (($a->module == "users") AND ($a->cmd == "users/sign_in"))
$a->module = "login"; $a->module = "login";
}
$privateapps = get_config('config','private_addons'); $privateapps = get_config('config','private_addons');
@ -248,11 +246,11 @@ if (strlen($a->module)) {
//Check if module is an app and if public access to apps is allowed or not //Check if module is an app and if public access to apps is allowed or not
if ((!local_user()) && plugin_is_app($a->module) && $privateapps === "1") { if ((!local_user()) && plugin_is_app($a->module) && $privateapps === "1") {
info( t("You must be logged in to use addons. ")); info( t("You must be logged in to use addons. "));
} else {
include_once("addon/{$a->module}/{$a->module}.php");
if (function_exists($a->module . '_module')) {
$a->module_loaded = true;
} }
else {
include_once("addon/{$a->module}/{$a->module}.php");
if(function_exists($a->module . '_module'))
$a->module_loaded = true;
} }
} }
@ -394,15 +392,13 @@ $a->init_page_end();
// If you're just visiting, let javascript take you home // If you're just visiting, let javascript take you home
if (x($_SESSION,'visitor_home')) { if(x($_SESSION,'visitor_home'))
$homebase = $_SESSION['visitor_home']; $homebase = $_SESSION['visitor_home'];
} elseif (local_user()) { elseif(local_user())
$homebase = 'profile/' . $a->user['nickname']; $homebase = 'profile/' . $a->user['nickname'];
}
if (isset($homebase)) { if(isset($homebase))
$a->page['content'] .= '<script>var homebase="' . $homebase . '" ; </script>'; $a->page['content'] .= '<script>var homebase="' . $homebase . '" ; </script>';
}
// now that we've been through the module content, see if the page reported // now that we've been through the module content, see if the page reported
// a permission problem and if so, a 403 response would seem to be in order. // a permission problem and if so, a 403 response would seem to be in order.
@ -452,7 +448,8 @@ if ($a->module != 'install' && $a->module != 'maintenance') {
if($a->is_mobile || $a->is_tablet) { if($a->is_mobile || $a->is_tablet) {
if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) { if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
$link = 'toggle_mobile?address=' . curPageURL(); $link = 'toggle_mobile?address=' . curPageURL();
} else { }
else {
$link = 'toggle_mobile?off=1&address=' . curPageURL(); $link = 'toggle_mobile?off=1&address=' . curPageURL();
} }
$a->page['footer'] = replace_macros(get_markup_template("toggle_mobile_footer.tpl"), array( $a->page['footer'] = replace_macros(get_markup_template("toggle_mobile_footer.tpl"), array(
@ -465,11 +462,10 @@ if ($a->is_mobile || $a->is_tablet) {
* Build the page - now that we have all the components * Build the page - now that we have all the components
*/ */
if (!$a->theme['stylesheet']) { if(!$a->theme['stylesheet'])
$stylesheet = current_theme_url(); $stylesheet = current_theme_url();
} else { else
$stylesheet = $a->theme['stylesheet']; $stylesheet = $a->theme['stylesheet'];
}
$a->page['htmlhead'] = str_replace('{{$stylesheet}}',$stylesheet,$a->page['htmlhead']); $a->page['htmlhead'] = str_replace('{{$stylesheet}}',$stylesheet,$a->page['htmlhead']);
//$a->page['htmlhead'] = replace_macros($a->page['htmlhead'], array('$stylesheet' => $stylesheet)); //$a->page['htmlhead'] = replace_macros($a->page['htmlhead'], array('$stylesheet' => $stylesheet));
@ -503,9 +499,8 @@ if (isset($_GET["mode"]) AND ($_GET["mode"] == "raw")) {
echo substr($target->saveHTML(), 6, -8); echo substr($target->saveHTML(), 6, -8);
if (!$a->is_backend()) { if (!$a->is_backend())
session_write_close(); session_write_close();
}
exit; exit;
} }

View file

@ -859,9 +859,8 @@ function admin_page_site(App $a) {
$allowed_theme_list = Config::get('system', 'allowed_themes'); $allowed_theme_list = Config::get('system', 'allowed_themes');
foreach ($files as $file) { foreach ($files as $file) {
if (file_exists($file.'/unsupported')) if (intval(file_exists($file.'/unsupported')))
continue; continue;
}
$f = basename($file); $f = basename($file);
@ -1275,7 +1274,7 @@ function admin_page_users(App $a) {
if ($a->argc>2) { if ($a->argc>2) {
$uid = $a->argv[3]; $uid = $a->argv[3];
$user = q("SELECT `username`, `blocked` FROM `user` WHERE `uid` = %d", intval($uid)); $user = q("SELECT `username`, `blocked` FROM `user` WHERE `uid` = %d", intval($uid));
if (!dbm::is_result($user)) { if (count($user) == 0) {
notice('User not found'.EOL); notice('User not found'.EOL);
goaway('admin/users'); goaway('admin/users');
return ''; // NOTREACHED return ''; // NOTREACHED
@ -1707,9 +1706,9 @@ function admin_page_themes(App $a) {
continue; continue;
} }
$is_experimental = file_exists($file.'/experimental'); $is_experimental = intval(file_exists($file.'/experimental'));
$is_supported = (!file_exists($file.'/unsupported')); $is_supported = 1-(intval(file_exists($file.'/unsupported')));
$is_allowed = in_array($f,$allowed_themes); $is_allowed = intval(in_array($f,$allowed_themes));
if ($is_allowed OR $is_supported OR get_config("system", "show_unsupported_themes")) { if ($is_allowed OR $is_supported OR get_config("system", "show_unsupported_themes")) {
$themes[] = array('name' => $f, 'experimental' => $is_experimental, 'supported' => $is_supported, 'allowed' => $is_allowed); $themes[] = array('name' => $f, 'experimental' => $is_experimental, 'supported' => $is_supported, 'allowed' => $is_allowed);
@ -1762,7 +1761,7 @@ function admin_page_themes(App $a) {
$status="off"; $action= t("Enable"); $status="off"; $action= t("Enable");
} }
$readme = null; $readme = Null;
if (is_file("view/theme/$theme/README.md")) { if (is_file("view/theme/$theme/README.md")) {
$readme = file_get_contents("view/theme/$theme/README.md"); $readme = file_get_contents("view/theme/$theme/README.md");
$readme = Markdown($readme); $readme = Markdown($readme);

View file

@ -37,9 +37,8 @@ function allfriends_content(App $a) {
$total = count_all_friends(local_user(), $cid); $total = count_all_friends(local_user(), $cid);
if (count($total)) { if(count($total))
$a->set_pager_total($total); $a->set_pager_total($total);
}
$r = all_friends(local_user(), $cid, $a->pager['start'], $a->pager['itemspage']); $r = all_friends(local_user(), $cid, $a->pager['start'], $a->pager['itemspage']);

View file

@ -5,19 +5,21 @@ function apps_content(App $a) {
if ($privateaddons === "1") { if ($privateaddons === "1") {
if((! (local_user()))) { if((! (local_user()))) {
info( t("You must be logged in to use addons. ")); info( t("You must be logged in to use addons. "));
return; return;};
}
} }
$title = t('Applications'); $title = t('Applications');
if (count($a->apps) == 0) { if(count($a->apps)==0)
notice( t('No installed applications.') . EOL); notice( t('No installed applications.') . EOL);
}
$tpl = get_markup_template("apps.tpl"); $tpl = get_markup_template("apps.tpl");
return replace_macros($tpl, array( return replace_macros($tpl, array(
'$title' => $title, '$title' => $title,
'$apps' => $a->apps, '$apps' => $a->apps,
)); ));
} }

View file

@ -69,7 +69,6 @@ function cal_content(App $a) {
// First day of the week (0 = Sunday) // First day of the week (0 = Sunday)
$firstDay = get_pconfig(local_user(),'system','first_day_of_week'); $firstDay = get_pconfig(local_user(),'system','first_day_of_week');
/// @TODO Convert all these to with curly braces
if ($firstDay === false) $firstDay=0; if ($firstDay === false) $firstDay=0;
// get the translation strings for the callendar // get the translation strings for the callendar
@ -95,7 +94,6 @@ function cal_content(App $a) {
$m = 0; $m = 0;
$ignored = ((x($_REQUEST,'ignored')) ? intval($_REQUEST['ignored']) : 0); $ignored = ((x($_REQUEST,'ignored')) ? intval($_REQUEST['ignored']) : 0);
/// @TODO Convert to one if() statement
if($a->argc == 4) { if($a->argc == 4) {
if($a->argv[2] == 'export') { if($a->argv[2] == 'export') {
$mode = 'export'; $mode = 'export';
@ -237,10 +235,9 @@ function cal_content(App $a) {
$events=array(); $events=array();
// transform the event in a usable array // transform the event in a usable array
if (dbm::is_result($r)) { if (dbm::is_result($r))
$r = sort_by_date($r); $r = sort_by_date($r);
$events = process_events($r); $events = process_events($r);
}
if ($a->argv[2] === 'json'){ if ($a->argv[2] === 'json'){
echo json_encode($events); killme(); echo json_encode($events); killme();

View file

@ -63,18 +63,17 @@ function common_content(App $a) {
dbesc(normalise_link(get_my_url())), dbesc(normalise_link(get_my_url())),
intval($profile_uid) intval($profile_uid)
); );
if (dbm::is_result($r)) { if (dbm::is_result($r))
$cid = $r[0]['id']; $cid = $r[0]['id'];
} else { else {
$r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1", $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
dbesc(normalise_link(get_my_url())) dbesc(normalise_link(get_my_url()))
); );
if (dbm::is_result($r)) { if (dbm::is_result($r))
$zcid = $r[0]['id']; $zcid = $r[0]['id'];
} }
} }
} }
}
if ($cid == 0 && $zcid == 0) { if ($cid == 0 && $zcid == 0) {
return; return;

View file

@ -79,9 +79,8 @@ function community_content(App $a, $update = 0) {
$r = community_getitems($a->pager['start'] + ($count * $a->pager['itemspage']), $a->pager['itemspage']); $r = community_getitems($a->pager['start'] + ($count * $a->pager['itemspage']), $a->pager['itemspage']);
} while ((sizeof($s) < $a->pager['itemspage']) AND (++$count < 50) AND (sizeof($r) > 0)); } while ((sizeof($s) < $a->pager['itemspage']) AND (++$count < 50) AND (sizeof($r) > 0));
} else { } else
$s = $r; $s = $r;
}
// we behave the same in message lists as the search module // we behave the same in message lists as the search module

View file

@ -14,10 +14,9 @@ function contactgroup_content(App $a) {
intval($a->argv[2]), intval($a->argv[2]),
intval(local_user()) intval(local_user())
); );
if (dbm::is_result($r)) { if (dbm::is_result($r))
$change = intval($a->argv[2]); $change = intval($a->argv[2]);
} }
}
if(($a->argc > 1) && (intval($a->argv[1]))) { if(($a->argc > 1) && (intval($a->argv[1]))) {
@ -33,15 +32,15 @@ function contactgroup_content(App $a) {
$members = group_get_members($group['id']); $members = group_get_members($group['id']);
$preselected = array(); $preselected = array();
if(count($members)) { if(count($members)) {
foreach ($members as $member) { foreach($members as $member)
$preselected[] = $member['id']; $preselected[] = $member['id'];
} }
}
if($change) { if($change) {
if(in_array($change,$preselected)) { if(in_array($change,$preselected)) {
group_rmv_member(local_user(),$group['name'],$change); group_rmv_member(local_user(),$group['name'],$change);
} else { }
else {
group_add_member(local_user(),$group['name'],$change); group_add_member(local_user(),$group['name'],$change);
} }
} }

View file

@ -99,22 +99,13 @@ function contacts_init(App $a) {
function contacts_batch_actions(App $a) { function contacts_batch_actions(App $a) {
$contacts_id = $_POST['contact_batch']; $contacts_id = $_POST['contact_batch'];
if (!is_array($contacts_id)) { if (!is_array($contacts_id)) return;
return;
}
$orig_records = q("SELECT * FROM `contact` WHERE `id` IN (%s) AND `uid` = %d AND `self` = 0", $orig_records = q("SELECT * FROM `contact` WHERE `id` IN (%s) AND `uid` = %d AND `self` = 0",
implode(",", $contacts_id), implode(",", $contacts_id),
intval(local_user()) intval(local_user())
); );
if (!dbm::is_result($orig_records)) {
/// @TODO EOL really needed?
notice( t('Could not access contact record(s).') . EOL);
goaway('contacts');
return; // NOTREACHED
}
$count_actions=0; $count_actions=0;
foreach($orig_records as $orig_record) { foreach($orig_records as $orig_record) {
$contact_id = $orig_record['id']; $contact_id = $orig_record['id'];
@ -139,14 +130,14 @@ function contacts_batch_actions(App $a) {
$count_actions++; $count_actions++;
} }
} }
if ($count_actions>0) { if ($count_actions>0) {
info ( sprintf( tt("%d contact edited.", "%d contacts edited.", $count_actions), $count_actions) ); info ( sprintf( tt("%d contact edited.", "%d contacts edited.", $count_actions), $count_actions) );
} }
if (x($_SESSION,'return_url')) { if (x($_SESSION,'return_url')) {
goaway('' . $_SESSION['return_url']); goaway('' . $_SESSION['return_url']);
} else { }
else {
goaway('contacts'); goaway('contacts');
} }
@ -174,8 +165,7 @@ function contacts_post(App $a) {
intval(local_user()) intval(local_user())
); );
if (! dbm::is_result($orig_record)) { if (! count($orig_record)) {
/// @TODO EOL really needed?
notice( t('Could not access contact record.') . EOL); notice( t('Could not access contact record.') . EOL);
goaway('contacts'); goaway('contacts');
return; // NOTREACHED return; // NOTREACHED
@ -204,10 +194,8 @@ function contacts_post(App $a) {
$ffi_keyword_blacklist = escape_tags(trim($_POST['ffi_keyword_blacklist'])); $ffi_keyword_blacklist = escape_tags(trim($_POST['ffi_keyword_blacklist']));
$priority = intval($_POST['poll']); $priority = intval($_POST['poll']);
if($priority > 5 || $priority < 0)
if ($priority > 5 || $priority < 0) {
$priority = 0; $priority = 0;
}
$info = escape_tags(trim($_POST['info'])); $info = escape_tags(trim($_POST['info']));
@ -224,21 +212,17 @@ function contacts_post(App $a) {
intval($contact_id), intval($contact_id),
intval(local_user()) intval(local_user())
); );
/// @TODO Decide to use dbm::is_result() here, what does $r include? if($r)
if ($r) {
info( t('Contact updated.') . EOL); info( t('Contact updated.') . EOL);
} else { else
notice( t('Failed to update contact record.') . EOL); notice( t('Failed to update contact record.') . EOL);
}
$r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1", $r = q("select * from contact where id = %d and uid = %d limit 1",
intval($contact_id), intval($contact_id),
intval(local_user()) intval(local_user())
); );
if($r && dbm::is_result($r))
if (dbm::is_result($r)) {
$a->data['contact'] = $r[0]; $a->data['contact'] = $r[0];
}
return; return;
@ -247,47 +231,40 @@ function contacts_post(App $a) {
/*contact actions*/ /*contact actions*/
function _contact_update($contact_id) { function _contact_update($contact_id) {
$r = q("SELECT `uid`, `url`, `network` FROM `contact` WHERE `id` = %d", intval($contact_id)); $r = q("SELECT `uid`, `url`, `network` FROM `contact` WHERE `id` = %d", intval($contact_id));
if (!dbm::is_result($r)) { if (!$r)
return; return;
}
$uid = $r[0]["uid"]; $uid = $r[0]["uid"];
if ($uid != local_user()) { if ($uid != local_user())
return; return;
}
if ($r[0]["network"] == NETWORK_OSTATUS) { if ($r[0]["network"] == NETWORK_OSTATUS) {
$result = new_contact($uid, $r[0]["url"], false); $result = new_contact($uid, $r[0]["url"], false);
if ($result['success']) { if ($result['success'])
$r = q("UPDATE `contact` SET `subhub` = 1 WHERE `id` = %d", $r = q("UPDATE `contact` SET `subhub` = 1 WHERE `id` = %d",
intval($contact_id)); intval($contact_id));
} } else
} else {
// pull feed and consume it, which should subscribe to the hub. // pull feed and consume it, which should subscribe to the hub.
proc_run(PRIORITY_HIGH, "include/onepoll.php", $contact_id, "force"); proc_run(PRIORITY_HIGH, "include/onepoll.php", $contact_id, "force");
} }
}
function _contact_update_profile($contact_id) { function _contact_update_profile($contact_id) {
$r = q("SELECT `uid`, `url`, `network` FROM `contact` WHERE `id` = %d", intval($contact_id)); $r = q("SELECT `uid`, `url`, `network` FROM `contact` WHERE `id` = %d", intval($contact_id));
if (!dbm::is_result($r)) { if (!$r)
return; return;
}
$uid = $r[0]["uid"]; $uid = $r[0]["uid"];
if ($uid != local_user()) { if ($uid != local_user())
return; return;
}
$data = probe_url($r[0]["url"]); $data = probe_url($r[0]["url"]);
// "Feed" or "Unknown" is mostly a sign of communication problems // "Feed" or "Unknown" is mostly a sign of communication problems
if ((in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM))) AND ($data["network"] != $r[0]["network"])) { if ((in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM))) AND ($data["network"] != $r[0]["network"]))
return; return;
}
$updatefields = array("name", "nick", "url", "addr", "batch", "notify", "poll", "request", "confirm", $updatefields = array("name", "nick", "url", "addr", "batch", "notify", "poll", "request", "confirm",
"poco", "network", "alias"); "poco", "network", "alias");
@ -296,36 +273,30 @@ function _contact_update_profile($contact_id) {
if ($data["network"] == NETWORK_OSTATUS) { if ($data["network"] == NETWORK_OSTATUS) {
$result = new_contact($uid, $data["url"], false); $result = new_contact($uid, $data["url"], false);
if ($result['success']) { if ($result['success'])
$update["subhub"] = true; $update["subhub"] = true;
} }
}
foreach ($updatefields AS $field) { foreach($updatefields AS $field)
if (isset($data[$field]) AND ($data[$field] != "")) { if (isset($data[$field]) AND ($data[$field] != ""))
$update[$field] = $data[$field]; $update[$field] = $data[$field];
}
}
$update["nurl"] = normalise_link($data["url"]); $update["nurl"] = normalise_link($data["url"]);
$query = ""; $query = "";
if (isset($data["priority"]) AND ($data["priority"] != 0)) { if (isset($data["priority"]) AND ($data["priority"] != 0))
$query = "`priority` = ".intval($data["priority"]); $query = "`priority` = ".intval($data["priority"]);
}
foreach($update AS $key => $value) { foreach($update AS $key => $value) {
if ($query != "") { if ($query != "")
$query .= ", "; $query .= ", ";
}
$query .= "`".$key."` = '".dbesc($value)."'"; $query .= "`".$key."` = '".dbesc($value)."'";
} }
if ($query == "") { if ($query == "")
return; return;
}
$r = q("UPDATE `contact` SET $query WHERE `id` = %d AND `uid` = %d", $r = q("UPDATE `contact` SET $query WHERE `id` = %d AND `uid` = %d",
intval($contact_id), intval($contact_id),
@ -393,9 +364,8 @@ function contacts_content(App $a) {
if($a->argc == 3) { if($a->argc == 3) {
$contact_id = intval($a->argv[1]); $contact_id = intval($a->argv[1]);
if (! $contact_id) { if(! $contact_id)
return; return;
}
$cmd = $a->argv[2]; $cmd = $a->argv[2];
@ -404,7 +374,7 @@ function contacts_content(App $a) {
intval(local_user()) intval(local_user())
); );
if (! dbm::is_result($orig_record)) { if(! count($orig_record)) {
notice( t('Could not access contact record.') . EOL); notice( t('Could not access contact record.') . EOL);
goaway('contacts'); goaway('contacts');
return; // NOTREACHED return; // NOTREACHED
@ -424,7 +394,6 @@ function contacts_content(App $a) {
if($cmd === 'block') { if($cmd === 'block') {
$r = _contact_block($contact_id, $orig_record[0]); $r = _contact_block($contact_id, $orig_record[0]);
/// @TODO is $r a database result?
if ($r) { if ($r) {
$blocked = (($orig_record[0]['blocked']) ? 0 : 1); $blocked = (($orig_record[0]['blocked']) ? 0 : 1);
info((($blocked) ? t('Contact has been blocked') : t('Contact has been unblocked')).EOL); info((($blocked) ? t('Contact has been blocked') : t('Contact has been unblocked')).EOL);
@ -436,7 +405,6 @@ function contacts_content(App $a) {
if($cmd === 'ignore') { if($cmd === 'ignore') {
$r = _contact_ignore($contact_id, $orig_record[0]); $r = _contact_ignore($contact_id, $orig_record[0]);
/// @TODO is $r a database result?
if ($r) { if ($r) {
$readonly = (($orig_record[0]['readonly']) ? 0 : 1); $readonly = (($orig_record[0]['readonly']) ? 0 : 1);
info((($readonly) ? t('Contact has been ignored') : t('Contact has been unignored')).EOL); info((($readonly) ? t('Contact has been ignored') : t('Contact has been unignored')).EOL);
@ -449,7 +417,6 @@ function contacts_content(App $a) {
if($cmd === 'archive') { if($cmd === 'archive') {
$r = _contact_archive($contact_id, $orig_record[0]); $r = _contact_archive($contact_id, $orig_record[0]);
/// @TODO is $r a database result?
if ($r) { if ($r) {
$archived = (($orig_record[0]['archive']) ? 0 : 1); $archived = (($orig_record[0]['archive']) ? 0 : 1);
info((($archived) ? t('Contact has been archived') : t('Contact has been unarchived')).EOL); info((($archived) ? t('Contact has been archived') : t('Contact has been unarchived')).EOL);
@ -492,7 +459,8 @@ function contacts_content(App $a) {
if ($_REQUEST['canceled']) { if ($_REQUEST['canceled']) {
if (x($_SESSION,'return_url')) { if (x($_SESSION,'return_url')) {
goaway('' . $_SESSION['return_url']); goaway('' . $_SESSION['return_url']);
} else { }
else {
goaway('contacts'); goaway('contacts');
} }
} }
@ -501,7 +469,8 @@ function contacts_content(App $a) {
info( t('Contact has been removed.') . EOL ); info( t('Contact has been removed.') . EOL );
if (x($_SESSION,'return_url')) { if (x($_SESSION,'return_url')) {
goaway('' . $_SESSION['return_url']); goaway('' . $_SESSION['return_url']);
} else { }
else {
goaway('contacts'); goaway('contacts');
} }
return; // NOTREACHED return; // NOTREACHED
@ -569,7 +538,7 @@ function contacts_content(App $a) {
? t('Never') ? t('Never')
: datetime_convert('UTC',date_default_timezone_get(),$contact['last-update'],'D, j M Y, g:i A')); : datetime_convert('UTC',date_default_timezone_get(),$contact['last-update'],'D, j M Y, g:i A'));
if ($contact['last-update'] !== NULL_DATE) { if ($contact['last-update'] > NULL_DATE) {
$last_update .= ' ' . (($contact['last-update'] <= $contact['success_update']) ? t("\x28Update was successful\x29") : t("\x28Update was not successful\x29")); $last_update .= ' ' . (($contact['last-update'] <= $contact['success_update']) ? t("\x28Update was successful\x29") : t("\x28Update was not successful\x29"));
} }
$lblsuggest = (($contact['network'] === NETWORK_DFRN) ? t('Suggest friends') : ''); $lblsuggest = (($contact['network'] === NETWORK_DFRN) ? t('Suggest friends') : '');
@ -595,22 +564,20 @@ function contacts_content(App $a) {
$fetch_further_information = array('fetch_further_information', t('Fetch further information for feeds'), $contact['fetch_further_information'], t('Fetch further information for feeds'), $fetch_further_information = array('fetch_further_information', t('Fetch further information for feeds'), $contact['fetch_further_information'], t('Fetch further information for feeds'),
array('0'=>t('Disabled'), '1'=>t('Fetch information'), '2'=>t('Fetch information and keywords'))); array('0'=>t('Disabled'), '1'=>t('Fetch information'), '2'=>t('Fetch information and keywords')));
} }
if (in_array($contact['network'], array(NETWORK_FEED, NETWORK_MAIL, NETWORK_MAIL2))) { if (in_array($contact['network'], array(NETWORK_FEED, NETWORK_MAIL, NETWORK_MAIL2)))
$poll_interval = contact_poll_interval($contact['priority'],(! $poll_enabled)); $poll_interval = contact_poll_interval($contact['priority'],(! $poll_enabled));
}
if ($contact['network'] == NETWORK_DFRN) { if ($contact['network'] == NETWORK_DFRN)
$profile_select = contact_profile_assign($contact['profile-id'],(($contact['network'] !== NETWORK_DFRN) ? true : false)); $profile_select = contact_profile_assign($contact['profile-id'],(($contact['network'] !== NETWORK_DFRN) ? true : false));
}
if (in_array($contact['network'], array(NETWORK_DIASPORA, NETWORK_OSTATUS)) AND if (in_array($contact['network'], array(NETWORK_DIASPORA, NETWORK_OSTATUS)) AND
($contact['rel'] == CONTACT_IS_FOLLOWER)) { ($contact['rel'] == CONTACT_IS_FOLLOWER))
$follow = App::get_baseurl(true)."/follow?url=".urlencode($contact["url"]); $follow = App::get_baseurl(true)."/follow?url=".urlencode($contact["url"]);
}
// Load contactact related actions like hide, suggest, delete and others // Load contactact related actions like hide, suggest, delete and others
$contact_actions = contact_actions($contact); $contact_actions = contact_actions($contact);
$o .= replace_macros($tpl, array( $o .= replace_macros($tpl, array(
//'$header' => t('Contact Editor'), //'$header' => t('Contact Editor'),
'$header' => t("Contact"), '$header' => t("Contact"),
@ -697,21 +664,25 @@ function contacts_content(App $a) {
if(($a->argc == 2) && ($a->argv[1] === 'all')) { if(($a->argc == 2) && ($a->argv[1] === 'all')) {
$sql_extra = ''; $sql_extra = '';
$all = true; $all = true;
} elseif (($a->argc == 2) && ($a->argv[1] === 'blocked')) { }
elseif(($a->argc == 2) && ($a->argv[1] === 'blocked')) {
$sql_extra = " AND `blocked` = 1 "; $sql_extra = " AND `blocked` = 1 ";
$blocked = true; $blocked = true;
} elseif (($a->argc == 2) && ($a->argv[1] === 'hidden')) { }
elseif(($a->argc == 2) && ($a->argv[1] === 'hidden')) {
$sql_extra = " AND `hidden` = 1 "; $sql_extra = " AND `hidden` = 1 ";
$hidden = true; $hidden = true;
} elseif (($a->argc == 2) && ($a->argv[1] === 'ignored')) { }
elseif(($a->argc == 2) && ($a->argv[1] === 'ignored')) {
$sql_extra = " AND `readonly` = 1 "; $sql_extra = " AND `readonly` = 1 ";
$ignored = true; $ignored = true;
} elseif (($a->argc == 2) && ($a->argv[1] === 'archived')) { }
elseif(($a->argc == 2) && ($a->argv[1] === 'archived')) {
$sql_extra = " AND `archive` = 1 "; $sql_extra = " AND `archive` = 1 ";
$archived = true; $archived = true;
} else {
$sql_extra = " AND `blocked` = 0 ";
} }
else
$sql_extra = " AND `blocked` = 0 ";
$search = ((x($_GET,'search')) ? notags(trim($_GET['search'])) : ''); $search = ((x($_GET,'search')) ? notags(trim($_GET['search'])) : '');
$nets = ((x($_GET,'nets')) ? notags(trim($_GET['nets'])) : ''); $nets = ((x($_GET,'nets')) ? notags(trim($_GET['nets'])) : '');
@ -783,6 +754,8 @@ function contacts_content(App $a) {
$tab_tpl = get_markup_template('common_tabs.tpl'); $tab_tpl = get_markup_template('common_tabs.tpl');
$t = replace_macros($tab_tpl, array('$tabs'=>$tabs)); $t = replace_macros($tab_tpl, array('$tabs'=>$tabs));
$searching = false; $searching = false;
if($search) { if($search) {
$search_hdr = $search; $search_hdr = $search;
@ -791,12 +764,12 @@ function contacts_content(App $a) {
} }
$sql_extra .= (($searching) ? " AND (name REGEXP '$search_txt' OR url REGEXP '$search_txt' OR nick REGEXP '$search_txt') " : ""); $sql_extra .= (($searching) ? " AND (name REGEXP '$search_txt' OR url REGEXP '$search_txt' OR nick REGEXP '$search_txt') " : "");
if ($nets) { if($nets)
$sql_extra .= sprintf(" AND network = '%s' ", dbesc($nets)); $sql_extra .= sprintf(" AND network = '%s' ", dbesc($nets));
}
$sql_extra2 = ((($sort_type > 0) && ($sort_type <= CONTACT_IS_FRIEND)) ? sprintf(" AND `rel` = %d ",intval($sort_type)) : ''); $sql_extra2 = ((($sort_type > 0) && ($sort_type <= CONTACT_IS_FRIEND)) ? sprintf(" AND `rel` = %d ",intval($sort_type)) : '');
$r = q("SELECT COUNT(*) AS `total` FROM `contact` $r = q("SELECT COUNT(*) AS `total` FROM `contact`
WHERE `uid` = %d AND `self` = 0 AND `pending` = 0 $sql_extra $sql_extra2 ", WHERE `uid` = %d AND `self` = 0 AND `pending` = 0 $sql_extra $sql_extra2 ",
intval($_SESSION['uid'])); intval($_SESSION['uid']));
@ -884,25 +857,23 @@ function contacts_tab($a, $contact_id, $active_tab) {
// Show this tab only if there is visible friend list // Show this tab only if there is visible friend list
$x = count_all_friends(local_user(), $contact_id); $x = count_all_friends(local_user(), $contact_id);
if ($x) { if ($x)
$tabs[] = array('label'=>t('Contacts'), $tabs[] = array('label'=>t('Contacts'),
'url' => "allfriends/".$contact_id, 'url' => "allfriends/".$contact_id,
'sel' => (($active_tab == 3)?'active':''), 'sel' => (($active_tab == 3)?'active':''),
'title' => t('View all contacts'), 'title' => t('View all contacts'),
'id' => 'allfriends-tab', 'id' => 'allfriends-tab',
'accesskey' => 't'); 'accesskey' => 't');
}
// Show this tab only if there is visible common friend list // Show this tab only if there is visible common friend list
$common = count_common_friends(local_user(),$contact_id); $common = count_common_friends(local_user(),$contact_id);
if ($common) { if ($common)
$tabs[] = array('label'=>t('Common Friends'), $tabs[] = array('label'=>t('Common Friends'),
'url' => "common/loc/".local_user()."/".$contact_id, 'url' => "common/loc/".local_user()."/".$contact_id,
'sel' => (($active_tab == 4)?'active':''), 'sel' => (($active_tab == 4)?'active':''),
'title' => t('View all common friends'), 'title' => t('View all common friends'),
'id' => 'common-loc-tab', 'id' => 'common-loc-tab',
'accesskey' => 'd'); 'accesskey' => 'd');
}
$tabs[] = array('label' => t('Advanced'), $tabs[] = array('label' => t('Advanced'),
'url' => 'crepair/' . $contact_id, 'url' => 'crepair/' . $contact_id,
@ -920,13 +891,12 @@ function contacts_tab($a, $contact_id, $active_tab) {
function contact_posts($a, $contact_id) { function contact_posts($a, $contact_id) {
$r = q("SELECT `url` FROM `contact` WHERE `id` = %d", intval($contact_id)); $r = q("SELECT `url` FROM `contact` WHERE `id` = %d", intval($contact_id));
if (dbm::is_result($r)) { if ($r) {
$contact = $r[0]; $contact = $r[0];
$a->page['aside'] = ""; $a->page['aside'] = "";
profile_load($a, "", 0, get_contact_details_by_url($contact["url"])); profile_load($a, "", 0, get_contact_details_by_url($contact["url"]));
} else { } else
$profile = ""; $profile = "";
}
$tab_str = contacts_tab($a, $contact_id, 1); $tab_str = contacts_tab($a, $contact_id, 1);
@ -958,7 +928,8 @@ function _contact_detail_for_template($rr){
if(($rr['network'] === NETWORK_DFRN) && ($rr['rel'])) { if(($rr['network'] === NETWORK_DFRN) && ($rr['rel'])) {
$url = "redir/{$rr['id']}"; $url = "redir/{$rr['id']}";
$sparkle = ' class="sparkle" '; $sparkle = ' class="sparkle" ';
} else { }
else {
$url = $rr['url']; $url = $rr['url'];
$sparkle = ''; $sparkle = '';
} }

View file

@ -41,15 +41,17 @@ function content_content(App $a, $update = 0) {
if($a->argc > 1) { if($a->argc > 1) {
for($x = 1; $x < $a->argc; $x ++) { for($x = 1; $x < $a->argc; $x ++) {
if(is_a_date_arg($a->argv[$x])) { if(is_a_date_arg($a->argv[$x])) {
if ($datequery) { if($datequery)
$datequery2 = escape_tags($a->argv[$x]); $datequery2 = escape_tags($a->argv[$x]);
} else { else {
$datequery = escape_tags($a->argv[$x]); $datequery = escape_tags($a->argv[$x]);
$_GET['order'] = 'post'; $_GET['order'] = 'post';
} }
} elseif ($a->argv[$x] === 'new') { }
elseif($a->argv[$x] === 'new') {
$nouveau = true; $nouveau = true;
} elseif (intval($a->argv[$x])) { }
elseif(intval($a->argv[$x])) {
$group = intval($a->argv[$x]); $group = intval($a->argv[$x]);
$def_acl = array('allow_gid' => '<' . $group . '>'); $def_acl = array('allow_gid' => '<' . $group . '>');
} }
@ -840,9 +842,8 @@ function render_content(App $a, $items, $mode, $update, $preview = false) {
// process action responses - e.g. like/dislike/attend/agree/whatever // process action responses - e.g. like/dislike/attend/agree/whatever
$response_verbs = array('like'); $response_verbs = array('like');
if (feature_enabled($profile_owner,'dislike')) { if(feature_enabled($profile_owner,'dislike'))
$response_verbs[] = 'dislike'; $response_verbs[] = 'dislike';
}
if($item['object-type'] === ACTIVITY_OBJ_EVENT) { if($item['object-type'] === ACTIVITY_OBJ_EVENT) {
$response_verbs[] = 'attendyes'; $response_verbs[] = 'attendyes';
$response_verbs[] = 'attendno'; $response_verbs[] = 'attendno';
@ -862,9 +863,8 @@ function render_content(App $a, $items, $mode, $update, $preview = false) {
$indent = (($toplevelpost) ? '' : ' comment'); $indent = (($toplevelpost) ? '' : ' comment');
$shiny = ""; $shiny = "";
if (strcmp(datetime_convert('UTC','UTC',$item['created']),datetime_convert('UTC','UTC','now - 12 hours')) > 0) { if(strcmp(datetime_convert('UTC','UTC',$item['created']),datetime_convert('UTC','UTC','now - 12 hours')) > 0)
$shiny = 'shiny'; $shiny = 'shiny';
}
// //
localize_item($item); localize_item($item);
@ -873,9 +873,7 @@ function render_content(App $a, $items, $mode, $update, $preview = false) {
$tags=array(); $tags=array();
foreach(explode(',',$item['tag']) as $tag){ foreach(explode(',',$item['tag']) as $tag){
$tag = trim($tag); $tag = trim($tag);
if ($tag!="") { if ($tag!="") $tags[] = bbcode($tag);
$tags[] = bbcode($tag);
}
} }
// Build the HTML // Build the HTML
@ -890,7 +888,8 @@ function render_content(App $a, $items, $mode, $update, $preview = false) {
$title_e = template_escape($item['title']); $title_e = template_escape($item['title']);
$location_e = template_escape($location); $location_e = template_escape($location);
$owner_name_e = template_escape($owner_name); $owner_name_e = template_escape($owner_name);
} else { }
else {
$body_e = $body; $body_e = $body;
$text_e = strip_tags($body); $text_e = strip_tags($body);
$name_e = $profile_name; $name_e = $profile_name;

View file

@ -20,9 +20,8 @@ function crepair_init(App $a) {
} }
} }
if (! x($a->page,'aside')) { if(! x($a->page,'aside'))
$a->page['aside'] = ''; $a->page['aside'] = '';
}
if($contact_id) { if($contact_id) {
$a->data['contact'] = $r[0]; $a->data['contact'] = $r[0];
@ -36,9 +35,6 @@ function crepair_post(App $a) {
return; return;
} }
// Init $r here if $cid is not set
$r = false;
$cid = (($a->argc > 1) ? intval($a->argv[1]) : 0); $cid = (($a->argc > 1) ? intval($a->argv[1]) : 0);
if($cid) { if($cid) {
@ -89,11 +85,11 @@ function crepair_post(App $a) {
update_contact_avatar($photo,local_user(),$contact['id']); update_contact_avatar($photo,local_user(),$contact['id']);
} }
if ($r) { if($r)
info( t('Contact settings applied.') . EOL); info( t('Contact settings applied.') . EOL);
} else { else
notice( t('Contact update failed.') . EOL); notice( t('Contact update failed.') . EOL);
}
return; return;
} }

View file

@ -23,16 +23,16 @@ function delegate_content(App $a) {
$id = $a->argv[2]; $id = $a->argv[2];
$r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1", $r = q("select `nickname` from user where uid = %d limit 1",
intval($id) intval($id)
); );
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
$r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1", $r = q("select id from contact where uid = %d and nurl = '%s' limit 1",
intval(local_user()), intval(local_user()),
dbesc(normalise_link(App::get_baseurl() . '/profile/' . $r[0]['nickname'])) dbesc(normalise_link(App::get_baseurl() . '/profile/' . $r[0]['nickname']))
); );
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
q("INSERT INTO `manage` ( `uid`, `mid` ) VALUES ( %d , %d ) ", q("insert into manage ( uid, mid ) values ( %d , %d ) ",
intval($a->argv[2]), intval($a->argv[2]),
intval(local_user()) intval(local_user())
); );
@ -64,40 +64,34 @@ function delegate_content(App $a) {
dbesc($a->user['email']), dbesc($a->user['email']),
dbesc($a->user['password']) dbesc($a->user['password'])
); );
if (dbm::is_result($r)) { if (dbm::is_result($r))
$full_managers = $r; $full_managers = $r;
}
$delegates = array(); $delegates = array();
// find everybody that currently has delegated management to this account/page // find everybody that currently has delegated management to this account/page
$r = q("SELECT * FROM `user` WHERE `uid` IN ( SELECT `uid` FROM `manage` WHERE `mid` = %d ) ", $r = q("select * from user where uid in ( select uid from manage where mid = %d ) ",
intval(local_user()) intval(local_user())
); );
if (dbm::is_result($r)) { if (dbm::is_result($r))
$delegates = $r; $delegates = $r;
}
$uids = array(); $uids = array();
if (count($full_managers)) { if(count($full_managers))
foreach ($full_managers as $rr) { foreach($full_managers as $rr)
$uids[] = $rr['uid']; $uids[] = $rr['uid'];
}
}
if (count($delegates)) { if(count($delegates))
foreach ($delegates as $rr) { foreach($delegates as $rr)
$uids[] = $rr['uid']; $uids[] = $rr['uid'];
}
}
// find every contact who might be a candidate for delegation // find every contact who might be a candidate for delegation
$r = q("SELECT `nurl` FROM `contact` WHERE SUBSTRING_INDEX(`contact`.`nurl`,'/',3) = '%s' $r = q("select nurl from contact where substring_index(contact.nurl,'/',3) = '%s'
AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `network` = '%s' ", and contact.uid = %d and contact.self = 0 and network = '%s' ",
dbesc(normalise_link(App::get_baseurl())), dbesc(normalise_link(App::get_baseurl())),
intval(local_user()), intval(local_user()),
dbesc(NETWORK_DFRN) dbesc(NETWORK_DFRN)
@ -122,15 +116,12 @@ function delegate_content(App $a) {
// get user records for all potential page delegates who are not already delegates or managers // get user records for all potential page delegates who are not already delegates or managers
$r = q("SELECT `uid`, `username`, `nickname` FROM `user` WHERE `nickname` IN ( $nicks )"); $r = q("select `uid`, `username`, `nickname` from user where nickname in ( $nicks )");
if (dbm::is_result($r)) { if (dbm::is_result($r))
foreach ($r as $rr) { foreach($r as $rr)
if (! in_array($rr['uid'],$uids)) { if(! in_array($rr['uid'],$uids))
$potentials[] = $rr; $potentials[] = $rr;
}
}
}
require_once("mod/settings.php"); require_once("mod/settings.php");
settings_init($a); settings_init($a);

View file

@ -349,7 +349,8 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
dbesc(NETWORK_DFRN), dbesc(NETWORK_DFRN),
intval($contact_id) intval($contact_id)
); );
} else { }
else {
// $network !== NETWORK_DFRN // $network !== NETWORK_DFRN
@ -585,18 +586,17 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
dbesc($decrypted_source_url), dbesc($decrypted_source_url),
intval($local_uid) intval($local_uid)
); );
if (!dbm::is_result($ret)) { if(! count($ret)) {
if (strstr($decrypted_source_url,'http:')) { if(strstr($decrypted_source_url,'http:'))
$newurl = str_replace('http:','https:',$decrypted_source_url); $newurl = str_replace('http:','https:',$decrypted_source_url);
} else { else
$newurl = str_replace('https:','http:',$decrypted_source_url); $newurl = str_replace('https:','http:',$decrypted_source_url);
}
$ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1", $ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
dbesc($newurl), dbesc($newurl),
intval($local_uid) intval($local_uid)
); );
if (!dbm::is_result($ret)) { if(! count($ret)) {
// this is either a bogus confirmation (?) or we deleted the original introduction. // this is either a bogus confirmation (?) or we deleted the original introduction.
$message = t('Contact record was not found for you on our site.'); $message = t('Contact record was not found for you on our site.');
xml_status(3,$message); xml_status(3,$message);
@ -755,7 +755,7 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
intval($local_uid) intval($local_uid)
); );
if (dbm::is_result($self)) { if(count($self)) {
$arr = array(); $arr = array();
$arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $local_uid); $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $local_uid);
@ -792,9 +792,8 @@ function dfrn_confirm_post(App $a, $handsfree = null) {
$arr['deny_gid'] = $user[0]['deny_gid']; $arr['deny_gid'] = $user[0]['deny_gid'];
$i = item_store($arr); $i = item_store($arr);
if ($i) { if($i)
proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i); proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
}
} }
} }

View file

@ -143,9 +143,7 @@ function dfrn_notify_post(App $a) {
$rino = get_config('system','rino_encrypt'); $rino = get_config('system','rino_encrypt');
$rino = intval($rino); $rino = intval($rino);
// use RINO1 if mcrypt isn't installed and RINO2 was selected // use RINO1 if mcrypt isn't installed and RINO2 was selected
if ($rino == 2 and !function_exists('mcrypt_create_iv')) { if ($rino==2 and !function_exists('mcrypt_create_iv')) $rino=1;
$rino=1;
}
logger("Local rino version: ". $rino, LOGGER_DEBUG); logger("Local rino version: ". $rino, LOGGER_DEBUG);
@ -303,12 +301,13 @@ function dfrn_notify_content(App $a) {
if((($dplx) && (strlen($prv_key))) || ((strlen($prv_key)) && (!(strlen($pub_key))))) { if((($dplx) && (strlen($prv_key))) || ((strlen($prv_key)) && (!(strlen($pub_key))))) {
openssl_private_encrypt($hash,$challenge,$prv_key); openssl_private_encrypt($hash,$challenge,$prv_key);
openssl_private_encrypt($id_str,$encrypted_id,$prv_key); openssl_private_encrypt($id_str,$encrypted_id,$prv_key);
} elseif (strlen($pub_key)) { }
elseif(strlen($pub_key)) {
openssl_public_encrypt($hash,$challenge,$pub_key); openssl_public_encrypt($hash,$challenge,$pub_key);
openssl_public_encrypt($id_str,$encrypted_id,$pub_key); openssl_public_encrypt($id_str,$encrypted_id,$pub_key);
} else {
$status = 1;
} }
else
$status = 1;
$challenge = bin2hex($challenge); $challenge = bin2hex($challenge);
$encrypted_id = bin2hex($encrypted_id); $encrypted_id = bin2hex($encrypted_id);
@ -317,9 +316,7 @@ function dfrn_notify_content(App $a) {
$rino = get_config('system','rino_encrypt'); $rino = get_config('system','rino_encrypt');
$rino = intval($rino); $rino = intval($rino);
// use RINO1 if mcrypt isn't installed and RINO2 was selected // use RINO1 if mcrypt isn't installed and RINO2 was selected
if ($rino == 2 and !function_exists('mcrypt_create_iv')) { if ($rino==2 and !function_exists('mcrypt_create_iv')) $rino=1;
$rino=1;
}
logger("Local rino version: ". $rino, LOGGER_DEBUG); logger("Local rino version: ". $rino, LOGGER_DEBUG);
@ -329,7 +326,8 @@ function dfrn_notify_content(App $a) {
if((($r[0]['rel']) && ($r[0]['rel'] != CONTACT_IS_SHARING)) || ($r[0]['page-flags'] == PAGE_COMMUNITY)) { if((($r[0]['rel']) && ($r[0]['rel'] != CONTACT_IS_SHARING)) || ($r[0]['page-flags'] == PAGE_COMMUNITY)) {
$perm = 'rw'; $perm = 'rw';
} else { }
else {
$perm = 'r'; $perm = 'r';
} }

View file

@ -185,9 +185,8 @@ function directory_content(App $a) {
unset($profile); unset($profile);
unset($location); unset($location);
if (! $arr['entry']) { if(! $arr['entry'])
continue; continue;
}
$entries[] = $arr['entry']; $entries[] = $arr['entry'];

View file

@ -166,9 +166,8 @@ function dirfind_content(App $a, $prefix = "") {
$p = (($a->pager['page'] != 1) ? '&p=' . $a->pager['page'] : ''); $p = (($a->pager['page'] != 1) ? '&p=' . $a->pager['page'] : '');
if (strlen(get_config('system','directory'))) { if(strlen(get_config('system','directory')))
$x = fetch_url(get_server().'/lsearch?f=' . $p . '&search=' . urlencode($search)); $x = fetch_url(get_server().'/lsearch?f=' . $p . '&search=' . urlencode($search));
}
$j = json_decode($x); $j = json_decode($x);
} }

View file

@ -112,7 +112,7 @@ function events_post(App $a) {
$c = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1", $c = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
intval(local_user()) intval(local_user())
); );
if (dbm::is_result($c)) { if (count($c)) {
$self = $c[0]['id']; $self = $c[0]['id'];
} else { } else {
$self = 0; $self = 0;
@ -142,7 +142,7 @@ function events_post(App $a) {
$str_group_allow = $str_contact_deny = $str_group_deny = ''; $str_group_allow = $str_contact_deny = $str_group_deny = '';
} }
/// @TODO One-time array initialization, one large block
$datarray = array(); $datarray = array();
$datarray['guid'] = get_guid(32); $datarray['guid'] = get_guid(32);
$datarray['start'] = $start; $datarray['start'] = $start;
@ -407,9 +407,7 @@ function events_content(App $a) {
// Passed parameters overrides anything found in the DB // Passed parameters overrides anything found in the DB
if ($mode === 'edit' || $mode === 'new') { if ($mode === 'edit' || $mode === 'new') {
if (!x($orig_event)) { if (!x($orig_event)) {$orig_event = array();}
$orig_event = array();
}
// In case of an error the browser is redirected back here, with these parameters filled in with the previous values // In case of an error the browser is redirected back here, with these parameters filled in with the previous values
if (x($_REQUEST, 'nofinish')) {$orig_event['nofinish'] = $_REQUEST['nofinish'];} if (x($_REQUEST, 'nofinish')) {$orig_event['nofinish'] = $_REQUEST['nofinish'];}
if (x($_REQUEST, 'adjust')) {$orig_event['adjust'] = $_REQUEST['adjust'];} if (x($_REQUEST, 'adjust')) {$orig_event['adjust'] = $_REQUEST['adjust'];}

View file

@ -68,7 +68,8 @@ function fbrowser_content(App $a) {
if($a->theme['template_engine'] === 'internal') { if($a->theme['template_engine'] === 'internal') {
$filename_e = template_escape($rr['filename']); $filename_e = template_escape($rr['filename']);
} else { }
else {
$filename_e = $rr['filename']; $filename_e = $rr['filename'];
} }

View file

@ -95,9 +95,7 @@ function friendica_content(App $a) {
sort($sorted); sort($sorted);
foreach($sorted as $p) { foreach($sorted as $p) {
if(strlen($p)) { if(strlen($p)) {
if (strlen($s)) { if(strlen($s)) $s .= ', ';
$s .= ', ';
}
$s .= $p; $s .= $p;
} }
} }

View file

@ -80,9 +80,8 @@ function fsuggest_content(App $a) {
return; return;
} }
if ($a->argc != 2) { if($a->argc != 2)
return; return;
}
$contact_id = intval($a->argv[1]); $contact_id = intval($a->argv[1]);

View file

@ -80,12 +80,10 @@ function group_content(App $a) {
// Switch to text mode interface if we have more than 'n' contacts or group members // Switch to text mode interface if we have more than 'n' contacts or group members
$switchtotext = get_pconfig(local_user(),'system','groupedit_image_limit'); $switchtotext = get_pconfig(local_user(),'system','groupedit_image_limit');
if ($switchtotext === false) { if($switchtotext === false)
$switchtotext = get_config('system','groupedit_image_limit'); $switchtotext = get_config('system','groupedit_image_limit');
} if($switchtotext === false)
if ($switchtotext === false) {
$switchtotext = 400; $switchtotext = 400;
}
$tpl = get_markup_template('group_edit.tpl'); $tpl = get_markup_template('group_edit.tpl');
@ -101,6 +99,8 @@ function group_content(App $a) {
'$gid' => 'new', '$gid' => 'new',
'$form_security_token' => get_form_security_token("group_edit"), '$form_security_token' => get_form_security_token("group_edit"),
)); ));
} }
if (($a->argc == 3) && ($a->argv[1] === 'drop')) { if (($a->argc == 3) && ($a->argv[1] === 'drop')) {
@ -135,10 +135,9 @@ function group_content(App $a) {
intval($a->argv[2]), intval($a->argv[2]),
intval(local_user()) intval(local_user())
); );
if (dbm::is_result($r)) { if (dbm::is_result($r))
$change = intval($a->argv[2]); $change = intval($a->argv[2]);
} }
}
if (($a->argc > 1) && (intval($a->argv[1]))) { if (($a->argc > 1) && (intval($a->argv[1]))) {
@ -155,15 +154,15 @@ function group_content(App $a) {
$members = group_get_members($group['id']); $members = group_get_members($group['id']);
$preselected = array(); $preselected = array();
if(count($members)) { if(count($members)) {
foreach ($members as $member) { foreach($members as $member)
$preselected[] = $member['id']; $preselected[] = $member['id'];
} }
}
if($change) { if($change) {
if(in_array($change,$preselected)) { if(in_array($change,$preselected)) {
group_rmv_member(local_user(),$group['name'],$change); group_rmv_member(local_user(),$group['name'],$change);
} else { }
else {
group_add_member(local_user(),$group['name'],$change); group_add_member(local_user(),$group['name'],$change);
} }
@ -194,9 +193,8 @@ function group_content(App $a) {
} }
if (! isset($group)) { if(! isset($group))
return; return;
}
$groupeditor = array( $groupeditor = array(
'label_members' => t('Members'), 'label_members' => t('Members'),
@ -212,9 +210,9 @@ function group_content(App $a) {
if($member['url']) { if($member['url']) {
$member['click'] = 'groupChangeMember(' . $group['id'] . ',' . $member['id'] . ',\'' . $sec_token . '\'); return true;'; $member['click'] = 'groupChangeMember(' . $group['id'] . ',' . $member['id'] . ',\'' . $sec_token . '\'); return true;';
$groupeditor['members'][] = micropro($member,true,'mpgroup', $textmode); $groupeditor['members'][] = micropro($member,true,'mpgroup', $textmode);
} else {
group_rmv_member(local_user(),$group['name'],$member['id']);
} }
else
group_rmv_member(local_user(),$group['name'],$member['id']);
} }
$r = q("SELECT * FROM `contact` WHERE `uid` = %d AND NOT `blocked` AND NOT `pending` AND NOT `self` ORDER BY `name` ASC", $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND NOT `blocked` AND NOT `pending` AND NOT `self` ORDER BY `name` ASC",

View file

@ -31,9 +31,8 @@ function help_content(App $a) {
// looping through the argv keys bigger than 0 to build // looping through the argv keys bigger than 0 to build
// a path relative to /help // a path relative to /help
for($x = 1; $x < argc(); $x ++) { for($x = 1; $x < argc(); $x ++) {
if (strlen($path)) { if(strlen($path))
$path .= '/'; $path .= '/';
}
$path .= argv($x); $path .= argv($x);
} }
$title = basename($path); $title = basename($path);
@ -72,16 +71,10 @@ function help_content(App $a) {
if ($level!="r") { if ($level!="r") {
$level = intval($level); $level = intval($level);
if ($level<$lastlevel) { if ($level<$lastlevel) {
for ($k=$level;$k<$lastlevel; $k++) { for($k=$level;$k<$lastlevel; $k++) $toc.="</ul>";
$toc.="</ul>"; for($k=$level+1;$k<count($idnum);$k++) $idnum[$k]=0;
}
for ($k=$level+1;$k<count($idnum);$k++) {
$idnum[$k]=0;
}
}
if ($level>$lastlevel) {
$toc.="<ul>";
} }
if ($level>$lastlevel) $toc.="<ul>";
$idnum[$level]++; $idnum[$level]++;
$id = implode("_", array_slice($idnum,1,$level)); $id = implode("_", array_slice($idnum,1,$level));
$href = App::get_baseurl()."/help/{$filename}#{$id}"; $href = App::get_baseurl()."/help/{$filename}#{$id}";

View file

@ -37,11 +37,8 @@ function ignored_init(App $a) {
$return_path = ((x($_REQUEST,'return')) ? $_REQUEST['return'] : ''); $return_path = ((x($_REQUEST,'return')) ? $_REQUEST['return'] : '');
if ($return_path) { if ($return_path) {
$rand = '_=' . time(); $rand = '_=' . time();
if (strpos($return_path, '?')) { if(strpos($return_path, '?')) $rand = "&$rand";
$rand = "&$rand"; else $rand = "?$rand";
} else {
$rand = "?$rand";
}
goaway(App::get_baseurl() . "/" . $return_path . $rand); goaway(App::get_baseurl() . "/" . $return_path . $rand);
} }

0
mod/install.php Normal file → Executable file
View file

View file

@ -575,9 +575,8 @@ function item_post(App $a) {
if(count($tags)) { if(count($tags)) {
foreach($tags as $tag) { foreach($tags as $tag) {
if (strpos($tag,'#') === 0) { if(strpos($tag,'#') === 0)
continue; continue;
}
// If we already tagged 'Robert Johnson', don't try and tag 'Robert'. // If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
// Robert Johnson should be first in the $tags array // Robert Johnson should be first in the $tags array
@ -589,9 +588,8 @@ function item_post(App $a) {
break; break;
} }
} }
if ($fullnametagged) { if($fullnametagged)
continue; continue;
}
$success = handle_tag($a, $body, $inform, $str_tags, (local_user()) ? local_user() : $profile_uid , $tag, $network); $success = handle_tag($a, $body, $inform, $str_tags, (local_user()) ? local_user() : $profile_uid , $tag, $network);
if ($success['replaced']) { if ($success['replaced']) {
@ -724,9 +722,8 @@ function item_post(App $a) {
$datarray['last-child'] = 1; $datarray['last-child'] = 1;
$datarray['visible'] = 1; $datarray['visible'] = 1;
if ($orig_post) { if($orig_post)
$datarray['edit'] = true; $datarray['edit'] = true;
}
// Search for hashtags // Search for hashtags
item_body_set_hashtags($datarray); item_body_set_hashtags($datarray);
@ -1035,9 +1032,8 @@ function item_post(App $a) {
function item_post_return($baseurl, $api_source, $return_path) { function item_post_return($baseurl, $api_source, $return_path) {
// figure out how to return, depending on from whence we came // figure out how to return, depending on from whence we came
if ($api_source) { if($api_source)
return; return;
}
if ($return_path) { if ($return_path) {
goaway($return_path); goaway($return_path);
@ -1115,24 +1111,19 @@ function handle_tag($a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $netwo
$r = q("SELECT `alias`, `name` FROM `contact` WHERE `nurl` = '%s' AND `alias` != '' AND `uid` = 0", $r = q("SELECT `alias`, `name` FROM `contact` WHERE `nurl` = '%s' AND `alias` != '' AND `uid` = 0",
normalise_link($matches[1])); normalise_link($matches[1]));
if (!$r)
if (!dbm::is_result($r)) {
$r = q("SELECT `alias`, `name` FROM `gcontact` WHERE `nurl` = '%s' AND `alias` != ''", $r = q("SELECT `alias`, `name` FROM `gcontact` WHERE `nurl` = '%s' AND `alias` != ''",
normalise_link($matches[1])); normalise_link($matches[1]));
if ($r)
}
if (dbm::is_result($r)) {
$data = $r[0]; $data = $r[0];
} else { else
$data = probe_url($matches[1]); $data = probe_url($matches[1]);
}
if ($data["alias"] != "") { if ($data["alias"] != "") {
$newtag = '@[url='.$data["alias"].']'.$data["name"].'[/url]'; $newtag = '@[url='.$data["alias"].']'.$data["name"].'[/url]';
if(!stristr($str_tags,$newtag)) { if(!stristr($str_tags,$newtag)) {
if (strlen($str_tags)) { if(strlen($str_tags))
$str_tags .= ','; $str_tags .= ',';
}
$str_tags .= $newtag; $str_tags .= $newtag;
} }
} }
@ -1164,7 +1155,7 @@ function handle_tag($a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $netwo
); );
// Then check in the contact table for the url // Then check in the contact table for the url
if (!dbm::is_result($r)) { if (!$r)
$r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `contact` $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `contact`
WHERE `nurl` = '%s' AND `uid` = %d AND WHERE `nurl` = '%s' AND `uid` = %d AND
(`network` != '%s' OR (`notify` != '' AND `alias` != '')) (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
@ -1173,7 +1164,6 @@ function handle_tag($a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $netwo
intval($profile_uid), intval($profile_uid),
dbesc(NETWORK_OSTATUS) dbesc(NETWORK_OSTATUS)
); );
}
// Then check in the global contacts for the address // Then check in the global contacts for the address
if (!$r) if (!$r)
@ -1185,16 +1175,15 @@ function handle_tag($a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $netwo
); );
// Then check in the global contacts for the url // Then check in the global contacts for the url
if (!dbm::is_result($r)) { if (!$r)
$r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact` $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
WHERE `nurl` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != '')) WHERE `nurl` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
LIMIT 1", LIMIT 1",
dbesc(normalise_link($name)), dbesc(normalise_link($name)),
dbesc(NETWORK_OSTATUS) dbesc(NETWORK_OSTATUS)
); );
}
if (!dbm::is_result($r)) { if (!$r) {
$probed = probe_url($name); $probed = probe_url($name);
if ($result['network'] != NETWORK_PHANTOM) { if ($result['network'] != NETWORK_PHANTOM) {
update_gcontact($probed); update_gcontact($probed);
@ -1215,61 +1204,55 @@ function handle_tag($a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $netwo
} }
//select someone by attag or nick and the name passed in the current network //select someone by attag or nick and the name passed in the current network
if (!dbm::is_result($r) AND ($network != "")) { if(!$r AND ($network != ""))
$r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `network` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1", $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `network` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
dbesc($name), dbesc($name),
dbesc($name), dbesc($name),
dbesc($network), dbesc($network),
intval($profile_uid) intval($profile_uid)
); );
}
//select someone from this user's contacts by name in the current network //select someone from this user's contacts by name in the current network
if (!dbm::is_result($r) AND ($network != "")) { if (!$r AND ($network != ""))
$r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `network` = '%s' AND `uid` = %d LIMIT 1", $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `network` = '%s' AND `uid` = %d LIMIT 1",
dbesc($name), dbesc($name),
dbesc($network), dbesc($network),
intval($profile_uid) intval($profile_uid)
); );
}
//select someone by attag or nick and the name passed in //select someone by attag or nick and the name passed in
if (!dbm::is_result($r)) { if(!$r)
$r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1", $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
dbesc($name), dbesc($name),
dbesc($name), dbesc($name),
intval($profile_uid) intval($profile_uid)
); );
}
//select someone from this user's contacts by name //select someone from this user's contacts by name
if (!dbm::is_result($r)) { if(!$r)
$r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1", $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
dbesc($name), dbesc($name),
intval($profile_uid) intval($profile_uid)
); );
} }
}
if (dbm::is_result($r)) { if ($r) {
if (strlen($inform) AND (isset($r[0]["notify"]) OR isset($r[0]["id"]))) { if(strlen($inform) AND (isset($r[0]["notify"]) OR isset($r[0]["id"])))
$inform .= ','; $inform .= ',';
}
if (isset($r[0]["id"])) { if (isset($r[0]["id"]))
$inform .= 'cid:' . $r[0]["id"]; $inform .= 'cid:' . $r[0]["id"];
} elseif (isset($r[0]["notify"])) { elseif (isset($r[0]["notify"]))
$inform .= $r[0]["notify"]; $inform .= $r[0]["notify"];
}
$profile = $r[0]["url"]; $profile = $r[0]["url"];
$alias = $r[0]["alias"]; $alias = $r[0]["alias"];
$newname = $r[0]["nick"]; $newname = $r[0]["nick"];
if (($newname == "") OR (($r[0]["network"] != NETWORK_OSTATUS) AND ($r[0]["network"] != NETWORK_TWITTER) if (($newname == "") OR (($r[0]["network"] != NETWORK_OSTATUS) AND ($r[0]["network"] != NETWORK_TWITTER)
AND ($r[0]["network"] != NETWORK_STATUSNET) AND ($r[0]["network"] != NETWORK_APPNET))) { AND ($r[0]["network"] != NETWORK_STATUSNET) AND ($r[0]["network"] != NETWORK_APPNET)))
$newname = $r[0]["name"]; $newname = $r[0]["name"];
} }
}
//if there is an url for this persons profile //if there is an url for this persons profile
if (isset($profile) AND ($newname != "")) { if (isset($profile) AND ($newname != "")) {
@ -1281,9 +1264,8 @@ function handle_tag($a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $netwo
$body = str_replace('@'.$name, $newtag, $body); $body = str_replace('@'.$name, $newtag, $body);
//append tag to str_tags //append tag to str_tags
if(! stristr($str_tags,$newtag)) { if(! stristr($str_tags,$newtag)) {
if (strlen($str_tags)) { if(strlen($str_tags))
$str_tags .= ','; $str_tags .= ',';
}
$str_tags .= $newtag; $str_tags .= $newtag;
} }
@ -1293,9 +1275,8 @@ function handle_tag($a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $netwo
if(strlen($alias)) { if(strlen($alias)) {
$newtag = '@[url='.$alias.']'.$newname.'[/url]'; $newtag = '@[url='.$alias.']'.$newname.'[/url]';
if(! stristr($str_tags,$newtag)) { if(! stristr($str_tags,$newtag)) {
if (strlen($str_tags)) { if(strlen($str_tags))
$str_tags .= ','; $str_tags .= ',';
}
$str_tags .= $newtag; $str_tags .= $newtag;
} }
} }

14
mod/like.php Normal file → Executable file
View file

@ -13,16 +13,13 @@ function like_content(App $a) {
$verb = notags(trim($_GET['verb'])); $verb = notags(trim($_GET['verb']));
if (! $verb) { if(! $verb)
$verb = 'like'; $verb = 'like';
}
$item_id = (($a->argc > 1) ? notags(trim($a->argv[1])) : 0); $item_id = (($a->argc > 1) ? notags(trim($a->argv[1])) : 0);
$r = do_like($item_id, $verb); $r = do_like($item_id, $verb);
if (!$r) { if (!$r) return;
return;
}
// See if we've been passed a return path to redirect to // See if we've been passed a return path to redirect to
$return_path = ((x($_REQUEST,'return')) ? $_REQUEST['return'] : ''); $return_path = ((x($_REQUEST,'return')) ? $_REQUEST['return'] : '');
@ -40,11 +37,8 @@ function like_content_return($baseurl, $return_path) {
if($return_path) { if($return_path) {
$rand = '_=' . time(); $rand = '_=' . time();
if (strpos($return_path, '?')) { if(strpos($return_path, '?')) $rand = "&$rand";
$rand = "&$rand"; else $rand = "?$rand";
} else {
$rand = "?$rand";
}
goaway($baseurl . "/" . $return_path . $rand); goaway($baseurl . "/" . $return_path . $rand);
} }

View file

@ -6,23 +6,20 @@ require_once('include/datetime.php');
function localtime_post(App $a) { function localtime_post(App $a) {
$t = $_REQUEST['time']; $t = $_REQUEST['time'];
if (! $t) { if(! $t)
$t = 'now'; $t = 'now';
}
$bd_format = t('l F d, Y \@ g:i A') ; // Friday January 18, 2011 @ 8 AM $bd_format = t('l F d, Y \@ g:i A') ; // Friday January 18, 2011 @ 8 AM
if ($_POST['timezone']) { if($_POST['timezone'])
$a->data['mod-localtime'] = datetime_convert('UTC',$_POST['timezone'],$t,$bd_format); $a->data['mod-localtime'] = datetime_convert('UTC',$_POST['timezone'],$t,$bd_format);
}
} }
function localtime_content(App $a) { function localtime_content(App $a) {
$t = $_REQUEST['time']; $t = $_REQUEST['time'];
if (! $t) { if(! $t)
$t = 'now'; $t = 'now';
}
$o .= '<h3>' . t('Time Conversion') . '</h3>'; $o .= '<h3>' . t('Time Conversion') . '</h3>';
@ -32,13 +29,11 @@ function localtime_content(App $a) {
$o .= '<p>' . sprintf( t('UTC time: %s'), $t) . '</p>'; $o .= '<p>' . sprintf( t('UTC time: %s'), $t) . '</p>';
if ($_REQUEST['timezone']) { if($_REQUEST['timezone'])
$o .= '<p>' . sprintf( t('Current timezone: %s'), $_REQUEST['timezone']) . '</p>'; $o .= '<p>' . sprintf( t('Current timezone: %s'), $_REQUEST['timezone']) . '</p>';
}
if (x($a->data,'mod-localtime')) { if(x($a->data,'mod-localtime'))
$o .= '<p>' . sprintf( t('Converted localtime: %s'),$a->data['mod-localtime']) . '</p>'; $o .= '<p>' . sprintf( t('Converted localtime: %s'),$a->data['mod-localtime']) . '</p>';
}
$o .= '<form action ="' . App::get_baseurl() . '/localtime?f=&time=' . $t . '" method="post" >'; $o .= '<form action ="' . App::get_baseurl() . '/localtime?f=&time=' . $t . '" method="post" >';

View file

@ -53,21 +53,17 @@ function lockview_content(App $a) {
$r = q("SELECT `name` FROM `group` WHERE `id` IN ( %s )", $r = q("SELECT `name` FROM `group` WHERE `id` IN ( %s )",
dbesc(implode(', ', $allowed_groups)) dbesc(implode(', ', $allowed_groups))
); );
if (dbm::is_result($r)) { if (dbm::is_result($r))
foreach ($r as $rr) { foreach($r as $rr)
$l[] = '<b>' . $rr['name'] . '</b>'; $l[] = '<b>' . $rr['name'] . '</b>';
} }
}
}
if(count($allowed_users)) { if(count($allowed_users)) {
$r = q("SELECT `name` FROM `contact` WHERE `id` IN ( %s )", $r = q("SELECT `name` FROM `contact` WHERE `id` IN ( %s )",
dbesc(implode(', ',$allowed_users)) dbesc(implode(', ',$allowed_users))
); );
if (dbm::is_result($r)) { if (dbm::is_result($r))
foreach ($r as $rr) { foreach($r as $rr)
$l[] = $rr['name']; $l[] = $rr['name'];
}
}
} }
@ -75,21 +71,17 @@ function lockview_content(App $a) {
$r = q("SELECT `name` FROM `group` WHERE `id` IN ( %s )", $r = q("SELECT `name` FROM `group` WHERE `id` IN ( %s )",
dbesc(implode(', ', $deny_groups)) dbesc(implode(', ', $deny_groups))
); );
if (dbm::is_result($r)) { if (dbm::is_result($r))
foreach ($r as $rr) { foreach($r as $rr)
$l[] = '<b><strike>' . $rr['name'] . '</strike></b>'; $l[] = '<b><strike>' . $rr['name'] . '</strike></b>';
} }
}
}
if(count($deny_users)) { if(count($deny_users)) {
$r = q("SELECT `name` FROM `contact` WHERE `id` IN ( %s )", $r = q("SELECT `name` FROM `contact` WHERE `id` IN ( %s )",
dbesc(implode(', ',$deny_users)) dbesc(implode(', ',$deny_users))
); );
if (dbm::is_result($r)) { if (dbm::is_result($r))
foreach ($r as $rr) { foreach($r as $rr)
$l[] = '<strike>' . $rr['name'] . '</strike>'; $l[] = '<strike>' . $rr['name'] . '</strike>';
}
}
} }

View file

@ -1,16 +1,13 @@
<?php <?php
function login_content(App $a) { function login_content(App $a) {
if (x($_SESSION,'theme')) { if(x($_SESSION,'theme'))
unset($_SESSION['theme']); unset($_SESSION['theme']);
} if(x($_SESSION,'mobile-theme'))
if (x($_SESSION,'mobile-theme')) {
unset($_SESSION['mobile-theme']); unset($_SESSION['mobile-theme']);
}
if (local_user()) { if(local_user())
goaway(z_root()); goaway(z_root());
}
return login(($a->config['register_policy'] == REGISTER_CLOSED) ? false : true); return login(($a->config['register_policy'] == REGISTER_CLOSED) ? false : true);
} }

View file

@ -79,6 +79,7 @@ function lostpass_post(App $a) {
function lostpass_content(App $a) { function lostpass_content(App $a) {
if(x($_GET,'verify')) { if(x($_GET,'verify')) {
$verify = $_GET['verify']; $verify = $_GET['verify'];
$hash = hash('whirlpool', $verify); $hash = hash('whirlpool', $verify);

View file

@ -13,7 +13,7 @@ function manage_post(App $a) {
$orig_record = $a->user; $orig_record = $a->user;
if((x($_SESSION,'submanage')) && intval($_SESSION['submanage'])) { if((x($_SESSION,'submanage')) && intval($_SESSION['submanage'])) {
$r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", $r = q("select * from user where uid = %d limit 1",
intval($_SESSION['submanage']) intval($_SESSION['submanage'])
); );
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
@ -22,16 +22,15 @@ function manage_post(App $a) {
} }
} }
$r = q("SELECT * FROM `manage` WHERE `uid` = %d", $r = q("select * from manage where uid = %d",
intval($uid) intval($uid)
); );
$submanage = $r; $submanage = $r;
$identity = ((x($_POST['identity'])) ? intval($_POST['identity']) : 0); $identity = ((x($_POST['identity'])) ? intval($_POST['identity']) : 0);
if (! $identity) { if(! $identity)
return; return;
}
$limited_id = 0; $limited_id = 0;
$original_id = $uid; $original_id = $uid;
@ -49,7 +48,8 @@ function manage_post(App $a) {
$r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
intval($limited_id) intval($limited_id)
); );
} else { }
else {
$r = q("SELECT * FROM `user` WHERE `uid` = %d AND `email` = '%s' AND `password` = '%s' LIMIT 1", $r = q("SELECT * FROM `user` WHERE `uid` = %d AND `email` = '%s' AND `password` = '%s' LIMIT 1",
intval($identity), intval($identity),
dbesc($orig_record['email']), dbesc($orig_record['email']),
@ -70,22 +70,18 @@ function manage_post(App $a) {
unset($_SESSION['mobile-theme']); unset($_SESSION['mobile-theme']);
unset($_SESSION['page_flags']); unset($_SESSION['page_flags']);
unset($_SESSION['return_url']); unset($_SESSION['return_url']);
if (x($_SESSION,'submanage')) { if(x($_SESSION,'submanage'))
unset($_SESSION['submanage']); unset($_SESSION['submanage']);
} if(x($_SESSION,'sysmsg'))
if (x($_SESSION,'sysmsg')) {
unset($_SESSION['sysmsg']); unset($_SESSION['sysmsg']);
} if(x($_SESSION,'sysmsg_info'))
if (x($_SESSION,'sysmsg_info')) {
unset($_SESSION['sysmsg_info']); unset($_SESSION['sysmsg_info']);
}
require_once('include/security.php'); require_once('include/security.php');
authenticate_success($r[0],true,true); authenticate_success($r[0],true,true);
if ($limited_id) { if($limited_id)
$_SESSION['submanage'] = $original_id; $_SESSION['submanage'] = $original_id;
}
$ret = array(); $ret = array();
call_hooks('home_init',$ret); call_hooks('home_init',$ret);

View file

@ -78,9 +78,9 @@ function message_post(App $a) {
if($norecip) { if($norecip) {
$a->argc = 2; $a->argc = 2;
$a->argv[1] = 'new'; $a->argv[1] = 'new';
} else {
goaway($_SESSION['return_url']);
} }
else
goaway($_SESSION['return_url']);
} }
@ -109,15 +109,14 @@ function item_extract_images($body) {
$new_body = $new_body . substr($orig_body, 0, $img_start) . '[!#saved_image' . $cnt . '#!]'; $new_body = $new_body . substr($orig_body, 0, $img_start) . '[!#saved_image' . $cnt . '#!]';
$cnt++; $cnt++;
} else {
$new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
} }
else
$new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
$orig_body = substr($orig_body, $img_end + strlen('[/img]')); $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
if ($orig_body === false) {// in case the body ends on a closing image tag if($orig_body === false) // in case the body ends on a closing image tag
$orig_body = ''; $orig_body = '';
}
$img_start = strpos($orig_body, '[img'); $img_start = strpos($orig_body, '[img');
$img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false); $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
@ -252,10 +251,9 @@ function message_content(App $a) {
// ); // );
//} //}
if ($r) { if($r)
info( t('Conversation removed.') . EOL ); info( t('Conversation removed.') . EOL );
} }
}
//goaway(App::get_baseurl(true) . '/message' ); //goaway(App::get_baseurl(true) . '/message' );
goaway($_SESSION['return_url']); goaway($_SESSION['return_url']);
} }
@ -432,9 +430,8 @@ function message_content(App $a) {
$unknown = false; $unknown = false;
foreach($messages as $message) { foreach($messages as $message) {
if ($message['unknown']) { if($message['unknown'])
$unknown = true; $unknown = true;
}
if($message['from-url'] == $myprofile) { if($message['from-url'] == $myprofile) {
$from_url = $myprofile; $from_url = $myprofile;
$sparkle = ''; $sparkle = '';
@ -448,9 +445,8 @@ function message_content(App $a) {
$extracted = item_extract_images($message['body']); $extracted = item_extract_images($message['body']);
if ($extracted['images']) { if($extracted['images'])
$message['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $message['contact-id']); $message['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $message['contact-id']);
}
if($a->theme['template_engine'] === 'internal') { if($a->theme['template_engine'] === 'internal') {
$from_name_e = template_escape($message['from-name']); $from_name_e = template_escape($message['from-name']);
@ -465,11 +461,10 @@ function message_content(App $a) {
} }
$contact = get_contact_details_by_url($message['from-url']); $contact = get_contact_details_by_url($message['from-url']);
if (isset($contact["thumb"])) { if (isset($contact["thumb"]))
$from_photo = $contact["thumb"]; $from_photo = $contact["thumb"];
} else { else
$from_photo = $message['from-photo']; $from_photo = $message['from-photo'];
}
$mails[] = array( $mails[] = array(
'id' => $message['id'], 'id' => $message['id'],
@ -496,7 +491,8 @@ function message_content(App $a) {
if($a->theme['template_engine'] === 'internal') { if($a->theme['template_engine'] === 'internal') {
$subjtxt_e = template_escape($message['title']); $subjtxt_e = template_escape($message['title']);
} else { }
else {
$subjtxt_e = $message['title']; $subjtxt_e = $message['title'];
} }

View file

@ -123,11 +123,9 @@ function mood_content(App $a) {
$verbs = get_mood_verbs(); $verbs = get_mood_verbs();
$shortlist = array(); $shortlist = array();
foreach ($verbs as $k => $v) { foreach($verbs as $k => $v)
if ($v !== 'NOTRANSLATION') { if($v !== 'NOTRANSLATION')
$shortlist[] = array($k,$v); $shortlist[] = array($k,$v);
}
}
$tpl = get_markup_template('mood_content.tpl'); $tpl = get_markup_template('mood_content.tpl');

View file

@ -329,15 +329,17 @@ function network_content(App $a, $update = 0) {
if($a->argc > 1) { if($a->argc > 1) {
for($x = 1; $x < $a->argc; $x ++) { for($x = 1; $x < $a->argc; $x ++) {
if(is_a_date_arg($a->argv[$x])) { if(is_a_date_arg($a->argv[$x])) {
if ($datequery) { if($datequery)
$datequery2 = escape_tags($a->argv[$x]); $datequery2 = escape_tags($a->argv[$x]);
} else { else {
$datequery = escape_tags($a->argv[$x]); $datequery = escape_tags($a->argv[$x]);
$_GET['order'] = 'post'; $_GET['order'] = 'post';
} }
} elseif ($a->argv[$x] === 'new') { }
elseif($a->argv[$x] === 'new') {
$nouveau = true; $nouveau = true;
} elseif (intval($a->argv[$x])) { }
elseif(intval($a->argv[$x])) {
$group = intval($a->argv[$x]); $group = intval($a->argv[$x]);
$def_acl = array('allow_gid' => '<' . $group . '>'); $def_acl = array('allow_gid' => '<' . $group . '>');
} }

View file

@ -47,9 +47,8 @@ function newmember_content(App $a) {
$mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1); $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
if (! $mail_disabled) { if(! $mail_disabled)
$o .= '<li>' . '<a target="newmember" href="settings/connectors">' . t('Importing Emails') . '</a><br />' . t('Enter your email access information on your Connector Settings page if you wish to import and interact with friends or mailing lists from your email INBOX') . '</li>' . EOL; $o .= '<li>' . '<a target="newmember" href="settings/connectors">' . t('Importing Emails') . '</a><br />' . t('Enter your email access information on your Connector Settings page if you wish to import and interact with friends or mailing lists from your email INBOX') . '</li>' . EOL;
}
$o .= '<li>' . '<a target="newmember" href="contacts">' . t('Go to Your Contacts Page') . '</a><br />' . t('Your Contacts page is your gateway to managing friendships and connecting with friends on other networks. Typically you enter their address or site URL in the <em>Add New Contact</em> dialog.') . '</li>' . EOL; $o .= '<li>' . '<a target="newmember" href="contacts">' . t('Go to Your Contacts Page') . '</a><br />' . t('Your Contacts page is your gateway to managing friendships and connecting with friends on other networks. Typically you enter their address or site URL in the <em>Add New Contact</em> dialog.') . '</li>' . EOL;

View file

@ -2,11 +2,10 @@
function noscrape_init(App $a) { function noscrape_init(App $a) {
if ($a->argc > 1) { if($a->argc > 1)
$which = $a->argv[1]; $which = $a->argv[1];
} else { else
killme(); killme();
}
$profile = 0; $profile = 0;
if((local_user()) && ($a->argc > 2) && ($a->argv[2] === 'view')) { if((local_user()) && ($a->argc > 2) && ($a->argv[2] === 'view')) {

View file

@ -104,9 +104,8 @@ function notes_content(App $a, $update = false) {
$parents_str = ''; $parents_str = '';
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
foreach ($r as $rr) { foreach($r as $rr)
$parents_arr[] = $rr['item_id']; $parents_arr[] = $rr['item_id'];
}
$parents_str = implode(', ', $parents_arr); $parents_str = implode(', ', $parents_arr);
$r = q("SELECT %s FROM `item` %s $r = q("SELECT %s FROM `item` %s

View file

@ -309,10 +309,9 @@ function notifications_content(App $a) {
} }
// Output if there aren't any notifications available // Output if there aren't any notifications available
if ($notifs['total'] == 0) { if($notifs['total'] == 0)
$notif_nocontent = sprintf( t('No more %s notifications.'), $notifs['ident']); $notif_nocontent = sprintf( t('No more %s notifications.'), $notifs['ident']);
} }
}
$o .= replace_macros($notif_tpl, array( $o .= replace_macros($notif_tpl, array(
'$notif_header' => $notif_header, '$notif_header' => $notif_header,

View file

@ -84,7 +84,8 @@ function photo_init(App $a) {
$data = file_get_contents($default); $data = file_get_contents($default);
$mimetype = 'image/jpeg'; $mimetype = 'image/jpeg';
} }
} else { }
else {
/** /**
* Other photos * Other photos

View file

@ -1345,11 +1345,10 @@ function photos_content(App $a) {
// The query leads to a really intense used index. // The query leads to a really intense used index.
// By now we hide it if someone wants to. // By now we hide it if someone wants to.
if (!Config::get('system', 'no_count', false)) { if (!Config::get('system', 'no_count', false)) {
if ($_GET['order'] === 'posted') { if ($_GET['order'] === 'posted')
$order = 'ASC'; $order = 'ASC';
} else { else
$order = 'DESC'; $order = 'DESC';
}
$prvnxt = qu("SELECT `resource-id` FROM `photo` WHERE `album` = '%s' AND `uid` = %d AND `scale` = 0 $prvnxt = qu("SELECT `resource-id` FROM `photo` WHERE `album` = '%s' AND `uid` = %d AND `scale` = 0
$sql_extra ORDER BY `created` $order ", $sql_extra ORDER BY `created` $order ",
@ -1357,17 +1356,15 @@ function photos_content(App $a) {
intval($owner_uid) intval($owner_uid)
); );
if (dbm::is_result($prvnxt)) { if (count($prvnxt)) {
for($z = 0; $z < count($prvnxt); $z++) { for($z = 0; $z < count($prvnxt); $z++) {
if ($prvnxt[$z]['resource-id'] == $ph[0]['resource-id']) { if ($prvnxt[$z]['resource-id'] == $ph[0]['resource-id']) {
$prv = $z - 1; $prv = $z - 1;
$nxt = $z + 1; $nxt = $z + 1;
if ($prv < 0) { if ($prv < 0)
$prv = count($prvnxt) - 1; $prv = count($prvnxt) - 1;
} if ($nxt >= count($prvnxt))
if ($nxt >= count($prvnxt)) {
$nxt = 0; $nxt = 0;
}
break; break;
} }
} }
@ -1377,9 +1374,8 @@ function photos_content(App $a) {
} }
} }
if (count($ph) == 1) { if (count($ph) == 1)
$hires = $lores = $ph[0]; $hires = $lores = $ph[0];
}
if (count($ph) > 1) { if (count($ph) > 1) {
if ($ph[1]['scale'] == 2) { if ($ph[1]['scale'] == 2) {
// original is 640 or less, we can display it directly // original is 640 or less, we can display it directly

View file

@ -157,12 +157,12 @@ function poco_init(App $a) {
if (x($_GET,'updatedSince') AND !$global) { if (x($_GET,'updatedSince') AND !$global) {
$ret['updatedSince'] = false; $ret['updatedSince'] = false;
} }
$ret['startIndex'] = (int) $startIndex; $ret['startIndex'] = (int) $startIndex;
$ret['itemsPerPage'] = (int) $itemsPerPage; $ret['itemsPerPage'] = (int) $itemsPerPage;
$ret['totalResults'] = (int) $totalResults; $ret['totalResults'] = (int) $totalResults;
$ret['entry'] = array(); $ret['entry'] = array();
$fields_ret = array( $fields_ret = array(
'id' => false, 'id' => false,
'displayName' => false, 'displayName' => false,
@ -207,17 +207,14 @@ function poco_init(App $a) {
if (($rr['about'] == "") AND isset($rr['pabout'])) { if (($rr['about'] == "") AND isset($rr['pabout'])) {
$rr['about'] = $rr['pabout']; $rr['about'] = $rr['pabout'];
} }
if ($rr['location'] == "") { if ($rr['location'] == "") {
if (isset($rr['plocation'])) { if (isset($rr['plocation'])) {
$rr['location'] = $rr['plocation']; $rr['location'] = $rr['plocation'];
} }
if (isset($rr['pregion']) AND ($rr['pregion'] != "")) { if (isset($rr['pregion']) AND ($rr['pregion'] != "")) {
if ($rr['location'] != "") { if ($rr['location'] != "") {
$rr['location'] .= ", "; $rr['location'] .= ", ";
} }
$rr['location'] .= $rr['pregion']; $rr['location'] .= $rr['pregion'];
} }
@ -295,7 +292,6 @@ function poco_init(App $a) {
} else { } else {
$entry['updated'] = $rr['updated']; $entry['updated'] = $rr['updated'];
} }
$entry['updated'] = date("c", strtotime($entry['updated'])); $entry['updated'] = date("c", strtotime($entry['updated']));
} }
if ($fields_ret['photos']) { if ($fields_ret['photos']) {
@ -349,7 +345,6 @@ function poco_init(App $a) {
if ($fields_ret['contactType']) { if ($fields_ret['contactType']) {
$entry['contactType'] = intval($rr['contact-type']); $entry['contactType'] = intval($rr['contact-type']);
} }
$ret['entry'][] = $entry; $ret['entry'][] = $entry;
} }
} else { } else {
@ -358,7 +353,6 @@ function poco_init(App $a) {
} else { } else {
http_status_exit(500); http_status_exit(500);
} }
logger("End of poco", LOGGER_DEBUG); logger("End of poco", LOGGER_DEBUG);
if ($format === 'xml') { if ($format === 'xml') {
@ -373,5 +367,4 @@ function poco_init(App $a) {
} else { } else {
http_status_exit(500); http_status_exit(500);
} }
} }

View file

@ -185,11 +185,9 @@ function poke_content(App $a) {
$verbs = get_poke_verbs(); $verbs = get_poke_verbs();
$shortlist = array(); $shortlist = array();
foreach ($verbs as $k => $v) { foreach($verbs as $k => $v)
if ($v[1] !== 'NOTRANSLATION') { if($v[1] !== 'NOTRANSLATION')
$shortlist[] = array($k,$v[1]); $shortlist[] = array($k,$v[1]);
}
}
$tpl = get_markup_template('poke_content.tpl'); $tpl = get_markup_template('poke_content.tpl');

View file

@ -16,7 +16,8 @@ function post_post(App $a) {
if ($a->argc == 1) { if ($a->argc == 1) {
$bulk_delivery = true; $bulk_delivery = true;
} else { }
else {
$nickname = $a->argv[2]; $nickname = $a->argv[2];
$r = q("SELECT * FROM `user` WHERE `nickname` = '%s' $r = q("SELECT * FROM `user` WHERE `nickname` = '%s'
AND `account_expired` = 0 AND `account_removed` = 0 LIMIT 1", AND `account_expired` = 0 AND `account_removed` = 0 LIMIT 1",
@ -33,17 +34,15 @@ function post_post(App $a) {
logger('mod-post: new zot: ' . $xml, LOGGER_DATA); logger('mod-post: new zot: ' . $xml, LOGGER_DATA);
if (! $xml) { if(! $xml)
http_status_exit(500); http_status_exit(500);
}
$msg = zot_decode($importer,$xml); $msg = zot_decode($importer,$xml);
logger('mod-post: decoded msg: ' . print_r($msg,true), LOGGER_DATA); logger('mod-post: decoded msg: ' . print_r($msg,true), LOGGER_DATA);
if (! is_array($msg)) { if(! is_array($msg))
http_status_exit(500); http_status_exit(500);
}
$ret = 0; $ret = 0;
$ret = zot_incoming($bulk_delivery, $importer,$msg); $ret = zot_incoming($bulk_delivery, $importer,$msg);

View file

@ -10,7 +10,8 @@ function pretheme_init(App $a) {
$desc = $info['description']; $desc = $info['description'];
$version = $info['version']; $version = $info['version'];
$credits = $info['credits']; $credits = $info['credits'];
} else { }
else {
$desc = ''; $desc = '';
$version = ''; $version = '';
$credits = ''; $credits = '';

View file

@ -6,17 +6,17 @@ require_once('include/redir.php');
function profile_init(App $a) { function profile_init(App $a) {
if (! x($a->page,'aside')) { if(! x($a->page,'aside'))
$a->page['aside'] = ''; $a->page['aside'] = '';
}
if ($a->argc > 1) { if($a->argc > 1)
$which = htmlspecialchars($a->argv[1]); $which = htmlspecialchars($a->argv[1]);
}else { else {
$r = q("select nickname from user where blocked = 0 and account_expired = 0 and account_removed = 0 and verified = 1 order by rand() limit 1"); $r = q("select nickname from user where blocked = 0 and account_expired = 0 and account_removed = 0 and verified = 1 order by rand() limit 1");
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
goaway(App::get_baseurl() . '/profile/' . $r[0]['nickname']); goaway(App::get_baseurl() . '/profile/' . $r[0]['nickname']);
} else { }
else {
logger('profile error: mod_profile ' . $a->query_string, LOGGER_DEBUG); logger('profile error: mod_profile ' . $a->query_string, LOGGER_DEBUG);
notice( t('Requested profile is not available.') . EOL ); notice( t('Requested profile is not available.') . EOL );
$a->error = 404; $a->error = 404;
@ -28,7 +28,8 @@ function profile_init(App $a) {
if((local_user()) && ($a->argc > 2) && ($a->argv[2] === 'view')) { if((local_user()) && ($a->argc > 2) && ($a->argv[2] === 'view')) {
$which = $a->user['nickname']; $which = $a->user['nickname'];
$profile = htmlspecialchars($a->argv[1]); $profile = htmlspecialchars($a->argv[1]);
} else { }
else {
auto_redir($a, $which); auto_redir($a, $which);
} }
@ -288,9 +289,8 @@ function profile_content(App $a, $update = 0) {
$parents_str = ''; $parents_str = '';
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
foreach ($r as $rr) { foreach($r as $rr)
$parents_arr[] = $rr['item_id']; $parents_arr[] = $rr['item_id'];
}
$parents_str = implode(', ', $parents_arr); $parents_str = implode(', ', $parents_arr);
$items = q(item_query()." AND `item`.`uid` = %d $items = q(item_query()." AND `item`.`uid` = %d

View file

@ -34,9 +34,8 @@ function profiles_init(App $a) {
intval($a->argv[2]), intval($a->argv[2]),
intval(local_user()) intval(local_user())
); );
if ($r) { if($r)
info(t('Profile deleted.').EOL); info(t('Profile deleted.').EOL);
}
goaway('profiles'); goaway('profiles');
return; // NOTREACHED return; // NOTREACHED
@ -248,13 +247,11 @@ function profiles_post(App $a) {
$withchanged = true; $withchanged = true;
$prf = ''; $prf = '';
$lookup = $with; $lookup = $with;
if (strpos($lookup,'@') === 0) { if(strpos($lookup,'@') === 0)
$lookup = substr($lookup,1); $lookup = substr($lookup,1);
}
$lookup = str_replace('_',' ', $lookup); $lookup = str_replace('_',' ', $lookup);
if(strpos($lookup,'@') || (strpos($lookup,'http://'))) { if(strpos($lookup,'@') || (strpos($lookup,'http://'))) {
$newname = $lookup; $newname = $lookup;
/// @TODO Maybe kill those error/debugging-surpressing @ characters
$links = @Probe::lrdd($lookup); $links = @Probe::lrdd($lookup);
if(count($links)) { if(count($links)) {
foreach($links as $link) { foreach($links as $link) {
@ -263,14 +260,16 @@ function profiles_post(App $a) {
} }
} }
} }
} else { }
else {
$newname = $lookup; $newname = $lookup;
/* if(strstr($lookup,' ')) { /* if(strstr($lookup,' ')) {
$r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1", $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
dbesc($newname), dbesc($newname),
intval(local_user()) intval(local_user())
); );
} else { }
else {
$r = q("SELECT * FROM `contact` WHERE `nick` = '%s' AND `uid` = %d LIMIT 1", $r = q("SELECT * FROM `contact` WHERE `nick` = '%s' AND `uid` = %d LIMIT 1",
dbesc($lookup), dbesc($lookup),
intval(local_user()) intval(local_user())
@ -474,9 +473,8 @@ function profiles_post(App $a) {
intval(local_user()) intval(local_user())
); );
if ($r) { if($r)
info( t('Profile updated.') . EOL); info( t('Profile updated.') . EOL);
}
if($namechanged && $is_default) { if($namechanged && $is_default) {

View file

@ -142,9 +142,8 @@ function pubsub_post(App $a) {
// we have no way to match Diaspora guid's with atom post id's and could get duplicates. // we have no way to match Diaspora guid's with atom post id's and could get duplicates.
// we'll assume that direct delivery is robust (and this is a bad assumption, but the duplicates are messy). // we'll assume that direct delivery is robust (and this is a bad assumption, but the duplicates are messy).
if ($r[0]['network'] === NETWORK_DIASPORA) { if($r[0]['network'] === NETWORK_DIASPORA)
hub_post_return(); hub_post_return();
}
$feedhub = ''; $feedhub = '';

View file

@ -10,14 +10,12 @@ function qsearch_init(App $a) {
$search = ((x($_GET,'s')) ? notags(trim(urldecode($_GET['s']))) : ''); $search = ((x($_GET,'s')) ? notags(trim(urldecode($_GET['s']))) : '');
if (! strlen($search)) { if(! strlen($search))
killme(); killme();
}
if ($search) { if($search)
$search = dbesc($search); $search = dbesc($search);
}
$results = array(); $results = array();
@ -27,10 +25,10 @@ function qsearch_init(App $a) {
); );
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
foreach ($r as $rr) {
foreach($r as $rr)
$results[] = array( 0, (int) $rr['id'], $rr['name'], '', ''); $results[] = array( 0, (int) $rr['id'], $rr['name'], '', '');
} }
}
$sql_extra = ((strlen($search)) ? " AND (`name` REGEXP '$search' OR `nick` REGEXP '$search') " : ""); $sql_extra = ((strlen($search)) ? " AND (`name` REGEXP '$search' OR `nick` REGEXP '$search') " : "");
@ -42,10 +40,10 @@ function qsearch_init(App $a) {
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
foreach ($r as $rr) {
foreach($r as $rr)
$results[] = array( (int) $rr['id'], 0, $rr['name'],$rr['url'],$rr['photo']); $results[] = array( (int) $rr['id'], 0, $rr['name'],$rr['url'],$rr['photo']);
} }
}
echo json_encode((object) $results); echo json_encode((object) $results);
killme(); killme();

View file

@ -72,9 +72,8 @@ function user_deny($hash) {
dbesc($hash) dbesc($hash)
); );
if (! dbm::is_result($register)) { if(! dbm::is_result($register))
return false; return false;
}
$user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", $user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
intval($register[0]['uid']) intval($register[0]['uid'])

0
mod/repair_ostatus.php Normal file → Executable file
View file

View file

@ -384,10 +384,7 @@ function settings_post(App $a) {
// check if the old password was supplied correctly before // check if the old password was supplied correctly before
// changing it to the new value // changing it to the new value
$r = q("SELECT `password` FROM `user`WHERE `uid` = %d LIMIT 1", intval(local_user())); $r = q("SELECT `password` FROM `user`WHERE `uid` = %d LIMIT 1", intval(local_user()));
if (!dbm::is_result($r)) { if( $oldpass != $r[0]['password'] ) {
/// @todo Don't quit silently here
killme();
} elseif ( $oldpass != $r[0]['password'] ) {
notice( t('Wrong password.') . EOL); notice( t('Wrong password.') . EOL);
$err = true; $err = true;
} }
@ -398,13 +395,12 @@ function settings_post(App $a) {
dbesc($password), dbesc($password),
intval(local_user()) intval(local_user())
); );
if ($r) { if($r)
info( t('Password changed.') . EOL); info( t('Password changed.') . EOL);
} else { else
notice( t('Password update failed. Please try again.') . EOL); notice( t('Password update failed. Please try again.') . EOL);
} }
} }
}
$username = ((x($_POST,'username')) ? notags(trim($_POST['username'])) : ''); $username = ((x($_POST,'username')) ? notags(trim($_POST['username'])) : '');
@ -446,41 +442,32 @@ function settings_post(App $a) {
$notify = 0; $notify = 0;
if (x($_POST,'notify1')) { if(x($_POST,'notify1'))
$notify += intval($_POST['notify1']); $notify += intval($_POST['notify1']);
} if(x($_POST,'notify2'))
if (x($_POST,'notify2')) {
$notify += intval($_POST['notify2']); $notify += intval($_POST['notify2']);
} if(x($_POST,'notify3'))
if (x($_POST,'notify3')) {
$notify += intval($_POST['notify3']); $notify += intval($_POST['notify3']);
} if(x($_POST,'notify4'))
if (x($_POST,'notify4')) {
$notify += intval($_POST['notify4']); $notify += intval($_POST['notify4']);
} if(x($_POST,'notify5'))
if (x($_POST,'notify5')) {
$notify += intval($_POST['notify5']); $notify += intval($_POST['notify5']);
} if(x($_POST,'notify6'))
if (x($_POST,'notify6')) {
$notify += intval($_POST['notify6']); $notify += intval($_POST['notify6']);
} if(x($_POST,'notify7'))
if (x($_POST,'notify7')) {
$notify += intval($_POST['notify7']); $notify += intval($_POST['notify7']);
} if(x($_POST,'notify8'))
if (x($_POST,'notify8')) {
$notify += intval($_POST['notify8']); $notify += intval($_POST['notify8']);
}
// Adjust the page flag if the account type doesn't fit to the page flag. // Adjust the page flag if the account type doesn't fit to the page flag.
if (($account_type == ACCOUNT_TYPE_PERSON) AND !in_array($page_flags, array(PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE))) { if (($account_type == ACCOUNT_TYPE_PERSON) AND !in_array($page_flags, array(PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE)))
$page_flags = PAGE_NORMAL; $page_flags = PAGE_NORMAL;
} elseif (($account_type == ACCOUNT_TYPE_ORGANISATION) AND !in_array($page_flags, array(PAGE_SOAPBOX))) { elseif (($account_type == ACCOUNT_TYPE_ORGANISATION) AND !in_array($page_flags, array(PAGE_SOAPBOX)))
$page_flags = PAGE_SOAPBOX; $page_flags = PAGE_SOAPBOX;
} elseif (($account_type == ACCOUNT_TYPE_NEWS) AND !in_array($page_flags, array(PAGE_SOAPBOX))) { elseif (($account_type == ACCOUNT_TYPE_NEWS) AND !in_array($page_flags, array(PAGE_SOAPBOX)))
$page_flags = PAGE_SOAPBOX; $page_flags = PAGE_SOAPBOX;
} elseif (($account_type == ACCOUNT_TYPE_COMMUNITY) AND !in_array($page_flags, array(PAGE_COMMUNITY, PAGE_PRVGROUP))) { elseif (($account_type == ACCOUNT_TYPE_COMMUNITY) AND !in_array($page_flags, array(PAGE_COMMUNITY, PAGE_PRVGROUP)))
$page_flags = PAGE_COMMUNITY; $page_flags = PAGE_COMMUNITY;
}
$email_changed = false; $email_changed = false;
@ -490,13 +477,11 @@ function settings_post(App $a) {
if($username != $a->user['username']) { if($username != $a->user['username']) {
$name_change = true; $name_change = true;
if (strlen($username) > 40) { if(strlen($username) > 40)
$err .= t(' Please use a shorter name.'); $err .= t(' Please use a shorter name.');
} if(strlen($username) < 3)
if (strlen($username) < 3) {
$err .= t(' Name too short.'); $err .= t(' Name too short.');
} }
}
if($email != $a->user['email']) { if($email != $a->user['email']) {
$email_changed = true; $email_changed = true;
@ -508,9 +493,8 @@ function settings_post(App $a) {
$email = $a->user['email']; $email = $a->user['email'];
} }
// check the email is valid // check the email is valid
if (! valid_email($email)) { if(! valid_email($email))
$err .= t(' Not valid email.'); $err .= t(' Not valid email.');
}
// ensure new email is not the admin mail // ensure new email is not the admin mail
//if((x($a->config,'admin_email')) && (strcasecmp($email,$a->config['admin_email']) == 0)) { //if((x($a->config,'admin_email')) && (strcasecmp($email,$a->config['admin_email']) == 0)) {
if(x($a->config,'admin_email')) { if(x($a->config,'admin_email')) {
@ -527,7 +511,8 @@ function settings_post(App $a) {
return; return;
} }
if ($timezone != $a->user['timezone'] && strlen($timezone)) { if($timezone != $a->user['timezone']) {
if(strlen($timezone))
date_default_timezone_set($timezone); date_default_timezone_set($timezone);
} }
@ -549,9 +534,9 @@ function settings_post(App $a) {
$open_id_obj = new LightOpenID; $open_id_obj = new LightOpenID;
$open_id_obj->identity = $openid; $open_id_obj->identity = $openid;
$openidserver = $open_id_obj->discover($open_id_obj->identity); $openidserver = $open_id_obj->discover($open_id_obj->identity);
} else {
$openidserver = '';
} }
else
$openidserver = '';
} }
set_pconfig(local_user(),'expire','items', $expire_items); set_pconfig(local_user(),'expire','items', $expire_items);
@ -573,7 +558,8 @@ function settings_post(App $a) {
if($def_gid) { if($def_gid) {
info( t('Private forum has no privacy permissions. Using default privacy group.'). EOL); info( t('Private forum has no privacy permissions. Using default privacy group.'). EOL);
$str_group_allow = '<' . $def_gid . '>'; $str_group_allow = '<' . $def_gid . '>';
} else { }
else {
notice( t('Private forum has no privacy permissions and no default privacy group.') . EOL); notice( t('Private forum has no privacy permissions and no default privacy group.') . EOL);
} }
} }
@ -613,9 +599,8 @@ function settings_post(App $a) {
dbesc($language), dbesc($language),
intval(local_user()) intval(local_user())
); );
if ($r) { if($r)
info( t('Settings updated.') . EOL); info( t('Settings updated.') . EOL);
}
// clear session language // clear session language
unset($_SESSION['language']); unset($_SESSION['language']);
@ -684,6 +669,8 @@ function settings_content(App $a) {
return; return;
} }
if (($a->argc > 1) && ($a->argv[1] === 'oauth')) { if (($a->argc > 1) && ($a->argv[1] === 'oauth')) {
if (($a->argc > 2) && ($a->argv[2] === 'add')) { if (($a->argc > 2) && ($a->argv[2] === 'add')) {

View file

@ -14,7 +14,8 @@ function smilies_content(App $a) {
$results[] = array('text' => $tmp['texts'][$i], 'icon' => $tmp['icons'][$i]); $results[] = array('text' => $tmp['texts'][$i], 'icon' => $tmp['icons'][$i]);
} }
json_return_and_die($results); json_return_and_die($results);
} else { }
else {
return Smilies::replace('',true); return Smilies::replace('',true);
} }
} }

View file

@ -25,9 +25,8 @@ function videos_init(App $a) {
dbesc($nick) dbesc($nick)
); );
if (!dbm::is_result($user)) { if(! count($user))
return; return;
}
$a->data['user'] = $user[0]; $a->data['user'] = $user[0];
$a->profile_uid = $user[0]['uid']; $a->profile_uid = $user[0]['uid'];

View file

@ -9,10 +9,9 @@ function view_init($a){
if ($a->argc == 4){ if ($a->argc == 4){
$theme = $a->argv[2]; $theme = $a->argv[2];
$THEMEPATH = "view/theme/$theme"; $THEMEPATH = "view/theme/$theme";
if (file_exists("view/theme/$theme/style.php")) { if(file_exists("view/theme/$theme/style.php"))
require_once("view/theme/$theme/style.php"); require_once("view/theme/$theme/style.php");
} }
}
killme(); killme();
} }

View file

@ -90,11 +90,10 @@ function viewcontacts_content(App $a) {
$is_owner = ((local_user() && ($a->profile['profile_uid'] == local_user())) ? true : false); $is_owner = ((local_user() && ($a->profile['profile_uid'] == local_user())) ? true : false);
if ($is_owner && ($rr['network'] === NETWORK_DFRN) && ($rr['rel'])) { if($is_owner && ($rr['network'] === NETWORK_DFRN) && ($rr['rel']))
$url = 'redir/' . $rr['id']; $url = 'redir/' . $rr['id'];
} else { else
$url = zrl($url); $url = zrl($url);
}
$contact_details = get_contact_details_by_url($rr['url'], $a->profile['uid'], $rr); $contact_details = get_contact_details_by_url($rr['url'], $a->profile['uid'], $rr);

View file

@ -228,25 +228,23 @@ function wall_upload_post(App $a, $desktopmode = true) {
if($width > 640 || $height > 640) { if($width > 640 || $height > 640) {
$ph->scaleImage(640); $ph->scaleImage(640);
$r = $ph->store($page_owner_uid, $visitor, $hash, $filename, t('Wall Photos'), 1, 0, $defperm); $r = $ph->store($page_owner_uid, $visitor, $hash, $filename, t('Wall Photos'), 1, 0, $defperm);
if ($r) { if($r)
$smallest = 1; $smallest = 1;
} }
}
if($width > 320 || $height > 320) { if($width > 320 || $height > 320) {
$ph->scaleImage(320); $ph->scaleImage(320);
$r = $ph->store($page_owner_uid, $visitor, $hash, $filename, t('Wall Photos'), 2, 0, $defperm); $r = $ph->store($page_owner_uid, $visitor, $hash, $filename, t('Wall Photos'), 2, 0, $defperm);
if ($r AND ($smallest == 0)) { if($r AND ($smallest == 0))
$smallest = 2; $smallest = 2;
} }
}
$basename = basename($filename); $basename = basename($filename);
if (!$desktopmode) { if (!$desktopmode) {
$r = q("SELECT `id`, `datasize`, `width`, `height`, `type` FROM `photo` WHERE `resource-id` = '%s' ORDER BY `width` DESC LIMIT 1", $hash); $r = q("SELECT `id`, `datasize`, `width`, `height`, `type` FROM `photo` WHERE `resource-id` = '%s' ORDER BY `width` DESC LIMIT 1", $hash);
if (!dbm::is_result($r)) { if (!$r){
if ($r_json) { if ($r_json) {
echo json_encode(array('error'=>'')); echo json_encode(array('error'=>''));
killme(); killme();

View file

@ -98,14 +98,11 @@ function wallmessage_content(App $a) {
return; return;
} }
$r = q("SELECT COUNT(*) AS `total` FROM `mail` WHERE `uid` = %d AND `created` > UTC_TIMESTAMP() - INTERVAL 1 DAY AND `unknown` = 1", $r = q("select count(*) as total from mail where uid = %d and created > UTC_TIMESTAMP() - INTERVAL 1 day and unknown = 1",
intval($user['uid']) intval($user['uid'])
); );
if (!dbm::is_result($r)) { if($r[0]['total'] > $user['cntunkmail']) {
///@TODO Output message to use of failed query
return;
} elseif ($r[0]['total'] > $user['cntunkmail']) {
notice( sprintf( t('Number of daily wall messages for %s exceeded. Message failed.', $user['username']))); notice( sprintf( t('Number of daily wall messages for %s exceeded. Message failed.', $user['username'])));
return; return;
} }

View file

@ -12,9 +12,8 @@ function xrd_init(App $a) {
} else { } else {
$acct = true; $acct = true;
$local = str_replace('acct:', '', $uri); $local = str_replace('acct:', '', $uri);
if (substr($local,0,2) == '//') { if(substr($local,0,2) == '//')
$local = substr($local,2); $local = substr($local,2);
}
$name = substr($local,0,strpos($local,'@')); $name = substr($local,0,strpos($local,'@'));
} }

View file

@ -1,7 +1,6 @@
<?php <?php
if (class_exists('BaseObject')) { if(class_exists('BaseObject'))
return; return;
}
require_once('boot.php'); require_once('boot.php');
@ -19,9 +18,8 @@ class BaseObject {
* Same as get_app from boot.php * Same as get_app from boot.php
*/ */
public function get_app() { public function get_app() {
if (self::$app) { if(self::$app)
return self::$app; return self::$app;
}
self::$app = get_app(); self::$app = get_app();

View file

@ -1,7 +1,6 @@
<?php <?php
if (class_exists('Conversation')) { if(class_exists('Conversation'))
return; return;
}
require_once('boot.php'); require_once('boot.php');
require_once('object/BaseObject.php'); require_once('object/BaseObject.php');
@ -134,9 +133,8 @@ class Conversation extends BaseObject {
$i = 0; $i = 0;
foreach($this->threads as $item) { foreach($this->threads as $item) {
if ($item->get_data_value('network') === NETWORK_MAIL && local_user() != $item->get_data_value('uid')) { if($item->get_data_value('network') === NETWORK_MAIL && local_user() != $item->get_data_value('uid'))
continue; continue;
}
$item_data = $item->get_template_data($conv_responses); $item_data = $item->get_template_data($conv_responses);
@ -159,10 +157,9 @@ class Conversation extends BaseObject {
*/ */
private function get_thread($id) { private function get_thread($id) {
foreach($this->threads as $item) { foreach($this->threads as $item) {
if ($item->get_id() == $id) { if($item->get_id() == $id)
return $item; return $item;
} }
}
return false; return false;
} }

View file

@ -1,7 +1,6 @@
<?php <?php
if (class_exists('Item')) { if(class_exists('Item'))
return; return;
}
require_once('object/BaseObject.php'); require_once('object/BaseObject.php');
require_once('include/text.php'); require_once('include/text.php');

View file

@ -15,8 +15,7 @@
*/ */
if (($_SERVER["argc"] > 1) && isset($_SERVER["argv"][1])) { if(($_SERVER["argc"] > 1) && isset($_SERVER["argv"][1]))
echo $_SERVER["argv"][1]; echo $_SERVER["argv"][1];
} else { else
echo ''; echo '';
}

View file

@ -37,7 +37,7 @@ define('UPDATE_VERSION' , 1216);
*/ */
/// @TODO These old updates need to have UPDATE_SUCCESS returned on success?
function update_1000() { function update_1000() {
q("ALTER TABLE `item` DROP `like`, DROP `dislike` "); q("ALTER TABLE `item` DROP `like`, DROP `dislike` ");
@ -157,18 +157,17 @@ function update_1014() {
$r = q("SELECT * FROM `contact` WHERE 1"); $r = q("SELECT * FROM `contact` WHERE 1");
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
foreach ($r as $rr) { foreach ($r as $rr) {
if (stristr($rr['thumb'],'avatar')) { if(stristr($rr['thumb'],'avatar'))
q("UPDATE `contact` SET `micro` = '%s' WHERE `id` = %d", q("UPDATE `contact` SET `micro` = '%s' WHERE `id` = %d",
dbesc(str_replace('avatar','micro',$rr['thumb'])), dbesc(str_replace('avatar','micro',$rr['thumb'])),
intval($rr['id'])); intval($rr['id']));
} else { else
q("UPDATE `contact` SET `micro` = '%s' WHERE `id` = %d", q("UPDATE `contact` SET `micro` = '%s' WHERE `id` = %d",
dbesc(str_replace('5.jpg','6.jpg',$rr['thumb'])), dbesc(str_replace('5.jpg','6.jpg',$rr['thumb'])),
intval($rr['id'])); intval($rr['id']));
} }
} }
} }
}
function update_1015() { function update_1015() {
q("ALTER TABLE `item` CHANGE `body` `body` mediumtext NOT NULL"); q("ALTER TABLE `item` CHANGE `body` `body` mediumtext NOT NULL");
@ -309,7 +308,7 @@ function update_1030() {
function update_1031() { function update_1031() {
// Repair any bad links that slipped into the item table // Repair any bad links that slipped into the item table
$r = q("SELECT `id`, `object` FROM `item` WHERE `object` != '' "); $r = q("SELECT `id`, `object` FROM `item` WHERE `object` != '' ");
if (dbm::is_result($r)) { if($r && dbm::is_result($r)) {
foreach ($r as $rr) { foreach ($r as $rr) {
if(strstr($rr['object'],'type=&quot;http')) { if(strstr($rr['object'],'type=&quot;http')) {
q("UPDATE `item` SET `object` = '%s' WHERE `id` = %d", q("UPDATE `item` SET `object` = '%s' WHERE `id` = %d",
@ -369,7 +368,9 @@ function update_1036() {
} }
function update_1037() { function update_1037() {
q("ALTER TABLE `contact` CHANGE `lrdd` `alias` CHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL "); q("ALTER TABLE `contact` CHANGE `lrdd` `alias` CHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ");
} }
function update_1038() { function update_1038() {
@ -530,12 +531,9 @@ function update_1065() {
} }
function update_1066() { function update_1066() {
$r = q("ALTER TABLE `item` ADD `received` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER `edited` "); $r = q("ALTER TABLE `item` ADD `received` DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00' AFTER `edited` ");
if($r)
/// @TODO Decide to use dbm::is_result() here, what does $r include?
if ($r) {
q("ALTER TABLE `item` ADD INDEX ( `received` ) "); q("ALTER TABLE `item` ADD INDEX ( `received` ) ");
}
$r = q("UPDATE `item` SET `received` = `edited` WHERE 1"); $r = q("UPDATE `item` SET `received` = `edited` WHERE 1");
} }
@ -597,12 +595,11 @@ function update_1074() {
q("ALTER TABLE `user` ADD `hidewall` TINYINT( 1) NOT NULL DEFAULT '0' AFTER `blockwall` "); q("ALTER TABLE `user` ADD `hidewall` TINYINT( 1) NOT NULL DEFAULT '0' AFTER `blockwall` ");
$r = q("SELECT `uid` FROM `profile` WHERE `is-default` = 1 AND `hidewall` = 1"); $r = q("SELECT `uid` FROM `profile` WHERE `is-default` = 1 AND `hidewall` = 1");
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
foreach ($r as $rr) { foreach($r as $rr)
q("UPDATE `user` SET `hidewall` = 1 WHERE `uid` = %d", q("UPDATE `user` SET `hidewall` = 1 WHERE `uid` = %d",
intval($rr['uid']) intval($rr['uid'])
); );
} }
}
q("ALTER TABLE `profile` DROP `hidewall`"); q("ALTER TABLE `profile` DROP `hidewall`");
} }
@ -617,9 +614,8 @@ function update_1075() {
$x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1", $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
dbesc($guid) dbesc($guid)
); );
if (!dbm::is_result($x)) { if(! count($x))
$found = false; $found = false;
}
} while ($found == true ); } while ($found == true );
q("UPDATE `user` SET `guid` = '%s' WHERE `uid` = %d", q("UPDATE `user` SET `guid` = '%s' WHERE `uid` = %d",
@ -688,19 +684,14 @@ function update_1082() {
q("ALTER TABLE `photo` ADD `guid` CHAR( 64 ) NOT NULL AFTER `contact-id`, q("ALTER TABLE `photo` ADD `guid` CHAR( 64 ) NOT NULL AFTER `contact-id`,
ADD INDEX ( `guid` ) "); ADD INDEX ( `guid` ) ");
// make certain the following code is only executed once // make certain the following code is only executed once
$r = q("select `id` from `photo` where `guid` != '' limit 1");
$r = q("SELECT `id` FROM `photo` WHERE `guid` != '' LIMIT 1"); if (dbm::is_result($r))
if (dbm::is_result($r)) {
return; return;
}
$r = q("SELECT distinct(`resource-id`) FROM `photo` WHERE 1 group by `id`"); $r = q("SELECT distinct(`resource-id`) FROM `photo` WHERE 1 group by `id`");
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
foreach ($r as $rr) { foreach ($r as $rr) {
$guid = get_guid(); $guid = get_guid();
q("UPDATE `photo` SET `guid` = '%s' WHERE `resource-id` = '%s'", q("update `photo` set `guid` = '%s' where `resource-id` = '%s'",
dbesc($guid), dbesc($guid),
dbesc($rr['resource-id']) dbesc($rr['resource-id'])
); );
@ -745,8 +736,7 @@ function update_1087() {
$x = q("SELECT max(`created`) AS `cdate` FROM `item` WHERE `parent` = %d LIMIT 1", $x = q("SELECT max(`created`) AS `cdate` FROM `item` WHERE `parent` = %d LIMIT 1",
intval($rr['id']) intval($rr['id'])
); );
if(count($x))
if (dbm::is_result($x)) {
q("UPDATE `item` SET `commented` = '%s' WHERE `id` = %d", q("UPDATE `item` SET `commented` = '%s' WHERE `id` = %d",
dbesc($x[0]['cdate']), dbesc($x[0]['cdate']),
intval($rr['id']) intval($rr['id'])
@ -754,7 +744,6 @@ function update_1087() {
} }
} }
} }
}
function update_1088() { function update_1088() {
q("ALTER TABLE `user` ADD `account_expired` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `expire` , q("ALTER TABLE `user` ADD `account_expired` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `expire` ,
@ -860,14 +849,14 @@ function update_1099() {
function update_1100() { function update_1100() {
q("ALTER TABLE `contact` ADD `nurl` CHAR( 255 ) NOT NULL AFTER `url` "); q("ALTER TABLE `contact` ADD `nurl` CHAR( 255 ) NOT NULL AFTER `url` ");
q("ALTER TABLE `contact` ADD INDEX (`nurl`) "); q("alter table contact add index (`nurl`) ");
require_once('include/text.php'); require_once('include/text.php');
$r = q("SELECT `id`, `url` FROM `contact` WHERE `url` != '' AND `nurl` = '' "); $r = q("select id, url from contact where url != '' and nurl = '' ");
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
foreach ($r as $rr) { foreach ($r as $rr) {
q("UPDATE `contact` SET `nurl` = '%s' WHERE `id` = %d", q("update contact set nurl = '%s' where id = %d",
dbesc(normalise_link($rr['url'])), dbesc(normalise_link($rr['url'])),
intval($rr['id']) intval($rr['id'])
); );
@ -897,7 +886,6 @@ function update_1102() {
function update_1103() { function update_1103() {
/// @TODO Commented out:
// q("ALTER TABLE `item` ADD INDEX ( `wall` ) "); // q("ALTER TABLE `item` ADD INDEX ( `wall` ) ");
q("ALTER TABLE `item` ADD FULLTEXT ( `tag` ) "); q("ALTER TABLE `item` ADD FULLTEXT ( `tag` ) ");
q("ALTER TABLE `contact` ADD INDEX ( `pending` ) "); q("ALTER TABLE `contact` ADD INDEX ( `pending` ) ");
@ -1043,12 +1031,10 @@ function update_1120() {
$r = q("describe item"); $r = q("describe item");
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
foreach ($r as $rr) { foreach($r as $rr)
if ($rr['Field'] == 'spam') { if($rr['Field'] == 'spam')
return; return;
} }
}
}
q("ALTER TABLE `item` ADD `spam` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `visible` , ADD INDEX (`spam`) "); q("ALTER TABLE `item` ADD `spam` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `visible` , ADD INDEX (`spam`) ");
} }
@ -1090,7 +1076,7 @@ function update_1123() {
} }
function update_1124() { function update_1124() {
q("ALTER TABLE `item` ADD INDEX (`author-name`) "); q("alter table item add index (`author-name`) ");
} }
function update_1125() { function update_1125() {
@ -1102,7 +1088,7 @@ function update_1125() {
`receiver-uid` INT NOT NULL, `receiver-uid` INT NOT NULL,
INDEX ( `master-parent-item` ), INDEX ( `master-parent-item` ),
INDEX ( `receiver-uid` ) INDEX ( `receiver-uid` )
) DEFAULT CHARSET=utf8"); ) ENGINE = MyISAM DEFAULT CHARSET=utf8");
} }
function update_1126() { function update_1126() {
@ -1121,12 +1107,12 @@ function update_1127() {
INDEX ( `spam` ), INDEX ( `spam` ),
INDEX ( `ham` ), INDEX ( `ham` ),
INDEX ( `term` ) INDEX ( `term` )
) DEFAULT CHARSET=utf8"); ) ENGINE = MyISAM DEFAULT CHARSET=utf8");
} }
function update_1128() { function update_1128() {
q("ALTER TABLE `spam` ADD `date` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER `term` "); q("alter table spam add `date` DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00' AFTER `term` ");
} }
function update_1129() { function update_1129() {
@ -1147,7 +1133,7 @@ function update_1132() {
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`username` CHAR( 255 ) NOT NULL, `username` CHAR( 255 ) NOT NULL,
INDEX ( `username` ) INDEX ( `username` )
) "); ) ENGINE = MYISAM ");
} }
@ -1181,14 +1167,14 @@ function update_1136() {
// order in reverse so that we save the newest entry // order in reverse so that we save the newest entry
$r = q("SELECT * FROM `config` WHERE 1 ORDER BY `id` DESC"); $r = q("select * from config where 1 order by id desc");
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
foreach ($r as $rr) { foreach ($r as $rr) {
$found = false; $found = false;
foreach($arr as $x) { foreach($arr as $x) {
if($x['cat'] == $rr['cat'] && $x['k'] == $rr['k']) { if($x['cat'] == $rr['cat'] && $x['k'] == $rr['k']) {
$found = true; $found = true;
q("DELETE FROM `config` WHERE `id` = %d", q("delete from config where id = %d",
intval($rr['id']) intval($rr['id'])
); );
} }
@ -1200,14 +1186,14 @@ function update_1136() {
} }
$arr = array(); $arr = array();
$r = q("SELECT * FROM `pconfig` WHERE 1 ORDER BY `id` DESC"); $r = q("select * from pconfig where 1 order by id desc");
if (dbm::is_result($r)) { if (dbm::is_result($r)) {
foreach ($r as $rr) { foreach ($r as $rr) {
$found = false; $found = false;
foreach($arr as $x) { foreach($arr as $x) {
if($x['uid'] == $rr['uid'] && $x['cat'] == $rr['cat'] && $x['k'] == $rr['k']) { if($x['uid'] == $rr['uid'] && $x['cat'] == $rr['cat'] && $x['k'] == $rr['k']) {
$found = true; $found = true;
q("DELETE FROM `pconfig` WHERE `id` = %d", q("delete from pconfig where id = %d",
intval($rr['id']) intval($rr['id'])
); );
} }
@ -1224,153 +1210,114 @@ function update_1136() {
function update_1137() { function update_1137() {
q("ALTER TABLE `item_id` DROP `face` , DROP `dspr` , DROP `twit` , DROP `stat` "); q("alter table item_id DROP `face` , DROP `dspr` , DROP `twit` , DROP `stat` ");
q("ALTER TABLE `item_id` ADD `sid` CHAR( 255 ) NOT NULL AFTER `uid` , ADD `service` CHAR( 255 ) NOT NULL AFTER `sid` , ADD INDEX (`sid`), ADD INDEX ( `service`) "); q("ALTER TABLE `item_id` ADD `sid` CHAR( 255 ) NOT NULL AFTER `uid` , ADD `service` CHAR( 255 ) NOT NULL AFTER `sid` , add index (`sid`), add index ( `service`) ");
} }
function update_1138() { function update_1138() {
q("ALTER TABLE `contact` ADD `archive` TINYINT(1) NOT NULL DEFAULT '0' AFTER `hidden`, ADD INDEX (`archive`)"); q("alter table contact add archive tinyint(1) not null default '0' after hidden, add index (archive)");
} }
function update_1139() { function update_1139() {
$r = q("ALTER TABLE `user` ADD `account_removed` TINYINT(1) NOT NULL DEFAULT '0' AFTER `expire`, ADD INDEX(`account_removed`)"); $r = q("alter table user add account_removed tinyint(1) not null default '0' after expire, add index(account_removed) ");
if(! $r)
if ($r) {
return UPDATE_SUCCESS ;
}
return UPDATE_FAILED ; return UPDATE_FAILED ;
return UPDATE_SUCCESS ;
} }
function update_1140() { function update_1140() {
$r = q("ALTER TABLE `addon` ADD `hidden` TINYINT(1) NOT NULL DEFAULT '0' AFTER `installed`, ADD INDEX(`hidden`) "); $r = q("alter table addon add hidden tinyint(1) not null default '0' after installed, add index(hidden) ");
if(! $r)
if ($r) {
return UPDATE_SUCCESS ;
}
return UPDATE_FAILED ; return UPDATE_FAILED ;
return UPDATE_SUCCESS ;
} }
function update_1141() { function update_1141() {
$r = q("ALTER TABLE `glink` ADD `zcid` INT(11) NOT NULL AFTER `gcid`, ADD INDEX(`zcid`) "); $r = q("alter table glink add zcid int(11) not null after gcid, add index(zcid) ");
if(! $r)
if ($r) {
return UPDATE_SUCCESS ;
}
return UPDATE_FAILED ; return UPDATE_FAILED ;
return UPDATE_SUCCESS ;
} }
function update_1142() { function update_1142() {
$r = q("ALTER TABLE `user` ADD `service_class` CHAR(32) NOT NULL AFTER `expire_notification_sent`, ADD INDEX(`service_class`) "); $r = q("alter table user add service_class char(32) not null after expire_notification_sent, add index(service_class) ");
if(! $r)
if ($r) {
return UPDATE_SUCCESS ;
}
return UPDATE_FAILED ; return UPDATE_FAILED ;
return UPDATE_SUCCESS ;
} }
function update_1143() { function update_1143() {
$r = q("ALTER TABLE `user` ADD `def_gid` INT(11) NOT NULL DEFAULT '0' AFTER `service_class`"); $r = q("alter table user add def_gid int(11) not null default '0' after service_class");
if(! $r)
if ($r) {
return UPDATE_SUCCESS ;
}
return UPDATE_FAILED ; return UPDATE_FAILED ;
return UPDATE_SUCCESS ;
} }
function update_1144() { function update_1144() {
$r = q("ALTER TABLE `contact` ADD `prv` TINYINT(1) NOT NULL DEFAULT '0' AFTER `forum`"); $r = q("alter table contact add prv tinyint(1) not null default '0' after forum");
if(! $r)
if ($r) {
return UPDATE_SUCCESS ;
}
return UPDATE_FAILED ; return UPDATE_FAILED ;
return UPDATE_SUCCESS ;
} }
function update_1145() { function update_1145() {
$r = q("ALTER TABLE `profile` ADD `howlong` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER `with`"); $r = q("alter table profile add howlong datetime not null default '0001-01-01 00:00:00' after `with`");
if(! $r)
if ($r) {
return UPDATE_SUCCESS ;
}
return UPDATE_FAILED ; return UPDATE_FAILED ;
return UPDATE_SUCCESS ;
} }
function update_1146() { function update_1146() {
$r = q("ALTER TABLE `profile` ADD `hometown` CHAR(255) NOT NULL AFTER `country-name`, ADD INDEX ( `hometown` ) "); $r = q("alter table profile add hometown char(255) not null after `country-name`, add index ( `hometown` ) ");
if(! $r)
if ($r) {
return UPDATE_SUCCESS ;
}
return UPDATE_FAILED ; return UPDATE_FAILED ;
return UPDATE_SUCCESS ;
} }
function update_1147() { function update_1147() {
$r1 = q("ALTER TABLE `sign` ALTER `iid` SET DEFAULT '0'"); $r1 = q("ALTER TABLE `sign` ALTER `iid` SET DEFAULT '0'");
$r2 = q("ALTER TABLE `sign` ADD `retract_iid` INT(10) UNSIGNED NOT NULL DEFAULT '0' AFTER `iid`"); $r2 = q("ALTER TABLE `sign` ADD `retract_iid` INT(10) UNSIGNED NOT NULL DEFAULT '0' AFTER `iid`");
$r3 = q("ALTER TABLE `sign` ADD INDEX ( `retract_iid` )"); $r3 = q("ALTER TABLE `sign` ADD INDEX ( `retract_iid` )");
if((! $r1) || (! $r2) || (! $r3))
if ($r1 && $r2 && $r3) {
return UPDATE_SUCCESS ;
}
return UPDATE_FAILED ; return UPDATE_FAILED ;
return UPDATE_SUCCESS ;
} }
function update_1148() { function update_1148() {
$r = q("ALTER TABLE `photo` ADD `type` CHAR(128) NOT NULL DEFAULT 'image/jpeg' AFTER `filename`"); $r = q("ALTER TABLE photo ADD type CHAR(128) NOT NULL DEFAULT 'image/jpeg' AFTER filename");
if (!$r)
if ($r) {
return UPDATE_SUCCESS ;
}
return UPDATE_FAILED; return UPDATE_FAILED;
return UPDATE_SUCCESS;
} }
function update_1149() { function update_1149() {
$r1 = q("ALTER TABLE `profile` ADD `likes` TEXT NOT NULL AFTER `prv_keywords`"); $r1 = q("ALTER TABLE profile ADD likes text NOT NULL after prv_keywords");
$r2 = q("ALTER TABLE `profile` ADD `dislikes` TEXT NOT NULL AFTER `likes`"); $r2 = q("ALTER TABLE profile ADD dislikes text NOT NULL after likes");
if (! ($r1 && $r2))
if ($r1 && $r2) {
return UPDATE_SUCCESS;
}
return UPDATE_FAILED; return UPDATE_FAILED;
return UPDATE_SUCCESS;
} }
function update_1150() { function update_1150() {
$r = q("ALTER TABLE `event` ADD `summary` TEXT NOT NULL AFTER `finish`, ADD INDEX ( `uid` ), ADD INDEX ( `cid` ), ADD INDEX ( `uri` ), ADD INDEX ( `start` ), ADD INDEX ( `finish` ), ADD INDEX ( `type` ), ADD INDEX ( `adjust` ) "); $r = q("ALTER TABLE event ADD summary text NOT NULL after finish, add index ( uid ), add index ( cid ), add index ( uri ), add index ( `start` ), add index ( finish ), add index ( `type` ), add index ( adjust ) ");
if(! $r)
if ($r) {
return UPDATE_SUCCESS ;
}
return UPDATE_FAILED; return UPDATE_FAILED;
return UPDATE_SUCCESS;
} }
function update_1151() { function update_1151() {
$r = q("CREATE TABLE IF NOT EXISTS `locks` ( $r = q("CREATE TABLE IF NOT EXISTS locks (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` CHAR( 128 ) NOT NULL , name CHAR( 128 ) NOT NULL ,
`locked` TINYINT( 1 ) NOT NULL DEFAULT '0' locked TINYINT( 1 ) NOT NULL DEFAULT '0'
) DEFAULT CHARSET=utf8 "); ) ENGINE = MYISAM DEFAULT CHARSET=utf8 ");
if (!$r)
if ($r) {
return UPDATE_SUCCESS ;
}
return UPDATE_FAILED; return UPDATE_FAILED;
return UPDATE_SUCCESS;
} }
function update_1152() { function update_1152() {
@ -1385,43 +1332,33 @@ function update_1152() {
KEY `otype` ( `otype` ), KEY `otype` ( `otype` ),
KEY `type` ( `type` ), KEY `type` ( `type` ),
KEY `term` ( `term` ) KEY `term` ( `term` )
) DEFAULT CHARSET=utf8 "); ) ENGINE = MYISAM DEFAULT CHARSET=utf8 ");
if (!$r)
if ($r) {
return UPDATE_SUCCESS;
}
return UPDATE_FAILED; return UPDATE_FAILED;
return UPDATE_SUCCESS;
} }
function update_1153() { function update_1153() {
$r = q("ALTER TABLE `hook` ADD `priority` INT(11) UNSIGNED NOT NULL DEFAULT '0'"); $r = q("ALTER TABLE `hook` ADD `priority` INT(11) UNSIGNED NOT NULL DEFAULT '0'");
if ($r) { if(!$r) return UPDATE_FAILED;
return UPDATE_SUCCESS; return UPDATE_SUCCESS;
} }
return UPDATE_FAILED;
}
function update_1154() { function update_1154() {
$r = q("ALTER TABLE `event` ADD `ignore` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT '0' AFTER `adjust` , ADD INDEX ( `ignore` )"); $r = q("ALTER TABLE `event` ADD `ignore` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT '0' AFTER `adjust` , ADD INDEX ( `ignore` )");
if ($r) { if(!$r) return UPDATE_FAILED;
return UPDATE_SUCCESS; return UPDATE_SUCCESS;
} }
return UPDATE_FAILED;
}
function update_1155() { function update_1155() {
$r1 = q("ALTER TABLE `item_id` DROP PRIMARY KEY"); $r1 = q("ALTER TABLE `item_id` DROP PRIMARY KEY");
$r2 = q("ALTER TABLE `item_id` ADD `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST"); $r2 = q("ALTER TABLE `item_id` ADD `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST");
$r3 = q("ALTER TABLE `item_id` ADD INDEX ( `iid` ) "); $r3 = q("ALTER TABLE `item_id` ADD INDEX ( `iid` ) ");
if ($r1 && $r2 && $r3) { if($r1 && $r2 && $r3)
return UPDATE_SUCCESS; return UPDATE_SUCCESS;
}
return UPDATE_FAILED; return UPDATE_FAILED;
} }
@ -1430,13 +1367,10 @@ function update_1156() {
$r = q("ALTER TABLE `photo` ADD `datasize` INT UNSIGNED NOT NULL DEFAULT '0' AFTER `width` , $r = q("ALTER TABLE `photo` ADD `datasize` INT UNSIGNED NOT NULL DEFAULT '0' AFTER `width` ,
ADD INDEX ( `datasize` ) "); ADD INDEX ( `datasize` ) ");
if ($r) { if(!$r) return UPDATE_FAILED;
return UPDATE_SUCCESS; return UPDATE_SUCCESS;
} }
return UPDATE_FAILED;
}
function update_1157() { function update_1157() {
$r = q("CREATE TABLE IF NOT EXISTS `dsprphotoq` ( $r = q("CREATE TABLE IF NOT EXISTS `dsprphotoq` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT, `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
@ -1447,13 +1381,10 @@ function update_1157() {
) ENGINE=MyISAM DEFAULT CHARSET=utf8" ) ENGINE=MyISAM DEFAULT CHARSET=utf8"
); );
if ($r) { if($r)
return UPDATE_SUCCESS; return UPDATE_SUCCESS;
} }
return UPDATE_FAILED;
}
function update_1158() { function update_1158() {
set_config('system', 'maintenance', 1); set_config('system', 'maintenance', 1);
@ -1464,9 +1395,8 @@ function update_1158() {
$r = q("CREATE INDEX event_id ON item(`event-id`)"); $r = q("CREATE INDEX event_id ON item(`event-id`)");
set_config('system', 'maintenance', 0); set_config('system', 'maintenance', 0);
if ($r) { if($r)
return UPDATE_SUCCESS; return UPDATE_SUCCESS;
}
return UPDATE_FAILED; return UPDATE_FAILED;
} }
@ -1477,11 +1407,10 @@ function update_1159() {
ADD INDEX (`uid`), ADD INDEX (`uid`),
ADD INDEX (`aid`)"); ADD INDEX (`aid`)");
if ($r) { if(!$r)
return UPDATE_SUCCESS;
}
return UPDATE_FAILED; return UPDATE_FAILED;
return UPDATE_SUCCESS;
} }
function update_1160() { function update_1160() {
@ -1494,21 +1423,19 @@ function update_1160() {
$r = q("ALTER TABLE `item` ADD `mention` TINYINT(1) NOT NULL DEFAULT '0', ADD INDEX (`mention`)"); $r = q("ALTER TABLE `item` ADD `mention` TINYINT(1) NOT NULL DEFAULT '0', ADD INDEX (`mention`)");
set_config('system', 'maintenance', 0); set_config('system', 'maintenance', 0);
if ($r) { if(!$r)
return UPDATE_SUCCESS;
}
return UPDATE_FAILED; return UPDATE_FAILED;
return UPDATE_SUCCESS;
} }
function update_1161() { function update_1161() {
$r = q("ALTER TABLE `pconfig` ADD INDEX (`cat`)"); $r = q("ALTER TABLE `pconfig` ADD INDEX (`cat`)");
if ($r) { if(!$r)
return UPDATE_SUCCESS;
}
return UPDATE_FAILED; return UPDATE_FAILED;
return UPDATE_SUCCESS;
} }
function update_1162() { function update_1162() {
@ -1524,12 +1451,10 @@ function update_1163() {
$r = q("ALTER TABLE `item` ADD `network` char(32) NOT NULL"); $r = q("ALTER TABLE `item` ADD `network` char(32) NOT NULL");
set_config('system', 'maintenance', 0); set_config('system', 'maintenance', 0);
if(!$r)
if ($r) {
return UPDATE_SUCCESS;
}
return UPDATE_FAILED; return UPDATE_FAILED;
return UPDATE_SUCCESS;
} }
function update_1164() { function update_1164() {
set_config('system', 'maintenance', 1); set_config('system', 'maintenance', 1);
@ -1594,13 +1519,11 @@ function update_1165() {
`push` INT NOT NULL, `push` INT NOT NULL,
`last_update` DATETIME NOT NULL, `last_update` DATETIME NOT NULL,
`secret` CHAR( 255 ) NOT NULL `secret` CHAR( 255 ) NOT NULL
) DEFAULT CHARSET=utf8 "); ) ENGINE = MYISAM DEFAULT CHARSET=utf8 ");
if (!$r)
if ($r) {
return UPDATE_SUCCESS;
}
return UPDATE_FAILED; return UPDATE_FAILED;
return UPDATE_SUCCESS;
} }
function update_1166() { function update_1166() {
@ -1611,33 +1534,27 @@ function update_1166() {
`name` CHAR(255) NOT NULL, `name` CHAR(255) NOT NULL,
`avatar` CHAR(255) NOT NULL, `avatar` CHAR(255) NOT NULL,
INDEX (`url`) INDEX (`url`)
) DEFAULT CHARSET=utf8 "); ) ENGINE = MYISAM DEFAULT CHARSET=utf8 ");
if (!$r)
if ($r) {
return UPDATE_SUCCESS;
}
return UPDATE_FAILED; return UPDATE_FAILED;
return UPDATE_SUCCESS;
} }
function update_1167() { function update_1167() {
$r = q("ALTER TABLE `contact` ADD `notify_new_posts` TINYINT(1) NOT NULL DEFAULT '0'"); $r = q("ALTER TABLE `contact` ADD `notify_new_posts` TINYINT(1) NOT NULL DEFAULT '0'");
if (!$r)
if ($r) {
return UPDATE_SUCCESS;
}
return UPDATE_FAILED; return UPDATE_FAILED;
return UPDATE_SUCCESS;
} }
function update_1168() { function update_1168() {
$r = q("ALTER TABLE `contact` ADD `fetch_further_information` TINYINT(1) NOT NULL DEFAULT '0'"); $r = q("ALTER TABLE `contact` ADD `fetch_further_information` TINYINT(1) NOT NULL DEFAULT '0'");
if (!$r)
if ($r) {
return UPDATE_SUCCESS ;
}
return UPDATE_FAILED; return UPDATE_FAILED;
return UPDATE_SUCCESS;
} }
function update_1169() { function update_1169() {
@ -1675,10 +1592,8 @@ function update_1169() {
KEY `uid_created` (`uid`,`created`), KEY `uid_created` (`uid`,`created`),
KEY `uid_commented` (`uid`,`commented`) KEY `uid_commented` (`uid`,`commented`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;"); ) ENGINE=MyISAM DEFAULT CHARSET=utf8;");
if (!$r)
if (!$r) {
return UPDATE_FAILED; return UPDATE_FAILED;
}
proc_run(PRIORITY_LOW, "include/threadupdate.php"); proc_run(PRIORITY_LOW, "include/threadupdate.php");
@ -1784,22 +1699,19 @@ function update_1190() {
$key = $rr['k']; $key = $rr['k'];
$value = $rr['v']; $value = $rr['v'];
if ($key === 'randomise') { if ($key === 'randomise')
del_pconfig($uid,$family,$key); del_pconfig($uid,$family,$key);
}
if ($key === 'show_on_profile') { if ($key === 'show_on_profile') {
if ($value) { if ($value)
set_pconfig($uid,feature,forumlist_profile,$value); set_pconfig($uid,feature,forumlist_profile,$value);
}
del_pconfig($uid,$family,$key); del_pconfig($uid,$family,$key);
} }
if ($key === 'show_on_network') { if ($key === 'show_on_network') {
if ($value) { if ($value)
set_pconfig($uid,feature,forumlist_widget,$value); set_pconfig($uid,feature,forumlist_widget,$value);
}
del_pconfig($uid,$family,$key); del_pconfig($uid,$family,$key);
} }

View file

@ -43,24 +43,21 @@ function string_plural_select($n){
foreach($arr as $a) { foreach($arr as $a) {
if (is_array($a)){ if (is_array($a)){
if (substr($a[1],0,1) == '$') { if(substr($a[1],0,1) == '$')
continue; continue;
}
$s .= '$a->strings[' . $a[0] . "] = array(\n"; $s .= '$a->strings[' . $a[0] . "] = array(\n";
$s .= "\t0 => ". $a[0]. ",\n"; $s .= "\t0 => ". $a[0]. ",\n";
$s .= "\t1 => ". $a[1]. ",\n"; $s .= "\t1 => ". $a[1]. ",\n";
$s .= ");\n"; $s .= ");\n";
} else { } else {
if (substr($a,0,1) == '$') { if(substr($a,0,1) == '$')
continue; continue;
}
$s .= '$a->strings[' . $a . '] = '. $a . ';' . "\n"; $s .= '$a->strings[' . $a . '] = '. $a . ';' . "\n";
} }
} }
$zones = timezone_identifiers_list(); $zones = timezone_identifiers_list();
foreach ($zones as $zone) { foreach($zones as $zone)
$s .= '$a->strings[\'' . $zone . '\'] = \'' . $zone . '\';' . "\n"; $s .= '$a->strings[\'' . $zone . '\'] = \'' . $zone . '\';' . "\n";
}
echo $s; echo $s;

View file

@ -12,11 +12,10 @@ function po2php_run(&$argv, &$argc) {
$pofile = $argv[1]; $pofile = $argv[1];
$outfile = dirname($pofile)."/strings.php"; $outfile = dirname($pofile)."/strings.php";
if (strstr($outfile,'util')) { if(strstr($outfile,'util'))
$lang = 'en'; $lang = 'en';
} else { else
$lang = str_replace('-','_',basename(dirname($pofile))); $lang = str_replace('-','_',basename(dirname($pofile)));
}
@ -42,9 +41,7 @@ function po2php_run(&$argv, &$argc) {
foreach ($infile as $l) { foreach ($infile as $l) {
$l = str_replace('\"', DQ_ESCAPE, $l); $l = str_replace('\"', DQ_ESCAPE, $l);
$len = strlen($l); $len = strlen($l);
if ($l[0]=="#") { if ($l[0]=="#") $l="";
$l="";
}
if (substr($l,0,15)=='"Plural-Forms: '){ if (substr($l,0,15)=='"Plural-Forms: '){
$match=Array(); $match=Array();
preg_match("|nplurals=([0-9]*); *plural=(.*)[;\\\\]|", $l, $match); preg_match("|nplurals=([0-9]*); *plural=(.*)[;\\\\]|", $l, $match);
@ -57,15 +54,12 @@ function po2php_run(&$argv, &$argc) {
$out .= '}}'."\n"; $out .= '}}'."\n";
} }
if ($k!="" && substr($l,0,7)=="msgstr "){ if ($k!="" && substr($l,0,7)=="msgstr "){
if ($ink) { if ($ink) { $ink = False; $out .= '$a->strings["'.$k.'"] = '; }
$ink = False; if ($inv) { $inv = False; $out .= '"'.$v.'"'; }
$out .= '$a->strings["'.$k.'"] = ';
}
if ($inv) {
$inv = False;
$out .= '"'.$v.'"';
}
$v = substr($l,8,$len-10); $v = substr($l,8,$len-10);
$v = preg_replace_callback($escape_s_exp,'escape_s',$v); $v = preg_replace_callback($escape_s_exp,'escape_s',$v);
@ -73,14 +67,8 @@ function po2php_run(&$argv, &$argc) {
//$out .= $v; //$out .= $v;
} }
if ($k!="" && substr($l,0,7)=="msgstr["){ if ($k!="" && substr($l,0,7)=="msgstr["){
if ($ink) { if ($ink) { $ink = False; $out .= '$a->strings["'.$k.'"] = '; }
$ink = False; if ($inv) { $inv = False; $out .= '"'.$v.'"'; }
$out .= '$a->strings["'.$k.'"] = ';
}
if ($inv) {
$inv = False;
$out .= '"'.$v.'"';
}
if (!$arr) { if (!$arr) {
$arr=True; $arr=True;
@ -96,6 +84,7 @@ function po2php_run(&$argv, &$argc) {
if (substr($l,0,6)=="msgid_") { $ink = False; $out .= '$a->strings["'.$k.'"] = '; }; if (substr($l,0,6)=="msgid_") { $ink = False; $out .= '$a->strings["'.$k.'"] = '; };
if ($ink) { if ($ink) {
$k .= trim($l,"\"\r\n"); $k .= trim($l,"\"\r\n");
$k = preg_replace_callback($escape_s_exp,'escape_s',$k); $k = preg_replace_callback($escape_s_exp,'escape_s',$k);
@ -103,13 +92,8 @@ function po2php_run(&$argv, &$argc) {
} }
if (substr($l,0,6)=="msgid "){ if (substr($l,0,6)=="msgid "){
if ($inv) { if ($inv) { $inv = False; $out .= '"'.$v.'"'; }
$inv = False; if ($k!="") $out .= $arr?");\n":";\n";
$out .= '"'.$v.'"';
}
if ($k != "") {
$out .= $arr?");\n":";\n";
}
$arr=False; $arr=False;
$k = str_replace("msgid ","",$l); $k = str_replace("msgid ","",$l);
if ($k != '""' ) { if ($k != '""' ) {
@ -131,13 +115,8 @@ function po2php_run(&$argv, &$argc) {
} }
if ($inv) { if ($inv) { $inv = False; $out .= '"'.$v.'"'; }
$inv = False; if ($k!="") $out .= $arr?");\n":";\n";
$out .= '"'.$v.'"';
}
if ($k!="") {
$out .= $arr?");\n":";\n";
}
$out = str_replace(DQ_ESCAPE, '\"', $out); $out = str_replace(DQ_ESCAPE, '\"', $out);
file_put_contents($outfile, $out); file_put_contents($outfile, $out);

View file

@ -12,11 +12,11 @@ include 'boot.php';
$a = new App(); $a = new App();
if (x($a->config,'php_path')) { if(x($a->config,'php_path'))
$phpath = $a->config['php_path']; $phpath = $a->config['php_path'];
} else { else
$phpath = 'php'; $phpath = 'php';
}
echo "Directory: mod\n"; echo "Directory: mod\n";
$files = glob('mod/*.php'); $files = glob('mod/*.php');
@ -47,6 +47,7 @@ foreach ($dirs as $dir) {
} }
} }
echo "String files\n"; echo "String files\n";
echo 'util/strings.php' . "\n"; echo 'util/strings.php' . "\n";

0
view/smarty3/.gitignore vendored Normal file → Executable file
View file

View file

@ -5,29 +5,22 @@ function duepuntozero_init(App $a) {
set_template_engine($a, 'smarty3'); set_template_engine($a, 'smarty3');
$colorset = get_pconfig( local_user(), 'duepuntozero','colorset'); $colorset = get_pconfig( local_user(), 'duepuntozero','colorset');
if (!$colorset) { if (!$colorset)
$colorset = get_config('duepuntozero', 'colorset'); // user setting have priority, then node settings $colorset = get_config('duepuntozero', 'colorset'); // user setting have priority, then node settings
}
if ($colorset) { if ($colorset) {
if ($colorset == 'greenzero') { if ($colorset == 'greenzero')
$a->page['htmlhead'] .= '<link rel="stylesheet" href="view/theme/duepuntozero/deriv/greenzero.css" type="text/css" media="screen" />'."\n"; $a->page['htmlhead'] .= '<link rel="stylesheet" href="view/theme/duepuntozero/deriv/greenzero.css" type="text/css" media="screen" />'."\n";
} if ($colorset == 'purplezero')
if ($colorset == 'purplezero') {
$a->page['htmlhead'] .= '<link rel="stylesheet" href="view/theme/duepuntozero/deriv/purplezero.css" type="text/css" media="screen" />'."\n"; $a->page['htmlhead'] .= '<link rel="stylesheet" href="view/theme/duepuntozero/deriv/purplezero.css" type="text/css" media="screen" />'."\n";
} if ($colorset == 'easterbunny')
if ($colorset == 'easterbunny') {
$a->page['htmlhead'] .= '<link rel="stylesheet" href="view/theme/duepuntozero/deriv/easterbunny.css" type="text/css" media="screen" />'."\n"; $a->page['htmlhead'] .= '<link rel="stylesheet" href="view/theme/duepuntozero/deriv/easterbunny.css" type="text/css" media="screen" />'."\n";
} if ($colorset == 'darkzero')
if ($colorset == 'darkzero') {
$a->page['htmlhead'] .= '<link rel="stylesheet" href="view/theme/duepuntozero/deriv/darkzero.css" type="text/css" media="screen" />'."\n"; $a->page['htmlhead'] .= '<link rel="stylesheet" href="view/theme/duepuntozero/deriv/darkzero.css" type="text/css" media="screen" />'."\n";
} if ($colorset == 'comix')
if ($colorset == 'comix') {
$a->page['htmlhead'] .= '<link rel="stylesheet" href="view/theme/duepuntozero/deriv/comix.css" type="text/css" media="screen" />'."\n"; $a->page['htmlhead'] .= '<link rel="stylesheet" href="view/theme/duepuntozero/deriv/comix.css" type="text/css" media="screen" />'."\n";
} if ($colorset == 'slackr')
if ($colorset == 'slackr') {
$a->page['htmlhead'] .= '<link rel="stylesheet" href="view/theme/duepuntozero/deriv/slackr.css" type="text/css" media="screen" />'."\n"; $a->page['htmlhead'] .= '<link rel="stylesheet" href="view/theme/duepuntozero/deriv/slackr.css" type="text/css" media="screen" />'."\n";
} }
}
$a->page['htmlhead'] .= <<< EOT $a->page['htmlhead'] .= <<< EOT
<script> <script>
function insertFormatting(BBcode, id) { function insertFormatting(BBcode, id) {

View file

@ -9,7 +9,6 @@
/** /**
* A color utility that helps manipulate HEX colors * A color utility that helps manipulate HEX colors
* @todo convert space -> tab
*/ */
class Color { class Color {