Enforcing standards ahead of moving App to src

This commit is contained in:
Hypolite Petovan 2017-05-01 22:50:24 -04:00
parent 0747ce0e6e
commit 68c1939d12
13 changed files with 1292 additions and 1298 deletions

102
boot.php
View file

@ -26,14 +26,12 @@ define('NAMESPACE_DFRN', 'http://purl.org/macgirvin/dfrn/1.0');
/** /**
* log levels * log levels
*/ */
define('LOGGER_NORMAL', 0); define('LOGGER_NORMAL', 0);
define('LOGGER_TRACE', 1); define('LOGGER_TRACE', 1);
define('LOGGER_DEBUG', 2); define('LOGGER_DEBUG', 2);
define('LOGGER_DATA', 3); define('LOGGER_DATA', 3);
define('LOGGER_ALL', 4); define('LOGGER_ALL', 4);
class App class App
{ {
public $module_loaded = false; public $module_loaded = false;
@ -64,12 +62,10 @@ class App
{ {
$this->config = array(); $this->config = array();
$this->page = array(); $this->page = array();
$this->pager= array(); $this->pager = array();
$this->scheme = ((isset($_SERVER['HTTPS']) $this->scheme = ((isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'])) ? 'https' : 'http');
&& ($_SERVER['HTTPS'])) ? 'https' : 'http'); $this->hostname = str_replace('www.', '', $_SERVER['SERVER_NAME']);
$this->hostname = str_replace('www.', '',
$_SERVER['SERVER_NAME']);
set_include_path("include/$this->hostname" set_include_path("include/$this->hostname"
. PATH_SEPARATOR . 'include' . PATH_SEPARATOR . 'include'
. PATH_SEPARATOR . '.'); . PATH_SEPARATOR . '.');
@ -104,8 +100,7 @@ class App
} }
$this->baseurl = (($ssl) ? 'https' : $this->scheme) . "://" . $this->hostname $this->baseurl = (($ssl) ? 'https' : $this->scheme) . "://" . $this->hostname
. ((isset($this->path) && strlen($this->path)) . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '');
? '/' . $this->path : '');
return $this->baseurl; return $this->baseurl;
} }
@ -157,8 +152,7 @@ class App
} }
} }
if (!function_exists('x')) {
if (! function_exists('x')) {
function x($s, $k = null) function x($s, $k = null)
{ {
if ($k != null) { if ($k != null) {
@ -181,7 +175,7 @@ if (! function_exists('x')) {
} }
} }
if (! function_exists('system_unavailable')) { if (!function_exists('system_unavailable')) {
function system_unavailable() function system_unavailable()
{ {
include('system_unavailable.php'); include('system_unavailable.php');
@ -189,14 +183,14 @@ if (! function_exists('system_unavailable')) {
} }
} }
if (! function_exists('logger')) { if (!function_exists('logger')) {
function logger($msg, $level = 0) function logger($msg, $level = 0)
{ {
$debugging = 1; $debugging = 1;
$loglevel = LOGGER_ALL; $loglevel = LOGGER_ALL;
$logfile = 'logfile.out'; $logfile = 'logfile.out';
if ((! $debugging) || (! $logfile) || ($level > $loglevel)) { if ((!$debugging) || (!$logfile) || ($level > $loglevel)) {
return; return;
} }
require_once('include/datetime.php'); require_once('include/datetime.php');
@ -207,7 +201,7 @@ if (! function_exists('logger')) {
} }
if (! function_exists('replace_macros')) { if (!function_exists('replace_macros')) {
function replace_macros($s, $r) function replace_macros($s, $r)
{ {
$search = array(); $search = array();
@ -224,14 +218,14 @@ if (! function_exists('replace_macros')) {
} }
if (! function_exists('load_translation_table')) { if (!function_exists('load_translation_table')) {
function load_translation_table($lang) function load_translation_table($lang)
{ {
global $a; global $a;
} }
} }
if (! function_exists('t')) { if (!function_exists('t')) {
function t($s) function t($s)
{ {
global $a; global $a;
@ -243,14 +237,11 @@ if (! function_exists('t')) {
} }
} }
if (!function_exists('fetch_url')) {
function fetch_url($url, $binary = false, $timeout = 20)
if (! function_exists('fetch_url')) {
function fetch_url($url, $binary = false, $timeout=20)
{ {
$ch = curl_init($url); $ch = curl_init($url);
if (! $ch) { if (!$ch) {
return false; return false;
} }
@ -269,12 +260,11 @@ if (! function_exists('fetch_url')) {
} }
} }
if (!function_exists('post_url')) {
if (! function_exists('post_url')) {
function post_url($url, $params) function post_url($url, $params)
{ {
$ch = curl_init($url); $ch = curl_init($url);
if (! $ch) { if (!$ch) {
return false; return false;
} }
@ -290,15 +280,14 @@ if (! function_exists('post_url')) {
} }
} }
if (!function_exists('random_string')) {
if (! function_exists('random_string')) {
function random_string() function random_string()
{ {
return(hash('sha256', uniqid(rand(), true))); return(hash('sha256', uniqid(rand(), true)));
} }
} }
if (! function_exists('notags')) { if (!function_exists('notags')) {
function notags($string) function notags($string)
{ {
// protect against :<> with high-bit set // protect against :<> with high-bit set
@ -306,14 +295,14 @@ if (! function_exists('notags')) {
} }
} }
if (! function_exists('escape_tags')) { if (!function_exists('escape_tags')) {
function escape_tags($string) function escape_tags($string)
{ {
return(htmlspecialchars($string)); return(htmlspecialchars($string));
} }
} }
if (! function_exists('login')) { if (!function_exists('login')) {
function login($register = false) function login($register = false)
{ {
$o = ""; $o = "";
@ -325,14 +314,13 @@ if (! function_exists('login')) {
} else { } else {
$o = file_get_contents("view/login.tpl"); $o = file_get_contents("view/login.tpl");
$o = replace_macros($o, array('$register_html' => $register_html )); $o = replace_macros($o, array('$register_html' => $register_html));
} }
return $o; return $o;
} }
} }
if (!function_exists('killme')) {
if (! function_exists('killme')) {
function killme() function killme()
{ {
session_write_close(); session_write_close();
@ -341,7 +329,7 @@ if (! function_exists('killme')) {
} }
} }
if (! function_exists('goaway')) { if (!function_exists('goaway')) {
function goaway($s) function goaway($s)
{ {
header("Location: $s"); header("Location: $s");
@ -349,7 +337,7 @@ if (! function_exists('goaway')) {
} }
} }
if (! function_exists('local_user')) { if (!function_exists('local_user')) {
function local_user() function local_user()
{ {
if ((x($_SESSION, 'authenticated')) && (x($_SESSION, 'uid'))) { if ((x($_SESSION, 'authenticated')) && (x($_SESSION, 'uid'))) {
@ -359,7 +347,7 @@ if (! function_exists('local_user')) {
} }
} }
if (! function_exists('notice')) { if (!function_exists('notice')) {
function notice($s) function notice($s)
{ {
if (!isset($_SESSION['sysmsg'])) { if (!isset($_SESSION['sysmsg'])) {
@ -369,18 +357,14 @@ if (! function_exists('notice')) {
} }
} }
if (! function_exists('hex2bin')) { if (!function_exists('hex2bin')) {
function hex2bin($s) function hex2bin($s)
{ {
return(pack("H*", $s)); return(pack("H*", $s));
} }
} }
if (!function_exists('paginate')) {
if (! function_exists('paginate')) {
function paginate(&$a) function paginate(&$a)
{ {
$o = ''; $o = '';
@ -388,16 +372,15 @@ if (! function_exists('paginate')) {
$stripped = str_replace('q=', '', $stripped); $stripped = str_replace('q=', '', $stripped);
$stripped = trim($stripped, '/'); $stripped = trim($stripped, '/');
$pagenum = $a->pager['page']; $pagenum = $a->pager['page'];
$url = $a->get_baseurl() . '/' . $stripped ; $url = $a->get_baseurl() . '/' . $stripped;
if ($a->pager['total'] > $a->pager['itemspage']) { if ($a->pager['total'] > $a->pager['itemspage']) {
$o .= '<div class="pager">'; $o .= '<div class="pager">';
if ($a->pager['page'] != 1) { if ($a->pager['page'] != 1) {
$o .= '<span class="pager_prev">'."<a href=\"$url".'&page='.($a->pager['page'] - 1).'">' . t('prev') . '</a></span> '; $o .= '<span class="pager_prev">' . "<a href=\"$url" . '&page=' . ($a->pager['page'] - 1) . '">' . t('prev') . '</a></span> ';
} }
$o .= "<span class=\"pager_first\"><a href=\"$url"."&page=1\">" . t('first') . "</a></span> "; $o .= "<span class=\"pager_first\"><a href=\"$url" . "&page=1\">" . t('first') . "</a></span> ";
$numpages = $a->pager['total'] / $a->pager['itemspage']; $numpages = $a->pager['total'] / $a->pager['itemspage'];
@ -411,35 +394,34 @@ if (! function_exists('paginate')) {
for ($i = $numstart; $i <= $numstop; $i++) { for ($i = $numstart; $i <= $numstop; $i++) {
if ($i == $a->pager['page']) { if ($i == $a->pager['page']) {
$o .= '<span class="pager_current">'.(($i < 10) ? '&nbsp;'.$i : $i); $o .= '<span class="pager_current">' . (($i < 10) ? '&nbsp;' . $i : $i);
} else { } else {
$o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? '&nbsp;'.$i : $i)."</a>"; $o .= "<span class=\"pager_n\"><a href=\"$url" . "&page=$i\">" . (($i < 10) ? '&nbsp;' . $i : $i) . "</a>";
} }
$o .= '</span> '; $o .= '</span> ';
} }
if (($a->pager['total'] % $a->pager['itemspage']) != 0) { if (($a->pager['total'] % $a->pager['itemspage']) != 0) {
if ($i == $a->pager['page']) { if ($i == $a->pager['page']) {
$o .= '<span class="pager_current">'.(($i < 10) ? '&nbsp;'.$i : $i); $o .= '<span class="pager_current">' . (($i < 10) ? '&nbsp;' . $i : $i);
} else { } else {
$o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? '&nbsp;'.$i : $i)."</a>"; $o .= "<span class=\"pager_n\"><a href=\"$url" . "&page=$i\">" . (($i < 10) ? '&nbsp;' . $i : $i) . "</a>";
} }
$o .= '</span> '; $o .= '</span> ';
} }
$lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages); $lastpage = (($numpages > intval($numpages)) ? intval($numpages) + 1 : $numpages);
$o .= "<span class=\"pager_last\"><a href=\"$url"."&page=$lastpage\">" . t('last') . "</a></span> "; $o .= "<span class=\"pager_last\"><a href=\"$url" . "&page=$lastpage\">" . t('last') . "</a></span> ";
if (($a->pager['total'] - ($a->pager['itemspage'] * $a->pager['page'])) > 0) { if (($a->pager['total'] - ($a->pager['itemspage'] * $a->pager['page'])) > 0) {
$o .= '<span class="pager_next">'."<a href=\"$url"."&page=".($a->pager['page'] + 1).'">' . t('next') . '</a></span>'; $o .= '<span class="pager_next">' . "<a href=\"$url" . "&page=" . ($a->pager['page'] + 1) . '">' . t('next') . '</a></span>';
} }
$o .= '</div>'."\r\n"; $o .= '</div>' . "\r\n";
} }
return $o; return $o;
} }
} }
function get_my_url() function get_my_url()
{ {
if (x($_SESSION, 'my_url')) { if (x($_SESSION, 'my_url')) {
@ -450,10 +432,10 @@ function get_my_url()
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;
} }
$achar = strpos($s, '?') ? '&' : '?'; $achar = strpos($s, '?') ? '&' : '?';
@ -464,7 +446,7 @@ function zrl($s, $force = false)
return $s; return $s;
} }
if (! function_exists('link_compare')) { if (!function_exists('link_compare')) {
function link_compare($a, $b) function link_compare($a, $b)
{ {
if (strcasecmp(normalise_link($a), normalise_link($b)) === 0) { if (strcasecmp(normalise_link($a), normalise_link($b)) === 0) {
@ -474,7 +456,7 @@ if (! function_exists('link_compare')) {
} }
} }
if (! function_exists('normalise_link')) { if (!function_exists('normalise_link')) {
function normalise_link($url) function normalise_link($url)
{ {
$ret = str_replace(array('https:', '//www.'), array('http:', '//'), $url); $ret = str_replace(array('https:', '//www.'), array('http:', '//'), $url);

View file

@ -1,76 +1,87 @@
<?php <?php
// Debug stuff. // Debug stuff.
// ini_set('display_errors', 1); // ini_set('display_errors', 1);
// ini_set('log_errors','0'); // ini_set('log_errors','0');
error_reporting(E_ALL^E_NOTICE); error_reporting(E_ALL ^ E_NOTICE);
$start_maintain = time(); $start_maintain = time();
$verbose = $argv[1] === 'verbose'; $verbose = $argv[1] === 'verbose';
//Startup. //Startup.
require_once('boot.php'); require_once 'boot.php';
$a = new App;
//Config and DB. $a = new App;
require_once(".htconfig.php");
require_once("dba.php");
$db = new dba($db_host, $db_user, $db_pass, $db_data, $install);
//Get our set of items. Youngest items first, after the threshold. //Config and DB.
//This may be counter-intuitive, but is to prevent items that fail to update from blocking the rest. require_once '.htconfig.php';
$res = q( require_once 'dba.php';
"SELECT `id`, `homepage`, `censored` FROM `profile` WHERE `updated` < '%s' ORDER BY `updated` DESC LIMIT %u", $db = new dba($db_host, $db_user, $db_pass, $db_data, $install);
dbesc(date('Y-m-d H:i:s', time()-$a->config['maintenance']['min_scrape_delay'])),
//Get our set of items. Youngest items first, after the threshold.
//This may be counter-intuitive, but is to prevent items that fail to update from blocking the rest.
$res = q("SELECT `id`, `homepage`, `censored`
FROM `profile`
WHERE `updated` < '%s'
ORDER BY `updated` DESC
LIMIT %u",
dbesc(date('Y-m-d H:i:s', time() - $a->config['maintenance']['min_scrape_delay'])),
intval($a->config['maintenance']['max_scrapes']) intval($a->config['maintenance']['max_scrapes'])
); );
//Nothing to do. //Nothing to do.
if(!$res || !count($res)){ if (!$res || !count($res)) {
exit; exit;
} }
//Close DB here. Threads need their private connection. //Close DB here. Threads need their private connection.
$db->getdb()->close(); $db->getdb()->close();
//We need the scraper. //We need the scraper.
require_once('include/submit.php'); require_once 'include/submit.php';
//POSIX threads only. //POSIX threads only.
if(!function_exists('pcntl_fork')){ if (!function_exists('pcntl_fork')) {
logger('Error: no pcntl_fork support. Are you running a different OS? Report an issue please.'); logger('Error: no pcntl_fork support. Are you running a different OS? Report an issue please.');
die('Error: no pcntl_fork support. Are you running a different OS? Report an issue please.'); die('Error: no pcntl_fork support. Are you running a different OS? Report an issue please.');
} }
//Create the threads we need. //Create the threads we need.
$items = count($res); $items = count($res);
$threadc = min($a->config['maintenance']['threads'], $items); //Don't need more threads than items. $threadc = min($a->config['maintenance']['threads'], $items); //Don't need more threads than items.
$threads = array(); $threads = array();
//Debug... //Debug...
if($verbose) echo("Creating $threadc maintainer threads for $items profiles.".PHP_EOL); if ($verbose) {
logger("Creating $threadc maintainer threads for $items profiles."); echo "Creating $threadc maintainer threads for $items profiles." . PHP_EOL;
}
logger("Creating $threadc maintainer threads for $items profiles.");
for($i = 0; $i < $threadc; $i++){ for ($i = 0; $i < $threadc; $i++) {
$pid = pcntl_fork(); $pid = pcntl_fork();
if($pid === -1){ if ($pid === -1) {
if($verbose) echo('Error: something went wrong with the fork. '.pcntl_strerror()); if ($verbose) {
logger('Error: something went wrong with the fork. '.pcntl_strerror()); echo('Error: something went wrong with the fork. ' . pcntl_strerror());
die('Error: something went wrong with the fork. '.pcntl_strerror()); }
logger('Error: something went wrong with the fork. ' . pcntl_strerror());
die('Error: something went wrong with the fork. ' . pcntl_strerror());
} }
//You're a child, go do some labor! //You're a child, go do some labor!
if($pid === 0) break; if ($pid === 0) {
break;
//Store the list of PID's.
if($pid > 0) $threads[] = $pid;
} }
//The work for child processes. //Store the list of PID's.
if($pid === 0){ if ($pid > 0) {
$threads[] = $pid;
}
}
//The work for child processes.
if ($pid === 0) {
//Lets be nice, we're only doing maintenance here... //Lets be nice, we're only doing maintenance here...
pcntl_setpriority(5); pcntl_setpriority(5);
@ -79,36 +90,39 @@
$db = new dba($db_host, $db_user, $db_pass, $db_data, $install); $db = new dba($db_host, $db_user, $db_pass, $db_data, $install);
//Get our (round-robin) workload from the DB results. //Get our (round-robin) workload from the DB results.
$myIndex = $i+1; $myIndex = $i + 1;
$workload = array(); $workload = array();
while(isset($res[$i])){ while (isset($res[$i])) {
$entry = $res[$i]; $entry = $res[$i];
$workload[] = $entry; $workload[] = $entry;
$ids[] = $entry['id']; $ids[] = $entry['id'];
$i+=$threadc; $i += $threadc;
} }
while(count($workload)){ while (count($workload)) {
$entry = array_pop($workload); $entry = array_pop($workload);
set_time_limit(20); //This should work for 1 submit. set_time_limit(20); //This should work for 1 submit.
if($verbose) echo "Submitting ".$entry['homepage'].PHP_EOL; if ($verbose) {
echo "Submitting " . $entry['homepage'] . PHP_EOL;
}
run_submit($entry['homepage']); run_submit($entry['homepage']);
} }
exit; exit;
} else {
}
//The main process. //The main process.
else{ foreach ($threads as $pid) {
foreach($threads as $pid){
pcntl_waitpid($pid, $status); pcntl_waitpid($pid, $status);
if($status !== 0){ if ($status !== 0) {
if($verbose) echo "Bad process return value $pid:$status".PHP_EOL; if ($verbose) {
echo "Bad process return value $pid:$status" . PHP_EOL;
}
logger("Bad process return value $pid:$status"); logger("Bad process return value $pid:$status");
} }
} }
$time = time() - $start_maintain; $time = time() - $start_maintain;
if($verbose) echo("Maintenance completed. Took $time seconds.".PHP_EOL); if ($verbose) {
logger("Maintenance completed. Took $time seconds."); echo("Maintenance completed. Took $time seconds." . PHP_EOL);
} }
logger("Maintenance completed. Took $time seconds.");
}

View file

@ -38,39 +38,44 @@
* Decide if cron_sync.php should be split into push pull and pull-all commands. * Decide if cron_sync.php should be split into push pull and pull-all commands.
*/ */
// Debug stuff. // Debug stuff.
ini_set('display_errors', 1); ini_set('display_errors', 1);
ini_set('log_errors','0'); ini_set('log_errors', '0');
error_reporting(E_ALL^E_NOTICE); error_reporting(E_ALL ^ E_NOTICE);
$start_syncing = time(); $start_syncing = time();
//Startup. //Startup.
require_once('boot.php'); require_once 'boot.php';
$a = new App; $a = new App;
//Create a simple log function for CLI use. //Create a simple log function for CLI use.
global $verbose; global $verbose;
$verbose = $argv[1] === 'verbose'; $verbose = $argv[1] === 'verbose';
function msg($message, $fatal=false){ function msg($message, $fatal = false)
{
global $verbose; global $verbose;
if($verbose || $fatal) echo($message.PHP_EOL); if ($verbose || $fatal)
echo($message . PHP_EOL);
logger($message); logger($message);
if($fatal) exit(1); if ($fatal) {
}; exit(1);
}
}
//Config. //Config.
require_once(".htconfig.php"); require_once '.htconfig.php';
//Connect the DB. //Connect the DB.
require_once("dba.php"); require_once 'dba.php';
$db = new dba($db_host, $db_user, $db_pass, $db_data, $install); $db = new dba($db_host, $db_user, $db_pass, $db_data, $install);
//Import syncing functions. //Import syncing functions.
require_once('sync.php'); require_once 'sync.php';
//Get work for pulling. //Get work for pulling.
$pull_batch = get_pulling_job($a); $pull_batch = get_pulling_job($a);
@ -81,12 +86,14 @@ list($push_targets, $push_batch) = get_pushing_job($a);
//Close the connection for now. Process forking and DB connections are not the best of friends. //Close the connection for now. Process forking and DB connections are not the best of friends.
$db->getdb()->close(); $db->getdb()->close();
if(count($pull_batch)) if (count($pull_batch)) {
run_pulling_job($a, $pull_batch, $db_host, $db_user, $db_pass, $db_data, $install); run_pulling_job($a, $pull_batch, $db_host, $db_user, $db_pass, $db_data, $install);
}
//Do our multi-fork job, if we have a batch and targets. //Do our multi-fork job, if we have a batch and targets.
if(count($push_targets) && count($push_batch)) if (count($push_targets) && count($push_batch)) {
run_pushing_job($push_targets, $push_batch, $db_host, $db_user, $db_pass, $db_data, $install); run_pushing_job($push_targets, $push_batch, $db_host, $db_user, $db_pass, $db_data, $install);
}
//Log the time it took. //Log the time it took.
$time = time() - $start_syncing; $time = time() - $start_syncing;

View file

@ -1,27 +1,31 @@
<?php <?php
require_once("boot.php"); require_once 'boot.php';
$a = new App; $a = new App;
@include(".htconfig.php"); @include '.htconfig.php';
require_once("dba.php");
$db = new dba($db_host, $db_user, $db_pass, $db_data);
unset($db_host, $db_user, $db_pass, $db_data);
require_once 'dba.php';
if($argc != 2) $db = new dba($db_host, $db_user, $db_pass, $db_data);
unset($db_host, $db_user, $db_pass, $db_data);
if ($argc != 2) {
exit; exit;
}
load_config('system'); load_config('system');
$a->set_baseurl(get_config('system','url')); $a->set_baseurl(get_config('system', 'url'));
$dir = get_config('system','directory_submit_url'); $dir = get_config('system', 'directory_submit_url');
if(! strlen($dir)) if (!strlen($dir)) {
exit; exit;
}
fetch_url($dir . '?url=' . bin2hex($argv[1])); fetch_url($dir . '?url=' . bin2hex($argv[1]));
exit; exit;

View file

@ -1,87 +1,85 @@
<?php <?php
require_once 'boot.php';
require_once("boot.php"); $a = new App;
$a = new App; @include '.htconfig.php';
@include(".htconfig.php"); require_once 'dba.php';
require_once("dba.php");
$db = new dba($db_host, $db_user, $db_pass, $db_data);
unset($db_host, $db_user, $db_pass, $db_data);
require_once("session.php"); $db = new dba($db_host, $db_user, $db_pass, $db_data);
require_once("datetime.php");
if($argc < 3) unset($db_host, $db_user, $db_pass, $db_data);
require_once 'session.php';
require_once 'datetime.php';
if ($argc < 3) {
exit; exit;
}
$a->set_baseurl(get_config('system','url')); $a->set_baseurl(get_config('system', 'url'));
$cmd = $argv[1]; $cmd = $argv[1];
switch($cmd) { switch ($cmd) {
case 'mail': case 'mail':
default: default:
$item_id = intval($argv[2]); $item_id = intval($argv[2]);
if(! $item_id) if (!$item_id) {
killme(); killme();
break;
} }
break;
}
$recipients = array();
$recipients = array(); if ($cmd == 'mail') {
if($cmd == 'mail') { $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1", intval($item_id));
if (!count($message)) {
$message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
intval($item_id)
);
if(! count($message))
killme(); killme();
}
$recipients[] = $message[0]['contact-id']; $recipients[] = $message[0]['contact-id'];
$item = $message[0]; $item = $message[0];
} else {
}
else {
// find ancestors // find ancestors
$r = q("SELECT `parent`, `edited` FROM `item` WHERE `id` = %d LIMIT 1", $r = q("SELECT `parent`, `edited` FROM `item` WHERE `id` = %d LIMIT 1", intval($item_id));
intval($item_id) if (!count($r)) {
);
if(! count($r))
killme(); killme();
}
$parent = $r[0]['parent']; $parent = $r[0]['parent'];
$updated = $r[0]['edited']; $updated = $r[0]['edited'];
$items = q("SELECT * FROM `item` WHERE `parent` = %d ORDER BY `id` ASC", $items = q("SELECT * FROM `item` WHERE `parent` = %d ORDER BY `id` ASC", intval($parent));
intval($parent)
);
if(! count($items)) if (!count($items)) {
killme(); killme();
} }
}
$r = q("SELECT * FROM `contact` WHERE `self` = 1 LIMIT 1"); $r = q("SELECT * FROM `contact` WHERE `self` = 1 LIMIT 1");
if(count($r)) if (count($r)) {
$owner = $r[0]; $owner = $r[0];
else } else {
killme(); killme();
}
if($cmd != 'mail') { if ($cmd != 'mail') {
require_once('include/group.php'); require_once 'include/group.php';
$parent = $items[0]; $parent = $items[0];
if($parent['type'] == 'remote') { if ($parent['type'] == 'remote') {
// local followup to remote post // local followup to remote post
$followup = true; $followup = true;
$conversant_str = dbesc($parent['contact-id']); $conversant_str = dbesc($parent['contact-id']);
} } else {
else {
$followup = false; $followup = false;
$allow_people = expand_acl($parent['allow_cid']); $allow_people = expand_acl($parent['allow_cid']);
@ -91,102 +89,91 @@
$conversants = array(); $conversants = array();
foreach($items as $item) { foreach ($items as $item) {
$recipients[] = $item['contact-id']; $recipients[] = $item['contact-id'];
$conversants[] = $item['contact-id']; $conversants[] = $item['contact-id'];
} }
$conversants = array_unique($conversants,SORT_NUMERIC); $conversants = array_unique($conversants, SORT_NUMERIC);
$recipients = array_unique(array_merge($recipients, $allow_people, $allow_groups), SORT_NUMERIC);
$deny = array_unique(array_merge($deny_people, $deny_groups), SORT_NUMERIC);
$recipients = array_diff($recipients, $deny);
$recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups),SORT_NUMERIC); $conversant_str = dbesc(implode(', ', $conversants));
$deny = array_unique(array_merge($deny_people,$deny_groups),SORT_NUMERIC);
$recipients = array_diff($recipients,$deny);
$conversant_str = dbesc(implode(', ',$conversants));
} }
$r = q("SELECT * FROM `contact` WHERE `id` IN ( $conversant_str ) AND `blocked` = 0 AND `pending` = 0"); $r = q("SELECT * FROM `contact` WHERE `id` IN ( $conversant_str ) AND `blocked` = 0 AND `pending` = 0");
if( ! count($r)) if (!count($r)) {
killme(); killme();
}
$contacts = $r; $contacts = $r;
$tomb_template = file_get_contents('view/atom_tomb.tpl'); $tomb_template = file_get_contents('view/atom_tomb.tpl');
$item_template = file_get_contents('view/atom_item.tpl'); $item_template = file_get_contents('view/atom_item.tpl');
$cmnt_template = file_get_contents('view/atom_cmnt.tpl'); $cmnt_template = file_get_contents('view/atom_cmnt.tpl');
} }
$feed_template = file_get_contents('view/atom_feed.tpl'); $feed_template = file_get_contents('view/atom_feed.tpl');
$mail_template = file_get_contents('view/atom_mail.tpl'); $mail_template = file_get_contents('view/atom_mail.tpl');
$atom = ''; $atom = '';
$atom .= replace_macros($feed_template, array(
$atom .= replace_macros($feed_template, array(
'$feed_id' => xmlify($a->get_baseurl()), '$feed_id' => xmlify($a->get_baseurl()),
'$feed_title' => xmlify($owner['name']), '$feed_title' => xmlify($owner['name']),
'$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00', 'Y-m-d\TH:i:s\Z')),
$updated . '+00:00' , 'Y-m-d\TH:i:s\Z')) ,
'$name' => xmlify($owner['name']), '$name' => xmlify($owner['name']),
'$profile_page' => xmlify($owner['url']), '$profile_page' => xmlify($owner['url']),
'$photo' => xmlify($owner['photo']), '$photo' => xmlify($owner['photo']),
'$thumb' => xmlify($owner['thumb']), '$thumb' => xmlify($owner['thumb']),
'$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , 'Y-m-d\TH:i:s\Z')) , '$picdate' => xmlify(datetime_convert('UTC', 'UTC', $owner['avatar-date'] . '+00:00', 'Y-m-d\TH:i:s\Z')),
'$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , 'Y-m-d\TH:i:s\Z')) , '$uridate' => xmlify(datetime_convert('UTC', 'UTC', $owner['uri-date'] . '+00:00', 'Y-m-d\TH:i:s\Z')),
'$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , 'Y-m-d\TH:i:s\Z')) '$namdate' => xmlify(datetime_convert('UTC', 'UTC', $owner['name-date'] . '+00:00', 'Y-m-d\TH:i:s\Z'))
)); ));
if($cmd == 'mail') { if ($cmd == 'mail') {
$atom .= replace_macros($mail_template, array( $atom .= replace_macros($mail_template, array(
'$name' => xmlify($owner['name']), '$name' => xmlify($owner['name']),
'$profile_page' => xmlify($owner['url']), '$profile_page' => xmlify($owner['url']),
'$thumb' => xmlify($owner['thumb']), '$thumb' => xmlify($owner['thumb']),
'$item_id' => xmlify($item['uri']), '$item_id' => xmlify($item['uri']),
'$subject' => xmlify($item['title']), '$subject' => xmlify($item['title']),
'$created' => xmlify(datetime_convert('UTC', 'UTC', '$created' => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00', 'Y-m-d\TH:i:s\Z')),
$item['created'] . '+00:00' , 'Y-m-d\TH:i:s\Z')), '$content' => xmlify($item['body']),
'$content' =>xmlify($item['body']),
'$parent_id' => xmlify($item['parent-uri']) '$parent_id' => xmlify($item['parent-uri'])
)); ));
} } else {
else { if ($followup) {
foreach ($items as $item) {
if($followup) { if ($item['id'] == $item_id) {
foreach($items as $item) {
if($item['id'] == $item_id) {
$atom .= replace_macros($cmnt_template, array( $atom .= replace_macros($cmnt_template, array(
'$name' => xmlify($owner['name']), '$name' => xmlify($owner['name']),
'$profile_page' => xmlify($owner['url']), '$profile_page' => xmlify($owner['url']),
'$thumb' => xmlify($owner['thumb']), '$thumb' => xmlify($owner['thumb']),
'$item_id' => xmlify($item['uri']), '$item_id' => xmlify($item['uri']),
'$title' => xmlify($item['title']), '$title' => xmlify($item['title']),
'$published' => xmlify(datetime_convert('UTC', 'UTC', '$published' => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00', 'Y-m-d\TH:i:s\Z')),
$item['created'] . '+00:00' , 'Y-m-d\TH:i:s\Z')), '$updated' => xmlify(datetime_convert('UTC', 'UTC', $item['edited'] . '+00:00', 'Y-m-d\TH:i:s\Z')),
'$updated' => xmlify(datetime_convert('UTC', 'UTC', '$content' => xmlify($item['body']),
$item['edited'] . '+00:00' , 'Y-m-d\TH:i:s\Z')),
'$content' =>xmlify($item['body']),
'$parent_id' => xmlify($item['parent-uri']), '$parent_id' => xmlify($item['parent-uri']),
'$comment_allow' => 0 '$comment_allow' => 0
)); ));
} }
} }
} } else {
else { foreach ($items as $item) {
foreach($items as $item) { if ($item['deleted']) {
if($item['deleted']) {
$atom .= replace_macros($tomb_template, array( $atom .= replace_macros($tomb_template, array(
'$id' => xmlify($item['uri']), '$id' => xmlify($item['uri']),
'$updated' => xmlify(datetime_convert('UTC', 'UTC', '$updated' => xmlify(datetime_convert('UTC', 'UTC', $item['edited'] . '+00:00', 'Y-m-d\TH:i:s\Z'))
$item['edited'] . '+00:00' , 'Y-m-d\TH:i:s\Z'))
)); ));
} } else {
else { foreach ($contacts as $contact) {
foreach($contacts as $contact) { if ($item['contact-id'] == $contact['id']) {
if($item['contact-id'] == $contact['id']) { if ($item['parent'] == $item['id']) {
if($item['parent'] == $item['id']) {
$atom .= replace_macros($item_template, array( $atom .= replace_macros($item_template, array(
'$name' => xmlify($contact['name']), '$name' => xmlify($contact['name']),
'$profile_page' => xmlify($contact['url']), '$profile_page' => xmlify($contact['url']),
@ -196,26 +183,21 @@
'$owner_thumb' => xmlify($item['owner-avatar']), '$owner_thumb' => xmlify($item['owner-avatar']),
'$item_id' => xmlify($item['uri']), '$item_id' => xmlify($item['uri']),
'$title' => xmlify($item['title']), '$title' => xmlify($item['title']),
'$published' => xmlify(datetime_convert('UTC', 'UTC', '$published' => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00', 'Y-m-d\TH:i:s\Z')),
$item['created'] . '+00:00' , 'Y-m-d\TH:i:s\Z')), '$updated' => xmlify(datetime_convert('UTC', 'UTC', $item['edited'] . '+00:00', 'Y-m-d\TH:i:s\Z')),
'$updated' => xmlify(datetime_convert('UTC', 'UTC', '$content' => xmlify($item['body']),
$item['edited'] . '+00:00' , 'Y-m-d\TH:i:s\Z')),
'$content' =>xmlify($item['body']),
'$comment_allow' => (($item['last-child'] && strlen($contact['dfrn-id'])) ? 1 : 0) '$comment_allow' => (($item['last-child'] && strlen($contact['dfrn-id'])) ? 1 : 0)
)); ));
} } else {
else {
$atom .= replace_macros($cmnt_template, array( $atom .= replace_macros($cmnt_template, array(
'$name' => xmlify($contact['name']), '$name' => xmlify($contact['name']),
'$profile_page' => xmlify($contact['url']), '$profile_page' => xmlify($contact['url']),
'$thumb' => xmlify($contact['thumb']), '$thumb' => xmlify($contact['thumb']),
'$item_id' => xmlify($item['uri']), '$item_id' => xmlify($item['uri']),
'$title' => xmlify($item['title']), '$title' => xmlify($item['title']),
'$published' => xmlify(datetime_convert('UTC', 'UTC', '$published' => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00', 'Y-m-d\TH:i:s\Z')),
$item['created'] . '+00:00' , 'Y-m-d\TH:i:s\Z')), '$updated' => xmlify(datetime_convert('UTC', 'UTC', $item['edited'] . '+00:00', 'Y-m-d\TH:i:s\Z')),
'$updated' => xmlify(datetime_convert('UTC', 'UTC', '$content' => xmlify($item['body']),
$item['edited'] . '+00:00' , 'Y-m-d\TH:i:s\Z')),
'$content' =>xmlify($item['body']),
'$parent_id' => xmlify($item['parent-uri']), '$parent_id' => xmlify($item['parent-uri']),
'$comment_allow' => (($item['last-child']) ? 1 : 0) '$comment_allow' => (($item['last-child']) ? 1 : 0)
)); ));
@ -225,54 +207,57 @@
} }
} }
} }
} }
$atom .= "</feed>\r\n"; $atom .= "</feed>\r\n";
// create a clone of this feed but with comments disabled to send to those who can't respond. // create a clone of this feed but with comments disabled to send to those who can't respond.
$atom_nowrite = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom); $atom_nowrite = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
if($followup) if ($followup) {
$recip_str = $parent['contact-id']; $recip_str = $parent['contact-id'];
else } else {
$recip_str = implode(', ', $recipients); $recip_str = implode(', ', $recipients);
}
$r = q("SELECT * FROM `contact` WHERE `id` IN ( %s ) ", $r = q("SELECT * FROM `contact` WHERE `id` IN ( %s ) ", dbesc($recip_str));
dbesc($recip_str) if (!count($r)) {
);
if(! count($r))
killme(); killme();
}
// delivery loop // delivery loop
foreach($r as $rr) { foreach ($r as $rr) {
if($rr['self']) if ($rr['self']) {
continue; continue;
}
if(! strlen($rr['dfrn-id'])) if (!strlen($rr['dfrn-id'])) {
continue; continue;
}
$url = $rr['notify'] . '?dfrn_id=' . $rr['dfrn-id']; $url = $rr['notify'] . '?dfrn_id=' . $rr['dfrn-id'];
$xml = fetch_url($url); $xml = fetch_url($url);
if(! $xml) if (!$xml) {
continue; continue;
}
$res = simplexml_load_string($xml); $res = simplexml_load_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))) {
continue; continue;
}
$postvars = array(); $postvars = array();
$sent_dfrn_id = hex2bin($res->dfrn_id); $sent_dfrn_id = hex2bin($res->dfrn_id);
$final_dfrn_id = ''; $final_dfrn_id = '';
openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$rr['pubkey']); openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $rr['pubkey']);
$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($final_dfrn_id != $rr['dfrn-id']) { if ($final_dfrn_id != $rr['dfrn-id']) {
// did not decode properly - cannot trust this site // did not decode properly - cannot trust this site
continue; continue;
} }
@ -281,31 +266,26 @@
$challenge = hex2bin($res->challenge); $challenge = hex2bin($res->challenge);
openssl_public_decrypt($challenge,$postvars['challenge'],$rr['pubkey']); openssl_public_decrypt($challenge, $postvars['challenge'], $rr['pubkey']);
if($cmd == 'mail') { if ($cmd == 'mail') {
$postvars['data'] = $atom; $postvars['data'] = $atom;
} } elseif (strlen($rr['dfrn-id']) && (!($rr['blocked']) || ($rr['readonly']))) {
elseif(strlen($rr['dfrn-id']) && (! ($rr['blocked']) || ($rr['readonly']))) {
$postvars['data'] = $atom; $postvars['data'] = $atom;
} } else {
else {
$postvars['data'] = $atom_nowrite; $postvars['data'] = $atom_nowrite;
} }
$xml = post_url($rr['notify'],$postvars); $xml = post_url($rr['notify'], $postvars);
$res = simplexml_load_string($xml); $res = simplexml_load_string($xml);
// Currently there is no retry attempt for failed mail delivery. // Currently there is no retry attempt for failed mail delivery.
// We need to handle this in the UI, report the non-deliverables and try again // We need to handle this in the UI, report the non-deliverables and try again
if(($cmd == 'mail') && (intval($res->status) == 0)) { if (($cmd == 'mail') && (intval($res->status) == 0)) {
$r = q("UPDATE `mail` SET `delivered` = 1 WHERE `id` = %d LIMIT 1", intval($item_id));
$r = q("UPDATE `mail` SET `delivered` = 1 WHERE `id` = %d LIMIT 1",
intval($item_id)
);
}
} }
}
killme(); killme();

View file

@ -1,93 +1,95 @@
<?php <?php
require_once 'boot.php';
require_once('boot.php'); $a = new App;
$a = new App; @include('.htconfig.php');
@include('.htconfig.php'); require_once 'dba.php';
require_once('dba.php');
$db = new dba($db_host, $db_user, $db_pass, $db_data);
unset($db_host, $db_user, $db_pass, $db_data);
require_once('session.php'); $db = new dba($db_host, $db_user, $db_pass, $db_data);
require_once('datetime.php');
require_once('simplepie/simplepie.inc');
require_once('include/items.php');
$a->set_baseurl(get_config('system','url')); unset($db_host, $db_user, $db_pass, $db_data);
$contacts = q("SELECT * FROM `contact` require_once 'session.php';
require_once 'datetime.php';
require_once 'simplepie/simplepie.inc';
require_once 'include/items.php';
$a->set_baseurl(get_config('system', 'url'));
$contacts = q("SELECT * FROM `contact`
WHERE `dfrn-id` != '' AND `self` = 0 AND `blocked` = 0 WHERE `dfrn-id` != '' AND `self` = 0 AND `blocked` = 0
AND `readonly` = 0 ORDER BY RAND()"); AND `readonly` = 0 ORDER BY RAND()");
if(! count($contacts)) if (!count($contacts)) {
killme(); killme();
}
foreach($contacts as $contact) { foreach ($contacts as $contact) {
if ($contact['priority']) {
if($contact['priority']) {
$update = false; $update = false;
$t = $contact['last-update']; $t = $contact['last-update'];
switch ($contact['priority']) { switch ($contact['priority']) {
case 5: case 5:
if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', t . " + 1 month")) if (datetime_convert('UTC', 'UTC', 'now') > datetime_convert('UTC', 'UTC', t . " + 1 month"))
$update = true; $update = true;
break; break;
case 4: case 4:
if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', t . " + 1 week")) if (datetime_convert('UTC', 'UTC', 'now') > datetime_convert('UTC', 'UTC', t . " + 1 week"))
$update = true; $update = true;
break; break;
case 3: case 3:
if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', t . " + 1 day")) if (datetime_convert('UTC', 'UTC', 'now') > datetime_convert('UTC', 'UTC', t . " + 1 day"))
$update = true; $update = true;
break; break;
case 2: case 2:
if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', t . " + 12 hour")) if (datetime_convert('UTC', 'UTC', 'now') > datetime_convert('UTC', 'UTC', t . " + 12 hour"))
$update = true; $update = true;
break; break;
case 1: case 1:
default: default:
if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', t . " + 1 hour")) if (datetime_convert('UTC', 'UTC', 'now') > datetime_convert('UTC', 'UTC', t . " + 1 hour"))
$update = true; $update = true;
break; break;
} }
if(! $update) if (!$update) {
continue;
}
}
$r = q("SELECT * FROM `contact` WHERE `self` = 1 LIMIT 1");
if (!count($r)) {
continue; continue;
} }
$r = q("SELECT * FROM `contact` WHERE `self` = 1 LIMIT 1");
if(! count($r))
continue;
$importer = $r[0]; $importer = $r[0];
$last_update = (($contact['last-update'] == '0000-00-00 00:00:00') $last_update = (($contact['last-update'] == '0000-00-00 00:00:00') ? datetime_convert('UTC', 'UTC', 'now - 30 days', 'Y-m-d\TH:i:s\Z') : datetime_convert('UTC', 'UTC', $contact['last-update'], 'Y-m-d\TH:i:s\Z'));
? datetime_convert('UTC','UTC','now - 30 days','Y-m-d\TH:i:s\Z')
: datetime_convert('UTC','UTC',$contact['last-update'],'Y-m-d\TH:i:s\Z'));
$url = $contact['poll'] . '?dfrn_id=' . $contact['dfrn-id'] . '&type=data&last_update=' . $last_update ; $url = $contact['poll'] . '?dfrn_id=' . $contact['dfrn-id'] . '&type=data&last_update=' . $last_update;
$xml = fetch_url($url); $xml = fetch_url($url);
if(! $xml) if (!$xml) {
continue; continue;
}
$res = simplexml_load_string($xml); $res = simplexml_load_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))) {
continue; continue;
}
$postvars = array(); $postvars = array();
$sent_dfrn_id = hex2bin($res->dfrn_id); $sent_dfrn_id = hex2bin($res->dfrn_id);
$final_dfrn_id = ''; $final_dfrn_id = '';
openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']); openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
$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($final_dfrn_id != $contact['dfrn-id']) { if ($final_dfrn_id != $contact['dfrn-id']) {
// did not decode properly - cannot trust this site // did not decode properly - cannot trust this site
continue; continue;
} }
@ -95,13 +97,14 @@
$postvars['dfrn_id'] = $contact['dfrn-id']; $postvars['dfrn_id'] = $contact['dfrn-id'];
$challenge = hex2bin($res->challenge); $challenge = hex2bin($res->challenge);
openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']); openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
$xml = post_url($contact['poll'],$postvars); $xml = post_url($contact['poll'], $postvars);
if(! strlen($xml)) { if (!strlen($xml)) {
// an empty response may mean there's nothing new - record the fact that we checked // an empty response may mean there's nothing new - record the fact that we checked
$r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1", $r = q(
"UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
dbesc(datetime_convert()), dbesc(datetime_convert()),
intval($contact['id']) intval($contact['id'])
); );
@ -113,24 +116,25 @@
$feed->enable_order_by_date(false); $feed->enable_order_by_date(false);
$feed->init(); $feed->init();
$photo_rawupdate = $feed->get_feed_tags(NAMESPACE_DFRN,'icon-updated'); $photo_rawupdate = $feed->get_feed_tags(NAMESPACE_DFRN, 'icon-updated');
if($photo_rawupdate) {
$photo_timestamp = datetime_convert('UTC','UTC',$photo_rawupdate[0]['data']);
$photo_url = $feed->get_image_url();
if(strlen($photo_url) && $photo_timestamp > $contact['avatar-date']) {
require_once("Photo.php"); if ($photo_rawupdate) {
$photo_timestamp = datetime_convert('UTC', 'UTC', $photo_rawupdate[0]['data']);
$photo_url = $feed->get_image_url();
if (strlen($photo_url) && $photo_timestamp > $contact['avatar-date']) {
require_once 'Photo.php';
$photo_failure = false; $photo_failure = false;
$r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d LIMIT 1", $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d LIMIT 1", intval($contact['id']));
intval($contact['id'])
); if (count($r)) {
if(count($r)) {
$resource_id = $r[0]['resource-id']; $resource_id = $r[0]['resource-id'];
$img_str = fetch_url($photo_url,true); $img_str = fetch_url($photo_url, true);
$img = new Photo($img_str); $img = new Photo($img_str);
if($img) {
if ($img) {
q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND contact-id` = %d ", q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND contact-id` = %d ",
dbesc($resource_id), dbesc($resource_id),
intval($contact['id']) intval($contact['id'])
@ -140,11 +144,11 @@
$hash = $resource_id; $hash = $resource_id;
$r = $img->store($contact['id'], $hash, basename($photo_url), t('Contact Photos') , 4); $r = $img->store($contact['id'], $hash, basename($photo_url), t('Contact Photos'), 4);
$img->scaleImage(80); $img->scaleImage(80);
$r = $img->store($contact['id'], $hash, basename($photo_url), t('Contact Photos') , 5); $r = $img->store($contact['id'], $hash, basename($photo_url), t('Contact Photos'), 5);
if($r) if ($r) {
q("UPDATE `contact` SET `avatar-date` = '%s' WHERE `id` = %d LIMIT 1", q("UPDATE `contact` SET `avatar-date` = '%s' WHERE `id` = %d LIMIT 1",
dbesc(datetime_convert()), dbesc(datetime_convert()),
intval($contact['id']) intval($contact['id'])
@ -153,37 +157,36 @@
} }
} }
} }
}
foreach ($feed->get_items() as $item) {
foreach($feed->get_items() as $item) {
$deleted = false; $deleted = false;
$rawdelete = $item->get_item_tags("http://purl.org/atompub/tombstones/1.0", 'deleted-entry'); $rawdelete = $item->get_item_tags("http://purl.org/atompub/tombstones/1.0", 'deleted-entry');
if(isset($rawdelete[0]['attribs']['']['ref'])) {
if (isset($rawdelete[0]['attribs']['']['ref'])) {
$uri = $rawthread[0]['attribs']['']['ref']; $uri = $rawthread[0]['attribs']['']['ref'];
$deleted = true; $deleted = true;
if(isset($rawdelete[0]['attribs']['']['when'])) {
if (isset($rawdelete[0]['attribs']['']['when'])) {
$when = $rawthread[0]['attribs']['']['when']; $when = $rawthread[0]['attribs']['']['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 {
$when = datetime_convert('UTC', 'UTC', 'now', 'Y-m-d H:i:s');
} }
else
$when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
} }
if($deleted) {
$r = q("SELECT * FROM `item` WHERE `uri` = '%s' LIMIT 1", if ($deleted) {
dbesc($uri) $r = q("SELECT * FROM `item` WHERE `uri` = '%s' LIMIT 1", dbesc($uri));
); if (count($r)) {
if(count($r)) { if ($r[0]['uri'] == $r[0]['parent-uri']) {
if($r[0]['uri'] == $r[0]['parent-uri']) {
$r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s',
`body` = '', `title` = '' `body` = '', `title` = ''
WHERE `parent-uri` = '%s'", WHERE `parent-uri` = '%s'",
dbesc($when), dbesc($when),
dbesc($r[0]['uri']) dbesc($r[0]['uri'])
); );
} } else {
else {
$r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s',
`body` = '', `title` = '' `body` = '', `title` = ''
WHERE `uri` = '%s' LIMIT 1", WHERE `uri` = '%s' LIMIT 1",
@ -195,29 +198,25 @@
continue; continue;
} }
$is_reply = false; $is_reply = false;
$item_id = $item->get_id(); $item_id = $item->get_id();
$rawthread = $item->get_item_tags("http://purl.org/syndication/thread/1.0",'in-reply-to'); $rawthread = $item->get_item_tags("http://purl.org/syndication/thread/1.0", 'in-reply-to');
if(isset($rawthread[0]['attribs']['']['ref'])) {
if (isset($rawthread[0]['attribs']['']['ref'])) {
$is_reply = true; $is_reply = true;
$parent_uri = $rawthread[0]['attribs']['']['ref']; $parent_uri = $rawthread[0]['attribs']['']['ref'];
} }
if ($is_reply) {
if($is_reply) {
// Have we seen it? If not, import it. // Have we seen it? If not, import it.
$item_id = $item->get_id(); $item_id = $item->get_id();
$r = q("SELECT `last-child`, `edited` FROM `item` WHERE `uri` = '%s' LIMIT 1", $r = q("SELECT `last-child`, `edited` FROM `item` WHERE `uri` = '%s' LIMIT 1", dbesc($item_id));
dbesc($item_id)
);
// FIXME update content if 'updated' changes // FIXME update content if 'updated' changes
if(count($r)) { if (count($r)) {
$allow = $item->get_item_tags( NAMESPACE_DFRN , 'comment-allow'); $allow = $item->get_item_tags(NAMESPACE_DFRN, 'comment-allow');
if($allow && $allow[0]['data'] != $r[0]['last-child']) { if ($allow && $allow[0]['data'] != $r[0]['last-child']) {
$r = q("UPDATE `item` SET `last-child` = %d WHERE `uri` = '%s' LIMIT 1", $r = q("UPDATE `item` SET `last-child` = %d WHERE `uri` = '%s' LIMIT 1",
intval($allow[0]['data']), intval($allow[0]['data']),
dbesc($item_id) dbesc($item_id)
@ -225,23 +224,22 @@
} }
continue; continue;
} }
$datarray = get_atom_elements($item); $datarray = get_atom_elements($item);
$datarray['parent-uri'] = $parent_uri; $datarray['parent-uri'] = $parent_uri;
$datarray['contact-id'] = $contact['id']; $datarray['contact-id'] = $contact['id'];
$r = post_remote($a,$datarray); $r = post_remote($a, $datarray);
continue;
}
else { continue;
} else {
// Head post of a conversation. Have we seen it? If not, import it. // Head post of a conversation. Have we seen it? If not, import it.
$item_id = $item->get_id(); $item_id = $item->get_id();
$r = q("SELECT `last-child`, `edited` FROM `item` WHERE `uri` = '%s' LIMIT 1", $r = q("SELECT `last-child`, `edited` FROM `item` WHERE `uri` = '%s' LIMIT 1", dbesc($item_id));
dbesc($item_id)
); if (count($r)) {
if(count($r)) { $allow = $item->get_item_tags(NAMESPACE_DFRN, 'comment-allow');
$allow = $item->get_item_tags( NAMESPACE_DFRN ,'comment-allow'); if ($allow && $allow[0]['data'] != $r[0]['last-child']) {
if($allow && $allow[0]['data'] != $r[0]['last-child']) {
$r = q("UPDATE `item` SET `last-child` = %d WHERE `uri` = '%s' LIMIT 1", $r = q("UPDATE `item` SET `last-child` = %d WHERE `uri` = '%s' LIMIT 1",
intval($allow[0]['data']), intval($allow[0]['data']),
dbesc($item_id) dbesc($item_id)
@ -253,18 +251,16 @@
$datarray = get_atom_elements($item); $datarray = get_atom_elements($item);
$datarray['parent-uri'] = $item_id; $datarray['parent-uri'] = $item_id;
$datarray['contact-id'] = $contact['id']; $datarray['contact-id'] = $contact['id'];
$r = post_remote($a,$datarray); $r = post_remote($a, $datarray);
continue; continue;
} }
} }
$r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1", $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
dbesc(datetime_convert()), dbesc(datetime_convert()),
intval($contact['id']) intval($contact['id'])
); );
}
} killme();
killme();

View file

@ -1,36 +1,39 @@
<?php <?php
require_once("boot.php"); require_once 'boot.php';
$a = new App; $a = new App;
@include(".htconfig.php"); @include(".htconfig.php");
require_once("dba.php"); require_once 'dba.php';
$db = new dba($db_host, $db_user, $db_pass, $db_data, $install);
unset($db_host, $db_user, $db_pass, $db_data);
require_once("session.php"); $db = new dba($db_host, $db_user, $db_pass, $db_data, $install);
require_once("datetime.php");
$a->set_baseurl(get_config('system','url')); unset($db_host, $db_user, $db_pass, $db_data);
$u = q("SELECT * FROM `user` WHERE 1 LIMIT 1"); require_once 'session.php';
if(! count($u)) require_once 'datetime.php';
$a->set_baseurl(get_config('system', 'url'));
$u = q("SELECT * FROM `user` WHERE 1 LIMIT 1");
if (!count($u)) {
killme(); killme();
}
$uid = $u[0]['uid']; $uid = $u[0]['uid'];
$nickname = $u[0]['nickname']; $nickname = $u[0]['nickname'];
$intros = q("SELECT `intro`.*, `intro`.`id` AS `intro_id`, `contact`.* $intros = q("SELECT `intro`.*, `intro`.`id` AS `intro_id`, `contact`.*
FROM `intro` LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id` FROM `intro` LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
WHERE `intro`.`blocked` = 0 AND `intro`.`ignore` = 0"); WHERE `intro`.`blocked` = 0 AND `intro`.`ignore` = 0");
if(! count($intros)) if (!count($intros)) {
return; return;
}
foreach ($intros as $intro) {
foreach($intros as $intro) {
$intro_id = intval($intro['intro_id']); $intro_id = intval($intro['intro_id']);
$dfrn_id = $intro['issued-id']; $dfrn_id = $intro['issued-id'];
@ -40,10 +43,10 @@
$dfrn_confirm = $intro['confirm']; $dfrn_confirm = $intro['confirm'];
$aes_allow = $intro['aes_allow']; $aes_allow = $intro['aes_allow'];
$res=openssl_pkey_new(array( $res = openssl_pkey_new(array(
'digest_alg' => 'whirlpool', 'digest_alg' => 'whirlpool',
'private_key_bits' => 4096, 'private_key_bits' => 4096,
'encrypt_key' => false )); 'encrypt_key' => false));
$private_key = ''; $private_key = '';
@ -63,30 +66,29 @@
$src_aes_key = random_string(); $src_aes_key = random_string();
$result = ""; $result = "";
openssl_private_encrypt($dfrn_id,$result,$u[0]['prvkey']); openssl_private_encrypt($dfrn_id, $result, $u[0]['prvkey']);
$params['dfrn_id'] = $result; $params['dfrn_id'] = $result;
$params['public_key'] = $public_key; $params['public_key'] = $public_key;
$my_url = $a->get_baseurl() . '/profile/' . $nickname ; $my_url = $a->get_baseurl() . '/profile/' . $nickname;
openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey); openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
if($aes_allow && function_exists('openssl_encrypt')) { if ($aes_allow && function_exists('openssl_encrypt')) {
openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey); openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
$params['public_key'] = openssl_encrypt($public_key,'AES-256-CBC',$src_aes_key); $params['public_key'] = openssl_encrypt($public_key, 'AES-256-CBC', $src_aes_key);
} }
$res = post_url($dfrn_confirm,$params); $res = post_url($dfrn_confirm, $params);
$xml = simplexml_load_string($res); $xml = simplexml_load_string($res);
$status = (int) $xml->status; $status = (int) $xml->status;
switch($status) { switch ($status) {
case 0: case 0:
break; break;
case 1: case 1:
// birthday paradox - generate new dfrn-id and fall through. // birthday paradox - generate new dfrn-id and fall through.
$new_dfrn_id = random_string(); $new_dfrn_id = random_string();
$r = q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d LIMIT 1", $r = q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d LIMIT 1",
dbesc($new_dfrn_id), dbesc($new_dfrn_id),
@ -100,48 +102,47 @@
break; break;
} }
if(($status == 0 || $status == 3) && ($intro_id)) { if (($status == 0 || $status == 3) && ($intro_id)) {
// delete the notification // delete the notification
$r = q("DELETE FROM `intro` WHERE `id` = %d LIMIT 1", intval($intro_id));
$r = q("DELETE FROM `intro` WHERE `id` = %d LIMIT 1",
intval($intro_id)
);
} }
if($status != 0)
killme();
require_once("Photo.php"); if ($status != 0) {
killme();
}
require_once 'Photo.php';
$photo_failure = false; $photo_failure = false;
$filename = basename($intro['photo']); $filename = basename($intro['photo']);
$img_str = fetch_url($intro['photo'],true); $img_str = fetch_url($intro['photo'], true);
$img = new Photo($img_str); $img = new Photo($img_str);
if($img) {
if ($img) {
$img->scaleImageSquare(175); $img->scaleImageSquare(175);
$hash = hash('md5',uniqid(mt_rand(),true)); $hash = hash('md5', uniqid(mt_rand(), true));
$r = $img->store($contact_id, $hash, $filename, t('Contact Photos'), 4 ); $r = $img->store($contact_id, $hash, $filename, t('Contact Photos'), 4);
if($r === false) if ($r === false) {
$photo_failure = true; $photo_failure = true;
}
$img->scaleImage(80); $img->scaleImage(80);
$r = $img->store($contact_id, $hash, $filename, t('Contact Photos'), 5 ); $r = $img->store($contact_id, $hash, $filename, t('Contact Photos'), 5);
if($r === false) if ($r === false) {
$photo_failure = true; $photo_failure = true;
}
$photo = $a->get_baseurl() . '/photo/' . $hash . '-4.jpg'; $photo = $a->get_baseurl() . '/photo/' . $hash . '-4.jpg';
$thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.jpg'; $thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.jpg';
} } else {
else
$photo_failure = true; $photo_failure = true;
}
if($photo_failure) { if ($photo_failure) {
$photo = $a->get_baseurl() . '/images/default-profile.jpg'; $photo = $a->get_baseurl() . '/images/default-profile.jpg';
$thumb = $a->get_baseurl() . '/images/default-profile-sm.jpg'; $thumb = $a->get_baseurl() . '/images/default-profile-sm.jpg';
} }
@ -156,10 +157,9 @@
dbesc(datetime_convert()), dbesc(datetime_convert()),
dbesc(datetime_convert()), dbesc(datetime_convert()),
dbesc(datetime_convert()), dbesc(datetime_convert()),
intval((x($a->config,'rockstar-readonly')) ? $a->config['rockstar-readonly'] : 0), intval((x($a->config, 'rockstar-readonly')) ? $a->config['rockstar-readonly'] : 0),
intval((x($a->config,'rockstar-profile')) ? $a->config['rockstar-profile'] : 0), intval((x($a->config, 'rockstar-profile')) ? $a->config['rockstar-profile'] : 0),
intval($contact_id) intval($contact_id)
); );
}
} killme();
killme();

View file

@ -7,14 +7,12 @@
*/ */
function sync_pull($url) function sync_pull($url)
{ {
global $a; global $a;
//If we support it that is. //If we support it that is.
if($a->config['syncing']['enable_pulling']){ if ($a->config['syncing']['enable_pulling']) {
q("INSERT INTO `sync-pull-queue` (`url`) VALUES ('%s')", dbesc($url)); q("INSERT INTO `sync-pull-queue` (`url`) VALUES ('%s')", dbesc($url));
} }
} }
/** /**
@ -24,16 +22,14 @@ function sync_pull($url)
*/ */
function sync_push($url) function sync_push($url)
{ {
global $a; global $a;
//If we support it that is. //If we support it that is.
if($a->config['syncing']['enable_pushing']){ if ($a->config['syncing']['enable_pushing']) {
q("INSERT INTO `sync-push-queue` (`url`) VALUES ('%s')", dbesc($url)); q("INSERT INTO `sync-push-queue` (`url`) VALUES ('%s')", dbesc($url));
} }
sync_mark($url); sync_mark($url);
} }
/** /**
@ -44,21 +40,20 @@ function sync_push($url)
*/ */
function sync_mark($url) function sync_mark($url)
{ {
global $a; global $a;
//If we support it that is. //If we support it that is.
if(!$a->config['syncing']['enable_pulling']){ if (!$a->config['syncing']['enable_pulling']) {
return; return;
} }
$exists = count(q("SELECT * FROM `sync-timestamps` WHERE `url`='%s'", dbesc($url))); $exists = count(q("SELECT * FROM `sync-timestamps` WHERE `url`='%s'", dbesc($url)));
if(!$exists) if (!$exists) {
q("INSERT INTO `sync-timestamps` (`url`, `modified`) VALUES ('%s', NOW())", dbesc($url)); q("INSERT INTO `sync-timestamps` (`url`, `modified`) VALUES ('%s', NOW())", dbesc($url));
else } else {
q("UPDATE `sync-timestamps` SET `modified`=NOW() WHERE `url`='%s'", dbesc($url)); q("UPDATE `sync-timestamps` SET `modified`=NOW() WHERE `url`='%s'", dbesc($url));
}
} }
/** /**
@ -70,26 +65,25 @@ function sync_mark($url)
*/ */
function push_worker($target, $batch) function push_worker($target, $batch)
{ {
//Lets be nice, we're only doing a background job here... //Lets be nice, we're only doing a background job here...
pcntl_setpriority(5); pcntl_setpriority(5);
//Find our target's submit URL. //Find our target's submit URL.
$submit = $target['base_url'].'/submit'; $submit = $target['base_url'] . '/submit';
foreach($batch as $item){ foreach ($batch as $item) {
set_time_limit(30); //This should work for 1 submit. set_time_limit(30); //This should work for 1 submit.
msg("Submitting {$item['url']} to $submit"); msg("Submitting {$item['url']} to $submit");
fetch_url($submit.'?url='.bin2hex($item['url'])); fetch_url($submit . '?url=' . bin2hex($item['url']));
} }
} }
/** /**
* Gets an array of push targets. * Gets an array of push targets.
* @return array Push targets. * @return array Push targets.
*/ */
function get_push_targets(){ function get_push_targets()
{
return q("SELECT * FROM `sync-targets` WHERE `push`=b'1'"); return q("SELECT * FROM `sync-targets` WHERE `push`=b'1'");
} }
@ -98,7 +92,8 @@ function get_push_targets(){
* @param object $a The App instance. * @param object $a The App instance.
* @return array Batch of URL's. * @return array Batch of URL's.
*/ */
function get_push_batch($a){ function get_push_batch($a)
{
return q("SELECT * FROM `sync-push-queue` LIMIT %u", intval($a->config['syncing']['max_push_items'])); return q("SELECT * FROM `sync-push-queue` LIMIT %u", intval($a->config['syncing']['max_push_items']));
} }
@ -109,35 +104,31 @@ function get_push_batch($a){
*/ */
function get_pushing_job($a) function get_pushing_job($a)
{ {
//When pushing is requested... //When pushing is requested...
if(!!$a->config['syncing']['enable_pushing']){ if (!!$a->config['syncing']['enable_pushing']) {
//Find our targets. //Find our targets.
$targets = get_push_targets(); $targets = get_push_targets();
//No targets? //No targets?
if(!count($targets)){ if (!count($targets)) {
msg('Pushing enabled, but no push targets.'); msg('Pushing enabled, but no push targets.');
$batch = array(); $batch = array();
} }
//If we have targets, get our batch. //If we have targets, get our batch.
else{ else {
$batch = get_push_batch($a); $batch = get_push_batch($a);
if(!count($batch)) msg('Empty pushing queue.'); //No batch, means no work. if (!count($batch))
msg('Empty pushing queue.'); //No batch, means no work.
} }
} else {
}
//No pushing if it's disabled. //No pushing if it's disabled.
else{
$targets = array(); $targets = array();
$batch = array(); $batch = array();
} }
return array($targets, $batch); return array($targets, $batch);
} }
/** /**
@ -153,23 +144,20 @@ function get_pushing_job($a)
*/ */
function run_pushing_job($targets, $batch, $db_host, $db_user, $db_pass, $db_data, $install) function run_pushing_job($targets, $batch, $db_host, $db_user, $db_pass, $db_data, $install)
{ {
//Create a thread for each target we want to serve push messages to. //Create a thread for each target we want to serve push messages to.
//Not good creating more, because it would stress their server too much. //Not good creating more, because it would stress their server too much.
$threadc = count($targets); $threadc = count($targets);
$threads = array(); $threads = array();
//Do we only have 1 target? No need for threads. //Do we only have 1 target? No need for threads.
if($threadc === 1){ if ($threadc === 1) {
msg('No threads needed. Only one pushing target.'); msg('No threads needed. Only one pushing target.');
push_worker($targets[0], $batch); push_worker($targets[0], $batch);
} } elseif ($threadc > 1) {
//When we need threads. //When we need threads.
elseif($threadc > 1){
//POSIX threads only. //POSIX threads only.
if(!function_exists('pcntl_fork')){ if (!function_exists('pcntl_fork')) {
msg('Error: no pcntl_fork support. Are you running a different OS? Report an issue please.', true); msg('Error: no pcntl_fork support. Are you running a different OS? Report an issue please.', true);
} }
@ -178,49 +166,54 @@ function run_pushing_job($targets, $batch, $db_host, $db_user, $db_pass, $db_dat
msg("Creating $threadc push threads for $items items."); msg("Creating $threadc push threads for $items items.");
//Loop while we need more threads. //Loop while we need more threads.
for($i = 0; $i < $threadc; $i++){ for ($i = 0; $i < $threadc; $i++) {
$pid = pcntl_fork(); $pid = pcntl_fork();
if($pid === -1) msg('Error: something went wrong with the fork. '.pcntl_strerror(), true); if ($pid === -1)
msg('Error: something went wrong with the fork. ' . pcntl_strerror(), true);
//You're a child, go do some labor! //You're a child, go do some labor!
if($pid === 0){push_worker($targets[$i], $batch); exit;} if ($pid === 0) {
push_worker($targets[$i], $batch);
//Store the list of PID's. exit;
if($pid > 0) $threads[] = $pid;
} }
//Store the list of PID's.
if ($pid > 0) {
$threads[] = $pid;
}
}
} }
//Wait for all child processes. //Wait for all child processes.
$theading_problems = false; $theading_problems = false;
foreach($threads as $pid){
foreach ($threads as $pid) {
pcntl_waitpid($pid, $status); pcntl_waitpid($pid, $status);
if($status !== 0){
if ($status !== 0) {
$theading_problems = true; $theading_problems = true;
msg("Bad process return value $pid:$status"); msg("Bad process return value $pid:$status");
} }
} }
//If we did not have any "threading" problems. //If we did not have any "threading" problems.
if(!$theading_problems){ if (!$theading_problems) {
//Reconnect //Reconnect
global $db; global $db;
$db = new dba($db_host, $db_user, $db_pass, $db_data, $install); $db = new dba($db_host, $db_user, $db_pass, $db_data, $install);
//Create a query for deleting this queue. //Create a query for deleting this queue.
$where = array(); $where = array();
foreach($batch as $item) $where[] = dbesc($item['url']); foreach ($batch as $item) {
$where = "WHERE `url` IN ('".implode("', '", $where)."')"; $where[] = dbesc($item['url']);
}
$where = "WHERE `url` IN ('" . implode("', '", $where) . "')";
//Remove the items from queue. //Remove the items from queue.
q("DELETE FROM `sync-push-queue` $where LIMIT %u", count($batch)); q("DELETE FROM `sync-push-queue` $where LIMIT %u", count($batch));
msg('Removed items from push queue.'); msg('Removed items from push queue.');
} }
} }
/** /**
@ -228,7 +221,8 @@ function run_pushing_job($targets, $batch, $db_host, $db_user, $db_pass, $db_dat
* @param object $a The App instance. * @param object $a The App instance.
* @return array Batch of URL's. * @return array Batch of URL's.
*/ */
function get_queued_pull_batch($a){ function get_queued_pull_batch($a)
{
//Randomize this, to prevent scraping the same servers too much or dead URL's. //Randomize this, to prevent scraping the same servers too much or dead URL's.
$batch = q("SELECT * FROM `sync-pull-queue` ORDER BY RAND() LIMIT %u", intval($a->config['syncing']['max_pull_items'])); $batch = q("SELECT * FROM `sync-pull-queue` ORDER BY RAND() LIMIT %u", intval($a->config['syncing']['max_pull_items']));
msg(sprintf('Pulling %u items from queue.', count($batch))); msg(sprintf('Pulling %u items from queue.', count($batch)));
@ -239,7 +233,8 @@ function get_queued_pull_batch($a){
* Gets an array of pull targets. * Gets an array of pull targets.
* @return array Pull targets. * @return array Pull targets.
*/ */
function get_pull_targets(){ function get_pull_targets()
{
return q("SELECT * FROM `sync-targets` WHERE `pull`=b'1'"); return q("SELECT * FROM `sync-targets` WHERE `pull`=b'1'");
} }
@ -250,57 +245,59 @@ function get_pull_targets(){
*/ */
function get_remote_pull_batch($a) function get_remote_pull_batch($a)
{ {
//Find our targets. //Find our targets.
$targets = get_pull_targets(); $targets = get_pull_targets();
msg(sprintf('Pulling from %u remote targets.', count($targets))); msg(sprintf('Pulling from %u remote targets.', count($targets)));
//No targets, means no batch. //No targets, means no batch.
if(!count($targets)) if (!count($targets)) {
return array(); return array();
}
//Pull a list of URL's from each target. //Pull a list of URL's from each target.
$urls = array(); $urls = array();
foreach($targets as $i => $target){
foreach ($targets as $i => $target) {
//First pull, or an update? //First pull, or an update?
if(!$target['dt_last_pull']) if (!$target['dt_last_pull']) {
$url = $target['base_url'].'/sync/pull/all'; $url = $target['base_url'] . '/sync/pull/all';
else } else {
$url = $target['base_url'].'/sync/pull/since/'.intval($target['dt_last_pull']); $url = $target['base_url'] . '/sync/pull/since/' . intval($target['dt_last_pull']);
}
//Go for it :D //Go for it :D
$targets[$i]['pull_data'] = json_decode(fetch_url($url), true); $targets[$i]['pull_data'] = json_decode(fetch_url($url), true);
//If we didn't get any JSON. //If we didn't get any JSON.
if(!$targets[$i]['pull_data']){ if (!$targets[$i]['pull_data']) {
msg(sprintf('Failed to pull from "%s".', $url)); msg(sprintf('Failed to pull from "%s".', $url));
continue; continue;
} }
//Add all entries as keys, to remove duplicates. //Add all entries as keys, to remove duplicates.
foreach($targets[$i]['pull_data']['results'] as $url) foreach ($targets[$i]['pull_data']['results'] as $url) {
$urls[$url]=true; $urls[$url] = true;
}
} }
//Now that we have our URL's. Store them in the queue. //Now that we have our URL's. Store them in the queue.
foreach($urls as $url=>$bool){ foreach ($urls as $url => $bool) {
if($url) sync_pull($url); if ($url) {
sync_pull($url);
}
} }
//Since this all worked out, mark each source with the timestamp of pulling. //Since this all worked out, mark each source with the timestamp of pulling.
foreach($targets as $target){ foreach ($targets as $target) {
if($target['pull_data'] && $target['pull_data']['now']){ if ($target['pull_data'] && $target['pull_data']['now']) {
msg('New pull timestamp '.$target['pull_data']['now'].' for '.$target['base_url']); msg('New pull timestamp ' . $target['pull_data']['now'] . ' for ' . $target['base_url']);
q("UPDATE `sync-targets` SET `dt_last_pull`=%u WHERE `base_url`='%s'", $target['pull_data']['now'], dbesc($target['base_url'])); q("UPDATE `sync-targets` SET `dt_last_pull`=%u WHERE `base_url`='%s'", $target['pull_data']['now'], dbesc($target['base_url']));
} }
} }
//Finally, return a batch of this. //Finally, return a batch of this.
return get_queued_pull_batch($a); return get_queued_pull_batch($a);
} }
/** /**
@ -310,19 +307,22 @@ function get_remote_pull_batch($a)
*/ */
function get_pulling_job($a) function get_pulling_job($a)
{ {
//No pulling today... //No pulling today...
if(!$a->config['syncing']['enable_pulling']) if (!$a->config['syncing']['enable_pulling']) {
return array(); return array();
}
//Firstly, finish the items from our queue. //Firstly, finish the items from our queue.
$batch = get_queued_pull_batch($a); $batch = get_queued_pull_batch($a);
if(count($batch)) return $batch; if (count($batch)) {
return $batch;
}
//If that is empty, fill the queue with remote items and return a batch of that. //If that is empty, fill the queue with remote items and return a batch of that.
$batch = get_remote_pull_batch($a); $batch = get_remote_pull_batch($a);
if(count($batch)) return $batch; if (count($batch)) {
return $batch;
}
} }
/** /**
@ -340,7 +340,6 @@ function get_pulling_job($a)
*/ */
function pull_worker($i, $threadc, $pull_batch, $db_host, $db_user, $db_pass, $db_data, $install) function pull_worker($i, $threadc, $pull_batch, $db_host, $db_user, $db_pass, $db_data, $install)
{ {
//Lets be nice, we're only doing maintenance here... //Lets be nice, we're only doing maintenance here...
pcntl_setpriority(5); pcntl_setpriority(5);
@ -350,20 +349,19 @@ function pull_worker($i, $threadc, $pull_batch, $db_host, $db_user, $db_pass, $d
//Get our (round-robin) workload from the batch. //Get our (round-robin) workload from the batch.
$workload = array(); $workload = array();
while(isset($pull_batch[$i])){ while (isset($pull_batch[$i])) {
$entry = $pull_batch[$i]; $entry = $pull_batch[$i];
$workload[] = $entry; $workload[] = $entry;
$i+=$threadc; $i += $threadc;
} }
//While we've got work to do. //While we've got work to do.
while(count($workload)){ while (count($workload)) {
$entry = array_pop($workload); $entry = array_pop($workload);
set_time_limit(20); //This should work for 1 submit. set_time_limit(20); //This should work for 1 submit.
msg("Submitting ".$entry['url']); msg("Submitting " . $entry['url']);
run_submit($entry['url']); run_submit($entry['url']);
} }
} }
/** /**
@ -379,12 +377,11 @@ function pull_worker($i, $threadc, $pull_batch, $db_host, $db_user, $db_pass, $d
*/ */
function run_pulling_job($a, $pull_batch, $db_host, $db_user, $db_pass, $db_data, $install) function run_pulling_job($a, $pull_batch, $db_host, $db_user, $db_pass, $db_data, $install)
{ {
//We need the scraper. //We need the scraper.
require_once('include/submit.php'); require_once 'include/submit.php';
//POSIX threads only. //POSIX threads only.
if(!function_exists('pcntl_fork')){ if (!function_exists('pcntl_fork')) {
msg('Error: no pcntl_fork support. Are you running a different OS? Report an issue please.', true); msg('Error: no pcntl_fork support. Are you running a different OS? Report an issue please.', true);
} }
@ -396,45 +393,50 @@ function run_pulling_job($a, $pull_batch, $db_host, $db_user, $db_pass, $db_data
msg("Creating $threadc pulling threads for $items profiles."); msg("Creating $threadc pulling threads for $items profiles.");
//Build the threads. //Build the threads.
for($i = 0; $i < $threadc; $i++){ for ($i = 0; $i < $threadc; $i++) {
$pid = pcntl_fork(); $pid = pcntl_fork();
if($pid === -1) msg('Error: something went wrong with the fork. '.pcntl_strerror(), true); if ($pid === -1) {
msg('Error: something went wrong with the fork. ' . pcntl_strerror(), true);
}
//You're a child, go do some labor! //You're a child, go do some labor!
if($pid === 0){pull_worker($i, $threadc, $pull_batch, $db_host, $db_user, $db_pass, $db_data, $install); exit;} if ($pid === 0) {
pull_worker($i, $threadc, $pull_batch, $db_host, $db_user, $db_pass, $db_data, $install);
exit;
}
//Store the list of PID's. //Store the list of PID's.
if($pid > 0) $threads[] = $pid; if ($pid > 0) {
$threads[] = $pid;
}
} }
//Wait for all child processes. //Wait for all child processes.
$theading_problems = false; $theading_problems = false;
foreach($threads as $pid){ foreach ($threads as $pid) {
pcntl_waitpid($pid, $status); pcntl_waitpid($pid, $status);
if($status !== 0){ if ($status !== 0) {
$theading_problems = true; $theading_problems = true;
msg("Bad process return value $pid:$status"); msg("Bad process return value $pid:$status");
} }
} }
//If we did not have any "threading" problems. //If we did not have any "threading" problems.
if(!$theading_problems){ if (!$theading_problems) {
//Reconnect //Reconnect
global $db; global $db;
$db = new dba($db_host, $db_user, $db_pass, $db_data, $install); $db = new dba($db_host, $db_user, $db_pass, $db_data, $install);
//Create a query for deleting this queue. //Create a query for deleting this queue.
$where = array(); $where = array();
foreach($pull_batch as $item) $where[] = dbesc($item['url']); foreach ($pull_batch as $item) {
$where = "WHERE `url` IN ('".implode("', '", $where)."')"; $where[] = dbesc($item['url']);
}
$where = "WHERE `url` IN ('" . implode("', '", $where) . "')";
//Remove the items from queue. //Remove the items from queue.
q("DELETE FROM `sync-pull-queue` $where LIMIT %u", count($pull_batch)); q("DELETE FROM `sync-pull-queue` $where LIMIT %u", count($pull_batch));
msg('Removed items from pull queue.'); msg('Removed items from pull queue.');
} }
} }

View file

@ -5,8 +5,8 @@ require_once 'boot.php';
$a = new App; $a = new App;
error_reporting(E_ERROR | E_WARNING | E_PARSE ); error_reporting(E_ERROR | E_WARNING | E_PARSE);
error_reporting(E_ALL ); error_reporting(E_ALL);
ini_set('error_log', 'php.out'); ini_set('error_log', 'php.out');
ini_set('log_errors', '1'); ini_set('log_errors', '1');
ini_set('display_errors', '0'); ini_set('display_errors', '0');
@ -18,7 +18,7 @@ require_once '.htconfig.php';
require_once 'dba.php'; require_once 'dba.php';
$db = new dba($db_host, $db_user, $db_pass, $db_data); $db = new dba($db_host, $db_user, $db_pass, $db_data);
unset($db_host, $db_user, $db_pass, $db_data); unset($db_host, $db_user, $db_pass, $db_data);
$a->init_pagehead(); $a->init_pagehead();
$a->page['aside'] = '<div id="logo"><img src="images/friendica-32.png" alt="friendica logo" /> <a href="http://friendica.com">Friendica</a></div><div id="slogan">Your friends. Your web.</div>'; $a->page['aside'] = '<div id="logo"><img src="images/friendica-32.png" alt="friendica logo" /> <a href="http://friendica.com">Friendica</a></div><div id="slogan">Your friends. Your web.</div>';
@ -43,35 +43,35 @@ if (strlen($a->module)) {
include("mod/{$a->module}.php"); include("mod/{$a->module}.php");
$a->module_loaded = true; $a->module_loaded = true;
} }
if (! $a->module_loaded) {
if (!$a->module_loaded) {
if ((x($_SERVER, 'QUERY_STRING')) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) { if ((x($_SERVER, 'QUERY_STRING')) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
goaway($a->get_baseurl() . $_SERVER['REQUEST_URI']); goaway($a->get_baseurl() . $_SERVER['REQUEST_URI']);
} }
header($_SERVER['SERVER_PROTOCOL'] . ' 404 ' . t('Not Found')); header($_SERVER['SERVER_PROTOCOL'] . ' 404 ' . t('Not Found'));
notice(t('Page not found' ) . EOL); notice(t('Page not found') . EOL);
} }
} }
if ($a->module_loaded) { if ($a->module_loaded) {
$a->page['page_title'] = $a->module; $a->page['page_title'] = $a->module;
if (function_exists($a->module . '_init')) { if (function_exists($a->module . '_init')) {
$func = $a->module . '_init'; $func = $a->module . '_init';
$func($a); $func($a);
} }
if (($_SERVER['REQUEST_METHOD'] == 'POST') && (! $a->error) if (($_SERVER['REQUEST_METHOD'] == 'POST') && (!$a->error) && (function_exists($a->module . '_post')) && (!x($_POST, 'auth-params'))) {
&& (function_exists($a->module . '_post'))
&& (! x($_POST, 'auth-params'))) {
$func = $a->module . '_post'; $func = $a->module . '_post';
$func($a); $func($a);
} }
if ((! $a->error) && (function_exists($a->module . '_afterpost'))) { if ((!$a->error) && (function_exists($a->module . '_afterpost'))) {
$func = $a->module . '_afterpost'; $func = $a->module . '_afterpost';
$func($a); $func($a);
} }
if ((! $a->error) && (function_exists($a->module . '_content'))) { if ((!$a->error) && (function_exists($a->module . '_content'))) {
$func = $a->module . '_content'; $func = $a->module . '_content';
$a->page['content'] = $func($a); $a->page['content'] = $func($a);
} }
@ -83,9 +83,11 @@ if (x($_SESSION, 'sysmsg')) {
if (stristr($_SESSION['sysmsg'], t('Permission denied'))) { if (stristr($_SESSION['sysmsg'], t('Permission denied'))) {
header($_SERVER['SERVER_PROTOCOL'] . ' 403 ' . t('Permission denied.')); header($_SERVER['SERVER_PROTOCOL'] . ' 403 ' . t('Permission denied.'));
} }
if (!isset($a->page['content'])) { if (!isset($a->page['content'])) {
$a->page['content'] = ''; $a->page['content'] = '';
} }
$a->page['content'] = '<div id="sysmsg" class="error-message">' . $_SESSION['sysmsg'] . '</div>' . PHP_EOL $a->page['content'] = '<div id="sysmsg" class="error-message">' . $_SESSION['sysmsg'] . '</div>' . PHP_EOL
. $a->page['content']; . $a->page['content'];
unset($_SESSION['sysmsg']); unset($_SESSION['sysmsg']);
@ -97,17 +99,21 @@ $a->page['htmlhead'] = replace_macros($a->page['htmlhead'], array(
'$stylesheet' => $a->get_baseurl() . '/view/theme/' '$stylesheet' => $a->get_baseurl() . '/view/theme/'
. ((x($_SESSION, 'theme')) ? $_SESSION['theme'] : 'default') . ((x($_SESSION, 'theme')) ? $_SESSION['theme'] : 'default')
. '/style.css' . '/style.css'
)); ));
$page = $a->page; $page = $a->page;
$profile = $a->profile; $profile = $a->profile;
header('Content-type: text/html; charset=utf-8'); header('Content-type: text/html; charset=utf-8');
$template = 'view/' $template = 'view/'
. ((x($a->page, 'template')) ? $a->page['template'] : 'default' ) . ((x($a->page, 'template')) ? $a->page['template'] : 'default' )
. '.php'; . '.php';
require_once $template; require_once $template;
session_write_close(); session_write_close();
closedb(); closedb();
exit; exit;

View file

@ -2,7 +2,8 @@
require_once 'datetime.php'; require_once 'datetime.php';
function photo_init(App $a) { function photo_init(App $a)
{
switch ($a->argc) { switch ($a->argc) {
case 2: case 2:
$photo = $a->argv[1]; $photo = $a->argv[1];
@ -14,13 +15,13 @@ function photo_init(App $a) {
$profile_id = str_replace('.jpg', '', $photo); $profile_id = str_replace('.jpg', '', $photo);
$r = q('SELECT * FROM `photo` WHERE `profile-id` = %d LIMIT 1', $r = q('SELECT * FROM `photo` WHERE `profile-id` = %d LIMIT 1', intval($profile_id));
intval($profile_id)
);
if (count($r)) { if (count($r)) {
$data = $r[0]['data']; $data = $r[0]['data'];
} }
if (x($data) === false || (! strlen($data))) {
if (x($data) === false || (!strlen($data))) {
$data = file_get_contents('images/default-profile-sm.jpg'); $data = file_get_contents('images/default-profile-sm.jpg');
} }
@ -29,9 +30,10 @@ function photo_init(App $a) {
//Try and cache our result. //Try and cache our result.
$etag = md5($data); $etag = md5($data);
header('Etag: '.$etag); header('Etag: ' . $etag);
header('Expires: ' . datetime_convert('UTC', 'UTC', 'now + 1 week', 'D, d M Y H:i:s' . ' GMT')); header('Expires: ' . datetime_convert('UTC', 'UTC', 'now + 1 week', 'D, d M Y H:i:s' . ' GMT'));
header('Cache-Control: max-age=' . intval(7*24*3600)); header('Cache-Control: max-age=' . intval(7 * 24 * 3600));
if (function_exists('header_remove')) { if (function_exists('header_remove')) {
header_remove('Pragma'); header_remove('Pragma');
header_remove('pragma'); header_remove('pragma');

View file

@ -4,15 +4,15 @@ use Friendica\Directory\Rendering\View;
use Friendica\Directory\Helper\Search as SearchHelper; use Friendica\Directory\Helper\Search as SearchHelper;
use Friendica\Directory\Helper\Profile as ProfileHelper; use Friendica\Directory\Helper\Profile as ProfileHelper;
function search_content(&$a) { function search_content(App $a)
{
//Filters //Filters
$community = null; $community = null;
$filter = null; $filter = null;
if($a->argc >= 2){
if ($a->argc >= 2) {
$filter = $a->argv[1]; $filter = $a->argv[1];
switch($filter){ switch ($filter) {
case 'forums': case 'forums':
$community = 1; $community = 1;
@ -26,48 +26,50 @@ function search_content(&$a) {
$community = null; $community = null;
$filter = null; $filter = null;
break; break;
} }
} }
$alpha = false; $alpha = false;
if(x($_GET, 'alpha') == 1) if (x($_GET, 'alpha') == 1)
$alpha = true; $alpha = true;
//Query //Query
$search = ((x($_GET,'query')) ? notags(trim($_GET['query'])) : ''); $search = ((x($_GET, 'query')) ? notags(trim($_GET['query'])) : '');
if(empty($search)){ if (empty($search)) {
goaway('/home'); goaway('/home');
} }
if($search) if ($search) {
$alpha = true; $alpha = true;
}
//Run our query. //Run our query.
if($search) if ($search) {
$search = dbesc($search . '*'); $search = dbesc($search . '*');
}
$sql_extra = ((strlen($search)) ? " AND MATCH (`name`, `pdesc`, `homepage`, `locality`, `region`, `country-name`, `tags` ) $sql_extra = ((strlen($search)) ? " AND MATCH (`name`, `pdesc`, `homepage`, `locality`, `region`, `country-name`, `tags` )
AGAINST ('$search' IN BOOLEAN MODE) " : ""); AGAINST ('$search' IN BOOLEAN MODE) " : "");
if(!is_null($community)) if (!is_null($community)) {
$sql_extra .= " and comm=".intval($community)." "; $sql_extra .= " and comm=" . intval($community) . " ";
}
$sql_extra = str_replace('%','%%',$sql_extra); $sql_extra = str_replace('%', '%%', $sql_extra);
$total = 0; $total = 0;
$r = q("SELECT COUNT(*) AS `total` FROM `profile` WHERE `censored` = 0 $sql_extra "); $r = q("SELECT COUNT(*) AS `total` FROM `profile` WHERE `censored` = 0 $sql_extra ");
if(count($r)){ if (count($r)) {
$total = $r[0]['total']; $total = $r[0]['total'];
$a->set_pager_total($r[0]['total']); $a->set_pager_total($r[0]['total']);
} }
if($alpha) if ($alpha) {
$order = " order by name asc "; $order = " order by name asc ";
else } else {
$order = " order by updated desc, id desc "; $order = " order by updated desc, id desc ";
}
$r = q("SELECT * FROM `profile` WHERE `censored` = 0 $sql_extra $order LIMIT %d , %d ", $r = q("SELECT * FROM `profile` WHERE `censored` = 0 $sql_extra $order LIMIT %d , %d ",
intval($a->pager['start']), intval($a->pager['start']),
@ -77,7 +79,9 @@ function search_content(&$a) {
//Show results. //Show results.
$view = new View('search'); $view = new View('search');
$view->addHelper('paginate', function()use($a){return paginate($a);}); $view->addHelper('paginate', function() use ($a) {
return paginate($a);
});
$view->addHelper('photoUrl', ProfileHelper::get('photoUrl')); $view->addHelper('photoUrl', ProfileHelper::get('photoUrl'));
$view->addHelper('filterAllUrl', SearchHelper::get('filterAllUrl')); $view->addHelper('filterAllUrl', SearchHelper::get('filterAllUrl'));
$view->addHelper('filterPeopleUrl', SearchHelper::get('filterPeopleUrl')); $view->addHelper('filterPeopleUrl', SearchHelper::get('filterPeopleUrl'));
@ -87,7 +91,6 @@ function search_content(&$a) {
'total' => number_format($total), 'total' => number_format($total),
'results' => $r, 'results' => $r,
'filter' => $filter, 'filter' => $filter,
'query' => x($_GET,'query') ? $_GET['query'] : '' 'query' => x($_GET, 'query') ? $_GET['query'] : ''
)); ));
} }

View file

@ -2,7 +2,7 @@
use Friendica\Directory\Rendering\View; use Friendica\Directory\Rendering\View;
require_once('include/site-health.php'); require_once 'include/site-health.php';
function servers_content(&$a) { function servers_content(&$a) {

View file

@ -1,4 +1,6 @@
<?php namespace Friendica\Directory\Helper; <?php
namespace Friendica\Directory\Helper;
use \OutOfBoundsException; use \OutOfBoundsException;
use \ReflectionMethod; use \ReflectionMethod;
@ -8,6 +10,11 @@ use \ReflectionMethod;
*/ */
abstract class BaseHelper abstract class BaseHelper
{ {
/**
* A reference to the global App.
* @var \App
*/
protected $app;
public static function get($name) public static function get($name)
{ {
@ -15,12 +22,6 @@ abstract class BaseHelper
return $helper->{$name}; return $helper->{$name};
} }
/**
* A reference to the global App.
* @var \App
*/
protected $app;
public function __construct() public function __construct()
{ {
global $a; global $a;
@ -30,18 +31,15 @@ abstract class BaseHelper
//Provides access to a wrapper for your helper functions. //Provides access to a wrapper for your helper functions.
public function __get($name) public function __get($name)
{ {
if (!method_exists($this, $name)) {
if(!method_exists($this, $name)){ throw new OutOfBoundsException("Helper method '$name' does not exist on " . get_class($this));
throw new OutOfBoundsException("Helper method '$name' does not exist on ".get_class($this));
} }
$helper = $this; $helper = $this;
$method = new ReflectionMethod($this, $name); $method = new ReflectionMethod($this, $name);
return function()use($method, $helper){ return function()use($method, $helper) {
$arguments = func_get_args(); $arguments = func_get_args();
return $method->invokeArgs($helper, $arguments); return $method->invokeArgs($helper, $arguments);
}; };
} }
} }