]> git.mxchange.org Git - friendica.git/commitdiff
Merge branch 'develop' into rewrites/coding-convention-split2
authorRoland Häder <Quix0r@users.noreply.github.com>
Sat, 1 Apr 2017 20:16:08 +0000 (22:16 +0200)
committerGitHub <noreply@github.com>
Sat, 1 Apr 2017 20:16:08 +0000 (22:16 +0200)
1  2 
boot.php
include/dfrn.php
include/ostatus.php
mod/admin.php
mod/dfrn_confirm.php
mod/dfrn_notify.php
mod/install.php

diff --combined boot.php
index 5f65572d50b9408ab3f34b712b2fe63eb2d075a7,74d6ee4c4f0c37497f1764810c4cbd82d9849425..b1c7b265b28e1ea0905ba21b4e5826f07c454c04
+++ b/boot.php
@@@ -253,6 -253,7 +253,6 @@@ define ( 'NETWORK_PHANTOM',          'u
   * and existing allocations MUST NEVER BE CHANGED
   * OR RE-ASSIGNED! You may only add to them.
   */
 -
  $netgroup_ids = array(
        NETWORK_DFRN     => (-1),
        NETWORK_ZOT      => (-2),
@@@ -502,7 -503,6 +502,7 @@@ function startup() 
   */
  class App {
  
 +      /// @TODO decide indending as a colorful mixure is ahead ...
        public  $module_loaded = false;
        public  $query_string;
        public  $config;
         * beyond are used.
         */
        public  $theme = array(
 -              'sourcename' => '',
 -              'videowidth' => 425,
 -              'videoheight' => 350,
 +              'sourcename'      => '',
 +              'videowidth'      => 425,
 +              'videoheight'     => 350,
                'force_max_items' => 0,
 -              'thread_allow' => true,
 -              'stylesheet' => '',
 +              'thread_allow'    => true,
 +              'stylesheet'      => '',
                'template_engine' => 'smarty3',
        );
  
  
                $hostname = "";
  
 -              if (file_exists(".htpreconfig.php"))
 -                      @include(".htpreconfig.php");
 +              if (file_exists(".htpreconfig.php")) {
 +                      include ".htpreconfig.php";
 +              }
  
                $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
  
                set_include_path(
                                'include' . PATH_SEPARATOR
                                . 'library' . PATH_SEPARATOR
-                               . 'library/phpsec' . PATH_SEPARATOR
                                . 'library/langdet' . PATH_SEPARATOR
                                . '.' );
  
  
                $this->scheme = 'http';
 -              if((x($_SERVER,'HTTPS') && $_SERVER['HTTPS']) ||
 -                 (x($_SERVER['HTTP_FORWARDED']) && preg_match("/proto=https/", $_SERVER['HTTP_FORWARDED'])) ||
 -                 (x($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
 -                 (x($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
 -                 (x($_SERVER['FRONT_END_HTTPS']) && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
 -                 (x($_SERVER,'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
 -                 ) {
 +
 +              if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
 +                              (x($_SERVER, 'HTTP_FORWARDED') && preg_match("/proto=https/", $_SERVER['HTTP_FORWARDED'])) ||
 +                              (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
 +                              (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
 +                              (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
 +                              (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
 +                              ) {
                        $this->scheme = 'https';
 -                 }
 +              }
  
 -              if(x($_SERVER,'SERVER_NAME')) {
 +              if (x($_SERVER, 'SERVER_NAME')) {
                        $this->hostname = $_SERVER['SERVER_NAME'];
  
 -                      if(x($_SERVER,'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443)
 +                      if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
                                $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
 +                      }
                        /*
                         * Figure out if we are running at the top of a domain
                         * or in a sub-directory and adjust accordingly
                         */
  
 -                      $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
 -                      if(isset($path) && strlen($path) && ($path != $this->path))
 +                      /// @TODO This kind of escaping breaks syntax-highlightning on CoolEdit (Midnight Commander)
 +                      $path = trim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
 +                      if (isset($path) && strlen($path) && ($path != $this->path)) {
                                $this->path = $path;
 +                      }
                }
  
 -              if ($hostname != "")
 +              if ($hostname != "") {
                        $this->hostname = $hostname;
 +              }
  
 -              if (is_array($_SERVER["argv"]) && $_SERVER["argc"]>1 && substr(end($_SERVER["argv"]), 0, 4)=="http" ) {
 -                      $this->set_baseurl(array_pop($_SERVER["argv"]) );
 +              if (is_array($_SERVER["argv"]) && $_SERVER["argc"] > 1 && substr(end($_SERVER["argv"]), 0, 4) == "http" ) {
 +                      $this->set_baseurl(array_pop($_SERVER["argv"]));
                        $_SERVER["argc"] --;
                }
  
 -              #set_include_path("include/$this->hostname" . PATH_SEPARATOR . get_include_path());
 +              if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === "pagename=") {
 +                      $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
  
 -              if ((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,9) === "pagename=") {
 -                      $this->query_string = substr($_SERVER['QUERY_STRING'],9);
                        // removing trailing / - maybe a nginx problem
 -                      if (substr($this->query_string, 0, 1) == "/")
 -                              $this->query_string = substr($this->query_string, 1);
 -              } elseif ((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
 -                      $this->query_string = substr($_SERVER['QUERY_STRING'],2);
 +                      $this->query_string = ltrim($this->query_string, '/');
 +              } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === "q=") {
 +                      $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
 +
                        // removing trailing / - maybe a nginx problem
 -                      if (substr($this->query_string, 0, 1) == "/")
 -                              $this->query_string = substr($this->query_string, 1);
 +                      $this->query_string = ltrim($this->query_string, '/');
                }
  
 -              if (x($_GET,'pagename')) {
 -                      $this->cmd = trim($_GET['pagename'],'/\\');
 -              } elseif (x($_GET,'q')) {
 -                      $this->cmd = trim($_GET['q'],'/\\');
 +              if (x($_GET, 'pagename')) {
 +                      $this->cmd = trim($_GET['pagename'], '/\\');
 +              } elseif (x($_GET, 'q')) {
 +                      $this->cmd = trim($_GET['q'], '/\\');
                }
  
  
                // 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"
 -
 -              if (substr($this->cmd,0,1) === '~') {
 -                      $this->cmd = 'profile/' . substr($this->cmd,1);
 +              if (substr($this->cmd, 0, 1) === '~') {
 +                      $this->cmd = 'profile/' . substr($this->cmd, 1);
                }
  
                // Diaspora style profile url
 -
 -              if (substr($this->cmd,0,2) === 'u/') {
 -                      $this->cmd = 'profile/' . substr($this->cmd,2);
 +              if (substr($this->cmd, 0, 2) === 'u/') {
 +                      $this->cmd = 'profile/' . substr($this->cmd, 2);
                }
  
  
                /*
 -               *
                 * Break the URL path into C style argc/argv style arguments for our
                 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
                 * will be 3 (integer) and $this->argv will contain:
                 *
                 * There will always be one argument. If provided a naked domain
                 * URL, $this->argv[0] is set to "home".
 -               *
                 */
  
 -              $this->argv = explode('/',$this->cmd);
 +              $this->argv = explode('/', $this->cmd);
                $this->argc = count($this->argv);
 -              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->module);
 -              }
 -              else {
 +              } else {
                        $this->argc = 1;
                        $this->argv = array('home');
                        $this->module = 'home';
                 * pagination
                 */
  
 -              $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['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['total'] = 0;
  
                /*
  
                $basepath = get_config("system", "basepath");
  
 -              if ($basepath == "")
 +              if ($basepath == "") {
                        $basepath = dirname(__FILE__);
 +              }
  
 -              if ($basepath == "")
 +              if ($basepath == "") {
                        $basepath = $_SERVER["DOCUMENT_ROOT"];
 +              }
  
 -              if ($basepath == "")
 +              if ($basepath == "") {
                        $basepath = $_SERVER["PWD"];
 +              }
  
 -              return($basepath);
 +              return $basepath;
        }
  
        function get_scheme() {
 -              return($this->scheme);
 +              return $this->scheme;
        }
  
        /**
        function set_baseurl($url) {
                $parsed = @parse_url($url);
  
 -              if($parsed) {
 +              if ($parsed) {
                        $this->scheme = $parsed['scheme'];
  
                        $hostname = $parsed['host'];
                        }
  
                        if (file_exists(".htpreconfig.php")) {
 -                              @include(".htpreconfig.php");
 +                              include ".htpreconfig.php";
                        }
  
                        if (get_config('config', 'hostname') != '') {
        }
  
        function get_hostname() {
 -              if (get_config('config','hostname') != "")
 -                      $this->hostname = get_config('config','hostname');
 +              if (get_config('config', 'hostname') != "") {
 +                      $this->hostname = get_config('config', 'hostname');
 +              }
  
                return $this->hostname;
        }
        }
  
        function set_path($p) {
 -              $this->path = trim(trim($p),'/');
 +              $this->path = trim(trim($p), '/');
        }
  
        function get_path() {
                $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 ($interval < 0)
 +              if ($interval < 0) {
                        $interval = 2147483647;
 +              }
  
 -              if($interval < 10000)
 +              if ($interval < 10000) {
                        $interval = 40000;
 +              }
  
                // compose the page title from the sitename and the
                // current module called
 -              if (!$this->module=='')
 -              {
 -                  $this->page['title'] = $this->config['sitename'].' ('.$this->module.')';
 +              if (!$this->module == '') {
 +                  $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
                } else {
 -                  $this->page['title'] = $this->config['sitename'];
 +                      $this->page['title'] = $this->config['sitename'];
                }
  
                /* put the head template at the beginning of page['htmlhead']
                 * since the code added by the modules frequently depends on it
                 * being first
                 */
 -              if(!isset($this->page['htmlhead']))
 +              if (!isset($this->page['htmlhead'])) {
                        $this->page['htmlhead'] = '';
 +              }
  
                // If we're using Smarty, then doing replace_macros() will replace
                // any unrecognized variables with a blank string. Since we delay
                // replacing $stylesheet until later, we need to replace it now
                // 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');
 -              else
 +              } else {
                        $stylesheet = '$stylesheet';
 +              }
  
                $shortcut_icon = get_config("system", "shortcut_icon");
 -              if ($shortcut_icon == "")
 +              if ($shortcut_icon == "") {
                        $shortcut_icon = "images/friendica-32.png";
 +              }
  
                $touch_icon = get_config("system", "touch_icon");
 -              if ($touch_icon == "")
 +              if ($touch_icon == "") {
                        $touch_icon = "images/friendica-128.png";
 +              }
  
                // get data wich is needed for infinite scroll on the network page
                $invinite_scroll = infinite_scroll_data($this->module);
        }
  
        function init_page_end() {
 -              if(!isset($this->page['end']))
 +              if (!isset($this->page['end'])) {
                        $this->page['end'] = '';
 +              }
                $tpl = get_markup_template('end.tpl');
                $this->page['end'] = replace_macros($tpl,array(
                        '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
  
        function get_cached_avatar_image($avatar_image){
                return $avatar_image;
 -
 -              // The following code is deactivated. It doesn't seem to make any sense and it slows down the system.
 -              /*
 -              if($this->cached_profile_image[$avatar_image])
 -                      return $this->cached_profile_image[$avatar_image];
 -
 -              $path_parts = explode("/",$avatar_image);
 -              $common_filename = $path_parts[count($path_parts)-1];
 -
 -              if($this->cached_profile_picdate[$common_filename]){
 -                      $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
 -              } else {
 -                      $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like '%%/%s'",
 -                              $common_filename);
 -                      if (! dbm::is_result($r)) {
 -                              $this->cached_profile_image[$avatar_image] = $avatar_image;
 -                      } else {
 -                              $this->cached_profile_picdate[$common_filename] = "?rev=".urlencode($r[0]['picdate']);
 -                              $this->cached_profile_image[$avatar_image] = $avatar_image.$this->cached_profile_picdate[$common_filename];
 -                      }
 -              }
 -              return $this->cached_profile_image[$avatar_image];
 -              */
        }
  
  
  
                // Is the function called statically?
                if (!(isset($this) && get_class($this) == __CLASS__)) {
 -                      return(self::$a->remove_baseurl($orig_url));
 +                      return self::$a->remove_baseurl($orig_url);
                }
  
                // Remove the hostname from the url if it is an internal link
         * @param string $name
         */
        function register_template_engine($class, $name = '') {
 -              if ($name===""){
 +              /// @TODO Really === and not just == ?
 +              if ($name === "") {
                        $v = get_class_vars( $class );
 -                      if(x($v,"name")) $name = $v['name'];
 +                      if (x($v,"name")) $name = $v['name'];
                }
 -              if ($name===""){
 +              if ($name === "") {
                        echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
                        killme();
                }
         * @param strin $name Template engine name
         * @return object Template Engine instance
         */
 -      function template_engine($name = ''){
 -              if ($name!=="") {
 +      function template_engine($name = '') {
 +              /// @TODO really type-check included?
 +              if ($name !== "") {
                        $template_engine = $name;
                } else {
                        $template_engine = 'smarty3';
                }
  
                if (isset($this->template_engines[$template_engine])){
 -                      if(isset($this->template_engine_instance[$template_engine])){
 +                      if (isset($this->template_engine_instance[$template_engine])){
                                return $this->template_engine_instance[$template_engine];
                        } else {
                                $class = $this->template_engines[$template_engine];
  
        function set_template_engine($engine = 'smarty3') {
                $this->theme['template_engine'] = $engine;
 -              /*
 -              $this->theme['template_engine'] = 'smarty3';
 -
 -              switch($engine) {
 -                      case 'smarty3':
 -                              if(is_writable('view/smarty3/'))
 -                                      $this->theme['template_engine'] = 'smarty3';
 -                              break;
 -                      default:
 -                              break;
 -              }
 -              */
        }
  
        function get_template_ldelim($engine = 'smarty3') {
        }
  
        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;
 +              }
  
                $duration = (float)(microtime(true)-$stamp);
  
                array_shift($trace);
  
                $callstack = array();
 -              foreach ($trace AS $func)
 +              foreach ($trace AS $func) {
                        $callstack[] = $func["function"];
 +              }
  
                return implode(", ", $callstack);
        }
  
        function get_useragent() {
 -              return(FRIENDICA_PLATFORM." '".FRIENDICA_CODENAME."' ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION."; ".$this->get_baseurl());
 +              return
 +                      FRIENDICA_PLATFORM . " '" .
 +                      FRIENDICA_CODENAME . "' " .
 +                      FRIENDICA_VERSION . "-" .
 +                      DB_UPDATE_VERSION . "; " .
 +                      $this->get_baseurl();
        }
  
        function is_friendica_app() {
 -              return($this->is_friendica_app);
 +              return $this->is_friendica_app;
        }
  
        /**
         * @return bool Is it a known backend?
         */
        function is_backend() {
 -              $backend = array();
 -              $backend[] = "_well_known";
 -              $backend[] = "api";
 -              $backend[] = "dfrn_notify";
 -              $backend[] = "fetch";
 -              $backend[] = "hcard";
 -              $backend[] = "hostxrd";
 -              $backend[] = "nodeinfo";
 -              $backend[] = "noscrape";
 -              $backend[] = "p";
 -              $backend[] = "poco";
 -              $backend[] = "post";
 -              $backend[] = "proxy";
 -              $backend[] = "pubsub";
 -              $backend[] = "pubsubhubbub";
 -              $backend[] = "receive";
 -              $backend[] = "rsd_xml";
 -              $backend[] = "salmon";
 -              $backend[] = "statistics_json";
 -              $backend[] = "xrd";
 -
 -              if (in_array($this->module, $backend))
 -                      return(true);
 -              else
 -                      return($this->backend);
 +              static $backends = array();
 +              $backends[] = "_well_known";
 +              $backends[] = "api";
 +              $backends[] = "dfrn_notify";
 +              $backends[] = "fetch";
 +              $backends[] = "hcard";
 +              $backends[] = "hostxrd";
 +              $backends[] = "nodeinfo";
 +              $backends[] = "noscrape";
 +              $backends[] = "p";
 +              $backends[] = "poco";
 +              $backends[] = "post";
 +              $backends[] = "proxy";
 +              $backends[] = "pubsub";
 +              $backends[] = "pubsubhubbub";
 +              $backends[] = "receive";
 +              $backends[] = "rsd_xml";
 +              $backends[] = "salmon";
 +              $backends[] = "statistics_json";
 +              $backends[] = "xrd";
 +
 +              // Check if current module is in backend or backend flag is set
 +              return (in_array($this->module, $backends) || $this->backend);
        }
  
        /**
                if ($this->is_backend()) {
                        $process = "backend";
                        $max_processes = get_config('system', 'max_processes_backend');
 -                      if (intval($max_processes) == 0)
 +                      if (intval($max_processes) == 0) {
                                $max_processes = 5;
 +                      }
                } else {
                        $process = "frontend";
                        $max_processes = get_config('system', 'max_processes_frontend');
 -                      if (intval($max_processes) == 0)
 +                      if (intval($max_processes) == 0) {
                                $max_processes = 20;
 +                      }
                }
  
                $processlist = dbm::processlist();
                if ($this->is_backend()) {
                        $process = "backend";
                        $maxsysload = intval(get_config('system', 'maxloadavg'));
 -                      if ($maxsysload < 1)
 +                      if ($maxsysload < 1) {
                                $maxsysload = 50;
 +                      }
                } else {
                        $process = "frontend";
                        $maxsysload = intval(get_config('system','maxloadavg_frontend'));
 -                      if ($maxsysload < 1)
 +                      if ($maxsysload < 1) {
                                $maxsysload = 50;
 +                      }
                }
  
                $load = current_load();
                // This should prevent the forking of masses of workers.
                $cachekey = "app:proc_run:started";
                $result = Cache::get($cachekey);
 -              if (!is_null($result)) {
 -                      if ((time() - $result) < 10) {
 -                              return;
 -                      }
 +
 +              if (!is_null($result) AND (time() - $result) < 10) {
 +                      return;
                }
 +
                // Set the timestamp of the last proc_run
                Cache::set($cachekey, time(), CACHE_MINUTE);
  
                // add baseurl to args. cli scripts can't construct it
                $args[] = $this->get_baseurl();
  
 -              for($x = 0; $x < count($args); $x ++)
 +              for ($x = 0; $x < count($args); $x ++) {
                        $args[$x] = escapeshellarg($args[$x]);
 +              }
  
 -              $cmdline = implode($args," ");
 +              $cmdline = implode($args, " ");
  
 -              if(get_config('system','proc_windows'))
 -                      proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
 -              else
 -                      proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
 +              if (get_config('system', 'proc_windows')) {
 +                      proc_close(proc_open('cmd /c start /b ' . $cmdline, array(), $foo, dirname(__FILE__)));
 +              } else {
 +                      proc_close(proc_open($cmdline . " &", array(), $foo, dirname(__FILE__)));
 +              }
  
        }
  
@@@ -1449,17 -1460,17 +1448,17 @@@ function get_app() 
   * @return bool|int
   */
  function x($s,$k = NULL) {
 -      if($k != NULL) {
 -              if((is_array($s)) && (array_key_exists($k,$s))) {
 -                      if($s[$k])
 +      if ($k != NULL) {
 +              if ((is_array($s)) && (array_key_exists($k, $s))) {
 +                      if ($s[$k]) {
                                return (int) 1;
 +                      }
                        return (int) 0;
 -      }
 +              }
                return false;
 -      }
 -      else {
 -              if(isset($s)) {
 -                      if($s) {
 +      } else {
 +              if (isset($s)) {
 +                      if ($s) {
                                return (int) 1;
                        }
                        return (int) 0;
@@@ -1487,9 -1498,8 +1486,9 @@@ function clean_urls() 
  function z_path() {
        $base = App::get_baseurl();
  
 -      if(! clean_urls())
 +      if (! clean_urls()) {
                $base .= '/?q=';
 +      }
  
        return $base;
  }
@@@ -1514,9 -1524,8 +1513,9 @@@ function z_root() 
   * @return string
   */
  function absurl($path) {
 -      if(strpos($path,'/') === 0)
 +      if (strpos($path,'/') === 0) {
                return z_path() . $path;
 +      }
        return $path;
  }
  
@@@ -1532,13 -1541,12 +1531,13 @@@ function is_ajax() 
  function check_db() {
  
        $build = get_config('system','build');
 -      if(! x($build)) {
 +      if (! x($build)) {
                set_config('system','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');
 +      }
  
  }
  
@@@ -1557,12 -1565,10 +1556,12 @@@ function check_url(App $a) 
        // and www.example.com vs example.com.
        // 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());
 -      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());
 +      }
  
        return;
  }
   */
  function update_db(App $a) {
        $build = get_config('system','build');
 -      if(! x($build))
 +      if (! x($build)) {
                $build = set_config('system','build',DB_UPDATE_VERSION);
 +      }
  
 -      if($build != DB_UPDATE_VERSION) {
 +      if ($build != DB_UPDATE_VERSION) {
                $stored = intval($build);
                $current = intval(DB_UPDATE_VERSION);
 -              if($stored < $current) {
 +              if ($stored < $current) {
                        Config::load('database');
  
                        // We're reporting a different version than what is currently installed.
                        // updating right this very second and the correct version of the update.php
                        // file may not be here yet. This can happen on a very busy site.
  
 -                      if(DB_UPDATE_VERSION == UPDATE_VERSION) {
 +                      if (DB_UPDATE_VERSION == UPDATE_VERSION) {
                                // Compare the current structure with the defined structure
  
                                $t = get_config('database','dbupdate_'.DB_UPDATE_VERSION);
 -                              if($t !== false)
 +                              if ($t !== false) {
                                        return;
 +                              }
  
                                set_config('database','dbupdate_'.DB_UPDATE_VERSION, time());
  
                                // conflits with new routine)
                                for ($x = $stored; $x < NEW_UPDATE_ROUTINE_VERSION; $x++) {
                                        $r = run_update_function($x);
 -                                      if (!$r) break;
 +                                      if (!$r) {
 +                                              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
                                // it update the structure in one call
                                $retval = update_structure(false, true);
 -                              if($retval) {
 +                              if ($retval) {
                                        update_fail(
                                                DB_UPDATE_VERSION,
                                                $retval
                                }
  
                                // 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);
 -                                      if (!$r) break;
 +                                      if (!$r) {
 +                                              break;
 +                                      }
                                }
                        }
                }
  }
  
  function run_update_function($x) {
 -      if(function_exists('update_' . $x)) {
 +      if (function_exists('update_' . $x)) {
  
                // There could be a lot of processes running or about to run.
                // We want exactly one process to run the update command.
                // delete the config entry to try again.
  
                $t = get_config('database','update_' . $x);
 -              if($t !== false)
 +              if ($t !== false) {
                        return false;
 +              }
                set_config('database','update_' . $x, time());
  
                // call the specific update
                $func = 'update_' . $x;
                $retval = $func();
  
 -              if($retval) {
 +              if ($retval) {
                        //send the administrator an e-mail
                        update_fail(
                                $x,
   *
   * @param App $a
   *
 -       */
 + */
  function check_plugins(App $a) {
  
        $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
 -      if (dbm::is_result($r))
 +      if (dbm::is_result($r)) {
                $installed = $r;
 -      else
 +      } else {
                $installed = array();
 +      }
  
        $plugins = get_config('system','addon');
        $plugins_arr = array();
  
 -      if($plugins)
 +      if ($plugins) {
                $plugins_arr = explode(',',str_replace(' ', '',$plugins));
 +      }
  
        $a->plugins = $plugins_arr;
  
        $installed_arr = array();
  
 -      if(count($installed)) {
 -              foreach($installed as $i) {
 -                      if(! in_array($i['name'],$plugins_arr)) {
 +      if (count($installed)) {
 +              foreach ($installed as $i) {
 +                      if (! in_array($i['name'],$plugins_arr)) {
                                uninstall_plugin($i['name']);
 -                      }
 -                      else {
 +                      } else {
                                $installed_arr[] = $i['name'];
                        }
                }
        }
  
 -      if(count($plugins_arr)) {
 -              foreach($plugins_arr as $p) {
 -                      if(! in_array($p,$installed_arr)) {
 +      if (count($plugins_arr)) {
 +              foreach ($plugins_arr as $p) {
 +                      if (! in_array($p,$installed_arr)) {
                                install_plugin($p);
                        }
                }
@@@ -1746,9 -1743,8 +1745,9 @@@ function get_guid($size=16, $prefix = "
                $prefix = hash("crc32", $a->get_hostname());
        }
  
 -      while (strlen($prefix) < ($size - 13))
 +      while (strlen($prefix) < ($size - 13)) {
                $prefix .= mt_rand();
 +      }
  
        if ($size >= 24) {
                $prefix = substr($prefix, 0, $size - 22);
@@@ -1788,11 -1784,12 +1787,11 @@@ function login($register = false, $hidd
  
        $dest_url = $a->query_string;
  
 -      if(local_user()) {
 +      if (local_user()) {
                $tpl = get_markup_template("logout.tpl");
 -      }
 -      else {
 +      } else {
                $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
 -                      '$baseurl'              => $a->get_baseurl(true)
 +                      '$baseurl' => $a->get_baseurl(true)
                ));
  
                $tpl = get_markup_template("login.tpl");
  
        $o .= replace_macros($tpl, array(
  
 -              '$dest_url'     => $dest_url,
 -              '$logout'       => t('Logout'),
 -              '$login'        => t('Login'),
 +              '$dest_url'     => $dest_url,
 +              '$logout'       => t('Logout'),
 +              '$login'        => t('Login'),
  
 -              '$lname'        => array('username', t('Nickname or Email: ') , '', ''),
 -              '$lpassword'    => array('password', t('Password: '), '', ''),
 -              '$lremember'    => array('remember', t('Remember me'), 0,  ''),
 +              '$lname'        => array('username', t('Nickname or Email: ') , '', ''),
 +              '$lpassword'    => array('password', t('Password: '), '', ''),
 +              '$lremember'    => array('remember', t('Remember me'), 0,  ''),
  
 -              '$openid'       => !$noid,
 -              '$lopenid'      => array('openid_url', t('Or login using OpenID: '),'',''),
 +              '$openid'       => !$noid,
 +              '$lopenid'      => array('openid_url', t('Or login using OpenID: '),'',''),
  
 -              '$hiddens'      => $hiddens,
 +              '$hiddens'      => $hiddens,
  
 -              '$register'     => $reg,
 +              '$register'     => $reg,
  
                '$lostpass'     => t('Forgot your password?'),
                '$lostlink'     => t('Password Reset'),
  
 -              '$tostitle'     => t('Website Terms of Service'),
 -              '$toslink'      => t('terms of service'),
 +              '$tostitle'     => t('Website Terms of Service'),
 +              '$toslink'      => t('terms of service'),
  
 -              '$privacytitle' => t('Website Privacy Policy'),
 -              '$privacylink'  => t('privacy policy'),
 +              '$privacytitle' => t('Website Privacy Policy'),
 +              '$privacylink'  => t('privacy policy'),
  
        ));
  
   */
  function killme() {
  
 -      if (!get_app()->is_backend())
 +      if (!get_app()->is_backend()) {
                session_write_close();
 +      }
  
 -      exit;
 +      exit();
  }
  
  /**
   * @brief Redirect to another URL and terminate this process.
   */
  function goaway($s) {
 -      if (!strstr(normalise_link($s), "http://"))
 +      if (!strstr(normalise_link($s), "http://")) {
                $s = App::get_baseurl()."/".$s;
 +      }
  
        header("Location: $s");
        killme();
@@@ -1882,11 -1877,11 +1881,11 @@@ function public_contact() 
                if (x($_SESSION, 'my_address')) {
                        // Local user
                        $public_contact_id = intval(get_contact($_SESSION['my_address'], 0));
 -              } else if (x($_SESSION, 'visitor_home')) {
 +              } elseif (x($_SESSION, 'visitor_home')) {
                        // Remote user
                        $public_contact_id = intval(get_contact($_SESSION['visitor_home'], 0));
                }
 -      } else if (!x($_SESSION, 'authenticated')) {
 +      } elseif (!x($_SESSION, 'authenticated')) {
                $public_contact_id = false;
        }
  
   * @return int|bool visitor_id or false
   */
  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 false;
  }
  
   */
  function notice($s) {
        $a = get_app();
 -      if(! x($_SESSION,'sysmsg'))     $_SESSION['sysmsg'] = array();
 -      if($a->interactive)
 +      if (! x($_SESSION,'sysmsg')) {
 +              $_SESSION['sysmsg'] = array();
 +      }
 +      if ($a->interactive) {
                $_SESSION['sysmsg'][] = $s;
 +      }
  }
  
  /**
  function info($s) {
        $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;
 +      }
  
 -      if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
 -      if($a->interactive)
 +      if (! x($_SESSION,'sysmsg_info')) {
 +              $_SESSION['sysmsg_info'] = array();
 +      }
 +      if ($a->interactive) {
                $_SESSION['sysmsg_info'][] = $s;
 +      }
  }
  
  
@@@ -2003,9 -1990,8 +2002,9 @@@ function proc_run($cmd)
        $arr = array('args' => $args, 'run_cmd' => true);
  
        call_hooks("proc_run", $arr);
 -      if (!$arr['run_cmd'] OR !count($args))
 +      if (!$arr['run_cmd'] OR !count($args)) {
                return;
 +      }
  
        $priority = PRIORITY_MEDIUM;
        $dont_fork = get_config("system", "worker_dont_fork");
        $found = q("SELECT `id` FROM `workerqueue` WHERE `parameter` = '%s'",
                dbesc($parameters));
  
 -      if (!$found)
 +      if (!dbm::is_result($found)) {
                q("INSERT INTO `workerqueue` (`parameter`, `created`, `priority`)
                        VALUES ('%s', '%s', %d)",
                        dbesc($parameters),
                        dbesc(datetime_convert()),
                        intval($priority));
 +      }
  
        // Should we quit and wait for the poller to be called as a cronjob?
        if ($dont_fork) {
        // Get number of allowed number of worker threads
        $queues = intval(get_config("system", "worker_queues"));
  
 -      if ($queues == 0)
 +      if ($queues == 0) {
                $queues = 4;
 +      }
  
        // If there are already enough workers running, don't fork another one
 -      if ($workers[0]["workers"] >= $queues)
 +      if ($workers[0]["workers"] >= $queues) {
                return;
 +      }
  
        // Now call the poller to execute the jobs that we just added to the queue
        $args = array("include/poller.php", "no_cron");
@@@ -2071,22 -2054,20 +2070,22 @@@ function current_theme()
  
        // Find the theme that belongs to the user whose stuff we are looking at
  
 -      if($a->profile_uid && ($a->profile_uid != local_user())) {
 +      if ($a->profile_uid && ($a->profile_uid != local_user())) {
                $r = q("select theme from user where uid = %d limit 1",
                        intval($a->profile_uid)
                );
 -              if (dbm::is_result($r))
 +              if (dbm::is_result($r)) {
                        $page_theme = $r[0]['theme'];
 +              }
        }
  
        // 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
  
 -      if($page_theme && local_user() && (local_user() != $a->profile_uid)) {
 -              if(get_pconfig(local_user(),'system','always_my_theme'))
 +      if ($page_theme && local_user() && (local_user() != $a->profile_uid)) {
 +              if (get_pconfig(local_user(),'system','always_my_theme')) {
                        $page_theme = null;
 +              }
        }
  
  //            $mobile_detect = new Mobile_Detect();
                        }
                        $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
  
 -                      if($theme_name === '---') {
 +                      if ($theme_name === '---') {
                                // user has selected to have the mobile theme be the same as the normal one
                                $system_theme = $standard_system_theme;
                                $theme_name = $standard_theme_name;
  
 -                              if($page_theme)
 +                              if ($page_theme) {
                                        $theme_name = $page_theme;
 +                              }
                        }
                }
 -      }
 -      else {
 +      } else {
                $system_theme = $standard_system_theme;
                $theme_name = $standard_theme_name;
  
 -              if($page_theme)
 +              if ($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.php')))
 +                                      file_exists('view/theme/' . $theme_name . '/style.php'))) {
                return($theme_name);
 +      }
  
 -      foreach($app_base_themes as $t) {
 -              if(file_exists('view/theme/' . $t . '/style.css')||
 -                              file_exists('view/theme/' . $t . '/style.php'))
 +      foreach ($app_base_themes as $t) {
 +              if (file_exists('view/theme/' . $t . '/style.css') ||
 +                              file_exists('view/theme/' . $t . '/style.php')) {
                        return($t);
 +              }
        }
  
        $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)));
 +      }
  
 +      /// @TODO No final return statement?
  }
  
  /**
@@@ -2160,9 -2136,8 +2159,9 @@@ function current_theme_url() 
        $t = current_theme();
  
        $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.css');
  }
@@@ -2191,9 -2166,8 +2190,9 @@@ function feed_birthday($uid,$tz) 
  
        $birthday = '';
  
 -      if(! strlen($tz))
 +      if (! strlen($tz)) {
                $tz = 'UTC';
 +      }
  
        $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
                        intval($uid)
  
        if (dbm::is_result($p)) {
                $tmp_dob = substr($p[0]['dob'],5);
 -              if(intval($tmp_dob)) {
 +              if (intval($tmp_dob)) {
                        $y = datetime_convert($tz,$tz,'now','Y');
                        $bd = $y . '-' . $tmp_dob . ' 00:00';
                        $t_dob = strtotime($bd);
                        $now = strtotime(datetime_convert($tz,$tz,'now'));
 -                      if($t_dob < $now)
 +                      if ($t_dob < $now) {
                                $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
 +                      }
                        $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
                }
        }
@@@ -2227,9 -2200,8 +2226,9 @@@ function is_site_admin() 
        $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
  
        //if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
 -      if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && in_array($a->user['email'], $adminlist))
 +      if (local_user() && x($a->user,'email') && x($a->config,'admin_email') && in_array($a->user['email'], $adminlist)) {
                return true;
 +      }
        return false;
  }
  
   *
   * @return string
   */
 -function build_querystring($params, $name=null) {
 +function build_querystring($params, $name = null) {
        $ret = "";
 -      foreach($params as $key=>$val) {
 -              if(is_array($val)) {
 -                      if($name==null) {
 +      foreach ($params as $key => $val) {
 +              if (is_array($val)) {
 +                      /// @TODO maybe not compare against null, use is_null()
 +                      if ($name == null) {
                                $ret .= build_querystring($val, $key);
                        } else {
                                $ret .= build_querystring($val, $name."[$key]");
                        }
                } else {
                        $val = urlencode($val);
 -                      if($name!=null) {
 -                              $ret.=$name."[$key]"."=$val&";
 +                      /// @TODO maybe not compare against null, use is_null()
 +                      if ($name != null) {
 +                              /// @TODO two string concated, can be merged to one
 +                              $ret .= $name . "[$key]" . "=$val&";
                        } else {
 -                              $ret.= "$key=$val&";
 +                              $ret .= "$key=$val&";
                        }
                }
        }
  
  function explode_querystring($query) {
        $arg_st = strpos($query, '?');
 -      if($arg_st !== false) {
 +      if ($arg_st !== false) {
                $base = substr($query, 0, $arg_st);
                $arg_st += 1;
        } else {
        }
  
        $args = explode('&', substr($query, $arg_st));
 -      foreach($args as $k=>$arg) {
 -              if($arg === '')
 +      foreach ($args as $k => $arg) {
 +              /// @TODO really compare type-safe here?
 +              if ($arg === '') {
                        unset($args[$k]);
 +              }
        }
        $args = array_values($args);
  
 -      if(!$base) {
 +      if (!$base) {
                $base = $args[0];
                unset($args[0]);
                $args = array_values($args);
  */
  function curPageURL() {
        $pageURL = 'http';
 -      if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 +      if ($_SERVER["HTTPS"] == "on") {
 +              $pageURL .= "s";
 +      }
 +
        $pageURL .= "://";
 +
        if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
                $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
        } else {
  
  function random_digits($digits) {
        $rn = '';
 -      for($i = 0; $i < $digits; $i++) {
 +      for ($i = 0; $i < $digits; $i++) {
 +              /// @TODO rand() is different to mt_rand() and maybe lesser "random"
                $rn .= rand(0,9);
        }
        return $rn;
  function get_server() {
        $server = get_config("system", "directory");
  
 -      if ($server == "")
 +      if ($server == "") {
                $server = "http://dir.friendi.ca";
 +      }
  
        return($server);
  }
  function get_cachefile($file, $writemode = true) {
        $cache = get_itemcachepath();
  
 -      if ((! $cache) || (! is_dir($cache)))
 +      if ((! $cache) || (! is_dir($cache))) {
                return("");
 +      }
  
 -      $subfolder = $cache."/".substr($file, 0, 2);
 +      $subfolder = $cache . "/" . substr($file, 0, 2);
  
 -      $cachepath = $subfolder."/".$file;
 +      $cachepath = $subfolder . "/" . $file;
  
        if ($writemode) {
                if (!is_dir($subfolder)) {
                }
        }
  
 -      return($cachepath);
 +      /// @TODO no need to put braces here
 +      return $cachepath;
  }
  
  function clear_cache($basepath = "", $path = "") {
                $path = $basepath;
        }
  
 -      if (($path == "") OR (!is_dir($path)))
 +      if (($path == "") OR (!is_dir($path))) {
                return;
 +      }
  
 -      if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
 +      if (substr(realpath($path), 0, strlen($basepath)) != $basepath) {
                return;
 +      }
  
        $cachetime = (int)get_config('system','itemcache_duration');
 -      if ($cachetime == 0)
 +      if ($cachetime == 0) {
                $cachetime = 86400;
 +      }
  
        if (is_writable($path)){
                if ($dh = opendir($path)) {
                        while (($file = readdir($dh)) !== false) {
                                $fullpath = $path."/".$file;
 -                              if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
 +                              if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != "..")) {
                                        clear_cache($basepath, $fullpath);
 -                              if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
 +                              }
 +                              if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime))) {
                                        unlink($fullpath);
 +                              }
                        }
                        closedir($dh);
                }
  function get_itemcachepath() {
        // Checking, if the cache is deactivated
        $cachetime = (int)get_config('system','itemcache_duration');
 -      if ($cachetime < 0)
 +      if ($cachetime < 0) {
                return "";
 +      }
  
        $itemcache = get_config('system','itemcache');
        if (($itemcache != "") AND App::directory_usable($itemcache)) {
  
        if ($temppath != "") {
                $itemcache = $temppath."/itemcache";
 -              if(!file_exists($itemcache) && !is_dir($itemcache)) {
 +              if (!file_exists($itemcache) && !is_dir($itemcache)) {
                        mkdir($itemcache);
                }
  
@@@ -2475,10 -2428,8 +2474,10 @@@ function get_temppath() 
        if (($temppath != "") AND App::directory_usable($temppath)) {
                // To avoid any interferences with other systems we create our own directory
                $new_temppath .= "/".$a->get_hostname();
 -              if (!is_dir($new_temppath))
 +              if (!is_dir($new_temppath)) {
 +                      /// @TODO There is a mkdir()+chmod() upwards, maybe generalize this (+ configurable) into a function/method?
                        mkdir($new_temppath);
 +              }
  
                if (App::directory_usable($new_temppath)) {
                        // The new path is usable, we are happy
  function set_template_engine(App $a, $engine = 'internal') {
  /// @note This function is no longer necessary, but keep it as a wrapper to the class method
  /// to avoid breaking themes again unnecessarily
 +/// @TODO maybe output a warning here so the theme developer can see it? PHP won't show such warnings like Java does.
  
        $a->set_template_engine($engine);
  }
  
 -if(!function_exists('exif_imagetype')) {
 +if (!function_exists('exif_imagetype')) {
        function exif_imagetype($file) {
                $size = getimagesize($file);
 -              return($size[2]);
 +              return $size[2];
        }
  }
  
@@@ -2516,42 -2466,37 +2515,42 @@@ function validate_include(&$file) 
  
        $file = realpath($file);
  
 -      if (strpos($file, getcwd()) !== 0)
 +      if (strpos($file, getcwd()) !== 0) {
                return false;
 +      }
  
        $file = str_replace(getcwd()."/", "", $file, $count);
 -      if ($count != 1)
 +      if ($count != 1) {
                return false;
 +      }
  
 -      if ($orig_file !== $file)
 +      if ($orig_file !== $file) {
                return false;
 +      }
  
        $valid = false;
 -      if (strpos($file, "include/") === 0)
 +      if (strpos($file, "include/") === 0) {
                $valid = true;
 +      }
  
 -      if (strpos($file, "addon/") === 0)
 +      if (strpos($file, "addon/") === 0) {
                $valid = true;
 +      }
  
 -      if (!$valid)
 -              return false;
 -
 -      return true;
 +      // Simply return flag
 +      return ($valid);
  }
  
  function current_load() {
 -      if (!function_exists('sys_getloadavg'))
 +      if (!function_exists('sys_getloadavg')) {
                return false;
 +      }
  
        $load_arr = sys_getloadavg();
  
 -      if (!is_array($load_arr))
 +      if (!is_array($load_arr)) {
                return false;
 +      }
  
        return max($load_arr[0], $load_arr[1]);
  }
@@@ -2572,9 -2517,8 +2571,9 @@@ function argc() 
   * @return string Value of the argv key
   */
  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 '';
  }
@@@ -2598,24 -2542,20 +2597,24 @@@ function infinite_scroll_data($module) 
                AND ($module == "network") AND ($_GET["mode"] != "minimal")) {
  
                // get the page number
 -              if (is_string($_GET["page"]))
 +              if (is_string($_GET["page"])) {
                        $pageno = $_GET["page"];
 -              else
 +              } else {
                        $pageno = 1;
 +              }
  
                $reload_uri = "";
  
                // try to get the uri from which we load the content
 -              foreach ($_GET AS $param => $value)
 -                      if (($param != "page") AND ($param != "q"))
 -                              $reload_uri .= "&".$param."=".urlencode($value);
 +              foreach ($_GET AS $param => $value) {
 +                      if (($param != "page") AND ($param != "q")) {
 +                              $reload_uri .= "&" . $param . "=" . urlencode($value);
 +                      }
 +              }
  
 -              if (($a->page_offset != "") AND !strstr($reload_uri, "&offset="))
 -                      $reload_uri .= "&offset=".urlencode($a->page_offset);
 +              if (($a->page_offset != "") AND !strstr($reload_uri, "&offset=")) {
 +                      $reload_uri .= "&offset=" . urlencode($a->page_offset);
 +              }
  
                $arr = array("pageno" => $pageno, "reload_uri" => $reload_uri);
  
diff --combined include/dfrn.php
index 83d76a0ae45cea961b58cd1ea60944fac1f10a0c,4002bb4268de07a2dca041789dfac033ff557666..aae935963d0427c7b6ab7afd3cefc62ecc73893a
@@@ -41,7 -41,6 +41,7 @@@ class dfrn 
         * @param array $owner Owner record
         *
         * @return string DFRN entries
 +       * @todo Add type-hints
         */
        public static function entries($items,$owner) {
  
  
                $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
  
 -              if(! count($items))
 +              if (! count($items)) {
                        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"]);
                        $root->appendChild($entry);
                }
                $starred     = false;   // not yet implemented, possible security issues
                $converse    = false;
  
 -              if($public_feed && $a->argc > 2) {
 -                      for($x = 2; $x < $a->argc; $x++) {
 -                              if($a->argv[$x] == 'converse')
 +              if ($public_feed && $a->argc > 2) {
 +                      for ($x = 2; $x < $a->argc; $x++) {
 +                              if ($a->argv[$x] == 'converse') {
                                        $converse = true;
 -                              if($a->argv[$x] == 'starred')
 +                              }
 +                              if ($a->argv[$x] == 'starred') {
                                        $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];
 +                              }
                        }
                }
  
  
                $sql_post_table = "";
  
 -              if(! $public_feed) {
 +              if (! $public_feed) {
  
                        $sql_extra = '';
                        switch($direction) {
                        require_once('include/security.php');
                        $groups = init_groups_visitor($contact['id']);
  
 -                      if(count($groups)) {
 -                              for($x = 0; $x < count($groups); $x ++)
 +                      if (count($groups)) {
 +                              for ($x = 0; $x < count($groups); $x ++)
                                        $groups[$x] = '<' . intval($groups[$x]) . '>' ;
                                $gs = implode('|', $groups);
 -                      } else
 +                      } else {
                                $gs = '<<>>' ; // Impossible to match
 +                      }
  
                        $sql_extra = sprintf("
                                AND ( `allow_cid` = '' OR     `allow_cid` REGEXP '<%d>' )
                        );
                }
  
 -              if($public_feed)
 +              if ($public_feed) {
                        $sort = 'DESC';
 -              else
 +              } else {
                        $sort = 'ASC';
 +              }
  
 -              if(! strlen($last_update))
 +              if (! strlen($last_update)) {
                        $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` ",
                                        dbesc(protect_sprintf($category)), intval(TERM_OBJ_POST), intval(TERM_CATEGORY), intval($owner_id));
                        //$sql_extra .= file_tag_file_query('item',$category,'category');
                }
  
 -              if($public_feed) {
 -                      if(! $converse)
 +              if ($public_feed) {
 +                      if (! $converse) {
                                $sql_extra .= " AND `contact`.`self` = 1 ";
 +                      }
                }
  
                $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
                        dbesc($sort)
                );
  
 -              // Will check further below if this actually returned results.
 -              // We will provide an empty feed if that is the case.
 +              /*
 +               * Will check further below if this actually returned results.
 +               * We will provide an empty feed if that is the case.
 +               */
  
                $items = $r;
  
  
                $alternatelink = $owner['url'];
  
 -              if(isset($category))
 +              if (isset($category)) {
                        $alternatelink .= "/category/".$category;
 +              }
  
 -              if ($public_feed)
 +              if ($public_feed) {
                        $author = "dfrn:owner";
 -              else
 +              } else {
                        $author = "author";
 +              }
  
                $root = self::add_header($doc, $owner, $author, $alternatelink, true);
  
 -              // This hook can't work anymore
 +              /// @TODO This hook can't work anymore
                //      call_hooks('atom_feed', $atom);
  
 -              if (!count($items) OR $onlyheader) {
 +              if (!dbm::is_result($items) OR $onlyheader) {
                        $atom = trim($doc->saveXML());
  
                        call_hooks('atom_feed_end', $atom);
                        return $atom;
                }
  
 -              foreach($items as $item) {
 +              foreach ($items as $item) {
  
                        // prevent private email from leaking.
 -                      if($item['network'] == NETWORK_MAIL)
 +                      if ($item['network'] == NETWORK_MAIL) {
                                continue;
 +                      }
  
                        // public feeds get html, our own nodes use bbcode
  
 -                      if($public_feed) {
 +                      if ($public_feed) {
                                $type = 'html';
                                // catch any email that's in a public conversation and make sure it doesn't leak
 -                              if($item['private'])
 +                              if ($item['private']) {
                                        continue;
 -                      } else
 +                              }
 +                      } else {
                                $type = 'text';
 +                      }
  
                        $entry = self::entry($doc, $type, $item, $owner, true);
                        $root->appendChild($entry);
         * @param array $owner Owner record
         *
         * @return string DFRN mail
 +       * @todo Add type-hints
         */
        public static function mail($item, $owner) {
                $doc = new DOMDocument('1.0', 'utf-8');
         * @param array $owner Owner record
         *
         * @return string DFRN suggestions
 +       * @todo Add type-hints
         */
        public static function fsuggest($item, $owner) {
                $doc = new DOMDocument('1.0', 'utf-8');
         * @param int $uid User ID
         *
         * @return string DFRN relocations
 +       * @todo Add type-hints
         */
        public static function relocate($owner, $uid) {
  
                /* get site pubkey. this could be a new installation with no site keys*/
                $pubkey = get_config('system','site_pubkey');
 -              if(! $pubkey) {
 +              if (! $pubkey) {
                        $res = new_keypair(1024);
                        set_config('system','site_prvkey', $res['prvkey']);
                        set_config('system','site_pubkey', $res['pubkey']);
                $photos = array();
                $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']];
 +              }
  
                unset($rp, $ext);
  
         * @param bool $public Is it a header for public posts?
         *
         * @return object XML root object
 +       * @todo Add type-hints
         */
        private static function add_header($doc, $owner, $authorelement, $alternatelink = "", $public = false) {
  
 -              if ($alternatelink == "")
 +              if ($alternatelink == "") {
                        $alternatelink = $owner['url'];
 +              }
  
                $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
                $doc->appendChild($root);
                }
  
                // 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);
 +              }
  
                // The former element is replaced by this one
                xml::add_element($doc, $root, "dfrn:account_type", $owner["account-type"]);
         * @param string $authorelement Element name for the author
         *
         * @return object XML author object
 +       * @todo Add type-hints
         */
        private static function add_author($doc, $owner, $authorelement, $public) {
  
                $r = q("SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
                                WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
                        intval($owner['uid']));
 -              if ($r)
 +              if (dbm::is_result($r)) {
                        $hidewall = true;
 -              else
 +              } else {
                        $hidewall = false;
 +              }
  
                $author = $doc->createElement($authorelement);
  
                $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
                $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
  
 -              if (!$public OR !$hidewall)
 +              $attributes = array();
 +
 +              if (!$public OR !$hidewall) {
                        $attributes = array("dfrn:updated" => $namdate);
 -              else
 -                      $attributes = array();
 +              }
  
                xml::add_element($doc, $author, "name", $owner["name"], $attributes);
                xml::add_element($doc, $author, "uri", app::get_baseurl().'/profile/'.$owner["nickname"], $attributes);
                $attributes = array("rel" => "photo", "type" => "image/jpeg",
                                        "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
  
 -              if (!$public OR !$hidewall)
 +              if (!$public OR !$hidewall) {
                        $attributes["dfrn:updated"] = $picdate;
 +              }
  
                xml::add_element($doc, $author, "link", "", $attributes);
  
                $attributes["rel"] = "avatar";
                xml::add_element($doc, $author, "link", "", $attributes);
  
 -              if ($hidewall)
 +              if ($hidewall) {
                        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
 -              if ($public)
 +              if ($public) {
                        return $author;
 +              }
  
                $birthday = feed_birthday($owner['uid'], $owner['timezone']);
  
                                INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
                                WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
                        intval($owner['uid']));
 -              if ($r) {
 +              if (dbm::is_result($r)) {
                        $profile = $r[0];
  
                        xml::add_element($doc, $author, "poco:displayName", $profile["name"]);
                        if (trim($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, $element, "poco:formatted", formatted_location($profile));
  
 -                              if (trim($profile["locality"]) != "")
 +                              if (trim($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"]);
 +                              }
  
 -                              if (trim($profile["country-name"]) != "")
 +                              if (trim($profile["country-name"]) != "") {
                                        xml::add_element($doc, $element, "poco:country", $profile["country-name"]);
 +                              }
  
                                $author->appendChild($element);
                        }
         * @param array $items Item elements
         *
         * @return object XML author object
 +       * @todo Add type-hints
         */
        private static function add_entry_author($doc, $element, $contact_url, $item) {
  
         * @param string $activity activity value
         *
         * @return object XML activity object
 +       * @todo Add type-hints
         */
        private static function create_activity($doc, $element, $activity) {
  
 -              if($activity) {
 +              if ($activity) {
                        $entry = $doc->createElement($element);
  
                        $r = parse_xml_string($activity, false);
 -                      if(!$r)
 +                      if (!$r) {
                                return false;
 -                      if($r->type)
 +                      }
 +                      if ($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);
 -                      if($r->title)
 +                      }
 +                      if ($r->title) {
                                xml::add_element($doc, $entry, "title", $r->title);
 -                      if($r->link) {
 -                              if(substr($r->link,0,1) == '<') {
 -                                      if(strstr($r->link,'&') && (! strstr($r->link,'&amp;')))
 -                                              $r->link = str_replace('&','&amp;', $r->link);
 +                      }
  
 -                                      $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
 +                      if ($r->link) {
 +                              if (substr($r->link, 0, 1) == '<') {
 +                                      if (strstr($r->link, '&') && (! strstr($r->link, '&amp;'))) {
 +                                              $r->link = str_replace('&', '&amp;', $r->link);
 +                                      }
 +
 +                                      $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
  
                                        // XML does need a single element as root element so we add a dummy element here
 -                                      $data = parse_xml_string("<dummy>".$r->link."</dummy>", false);
 +                                      $data = parse_xml_string("<dummy>" . $r->link . "</dummy>", false);
                                        if (is_object($data)) {
                                                foreach ($data->link AS $link) {
                                                        $attributes = array();
 -                                                      foreach ($link->attributes() AS $parameter => $value)
 +                                                      foreach ($link->attributes() AS $parameter => $value) {
                                                                $attributes[$parameter] = $value;
 +                                                      }
                                                        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"));
 +                      }
  
                        return $entry;
                }
         * @param array $item Item element
         *
         * @return object XML attachment object
 +       * @todo Add type-hints
         */
        private static function get_attachment($doc, $root, $item) {
                $arr = explode('[/attach],',$item['attach']);
 -              if(count($arr)) {
 -                      foreach($arr as $r) {
 +              if (count($arr)) {
 +                      foreach ($arr as $r) {
                                $matches = false;
                                $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
 -                              if($cnt) {
 +                              if ($cnt) {
                                        $attributes = array("rel" => "enclosure",
                                                        "href" => $matches[1],
                                                        "type" => $matches[3]);
  
 -                                      if(intval($matches[2]))
 +                                      if (intval($matches[2])) {
                                                $attributes["length"] = intval($matches[2]);
 +                                      }
  
 -                                      if(trim($matches[4]) != "")
 +                                      if (trim($matches[4]) != "") {
                                                $attributes["title"] = trim($matches[4]);
 +                                      }
  
                                        xml::add_element($doc, $root, "link", "", $attributes);
                                }
         * @param int $cid Contact ID of the recipient
         *
         * @return object XML entry object
 +       * @todo Add type-hints
         */
        private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0) {
  
                $mentioned = array();
  
 -              if(!$item['parent'])
 +              if (!$item['parent']) {
                        return;
 +              }
  
 -              if($item['deleted']) {
 +              if ($item['deleted']) {
                        $attributes = array("ref" => $item['uri'], "when" => datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME));
                        return xml::create_element($doc, "at:deleted-entry", "", $attributes);
                }
  
                $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);
 -              else
 +              } else {
                        $body = $item['body'];
 +              }
  
                // Remove the abstract element. It is only locally important.
                $body = remove_abstract($body);
                if ($type == 'html') {
                        $htmlbody = $body;
  
 -                      if ($item['title'] != "")
 +                      if ($item['title'] != "") {
                                $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
 +                      }
  
                        $htmlbody = bbcode($htmlbody, false, false, 7);
                }
                $dfrnowner = self::add_entry_author($doc, "dfrn:owner", $item["owner-link"], $item);
                $entry->appendChild($dfrnowner);
  
 -              if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
 +              if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
                        $parent = q("SELECT `guid` FROM `item` WHERE `id` = %d", intval($item["parent"]));
                        $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
                        $attributes = array("ref" => $parent_item, "type" => "text/html",
  
                // "comment-allow" is some old fashioned stuff for old Friendica versions.
                // 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']));
 +              }
  
 -              if($item['location'])
 +              if ($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']);
 +              }
  
 -              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));
 +              }
  
 -              if($item['extid'])
 +              if ($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");
 +              }
  
 -              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, "dfrn:diaspora_guid", $item["guid"]);
  
  
                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']);
 -              elseif ($item['id'] == $item['parent'])
 +              } elseif ($item['id'] == $item['parent']) {
                        xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
 -              else
 +              } else {
                        xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
 +              }
  
                $actobj = self::create_activity($doc, "activity:object", $item['object']);
 -              if ($actobj)
 +              if ($actobj) {
                        $entry->appendChild($actobj);
 +              }
  
                $actarg = self::create_activity($doc, "activity:target", $item['target']);
 -              if ($actarg)
 +              if ($actarg) {
                        $entry->appendChild($actarg);
 +              }
  
                $tags = item_getfeedtags($item);
  
 -              if(count($tags)) {
 -                      foreach($tags as $t)
 -                              if (($type != 'html') OR ($t[0] != "@"))
 +              if (count($tags)) {
 +                      foreach ($tags as $t) {
 +                              if (($type != 'html') OR ($t[0] != "@")) {
                                        xml::add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]));
 +                              }
 +                      }
                }
  
 -              if(count($tags))
 -                      foreach($tags as $t)
 -                              if ($t[0] == "@")
 +              if (count($tags)) {
 +                      foreach ($tags as $t) {
 +                              if ($t[0] == "@") {
                                        $mentioned[$t[1]] = $t[1];
 +                              }
 +                      }
 +              }
  
                foreach ($mentioned AS $mention) {
                        $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
                                intval($owner["uid"]),
                                dbesc(normalise_link($mention)));
 -                      if ($r[0]["forum"] OR $r[0]["prv"])
 +
 +                      if (dbm::is_result($r) AND ($r[0]["forum"] OR $r[0]["prv"])) {
                                xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
                                                                                        "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
                                                                                        "href" => $mention));
 -                      else
 +                      } else {
                                xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
                                                                                        "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
                                                                                        "href" => $mention));
 +                      }
                }
  
                self::get_attachment($doc, $entry, $item);
                return $entry;
        }
  
+       /**
+        * @brief encrypts data via AES
+        *
+        * @param string $data The data that is to be encrypted
+        * @param string $key The AES key
+        *
+        * @return string encrypted data
+        */
+       private static function aes_encrypt($data, $key) {
+               return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
+       }
+       /**
+        * @brief decrypts data via AES
+        *
+        * @param string $encrypted The encrypted data
+        * @param string $key The AES key
+        *
+        * @return string decrypted data
+        */
+       public static function aes_decrypt($encrypted, $key) {
+               return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
+       }
        /**
         * @brief Delivers the atom content to the contacts
         *
         * @param bool $dissolve (to be documented)
         *
         * @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) {
  
  
                $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;
 -              if($contact['duplex'] && $contact['issued-id'])
 +              }
 +              if ($contact['duplex'] && $contact['issued-id']) {
                        $idtosend = '1:' . $orig_id;
 +              }
  
 -
 -              $rino = get_config('system','rino_encrypt');
 +              $rino = get_config('system', 'rino_encrypt');
                $rino = intval($rino);
  
-               // use RINO1 if mcrypt isn't installed and RINO2 was selected
-               if ($rino == 2 and !function_exists('mcrypt_create_iv')) {
-                       $rino = 1;
-               }
                logger("Local rino version: ". $rino, LOGGER_DEBUG);
  
                $ssl_val = intval(get_config('system','ssl_policy'));
                $ssl_policy = '';
  
 -              switch($ssl_val){
 +              switch ($ssl_val) {
                        case SSL_POLICY_FULL:
                                $ssl_policy = 'full';
                                break;
  
                logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
  
 -              if(! $xml)
 +              if (! $xml) {
                        return 3;
 +              }
  
 -              if(strpos($xml,'<?xml') === false) {
 +              if (strpos($xml,'<?xml') === false) {
                        logger('dfrn_deliver: no valid XML returned');
                        logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
                        return 3;
  
                $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);
 +              }
  
                $postvars     = array();
                $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
  
                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;
 +              }
  
                $final_dfrn_id = '';
  
 -              if($perm) {
 -                      if((($perm == 'rw') && (! intval($contact['writable'])))
 +              if ($perm) {
 +                      if ((($perm == 'rw') && (! intval($contact['writable'])))
                                || (($perm == 'r') && (intval($contact['writable'])))) {
                                q("update contact set writable = %d where id = %d",
                                        intval(($perm == 'rw') ? 1 : 0),
                        }
                }
  
 -              if(($contact['duplex'] && strlen($contact['pubkey']))
 +              if (($contact['duplex'] && strlen($contact['pubkey']))
                        || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
                        || ($contact['rel'] == CONTACT_IS_SHARING && strlen($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, '.'));
  
 -              if(strpos($final_dfrn_id,':') == 1)
 +              if (strpos($final_dfrn_id,':') == 1) {
                        $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.');
                        // did not decode properly - cannot trust this site
                        return 3;
  
                $postvars['dfrn_id']      = $idtosend;
                $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
 -              if($dissolve)
 +              if ($dissolve) {
                        $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)) {
                        $postvars['data'] = $atom;
                        $postvars['perm'] = 'rw';
                } else {
  
                $postvars['ssl_policy'] = $ssl_policy;
  
 -              if($page)
 +              if ($page) {
                        $postvars['page'] = $page;
 +              }
  
  
 -              if($rino>0 && $rino_remote_version>0 && (! $dissolve)) {
 +              if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
                        logger('rino version: '. $rino_remote_version);
  
 -                      switch($rino_remote_version) {
 +                      switch ($rino_remote_version) {
                                case 1:
                                        // Deprecated rino version!
-                                       $key = substr(random_string(), 0, 16);
-                                       $data = aes_encrypt($postvars['data'],$key);
+                                       $key = openssl_random_pseudo_bytes(16);
+                                       $data = self::aes_encrypt($postvars['data'], $key);
                                        break;
                                case 2:
                                        // RINO 2 based on php-encryption
                        $postvars['rino'] = $rino_remote_version;
                        $postvars['data'] = bin2hex($data);
  
 -                      #logger('rino: sent key = ' . $key, LOGGER_DEBUG);
 -
 +                      //logger('rino: sent key = ' . $key, LOGGER_DEBUG);
  
 -                      if($dfrn_version >= 2.1) {
 -                              if(($contact['duplex'] && strlen($contact['pubkey']))
 -                                      || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
 -                                      || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey'])))
  
 +                      if ($dfrn_version >= 2.1) {
 +                              if (($contact['duplex'] && strlen($contact['pubkey']))
 +                                              || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
 +                                              || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
                                        openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
 -                              else
 +                              } else {
                                        openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
 +                              }
  
                        } 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']);
 -                              else
 +                              } else {
                                        openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
 +                              }
  
                        }
  
                        return -10;
                }
  
 -              if(strpos($xml,'<?xml') === false) {
 +              if (strpos($xml,'<?xml') === false) {
                        logger('dfrn_deliver: phase 2: no valid XML returned');
                        logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
                        return 3;
         *
         * @param array $contact Contact record
         * @param string $birthday Birthday of the contact
 -       *
 +       * @todo Add array type-hint for $contact
         */
        private static function birthday_event($contact, $birthday) {
  
         * @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
 +       * @todo Find good type-hints for all parameter
         */
        private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "") {
  
                                `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
                                FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
                        intval($importer["uid"]), dbesc(normalise_link($author["link"])), dbesc(NETWORK_STATUSNET));
 -              if ($r) {
 +
 +              if (dbm::is_result($r)) {
                        $contact = $r[0];
                        $author["contact-id"] = $r[0]["id"];
                        $author["network"] = $r[0]["network"];
                } else {
 -                      if (!$onlyfetch)
 +                      if (!$onlyfetch) {
                                logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
 +                      }
  
                        $author["contact-id"] = $importer["id"];
                        $author["network"] = $importer["network"];
                $avatarlist = array();
                /// @todo check if "avatar" or "photo" would be the best field in the specification
                $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
 -              foreach($avatars AS $avatar) {
 +              foreach ($avatars AS $avatar) {
                        $href = "";
                        $width = 0;
 -                      foreach($avatar->attributes AS $attributes) {
 -                              if ($attributes->name == "href")
 +                      foreach ($avatar->attributes AS $attributes) {
 +                              /// @TODO Rewrite these similar if() to one switch
 +                              if ($attributes->name == "href") {
                                        $href = $attributes->textContent;
 -                              if ($attributes->name == "width")
 +                              }
 +                              if ($attributes->name == "width") {
                                        $width = $attributes->textContent;
 -                              if ($attributes->name == "updated")
 +                              }
 +                              if ($attributes->name == "updated") {
                                        $contact["avatar-date"] = $attributes->textContent;
 +                              }
                        }
 -                      if (($width > 0) AND ($href != ""))
 +                      if (($width > 0) AND ($href != "")) {
                                $avatarlist[$width] = $href;
 +                      }
                }
                if (count($avatarlist) > 0) {
                        krsort($avatarlist);
                        $author["avatar"] = current($avatarlist);
                }
  
 -              if ($r AND !$onlyfetch) {
 -                      logger("Check if contact details for contact ".$r[0]["id"]." (".$r[0]["nick"].") have to be updated.", LOGGER_DEBUG);
 +              if (dbm::is_result($r) AND !$onlyfetch) {
 +                      logger("Check if contact details for contact " . $r[0]["id"] . " (" . $r[0]["nick"] . ") have to be updated.", LOGGER_DEBUG);
  
                        $poco = array("url" => $contact["url"]);
  
                        // When was the last change to name or uri?
 -                      $name_element = $xpath->query($element."/atom:name", $context)->item(0);
 -                      foreach($name_element->attributes AS $attributes)
 -                              if ($attributes->name == "updated")
 +                      $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
 +                      foreach ($name_element->attributes AS $attributes) {
 +                              if ($attributes->name == "updated") {
                                        $poco["name-date"] = $attributes->textContent;
 +                              }
 +                      }
  
 -                      $link_element = $xpath->query($element."/atom:link", $context)->item(0);
 -                      foreach($link_element->attributes AS $attributes)
 -                              if ($attributes->name == "updated")
 +                      $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
 +                      foreach ($link_element->attributes AS $attributes) {
 +                              if ($attributes->name == "updated") {
                                        $poco["uri-date"] = $attributes->textContent;
 +                              }
 +                      }
  
                        // Update contact data
 -                      $value = $xpath->evaluate($element."/dfrn:handle/text()", $context)->item(0)->nodeValue;
 -                      if ($value != "")
 +                      $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
 +                      if ($value != "") {
                                $poco["addr"] = $value;
 +                      }
  
 -                      $value = $xpath->evaluate($element."/poco:displayName/text()", $context)->item(0)->nodeValue;
 -                      if ($value != "")
 +                      $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
 +                      if ($value != "") {
                                $poco["name"] = $value;
 +                      }
  
 -                      $value = $xpath->evaluate($element."/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
 -                      if ($value != "")
 +                      $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
 +                      if ($value != "") {
                                $poco["nick"] = $value;
 +                      }
  
 -                      $value = $xpath->evaluate($element."/poco:note/text()", $context)->item(0)->nodeValue;
 -                      if ($value != "")
 +                      $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
 +                      if ($value != "") {
                                $poco["about"] = $value;
 +                      }
  
 -                      $value = $xpath->evaluate($element."/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
 -                      if ($value != "")
 +                      $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
 +                      if ($value != "") {
                                $poco["location"] = $value;
 +                      }
  
                        /// @todo Only search for elements with "poco:type" = "xmpp"
 -                      $value = $xpath->evaluate($element."/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
 -                      if ($value != "")
 +                      $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
 +                      if ($value != "") {
                                $poco["xmpp"] = $value;
 +                      }
  
                        /// @todo Add support for the following fields that we don't support by now in the contact table:
                        /// - poco:utcOffset
                        /// - poco:country
  
                        // If the "hide" element is present then the profile isn't searchable.
 -                      $hide = intval($xpath->evaluate($element."/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
 +                      $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
  
 -                      logger("Hidden status for contact ".$contact["url"].": ".$hide, LOGGER_DEBUG);
 +                      logger("Hidden status for contact " . $contact["url"] . ": " . $hide, LOGGER_DEBUG);
  
                        // If the contact isn't searchable then set the contact to "hidden".
                        // Problem: This can be manually overridden by the user.
 -                      if ($hide)
 +                      if ($hide) {
                                $contact["hidden"] = true;
 +                      }
  
                        // Save the keywords into the contact table
                        $tags = array();
 -                      $tagelements = $xpath->evaluate($element."/poco:tags/text()", $context);
 -                      foreach($tagelements AS $tag)
 +                      $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
 +                      foreach ($tagelements AS $tag) {
                                $tags[$tag->nodeValue] = $tag->nodeValue;
 +                      }
  
 -                      if (count($tags))
 +                      if (count($tags)) {
                                $poco["keywords"] = implode(", ", $tags);
 +                      }
  
                        // "dfrn:birthday" contains the birthday converted to UTC
                        $old_bdyear = $contact["bdyear"];
  
 -                      $birthday = $xpath->evaluate($element."/dfrn:birthday/text()", $context)->item(0)->nodeValue;
 +                      $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
  
                        if (strtotime($birthday) > time()) {
                                $bd_timestamp = strtotime($birthday);
                        }
  
                        // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
 -                      $value = $xpath->evaluate($element."/poco:birthday/text()", $context)->item(0)->nodeValue;
 +                      $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
  
                        if (!in_array($value, array("", "0000-00-00"))) {
                                $bdyear = date("Y");
  
                        $contact = array_merge($contact, $poco);
  
 -                      if ($old_bdyear != $contact["bdyear"])
 +                      if ($old_bdyear != $contact["bdyear"]) {
                                self::birthday_event($contact, $birthday);
 +                      }
  
                        // Get all field names
                        $fields = array();
 -                      foreach ($r[0] AS $field => $data)
 +                      foreach ($r[0] AS $field => $data) {
                                $fields[$field] = $data;
 +                      }
  
                        unset($fields["id"]);
                        unset($fields["uid"]);
  
                        // Update check for this field has to be done differently
                        $datefields = array("name-date", "uri-date");
 -                      foreach ($datefields AS $field)
 +                      foreach ($datefields AS $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;
                                }
 +                      }
  
 -                      foreach ($fields AS $field => $data)
 +                      foreach ($fields AS $field => $data) {
                                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;
                                }
 +                      }
  
                        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);
  
                                q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
                                        `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
                        update_contact_avatar($author["avatar"], $importer["uid"], $contact["id"],
                                                (strtotime($contact["avatar-date"]) > strtotime($r[0]["avatar-date"])));
  
 -                      // The generation is a sign for the reliability of the provided data.
 -                      // It is used in the socgraph.php to prevent that old contact data
 -                      // that was relayed over several servers can overwrite contact
 -                      // data that we received directly.
 +                      /*
 +                       * The generation is a sign for the reliability of the provided data.
 +                       * It is used in the socgraph.php to prevent that old contact data
 +                       * that was relayed over several servers can overwrite contact
 +                       * data that we received directly.
 +                       */
  
                        $poco["generation"] = 2;
                        $poco["photo"] = $author["avatar"];
                        $poco["hide"] = $hide;
                        $poco["contact-type"] = $contact["contact-type"];
-                       update_gcontact($poco);
+                       $gcid = update_gcontact($poco);
+                       link_gcontact($gcid, $importer["uid"], $contact["id"]);
                }
  
                return($author);
         * @param text $element element name
         *
         * @return string XML string
 +       * @todo Find good type-hints for all parameter
         */
        private static function transform_activity($xpath, $activity, $element) {
 -              if (!is_object($activity))
 +              if (!is_object($activity)) {
                        return "";
 +              }
  
                $obj_doc = new DOMDocument("1.0", "utf-8");
                $obj_doc->formatOutput = true;
                xml::add_element($obj_doc, $obj_element, "type", $activity_type);
  
                $id = $xpath->query("atom:id", $activity)->item(0);
 -              if (is_object($id))
 +              if (is_object($id)) {
                        $obj_element->appendChild($obj_doc->importNode($id, true));
 +              }
  
                $title = $xpath->query("atom:title", $activity)->item(0);
 -              if (is_object($title))
 +              if (is_object($title)) {
                        $obj_element->appendChild($obj_doc->importNode($title, true));
 +              }
  
                $links = $xpath->query("atom:link", $activity);
 -              if (is_object($links))
 -                      foreach ($links AS $link)
 +              if (is_object($links)) {
 +                      foreach ($links AS $link) {
                                $obj_element->appendChild($obj_doc->importNode($link, true));
 +                      }
 +              }
  
                $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_doc->appendChild($obj_element);
  
         * @param object $xpath XPath object
         * @param object $mail mail elements
         * @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) {
  
                logger("Processing mails");
  
 +              /// @TODO Rewrite this to one statement
                $msg = array();
                $msg["uid"] = $importer["importer_uid"];
                $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
                $r = dbq("INSERT INTO `mail` (`".implode("`, `", array_keys($msg))."`) VALUES (".implode(", ", array_values($msg)).")");
  
                // send notifications.
 -
 +              /// @TODO Arange this mess
                $notif_params = array(
                        "type" => NOTIFY_MAIL,
                        "notify_flags" => $importer["notify-flags"],
         * @param object $xpath XPath object
         * @param object $suggestion suggestion elements
         * @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) {
                $a = get_app();
  
                logger("Processing suggestions");
  
 +              /// @TODO Rewrite this to one statement
                $suggest = array();
                $suggest["uid"] = $importer["importer_uid"];
                $suggest["cid"] = $importer["id"];
                        dbesc(normalise_link($suggest["url"])),
                        intval($suggest["uid"])
                );
 -              if (dbm::is_result($r))
 +
 +              /*
 +               * The valid result means the friend we're about to send a friend
 +               * suggestion already has them in their contact, which means no further
 +               * action is required.
 +               *
 +               * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
 +               */
 +              if (dbm::is_result($r)) {
                        return false;
 +              }
  
                // Do we already have an fcontact record for this person?
  
                                intval($suggest["uid"]),
                                intval($fid)
                        );
 -                      if (dbm::is_result($r))
 +
 +                      /*
 +                       * The valid result means the friend we're about to send a friend
 +                       * suggestion already has them in their contact, which means no further
 +                       * action is required.
 +                       *
 +                       * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
 +                       */
 +                      if (dbm::is_result($r)) {
                                return false;
 +                      }
                }
 -              if(!$fid)
 +              if (!$fid) {
                        $r = q("INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
 -                      dbesc($suggest["name"]),
 -                      dbesc($suggest["url"]),
 -                      dbesc($suggest["photo"]),
 -                      dbesc($suggest["request"])
 -              );
 +                              dbesc($suggest["name"]),
 +                              dbesc($suggest["url"]),
 +                              dbesc($suggest["photo"]),
 +                              dbesc($suggest["request"])
 +                      );
 +              }
                $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
                        dbesc($suggest["url"]),
                        dbesc($suggest["name"]),
                        dbesc($suggest["request"])
                );
 -              if (dbm::is_result($r))
 -                      $fid = $r[0]["id"];
 -              else
 +
 +              /*
 +               * If no record in fcontact is found, below INSERT statement will not
 +               * link an introduction to it.
 +               */
 +              if (!dbm::is_result($r)) {
                        // database record did not get created. Quietly give up.
 -                      return false;
 +                      killme();
 +              }
  
 +              $fid = $r[0]["id"];
  
                $hash = random_string();
  
         * @param object $xpath XPath object
         * @param object $relocation relocation elements
         * @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) {
  
                logger("Processing relocations");
  
 +              /// @TODO Rewrite this to one statement
                $relocate = array();
                $relocate["uid"] = $importer["importer_uid"];
                $relocate["cid"] = $importer["id"];
                $relocate["poll"] = $xpath->query("dfrn:poll/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"];
 +              }
  
 -              if ($relocate["addr"] == "")
 +              if ($relocate["addr"] == "") {
                        $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
 +              }
  
                // update contact
                $r = q("SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
                        intval($importer["id"]),
                        intval($importer["importer_uid"]));
 -              if (!$r)
 +
 +              if (!dbm::is_result($r)) {
 +                      logger("Query failed to execute, no result returned in " . __FUNCTION__);
                        return false;
 +              }
  
                $old = $r[0];
  
  
                update_contact_avatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
  
 -              if ($x === false)
 +              if ($x === false) {
                        return false;
 +              }
  
                // update items
                /// @todo This is an extreme performance killer
                        'author-link' => array($old["url"], $relocate["url"]),
                        //'owner-avatar' => array($old["photo"], $relocate["photo"]),
                        //'author-avatar' => array($old["photo"], $relocate["photo"]),
 -                      );
 +              );
                foreach ($fields as $n=>$f) {
                        $r = q("SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
                                        $n, dbesc($f[0]),
                                        intval($importer["importer_uid"]));
  
 -                      if ($r) {
 +                      if (dbm::is_result($r)) {
                                $x = q("UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
                                                $n, dbesc($f[1]),
                                                $n, dbesc($f[0]),
                                                intval($importer["importer_uid"]));
 -                                      if ($x === false)
 +
 +                                      if ($x === false) {
                                                return false;
 +                                      }
                        }
                }
  
         * @param array $item the new item record
         * @param array $importer Record of the importer user mixed with contact of the content
         * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
 +       * @todo set proper type-hints (array?)
         */
        private static function update_content($current, $item, $importer, $entrytype) {
                $changed = false;
                if (edited_timestamp_is_newer($current, $item)) {
  
                        // do not accept (ignore) an earlier edit than one we currently have.
 -                      if(datetime_convert("UTC","UTC",$item["edited"]) < $current["edited"])
 -                              return(false);
 +                      if (datetime_convert("UTC","UTC",$item["edited"]) < $current["edited"]) {
 +                              return false;
 +                      }
  
                        $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
                                dbesc($item["title"]),
  
                        $changed = true;
  
 -                      if ($entrytype == DFRN_REPLY_RC)
 +                      if ($entrytype == DFRN_REPLY_RC) {
                                proc_run(PRIORITY_HIGH, "include/notifier.php","comment-import", $current["id"]);
 +                      }
                }
  
                // 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"])) {
                        $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
                                dbesc(datetime_convert()),
                                dbesc($item["parent-uri"]),
         * @param array $item the new item record
         *
         * @return int Is it a toplevel entry, a comment or a relayed comment?
 +       * @todo set proper type-hints (array?)
         */
        private static function get_entry_type($importer, $item) {
                if ($item["parent-uri"] != $item["uri"]) {
                        $community = false;
  
 -                      if($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
 +                      if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
                                $sql_extra = "";
                                $community = true;
                                logger("possible community action");
 -                      } else
 +                      } else {
                                $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
 +                      }
  
                        // was the top-level post for this action written by somebody on this site?
                        // Specifically, the recipient?
                                        dbesc($r[0]["parent-uri"]),
                                        intval($importer["importer_uid"])
                                );
 -                              if (dbm::is_result($r))
 +                              if (dbm::is_result($r)) {
                                        $is_a_remote_action = true;
 +                              }
                        }
  
 -                      // 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
 -                      // valid community action. Also forum_mode makes it valid for sure.
 -                      // If neither, it's not.
 -
 -                      if($is_a_remote_action && $community) {
 -                              if((!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
 -                                      $is_a_remote_action = false;
 -                                      logger("not a community 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
 +                       * valid community action. Also forum_mode makes it valid for sure.
 +                       * If neither, it's not.
 +                       */
 +
 +                      /// @TODO Maybe merge these if() blocks into one?
 +                      if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
 +                              $is_a_remote_action = false;
 +                              logger("not a community action");
                        }
  
 -                      if ($is_a_remote_action)
 +                      if ($is_a_remote_action) {
                                return DFRN_REPLY_RC;
 -                      else
 +                      } else {
                                return DFRN_REPLY;
 -
 -              } else
 +                      }
 +              } else {
                        return DFRN_TOP_LEVEL;
 +              }
  
        }
  
         * @param array $item the new item record
         * @param array $importer Record of the importer user mixed with contact of the content
         * @param int $posted_id The record number of item record that was just posted
 +       * @todo set proper type-hints (array?)
         */
        private static function do_poke($item, $importer, $posted_id) {
                $verb = urldecode(substr($item["verb"],strpos($item["verb"], "#")+1));
 -              if(!$verb)
 +              if (!$verb) {
                        return;
 +              }
                $xo = parse_xml_string($item["object"],false);
  
 -              if(($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
 +              if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
  
                        // somebody was poked/prodded. Was it me?
 -                      foreach($xo->link as $l) {
 +                      foreach ($xo->link as $l) {
                                $atts = $l->attributes();
 -                              switch($atts["rel"]) {
 +                              switch ($atts["rel"]) {
                                        case "alternate":
                                                $Blink = $atts["href"];
                                                break;
                                }
                        }
  
 -                      if($Blink && link_compare($Blink,App::get_baseurl()."/profile/".$importer["nickname"])) {
 +                      if ($Blink && link_compare($Blink, App::get_baseurl() . "/profile/" . $importer["nickname"])) {
  
                                // send a notification
                                notification(array(
         * @param bool $is_like Is the verb a "like"?
         *
         * @return bool Should the processing of the entries be continued?
 +       * @todo set proper type-hints (array?)
         */
        private static function process_verbs($entrytype, $importer, &$item, &$is_like) {
  
  
                        // Big question: Do we need these functions? They were part of the "consume_feed" function.
                        // This function once was responsible for DFRN and OStatus.
 -                      if(activity_match($item["verb"],ACTIVITY_FOLLOW)) {
 +                      if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
                                logger("New follower");
                                new_follower($importer, $contact, $item, $nickname);
                                return false;
                        }
 -                      if(activity_match($item["verb"],ACTIVITY_UNFOLLOW))  {
 +                      if (activity_match($item["verb"], ACTIVITY_UNFOLLOW))  {
                                logger("Lost follower");
                                lose_follower($importer, $contact, $item);
                                return false;
                        }
 -                      if(activity_match($item["verb"],ACTIVITY_REQ_FRIEND)) {
 +                      if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
                                logger("New friend request");
                                new_follower($importer, $contact, $item, $nickname, true);
                                return false;
                        }
 -                      if(activity_match($item["verb"],ACTIVITY_UNFRIEND))  {
 +                      if (activity_match($item["verb"], ACTIVITY_UNFRIEND))  {
                                logger("Lost sharer");
                                lose_sharer($importer, $contact, $item);
                                return false;
                        }
                } else {
 -                      if(($item["verb"] == ACTIVITY_LIKE)
 +                      if (($item["verb"] == ACTIVITY_LIKE)
                                || ($item["verb"] == ACTIVITY_DISLIKE)
                                || ($item["verb"] == ACTIVITY_ATTEND)
                                || ($item["verb"] == ACTIVITY_ATTENDNO)
                                        dbesc($item["verb"]),
                                        dbesc($item["parent-uri"])
                                );
 -                              if (dbm::is_result($r))
 +                              if (dbm::is_result($r)) {
                                        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",
                                        intval($item["uid"]),
                                        dbesc($item["verb"]),
                                        dbesc($item["parent-uri"])
                                );
 -                              if (dbm::is_result($r))
 +                              if (dbm::is_result($r)) {
                                        return false;
 -                      } else
 +                              }
 +                      } else {
                                $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)) {
  
                                $xo = parse_xml_string($item["object"],false);
                                $xt = parse_xml_string($item["target"],false);
  
 -                              if($xt->type == ACTIVITY_OBJ_NOTE) {
 +                              if ($xt->type == ACTIVITY_OBJ_NOTE) {
                                        $r = q("SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
                                                dbesc($xt->id),
                                                intval($importer["importer_uid"])
                                        );
  
 -                                      if (!dbm::is_result($r))
 +                                      if (!dbm::is_result($r)) {
 +                                              logger("Query failed to execute, no result returned in " . __FUNCTION__);
                                                return false;
 +                                      }
  
                                        // extract tag, if not duplicate, add to parent item
 -                                      if($xo->content) {
 -                                              if(!(stristr($r[0]["tag"],trim($xo->content)))) {
 +                                      if ($xo->content) {
 +                                              if (!(stristr($r[0]["tag"],trim($xo->content)))) {
                                                        q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
                                                                dbesc($r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
                                                                intval($r[0]["id"])
         *
         * @param object $links link elements
         * @param array $item the item record
 +       * @todo set proper type-hints
         */
        private static function parse_links($links, &$item) {
                $rel = "";
                $length = "0";
                $title = "";
                foreach ($links AS $link) {
 -                      foreach($link->attributes AS $attributes) {
 -                              if ($attributes->name == "href")
 +                      foreach ($link->attributes AS $attributes) {
 +                              /// @TODO Rewrite these repeated (same) if() statements to a switch()
 +                              if ($attributes->name == "href") {
                                        $href = $attributes->textContent;
 -                              if ($attributes->name == "rel")
 +                              }
 +                              if ($attributes->name == "rel") {
                                        $rel = $attributes->textContent;
 -                              if ($attributes->name == "type")
 +                              }
 +                              if ($attributes->name == "type") {
                                        $type = $attributes->textContent;
 -                              if ($attributes->name == "length")
 +                              }
 +                              if ($attributes->name == "length") {
                                        $length = $attributes->textContent;
 -                              if ($attributes->name == "title")
 +                              }
 +                              if ($attributes->name == "title") {
                                        $title = $attributes->textContent;
 +                              }
                        }
 -                      if (($rel != "") AND ($href != ""))
 -                              switch($rel) {
 +                      if (($rel != "") AND ($href != "")) {
 +                              switch ($rel) {
                                        case "alternate":
                                                $item["plink"] = $href;
                                                break;
                                        case "enclosure":
                                                $enclosure = $href;
 -                                              if(strlen($item["attach"]))
 +                                              if (strlen($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;
                                }
 +                      }
                }
        }
  
         * @param object $xpath XPath object
         * @param object $entry entry elements
         * @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) {
  
                $item["body"] = limit_body_size($item["body"]);
  
                /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
 -              if((strpos($item['body'],'<') !== false) && (strpos($item['body'],'>') !== false)) {
 +              if ((strpos($item['body'],'<') !== false) && (strpos($item['body'],'>') !== false)) {
  
                        $item['body'] = reltoabs($item['body'],$base_url);
  
                $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
  
                $georsspoint = $xpath->query("georss:point", $entry);
 -              if ($georsspoint)
 +              if ($georsspoint) {
                        $item["coord"] = $georsspoint->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;
  
 -              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;
 +              }
  
                $notice_info = $xpath->query("statusnet:notice_info", $entry);
                if ($notice_info AND ($notice_info->length > 0)) {
 -                      foreach($notice_info->item(0)->attributes AS $attributes) {
 -                              if ($attributes->name == "source")
 +                      foreach ($notice_info->item(0)->attributes AS $attributes) {
 +                              if ($attributes->name == "source") {
                                        $item["app"] = strip_tags($attributes->textContent);
 +                              }
                        }
                }
  
  
                // 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);
 -              if ($dsprsig != "")
 +              if ($dsprsig != "") {
                        $item["dsprsig"] = $dsprsig;
 +              }
  
                $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;
 +              }
  
                $object = $xpath->query("activity:object", $entry)->item(0);
                $item["object"] = self::transform_activity($xpath, $object, "object");
  
                if (trim($item["object"]) != "") {
                        $r = parse_xml_string($item["object"], false);
 -                      if (isset($r->type))
 +                      if (isset($r->type)) {
                                $item["object-type"] = $r->type;
 +                      }
                }
  
                $target = $xpath->query("activity:target", $entry)->item(0);
                        foreach ($categories AS $category) {
                                $term = "";
                                $scheme = "";
 -                              foreach($category->attributes AS $attributes) {
 -                                      if ($attributes->name == "term")
 +                              foreach ($category->attributes AS $attributes) {
 +                                      if ($attributes->name == "term") {
                                                $term = $attributes->textContent;
 +                                      }
  
 -                                      if ($attributes->name == "scheme")
 +                                      if ($attributes->name == "scheme") {
                                                $scheme = $attributes->textContent;
 +                                      }
                                }
  
                                if (($term != "") AND ($scheme != "")) {
                                                $termhash = array_shift($parts);
                                                $termurl = implode(":", $parts);
  
 -                                              if(strlen($item["tag"]))
 +                                              if (strlen($item["tag"])) {
                                                        $item["tag"] .= ",";
 +                                              }
  
 -                                              $item["tag"] .= $termhash."[url=".$termurl."]".$term."[/url]";
 +                                              $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
                                        }
                                }
                        }
                $enclosure = "";
  
                $links = $xpath->query("atom:link", $entry);
 -              if ($links)
 +              if ($links) {
                        self::parse_links($links, $item);
 +              }
  
                // Is it a reply or a top level posting?
                $item["parent-uri"] = $item["uri"];
  
                $inreplyto = $xpath->query("thr:in-reply-to", $entry);
 -              if (is_object($inreplyto->item(0)))
 -                      foreach($inreplyto->item(0)->attributes AS $attributes)
 -                              if ($attributes->name == "ref")
 +              if (is_object($inreplyto->item(0))) {
 +                      foreach ($inreplyto->item(0)->attributes AS $attributes) {
 +                              if ($attributes->name == "ref") {
                                        $item["parent-uri"] = $attributes->textContent;
 +                              }
 +                      }
 +              }
  
                // Get the type of the item (Top level post, reply or remote reply)
                $entrytype = self::get_entry_type($importer, $item);
  
                // 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 (!isset($item["object-type"]))
 +                      if (!isset($item["object-type"])) {
                                $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"];
 +                      }
  
 -                      if (($item["network"] != $owner["network"]) AND ($owner["network"] != ""))
 +                      if (($item["network"] != $owner["network"]) AND ($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"];
 +                      }
  
 -                      if (($item["network"] != $author["network"]) AND ($author["network"] != ""))
 +                      if (($item["network"] != $author["network"]) AND ($author["network"] != "")) {
                                $item["network"] = $author["network"];
 +                      }
  
 +                      /// @TODO maybe remove this old-lost code then?
                        // This code was taken from the old DFRN code
                        // When activated, forums don't work.
                        // And: Why should we disallow commenting by followers?
                        $item["type"] = "remote-comment";
                        $item["wall"] = 1;
                } elseif ($entrytype == DFRN_TOP_LEVEL) {
 -                      if (!isset($item["object-type"]))
 +                      if (!isset($item["object-type"])) {
                                $item["object-type"] = ACTIVITY_OBJ_NOTE;
 +                      }
  
                        // Is it an event?
                        if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
                                logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
                                $ev = bbtoevent($item["body"]);
 -                              if((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
 +                              if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
                                        logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
 +                                      /// @TODO Mixure of "/' ahead ...
                                        $ev["cid"] = $importer["id"];
                                        $ev["uid"] = $importer["uid"];
                                        $ev["uri"] = $item["uri"];
                                                dbesc($item["uri"]),
                                                intval($importer["uid"])
                                        );
 -                                      if (dbm::is_result($r))
 +                                      if (dbm::is_result($r)) {
                                                $ev["id"] = $r[0]["id"];
 +                                      }
  
                                        $event_id = event_store($ev);
                                        logger("Event ".$event_id." was stored", LOGGER_DEBUG);
  
                // Update content if 'updated' changes
                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);
 -                      else
 +                      } else {
                                logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
 +                      }
                        return;
                }
  
                        $posted_id = item_store($item);
                        $parent = 0;
  
 -                      if($posted_id) {
 +                      if ($posted_id) {
  
                                logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
  
                                        $parent_uri = $r[0]["parent-uri"];
                                }
  
 -                              if(!$is_like) {
 +                              if (!$is_like) {
                                        $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
                                                dbesc(datetime_convert()),
                                                intval($importer["importer_uid"]),
                                        );
                                }
  
 -                              if($posted_id AND $parent AND ($entrytype == DFRN_REPLY_RC)) {
 +                              if ($posted_id AND $parent AND ($entrytype == DFRN_REPLY_RC)) {
                                        logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
                                        proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $posted_id);
                                }
                                return true;
                        }
                } else { // $entrytype == DFRN_TOP_LEVEL
 -                      if(!link_compare($item["owner-link"],$importer["url"])) {
 -                              // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
 -                              // but otherwise there's a possible data mixup on the sender's system.
 -                              // the tgroup delivery code called from item_store will correct it if it's a forum,
 -                              // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
 +                      if (!link_compare($item["owner-link"],$importer["url"])) {
 +                              /*
 +                               * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
 +                               * but otherwise there's a possible data mixup on the sender's system.
 +                               * the tgroup delivery code called from item_store will correct it if it's a forum,
 +                               * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
 +                               */
                                logger('Correcting item owner.', LOGGER_DEBUG);
                                $item["owner-name"]   = $importer["senderName"];
                                $item["owner-link"]   = $importer["url"];
                                $item["owner-avatar"] = $importer["thumb"];
                        }
  
 -                      if(($importer["rel"] == CONTACT_IS_FOLLOWER) && (!tgroup_check($importer["importer_uid"], $item))) {
 +                      if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!tgroup_check($importer["importer_uid"], $item))) {
                                logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
                                return;
                        }
         * @param object $xpath XPath object
         * @param object $deletion deletion elements
         * @param array $importer Record of the importer user mixed with contact of the content
 +       * @todo set proper type-hints
         */
        private static function process_deletion($xpath, $deletion, $importer) {
  
                logger("Processing deletions");
  
 -              foreach($deletion->attributes AS $attributes) {
 -                      if ($attributes->name == "ref")
 +              foreach ($deletion->attributes AS $attributes) {
 +                      if ($attributes->name == "ref") {
                                $uri = $attributes->textContent;
 -                      if ($attributes->name == "when")
 +                      }
 +                      if ($attributes->name == "when") {
                                $when = $attributes->textContent;
 +                      }
                }
 -              if ($when)
 +              if ($when) {
                        $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");
 +              }
  
 -              if (!$uri OR !$importer["id"])
 +              if (!$uri OR !$importer["id"]) {
                        return false;
 +              }
  
                /// @todo Only select the used fields
                $r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
                                intval($importer["id"])
                        );
                if (!dbm::is_result($r)) {
 -                      logger("Item with uri ".$uri." from contact ".$importer["id"]." for user ".$importer["uid"]." wasn't found.", LOGGER_DEBUG);
 +                      logger("Item with uri " . $uri . " from contact " . $importer["id"] . " for user " . $importer["uid"] . " wasn't found.", LOGGER_DEBUG);
                        return;
                } else {
  
  
                        $entrytype = self::get_entry_type($importer, $item);
  
 -                      if(!$item["deleted"])
 +                      if (!$item["deleted"]) {
                                logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
 -                      else
 +                      } else {
                                return;
 +                      }
  
 -                      if($item["object-type"] == ACTIVITY_OBJ_EVENT) {
 +                      if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
                                logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
                                event_delete($item["event-id"]);
                        }
  
 -                      if(($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
 +                      if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
  
                                $xo = parse_xml_string($item["object"],false);
                                $xt = parse_xml_string($item["target"],false);
  
 -                              if($xt->type == ACTIVITY_OBJ_NOTE) {
 +                              if ($xt->type == ACTIVITY_OBJ_NOTE) {
                                        $i = q("SELECT `id`, `contact-id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
                                                dbesc($xt->id),
                                                intval($importer["importer_uid"])
                                                $author_remove = (($item["origin"] && $item["self"]) ? true : false);
                                                $author_copy = (($item["origin"]) ? true : false);
  
 -                                              if($owner_remove && $author_copy)
 +                                              if ($owner_remove && $author_copy) {
                                                        return;
 -                                              if($author_remove || $owner_remove) {
 +                                              }
 +                                              if ($author_remove || $owner_remove) {
                                                        $tags = explode(',',$i[0]["tag"]);
                                                        $newtags = array();
 -                                                      if(count($tags)) {
 -                                                              foreach($tags as $tag)
 -                                                                      if(trim($tag) !== trim($xo->body))
 +                                                      if (count($tags)) {
 +                                                              foreach ($tags as $tag) {
 +                                                                      if (trim($tag) !== trim($xo->body)) {
                                                                                $newtags[] = trim($tag);
 +                                                                      }
 +                                                              }
                                                        }
                                                        q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
 -                                                              dbesc(implode(',',$newtags)),
 +                                                              dbesc(implode(',', $newtags)),
                                                                intval($i[0]["id"])
                                                        );
                                                        create_tags_from_item($i[0]["id"]);
                                }
                        }
  
 -                      if($entrytype == DFRN_TOP_LEVEL) {
 +                      if ($entrytype == DFRN_TOP_LEVEL) {
                                $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
                                                `body` = '', `title` = ''
                                        WHERE `parent-uri` = '%s' AND `uid` = %d",
                                }
                                // if this is a relayed delete, propagate it to other recipients
  
 -                              if($entrytype == DFRN_REPLY_RC) {
 -                                      logger("Notifying followers about deletion of post ".$item["id"], LOGGER_DEBUG);
 +                              if ($entrytype == DFRN_REPLY_RC) {
 +                                      logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
                                        proc_run(PRIORITY_HIGH, "include/notifier.php","drop", $item["id"]);
                                }
                        }
         * @param text $xml The DFRN message
         * @param array $importer Record of the importer user mixed with contact of the content
         * @param bool $sort_by_date Is used when feeds are polled
 +       * @todo set proper type-hints
         */
        public static function import($xml,$importer, $sort_by_date = false) {
  
 -              if ($xml == "")
 +              if ($xml == "") {
                        return;
 +              }
  
 -              if($importer["readonly"]) {
 +              if ($importer["readonly"]) {
                        // We aren't receiving stuff from this person. But we will quietly ignore them
                        // rather than a blatant "go away" message.
                        logger('ignoring contact '.$importer["id"]);
                // Update the contact table if the data has changed
  
                // 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);
 +              }
  
                // 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);
 +              }
  
 -              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);
  
                // The account type is new since 3.5.1
                if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
                        $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()", $context)->item(0)->nodeValue);
  
 -                      if ($accounttype != $importer["contact-type"])
 +                      if ($accounttype != $importer["contact-type"]) {
 +                              /// @TODO this way is the norm or putting ); at the end of the line?
                                q("UPDATE `contact` SET `contact-type` = %d WHERE `id` = %d",
                                        intval($accounttype),
                                        intval($importer["id"])
                                );
 +                      }
                }
  
                // is it a public forum? Private forums aren't supported with this method
                // This is deprecated since 3.5.1
                $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",
                                intval($forum), intval($forum),
                                intval($importer["id"])
                        );
 +              }
  
                $mails = $xpath->query("/atom:feed/dfrn:mail");
 -              foreach ($mails AS $mail)
 +              foreach ($mails AS $mail) {
                        self::process_mail($xpath, $mail, $importer);
 +              }
  
                $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
 -              foreach ($suggestions AS $suggestion)
 +              foreach ($suggestions AS $suggestion) {
                        self::process_suggestion($xpath, $suggestion, $importer);
 +              }
  
                $relocations = $xpath->query("/atom:feed/dfrn:relocate");
 -              foreach ($relocations AS $relocation)
 +              foreach ($relocations AS $relocation) {
                        self::process_relocation($xpath, $relocation, $importer);
 +              }
  
                $deletions = $xpath->query("/atom:feed/at:deleted-entry");
 -              foreach ($deletions AS $deletion)
 +              foreach ($deletions AS $deletion) {
                        self::process_deletion($xpath, $deletion, $importer);
 +              }
  
                if (!$sort_by_date) {
                        $entries = $xpath->query("/atom:feed/atom:entry");
 -                      foreach ($entries AS $entry)
 +                      foreach ($entries AS $entry) {
                                self::process_entry($header, $xpath, $entry, $importer);
 +                      }
                } else {
                        $newentries = array();
                        $entries = $xpath->query("/atom:feed/atom:entry");
                        // Now sort after the publishing date
                        ksort($newentries);
  
 -                      foreach ($newentries AS $entry)
 +                      foreach ($newentries AS $entry) {
                                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);
        }
  }
 -?>
diff --combined include/ostatus.php
index 6061ef9e11847ba3117d2f9205695f4ba5715aec,e6087de0873e0e85aa4ac7796cf509a7b6277354..7090e765feb154a6416048aaf8e494f0aa4d689b
@@@ -132,9 -132,6 +132,6 @@@ class ostatus 
                                        dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["alias"]),
                                        dbesc($contact["about"]), dbesc($contact["location"]),
                                        dbesc(datetime_convert()), intval($contact["id"]));
-                               poco_check($contact["url"], $contact["name"], $contact["network"], $author["author-avatar"], $contact["about"], $contact["location"],
-                                                       "", "", "", datetime_convert(), 2, $contact["id"], $contact["uid"]);
                        }
  
                        if (isset($author["author-avatar"]) AND ($author["author-avatar"] != $r[0]['avatar'])) {
                        $contact["generation"] = 2;
                        $contact["hide"] = false; // OStatus contacts are never hidden
                        $contact["photo"] = $author["author-avatar"];
-                       update_gcontact($contact);
+                       $gcid = update_gcontact($contact);
+                       link_gcontact($gcid, $contact["uid"], $contact["id"]);
                }
  
                return($author);
                                                if ($attributes->name == "title")
                                                        $title = $attributes->textContent;
                                        }
 -                                      if (($rel != "") AND ($href != ""))
 -                                              switch($rel) {
 +                                      if (($rel != "") AND ($href != "")) {
 +                                              switch ($rel) {
                                                        case "alternate":
                                                                $item["plink"] = $href;
 +                                                              /// @TODO These multi-lines can confuse, let's avoid them
                                                                if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) OR
 -                                                                      ($item["object-type"] == ACTIVITY_OBJ_EVENT))
 +                                                                      ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
                                                                        $item["body"] .= add_page_info($href);
 +                                                              }
                                                                break;
                                                        case "ostatus:conversation":
                                                                $conversation = $href;
                                                                break;
                                                        case "enclosure":
                                                                $enclosure = $href;
 -                                                              if(strlen($item["attach"]))
 +                                                              if (strlen($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;
                                                        case "related":
                                                                if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
 -                                                                      if (!isset($item["parent-uri"]))
 +                                                                      if (!isset($item["parent-uri"])) {
                                                                                $item["parent-uri"] = $href;
 +                                                                      }
  
 -                                                                      if ($related == "")
 +                                                                      if ($related == "") {
                                                                                $related = $href;
 -                                                              } else
 +                                                                      }
 +                                                              } else {
                                                                        $item["body"] .= add_page_info($href);
 +                                                              }
                                                                break;
                                                        case "self":
                                                                $self = $href;
                                                                break;
                                                        case "mentioned":
                                                                // Notification check
 -                                                              if ($importer["nurl"] == normalise_link($href))
 +                                                              if ($importer["nurl"] == normalise_link($href)) {
                                                                        $mention = true;
 +                                                              }
                                                                break;
                                                }
 +                                      }
                                }
                        }
  
  
                /// @todo This function is totally ugly and has to be rewritten totally
  
+               // Import all threads or only threads that were started by our followers?
+               $all_threads = !get_config('system','ostatus_full_threads');
                $item_stored = -1;
  
                $conversation_url = self::fetch_conversation($self, $conversation_url);
                // Don't do a completion on liked content
                if (((intval(get_config('system','ostatus_poll_interval')) == -2) AND (count($item) > 0)) OR
                        ($item["verb"] == ACTIVITY_LIKE) OR ($conversation_url == "")) {
-                       $item_stored = item_store($item, true);
-                       return($item_stored);
+                       $item_stored = item_store($item, $all_threads);
+                       return $item_stored;
                }
  
                // Get the parent
  
                if (!sizeof($items)) {
                        if (count($item) > 0) {
-                               $item_stored = item_store($item, true);
+                               $item_stored = item_store($item, $all_threads);
  
                                if ($item_stored) {
                                        logger("Conversation ".$conversation_url." couldn't be fetched. Item uri ".$item["uri"]." stored: ".$item_stored, LOGGER_DEBUG);
                                }
                        }
  
-                       $item_stored = item_store($item, true);
+                       $item_stored = item_store($item, $all_threads);
                        if ($item_stored) {
                                logger("Uri ".$item["uri"]." wasn't found in conversation ".$conversation_url, LOGGER_DEBUG);
                                self::store_conversation($item_stored, $conversation_url);
diff --combined mod/admin.php
index 79fcebf47be52f072a24e157a28eed04c2393fb9,cf0714ef9058963e7d0fa14e9d09a720a5999893..3ca8ea49359cff8e7c8d41fe34331b2dfe283314
@@@ -629,7 -629,6 +629,6 @@@ function admin_page_site_post(App $a) 
        $no_multi_reg           =       ((x($_POST,'no_multi_reg'))             ? True                                          : False);
        $no_openid              =       !((x($_POST,'no_openid'))               ? True                                          : False);
        $no_regfullname         =       !((x($_POST,'no_regfullname'))          ? True                                          : False);
-       $no_utf                 =       !((x($_POST,'no_utf'))                  ? True                                          : False);
        $community_page_style   =       ((x($_POST,'community_page_style'))     ? intval(trim($_POST['community_page_style']))  : 0);
        $max_author_posts_community_page        =       ((x($_POST,'max_author_posts_community_page'))  ? intval(trim($_POST['max_author_posts_community_page']))       : 0);
  
        $proxy_disabled         =       ((x($_POST,'proxy_disabled'))           ? True                                          : False);
        $only_tag_search        =       ((x($_POST,'only_tag_search'))          ? True                                          : False);
        $rino                   =       ((x($_POST,'rino'))                     ? intval($_POST['rino'])                        : 0);
-       $embedly                =       ((x($_POST,'embedly'))                  ? notags(trim($_POST['embedly']))               : '');
        $worker_queues          =       ((x($_POST,'worker_queues'))            ? intval($_POST['worker_queues'])               : 4);
        $worker_dont_fork       =       ((x($_POST,'worker_dont_fork'))         ? True                                          : False);
        $worker_fastlane        =       ((x($_POST,'worker_fastlane'))          ? True                                          : False);
                } else {
                        set_config('system','singleuser', $singleuser);
                }
-       set_config('system','maximagesize', $maximagesize);
-       set_config('system','max_image_length', $maximagelength);
-       set_config('system','jpeg_quality', $jpegimagequality);
-       set_config('config','register_policy', $register_policy);
-       set_config('system','max_daily_registrations', $daily_registrations);
-       set_config('system','account_abandon_days', $abandon_days);
-       set_config('config','register_text', $register_text);
-       set_config('system','allowed_sites', $allowed_sites);
-       set_config('system','allowed_email', $allowed_email);
-       set_config('system','block_public', $block_public);
-       set_config('system','publish_all', $force_publish);
-       set_config('system','directory', $global_directory);
-       set_config('system','thread_allow', $thread_allow);
-       set_config('system','newuser_private', $newuser_private);
-       set_config('system','enotify_no_content', $enotify_no_content);
-       set_config('system','disable_embedded', $disable_embedded);
-       set_config('system','allow_users_remote_self', $allow_users_remote_self);
-       set_config('system','block_extended_register', $no_multi_reg);
-       set_config('system','no_openid', $no_openid);
-       set_config('system','no_regfullname', $no_regfullname);
-       set_config('system','community_page_style', $community_page_style);
-       set_config('system','max_author_posts_community_page', $max_author_posts_community_page);
-       set_config('system','no_utf', $no_utf);
-       set_config('system','verifyssl', $verifyssl);
-       set_config('system','proxyuser', $proxyuser);
-       set_config('system','proxy', $proxy);
-       set_config('system','curl_timeout', $timeout);
-       set_config('system','dfrn_only', $dfrn_only);
-       set_config('system','ostatus_disabled', $ostatus_disabled);
-       set_config('system','ostatus_poll_interval', $ostatus_poll_interval);
-       set_config('system','ostatus_full_threads', $ostatus_full_threads);
-       set_config('system','diaspora_enabled', $diaspora_enabled);
-       set_config('config','private_addons', $private_addons);
-       set_config('system','force_ssl', $force_ssl);
-       set_config('system','hide_help', $hide_help);
-       set_config('system','use_fulltext_engine', $use_fulltext_engine);
-       set_config('system','itemcache', $itemcache);
-       set_config('system','itemcache_duration', $itemcache_duration);
-       set_config('system','max_comments', $max_comments);
-       set_config('system','temppath', $temppath);
-       set_config('system','basepath', $basepath);
-       set_config('system','proxy_disabled', $proxy_disabled);
-       set_config('system','only_tag_search', $only_tag_search);
-       set_config('system','worker_queues', $worker_queues);
-       set_config('system','worker_dont_fork', $worker_dont_fork);
-       set_config('system','worker_fastlane', $worker_fastlane);
-       set_config('system','frontend_worker', $worker_frontend);
-       if (($rino == 2) and !function_exists('mcrypt_create_iv')) {
-               notice(t("RINO2 needs mcrypt php extension to work."));
-       } else {
-               set_config('system','rino_encrypt', $rino);
-       }
-       set_config('system','embedly', $embedly);
+       set_config('system', 'maximagesize', $maximagesize);
+       set_config('system', 'max_image_length', $maximagelength);
+       set_config('system', 'jpeg_quality', $jpegimagequality);
+       set_config('config', 'register_policy', $register_policy);
+       set_config('system', 'max_daily_registrations', $daily_registrations);
+       set_config('system', 'account_abandon_days', $abandon_days);
+       set_config('config', 'register_text', $register_text);
+       set_config('system', 'allowed_sites', $allowed_sites);
+       set_config('system', 'allowed_email', $allowed_email);
+       set_config('system', 'block_public', $block_public);
+       set_config('system', 'publish_all', $force_publish);
+       set_config('system', 'directory', $global_directory);
+       set_config('system', 'thread_allow', $thread_allow);
+       set_config('system', 'newuser_private', $newuser_private);
+       set_config('system', 'enotify_no_content', $enotify_no_content);
+       set_config('system', 'disable_embedded', $disable_embedded);
+       set_config('system', 'allow_users_remote_self', $allow_users_remote_self);
+       set_config('system', 'block_extended_register', $no_multi_reg);
+       set_config('system', 'no_openid', $no_openid);
+       set_config('system', 'no_regfullname', $no_regfullname);
+       set_config('system', 'community_page_style', $community_page_style);
+       set_config('system', 'max_author_posts_community_page', $max_author_posts_community_page);
+       set_config('system', 'verifyssl', $verifyssl);
+       set_config('system', 'proxyuser', $proxyuser);
+       set_config('system', 'proxy', $proxy);
+       set_config('system', 'curl_timeout', $timeout);
+       set_config('system', 'dfrn_only', $dfrn_only);
+       set_config('system', 'ostatus_disabled', $ostatus_disabled);
+       set_config('system', 'ostatus_poll_interval', $ostatus_poll_interval);
+       set_config('system', 'ostatus_full_threads', $ostatus_full_threads);
+       set_config('system', 'diaspora_enabled', $diaspora_enabled);
+       set_config('config', 'private_addons', $private_addons);
+       set_config('system', 'force_ssl', $force_ssl);
+       set_config('system', 'hide_help', $hide_help);
+       set_config('system', 'use_fulltext_engine', $use_fulltext_engine);
+       set_config('system', 'itemcache', $itemcache);
+       set_config('system', 'itemcache_duration', $itemcache_duration);
+       set_config('system', 'max_comments', $max_comments);
+       set_config('system', 'temppath', $temppath);
+       set_config('system', 'basepath', $basepath);
+       set_config('system', 'proxy_disabled', $proxy_disabled);
+       set_config('system', 'only_tag_search', $only_tag_search);
+       set_config('system', 'worker_queues', $worker_queues);
+       set_config('system', 'worker_dont_fork', $worker_dont_fork);
+       set_config('system', 'worker_fastlane', $worker_fastlane);
+       set_config('system', 'frontend_worker', $worker_frontend);
+       set_config('system', 'rino_encrypt', $rino);
  
        info(t('Site settings updated.').EOL);
        goaway('admin/site');
@@@ -1012,7 -1001,6 +1001,6 @@@ function admin_page_site(App $a) 
                '$no_multi_reg'         => array('no_multi_reg', t("Block multiple registrations"),  get_config('system','block_extended_register'), t("Disallow users to register additional accounts for use as pages.")),
                '$no_openid'            => array('no_openid', t("OpenID support"), !get_config('system','no_openid'), t("OpenID support for registration and logins.")),
                '$no_regfullname'       => array('no_regfullname', t("Fullname check"), !get_config('system','no_regfullname'), t("Force users to register with a space between firstname and lastname in Full name, as an antispam measure")),
-               '$no_utf'               => array('no_utf', t("UTF-8 Regular expressions"), !get_config('system','no_utf'), t("Use PHP UTF8 regular expressions")),
                '$community_page_style' => array('community_page_style', t("Community Page Style"), get_config('system','community_page_style'), t("Type of community page to show. 'Global community' shows every public posting from an open distributed network that arrived on this server."), $community_page_style_choices),
                '$max_author_posts_community_page' => array('max_author_posts_community_page', t("Posts per user on community page"), get_config('system','max_author_posts_community_page'), t("The maximum number of posts per user on the community page. (Not valid for 'Global Community')")),
                '$ostatus_disabled'     => array('ostatus_disabled', t("Enable OStatus support"), !get_config('system','ostatus_disabled'), t("Provide built-in OStatus \x28StatusNet, GNU Social etc.\x29 compatibility. All communications in OStatus are public, so privacy warnings will be occasionally displayed.")),
                '$relocate_url'         => array('relocate_url', t("New base url"), App::get_baseurl(), t("Change base url for this server. Sends relocate message to all DFRN contacts of all users.")),
  
                '$rino'                 => array('rino', t("RINO Encryption"), intval(get_config('system','rino_encrypt')), t("Encryption layer between nodes."), array("Disabled", "RINO1 (deprecated)", "RINO2")),
-               '$embedly'              => array('embedly', t("Embedly API key"), get_config('system','embedly'), t("<a href='http://embed.ly'>Embedly</a> is used to fetch additional data for web pages. This is an optional parameter.")),
  
                '$worker_queues'        => array('worker_queues', t("Maximum number of parallel workers"), get_config('system','worker_queues'), t("On shared hosters set this to 2. On larger systems, values of 10 are great. Default value is 4.")),
                '$worker_dont_fork'     => array('worker_dont_fork', t("Don't use 'proc_open' with the worker"), get_config('system','worker_dont_fork'), t("Enable this if your system doesn't allow the use of 'proc_open'. This can happen on shared hosters. If this is enabled you should increase the frequency of poller calls in your crontab.")),
@@@ -2017,22 -2004,22 +2004,22 @@@ function admin_page_features_post(App $
        $features = get_features(false);
  
        foreach ($features as $fname => $fdata) {
 -              foreach (array_slice($fdata,1) as $f) {
 +              foreach (array_slice($fdata, 1) as $f) {
                        $feature = $f[0];
 -                      $feature_state = 'feature_'.$feature;
 -                      $featurelock = 'featurelock_'.$feature;
 +                      $feature_state = 'feature_' . $feature;
 +                      $featurelock = 'featurelock_' . $feature;
  
 -                      if (x($_POST[$feature_state])) {
 -                              $val = intval($_POST['feature_'.$feature]);
 +                      if (x($_POST, $feature_state)) {
 +                              $val = intval($_POST[$feature_state]);
                        } else {
                                $val = 0;
                        }
                        set_config('feature',$feature,$val);
  
 -                      if (x($_POST[$featurelock])) {
 -                              set_config('feature_lock',$feature,$val);
 +                      if (x($_POST, $featurelock)) {
 +                              set_config('feature_lock', $feature, $val);
                        } else {
 -                              del_config('feature_lock',$feature);
 +                              del_config('feature_lock', $feature);
                        }
                }
        }
diff --combined mod/dfrn_confirm.php
index 7e14610e3397c15106a28caa5e586d44df154bb4,7a3882a5ba55691866296f216239527e17bca651..001fa446891b28eaf205b763d8168dff26005a1f
@@@ -185,10 -185,10 +185,10 @@@ function dfrn_confirm_post(App $a, $han
                         *
                         */
  
-                       $src_aes_key = random_string();
+                       $src_aes_key = openssl_random_pseudo_bytes(64);
  
                        $result = '';
-                       openssl_private_encrypt($dfrn_id,$result,$user[0]['prvkey']);
+                       openssl_private_encrypt($dfrn_id, $result, $user[0]['prvkey']);
  
                        $params['dfrn_id'] = bin2hex($result);
                        $params['public_key'] = $public_key;
                        dbesc($decrypted_source_url),
                        intval($local_uid)
                );
 -              if(! count($ret)) {
 -                      if(strstr($decrypted_source_url,'http:'))
 +              if (!dbm::is_result($ret)) {
 +                      if (strstr($decrypted_source_url,'http:')) {
                                $newurl = str_replace('http:','https:',$decrypted_source_url);
 -                      else
 +                      } else {
                                $newurl = str_replace('https:','http:',$decrypted_source_url);
 +                      }
  
                        $ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
                                dbesc($newurl),
                                intval($local_uid)
                        );
 -                      if(! count($ret)) {
 +                      if (!dbm::is_result($ret)) {
                                // this is either a bogus confirmation (?) or we deleted the original introduction.
                                $message = t('Contact record was not found for you on our site.');
                                xml_status(3,$message);
                $foreign_pubkey = $ret[0]['site-pubkey'];
                $dfrn_record    = $ret[0]['id'];
  
 -              if(! $foreign_pubkey) {
 +              if (! $foreign_pubkey) {
                        $message = sprintf( t('Site public key not available in contact record for URL %s.'), $newurl);
                        xml_status(3,$message);
                }
                $decrypted_dfrn_id = "";
                openssl_public_decrypt($dfrn_id,$decrypted_dfrn_id,$foreign_pubkey);
  
 -              if(strlen($aes_key)) {
 +              if (strlen($aes_key)) {
                        $decrypted_aes_key = "";
                        openssl_private_decrypt($aes_key,$decrypted_aes_key,$my_prvkey);
                        $dfrn_pubkey = openssl_decrypt($public_key,'AES-256-CBC',$decrypted_aes_key);
diff --combined mod/dfrn_notify.php
index ddbc9219b1d209d14b609a9feb8d38b2b1702c19,8df462e58fd181d01d9711726dc3594617b89788..b42ef9b70a82cee1bc669945d2bd8c3c9fba0a27
@@@ -28,14 -28,14 +28,14 @@@ function dfrn_notify_post(App $a) 
        $prv   = (($page == 2) ? 1 : 0);
  
        $writable = (-1);
 -      if($dfrn_version >= 2.21) {
 +      if ($dfrn_version >= 2.21) {
                $writable = (($perm === 'rw') ? 1 : 0);
        }
  
        $direction = (-1);
 -      if(strpos($dfrn_id,':') == 1) {
 -              $direction = intval(substr($dfrn_id,0,1));
 -              $dfrn_id = substr($dfrn_id,2);
 +      if (strpos($dfrn_id, ':') == 1) {
 +              $direction = intval(substr($dfrn_id, 0, 1));
 +              $dfrn_id = substr($dfrn_id, 2);
        }
  
        $r = q("SELECT * FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1",
                        break; // NOTREACHED
        }
  
 -      // be careful - $importer will contain both the contact information for the contact
 -      // sending us the post, and also the user information for the person receiving it.
 -      // since they are mixed together, it is easy to get them confused.
 +      /*
 +       * be careful - $importer will contain both the contact information for the contact
 +       * sending us the post, and also the user information for the person receiving it.
 +       * since they are mixed together, it is easy to get them confused.
 +       */
  
        $r = q("SELECT  `contact`.*, `contact`.`uid` AS `importer_uid`,
                                        `contact`.`pubkey` AS `cpubkey`,
  
        logger("Remote rino version: ".$rino_remote." for ".$importer["url"], LOGGER_DEBUG);
  
 -      if((($writable != (-1)) && ($writable != $importer['writable'])) || ($importer['forum'] != $forum) || ($importer['prv'] != $prv)) {
 +      if ((($writable != (-1)) && ($writable != $importer['writable'])) || ($importer['forum'] != $forum) || ($importer['prv'] != $prv)) {
                q("UPDATE `contact` SET `writable` = %d, forum = %d, prv = %d WHERE `id` = %d",
                        intval(($writable == (-1)) ? $importer['writable'] : $writable),
                        intval($forum),
                        intval($prv),
                        intval($importer['id'])
                );
 -              if($writable != (-1))
 +              if ($writable != (-1)) {
                        $importer['writable'] = $writable;
 +              }
                $importer['forum'] = $page;
        }
  
        logger('dfrn_notify: received notify from ' . $importer['name'] . ' for ' . $importer['username']);
        logger('dfrn_notify: data: ' . $data, LOGGER_DATA);
  
 -      if($dissolve == 1) {
 +      if ($dissolve == 1) {
  
                /*
                 * Relationship is dissolved permanently
  
        }
  
 -
 -      // If we are setup as a soapbox we aren't accepting input from this person
 -      // This behaviour is deactivated since it really doesn't make sense to even disallow comments
 -      // The check if someone is a friend or simply a follower is done in a later place so it needn't to be done here
 -      //if($importer['page-flags'] == PAGE_SOAPBOX)
 -      //      xml_status(0);
 -
 -      $rino = get_config('system','rino_encrypt');
 +      $rino = get_config('system', 'rino_encrypt');
        $rino = intval($rino);
-       // use RINO1 if mcrypt isn't installed and RINO2 was selected
-       if ($rino == 2 && !function_exists('mcrypt_create_iv')) {
-               $rino = 1;
-       }
  
 -      logger("Local rino version: ". $rino, LOGGER_DEBUG);
 +      logger("Local rino version: " .  $rino, LOGGER_DEBUG);
  
 -      if(strlen($key)) {
 +      if (strlen($key)) {
  
                // if local rino is lower than remote rino, abort: should not happen!
                // but only for $remote_rino > 1, because old code did't send rino version
                logger('rino: md5 raw key: ' . md5($rawkey));
                $final_key = '';
  
 -              if($dfrn_version >= 2.1) {
 -                      if((($importer['duplex']) && strlen($importer['cprvkey'])) || (! strlen($importer['cpubkey']))) {
 -                              openssl_private_decrypt($rawkey,$final_key,$importer['cprvkey']);
 +              if ($dfrn_version >= 2.1) {
 +                      if ((($importer['duplex']) && strlen($importer['cprvkey'])) || (! strlen($importer['cpubkey']))) {
 +                              openssl_private_decrypt($rawkey, $final_key, $importer['cprvkey']);
 +                      } else {
 +                              openssl_public_decrypt($rawkey, $final_key, $importer['cpubkey']);
                        }
 -                      else {
 -                              openssl_public_decrypt($rawkey,$final_key,$importer['cpubkey']);
 -                      }
 -              }
 -              else {
 -                      if((($importer['duplex']) && strlen($importer['cpubkey'])) || (! strlen($importer['cprvkey']))) {
 -                              openssl_public_decrypt($rawkey,$final_key,$importer['cpubkey']);
 -                      }
 -                      else {
 -                              openssl_private_decrypt($rawkey,$final_key,$importer['cprvkey']);
 +              } else {
 +                      if ((($importer['duplex']) && strlen($importer['cpubkey'])) || (! strlen($importer['cprvkey']))) {
 +                              openssl_public_decrypt($rawkey, $final_key, $importer['cpubkey']);
 +                      } else {
 +                              openssl_private_decrypt($rawkey, $final_key, $importer['cprvkey']);
                        }
                }
  
                switch($rino_remote) {
                        case 0:
                        case 1:
 -                              // we got a key. old code send only the key, without RINO version.
 -                              // we assume RINO 1 if key and no RINO version
 -                              $data = dfrn::aes_decrypt(hex2bin($data),$final_key);
 +                              /*
-                                * we got a key. old code send only the key, without RINO version.
++                               *we got a key. old code send only the key, without RINO version.
 +                               * we assume RINO 1 if key and no RINO version
 +                               */
-                               $data = aes_decrypt(hex2bin($data), $final_key);
++                              $data = dfrn::aes_decrypt(hex2bin($data), $final_key);
                                break;
                        case 2:
                                try {
 -                                      $data = Crypto::decrypt(hex2bin($data),$final_key);
 +                                      $data = Crypto::decrypt(hex2bin($data), $final_key);
                                } catch (InvalidCiphertext $ex) { // VERY IMPORTANT
 -                                      // Either:
 -                                      //   1. The ciphertext was modified by the attacker,
 -                                      //   2. The key is wrong, or
 -                                      //   3. $ciphertext is not a valid ciphertext or was corrupted.
 -                                      // Assume the worst.
 +                                      /*
 +                                       * Either:
 +                                       *   1. The ciphertext was modified by the attacker,
 +                                       *   2. The key is wrong, or
 +                                       *   3. $ciphertext is not a valid ciphertext or was corrupted.
 +                                       * Assume the worst.
 +                                       */
                                        logger('The ciphertext has been tampered with!');
 -                                      xml_status(0,'The ciphertext has been tampered with!');
 +                                      xml_status(0, 'The ciphertext has been tampered with!');
                                } catch (Ex\CryptoTestFailed $ex) {
                                        logger('Cannot safely perform dencryption');
 -                                      xml_status(0,'CryptoTestFailed');
 +                                      xml_status(0, 'CryptoTestFailed');
                                } catch (Ex\CannotPerformOperation $ex) {
                                        logger('Cannot safely perform decryption');
 -                                      xml_status(0,'Cannot safely perform decryption');
 +                                      xml_status(0, 'Cannot safely perform decryption');
                                }
                                break;
                        default:
@@@ -224,10 -223,8 +220,10 @@@ function dfrn_notify_content(App $a) 
  
        if(x($_GET,'dfrn_id')) {
  
 -              // initial communication from external contact, $direction is their direction.
 -              // If this is a duplex communication, ours will be the opposite.
 +              /*
 +               * initial communication from external contact, $direction is their direction.
 +               * If this is a duplex communication, ours will be the opposite.
 +               */
  
                $dfrn_id = notags(trim($_GET['dfrn_id']));
                $dfrn_version = (float) $_GET['dfrn_version'];
  
                logger("Remote rino version: ".$rino_remote." for ".$r[0]["url"], LOGGER_DEBUG);
  
 -              $challenge = '';
 +              $challenge    = '';
                $encrypted_id = '';
 -              $id_str = $my_id . '.' . mt_rand(1000,9999);
 +              $id_str       = $my_id . '.' . mt_rand(1000,9999);
  
                $prv_key = trim($r[0]['prvkey']);
                $pub_key = trim($r[0]['pubkey']);
 -              $dplx = intval($r[0]['duplex']);
 -
 -              if((($dplx) && (strlen($prv_key))) || ((strlen($prv_key)) && (!(strlen($pub_key))))) {
 -                      openssl_private_encrypt($hash,$challenge,$prv_key);
 -                      openssl_private_encrypt($id_str,$encrypted_id,$prv_key);
 -              }
 -              elseif(strlen($pub_key)) {
 -                      openssl_public_encrypt($hash,$challenge,$pub_key);
 -                      openssl_public_encrypt($id_str,$encrypted_id,$pub_key);
 -              }
 -              else
 +              $dplx    = intval($r[0]['duplex']);
 +
 +              if ((($dplx) && (strlen($prv_key))) || ((strlen($prv_key)) && (!(strlen($pub_key))))) {
 +                      openssl_private_encrypt($hash, $challenge, $prv_key);
 +                      openssl_private_encrypt($id_str, $encrypted_id, $prv_key);
 +              } elseif (strlen($pub_key)) {
 +                      openssl_public_encrypt($hash, $challenge, $pub_key);
 +                      openssl_public_encrypt($id_str, $encrypted_id, $pub_key);
 +              } else {
 +                      /// @TODO these kind of else-blocks are making the code harder to understand
                        $status = 1;
 +              }
  
                $challenge    = bin2hex($challenge);
                $encrypted_id = bin2hex($encrypted_id);
  
  
 -              $rino = get_config('system','rino_encrypt');
 +              $rino = get_config('system', 'rino_encrypt');
                $rino = intval($rino);
-               // use RINO1 if mcrypt isn't installed and RINO2 was selected
-               if ($rino == 2 && !function_exists('mcrypt_create_iv')) {
-                       $rino = 1;
-               }
  
                logger("Local rino version: ". $rino, LOGGER_DEBUG);
  
                // if requested rino is lower than enabled local rino, lower local rino version
                // if requested rino is higher than enabled local rino, reply with local rino
 -              if ($rino_remote < $rino) $rino = $rino_remote;
 +              if ($rino_remote < $rino) {
 +                      $rino = $rino_remote;
 +              }
  
                if((($r[0]['rel']) && ($r[0]['rel'] != CONTACT_IS_SHARING)) || ($r[0]['page-flags'] == PAGE_COMMUNITY)) {
                        $perm = 'rw';
 -              }
 -              else {
 +              } else {
                        $perm = 'r';
                }
  
diff --combined mod/install.php
index 6db79dca286b6b25aba7a3bcb706e58ca93e7149,ce229244c07d006cae88485ca87eebc2588b502c..fbd296a9da565b5b09f45a1349ae2ee12dfa2af6
@@@ -78,14 -78,7 +78,7 @@@ function install_post(App $a) 
                        $timezone = notags(trim($_POST['timezone']));
                        $language = notags(trim($_POST['language']));
                        $adminmail = notags(trim($_POST['adminmail']));
-                       // In step 4 of the installer, we passed the  check for mcrypt
-                       // already, so we can activate RINO, make RINO2 the default
-                       // and only fall back if the mcrypt_create_iv function is
-                       // not available on the system.
                        $rino = 2;
-                       if (! function_exists('mcrypt_create_iv')) {
-                               $rino = 1;
-                       }
  
                        // connect to db
                        $db = new dba($dbhost, $dbuser, $dbpass, $dbdata, true);
@@@ -422,7 -415,6 +415,6 @@@ function check_funcs(&$checks) 
        check_add($ck_funcs, t('OpenSSL PHP module'), true, true, "");
        check_add($ck_funcs, t('mysqli PHP module'), true, true, "");
        check_add($ck_funcs, t('mb_string PHP module'), true, true, "");
-       check_add($ck_funcs, t('mcrypt PHP module'), true, true, "");
        check_add($ck_funcs, t('XML PHP module'), true, true, "");
        check_add($ck_funcs, t('iconv module'), true, true, "");
  
                $ck_funcs[4]['status']= false;
                $ck_funcs[4]['help']= t('Error: mb_string PHP module required but not installed.');
        }
-       if (! function_exists('mcrypt_create_iv')){
-               $ck_funcs[5]['status']= false;
-               $ck_funcs[5]['help']= t('Error: mcrypt PHP module required but not installed.');
-       }
        if (! function_exists('iconv_strlen')){
                $ck_funcs[7]['status']= false;
                $ck_funcs[7]['help']= t('Error: iconv PHP module required but not installed.');
  
        $checks = array_merge($checks, $ck_funcs);
  
-       // check for 'mcrypt_create_iv()', needed for RINO2
-       if ($ck_funcs[5]['status']) {
-               if (function_exists('mcrypt_create_iv')) {
-                       $__status = true;
-                       $__help = t("If you are using php_cli, please make sure that mcrypt module is enabled in its config file");
-               } else {
-                       $__status = false;
-                       $__help = t('Function mcrypt_create_iv() is not defined. This is needed to enable RINO2 encryption layer.');
-               }
-               check_add($checks, t('mcrypt_create_iv() function'), $__status, false, $__help);
-       }
        // check for XML DOM Documents being able to be generated
        try {
                $xml = new DOMDocument();
                $ck_funcs[6]['status'] = false;
                $ck_funcs[6]['help'] = t('Error, XML PHP module required but not installed.');
        }
 -
 -      /*if((x($_SESSION,'sysmsg')) && is_array($_SESSION['sysmsg']) && count($_SESSION['sysmsg']))
 -              notice( t('Please see the file "INSTALL.txt".') . EOL);*/
  }