diff --git a/Idno/Caching/APCuCache.php b/Idno/Caching/APCuCache.php index a6d8b10169..af401ab843 100644 --- a/Idno/Caching/APCuCache.php +++ b/Idno/Caching/APCuCache.php @@ -3,15 +3,16 @@ namespace Idno\Caching { use Symfony\Component\Cache\Adapter\ApcuAdapter; - + /** * Implement a persistent cache using APC User caching. */ class APCuCache extends PersistentCache { - public function __construct() { + public function __construct() + { parent::__construct(); - + $this->setCacheEngine(new ApcuAdapter()); } diff --git a/Idno/Caching/ArrayCache.php b/Idno/Caching/ArrayCache.php index 3463d8dc7d..7764719eb6 100644 --- a/Idno/Caching/ArrayCache.php +++ b/Idno/Caching/ArrayCache.php @@ -1,7 +1,7 @@ setCacheEngine(new ArrayAdapter()); } } diff --git a/Idno/Caching/Cache.php b/Idno/Caching/Cache.php index f38e01bbb9..970250d7ee 100644 --- a/Idno/Caching/Cache.php +++ b/Idno/Caching/Cache.php @@ -3,89 +3,100 @@ namespace Idno\Caching { use Symfony\Component\Cache\Adapter\AbstractAdapter; - + abstract class Cache extends \Idno\Common\Component implements \ArrayAccess { /// This is the cache engine underlaying the engine private $cache; - + /** * Set the cache engine used by this. + * * @param AbstractAdapter $adapter */ - protected function setCacheEngine(AbstractAdapter $adapter) { + protected function setCacheEngine(AbstractAdapter $adapter) + { $this->cache = $adapter; } - + /** * Get the current cache engine. + * * @return AbstractAdapter */ - public function getCacheEngine() : AbstractAdapter { + public function getCacheEngine() : AbstractAdapter + { return $this->cache; } - - + + /** * Return the number of keys currently stored. + * * @deprecated */ - public function size() { - + public function size() + { + $engine = $this->getCacheEngine(); - + return count($engine->getItems()); } /** * Retrieve a value from the store. - * @param $key Key to retrieve + * + * @param $key Key to retrieve * @return mixed|false */ - public function load($key) { - + public function load($key) + { + $engine = $this->getCacheEngine(); - + $item = $engine->getItem($key); if ($item->isHit()) { return $item->get(); } - + return false; } - + /** * Store or replace a value in the cache. * - * @param $key string Identifier for this value - * @param $value mixed Value to store + * @param $key string Identifier for this value + * @param $value mixed Value to store * @return bool */ - public function store($key, $value) { - + public function store($key, $value) + { + $engine = $this->getCacheEngine(); - + $item = $engine->getItem($key); $item->set($value); - + return $engine->save($item); } /** * Remove a key from the cache. - * @param The key + * + * @param The key * @return bool */ - public function delete($key) { - + public function delete($key) + { + $engine = $this->getCacheEngine(); - + return $engine->delete($key); } - + /* Object interface */ public function __isset($key) @@ -97,9 +108,9 @@ public function __unset($key) { return $this->delete($key); } - + /* Candy */ - + public function __get($key) { return $this->load($key); @@ -109,7 +120,7 @@ public function __set($key, $value) { return $this->store($key, $value); } - + /* Array access interface */ diff --git a/Idno/Caching/FilesystemCache.php b/Idno/Caching/FilesystemCache.php index ea23677bbe..d0845f9204 100644 --- a/Idno/Caching/FilesystemCache.php +++ b/Idno/Caching/FilesystemCache.php @@ -3,7 +3,7 @@ namespace Idno\Caching { use Symfony\Component\Cache\Adapter\FilesystemAdapter; - + /** * Implement a persistent cache using the local filesystem. * @@ -15,19 +15,22 @@ class FilesystemCache extends PersistentCache public function __construct() { $domain = md5(\Idno\Core\Idno::site()->config()->host); - if (empty($domain)) + if (empty($domain)) { throw new \RuntimeException(\Idno\Core\Idno::site()->language()->_("No domain specified for cache")); + } $pathbase = \Idno\Core\Idno::site()->config()->cachepath; - if (empty($pathbase)) + if (empty($pathbase)) { $pathbase = \Idno\Core\Idno::site()->config()->uploadpath; - if (empty($pathbase)) + } + if (empty($pathbase)) { $pathbase = \Idno\Core\Idno::site()->config()->getTempDir(); + } $engine = new FilesystemAdapter($domain, 0, $pathbase); - + $this->setCacheEngine($engine); - + } } diff --git a/Idno/Caching/StaticArrayCache.php b/Idno/Caching/StaticArrayCache.php index b5de082fdd..84dc8d748a 100644 --- a/Idno/Caching/StaticArrayCache.php +++ b/Idno/Caching/StaticArrayCache.php @@ -5,6 +5,7 @@ /** * A version of ArrayCache which uses a shared array, this means it's safe to use "$foo = new StaticArrayCache()" and still have access * to values set elsewhere in the system. + * * @deprecated */ class StaticArrayCache extends ArrayCache diff --git a/Idno/Common/Component.php b/Idno/Common/Component.php index 4d96ee8d35..d7fa5a3476 100644 --- a/Idno/Common/Component.php +++ b/Idno/Common/Component.php @@ -3,7 +3,7 @@ /** * All idno components inherit this base class * - * @package idno + * @package idno * @subpackage core */ @@ -20,11 +20,11 @@ function __construct() $this->registerPages(); $this->registerTranslations(); } - + /** * Register any autoloaders here. */ - function registerLibraries() + function registerLibraries() { } @@ -70,6 +70,7 @@ function registerTranslations() /** * Helper function that gets the full class name of this entity + * * @return string */ function getClass() @@ -80,6 +81,7 @@ function getClass() /** * Helper method to retrieve the filename of the current component * (works with inheritance). + * * @return string */ function getFilename() @@ -91,6 +93,7 @@ function getFilename() /** * Returns a camelCase version of the object title, suitable for use in element IDs + * * @return string */ function getIDSelector() @@ -100,14 +103,17 @@ function getIDSelector() /** * Returns the camelCased version of a given string - * @param $string + * + * @param $string * @return $string */ function camelCase($string) { - $string = preg_replace_callback('/\s([a-z])/', function ($matches) { - return strtoupper($matches[0]); - }, strtolower($string)); + $string = preg_replace_callback( + '/\s([a-z])/', function ($matches) { + return strtoupper($matches[0]); + }, strtolower($string) + ); $string = preg_replace('/\s/', '', $string); return $string; @@ -115,6 +121,7 @@ function camelCase($string) /** * Returns a camelCase version of the object class, suitable for use in element IDs + * * @return string */ function getClassSelector() @@ -124,6 +131,7 @@ function getClassSelector() /** * Get the name of this class without its namespace + * * @return string */ function getClassName() @@ -144,7 +152,8 @@ function getNamespace() /** * Gets the name of this class including its namespace - * @param bool $convert_slashes If set to true, converts \ slashes to / (false by default) + * + * @param bool $convert_slashes If set to true, converts \ slashes to / (false by default) * @return string */ function getFullClassName($convert_slashes = false) diff --git a/Idno/Common/ConsolePlugin.php b/Idno/Common/ConsolePlugin.php index cbba7d77aa..6228af2659 100644 --- a/Idno/Common/ConsolePlugin.php +++ b/Idno/Common/ConsolePlugin.php @@ -3,7 +3,7 @@ /** * All known console plugins should extend this component. * - * @package idno + * @package idno * @subpackage core */ diff --git a/Idno/Common/ContentType.php b/Idno/Common/ContentType.php index 71b77f1c50..ea6ebfee5f 100644 --- a/Idno/Common/ContentType.php +++ b/Idno/Common/ContentType.php @@ -21,7 +21,8 @@ class ContentType extends Component /** * Given a content type category slug, retrieves its namespaced class name - * @param $friendly_name + * + * @param $friendly_name * @return bool|string */ static function categoryTitleSlugToClass($slug) @@ -42,6 +43,7 @@ static function categoryTitleSlugToClass($slug) /** * Get all ContentType objects registered in the system. + * * @return array */ static function getRegistered() @@ -51,6 +53,7 @@ static function getRegistered() /** * Returns a version of this content type's category title suitable for including in a URL + * * @return string */ function getCategoryTitleSlug() @@ -60,6 +63,7 @@ function getCategoryTitleSlug() /** * Describes this content type as a category (eg "photos") + * * @return string */ function getCategoryTitle() @@ -73,6 +77,7 @@ function getCategoryTitle() /** * Return the name of this content type + * * @return string */ function getTitle() @@ -82,7 +87,8 @@ function getTitle() /** * Retrieves the name of the entity class associated with this content type - * @param bool $convert_slashes If set to true, converts \ slashes to / (false by default) + * + * @param bool $convert_slashes If set to true, converts \ slashes to / (false by default) * @return string */ function getEntityClass($convert_slashes = false) @@ -97,7 +103,8 @@ function getEntityClass($convert_slashes = false) /** * Given a class name, retrieves a content type object - * @param $class + * + * @param $class * @return bool|ContentType */ static function getContentTypeObjectFromClass($class) @@ -117,7 +124,8 @@ static function getContentTypeObjectFromClass($class) /** * Given multiple content types, creates a friendly string describing all of them - * @param $slugs + * + * @param $slugs * @return string */ static function categoryTitleSlugsToFriendlyName($slugs) @@ -135,7 +143,8 @@ static function categoryTitleSlugsToFriendlyName($slugs) /** * Given a content type category slug, retrieves its friendly name - * @param $slug + * + * @param $slug * @return bool|string */ static function categoryTitleSlugToFriendlyName($slug) @@ -159,7 +168,8 @@ static function categoryTitleSlugToFriendlyName($slug) /** * Given a content type category name, retrieves its namespaced class name - * @param $friendly_name + * + * @param $friendly_name * @return bool|string */ static function categoryTitleToClass($friendly_name) @@ -181,7 +191,7 @@ static function categoryTitleToClass($friendly_name) /** * Register a content type as being available to create / edit * - * @param $class The string name of a class that extends Idno\Common\ContentType. + * @param $class The string name of a class that extends Idno\Common\ContentType. * @return bool */ static function register($class) @@ -200,6 +210,7 @@ static function register($class) /** * Get the classes of all entities supplied by ContentType objects registered in the system. + * * @return array */ static function getRegisteredClasses() @@ -218,6 +229,7 @@ static function getRegisteredClasses() /** * Get the category title slugs of all entities supplied by ContentType objects registered in the system. + * * @return array */ static function getRegisteredCategorySlugs() @@ -238,7 +250,7 @@ static function getRegisteredCategorySlugs() * Given an IndieWeb content type ('note', 'reply', 'rsvp', etc), * retrieves the first registered plugin content type that maps to it * - * @param $type + * @param $type * @return \Idno\Common\ContentType */ static function getRegisteredForIndieWebPostType($type) @@ -256,7 +268,8 @@ static function getRegisteredForIndieWebPostType($type) /** * Retrieves the icon associated with this content type - * @param int $width The width of the icon to be returned. (Returned icon may not be the exact width.) + * + * @param int $width The width of the icon to be returned. (Returned icon may not be the exact width.) * @return string The public URL to the content type. */ function getIcon() @@ -272,6 +285,7 @@ function getIcon() /** * Returns the namespace-free entity class associated with this content type + * * @return string */ function getEntityClassName() @@ -283,6 +297,7 @@ function getEntityClassName() /** * Create an object with the entity class associated with this content type + * * @return \Idno\Common\Entity */ function createEntity() @@ -298,6 +313,7 @@ function createEntity() /** * Retrieves the URL to the form to create a new object related to this content type + * * @return string */ function getEditURL() diff --git a/Idno/Common/Entity.php b/Idno/Common/Entity.php index 1e2a72e9a0..1a9e0034bc 100644 --- a/Idno/Common/Entity.php +++ b/Idno/Common/Entity.php @@ -18,7 +18,6 @@ abstract class Entity extends Component implements EntityInterface { - // Which collection should this be stored in? private $collection = 'entities'; static $retrieve_collection = 'entities'; @@ -174,9 +173,10 @@ static function countFromX($class, $search = array()): int static function getOne($search = array(), $fields = array()) { - if ($records = static::get($search, $fields, 1)) + if ($records = static::get($search, $fields, 1)) { foreach ($records as $record) return $record; + } return false; } @@ -209,17 +209,21 @@ static function getByX($identifier) $object = null; - if (empty($object)) + if (empty($object)) { $object = static::getByID($identifier); + } - if (empty($object)) + if (empty($object)) { $object = static::getByUUID($identifier); + } - if (empty($object)) + if (empty($object)) { $object = static::getBySlug($identifier); + } - if (empty($object)) + if (empty($object)) { $object = static::getByShortURL($identifier); + } return $object; } @@ -250,10 +254,10 @@ static function getByID($id) static function getOneFromAll($search = array(), $fields = array()) { - if ($records = static::getFromAll($search, $fields, 1)) + if ($records = static::getFromAll($search, $fields, 1)) { foreach ($records as $record) return $record; - + } return false; } @@ -331,15 +335,17 @@ static function getByURL($url, $cached = true) { if (isset(self::$entity_cache[$url]) && $cached) return self::$entity_cache[$url]; - if (!self::isLocalUUID($url)) + if (!self::isLocalUUID($url)) { return false; + } $return = \Idno\Core\Idno::site()->events()->triggerEvent('object/getbyurl', [ 'url' => $url ], false); - if (!empty($return)) + if (!empty($return)) { self::$entity_cache[$url] = $return; + } return $return; } @@ -554,11 +560,8 @@ function publish() */ public function setPublishStatus($status = 'published') { - $status = trim($status); - $this->publish_status = $status; - } /** @@ -567,9 +570,7 @@ public function setPublishStatus($status = 'published') */ public function getPublishStatus() { - return $this->publish_status; - } /** @@ -2487,8 +2488,9 @@ function getAnnotation($uuid) { if (!empty($this->annotations) && is_array($this->annotations)) { foreach ($this->annotations as $subtype => $array) { - if (isset($array[$uuid])) + if (isset($array[$uuid])) { return $array[$uuid]; + } } } diff --git a/Idno/Common/EntityInterface.php b/Idno/Common/EntityInterface.php index 9e0861709d..52dede3ebd 100644 --- a/Idno/Common/EntityInterface.php +++ b/Idno/Common/EntityInterface.php @@ -6,7 +6,7 @@ * This is designed to be implemented by anything that needs to be an * object in the idno system * - * @package idno + * @package idno * @subpackage core */ diff --git a/Idno/Common/JSONLDSerialisable.php b/Idno/Common/JSONLDSerialisable.php index dfae6ed611..f6b4864368 100644 --- a/Idno/Common/JSONLDSerialisable.php +++ b/Idno/Common/JSONLDSerialisable.php @@ -10,7 +10,8 @@ interface JSONLDSerialisable /** * Serialise a object to a Structured Data schema. - * @param array $params Optional params + * + * @param array $params Optional params * @return array */ public function jsonLDSerialise(array $params = []); diff --git a/Idno/Common/MappingIterator.php b/Idno/Common/MappingIterator.php index 035ef16f51..908fa91b66 100644 --- a/Idno/Common/MappingIterator.php +++ b/Idno/Common/MappingIterator.php @@ -14,7 +14,7 @@ class MappingIterator extends \IteratorIterator /** * @param Traversable $iterator - * @param callable $func + * @param callable $func */ function __construct($iterator, $func) { diff --git a/Idno/Common/Page.php b/Idno/Common/Page.php index 70145c0ad9..6116f60967 100644 --- a/Idno/Common/Page.php +++ b/Idno/Common/Page.php @@ -11,7 +11,7 @@ * postContent: handles content submitted to the page (assuming that form * elements were correctly signed) * - * @package idno + * @package idno * @subpackage core */ @@ -77,15 +77,18 @@ function init() $_SERVER['HTTP_REFERER'] = $_SERVER['HTTP_REFERER']??''; // Ensure that the $_SERVER['HTTP_REFERER'] is never blank // Default exception handler - set_exception_handler(function ($exception) { - $page = \Idno\Core\Idno::site()->currentPage(); - if (!empty($page)) - $page->exception($exception); - - else - \Idno\Core\site()->logging()->error($exception->getMessage()); + set_exception_handler( + function ($exception) { + $page = \Idno\Core\Idno::site()->currentPage(); + if (!empty($page)) { + $page->exception($exception); + + } else { + \Idno\Core\site()->logging()->error($exception->getMessage()); + } - }); + } + ); \Idno\Core\Idno::site()->embedded(); @@ -96,11 +99,11 @@ function init() /** * Retrieves input. * - * @param string $name Name of the input variable - * @param mixed $default A default return value if no value specified (default: null) - * @param boolean $filter Whether or not to filter the variable for safety (default: null), you can pass - * a callable method, function or enclosure with a definition like function($name, $value), which - * will return the filtered result. + * @param string $name Name of the input variable + * @param mixed $default A default return value if no value specified (default: null) + * @param boolean $filter Whether or not to filter the variable for safety (default: null), you can pass + * a callable method, function or enclosure with a definition like + * function($name, $value), which will return the filtered result. * @return mixed */ function getInput($name, $default = null, callable $filter = null) @@ -113,8 +116,9 @@ function getInput($name, $default = null, callable $filter = null) } else if (isset($this->data[$name])) { $value = $this->data[$name]; } - if (($value===null) && ($default!==null)) + if (($value===null) && ($default!==null)) { $value = $default; + } if (!$value!==null) { if (isset($filter) && is_callable($filter) && empty($request)) { $value = call_user_func($filter, $name, $value); @@ -167,6 +171,7 @@ function setResponse(int $code) /** * Return the current response code for the page. + * * @return int */ function response():int @@ -181,7 +186,8 @@ function head_xhr() \Idno\Core\Idno::site()->template()->autodetectTemplateType(); $arguments = func_get_args(); - if (!empty($arguments)) $this->arguments = $arguments; + if (!empty($arguments)) { $this->arguments = $arguments; + } $this->xhr = true; $this->head(); @@ -196,7 +202,8 @@ function head() $this->parseJSONPayload(); $arguments = func_get_args(); - if (!empty($arguments)) $this->arguments = $arguments; + if (!empty($arguments)) { $this->arguments = $arguments; + } \Idno\Core\Idno::site()->events()->triggerEvent('page/head', array('page_class' => get_called_class(), 'arguments' => $arguments)); @@ -240,6 +247,7 @@ function parseJSONPayload() /** * Return the arguments sent to the page via regular expression + * * @return array */ function &arguments() : array @@ -249,6 +257,7 @@ function &arguments() : array /** * Provide access to page data + * * @return array */ function &data() : array @@ -258,6 +267,7 @@ function &data() : array /** * Is this an XHR page or not + * * @return bool */ function xhr(): bool @@ -284,7 +294,8 @@ function get_xhr() \Idno\Core\Idno::site()->template()->autodetectTemplateType(); $arguments = func_get_args(); - if (!empty($arguments)) $this->arguments = $arguments; + if (!empty($arguments)) { $this->arguments = $arguments; + } $this->xhr = true; $this->get(); } @@ -304,7 +315,8 @@ function get($params = array()) $this->parseJSONPayload(); $arguments = func_get_args(); - if (!empty($arguments)) $this->arguments = $arguments; + if (!empty($arguments)) { $this->arguments = $arguments; + } \Idno\Core\Idno::site()->events()->triggerEvent('page/head', array('page' => $this)); \Idno\Core\Idno::site()->events()->triggerEvent('page/get', array('page_class' => get_called_class(), 'arguments' => $arguments)); @@ -320,22 +332,25 @@ protected function debugLogToken() { $ts = ""; - if (empty($_REQUEST['__bTs'])) + if (empty($_REQUEST['__bTs'])) { \Idno\Core\Idno::site()->logging()->error("__bTs timestamp is missing"); - else + } else { $ts = $_REQUEST['__bTs']; + } $ta = ""; - if (empty($_REQUEST['__bTa'])) + if (empty($_REQUEST['__bTa'])) { \Idno\Core\Idno::site()->logging()->warning("__bTa action is missing"); - else + } else { $ta = $_REQUEST['__bTa']; + } $tk = ""; - if (empty($_REQUEST['__bTk'])) + if (empty($_REQUEST['__bTk'])) { \Idno\Core\Idno::site()->logging()->error("__bTk token is missing"); - else + } else { $tk = $_REQUEST['__bTk']; + } $debug = [ 'time' => $ts, @@ -364,7 +379,8 @@ function post_xhr() \Idno\Core\Idno::site()->template()->autodetectTemplateType(); $arguments = func_get_args(); - if (!empty($arguments)) $this->arguments = $arguments; + if (!empty($arguments)) { $this->arguments = $arguments; + } $this->xhr = true; $this->forward = false; $this->post(); @@ -382,7 +398,8 @@ function post() \Idno\Core\Idno::site()->template()->autodetectTemplateType(); $arguments = func_get_args(); - if (!empty($arguments)) $this->arguments = $arguments; + if (!empty($arguments)) { $this->arguments = $arguments; + } \Idno\Core\Idno::site()->events()->triggerEvent('page/head', array('page' => $this)); \Idno\Core\Idno::site()->events()->triggerEvent('page/post', array('page_class' => get_called_class(), 'arguments' => $arguments)); @@ -447,16 +464,21 @@ function postContent() /** * Default handling of OPTIONS (mostly to handle CORS) */ - function options() { + function options() + { - header('Access-Control-Allow-Methods: ' . implode(', ', [ - 'GET', - 'POST', - 'HEAD', - 'OPTIONS', - 'PUT', - 'DELETE' - ]) ); + header( + 'Access-Control-Allow-Methods: ' . implode( + ', ', [ + 'GET', + 'POST', + 'HEAD', + 'OPTIONS', + 'PUT', + 'DELETE' + ] + ) + ); header('Access-Control-Max-Age: 86400'); @@ -465,9 +487,11 @@ function options() { /** * Return the referrer, or an empty string + * * @return string */ - function referrer() : string { + function referrer() : string + { return $this->referrer; } @@ -476,7 +500,7 @@ function referrer() : string { * the browser on. Otherwise, do nothing * * @param string $location Location to forward to (eg "/foo/bar") - * @param bool $exit If set to true (which it is by default), execution finishes once the header is sent. + * @param bool $exit If set to true (which it is by default), execution finishes once the header is sent. */ function forward(string $location = '', bool $exit = true) { @@ -509,14 +533,17 @@ function forward(string $location = '', bool $exit = true) $call_trace = ""; - if (!empty($trace[0])) + if (!empty($trace[0])) { $call_trace .= "Forward at {$trace[0]['file']}:{$trace[0]['line']}"; + } if (!empty($trace[1])) { $trace_file = 'UNKNOWN'; - if (!empty($trace[1]['file'])) $trace_file = $trace[1]['file']; + if (!empty($trace[1]['file'])) { $trace_file = $trace[1]['file']; + } $trace_line = 'xxx'; - if (!empty($trace[1]['line'])) $trace_line = $trace[1]['line']; + if (!empty($trace[1]['line'])) { $trace_line = $trace[1]['line']; + } $call_trace .= ", called by {$trace[1]['function']} in {$trace_file}:{$trace_line}"; } @@ -532,11 +559,13 @@ function forward(string $location = '', bool $exit = true) $location = [ 'location' => $location ]; - if (!empty($call_trace)) + if (!empty($call_trace)) { $location['trace'] = $call_trace; + } echo json_encode($location); } elseif (!\Idno\Core\Idno::site()->session()->isAPIRequest() || $this->response == 200) { - if (!empty($call_trace)) header('X-Known-Forward-Trace: ' . $call_trace); + if (!empty($call_trace)) { header('X-Known-Forward-Trace: ' . $call_trace); + } header('Location: ' . $location); } @@ -548,8 +577,9 @@ function forward(string $location = '', bool $exit = true) /** * Forwards to login page with optional forward param + * * @param string $fwd - * @param bool $string If set to true, will return a string instead of forwarding + * @param bool $string If set to true, will return a string instead of forwarding */ function forwardToLogin($fwd = '', $string = false) { @@ -571,7 +601,8 @@ function put_xhr() \Idno\Core\Idno::site()->template()->autodetectTemplateType(); $arguments = func_get_args(); - if (!empty($arguments)) $this->arguments = $arguments; + if (!empty($arguments)) { $this->arguments = $arguments; + } $this->xhr = true; $this->forward = false; $this->put(); @@ -589,7 +620,8 @@ function put() \Idno\Core\Idno::site()->template()->autodetectTemplateType(); $arguments = func_get_args(); - if (!empty($arguments)) $this->arguments = $arguments; + if (!empty($arguments)) { $this->arguments = $arguments; + } \Idno\Core\Idno::site()->events()->triggerEvent('page/head', array('page' => $this)); \Idno\Core\Idno::site()->events()->triggerEvent('page/put', array('page_class' => get_called_class(), 'arguments' => $arguments)); @@ -634,8 +666,9 @@ function put() $this->forward(); // If we haven't forwarded yet, do so (if we can) } - if (http_response_code() != 200) + if (http_response_code() != 200) { http_response_code($this->response); + } } /** @@ -657,7 +690,8 @@ function delete_xhr() \Idno\Core\Idno::site()->template()->autodetectTemplateType(); $arguments = func_get_args(); - if (!empty($arguments)) $this->arguments = $arguments; + if (!empty($arguments)) { $this->arguments = $arguments; + } $this->xhr = true; $this->forward = false; $this->delete(); @@ -675,7 +709,8 @@ function delete() \Idno\Core\Idno::site()->template()->autodetectTemplateType(); $arguments = func_get_args(); - if (!empty($arguments)) $this->arguments = $arguments; + if (!empty($arguments)) { $this->arguments = $arguments; + } \Idno\Core\Idno::site()->events()->triggerEvent('page/head', array('page' => $this)); \Idno\Core\Idno::site()->events()->triggerEvent('page/delete', array('page_class' => get_called_class(), 'arguments' => $arguments)); @@ -720,8 +755,9 @@ function delete() $this->forward(); // If we haven't forwarded yet, do so (if we can) } - if (http_response_code() != 200) + if (http_response_code() != 200) { http_response_code($this->response); + } } /** @@ -749,10 +785,10 @@ function webmention() * Called when there's been a successful webmention call to the given page. * To be extended by developers. * - * @param string $source The source URL (i.e., third-party site URL) - * @param string $target The target URL (i.e., this page) - * @param array $source_response The Webservice response from fetching the source page - * @param array $source_mf2 The full, parsed Microformats 2 content of the source URL + * @param string $source The source URL (i.e., third-party site URL) + * @param string $target The target URL (i.e., this page) + * @param array $source_response The Webservice response from fetching the source page + * @param array $source_mf2 The full, parsed Microformats 2 content of the source URL * @return bool true if this page accepts webmentions */ function webmentionContent($source, $target, $source_response, $source_mf2) @@ -902,14 +938,17 @@ function adminGatekeeper() /** * Sets the entity on the page to the specified object + * * @param object $entity */ - function setEntity($entity) { + function setEntity($entity) + { $this->entity = $entity; } /** * Returns the entity associated with this page, if it exists + * * @return \Idno\Common\Entity|null */ function getEntity(): ?Entity @@ -920,24 +959,28 @@ function getEntity(): ?Entity /** * Removes any entity associated with this page */ - function removeEntity() { + function removeEntity() + { $this->entity = null; } /** * Is this page a permalink for an object? This should be set to 'true' * if it is. Optionally, we can also associate the page with the object here. - * @param bool $status Is this a permalink? Defaults to 'true' + * + * @param bool $status Is this a permalink? Defaults to 'true' * @param object $entity Optionally, an entity this page is associated with */ function setPermalink(bool $status = true, Entity $entity = null) { $this->isPermalinkPage = $status; - if ($status && $entity) $this->setEntity($entity); + if ($status && $entity) { $this->setEntity($entity); + } } /** * Is this page a permalink for an object? + * * @return bool */ function isPermalink() @@ -965,17 +1008,21 @@ function sslGatekeeper() /** * Has the page been requested over SSL? + * * @return boolean */ static function isSSL() { if (isset($_SERVER['HTTPS'])) { - if ($_SERVER['HTTPS'] == '1') + if ($_SERVER['HTTPS'] == '1') { return true; - if (strtolower($_SERVER['HTTPS']) == 'on') + } + if (strtolower($_SERVER['HTTPS']) == 'on') { return true; - } else if (isset($_SERVER['SERVER_PORT']) && ($_SERVER['SERVER_PORT'] == '443')) + } + } else if (isset($_SERVER['SERVER_PORT']) && ($_SERVER['SERVER_PORT'] == '443')) { return true; + } if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https') { return true; @@ -987,7 +1034,7 @@ static function isSSL() /** * Return the full URL of the current page. * - * @param $tokenise bool If true then an exploded tokenised version is returned. + * @param $tokenise bool If true then an exploded tokenised version is returned. * @return url|array */ public function currentUrl($tokenise = false) @@ -1005,7 +1052,8 @@ public function currentUrl($tokenise = false) /** * Helper function to see if the given Known base path matches the current page URL. * This is useful for setting active on menus in subdirectory installs. - * @param type $path Path, relative to the Known base + * + * @param type $path Path, relative to the Known base * @return bool */ public function doesPathMatch($path) @@ -1020,36 +1068,43 @@ public function doesPathMatch($path) /** * Construct a URL from array components (basically an implementation of http_build_url() without PECL. * - * @param array $url + * @param array $url * @return string */ public static function buildUrl(array $url) { - if (!empty($url['scheme'])) + if (!empty($url['scheme'])) { $page = $url['scheme'] . "://"; - else + } else { $page = '//'; + } // user/pass - if ((isset($url['user'])) && !empty($url['user'])) + if ((isset($url['user'])) && !empty($url['user'])) { $page .= $url['user']; - if ((isset($url['pass'])) && !empty($url['pass'])) + } + if ((isset($url['pass'])) && !empty($url['pass'])) { $page .= ":" . $url['pass']; - if (!empty($url['user']) || !empty($url['pass'])) + } + if (!empty($url['user']) || !empty($url['pass'])) { $page .= "@"; + } $page .= $url['host']; - if ((isset($url['port'])) && ($url['port'])) + if ((isset($url['port'])) && ($url['port'])) { $page .= ":" . $url['port']; + } $page .= $url['path']; - if ((isset($url['query'])) && ($url['query'])) + if ((isset($url['query'])) && ($url['query'])) { $page .= "?" . $url['query']; + } - if ((isset($url['fragment'])) && ($url['fragment'])) + if ((isset($url['fragment'])) && ($url['fragment'])) { $page .= "#" . $url['fragment']; + } return $page; } @@ -1060,7 +1115,7 @@ public static function buildUrl(array $url) * variables) will still take precedence. * * @param string $name - * @param mixed $value + * @param mixed $value */ function setInput($name, $value) { @@ -1086,10 +1141,12 @@ function getReferrer() /** * Detects whether the current web browser accepts the given content type. - * @param string $contentType The MIME content type. - * @param bool $ignore_priority If true, the 'q' parameter is ignored and the method returns true if - * $contentType appears anywhere in the accept header (original behaviour), otherwise it'll - * return true only if it's the highest value parameter. See #1622 + * + * @param string $contentType The MIME content type. + * @param bool $ignore_priority If true, the 'q' parameter is ignored and the method returns true if + * $contentType appears anywhere in the accept header (original + * behaviour), otherwise it'll return true only if it's the highest + * value parameter. See #1622 * @return bool */ function isAcceptedContentType($contentType, $ignore_priority = false) @@ -1100,7 +1157,8 @@ function isAcceptedContentType($contentType, $ignore_priority = false) if ($ignore_priority) { if (!empty($headers['Accept'])) { - if (substr_count($headers['Accept'], $contentType)) return true; + if (substr_count($headers['Accept'], $contentType)) { return true; + } } } else { if (!empty($headers['Accept'])) { @@ -1135,6 +1193,7 @@ function isAcceptedContentType($contentType, $ignore_priority = false) /** * Shim for running on nginx, which doesn't provide the * getallheaders function + * * @return array */ static function getallheaders() @@ -1154,17 +1213,20 @@ static function getallheaders() /** * Retrieve bearer token passed to this page, if any. + * * @return string|null */ - public static function getBearerToken(): ?string { + public static function getBearerToken(): ?string + { $headers = null; $serverheaders = \Idno\Common\Page::getallheaders(); - if (isset($serverheaders['Authorization'])) + if (isset($serverheaders['Authorization'])) { $headers = trim($serverheaders["Authorization"]); - else if (isset($serverheaders['HTTP_AUTHORIZATION'])) + } else if (isset($serverheaders['HTTP_AUTHORIZATION'])) { $headers = trim($serverheaders["HTTP_AUTHORIZATION"]); + } if (!empty($headers)) { if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) { @@ -1177,21 +1239,25 @@ public static function getBearerToken(): ?string { /** * Set or add a file asset. - * @param type $name Name of the asset (e.g. 'idno', 'jquery') + * + * @param type $name Name of the asset (e.g. 'idno', 'jquery') * @param type $class Class of asset (e.g. 'javascript', 'css') * @param type $value A URL or other value */ public function setAsset(string $name, string $value, string $class) { - if (!isset($this->assets) || !is_array($this->assets)) $this->assets = array(); - if (!isset($this->assets[$class]) || !is_array($this->assets)) $this->assets[$class] = array(); + if (!isset($this->assets) || !is_array($this->assets)) { $this->assets = array(); + } + if (!isset($this->assets[$class]) || !is_array($this->assets)) { $this->assets[$class] = array(); + } $this->assets[$class][$name] = $value; } /** * Get assets of a given class. - * @param type $class + * + * @param type $class * @return array */ public function getAssets(string $class) @@ -1223,6 +1289,7 @@ public function getIcon() /** * Retrieves the effective owner of this page, if one has been set + * * @return bool|User */ function getOwner() @@ -1238,6 +1305,7 @@ function getOwner() /** * Sets the given user as owner of this page + * * @param $user */ function setOwner($user) @@ -1260,6 +1328,7 @@ public function setNoCache() /** * Set the last updated header for this page. * Takes a unix timestamp and outputs it as RFC2616 date. + * * @param int $timestamp Unix timestamp. */ public function setLastModifiedHeader(int $timestamp) @@ -1270,6 +1339,7 @@ public function setLastModifiedHeader(int $timestamp) /** * Simplify if modified since checks. * Set a 304 not modified if If-Modified-Since header is less than the given timestamp. + * * @param type $timestamp Timestamp to check */ public function lastModifiedGatekeeper($timestamp) @@ -1285,6 +1355,7 @@ public function lastModifiedGatekeeper($timestamp) /** * Return whether the current page URL matches the given regex string. + * * @param type $regex_string URL string in the same format as the page handler definition. */ public function matchUrl($regex_string) @@ -1293,11 +1364,13 @@ public function matchUrl($regex_string) $page = $url['path']; - if ((isset($url['query'])) && ($url['query'])) + if ((isset($url['query'])) && ($url['query'])) { $page .= "?" . $url['query']; + } - if ((isset($url['fragment'])) && ($url['fragment'])) + if ((isset($url['fragment'])) && ($url['fragment'])) { $page .= "#" . $url['fragment']; + } $url = $page; diff --git a/Idno/Common/Plugin.php b/Idno/Common/Plugin.php index a4173b1151..7f0bb41fa2 100644 --- a/Idno/Common/Plugin.php +++ b/Idno/Common/Plugin.php @@ -3,7 +3,7 @@ /** * All idno plugins should extend this component. * - * @package idno + * @package idno * @subpackage core */ @@ -21,15 +21,16 @@ function init() return $result; } - - function registerLibraries() { - + + function registerLibraries() + { + $plugin = new \ReflectionClass(get_called_class()); $file = $plugin->getFileName(); - + if (file_exists(dirname($file) . '/vendor/autoload.php')) { - include_once(dirname($file) . '/vendor/autoload.php'); + include_once dirname($file) . '/vendor/autoload.php'; } } @@ -49,7 +50,8 @@ function registerContentTypes() /** * Returns the bytes used by this plugin; if a user ID is included, limits to that user's uploads - * @param string|bool $user (By default this isn't set) + * + * @param string|bool $user (By default this isn't set) * @return int */ function getFileUsage($user = false) @@ -62,8 +64,9 @@ function getFileUsage($user = false) */ public function getManifest() { - if (!empty($this->manifest)) + if (!empty($this->manifest)) { return $this->manifest; + } $reflection = new \ReflectionClass(get_called_class()); @@ -76,6 +79,7 @@ public function getManifest() /** * Return the version of this plugin. + * * @return type * @throws \Idno\Exceptions\ConfigurationException */ @@ -83,8 +87,9 @@ public function getVersion() { $manifest = $this->getManifest(); - if (empty($manifest['version'])) + if (empty($manifest['version'])) { throw new \Idno\Exceptions\ConfigurationException(\Idno\Core\Idno::site()->language()->_('Plugin %s doesn\'t have a version', [get_class($this)])); + } return $manifest['version']; } diff --git a/Idno/Common/RSSSerialisable.php b/Idno/Common/RSSSerialisable.php index d4c710ef83..083cbc2b70 100644 --- a/Idno/Common/RSSSerialisable.php +++ b/Idno/Common/RSSSerialisable.php @@ -3,7 +3,7 @@ /** * Describe an interface for outputting something as an RSS compatible DOM. * - * @package idno + * @package idno * @subpackage core */ @@ -14,7 +14,8 @@ interface RSSSerialisable /** * Serialise an item into a rss compatible DOMElement. - * @param array $params Optional params + * + * @param array $params Optional params * @return \DOMElement */ public function rssSerialise(array $params = []); diff --git a/Idno/Common/SessionStorageInterface.php b/Idno/Common/SessionStorageInterface.php index da36ea2207..90e21d4b47 100644 --- a/Idno/Common/SessionStorageInterface.php +++ b/Idno/Common/SessionStorageInterface.php @@ -14,6 +14,7 @@ interface SessionStorageInterface /** * Offer a session handler for the current session. + * * @return bool True if the session was handled */ public function handleSession(); diff --git a/Idno/Common/Theme.php b/Idno/Common/Theme.php index 66f6a3296f..0cc4abeb05 100644 --- a/Idno/Common/Theme.php +++ b/Idno/Common/Theme.php @@ -3,7 +3,7 @@ /** * All Known theme controllers should extend this component. * - * @package idno + * @package idno * @subpackage core */ @@ -19,14 +19,15 @@ function init() return $result; } - function registerLibraries() { - + function registerLibraries() + { + $plugin = new \ReflectionClass(get_called_class()); $file = $plugin->getFileName(); - + if (file_exists(dirname($file) . '/vendor/autoload.php')) { - include_once(dirname($file) . '/vendor/autoload.php'); + include_once dirname($file) . '/vendor/autoload.php'; } } } diff --git a/Idno/Core/Account.php b/Idno/Core/Account.php index dd1afbcff0..9b229bb439 100644 --- a/Idno/Core/Account.php +++ b/Idno/Core/Account.php @@ -3,7 +3,7 @@ /** * Account management class * - * @package idno + * @package idno * @subpackage core */ diff --git a/Idno/Core/Actions.php b/Idno/Core/Actions.php index 6b7b7f5b45..c12b194fea 100644 --- a/Idno/Core/Actions.php +++ b/Idno/Core/Actions.php @@ -3,7 +3,7 @@ /** * Action management class * - * @package idno + * @package idno * @subpackage core */ @@ -16,8 +16,8 @@ class Actions extends \Idno\Core\Bonita\Forms * Gatekeeper function that validates input forms and prevents csrf attacks. * Call this from your form action code. * - * @param string $targetURL The URL of the form action that brought us here. - * @param boolean $haltExecutionOnBadRequest If set to true, the function halts all execution if the form doesn't validate. (True by default.) + * @param string $targetURL The URL of the form action that brought us here. + * @param boolean $haltExecutionOnBadRequest If set to true, the function halts all execution if the form doesn't validate. (True by default.) * @return true|false */ public static function validateToken($action = '', $haltExecutionOnBadRequest = true) @@ -33,10 +33,10 @@ public static function validateToken($action = '', $haltExecutionOnBadRequest = * Creates an action link that will submit via POST to the page * specified at $pageurl with the data specified in $data * - * @param string $pageurl URL of the page to point to - * @param string $label The text of the link - * @param array $data Array of name:value pairs that will be submitted to $pageurl - * @param array $options Array of options for future use (optional) + * @param string $pageurl URL of the page to point to + * @param string $label The text of the link + * @param array $data Array of name:value pairs that will be submitted to $pageurl + * @param array $options Array of options for future use (optional) * @return string */ function createLink($pageurl, $label, $data = array(), $options = array()) @@ -50,8 +50,8 @@ function createLink($pageurl, $label, $data = array(), $options = array()) /** * Creates a properly-signed POST form * - * @param string $pageurl URL of the page to point to - * @param string $body The body for the form + * @param string $pageurl URL of the page to point to + * @param string $body The body for the form * @return type */ function createForm($pageurl, $body) diff --git a/Idno/Core/Admin.php b/Idno/Core/Admin.php index db6a21b515..e4b0d0831a 100644 --- a/Idno/Core/Admin.php +++ b/Idno/Core/Admin.php @@ -3,7 +3,7 @@ /** * Site administration * - * @package idno + * @package idno * @subpackage core */ @@ -41,8 +41,9 @@ function registerPages() /** * Retrieve users by admins. - * @param type $limit - * @param type $offset + * + * @param type $limit + * @param type $offset * @return type */ static function getAdmins($limit = 10, $offset = 0) diff --git a/Idno/Core/AsynchronousQueue.php b/Idno/Core/AsynchronousQueue.php index 87017cb083..cb8d7c7955 100644 --- a/Idno/Core/AsynchronousQueue.php +++ b/Idno/Core/AsynchronousQueue.php @@ -16,8 +16,9 @@ function registerPages() function enqueue($queueName, $eventName, array $eventData) { - if (empty($queueName)) + if (empty($queueName)) { $queueName = 'default'; + } $queuedEvent = new \Idno\Entities\AsynchronousQueuedEvent(); $queuedEvent->queue = $queueName; @@ -52,19 +53,23 @@ function getResult($id) /** * Dispatch event. + * * @param \Idno\Entities\AsynchronousQueuedEvent $event */ function dispatch(\Idno\Entities\AsynchronousQueuedEvent &$event) { - if (empty($event)) + if (empty($event)) { throw new \RuntimeException(\Idno\Core\Idno::site()->language()->_('No event passed')); + } - if (!($event instanceof \Idno\Entities\AsynchronousQueuedEvent)) + if (!($event instanceof \Idno\Entities\AsynchronousQueuedEvent)) { throw new \RuntimeException(\Idno\Core\Idno::site()->language()->_('Event passed is not a queued event, and so can\'t be dispatched')); + } - if ($event->complete) + if ($event->complete) { throw new \RuntimeException(\Idno\Core\Idno::site()->language()->_('Sorry, this event has already been dispatched (but not yet cleaned up)')); + } try { @@ -72,8 +77,9 @@ function dispatch(\Idno\Entities\AsynchronousQueuedEvent &$event) if (!empty($event->runAsContext)) { $user = \Idno\Entities\User::getByUUID($event->runAsContext); - if (empty($user)) + if (empty($user)) { throw new \RuntimeException(\Idno\Core\Idno::site()->language()->_("Invalid user (%s) given for runAsContext, aborting", [$event->runAsContext])); + } \Idno\Core\Idno::site()->session()->logUserOn($user); @@ -114,8 +120,9 @@ function gc($timeago = 300, $queue = null) 'complete' => true, ]; - if (!empty($queue)) + if (!empty($queue)) { $search['queue'] = $queue; + } if ($events = \Idno\Entities\AsynchronousQueuedEvent::get($search)) { diff --git a/Idno/Core/Autosave.php b/Idno/Core/Autosave.php index 4c61f3a410..dc2f625f56 100644 --- a/Idno/Core/Autosave.php +++ b/Idno/Core/Autosave.php @@ -3,7 +3,7 @@ /** * Site administration * - * @package idno + * @package idno * @subpackage core */ @@ -14,9 +14,10 @@ class Autosave extends \Idno\Common\Component /** * Caches the autosave value for the element $name in the context $context. - * @param string $context - * @param string $name - * @param mixed $value + * + * @param string $context + * @param string $name + * @param mixed $value * @return bool */ function setValue($context, $name, $value) @@ -41,6 +42,7 @@ function setValue($context, $name, $value) /** * Caches the autosave values for the specified elements in the associative array $elements. + * * @param $context * @param $elements */ @@ -64,9 +66,10 @@ function setValues($context, $elements) /** * Retrieves the cached autosave value (if it exists) for $name in the context $context - * @param string $context - * @param string $name - * @param string $default Value to default to if the cache does not exist + * + * @param string $context + * @param string $name + * @param string $default Value to default to if the cache does not exist * @return mixed|bool */ function getValue($context, $name, $default = '') @@ -87,7 +90,8 @@ function getValue($context, $name, $default = '') /** * Clears the autosave cache for a particular context - * @param $context + * + * @param $context * @return bool|false|MongoID|null */ function clearContext($context) diff --git a/Idno/Core/Bonita/BonDrawable.class.php b/Idno/Core/Bonita/BonDrawable.class.php index c4757b4c6c..6164cd0bae 100644 --- a/Idno/Core/Bonita/BonDrawable.class.php +++ b/Idno/Core/Bonita/BonDrawable.class.php @@ -1,15 +1,13 @@ 'value1', 'name2' => 'value2')) + * + * @param $vars array Variables to add to the template (eg array('name1' => 'value1', 'name2' => 'value2')) * @return \Bonita\Templates this template object */ function __($vars) { if (!empty($vars) && is_array($vars)) { - foreach ($vars as $var => $value) + foreach ($vars as $var => $value) { $this->$var = $value; + } } return $this; } /** * Method to draw an actual template element - * @param string $templateName Name of the template element to draw - * @param boolean $returnBlank If true, returns a blank string on failure; otherwise false + * + * @param string $templateName Name of the template element to draw + * @param boolean $returnBlank If true, returns a blank string on failure; otherwise false * @return string|false Rendered template element or false, depending on $returnBlank */ function draw($templateName, $returnBlank = true) @@ -91,40 +94,44 @@ function draw($templateName, $returnBlank = true) // Add template types to an array; ensure we revert to default $templateTypes = array($this->getTemplateType()); if ($this->fallbackToDefault) { - if ($this->getTemplateType() != 'default') + if ($this->getTemplateType() != 'default') { $templateTypes[] = 'default'; + } } // Cycle through the additional paths and check for the template file // - if it exists, break out of the foreach - foreach ($templateTypes as $templateType) - foreach ($paths as $basepath) { - $path = $basepath . '/templates/' . $templateType . '/' . $templateName . '.tpl.php'; - if (file_exists($path)) { - // create an anonymous function for scoping - $fn = (function ($path, $vars, $t) { - // dump the variables into the local scope - foreach ($vars as $k => $v) { - ${$k} = $v; - } - ob_start(); - include $path; - return ob_get_clean(); - }); - return $fn($path, $this->vars, $this); + foreach ($templateTypes as $templateType) { + foreach ($paths as $basepath) { + $path = $basepath . '/templates/' . $templateType . '/' . $templateName . '.tpl.php'; + if (file_exists($path)) { + // create an anonymous function for scoping + $fn = (function ($path, $vars, $t) { + // dump the variables into the local scope + foreach ($vars as $k => $v) { + ${$k} = $v; + } + ob_start(); + include $path; + return ob_get_clean(); + }); + return $fn($path, $this->vars, $this); + } } } } // If we've got here, just return a blank string; the template doesn't exist - if ($returnBlank) + if ($returnBlank) { return ''; + } return false; } /** * Draws a list of PHP objects using a specified list template. Objects * must have a template of the form object/classname - * @param $items An array of PHP objects + * + * @param $items An array of PHP objects * @return string */ function drawList($items, $style = 'stream') @@ -140,7 +147,8 @@ function drawList($items, $style = 'stream') /** * Draws a single supplied PHP object. Objects should have a corresponding template * of the form object/classname - * @param $item PHP object + * + * @param $item PHP object * @return string */ function drawObject($object) @@ -148,10 +156,12 @@ function drawObject($object) if (is_object($object)) { $t = new \Idno\Core\Bonita\Templates($this); $t->object = $object; - if (($result = $t->draw('object/' . get_class($object), false)) !== false) + if (($result = $t->draw('object/' . get_class($object), false)) !== false) { return $result; - if ($object instanceof BonDrawable) + } + if ($object instanceof BonDrawable) { return $t->draw('object/default'); + } } return ''; } @@ -160,8 +170,9 @@ function drawObject($object) * Takes some text and runs it through the current template's processor. * This is in the form of a template at processors/text, or processors/X where X * is a custom processor - * @param $content Some content - * @param $processor Optionally, the processor you want to use (default: text) + * + * @param $content Some content + * @param $processor Optionally, the processor you want to use (default: text) * @return string Formatted content (or the input content if the processor doesn't exist) */ function process($content, $processor = 'text') @@ -169,14 +180,16 @@ function process($content, $processor = 'text') $t = new \Idno\Core\Bonita\Templates(); $t->content = $content; $t->setTemplateType($this->getTemplateType()); - if (($result = $t->draw('processor/' . $processor, false)) !== false) + if (($result = $t->draw('processor/' . $processor, false)) !== false) { return $result; + } return $content; } /** * Draws the shell template - * @param $echo If set to true (by default), echoes the page; otherwise returns it + * + * @param $echo If set to true (by default), echoes the page; otherwise returns it * @param $shell Optional override of the page shell template to be used */ function drawPage($echo = true, $shell = 'shell') @@ -189,16 +202,19 @@ function drawPage($echo = true, $shell = 'shell') // Break long output to avoid an Apache performance bug $split_output = str_split($content, 1024); - foreach ($split_output as $chunk) + foreach ($split_output as $chunk) { echo $chunk; + } exit; - } else + } else { return $this->draw($shell); + } } /** * Returns the current template type + * * @return string Name of the current template ('default' by default) */ function getTemplateType() @@ -208,6 +224,7 @@ function getTemplateType() /** * Sets the current template type + * * @param string $template The name of the template you wish to use */ function setTemplateType($templateType) @@ -222,7 +239,8 @@ function setTemplateType($templateType) /** * Does the specified template type exist? - * @param string Name of the template type + * + * @param string Name of the template type * @return true|false */ function templateTypeExists($templateType) @@ -232,8 +250,9 @@ function templateTypeExists($templateType) $paths = \Idno\Core\Bonita\Main::getPaths(); foreach ($paths as $basepath) { $path = $basepath . '/templates/' . $templateType . '/'; - if (file_exists($path)) + if (file_exists($path)) { return true; + } } } return false; diff --git a/Idno/Core/Config.php b/Idno/Core/Config.php index 1eea1dc42c..8ff0d42cb7 100644 --- a/Idno/Core/Config.php +++ b/Idno/Core/Config.php @@ -3,7 +3,7 @@ /** * Configuration management class * - * @package idno + * @package idno * @subpackage core */ @@ -89,7 +89,8 @@ function __set($name, $value) function __isset($name) { - if (!empty($this->config[$name])) return true; + if (!empty($this->config[$name])) { return true; + } return false; } @@ -100,7 +101,8 @@ function __isset($name) */ function load() { - if (empty($config)) $config = \Idno\Core\Idno::site()->db()->getAnyRecord('config'); + if (empty($config)) { $config = \Idno\Core\Idno::site()->db()->getAnyRecord('config'); + } if ($config) { $this->default_config = false; unset($config['dbname']); // Ensure we don't accidentally load protected data from db @@ -132,8 +134,10 @@ function load() } } else { // If we don't have a saved config, this is a new site. Set some plugin defaults - if (!is_array($this->config)) $this->config = []; - if (!is_array($this->config['plugins'])) $this->config['plugins'] = []; + if (!is_array($this->config)) { $this->config = []; + } + if (!is_array($this->config['plugins'])) { $this->config['plugins'] = []; + } $this->config['plugins'][] = 'Status'; $this->config['plugins'][] = 'Text'; $this->config['plugins'][] = 'Photo'; @@ -246,7 +250,8 @@ function loadIniFiles() } // Perform some sanity checks on some user contributed settings - if (isset($this->ini_config['uploadpath'])) $this->ini_config['uploadpath'] = rtrim($this->ini_config['uploadpath'], ' /') . '/'; // End trailing slash insanity once and for all + if (isset($this->ini_config['uploadpath'])) { $this->ini_config['uploadpath'] = rtrim($this->ini_config['uploadpath'], ' /') . '/'; // End trailing slash insanity once and for all + } unset($this->ini_config['path']); // Path should always be derived unset($this->ini_config['host']); // Host should always come from URL } @@ -258,6 +263,7 @@ function loadIniFiles() /** * Saves configuration information to the database, if possible. + * * @return true|false */ function save() @@ -399,8 +405,9 @@ protected function detectBaseURL() $url = (\Idno\Common\Page::isSSL() ? 'https://' : 'http://') . $domain; $port = getenv('KNOWN_PORT'); - if (!$port) + if (!$port) { $port = 80; + } if ($port != 80 && $port != 443) { $url .= ':' . $port; @@ -422,6 +429,7 @@ protected function detectBaseURL() /** * Return a version of the URL suitable for displaying in templates etc + * * @return string */ function getDisplayURL() @@ -445,6 +453,7 @@ function getDisplayURL() /** * Retrieve the canonical URL of the site + * * @return string */ function getURL() @@ -458,6 +467,7 @@ function getURL() /** * Returns the upload path for Known. + * * @return string */ function getUploadPath() @@ -467,6 +477,7 @@ function getUploadPath() /** * Returns the installation path for Known. + * * @return string */ function getPath() @@ -485,7 +496,8 @@ protected function sanitizeValues() /** * Given a URL, ensure it fits the content standards we need - * @param $url + * + * @param $url * @return bool */ function sanitizeURL($url) @@ -505,7 +517,8 @@ function sanitizeURL($url) /** * Make sure attachment URL is pointing to the right place - * @param $url + * + * @param $url * @return mixed */ function sanitizeAttachmentURL($url) @@ -521,6 +534,7 @@ function sanitizeAttachmentURL($url) /** * Get a version of the URL without URI scheme or trailing slash + * * @return string */ function getSchemelessURL($preceding_slashes = false) @@ -541,6 +555,7 @@ function getSchemelessURL($preceding_slashes = false) /** * Retrieves the URL for static assets + * * @return string */ function getStaticURL() @@ -554,7 +569,8 @@ function getStaticURL() /** * Adds an email address to the blocked list - * @param $email + * + * @param $email * @return array|bool */ function addBlockedEmail($email) @@ -571,6 +587,7 @@ function addBlockedEmail($email) /** * Retrieve an array of email addresses that are blocked from registering on this site. + * * @return array */ function getBlockedEmails() @@ -585,7 +602,8 @@ function getBlockedEmails() /** * Remove an email address from the blocklist - * @param $email + * + * @param $email * @return array|bool */ function removeBlockedEmail($email) @@ -607,7 +625,8 @@ function removeBlockedEmail($email) /** * Is the specified email address blocked from registering? - * @param $email + * + * @param $email * @return bool */ function emailIsBlocked($email) @@ -626,6 +645,7 @@ function emailIsBlocked($email) /** * Does this site have SSL? + * * @return bool */ function hasSSL() @@ -639,6 +659,7 @@ function hasSSL() /** * Retrieve the name of this site + * * @return string */ function getTitle() @@ -652,6 +673,7 @@ function getTitle() /** * Retrieve the description of this site + * * @return string */ function getDescription() @@ -665,6 +687,7 @@ function getDescription() /** * Returns the base folder name to use when storing files (usually the site host) + * * @return mixed|string */ function getFileBaseDirName() @@ -680,6 +703,7 @@ function getFileBaseDirName() /** * Return a normalized version of the host, for use in file paths etc + * * @return string */ function pathHost() @@ -689,6 +713,7 @@ function pathHost() /** * Is this site's content available to non-members? + * * @return bool */ function isPublicSite() @@ -702,6 +727,7 @@ function isPublicSite() /** * Does this site allow users to have multiple syndication accounts? + * * @return bool */ function multipleSyndicationAccounts() @@ -715,6 +741,7 @@ function multipleSyndicationAccounts() /** * Can new users be added to the site? Defaults to true; uses a hook to determine. + * * @return bool */ function canAddUsers() @@ -728,6 +755,7 @@ function canAddUsers() /** * Can the site administrator make this site private? Defaults to true; uses a hook to determine. + * * @return bool */ function canMakeSitePrivate() @@ -741,6 +769,7 @@ function canMakeSitePrivate() /** * Is this the default site configuration? + * * @return bool */ function isDefaultConfig() @@ -754,6 +783,7 @@ function isDefaultConfig() /** * Get the content types that this site should display on its homepage. + * * @return array */ function getHomepageContentTypes() @@ -774,6 +804,7 @@ function getHomepageContentTypes() /** * Attempt to get a temporary folder suitable for writing in. + * * @return string */ function getTempDir() @@ -806,8 +837,9 @@ function getTempDir() /** * Add a trailing slash to the ends of paths - * @todo Further sanitization tasks - * @param $path + * + * @todo Further sanitization tasks + * @param $path * @return string */ function sanitizePath($path) @@ -822,6 +854,7 @@ function sanitizePath($path) /** * Get the configured permalink structure for posts in the * format /:tag1/:tag2 + * * @return string */ function getPermalinkStructure() diff --git a/Idno/Core/DataConcierge.php b/Idno/Core/DataConcierge.php index f56e6435ff..16c64dd02c 100644 --- a/Idno/Core/DataConcierge.php +++ b/Idno/Core/DataConcierge.php @@ -6,13 +6,13 @@ * implement the functions, and set Idno\Core\Idno->$db to be its * replacement. * - * @package idno + * @package idno * @subpackage core */ namespace Idno\Core { - use Ramsey\Uuid\Uuid; + use Ramsey\Uuid\Uuid; abstract class DataConcierge extends \Idno\Common\Component { @@ -23,6 +23,7 @@ abstract class DataConcierge extends \Idno\Common\Component /** * Performs database optimizations, depending on engine + * * @return bool */ function optimize() @@ -32,6 +33,7 @@ function optimize() /** * Returns an instance of the database client reference variable + * * @return \Mongo */ function getClient() @@ -64,7 +66,7 @@ function saveObject($object) * Retrieves an Idno entity object by its UUID, casting it to the * correct class * - * @param string $id + * @param string $id * @return \Idno\Common\Entity | false */ @@ -85,7 +87,7 @@ function getObject($uuid) /** * Retrieves ANY object from a collection. * - * @param string $collection + * @param string $collection * @return \Idno\Common\Entity | false */ function getAnyObject($collection = 'entities') @@ -100,7 +102,8 @@ function getAnyObject($collection = 'entities') /** * Temporarily set the ability to disable access controls. - * @param bool $value True to ignore + * + * @param bool $value True to ignore * @return bool The previous value */ function setIgnoreAccess($value = true) @@ -123,8 +126,8 @@ function getIgnoreAccess() /** * Saves a record to the specified database collection * - * @param string $collection - * @param array $array + * @param string $collection + * @param array $array * @return id | false */ abstract function saveRecord($collection, $array); @@ -133,8 +136,8 @@ abstract function saveRecord($collection, $array); /** * Retrieves a record from the database by its UUID * - * @param string $id - * @param string $collection The collection to retrieve from (default: entities) + * @param string $id + * @param string $collection The collection to retrieve from (default: entities) * @return array */ @@ -144,7 +147,7 @@ abstract function getRecordByUUID($uuid, $collection = 'entities'); /** * Converts a database row into an Idno entity * - * @param array $row + * @param array $row * @return \Idno\Common\Entity | false */ function rowToEntity($row) @@ -167,7 +170,8 @@ function rowToEntity($row) /** * Process the ID appropriately - * @param $id + * + * @param $id * @return \MongoId */ abstract function processID($id); @@ -175,7 +179,7 @@ abstract function processID($id); /** * Return an ID */ - function generateID() : string + function generateID() : string { return Uuid::uuid4(); } @@ -183,8 +187,8 @@ function generateID() : string /** * Retrieves a record from the database by ID * - * @param string $id - * @param string $entities The collection name to retrieve from (default: 'entities') + * @param string $id + * @param string $entities The collection name to retrieve from (default: 'entities') * @return array */ @@ -193,7 +197,7 @@ abstract function getRecord($id, $collection = 'entities'); /** * Retrieves ANY record from a collection * - * @param string $collection + * @param string $collection * @return array */ abstract function getAnyRecord($collection = 'entities'); @@ -203,13 +207,13 @@ abstract function getAnyRecord($collection = 'entities'); * (or excluding kinds that we don't want to see), * in reverse chronological order * - * @param string|array $subtypes String or array of subtypes we're allowed to see - * @param array $search Any extra search terms in array format (eg array('foo' => 'bar')) (default: empty) - * @param array $fields An array of fieldnames to return (leave empty for all; default: all) - * @param int $limit Maximum number of records to return (default: 10) - * @param int $offset Number of records to skip (default: 0) - * @param string $collection Collection to query; default: entities - * @param array $readGroups Which ACL groups should we check? (default: everything the user can see) + * @param string|array $subtypes String or array of subtypes we're allowed to see + * @param array $search Any extra search terms in array format (eg array('foo' => 'bar')) (default: empty) + * @param array $fields An array of fieldnames to return (leave empty for all; default: all) + * @param int $limit Maximum number of records to return (default: 10) + * @param int $offset Number of records to skip (default: 0) + * @param string $collection Collection to query; default: entities + * @param array $readGroups Which ACL groups should we check? (default: everything the user can see) * @return array|false Array of elements or false, depending on success */ @@ -219,10 +223,10 @@ abstract function getObjects($subtypes = '', $search = array(), $fields = array( * Retrieves a set of records from the database with given parameters, in * reverse chronological order * - * @param array $parameters Query parameters in MongoDB format - * @param int $limit Maximum number of records to return - * @param int $offset Number of records to skip - * @param string $collection The collection to interrogate (default: 'entities') + * @param array $parameters Query parameters in MongoDB format + * @param int $limit Maximum number of records to return + * @param int $offset Number of records to skip + * @param string $collection The collection to interrogate (default: 'entities') * @return iterator|false Iterator or false, depending on success */ @@ -230,9 +234,10 @@ abstract function getRecords($fields, $parameters, $limit, $offset, $collection /** * Export a collection to JSON. - * @param string $collection - * @param int $limit - * @param int $offset + * + * @param string $collection + * @param int $limit + * @param int $offset * @return bool|string */ abstract function exportRecords($collection = 'entities', $limit = 10, $offset = 0); @@ -240,30 +245,33 @@ abstract function exportRecords($collection = 'entities', $limit = 10, $offset = /** * Count objects of a certain kind that we're allowed to see * - * @param string|array $subtypes String or array of subtypes we're allowed to see - * @param array $search Any extra search terms in array format (eg array('foo' => 'bar')) (default: empty) - * @param string $collection Collection to query; default: entities + * @param string|array $subtypes String or array of subtypes we're allowed to see + * @param array $search Any extra search terms in array format (eg array('foo' => 'bar')) (default: empty) + * @param string $collection Collection to query; default: entities */ abstract function countObjects($subtypes = '', $search = array(), $collection = 'entities'); /** * Count the number of records that match the given parameters - * @param array $parameters - * @param string $collection The collection to interrogate (default: 'entities') + * + * @param array $parameters + * @param string $collection The collection to interrogate (default: 'entities') * @return int */ abstract function countRecords($parameters, $collection = 'entities'); /** * Remove an entity from the database - * @param string $id + * + * @param string $id * @return true|false */ abstract function deleteRecord($id, $collection = 'entities'); /** * Remove all entities from the database - * @param string $collection + * + * @param string $collection * @return mixed */ abstract function deleteAllRecords($collection); @@ -271,13 +279,15 @@ abstract function deleteAllRecords($collection); /** * Retrieve the filesystem associated with the current db, suitable for saving * and retrieving files + * * @return bool|filesystem */ abstract function getFilesystem(); /** * Given a text query, return an array suitable for adding into getFromX calls - * @param $query + * + * @param $query * @return array */ abstract function createSearchArray($query); @@ -285,6 +295,7 @@ abstract function createSearchArray($query); /** * Internal function which ensures collections are sanitised. + * * @return string Contents of $collection stripped of invalid characters. */ protected function sanitiseCollection($collection) @@ -295,15 +306,18 @@ protected function sanitiseCollection($collection) /** * Utility function which normalises a variable into an array. * Sometimes you want to be sure you always have an array, but sometimes array values are saved as a single value if they e.g. contain only one value. + * * @param mixed $variable */ public static function normaliseArray($variable) { $return = $variable; - if (empty($return)) $return = []; - if (!empty($return) && !is_array($return)) + if (empty($return)) { $return = []; + } + if (!empty($return) && !is_array($return)) { $return = [$return]; + } return $return; } @@ -311,6 +325,7 @@ public static function normaliseArray($variable) /** * Helper function that returns the current database object + * * @return \Idno\Core\DataConcierge */ function db() diff --git a/Idno/Core/DefaultTemplate.php b/Idno/Core/DefaultTemplate.php index 80f77774d4..d5acc862f1 100644 --- a/Idno/Core/DefaultTemplate.php +++ b/Idno/Core/DefaultTemplate.php @@ -3,7 +3,7 @@ /** * Template management class * - * @package idno + * @package idno * @subpackage core */ @@ -16,26 +16,26 @@ class DefaultTemplate extends \Idno\Core\Bonita\Templates { // Require sample texts use Templating\SampleText; - + // Utility URLs use Templating\Urls; - + // Parsing strings use Templating\Parsing; - + // Formatting functions use Templating\Formatting; - + // Template variables use Templating\Variables; - + // Data variables use Templating\Data; - + // Class manipulations stuff use Templating\Classes; - - + + // We'll keep track of extensions to templates here public $extensions = array(); @@ -76,8 +76,9 @@ function __construct($template = false) /** * Override a page shell based on the page root. + * * @param type $path_root Url base, e.g. 'settings' - * @param type $shell The shell, e.g. 'settings-shell' + * @param type $shell The shell, e.g. 'settings-shell' */ public function addUrlShellOverride($path_root, $shell) { @@ -87,9 +88,9 @@ public function addUrlShellOverride($path_root, $shell) /** * Extension-aware version of the template drawing function * - * @param string $templateName - * @param bool $returnBlank Should we return a blank string if the template doesn't exist? (Defaults to true) - * @param book $replacements Should we honor template replacements? (Defaults to true) + * @param string $templateName + * @param bool $returnBlank Should we return a blank string if the template doesn't exist? (Defaults to true) + * @param book $replacements Should we honor template replacements? (Defaults to true) * @return \Idno\Core\Bonita\false|string */ function draw($templateName, $returnBlank = true, $replacements = true) @@ -127,16 +128,19 @@ function draw($templateName, $returnBlank = true, $replacements = true) } } - if (!empty($result)) return $result; - if ($returnBlank) return ''; + if (!empty($result)) { return $result; + } + if ($returnBlank) { return ''; + } return false; } /** * Draws the page shell. - * @param bool $echo - * @param $shell Optional override of the page shell template to be used + * + * @param bool $echo + * @param $shell Optional override of the page shell template to be used * @return false|string */ function drawPage($echo = true, $shell = 'shell') @@ -144,8 +148,7 @@ function drawPage($echo = true, $shell = 'shell') // Detect page, and see if we need to use a different shell foreach ($this->url_shell_overrides as $url => $page_shell) { - if (strpos(\Idno\Core\Idno::site()->currentPage()->currentUrl(), \Idno\Core\Idno::site()->config()->getDisplayURL() . $url.'/') === 0) - { + if (strpos(\Idno\Core\Idno::site()->currentPage()->currentUrl(), \Idno\Core\Idno::site()->config()->getDisplayURL() . $url.'/') === 0) { $shell = $page_shell; } @@ -163,28 +166,34 @@ function drawPage($echo = true, $shell = 'shell') /** * Draw syndication buttons relating to a particular content type - * @param $content_type - * @param $posse_links containing Entity::getPosseLinks() + * + * @param $content_type + * @param $posse_links containing Entity::getPosseLinks() * @return \Idno\Core\Bonita\false|string */ function drawSyndication($content_type, $posse_links = []) { - return $this->__(array('services' => \Idno\Core\Idno::site()->syndication()->getServices($content_type), + return $this->__( + array('services' => \Idno\Core\Idno::site()->syndication()->getServices($content_type), 'content_type' => $content_type, - 'posseLinks' => $posse_links))->draw('content/syndication'); + 'posseLinks' => $posse_links) + )->draw('content/syndication'); } /** * Draws generic pagination suitable for placing somewhere on a page (offset is drawn from the 'offset' input variable) - * @param int $count Number of items in total (across all pages) - * @param int $items_per_page Number of items you're displaying per page - * @param array $vars Additional template variables + * + * @param int $count Number of items in total (across all pages) + * @param int $items_per_page Number of items you're displaying per page + * @param array $vars Additional template variables * @return string */ function drawPagination($count, $items_per_page = null, array $vars = []) { - if (empty($vars)) $vars = []; - if ($items_per_page == null) $items_per_page = \Idno\Core\Idno::site()->config()->items_per_page; + if (empty($vars)) { $vars = []; + } + if ($items_per_page == null) { $items_per_page = \Idno\Core\Idno::site()->config()->items_per_page; + } $page = \Idno\Core\Idno::site()->currentPage(); $offset = (int)$page->getInput('offset'); if ($offset == 0 && $count < $items_per_page) { @@ -203,7 +212,7 @@ function drawPagination($count, $items_per_page = null, array $vars = []) * * @param string $templateName * @param string $extensionTemplateName - * @param bool $to_front If set, this will add the template to the beginning of the template queue + * @param bool $to_front If set, this will add the template to the beginning of the template queue */ function extendTemplate($templateName, $extensionTemplateName, $to_front = false, $templateType = '*') { @@ -225,7 +234,7 @@ function extendTemplate($templateName, $extensionTemplateName, $to_front = false * * @param string $templateName * @param string $prependTemplateName - * @param bool $to_front If set, this will add the template to the beginning of the template queue + * @param bool $to_front If set, this will add the template to the beginning of the template queue */ function prependTemplate($templateName, $prependTemplateName, $to_front = false) { @@ -261,6 +270,7 @@ function replaceTemplate($templateName, $replacementTemplateName, $templateType /** * Extends a given template with pre-rendered content. All pre-rendered content will be drawn after * template-driven content. + * * @param $templateName * @param $content */ diff --git a/Idno/Core/Deprecated/Idno.php b/Idno/Core/Deprecated/Idno.php index 193f5d65ba..255ecaf2ec 100644 --- a/Idno/Core/Deprecated/Idno.php +++ b/Idno/Core/Deprecated/Idno.php @@ -13,9 +13,9 @@ trait Idno * page handling syntax * * @deprecated - * @param string $pattern The pattern to match - * @param string $handler The name of the Page class that will serve this route - * @param bool $public If set to true, this page is always public, even on non-public sites + * @param string $pattern The pattern to match + * @param string $handler The name of the Page class that will serve this route + * @param bool $public If set to true, this page is always public, even on non-public sites */ function addPageHandler($pattern, $handler, $public = false) { @@ -29,9 +29,9 @@ function addPageHandler($pattern, $handler, $public = false) * page handling syntax - and ensures it will be handled first * * @deprecated - * @param string $pattern The pattern to match - * @param string $handler The name of the Page class that will serve this route - * @param bool $public If set to true, this page is always public, even on non-public sites + * @param string $pattern The pattern to match + * @param string $handler The name of the Page class that will serve this route + * @param bool $public If set to true, this page is always public, even on non-public sites */ function hijackPageHandler($pattern, $handler, $public = false) { @@ -42,8 +42,9 @@ function hijackPageHandler($pattern, $handler, $public = false) /** * Mark a page handler class as offering public content even on walled garden sites + * * @deprecated - * @param $class + * @param $class */ function addPublicPageHandler($class) { @@ -54,8 +55,9 @@ function addPublicPageHandler($class) /** * Retrieve an array of walled garden page handlers + * * @deprecated - * @return array + * @return array */ function getPublicPageHandlers() { @@ -66,9 +68,10 @@ function getPublicPageHandlers() /** * Does the specified page handler class represent a public page, even on walled gardens? + * * @deprecated - * @param $class - * @return bool + * @param $class + * @return bool */ function isPageHandlerPublic($class) { @@ -82,8 +85,8 @@ function isPageHandlerPublic($class) * a particular page (if any). May also be a whole URL. * * @deprecated - * @param string $path_info The path, including the initial /, or the URL - * @return bool|\Idno\Common\Page + * @param string $path_info The path, including the initial /, or the URL + * @return bool|\Idno\Common\Page */ function getPageHandler($path_info) { @@ -97,11 +100,11 @@ function getPageHandler($path_info) * Shortcut to trigger an event: supply the event name and * (optionally) an array of data, and get a variable back. * - * @param string $eventName The name of the event to trigger - * @param array $data Data to pass to the event - * @param mixed $default Default response (if not forwarding) + * @param string $eventName The name of the event to trigger + * @param array $data Data to pass to the event + * @param mixed $default Default response (if not forwarding) * @deprecated - * @return mixed + * @return mixed */ function triggerEvent($eventName, $data = array(), $default = true) @@ -117,9 +120,9 @@ function triggerEvent($eventName, $data = array(), $default = true) * that specifies order priority; the higher the number, the earlier * in the chain $listener will be notified. * - * @param string $event - * @param callable $listener - * @param int $priority + * @param string $event + * @param callable $listener + * @param int $priority * @deprecated */ function addEventHook($event, $listener, $priority = 0) diff --git a/Idno/Core/Email.php b/Idno/Core/Email.php index c251ce87cd..1afaeeb18f 100644 --- a/Idno/Core/Email.php +++ b/Idno/Core/Email.php @@ -19,6 +19,7 @@ function init() /** * Set the subject of the message + * * @param $subject */ function setSubject($subject) @@ -28,8 +29,9 @@ function setSubject($subject) /** * Set the "From" address of the message - * @param $email The email address of the account - * @param $name The name of the account + * + * @param $email The email address of the account + * @param $name The name of the account * @return mixed */ function setFrom($email, $name = '') @@ -43,8 +45,9 @@ function setFrom($email, $name = '') /** * Add a recipient - * @param string $email The email address of the recipient - * @param string $name The name of the recipient (optional) + * + * @param string $email The email address of the recipient + * @param string $name The name of the recipient (optional) * @return mixed */ function addTo($email, $name = '') @@ -58,7 +61,8 @@ function addTo($email, $name = '') /** * Adds an email to the BCC list - * @param $email + * + * @param $email * @return mixed */ function addBcc($email) @@ -68,8 +72,9 @@ function addBcc($email) /** * Add a "reply to" message - * @param $email - * @param string $name + * + * @param $email + * @param string $name * @return mixed */ function setReplyTo($email, $name = '') @@ -83,8 +88,9 @@ function setReplyTo($email, $name = '') /** * Given the name of a template and a set of variables to include, generates an HTML body and adds it to the message - * @param $template_name - * @param array $vars + * + * @param $template_name + * @param array $vars * @return mixed */ function setHTMLBodyFromTemplate($template_name, $vars = array(), array $shellVars = []) @@ -98,9 +104,10 @@ function setHTMLBodyFromTemplate($template_name, $vars = array(), array $shellVa /** * Sets the HTML body of the message (optionally setting it inside the email pageshell as defined by the email template) - * @param $body The formatted HTML body text of the message - * @param bool $shell Should the message be placed inside the pageshell? Default: true - * @param array $shellVars Variables to pass to the page shell template + * + * @param $body The formatted HTML body text of the message + * @param bool $shell Should the message be placed inside the pageshell? Default: true + * @param array $shellVars Variables to pass to the page shell template * @return mixed */ function setHTMLBody($body, $shell = true, array $shellVars = []) @@ -118,8 +125,9 @@ function setHTMLBody($body, $shell = true, array $shellVars = []) /** * Set the text only component of an email. - * @param type $template_name - * @param type $vars + * + * @param type $template_name + * @param type $vars * @return mixed */ function setTextBodyFromTemplate($template_name, $vars = array()) @@ -133,7 +141,8 @@ function setTextBodyFromTemplate($template_name, $vars = array()) /** * Sets the plain text body of the message - * @param string $body The body of the message + * + * @param string $body The body of the message * @return mixed */ function setTextBody($body) @@ -143,6 +152,7 @@ function setTextBody($body) /** * Send the message + * * @return int */ function send() diff --git a/Idno/Core/Event.php b/Idno/Core/Event.php index 87e9e57a86..52c17ed0d6 100644 --- a/Idno/Core/Event.php +++ b/Idno/Core/Event.php @@ -3,7 +3,7 @@ /** * Event class to handle data transport during event triggering * - * @package idno + * @package idno * @subpackage core */ @@ -25,6 +25,7 @@ function __construct($data = array()) /** * Retrieve data associated with an event + * * @return mixed */ function &data() @@ -34,6 +35,7 @@ function &data() /** * Retrieve the response variable associated with this event + * * @return type */ function &response() @@ -43,7 +45,8 @@ function &response() /** * Set the response variable associated with this event - * @param $value + * + * @param $value * @return true|false */ function setResponse($value) @@ -54,6 +57,7 @@ function setResponse($value) /** * Retrieve the variable associated with the URL to forward to * (if any) after this event + * * @return type */ function &forward() @@ -69,7 +73,8 @@ function &forward() function __isset($name) { - if (!empty($this->attributes[$name])) return true; + if (!empty($this->attributes[$name])) { return true; + } return false; } diff --git a/Idno/Core/EventDispatcher.php b/Idno/Core/EventDispatcher.php index 8ccd107a54..a39f74a609 100644 --- a/Idno/Core/EventDispatcher.php +++ b/Idno/Core/EventDispatcher.php @@ -3,7 +3,7 @@ /** * Event dispatcher class * - * @package idno + * @package idno * @subpackage core */ @@ -29,9 +29,9 @@ public function __construct() * that specifies order priority; the higher the number, the earlier * in the chain $listener will be notified. * - * @param string $event + * @param string $event * @param callable $listener - * @param int $priority + * @param int $priority */ function addListener($event, $listener, $priority = 0) { @@ -44,9 +44,9 @@ function addListener($event, $listener, $priority = 0) * Shortcut to trigger an event: supply the event name and * (optionally) an array of data, and get a variable back. * - * @param string $eventName The name of the event to trigger - * @param array $data Data to pass to the event - * @param mixed $default Default response (if not forwarding) + * @param string $eventName The name of the event to trigger + * @param array $data Data to pass to the event + * @param mixed $default Default response (if not forwarding) * @return mixed */ function triggerEvent($eventName, $data = array(), $default = true) @@ -69,7 +69,8 @@ function triggerEvent($eventName, $data = array(), $default = true) /** * Low level event dispatcher for an already existing Event - * @param string $eventName + * + * @param string $eventName * @param \Idno\Core\Event $event */ function dispatch(string $eventName, Event $event = null) diff --git a/Idno/Core/EventQueue.php b/Idno/Core/EventQueue.php index f615bdec05..481d71bbbb 100644 --- a/Idno/Core/EventQueue.php +++ b/Idno/Core/EventQueue.php @@ -13,30 +13,34 @@ abstract class EventQueue extends \Idno\Common\Component /** * Enqueue an event for processing. - * @param string $queueName the named queue to put this event on (currently unused) - * @param string $eventName the name of the event, e.g. "webmention/send" - * @param array $eventData the data sent to the event when it is triggered. + * + * @param string $queueName the named queue to put this event on (currently unused) + * @param string $eventName the name of the event, e.g. "webmention/send" + * @param array $eventData the data sent to the event when it is triggered. * @return string an ID that can be used to query the job status */ abstract function enqueue($queueName, $eventName, array $eventData); /** * Check whether a previously enqueued job has completed. - * @param string $jobId the ID of the job returned from enqueue() + * + * @param string $jobId the ID of the job returned from enqueue() * @return boolean */ abstract function isComplete($jobId); /** * Retrieve the result of a completed job by its ID. - * @param string $jobId the ID of the job returned from enqueue() + * + * @param string $jobId the ID of the job returned from enqueue() * @return mixed */ abstract function getResult($jobId); /** * Convert a JSON object to a string, replacing any Entity with its UUID. - * @param array $args + * + * @param array $args * @return string */ function serialize($args) @@ -46,7 +50,8 @@ function serialize($args) /** * Convert a string back to a JSON object, restoring Entities from their UUIDs. - * @param string $str + * + * @param string $str * @return array */ function deserialize($str) diff --git a/Idno/Core/Geocoder.php b/Idno/Core/Geocoder.php index 8b2096e56d..01df2d981f 100644 --- a/Idno/Core/Geocoder.php +++ b/Idno/Core/Geocoder.php @@ -3,7 +3,7 @@ /** * Geocoding tools. * - * @package idno + * @package idno * @subpackage core */ @@ -22,6 +22,7 @@ public function __construct() /** * Get the endpoint for the geocoder. + * * @return string */ protected function getEndpoint() @@ -33,8 +34,8 @@ protected function getEndpoint() * Given a latitude and longitude, reverse geocode it into a structure including name, address, * city, etc * - * @param $latitude - * @param $longitude + * @param $latitude + * @param $longitude * @return bool|mixed */ function queryLatLong($latitude, $longitude) @@ -66,7 +67,7 @@ function queryLatLong($latitude, $longitude) /** * Takes an address and returns OpenStreetMap data via Nominatim, including latitude and longitude * - * @param string $address + * @param string $address * @return array|bool */ function queryAddress($address) diff --git a/Idno/Core/GetTextTranslation.php b/Idno/Core/GetTextTranslation.php index 26036e6628..c76eee777f 100644 --- a/Idno/Core/GetTextTranslation.php +++ b/Idno/Core/GetTextTranslation.php @@ -13,13 +13,14 @@ class GetTextTranslation extends Translation /** * Create a GetText translation. - * @param type $domain 'known' for core, 'mypluginname' for plugins - * @param type $path Full path to where to find the translations. + * + * @param type $domain 'known' for core, 'mypluginname' for plugins + * @param type $path Full path to where to find the translations. * @throws \RuntimeException */ public function __construct( - $domain = 'known', - $path = '' + $domain = 'known', + $path = '' ) { if (!extension_loaded('gettext')) { diff --git a/Idno/Core/HelperRobot.php b/Idno/Core/HelperRobot.php index 52cd78a01a..36085cfb68 100644 --- a/Idno/Core/HelperRobot.php +++ b/Idno/Core/HelperRobot.php @@ -17,45 +17,48 @@ function registerPages() function registerEventHooks() { - \Idno\Core\Idno::site()->events()->addListener('saved', function (\Idno\Core\Event $event) { - - $eventdata = $event->data(); - if ($object = $eventdata['object']) { - if (site()->session()->isLoggedOn()) { - if (!($object instanceof User)) { - if (!empty(site()->session()->currentUser()->robot_state)) { - $user = site()->session()->currentUser(); - switch ($user->robot_state) { - - case '1': - if (class_exists('IdnoPlugins\Status') && $object instanceof \IdnoPlugins\Status) { - $user->robot_state = '2a'; - } else { - $user->robot_state = '2b'; - } - self::$changed_state = 1; - break; - case '2a': - if (class_exists('IdnoPlugins\Photo') && $object instanceof \IdnoPlugins\Photo) { - $user->robot_state = '3a'; - } - self::$changed_state = 1; - break; - case '2b': - $user->robot_state = '3b'; - self::$changed_state = 1; - break; + \Idno\Core\Idno::site()->events()->addListener( + 'saved', function (\Idno\Core\Event $event) { + + $eventdata = $event->data(); + if ($object = $eventdata['object']) { + if (site()->session()->isLoggedOn()) { + if (!($object instanceof User)) { + if (!empty(site()->session()->currentUser()->robot_state)) { + $user = site()->session()->currentUser(); + switch ($user->robot_state) { + + case '1': + if (class_exists('IdnoPlugins\Status') && $object instanceof \IdnoPlugins\Status) { + $user->robot_state = '2a'; + } else { + $user->robot_state = '2b'; + } + self::$changed_state = 1; + break; + + case '2a': + if (class_exists('IdnoPlugins\Photo') && $object instanceof \IdnoPlugins\Photo) { + $user->robot_state = '3a'; + } + self::$changed_state = 1; + break; + + case '2b': + $user->robot_state = '3b'; + self::$changed_state = 1; + break; + } + $user->save(); + site()->session()->refreshSessionUser($user); } - $user->save(); - site()->session()->refreshSessionUser($user); - } } } - } - }); + } + ); } diff --git a/Idno/Core/Hub.php b/Idno/Core/Hub.php index de02d6feb4..db3436d577 100644 --- a/Idno/Core/Hub.php +++ b/Idno/Core/Hub.php @@ -3,7 +3,6 @@ /** * Hubs are central, or semi-central servers, that provide functionality for groups of Known users. * Functionality may include managed cron jobs, feed parsing, social syndication, discovery, and more. - * */ namespace Idno\Core { @@ -27,6 +26,7 @@ function __construct($server) /** * Sets the hub server to connect to + * * @param $server */ function setServer($server) @@ -44,18 +44,20 @@ function registerPages() function registerEventHooks() { // Register user on login - \Idno\Core\Idno::site()->events()->addListener('login/success', function (\Idno\Core\Event $event) { - $eventdata = $event->data(); - if ($user = $eventdata['user']) { - $this->registerUser($user); + \Idno\Core\Idno::site()->events()->addListener( + 'login/success', function (\Idno\Core\Event $event) { + $eventdata = $event->data(); + if ($user = $eventdata['user']) { + $this->registerUser($user); + } } - }); + ); } /** * Register the current user with the Known hub. The site must have been registered first. * - * @param bool $user + * @param bool $user * @return bool */ function registerUser($user = false) @@ -68,12 +70,14 @@ function registerUser($user = false) $contents = json_encode($user); $time = time(); $details = $this->loadDetails(); - $results = Webservice::post($this->server . 'hub/user/register', array( + $results = Webservice::post( + $this->server . 'hub/user/register', array( 'content' => $contents, 'time' => $time, 'auth_token' => $details['auth_token'], 'signature' => hash_hmac('sha1', $contents . $time . $details['auth_token'], $details['secret']) - )); + ) + ); if ($results['response'] == 401) { \Idno\Core\Idno::site()->config()->hub_settings = array(); @@ -94,6 +98,7 @@ function registerUser($user = false) /** * Load the locally stored auth token & secret details, or register with the hub if no details have been * saved + * * @return bool */ function loadDetails() @@ -110,6 +115,7 @@ function loadDetails() /** * Sets the public auth token to use to communicate with the hub server + * * @param $token */ function setAuthToken($token) @@ -119,6 +125,7 @@ function setAuthToken($token) /** * Sets the secret auth token to use to communicate with the hub server + * * @param $secret */ function setSecret($secret) @@ -137,10 +144,9 @@ function connect() $details = $this->loadDetails(); if (!empty($details['auth_token'])) { // Apply pre-stored auth details and connect to server - } else if ( - !substr_count($_SERVER['REQUEST_URI'], 'callback') && - !substr_count($_SERVER['REQUEST_URI'], '.') && - !substr_count($_SERVER['REQUEST_URI'], '/file/') + } else if (!substr_count($_SERVER['REQUEST_URI'], 'callback') + && !substr_count($_SERVER['REQUEST_URI'], '.') + && !substr_count($_SERVER['REQUEST_URI'], '/file/') ) { // Establish auth details, save them, and then connect if ($details = $this->register()) { @@ -180,11 +186,13 @@ function register() if ($last_ping < (time() - 10)) { // Throttling registration pings to hub - $results = Webservice::post($this->server . 'hub/site/register', array( + $results = Webservice::post( + $this->server . 'hub/site/register', array( 'url' => \Idno\Core\Idno::site()->config()->getURL(), 'title' => \Idno\Core\Idno::site()->config()->getTitle(), 'token' => $this->getRegistrationToken() - )); + ) + ); if ($results['response'] == 200) { \Idno\Core\Idno::site()->config()->load(); @@ -201,6 +209,7 @@ function register() /** * Retrieves a token for use in registering this Known site with a hub. Tokens last for 10 minutes. + * * @return string */ function getRegistrationToken() @@ -233,7 +242,8 @@ function getRegistrationToken() /** * Detect whether the current user has registered with the hub & stored credentials - * @param bool $user + * + * @param bool $user * @return bool */ function userIsRegistered($user = false) @@ -256,9 +266,9 @@ function userIsRegistered($user = false) /** * Makes a call to the hub * - * @param $endpoint - * @param $contents - * @param bool $user + * @param $endpoint + * @param $contents + * @param bool $user * @return array|bool */ function makeCall($endpoint, $contents, $user = false) @@ -273,12 +283,14 @@ function makeCall($endpoint, $contents, $user = false) $contents = json_encode($contents); $time = time(); $details = $user->hub_settings; - $results = Webservice::post($this->server . $endpoint, array( + $results = Webservice::post( + $this->server . $endpoint, array( 'content' => $contents, 'time' => $time, 'auth_token' => $details['token'], 'signature' => hash_hmac('sha1', $contents . $time . $details['token'], $details['secret']) - )); + ) + ); return $results; } @@ -291,8 +303,8 @@ function makeCall($endpoint, $contents, $user = false) /** * Retrieves a link that will allow the current user to log into the hub page at $endpoint * - * @param $endpoint - * @param $callback + * @param $endpoint + * @param $callback * @return bool|string */ function getRemoteLink($endpoint, $callback) @@ -316,6 +328,7 @@ function getRemoteLink($endpoint, $callback) /** * Save hub auth + * * @param $token * @param $secret */ diff --git a/Idno/Core/HybridTwigTemplate.php b/Idno/Core/HybridTwigTemplate.php index 725ed87162..bee0841922 100644 --- a/Idno/Core/HybridTwigTemplate.php +++ b/Idno/Core/HybridTwigTemplate.php @@ -3,62 +3,67 @@ /** * Hybrid twig template management class * - * @package idno + * @package idno * @subpackage core */ namespace Idno\Core { - + use Twig\Loader\FilesystemLoader; use Twig\Environment; - + /** * Hybrid twig template management class. - * + * * This class extends the Known template to, in addition to supporting the Known php based templates, to support * the more standard twig templates. */ - class HybridTwigTemplate extends DefaultTemplate { - + class HybridTwigTemplate extends DefaultTemplate + { + private $twig; - + private $loader; - - public function __construct($template = false) { - + + public function __construct($template = false) + { + // Create cache $cache = \Idno\Core\Idno::site()->config()->getUploadPath() . 'twig/'; @mkdir($cache); - + // Set up twig environment $this->loader = new FilesystemLoader(\Idno\Core\Bonita\Main::getPaths()); - $this->twig = new Environment($this->loader, [ + $this->twig = new Environment( + $this->loader, [ 'cache' => $cache - ]); - + ] + ); + // Update with the parent return parent::__construct($template); } - + /** * Extension-aware version of the template drawing function * - * @param string $templateName - * @param bool $returnBlank Should we return a blank string if the template doesn't exist? (Defaults to true) - * @param book $replacements Should we honor template replacements? (Defaults to true) + * @param string $templateName + * @param bool $returnBlank Should we return a blank string if the template doesn't exist? (Defaults to true) + * @param book $replacements Should we honor template replacements? (Defaults to true) * @return false|string */ function draw($templateName, $returnBlank = true, $replacements = true) { $this->loader->setPaths(\Idno\Core\Bonita\Main::getPaths()); - + // Add template types to an array; ensure we revert to default $templateTypes = array($this->getTemplateType()); if ($this->fallbackToDefault) { - if ($this->getTemplateType() != 'default') + if ($this->getTemplateType() != 'default') { $templateTypes[] = 'default'; + } } - + $result = ''; if (!empty($this->prepends[$templateName])) { foreach ($this->prepends[$templateName] as $template) { @@ -70,7 +75,7 @@ function draw($templateName, $returnBlank = true, $replacements = true) // Ignore loading errors here } } - + } } $replaced = false; @@ -108,21 +113,21 @@ function draw($templateName, $returnBlank = true, $replacements = true) //$result .= $this->twig->render("templates/{$type}/{$templateName}.html.twig", $this->vars); $result .= $this->twig->render("templates/{$type}/{$templateName}.html.twig", $this->vars); break; - } catch (\Exception $e) { + } catch (\Exception $e) { // Ignore loading errors here - + } } } - + // We have a twig template, return it - if (!empty($result)) { + if (!empty($result)) { return $result; } - + // No twig template, look for a bonita template return parent::draw($templateName, $returnBlank, $replacements); } } - + } \ No newline at end of file diff --git a/Idno/Core/Idno.php b/Idno/Core/Idno.php index 61f3310415..b2f0bba961 100644 --- a/Idno/Core/Idno.php +++ b/Idno/Core/Idno.php @@ -3,7 +3,7 @@ /** * Base Idno class * - * @package idno + * @package idno * @subpackage core */ @@ -126,25 +126,33 @@ function init() // Log some page statistics \Idno\Stats\Timer::start('script'); - register_shutdown_function(function () { - $stats = \Idno\Core\Idno::site()->statistics(); - if (!empty($stats)) { - $stats->timing('timer.script', \Idno\Stats\Timer::value('script')); + register_shutdown_function( + function () { + $stats = \Idno\Core\Idno::site()->statistics(); + if (!empty($stats)) { + $stats->timing('timer.script', \Idno\Stats\Timer::value('script')); + } } - }); + ); // Attempt to create a cache object, making use of support present on the system $cache_default = "Idno\\Caching\\FilesystemCache"; - if (extension_loaded('apc') && ini_get('apc.enabled')) + if (extension_loaded('apc') && ini_get('apc.enabled')) { $cache_default = "Idno\\Caching\\APCuCache"; + } $this->cache = $this->componentFactory($this->config->cache, "Idno\\Caching\\Cache", "Idno\\Caching\\", $cache_default); // No URL is a critical error, default base fallback is now a warning (Refs #526) if (!defined('KNOWN_CONSOLE')) { - if (!$this->config->url) throw new \Idno\Exceptions\ConfigurationException('Known was unable to work out your base URL! You might try setting url="http://yourdomain.com/" in your config.ini'); - if ($this->config->url == '/') $this->logging->warning('Base URL has defaulted to "/" because Known was unable to detect your server name. ' - . 'This may be because you\'re loading Known via a script. ' - . 'Try setting url="http://yourdomain.com/" in your config.ini to remove this message'); + if (!$this->config->url) { throw new \Idno\Exceptions\ConfigurationException('Known was unable to work out your base URL! You might try setting url="http://yourdomain.com/" in your config.ini'); + } + if ($this->config->url == '/') { + $this->logging->warning( + 'Base URL has defaulted to "/" because Known was unable to detect your server name. ' + . 'This may be because you\'re loading Known via a script. ' + . 'Try setting url="http://yourdomain.com/" in your config.ini to remove this message' + ); + } } // Connect to a Known hub if one is listed in the configuration file @@ -152,10 +160,9 @@ function init() if (empty(site()->session()->hub_connect)) { site()->session()->hub_connect = 0; } - if ( - !empty($this->config->known_hub) && - !substr_count($_SERVER['REQUEST_URI'], '.') && - $this->config->known_hub != $this->config->url + if (!empty($this->config->known_hub) + && !substr_count($_SERVER['REQUEST_URI'], '.') + && $this->config->known_hub != $this->config->url ) { site()->session()->hub_connect = time(); \Idno\Core\Idno::site()->known_hub = new \Idno\Core\Hub($this->config->known_hub); @@ -172,14 +179,18 @@ function registerPages() { $permalink_route = \Idno\Common\Entity::getPermalinkRoute(); - /** Homepage */ + /** + * Homepage + */ $this->routes()->addRoute('/?', '\Idno\Pages\Homepage'); $this->routes()->addRoute('/feed\.xml', '\Idno\Pages\Feed'); $this->routes()->addRoute('/feed/?', '\Idno\Pages\Feed'); $this->routes()->addRoute('/rss\.xml', '\Idno\Pages\Feed'); $this->routes()->addRoute('/content/([A-Za-z\-\/]+)+', '\Idno\Pages\Homepage'); - /** Individual entities / posting / deletion */ + /** + * Individual entities / posting / deletion + */ $this->routes()->addRoute('/view/:id/?', '\Idno\Pages\Entity\View'); $this->routes()->addRoute('/s/:id/?', '\Idno\Pages\Entity\Shortlink'); $this->routes()->addRoute($permalink_route . '/?', '\Idno\Pages\Entity\View'); @@ -189,48 +200,68 @@ function registerPages() $this->routes()->addRoute('/attachment/:id/:id/?', '\Idno\Pages\Entity\Attachment\Delete'); - /** Annotations */ + /** + * Annotations + */ $this->routes()->addRoute('/view/:id/annotations/:id?', '\Idno\Pages\Annotation\View'); $this->routes()->addRoute($permalink_route . '/annotations/:id?', '\Idno\Pages\Annotation\View'); $this->routes()->addRoute($permalink_route . '/annotations/:id/delete/?', '\Idno\Pages\Annotation\Delete'); // Delete annotation $this->routes()->addRoute($permalink_route .'/annotation/delete/?', '\Idno\Pages\Annotation\Delete'); // Delete annotation alternate $this->routes()->addRoute('/annotation/post/?', '\Idno\Pages\Annotation\Post'); - /** Bookmarklets and sharing */ + /** + * Bookmarklets and sharing + */ $this->routes()->addRoute('/share/?', '\Idno\Pages\Entity\Share'); $this->routes()->addRoute('/bookmarklet\.js', '\Idno\Pages\Entity\Bookmarklet', true); - /** Mobile integrations */ + /** + * Mobile integrations + */ $this->routes()->addRoute('/chrome/manifest\.json', '\Idno\Pages\Chrome\Manifest', true); - /** Service worker */ + /** + * Service worker + */ $this->routes()->addRoute('/service-worker(\.min)?\.js', '\Idno\Pages\Chrome\ServiceWorker', true); - /** Files */ + /** + * Files + */ $this->routes()->addRoute('/file/mint/?', \Idno\Pages\File\Mint::class); $this->routes()->addRoute('/file/upload/?', '\Idno\Pages\File\Upload', true); $this->routes()->addRoute('/file/picker/?', '\Idno\Pages\File\Picker', true); $this->routes()->addRoute('/filepicker/?', '\Idno\Pages\File\Picker', true); $this->routes()->addRoute('/file/(:id)(/.*)?', '\Idno\Pages\File\View', true); - /** Users */ + /** + * Users + */ $this->routes()->addRoute('/profile/([^\/]+)/?', '\Idno\Pages\User\View'); $this->routes()->addRoute('/profile/([^\/]+)/edit/?', '\Idno\Pages\User\Edit'); $this->routes()->addRoute('/profile/([^\/]+)/([A-Za-z\-\/]+)+', '\Idno\Pages\User\View'); - /** Search */ + /** + * Search + */ $this->routes()->addRoute('/search/?', '\Idno\Pages\Search\Forward'); $this->routes()->addRoute('/search/mentions\.json', '\Idno\Pages\Search\Mentions'); $this->routes()->addRoute('/tag/([^\s]+)\/?', '\Idno\Pages\Search\Tags'); $this->routes()->addRoute('/search/users/?', '\Idno\Pages\Search\User'); - /** robots.txt */ + /** + * robots.txt + */ $this->routes()->addRoute('/robots\.txt', '\Idno\Pages\Txt\Robots'); - /** Autosave / preview */ + /** + * Autosave / preview + */ $this->routes()->addRoute('/autosave/?', '\Idno\Pages\Entity\Autosave'); - /** Installation / first use */ + /** + * Installation / first use + */ $this->routes()->addRoute('/begin/?', '\Idno\Pages\Onboarding\Begin', true); $this->routes()->addRoute('/begin/register/?', '\Idno\Pages\Onboarding\Register', true); $this->routes()->addRoute('/begin/profile/?', '\Idno\Pages\Onboarding\Profile'); @@ -238,7 +269,9 @@ function registerPages() $this->routes()->addRoute('/begin/connect\-forwarder/?', '\Idno\Pages\Onboarding\ConnectForwarder'); $this->routes()->addRoute('/begin/publish/?', '\Idno\Pages\Onboarding\Publish'); - /** Add some services */ + /** + * Add some services + */ $this->routes()->addRoute('/service/db/optimise/?', '\Idno\Pages\Service\Db\Optimise'); $this->routes()->addRoute('/service/vendor/messages/?', '\Idno\Pages\Service\Vendor\Messages'); $this->routes()->addRoute('/service/security/csrftoken/?', '\Idno\Pages\Service\Security\CSRFToken'); @@ -253,11 +286,11 @@ function registerPages() // These must be loaded last $this->plugins = new Plugins(); $this->themes = new Themes(); - } /** * Return the database layer loaded as part of this site + * * @return \Idno\Core\DataConcierge */ function &db() : ?DataConcierge @@ -267,6 +300,7 @@ function &db() : ?DataConcierge /** * Return the event dispatcher loaded as part of this site + * * @return \Idno\Core\EventDispatcher */ function &events() : ?EventDispatcher @@ -277,6 +311,7 @@ function &events() : ?EventDispatcher /** * Access to the EventQueue for dispatching events * asynchronously + * * @return \Idno\Core\EventQueue */ function &queue() : ?EventQueue @@ -286,6 +321,7 @@ function &queue() : ?EventQueue /** * Returns the current filesystem + * * @return \Idno\Files\FileSystem */ function &filesystem() : ? \Idno\Files\FileSystem @@ -295,6 +331,7 @@ function &filesystem() : ? \Idno\Files\FileSystem /** * Returns the current Known hub + * * @return \Idno\Core\Hub */ function &hub() : ?Hub @@ -304,6 +341,7 @@ function &hub() : ?Hub /** * Returns the current logging interface + * * @return \Idno\Core\Logging */ function &logging() : ?Logging @@ -313,6 +351,7 @@ function &logging() : ?Logging /** * Return a persistent cache object. + * * @return \Idno\Caching\PersistentCache */ function &cache() : ?\Idno\Caching\PersistentCache @@ -322,6 +361,7 @@ function &cache() : ?\Idno\Caching\PersistentCache /** * Return a statistics collector + * * @return \Idno\Stats\StatisticsCollector */ function &statistics() : ?\Idno\Stats\StatisticsCollector @@ -331,6 +371,7 @@ function &statistics() : ?\Idno\Stats\StatisticsCollector /** * Return page handlers + * * @return \Idno\Core\PageHandler */ function &routes() : ?PageHandler @@ -348,14 +389,16 @@ function &routes() : ?PageHandler */ function &config($setting = false) { - if ($setting === false) + if ($setting === false) { return $this->config; - else + } else { return $this->config->$setting; + } } /** * Helper function that returns the current syndication object for this site + * * @return \Idno\Core\Syndication */ function &syndication() : ?Syndication @@ -365,9 +408,9 @@ function &syndication() : ?Syndication /** * Return the session handler associated with this site + * * @return \Idno\Core\Session */ - function &session() : ?Session { return $this->session; @@ -375,6 +418,7 @@ function &session() : ?Session /** * Return the plugin handler associated with this site + * * @return \Idno\Core\Plugins */ function &plugins() : ?Plugins @@ -384,6 +428,7 @@ function &plugins() : ?Plugins /** * Return the theme handler associated with this site + * * @return \Idno\Core\Themes */ function &themes() : ?Themes @@ -393,6 +438,7 @@ function &themes() : ?Themes /** * Return the template handler associated with this site + * * @return \Idno\Core\Template */ @@ -403,6 +449,7 @@ function &template() : ?Template /** * Return the language handler associated with this site + * * @return \Idno\Core\Language */ function &language() : ?Language @@ -416,6 +463,7 @@ function &language() : ?Language /** * Return the action helper associated with this site + * * @return \Idno\Core\Actions */ function &actions() : ?Actions @@ -425,6 +473,7 @@ function &actions() : ?Actions /** * Return the reader associated with this site + * * @return \Idno\Core\Reader */ function &reader() : ?Reader @@ -463,6 +512,7 @@ function &site_details() : ? Site /** * Sets the current page (if any) for access throughout the system + * * @param \Idno\Common\Page $page */ function setCurrentPage(\Idno\Common\Page $page) @@ -472,6 +522,7 @@ function setCurrentPage(\Idno\Common\Page $page) /** * Retrieve the current page + * * @return bool|\Idno\Common\Page */ function currentPage() @@ -490,14 +541,13 @@ function currentPage() * * This essentially means 'can the user edit configuration about the site', generally only admins can do this. * - * @param string $user_id + * @param string $user_id * @return true|false */ - function canEdit($user_id = '') { - - if (!\Idno\Core\Idno::site()->session()->isLoggedOn()) return false; + if (!\Idno\Core\Idno::site()->session()->isLoggedOn()) { return false; + } if (empty($user_id)) { $user_id = \Idno\Core\Idno::site()->session()->currentUserUUID(); @@ -505,18 +555,20 @@ function canEdit($user_id = '') if ($user = \Idno\Entities\User::getByUUID($user_id)) { - return \Idno\Core\Idno::site()->events()->triggerEvent('canEdit/site', [ + return \Idno\Core\Idno::site()->events()->triggerEvent( + 'canEdit/site', [ 'object' => $this, 'user_id' => $user_id, 'user' => $user - ], (function () use ($user) { + ], (function () use ($user) { - if ($user->isAdmin()) { - return true; - } + if ($user->isAdmin()) { + return true; + } - return false; - })()); + return false; + })() + ); } @@ -528,13 +580,13 @@ function canEdit($user_id = '') * or the currently logged-in user if this is left blank) publish * content on the site? * - * @param string $user_id + * @param string $user_id * @return true|false */ - function canWrite($user_id = '') { - if (!\Idno\Core\Idno::site()->session()->isLoggedOn()) return false; + if (!\Idno\Core\Idno::site()->session()->isLoggedOn()) { return false; + } if (empty($user_id)) { $user_id = \Idno\Core\Idno::site()->session()->currentUserUUID(); @@ -543,27 +595,29 @@ function canWrite($user_id = '') if ($user = \Idno\Entities\User::getByUUID($user_id)) { // Make site level canWrite extensible - return \Idno\Core\Idno::site()->events()->triggerEvent('canWrite/site', [ + return \Idno\Core\Idno::site()->events()->triggerEvent( + 'canWrite/site', [ 'object' => $this, 'user_id' => $user_id, 'user' => $user - ], (function () use ($user) { + ], (function () use ($user) { - // Remote users can't ever create anything :( - for now - if ($user instanceof \Idno\Entities\RemoteUser) { - return false; - } + // Remote users can't ever create anything :( - for now + if ($user instanceof \Idno\Entities\RemoteUser) { + return false; + } - // But local users can - if ($user instanceof \Idno\Entities\User) { - if (empty($user->read_only)) { - return true; + // But local users can + if ($user instanceof \Idno\Entities\User) { + if (empty($user->read_only)) { + return true; + } } - } - return false; + return false; - })()); + })() + ); } return false; @@ -577,10 +631,9 @@ function canWrite($user_id = '') * Always returns true at the moment, but might be a good way to build * walled garden functionality. * - * @param string $user_id + * @param string $user_id * @return true|false */ - function canRead($user_id = '') { return true; @@ -629,6 +682,7 @@ function getSiteIcons() : array /** * Is this site being run in embedded mode? Hides the navigation bar, maybe more. + * * @return bool */ function embedded() @@ -655,7 +709,6 @@ function embedded() */ function upgrade() { - $last_update = 0; if (!empty($this->config()->update_version)) { $last_update = $this->config()->update_version; @@ -664,10 +717,13 @@ function upgrade() if ($last_update < $machine_version) { - if ($this->events()->triggerEvent('upgrade', [ + if ($this->events()->triggerEvent( + 'upgrade', [ 'last_update' => $last_update, 'new_version' => $machine_version - ])) { + ] + ) + ) { // Save updated $this->config()->update_version = $machine_version; @@ -682,6 +738,7 @@ function upgrade() /** * This is a state dependant object, and so can not be serialised. + * * @return array */ function __sleep() @@ -691,6 +748,7 @@ function __sleep() /** * Helper method that returns the current site object + * * @return \Idno\Core\Idno $site */ static function &site() : ?Idno @@ -701,10 +759,11 @@ static function &site() : ?Idno /** * Attempt to construct a component. * This allows for config configurable, and plugin extensible, system conponents, without the need for a lot of repeat typing. - * @param string $className Class name of component, either partial or full namespace - * @param string $expectedBaseClass Class type to verify newly created component against + * + * @param string $className Class name of component, either partial or full namespace + * @param string $expectedBaseClass Class type to verify newly created component against * @param string $defaultClassNameBase If a full namespace is not provided in $configValue, use this value as base class namespace - * @param string $defaultClass If class could not be constructed, return a new instance of this class name + * @param string $defaultClass If class could not be constructed, return a new instance of this class name */ public function componentFactory($className, $expectedBaseClass = "Idno\\Common\\Component" , $defaultClassNameBase = "Idno\\Core\\", $defaultClass = null) { @@ -737,14 +796,16 @@ public function componentFactory($className, $expectedBaseClass = "Idno\\Common\ if (!empty($defaultClass)) { - if (is_string($defaultClass)) + if (is_string($defaultClass)) { $component = new $defaultClass(); - else + } else { $component = $defaultClass; + } // validate - if (!is_subclass_of($component, $expectedBaseClass)) + if (!is_subclass_of($component, $expectedBaseClass)) { $component = null; + } } } @@ -753,6 +814,7 @@ public function componentFactory($className, $expectedBaseClass = "Idno\\Common\ /** * Get the current version + * * @return boolean|string */ public function getVersion() @@ -763,12 +825,12 @@ public function getVersion() /** * Helper function that returns the current site object + * * @deprecated Use \Idno\Core\Idno::site() - * @return \Idno\Core\Idno $site + * @return \Idno\Core\Idno $site */ function &site() : Idno { return \Idno\Core\Idno::site(); } - } diff --git a/Idno/Core/Input.php b/Idno/Core/Input.php index 83541ad677..f1ed34c5e7 100644 --- a/Idno/Core/Input.php +++ b/Idno/Core/Input.php @@ -3,7 +3,7 @@ /** * Input handling methods * - * @package idno + * @package idno * @subpackage core */ @@ -15,11 +15,11 @@ class Input extends \Idno\Common\Component /** * Retrieves input from $_REQUEST, and performs optional filtering. * - * @param string $name Name of the input variable - * @param mixed $default A default return value if no value specified (default: null) - * @param boolean $filter Whether or not to filter the variable for safety (default: null), you can pass - * a callable method, function or enclosure with a definition like function($name, $value), which - * will return the filtered result. + * @param string $name Name of the input variable + * @param mixed $default A default return value if no value specified (default: null) + * @param boolean $filter Whether or not to filter the variable for safety (default: null), you can pass + * a callable method, function or enclosure with a definition like + * function($name, $value), which will return the filtered result. * @return mixed */ public static function getInput($name, $default = null, callable $filter = null) @@ -29,8 +29,9 @@ public static function getInput($name, $default = null, callable $filter = null) if (isset($_REQUEST[$name])) { $value = $_REQUEST[$name]; } - if (($value===null) && ($default!==null)) + if (($value===null) && ($default!==null)) { $value = $default; + } if (!$value!==null) { if (isset($filter) && is_callable($filter)) { $value = call_user_func($filter, $name, $value); @@ -49,14 +50,16 @@ public static function getInput($name, $default = null, callable $filter = null) * Retrieve files from input. * Retrieve a formatted files array from input, if multiple files are found, this will be turned into * a sensible structure. + * * @param type $name */ public static function getFiles($name) { $files = $_FILES[$name]; - if (!is_array($files['name'])) + if (!is_array($files['name'])) { return $files; // Short circuit if there's only one entry for a name + } // Normalize file array, // HT: https://gist.github.com/umidjons/9893735 @@ -64,9 +67,11 @@ public static function getFiles($name) $_files_count = count($files['name']); $_files_keys = array_keys($files); - for ($i = 0; $i < $_files_count; $i++) - foreach ($_files_keys as $key) + for ($i = 0; $i < $_files_count; $i++) { + foreach ($_files_keys as $key) { $_files[$i][$key] = $files[$key][$i]; + } + } return $_files; } diff --git a/Idno/Core/Installer.php b/Idno/Core/Installer.php index a6d11e4f99..0076759b69 100644 --- a/Idno/Core/Installer.php +++ b/Idno/Core/Installer.php @@ -44,6 +44,7 @@ abstract public function run(); /** * When given a file, create a backup of it. + * * @param type $file */ protected function backupFile($file) @@ -67,7 +68,8 @@ protected function backupFile($file) /** * Check that the upload directory exists and is readable and writable - * @param type $upload_path + * + * @param type $upload_path * @return boolean * @throws \RuntimeException */ @@ -149,8 +151,9 @@ protected function writeApacheConfig() /** * Write out the configuration - * @param type $ini_file - * @param type $name + * + * @param type $ini_file + * @param type $name * @throws \RuntimeException */ protected function writeConfig($ini_file, $name = 'config.ini') @@ -171,7 +174,8 @@ protected function writeConfig($ini_file, $name = 'config.ini') /** * Generate a configuration file from a template. - * @param array $params Name => Value array of configuration values, e.g. "dbname" => "known" + * + * @param array $params Name => Value array of configuration values, e.g. "dbname" => "known" * @return string The built ini file */ protected function buildConfig(array $params = []) @@ -196,8 +200,9 @@ protected function buildConfig(array $params = []) // Load template $template = file_get_contents($this->root_path . '/warmup/webserver-configs/config.ini.template'); - if (empty($template)) + if (empty($template)) { throw new \Idno\Exceptions\ConfigurationException('Configuration template could not be loaded.'); + } // Build config output foreach ($params as $name => $value) { @@ -209,20 +214,21 @@ protected function buildConfig(array $params = []) /** * Install the mysql DB schema - * @param type $host - * @param type $dbname - * @param type $user - * @param type $pass - * @param type $schema + * + * @param type $host + * @param type $dbname + * @param type $user + * @param type $pass + * @param type $schema * @return boolean * @throws \RuntimeException */ protected function installSchema( - $host, - $dbname, - $user, - $pass, - $schema = 'mysql' + $host, + $dbname, + $user, + $pass, + $schema = 'mysql' ) { @@ -230,8 +236,9 @@ protected function installSchema( $schema = preg_replace("/[^a-zA-Z0-9\_\.]/", "", strtolower($schema)); // Sanitise $schema // Skip schema install for mongo, not necessary - if ($schema == 'mongo' || $schema == 'mongodb') + if ($schema == 'mongo' || $schema == 'mongodb') { return true; + } // Crufty hack to alias schemas if they're different from class. TODO: do this nicer $dbscheme = ""; diff --git a/Idno/Core/Language.php b/Idno/Core/Language.php index 2fce173959..9ee7b7d084 100644 --- a/Idno/Core/Language.php +++ b/Idno/Core/Language.php @@ -9,18 +9,21 @@ class Language extends Component /** * Language associated array of translation objects. + * * @var type */ private $translations = []; /** * Current language + * * @var type */ private $language; /** * Construct a language object + * * @param type $language */ public function __construct($language = null) @@ -28,16 +31,19 @@ public function __construct($language = null) $session = \Idno\Core\Idno::site()->session(); if (!empty($session)) { if ($user = \Idno\Core\Idno::site()->session()->currentUser()) { - if (!empty($user->language)) + if (!empty($user->language)) { return $user->language; + } } } - if (empty($language)) + if (empty($language)) { $language = self::detectBrowserLanguage(); + } - if (empty($language)) + if (empty($language)) { $language = 'en_US'; + } $this->language = $language; @@ -60,8 +66,9 @@ function __get($string) /** * Return a translated string, substituting variables in subs in the format of sprintf. - * @param type $string String to translate - * @param array $subs List of substitution variables to be used in the translated string + * + * @param type $string String to translate + * @param array $subs List of substitution variables to be used in the translated string * @return string */ public function _($string, array $subs = []) @@ -71,8 +78,9 @@ public function _($string, array $subs = []) /** * Return an ESCAPED translated string, substituting variables in subs in the format of sprintf. - * @param type $string String to translate - * @param array $subs List of substitution variables to be used in the translated string + * + * @param type $string String to translate + * @param array $subs List of substitution variables to be used in the translated string * @return string */ public function esc_($string, array $subs = []) @@ -84,6 +92,7 @@ public function esc_($string, array $subs = []) * Register a translation. * Register translation strings. It is safe to provide Translation objects for multiple languages, only translations for * $this->getLanguage() will be loaded. + * * @param \Idno\Core\Translation $translation */ public function register(Translation $translation) @@ -96,8 +105,9 @@ public function register(Translation $translation) /** * Shortcut for getTranslation. - * @param $string - * @param bool|true $failover + * + * @param $string + * @param bool|true $failover * @return bool|string */ function get($string, $failover = true) @@ -108,8 +118,9 @@ function get($string, $failover = true) /** * Retrieves a translation for a given string. If $failover is true (as set by default), the function will * return the original string if no translation exists. Otherwise it will return false. - * @param $string - * @param bool|true $failover + * + * @param $string + * @param bool|true $failover * @return string|bool */ function getTranslation($string, $failover = true) @@ -118,16 +129,19 @@ function getTranslation($string, $failover = true) // Look through translation objects foreach ($this->translations as $translation) { $value = $translation->getString($string); - if (!empty($value) && ($value != $string)) + if (!empty($value) && ($value != $string)) { return $value; + } } // If we're in lang_debug mode, lets flag untranslated strings if (!empty(\Idno\Core\Idno::site()->config()->lang_debug)) { - \Idno\Core\Idno::site()->events()->triggerEvent('language/translation/missing-string', [ + \Idno\Core\Idno::site()->events()->triggerEvent( + 'language/translation/missing-string', [ 'string' => $string, 'language' => $this->language - ]); + ] + ); } if ($failover) { @@ -147,7 +161,8 @@ public function getLanguage() /** * Replace curly quotes with uncurly quotes - * @param $string + * + * @param $string * @return mixed */ function uncurlQuotes($string) @@ -188,18 +203,20 @@ function uncurlQuotes($string) * Detect current language from browser string. * * TODO: Put more logic here, with better fallbacks. + * * @param bool $full if true, the full locale is returned, e.g. en_GB */ public static function detectBrowserLanguage($full = true) { $length = 2; // Short form - + $lang = ""; if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { - if ($full) + if ($full) { $length = strpos($_SERVER['HTTP_ACCEPT_LANGUAGE'], ','); + } $lang = preg_replace("/[^a-zA-Z\-_\s]/", "", substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, $length)); $lang = str_replace('-', '_', $lang); @@ -209,13 +226,15 @@ public static function detectBrowserLanguage($full = true) if (defined('KNOWN_CONSOLE')) { $lang = getenv('LANGUAGE'); - if (empty($lang)) + if (empty($lang)) { $lang = getenv('LANG'); + } if (preg_match('/[a-z]{2}_[A-Z]{2}/', $lang, $matches)) { $lang = $matches[0]; - if (!$full) + if (!$full) { $lang = explode('_', $lang)[0]; + } } } diff --git a/Idno/Core/Logging.php b/Idno/Core/Logging.php index 61872c2574..0be5fc6b02 100644 --- a/Idno/Core/Logging.php +++ b/Idno/Core/Logging.php @@ -3,7 +3,7 @@ /** * Allow logging, with toggle support * - * @package idno + * @package idno * @subpackage core */ @@ -23,12 +23,13 @@ class Logging extends Component implements LoggerInterface * Create a basic logger to log to the PHP log. * * @param type $loglevel_filter Log levels to show 0 - off, 1 - errors, 2 - errors & warnings, 3 - errors, warnings and info, 4 - 3 + debug - * @param type $identifier Identify this site in the log (defaults to current domain) + * @param type $identifier Identify this site in the log (defaults to current domain) */ public function __construct($loglevel_filter = 0, $identifier = null) { - if (!$identifier) + if (!$identifier) { $identifier = Idno::site()->config()->host; + } if (isset(Idno::site()->config()->loglevel)) { $loglevel_filter = Idno::site()->config()->loglevel; } @@ -37,55 +38,61 @@ public function __construct($loglevel_filter = 0, $identifier = null) $this->identifier = $identifier; // Set log to handle PHP errors - set_error_handler(function ($errno, $errstr, $errfile, $errline, $errcontext = []) { + set_error_handler( + function ($errno, $errstr, $errfile, $errline, $errcontext = []) { - if (!(error_reporting() & $errno)) { - // This error code is not included in error_reporting - return; - } + if (!(error_reporting() & $errno)) { + // This error code is not included in error_reporting + return; + } - $message = "PHP [{$errno}] {$errstr} in {$errfile}:{$errline}"; + $message = "PHP [{$errno}] {$errstr} in {$errfile}:{$errline}"; - // Pedantic mode - if (\Idno\Core\Idno::site()->config()->pedantic_mode) { - $this->error($message); - throw new \ErrorException($message, 0, $errno, $errfile, $errline); - } + // Pedantic mode + if (\Idno\Core\Idno::site()->config()->pedantic_mode) { + $this->error($message); + throw new \ErrorException($message, 0, $errno, $errfile, $errline); + } - switch ($errno) { - case E_PARSE: - case E_ERROR: - case E_CORE_ERROR: - case E_COMPILE_ERROR: - case E_USER_ERROR: $this->error($message); - break; - - case E_WARNING: - case E_CORE_WARNING: - case E_COMPILE_WARNING: - case E_USER_WARNING: $this->warning($message); - break; - - case E_STRICT: - case E_NOTICE: - case E_DEPRECATED: - case E_USER_DEPRECATED: - case E_STRICT: - case E_USER_NOTICE: $this->notice($message); - break; - - default: - $this->notice("Unknown error type: {$message}"); - break; - } + switch ($errno) { + case E_PARSE: + case E_ERROR: + case E_CORE_ERROR: + case E_COMPILE_ERROR: + case E_USER_ERROR: + $this->error($message); + break; - /* Don't execute PHP internal error handler */ - //return true; - }); + case E_WARNING: + case E_CORE_WARNING: + case E_COMPILE_WARNING: + case E_USER_WARNING: + $this->warning($message); + break; + + case E_STRICT: + case E_NOTICE: + case E_DEPRECATED: + case E_USER_DEPRECATED: + case E_STRICT: + case E_USER_NOTICE: + $this->notice($message); + break; + + default: + $this->notice("Unknown error type: {$message}"); + break; + } + + /* Don't execute PHP internal error handler */ + //return true; + } + ); } /** * Sets the log level + * * @param $loglevel */ public function setLogLevel($loglevel) @@ -95,6 +102,7 @@ public function setLogLevel($loglevel) /** * Check whether a LogLevel meets the current loglevel_filter. + * * @param string $level * @return boolean true if messages at this level should be logged */ @@ -116,6 +124,7 @@ private function passesFilter($level) /** * Write a message to the log. + * * @param string $level * @param string $message * @param array $context @@ -128,14 +137,18 @@ public function log($level, $message = LOGLEVEL_INFO, array $context = array()) // calling style is deprecated and will eventually // go away. $temp = $level; - if ($message === LOGLEVEL_ERROR) + if ($message === LOGLEVEL_ERROR) { $level = LogLevel::ERROR; - if ($message === LOGLEVEL_WARNING) + } + if ($message === LOGLEVEL_WARNING) { $level = LogLevel::WARNING; - if ($message === LOGLEVEL_INFO) + } + if ($message === LOGLEVEL_INFO) { $level = LogLevel::INFO; - if ($message === LOGLEVEL_DEBUG) + } + if ($message === LOGLEVEL_DEBUG) { $level = LogLevel::DEBUG; + } $message = $temp; } @@ -177,8 +190,9 @@ public function log($level, $message = LOGLEVEL_INFO, array $context = array()) foreach ($message as $log) { $logline = "Known ({$this->identifier}): $level - " . rtrim($log); - if ($lines == count($message)-1) + if ($lines == count($message)-1) { $logline.=$trace; + } error_log($logline); @@ -305,6 +319,7 @@ public function debug($message, array $context = array()) /** * (attempt) to send, if configured, a message when a fatal error occurs, or an exception is caught. + * * @param type $message * @param type $title */ @@ -316,7 +331,8 @@ public static function oopsAlert($message, $title = "") if (!empty($config) && !empty($config->oops_notify)) { $notify = $config->oops_notify; - if (!is_array($notify)) $notify = [$notify]; + if (!is_array($notify)) { $notify = [$notify]; + } $title = $config->host . ": $title"; @@ -334,21 +350,26 @@ public static function oopsAlert($message, $title = "") ]; $uuid = \Idno\Core\Idno::site()->session()->currentUserUUID(); - if (!empty($uuid)) + if (!empty($uuid)) { $vars['user'] = \Idno\Core\Idno::site()->session()->currentUserUUID(); + } - if (!empty($_SERVER['HTTP_USER_AGENT'])) + if (!empty($_SERVER['HTTP_USER_AGENT'])) { $vars['agent'] = $_SERVER['HTTP_USER_AGENT']; + } - if (!empty($_SERVER['QUERY_STRING'])) + if (!empty($_SERVER['QUERY_STRING'])) { $vars['qs'] = $_SERVER['QUERY_STRING']; + } - if (!empty($_SERVER['HTTP_REFERER'])) + if (!empty($_SERVER['HTTP_REFERER'])) { $vars['referrer'] = $_SERVER['HTTP_REFERER']; + } $email = new Email(); - if (!empty($title)) + if (!empty($title)) { $email->setSubject($title); + } $email->setHTMLBodyFromTemplate('admin/oops', $vars); $email->setTextBodyFromTemplate('admin/oops', $vars); $email->addTo($emailaddress); diff --git a/Idno/Core/MentionClient.php b/Idno/Core/MentionClient.php index 4c39fa6f3d..306293368c 100644 --- a/Idno/Core/MentionClient.php +++ b/Idno/Core/MentionClient.php @@ -6,7 +6,7 @@ * This class extends the IndieWeb webmention client and better integrates it * with Known core. * - * @package idno + * @package idno * @subpackage core */ diff --git a/Idno/Core/Migration.php b/Idno/Core/Migration.php index 2fbfa17605..fabf0c2fe8 100644 --- a/Idno/Core/Migration.php +++ b/Idno/Core/Migration.php @@ -11,6 +11,7 @@ class Migration extends \Idno\Common\Component /** * Prepares an archive containing all of this site's data. + * * @return string */ static function exportToFolder($dir = false) @@ -19,8 +20,9 @@ static function exportToFolder($dir = false) set_time_limit(0); // Switch off the time limit for PHP $page = Idno::site()->currentPage(); - if (!empty($page)) + if (!empty($page)) { Idno::site()->currentPage()->setPermalink(true); + } // Prepare a unique name for the archive $name = md5(time() . rand(0, 9999) . Idno::site()->config()->getURL()); @@ -65,13 +67,17 @@ static function exportToFolder($dir = false) // If we've made it here, we've created a temporary directory with the hash name // Write some details about the export - file_put_contents($dir . $name . DIRECTORY_SEPARATOR . 'known.json', json_encode([ - 'url' => Idno::site()->config()->getURL(), - 'title' => Idno::site()->config()->getTitle(), - // Include some version info in case we change the export format - 'version' => \Idno\Core\Version::version(), - 'build' => \Idno\Core\Version::build(), - ], JSON_PRETTY_PRINT)); + file_put_contents( + $dir . $name . DIRECTORY_SEPARATOR . 'known.json', json_encode( + [ + 'url' => Idno::site()->config()->getURL(), + 'title' => Idno::site()->config()->getTitle(), + // Include some version info in case we change the export format + 'version' => \Idno\Core\Version::version(), + 'build' => \Idno\Core\Version::build(), + ], JSON_PRETTY_PRINT + ) + ); // We now also want to output the current loaded config file_put_contents($dir . $name . DIRECTORY_SEPARATOR . 'config.json', json_encode(\Idno\Core\Idno::site()->config(), JSON_PRETTY_PRINT)); @@ -176,20 +182,23 @@ static function exportToFolder($dir = false) $offset = 0; $f = fopen($dir . $name . DIRECTORY_SEPARATOR . 'exported_data.' . $export_ext, 'wb'); - if ($export_ext == 'json') + if ($export_ext == 'json') { fwrite($f, '['); + } while ($exported_records = \Idno\Core\Idno::site()->db()->exportRecords('entities', $limit, $offset)) { - if ($export_ext == 'json') + if ($export_ext == 'json') { fwrite($f, trim($exported_records, '[],') . ','); - else + } else { fwrite($f, $exported_records); + } $offset += $limit; } - if ($export_ext == 'json') + if ($export_ext == 'json') { fwrite($f, '{}]'); // Fudge to allow json decode + } fclose($f); // As we're successful, return the unique name of the archive @@ -201,8 +210,8 @@ static function exportToFolder($dir = false) * Given the path to a Known export, creates a complete .tar.gz file and returns the path to that. * If $save_path is false, will save to the temporary folder. * - * @param $path - * @param $save_path + * @param $path + * @param $save_path * @return string */ static function archiveExportFolder($path, $save_path = false) @@ -224,8 +233,9 @@ static function archiveExportFolder($path, $save_path = false) } $filename = str_replace('.', '_', Idno::site()->config()->host); - if (empty($filename)) + if (empty($filename)) { $filename = 'export'; + } if (file_exists(site()->config()->getTempDir() . $filename . '.tar')) { @unlink(site()->config()->getTempDir() . $filename . '.tar'); @@ -244,7 +254,8 @@ static function archiveExportFolder($path, $save_path = false) /** * Wrapper function that exports Known data and returns the path to the archive of it. - * @param $dir Path to export + * + * @param $dir Path to export * @return bool|string */ static function createCompressedArchive($dir = false) @@ -262,6 +273,7 @@ static function createCompressedArchive($dir = false) /** * Given the path to an archive folder, recursively removes it + * * @param $path */ static function cleanUpFolder($path) @@ -278,6 +290,7 @@ static function cleanUpFolder($path) /** * Given the XML source of an export, imports each post into Known. + * * @param $xml */ static function importFeedXML($xml) @@ -342,8 +355,9 @@ static function importFeedXML($xml) } // for now, lets assume a successful save - if ($imported > 0) + if ($imported > 0) { return true; + } } } @@ -388,6 +402,7 @@ static function importImagesFromBodyHTML($body, $src_url) /** * Given the XML source of a Blogger export, imports each post into Known. + * * @param $xml */ static function importBloggerXML($xml) @@ -398,6 +413,7 @@ static function importBloggerXML($xml) /** * Given the XML source of a WordPress export, imports each post into Known. + * * @param $xml */ static function importWordPressXML($xml) @@ -495,7 +511,8 @@ static function importWordPressXML($xml) } foreach ($item['wp:comment'] as $comment_obj) { $comment = (array) $comment_obj; - if ($object->addAnnotation('reply', $comment['comment_author'], $comment['comment_author_url'], '', $comment['comment_content'], null, strtotime($comment['comment_date_gmt']), null, [], false + if ($object->addAnnotation( + 'reply', $comment['comment_author'], $comment['comment_author_url'], '', $comment['comment_content'], null, strtotime($comment['comment_date_gmt']), null, [], false ) ) { $object->save(); @@ -506,8 +523,9 @@ static function importWordPressXML($xml) } // For now, lets assume that everything saved ok, if something was imported - if ($imported > 0) + if ($imported > 0) { return true; + } } } @@ -521,8 +539,9 @@ static function importWordPressXML($xml) /** * Retrieve all posts as an RSS feed - * @param bool|true $hide_private Should we hide private posts? Default: true. - * @param string $user_uuid User UUID to export for. Default: all users. + * + * @param bool|true $hide_private Should we hide private posts? Default: true. + * @param string $user_uuid User UUID to export for. Default: all users. * @return resource a file pointer resource on success, false on error */ static function getExportRSS($hide_private = true, $user_uuid = '') @@ -590,18 +609,24 @@ static function getExportRSS($hide_private = true, $user_uuid = '') $rss_theme = new DefaultTemplate(); $rss_theme->setTemplateType('rss'); - file_put_contents($rss_path . 'template.rss.fragment', $rss_theme->__(array( + file_put_contents( + $rss_path . 'template.rss.fragment', $rss_theme->__( + array( 'title' => $title, 'description' => $description, - 'body' => $rss_theme->__(array( + 'body' => $rss_theme->__( + array( 'items' => $feed, 'offset' => 0, 'count' => sizeof($feed), 'subject' => [], //'nocdata' => true, 'base_url' => $base_url - ))->draw('pages/home'), - ))->drawPage(false)); + ) + )->draw('pages/home'), + ) + )->drawPage(false) + ); // Now construct full rss $f = fopen($rss_path . 'export.rss', 'wb'); diff --git a/Idno/Core/PageHandler.php b/Idno/Core/PageHandler.php index dd5f796bbc..9c12c3c0f1 100644 --- a/Idno/Core/PageHandler.php +++ b/Idno/Core/PageHandler.php @@ -3,7 +3,7 @@ /** * Page handler class * - * @package idno + * @package idno * @subpackage core */ @@ -34,7 +34,7 @@ function routeTokens() * * @param string $pattern The pattern to match * @param string $handler The name of the Page class that will serve this route - * @param bool $public If set to true, this page is always public, even on non-public sites + * @param bool $public If set to true, this page is always public, even on non-public sites */ function addRoute(string $pattern, string $handler, bool $public = false) { @@ -61,7 +61,7 @@ function addRoute(string $pattern, string $handler, bool $public = false) * * @param string $pattern The pattern to match * @param string $handler The name of the Page class that will serve this route - * @param bool $public If set to true, this page is always public, even on non-public sites + * @param bool $public If set to true, this page is always public, even on non-public sites */ function hijackRoute(string $pattern, string $handler, bool $public = false) { @@ -78,6 +78,7 @@ function hijackRoute(string $pattern, string $handler, bool $public = false) /** * Mark a page handler class as offering public content even on walled garden sites + * * @param $class */ function addPublicRoute(string $class) @@ -89,6 +90,7 @@ function addPublicRoute(string $class) /** * Retrieve an array of walled garden page handlers + * * @return array */ function getPublicRoute() @@ -102,7 +104,8 @@ function getPublicRoute() /** * Does the specified page handler class represent a public page, even on walled gardens? - * @param $class + * + * @param $class * @return bool */ function isRoutePublic(string $class) : bool @@ -126,7 +129,7 @@ function isRoutePublic(string $class) : bool * Retrieves an instantiated version of the page handler class responsible for * a particular page (if any). May also be a whole URL. * - * @param string $path_info The path, including the initial /, or the URL + * @param string $path_info The path, including the initial /, or the URL * @return bool|\Idno\Common\Page */ function getRoute(string $path_info) @@ -163,7 +166,7 @@ function getRoute(string $path_info) * * @see ToroHook * - * @param string $hookName Name of hook + * @param string $hookName Name of hook * @param callable $callable */ static function hook(string $hookName, callable $callable) diff --git a/Idno/Core/Plugins.php b/Idno/Core/Plugins.php index a1b7bd15bc..3329b726e2 100644 --- a/Idno/Core/Plugins.php +++ b/Idno/Core/Plugins.php @@ -3,7 +3,7 @@ /** * Plugin management class * - * @package idno + * @package idno * @subpackage core */ @@ -13,7 +13,6 @@ class Plugins extends \Idno\Common\Component { - public $plugins = array(); // Property containing instantiated plugin classes /** @@ -23,7 +22,7 @@ class Plugins extends \Idno\Common\Component */ public function init() { - + if (!empty(\Idno\Core\Idno::site()->config()->directloadplugins)) { foreach (\Idno\Core\Idno::site()->config()->directloadplugins as $plugin => $folder) { @include $folder . '/Main.php'; @@ -42,7 +41,8 @@ public function init() } } if (!empty(\Idno\Core\Idno::site()->config()->alwaysplugins)) { - if (empty(\Idno\Core\Idno::site()->config()->plugins)) \Idno\Core\Idno::site()->config()->plugins = []; + if (empty(\Idno\Core\Idno::site()->config()->plugins)) { \Idno\Core\Idno::site()->config()->plugins = []; + } \Idno\Core\Idno::site()->config()->plugins = array_merge(\Idno\Core\Idno::site()->config()->plugins, \Idno\Core\Idno::site()->config()->alwaysplugins); } if (!empty(\Idno\Core\Idno::site()->config()->plugins)) { @@ -65,12 +65,14 @@ public function init() /** * Magic method to return the instantiated plugin object when * $Plugins->plugin_name is accessed - * @param $name + * + * @param $name * @return mixed */ public function __get($name) { - if (!empty($this->plugins[$name])) return $this->plugins[$name]; + if (!empty($this->plugins[$name])) { return $this->plugins[$name]; + } return null; } @@ -78,18 +80,21 @@ public function __get($name) /** * Magic method to check for the existence of plugin objects as properties * on the plugin handler object - * @param $name + * + * @param $name * @return bool */ public function __isset($name) { - if (!empty($this->plugins[$name])) return true; + if (!empty($this->plugins[$name])) { return true; + } return false; } /** * Retrieves the array of loaded plugin objects + * * @return array */ public function getLoaded() @@ -99,7 +104,8 @@ public function getLoaded() /** * Retrieve the Plugin object associated with a loaded plugin - * @param string $plugin Plugin name + * + * @param string $plugin Plugin name * @return bool|\Idno\Common\Plugin */ public function get($plugin) @@ -113,7 +119,8 @@ public function get($plugin) /** * Is the specified plugin allowed to be displayed? - * @param $plugin + * + * @param $plugin * @return bool */ public function isVisible($plugin) @@ -130,6 +137,7 @@ public function isVisible($plugin) /** * Retrieves a list of stored plugins (but not necessarily loaded ones) + * * @return array */ public function getStored() @@ -189,7 +197,8 @@ public function getStored() /** * Is the specified plugin allowed to be loaded? - * @param $plugin + * + * @param $plugin * @return bool */ public function isAllowed($plugin) @@ -216,6 +225,7 @@ public function isAllowed($plugin) /** * Retrieves the number of bytes stored by all plugins in the system. + * * @return int */ public function getTotalFileUsage() @@ -229,6 +239,7 @@ public function getTotalFileUsage() /** * Retrieves the file bytes stored by each plugin + * * @return array */ public function getFileUsageByPlugin() @@ -247,14 +258,16 @@ public function getFileUsageByPlugin() /** * Enable a specific plugin - * @param string $plugin + * + * @param string $plugin * @return boolean */ public function enable($plugin) { - if (!$this->exists($plugin)) + if (!$this->exists($plugin)) { return false; + } \Idno\Core\Idno::site()->events()->triggerEvent('plugin/load/' . $plugin); @@ -271,14 +284,15 @@ public function enable($plugin) /** * Disable a plugin - * @param string $plugin The plugin + * + * @param string $plugin The plugin * @return boolean */ public function disable($plugin) { - - if (!$this->exists($plugin)) + if (!$this->exists($plugin)) { return false; + } if (($key = array_search($plugin, \Idno\Core\Idno::site()->config()->config['plugins'])) !== false) { \Idno\Core\Idno::site()->events()->triggerEvent('plugin/unload/' . $plugin); unset(\Idno\Core\Idno::site()->config()->config['plugins'][$key]); @@ -293,7 +307,8 @@ public function disable($plugin) /** * Returns whether the selected plugin exists. - * @param string $plugin + * + * @param string $plugin * @return boolean */ public function exists($plugin) @@ -303,21 +318,17 @@ public function exists($plugin) $host = KNOWN_MULTITENANT_HOST; } - if (!preg_match('/^[a-zA-Z0-9]+$/', $plugin)) - { + if (!preg_match('/^[a-zA-Z0-9]+$/', $plugin)) { return false; } - if ( - (file_exists(\Idno\Core\Idno::site()->config()->path . '/IdnoPlugins/' . $plugin)) || - (!empty(\Idno\Core\Idno::site()->config()->external_plugin_path) && file_exists(\Idno\Core\Idno::site()->config()->external_plugin_path . '/IdnoPlugins/' . $plugin)) || - (!empty($host) && file_exists(\Idno\Core\Idno::site()->config()->path . '/hosts/' . $host . '/IdnoPlugins/' . $plugin)) + if ((file_exists(\Idno\Core\Idno::site()->config()->path . '/IdnoPlugins/' . $plugin)) + || (!empty(\Idno\Core\Idno::site()->config()->external_plugin_path) && file_exists(\Idno\Core\Idno::site()->config()->external_plugin_path . '/IdnoPlugins/' . $plugin)) + || (!empty($host) && file_exists(\Idno\Core\Idno::site()->config()->path . '/hosts/' . $host . '/IdnoPlugins/' . $plugin)) ) { return true; } return false; } - } - } diff --git a/Idno/Core/PubSubHubbub.php b/Idno/Core/PubSubHubbub.php index 5b3259324c..5595e026f9 100644 --- a/Idno/Core/PubSubHubbub.php +++ b/Idno/Core/PubSubHubbub.php @@ -3,7 +3,7 @@ /** * PubSubHubbub publishing * - * @package idno + * @package idno * @subpackage core */ @@ -23,111 +23,130 @@ function registerEventHooks() { // Hook into the "published" event to inform the PuSH hub when an entity is published - Idno::site()->events()->addListener('published', function (Event $event) { - $eventdata = $event->data(); - if ($object = $eventdata['object']) { - /* @var \Idno\Common\Entity $object */ - if ($object->isPublic()) { - Idno::site()->queue()->enqueue('default', 'pubsubhubbub/ping', $eventdata); + Idno::site()->events()->addListener( + 'published', function (Event $event) { + $eventdata = $event->data(); + if ($object = $eventdata['object']) { + /* @var \Idno\Common\Entity $object */ + if ($object->isPublic()) { + Idno::site()->queue()->enqueue('default', 'pubsubhubbub/ping', $eventdata); + } } } - }); - - Idno::site()->events()->addListener('pubsubhubbub/ping', function (Event $event) { - $eventdata = $event->data(); - $object = $eventdata['object']; - $result = Pubsubhubbub::publish($object); - $event->setResponse($result); - }); - - // Add PuSH headers to the top of the page - Idno::site()->events()->addListener('page/head', function (Event $event) { + ); - if (!empty(site()->config()->hub)) { + Idno::site()->events()->addListener( + 'pubsubhubbub/ping', function (Event $event) { $eventdata = $event->data(); - header('Link: <' . site()->config()->hub . '>; rel="hub"', false); - header('Link: <' . site()->template()->getCurrentURL() . '>; rel="self"', false); + $object = $eventdata['object']; + $result = Pubsubhubbub::publish($object); + $event->setResponse($result); } + ); - }); - - // When we follow a user, try and subscribe to their hub - Idno::site()->events()->addListener('follow', function (Event $event) { - - $eventdata = $event->data(); - $user = $eventdata['user']; - $eventdata = $event->data(); - $following = $eventdata['following']; - - if (($user instanceof \Idno\Entities\User) && ($following instanceof \Idno\Entities\User)) { - - $url = $following->getURL(); - - // Find self reference from profile url - if ($feed = $this->findSelf($url)) { - $following->pubsub_self = $feed; - - if ($hubs = $this->discoverHubs($url)) { - - $pending = unserialize($user->pubsub_pending); - if (!$pending) - $pending = new \stdClass(); - if (!is_array($pending->subscribe)) - $pending->subscribe = array(); + // Add PuSH headers to the top of the page + Idno::site()->events()->addListener( + 'page/head', function (Event $event) { - $pending->subscribe[] = $following->getUUID(); - $user->pubsub_pending = serialize($pending); - $user->save(); + if (!empty(site()->config()->hub)) { + $eventdata = $event->data(); + header('Link: <' . site()->config()->hub . '>; rel="hub"', false); + header('Link: <' . site()->template()->getCurrentURL() . '>; rel="self"', false); + } - $following->pubsub_hub = $hubs[0]; - $following->save(); + } + ); - $return = Webservice::post($following->pubsub_hub, array( - 'hub.callback' => Idno::site()->config()->url . 'pubsub/callback/' . $user->getID() . '/' . $following->getID(), // Callback, unique to each subscriber - 'hub.mode' => 'subscribe', - 'hub.verify' => 'async', // Backwards compatibility with v0.3 hubs - 'hub.topic' => $feed, // Subscribe to rss - )); + // When we follow a user, try and subscribe to their hub + Idno::site()->events()->addListener( + 'follow', function (Event $event) { - Idno::site()->logging()->info("Pubsub subscribed", ['response' => $return]); - } else - Idno::site()->logging()->info("Pubsub: No hubs found"); + $eventdata = $event->data(); + $user = $eventdata['user']; + $eventdata = $event->data(); + $following = $eventdata['following']; + + if (($user instanceof \Idno\Entities\User) && ($following instanceof \Idno\Entities\User)) { + + $url = $following->getURL(); + + // Find self reference from profile url + if ($feed = $this->findSelf($url)) { + $following->pubsub_self = $feed; + + if ($hubs = $this->discoverHubs($url)) { + + $pending = unserialize($user->pubsub_pending); + if (!$pending) { + $pending = new \stdClass(); + } + if (!is_array($pending->subscribe)) { + $pending->subscribe = array(); + } + + $pending->subscribe[] = $following->getUUID(); + $user->pubsub_pending = serialize($pending); + $user->save(); + + $following->pubsub_hub = $hubs[0]; + $following->save(); + + $return = Webservice::post( + $following->pubsub_hub, array( + 'hub.callback' => Idno::site()->config()->url . 'pubsub/callback/' . $user->getID() . '/' . $following->getID(), // Callback, unique to each subscriber + 'hub.mode' => 'subscribe', + 'hub.verify' => 'async', // Backwards compatibility with v0.3 hubs + 'hub.topic' => $feed, // Subscribe to rss + ) + ); + + Idno::site()->logging()->info("Pubsub subscribed", ['response' => $return]); + } else { + Idno::site()->logging()->info("Pubsub: No hubs found"); + } + } } } - }); + ); // Send unfollow notification to their hub - Idno::site()->events()->addListener('unfollow', function (Event $event) { - - $eventdata = $event->data(); - $user = $eventdata['user']; - $eventdata = $event->data(); - $following = $eventdata['following']; - - if (($user instanceof \Idno\Entities\User) && ($following instanceof \Idno\Entities\User)) { - - $url = $following->getURL(); - - $pending = unserialize($user->pubsub_pending); - if (!$pending) - $pending = new \stdClass(); - if (!is_array($pending->subscribe)) - $pending->unsubscribe = array(); - - $pending->unsubscribe[] = $following->getID(); - $user->pubsub_pending = serialize($pending); - $user->save(); + Idno::site()->events()->addListener( + 'unfollow', function (Event $event) { - $return = Webservice::post($following->pubsub_hub, array( - 'hub.callback' => Idno::site()->config()->url . 'pubsub/callback/' . $user->getID() . '/' . $following->getID(), // Callback, unique to each subscriber - 'hub.mode' => 'unsubscribe', - 'hub.verify' => 'async', // Backwards compatibility with v0.3 hubs - 'hub.topic' => $following->pubsub_self - )); - - Idno::site()->logging()->info("Pubsub unsubscribed.", ['response' => $return]); + $eventdata = $event->data(); + $user = $eventdata['user']; + $eventdata = $event->data(); + $following = $eventdata['following']; + + if (($user instanceof \Idno\Entities\User) && ($following instanceof \Idno\Entities\User)) { + + $url = $following->getURL(); + + $pending = unserialize($user->pubsub_pending); + if (!$pending) { + $pending = new \stdClass(); + } + if (!is_array($pending->subscribe)) { + $pending->unsubscribe = array(); + } + + $pending->unsubscribe[] = $following->getID(); + $user->pubsub_pending = serialize($pending); + $user->save(); + + $return = Webservice::post( + $following->pubsub_hub, array( + 'hub.callback' => Idno::site()->config()->url . 'pubsub/callback/' . $user->getID() . '/' . $following->getID(), // Callback, unique to each subscriber + 'hub.mode' => 'unsubscribe', + 'hub.verify' => 'async', // Backwards compatibility with v0.3 hubs + 'hub.topic' => $following->pubsub_self + ) + ); + + Idno::site()->logging()->info("Pubsub unsubscribed.", ['response' => $return]); + } } - }); + ); } function registerPages() @@ -139,9 +158,10 @@ function registerPages() /** * Find all hub urls for a given url, by looking at its feeds. - * @param $url the URL of the page to check + * + * @param $url the URL of the page to check * @param $page optionally, the contents of the page at $url - * @todo replace this with xpath. + * @todo replace this with xpath. */ protected function discoverHubs($url, $page = '') { @@ -177,23 +197,26 @@ protected function discoverHubs($url, $page = '') } } - if (count($hubs)) + if (count($hubs)) { return $hubs; + } return false; } /** * Find the (first) feed on a given URL. - * @param type $url + * + * @param type $url * @return type */ protected function findFeed($url, $data = null) { $feed = null; - if (!$data) + if (!$data) { $data = Webservice::file_get_contents($url); + } // search for all 'RSS Feed' declarations if (preg_match_all('#]+type="application/rss\+xml"[^>]*>#is', $data, $rawMatches)) { @@ -220,6 +243,7 @@ protected function findFeed($url, $data = null) /** * Find the self resource. * This method will find a link self on a feed, finding the feed first + * * @param type $url */ protected function findSelf($url) @@ -248,7 +272,8 @@ protected function findSelf($url) /** * If this Known installation has a PubSubHubbub hub, send a publish notification to the hub - * @param \Idno\Common\Entity $object + * + * @param \Idno\Common\Entity $object * @return array */ static function publish($object) @@ -292,13 +317,16 @@ static function publish($object) foreach ($feeds as $feed) { $encurls[] = urlencode($feed); $encurls[] = urlencode( - Idno::site()->template()->getURLWithVar('_t', 'rss', $feed)); + Idno::site()->template()->getURLWithVar('_t', 'rss', $feed) + ); } $formdata = 'hub.mode=publish&hub.url=' . implode(',', $encurls); Idno::site()->logging()->info('Pinging ' . $hub . ' with data ' . $formdata); - Webservice::post($hub, $formdata, array( - 'Content-Type' => 'application/x-www-form-urlencoded')); + Webservice::post( + $hub, $formdata, array( + 'Content-Type' => 'application/x-www-form-urlencoded') + ); } return true; diff --git a/Idno/Core/Purifier.php b/Idno/Core/Purifier.php index e5bb4fedb7..f1b2517912 100644 --- a/Idno/Core/Purifier.php +++ b/Idno/Core/Purifier.php @@ -38,22 +38,27 @@ function init() function registerEventHooks() { - \Idno\Core\Idno::site()->events()->addListener('text/filter', function (\Idno\Core\Event $event) { - $text = $event->response(); - $text = $this->purify($text); - $event->setResponse($text); - }); - \Idno\Core\Idno::site()->events()->addListener('text/filter/basic', function (\Idno\Core\Event $event) { - $text = $event->response(); - $text = $this->purify($text, true); - $event->setResponse($text); - }); + \Idno\Core\Idno::site()->events()->addListener( + 'text/filter', function (\Idno\Core\Event $event) { + $text = $event->response(); + $text = $this->purify($text); + $event->setResponse($text); + } + ); + \Idno\Core\Idno::site()->events()->addListener( + 'text/filter/basic', function (\Idno\Core\Event $event) { + $text = $event->response(); + $text = $this->purify($text, true); + $event->setResponse($text); + } + ); } /** * Purifies HTML code - * @param $html - * @param $basic_html Should the purifier strip out inline styles and similar attributes? Defaults to false. + * + * @param $html + * @param $basic_html Should the purifier strip out inline styles and similar attributes? Defaults to false. * @return string Purified HTML */ function purify($html, $basic_html = false) diff --git a/Idno/Core/Reader.php b/Idno/Core/Reader.php index 4b634f75ca..cc3de49da6 100644 --- a/Idno/Core/Reader.php +++ b/Idno/Core/Reader.php @@ -23,8 +23,9 @@ function registerPages() /** * Given the content of a page and its URL, returns an array of FeedItem objects (or false on failure) - * @param $content - * @param $url + * + * @param $content + * @param $url * @return array|bool */ function parseFeed($content, $url) @@ -80,8 +81,9 @@ function parseAndSaveFeeds() /** * Given a parsed microformat feed, returns an array of FeedItem objects - * @param $mf2_content - * @param $url + * + * @param $mf2_content + * @param $url * @return array */ function mf2FeedToFeedItems($mf2_content, $url) @@ -105,8 +107,9 @@ function mf2FeedToFeedItems($mf2_content, $url) /** * Given a parsed RSS or Atom feed, returns an array of FeedItem objects - * @param $rss_content - * @param $url + * + * @param $rss_content + * @param $url * @return array */ function xmlFeedToFeedItems($xml_items, $url) @@ -130,7 +133,7 @@ function xmlFeedToFeedItems($xml_items, $url) /** * - * @param $url + * @param $url * @return array|bool */ function fetchAndParseFeed($url) @@ -152,7 +155,8 @@ function fetchAndParseFeed($url) * Given the URL of a website, returns a single linked array containing the URL and title of a feed * (whether Microformats or RSS / Atom). The function will attempt to discover RSS and Atom feeds in * the page if this is an HTML site. Returns false if there is no feed. - * @param $url + * + * @param $url * @return array|false */ function getFeedDetails($url) @@ -217,8 +221,9 @@ function getFeedDetails($url) /** * Retrieves a feed object for the given URL, or creates one if it's new to the system - * @param $url - * @param $update Set to true in order to refresh saved feed details. False by default. + * + * @param $url + * @param $update Set to true in order to refresh saved feed details. False by default. * @return bool|false|\Idno\Common\Entity|Feed */ function getFeedObject($url, $update = false) @@ -258,7 +263,8 @@ function getFeedObject($url, $update = false) /** * Given the content of a web page, returns the URL of a linked-to RSS or Atom feed - * @param $content + * + * @param $content * @return array|bool */ function findXMLFeedURL($html) @@ -287,7 +293,8 @@ function findXMLFeedURL($html) /** * Retrieve a particular user's subscriptions - * @param $user + * + * @param $user * @return array|bool */ function getUserSubscriptions($user) diff --git a/Idno/Core/RemoteVersion.php b/Idno/Core/RemoteVersion.php index 92833a0981..4e3bd1d929 100644 --- a/Idno/Core/RemoteVersion.php +++ b/Idno/Core/RemoteVersion.php @@ -15,8 +15,9 @@ class RemoteVersion extends \Idno\Core\Version protected static function parse() { - if (!empty(static::$remoteDetails)) + if (!empty(static::$remoteDetails)) { return static::$remoteDetails; + } try { $versionfile = Webservice::get(static::$remoteVersion); diff --git a/Idno/Core/Service.php b/Idno/Core/Service.php index da55c196dd..46bc4829db 100644 --- a/Idno/Core/Service.php +++ b/Idno/Core/Service.php @@ -3,7 +3,7 @@ /** * Tools for Known services. * - * @package idno + * @package idno * @subpackage core */ @@ -15,23 +15,27 @@ class Service extends \Idno\Common\Component /** * Check that a page is being accessed by a local service. * This is used to limit access to certain api endpoints to local services (event queue, cron etc). + * * @TODO: Find a cleaner way. */ public static function gatekeeper() { $service_signature = $_SERVER['HTTP_X_KNOWN_SERVICE_SIGNATURE']; - if (empty($service_signature)) + if (empty($service_signature)) { throw new \RuntimeException(\Idno\Core\Idno::site()->language()->_('Missing X-Known-Service-Signature, service call is not possible.')); + } - if ($service_signature != static::generateToken(\Idno\Core\Idno::site()->currentPage()->currentUrl())) + if ($service_signature != static::generateToken(\Idno\Core\Idno::site()->currentPage()->currentUrl())) { throw new \RuntimeException(\Idno\Core\Idno::site()->language()->_('Sorry, signature doesn\'t match up.')); + } return true; } /** * Generate a token based on the site secret and URL. - * @param type $url Endpoint URL you're calling + * + * @param type $url Endpoint URL you're calling * @return string * @throws \Idno\Exceptions\ConfigurationException * @throws \RuntimeException @@ -40,8 +44,9 @@ public static function generateToken($url) { $site_secret = \Idno\Core\Idno::site()->config()->site_secret; - if (empty($site_secret)) + if (empty($site_secret)) { throw new \Idno\Exceptions\ConfigurationException(\Idno\Core\Idno::site()->language()->_('Missing site secret')); + } $url = explode('?', $url)[0]; @@ -49,44 +54,53 @@ public static function generateToken($url) $url = str_replace('https://', '', $url); $url = str_replace('http://', '', $url); - if (empty($url)) + if (empty($url)) { throw new \RuntimeException(\Idno\Core\Idno::site()->language()->_('Url not provided to token generation.')); + } return hash_hmac('sha256', $url, $site_secret); } /** * Call a service endpoint - * @param type $endpoint + * + * @param type $endpoint * @return boolean * @throws \RuntimeException */ public static function call($endpoint, $params = []) { - if (empty($endpoint)) + if (empty($endpoint)) { throw new \RuntimeException('No endpoint given'); + } - if (strpos($endpoint, 'http')===false) // Handle variation in endpoint call + if (strpos($endpoint, 'http')===false) { // Handle variation in endpoint call $endpoint = \Idno\Core\Idno::site()->config()->getDisplayURL() . ltrim($endpoint, '/'); + } \Idno\Core\Idno::site()->logging()->debug("Calling $endpoint"); $signature = \Idno\Core\Service::generateToken($endpoint); - if ($result = \Idno\Core\Webservice::get($endpoint, $params, [ + if ($result = \Idno\Core\Webservice::get( + $endpoint, $params, [ 'X-KNOWN-SERVICE-SIGNATURE: ' . $signature - ])) { + ] + ) + ) { $error = $result['response']; $content = json_decode($result['content']); if ($error != 200) { - if (empty($content)) + if (empty($content)) { throw new \RuntimeException(\Idno\Core\Idno::site()->language()->_('Response from service endpoint was not json')); + } - if (!empty($content->exception->message)) + if (!empty($content->exception->message)) { throw new \RuntimeException($content->exception->message); + } } else { @@ -103,13 +117,15 @@ public static function call($endpoint, $params = []) /** * Returns true if given system call is available (i.e. not in disable_functions). - * @param type $func + * + * @param type $func * @return boolean */ public static function isFunctionAvailable($func) { - if (!is_callable($func)) + if (!is_callable($func)) { return false; + } // https://stackoverflow.com/questions/4033841/how-to-test-if-php-system-function-is-allowed-and-not-turned-off-for-security // is_callable does not check disabled functions. diff --git a/Idno/Core/Session.php b/Idno/Core/Session.php index 7d48722a40..70ca419f95 100644 --- a/Idno/Core/Session.php +++ b/Idno/Core/Session.php @@ -3,7 +3,7 @@ /** * Session management class * - * @package idno + * @package idno * @subpackage core */ @@ -96,36 +96,44 @@ function init() Idno::site()->routes()->addRoute('/currentUser/?', '\Idno\Pages\Session\CurrentUser'); // Update the session on save if we're saving the current user - \Idno\Core\Idno::site()->events()->addListener('save', function (\Idno\Core\Event $event) { + \Idno\Core\Idno::site()->events()->addListener( + 'save', function (\Idno\Core\Event $event) { - $eventdata = $event->data(); - $object = $eventdata['object']; + $eventdata = $event->data(); + $object = $eventdata['object']; - if (empty($object) || empty($this->user) || - !($object instanceof User) || !($this->user instanceof User) - ) return; + if (empty($object) || empty($this->user) + || !($object instanceof User) || !($this->user instanceof User) + ) { return; + } - if ($object->getUUID() != $this->user->getUUID()) return; + if ($object->getUUID() != $this->user->getUUID()) { return; + } - if (!empty($_SESSION['user_uuid'])) { - if ($object->getUUID() != $_SESSION['user_uuid']) return; - } + if (!empty($_SESSION['user_uuid'])) { + if ($object->getUUID() != $_SESSION['user_uuid']) { return; + } + } - $this->user = $this->refreshSessionUser($object); + $this->user = $this->refreshSessionUser($object); - }); + } + ); // If this is an API request, we need to destroy the session afterwards. See #1028 - register_shutdown_function(function () { - $session = Idno::site()->session(); - if ($session && $session->isAPIRequest()) { - $session->logUserOff(); + register_shutdown_function( + function () { + $session = Idno::site()->session(); + if ($session && $session->isAPIRequest()) { + $session->logUserOff(); + } } - }); + ); } /** * Validate the session. + * * @throws \Exception if the session is invalid. */ protected function validate() @@ -163,7 +171,8 @@ function currentUserUUID() /** * Wrapper function for isLoggedIn() - * @see Idno\Core\Session::isLoggedIn() + * + * @see Idno\Core\Session::isLoggedIn() * @return true|false */ @@ -174,6 +183,7 @@ function isLoggedOn() /** * Is a user logged into the current session? + * * @return true|false */ function isLoggedIn() @@ -187,6 +197,7 @@ function isLoggedIn() /** * Returns true if a user is logged into the current session, and they're an admin. + * * @return bool */ function isAdmin() @@ -200,6 +211,7 @@ function isAdmin() /** * Returns the currently logged-in user, if any + * * @return \Idno\Entities\User */ @@ -214,7 +226,8 @@ function currentUser() /** * Adds a message to the queue to be delivered to the user as soon as is possible - * @param string $message The text of the message + * + * @param string $message The text of the message * @param string $message_type This type of message; this will be added to the displayed message class, or returned as data */ @@ -228,8 +241,9 @@ function addMessage($message, $message_type = 'alert-info') /** * Draw a message - * @param $message - * @param string $message_type + * + * @param $message + * @param string $message_type * @return string */ function drawMessage($message, $message_type = 'alert-info') @@ -241,7 +255,8 @@ function drawMessage($message, $message_type = 'alert-info') /** * Draw a message from a message structure - * @param array $message + * + * @param array $message * @return string */ function drawStructuredMessage($message) @@ -253,8 +268,9 @@ function drawStructuredMessage($message) /** * Turns a string message into a message structure - * @param $message - * @param string $message_type + * + * @param $message + * @param string $message_type * @return array */ function getStructuredMessage($message, $message_type = 'alert-info') @@ -264,6 +280,7 @@ function getStructuredMessage($message, $message_type = 'alert-info') /** * Error message wrapper for addMessage() + * * @param string $message */ function addErrorMessage($message) @@ -273,7 +290,8 @@ function addErrorMessage($message) /** * Adds a message to the queue to be delivered to the user as soon as is possible, ensuring it's at the beginning of the list - * @param string $message The text of the message + * + * @param string $message The text of the message * @param string $message_type This type of message; this will be added to the displayed message class, or returned as data */ @@ -287,6 +305,7 @@ function addMessageAtStart($message, $message_type = 'alert-info') /** * Retrieve any messages from the session, remove them from the session, and return them + * * @return array */ function getAndFlushMessages() @@ -299,6 +318,7 @@ function getAndFlushMessages() /** * Retrieve any messages waiting for the user in the session + * * @return array */ function getMessages() @@ -322,6 +342,7 @@ function flushMessages() /** * Get access groups the current user is allowed to write to + * * @return array */ @@ -336,32 +357,37 @@ function getWriteAccessGroups() /** * Get IDs of the access groups the current user is allowed to write to + * * @return array */ function getWriteAccessGroupIDs() { - if ($this->isLoggedOn()) + if ($this->isLoggedOn()) { return $this->currentUser()->getWriteAccessGroups(); + } return array(); } /** * Get access groups the current user (if any) is allowed to read from + * * @return array */ function getReadAccessGroups() { - if ($this->isLoggedOn()) + if ($this->isLoggedOn()) { return $this->currentUser()->getReadAccessGroups(); + } return array('PUBLIC'); } /** * Get IDs of the access groups the current user (if any) is allowed to read from + * * @return array */ @@ -377,15 +403,18 @@ function getReadAccessGroupIDs() /** * Log the current session user off + * * @return true */ function logUserOff() { - \Idno\Core\Idno::site()->events()->triggerEvent("user/logoff", array( + \Idno\Core\Idno::site()->events()->triggerEvent( + "user/logoff", array( "user" => !empty($this->user) ? $this->user : null, - )); + ) + ); unset($_SESSION['user_uuid']); unset($this->user); @@ -399,7 +428,8 @@ function logUserOff() if (!$this->isAPIRequest()) { // #1365 - we need to destroy the session, but resetting cookie causes problems with the api if (ini_get("session.use_cookies")) { $params = session_get_cookie_params(); - setcookie(session_name(), '', time() - 42000, + setcookie( + session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"] ); @@ -414,8 +444,9 @@ function logUserOff() /** * Set a piece of session data + * * @param string $name - * @param mixed $value + * @param mixed $value */ function set($name, $value) { @@ -424,7 +455,8 @@ function set($name, $value) /** * Retrieve the session data with key $name, if it exists - * @param string $name + * + * @param string $name * @return mixed */ function get($name) @@ -438,6 +470,7 @@ function get($name) /** * Remove data with key $name from the session + * * @param $name */ function remove($name) @@ -475,7 +508,8 @@ function tryAuthUser() } $user = \Idno\Entities\User::getByHandle($_SERVER['HTTP_X_KNOWN_USERNAME']); - if (empty($user)) $user = \Idno\Entities\User::getByEmail($_SERVER['HTTP_X_KNOWN_USERNAME']); + if (empty($user)) { $user = \Idno\Entities\User::getByEmail($_SERVER['HTTP_X_KNOWN_USERNAME']); + } if (!empty($user)) { \Idno\Core\Idno::site()->logging()->debug("API auth found user by username: {$_SERVER['HTTP_X_KNOWN_USERNAME']} - " . $user->getName()); @@ -520,10 +554,12 @@ function tryAuthUser() } } - $return = \Idno\Core\Idno::site()->events()->triggerEvent($return ? "user/auth/success" : "user/auth/failure", array( + $return = \Idno\Core\Idno::site()->events()->triggerEvent( + $return ? "user/auth/success" : "user/auth/failure", array( "user" => $return, "is api" => $this->isAPIRequest(), - ), $return); + ), $return + ); return $return; } @@ -531,7 +567,7 @@ function tryAuthUser() /** * Log the specified user on (note that this is NOT the same as taking the user's auth credentials) * - * @param \Idno\Entities\User $user + * @param \Idno\Entities\User $user * @return \Idno\Entities\User */ @@ -546,21 +582,26 @@ function logUserOn(\Idno\Entities\User $user) @session_regenerate_id(true); // user/auth/success event needs to be triggered here - $return = \Idno\Core\Idno::site()->events()->triggerEvent($return ? "user/auth/success" : "user/auth/failure", array( + $return = \Idno\Core\Idno::site()->events()->triggerEvent( + $return ? "user/auth/success" : "user/auth/failure", array( "user" => $return, "is api" => $this->isAPIRequest(), - ), $return); + ), $return + ); - \Idno\Core\Idno::site()->events()->triggerEvent("user/logon", array( + \Idno\Core\Idno::site()->events()->triggerEvent( + "user/logon", array( "user" => $return, - )); + ) + ); return $return; } /** * Refresh the user currently stored in the session - * @param \Idno\Entities\User $user + * + * @param \Idno\Entities\User $user * @return \Idno\Entities\User */ function refreshSessionUser(\Idno\Entities\User $user) @@ -605,6 +646,7 @@ function refreshCurrentSessionuser() /** * Sets whether this session is an API request or a manual browse + * * @param boolean $is_api_request */ function setIsAPIRequest($is_api_request) @@ -615,6 +657,7 @@ function setIsAPIRequest($is_api_request) /** * Is this session an API request? + * * @return bool */ function isAPIRequest() diff --git a/Idno/Core/Site.php b/Idno/Core/Site.php index 7dc1b048f1..25f306fa4d 100644 --- a/Idno/Core/Site.php +++ b/Idno/Core/Site.php @@ -7,21 +7,22 @@ class Site extends Entity { - + private $collection = 'site'; static $retrieve_collection = 'site'; - + function getCollection() { return $this->collection; } - public function uuid() : ? string { - + public function uuid() : ? string + { + if (!empty($this->_id)) { return $this->_id; } - + return null; } } diff --git a/Idno/Core/Statistics.php b/Idno/Core/Statistics.php index f64f6b62a7..ee113fd8f2 100644 --- a/Idno/Core/Statistics.php +++ b/Idno/Core/Statistics.php @@ -24,7 +24,8 @@ public static function basic() /** * Gather statistics. - * @param $report string Named report to gather, or empty for all. + * + * @param $report string Named report to gather, or empty for all. * @return array */ public static function gather($report = null) @@ -37,9 +38,11 @@ public static function gather($report = null) $stats['Basic'] = static::basic(); } - return \Idno\Core\Idno::site()->events()->triggerEvent('statistics/gather', [ + return \Idno\Core\Idno::site()->events()->triggerEvent( + 'statistics/gather', [ 'report' => $report - ], $stats); + ], $stats + ); } } diff --git a/Idno/Core/Syndication.php b/Idno/Core/Syndication.php index 2b4932eec6..871dace5f9 100644 --- a/Idno/Core/Syndication.php +++ b/Idno/Core/Syndication.php @@ -3,7 +3,7 @@ /** * Syndication (or POSSE - Publish Own Site, Share Everywhere) helpers * - * @package idno + * @package idno * @subpackage core */ @@ -22,34 +22,37 @@ function init() function registerEventHooks() { - \Idno\Core\Idno::site()->events()->addListener('syndicate', function (\Idno\Core\Event $event) { - - $eventdata = $event->data(); - if (!empty($eventdata['object'])) { - $content_type = $eventdata['object']->getActivityStreamsObjectType(); - if ($services = \Idno\Core\Idno::site()->syndication()->getServices($content_type)) { - if ($selected_services = \Idno\Core\Idno::site()->currentPage()->getInput('syndication')) { - if (!empty($selected_services) && is_array($selected_services)) { - foreach ($selected_services as $selected_service) { - $eventdata['syndication_account'] = false; - if (in_array($selected_service, $services)) { - site()->queue()->enqueue('default', 'post/' . $content_type . '/' . $selected_service, $eventdata); - } else if ($implied_service = $this->getServiceByAccountString($selected_service)) { - $eventdata['syndication_account'] = $this->getAccountFromAccountString($selected_service); - site()->queue()->enqueue('default', 'post/' . $content_type . '/' . $implied_service, $eventdata); + \Idno\Core\Idno::site()->events()->addListener( + 'syndicate', function (\Idno\Core\Event $event) { + + $eventdata = $event->data(); + if (!empty($eventdata['object'])) { + $content_type = $eventdata['object']->getActivityStreamsObjectType(); + if ($services = \Idno\Core\Idno::site()->syndication()->getServices($content_type)) { + if ($selected_services = \Idno\Core\Idno::site()->currentPage()->getInput('syndication')) { + if (!empty($selected_services) && is_array($selected_services)) { + foreach ($selected_services as $selected_service) { + $eventdata['syndication_account'] = false; + if (in_array($selected_service, $services)) { + site()->queue()->enqueue('default', 'post/' . $content_type . '/' . $selected_service, $eventdata); + } else if ($implied_service = $this->getServiceByAccountString($selected_service)) { + $eventdata['syndication_account'] = $this->getAccountFromAccountString($selected_service); + site()->queue()->enqueue('default', 'post/' . $content_type . '/' . $implied_service, $eventdata); + } } } } } } - } - }); + } + ); } /** * Return an array of the services registered for a particular content type - * @param $content_type + * + * @param $content_type * @return array */ function getServices($content_type = false) @@ -76,7 +79,8 @@ function getServices($content_type = false) /** * Given an account string (generated by the syndication input buttons), returns the service it's associated with - * @param $account_string + * + * @param $account_string * @return bool|int|string */ function getServiceByAccountString($account_string) @@ -96,6 +100,7 @@ function getServiceByAccountString($account_string) /** * Retrieve all the account identifiers associated with syndicating to all registered services + * * @return array */ function getServiceAccountsByService() @@ -113,7 +118,8 @@ function getServiceAccountsByService() /** * Given an account string (generated by the syndication input buttons), returns the account portion - * @param $account_string + * + * @param $account_string * @return bool|mixed */ function getAccountFromAccountString($account_string) @@ -127,9 +133,10 @@ function getAccountFromAccountString($account_string) /** * Register syndication $service with idno. - * @param string $service The name of the service. - * @param callable $checker A function that will return true if the current user has the service enabled; false otherwise - * @param array $content_types An array of content types that the service supports syndication for + * + * @param string $service The name of the service. + * @param callable $checker A function that will return true if the current user has the service enabled; false otherwise + * @param array $content_types An array of content types that the service supports syndication for */ function registerService($service, callable $checker, $content_types = array('article', 'note', 'event', 'rsvp', 'reply')) { @@ -150,10 +157,11 @@ function registerService($service, callable $checker, $content_types = array('ar /** * Registers an account on a particular service as being available. The service itself must also have been registered. - * @param string $service The name of the service. - * @param string $username The username or user identifier on the service. - * @param string $display_name A human-readable name for this account. - * @param array $other_properties An optional list of additional properties to include in the account record + * + * @param string $service The name of the service. + * @param string $username The username or user identifier on the service. + * @param string $display_name A human-readable name for this account. + * @param array $other_properties An optional list of additional properties to include in the account record */ function registerServiceAccount($service, $username, $display_name, $other_properties=array()) { @@ -170,6 +178,7 @@ function registerServiceAccount($service, $username, $display_name, $other_prope /** * Adds a content type that the specified service will support + * * @param $service * @param $content_type */ @@ -182,7 +191,8 @@ function addServiceContentType($service, $content_type) /** * Retrieve the user identifiers associated with syndicating to the specified service - * @param $service + * + * @param $service * @return bool */ function getServiceAccounts($service) @@ -196,6 +206,7 @@ function getServiceAccounts($service) /** * Get a list of fully-formatted service::username syndication strings + * * @return array */ function getServiceAccountStrings() @@ -214,6 +225,7 @@ function getServiceAccountStrings() /** * Get a list of expanded service data + * * @return array */ function getServiceAccountData() @@ -237,7 +249,8 @@ function getServiceAccountData() /** * Does the currently logged-in user have service $service? - * @param $service + * + * @param $service * @return bool */ function has($service) diff --git a/Idno/Core/Template.php b/Idno/Core/Template.php index 810cc5a8ec..3c607c547a 100644 --- a/Idno/Core/Template.php +++ b/Idno/Core/Template.php @@ -2,46 +2,51 @@ namespace Idno\Core { - interface Template { - + interface Template + { + /** * Override a page shell based on the page root. + * * @param type $path_root Url base, e.g. 'settings' - * @param type $shell The shell, e.g. 'settings-shell' + * @param type $shell The shell, e.g. 'settings-shell' */ public function addUrlShellOverride($path_root, $shell); /** * Extension-aware version of the template drawing function * - * @param string $templateName - * @param bool $returnBlank Should we return a blank string if the template doesn't exist? (Defaults to true) - * @param book $replacements Should we honor template replacements? (Defaults to true) + * @param string $templateName + * @param bool $returnBlank Should we return a blank string if the template doesn't exist? (Defaults to true) + * @param book $replacements Should we honor template replacements? (Defaults to true) * @return \Idno\Core\Bonita\false|string */ function draw($templateName, $returnBlank = true, $replacements = true); /** * Draws the page shell. - * @param bool $echo - * @param $shell Optional override of the page shell template to be used + * + * @param bool $echo + * @param $shell Optional override of the page shell template to be used * @return false|string */ function drawPage($echo = true, $shell = 'shell'); /** * Draw syndication buttons relating to a particular content type - * @param $content_type - * @param $posse_links containing Entity::getPosseLinks() + * + * @param $content_type + * @param $posse_links containing Entity::getPosseLinks() * @return \Idno\Core\Bonita\false|string */ function drawSyndication($content_type, $posse_links = []); /** * Draws generic pagination suitable for placing somewhere on a page (offset is drawn from the 'offset' input variable) - * @param int $count Number of items in total (across all pages) - * @param int $items_per_page Number of items you're displaying per page - * @param array $vars Additional template variables + * + * @param int $count Number of items in total (across all pages) + * @param int $items_per_page Number of items you're displaying per page + * @param array $vars Additional template variables * @return string */ function drawPagination($count, $items_per_page = null, array $vars = []); @@ -54,7 +59,7 @@ function drawPagination($count, $items_per_page = null, array $vars = []); * * @param string $templateName * @param string $extensionTemplateName - * @param bool $to_front If set, this will add the template to the beginning of the template queue + * @param bool $to_front If set, this will add the template to the beginning of the template queue */ function extendTemplate($templateName, $extensionTemplateName, $to_front = false, $templateType = '*'); @@ -66,7 +71,7 @@ function extendTemplate($templateName, $extensionTemplateName, $to_front = false * * @param string $templateName * @param string $prependTemplateName - * @param bool $to_front If set, this will add the template to the beginning of the template queue + * @param bool $to_front If set, this will add the template to the beginning of the template queue */ function prependTemplate($templateName, $prependTemplateName, $to_front = false); @@ -82,17 +87,19 @@ function prependTemplate($templateName, $prependTemplateName, $to_front = false) * @param string $extensionTemplateName */ function replaceTemplate($templateName, $replacementTemplateName, $templateType = '*'); - + /** * Extends a given template with pre-rendered content. All pre-rendered content will be drawn after * template-driven content. + * * @param $templateName * @param $content */ function extendTemplateWithContent($templateName, $content); - + /** * Sets the current template type + * * @param string $template The name of the template you wish to use */ function setTemplateType($templateType); @@ -101,7 +108,7 @@ function setTemplateType($templateType); * Sets the template type based on various environmental factors */ function autodetectTemplateType(); - + } } \ No newline at end of file diff --git a/Idno/Core/Templating/Classes.php b/Idno/Core/Templating/Classes.php index fbb05eb0f0..aab284943d 100644 --- a/Idno/Core/Templating/Classes.php +++ b/Idno/Core/Templating/Classes.php @@ -2,11 +2,13 @@ namespace Idno\Core\Templating { - - trait Classes { - + + trait Classes + { + /** * Retrieves a set of contextual body classes suitable for including in a shell template + * * @return string */ function getBodyClasses() diff --git a/Idno/Core/Templating/Data.php b/Idno/Core/Templating/Data.php index caa778dccf..f3a56ec850 100644 --- a/Idno/Core/Templating/Data.php +++ b/Idno/Core/Templating/Data.php @@ -1,11 +1,13 @@ object_data[$objectType])) return $this->object_data[$objectType]; + if (!empty($this->object_data[$objectType])) { return $this->object_data[$objectType]; + } return []; } /** * Returns a string of data attributes to be attached to the HTML of a particular object type - * @param $objectType + * + * @param $objectType * @return string */ function getDataHTMLAttributesForObjectType($objectType) @@ -45,10 +50,11 @@ function getDataHTMLAttributesForObjectType($objectType) } return implode(' ', $attributes); } - + /** * Get the modified time of a Known file. * Primarily used by cache busting, this method returns when a file was last modified. + * * @param type $file The file, relative to the known path. */ public function getModifiedTS($file) @@ -59,5 +65,5 @@ public function getModifiedTS($file) return (int)$ts; } } - -} \ No newline at end of file + +} diff --git a/Idno/Core/Templating/Formatting.php b/Idno/Core/Templating/Formatting.php index b4131b1791..ea9fa0ee84 100644 --- a/Idno/Core/Templating/Formatting.php +++ b/Idno/Core/Templating/Formatting.php @@ -2,14 +2,16 @@ namespace Idno\Core\Templating { - + use \Idno\Core\Idno; - - trait Formatting { - + + trait Formatting + { + /** * Automatically adds paragraph tags (etc) to a given piece of unformatted or semi-formatted text. - * @param $html + * + * @param $html * @return \false|string */ function autop($html) @@ -23,7 +25,8 @@ function autop($html) /** * Wrapper for those on UK spelling. - * @param $html + * + * @param $html * @return mixed */ function sanitise_html($html) @@ -34,6 +37,7 @@ function sanitise_html($html) /** * Sanitize HTML in a large block of text, removing XSS and other vulnerabilities. * This works by calling the text/filter event, as well as any built-in purifier. + * * @param type $html */ function sanitize_html($html) diff --git a/Idno/Core/Templating/Parsing.php b/Idno/Core/Templating/Parsing.php index 623d68def5..7722abe95f 100644 --- a/Idno/Core/Templating/Parsing.php +++ b/Idno/Core/Templating/Parsing.php @@ -1,58 +1,63 @@ "\']+)/i', function ($matches) use ($code) { - $url = $matches[1]; - $punc = ''; - - while ($url) { - $last = substr($url, -1, 1); - if (strstr('.!?,;:(', $last) - // strip ) if there isn't a matching ( earlier in the url - || ($last === ')' && !strstr($url, '(')) - ) { - $punc = $last . $punc; - $url = substr($url, 0, -1); - } else { - break; // found a non-punctuation character + $r = preg_replace_callback( + '/(?"\']+)/i', function ($matches) use ($code) { + $url = $matches[1]; + $punc = ''; + + while ($url) { + $last = substr($url, -1, 1); + if (strstr('.!?,;:(', $last) + // strip ) if there isn't a matching ( earlier in the url + || ($last === ')' && !strstr($url, '(')) + ) { + $punc = $last . $punc; + $url = substr($url, 0, -1); + } else { + break; // found a non-punctuation character + } } - } - $result = "', static::sampleTextChars($url, 100)); - $result .= "$punc"; + $result = "', static::sampleTextChars($url, 100)); + $result .= "$punc"; - return $result; + return $result; - }, $text); + }, $text + ); return $r; } /** * Link any hashtags in the text - * @param $text + * + * @param $text * @return string */ function parseHashtags($text) @@ -65,27 +70,30 @@ function parseHashtags($text) $text ) ); - $r = preg_replace_callback('/(?<=^|[\>\s\n])(\#[\p{L}0-9\_]+)/u', function ($matches) { - $url = $matches[1]; - $tag = str_replace('#', '', $matches[1]); + $r = preg_replace_callback( + '/(?<=^|[\>\s\n])(\#[\p{L}0-9\_]+)/u', function ($matches) { + $url = $matches[1]; + $tag = str_replace('#', '', $matches[1]); - if (preg_match('/\#[0-9]{1,3}$/', $matches[1])) { - return $matches[1]; - } + if (preg_match('/\#[0-9]{1,3}$/', $matches[1])) { + return $matches[1]; + } - if (preg_match('/\#[A-Fa-f0-9]{6}$/', $matches[1])) { - return $matches[1]; - } + if (preg_match('/\#[A-Fa-f0-9]{6}$/', $matches[1])) { + return $matches[1]; + } - return ''; - }, $text); + return ''; + }, $text + ); return $r; } /** * Change @user links into active users. - * @param type $text The text to parse + * + * @param type $text The text to parse * @param type $in_reply_to If specified, the function will make a (hopefully) sensible guess as to where the user is located */ function parseUsers($text, $in_reply_to = null) @@ -101,49 +109,56 @@ function parseUsers($text, $in_reply_to = null) // It is only safe to make assumptions on @users if only one reply to is given if (!is_array($in_reply_to) || (is_array($in_reply_to) && count($in_reply_to) == 1)) { - if (is_array($in_reply_to)) + if (is_array($in_reply_to)) { $in_reply_to = $in_reply_to[0]; + } - $r = preg_replace_callback($usermatch_regex, function ($matches) use ($in_reply_to) { - $url = $matches[1]; - - // Find and replace twitter - if (strpos($in_reply_to, 'twitter.com') !== false) { - return '' . $url . ''; - // Activate github - } else if (strpos($in_reply_to, 'github.com') !== false) { - return '' . $url . ''; - } else { - return \Idno\Core\Idno::site()->events()->triggerEvent("template/parseusers", [ - 'in_reply_to' => $in_reply_to, - 'in_reply_to_domain' => parse_url($in_reply_to, PHP_URL_HOST), - 'username' => ltrim($matches[1], '@'), - 'match' => $url - ], $url); - } - }, $text); + $r = preg_replace_callback( + $usermatch_regex, function ($matches) use ($in_reply_to) { + $url = $matches[1]; + + // Find and replace twitter + if (strpos($in_reply_to, 'twitter.com') !== false) { + return '' . $url . ''; + // Activate github + } else if (strpos($in_reply_to, 'github.com') !== false) { + return '' . $url . ''; + } else { + return \Idno\Core\Idno::site()->events()->triggerEvent( + "template/parseusers", [ + 'in_reply_to' => $in_reply_to, + 'in_reply_to_domain' => parse_url($in_reply_to, PHP_URL_HOST), + 'username' => ltrim($matches[1], '@'), + 'match' => $url + ], $url + ); + } + }, $text + ); } } else { // No in-reply, so we assume a local user - $r = preg_replace_callback($usermatch_regex, function ($matches) { - $url = $matches[1]; + $r = preg_replace_callback( + $usermatch_regex, function ($matches) { + $url = $matches[1]; - $username = ltrim($matches[1], '@'); + $username = ltrim($matches[1], '@'); - if ($user = User::getByHandle($username)) { - return '' . $url . ''; - } else { - return $url; - } + if ($user = User::getByHandle($username)) { + return '' . $url . ''; + } else { + return $url; + } - }, $text); + }, $text + ); } return $r; } - + } } \ No newline at end of file diff --git a/Idno/Core/Templating/SampleText.php b/Idno/Core/Templating/SampleText.php index 61b48a19a1..75d7821b91 100644 --- a/Idno/Core/Templating/SampleText.php +++ b/Idno/Core/Templating/SampleText.php @@ -2,13 +2,15 @@ namespace Idno\Core\Templating { - - trait SampleText { - + + trait SampleText + { + /** * Given HTML text, attempts to return text from the first $paras paragraphs - * @param $html_text - * @param int $paras Number of paragraphs to return; defaults to 1 + * + * @param $html_text + * @param int $paras Number of paragraphs to return; defaults to 1 * @return string */ function sampleParagraph($html_text, $paras = 1) @@ -27,8 +29,9 @@ function sampleParagraph($html_text, $paras = 1) /** * Returns a snippet of plain text - * @param $text - * @param int $words + * + * @param $text + * @param int $words * @return array|string */ function sampleText($text, $words = 32) @@ -37,12 +40,14 @@ function sampleText($text, $words = 32) $formatted_text = explode(' ', $formatted_text); $formatted_text = array_slice($formatted_text, 0, $words); $formatted_text = implode(' ', $formatted_text); - if (strlen($formatted_text) < strlen($text)) $formatted_text .= ' ...'; + if (strlen($formatted_text) < strlen($text)) { $formatted_text .= ' ...'; + } return $formatted_text; } /** * Return a snippet of plain text based on a number of characters. + * * @param type $text * @param type $chars */ @@ -52,23 +57,26 @@ function sampleTextChars($text, $chars = 250, $dots = '...') $length = strlen($text); // Short circuit if number of text is less than max chars - if ($length <= $chars) + if ($length <= $chars) { return $text; + } $formatted_text = substr($text, 0, $chars); $space = strrpos($formatted_text, ' ', 0); // No space, don't crop - if ($space === false) + if ($space === false) { $space = $chars; + } $formatted_text = trim(substr($formatted_text, 0, $space)); - if ($length != strlen($formatted_text)) + if ($length != strlen($formatted_text)) { $formatted_text .= $dots; + } return $formatted_text; } - + } } \ No newline at end of file diff --git a/Idno/Core/Templating/Urls.php b/Idno/Core/Templating/Urls.php index 35a7907dd7..174284e97b 100644 --- a/Idno/Core/Templating/Urls.php +++ b/Idno/Core/Templating/Urls.php @@ -2,31 +2,36 @@ namespace Idno\Core\Templating { - + use Idno\Core\{ Idno, Webservice }; - - trait Urls { - - + + trait Urls + { + + /** * Returns a version of the current page URL with the specified variable removed from the address line - * @param string $variable_name + * + * @param string $variable_name * @return string */ function getCurrentURLWithoutVar($variable_name) { $components = parse_url($this->getCurrentURL()); parse_str($components['query'], $url_var_array); - if (!empty($url_var_array[$variable_name])) unset($url_var_array[$variable_name]); + if (!empty($url_var_array[$variable_name])) { unset($url_var_array[$variable_name]); + } $components['query'] = http_build_query($url_var_array); $url = $components['scheme'] . '://' . $components['host'] . (!empty($components['port']) ? ':' . $components['port'] : '') . $components['path']; - if (!empty($components['query'])) $url .= '?' . $components['query']; + if (!empty($components['query'])) { $url .= '?' . $components['query']; + } return $url; } /** * Returns a sanitized version of the current page URL + * * @return string */ function getCurrentURL() @@ -50,7 +55,8 @@ function getCurrentURL() /** * Returns a version of the current page URL with the specified variable removed from the address line - * @param string $variable_name + * + * @param string $variable_name * @return string */ function getURLWithoutVar($url, $variable_name) @@ -60,19 +66,23 @@ function getURLWithoutVar($url, $variable_name) } $components = parse_url($url); $url_var_array = []; - if (!empty($components['query'])) parse_str($components['query'], $url_var_array); - if (!empty($url_var_array[$variable_name])) unset($url_var_array[$variable_name]); + if (!empty($components['query'])) { parse_str($components['query'], $url_var_array); + } + if (!empty($url_var_array[$variable_name])) { unset($url_var_array[$variable_name]); + } $components['query'] = http_build_query($url_var_array); $url = $components['scheme'] . '://' . $components['host'] . (!empty($components['port']) ? ':' . $components['port'] : '') . $components['path']; - if (!empty($components['query'])) $url .= '?' . $components['query']; + if (!empty($components['query'])) { $url .= '?' . $components['query']; + } return $url; } /** * Returns a version of the current page URL with the specified URL variable set to the specified value - * @param $variable_name - * @param $value + * + * @param $variable_name + * @param $value * @return string */ function getCurrentURLWithVar($variable_name, $value) @@ -86,15 +96,17 @@ function getCurrentURLWithVar($variable_name, $value) $url_var_array[$variable_name] = $value; $components['query'] = http_build_query($url_var_array); $url = $components['scheme'] . '://' . $components['host'] . (!empty($components['port']) ? ':' . $components['port'] : '') . $components['path']; - if (!empty($components['query'])) $url .= '?' . $components['query']; + if (!empty($components['query'])) { $url .= '?' . $components['query']; + } return $url; } /** * Returns a version of the current page URL with the specified variable added to the address line - * @param string $variable_name - * @param string $variable_value + * + * @param string $variable_name + * @param string $variable_value * @return string */ function getURLWithVar($variable_name, $variable_value, $url = '') @@ -116,7 +128,8 @@ function getURLWithVar($variable_name, $variable_value, $url = '') $url_var_array[$variable_name] = $variable_value; $components['query'] = http_build_query($url_var_array); $url = $components['scheme'] . '://' . $components['host'] . (!empty($components['port']) ? ':' . $components['port'] : '') . $components['path']; - if (!empty($components['query'])) $url .= '?' . $components['query']; + if (!empty($components['query'])) { $url .= '?' . $components['query']; + } if ($blank_scheme) { $url = str_replace($components['scheme'] . ':', '', $url); } @@ -127,37 +140,41 @@ function getURLWithVar($variable_name, $variable_value, $url = '') /** * Convert a remote image URL into one addressing the local image proxying service. - * @param url $url - * @param int Maximum dimensions of proxied image - * @param string Transformations. Currently only 'square' is supported. + * + * @param url $url + * @param int Maximum dimensions of proxied image + * @param string Transformations. Currently only 'square' is supported. * @return URL */ public function getProxiedImageUrl($url, $maxsize = null, $transform = null) { // Local urls, just relay. - if (\Idno\Common\Entity::isLocalUUID($url)) + if (\Idno\Common\Entity::isLocalUUID($url)) { return $url; + } // Map to local $proxied_url = \Idno\Core\Idno::site()->config()->getDisplayURL() . 'service/web/imageproxy/' . Webservice::base64UrlEncode($url); - if (!empty($maxsize)) + if (!empty($maxsize)) { $proxied_url .= '/' . (int)$maxsize; + } - if (!empty($transform)) + if (!empty($transform)) { $proxied_url .= '/' . $transform; + } return $proxied_url; } - - + + /** * Return a schema-less version of the given URL * - * @param $url - * @param $match_host If set to true (default), only changes the URI if the host matches the site's host + * @param $url + * @param $match_host If set to true (default), only changes the URI if the host matches the site's host * @return mixed */ function makeDisplayURL($url, $match_host = true) @@ -175,10 +192,11 @@ function makeDisplayURL($url, $match_host = true) return str_replace($scheme . ':', $newuri, $url); } - + /** * Given a URL, fixes it to have a prefix if it needs one - * @param $url + * + * @param $url * @return string */ function fixURL($url) @@ -204,9 +222,10 @@ function fixURL($url) ? $url : 'http://' . $url; } - + /** * Checks the current URL for `tag/` and passes this down. + * * @return string */ function getTag() diff --git a/Idno/Core/Templating/Variables.php b/Idno/Core/Templating/Variables.php index a74e60a536..2fdb719e13 100644 --- a/Idno/Core/Templating/Variables.php +++ b/Idno/Core/Templating/Variables.php @@ -1,12 +1,14 @@ __(['formFields' => $vars]); } - + /** * Should we render as `h-feed`? + * * @return bool */ - public function isHFeed() { + public function isHFeed() + { $classes = \Idno\Core\Idno::site()->template()->getBodyClasses(); return (strpos($classes, "homepage") || strpos($classes, "page-content") || strpos($classes, "page-tag")); } - + /** * Returns a version of this template with variable defaults set up for the shell - * @param $vars + * + * @param $vars * @return \Idno\Core\Bonita\Templates */ function formatShellVariables($vars) @@ -80,12 +86,14 @@ function formatShellVariables($vars) $vars['title_className'] = ' class="p-name"'; } - if (empty($vars['title'])) $vars['title'] = ''; - if (empty($vars['body'])) $vars['body'] = ''; + if (empty($vars['title'])) { $vars['title'] = ''; + } + if (empty($vars['body'])) { $vars['body'] = ''; + } return $this->__($vars); } - - + + } } diff --git a/Idno/Core/Themes.php b/Idno/Core/Themes.php index ddb8a6fbb4..b5d1ed2a80 100644 --- a/Idno/Core/Themes.php +++ b/Idno/Core/Themes.php @@ -3,7 +3,7 @@ /** * Theme management class * - * @package idno + * @package idno * @subpackage core */ @@ -67,6 +67,7 @@ public function init() /** * Retrieves the array of loaded theme objects + * * @return array */ public function get() @@ -76,6 +77,7 @@ public function get() /** * Retrieves a list of stored themes (but not necessarily loaded ones) + * * @return array */ public function getStored() diff --git a/Idno/Core/Time.php b/Idno/Core/Time.php index dde9e35fa5..2c197f7003 100644 --- a/Idno/Core/Time.php +++ b/Idno/Core/Time.php @@ -3,7 +3,7 @@ /** * Time and time manipulation functions. * - * @package idno + * @package idno * @subpackage core */ @@ -14,6 +14,7 @@ class Time extends \Idno\Common\Component /** * Convert an epoch timestamp into an RFC2616 (HTTP) compatible date. + * * @param type $timestamp Optionally, an epoch timestamp. Defaults to the current time. */ public static function timestampToRFC2616($timestamp = false) @@ -27,7 +28,8 @@ public static function timestampToRFC2616($timestamp = false) /** * Get the GMT offset from a timezone. - * @param string $timezone E.g as returned by $user->getTimezone() + * + * @param string $timezone E.g as returned by $user->getTimezone() * @return int Offset in seconds */ public static function timezoneToGMTOffset($timezone) @@ -42,7 +44,8 @@ public static function timezoneToGMTOffset($timezone) /** * Take the offset produced by timezoneToGMTOffset() and display it as a printable version. - * @param int $offset + * + * @param int $offset * @return string */ public static function printTimezoneOffset($offset) @@ -55,15 +58,18 @@ public static function printTimezoneOffset($offset) /** * Work out the difference between two timezones. - * @param type $timezone1 - * @param type $timezone2 + * + * @param type $timezone1 + * @param type $timezone2 * @return type */ public static function timezoneDiff($timezone1, $timezone2) { - if (empty($timezone1)) return false; - if (empty($timezone2)) return false; + if (empty($timezone1)) { return false; + } + if (empty($timezone2)) { return false; + } $offset1 = self::timezoneToGMTOffset($timezone1); $offset2 = self::timezoneToGMTOffset($timezone2); @@ -73,32 +79,38 @@ public static function timezoneDiff($timezone1, $timezone2) /** * Print the difference between two timezones in a human readable way. - * @param type $diff + * + * @param type $diff * @return string */ public static function printTimezoneDiff($diff) { - if ($diff == 0) + if ($diff == 0) { return ''; + } $hours = intval($diff / 3600); $minutes = abs(intval($diff % 3600 / 60)); if ($hours!=0) { - if ($hours == 1) + if ($hours == 1) { $hours = abs($hours) . ' ' . \Idno\Core\Idno::site()->language()->_('hour'); - else + } else { $hours = abs($hours) . ' ' . \Idno\Core\Idno::site()->language()->_('hours'); - } else + } + } else { $hours = ''; + } if ($minutes!=0) { - if ($minutes == 1) + if ($minutes == 1) { $minutes = abs($minutes) . ' ' . \Idno\Core\Idno::site()->language()->_('minute'); - else + } else { $minutes = abs($minutes) . ' ' . \Idno\Core\Idno::site()->language()->_('minutes'); - } else + } + } else { $minutes = ''; + } $time = ($diff > 0) ? \Idno\Core\Idno::site()->language()->_('ahead') : \Idno\Core\Idno::site()->language()->_('behind'); diff --git a/Idno/Core/TokenProvider.php b/Idno/Core/TokenProvider.php index 6bb477c0df..c329ad8cf2 100644 --- a/Idno/Core/TokenProvider.php +++ b/Idno/Core/TokenProvider.php @@ -10,6 +10,7 @@ class TokenProvider extends Component /** * Generate a cryptographically secure random token, returning it as a HEX encoded string. * Note: Hex is two chars per byte, so $length = 16 would produce a 32 char string (same length as md5(rand()), but more secure) + * * @param int $length Length in bytes */ function generateHexToken($length) @@ -19,7 +20,8 @@ function generateHexToken($length) /** * Generate a cryptographically secure random token. - * @param type $length Length in bytes + * + * @param type $length Length in bytes * @return bytes * @throws \Exception If cryptographic functions are not strong enough. */ @@ -39,7 +41,8 @@ function generateToken($length) * Helper that will return a partially redacted token for output. * Sometimes it is necessary to output a token, but you might not want * to output the whole thing since all you really want to know is if they're similar to another. - * @param string $token + * + * @param string $token * @return retacted token */ public static function truncateToken($token) diff --git a/Idno/Core/Translation.php b/Idno/Core/Translation.php index 819e6348a5..2248a844f4 100644 --- a/Idno/Core/Translation.php +++ b/Idno/Core/Translation.php @@ -14,12 +14,14 @@ abstract class Translation /** * Language this translation is for. + * * @var type */ protected $language; /** * Create this translation, for the defined language. + * * @param type $language Which language is this for? Default 'en_US' */ public function __construct($language = 'en_US') @@ -29,7 +31,8 @@ public function __construct($language = 'en_US') /** * Can this object provide the given language. - * @param type $language + * + * @param type $language * @return bool */ public function canProvide($language) diff --git a/Idno/Core/Vendor.php b/Idno/Core/Vendor.php index 52d5028963..5673d2816c 100644 --- a/Idno/Core/Vendor.php +++ b/Idno/Core/Vendor.php @@ -7,6 +7,7 @@ class Vendor extends \Idno\Common\Component /** * Retrieve notices (eg notifications that a new version has been released) from Known HQ + * * @return string */ public static function getMessages() @@ -16,9 +17,11 @@ public static function getMessages() return ''; } - $results = Webservice::post('https://withknown.com/vendor-services/messages/', [ + $results = Webservice::post( + 'https://withknown.com/vendor-services/messages/', [ 'version' => Version::version(), - ]); + ] + ); if ($results['response'] == 200) { return $results['content']; diff --git a/Idno/Core/Version.php b/Idno/Core/Version.php index 95da46df41..fb6fdceb99 100644 --- a/Idno/Core/Version.php +++ b/Idno/Core/Version.php @@ -13,13 +13,15 @@ class Version extends \Idno\Common\Component protected static function parse() { - if (!empty(static::$details)) + if (!empty(static::$details)) { return static::$details; + } $versionfile = dirname(dirname(dirname(__FILE__))) . '/version.known'; - if (!file_exists($versionfile)) + if (!file_exists($versionfile)) { throw new \Idno\Exceptions\ConfigurationException("Version file $versionfile could not be found, Known doesn't appear to be installed correctly."); + } static::$details = @parse_ini_file($versionfile); @@ -28,7 +30,8 @@ protected static function parse() /** * Retrieve a field from the version file. - * @param string $field + * + * @param string $field * @return boolean|string */ public static function get($field) @@ -36,14 +39,16 @@ public static function get($field) $version = static::parse(); - if (isset($version[$field])) + if (isset($version[$field])) { return $version[$field]; + } return false; } /** * Return the human readable version. + * * @return boolean|string */ public static function version() @@ -53,6 +58,7 @@ public static function version() /** * Return the machine version. + * * @return type */ public static function build() diff --git a/Idno/Core/Webfinger.php b/Idno/Core/Webfinger.php index a39e74dba2..09b8b9f701 100644 --- a/Idno/Core/Webfinger.php +++ b/Idno/Core/Webfinger.php @@ -3,7 +3,7 @@ /** * Service discovery (via webfinger) class * - * @package idno + * @package idno * @subpackage core */ diff --git a/Idno/Core/Webmention.php b/Idno/Core/Webmention.php index 9cf8a41a00..3454eae091 100644 --- a/Idno/Core/Webmention.php +++ b/Idno/Core/Webmention.php @@ -3,7 +3,7 @@ /** * Content announcement (via webmention) class * - * @package idno + * @package idno * @subpackage core */ @@ -16,6 +16,7 @@ class Webmention extends \Idno\Common\Component /** * Get the MentionClient singleton (initializes on first use). + * * @return \Idno\Core\MentionClient */ private static function mentionClient() @@ -33,8 +34,9 @@ private static function mentionClient() /** * Pings mentions from a given page to any linked pages - * @param $pageURL Page URL - * @param string $text The text to mine for links + * + * @param $pageURL Page URL + * @param string $text The text to mine for links * @return int The number of pings that were sent out */ static function pingMentions($pageURL, $text) @@ -56,8 +58,8 @@ static function pingMentions($pageURL, $text) /** * Send a webmention payload to a target without parsing HTML * - * @param $sourceURL - * @param $targetURL + * @param $sourceURL + * @param $targetURL * @return bool */ static function sendWebmentionPayload($sourceURL, $targetURL) @@ -67,8 +69,9 @@ static function sendWebmentionPayload($sourceURL, $targetURL) /** * Does the supplied page support webmentions? - * @param $pageURL - * @param bool $sourceBody + * + * @param $pageURL + * @param bool $sourceBody * @return mixed */ static function supportsMentions($pageURL, $sourceBody = false) @@ -80,9 +83,10 @@ static function supportsMentions($pageURL, $sourceBody = false) /** * Given an array of URLs (or an empty array) and a target URL to check, * adds and rel="syndication" URLs in the target to the array - * @param $url - * @param array $inreplyto - * @param array $response (optional) response from fetching $url + * + * @param $url + * @param array $inreplyto + * @param array $response (optional) response from fetching $url * @return array */ static function addSyndicatedReplyTargets($url, $inreplyto = array(), $response = false) @@ -124,8 +128,9 @@ static function addSyndicatedReplyTargets($url, $inreplyto = array(), $response /** * Parses a given set of HTML for Microformats 2 content - * @param $content HTML to parse - * @param $url Optionally, the source URL of the content, so relative URLs can be parsed into absolute ones + * + * @param $content HTML to parse + * @param $url Optionally, the source URL of the content, so relative URLs can be parsed into absolute ones * @return array */ static function parseContent($content, $url = null) @@ -144,9 +149,10 @@ static function parseContent($content, $url = null) * Given a microformats document, find the "primary" item of a given type or types. * Primary means either a) it is the only item of that type at the top level, * or b) it is the first item that has the current page as its u-url - * @param array $mf2 parsed mf2 document - * @param string $url the source url of the document - * @param array or string $types the type or types of an item to consider + * + * @param array $mf2 parsed mf2 document + * @param string $url the source url of the document + * @param array or string $types the type or types of an item to consider * @return the parsed mf2 item, or false */ static function findRepresentativeHEntry($mf2, $url, $types=['h-entry']) @@ -184,9 +190,10 @@ static function findRepresentativeHEntry($mf2, $url, $types=['h-entry']) /** * Given a mf2 entry, try to find its author h-card. First check its "author" * property. Then check the top-level h-cards. If there is one and only one, return it. - * @param array $mf2 the full parsed mf2 document - * @param string $url the url of the document - * @param array $item the mf2 item in question + * + * @param array $mf2 the full parsed mf2 document + * @param string $url the url of the document + * @param array $item the mf2 item in question * @return array|false an h-card representing the author of this document */ static function findAuthorHCard($mf2, $url, $item) @@ -233,8 +240,9 @@ static function findAuthorHCard($mf2, $url, $item) /** * Given a source and HTML content, return the value of the tag - * @param string $source_content the fetched HTML content - * @param string $source url for the source + * + * @param string $source_content the fetched HTML content + * @param string $source url for the source * @return string title of the document or its url if no title is found */ static function getTitleFromContent($source_content, $source) @@ -254,7 +262,8 @@ static function getTitleFromContent($source_content, $source) /** * Given content, returns the type of action you can respond with - * @param $content + * + * @param $content * @return string */ static function getActionTypeFromHTML($content) @@ -280,7 +289,8 @@ static function getActionTypeFromHTML($content) /** * Given a URL, returns a user icon (or false) - * @param $url + * + * @param $url * @return bool|string */ static function getIconFromURL($url) @@ -294,8 +304,9 @@ static function getIconFromURL($url) /** * Retrieve a user's icon from a given homepage - * @param $content The content of the page - * @param $url The URL of the page + * + * @param $content The content of the page + * @param $url The URL of the page * @return $icon_url */ static function getIconFromWebsiteContent($content, $url) @@ -311,8 +322,10 @@ static function getIconFromWebsiteContent($content, $url) switch ($type) { case 'h-card': if (!empty($item['properties'])) { - if (!empty($item['properties']['name'])) $mentions['owner']['name'] = $item['properties']['name'][0]; - if (!empty($item['properties']['url'])) $mentions['owner']['url'] = $item['properties']['url'][0]; + if (!empty($item['properties']['name'])) { $mentions['owner']['name'] = $item['properties']['name'][0]; + } + if (!empty($item['properties']['url'])) { $mentions['owner']['url'] = $item['properties']['url'][0]; + } if (!empty($item['properties']['photo'])) { return \Idno\Core\Idno::site()->template()->getProxiedImageUrl($item['properties']['photo'][0], 300, 'square'); @@ -344,25 +357,31 @@ function registerEventHooks() { // Add webmention headers to the top of the page - Idno::site()->events()->addListener('page/head', function (Event $event) { - if (!empty(site()->config()->hub)) { - $eventdata = $event->data(); - header('Link: <' . \Idno\Core\Idno::site()->config()->getURL() . 'webmention/>; rel="http://webmention.org/"', false); - header('Link: <' . \Idno\Core\Idno::site()->config()->getURL() . 'webmention/>; rel="webmention"', false); + Idno::site()->events()->addListener( + 'page/head', function (Event $event) { + if (!empty(site()->config()->hub)) { + $eventdata = $event->data(); + header('Link: <' . \Idno\Core\Idno::site()->config()->getURL() . 'webmention/>; rel="http://webmention.org/"', false); + header('Link: <' . \Idno\Core\Idno::site()->config()->getURL() . 'webmention/>; rel="webmention"', false); + } + } + ); + + Idno::site()->events()->addListener( + 'webmention/sendall', function (Event $event) { + $data = $event->data(); + $result = self::pingMentions($data['source'], $data['text']); + $event->setResponse($result); + } + ); + + Idno::site()->events()->addListener( + 'webmention/send', function (Event $event) { + $data = $event->data(); + $result = self::sendWebmentionPayload($data['source'], $data['target']); + $event->setResponse($result); } - }); - - Idno::site()->events()->addListener('webmention/sendall', function (Event $event) { - $data = $event->data(); - $result = self::pingMentions($data['source'], $data['text']); - $event->setResponse($result); - }); - - Idno::site()->events()->addListener('webmention/send', function (Event $event) { - $data = $event->data(); - $result = self::sendWebmentionPayload($data['source'], $data['target']); - $event->setResponse($result); - }); + ); } diff --git a/Idno/Core/Webservice.php b/Idno/Core/Webservice.php index ee599044d5..3e38c08182 100644 --- a/Idno/Core/Webservice.php +++ b/Idno/Core/Webservice.php @@ -3,7 +3,7 @@ /** * Utility methods for handling external web services * - * @package idno + * @package idno * @subpackage core */ @@ -17,9 +17,10 @@ class Webservice extends \Idno\Common\Component /** * Send a web services POST request to a specified URI endpoint - * @param string $endpoint The URI to send the POST request to - * @param mixed $params Optionally, an array of parameters to send (keys are the parameter names), or the raw body text (depending on Content-Type) - * @param array $headers Optionally, an array of headers to send with the request (keys are the header names) + * + * @param string $endpoint The URI to send the POST request to + * @param mixed $params Optionally, an array of parameters to send (keys are the parameter names), or the raw body text (depending on Content-Type) + * @param array $headers Optionally, an array of headers to send with the request (keys are the header names) * @return array */ static function post($endpoint, $params = null, array $headers = null) @@ -29,10 +30,11 @@ static function post($endpoint, $params = null, array $headers = null) /** * Send a web services request to a specified endpoint - * @param string $verb The verb to send the request with; one of POST, GET, DELETE, PUT - * @param string $endpoint The URI to send the request to - * @param mixed $params Optionally, an array of parameters to send (keys are the parameter names), or the raw body text (depending on Content-Type) - * @param array $headers Optionally, an array of headers to send with the request (keys are the header names) + * + * @param string $verb The verb to send the request with; one of POST, GET, DELETE, PUT + * @param string $endpoint The URI to send the request to + * @param mixed $params Optionally, an array of parameters to send (keys are the parameter names), or the raw body text (depending on Content-Type) + * @param array $headers Optionally, an array of headers to send with the request (keys are the header names) * @return array */ static function send($verb, $endpoint, $params = null, array $headers = null) @@ -41,7 +43,7 @@ static function send($verb, $endpoint, $params = null, array $headers = null) $curl_handle = curl_init(); // prevent curl from interpreting values starting with '@' as a filename. if (defined('CURLOPT_SAFE_UPLOAD')) { - curl_setopt($curl_handle, CURLOPT_SAFE_UPLOAD, TRUE); + curl_setopt($curl_handle, CURLOPT_SAFE_UPLOAD, true); } switch (strtolower($verb)) { @@ -78,7 +80,8 @@ static function send($verb, $endpoint, $params = null, array $headers = null) curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $params); curl_setopt($curl_handle, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data")); case 'head': - if ($verb == 'head') curl_setopt($curl_handle, CURLOPT_NOBODY, true); + if ($verb == 'head') { curl_setopt($curl_handle, CURLOPT_NOBODY, true); + } case 'get': default: $req = ""; @@ -136,11 +139,13 @@ static function send($verb, $endpoint, $params = null, array $headers = null) $sizeLimit = \Idno\Core\Idno::site()->config()->webservice_max_download; } - curl_setopt($curl_handle, CURLOPT_PROGRESSFUNCTION, function ($curl_handle, $totalBytes, $receivedBytes) use ($sizeLimit) { - if ($totalBytes > $sizeLimit) { - return 1; // return non-zero value to abort transfer + curl_setopt( + $curl_handle, CURLOPT_PROGRESSFUNCTION, function ($curl_handle, $totalBytes, $receivedBytes) use ($sizeLimit) { + if ($totalBytes > $sizeLimit) { + return 1; // return non-zero value to abort transfer + } } - }); + ); // Proxy connection string provided if (!empty(\Idno\Core\Idno::site()->config()->proxy_string)) { @@ -180,7 +185,8 @@ static function send($verb, $endpoint, $params = null, array $headers = null) // Allow plugins and other services to extend headers, allowing for plugable authentication methods on calls $new_headers = \Idno\Core\Idno::site()->events()->triggerEvent('webservice:headers', array('headers' => $headers, 'verb' => $verb)); if (!empty($new_headers) && (is_array($new_headers))) { - if (empty($headers)) $headers = array(); + if (empty($headers)) { $headers = array(); + } $headers = array_merge($headers, $new_headers); } @@ -221,8 +227,9 @@ static function send($verb, $endpoint, $params = null, array $headers = null) /** * Wrapper for curl_exec - * @param $ch - * @param null $maxredirect + * + * @param $ch + * @param null $maxredirect * @return bool|mixed */ static function webservice_exec($ch, &$maxredirect = null) @@ -257,9 +264,10 @@ static function webservice_exec($ch, &$maxredirect = null) /** * Send a web services HEAD request to a specified URI endpoint - * @param string $endpoint The URI to send the HEAD request to - * @param array $params Optionally, an array of parameters to send (keys are the parameter names) - * @param array $headers Optionally, an array of headers to send with the request (keys are the header names) + * + * @param string $endpoint The URI to send the HEAD request to + * @param array $params Optionally, an array of parameters to send (keys are the parameter names) + * @param array $headers Optionally, an array of headers to send with the request (keys are the header names) * @return array */ static function head($endpoint, array $params = null, array $headers = null) @@ -269,9 +277,10 @@ static function head($endpoint, array $params = null, array $headers = null) /** * Send a web services PUT request to a specified URI endpoint - * @param string $endpoint The URI to send the PUT request to - * @param mixed $params Optionally, an array of parameters to send (keys are the parameter names), or the raw body text (depending on Content-Type) - * @param array $headers Optionally, an array of headers to send with the request (keys are the header names) + * + * @param string $endpoint The URI to send the PUT request to + * @param mixed $params Optionally, an array of parameters to send (keys are the parameter names), or the raw body text (depending on Content-Type) + * @param array $headers Optionally, an array of headers to send with the request (keys are the header names) * @return array */ static function put($endpoint, $params = null, array $headers = null) @@ -281,9 +290,10 @@ static function put($endpoint, $params = null, array $headers = null) /** * Send a web services DELETE request to a specified URI endpoint - * @param string $endpoint The URI to send the DELETE request to - * @param array $params Optionally, an array of parameters to send (keys are the parameter names) - * @param array $headers Optionally, an array of headers to send with the request (keys are the header names) + * + * @param string $endpoint The URI to send the DELETE request to + * @param array $params Optionally, an array of parameters to send (keys are the parameter names) + * @param array $headers Optionally, an array of headers to send with the request (keys are the header names) * @return array */ static function delete($endpoint, array $params = null, array $headers = null) @@ -294,20 +304,23 @@ static function delete($endpoint, array $params = null, array $headers = null) /** * Replacement for file_get_contents for retrieving remote files. * Essentially a wrapper for self::get() + * * @param type $url */ static function file_get_contents($url) { $result = self::file_get_contents_ex($url); - if (!empty($result) && ($result['error'] == "")) + if (!empty($result) && ($result['error'] == "")) { return $result['content']; + } return false; } /** * Identical to Webservice::file_get_contents(), except that this function returns the full context - headers and all. + * * @param type $url */ static function file_get_contents_ex($url) @@ -334,9 +347,10 @@ static function file_get_contents_ex($url) /** * Send a web services GET request to a specified URI endpoint - * @param string $endpoint The URI to send the GET request to - * @param array $params Optionally, an array of parameters to send (keys are the parameter names) - * @param array $headers Optionally, an array of headers to send with the request (keys are the header names) + * + * @param string $endpoint The URI to send the GET request to + * @param array $params Optionally, an array of parameters to send (keys are the parameter names) + * @param array $headers Optionally, an array of headers to send with the request (keys are the header names) * @return array */ static function get($endpoint, array $params = null, array $headers = null) @@ -346,7 +360,8 @@ static function get($endpoint, array $params = null, array $headers = null) /** * Take a URL, check for a schema and add one if necessary - * @param $url + * + * @param $url * @return string|bool */ static function sanitizeURL($url) @@ -364,7 +379,8 @@ static function sanitizeURL($url) /** * Takes a query array and flattens it for use in a POST request (etc) - * @param $params + * + * @param $params * @return string */ static function flattenArrayToQuery($params) @@ -378,6 +394,7 @@ static function flattenArrayToQuery($params) /** * Retrieves the last HTTP request sent by the service client + * * @return string */ static function getLastRequest() @@ -387,6 +404,7 @@ static function getLastRequest() /** * Retrieves the last HTTP response sent to the service client + * * @return string */ static function getLastResponse() @@ -396,7 +414,8 @@ static function getLastResponse() /** * Converts an "@" formatted file string into a CurlFile - * @param type $fileuploadstring + * + * @param type $fileuploadstring * @return CURLFile|false */ static function fileToCurlFile($fileuploadstring) @@ -441,26 +460,31 @@ static function fileToCurlFile($fileuploadstring) /** * Wrapper function to encode a value for use in web services. * This way if we change the algorithm, there's no need to change the whole codebase. - * @param $string + * + * @param $string * @return string */ - static function encodeValue($string) { + static function encodeValue($string) + { return self::base64UrlEncode($string); } /** * Wrapper function to decode a value for use in web services. * This way if we change the algorithm, there's no need to change the whole codebase. - * @param $string + * + * @param $string * @return string */ - static function decodeValue($string) { + static function decodeValue($string) + { return self::base64UrlDecode($string); } /** * Utility method to produce URL safe base64 encoding. - * @param type $string + * + * @param type $string * @return string */ static function base64UrlEncode($string) @@ -470,7 +494,8 @@ static function base64UrlEncode($string) /** * Utility method to decode URL safe base64 encoding. - * @param type $string + * + * @param type $string * @return string */ static function base64UrlDecode($string) @@ -480,7 +505,8 @@ static function base64UrlDecode($string) /** * Check whether a given url has valid HSTS stored for it - * @todo Handle includeSubDomains + * + * @todo Handle includeSubDomains * @param type $url */ public static function isHSTS($url) @@ -523,7 +549,8 @@ public static function isHSTS($url) /** * Parse out HSTS headers, and if a url has HSTS headers, that status is cached. - * @param string $url The endpoint url + * + * @param string $url The endpoint url * @param string|array $headers */ public static function checkForHSTSHeader($url, $headers) @@ -531,8 +558,9 @@ public static function checkForHSTSHeader($url, $headers) \Idno\Core\Idno::site()->logging()->debug("Checking for HSTS headers"); - if (!is_array($headers)) + if (!is_array($headers)) { $headers = explode("\n", $headers); + } if (static::isHSTS($url)) { \Idno\Core\Idno::site()->logging()->debug("Valid HSTS found, no need to store"); @@ -545,7 +573,7 @@ public static function checkForHSTSHeader($url, $headers) if (!empty($headers)) { foreach ($headers as $line) { - if (stripos($line, 'Strict-Transport-Security:')!==false){ + if (stripos($line, 'Strict-Transport-Security:')!==false) { \Idno\Core\Idno::site()->logging()->debug("HSTS headers found in response"); diff --git a/Idno/Core/WebserviceFile.php b/Idno/Core/WebserviceFile.php index f97062831f..a7941b028b 100644 --- a/Idno/Core/WebserviceFile.php +++ b/Idno/Core/WebserviceFile.php @@ -3,7 +3,7 @@ /** * Utility wrapper around files that will be used in web service calls * - * @package idno + * @package idno * @subpackage core */ @@ -25,6 +25,7 @@ function __construct($file, $mime, $name) /** * Return curl parameters supported by your system. + * * @return \CURLFile|string */ function getCurlParameters() @@ -39,7 +40,8 @@ function getCurlParameters() /** * Converts an "@" formatted file string into a WebserviceFile - * @param type $fileuploadstring + * + * @param type $fileuploadstring * @return WebserviceFile|false */ static function createFromCurlString($fileuploadstring) diff --git a/Idno/Data/AbstractSQL.php b/Idno/Data/AbstractSQL.php index 95c99fbd75..9bada9b9cf 100644 --- a/Idno/Data/AbstractSQL.php +++ b/Idno/Data/AbstractSQL.php @@ -3,12 +3,12 @@ /** * MySQL back-end for Known data. * - * @package idno + * @package idno * @subpackage data */ namespace Idno\Data { - + use Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler; use Symfony\Component\HttpFoundation\Session\Session; @@ -51,6 +51,7 @@ function __construct($dbuser = null, $dbpass = null, $dbname = null, $dbhost = n /** * Retrieve built-in fields that shouldn't be searched using metadata + * * @return array */ function getSchemaFields() @@ -60,6 +61,7 @@ function getSchemaFields() /** * Retrieve version information from the schema + * * @return array|bool */ function getVersions() @@ -84,9 +86,9 @@ function getVersions() function handleSession() { session_set_save_handler( - new PdoSessionHandler( - $this->client, - [ + new PdoSessionHandler( + $this->client, + [ 'db_table' => 'session', 'db_id_col' => 'session_id', 'db_data_col' => 'session_value', @@ -94,12 +96,13 @@ function handleSession() 'db_lifetime_col' => 'session_lifetime', 'lock_mode' => PdoSessionHandler::LOCK_ADVISORY ] - ), true + ), true ); } /** * Returns an instance of the database reference variable + * * @return string; */ function getDatabase() @@ -109,6 +112,7 @@ function getDatabase() /** * Returns an instance of the database client reference variable + * * @return \PDO */ function getClient() @@ -118,7 +122,8 @@ function getClient() /** * SQL doesn't need the ID to be processed. - * @param $id + * + * @param $id * @return string */ function processID($id) @@ -131,19 +136,18 @@ function processID($id) * (or excluding kinds that we don't want to see), * in reverse chronological order * - * @param string|array $subtypes String or array of subtypes we're allowed to see - * @param array $search Any extra search terms in array format (eg array('foo' => 'bar')) (default: empty) - * @param array $fields An array of fieldnames to return (leave empty for all; default: all) - * @param int $limit Maximum number of records to return (default: 10) - * @param int $offset Number of records to skip (default: 0) - * @param string $collection Collection to query; default: entities - * @param array $readGroups Which ACL groups should we check? (default: everything the user can see) + * @param string|array $subtypes String or array of subtypes we're allowed to see + * @param array $search Any extra search terms in array format (eg array('foo' => 'bar')) (default: empty) + * @param array $fields An array of fieldnames to return (leave empty for all; default: all) + * @param int $limit Maximum number of records to return (default: 10) + * @param int $offset Number of records to skip (default: 0) + * @param string $collection Collection to query; default: entities + * @param array $readGroups Which ACL groups should we check? (default: everything the user can see) * @return array|false Array of elements or false, depending on success */ function getObjects($subtypes = '', $search = array(), $fields = array(), $limit = 10, $offset = 0, $collection = 'entities', $readGroups = []) { - // Initialize query parameters to be an empty array $query_parameters = array(); @@ -186,8 +190,9 @@ function getObjects($subtypes = '', $search = array(), $fields = array(), $limit $query_parameters['access'] = array('$in' => $readGroups); } - if ($this->getIgnoreAccess()) + if ($this->getIgnoreAccess()) { unset($query_parameters['access']); + } // Join the rest of the search query elements to this search $query_parameters = array_merge($query_parameters, $search); @@ -218,13 +223,12 @@ function getObjects($subtypes = '', $search = array(), $fields = array(), $limit /** * Count objects of a certain kind that we're allowed to see * - * @param string|array $subtypes String or array of subtypes we're allowed to see - * @param array $search Any extra search terms in array format (eg array('foo' => 'bar')) (default: empty) - * @param string $collection Collection to query; default: entities + * @param string|array $subtypes String or array of subtypes we're allowed to see + * @param array $search Any extra search terms in array format (eg array('foo' => 'bar')) (default: empty) + * @param string $collection Collection to query; default: entities */ function countObjects($subtypes = '', $search = array(), $collection = 'entities') { - // Initialize query parameters to be an empty array $query_parameters = array(); @@ -270,11 +274,11 @@ function countObjects($subtypes = '', $search = array(), $collection = 'entities $query_parameters = array_merge($query_parameters, $search); return $this->countRecords($query_parameters, $collection); - } /** * Get database errors + * * @return mixed */ function getErrors() @@ -289,6 +293,7 @@ function getErrors() /** * Retrieve the filesystem associated with the current db, suitable for saving * and retrieving files + * * @return bool */ function getFilesystem() @@ -299,14 +304,13 @@ function getFilesystem() /** * Given a text query, return an array suitable for adding into getFromX calls - * @param $query + * + * @param $query * @return array */ function createSearchArray($query) { return array('$search' => array($query)); } - } - } diff --git a/Idno/Data/Mongo.php b/Idno/Data/Mongo.php index 15700a2c27..485e0a62eb 100644 --- a/Idno/Data/Mongo.php +++ b/Idno/Data/Mongo.php @@ -6,16 +6,17 @@ * This is a wrapper for DataConcierge, but begins to move mongo specific settings * to its own class. * - * @package idno + * @package idno * @subpackage data */ namespace Idno\Data { -use Idno\Core\Idno; + use Idno\Core\Idno; -/** + /** * Mongo DB support. + * * @deprecated MongoDB support is being phased out, please use MySQL. */ class Mongo extends \Idno\Core\DataConcierge @@ -67,11 +68,15 @@ function __construct($dbstring = null, $dbuser = null, $dbpass = null, $dbname = function init() { try { - $this->client = new \MongoDB\Client($this->dbstring, array_filter([ - 'authSource' => $this->dbauthsrc, - 'username' => $this->dbuser, - 'password' => $this->dbpass, - ])); + $this->client = new \MongoDB\Client( + $this->dbstring, array_filter( + [ + 'authSource' => $this->dbauthsrc, + 'username' => $this->dbuser, + 'password' => $this->dbpass, + ] + ) + ); } catch (\MongoConnectionException $e) { http_response_code(500); $message = '<p>Unfortunately we couldn\'t connect to the database:</p><p>' . $e->getMessage() . '</p>'; @@ -89,65 +94,70 @@ function registerEventHooks() parent::registerEventHooks(); // Diagnostics - \Idno\Core\Idno::site()->events()->addListener('diagnostics/basics', function (\Idno\Core\Event $event) { - $basics = $event->response(); + \Idno\Core\Idno::site()->events()->addListener( + 'diagnostics/basics', function (\Idno\Core\Event $event) { + $basics = $event->response(); - try { - // See if your mongo driver has https://github.com/mongodb/mongo-php-driver/issues/270 - $a = [ + try { + // See if your mongo driver has https://github.com/mongodb/mongo-php-driver/issues/270 + $a = [ '_id' => new \MongoDB\BSON\ObjectID('000000000000000000000001'), 'test' => 1, 'aa' => [ 'b' => 1, ] - ]; + ]; - $b = serialize($a); - } catch (\Exception $ex) { - $basics['report']['mongo-bson']['message'] = "Your MongoDB driver doesn't support BSON serialisation, some functionality will not work correctly. You could try upgrading your driver - 'pecl install mongodb'."; - $basics['report']['mongo-bson']['status'] = 'Warning'; - } + $b = serialize($a); + } catch (\Exception $ex) { + $basics['report']['mongo-bson']['message'] = "Your MongoDB driver doesn't support BSON serialisation, some functionality will not work correctly. You could try upgrading your driver - 'pecl install mongodb'."; + $basics['report']['mongo-bson']['status'] = 'Warning'; + } - $event->setResponse($basics); - }); + $event->setResponse($basics); + } + ); - \Idno\Core\Idno::site()->events()->addListener('upgrade', function (\Idno\Core\Event $event) { + \Idno\Core\Idno::site()->events()->addListener( + 'upgrade', function (\Idno\Core\Event $event) { - $new_version = $event->data()['new_version']; - $last_update = $event->data()['last_update']; + $new_version = $event->data()['new_version']; + $last_update = $event->data()['last_update']; - if ($last_update < 2016042301) { + if ($last_update < 2016042301) { - \Idno\Core\Idno::site()->logging()->debug("Mongo: Applying mongo upgrades - adding index."); - $this->database->entities->createIndex(['created' => 1]); - } - if ($last_update < 2016110101) { - \Idno\Core\Idno::site()->logging()->debug("Mongo: Applying mongo upgrades - adding publish_status backfill."); + \Idno\Core\Idno::site()->logging()->debug("Mongo: Applying mongo upgrades - adding index."); + $this->database->entities->createIndex(['created' => 1]); + } + if ($last_update < 2016110101) { + \Idno\Core\Idno::site()->logging()->debug("Mongo: Applying mongo upgrades - adding publish_status backfill."); - $limit = 25; - $offset = 0; + $limit = 25; + $offset = 0; - set_time_limit(0); + set_time_limit(0); - while ($results = \Idno\Common\Entity::getFromAll([], [], $limit, $offset)) { + while ($results = \Idno\Common\Entity::getFromAll([], [], $limit, $offset)) { - foreach ($results as $item) { + foreach ($results as $item) { - if (empty($item->publish_status)) { - \Idno\Core\Idno::site()->logging()->debug("Setting publish status on " . get_class($item) . " " . $item->getUUID()); - $item->setPublishStatus(); - $item->save(); + if (empty($item->publish_status)) { + \Idno\Core\Idno::site()->logging()->debug("Setting publish status on " . get_class($item) . " " . $item->getUUID()); + $item->setPublishStatus(); + $item->save(); + } } - } - $offset += $limit; + $offset += $limit; + } } } - }); + ); } /** * Offer a session handler for the current session + * * @deprecated Mongo can no longer handle sessions. */ function handleSession() @@ -158,8 +168,8 @@ function handleSession() /** * Saves a record to the specified database collection * - * @param string $collection - * @param array $array + * @param string $collection + * @param array $array * @return MongoID | false */ function saveRecord($collection, $array) @@ -180,7 +190,7 @@ function saveRecord($collection, $array) // Store if ($result = $collection_obj->insertOne($array, array('w' => 1))) { - if ($result->isAcknowledged() && ($result->getInsertedCount() > 0)){ + if ($result->isAcknowledged() && ($result->getInsertedCount() > 0)) { $array['_id'] = $result->getInsertedId(); @@ -201,7 +211,7 @@ function saveRecord($collection, $array) * Make an array safe for storage in Mongo. This means * %-escaping all .'s and $'s. * - * @param mixed $obj an array, scalar value, or null + * @param mixed $obj an array, scalar value, or null * @return mixed */ function sanitizeFields($obj) @@ -241,8 +251,8 @@ function sanitizeFields($obj) /** * Retrieves a record from the database by its UUID * - * @param string $id - * @param string $collection The collection to retrieve from (default: entities) + * @param string $id + * @param string $collection The collection to retrieve from (default: entities) * @return array */ function getRecordByUUID($uuid, $collection = 'entities') @@ -256,7 +266,7 @@ function getRecordByUUID($uuid, $collection = 'entities') * Restore an object's fields after removing it from * storage. * - * @param mixed $obj an array, scalar value, or null + * @param mixed $obj an array, scalar value, or null * @return mixed */ function unsanitizeFields($obj) @@ -284,7 +294,8 @@ function unsanitizeFields($obj) $orig_k = $k; $k = str_replace(array_values(self::$ESCAPE_SEQUENCES), array_keys(self::$ESCAPE_SEQUENCES), $k); $obj[$k] = $this->unsanitizeFields($v); - if ($k!=$orig_k) unset($obj[$orig_k]); + if ($k!=$orig_k) { unset($obj[$orig_k]); + } } } else if (is_array($obj)) { $result = []; @@ -292,7 +303,8 @@ function unsanitizeFields($obj) $orig_k = $k; $k = str_replace(array_values(self::$ESCAPE_SEQUENCES), array_keys(self::$ESCAPE_SEQUENCES), $k); $result[$k] = $this->unsanitizeFields($v); - if ($k!=$orig_k) unset($obj[$orig_k]); + if ($k!=$orig_k) { unset($obj[$orig_k]); + } } return $result; @@ -304,7 +316,8 @@ function unsanitizeFields($obj) /** * Process the ID appropriately - * @param $id + * + * @param $id * @return \MongoDB\BSON\ObjectID */ function processID($id) @@ -315,7 +328,7 @@ function processID($id) /** * Generate an ID. Not used in Mongo */ - public function generateID() : string + public function generateID() : string { throw new \RuntimeException('generateID() should not be used for Mongo'); } @@ -323,8 +336,8 @@ public function generateID() : string /** * Retrieves a record from the database by ID * - * @param string $id - * @param string $entities The collection name to retrieve from (default: 'entities') + * @param string $id + * @param string $entities The collection name to retrieve from (default: 'entities') * @return array */ function getRecord($id, $collection = 'entities') @@ -337,7 +350,7 @@ function getRecord($id, $collection = 'entities') /** * Retrieves ANY record from a collection * - * @param string $collection + * @param string $collection * @return array */ function getAnyRecord($collection = 'entities') @@ -352,13 +365,13 @@ function getAnyRecord($collection = 'entities') * (or excluding kinds that we don't want to see), * in reverse chronological order * - * @param string|array $subtypes String or array of subtypes we're allowed to see - * @param array $search Any extra search terms in array format (eg array('foo' => 'bar')) (default: empty) - * @param array $fields An array of fieldnames to return (leave empty for all; default: all) - * @param int $limit Maximum number of records to return (default: 10) - * @param int $offset Number of records to skip (default: 0) - * @param string $collection Collection to query; default: entities - * @param array $readGroups Which ACL groups should we check? (default: everything the user can see) + * @param string|array $subtypes String or array of subtypes we're allowed to see + * @param array $search Any extra search terms in array format (eg array('foo' => 'bar')) (default: empty) + * @param array $fields An array of fieldnames to return (leave empty for all; default: all) + * @param int $limit Maximum number of records to return (default: 10) + * @param int $offset Number of records to skip (default: 0) + * @param string $collection Collection to query; default: entities + * @param array $readGroups Which ACL groups should we check? (default: everything the user can see) * @return array|false Array of elements or false, depending on success */ function getObjects($subtypes = '', $search = array(), $fields = array(), $limit = 10, $offset = 0, $collection = 'entities', $readGroups = []) @@ -397,8 +410,9 @@ function getObjects($subtypes = '', $search = array(), $fields = array(), $limit $query_parameters['access'] = array('$in' => $readGroups); } - if ($this->getIgnoreAccess()) + if ($this->getIgnoreAccess()) { unset($query_parameters['access']); + } // Join the rest of the search query elements to this search $query_parameters = array_merge($query_parameters, $search); @@ -428,10 +442,10 @@ function getObjects($subtypes = '', $search = array(), $fields = array(), $limit * Retrieves a set of records from the database with given parameters, in * reverse chronological order * - * @param array $parameters Query parameters in MongoDB format - * @param int $limit Maximum number of records to return - * @param int $offset Number of records to skip - * @param string $collection The collection to interrogate (default: 'entities') + * @param array $parameters Query parameters in MongoDB format + * @param int $limit Maximum number of records to return + * @param int $offset Number of records to skip + * @param string $collection The collection to interrogate (default: 'entities') * @return iterator|false Iterator or false, depending on success */ function getRecords($fields, $parameters, $limit, $offset, $collection = 'entities') @@ -470,14 +484,14 @@ function getRecords($fields, $parameters, $limit, $offset, $collection = 'entiti /** * Export a collection to JSON. - * @param string $collection + * + * @param string $collection * @return bool|string */ function exportRecords($collection = 'entities', $limit = 10, $offset = 0) { try { - if ($result = $this->getRecords([], [], $limit, $offset, $collection)) - { + if ($result = $this->getRecords([], [], $limit, $offset, $collection)) { return json_encode($result, JSON_PRETTY_PRINT); } } catch (\Exception $e) { @@ -490,9 +504,9 @@ function exportRecords($collection = 'entities', $limit = 10, $offset = 0) /** * Count objects of a certain kind that we're allowed to see * - * @param string|array $subtypes String or array of subtypes we're allowed to see - * @param array $search Any extra search terms in array format (eg array('foo' => 'bar')) (default: empty) - * @param string $collection Collection to query; default: entities + * @param string|array $subtypes String or array of subtypes we're allowed to see + * @param array $search Any extra search terms in array format (eg array('foo' => 'bar')) (default: empty) + * @param string $collection Collection to query; default: entities */ function countObjects($subtypes = '', $search = array(), $collection = 'entities') { @@ -536,8 +550,9 @@ function countObjects($subtypes = '', $search = array(), $collection = 'entities /** * Count the number of records that match the given parameters - * @param array $parameters - * @param string $collection The collection to interrogate (default: 'entities') + * + * @param array $parameters + * @param string $collection The collection to interrogate (default: 'entities') * @return int */ function countRecords($parameters, $collection = 'entities') @@ -551,7 +566,8 @@ function countRecords($parameters, $collection = 'entities') /** * Remove an entity from the database - * @param string $id + * + * @param string $id * @return true|false */ function deleteRecord($id, $collection = 'entities') @@ -561,18 +577,21 @@ function deleteRecord($id, $collection = 'entities') /** * Removes all items from a collection - * @param string $collection + * + * @param string $collection * @return bool */ function deleteAllRecords($collection) { - if (empty($collection)) return false; + if (empty($collection)) { return false; + } return $this->database->$collection->drop(); } /** * Retrieve the filesystem associated with the current db, suitable for saving * and retrieving files + * * @return bool|\MongoGridFS */ function getFilesystem() @@ -586,7 +605,8 @@ function getFilesystem() /** * Given a text query, return an array suitable for adding into getFromX calls - * @param $query + * + * @param $query * @return array */ function createSearchArray($query) diff --git a/Idno/Data/MySQL.php b/Idno/Data/MySQL.php index 1bf62b2f0e..8dca366c7c 100644 --- a/Idno/Data/MySQL.php +++ b/Idno/Data/MySQL.php @@ -3,7 +3,7 @@ /** * MySQL back-end for Known data. * - * @package idno + * @package idno * @subpackage data */ @@ -54,7 +54,8 @@ function init() function checkAndUpgradeSchema() { $versions = $this->getVersions(); - if (!$versions) $versions = [(object)['label' => 'schema', 'value' => 0]]; + if (!$versions) { $versions = [(object)['label' => 'schema', 'value' => 0]]; + } if ($versions) { foreach ($versions as $version) { if ($version->label === 'schema') { @@ -103,7 +104,8 @@ function checkAndUpgradeSchema() } catch (\Exception $e) { error_log($e->getMessage()); - if ($client->inTransaction()) $client->rollback(); + if ($client->inTransaction()) { $client->rollback(); + } } } } @@ -114,6 +116,7 @@ function checkAndUpgradeSchema() /** * Optimize tables - this can reduce overall database storage space and query time + * * @return bool */ function optimize() @@ -138,6 +141,7 @@ function optimize() /** * Returns an instance of the database reference variable + * * @return string; */ function getDatabase() @@ -147,6 +151,7 @@ function getDatabase() /** * Returns an instance of the database client reference variable + * * @return \PDO */ function getClient() @@ -156,7 +161,8 @@ function getClient() /** * MySQL doesn't need the ID to be processed. - * @param $id + * + * @param $id * @return string */ function processID($id) @@ -167,8 +173,8 @@ function processID($id) /** * Saves a record to the specified database collection * - * @param string $collection - * @param array $array + * @param string $collection + * @param array $array * @return int | false */ @@ -192,8 +198,9 @@ function saveRecord($collection, $array) try { $contents = json_encode($array); - if (json_last_error() != JSON_ERROR_NONE) + if (json_last_error() != JSON_ERROR_NONE) { throw new \Exception(json_last_error_msg()); + } } catch (\Exception $e) { $contents = json_encode([]); @@ -254,22 +261,25 @@ function saveRecord($collection, $array) $benchmark_start = microtime(true); try { $client->beginTransaction(); - $statement = $client->prepare("insert into {$collection} + $statement = $client->prepare( + "insert into {$collection} (`uuid`, `_id`, `siteid`, `entity_subtype`,`owner`, `contents`, `publish_status`, `created`) values (:uuid, :id, :siteid, :subtype, :owner, :contents, :publish_status, :created) - on duplicate key update `uuid` = :uuid, `entity_subtype` = :subtype, `owner` = :owner, `contents` = :contents, `publish_status` = :publish_status, `created` = :created"); + on duplicate key update `uuid` = :uuid, `entity_subtype` = :subtype, `owner` = :owner, `contents` = :contents, `publish_status` = :publish_status, `created` = :created" + ); if ($statement->execute(array(':uuid' => $array['uuid'], ':id' => $array['_id'], ':siteid' => $array['siteid'], ':owner' => $array['owner'], ':subtype' => $array['entity_subtype'], ':contents' => $contents, ':publish_status' => $array['publish_status'], ':created' => $array['created']))) { // Update FTS - $statement = $client->prepare("insert into {$collection}_search + $statement = $client->prepare( + "insert into {$collection}_search (`_id`, `search`) values (:id, :search) - on duplicate key update `search` = :search"); + on duplicate key update `search` = :search" + ); $statement->execute(array(':id' => $array['_id'], ':search' => $search)); - $retval = $array['_id']; if ($statement = $client->prepare("delete from {$collection}_metadata where _id = :id")) { $statement->execute(array(':id' => $array['_id'])); @@ -284,8 +294,9 @@ function saveRecord($collection, $array) try { $value = json_encode($value); - if (json_last_error() != JSON_ERROR_NONE) + if (json_last_error() != JSON_ERROR_NONE) { throw new \Exception(json_last_error_msg()); + } } catch (\Exception $e) { $value = json_encode([]); \Idno\Core\Idno::site()->logging()->error($e->getMessage()); @@ -317,8 +328,8 @@ function saveRecord($collection, $array) /** * Retrieves a record from the database by its UUID * - * @param string $id - * @param string $collection The collection to retrieve from (default: entities) + * @param string $id + * @param string $collection The collection to retrieve from (default: entities) * @return array */ @@ -343,8 +354,8 @@ function getRecordByUUID($uuid, $collection = 'entities') /** * Retrieves a record from the database by ID * - * @param string $id - * @param string $entities The collection name to retrieve from (default: 'entities') + * @param string $id + * @param string $entities The collection name to retrieve from (default: 'entities') * @return array */ @@ -369,7 +380,7 @@ function getRecord($id, $collection = 'entities') /** * Retrieves ANY record from a collection * - * @param string $collection + * @param string $collection * @return array */ function getAnyRecord($collection = 'entities') @@ -384,8 +395,9 @@ function getAnyRecord($collection = 'entities') } } } catch (\Exception $e) { - if (\Idno\Core\Idno::site()->session() == null) + if (\Idno\Core\Idno::site()->session() == null) { throw $e; // Throw exception up if the session isn't set + } } return false; @@ -395,10 +407,10 @@ function getAnyRecord($collection = 'entities') * Retrieves a set of records from the database with given parameters, in * reverse chronological order * - * @param array $parameters Query parameters in MongoDB format - * @param int $limit Maximum number of records to return - * @param int $offset Number of records to skip - * @param string $collection The collection to interrogate (default: 'entities') + * @param array $parameters Query parameters in MongoDB format + * @param int $limit Maximum number of records to return + * @param int $offset Number of records to skip + * @param string $collection The collection to interrogate (default: 'entities') * @return iterator|false Iterator or false, depending on success */ @@ -454,12 +466,13 @@ function getRecords($fields, $parameters, $limit, $offset, $collection = 'entiti /** * Recursive function that takes an array of parameters and returns an array of clauses suitable * for compiling into an SQL query + * * @param $params * @param $where * @param $variables * @param $metadata_joins * @param $non_md_variables - * @param string $clause Defaults to 'and' + * @param string $clause Defaults to 'and' */ function build_where_from_array($params, &$variables, &$metadata_joins, &$non_md_variables, $clause = 'and', $collection = 'entities') { @@ -501,7 +514,8 @@ function build_where_from_array($params, &$variables, &$metadata_joins, &$non_md $notstring = "`{$collection}`.`$key` not in ("; $i = 0; foreach ($value['$not']['$in'] as $val) { - if ($i > 0) $notstring .= ', '; + if ($i > 0) { $notstring .= ', '; + } $notstring .= ":nonmdvalue{$non_md_variables}"; $variables[":nonmdvalue{$non_md_variables}"] = $val; $non_md_variables++; @@ -514,7 +528,8 @@ function build_where_from_array($params, &$variables, &$metadata_joins, &$non_md $variables[":name{$metadata_joins}"] = $key; $i = 0; foreach ($value['$not']['$in'] as $val) { - if ($i > 0) $notstring .= ', '; + if ($i > 0) { $notstring .= ', '; + } $notstring .= ":nonmdvalue{$non_md_variables}"; $variables[":nonmdvalue{$non_md_variables}"] = $val; $non_md_variables++; @@ -542,7 +557,8 @@ function build_where_from_array($params, &$variables, &$metadata_joins, &$non_md $instring = "`{$collection}`.`$key` in ("; $i = 0; foreach ($value['$in'] as $val) { - if ($i > 0) $instring .= ', '; + if ($i > 0) { $instring .= ', '; + } $instring .= ":nonmdvalue{$non_md_variables}"; $variables[":nonmdvalue{$non_md_variables}"] = $val; $non_md_variables++; @@ -555,7 +571,8 @@ function build_where_from_array($params, &$variables, &$metadata_joins, &$non_md $variables[":name{$metadata_joins}"] = $key; $i = 0; foreach ($value['$in'] as $val) { - if ($i > 0) $instring .= ', '; + if ($i > 0) { $instring .= ', '; + } $instring .= ":nonmdvalue{$non_md_variables}"; $variables[":nonmdvalue{$non_md_variables}"] = $val; $non_md_variables++; @@ -634,7 +651,8 @@ function build_where_from_array($params, &$variables, &$metadata_joins, &$non_md /** * Export a collection as SQL. - * @param string $collection + * + * @param string $collection * @return bool|string */ function exportRecords($collection = 'entities', $limit = 10, $offset = 0) @@ -653,12 +671,16 @@ function exportRecords($collection = 'entities', $limit = 10, $offset = 0) while ($object = $statement->fetch(\PDO::FETCH_ASSOC)) { $uuid = $object['uuid']; $fields = array_keys($object); - $fields = array_map(function ($v) { - return '`' . $v . '`'; - }, $fields); - $object = array_map(function ($v) { - return \Idno\Core\Idno::site()->db()->getClient()->quote($v); - }, $object); + $fields = array_map( + function ($v) { + return '`' . $v . '`'; + }, $fields + ); + $object = array_map( + function ($v) { + return \Idno\Core\Idno::site()->db()->getClient()->quote($v); + }, $object + ); $line = 'insert into ' . $collection . ' '; $line .= '(' . implode(',', $fields) . ')'; $line .= ' values '; @@ -668,12 +690,16 @@ function exportRecords($collection = 'entities', $limit = 10, $offset = 0) if ($metadata_response = $metadata_statement->execute([':uuid' => $uuid])) { while ($object = $metadata_statement->fetch(\PDO::FETCH_ASSOC)) { $fields = array_keys($object); - $fields = array_map(function ($v) { - return '`' . $v . '`'; - }, $fields); - $object = array_map(function ($v) { - return \Idno\Core\Idno::site()->db()->getClient()->quote($v); - }, $object); + $fields = array_map( + function ($v) { + return '`' . $v . '`'; + }, $fields + ); + $object = array_map( + function ($v) { + return \Idno\Core\Idno::site()->db()->getClient()->quote($v); + }, $object + ); $line = "insert into {$collection}_metadata "; $line .= '(' . implode(',', $fields) . ')'; $line .= ' values '; @@ -702,8 +728,9 @@ function exportRecords($collection = 'entities', $limit = 10, $offset = 0) /** * Count the number of records that match the given parameters - * @param array $parameters - * @param string $collection The collection to interrogate (default: 'entities') + * + * @param array $parameters + * @param string $collection The collection to interrogate (default: 'entities') * @return int */ function countRecords($parameters, $collection = 'entities') @@ -748,7 +775,8 @@ function countRecords($parameters, $collection = 'entities') /** * Remove an entity from the database - * @param string $id + * + * @param string $id * @return true|false */ function deleteRecord($id, $collection = 'entities') @@ -763,12 +791,12 @@ function deleteRecord($id, $collection = 'entities') return $statement->execute(array(':id' => $id)); // Don't need to explicitly delete metadata now due to cascade -// if ($statement->execute(array(':id' => $id))) { -// -// if ($statement = $client->prepare("delete from metadata where _id = :id")) { -// return $statement->execute(array(':id' => $id)); -// } -// } + // if ($statement->execute(array(':id' => $id))) { + // + // if ($statement = $client->prepare("delete from metadata where _id = :id")) { + // return $statement->execute(array(':id' => $id)); + // } + // } } catch (\Exception $e) { @@ -783,13 +811,15 @@ function deleteRecord($id, $collection = 'entities') /** * Remove all entities from a collection from the database - * @param string $collection + * + * @param string $collection * @return bool */ function deleteAllRecords($collection) { try { - if (empty($collection)) return false; + if (empty($collection)) { return false; + } $collection = $this->sanitiseCollection($collection); $client = $this->client; @@ -797,15 +827,15 @@ function deleteAllRecords($collection) $statement = $client->prepare("delete from {$collection}"); return $statement->execute(); -// if ($statement->execute()) { -// -// $statement = $client->prepare("delete from {$collection}_search"); -// $statement->execute(); -// -// if ($statement = $client->prepare("delete from metadata where collection = :collection")) { -// return $statement->execute([':collection' => $collection]); -// } -// } + // if ($statement->execute()) { + // + // $statement = $client->prepare("delete from {$collection}_search"); + // $statement->execute(); + // + // if ($statement = $client->prepare("delete from metadata where collection = :collection")) { + // return $statement->execute([':collection' => $collection]); + // } + // } } catch (\Exception $e) { \Idno\Core\Idno::site()->logging()->error($e->getMessage()); return false; diff --git a/Idno/Entities/AccessGroup.php b/Idno/Entities/AccessGroup.php index f9e4da80f6..b43dcfbde2 100644 --- a/Idno/Entities/AccessGroup.php +++ b/Idno/Entities/AccessGroup.php @@ -3,7 +3,7 @@ /** * Access group representation * - * @package idno + * @package idno * @subpackage core */ @@ -14,6 +14,7 @@ class AccessGroup extends \Idno\Common\Entity /** * On initial creation, make sure access groups have a members property + * * @return mixed */ function __construct() @@ -35,15 +36,19 @@ function __construct() * Can the specified user (or the currently logged-in user) access * content in this access group? * - * @param string $user_id The user ID (optional) + * @param string $user_id The user ID (optional) * @return true|false */ function canRead($user_id = '') { - if (empty($user_id)) $user_id = \Idno\Core\Idno::site()->session()->currentUser()->uuid; - if ($this->getOwnerID() == $user_id) return true; - if ($this->isMember($user_id)) return true; - if ($this->access == 'PUBLIC') return true; + if (empty($user_id)) { $user_id = \Idno\Core\Idno::site()->session()->currentUser()->uuid; + } + if ($this->getOwnerID() == $user_id) { return true; + } + if ($this->isMember($user_id)) { return true; + } + if ($this->access == 'PUBLIC') { return true; + } return false; } @@ -52,12 +57,13 @@ function canRead($user_id = '') * Is the specified user (or the currently logged-in user) a member * of this access group? * - * @param type $user_id + * @param type $user_id * @return type */ function isMember($user_id = '', $access = 'read') { - if (empty($user_id)) $user_id = \Idno\Core\Idno::site()->session()->currentUser()->uuid; + if (empty($user_id)) { $user_id = \Idno\Core\Idno::site()->session()->currentUser()->uuid; + } if (!empty($this->$access) && is_array($this->$access) && (array_search($user_id, $this->$access) !== false)) { return true; } @@ -69,14 +75,17 @@ function isMember($user_id = '', $access = 'read') * Can the specified user (or the currently logged-in user) publish * content to this access group? * - * @param string $user_id The user ID (optional) + * @param string $user_id The user ID (optional) * @return true|false */ function canPublish($user_id = '') { - if (empty($user_id)) $user_id = \Idno\Core\Idno::site()->session()->currentUser()->uuid; - if ($this->getOwnerID() == $user_id) return true; - if ($this->isMember($user_id, 'write')) return true; + if (empty($user_id)) { $user_id = \Idno\Core\Idno::site()->session()->currentUser()->uuid; + } + if ($this->getOwnerID() == $user_id) { return true; + } + if ($this->isMember($user_id, 'write')) { return true; + } return false; } @@ -84,7 +93,7 @@ function canPublish($user_id = '') /** * Adds a specified user to the access group * - * @param string $user_id The user UUID + * @param string $user_id The user UUID * @return true|false */ function addMember($user_id, $access = 'read') @@ -104,14 +113,17 @@ function addMember($user_id, $access = 'read') * Can the specified user (or the currently logged-in user) administer * this access group? * - * @param string $user_id The user ID (optional) + * @param string $user_id The user ID (optional) * @return true|false */ function canEdit($user_id = '') { - if (empty($user_id)) $user_id = \Idno\Core\Idno::site()->session()->currentUser()->uuid; - if ($this->getOwnerID() == $user_id) return true; - if ($this->isMember($user_id, 'admin')) return true; + if (empty($user_id)) { $user_id = \Idno\Core\Idno::site()->session()->currentUser()->uuid; + } + if ($this->getOwnerID() == $user_id) { return true; + } + if ($this->isMember($user_id, 'admin')) { return true; + } return false; } @@ -119,7 +131,7 @@ function canEdit($user_id = '') /** * Removes a specified user from the access group * - * @param string $user_id The user UUID + * @param string $user_id The user UUID * @return true|false */ function removeMember($user_id, $access = 'read') @@ -137,11 +149,12 @@ function removeMember($user_id, $access = 'read') /** * Get entities by access group. - * @param mixed $access_group - * @param type $search - * @param type $fields - * @param type $limit - * @param type $offset + * + * @param mixed $access_group + * @param type $search + * @param type $fields + * @param type $limit + * @param type $offset * @return boolean */ static function getByAccessGroup($access_group, $search = array(), $fields = array(), $limit = 10, $offset = 0) diff --git a/Idno/Entities/BaseObject.php b/Idno/Entities/BaseObject.php index c78f60baeb..47a9c43e62 100644 --- a/Idno/Entities/BaseObject.php +++ b/Idno/Entities/BaseObject.php @@ -3,7 +3,7 @@ /** * User-created object representation * - * @package idno + * @package idno * @subpackage core */ diff --git a/Idno/Entities/File.php b/Idno/Entities/File.php index de78735e56..92f7cd439f 100644 --- a/Idno/Entities/File.php +++ b/Idno/Entities/File.php @@ -3,7 +3,7 @@ /** * User-created file representation * - * @package idno + * @package idno * @subpackage core */ @@ -15,6 +15,7 @@ class File /** * Write data to temporary file. * This function writes a temporary file, returning filename on success. + * * @param type $data */ public static function writeTmpFile($data) @@ -32,10 +33,11 @@ public static function writeTmpFile($data) /** * Given a path to an image on disk, generates and saves a thumbnail with maximum dimension $max_dimension. - * @param string $file_path Path to the file. - * @param string $filename Filename that the file should have on download. - * @param int $max_dimension The maximum number of pixels the thumbnail image should be along its longest side. - * @param bool $square If this is set to true, the thumbnail will be made square. + * + * @param string $file_path Path to the file. + * @param string $filename Filename that the file should have on download. + * @param int $max_dimension The maximum number of pixels the thumbnail image should be along its longest side. + * @param bool $square If this is set to true, the thumbnail will be made square. * @return bool|id */ public static function createThumbnailFromFile($file_path, $filename, $max_dimension = 800, $square = false) @@ -47,7 +49,8 @@ public static function createThumbnailFromFile($file_path, $filename, $max_dimen if (is_callable('exif_read_data')) { try { if ($exif = exif_read_data($file_path)) { - if (!empty($exif['Orientation'])) $orientation = $exif['Orientation']; + if (!empty($exif['Orientation'])) { $orientation = $exif['Orientation']; + } } } catch (\Exception $e) { } @@ -155,11 +158,11 @@ public static function createThumbnailFromFile($file_path, $filename, $max_dimen /** * Save a file to the filesystem and return the ID * - * @param string $file_path Full local path to the file - * @param string $filename Filename to store - * @param string $mime_type MIME type associated with the file - * @param bool $return_object Return the file object? If set to false (as is default), will return the ID - * @param bool $destroy_exif When true, if an image is uploaded the exif data will be destroyed. + * @param string $file_path Full local path to the file + * @param string $filename Filename to store + * @param string $mime_type MIME type associated with the file + * @param bool $return_object Return the file object? If set to false (as is default), will return the ID + * @param bool $destroy_exif When true, if an image is uploaded the exif data will be destroyed. * @return bool|\id Depending on success */ public static function createFromFile($file_path, $filename, $mime_type = 'application/octet-stream', $return_object = false, $destroy_exif = false) @@ -235,7 +238,8 @@ public static function createFromFile($file_path, $filename, $mime_type = 'appli /** * Determines whether a file is an image or not. - * @param string $file_path The path to a file + * + * @param string $file_path The path to a file * @return bool */ public static function isImage($file_path) @@ -251,7 +255,8 @@ public static function isImage($file_path) /** * Retrieve a file by ID - * @param string $id + * + * @param string $id * @return \Idno\Common\Entity|\MongoGridFSFile|null */ static function getByID($id) @@ -269,7 +274,8 @@ static function getByID($id) /** * Given a file and an original file path, determines whether this file is an SVG - * @param $file_path + * + * @param $file_path * @return bool */ public static function isSVG($file_path, $original_file_path) @@ -283,7 +289,8 @@ public static function isSVG($file_path, $original_file_path) /** * Retrieve a file by UUID - * @param string $uuid + * + * @param string $uuid * @return bool|\Idno\Common\Entity */ static function getByUUID($uuid) @@ -298,7 +305,8 @@ static function getByUUID($uuid) /** * Attempt to extract a file from a URL to it. Will fail with false if the file is external or otherwise * can't be retrieved. - * @param $url + * + * @param $url * @return \Idno\Common\Entity|\MongoGridFSFile|null */ static function getByURL($url) @@ -317,7 +325,8 @@ static function getByURL($url) /** * Retrieve file data from an attachment (first trying load from local storage, then from URL) - * @param $attachment + * + * @param $attachment * @return bool|mixed|string */ static function getFileDataFromAttachment($attachment) @@ -360,7 +369,8 @@ static function getFileDataFromAttachment($attachment) /** * Retrieve file data by ID - * @param string $id + * + * @param string $id * @return mixed */ static function getFileDataByID($id) @@ -378,6 +388,7 @@ static function getFileDataByID($id) /** * Return the MIME type associated with this file + * * @return null|string */ function getMimeType() @@ -392,6 +403,7 @@ function getMimeType() /** * Get the publicly visible filename associated with this file + * * @return string */ function getURL() diff --git a/Idno/Entities/GenericDataItem.php b/Idno/Entities/GenericDataItem.php index 1f1535083e..36b2f9e0a3 100644 --- a/Idno/Entities/GenericDataItem.php +++ b/Idno/Entities/GenericDataItem.php @@ -4,7 +4,7 @@ * Generic data storage item. * A data item for storing arbitrary data using the Known data handling methods. * - * @package idno + * @package idno * @subpackage core */ @@ -14,6 +14,7 @@ class GenericDataItem extends \Idno\Entities\BaseObject { /** * Retrieve a bit of generic data by it's data type + * * @param type $datatype */ public static function getByDatatype($datatype, $search = array(), $fields = array(), $limit = 10, $offset = 0) @@ -25,6 +26,7 @@ public static function getByDatatype($datatype, $search = array(), $fields = arr /** * Label this item as being of a user defined type. + * * @param type $datatype */ public function setDatatype($datatype) diff --git a/Idno/Entities/Invitation.php b/Idno/Entities/Invitation.php index 01ea9b3ad7..830571594b 100644 --- a/Idno/Entities/Invitation.php +++ b/Idno/Entities/Invitation.php @@ -3,7 +3,7 @@ /** * Site invitation representation * - * @package idno + * @package idno * @subpackage core */ @@ -33,7 +33,8 @@ function generateCode() /** * Retrieves an invitation associated with a particular email address - * @param $email + * + * @param $email * @return bool */ static function getByEmail($email) @@ -49,8 +50,9 @@ static function getByEmail($email) /** * Validates an email address / invitation code combination (or returns false if no such invitation exists). - * @param $email - * @param $code + * + * @param $email + * @param $code * @return \Idno\Entities\Invitation|false */ static function validate($email, $code) @@ -64,8 +66,9 @@ static function validate($email, $code) /** * Retrieves an invitation associated with a particular email address and code. - * @param $email - * @param $code + * + * @param $email + * @param $code * @return bool */ static function getByEmailAndCode($email, $code) @@ -81,6 +84,7 @@ static function getByEmailAndCode($email, $code) /** * A cleanup utility method to remove all invitations associated with a given email address + * * @param string $email */ static function removeByEmail($email) @@ -97,8 +101,9 @@ static function removeByEmail($email) /** * Saves this invitation and sends it to the appropriate email address - * @param $email - * @param $from_email If set, sets a reply to + * + * @param $email + * @param $from_email If set, sets a reply to * @return bool|int */ function sendToEmail($email, $from_email = '') @@ -122,7 +127,8 @@ function sendToEmail($email, $from_email = '') /** * Associates this invitation with a particular email address; returns false if the address is invalid - * @param $email + * + * @param $email * @return bool */ function associateWithEmail($email) diff --git a/Idno/Entities/Mutable.php b/Idno/Entities/Mutable.php index e972399d42..6a53d295fc 100644 --- a/Idno/Entities/Mutable.php +++ b/Idno/Entities/Mutable.php @@ -6,16 +6,17 @@ /** * Define entities that can be mutated into other entities. */ -interface Mutable { - +interface Mutable +{ + /** * Mutate a class into one of its parents or children. * This is inherently risky, but sometimes it's useful to be able to do, for example - * when a RemoteUser becomes a regular local user. So that we keep their history, they need to be + * when a RemoteUser becomes a regular local user. So that we keep their history, they need to be * "mutated". - * - * @param string $targetClass The class name and namespace + * + * @param string $targetClass The class name and namespace * @return \Idno\Common\Entity|null */ - public function mutate(string $targetClass): ? \Idno\Common\Entity; + public function mutate(string $targetClass): ? \Idno\Common\Entity; } diff --git a/Idno/Entities/Mutate.php b/Idno/Entities/Mutate.php index ba79187482..c370c7a977 100644 --- a/Idno/Entities/Mutate.php +++ b/Idno/Entities/Mutate.php @@ -10,29 +10,30 @@ use Idno\Core\Idno; use Idno\Common\Entity; -trait Mutate { - - public function mutate(string $targetClass): ? Entity { - +trait Mutate +{ + + public function mutate(string $targetClass): ? Entity + { + // First, check that we're either a parent or a child - if (!($this instanceof $targetClass) && !($targetClass instanceof $this)) - { + if (!($this instanceof $targetClass) && !($targetClass instanceof $this)) { throw new \RuntimeException(Idno::site()->language()->_('%s is not a parent or child of %s', [$targetClass, get_called_class()])); } - + // Now do some witchcraft if ($this instanceof \Idno\Common\Entity) { if ($collection = $this->getCollection()) { $array = $this->saveToArray(); - + $array['entity_subtype'] = $targetClass; $result = Idno::site()->db()->saveRecord($collection, $array); - + return Entity::getByID($result); } } - + return null; } } diff --git a/Idno/Entities/Notification.php b/Idno/Entities/Notification.php index 51507e2475..f25b329abb 100644 --- a/Idno/Entities/Notification.php +++ b/Idno/Entities/Notification.php @@ -19,7 +19,7 @@ class Notification extends \Idno\Common\Entity * * This affects the result of getURL() * - * @param array $params + * @param array $params * @return true if the notification key represents a * unique notification, false if we've seen this one * before. @@ -34,6 +34,7 @@ function setNotificationKey(array $params) /** * The short text message to notify the user with. (eg, a * subject line.) + * * @param string $message */ function setMessage($message) @@ -50,8 +51,8 @@ function getMessage() /** * A template name pointing to a longer version of the * message with more detail. - * @param string $template * + * @param string $template */ function setMessageTemplate($template) { @@ -65,7 +66,7 @@ function getMessageTemplate() /** * @param string $actor URL (or UUID if local) of the - * person who initiated the action + * person who initiated the action */ function setActor($actor) { @@ -88,14 +89,15 @@ function getActor() /** * Optionally, a string describing the kind of action. eg, * "comment", "like", "share", or "follow". + * * @param string $verb */ function setVerb($verb) { $this->verb = $verb; } - - function getVerb() + + function getVerb() { return $this->verb; } @@ -105,6 +107,7 @@ function getVerb() * action. eg, if this is a comment, the object will be * the array that represents the annotation. * Note: unlike ActivityStreamsPost, object is not usually an Entity. + * * @param array|false $object */ function setObject($object) @@ -140,6 +143,7 @@ function setTarget($target) /** * Retrieve the indirect object of the action + * * @return bool|Entity */ function getTarget() @@ -153,6 +157,7 @@ function getTarget() /** * Has this notification been read? + * * @return bool */ function isRead() @@ -211,18 +216,22 @@ function saveDataFromInput() /** * Count the number of unread notifications for the specified user * - * @param bool $user Optionally, a user to check for; otherwise checks current user + * @param bool $user Optionally, a user to check for; otherwise checks current user * @return int */ static function countUnread($user = false) { - if (!$user) $user = Idno::site()->session()->currentUser(); - if (!($user instanceof User)) return 0; + if (!$user) { $user = Idno::site()->session()->currentUser(); + } + if (!($user instanceof User)) { return 0; + } - return self::countFromX('Idno\Entities\Notification', [ + return self::countFromX( + 'Idno\Entities\Notification', [ 'owner' => $user->getUUID(), 'read' => ['$not' => true] - ]); + ] + ); } } diff --git a/Idno/Entities/Reader/Feed.php b/Idno/Entities/Reader/Feed.php index 7ee00adc33..795af5cc03 100644 --- a/Idno/Entities/Reader/Feed.php +++ b/Idno/Entities/Reader/Feed.php @@ -13,6 +13,7 @@ class Feed extends Entity /** * Sets the URL of this feed + * * @param $url */ function setURL($url) @@ -22,6 +23,7 @@ function setURL($url) /** * Sets the URL of the feed this subscription belongs to + * * @param $url */ function setFeedURL($url) @@ -31,7 +33,8 @@ function setFeedURL($url) /** * Retrieves the URL of the feed this subscription belongs to - * @param $url + * + * @param $url * @return mixed */ function getFeedURL() @@ -41,6 +44,7 @@ function getFeedURL() /** * Set the type of this feed + * * @param $type */ function setType($type) @@ -50,6 +54,7 @@ function setType($type) /** * Get the type of this feed + * * @return mixed */ function getType() @@ -59,6 +64,7 @@ function getType() /** * Retrieves and parses this feed + * * @return array|bool */ function fetchAndParse() @@ -68,6 +74,7 @@ function fetchAndParse() /** * Get parsed items from this feed + * * @return array|bool */ function retrieveItems() @@ -81,6 +88,7 @@ function retrieveItems() /** * Sets the time that this item was last updated + * * @param $time */ function setLastUpdated($time) diff --git a/Idno/Entities/Reader/FeedItem.php b/Idno/Entities/Reader/FeedItem.php index 67e9eac2cb..81991add77 100644 --- a/Idno/Entities/Reader/FeedItem.php +++ b/Idno/Entities/Reader/FeedItem.php @@ -12,6 +12,7 @@ class FeedItem extends Entity /** * Sets the URL of the feed this item belongs to + * * @param $url */ function setFeedURL($url) @@ -21,7 +22,8 @@ function setFeedURL($url) /** * Retrieves the URL of the feed this item belongs to - * @param $url + * + * @param $url * @return mixed */ function getFeedURL() @@ -31,6 +33,7 @@ function getFeedURL() /** * Retrieves the body of this item + * * @return string */ function getBody() @@ -40,6 +43,7 @@ function getBody() /** * Sets the non-HTML value of this item + * * @param $content */ function setValue($content) @@ -49,6 +53,7 @@ function setValue($content) /** * Retrieves the non-HTML value of this item + * * @return mixed */ function getValue() @@ -58,7 +63,8 @@ function getValue() /** * Retrieves the URL of a photo associated with this item - * @param $photo + * + * @param $photo * @return mixed */ function getPhoto($photo) @@ -68,6 +74,7 @@ function getPhoto($photo) /** * Retrieves the name of the author of this item + * * @return mixed */ function getAuthorName() @@ -77,7 +84,8 @@ function getAuthorName() /** * Retrieves the URL of the author photo associated with this piece - * @param $author_photo + * + * @param $author_photo * @return mixed */ function getAuthorPhoto() @@ -93,6 +101,7 @@ function getAuthorPhoto() /** * Retrieves the URL of the author of this item + * * @return mixed */ function getAuthorURL() @@ -102,6 +111,7 @@ function getAuthorURL() /** * Retrieves the URLs to syndicated versions of this item + * * @return array */ function getSyndication() @@ -115,6 +125,7 @@ function getSyndication() /** * Given a parsed microformats 2 structure for this item, populates this object + * * @param $item * @param $url */ @@ -133,34 +144,40 @@ function loadFromMF2($mf) function mfpath($mf, $path) { - $elts = array_filter(explode("/", $path), function ($e) { - return $e != ""; - }); - - return array_reduce($elts, function ($result, $elt) { - return $this->mfprop($result, $elt); - }, $mf); + $elts = array_filter( + explode("/", $path), function ($e) { + return $e != ""; + } + ); + + return array_reduce( + $elts, function ($result, $elt) { + return $this->mfprop($result, $elt); + }, $mf + ); } function mfprop($mfs, $prop) { $props = array(); if ($prop == "1") { - if (isset($mfs[0])) return $mfs[0]; + if (isset($mfs[0])) { return $mfs[0]; + } return null; } foreach ($mfs as $mf) { - if (isset($mf["properties"][$prop])) + if (isset($mf["properties"][$prop])) { $thisprops = $this->scrubstrings($mf["properties"][$prop]); - else if ($prop == "children" && isset($mf[$prop])) + } else if ($prop == "children" && isset($mf[$prop])) { $thisprops = $mf[$prop]; - else if (($prop == "html") && isset($mf[$prop])) + } else if (($prop == "html") && isset($mf[$prop])) { $thisprops = array($mf[$prop]); - else if (($prop == "value") && isset($mf[$prop])) + } else if (($prop == "value") && isset($mf[$prop])) { $thisprops = $this->scrubstrings(array($mf[$prop])); - else + } else { continue; + } $props = array_merge($props, $thisprops); } @@ -169,16 +186,20 @@ function mfprop($mfs, $prop) function scrubstrings($arr) { - return array_map(function ($elt) { - if (gettype($elt) == "string") - return htmlspecialchars($elt); - - return $elt; - }, $arr); + return array_map( + function ($elt) { + if (gettype($elt) == "string") { + return htmlspecialchars($elt); + } + + return $elt; + }, $arr + ); } /** * Sets the time that this item was published + * * @param $time */ function setPublishDate($time) @@ -188,6 +209,7 @@ function setPublishDate($time) /** * Sets the body of this item to the given content string + * * @param $content */ function setBody($content) @@ -197,6 +219,7 @@ function setBody($content) /** * Sets the URL of a photo associated with this item + * * @param $photo */ function setPhoto($photo) @@ -206,6 +229,7 @@ function setPhoto($photo) /** * Sets the URL of this feed item + * * @param $url */ function setURL($url) @@ -215,6 +239,7 @@ function setURL($url) /** * Sets the name of the author of this item + * * @param $author_name */ function setAuthorName($author_name) @@ -224,6 +249,7 @@ function setAuthorName($author_name) /** * Sets the URL of the author photo associated with this piece + * * @param $author_photo */ function setAuthorPhoto($author_photo) @@ -233,6 +259,7 @@ function setAuthorPhoto($author_photo) /** * Sets the URL of the author of this item + * * @param $url */ function setAuthorURL($url) @@ -242,6 +269,7 @@ function setAuthorURL($url) /** * Sets an array containing the syndication points of this item + * * @param $syndication */ function setSyndication($syndication) @@ -251,6 +279,7 @@ function setSyndication($syndication) /** * Given a SimplePie-parsed XML item, populates this object + * * @param $item */ function loadFromXMLItem($item) @@ -268,13 +297,16 @@ function loadFromXMLItem($item) function mftype($parsed, $type) { - return array_filter($parsed["items"], function ($elt) use ($type) { - return in_array($type, $elt["type"]); - }); + return array_filter( + $parsed["items"], function ($elt) use ($type) { + return in_array($type, $elt["type"]); + } + ); } /** * Saves this item if it hasn't been saved yet + * * @return $this|bool|false|Entity */ function saveIfNotSaved() diff --git a/Idno/Entities/Reader/Subscription.php b/Idno/Entities/Reader/Subscription.php index b24fbc676c..55429d6f75 100644 --- a/Idno/Entities/Reader/Subscription.php +++ b/Idno/Entities/Reader/Subscription.php @@ -12,7 +12,8 @@ class Subscription extends Entity /** * Get a user's subscriptions - * @param $user + * + * @param $user * @return array */ static function getByUser($user) @@ -22,6 +23,7 @@ static function getByUser($user) /** * Sets the URL of the feed this subscription belongs to + * * @param $url */ function setFeedURL($url) @@ -31,6 +33,7 @@ function setFeedURL($url) /** * Returns the feed associated with this subscription + * * @return bool|false|Entity|Feed */ function getFeedObject() @@ -44,7 +47,8 @@ function getFeedObject() /** * Retrieves the URL of the feed this subscription belongs to - * @param $url + * + * @param $url * @return mixed */ function getFeedURL() diff --git a/Idno/Entities/RemoteObject.php b/Idno/Entities/RemoteObject.php index de05f34feb..1909849a7c 100644 --- a/Idno/Entities/RemoteObject.php +++ b/Idno/Entities/RemoteObject.php @@ -3,7 +3,7 @@ /** * Remote object representation * - * @package idno + * @package idno * @subpackage core */ diff --git a/Idno/Entities/RemoteUser.php b/Idno/Entities/RemoteUser.php index 2b74c396c3..be0ef732a9 100644 --- a/Idno/Entities/RemoteUser.php +++ b/Idno/Entities/RemoteUser.php @@ -3,7 +3,7 @@ /** * Remote user representation * - * @package idno + * @package idno * @subpackage core */ @@ -13,7 +13,7 @@ class RemoteUser extends \Idno\Entities\User implements Mutable { use Mutate; - + public function save($add_to_feed = false, $feed_verb = 'post') { // TODO: use a remote API to save to external sources if we have permission to @@ -32,8 +32,9 @@ public function getURL() { // Remote users don't have a local profile, so we need to override the remote url - if (!empty($this->url)) + if (!empty($this->url)) { return $this->url; + } return $this->getUUID(); } @@ -51,6 +52,7 @@ public function getUUID() /** * Set this user's remote profile url. + * * @param type $url */ public function setUrl($url) diff --git a/Idno/Entities/UnfurledUrl.php b/Idno/Entities/UnfurledUrl.php index 727f7e4f49..51b6ba3d58 100644 --- a/Idno/Entities/UnfurledUrl.php +++ b/Idno/Entities/UnfurledUrl.php @@ -9,6 +9,7 @@ class UnfurledUrl extends BaseObject /** * Copied and modified from https://github.com/mapkyca/php-ogp, extract information from graph headers + * * @param type $content */ private static function parseHeaders($content) @@ -26,7 +27,8 @@ public function isOEmbedWhitelisted() if (!empty($host)) { $host = str_replace('www.', '', $host); - return in_array($host, [ + return in_array( + $host, [ 'youtube.com', 'youtu.be', 'instagram.com', @@ -36,7 +38,8 @@ public function isOEmbedWhitelisted() 'amazon.com', 'amazon.co.uk', 'radiopublic.com', - ]); + ] + ); } return false; @@ -44,6 +47,7 @@ public function isOEmbedWhitelisted() /** * Unfurl and unpack a url, extracting title, description, open-graph and oembed + * * @param type $url */ public function unfurl($url) @@ -52,8 +56,9 @@ public function unfurl($url) $url = trim($url); $unfurled = []; - if (!filter_var($url, FILTER_VALIDATE_URL)) + if (!filter_var($url, FILTER_VALIDATE_URL)) { return false; + } $contents = \Idno\Core\Webservice::file_get_contents($url); if (!empty($contents)) { @@ -69,8 +74,9 @@ public function unfurl($url) $parser = new \Mf2\Parser($contents, $url); try { $mf2 = $parser->parse(); - if (!empty($mf2)) + if (!empty($mf2)) { $unfurled['mf2'] = $mf2; + } } catch (\Exception $e) { \Idno\Core\Idno::site()->logging()->debug($e->getMessage()); } diff --git a/Idno/Entities/User.php b/Idno/Entities/User.php index 8aad3a3b0a..cc47d48edd 100644 --- a/Idno/Entities/User.php +++ b/Idno/Entities/User.php @@ -3,7 +3,7 @@ /** * User representation * - * @package idno + * @package idno * @subpackage core */ @@ -36,16 +36,18 @@ static function registerEvents() { // Hook to add user data to webfinger - \Idno\Core\Idno::site()->events()->addListener('webfinger', function (\Idno\Core\Event $event) { + \Idno\Core\Idno::site()->events()->addListener( + 'webfinger', function (\Idno\Core\Event $event) { - $eventdata = $event->data(); - $user = $eventdata['object']; + $eventdata = $event->data(); + $user = $eventdata['object']; - $links = $event->response(); - if (empty($links)) $links = array(); + $links = $event->response(); + if (empty($links)) { $links = array(); + } - if ($user instanceof User) { - $links = array( + if ($user instanceof User) { + $links = array( array( 'rel' => 'http://webfinger.net/rel/avatar', 'href' => $user->getIcon() @@ -54,69 +56,74 @@ static function registerEvents() 'rel' => 'http://webfinger.net/rel/profile-page', 'href' => $user->getURL() ) - ); - } + ); + } - $event->setResponse($links); + $event->setResponse($links); - }); + } + ); // Refresh session user whenever it is saved - \Idno\Core\Idno::site()->events()->addListener('saved', function (\Idno\Core\Event $event) { + \Idno\Core\Idno::site()->events()->addListener( + 'saved', function (\Idno\Core\Event $event) { - $eventdata = $event->data(); - $user = $eventdata['object']; + $eventdata = $event->data(); + $user = $eventdata['object']; - if ($user instanceof User) { - if ($currentUser = \Idno\Core\Idno::site()->session()->currentUser()) { - if ($user->getUUID() == $currentUser->getUUID()) { - \Idno\Core\Idno::site()->session()->refreshSessionUser($user); + if ($user instanceof User) { + if ($currentUser = \Idno\Core\Idno::site()->session()->currentUser()) { + if ($user->getUUID() == $currentUser->getUUID()) { + \Idno\Core\Idno::site()->session()->refreshSessionUser($user); + } } } - } - }); + } + ); // Email notifications - \Idno\Core\Idno::site()->events()->addListener('notify', function (\Idno\Core\Event $event) { + \Idno\Core\Idno::site()->events()->addListener( + 'notify', function (\Idno\Core\Event $event) { - $eventdata = $event->data(); - $user = $eventdata['user']; - $notification = $eventdata['notification']; + $eventdata = $event->data(); + $user = $eventdata['user']; + $notification = $eventdata['notification']; - if ($user instanceof User && !defined('KNOWN_UNIT_TEST')) { + if ($user instanceof User && !defined('KNOWN_UNIT_TEST')) { - if (empty($user->notifications['email']) || $user->notifications['email'] == 'all' || ($user->notifications['email'] == 'comment' && in_array($notification->type, array('comment', 'reply')))) { + if (empty($user->notifications['email']) || $user->notifications['email'] == 'all' || ($user->notifications['email'] == 'comment' && in_array($notification->type, array('comment', 'reply')))) { - if (($obj = $notification->getObject()) && isset($obj['permalink'])) { - $permalink = $obj['permalink']; - } + if (($obj = $notification->getObject()) && isset($obj['permalink'])) { + $permalink = $obj['permalink']; + } - if (empty($user->notifications['ignored_domains']) || empty($permalink) || !in_array(parse_url($permalink, PHP_URL_HOST), $user->notifications['ignored_domains'])) { - if (filter_var($user->email, FILTER_VALIDATE_EMAIL)) { - $vars = [ + if (empty($user->notifications['ignored_domains']) || empty($permalink) || !in_array(parse_url($permalink, PHP_URL_HOST), $user->notifications['ignored_domains'])) { + if (filter_var($user->email, FILTER_VALIDATE_EMAIL)) { + $vars = [ 'user' => $user, 'notification' => $notification, - ]; - - $t = clone \Idno\Core\Idno::site()->template(); - $t->setTemplateType('email'); - $shellvars = []; - if ($preheader = $t->__($vars)->draw('content/notification/preheader/'.$notification->getVerb())) { - $shellvars['preheader'] = $preheader; + ]; + + $t = clone \Idno\Core\Idno::site()->template(); + $t->setTemplateType('email'); + $shellvars = []; + if ($preheader = $t->__($vars)->draw('content/notification/preheader/'.$notification->getVerb())) { + $shellvars['preheader'] = $preheader; + } + + $email = new Email(); + $email->setSubject($notification->getMessage()); + $email->setHTMLBodyFromTemplate($notification->getMessageTemplate(), $vars, $shellvars); + $email->setTextBodyFromTemplate($notification->getMessageTemplate(), $vars); + $email->addTo($user->email); + $email->send(); } - - $email = new Email(); - $email->setSubject($notification->getMessage()); - $email->setHTMLBodyFromTemplate($notification->getMessageTemplate(), $vars, $shellvars); - $email->setTextBodyFromTemplate($notification->getMessageTemplate(), $vars); - $email->addTo($user->email); - $email->send(); } } } } - }); + ); } @@ -144,6 +151,7 @@ function getIcon() /** * Return the user's current timezone. + * * @return type */ function getTimezone() @@ -153,6 +161,7 @@ function getTimezone() /** * A friendly alias for getTitle. + * * @return string */ function getName() @@ -162,6 +171,7 @@ function getName() /** * A friendly alias for SetTitle. + * * @param $name */ function setName($name) @@ -171,6 +181,7 @@ function setName($name) /** * Get the profile URL for this user + * * @return string */ function getURL() @@ -184,6 +195,7 @@ function getURL() /** * Get the IndieAuth identity URL for this user + * * @return string */ function getIndieAuthURL() @@ -197,6 +209,7 @@ function getIndieAuthURL() /** * Wrapper for getURL for consistency + * * @return string */ function getDisplayURL() @@ -206,6 +219,7 @@ function getDisplayURL() /** * Retrieve's this user's handle + * * @return string */ @@ -216,7 +230,8 @@ function getHandle() /** * Retrieves user by email address - * @param string $email + * + * @param string $email * @return User|false Depending on success */ static function getByEmail($email) @@ -242,6 +257,7 @@ function getOwnerID() /** * Retrieve a text description of this user + * * @return string */ function getDescription() @@ -256,7 +272,7 @@ function getDescription() /** * Retrieve a one-line text description of this user * - * @param int $words + * @param int $words * @return string */ function getShortDescription($words = 25) @@ -285,7 +301,8 @@ function getShortDescription($words = 25) /** * Sets this user's username handle (and balks if someone's already using it) - * @param string $handle + * + * @param string $handle * @return true|false True or false depending on success */ @@ -304,7 +321,8 @@ function setHandle($handle) /** * Retrieves user by handle - * @param string $handle + * + * @param string $handle * @return User|false Depending on success */ static function getByHandle($handle) @@ -320,7 +338,8 @@ static function getByHandle($handle) /** * Retrieve a user by their profile URL. - * @param string $url + * + * @param string $url * @return User|false */ static function getByProfileURL($url) @@ -332,8 +351,9 @@ static function getByProfileURL($url) } } // Ok, now try and see if we can get the local profile - if (preg_match("~" . \Idno\Core\Idno::site()->config()->url . 'profile/([A-Za-z0-9]+)?~', $url, $matches)) + if (preg_match("~" . \Idno\Core\Idno::site()->config()->url . 'profile/([A-Za-z0-9]+)?~', $url, $matches)) { return \Idno\Entities\User::getByHandle($matches[1]); + } // Can't find return false; @@ -342,6 +362,7 @@ static function getByProfileURL($url) /** * Returns this user's unique key for use with the API, and generates a new one if they don't * have one yet + * * @return string */ function getAPIkey() @@ -355,6 +376,7 @@ function getAPIkey() /** * Generate a semi-random API key for this user, and then return it + * * @return string */ function generateAPIkey() @@ -370,18 +392,22 @@ function generateAPIkey() /** * Is this user an admin? + * * @return bool */ function isAdmin() { - if (\Idno\Core\Idno::site()->session()->isAPIRequest()) return false; // Refs #831 - limit admin access on API - if (!empty($this->admin)) return true; + if (\Idno\Core\Idno::site()->session()->isAPIRequest()) { return false; // Refs #831 - limit admin access on API + } + if (!empty($this->admin)) { return true; + } return false; } /** * Set this user's site administrator status + * * @param bool $admin */ function setAdmin($admin) @@ -398,20 +424,22 @@ function setAdmin($admin) * or the currently logged-in user if this is left blank) edit * this user? * - * @param string $user_id + * @param string $user_id * @return true|false */ function canEdit($user_id = '') { - if (!parent::canEdit($user_id)) return false; + if (!parent::canEdit($user_id)) { return false; + } if (empty($user_id)) { $user_id = \Idno\Core\Idno::site()->session()->currentUserUUID(); } - if ($user_id == $this->getUUID()) return true; + if ($user_id == $this->getUUID()) { return true; + } return \Idno\Core\Idno::site()->events()->triggerEvent('canEdit/user', ['object' => $this, 'user_id' => $user_id], false); @@ -419,6 +447,7 @@ function canEdit($user_id = '') /** * Retrieve the URL required to edit this user + * * @return string */ function getEditURL() @@ -430,7 +459,7 @@ function getEditURL() * Sets the built-in password property to a safe hash (if the * password is acceptable) * - * @param string $password + * @param string $password * @return true|false */ function setPassword($password) @@ -447,7 +476,7 @@ function setPassword($password) /** * Verifies that the supplied password matches this user's password * - * @param string $password + * @param string $password * @return true|false */ function checkPassword($password) @@ -460,7 +489,8 @@ function checkPassword($password) /** * Check that a new password is strong. - * @param string $password + * + * @param string $password * @return bool */ static function checkNewPasswordStrength($password) @@ -473,14 +503,17 @@ static function checkNewPasswordStrength($password) $default = true; } - return \Idno\Core\Idno::site()->events()->triggerEvent('user/password/checkstrength', array( + return \Idno\Core\Idno::site()->events()->triggerEvent( + 'user/password/checkstrength', array( 'password' => $password - ), $default); + ), $default + ); } /** * Retrieve the current password recovery code - if it's less than three hours old + * * @return string|false */ function getPasswordRecoveryCode() @@ -496,6 +529,7 @@ function getPasswordRecoveryCode() /** * Add a password recovery code to the user + * * @return string The new recovery code, suitable for sending in an email */ function addPasswordRecoveryCode() @@ -529,13 +563,15 @@ function isComplete() { $handle = $this->getHandle(); $title = $this->getTitle(); - if (!empty($handle) && !empty($title)) return true; + if (!empty($handle) && !empty($title)) { return true; + } return false; } /** * Count the number of posts this user has made + * * @return int */ function countPosts() @@ -548,7 +584,7 @@ function countPosts() * Given a user entity (or a UUID), marks them as being followed by this user. * Remember to save this user entity. * - * @param \Idno\Entities\User|string $user + * @param \Idno\Entities\User|string $user * @return bool */ function addFollowing($user) @@ -560,10 +596,12 @@ function addFollowing($user) $this->following = $users; // Create/modify ACL for following user - $acl = \Idno\Entities\AccessGroup::getOne(array( + $acl = \Idno\Entities\AccessGroup::getOne( + array( 'owner' => $this->getUUID(), 'access_group_type' => 'FOLLOWING' - )); + ) + ); if (empty($acl)) { $acl = new \Idno\Entities\AccessGroup(); @@ -585,6 +623,7 @@ function addFollowing($user) /** * Get a list of user UUIDs that this user marks as following + * * @return array|null */ function getFollowingUUIDs() @@ -599,6 +638,7 @@ function getFollowingUUIDs() /** * Returns a list of users that this user marks as following, where the UUID is the array key, and * the array is of the form ['name' => 'Name', 'url' => 'Profile URL', 'icon' => 'Icon URI'] + * * @return array|null */ function getFollowingArray() @@ -614,7 +654,7 @@ function getFollowingArray() * Given a user entity (or a UUID), removes them from this user's followed list. * Remember to save this user entity. * - * @param \Idno\Entities\User|string $user + * @param \Idno\Entities\User|string $user * @return bool */ function removeFollowing($user) @@ -624,10 +664,12 @@ function removeFollowing($user) unset($users[$user->getUUID()]); $this->following = $users; - $acl = \Idno\Entities\AccessGroup::getOne(array( + $acl = \Idno\Entities\AccessGroup::getOne( + array( 'owner' => $this->getUUID(), 'access_group_type' => 'FOLLOWING' - )); + ) + ); if (!empty($acl)) { $acl->removeMember($user->getUUID()); @@ -645,7 +687,7 @@ function removeFollowing($user) /** * Is the given user following this user? * - * @param \Idno\Entities\User $user + * @param \Idno\Entities\User $user * @return bool */ function isFollowedBy($user) @@ -662,7 +704,7 @@ function isFollowedBy($user) /** * Is the given user a followed by this user? * - * @param \Idno\Entities\User|string $user + * @param \Idno\Entities\User|string $user * @return bool */ function isFollowing($user) @@ -691,7 +733,7 @@ function getReadAccessGroups() /** * Get an array of access groups that this user has arbitrary permissions for * - * @param string $permission The type of permission + * @param string $permission The type of permission * @return array */ function getXAccessGroups($permission) @@ -731,18 +773,20 @@ function getReadAccessGroupIDs() /** * Get an array of access group IDs that this user has an arbitrary permission for * - * @param string $permission Permission type + * @param string $permission Permission type * @return array */ function getXAccessGroupIDs($permission) { $return = array('PUBLIC', 'SITE', $this->getUUID()); - if ($groups = \Idno\Core\Idno::site()->db()->getRecords(array('uuid' => true), + if ($groups = \Idno\Core\Idno::site()->db()->getRecords( + array('uuid' => true), array( 'entity_subtype' => 'Idno\\Entities\\AccessGroup', $permission => $this->getUUID()), PHP_INT_MAX, - 0) + 0 + ) ) { foreach ($groups as $group) { $return[] = $group['uuid']; @@ -766,6 +810,7 @@ function getWriteAccessGroupIDs() /** * Does this user have the given permission. + * * @param string $permission */ function hasPermission($permission) @@ -777,14 +822,16 @@ function hasPermission($permission) $key = array_search($permission, $permissions); - if ($key!==false) + if ($key!==false) { return true; + } return false; } /** * Grant access to a specific permission. + * * @param string $permission */ function grantPermission($permission) @@ -804,6 +851,7 @@ function grantPermission($permission) /** * Revoke a given permission. + * * @param type $permission */ function revokePermission($permission) @@ -831,14 +879,16 @@ function revokePermission($permission) function getActivityStreamsObjectType() { $uuid = $this->getUUID(); - if (!empty($uuid)) + if (!empty($uuid)) { return 'person'; + } return false; } /** * Return the total size of all files owned by this user + * * @return int */ function getFileUsage() @@ -852,7 +902,8 @@ function getFileUsage() /** * Flag this user for "Restricted Processing" as defined under the GDPR - * @see https://techblog.bozho.net/gdpr-practical-guide-developers/ + * + * @see https://techblog.bozho.net/gdpr-practical-guide-developers/ * @param type $restrict */ public function setRestrictedProcessing($restrict = true) @@ -862,13 +913,15 @@ public function setRestrictedProcessing($restrict = true) /** * Get the "Restricted processing" status of this user. + * * @return boolean */ public function getRestrictedProcessing() { - if (!empty($this->restrictedProcessing)) + if (!empty($this->restrictedProcessing)) { return true; + } return false; } @@ -877,14 +930,16 @@ public function getRestrictedProcessing() * Hook to provide a method of notifying a user - for example, sending an email or displaying a popup. * * @param \Idno\Entities\Notification $notification - * @param \Idno\Common\Entity|null $object + * @param \Idno\Common\Entity|null $object */ public function notify($notification) { - return \Idno\Core\Idno::site()->events()->triggerEvent('notify', array( + return \Idno\Core\Idno::site()->events()->triggerEvent( + 'notify', array( 'user' => $this, 'notification' => $notification, - )); + ) + ); } /** @@ -894,23 +949,27 @@ public function notify($notification) */ public function countUnreadNotifications() { - $count = Notification::countFromX('Idno\Entities\Notification', [ + $count = Notification::countFromX( + 'Idno\Entities\Notification', [ 'owner' => $this->getUUID(), 'read' => false, - ]); + ] + ); return $count; } /** * Save form input - * @param \Idno\Common\Page $page + * + * @param \Idno\Common\Page $page * @return bool|\Idno\Common\false|\Idno\Common\true|\Idno\Core\false|\Idno\Core\MongoID|null */ function saveDataFromInput() { - if (!$this->canEdit()) return false; + if (!$this->canEdit()) { return false; + } $profile = \Idno\Core\Idno::site()->currentPage()->getInput('profile'); if (!empty($profile)) { @@ -937,6 +996,7 @@ function saveDataFromInput() /** * Remove this user and all its objects + * * @return bool */ function delete() @@ -955,10 +1015,10 @@ function delete() public function jsonSerialize() { $data = parent::jsonSerialize(); - + unset($data['updated']); unset($data['published']); - + $data['image'] = array('url' => $this->getIcon()); if (!empty($this->profile['url'])) { $data['sameAs'] = $this->profile['url']; diff --git a/Idno/Files/File.php b/Idno/Files/File.php index b5d3d22072..a8dd464123 100644 --- a/Idno/Files/File.php +++ b/Idno/Files/File.php @@ -5,6 +5,7 @@ /** * Class File * Represents a single file in the system + * * @package Idno\Files */ abstract class File @@ -16,7 +17,8 @@ abstract class File /** * Given a file size in bytes, converts it to a friendly version - * @param $bytes + * + * @param $bytes * @return string */ static function describeFileSize($bytes) @@ -35,30 +37,35 @@ static function describeFileSize($bytes) /** * Retrieve the bytes associated with the file + * * @return mixed */ abstract function getBytes(); /** * Pass through bytes associated with the file + * * @return mixed */ abstract function passThroughBytes(); /** * Get a stream resource referencing the file + * * @return mixed */ abstract function getResource(); /** * Returns this file's filename + * * @return string */ abstract function getFilename(); /** * Return the file's size in bytes. + * * @return int */ abstract function getSize(); @@ -69,13 +76,15 @@ abstract function getSize(); /** * Writes the contents of this file to a location specified in $path - * @param string $path + * + * @param string $path * @return mixed */ abstract function write($path); /** * Alias for delete + * * @return mixed */ function remove() diff --git a/Idno/Files/FileSystem.php b/Idno/Files/FileSystem.php index c8b7002a8f..6d8ec9c620 100644 --- a/Idno/Files/FileSystem.php +++ b/Idno/Files/FileSystem.php @@ -13,33 +13,37 @@ abstract class FileSystem /** * Find a file. - * @param $_id + * + * @param $_id * @return mixed */ abstract function findOne($_id); /** * Store the file at $file_path with $metadata and $options - * @param $file_path - * @param $metadata - * @param $options + * + * @param $file_path + * @param $metadata + * @param $options * @return id of file */ abstract function storeFile($file_path, $metadata, $options = []); /** * Store file from contents already loaded. - * @param $contents - * @param $metadata - * @param $options + * + * @param $contents + * @param $metadata + * @param $options * @return id of file */ abstract function storeContent($content, $metadata, $options = []); /** * Get a translated error message for PHP Upload errors. + * * @param int $code - * @see http://php.net/manual/en/features.file-upload.errors.php + * @see http://php.net/manual/en/features.file-upload.errors.php */ public static function getUploadErrorCodeMessage($code) { diff --git a/Idno/Files/LocalFile.php b/Idno/Files/LocalFile.php index b7aabc5097..89da0ad434 100644 --- a/Idno/Files/LocalFile.php +++ b/Idno/Files/LocalFile.php @@ -10,6 +10,7 @@ class LocalFile extends File /** * Get this file's contents. For larger files this might not be wise. + * * @return mixed|string */ function getBytes() @@ -28,6 +29,7 @@ function getSize() /** * Output the contents of the file to the buffer + * * @return mixed|void */ function passThroughBytes() @@ -43,6 +45,7 @@ function passThroughBytes() /** * Retrieves a stream resource referencing the file + * * @return mixed|resource */ function getResource() @@ -67,7 +70,8 @@ function delete() /** * Writes this file to the filename specified in $path - * @param string $path + * + * @param string $path * @return bool|mixed */ function write($path) @@ -77,6 +81,7 @@ function write($path) /** * Returns this file's filename + * * @return string */ function getFilename() diff --git a/Idno/Files/LocalFileSystem.php b/Idno/Files/LocalFileSystem.php index 2c573f327d..d479521cf7 100644 --- a/Idno/Files/LocalFileSystem.php +++ b/Idno/Files/LocalFileSystem.php @@ -13,7 +13,8 @@ class LocalFileSystem extends FileSystem /** * Find a file. - * @param $id + * + * @param $id * @return mixed */ public function findOne($id) @@ -53,9 +54,10 @@ public function findOne($id) /** * Store the file at $file_path with $metadata and $options - * @param $file_path - * @param $metadata - * @param $options + * + * @param $file_path + * @param $metadata + * @param $options * @return id of file */ public function storeFile($file_path, $metadata, $options = []) @@ -132,12 +134,10 @@ public function storeContent($content, $metadata, $options = []) } } - if (!@file_put_contents($upload_file, $content)) - { + if (!@file_put_contents($upload_file, $content)) { throw new \RuntimeException(\Idno\Core\Idno::site()->language()->_("There was a problem storing the file data.")); } - if (!@file_put_contents($data_file, $metadata)) - { + if (!@file_put_contents($data_file, $metadata)) { throw new \RuntimeException(\Idno\Core\Idno::site()->language()->_("There was a problem saving the file's metadata")); } diff --git a/Idno/Files/MongoDBFile.php b/Idno/Files/MongoDBFile.php index 86730939de..1f4e68bb27 100644 --- a/Idno/Files/MongoDBFile.php +++ b/Idno/Files/MongoDBFile.php @@ -9,6 +9,7 @@ class MongoDBFile extends File /** * Get this file's contents. For larger files this might not be wise. + * * @return mixed|string */ function getBytes() @@ -44,6 +45,7 @@ function getSize() /** * Output the contents of the file to the buffer + * * @return mixed|void */ function passThroughBytes() @@ -57,6 +59,7 @@ function passThroughBytes() /** * Retrieves a stream resource referencing the file + * * @return mixed|resource */ function getResource() @@ -80,7 +83,8 @@ function delete() /** * Writes this file to the filename specified in $path - * @param string $path + * + * @param string $path * @return bool|mixed */ function write($path) @@ -102,6 +106,7 @@ function write($path) /** * Returns this file's filename + * * @return string */ function getFilename() diff --git a/Idno/Files/MongoDBFileSystem.php b/Idno/Files/MongoDBFileSystem.php index 2b00b82f07..0bf76d778b 100644 --- a/Idno/Files/MongoDBFileSystem.php +++ b/Idno/Files/MongoDBFileSystem.php @@ -81,9 +81,11 @@ public function storeFile($file_path, $metadata, $options = []) if ($source = fopen($file_path, 'rb')) { - $id = $bucket->uploadFromStream($metadata['filename'], $source, [ + $id = $bucket->uploadFromStream( + $metadata['filename'], $source, [ 'metadata' => $metadata//new \MongoDB\Model\BSONDocument($metadata) - ]); + ] + ); fclose($source); @@ -107,9 +109,11 @@ public function storeContent($content, $metadata, $options = []) fwrite($source, $content); rewind($source); - $id = $bucket->uploadFromStream($metadata['filename'], $source, [ + $id = $bucket->uploadFromStream( + $metadata['filename'], $source, [ 'metadata' => $metadata//new \MongoDB\Model\BSONDocument($metadata) - ]); + ] + ); fclose($source); diff --git a/Idno/Pages/Account/Notifications.php b/Idno/Pages/Account/Notifications.php index 57eb1d14d9..c1214a77ee 100644 --- a/Idno/Pages/Account/Notifications.php +++ b/Idno/Pages/Account/Notifications.php @@ -17,25 +17,33 @@ function getContent($params = array()) $limit = 25; $offset = $this->getInput('offset', 0); - $notifs = Notification::getFromX('Idno\Entities\Notification', [ + $notifs = Notification::getFromX( + 'Idno\Entities\Notification', [ 'owner' => $user->getUUID(), - ], [], $limit, $offset); + ], [], $limit, $offset + ); - $count = Notification::countFromX('Idno\Entities\Notification', [ + $count = Notification::countFromX( + 'Idno\Entities\Notification', [ 'owner' => $user->getUUID(), - ]); + ] + ); - $body = Idno::site()->template()->__([ + $body = Idno::site()->template()->__( + [ 'user' => $user, 'items' => $notifs, 'count' => $count, 'items_per_page' => $limit - ])->draw('account/notifications'); + ] + )->draw('account/notifications'); - $page = Idno::site()->template()->__([ + $page = Idno::site()->template()->__( + [ 'title' => \Idno\Core\Idno::site()->language()->_('Notifications'), 'body' => $body, - ])->drawPage(false); + ] + )->drawPage(false); // mark all notifications as seen foreach ($notifs as $notif) { diff --git a/Idno/Pages/Account/Register.php b/Idno/Pages/Account/Register.php index afc8cdb44d..de4a2986b7 100644 --- a/Idno/Pages/Account/Register.php +++ b/Idno/Pages/Account/Register.php @@ -39,11 +39,13 @@ function getContent() $t->title = \Idno\Core\Idno::site()->language()->_('Create a new account'); echo $t->draw('shell'); } else { - $t->body = $t->__(array( + $t->body = $t->__( + array( 'email' => $email, 'code' => $code, 'set_name' => $set_name, - 'messages' => \Idno\Core\Idno::site()->session()->getAndFlushMessages()))->draw('onboarding/register'); + 'messages' => \Idno\Core\Idno::site()->session()->getAndFlushMessages()) + )->draw('onboarding/register'); $t->title = \Idno\Core\Idno::site()->language()->_('Create a new account'); echo $t->draw('shell/simple'); } @@ -79,22 +81,23 @@ function postContent() if (empty($handle) && empty($email)) { \Idno\Core\Idno::site()->session()->addErrorMessage(\Idno\Core\Idno::site()->language()->_("Please enter a username and email address.")); } else if (!empty($email) && filter_var($email, FILTER_VALIDATE_EMAIL)) { - if ( - !(\Idno\Core\Idno::site()->config()->emailIsBlocked($email)) && - !($emailuser = \Idno\Entities\User::getByEmail($email)) && - !($handleuser = \Idno\Entities\User::getByHandle($handle)) && - !empty($handle) && strlen($handle) <= 32 && - preg_match('/^[a-zA-Z0-9_]{1,}$/', $handle) && - !substr_count($handle, '/') && - $password == $password2 && - \Idno\Entities\User::checkNewPasswordStrength($password) && - \Idno\Core\Idno::site()->events()->triggerEvent('user/register/validate', [ + if (!(\Idno\Core\Idno::site()->config()->emailIsBlocked($email)) + && !($emailuser = \Idno\Entities\User::getByEmail($email)) + && !($handleuser = \Idno\Entities\User::getByHandle($handle)) + && !empty($handle) && strlen($handle) <= 32 + && preg_match('/^[a-zA-Z0-9_]{1,}$/', $handle) + && !substr_count($handle, '/') + && $password == $password2 + && \Idno\Entities\User::checkNewPasswordStrength($password) + && \Idno\Core\Idno::site()->events()->triggerEvent( + 'user/register/validate', [ 'name' => $name, 'handle' => $handle, 'email' => $email, 'password' => $password, 'password2' => $password2 - ], true) + ], true + ) ) { $user = new \Idno\Entities\User(); $user->email = $email; diff --git a/Idno/Pages/Account/Settings/Feedback.php b/Idno/Pages/Account/Settings/Feedback.php index f284b86ae4..6df92af7b5 100644 --- a/Idno/Pages/Account/Settings/Feedback.php +++ b/Idno/Pages/Account/Settings/Feedback.php @@ -29,7 +29,8 @@ function postContent() if (!empty($email) && !empty($message)) { - $results = Webservice::post('https://withknown.com/vendor-services/feedback/', array( + $results = Webservice::post( + 'https://withknown.com/vendor-services/feedback/', array( 'url' => \Idno\Core\Idno::site()->config()->getURL(), 'title' => \Idno\Core\Idno::site()->config()->getTitle(), 'version' => \Idno\Core\Version::version(), @@ -37,7 +38,8 @@ function postContent() 'hub' => \Idno\Core\Idno::site()->config()->known_hub, 'email' => $email, 'message' => $message - )); + ) + ); \Idno\Core\Idno::site()->session()->addMessage(\Idno\Core\Idno::site()->language()->_("Thanks! We received your feedback.")); diff --git a/Idno/Pages/Account/Settings/Following/Bookmarklet.php b/Idno/Pages/Account/Settings/Following/Bookmarklet.php index a055a4cb6c..0f3cae281e 100644 --- a/Idno/Pages/Account/Settings/Following/Bookmarklet.php +++ b/Idno/Pages/Account/Settings/Following/Bookmarklet.php @@ -52,18 +52,21 @@ function getContent() } - foreach ($hcard as $card) + foreach ($hcard as $card) { $body .= $t->__(array('mf2' => $card))->draw('account/settings/following/mf2user'); + } // List user $t->body = $body; $t->title = \Idno\Core\Idno::site()->language()->_('Found users'); $t->drawPage(); } - } else + } else { throw new \RuntimeException(\Idno\Core\Idno::site()->language()->_("Sorry, there was a problem parsing the page!")); - } else + } + } else { throw new \RuntimeException(\Idno\Core\Idno::site()->language()->_("Sorry, %s could not be retrieved!", [$u])); + } // forward back $this->forward($_SERVER['HTTP_REFERER']); @@ -71,6 +74,7 @@ function getContent() /** * When passed an array of MF2 data, recursively find hcard entries. + * * @param array $mf2 * @param array $out */ @@ -78,16 +82,19 @@ private function findHcard(array $mf2, array &$out) { foreach ($mf2 as $item) { // Find h-card - if (in_array('h-card', $item['type'])) + if (in_array('h-card', $item['type'])) { $out[] = $item; - if (isset($item['children'])) + } + if (isset($item['children'])) { $this->findHcard($item['children'], $out); + } } } /** * Go through the list of found hcards and remove duplicates (based on unique profile urls) - * @param array $hcards + * + * @param array $hcards * @return array */ private function removeDuplicateProfiles(array $hcards) @@ -96,8 +103,9 @@ private function removeDuplicateProfiles(array $hcards) foreach ($hcards as $card) { $key = serialize($card['properties']['url']); - if (!isset($cards[$key])) + if (!isset($cards[$key])) { $cards[$key] = $card; + } } return $cards; @@ -105,13 +113,15 @@ private function removeDuplicateProfiles(array $hcards) /** * Quickly find a title from a HTML page. + * * @return string|false - * @param type $content + * @param type $content */ private function findPageTitle($content) { - if (!preg_match("/<title>(.*)<\/title>/siU", $content, $matches)) + if (!preg_match("/<title>(.*)<\/title>/siU", $content, $matches)) { return false; + } return trim($matches[1], " \n"); } @@ -123,12 +133,11 @@ function postContent() if ($uuid = $this->getInput('uuid')) { - if ( - // TODO: Do this better, perhaps support late bindings - (!$new_user = \Idno\Entities\User::getByUUID($uuid)) && - (!$new_user = \Idno\Entities\User::getByProfileURL($uuid)) && - (!$new_user = \Idno\Entities\RemoteUser::getByUUID($uuid)) && - (!$new_user = \Idno\Entities\RemoteUser::getByProfileURL($uuid)) + if (// TODO: Do this better, perhaps support late bindings + (!$new_user = \Idno\Entities\User::getByUUID($uuid)) + && (!$new_user = \Idno\Entities\User::getByProfileURL($uuid)) + && (!$new_user = \Idno\Entities\RemoteUser::getByUUID($uuid)) + && (!$new_user = \Idno\Entities\RemoteUser::getByProfileURL($uuid)) ) { // No user found, so create it if it's remote @@ -145,12 +154,14 @@ function postContent() // TODO: Get a profile URL - get it from passed photo variable, upload to local and treat as avatar. - if (!$new_user->save()) + if (!$new_user->save()) { throw new \Exception(\Idno\Core\Idno::site()->language()->_("There was a problem saving the new remote user.")); + } } - } else + } else { \Idno\Core\Idno::site()->logging()->debug("New user found as " . $new_user->uuid); + } if ($new_user) { @@ -179,10 +190,12 @@ function postContent() \Idno\Core\Idno::site()->logging()->debug('Could not follow user for some reason (probably already following)'); \Idno\Core\Idno::site()->session()->addErrorMessage(\Idno\Core\Idno::site()->language()->esc_('You\'re already following %s', [$this->getInput('name')])); } - } else + } else { throw new \RuntimeException(\Idno\Core\Idno::site()->language()->_('Sorry, that user doesn\'t exist!')); - } else + } + } else { throw new \RuntimeException(\Idno\Core\Idno::site()->language()->_("No UUID, please try that again!")); + } } } diff --git a/Idno/Pages/Admin/Export.php b/Idno/Pages/Admin/Export.php index 58626869ea..f2d2d97a16 100644 --- a/Idno/Pages/Admin/Export.php +++ b/Idno/Pages/Admin/Export.php @@ -13,15 +13,19 @@ function getContent() $this->adminGatekeeper(); $t = \Idno\Core\Idno::site()->template(); - $t->__(array( + $t->__( + array( 'title' => \Idno\Core\Idno::site()->language()->_('Export data'), - 'body' => $t->__(array( + 'body' => $t->__( + array( 'export_last_requested' => \Idno\Core\Idno::site()->config()->export_last_requested, 'export_in_progress' => \Idno\Core\Idno::site()->config()->export_in_progress, 'export_filename' => \Idno\Core\Idno::site()->config()->export_filename, 'export_file_id' => \Idno\Core\Idno::site()->config()->export_file_id - ))->draw('admin/export'), - ))->drawPage(); + ) + )->draw('admin/export'), + ) + )->drawPage(); } diff --git a/Idno/Pages/Admin/Home.php b/Idno/Pages/Admin/Home.php index 9e3f433692..c7e8d49cb5 100644 --- a/Idno/Pages/Admin/Home.php +++ b/Idno/Pages/Admin/Home.php @@ -45,14 +45,20 @@ function postContent() $single_user = $this->getInput('single_user') === 'true'; $permalink_structure = $this->getInput('permalink_structure'); - if (!empty($title)) \Idno\Core\Idno::site()->config()->title = $title; + if (!empty($title)) { \Idno\Core\Idno::site()->config()->title = $title; + } \Idno\Core\Idno::site()->config()->homepagetitle = trim($homepagetitle); - if (!empty($description)) \Idno\Core\Idno::site()->config()->description = $description; - if (!empty($url)) \Idno\Core\Idno::site()->config()->url = $url; - if (!empty($path)) \Idno\Core\Idno::site()->config()->path = $path; - if (!empty($host)) \Idno\Core\Idno::site()->config()->host = $host; + if (!empty($description)) { \Idno\Core\Idno::site()->config()->description = $description; + } + if (!empty($url)) { \Idno\Core\Idno::site()->config()->url = $url; + } + if (!empty($path)) { \Idno\Core\Idno::site()->config()->path = $path; + } + if (!empty($host)) { \Idno\Core\Idno::site()->config()->host = $host; + } \Idno\Core\Idno::site()->config()->hub = $hub; - if (!empty($items_per_page) && is_int($items_per_page)) \Idno\Core\Idno::site()->config()->items_per_page = $items_per_page; + if (!empty($items_per_page) && is_int($items_per_page)) { \Idno\Core\Idno::site()->config()->items_per_page = $items_per_page; + } \Idno\Core\Idno::site()->config()->open_registration = $open_registration; \Idno\Core\Idno::site()->config()->walled_garden = $walled_garden; \Idno\Core\Idno::site()->config()->show_privacy = $show_privacy; diff --git a/Idno/Pages/Admin/Homepage.php b/Idno/Pages/Admin/Homepage.php index 6d37871bc6..f9cadd8ab8 100644 --- a/Idno/Pages/Admin/Homepage.php +++ b/Idno/Pages/Admin/Homepage.php @@ -36,7 +36,7 @@ function postContent() $default_feed_content = false; } - \Idno\Core\Idno::site()->config()->default_feed_content = $default_feed_content; + \Idno\Core\Idno::site()->config()->default_feed_content = $default_feed_content; if (\Idno\Core\Idno::site()->config()->save()) { \Idno\Core\Idno::site()->session()->addMessage(\Idno\Core\Idno::site()->language()->_("The default homepage content types were saved.")); diff --git a/Idno/Pages/Admin/Import.php b/Idno/Pages/Admin/Import.php index f35a26a00a..31abb3fbc2 100644 --- a/Idno/Pages/Admin/Import.php +++ b/Idno/Pages/Admin/Import.php @@ -14,10 +14,12 @@ function getContent() $this->adminGatekeeper(); $t = \Idno\Core\Idno::site()->template(); - $t->__(array( + $t->__( + array( 'title' => \Idno\Core\Idno::site()->language()->_('Import data'), 'body' => $t->draw('admin/import'), - ))->drawPage(); + ) + )->drawPage(); } diff --git a/Idno/Pages/Admin/Plugins.php b/Idno/Pages/Admin/Plugins.php index 33d54135d7..b9044f989e 100644 --- a/Idno/Pages/Admin/Plugins.php +++ b/Idno/Pages/Admin/Plugins.php @@ -16,10 +16,12 @@ function getContent() { $this->adminGatekeeper(); // Admins only $t = \Idno\Core\Idno::site()->template(); - $t->body = $t->__(array( + $t->body = $t->__( + array( 'plugins_stored' => \Idno\Core\Idno::site()->plugins()->getStored(), 'plugins_loaded' => \Idno\Core\Idno::site()->plugins()->getLoaded(), - ))->draw('admin/plugins'); + ) + )->draw('admin/plugins'); $t->title = \Idno\Core\Idno::site()->language()->_('Plugins'); $t->drawPage(); } @@ -32,22 +34,21 @@ function postContent() if (defined('KNOWN_MULTITENANT_HOST')) { $host = KNOWN_MULTITENANT_HOST; } - if ( - preg_match('/^[a-zA-Z0-9]+$/', $plugin) && - ( - \Idno\Core\Idno::site()->plugins()->exists($plugin) - ) + if (preg_match('/^[a-zA-Z0-9]+$/', $plugin) + && (\Idno\Core\Idno::site()->plugins()->exists($plugin)) ) { switch ($action) { case 'install': if (\Idno\Core\Idno::site()->plugins()->enable($plugin)) { \Idno\Core\Idno::site()->session()->addMessage(\Idno\Core\Idno::site()->language()->_('The plugin was enabled.')); - echo json_encode([ + echo json_encode( + [ 'action' => $action, 'status' => true, 'message' => \Idno\Core\Idno::site()->language()->_('The plugin was enabled.') - ]); + ] + ); exit; } @@ -57,11 +58,13 @@ function postContent() if (\Idno\Core\Idno::site()->plugins()->disable($plugin)) { \Idno\Core\Idno::site()->session()->addMessage(\Idno\Core\Idno::site()->language()->_('The plugin was disabled.')); - echo json_encode([ + echo json_encode( + [ 'action' => $action, 'status' => true, 'message' => \Idno\Core\Idno::site()->language()->_('The plugin was disabled.') - ]); + ] + ); exit; } @@ -70,10 +73,12 @@ function postContent() } - echo json_encode([ + echo json_encode( + [ 'action' => $action, 'status' => false, - ]); + ] + ); //$this->forward(\Idno\Core\Idno::site()->config()->getDisplayURL() . 'admin/plugins/'); } diff --git a/Idno/Pages/Admin/Statistics.php b/Idno/Pages/Admin/Statistics.php index 12c6e8c0c1..0eb1a46e38 100644 --- a/Idno/Pages/Admin/Statistics.php +++ b/Idno/Pages/Admin/Statistics.php @@ -12,8 +12,9 @@ function getContent() $stats = \Idno\Core\Statistics::gather($report); - if (empty($stats) || !is_array($stats)) + if (empty($stats) || !is_array($stats)) { throw new \RuntimeException(\Idno\Core\Idno::site()->language()->_("Something went wrong, either no statistics were returned or it wasn't in the correct format.")); + } if ($this->xhr) { diff --git a/Idno/Pages/Admin/Themes.php b/Idno/Pages/Admin/Themes.php index 6961e60377..214db1be13 100644 --- a/Idno/Pages/Admin/Themes.php +++ b/Idno/Pages/Admin/Themes.php @@ -15,10 +15,12 @@ function getContent() { $this->adminGatekeeper(); // Admins only $t = \Idno\Core\Idno::site()->template(); - $t->body = $t->__(array( + $t->body = $t->__( + array( 'themes_stored' => \Idno\Core\Idno::site()->themes()->getStored(), 'theme' => \Idno\Core\Idno::site()->themes()->get(), - ))->draw('admin/themes'); + ) + )->draw('admin/themes'); $t->title = \Idno\Core\Idno::site()->language()->_('Themes'); $t->drawPage(); } @@ -31,18 +33,9 @@ function postContent() if (defined('KNOWN_MULTITENANT_HOST')) { $host = KNOWN_MULTITENANT_HOST; } - if ( - ( - preg_match('/^[a-zA-Z0-9]+$/', $theme) && - ( - file_exists(\Idno\Core\Idno::site()->config()->path . '/Themes/' . $theme) || - ( - !empty($host) && ( - file_exists(\Idno\Core\Idno::site()->config()->path . '/hosts/' . $host . '/Themes/' . $theme) - ) - ) - ) - ) + if (( preg_match('/^[a-zA-Z0-9]+$/', $theme) + && ( file_exists(\Idno\Core\Idno::site()->config()->path . '/Themes/' . $theme) + || ( !empty($host) && ( file_exists(\Idno\Core\Idno::site()->config()->path . '/hosts/' . $host . '/Themes/' . $theme) ) ) )) || $theme == 'default' || $theme == '' ) { switch ($action) { diff --git a/Idno/Pages/Admin/Users.php b/Idno/Pages/Admin/Users.php index bcd296956a..47f00c6b71 100644 --- a/Idno/Pages/Admin/Users.php +++ b/Idno/Pages/Admin/Users.php @@ -142,11 +142,10 @@ function postContent() } else if (empty($handle) && empty($email)) { \Idno\Core\Idno::site()->session()->addMessage(\Idno\Core\Idno::site()->language()->_("Please enter a username and email address.")); } else if (!empty($email) && filter_var($email, FILTER_VALIDATE_EMAIL)) { - if ( - !($emailuser = \Idno\Entities\User::getByEmail($email)) && - !($handleuser = \Idno\Entities\User::getByHandle($handle)) && - !empty($handle) && strlen($handle) <= 32 && - !substr_count($handle, '/') + if (!($emailuser = \Idno\Entities\User::getByEmail($email)) + && !($handleuser = \Idno\Entities\User::getByHandle($handle)) + && !empty($handle) && strlen($handle) <= 32 + && !substr_count($handle, '/') ) { $user = new \Idno\Entities\User(); $user->email = $email; diff --git a/Idno/Pages/Annotation/Delete.php b/Idno/Pages/Annotation/Delete.php index 26c52df216..bb15490683 100644 --- a/Idno/Pages/Annotation/Delete.php +++ b/Idno/Pages/Annotation/Delete.php @@ -34,8 +34,9 @@ function postContent() $permalink = \Idno\Core\Webservice::base64UrlDecode($this->getInput('permalink')); // Default to constructed permalink if one is not provided. - if (empty($permalink)) + if (empty($permalink)) { $permalink = $object->getURL() . '/annotations/' . $this->arguments[1]; + } if ($object->canEditAnnotation($permalink)) { if (($object->removeAnnotation($permalink)) && ($object->save())) { diff --git a/Idno/Pages/Annotation/Post.php b/Idno/Pages/Annotation/Post.php index 4f92c37986..427a9a358b 100644 --- a/Idno/Pages/Annotation/Post.php +++ b/Idno/Pages/Annotation/Post.php @@ -69,10 +69,12 @@ function postContent() $heart_text = 'stars'; } - \Idno\Core\Idno::site()->template()->__([ + \Idno\Core\Idno::site()->template()->__( + [ 'number' => $likes, 'text' => "$likes $heart_text" - ])->drawPage(); + ] + )->drawPage(); } $this->forward($object->getDisplayURL() . '#comments'); diff --git a/Idno/Pages/Annotation/View.php b/Idno/Pages/Annotation/View.php index c345c8350b..330f576da2 100644 --- a/Idno/Pages/Annotation/View.php +++ b/Idno/Pages/Annotation/View.php @@ -36,13 +36,15 @@ function getContent() $this->setPermalink(); // This is a permalink $t = \Idno\Core\Idno::site()->template(); - $t->__(array( + $t->__( + array( 'title' => $object->getTitle(), 'body' => $t->__(array('annotation' => $annotation, 'subtype' => $subtype, 'permalink' => $permalink, 'object' => $object))->draw('entity/annotations/shell'), 'description' => $object->getShortDescription() - ))->drawPage(); + ) + )->drawPage(); } else { // List annotations for object @@ -63,23 +65,27 @@ function getContent() unset($t->vars['subtype']); unset($t->vars['permalink']); - if ($t->getTemplateType() == 'rss') + if ($t->getTemplateType() == 'rss') { unset($t->vars['object']); + } $items[] = $annotation; } } - if ($t->getTemplateType() == 'rss') + if ($t->getTemplateType() == 'rss') { $t->vars['annotations'] = $items; + } - $t->__(array( + $t->__( + array( 'title' => "Annotations on: " .$object->getTitle(), 'body' => $body, 'description' => $object->getShortDescription() - ))->drawPage(); + ) + )->drawPage(); } } diff --git a/Idno/Pages/Entity/Attachment/Delete.php b/Idno/Pages/Entity/Attachment/Delete.php index 8585469a5f..902ae70a59 100644 --- a/Idno/Pages/Entity/Attachment/Delete.php +++ b/Idno/Pages/Entity/Attachment/Delete.php @@ -21,8 +21,9 @@ function postContent() Idno::site()->session()->addMessage(\Idno\Core\Idno::site()->language()->_("We couldn't find the post.")); $this->goneContent(); } - if (!$object->canEdit()) + if (!$object->canEdit()) { $this->deniedContent(); + } if (!empty($this->arguments[1])) { $attachment_id = $this->arguments[1]; diff --git a/Idno/Pages/Entity/Delete.php b/Idno/Pages/Entity/Delete.php index a0ca7b7c0c..51ddafb635 100644 --- a/Idno/Pages/Entity/Delete.php +++ b/Idno/Pages/Entity/Delete.php @@ -21,15 +21,18 @@ function getContent() if (!empty($this->arguments[0])) { $object = \Idno\Common\Entity::getByID($this->arguments[0]); } - if (empty($object)) $this->forward(); // TODO: 404 + if (empty($object)) { $this->forward(); // TODO: 404 + } $t = \Idno\Core\Idno::site()->template(); - $t->__(array( + $t->__( + array( 'title' => $object->getTitle(), 'body' => $object->draw() - ))->drawPage(); + ) + )->drawPage(); } // Handle POST requests to the entity @@ -45,8 +48,9 @@ function postContent() Idno::site()->session()->addMessage(\Idno\Core\Idno::site()->language()->_("We couldn't find the post to delete.")); $this->forward(); } // TODO: 404 - if (!$object->canEdit()) + if (!$object->canEdit()) { $this->deniedContent(); + } if ($object->delete()) { \Idno\Core\Idno::site()->session()->addMessage(\Idno\Core\Idno::site()->language()->esc_('%s was deleted.', [$object->getTitle()])); diff --git a/Idno/Pages/Entity/Edit.php b/Idno/Pages/Entity/Edit.php index 0e06d877d1..7df6c907dd 100644 --- a/Idno/Pages/Entity/Edit.php +++ b/Idno/Pages/Entity/Edit.php @@ -19,8 +19,10 @@ function getContent() if (!empty($this->arguments[0])) { $object = \Idno\Common\Entity::getByID($this->arguments[0]); } - if (empty($object)) $this->forward(); // TODO: 404 - if (!$object->canEdit()) $this->forward($object->getDisplayURL()); + if (empty($object)) { $this->forward(); // TODO: 404 + } + if (!$object->canEdit()) { $this->forward($object->getDisplayURL()); + } if ($owner = $object->getOwner()) { $this->setOwner($owner); @@ -29,12 +31,14 @@ function getContent() session_write_close(); $t = \Idno\Core\Idno::site()->template(); - $t->__(array( + $t->__( + array( 'title' => $object->getTitle(), 'body' => $t->__(['object' => $object])->draw('entity/editwrapper'), - ))->drawPage(); + ) + )->drawPage(); } diff --git a/Idno/Pages/Entity/Shortlink.php b/Idno/Pages/Entity/Shortlink.php index cc9b058285..48df08ec8f 100644 --- a/Idno/Pages/Entity/Shortlink.php +++ b/Idno/Pages/Entity/Shortlink.php @@ -33,7 +33,8 @@ function webmentionContent($source, $target, $source_content, $source_mf2) if (!empty($this->arguments[0])) { $object = \Idno\Common\Entity::getByShortURL($this->arguments[0]); } - if (empty($object)) return false; + if (empty($object)) { return false; + } $return = true; diff --git a/Idno/Pages/Entity/View.php b/Idno/Pages/Entity/View.php index a46765dfb1..45c4e9932d 100644 --- a/Idno/Pages/Entity/View.php +++ b/Idno/Pages/Entity/View.php @@ -64,13 +64,15 @@ function getContent() $description = $t->sampleText($object->getDescription()); } - $t->__(array( + $t->__( + array( 'title' => $object->getTitle(), 'body' => $t->__(['object' => $object])->draw('entity/wrapper'), 'description' => $description - ))->drawPage(); + ) + )->drawPage(); } // Get webmention content and handle it @@ -109,7 +111,8 @@ function postContent() } } - if (empty($object)) $this->forward(); // TODO: 404 + if (empty($object)) { $this->forward(); // TODO: 404 + } if ($object->saveDataFromInput()) { $this->forward($object->getDisplayURL()); } @@ -126,7 +129,8 @@ function deleteContent() $object = \Idno\Common\Entity::getBySlug($this->arguments[0]); } } - if (empty($object)) $this->forward(); // TODO: 404 + if (empty($object)) { $this->forward(); // TODO: 404 + } if ($object->delete()) { \Idno\Core\Idno::site()->session()->addMessage(\Idno\Core\Idno::site()->language()->esc_('%s was deleted.', [$object->getTitle()])); } diff --git a/Idno/Pages/File/Mint.php b/Idno/Pages/File/Mint.php index 0da5bebdef..fcc10d5d3e 100644 --- a/Idno/Pages/File/Mint.php +++ b/Idno/Pages/File/Mint.php @@ -5,61 +5,58 @@ use Idno\Core\Idno; use Idno\Entities\File; -class Mint extends \Idno\Common\Page { - +class Mint extends \Idno\Common\Page +{ + /** * Mint a new file, and if successful, return the new ID */ - public function postContent() { - + public function postContent() + { + Idno::site()->template()->setTemplateType('json'); - + $this->createGatekeeper(); - + $name = $this->getInput('name'); // Name $type = $this->getInput('type'); // File type $size = $this->getInput('size'); // Size in bytes - + if (empty($name)) { throw new \RuntimeException(\Idno\Core\Idno::site()->language()->_('"name" (name of file) field needs to be supplied')); } - + if (empty($type)) { throw new \RuntimeException(\Idno\Core\Idno::site()->language()->_('"type" (mime type) field needs to be supplied')); } - + if (empty($size)) { throw new \RuntimeException(\Idno\Core\Idno::site()->language()->_('"size" (size in bytes) field needs to be supplied')); } - + // Get an upload URL - $upload_url = Idno::site()->events()->triggerEvent('file/upload/getuploadurl', [ + $upload_url = Idno::site()->events()->triggerEvent( + 'file/upload/getuploadurl', [ 'name' => $name, 'type' => $type, 'size' => $size - ], Idno::site()->config()->getDisplayURL() . '/file/upload/' . $file->getID()); - + ], Idno::site()->config()->getDisplayURL() . '/file/upload/' . $file->getID() + ); + // If no url, then remove file and error if (empty($upload_url)) { $file->delete(); - + throw new \RuntimeException(\Idno\Core\Idno::site()->language()->_('There was a problem getting an upload URL for the newly minted file')); } - + // Mint an ID - - - - - - - - - - + // Lets tell people about where to stick the data - echo json_encode([ + echo json_encode( + [ 'uploadUrl' => $upload_url - ]); + ] + ); } } diff --git a/Idno/Pages/File/View.php b/Idno/Pages/File/View.php index 3c3442c435..c98f6a713e 100644 --- a/Idno/Pages/File/View.php +++ b/Idno/Pages/File/View.php @@ -20,8 +20,9 @@ function getContent() $object = \Idno\Entities\File::getByID($this->arguments[0]); } - if (empty($object)) + if (empty($object)) { $this->noContent(); + } session_write_close(); // Close the session early //header("Pragma: public"); @@ -82,10 +83,9 @@ function getContent() \Idno\Core\Idno::site()->logging()->debug("Partial content request for $c_start - $c_end bytes from $size available bytes"); // Validate range - if ( - ($c_start > $c_end) || // Start after end - ($c_end > $size) || // End after size - ($c_start < 0) // Start less than zero + if (($c_start > $c_end) // Start after end + || ($c_end > $size) // End after size + || ($c_start < 0) // Start less than zero ) { $this->setResponse(416); \Idno\Core\Idno::site()->logging()->debug('Requested Range Not Satisfiable'); diff --git a/Idno/Pages/Following/Confirm.php b/Idno/Pages/Following/Confirm.php index c3824bb1a8..3b81e1a7c3 100644 --- a/Idno/Pages/Following/Confirm.php +++ b/Idno/Pages/Following/Confirm.php @@ -20,13 +20,17 @@ function getContent() $items = $feed->retrieveItems(); $t = \Idno\Core\Idno::site()->template(); - $t->__(array( + $t->__( + array( 'title' => 'Subscribe to ' . $feed->getTitle(), - 'body' => $t->__(array( + 'body' => $t->__( + array( 'feed' => $feed, 'items' => $items - ))->draw('following/confirm') - ))->drawPage(); + ) + )->draw('following/confirm') + ) + )->drawPage(); } diff --git a/Idno/Pages/Following/Home.php b/Idno/Pages/Following/Home.php index bdc5fce2b1..71ad5ba5e3 100644 --- a/Idno/Pages/Following/Home.php +++ b/Idno/Pages/Following/Home.php @@ -13,10 +13,12 @@ function getContent() $this->gatekeeper(); $subscriptions = \Idno\Core\Idno::site()->reader()->getUserSubscriptions(\Idno\Core\Idno::site()->session()->currentUserUUID()); - \Idno\Core\Idno::site()->template()->__(array( + \Idno\Core\Idno::site()->template()->__( + array( 'title' => \Idno\Core\Idno::site()->language()->_('Following'), 'body' => \Idno\Core\Idno::site()->template()->__(array('subscriptions' => $subscriptions))->draw('following/home') - ))->drawPage(); + ) + )->drawPage(); } diff --git a/Idno/Pages/Homepage.php b/Idno/Pages/Homepage.php index e0d5542a25..646e2926e7 100644 --- a/Idno/Pages/Homepage.php +++ b/Idno/Pages/Homepage.php @@ -123,21 +123,25 @@ function getContent() } $t = \Idno\Core\Idno::site()->template(); - $t->__(array( + $t->__( + array( 'title' => $title, 'description' => $description, 'content' => $friendly_types, - 'body' => $t->__(array( + 'body' => $t->__( + array( 'items' => $feed, 'contentTypes' => $create, 'offset' => $offset, 'count' => $count, 'subject' => $query, 'content' => $friendly_types - ))->draw('pages/home'), + ) + )->draw('pages/home'), - ))->drawPage(); + ) + )->drawPage(); } /** diff --git a/Idno/Pages/Onboarding/Begin.php b/Idno/Pages/Onboarding/Begin.php index 2e37cd824d..c1dfaaf396 100644 --- a/Idno/Pages/Onboarding/Begin.php +++ b/Idno/Pages/Onboarding/Begin.php @@ -18,11 +18,13 @@ function getContent() } $t = \Idno\Core\Idno::site()->template(); - echo $t->__(array( + echo $t->__( + array( 'body' => $t->draw('onboarding/begin'), 'title' => \Idno\Core\Idno::site()->language()->_('Welcome to Known'), 'messages' => \Idno\Core\Idno::site()->session()->getAndFlushMessages() - ))->draw('shell/simple'); + ) + )->draw('shell/simple'); } diff --git a/Idno/Pages/Onboarding/Connect.php b/Idno/Pages/Onboarding/Connect.php index 0de838c80f..4f5e649d3a 100644 --- a/Idno/Pages/Onboarding/Connect.php +++ b/Idno/Pages/Onboarding/Connect.php @@ -20,13 +20,15 @@ function getContent() $_SESSION['onboarding_passthrough'] = true; $t = \Idno\Core\Idno::site()->template(); - echo $t->__(array( + echo $t->__( + array( 'title' => \Idno\Core\Idno::site()->language()->_("Connect some networks"), 'body' => $t->__(array('user' => $user))->draw('onboarding/connect'), 'messages' => \Idno\Core\Idno::site()->session()->getAndFlushMessages() - ))->draw('shell/simple'); + ) + )->draw('shell/simple'); //} else { // $this->forward(\Idno\Core\Idno::site()->config()->getURL() . 'begin/publish'); //} diff --git a/Idno/Pages/Onboarding/Profile.php b/Idno/Pages/Onboarding/Profile.php index 1d49d35f57..50521bf74c 100644 --- a/Idno/Pages/Onboarding/Profile.php +++ b/Idno/Pages/Onboarding/Profile.php @@ -17,13 +17,15 @@ function getContent() $user = \Idno\Core\Idno::site()->session()->currentUser(); $t = \Idno\Core\Idno::site()->template(); - echo $t->__(array( + echo $t->__( + array( 'title' => \Idno\Core\Idno::site()->language()->_("Create your profile"), 'body' => $t->__(array('user' => $user))->draw('onboarding/profile'), 'messages' => \Idno\Core\Idno::site()->session()->getAndFlushMessages() - ))->draw('shell/simple'); + ) + )->draw('shell/simple'); } diff --git a/Idno/Pages/Pubsubhubbub/Callback.php b/Idno/Pages/Pubsubhubbub/Callback.php index 9d5e15b461..1673ecf612 100644 --- a/Idno/Pages/Pubsubhubbub/Callback.php +++ b/Idno/Pages/Pubsubhubbub/Callback.php @@ -42,8 +42,9 @@ function getContent() // Check whether the intent is valid if (is_array($pending->$hub_mode) && in_array($subscription->getUUID(), $pending->$hub_mode)) { $new = array(); - foreach ($pending->$hub_mode as $value) + foreach ($pending->$hub_mode as $value) { $new[] = $value; + } $subscriber->pubsub_pending = serialize($new); $subscriber->save(); @@ -64,7 +65,8 @@ function post() // Since we've overloaded post, we need to parse the arguments $arguments = func_get_args(); - if (!empty($arguments)) $this->arguments = $arguments; + if (!empty($arguments)) { $this->arguments = $arguments; + } // Find users if (!empty($this->arguments[0])) { @@ -82,11 +84,13 @@ function post() \Idno\Core\Idno::site()->logging()->debug("Pubsub: Ping received, pinging out..."); - \Idno\Core\Idno::site()->events()->triggerEvent('pubsubhubbub/ping', array( + \Idno\Core\Idno::site()->events()->triggerEvent( + 'pubsubhubbub/ping', array( 'subscriber' => $subscriber, 'subscription' => $subscription, 'data' => trim(file_get_contents("php://input")) - )); + ) + ); } diff --git a/Idno/Pages/Search/Mentions.php b/Idno/Pages/Search/Mentions.php index cae9d3729d..a3209a1136 100644 --- a/Idno/Pages/Search/Mentions.php +++ b/Idno/Pages/Search/Mentions.php @@ -18,9 +18,11 @@ function getContent() $username = $this->getInput('username'); if ($users = User::get(array(), array(), 9999)) { //User::getByHandle($username)) { - \Idno\Core\Idno::site()->events()->triggerEvent('search/mentions', [ + \Idno\Core\Idno::site()->events()->triggerEvent( + 'search/mentions', [ 'username' => $username - ], $users); + ], $users + ); foreach ($users as $user) { /* @var \Idno\Entities\User $user */ diff --git a/Idno/Pages/Search/User.php b/Idno/Pages/Search/User.php index 60ee1f75bc..af72d72cc8 100644 --- a/Idno/Pages/Search/User.php +++ b/Idno/Pages/Search/User.php @@ -55,8 +55,9 @@ public function getContent() } global $template_postponed_link_actions; - if (!empty($template_postponed_link_actions)) + if (!empty($template_postponed_link_actions)) { $results['rendered'] .= $template_postponed_link_actions; + } echo json_encode($results); exit; } diff --git a/Idno/Pages/Service/Notifications/NewNotifications.php b/Idno/Pages/Service/Notifications/NewNotifications.php index f7e60fc14c..6e2d2b286e 100644 --- a/Idno/Pages/Service/Notifications/NewNotifications.php +++ b/Idno/Pages/Service/Notifications/NewNotifications.php @@ -21,48 +21,59 @@ function getContent($params = array()) $last_time = 0; } - $notifs = Notification::getFromX('Idno\Entities\Notification', [ + $notifs = Notification::getFromX( + 'Idno\Entities\Notification', [ 'owner' => $user->getUUID(), 'created' => ['$gt' => $last_time] - ]); + ] + ); if ($notifs) { - $notifs = array_filter($notifs, function ($notif) use ($last_time) { - return $notif->created > $last_time; - }); + $notifs = array_filter( + $notifs, function ($notif) use ($last_time) { + return $notif->created > $last_time; + } + ); - if (!empty($notifs[0]->created)) + if (!empty($notifs[0]->created)) { $user->last_notification_time = $notifs[0]->created; + } $user->save(); - $arr = array_filter(array_map(function ($notif) { + $arr = array_filter( + array_map( + function ($notif) { - $target = $notif->getTarget(); + $target = $notif->getTarget(); - if (!empty($target)) { // Ensure that notifications on unavailable targets are not rendered + if (!empty($target)) { // Ensure that notifications on unavailable targets are not rendered - Idno::site()->template()->setTemplateType('email-text'); - $body = Idno::site()->template()->__(['notification' => $notif])->draw($notif->getMessageTemplate()); - $annotation = $notif->getObject(); + Idno::site()->template()->setTemplateType('email-text'); + $body = Idno::site()->template()->__(['notification' => $notif])->draw($notif->getMessageTemplate()); + $annotation = $notif->getObject(); - return [ - 'title' => $notif->getMessage(), - 'body' => $body, - 'icon' => $annotation['owner_image'], - 'created' => date('c', $notif->created), - 'link' => (empty($notif->url)) ? \Idno\Core\Idno::site()->config()->getDisplayURL() . 'account/notifications' : $notif->link - ]; + return [ + 'title' => $notif->getMessage(), + 'body' => $body, + 'icon' => $annotation['owner_image'], + 'created' => date('c', $notif->created), + 'link' => (empty($notif->url)) ? \Idno\Core\Idno::site()->config()->getDisplayURL() . 'account/notifications' : $notif->link + ]; - } - }, $notifs)); + } + }, $notifs + ) + ); } else { $arr = []; } Idno::site()->template()->setTemplateType('json'); - Idno::site()->template()->__([ + Idno::site()->template()->__( + [ 'notifications' => $arr, - ])->drawPage(); + ] + )->drawPage(); } } diff --git a/Idno/Pages/Service/Queues/Dispatch.php b/Idno/Pages/Service/Queues/Dispatch.php index b19e01b7ed..7d7388ef9c 100644 --- a/Idno/Pages/Service/Queues/Dispatch.php +++ b/Idno/Pages/Service/Queues/Dispatch.php @@ -17,19 +17,23 @@ public function getContent() if (!empty($this->arguments[0])) { $object = \Idno\Common\Entity::getByID($this->arguments[0]); } - if (empty($object)) $this->noContent(); + if (empty($object)) { $this->noContent(); + } $eventqueue = \Idno\Core\Idno::site()->queue(); - if (!$eventqueue instanceof \Idno\Core\AsynchronousQueue) + if (!$eventqueue instanceof \Idno\Core\AsynchronousQueue) { throw new \RuntimeException("Service can't run unless Known's queue is Asynchronous!"); + } $result = $eventqueue->dispatch($object); - Idno::site()->template()->__([ + Idno::site()->template()->__( + [ 'event_id' => $this->arguments[0], 'complete' => $object->complete, 'completed_ts' => $object->completedTs - ])->drawPage(); + ] + )->drawPage(); } } diff --git a/Idno/Pages/Service/Queues/GC.php b/Idno/Pages/Service/Queues/GC.php index 74e64f6ec9..6f84e00137 100644 --- a/Idno/Pages/Service/Queues/GC.php +++ b/Idno/Pages/Service/Queues/GC.php @@ -15,8 +15,9 @@ public function getContent() \Idno\Core\Service::gatekeeper(); $eventqueue = \Idno\Core\Idno::site()->queue(); - if (!$eventqueue instanceof \Idno\Core\AsynchronousQueue) + if (!$eventqueue instanceof \Idno\Core\AsynchronousQueue) { throw new \RuntimeException("You are not running an asynchronous message queue, so garbage collection is unnecessary."); + } $queue = $this->getInput('queue', 'default'); @@ -24,9 +25,11 @@ public function getContent() $eventqueue->gc(300, $queue); - Idno::site()->template()->__([ + Idno::site()->template()->__( + [ 'gc' => true - ])->drawPage(); + ] + )->drawPage(); } } } \ No newline at end of file diff --git a/Idno/Pages/Service/Queues/Queue.php b/Idno/Pages/Service/Queues/Queue.php index 54a0206df7..bebdf3c37e 100644 --- a/Idno/Pages/Service/Queues/Queue.php +++ b/Idno/Pages/Service/Queues/Queue.php @@ -27,9 +27,11 @@ public function getContent() } } - Idno::site()->template()->__([ + Idno::site()->template()->__( + [ 'queue' => $array, - ])->drawPage(); + ] + )->drawPage(); } } } \ No newline at end of file diff --git a/Idno/Pages/Service/Security/CSRFToken.php b/Idno/Pages/Service/Security/CSRFToken.php index d0b0bdaf7a..5b1313ceab 100644 --- a/Idno/Pages/Service/Security/CSRFToken.php +++ b/Idno/Pages/Service/Security/CSRFToken.php @@ -12,8 +12,9 @@ function getContent() $this->setNoCache(); $action = $this->getInput('url'); - if (empty($action)) + if (empty($action)) { throw new \RuntimeException(\Idno\Core\Idno::site()->language()->_("URL missing")); + } //\Idno\Core\Idno::site()->logging()->debug("Updating token for $action"); @@ -22,10 +23,12 @@ function getContent() $token = \Idno\Core\Bonita\Forms::token($action, $time); header('Content-type: application/json'); - echo json_encode([ + echo json_encode( + [ 'time' => $time, 'token' => $token - ]); + ] + ); } } diff --git a/Idno/Pages/Service/Web/ImageProxy.php b/Idno/Pages/Service/Web/ImageProxy.php index 4fdfa7e1d9..fbec43a76d 100644 --- a/Idno/Pages/Service/Web/ImageProxy.php +++ b/Idno/Pages/Service/Web/ImageProxy.php @@ -23,14 +23,16 @@ protected function outputContent($content, $meta) if (strlen($content)>0) { header('Content-Length: ' . strlen($content)); - if (!empty($meta['mime'])) + if (!empty($meta['mime'])) { header("Content-Type: " . $meta['mime']); + } // Break long output to avoid an Apache performance bug $split_output = str_split($content, 1024); - foreach ($split_output as $chunk) + foreach ($split_output as $chunk) { echo $chunk; + } } } @@ -47,18 +49,23 @@ public function deleteContent() $proxyparams = ""; $maxsize = ""; - if (!empty($this->arguments[1])) + if (!empty($this->arguments[1])) { $maxsize = (int)$this->arguments[1]; - if (!empty($maxsize)) + } + if (!empty($maxsize)) { $proxyparams .= ((strpos($proxyparams, '?')===false)? '?':'&') . "maxsize=$maxsize"; + } $transform = ""; - if (!empty($this->arguments[2])) + if (!empty($this->arguments[2])) { $transform = strtolower($this->arguments[2]); - if ($transform == 'none') + } + if ($transform == 'none') { $transform = ""; - if (!empty($transform)) + } + if (!empty($transform)) { $proxyparams .= ((strpos($proxyparams, '?')===false)? '?':'&') . "transform=$transform"; + } if ($url) { @@ -67,10 +74,12 @@ public function deleteContent() $cache->delete(sha1("{$url}{$proxyparams}")); $cache->delete(sha1("{$url}{$proxyparams}").'_meta'); - echo json_encode([ + echo json_encode( + [ 'url' => $url, 'status' => true - ]); + ] + ); exit; } else { @@ -99,18 +108,23 @@ public function getContent() $proxyparams = ""; $maxsize = ""; - if (!empty($this->arguments[1])) + if (!empty($this->arguments[1])) { $maxsize = (int)$this->arguments[1]; - if (!empty($maxsize)) + } + if (!empty($maxsize)) { $proxyparams .= ((strpos($proxyparams, '?')===false)? '?':'&') . "maxsize=$maxsize"; + } $transform = ""; - if (!empty($this->arguments[2])) + if (!empty($this->arguments[2])) { $transform = strtolower($this->arguments[2]); - if ($transform == 'none') + } + if ($transform == 'none') { $transform = ""; - if (!empty($transform)) + } + if (!empty($transform)) { $proxyparams .= ((strpos($proxyparams, '?')===false)? '?':'&') . "transform=$transform"; + } if (!empty($url)) { @@ -219,7 +233,8 @@ public function getContent() \Idno\Core\Idno::site()->logging()->debug("Transforming image: Maxsize=$maxsize, Square=" . var_export($square, true)); $tmp = \Idno\Entities\File::writeTmpFile($result['content']); - if (!$tmp) throw new \RuntimeException(\Idno\Core\Idno::site()->language()->_("Could not save temporary file")); + if (!$tmp) { throw new \RuntimeException(\Idno\Core\Idno::site()->language()->_("Could not save temporary file")); + } if (!\Idno\Entities\File::isSVG($tmp, $tmp)) { @@ -250,7 +265,8 @@ public function getContent() } $size = strlen($content); - if ($size == 0) throw new \RuntimeException(\Idno\Core\Idno::site()->language()->_("Looks like something went wrong, image was zero bytes big!")); + if ($size == 0) { throw new \RuntimeException(\Idno\Core\Idno::site()->language()->_("Looks like something went wrong, image was zero bytes big!")); + } \Idno\Core\Idno::site()->logging()->debug("Storing " . $size . ' bytes of content.'); \Idno\Core\Idno::site()->logging()->debug('Meta: ' . print_r($meta, true)); diff --git a/Idno/Pages/Service/Web/UrlUnfurl.php b/Idno/Pages/Service/Web/UrlUnfurl.php index a99d3138ee..0c04239943 100644 --- a/Idno/Pages/Service/Web/UrlUnfurl.php +++ b/Idno/Pages/Service/Web/UrlUnfurl.php @@ -16,15 +16,18 @@ function deleteContent() $url = trim($this->getInput('url')); - if (empty($url)) + if (empty($url)) { throw new \RuntimeException(\Idno\Core\Idno::site()->language()->_("You need to specify a working URL")); + } // Try and get UnfurledURL entity if ($object = \Idno\Entities\UnfurledUrl::getBySourceURL($url)) { - echo json_encode([ + echo json_encode( + [ 'url' => $url, 'status' => $object->delete() - ]); + ] + ); } else { $this->noContent(); } @@ -43,8 +46,9 @@ function getContent() $url = trim($this->getInput('url')); $forcenew = $this->getInput('forcenew', false); - if (empty($url)) + if (empty($url)) { throw new \RuntimeException(\Idno\Core\Idno::site()->language()->_("You need to specify a working URL")); + } // Try and get UnfurledURL entity $object = \Idno\Entities\UnfurledUrl::getBySourceURL($url); @@ -60,13 +64,15 @@ function getContent() exit; } - if (empty($object)) + if (empty($object)) { $object = new \Idno\Entities\UnfurledUrl(); + } $object->setAccess('PUBLIC'); $result = $object->unfurl($url); - if (!$result) + if (!$result) { throw new \RuntimeException(\Idno\Core\Idno::site()->language()->_("Url %s could not be unfurled", [$url])); + } $object->save(); diff --git a/Idno/Pages/Session/CurrentUser.php b/Idno/Pages/Session/CurrentUser.php index d5b097bb9c..aa14a520b4 100644 --- a/Idno/Pages/Session/CurrentUser.php +++ b/Idno/Pages/Session/CurrentUser.php @@ -24,18 +24,21 @@ function postContent() function getContent() { $user = \Idno\Core\Idno::site()->session()->currentUser(); - if (empty($user)) $this->noContent(); + if (empty($user)) { $this->noContent(); + } $this->setPermalink(); // This is a permalink $t = \Idno\Core\Idno::site()->template(); - $t->__(array( + $t->__( + array( 'title' => $user->getTitle(), 'body' => $t->__(array('user' => $user))->draw('entity/User/profile'), 'description' => \Idno\Core\Idno::site()->language()->_('The %s profile for %s', [\Idno\Core\Idno::site()->config()->title, $user->getTitle()]) - ))->drawPage(); + ) + )->drawPage(); } } diff --git a/Idno/Pages/Stream/Home.php b/Idno/Pages/Stream/Home.php index c0d849a46c..6d16b4fb29 100644 --- a/Idno/Pages/Stream/Home.php +++ b/Idno/Pages/Stream/Home.php @@ -13,12 +13,16 @@ function getContent() if ($items = FeedItem::get()) { $t = \Idno\Core\Idno::site()->template(); - $t->__(array( + $t->__( + array( 'title' => 'Stream', - 'body' => $t->__(array( + 'body' => $t->__( + array( 'items' => $items - ))->draw('stream/home') - ))->drawPage(); + ) + )->draw('stream/home') + ) + )->drawPage(); } diff --git a/Idno/Pages/User/Edit.php b/Idno/Pages/User/Edit.php index eb18132332..662862081c 100644 --- a/Idno/Pages/User/Edit.php +++ b/Idno/Pages/User/Edit.php @@ -19,18 +19,21 @@ function getContent() if (!empty($this->arguments[0])) { $user = \Idno\Entities\User::getByHandle($this->arguments[0]); } - if (empty($user)) $this->forward(); // TODO: 404 + if (empty($user)) { $this->forward(); // TODO: 404 + } if (!$user->canEdit()) { $this->deniedContent(); } $t = \Idno\Core\Idno::site()->template(); - $t->__(array( + $t->__( + array( 'title' => \Idno\Core\Idno::site()->language()->_('Edit profile: %s', [$user->getTitle()]), 'body' => $t->__(array('user' => $user))->draw('entity/User/edit') - ))->drawPage(); + ) + )->drawPage(); } } diff --git a/Idno/Pages/User/View.php b/Idno/Pages/User/View.php index 1d2fb3244e..272d59427c 100644 --- a/Idno/Pages/User/View.php +++ b/Idno/Pages/User/View.php @@ -65,13 +65,15 @@ function getContent() $this->setLastModifiedHeader($last_modified); $t = \Idno\Core\Idno::site()->template(); - $t->__(array( + $t->__( + array( 'title' => $user->getTitle(), 'body' => $t->__(array('user' => $user, 'items' => $feed, 'count' => $count, 'offset' => $offset))->draw('entity/User/profile'), 'description' => \Idno\Core\Idno::site()->language()->_('The %s profile for %s', [\Idno\Core\Idno::site()->config()->title, $user->getTitle()]) - ))->drawPage(); + ) + )->drawPage(); } // Handle POST requests to the entity @@ -81,7 +83,8 @@ function postContent() if (!empty($this->arguments[0])) { $user = \Idno\Entities\User::getByHandle($this->arguments[0]); } - if (empty($user)) $this->forward(); // TODO: 404 + if (empty($user)) { $this->forward(); // TODO: 404 + } if ($user->saveDataFromInput()) { if ($onboarding = $this->getInput('onboarding')) { $this->forward(\Idno\Core\Idno::site()->config()->getURL() . 'begin/publish'); @@ -98,7 +101,8 @@ function deleteContent() if (!empty($this->arguments[0])) { $object = \Idno\Common\Entity::getByID($this->arguments[0]); } - if (empty($object)) $this->forward(); // TODO: 404 + if (empty($object)) { $this->forward(); // TODO: 404 + } if ($object->delete()) { \Idno\Core\Idno::site()->session()->addMessage(\Idno\Core\Idno::site()->language()->esc_('%s was deleted.', [$object->getTitle()])); } diff --git a/Idno/Pages/Webfinger/View.php b/Idno/Pages/Webfinger/View.php index 25257a7ef9..ad0cb064d7 100644 --- a/Idno/Pages/Webfinger/View.php +++ b/Idno/Pages/Webfinger/View.php @@ -29,10 +29,12 @@ function getContent() } $t = \Idno\Core\Idno::site()->template(); $t->setTemplateType('json'); - $t->__(array( + $t->__( + array( 'subject' => $acct, 'links' => $links - ))->drawPage(); + ) + )->drawPage(); } diff --git a/Idno/Pages/Webmentions/Endpoint.php b/Idno/Pages/Webmentions/Endpoint.php index 674ad04965..2b9da3942f 100644 --- a/Idno/Pages/Webmentions/Endpoint.php +++ b/Idno/Pages/Webmentions/Endpoint.php @@ -15,10 +15,12 @@ class Endpoint extends \Idno\Common\Page function getContent() { $t = \Idno\Core\Idno::site()->template(); - $t->__([ + $t->__( + [ 'title' => \Idno\Core\Idno::site()->language()->_('Webmention endpoint'), 'body' => $t->draw('pages/webmention') - ])->drawPage(); + ] + )->drawPage(); } function post() diff --git a/Idno/Stats/Counter.php b/Idno/Stats/Counter.php index c7a8f316cf..4841448c41 100644 --- a/Idno/Stats/Counter.php +++ b/Idno/Stats/Counter.php @@ -3,7 +3,7 @@ /** * Simple stats counter * - * @package idno + * @package idno * @subpackage core */ @@ -12,13 +12,16 @@ class Counter { - /** Array of counters */ + /** + * Array of counters + */ private static $counters = []; /** * Set the value of a counter. + * * @param string $counter - * @param int $value + * @param int $value */ public static function set($counter, $value) { @@ -29,6 +32,7 @@ public static function set($counter, $value) /** * Increment a counter value. + * * @param type $counter */ public static function increment($counter) @@ -42,6 +46,7 @@ public static function increment($counter) /** * Decrement a counter value. + * * @param type $counter */ public static function decrement($counter) @@ -55,14 +60,16 @@ public static function decrement($counter) /** * Retrieve the counter value - * @param type $counter + * + * @param type $counter * @return int */ public static function get($counter) { - if (isset(self::$counters[$counter])) + if (isset(self::$counters[$counter])) { return self::$counters[$counter]; + } return 0; } diff --git a/Idno/Stats/DummyStatisticsCollector.php b/Idno/Stats/DummyStatisticsCollector.php index 61b08640f8..e2bd0c318e 100644 --- a/Idno/Stats/DummyStatisticsCollector.php +++ b/Idno/Stats/DummyStatisticsCollector.php @@ -3,7 +3,7 @@ /** * Null implementation of StatisticsCollector, so that the system always has one available. * - * @package idno + * @package idno * @subpackage core */ diff --git a/Idno/Stats/StatisticsCollector.php b/Idno/Stats/StatisticsCollector.php index a718301951..a4571eea54 100644 --- a/Idno/Stats/StatisticsCollector.php +++ b/Idno/Stats/StatisticsCollector.php @@ -3,7 +3,7 @@ /** * Interface defining a mechanism to collect statistics about your known site. * - * @package idno + * @package idno * @subpackage core */ @@ -16,30 +16,30 @@ abstract class StatisticsCollector extends \Idno\Common\Component * Set timing values * * @param string $stat The metric(s) to set. - * @param float $time The elapsed time (ms) to log + * @param float $time The elapsed time (ms) to log * */ abstract public function timing($stat, $time); /** * Set gauge to a value * - * @param string $stat The metric(s) to set. - * @param float $value The value for the stats. + * @param string $stat The metric(s) to set. + * @param float $value The value for the stats. * */ abstract public function gauge($stat, $value); /** * A "Set" is a count of unique events. * - * @param string $stat The metric to set. - * @param float $value The value for the stats. + * @param string $stat The metric to set. + * @param float $value The value for the stats. * */ abstract public function set($stat, $value); /** * Increments stats counters * - * @param string $stat The metric to increment. + * @param string $stat The metric to increment. * @return boolean * */ abstract public function increment($stat); @@ -47,7 +47,7 @@ abstract public function increment($stat); /** * Decrements stats counters. * - * @param string $stat The metric to decrement. + * @param string $stat The metric to decrement. * @return boolean * */ abstract public function decrement($stat); diff --git a/Idno/Stats/Timer.php b/Idno/Stats/Timer.php index 97b5b7e401..c618885f10 100644 --- a/Idno/Stats/Timer.php +++ b/Idno/Stats/Timer.php @@ -3,7 +3,7 @@ /** * Simple timer interface * - * @package idno + * @package idno * @subpackage core */ @@ -16,6 +16,7 @@ class Timer /** * Start a timer. + * * @param type $timer */ public static function start($timer) @@ -25,6 +26,7 @@ public static function start($timer) /** * Retrieve the current number of seconds (with milliseconds) since $timer was started. + * * @param type $timer */ public static function value($timer) @@ -41,6 +43,7 @@ public static function value($timer) /** * Shorthand to log a given timer to the debug log. + * * @param type $timer */ public static function logTimer($timer) diff --git a/Idno/Stats/TotalTimer.php b/Idno/Stats/TotalTimer.php index 2883137a65..f736478c94 100644 --- a/Idno/Stats/TotalTimer.php +++ b/Idno/Stats/TotalTimer.php @@ -4,7 +4,7 @@ * Simple totalising timer * Useful for loops and calculating how much time is in each section * - * @package idno + * @package idno * @subpackage core */ @@ -20,17 +20,19 @@ public static function stop($timer) $value = parent::value($timer); - if (!isset(static::$timerTotals[$timer])) + if (!isset(static::$timerTotals[$timer])) { static::$timerTotals[$timer] = $value; - else + } else { static::$timerTotals[$timer] += $value; + } return static::$timerTotals[$timer]; } /** * Return the TOTAL timer value. - * @param type $timer + * + * @param type $timer * @return type * @throws \RuntimeException */ diff --git a/Idno/shims.php b/Idno/shims.php index e0faebb2c7..e9d4359097 100644 --- a/Idno/shims.php +++ b/Idno/shims.php @@ -37,9 +37,9 @@ function http_parse_headers($raw_headers) $h = explode(':', $h, 2); if (isset($h[1])) { - if (!isset($headers[$h[0]])) + if (!isset($headers[$h[0]])) { $headers[$h[0]] = trim($h[1]); - elseif (is_array($headers[$h[0]])) { + } elseif (is_array($headers[$h[0]])) { $headers[$h[0]] = array_merge($headers[$h[0]], array(trim($h[1]))); } else { $headers[$h[0]] = array_merge(array($headers[$h[0]]), array(trim($h[1]))); @@ -47,10 +47,11 @@ function http_parse_headers($raw_headers) $key = $h[0]; } else { - if (substr($h[0], 0, 1) == "\t") + if (substr($h[0], 0, 1) == "\t") { $headers[$key] .= "\r\n\t" . trim($h[0]); - elseif (!$key) + } elseif (!$key) { $headers[0] = trim($h[0]); + } trim($h[0]); } } diff --git a/Idno/start.php b/Idno/start.php index 1cf4c15887..e118f5393a 100644 --- a/Idno/start.php +++ b/Idno/start.php @@ -3,69 +3,72 @@ /** * Known loader and all-purpose conductor * - * @package idno + * @package idno * @subpackage core */ // Register a function to catch premature shutdowns and output some friendlier text - register_shutdown_function(function () { - $error = error_get_last(); - if ($error["type"] == E_ERROR) { + register_shutdown_function( + function () { + $error = error_get_last(); + if ($error["type"] == E_ERROR) { + + try { + ob_clean(); + } catch (ErrorException $e) { + } - try { - ob_clean(); - } catch (ErrorException $e) { - } + http_response_code(500); - http_response_code(500); + if (!empty($_SERVER['SERVER_NAME'])) { + $server_name = $_SERVER['SERVER_NAME']; + } else { + $server_name = ''; + } + if (!empty($_SERVER['REQUEST_URI'])) { + $request_uri = $_SERVER['REQUEST_URI']; + } else { + $request_uri = ''; + } - if (!empty($_SERVER['SERVER_NAME'])) { - $server_name = $_SERVER['SERVER_NAME']; - } else { - $server_name = ''; - } - if (!empty($_SERVER['REQUEST_URI'])) { - $request_uri = $_SERVER['REQUEST_URI']; - } else { - $request_uri = ''; - } + $error_message = "Fatal Error: {$error['file']}:{$error['line']} - \"{$error['message']}\", on page {$server_name}{$request_uri}"; + $message_text = explode("\n", $error['message'])[0]; - $error_message = "Fatal Error: {$error['file']}:{$error['line']} - \"{$error['message']}\", on page {$server_name}{$request_uri}"; - $message_text = explode("\n", $error['message'])[0]; + $title = $heading = "Oh no! Known experienced a problem!"; + $body = "<p>Known experienced a problem with this page and couldn't continue.</p>"; + $body .= "<p><strong>$message_text</strong></p>"; + $body .= "<p>The technical details are as follows:</p>"; + $body .= "<pre>$error_message</pre>"; - $title = $heading = "Oh no! Known experienced a problem!"; - $body = "<p>Known experienced a problem with this page and couldn't continue.</p>"; - $body .= "<p><strong>$message_text</strong></p>"; - $body .= "<p>The technical details are as follows:</p>"; - $body .= "<pre>$error_message</pre>"; + if (file_exists(dirname(dirname(__FILE__)) . '/support.inc')) { + include dirname(dirname(__FILE__)) . '/support.inc'; + } else { + $helplink = '<a href="https://withknown.com/opensource" target="_blank">Connect to other open source users for help.</a>'; + } - if (file_exists(dirname(dirname(__FILE__)) . '/support.inc')) { - include dirname(dirname(__FILE__)) . '/support.inc'; - } else { - $helplink = '<a href="https://withknown.com/opensource" target="_blank">Connect to other open source users for help.</a>'; - } + include dirname(dirname(__FILE__)) . '/statics/error-page.php'; - include(dirname(dirname(__FILE__)) . '/statics/error-page.php'); + $stats = \Idno\Core\Idno::site()->statistics(); + if (!empty($stats)) { + $stats->increment("error.fatal"); + } - $stats = \Idno\Core\Idno::site()->statistics(); - if (!empty($stats)) { - $stats->increment("error.fatal"); - } + if (isset(\Idno\Core\Idno::site()->logging) && \Idno\Core\Idno::site()->logging) { + \Idno\Core\Idno::site()->logging()->error($error_message); + } else { + error_log($error_message); + } - if (isset(\Idno\Core\Idno::site()->logging) && \Idno\Core\Idno::site()->logging) - \Idno\Core\Idno::site()->logging()->error($error_message); - else - error_log($error_message); + try { + \Idno\Core\Logging::oopsAlert($error_message, 'Oh no! Known experienced a problem!'); + } catch (Exception $ex) { + error_log($ex->getMessage()); + } - try { - \Idno\Core\Logging::oopsAlert($error_message, 'Oh no! Known experienced a problem!'); - } catch (Exception $ex) { - error_log($ex->getMessage()); + exit; } - - exit; } - }); + ); // This is a good time to see if we're running in a subdirectory if (!defined('KNOWN_UNIT_TEST')) { @@ -92,7 +95,7 @@ // Load external libraries if (file_exists(dirname(dirname(__FILE__)) . '/vendor/autoload.php')) { - require_once(dirname(dirname(__FILE__)) . '/vendor/autoload.php'); + include_once dirname(dirname(__FILE__)) . '/vendor/autoload.php'; } else { http_response_code(500); @@ -101,22 +104,19 @@ $body = '<p>It looks like you\'re running Known directly from a GitHub checkout. You need to run "composer install" to fetch other required packages!</p>'; $helplink = "<a href=\"http://docs.withknown.com/en/latest/install/instructions/\">Read installation instructions.</a>"; - include(dirname(dirname(__FILE__)) . '/statics/error-page.php'); + include dirname(dirname(__FILE__)) . '/statics/error-page.php'; exit(); } - // Host for the purposes of extra paths if (!empty($_SERVER['HTTP_HOST'])) { - $host = strtolower($_SERVER['HTTP_HOST']); $host = str_replace('www.', '', $host); define('KNOWN_MULTITENANT_HOST', $host); - } // Shims - include 'shims.php'; + require 'shims.php'; // Register the idno-templates folder as the place to look for templates in Bonita \Idno\Core\Bonita\Main::additionalPath(dirname(dirname(__FILE__))); diff --git a/Tests/API/BasicAPITest.php b/Tests/API/BasicAPITest.php index 4c7896a439..a1f46407cb 100644 --- a/Tests/API/BasicAPITest.php +++ b/Tests/API/BasicAPITest.php @@ -17,16 +17,18 @@ public function testConnection() $user = \Tests\KnownTestCase::user(); $endpoint = \Idno\Core\Idno::site()->config()->getDisplayURL() . ''; - $result = \Idno\Core\Webservice::get($endpoint, [], [ + $result = \Idno\Core\Webservice::get( + $endpoint, [], [ 'Accept: application/json', - ]); + ] + ); $content = json_decode($result['content']); $response = $result['response']; $this->assertEmpty($result['error'], 'The result\'s error property should be empty.'); $this->assertNotEmpty($content, 'Retrieved content should not be empty. Have you set the KNOWN_DOMAIN environment variable? Endpoint: ' . $endpoint); - $this->assertEquals($response, 200, 'The response should have returned a 200 HTTP response.'); + $this->assertEquals($response, 200, 'The response should have returned a 200 HTTP response.'); } @@ -39,13 +41,15 @@ public function testAuthenticatedPost() $user = \Tests\KnownTestCase::user(); $endpoint = \Idno\Core\Idno::site()->config()->url . 'status/edit'; - $result = \Idno\Core\Webservice::post($endpoint, [ + $result = \Idno\Core\Webservice::post( + $endpoint, [ 'body' => "Making a test post via the API", - ], [ + ], [ 'Accept: application/json', 'X-KNOWN-USERNAME: ' . $user->handle, 'X-KNOWN-SIGNATURE: ' . base64_encode(hash_hmac('sha256', '/status/edit', $user->getAPIkey(), true)), - ]); + ] + ); $content = json_decode($result['content']); $response = $result['response']; @@ -53,7 +57,7 @@ public function testAuthenticatedPost() $this->assertEmpty($result['error'], 'The result\'s error property should be empty.'); $this->assertNotEmpty($content, 'Retrieved content should not be empty. Have you set the KNOWN_DOMAIN environment variable? Endpoint: ' . $endpoint); $this->assertNotEmpty($content->location, 'Response should contain the location of the post.'); - $this->assertEquals($response, 200, 'The response should have returned a 200 HTTP response.'); + $this->assertEquals($response, 200, 'The response should have returned a 200 HTTP response.'); } } diff --git a/Tests/API/HSTSTest.php b/Tests/API/HSTSTest.php index 81a184b9f0..f78e624c9c 100644 --- a/Tests/API/HSTSTest.php +++ b/Tests/API/HSTSTest.php @@ -4,16 +4,17 @@ /** * Test HSTS handling on webservice calls + * * @TODO: mock endpoints rather than having them call real sites; what if the user really does have HSTS headers on localhost? */ class HSTSTest extends \Tests\KnownTestCase { - function setUp(): void { + function setUp(): void + { // Tidy up - if ($cache = \Idno\Core\Idno::site()->cache()) - { + if ($cache = \Idno\Core\Idno::site()->cache()) { $cache->delete(parse_url('http://localhost', PHP_URL_HOST)); $cache->delete(parse_url('http://mapkyca.com', PHP_URL_HOST)); } @@ -23,7 +24,8 @@ function setUp(): void { /** * Test that the specified endpoint doesn't have HSTS headers */ - function testNoHSTS() { + function testNoHSTS() + { $result = \Idno\Core\Webservice::get('http://localhost'); @@ -33,6 +35,7 @@ function testNoHSTS() { /** * Test that the specified endpoint has HSTS headers + * * @TODO: fix this so it doesn't depend on a particular website being online */ function testHSTS() @@ -46,10 +49,10 @@ function testHSTS() } - function tearDown(): void { + function tearDown(): void + { - if ($cache = \Idno\Core\Idno::site()->cache()) - { + if ($cache = \Idno\Core\Idno::site()->cache()) { $cache->delete(parse_url('http://localhost', PHP_URL_HOST)); $cache->delete(parse_url('http://mapkyca.com', PHP_URL_HOST)); } diff --git a/Tests/API/UploadTest.php b/Tests/API/UploadTest.php index 32a5307d05..651c8ec554 100644 --- a/Tests/API/UploadTest.php +++ b/Tests/API/UploadTest.php @@ -16,15 +16,17 @@ public function testPhotoUpload() $user = \Tests\KnownTestCase::user(); $endpoint = \Idno\Core\Idno::site()->config()->url . 'photo/edit'; - $result = \Idno\Core\Webservice::post($endpoint, [ + $result = \Idno\Core\Webservice::post( + $endpoint, [ 'title' => 'A Photo upload', 'body' => "Uploading a pretty picture via the api", 'photo' => \Idno\Core\WebserviceFile::createFromCurlString("@" . dirname(__FILE__) . "/" . self::$file . ";filename=Photo.jpg;type=image/jpeg") - ], [ + ], [ 'Accept: application/json', 'X-KNOWN-USERNAME: ' . $user->handle, 'X-KNOWN-SIGNATURE: ' . base64_encode(hash_hmac('sha256', '/photo/edit', $user->getAPIkey(), true)), - ]); + ] + ); $content = json_decode($result['content']); $response = $result['response']; @@ -32,7 +34,7 @@ public function testPhotoUpload() $this->assertEmpty($result['error'], 'The result\'s error property should be empty.'); $this->assertNotEmpty($content, 'Retrieved content should not be empty. Have you set the KNOWN_DOMAIN environment variable? Endpoint: ' . $endpoint); $this->assertNotEmpty($content->location, 'Response should contain the location of the post.'); - $this->assertEquals($response, 200, 'The response should have returned a 200 HTTP response.'); + $this->assertEquals($response, 200, 'The response should have returned a 200 HTTP response.'); } } } diff --git a/Tests/Core/FilesystemTest.php b/Tests/Core/FilesystemTest.php index a34c7ef812..adf89f3d4f 100644 --- a/Tests/Core/FilesystemTest.php +++ b/Tests/Core/FilesystemTest.php @@ -2,21 +2,24 @@ namespace Tests\Core { - class FilesystemTest extends \Tests\KnownTestCase { + class FilesystemTest extends \Tests\KnownTestCase + { - function testStoreContent() { + function testStoreContent() + { $content = "this is test content"; $filename = get_class($this) . '_' . time(); $filesystem = \Idno\Core\Idno::site()->filesystem(); - $id = $filesystem->storeContent($content, [ + $id = $filesystem->storeContent( + $content, [ 'filename' => $filename, 'meta_type' => 'text/plain' - ]); - + ] + ); $loaded = $filesystem->findOne($id); diff --git a/Tests/Core/GatekeeperTest.php b/Tests/Core/GatekeeperTest.php index 226775d068..1370c80cff 100644 --- a/Tests/Core/GatekeeperTest.php +++ b/Tests/Core/GatekeeperTest.php @@ -14,20 +14,22 @@ public function testGatekeeper() $response = $result['response']; $this->assertEmpty($result['error'], 'The result\'s error property should be empty.'); - $this->assertEquals($response, 403, 'The response should have returned a 403 HTTP response.'); + $this->assertEquals($response, 403, 'The response should have returned a 403 HTTP response.'); $user = \Tests\KnownTestCase::user(); $this->assertIsObject(\Idno\Core\Idno::site()->session()->logUserOn($user)); - $result = \Idno\Core\Webservice::get(\Idno\Core\Idno::site()->config()->url . 'account/settings/', [], [ + $result = \Idno\Core\Webservice::get( + \Idno\Core\Idno::site()->config()->url . 'account/settings/', [], [ 'X-KNOWN-USERNAME: ' . $user->handle, 'X-KNOWN-SIGNATURE: ' . base64_encode(hash_hmac('sha256', '/account/settings/', $user->getAPIkey(), true)), - ]); + ] + ); $response = $result['response']; $this->assertEmpty($result['error'], 'The result\'s error property should be empty.'); - $this->assertEquals($response, 200, 'The response should have returned a 200 HTTP response.'); + $this->assertEquals($response, 200, 'The response should have returned a 200 HTTP response.'); \Idno\Core\Idno::site()->session()->logUserOff(); } @@ -38,36 +40,40 @@ public function testAdminGatekeeper() $response = $result['response']; $this->assertEmpty($result['error'], 'The result\'s error property should be empty.'); - $this->assertEquals($response, 403, 'The response should have returned a 403 HTTP response.'); + $this->assertEquals($response, 403, 'The response should have returned a 403 HTTP response.'); $user = \Tests\KnownTestCase::user(); $this->assertIsObject(\Idno\Core\Idno::site()->session()->logUserOn($user)); // Try normal user \Idno\Core\Idno::site()->session()->logUserOff(); - $result = \Idno\Core\Webservice::get(\Idno\Core\Idno::site()->config()->url . 'admin/', [], [ + $result = \Idno\Core\Webservice::get( + \Idno\Core\Idno::site()->config()->url . 'admin/', [], [ 'X-KNOWN-USERNAME: ' . $user->handle, 'X-KNOWN-SIGNATURE: ' . base64_encode(hash_hmac('sha256', '/admin/', $user->getAPIkey(), true)), - ]); + ] + ); $response = $result['response']; $this->assertEmpty($result['error'], 'The result\'s error property should be empty.'); - $this->assertEquals($response, 403, 'The response should have returned a 403 HTTP response.'); + $this->assertEquals($response, 403, 'The response should have returned a 403 HTTP response.'); // Try admin $user = \Tests\KnownTestCase::admin(); $this->assertIsObject(\Idno\Core\Idno::site()->session()->logUserOn($user)); - $result = \Idno\Core\Webservice::get(\Idno\Core\Idno::site()->config()->url . 'admin/', [], [ + $result = \Idno\Core\Webservice::get( + \Idno\Core\Idno::site()->config()->url . 'admin/', [], [ 'X-KNOWN-USERNAME: ' . $user->handle, 'X-KNOWN-SIGNATURE: ' . base64_encode(hash_hmac('sha256', '/admin/', $user->getAPIkey(), true)), - ]); + ] + ); $response = $result['response']; $this->assertEmpty($result['error'], 'The result\'s error property should be empty.'); - $this->assertEquals($response, 403, 'The response should have returned a 403 HTTP response.'); + $this->assertEquals($response, 403, 'The response should have returned a 403 HTTP response.'); \Idno\Core\Idno::site()->session()->logUserOff(); } diff --git a/Tests/Core/TemplateTest.php b/Tests/Core/TemplateTest.php index ed471d6e66..bbac391562 100644 --- a/Tests/Core/TemplateTest.php +++ b/Tests/Core/TemplateTest.php @@ -6,7 +6,8 @@ class TemplateTest extends \Tests\KnownTestCase { - function parseURLsProvider() { + function parseURLsProvider() + { return [ 'first' => [ "This links to a weird domain <a href=\"http://deals.blackfriday\" target=\"_blank\" >http://<wbr />deals.blackfriday</a>.", @@ -24,8 +25,8 @@ function parseURLsProvider() { } /** - * @param type $expected - * @param type $text + * @param type $expected + * @param type $text * @dataProvider parseURLsProvider */ function testParseURLs($expected, $text) @@ -35,7 +36,6 @@ function testParseURLs($expected, $text) $this->assertEquals($expected, $t->parseURLs($text), 'URLs should parse from supplied post body.'); - } function testDataAttributes() diff --git a/Tests/Data/AccessGroupTest.php b/Tests/Data/AccessGroupTest.php index dd2122f28e..ee6002a5d7 100644 --- a/Tests/Data/AccessGroupTest.php +++ b/Tests/Data/AccessGroupTest.php @@ -78,7 +78,7 @@ public function testPrivateObject() // Test objects in this UUID $objs = \Idno\Entities\AccessGroup::getByAccessGroup(self::$acl->getUUID()); - $this->assertEquals(count($objs), 1, 'Exactly 1 entity with the specified UUID should have been retrieved.'); + $this->assertEquals(count($objs), 1, 'Exactly 1 entity with the specified UUID should have been retrieved.'); $obj->delete(); diff --git a/Tests/Data/DataConciergeTest.php b/Tests/Data/DataConciergeTest.php index cae8273b6d..537cd9c0ad 100644 --- a/Tests/Data/DataConciergeTest.php +++ b/Tests/Data/DataConciergeTest.php @@ -129,7 +129,7 @@ public function testGetByMetadata() { $null = \Idno\Entities\GenericDataItem::get(['variable1' => 'not']); - $this->assertEmpty($null,); + $this->assertEmpty($null); $objs = \Idno\Entities\GenericDataItem::get(['variable1' => 'test']); $this->assertIsArray($objs, 'Should have returned an array of objects.'); @@ -157,7 +157,7 @@ public function testGetByRange() $count = \Idno\Entities\GenericDataItem::countFromX('Idno\Entities\GenericDataItem', $search); $this->assertIsInt($count, 'A count of entities should be an integer.'); - $this->assertEquals($count, 1, '1 entity should match our query.'); + $this->assertEquals($count, 1, '1 entity should match our query.'); } public function testGetByRangeNoResults() @@ -169,7 +169,7 @@ public function testGetByRangeNoResults() $count = \Idno\Entities\GenericDataItem::countFromX('Idno\Entities\GenericDataItem', $search); $this->assertIsInt($count, 'A count of entities should be an integer.'); - $this->assertEquals($count, 0, 'No entities should match our query.'); + $this->assertEquals($count, 0, 'No entities should match our query.'); } public function testSearchShort() @@ -189,8 +189,9 @@ public function testSearchShort() public function testSearchLong() { - - /** Create couple of FTS objects, since MySQL FTS tables operate in natural language mode */ + /** + * Create couple of FTS objects, since MySQL FTS tables operate in natural language mode + */ $obj = new \Idno\Entities\GenericDataItem(); $obj->setDatatype('UnitTestObject'); $obj->setTitle("This is a test obj to get around MySQL natural language mode"); @@ -253,7 +254,9 @@ protected function validateObject($obj) public static function tearDownAfterClass():void { - if (self::$object) self::$object->delete(); + if (self::$object) { + self::$object->delete(); + } if (self::$fts_objects) { foreach (self::$fts_objects as $obj) { $obj->delete(); @@ -264,3 +267,4 @@ public static function tearDownAfterClass():void } // get by metadata, search + diff --git a/Tests/Data/MutateTest.php b/Tests/Data/MutateTest.php index dacae3e5ab..4de27cdd01 100644 --- a/Tests/Data/MutateTest.php +++ b/Tests/Data/MutateTest.php @@ -5,7 +5,8 @@ class MutateTest extends \Tests\KnownTestCase { - public function testMutation() { + public function testMutation() + { $remoteuser = new \Idno\Entities\RemoteUser(); $remoteuser->handle = 'Test Mutation User'; diff --git a/Tests/KnownTestCase.php b/Tests/KnownTestCase.php index cd0fd1b232..938f766da5 100644 --- a/Tests/KnownTestCase.php +++ b/Tests/KnownTestCase.php @@ -13,18 +13,19 @@ class KnownTestCase extends \PHPUnit\Framework\TestCase /** * Return a test user, creating it if necessary. + * * @return \Idno\Entities\User */ protected function &user() { // Have we already got a user? - if (static::$testUser) + if (static::$testUser) { return static::$testUser; + } // Get a user (shouldn't happen) - if ($user = \Idno\Entities\User::getByHandle('testuser')) - { + if ($user = \Idno\Entities\User::getByHandle('testuser')) { static::$testUser = $user; return $user; @@ -46,18 +47,19 @@ protected function &user() /** * Return an admin test user, creating it if necessary. + * * @return \Idno\Entities\User */ protected function &admin() { // Have we already got a user? - if (static::$testAdmin) + if (static::$testAdmin) { return static::$testAdmin; + } // Get a user (shouldn't happen) - if ($user = \Idno\Entities\User::getByHandle('testadmin')) - { + if ($user = \Idno\Entities\User::getByHandle('testadmin')) { static::$testAdmin = $user; return $user; @@ -80,6 +82,7 @@ protected function &admin() /** * Swap the currently logged in user. + * * @param \Idno\Entities\User $user */ protected function swapUser($user) @@ -94,7 +97,7 @@ protected function swapUser($user) return $current; } - + /** * Set settings. diff --git a/Tests/Pages/HomepageTest.php b/Tests/Pages/HomepageTest.php index e21dc48f1f..9cb86947a9 100644 --- a/Tests/Pages/HomepageTest.php +++ b/Tests/Pages/HomepageTest.php @@ -31,10 +31,12 @@ function test404Page() private function doWebmentionContent($source, $target) { $notification = false; - Idno::site()->events()->addListener('notify', function (Event $event) use (&$notification) { - $eventdata = $event->data(); - $notification = $eventdata['notification']; - }); + Idno::site()->events()->addListener( + 'notify', function (Event $event) use (&$notification) { + $eventdata = $event->data(); + $notification = $eventdata['notification']; + } + ); $sourceContent = <<<EOD <div class="h-entry"> diff --git a/Tests/Pages/User/ViewTest.php b/Tests/Pages/User/ViewTest.php index 95bb8bc2fb..bc39f18db4 100644 --- a/Tests/Pages/User/ViewTest.php +++ b/Tests/Pages/User/ViewTest.php @@ -12,10 +12,12 @@ function testWebmentionContent() $user = $this->user(); $notification = false; - Idno::site()->events()->addListener('notify', function (Event $event) use (&$notification) { - $eventdata = $event->data(); - $notification = $eventdata['notification']; - }); + Idno::site()->events()->addListener( + 'notify', function (Event $event) use (&$notification) { + $eventdata = $event->data(); + $notification = $eventdata['notification']; + } + ); $source = 'http://karenpage.dummy/looking-for-information-' . md5(time() . rand(0, 9999)); $target = $user->getURL(); diff --git a/Tests/_bootstrap.php b/Tests/_bootstrap.php index 6a7ea018c1..70150dece4 100644 --- a/Tests/_bootstrap.php +++ b/Tests/_bootstrap.php @@ -4,7 +4,7 @@ // so we can use .env files. require_once ensures that our call to start.php later on won't // cause an issue, even though we're calling this twice. if (file_exists(dirname(dirname(__FILE__)) . '/vendor/autoload.php')) { - require_once(dirname(dirname(__FILE__)) . '/vendor/autoload.php'); + include_once dirname(dirname(__FILE__)) . '/vendor/autoload.php'; } if (file_exists(dirname(dirname(__FILE__)) . '/.env')) { @@ -16,23 +16,28 @@ // Set some environment: Use export KNOWN_DOMAIN / KNOWN_PORT to override from the command line $domain = 'localhost'; -if (isset($_SERVER['KNOWN_DOMAIN'])) $domain = $_SERVER['KNOWN_DOMAIN']; +if (isset($_SERVER['KNOWN_DOMAIN'])) { + $domain = $_SERVER['KNOWN_DOMAIN']; +} -if (!$domain && isset($_SERVER['SERVER_NAME'])) +if (!$domain && isset($_SERVER['SERVER_NAME'])) { $domain = $_SERVER['SERVER_NAME']; +} $_SERVER['SERVER_NAME'] = $domain; $port = getenv('KNOWN_PORT'); -if (!$port && isset($_SERVER['SERVER_PORT'])) +if (!$port && isset($_SERVER['SERVER_PORT'])) { $port = $_SERVER['SERVER_PORT']; -if (!$port) +} +if (!$port) { $port = 80; +} $_SERVER['SERVER_PORT'] = $port; try { // Load Known framework - require_once(dirname(dirname(__FILE__)) . '/Idno/start.php'); + include_once dirname(dirname(__FILE__)) . '/Idno/start.php'; } catch (Exception $ex) { echo $ex->getMessage(); diff --git a/index.php b/index.php index a7cdf83472..52da9ef52f 100644 --- a/index.php +++ b/index.php @@ -10,7 +10,7 @@ * Project homepage: https://withknown.com/ * Project repo: https://github.com/idno/known * - * @package idno + * @package idno * @subpackage core */ @@ -20,14 +20,14 @@ $body = "Sorry, this version of PHP (".phpversion().") is not supported. This probably means that you should update your server to the latest stable PHP release."; $heading = "PHP Version not supported"; $helplink = '<a href="http://docs.withknown.com/en/latest/install/requirements/" target="_blank">Read system requirements</a>'; - - require(dirname(__FILE__) . '/statics/error-page.php'); + + include dirname(__FILE__) . '/statics/error-page.php'; exit; } // Load the idno framework -require_once(dirname(__FILE__) . '/Idno/start.php'); +require_once dirname(__FILE__) . '/Idno/start.php'; // Get page routes @@ -48,13 +48,15 @@ // Manage routing -\Idno\Core\PageHandler::hook('404', function ($params = array()) { - http_response_code(404); - $t = \Idno\Core\Idno::site()->template(); +\Idno\Core\PageHandler::hook( + '404', function ($params = array()) { + http_response_code(404); + $t = \Idno\Core\Idno::site()->template(); - // Take over page detection - \Idno\Core\Idno::site()->template()->autodetectTemplateType(); + // Take over page detection + \Idno\Core\Idno::site()->template()->autodetectTemplateType(); - (new \Idno\Pages\Homepage())->noContent(); -}); + (new \Idno\Pages\Homepage())->noContent(); + } +); \Idno\Core\PageHandler::serve($routes); diff --git a/known.php b/known.php index 2382e91b29..5a9f9b79ef 100755 --- a/known.php +++ b/known.php @@ -2,13 +2,13 @@ <?php define('KNOWN_CONSOLE', 'true'); - + // Load external libraries - if (file_exists(dirname(__FILE__) . '/vendor/autoload.php')) { - require_once(dirname(__FILE__) . '/vendor/autoload.php'); - } else { - die('Could not find autoload.php, did you run "composer install" ..?'); - } +if (file_exists(dirname(__FILE__) . '/vendor/autoload.php')) { + include_once dirname(__FILE__) . '/vendor/autoload.php'; +} else { + die('Could not find autoload.php, did you run "composer install" ..?'); +} // Register console namespace use Symfony\Component\Console\Application; @@ -47,9 +47,9 @@ function &application() $c = new $class(); if ($c instanceof \Idno\Common\ConsolePlugin) { $console->register($c->getCommand()) - ->setDescription($c->getDescription()) - ->setDefinition($c->getParameters()) - ->setCode([$c, 'execute']); + ->setDescription($c->getDescription()) + ->setDefinition($c->getParameters()) + ->setCode([$c, 'execute']); } } } else { @@ -59,9 +59,9 @@ function &application() $c = new $stubclass(); if ($c instanceof \Idno\Common\ConsolePlugin) { $console->register($c->getCommand()) - ->setDescription($c->getDescription()) - ->setDefinition($c->getParameters()) - ->setCode([$c, 'execute']); + ->setDescription($c->getDescription()) + ->setDefinition($c->getParameters()) + ->setCode([$c, 'execute']); } } } @@ -78,9 +78,9 @@ function &application() $c = new $class(); if ($c instanceof \Idno\Common\ConsolePlugin) { $console->register($c->getCommand()) - ->setDescription($c->getDescription()) - ->setDefinition($c->getParameters()) - ->setCode([$c, 'execute']); + ->setDescription($c->getDescription()) + ->setDefinition($c->getParameters()) + ->setCode([$c, 'execute']); } } @@ -94,9 +94,9 @@ function &application() $c = new $class2(); if ($c instanceof \Idno\Common\ConsolePlugin) { $console->register($c->getCommand()) - ->setDescription($c->getDescription()) - ->setDefinition($c->getParameters()) - ->setCode([$c, 'execute']); + ->setDescription($c->getDescription()) + ->setDefinition($c->getParameters()) + ->setCode([$c, 'execute']); } } } @@ -109,15 +109,17 @@ function &application() ->register('version') ->setDescription(\Idno\Core\Idno::site()->language()->_('Returns the current Known version as defined in version.known')) ->setDefinition([]) - ->setCode(function (\Symfony\Component\Console\Input\InputInterface $input, \Symfony\Component\Console\Output\OutputInterface $output) { - $output->writeln(file_get_contents(dirname(__FILE__) . '/version.known')); + ->setCode( + function (\Symfony\Component\Console\Input\InputInterface $input, \Symfony\Component\Console\Output\OutputInterface $output) { + $output->writeln(file_get_contents(dirname(__FILE__) . '/version.known')); - $remoteVersion = \Idno\Core\RemoteVersion::build(); - if (\Idno\Core\Version::build() < $remoteVersion) { - $version = \Idno\Core\RemoteVersion::version(); - $output->writeln(\Idno\Core\Idno::site()->language()->_("WARNING: Your build of Known is behind the latest version from Github (%s - %s). If you're having problems, you may want to try updating to the latest version.\nUpdate now: https://github.com/idno/Known\n", [$version, $remoteVersion])); + $remoteVersion = \Idno\Core\RemoteVersion::build(); + if (\Idno\Core\Version::build() < $remoteVersion) { + $version = \Idno\Core\RemoteVersion::version(); + $output->writeln(\Idno\Core\Idno::site()->language()->_("WARNING: Your build of Known is behind the latest version from Github (%s - %s). If you're having problems, you may want to try updating to the latest version.\nUpdate now: https://github.com/idno/Known\n", [$version, $remoteVersion])); + } } - }); + ); // Run the application diff --git a/statics/db.php b/statics/db.php index cd7fc47eef..408411d6fa 100644 --- a/statics/db.php +++ b/statics/db.php @@ -3,8 +3,9 @@ $title = 'Database error'; $heading = 'Oh no! We couldn\'t connect to the database.'; - if (empty($message)) - $message = ""; +if (empty($message)) { + $message = ""; +} $body = " <p> This probably means that the database settings changed, this Known site hasn't been set up yet, or @@ -16,6 +17,6 @@ $helplink = " <a href=\"http://docs.withknown.com\">See the Known documentation for help.</a> "; - - require_once(dirname(__FILE__) . '/error-page.php'); - \ No newline at end of file + + require_once dirname(__FILE__) . '/error-page.php'; + diff --git a/statics/error-page.php b/statics/error-page.php index f445f6b251..752438e84c 100644 --- a/statics/error-page.php +++ b/statics/error-page.php @@ -5,7 +5,7 @@ <meta name="viewport" content="width=device-width, initial-scale=1"> <title> - <?= $title; ?> + <?php echo $title; ?>