diff --git a/.scrutinizer.yml b/.scrutinizer.yml index 83b0351..245f626 100644 --- a/.scrutinizer.yml +++ b/.scrutinizer.yml @@ -1,7 +1,7 @@ # language: php build: environment: - php: 8.0.11 + php: 8.1 nodes: tests: true analysis: diff --git a/admin/about.php b/admin/about.php index 0da7865..b541221 100644 --- a/admin/about.php +++ b/admin/about.php @@ -23,7 +23,7 @@ xoops_cp_header(); $adminObject->displayNavigation(basename(__FILE__)); -$adminObject::setPaypal('xoopsfoundation@gmail.com'); +Admin::setPaypal('xoopsfoundation@gmail.com'); $adminObject->displayAbout(false); require_once __DIR__ . '/admin_footer.php'; diff --git a/admin/admin_header.php b/admin/admin_header.php index 6d83e94..934346f 100644 --- a/admin/admin_header.php +++ b/admin/admin_header.php @@ -17,18 +17,19 @@ **/ use Xmf\Module\Admin; -use XoopsModules\News; -use XoopsModules\News\Helper; +use XoopsModules\News\{ + Helper +}; + +require_once \dirname(__DIR__) . '/preloads/autoloader.php'; require \dirname(__DIR__, 3) . '/include/cp_header.php'; -require_once $GLOBALS['xoops']->path('www/class/xoopsformloader.php'); +require \dirname(__DIR__, 3) . '/class/xoopsformloader.php'; // require_once \dirname(__DIR__) . '/class/Utility.php'; require_once \dirname(__DIR__) . '/include/common.php'; -require_once \dirname(__DIR__) . '/preloads/autoloader.php'; - $moduleDirName = \basename(\dirname(__DIR__)); -/** @var \XoopsModules\News\Helper $helper */ +/** @var XoopsModules\News\Helper $helper */ $helper = Helper::getInstance(); /** @var Xmf\Module\Admin $adminObject */ diff --git a/admin/amsimport.php b/admin/amsimport.php index 1cbea36..70b325d 100644 --- a/admin/amsimport.php +++ b/admin/amsimport.php @@ -24,11 +24,12 @@ * @copyright 2005, 2006 - Hervé Thouzard */ -use XoopsModules\Ams; use XoopsModules\Ams\Helper as AmsHelper; -use XoopsModules\News\Files; -use XoopsModules\News\NewsStory; -use XoopsModules\News\NewsTopic; +use XoopsModules\News\{ + Files, + NewsStory, + NewsTopic +}; require \dirname(__DIR__, 3) . '/include/cp_header.php'; xoops_cp_header(); @@ -39,16 +40,7 @@ require_once XOOPS_ROOT_PATH . '/class/xoopstree.php'; if (is_object($xoopsUser) && $xoopsUser->isAdmin($xoopsModule->mid())) { - if (!isset($_POST['go'])) { - echo '

Welcome to the AMS 2.41 import script

'; - echo '

Select the import options you wan to use :'; - echo "
"; - echo "
Import forums links inside news (at the bottom of the news)"; - echo "
Import external links inside news (at the bottom of the news)"; - echo "

"; - echo '
'; - echo "

If you check the two last options then the forum's link and all the external links will be added at the end of the body text."; - } else { + if (isset($_POST['go'])) { // Launch the import /** @var \XoopsModules\Ams\Helper $amsHelper */ $amsHelper = AmsHelper::getInstance(); @@ -123,17 +115,29 @@ $ams_newsid = $article['storyid']; // We search for the last version - $result2 = $db->query('SELECT * FROM ' . $ams_text . ' WHERE storyid=' . $ams_newsid . ' AND current=1'); + $sql = 'SELECT * FROM ' . $ams_text . ' WHERE storyid=' . $ams_newsid . ' AND current=1'; + $result2 = $db->query($sql); + if (!$db->isResultSet($result2)) { + \trigger_error("Query Failed! SQL: $sql Error: " . $db->error(), \E_USER_ERROR); + } $text_lastversion = $db->fetchArray($result2); // We search for the number of votes - $result3 = $db->query('SELECT count(*) AS cpt FROM ' . $ams_rating . ' WHERE storyid=' . $ams_newsid); + $sql = 'SELECT count(*) AS cpt FROM ' . $ams_rating . ' WHERE storyid=' . $ams_newsid; + $result3 = $db->query($sql); + if (!$db->isResultSet($result3)) { + \trigger_error("Query Failed! SQL: $sql Error: " . $db->error(), \E_USER_ERROR); + } $votes = $db->fetchArray($result3); // The links $links = ''; if ($use_extlinks) { - $result7 = $db->query('SELECT * FROM ' . $ams_links . ' WHERE storyid=' . $ams_newsid . ' ORDER BY linkid'); + $sql = 'SELECT * FROM ' . $ams_links . ' WHERE storyid=' . $ams_newsid . ' ORDER BY linkid'; + $result7 = $db->query($sql); + if (!$db->isResultSet($result7)) { + \trigger_error("Query Failed! SQL: $sql Error: " . $db->error(), \E_USER_ERROR); + } while (false !== ($link = $db->fetchArray($result7))) { if ('' == trim($links)) { $links = "\n\n" . _AMS_NW_RELATEDARTICLES . "\n\n"; @@ -179,7 +183,11 @@ $news_newsid = $news->storyid(); // ******************** // The files - $result4 = $db->query('SELECT * FROM ' . $ams_files . ' WHERE storyid=' . $ams_newsid); + $sql = 'SELECT * FROM ' . $ams_files . ' WHERE storyid=' . $ams_newsid; + $result4 = $db->query($sql); + if (!$db->isResultSet($result4)) { + \trigger_error("Query Failed! SQL: $sql Error: " . $db->error(), \E_USER_ERROR); + } while (false !== ($file = $db->fetchArray($result4))) { $sfile = new Files(); $sfile->setFileRealName($file['filerealname']); @@ -194,16 +202,19 @@ } // The ratings - $result5 = $db->query('SELECT * FROM ' . $ams_rating . ' WHERE storyid=' . $ams_newsid); + $sql = 'SELECT * FROM ' . $ams_rating . ' WHERE storyid=' . $ams_newsid; + $result5 = $db->query($sql); + if (!$db->isResultSet($result5)) { + \trigger_error("Query Failed! SQL: $sql Error: " . $db->error(), \E_USER_ERROR); + } while (false !== ($ratings = $db->fetchArray($result5))) { - $result6 = $db->queryF( - 'INSERT INTO ' . $news_stories_votedata . ' (storyid, ratinguser, rating, ratinghostname, ratingtimestamp) VALUES (' . $news_newsid . ',' . $ratings['ratinguser'] . ',' . $ratings['rating'] . ',' . $ratings['ratinghostname'] . ',' . $ratings['ratingtimestamp'] . ')' - ); + $sql = ' INSERT INTO ' . $news_stories_votedata . ' (storyid, ratinguser, rating, ratinghostname, ratingtimestamp) VALUES (' . $news_newsid . ',' . $ratings['ratinguser'] . ',' . $ratings['rating'] . ',' . $ratings['ratinghostname'] . ',' . $ratings['ratingtimestamp'] . ')'; + $result6 = $db->queryF($sql); } // The comments $comments = $commentHandler->getByItemId($ams_mid, $ams_newsid, 'ASC'); - if ($comments && is_array($comments)) { + if ($comments && \is_array($comments)) { foreach ($comments as $onecomment) { $onecomment->setNew(); $onecomment->setVar('com_modid', $news_mid); @@ -219,7 +230,7 @@ $criteria->add(new \Criteria('not_itemid', $ams_newsid)); $criteria->setOrder('ASC'); $notifications = $notificationHandler->getObjects($criteria); - if ($notifications && is_array($notifications)) { + if ($notifications && \is_array($notifications)) { foreach ($notifications as $onenotification) { $onenotification->setNew(); $onenotification->setVar('not_modid', $news_mid); @@ -235,7 +246,7 @@ $criteria->add(new \Criteria('not_category', 'global')); $criteria->setOrder('ASC'); $notifications = $notificationHandler->getObjects($criteria); - if ($notifications && is_array($notifications)) { + if ($notifications && \is_array($notifications)) { foreach ($notifications as $onenotification) { $onenotification->setNew(); $onenotification->setVar('not_modid', $news_mid); @@ -245,6 +256,15 @@ } unset($notifications); echo "

The import is finished, don't forget to verify and set the topics permissions !

"; + } else { + echo '

Welcome to the AMS 2.41 import script

'; + echo '

Select the import options you wan to use :'; + echo "
"; + echo "
Import forums links inside news (at the bottom of the news)"; + echo "
Import external links inside news (at the bottom of the news)"; + echo "

"; + echo '
'; + echo "

If you check the two last options then the forum's link and all the external links will be added at the end of the body text."; } } else { redirect_header(XOOPS_URL . '/modules/news/index.php', 3, _NOPERM); diff --git a/admin/functions.php b/admin/functions.php index dcc3abc..c266502 100644 --- a/admin/functions.php +++ b/admin/functions.php @@ -25,14 +25,14 @@ * * NOTE : Please give credits if you copy this code ! * - * @param string $tablename + * @param string|null $tablename * @param string $iconname * @copyright:: (c) Hervé Thouzard (https://www.herve-thouzard.com) * @author :: Hervé Thouzard (https://www.herve-thouzard.com) & Dojo Javscript Toolkit */ -function news_collapsableBar($tablename = '', $iconname = ''): void +function news_collapsableBar(?string $tablename = null, string $iconname = ''): void { - ?> + ?>$tablename ??= ''; '); } - } catch (\Throwable $e) { + } catch (\Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n", '
'; } } @@ -55,15 +53,19 @@ public static function copyFile(string $file, string $folder): bool } /** - * @param $src - * @param $dst + * @param string $src + * @param string $dst */ - public static function recurseCopy($src, $dst): void + public static function recurseCopy(string $src, string $dst): void { $dir = \opendir($src); // @mkdir($dst); - if (!@\mkdir($dst) && !\is_dir($dst)) { - throw new RuntimeException('The directory ' . $dst . ' could not be created.'); + try { + if (!\mkdir($dst) && !\is_dir($dst)) { + throw new \RuntimeException('The directory ' . $dst . ' could not be created.'); + } + } catch (\RuntimeException $e) { + echo 'Caught exception: ', $e->getMessage(), "
\n"; } while (false !== ($file = \readdir($dir))) { if (('.' !== $file) && ('..' !== $file)) { @@ -87,21 +89,21 @@ public static function recurseCopy($src, $dst): void * * @uses \Xmf\Module\Helper::getHelper() */ - public static function deleteDirectory($src) + public static function deleteDirectory(string $src): bool { // Only continue if user is a 'global' Admin - if (!($GLOBALS['xoopsUser'] instanceof XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) { + if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) { return false; } $success = true; // remove old files - $dirInfo = new SplFileInfo($src); + $dirInfo = new \SplFileInfo($src); // validate is a directory if ($dirInfo->isDir()) { $fileList = \array_diff(\scandir($src, \SCANDIR_SORT_NONE), ['..', '.']); foreach ($fileList as $k => $v) { - $fileInfo = new SplFileInfo("{$src}/{$v}"); + $fileInfo = new \SplFileInfo("$src/$v"); if ($fileInfo->isDir()) { // recursively handle subdirectories if (!$success = self::deleteDirectory($fileInfo->getRealPath())) { @@ -132,10 +134,10 @@ public static function deleteDirectory($src) * * @return bool true on success */ - public static function rrmdir($src) + public static function rrmdir(string $src): bool { // Only continue if user is a 'global' Admin - if (!($GLOBALS['xoopsUser'] instanceof XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) { + if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) { return false; } @@ -147,7 +149,7 @@ public static function rrmdir($src) $success = true; // Open the source directory to read in files - $iterator = new DirectoryIterator($src); + $iterator = new \DirectoryIterator($src); foreach ($iterator as $fObj) { if ($fObj->isFile()) { $filename = $fObj->getPathname(); @@ -173,10 +175,10 @@ public static function rrmdir($src) * * @return bool true on success */ - public static function rmove($src, $dest) + public static function rmove(string $src, string $dest): bool { // Only continue if user is a 'global' Admin - if (!($GLOBALS['xoopsUser'] instanceof XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) { + if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) { return false; } @@ -191,13 +193,13 @@ public static function rmove($src, $dest) } // Open the source directory to read in files - $iterator = new DirectoryIterator($src); + $iterator = new \DirectoryIterator($src); foreach ($iterator as $fObj) { if ($fObj->isFile()) { - \rename($fObj->getPathname(), "{$dest}/" . $fObj->getFilename()); + \rename($fObj->getPathname(), "$dest/" . $fObj->getFilename()); } elseif (!$fObj->isDot() && $fObj->isDir()) { // Try recursively on directory - self::rmove($fObj->getPathname(), "{$dest}/" . $fObj->getFilename()); + self::rmove($fObj->getPathname(), "$dest/" . $fObj->getFilename()); // rmdir($fObj->getPath()); // now delete the directory } } @@ -212,15 +214,15 @@ public static function rmove($src, $dest) * @param string $src - Source of files being moved * @param string $dest - Destination of files being moved * - * @return bool true on success + * @uses \Xmf\Module\Helper::getHelper() * @uses \Xmf\Module\Helper::isUserAdmin() * - * @uses \Xmf\Module\Helper::getHelper() + * @return bool true on success */ - public static function rcopy($src, $dest) + public static function rcopy(string $src, string $dest): bool { // Only continue if user is a 'global' Admin - if (!($GLOBALS['xoopsUser'] instanceof XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) { + if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) { return false; } @@ -235,12 +237,12 @@ public static function rcopy($src, $dest) } // Open the source directory to read in files - $iterator = new DirectoryIterator($src); + $iterator = new \DirectoryIterator($src); foreach ($iterator as $fObj) { if ($fObj->isFile()) { - \copy($fObj->getPathname(), "{$dest}/" . $fObj->getFilename()); + \copy($fObj->getPathname(), "$dest/" . $fObj->getFilename()); } elseif (!$fObj->isDot() && $fObj->isDir()) { - self::rcopy($fObj->getPathname(), "{$dest}/" . $fObj->getFilename()); + self::rcopy($fObj->getPathname(), "$dest/" . $fObj->getFilename()); } } diff --git a/class/Common/Migrate.php b/class/Common/Migrate.php index a8ce04d..4d51fff 100644 --- a/class/Common/Migrate.php +++ b/class/Common/Migrate.php @@ -52,9 +52,9 @@ public function __construct() * * @param string $tableName table to convert * @param string $columnName column to convert - * @param string $attribute new attribute + * @param string $attribute new attribute */ - private function changeColumnSize($tableName, $columnName, $attribute) + private function changeColumnSize(string $tableName, string $columnName, string $attribute): void { $moduleDirName = \basename(\dirname(__DIR__, 2)); $moduleDirNameUpper = \mb_strtoupper($moduleDirName); @@ -63,7 +63,7 @@ private function changeColumnSize($tableName, $columnName, $attribute) if ($tables->useTable($tableName)) { $tables->alterColumn($tableName, $columnName, $attribute); if (!$tables->executeQueue()) { - echo '
' . constant('CO_' . $moduleDirNameUpper . '_UPGRADEFAILED4') . ' ' . $tables->getLastError(); + echo '
' . \constant('CO_' . $moduleDirNameUpper . '_' . 'UPGRADEFAILED4') . ' ' . $tables->getLastError(); } } } diff --git a/class/Common/ModuleStats.php b/class/Common/ModuleStats.php new file mode 100644 index 0000000..025fa4b --- /dev/null +++ b/class/Common/ModuleStats.php @@ -0,0 +1,41 @@ + + */ + +trait ModuleStats +{ + /** + * @param \XoopsModules\News\Common\Configurator $configurator + * @return array + */ + + public static function getModuleStats($configurator) + { + $moduleStats = []; + if (\count($configurator->moduleStats) > 0) { + foreach (\array_keys($configurator->moduleStats) as $i) { + $moduleStats[$i] = $configurator->moduleStats[$i]; + } + } + + return $moduleStats; + } +} diff --git a/class/Common/ServerStats.php b/class/Common/ServerStats.php index ea1c9eb..72afdca 100644 --- a/class/Common/ServerStats.php +++ b/class/Common/ServerStats.php @@ -24,7 +24,7 @@ trait ServerStats * * @return string */ - public static function getServerStats() + public static function getServerStats(): string { //mb $wfdownloads = WfdownloadsWfdownloads::getInstance(); $moduleDirName = \basename(\dirname(__DIR__, 2)); @@ -36,40 +36,44 @@ public static function getServerStats() // $sql .= " WHERE metakey='version' LIMIT 1"; // $query = $GLOBALS['xoopsDB']->query($sql); // list($meta) = $GLOBALS['xoopsDB']->fetchRow($query); - $html .= "
" . \constant('CO_' . $moduleDirNameUpper . '_IMAGEINFO') . "\n"; + $html .= "
" . \constant('CO_' . $moduleDirNameUpper . '_' . 'IMAGEINFO') . "\n"; $html .= "
\n"; - // $html .= '
' . constant('CO_' . $moduleDirNameUpper . '_METAVERSION') . $meta . "
\n"; + // $html .= '
' . constant('CO_' . $moduleDirNameUpper . '_' . 'METAVERSION') . $meta . "
\n"; // $html .= "
\n"; // $html .= "
\n"; - $html .= '
' . \constant('CO_' . $moduleDirNameUpper . '_SPHPINI') . "
\n"; + $html .= '
' . \constant('CO_' . $moduleDirNameUpper . '_' . 'SPHPINI') . "
\n"; $html .= "
    \n"; - $gdlib = \function_exists('gd_info') ? '' . \constant('CO_' . $moduleDirNameUpper . '_GDON') . '' : '' . \constant('CO_' . $moduleDirNameUpper . '_GDOFF') . ''; - $html .= '
  • ' . \constant('CO_' . $moduleDirNameUpper . '_GDLIBSTATUS') . $gdlib; + $gdlib = \function_exists('gd_info') ? '' . \constant('CO_' . $moduleDirNameUpper . '_' . 'GDON') . '' : '' . \constant('CO_' . $moduleDirNameUpper . '_' . 'GDOFF') . ''; + $html .= '
  • ' . \constant('CO_' . $moduleDirNameUpper . '_' . 'GDLIBSTATUS') . $gdlib; if (\function_exists('gd_info')) { - if (true === ($gdlib = gd_info())) { - $html .= '
  • ' . \constant('CO_' . $moduleDirNameUpper . '_GDLIBVERSION') . '' . $gdlib['GD Version'] . ''; + $html .= '
  • ' . \constant('CO_' . $moduleDirNameUpper . '_' . 'GDLIBSTATUS') . '' . \constant('CO_' . $moduleDirNameUpper . '_' . 'GDON') . ''; + $gdlib = \gd_info(); + if (!empty(($gdlib))) { + $html .= '
  • ' . \constant('CO_' . $moduleDirNameUpper . '_' . 'GDLIBVERSION') . '' . $gdlib['GD Version'] . ''; } + } else { + $html .= '
  • ' . \constant('CO_' . $moduleDirNameUpper . '_' . 'GDLIBSTATUS') . '' . \constant('CO_' . $moduleDirNameUpper . '_' . 'GDOFF') . ''; } // - // $safemode = ini_get('safe_mode') ? constant('CO_' . $moduleDirNameUpper . '_ON') . constant('CO_' . $moduleDirNameUpper . '_SAFEMODEPROBLEMS : constant('CO_' . $moduleDirNameUpper . '_OFF'); + // $safemode = ini_get('safe_mode') ? constant('CO_' . $moduleDirNameUpper . '_' . 'ON') . constant('CO_' . $moduleDirNameUpper . '_SAFEMODEPROBLEMS : constant('CO_' . $moduleDirNameUpper . '_' . 'OFF'); // $html .= '
  • ' . constant('CO_' . $moduleDirNameUpper . '_SAFEMODESTATUS . $safemode; // - // $registerglobals = (!ini_get('register_globals')) ? "" . constant('CO_' . $moduleDirNameUpper . '_OFF') . '' : "" . constant('CO_' . $moduleDirNameUpper . '_ON') . ''; + // $registerglobals = (!ini_get('register_globals')) ? "" . constant('CO_' . $moduleDirNameUpper . '_' . 'OFF') . '' : "" . constant('CO_' . $moduleDirNameUpper . '_' . 'ON') . ''; // $html .= '
  • ' . constant('CO_' . $moduleDirNameUpper . '_REGISTERGLOBALS . $registerglobals; // - $downloads = \ini_get('file_uploads') ? '' . \constant('CO_' . $moduleDirNameUpper . '_ON') . '' : '' . \constant('CO_' . $moduleDirNameUpper . '_OFF') . ''; - $html .= '
  • ' . \constant('CO_' . $moduleDirNameUpper . '_SERVERUPLOADSTATUS') . $downloads; + $downloads = \ini_get('file_uploads') ? '' . \constant('CO_' . $moduleDirNameUpper . '_' . 'ON') . '' : '' . \constant('CO_' . $moduleDirNameUpper . '_' . 'OFF') . ''; + $html .= '
  • ' . \constant('CO_' . $moduleDirNameUpper . '_' . 'SERVERUPLOADSTATUS') . $downloads; - $html .= '
  • ' . \constant('CO_' . $moduleDirNameUpper . '_MAXUPLOADSIZE') . ' ' . \ini_get('upload_max_filesize') . "\n"; - $html .= '
  • ' . \constant('CO_' . $moduleDirNameUpper . '_MAXPOSTSIZE') . ' ' . \ini_get('post_max_size') . "\n"; - $html .= '
  • ' . \constant('CO_' . $moduleDirNameUpper . '_MEMORYLIMIT') . ' ' . \ini_get('memory_limit') . "\n"; + $html .= '
  • ' . \constant('CO_' . $moduleDirNameUpper . '_' . 'MAXUPLOADSIZE') . ' ' . \ini_get('upload_max_filesize') . "\n"; + $html .= '
  • ' . \constant('CO_' . $moduleDirNameUpper . '_' . 'MAXPOSTSIZE') . ' ' . \ini_get('post_max_size') . "\n"; + $html .= '
  • ' . \constant('CO_' . $moduleDirNameUpper . '_' . 'MEMORYLIMIT') . ' ' . \ini_get('memory_limit') . "\n"; $html .= "
\n"; $html .= "
    \n"; - $html .= '
  • ' . \constant('CO_' . $moduleDirNameUpper . '_SERVERPATH') . ' ' . XOOPS_ROOT_PATH . "\n"; + $html .= '
  • ' . \constant('CO_' . $moduleDirNameUpper . '_' . 'SERVERPATH') . ' ' . XOOPS_ROOT_PATH . "\n"; $html .= "
\n"; $html .= "
\n"; - $html .= \constant('CO_' . $moduleDirNameUpper . '_UPLOADPATHDSC') . "\n"; + $html .= \constant('CO_' . $moduleDirNameUpper . '_' . 'UPLOADPATHDSC') . "\n"; $html .= '
'; $html .= '

'; diff --git a/class/Common/SysUtility.php b/class/Common/SysUtility.php index 758bcb5..2b1df0f 100644 --- a/class/Common/SysUtility.php +++ b/class/Common/SysUtility.php @@ -22,123 +22,299 @@ * @author Mamba */ -use XoopsFormEditor; -use XoopsModules\News\Helper; +use Xmf\Request; +use Xmf\Module\Helper\Cache; +use XoopsModules\News\{ + Helper +}; + + /** * Class SysUtility */ class SysUtility { - use VersionChecks; + //traits + use VersionChecks; //checkVerXoops, checkVerPhp Traits + use ServerStats; // getServerStats Trait + use FilesManagement; // Files Management Trait + use ModuleStats; // ModuleStats Trait + + //--------------- Common module methods ----------------------------- + + /** + * Access the only instance of this class + */ + public static function getInstance(): self + { + static $instance; + if (null === $instance) { + $instance = new static(); + } + + return $instance; + } + + /** + * @param string $text + * @param string $form_sort + * + * @return string + */ + public static function selectSorting(string $text, string $form_sort): string + { + global $start, $order, $sort; + + $selectView = ''; + $helper = Helper::getInstance(); + + //$pathModIcon16 = XOOPS_URL . '/modules/' . $moduleDirName . '/' . $helper->getConfig('modicons16'); + $pathModIcon16 = $helper->url($helper->getModule()->getInfo('modicons16')); + + $selectView = '
' . $text . ''; + //$sorts = $sort == 'asc' ? 'desc' : 'asc'; + if ($form_sort == $sort) { + $sel1 = 'asc' === $order ? 'selasc.png' : 'asc.png'; + $sel2 = 'desc' === $order ? 'seldesc.png' : 'desc.png'; + } else { + $sel1 = 'asc.png'; + $sel2 = 'desc.png'; + } + $selectView .= ' ASC'; + $selectView .= 'DESC'; + $selectView .= '
'; - //checkVerXoops, checkVerPhp Traits + return $selectView; + } - use ServerStats; + //--------------- BLOCKS ----------------------------- - // getServerStats Trait + /** + * @param array $cats + * + * @return string + */ + public static function blockAddCatSelect(array $cats): string + { + $catSql = ''; + if (!empty($cats)) { + $catSql = '(' . \current($cats); + \array_shift($cats); + foreach ($cats as $cat) { + $catSql .= ',' . $cat; + } + $catSql .= ')'; + } - use FilesManagement; + return $catSql; + } - // Files Management Trait + /** + * @param string $content + * @return void + */ + public static function metaKeywords(string $content): void + { + global $xoopsTpl, $xoTheme; + $myts = \MyTextSanitizer::getInstance(); + $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content)); + if (\is_object($xoTheme)) { + $xoTheme->addMeta('meta', 'keywords', \strip_tags($content)); + } else { // Compatibility for old Xoops versions + $xoopsTpl->assign('xoops_metaKeywords', \strip_tags($content)); + } + } + + /** + * @param string $content + * @return void + */ + public static function metaDescription(string $content): void + { + global $xoopsTpl, $xoTheme; + $myts = \MyTextSanitizer::getInstance(); + $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content)); + if (\is_object($xoTheme)) { + $xoTheme->addMeta('meta', 'description', \strip_tags($content)); + } else { // Compatibility for old Xoops versions + $xoopsTpl->assign('xoops_metaDescription', \strip_tags($content)); + } + } + + /** + * @param string $tableName + * @param string $columnName + * + * @return array|null + */ + public static function enumerate(string $tableName, string $columnName): ?array + { + $table = $GLOBALS['xoopsDB']->prefix($tableName); + + // $result = $GLOBALS['xoopsDB']->query("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS + // WHERE TABLE_NAME = '" . $table . "' AND COLUMN_NAME = '" . $columnName . "'") + // || exit ($GLOBALS['xoopsDB']->error()); + + $sql = 'SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = "' . $table . '" AND COLUMN_NAME = "' . $columnName . '"'; + $result = $GLOBALS['xoopsDB']->query($sql); + if (!$GLOBALS['xoopsDB']->isResultSet($result)) { + // \trigger_error("Query Failed! SQL: $sql- Error: " . $GLOBALS['xoopsDB']->error(), E_USER_ERROR); + $logger = \XoopsLogger::getInstance(); + $logger->handleError(\E_USER_WARNING, $sql, __FILE__, __LINE__); + return null; + } + + $row = $GLOBALS['xoopsDB']->fetchBoth($result); + $enumList = \explode(',', \str_replace("'", '', \mb_substr($row['COLUMN_TYPE'], 5, - 6))); + return $enumList; + } + + + /** + * Clone a record in a dB + * + * @TODO need to exit more gracefully on error. Should throw/trigger error and then return false + * + * @param string $tableName name of dB table (without prefix) + * @param string $idField name of field (column) in dB table + * @param int $id item id to clone + * @return int|null + */ + public static function cloneRecord(string $tableName, string $idField, int $id): ?int + { + $newId = null; + $tempTable = []; + $table = $GLOBALS['xoopsDB']->prefix($tableName); + // copy content of the record you wish to clone + $sql = "SELECT * FROM $table WHERE $idField='" . $id . "' "; + $result = $GLOBALS['xoopsDB']->query($sql); + if ($GLOBALS['xoopsDB']->isResultSet($result)) { + $tempTable = $GLOBALS['xoopsDB']->fetchArray($result, \MYSQLI_ASSOC); + } + if (!$tempTable) { + \trigger_error("Query Failed! SQL: $sql- Error: " . $GLOBALS['xoopsDB']->error(), \E_USER_ERROR); + } + // set the auto-incremented id's value to blank. + unset($tempTable[$idField]); + // insert cloned copy of the original record + $sql = "INSERT INTO $table (" . \implode(', ', \array_keys($tempTable)) . ") VALUES ('" . \implode("', '", $tempTable) . "')"; + $result = $GLOBALS['xoopsDB']->queryF($sql); + if (!$result) { + \trigger_error("Query Failed! SQL: $sql- Error: " . $GLOBALS['xoopsDB']->error(), \E_USER_ERROR); + } else { + // Return the new id + $newId = $GLOBALS['xoopsDB']->getInsertId(); + } + return $newId; + } /** * truncateHtml can truncate a string up to a number of characters while preserving whole words and HTML tags * www.gsdesign.ro/blog/cut-html-string-without-breaking-the-tags * www.cakephp.org * + * @TODO: Refactor to consider HTML5 & void (self-closing) elements + * @TODO: Consider using https://github.com/jlgrall/truncateHTML/blob/master/truncateHTML.php + * * @param string $text String to truncate. - * @param int $length Length of returned string, including ellipsis. + * @param int|null $length Length of returned string, including ellipsis. * @param string $ending Ending to be appended to the trimmed string. * @param bool $exact If false, $text will not be cut mid-word * @param bool $considerHtml If true, HTML tags would be handled correctly * * @return string Trimmed string. */ - public static function truncateHtml($text, $length = 100, $ending = '...', $exact = false, $considerHtml = true) - { + public static function truncateHtml( + string $text, + ?int $length = 100, + string $ending = '...', + bool $exact = false, + bool $considerHtml = true + ): string { + $openTags = []; if ($considerHtml) { // if the plain text is shorter than the maximum length, return the whole text - if (mb_strlen(\preg_replace('/<.*?' . '>/', '', $text)) <= $length) { + if (\mb_strlen(\preg_replace('/<.*?' . '>/', '', $text)) <= $length) { return $text; } // splits all html-tags to scanable lines \preg_match_all('/(<.+?' . '>)?([^<>]*)/s', $text, $lines, \PREG_SET_ORDER); - $total_length = mb_strlen($ending); - $open_tags = []; - $truncate = ''; - foreach ($lines as $line_matchings) { + $totalLength = \mb_strlen($ending); + //$openTags = []; + $truncate = ''; + foreach ($lines as $lineMatchings) { // if there is any html-tag in this line, handle it and add it (uncounted) to the output - if (!empty($line_matchings[1])) { + if (!empty($lineMatchings[1])) { // if it's an "empty element" with or without xhtml-conform closing slash - if (\preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) { + if (\preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $lineMatchings[1])) { // do nothing // if tag is a closing tag - } elseif (\preg_match('/^<\s*\/(\S+?)\s*>$/s', $line_matchings[1], $tag_matchings)) { - // delete tag from $open_tags list - $pos = \array_search($tag_matchings[1], $open_tags, true); + } elseif (\preg_match('/^<\s*\/(\S+?)\s*>$/s', $lineMatchings[1], $tagMatchings)) { + // delete tag from $openTags list + $pos = \array_search($tagMatchings[1], $openTags, true); if (false !== $pos) { - unset($open_tags[$pos]); + unset($openTags[$pos]); } // if tag is an opening tag - } elseif (\preg_match('/^<\s*([^\s>!]+).*?' . '>$/s', $line_matchings[1], $tag_matchings)) { - // add tag to the beginning of $open_tags list - \array_unshift($open_tags, \mb_strtolower($tag_matchings[1])); + } elseif (\preg_match('/^<\s*([^\s>!]+).*?' . '>$/s', $lineMatchings[1], $tagMatchings)) { + // add tag to the beginning of $openTags list + \array_unshift($openTags, \mb_strtolower($tagMatchings[1])); } // add html-tag to $truncate'd text - $truncate .= $line_matchings[1]; + $truncate .= $lineMatchings[1]; } // calculate the length of the plain text part of the line; handle entities as one character - $content_length = mb_strlen(\preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2])); - if ($total_length + $content_length > $length) { + $contentLength = \mb_strlen(\preg_replace('/&[0-9a-z]{2,8};|&#\d{1,7};|[0-9a-f]{1,6};/i', ' ', $lineMatchings[2])); + if ($totalLength + $contentLength > $length) { // the number of characters which are left - $left = $length - $total_length; - $entities_length = 0; + $left = $length - $totalLength; + $entitiesLength = 0; // search for html entities - if (\preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, \PREG_OFFSET_CAPTURE)) { + if (\preg_match_all('/&[0-9a-z]{2,8};|&#\d{1,7};|[0-9a-f]{1,6};/i', $lineMatchings[2], $entities, \PREG_OFFSET_CAPTURE)) { // calculate the real length of all entities in the legal range foreach ($entities[0] as $entity) { - if ($left >= $entity[1] + 1 - $entities_length) { + if ($left >= $entity[1] + 1 - $entitiesLength) { $left--; - $entities_length += mb_strlen($entity[0]); + $entitiesLength += \mb_strlen($entity[0]); } else { // no more characters left break; } } } - $truncate .= mb_substr($line_matchings[2], 0, $left + $entities_length); - // maximum lenght is reached, so get off the loop + $truncate .= \mb_substr($lineMatchings[2], 0, $left + $entitiesLength); + // maximum length is reached, so get off the loop break; } - $truncate .= $line_matchings[2]; - $total_length += $content_length; + $truncate .= $lineMatchings[2]; + $totalLength += $contentLength; // if the maximum length is reached, get off the loop - if ($total_length >= $length) { + if ($totalLength >= $length) { break; } } } else { - if (mb_strlen($text) <= $length) { + if (\mb_strlen($text) <= $length) { return $text; } - $truncate = mb_substr($text, 0, $length - mb_strlen($ending)); + $truncate = \mb_substr($text, 0, $length - \mb_strlen($ending)); } // if the words shouldn't be cut in the middle... if (!$exact) { // ...search the last occurance of a space... - $spacepos = mb_strrpos($truncate, ' '); + $spacepos = \mb_strrpos($truncate, ' '); if (isset($spacepos)) { // ...and cut the text in this position - $truncate = mb_substr($truncate, 0, $spacepos); + $truncate = \mb_substr($truncate, 0, $spacepos); } } // add the defined ending to the text $truncate .= $ending; if ($considerHtml) { // close all unclosed html-tags - foreach ($open_tags as $tag) { + foreach ($openTags as $tag) { $truncate .= ''; } } @@ -147,12 +323,14 @@ public static function truncateHtml($text, $length = 100, $ending = '...', $exac } /** - * @param \Xmf\Module\Helper $helper - * @param array|null $options + * Get correct text editor based on user rights + * * @return \XoopsFormDhtmlTextArea|\XoopsFormEditor */ - public static function getEditor($helper = null, $options = null) + public static function getEditor(?\Xmf\Module\Helper $helper = null, ?array $options = null): ?\XoopsFormTextArea { + $descEditor = null; + /** @var Helper $helper */ if (null === $options) { $options = []; @@ -172,12 +350,12 @@ public static function getEditor($helper = null, $options = null) if (\class_exists('XoopsFormEditor')) { if ($isAdmin) { - $descEditor = new XoopsFormEditor(\ucfirst($options['name']), $helper->getConfig('editorAdmin'), $options, $nohtml = false, $onfailure = 'textarea'); + $descEditor = new \XoopsFormEditor(\ucfirst((string) $options['name']), $helper->getConfig('editorAdmin'), $options, false, 'textarea'); } else { - $descEditor = new XoopsFormEditor(\ucfirst($options['name']), $helper->getConfig('editorUser'), $options, $nohtml = false, $onfailure = 'textarea'); + $descEditor = new \XoopsFormEditor(\ucfirst((string) $options['name']), $helper->getConfig('editorUser'), $options, false, 'textarea'); } } else { - $descEditor = new \XoopsFormDhtmlTextArea(\ucfirst($options['name']), $options['name'], $options['value'], '100%', '100%'); + $descEditor = new \XoopsFormDhtmlTextArea(\ucfirst((string) $options['name']), $options['name'], $options['value']); } // $form->addElement($descEditor); @@ -186,51 +364,39 @@ public static function getEditor($helper = null, $options = null) } /** - * @param string $fieldname - * @param string $table + * Check if column in dB table exists * - * @return bool + * @param string $fieldname name of dB table field + * @param string $table name of dB table (including prefix) + * + * @return bool true if table exists + * @deprecated */ public static function fieldExists(string $fieldname, string $table): bool { - global $xoopsDB; - $result = $xoopsDB->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'"); + $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1); + $GLOBALS['xoopsLogger']->addDeprecated(__METHOD__ . "() use Xmf\Database\Tables instead - instantiated from {$trace[0]['file']} line {$trace[0]['line']}"); - return ($xoopsDB->getRowsNum($result) > 0); + $result = $GLOBALS['xoopsDB']->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'"); + return ($GLOBALS['xoopsDB']->getRowsNum($result) > 0); } + /** - * @param array|string $tableName - * @param string $id_field - * @param int $id + * Function responsible for checking if a directory exists, we can also write in and create an index.html file * - * @return mixed + * @param string $folder The full path of the directory to check */ - public static function cloneRecord($tableName, $id_field, $id) + public static function prepareFolder(string $folder): void { - $new_id = false; - $table = $GLOBALS['xoopsDB']->prefix($tableName); - // copy content of the record you wish to clone - $sql = "SELECT * FROM $table WHERE $id_field='" . $id . "' "; - $result = $GLOBALS['xoopsDB']->query($sql); - if ($GLOBALS['xoopsDB']->isResultSet($result)) { - $tempTable = $GLOBALS['xoopsDB']->fetchArray($result, \MYSQLI_ASSOC); - } - if (!$tempTable) { - \trigger_error($GLOBALS['xoopsDB']->error()); - } - // set the auto-incremented id's value to blank. - unset($tempTable[$id_field]); - // insert cloned copy of the original record - $sql = "INSERT INTO $table (" . \implode(', ', \array_keys($tempTable)) . ") VALUES ('" . \implode("', '", \array_values($tempTable)) . "')"; - $result = $GLOBALS['xoopsDB']->queryF($sql); - if (!$result) { - \trigger_error($GLOBALS['xoopsDB']->error()); + try { + if (!\is_dir($folder) && !\mkdir($folder) && !\is_dir($folder)) { + throw new \Exception(\sprintf('Unable to create the %s directory', $folder)); + } + file_put_contents($folder . '/index.html', ''); + } catch (\Exception $e) { + echo 'Caught exception: ', $e->getMessage(), "\n", '
'; } - // Return the new id - $new_id = $GLOBALS['xoopsDB']->getInsertId(); - - return $new_id; } /** @@ -243,7 +409,6 @@ public static function tableExists(string $tablename): bool { $ret = false; $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1); - \trigger_error(__FUNCTION__ . " is deprecated, called from {$trace[0]['file']} line {$trace[0]['line']}"); $GLOBALS['xoopsLogger']->addDeprecated( \basename(\dirname(__DIR__, 2)) . ' Module: ' . __FUNCTION__ . ' function is deprecated, please use Xmf\Database\Tables method(s) instead.' . " Called from {$trace[0]['file']}line {$trace[0]['line']}" ); @@ -255,4 +420,110 @@ public static function tableExists(string $tablename): bool return $ret; } + + /** + * Add a field to a mysql table + * + * @return bool|\mysqli_result + */ + public static function addField(string $field, string $table) + { + global $xoopsDB; + return $xoopsDB->queryF('ALTER TABLE ' . $table . " ADD $field;"); + } + + /** + * @return void + */ + public static function cleanCache(): void + { + $myDirName = \basename(\dirname(__DIR__, 2)); + $cacheHelper = new Cache($myDirName); + if (\method_exists($cacheHelper, 'clear')) { + $cacheHelper->clear(); + + return; + } + // for 2.5 systems, clear everything + require_once XOOPS_ROOT_PATH . '/modules/system/class/maintenance.php'; + $maintenance = new \SystemMaintenance(); + $cacheList = [ + 3, // xoops_cache + ]; + $maintenance->CleanCache($cacheList); + \xoops_setActiveModules(); + } + + /** + * @return bool + */ + public static function renameUploadFolder(): bool + { + $moduleDirName = \basename(\dirname(__DIR__)); + $moduleDirNameUpper = \mb_strtoupper($moduleDirName); + $helper = Helper::getInstance(); + + $success = true; + $helper->loadLanguage('admin'); + + // Rename uploads folder to BAK and add date to name + $uploadDirectory = $GLOBALS['xoops']->path("uploads/$moduleDirName"); + $dirInfo = new \SplFileInfo($uploadDirectory); + if ($dirInfo->isDir()) { + // The directory exists so rename it + $date = \date('Y-m-d'); + if (!\rename($uploadDirectory, $uploadDirectory . "_BAK_$date")) { + $helper->getModule()->setErrors(\sprintf(\constant('CO_' . $moduleDirNameUpper . '_' . 'ERROR_BAD_DEL_PATH'), $uploadDirectory)); + $success = false; + } + } + unset($dirInfo); + + return $success; + } + + /** + * Query and check if the result is a valid result set + * + * @param \XoopsMySQLDatabase $xoopsDB XOOPS Database + * @param string $sql a valid MySQL query + * @param int $limit number of records to return + * @param int $start offset of first record to return + * + * @return \mysqli_result query result + */ + public static function queryAndCheck(\XoopsMySQLDatabase $xoopsDB, string $sql, $limit = 0, $start = 0): \mysqli_result + { + $result = $xoopsDB->query($sql, $limit, $start); + + if (!$xoopsDB->isResultSet($result)) { + throw new \RuntimeException( + \sprintf(\_DB_QUERY_ERROR, $sql) . $xoopsDB->error(), \E_USER_ERROR); + } + + return $result; + } + + /** + * QueryF and check if the result is a valid result set + * + * @param \XoopsMySQLDatabase $xoopsDB XOOPS Database + * @param string $sql a valid MySQL query + * @param int $limit number of records to return + * @param int $start offset of first record to return + * + * @return \mysqli_result query result + */ + public static function queryFAndCheck(\XoopsMySQLDatabase $xoopsDB, string $sql, $limit = 0, $start = 0): \mysqli_result + { + $result = $xoopsDB->queryF($sql, $limit, $start); + + if (!$xoopsDB->isResultSet($result)) { + throw new \RuntimeException( + \sprintf(\_DB_QUERY_ERROR, $sql) . $xoopsDB->error(), \E_USER_ERROR + ); + } + + return $result; + } } diff --git a/class/Common/TestdataButtons.php b/class/Common/TestdataButtons.php index f7b2c3d..498789c 100644 --- a/class/Common/TestdataButtons.php +++ b/class/Common/TestdataButtons.php @@ -20,7 +20,10 @@ */ use Xmf\Yaml; -use XoopsModules\News\Helper; +use Xmf\Module\Admin; +use XoopsModules\News\{ + Helper +}; /** @var Helper $helper */ @@ -36,11 +39,11 @@ class TestdataButtons /** * Load the test button configuration * - * @param \Xmf\Module\Admin $adminObject + * @param Admin $adminObject * * @return void */ - public static function loadButtonConfig($adminObject): void + public static function loadButtonConfig(Admin $adminObject): void { $moduleDirName = \basename(\dirname(__DIR__, 2)); $moduleDirNameUpper = \mb_strtoupper($moduleDirName); diff --git a/class/Common/VersionChecks.php b/class/Common/VersionChecks.php index be89e40..255ae9b 100644 --- a/class/Common/VersionChecks.php +++ b/class/Common/VersionChecks.php @@ -17,6 +17,9 @@ * @license GNU GPL 2.0 or later (https://www.gnu.org/licenses/gpl-2.0.html) * @author mamba */ + +use Xmf\Module\Helper; + trait VersionChecks { /** @@ -26,7 +29,7 @@ trait VersionChecks * @param null|string $requiredVer * @return bool true if meets requirements, false if not */ - public static function checkVerXoops(?\XoopsModule $module, string $requiredVer = null): bool + public static function checkVerXoops(?\XoopsModule $module = null, ?string $requiredVer = null): bool { $moduleDirName = \basename(\dirname(__DIR__, 2)); $moduleDirNameUpper = \mb_strtoupper($moduleDirName); @@ -43,9 +46,9 @@ public static function checkVerXoops(?\XoopsModule $module, string $requiredVer } $success = true; - if (\version_compare($currentVer, $requiredVer, '<')) { + if ($module->versionCompare($currentVer, $requiredVer, '<')) { $success = false; - $module->setErrors(\sprintf(\constant('CO_' . $moduleDirNameUpper . '_ERROR_BAD_XOOPS'), $requiredVer, $currentVer)); + $module->setErrors(\sprintf(\constant('CO_' . $moduleDirNameUpper . '_' . 'ERROR_BAD_XOOPS'), $requiredVer, $currentVer)); } return $success; @@ -58,7 +61,7 @@ public static function checkVerXoops(?\XoopsModule $module, string $requiredVer * * @return bool true if meets requirements, false if not */ - public static function checkVerPhp(\XoopsModule $module = null): bool + public static function checkVerPhp(?\XoopsModule $module = null): bool { $moduleDirName = \basename(\dirname(__DIR__, 2)); $moduleDirNameUpper = \mb_strtoupper($moduleDirName); @@ -74,8 +77,8 @@ public static function checkVerPhp(\XoopsModule $module = null): bool $verNum = \PHP_VERSION; $reqVer = &$module->getInfo('min_php'); - if (false !== $reqVer && '' !== $reqVer && !is_array($reqVer) && \version_compare($verNum, $reqVer, '<')) { - $module->setErrors(\sprintf(\constant('CO_' . $moduleDirNameUpper . '_ERROR_BAD_PHP'), $reqVer, $verNum)); + if (false !== $reqVer && '' !== $reqVer && !\is_array($reqVer) && $module->versionCompare($verNum, $reqVer, '<')) { + $module->setErrors(\sprintf(\constant('CO_' . $moduleDirNameUpper . '_' . 'ERROR_BAD_PHP'), $reqVer, $verNum)); $success = false; } @@ -92,7 +95,7 @@ public static function checkVerPhp(\XoopsModule $module = null): bool * @return string|array|null info about the latest module version, if newer */ public static function checkVerModule( - \Xmf\Module\Helper $helper, + Helper $helper, ?string $source = null, ?string $default = null ): ?array { @@ -100,6 +103,7 @@ public static function checkVerModule( $default ??= 'master'; $moduleDirName = \basename(\dirname(__DIR__, 2)); $moduleDirNameUpper = \mb_strtoupper($moduleDirName); + $module = $helper->getModule(); $update = ''; $repository = 'XoopsModules25x/' . $moduleDirName; // $repository = 'XoopsModules25x/publisher'; //for testing only @@ -112,7 +116,7 @@ public static function checkVerModule( //TODO: how to avoid an error when 'Peer's Certificate issuer is not recognized' \curl_setopt($curlHandle, \CURLOPT_HTTPHEADER, ["User-Agent:Publisher\r\n"]); $curlReturn = \curl_exec($curlHandle); - if (is_bool($curlReturn)) { + if (\is_bool($curlReturn)) { \trigger_error(\curl_error($curlHandle)); } elseif (false !== \mb_strpos($curlReturn, 'Not Found')) { \trigger_error('Repository Not Found: ' . $infoReleasesUrl); @@ -137,7 +141,7 @@ public static function checkVerModule( $moduleVersion = \str_replace(' ', '', \mb_strtolower($moduleVersion)); // $moduleVersion = '1.0'; //for testing only // $moduleDirName = 'publisher'; //for testing only - if (!$prerelease && \version_compare($moduleVersion, $latestVersion, '<')) { + if (!$prerelease && $module->versionCompare($moduleVersion, $latestVersion, '<')) { $ret = []; $ret[] = $update; $ret[] = $latestVersionLink; diff --git a/class/Files.php b/class/Files.php index 66fcd8d..7eec3c2 100644 --- a/class/Files.php +++ b/class/Files.php @@ -25,20 +25,20 @@ */ class Files { - public $db; - public $table; - public $fileid; - public $filerealname; - public $storyid; - public $date; - public $mimetype; - public $downloadname; - public $counter; + public \XoopsDatabase $db; + public string $table; + public int $fileid; + public string $filerealname; + public int $storyid; + public int $date; + public string $mimetype; + public string $downloadname; + public int $counter; /** - * @param $fileid + * @param array|int $fileid */ - public function __construct($fileid = -1) + public function __construct(int $fileid = -1) { /** @var \XoopsMySQLDatabase $db */ $this->db = \XoopsDatabaseFactory::getDatabaseConnection(); @@ -57,13 +57,13 @@ public function __construct($fileid = -1) } /** - * @param $folder - * @param $filename - * @param bool $trimname + * @param string $folder + * @param string $filename + * @param bool $trimname * * @return string */ - public function createUploadName($folder, $filename, $trimname = false) + public function createUploadName(string $folder, string $filename, bool $trimname = false): string { $workingfolder = $folder; if ('/' !== \xoops_substr($workingfolder, mb_strlen($workingfolder) - 1, 1)) { @@ -98,7 +98,7 @@ public function createUploadName($folder, $filename, $trimname = false) * * @return string */ - public function giveMimetype($filename = '') + public function giveMimetype(string $filename = ''): string { $cmimetype = new Mimetype(); $workingfile = $this->downloadname; @@ -112,11 +112,11 @@ public function giveMimetype($filename = '') } /** - * @param $storyid + * @param string|int $storyid * * @return array */ - public function getAllbyStory($storyid) + public function getAllbyStory($storyid): array { $ret = []; $sql = 'SELECT * FROM ' . $this->table . ' WHERE storyid=' . (int)$storyid; @@ -131,19 +131,23 @@ public function getAllbyStory($storyid) } /** - * @param $id + * @param string|int $id */ public function getFile($id): void { $sql = 'SELECT * FROM ' . $this->table . ' WHERE fileid=' . (int)$id; - $array = $this->db->fetchArray($this->db->query($sql)); + $result = $this->db->query($sql); + if (!$this->db->isResultSet($result)){ + \trigger_error("Query Failed! SQL: $sql Error: " . $this->db->error(), \E_USER_ERROR); + } + $array = $this->db->fetchArray($result); $this->makeFile($array); } /** - * @param $array + * @param array $array */ - public function makeFile($array): void + public function makeFile(array $array): void { foreach ($array as $key => $value) { $this->$key = $value; @@ -153,7 +157,7 @@ public function makeFile($array): void /** * @return bool */ - public function store() + public function store(): bool { $myts = \MyTextSanitizer::getInstance(); $fileRealName = $GLOBALS['xoopsDB']->escape($this->filerealname); @@ -163,12 +167,12 @@ public function store() $counter = $this->counter; $storyid = $this->storyid; - if (!isset($this->fileid)) { + if (isset($this->fileid)) { + $sql = 'UPDATE ' . $this->table . ' SET storyid=' . $storyid . ",filerealname='" . $fileRealName . "',date=" . $date . ",mimetype='" . $mimetype . "',downloadname='" . $downloadname . "',counter=" . $counter . ' WHERE fileid=' . $this->getFileid(); + } else { $newid = (int)$this->db->genId($this->table . '_fileid_seq'); $sql = 'INSERT INTO ' . $this->table . ' (fileid, storyid, filerealname, date, mimetype, downloadname, counter) ' . 'VALUES (' . $newid . ',' . $storyid . ",'" . $fileRealName . "','" . $date . "','" . $mimetype . "','" . $downloadname . "'," . $counter . ')'; $this->fileid = $newid; - } else { - $sql = 'UPDATE ' . $this->table . ' SET storyid=' . $storyid . ",filerealname='" . $fileRealName . "',date=" . $date . ",mimetype='" . $mimetype . "',downloadname='" . $downloadname . "',counter=" . $counter . ' WHERE fileid=' . $this->getFileid(); } if (!$result = $this->db->query($sql)) { return false; @@ -182,7 +186,7 @@ public function store() * * @return bool */ - public function delete($workdir = XOOPS_UPLOAD_PATH) + public function delete(string $workdir = XOOPS_UPLOAD_PATH): bool { $sql = 'DELETE FROM ' . $this->table . ' WHERE fileid=' . $this->getFileid(); if (!$result = $this->db->query($sql)) { @@ -198,7 +202,7 @@ public function delete($workdir = XOOPS_UPLOAD_PATH) /** * @return bool */ - public function updateCounter() + public function updateCounter(): bool { $sql = 'UPDATE ' . $this->table . ' SET counter=counter+1 WHERE fileid=' . $this->getFileid(); if (!$result = $this->db->queryF($sql)) { @@ -213,15 +217,15 @@ public function updateCounter() // **************************************************************************************************************** /** - * @param $filename + * @param string $filename */ - public function setFileRealName($filename): void + public function setFileRealName(string $filename): void { $this->filerealname = $filename; } /** - * @param $id + * @param string|int $id */ public function setStoryid($id): void { @@ -229,17 +233,17 @@ public function setStoryid($id): void } /** - * @param $value + * @param string $value */ - public function setMimetype($value): void + public function setMimetype(string $value): void { $this->mimetype = $value; } /** - * @param $value + * @param string $value */ - public function setDownloadname($value): void + public function setDownloadname(string $value): void { $this->downloadname = $value; } @@ -251,7 +255,7 @@ public function setDownloadname($value): void /** * @return int */ - public function getFileid() + public function getFileid(): int { return (int)$this->fileid; } @@ -259,7 +263,7 @@ public function getFileid() /** * @return int */ - public function getStoryid() + public function getStoryid(): int { return $this->storyid; } @@ -267,7 +271,7 @@ public function getStoryid() /** * @return int */ - public function getCounter() + public function getCounter(): int { return $this->counter; } @@ -275,7 +279,7 @@ public function getCounter() /** * @return int */ - public function getDate() + public function getDate(): int { return $this->date; } @@ -283,9 +287,9 @@ public function getDate() /** * @param string $format * - * @return mixed + * @return string */ - public function getFileRealName($format = 'S') + public function getFileRealName(string $format = 'S'): string { $myts = \MyTextSanitizer::getInstance(); switch ($format) { @@ -313,9 +317,9 @@ public function getFileRealName($format = 'S') /** * @param string $format * - * @return mixed + * @return string */ - public function getMimetype($format = 'S') + public function getMimetype(string $format = 'S'): string { $myts = \MyTextSanitizer::getInstance(); switch ($format) { @@ -343,9 +347,9 @@ public function getMimetype($format = 'S') /** * @param string $format * - * @return mixed + * @return string */ - public function getDownloadname($format = 'S') + public function getDownloadname(string $format = 'S'): string { $myts = \MyTextSanitizer::getInstance(); switch ($format) { @@ -373,7 +377,7 @@ public function getDownloadname($format = 'S') // Deprecated /** - * @param $storyid + * @param string|int $storyid * * @return mixed */ @@ -381,17 +385,20 @@ public function getCountbyStory($storyid) { $sql = 'SELECT count(fileid) AS cnt FROM ' . $this->table . ' WHERE storyid=' . (int)$storyid; $result = $this->db->query($sql); + if (!$this->db->isResultSet($result)){ + \trigger_error("Query Failed! SQL: $sql Error: " . $this->db->error(), \E_USER_ERROR); + } $myrow = $this->db->fetchArray($result); return $myrow['cnt']; } /** - * @param $stories + * @param array $stories * * @return array */ - public function getCountbyStories($stories) + public function getCountbyStories(array $stories): array { $ret = []; if (\count($stories) > 0) { diff --git a/class/Helper.php b/class/Helper.php index a70be97..7cc6ee2 100644 --- a/class/Helper.php +++ b/class/Helper.php @@ -53,7 +53,7 @@ public static function getInstance(bool $debug = false): self /** * @return string */ - public function getDirname() + public function getDirname(): string { return $this->dirname; } @@ -77,7 +77,7 @@ public function getHandler($name) $db = \XoopsDatabaseFactory::getDatabaseConnection(); $helper = self::getInstance(); $ret = new $class($db, $helper); - $this->addLog("Getting handler '{$name}'"); + $this->addLog("Getting handler '$name'"); return $ret; } diff --git a/class/Keyhighlighter.php b/class/Keyhighlighter.php index a07fb82..73f50f8 100644 --- a/class/Keyhighlighter.php +++ b/class/Keyhighlighter.php @@ -22,15 +22,15 @@ class Keyhighlighter /** * @access private */ - public $preg_keywords = ''; + public string $preg_keywords = ''; /** * @access private */ - public $keywords = ''; + public string $keywords = ''; /** * @access private */ - public $singlewords = false; + public bool $singlewords = false; /** * @access private */ @@ -42,9 +42,9 @@ class Keyhighlighter * This is the main constructor of Keyhighlighter class.
* It's the only public method of the class. * - * @param string $keywords the keywords you want to highlight - * @param bool $singlewords specify if it has to highlight also the single words. - * @param callback $replace_callback a custom callback for keyword highlight. + * @param string $keywords the keywords you want to highlight + * @param bool|null $singlewords specify if it has to highlight also the single words. + * @param callback|null $replace_callback a custom callback for keyword highlight. * * */ // public function __construct () - public function __construct($keywords, $singlewords = false, $replace_callback = null) + public function __construct(string $keywords, ?bool $singlewords = null, ?callable $replace_callback = null) { + $singlewords ??= false; $this->keywords = $keywords; $this->singlewords = $singlewords; $this->replace_callback = $replace_callback; @@ -68,10 +69,10 @@ public function __construct($keywords, $singlewords = false, $replace_callback = /** * @access private - * @param $replace_matches + * @param array $replace_matches * @return mixed */ - public function replace($replace_matches) + public function replace(array $replace_matches) { $patterns = []; if ($this->singlewords) { @@ -98,14 +99,14 @@ public function replace($replace_matches) /** * @access private - * @param $buffer - * @return mixed|string + * @param string $buffer + * @return string */ - public function highlight($buffer) + public function highlight(string $buffer): string { $buffer = '>' . $buffer . '<'; - $this->preg_keywords = \preg_replace('/[^\w ]/si', '', $this->keywords); - $buffer = \preg_replace_callback('/(\>(((?' . '>[^><]+)|(?R))*)\<)/is', [&$this, 'replace'], $buffer); + $this->preg_keywords = \preg_replace('/[^\w ]/i', '', $this->keywords); + $buffer = \preg_replace_callback('/(\>(((?' . '>[^>i', [&$this, 'replace'], $buffer); $buffer = \xoops_substr($buffer, 1, -1); return $buffer; diff --git a/class/Mimetype.php b/class/Mimetype.php index e17ec30..6e08488 100644 --- a/class/Mimetype.php +++ b/class/Mimetype.php @@ -76,11 +76,11 @@ class Mimetype { /** - * @param $filename + * @param string $filename * * @return string */ - public function getType($filename) + public function getType(string $filename): string { // get base name of the filename provided by user $filename = \basename($filename); @@ -96,11 +96,11 @@ public function getType($filename) } /** - * @param $ext + * @param string $ext * * @return string */ - public function privFindType($ext) + public function privFindType(string $ext): string { // create mimetypes array $mimetypes = $this->privBuildMimeArray(); @@ -112,7 +112,7 @@ public function privFindType($ext) /** * @return array */ - public function privBuildMimeArray() + public function privBuildMimeArray(): array { return [ 'ez' => 'application/andrew-inset', diff --git a/class/NewsStoriesHandler.php b/class/NewsStoriesHandler.php index bbc2907..65dec8a 100644 --- a/class/NewsStoriesHandler.php +++ b/class/NewsStoriesHandler.php @@ -46,7 +46,7 @@ class NewsStoriesHandler extends XoopsPersistableObjectHandler /** * @param null|\XoopsDatabase $db */ - public function __construct(XoopsDatabase $db = null) + public function __construct(?\XoopsDatabase $db = null) { parent::__construct($db, 'news_stories', NewsStories::class, 'storyid', 'uid'); } diff --git a/class/NewsStory.php b/class/NewsStory.php index 44f49e0..372d83c 100644 --- a/class/NewsStory.php +++ b/class/NewsStory.php @@ -48,7 +48,7 @@ class NewsStory extends XoopsStory /** * Constructor - * @param int $storyid + * @param array|int $storyid */ public function __construct($storyid = -1) { @@ -65,24 +65,23 @@ public function __construct($storyid = -1) /** * Returns the number of stories published before a date - * @param $timestamp - * @param $expired - * @param string $topicslist + * @param int $timestamp + * @param int $expired + * @param string $topicslist * @return mixed */ - public function getCountStoriesPublishedBefore($timestamp, $expired, $topicslist = '') + public function getCountStoriesPublishedBefore(int $timestamp, int $expired, string $topicslist = '') { - /** @var \XoopsMySQLDatabase $db */ - $db = \XoopsDatabaseFactory::getDatabaseConnection(); - $sql = 'SELECT count(*) AS cpt FROM ' . $db->prefix('news_stories') . ' WHERE published <=' . $timestamp; + $count = 0; + $sql = 'SELECT count(*) AS cpt FROM ' . $this->db->prefix('news_stories') . ' WHERE published <=' . $timestamp; if ($expired) { $sql .= ' AND (expired>0 AND expired<=' . \time() . ')'; } if ('' !== \trim($topicslist)) { $sql .= ' AND topicid IN (' . $topicslist . ')'; } - $result = $db->query($sql); - [$count] = $db->fetchRow($result); + $result = Utility::queryAndCheck($this->db, $sql); + [$count] = $this->db->fetchRow($result); return $count; } @@ -93,10 +92,12 @@ public function getCountStoriesPublishedBefore($timestamp, $expired, $topicslist */ public function getStory($storyid): void { - /** @var \XoopsMySQLDatabase $db */ - $db = \XoopsDatabaseFactory::getDatabaseConnection(); - $sql = 'SELECT s.*, t.* FROM ' . $this->table . ' s, ' . $db->prefix('news_topics') . ' t WHERE (storyid=' . (int)$storyid . ') AND (s.topicid=t.topic_id)'; - $array = $db->fetchArray($db->query($sql)); + $sql = 'SELECT s.*, t.* FROM ' . $this->table . ' s, ' . $this->db->prefix('news_topics') . ' t WHERE (storyid=' . (int)$storyid . ') AND (s.topicid=t.topic_id)'; + $result = Utility::queryAndCheck($this->db, $sql); + if (!$this->db->isResultSet($result)){ + \trigger_error("Query Failed! SQL: $sql Error: " . $this->db->error(), \E_USER_ERROR); + } + $array = $this->db->fetchArray($result); $this->makeStory($array); } @@ -107,15 +108,13 @@ public function getStory($storyid): void * @param string $topicslist * @return bool */ - public function deleteBeforeDate($timestamp, $expired, $topicslist = '') + public function deleteBeforeDate($timestamp, $expired, string $topicslist = ''): bool { global $xoopsModule; - /** @var \XoopsMySQLDatabase $db */ - $db = \XoopsDatabaseFactory::getDatabaseConnection(); $mid = $xoopsModule->getVar('mid'); - $prefix = $db->prefix('news_stories'); - $vote_prefix = $db->prefix('news_stories_votedata'); - $files_prefix = $db->prefix('news_stories_files'); + $prefix = $this->db->prefix('news_stories'); + $vote_prefix = $this->db->prefix('news_stories_votedata'); + $files_prefix = $this->db->prefix('news_stories_files'); $sql = 'SELECT storyid FROM ' . $prefix . ' WHERE published <=' . $timestamp; if ($expired) { $sql .= ' (AND expired>0 AND expired<=' . \time() . ')'; @@ -123,44 +122,46 @@ public function deleteBeforeDate($timestamp, $expired, $topicslist = '') if ('' !== \trim($topicslist)) { $sql .= ' AND topicid IN (' . $topicslist . ')'; } - $result = $db->query($sql); - while (false !== ($myrow = $db->fetchArray($result))) { + $result = Utility::queryAndCheck($this->db, $sql); + while (false !== ($myrow = $this->db->fetchArray($result))) { \xoops_comment_delete($mid, $myrow['storyid']); // Delete comments \xoops_notification_deletebyitem($mid, 'story', $myrow['storyid']); // Delete notifications - $db->queryF('DELETE FROM ' . $vote_prefix . ' WHERE storyid=' . $myrow['storyid']); // Delete votes + $sql = 'DELETE FROM ' . $vote_prefix . ' WHERE storyid=' . $myrow['storyid']; + $result1 = $this->db->queryF($sql); // Delete votes // Remove files and records related to the files - $result2 = $db->query('SELECT * FROM ' . $files_prefix . ' WHERE storyid=' . $myrow['storyid']); - while (false !== ($myrow2 = $db->fetchArray($result2))) { + $sql = 'SELECT * FROM ' . $files_prefix . ' WHERE storyid=' . $myrow['storyid']; + $result2 = Utility::queryAndCheck($this->db, $sql); + while (false !== ($myrow2 = $this->db->fetchArray($result2))) { $name = XOOPS_ROOT_PATH . '/uploads/' . $myrow2['downloadname']; if (\is_file($name)) { \unlink($name); } - $db->query('DELETE FROM ' . $files_prefix . ' WHERE fileid=' . $myrow2['fileid']); + $sql = 'DELETE FROM ' . $files_prefix . ' WHERE fileid=' . $myrow2['fileid']; + $result3 = $this->db->query($sql); } - $db->queryF('DELETE FROM ' . $prefix . ' WHERE storyid=' . $myrow['storyid']); // Delete the story + $sql = 'DELETE FROM ' . $prefix . ' WHERE storyid=' . $myrow['storyid']; + $result4 = $this->db->queryF($sql); // Delete the story } return true; } /** - * @param $storyid - * @param bool $next - * @param bool $checkRight + * @param int|string $storyid + * @param bool $next + * @param int $checkRight * * @return array */ - public function _searchPreviousOrNextArticle($storyid, $next = true, $checkRight = false) + public function _searchPreviousOrNextArticle($storyid, bool $next = true, int $checkRight = 0): ?array { - /** @var \XoopsMySQLDatabase $db */ - $db = \XoopsDatabaseFactory::getDatabaseConnection(); $ret = []; $storyid = (int)$storyid; if ($next) { - $sql = 'SELECT storyid, title FROM ' . $db->prefix('news_stories') . ' WHERE (published > 0 AND published <= ' . \time() . ') AND (expired = 0 OR expired > ' . \time() . ') AND storyid > ' . $storyid; + $sql = 'SELECT storyid, title FROM ' . $this->db->prefix('news_stories') . ' WHERE (published > 0 AND published <= ' . \time() . ') AND (expired = 0 OR expired > ' . \time() . ') AND storyid > ' . $storyid; $orderBy = ' ORDER BY storyid ASC'; } else { - $sql = 'SELECT storyid, title FROM ' . $db->prefix('news_stories') . ' WHERE (published > 0 AND published <= ' . \time() . ') AND (expired = 0 OR expired > ' . \time() . ') AND storyid < ' . $storyid; + $sql = 'SELECT storyid, title FROM ' . $this->db->prefix('news_stories') . ' WHERE (published > 0 AND published <= ' . \time() . ') AND (expired = 0 OR expired > ' . \time() . ') AND storyid < ' . $storyid; $orderBy = ' ORDER BY storyid DESC'; } if ($checkRight) { @@ -173,10 +174,10 @@ public function _searchPreviousOrNextArticle($storyid, $next = true, $checkRight } $sql .= $orderBy; - $result = $db->query($sql, 1); - if ($result) { + $result = $this->db->query($sql, 1); + if ($this->db->isResultSet($result)) { $myts = \MyTextSanitizer::getInstance(); - while (false !== ($row = $db->fetchArray($result))) { + while (false !== ($row = $this->db->fetchArray($result))) { $ret = ['storyid' => $row['storyid'], 'title' => \htmlspecialchars($row['title'], \ENT_QUOTES | \ENT_HTML5)]; } } @@ -186,65 +187,55 @@ public function _searchPreviousOrNextArticle($storyid, $next = true, $checkRight /** * @param int $storyid - * @param bool $checkRight + * @param int $checkRight * * @return null|array */ - public function getNextArticle($storyid, $checkRight = false) + public function getNextArticle(int $storyid, int $checkRight = 0): ?array { return $this->_searchPreviousOrNextArticle($storyid, true, $checkRight); } /** * @param $storyid - * @param bool $checkRight + * @param int $checkRight * * @return array */ - public function getPreviousArticle($storyid, $checkRight = false) + public function getPreviousArticle($storyid, int $checkRight = 0): ?array { return $this->_searchPreviousOrNextArticle($storyid, false, $checkRight); } /** * Returns published stories according to some options - * @param int $limit - * @param int $start - * @param bool $checkRight - * @param int $topic - * @param int $ihome - * @param bool $asobject - * @param string $order - * @param bool $topic_frontpage + * @param int $limit + * @param int $start + * @param int $checkRight + * @param array|int $topic + * @param int $ihome + * @param bool $asobject + * @param string $order + * @param bool $topic_frontpage * @return array|null */ public static function getAllPublished( - $limit = 0, - $start = 0, - $checkRight = false, - $topic = 0, - $ihome = 0, - $asobject = true, - $order = 'published', - $topic_frontpage = false - ) { + int $limit = 0, + int $start = 0, + int $checkRight = 0, + int $topic = 0, + int $ihome = 0, + bool $asobject = true, + string $order = 'published', + bool $topic_frontpage = false + ): ?array { /** @var \XoopsMySQLDatabase $db */ $db = \XoopsDatabaseFactory::getDatabaseConnection(); $myts = \MyTextSanitizer::getInstance(); $ret = []; $sql = 'SELECT s.*, t.* FROM ' . $db->prefix('news_stories') . ' s, ' . $db->prefix('news_topics') . ' t WHERE (s.published > 0 AND s.published <= ' . \time() . ') AND (s.expired = 0 OR s.expired > ' . \time() . ') AND (s.topicid=t.topic_id) '; if (0 != $topic) { - if (!\is_array($topic)) { - if ($checkRight) { - $topics = Utility::getMyItemIds('news_view'); - if (!\in_array($topic, $topics, true)) { - return null; - } - $sql .= ' AND s.topicid=' . (int)$topic . ' AND (s.ihome=1 OR s.ihome=0)'; - } else { - $sql .= ' AND s.topicid=' . (int)$topic . ' AND (s.ihome=1 OR s.ihome=0)'; - } - } else { + if (\is_array($topic)) { if ($checkRight) { $topics = Utility::getMyItemIds('news_view'); $topic = \array_intersect($topic, $topics); @@ -254,6 +245,14 @@ public static function getAllPublished( } else { return null; } + } elseif ($checkRight) { + $topics = Utility::getMyItemIds('news_view'); + if (!\in_array($topic, $topics, true)) { + return null; + } + $sql .= ' AND s.topicid=' . (int)$topic . ' AND (s.ihome=1 OR s.ihome=0)'; + } else { + $sql .= ' AND s.topicid=' . (int)$topic . ' AND (s.ihome=1 OR s.ihome=0)'; } } else { if ($checkRight) { @@ -281,7 +280,8 @@ public static function getAllPublished( $helper->redirect('/index.php', 5, $db->error()); } - while (false !== ($myrow = $db->fetchArray($result))) { + /** @var array $myrow */ + while (false !== ($myrow = $db->fetchArray($result))) { if ($asobject) { $ret[] = new self($myrow); } else { @@ -293,26 +293,24 @@ public static function getAllPublished( } /** - * Retourne la liste des articles aux archives (pour une p�riode donn�e) - * @param $publish_start - * @param $publish_end - * @param bool $checkRight - * @param bool $asobject - * @param string $order + * Returns the list of articles in the archives (for a given period) + * @param int $publish_start + * @param int $publish_end + * @param int $checkRight + * @param bool $asobject + * @param string $order * @return array|null */ public function getArchive( - $publish_start, - $publish_end, - $checkRight = false, - $asobject = true, - $order = 'published' - ) { - /** @var \XoopsMySQLDatabase $db */ - $db = \XoopsDatabaseFactory::getDatabaseConnection(); + int $publish_start, + int $publish_end, + int $checkRight = 0, + bool $asobject = true, + string $order = 'published' + ): ?array { $myts = \MyTextSanitizer::getInstance(); $ret = []; - $sql = 'SELECT s.*, t.* FROM ' . $db->prefix('news_stories') . ' s, ' . $db->prefix('news_topics') . ' t WHERE (s.topicid=t.topic_id) AND (s.published > ' . $publish_start . ' AND s.published <= ' . $publish_end . ') AND (expired = 0 OR expired > ' . \time() . ') '; + $sql = 'SELECT s.*, t.* FROM ' . $this->db->prefix('news_stories') . ' s, ' . $this->db->prefix('news_topics') . ' t WHERE (s.topicid=t.topic_id) AND (s.published > ' . $publish_start . ' AND s.published <= ' . $publish_end . ') AND (expired = 0 OR expired > ' . \time() . ') '; if ($checkRight) { $topics = Utility::getMyItemIds('news_view'); @@ -324,12 +322,14 @@ public function getArchive( } } $sql .= " ORDER BY $order DESC"; - $result = $db->query($sql); - while (false !== ($myrow = $db->fetchArray($result))) { - if ($asobject) { - $ret[] = new self($myrow); - } else { - $ret[$myrow['storyid']] = \htmlspecialchars($myrow['title'], \ENT_QUOTES | \ENT_HTML5); + $result = $this->db->query($sql); + if ($this->db->isResultSet($result)) { + while (false !== ($myrow = $this->db->fetchArray($result))) { + if ($asobject) { + $ret[] = new self($myrow); + } else { + $ret[$myrow['storyid']] = \htmlspecialchars($myrow['title'], \ENT_QUOTES | \ENT_HTML5); + } } } @@ -339,31 +339,29 @@ public function getArchive( /** * Get the today's most readed article * - * @param int $limit records limit - * @param int $start starting record - * @param bool $checkRight Do we need to check permissions (by topics) ? - * @param int $topic limit the job to one topic - * @param int $ihome Limit to articles published in home page only ? - * @param bool $asobject Do we have to return an array of objects or a simple array ? - * @param string $order Fields to sort on + * @param int $limit records limit + * @param int $start starting record + * @param bool|int $checkRight Do we need to check permissions (by topics) ? + * @param array|int $topic limit the job to one topic + * @param int $ihome Limit to articles published in home page only ? + * @param bool $asobject Do we have to return an array of objects or a simple array ? + * @param string $order Fields to sort on * * @return array */ public function getBigStory( - $limit = 0, - $start = 0, - $checkRight = false, - $topic = 0, - $ihome = 0, - $asobject = true, - $order = 'counter' - ) { - /** @var \XoopsMySQLDatabase $db */ - $db = \XoopsDatabaseFactory::getDatabaseConnection(); + int $limit = 0, + int $start = 0, + int $checkRight = 0, + $topic = 0, + int $ihome = 0, + bool $asobject = true, + string $order = 'counter' + ): ?array { $myts = \MyTextSanitizer::getInstance(); $ret = []; $tdate = \mktime(0, 0, 0, (int)\date('n'), (int)\date('j'), (int)\date('Y')); - $sql = 'SELECT s.*, t.* FROM ' . $db->prefix('news_stories') . ' s, ' . $db->prefix('news_topics') . ' t WHERE (s.topicid=t.topic_id) AND (published > ' . $tdate . ' AND published < ' . \time() . ') AND (expired > ' . \time() . ' OR expired = 0) '; + $sql = 'SELECT s.*, t.* FROM ' . $this->db->prefix('news_stories') . ' s, ' . $this->db->prefix('news_topics') . ' t WHERE (s.topicid=t.topic_id) AND (published > ' . $tdate . ' AND published < ' . \time() . ') AND (expired > ' . \time() . ' OR expired = 0) '; if (0 != (int)$topic) { if (!\is_array($topic)) { @@ -388,12 +386,14 @@ public function getBigStory( } } $sql .= " ORDER BY $order DESC"; - $result = $db->query($sql, (int)$limit, (int)$start); - while (false !== ($myrow = $db->fetchArray($result))) { - if ($asobject) { - $ret[] = new self($myrow); - } else { - $ret[$myrow['storyid']] = \htmlspecialchars($myrow['title'], \ENT_QUOTES | \ENT_HTML5); + $result = $this->db->query($sql, (int)$limit, (int)$start); + if ($this->db->isResultSet($result)) { + while (false !== ($myrow = $this->db->fetchArray($result))) { + if ($asobject) { + $ret[] = new self($myrow); + } else { + $ret[$myrow['storyid']] = \htmlspecialchars($myrow['title'], \ENT_QUOTES | \ENT_HTML5); + } } } @@ -404,20 +404,17 @@ public function getBigStory( * Get all articles published by an author * * @param int $uid author's id - * @param bool $checkRight whether to check the user's rights to topics - * + * @param int $checkRight whether to check the user's rights to topics * @param bool $asobject * * @return array */ - public function getAllPublishedByAuthor($uid, $checkRight = false, $asobject = true) + public function getAllPublishedByAuthor(int $uid, int $checkRight = 0, bool $asobject = true): array { - /** @var \XoopsMySQLDatabase $db */ - $db = \XoopsDatabaseFactory::getDatabaseConnection(); $myts = \MyTextSanitizer::getInstance(); $ret = []; - $tblstory = $db->prefix('news_stories'); - $tbltopics = $db->prefix('news_topics'); + $tblstory = $this->db->prefix('news_stories'); + $tbltopics = $this->db->prefix('news_topics'); $sql = 'SELECT ' . $tblstory @@ -447,34 +444,36 @@ public function getAllPublishedByAuthor($uid, $checkRight = false, $asobject = t } } $sql .= ' ORDER BY ' . $tbltopics . '.topic_title ASC, ' . $tblstory . '.published DESC'; - $result = $db->query($sql); - while (false !== ($myrow = $db->fetchArray($result))) { - if ($asobject) { - $ret[] = new self($myrow); - } else { - if ($myrow['nohtml']) { - $html = 0; - } else { - $html = 1; - } - if ($myrow['nosmiley']) { - $smiley = 0; + $result = $this->db->query($sql); + if ($this->db->isResultSet($result)) { + while (false !== ($myrow = $this->db->fetchArray($result))) { + if ($asobject) { + $ret[] = new self($myrow); } else { - $smiley = 1; + if ($myrow['nohtml']) { + $html = 0; + } else { + $html = 1; + } + if ($myrow['nosmiley']) { + $smiley = 0; + } else { + $smiley = 1; + } + $ret[$myrow['storyid']] = [ + 'title' => $myts->displayTarea($myrow['title'], $html, $smiley, 1), + 'topicid' => (int)$myrow['topicid'], + 'storyid' => (int)$myrow['storyid'], + 'hometext' => $myts->displayTarea($myrow['hometext'], $html, $smiley, 1), + 'counter' => (int)$myrow['counter'], + 'created' => (int)$myrow['created'], + 'topic_title' => $myts->displayTarea($myrow['topic_title'], $html, $smiley, 1), + 'topic_color' => $myts->displayTarea($myrow['topic_color']), + 'published' => (int)$myrow['published'], + 'rating' => (float)$myrow['rating'], + 'votes' => (int)$myrow['votes'], + ]; } - $ret[$myrow['storyid']] = [ - 'title' => $myts->displayTarea($myrow['title'], $html, $smiley, 1), - 'topicid' => (int)$myrow['topicid'], - 'storyid' => (int)$myrow['storyid'], - 'hometext' => $myts->displayTarea($myrow['hometext'], $html, $smiley, 1), - 'counter' => (int)$myrow['counter'], - 'created' => (int)$myrow['created'], - 'topic_title' => $myts->displayTarea($myrow['topic_title'], $html, $smiley, 1), - 'topic_color' => $myts->displayTarea($myrow['topic_color']), - 'published' => (int)$myrow['published'], - 'rating' => (float)$myrow['rating'], - 'votes' => (int)$myrow['votes'], - ]; } } @@ -490,7 +489,7 @@ public function getAllPublishedByAuthor($uid, $checkRight = false, $asobject = t * @param bool $asobject * @return array */ - public static function getAllExpired($limit = 0, $start = 0, $topic = 0, $ihome = 0, $asobject = true) + public static function getAllExpired(int $limit = 0, int $start = 0, int $topic = 0, int $ihome = 0, bool $asobject = true): array { /** @var \XoopsMySQLDatabase $db */ $db = \XoopsDatabaseFactory::getDatabaseConnection(); @@ -505,11 +504,13 @@ public static function getAllExpired($limit = 0, $start = 0, $topic = 0, $ihome $sql .= ' ORDER BY expired DESC'; $result = $db->query($sql, (int)$limit, (int)$start); - while (false !== ($myrow = $db->fetchArray($result))) { - if ($asobject) { - $ret[] = new self($myrow); - } else { - $ret[$myrow['storyid']] = \htmlspecialchars($myrow['title'], \ENT_QUOTES | \ENT_HTML5); + if ($db->isResultSet($result)) { + while (false !== ($myrow = $db->fetchArray($result))) { + if ($asobject) { + $ret[] = new self($myrow); + } else { + $ret[$myrow['storyid']] = \htmlspecialchars($myrow['title'], \ENT_QUOTES | \ENT_HTML5); + } } } @@ -523,7 +524,7 @@ public static function getAllExpired($limit = 0, $start = 0, $topic = 0, $ihome * @param int $start * @return array */ - public static function getAllAutoStory($limit = 0, $asobject = true, $start = 0) + public static function getAllAutoStory(int $limit = 0, bool $asobject = true, int $start = 0): array { /** @var \XoopsMySQLDatabase $db */ $db = \XoopsDatabaseFactory::getDatabaseConnection(); @@ -531,11 +532,14 @@ public static function getAllAutoStory($limit = 0, $asobject = true, $start = 0) $ret = []; $sql = 'SELECT * FROM ' . $db->prefix('news_stories') . ' WHERE published > ' . \time() . ' ORDER BY published ASC'; $result = $db->query($sql, (int)$limit, (int)$start); - while (false !== ($myrow = $db->fetchArray($result))) { - if ($asobject) { - $ret[] = new self($myrow); - } else { - $ret[$myrow['storyid']] = \htmlspecialchars($myrow['title'], \ENT_QUOTES | \ENT_HTML5); + if ($db->isResultSet($result)) { + /** @var array $myrow */ + while (false !== ($myrow = $db->fetchArray($result))) { + if ($asobject) { + $ret[] = new self($myrow); + } else { + $ret[$myrow['storyid']] = \htmlspecialchars($myrow['title'], \ENT_QUOTES | \ENT_HTML5); + } } } @@ -545,16 +549,18 @@ public static function getAllAutoStory($limit = 0, $asobject = true, $start = 0) /** * Get all submitted stories awaiting approval * - * @param int $limit Denotes where to start the query - * @param bool $asobject true will returns the stories as an array of objects, false will return storyid => title - * @param bool $checkRight whether to check the user's rights to topics + * @param int|null $limit Denotes where to start the query + * @param bool $asobject true will return the stories as an array of objects, false will return storyid => title + * @param int|null $checkRight whether to check the user's rights to topics * * @param int $start * * @return array */ - public static function getAllSubmitted($limit = 0, $asobject = true, $checkRight = false, $start = 0) + public static function getAllSubmitted(?int $limit = null, bool $asobject = true, ?int $checkRight = null, int $start = 0): array { + $checkRight ??= false; + $limit ??= 0; /** @var \XoopsMySQLDatabase $db */ $db = \XoopsDatabaseFactory::getDatabaseConnection(); $myts = \MyTextSanitizer::getInstance(); @@ -575,11 +581,14 @@ public static function getAllSubmitted($limit = 0, $asobject = true, $checkRight $sql = 'SELECT s.*, t.* FROM ' . $db->prefix('news_stories') . ' s, ' . $db->prefix('news_topics') . ' t '; $sql .= ' ' . $criteria->renderWhere() . ' AND (s.topicid=t.topic_id) ORDER BY created DESC'; $result = $db->query($sql, (int)$limit, (int)$start); - while (false !== ($myrow = $db->fetchArray($result))) { - if ($asobject) { - $ret[] = new self($myrow); - } else { - $ret[$myrow['storyid']] = \htmlspecialchars($myrow['title'], \ENT_QUOTES | \ENT_HTML5); + if ($db->isResultSet($result)) { + /** @var array $myrow */ + while (false !== ($myrow = $db->fetchArray($result))) { + if ($asobject) { + $ret[] = new self($myrow); + } else { + $ret[$myrow['storyid']] = \htmlspecialchars($myrow['title'], \ENT_QUOTES | \ENT_HTML5); + } } } @@ -589,13 +598,14 @@ public static function getAllSubmitted($limit = 0, $asobject = true, $checkRight /** * Used in the module's admin to know the number of expired, automated or pubilshed news * - * @param int $storytype 1=Expired, 2=Automated, 3=New submissions, 4=Last published stories - * @param bool $checkRight verify permissions or not ? + * @param int|null $storytype 1=Expired, 2=Automated, 3=New submissions, 4=Last published stories + * @param int $checkRight verify permissions or not ? * * @return int */ - public static function getAllStoriesCount($storytype = 1, $checkRight = false) + public static function getAllStoriesCount(?int $storytype = null, int $checkRight = 0): int { + $storytype ??= 1; /** @var \XoopsMySQLDatabase $db */ $db = \XoopsDatabaseFactory::getDatabaseConnection(); $sql = 'SELECT count(*) AS cpt FROM ' . $db->prefix('news_stories') . ' WHERE '; @@ -623,26 +633,30 @@ public static function getAllStoriesCount($storytype = 1, $checkRight = false) } } $result = $db->query($sql); - $myrow = $db->fetchArray($result); - - return $myrow['cpt']; + if ($db->isResultSet($result)) { + $myrow = $db->fetchArray($result); + return (int)$myrow['cpt']; + } + return 0; } /** * Get a list of stories (as objects) related to a specific topic - * @param $topicid + * @param int $topicid * @param int $limit * @return array */ - public static function getByTopic($topicid, $limit = 0) + public static function getByTopic($topicid, int $limit = 0): array { $ret = []; /** @var \XoopsMySQLDatabase $db */ $db = \XoopsDatabaseFactory::getDatabaseConnection(); $sql = 'SELECT * FROM ' . $db->prefix('news_stories') . ' WHERE topicid=' . (int)$topicid . ' ORDER BY published DESC'; $result = $db->query($sql, (int)$limit, 0); - while (false !== ($myrow = $db->fetchArray($result))) { - $ret[] = new self($myrow); + if ($db->isResultSet($result)) { + while (false !== ($myrow = $db->fetchArray($result))) { + $ret[] = new self($myrow); + } } return $ret; @@ -650,39 +664,84 @@ public static function getByTopic($topicid, $limit = 0) /** * Count the number of news published for a specific topic - * @param int $topicid - * @param bool $checkRight - * @return mixed|null + * @param int|null $topicid + * @param bool|int $checkRight + * @return int|string */ - public static function countPublishedByTopic($topicid = 0, $checkRight = false) + public static function countPublishedByTopic(?int $topicid = null, int $checkRight = 0): int { + $topicid ??= 0; + $count = 0; + /** @var \XoopsMySQLDatabase $db */ - $db = \XoopsDatabaseFactory::getDatabaseConnection(); - $sql = 'SELECT COUNT(*) FROM ' . $db->prefix('news_stories') . ' WHERE published > 0 AND published <= ' . \time() . ' AND (expired = 0 OR expired > ' . \time() . ')'; - if (!empty($topicid)) { - $sql .= ' AND topicid=' . (int)$topicid; + $db = \XoopsDatabaseFactory::getDatabaseConnection(); + + // Base SQL query with placeholders for prepared statement + $sql = 'SELECT COUNT(*) FROM ' . $db->prefix('news_stories') . ' WHERE published > 0 AND published <= ? AND (expired = 0 OR expired > ?)'; + $params = [\time(), \time()]; + $types = 'ii'; // integer, integer + + // Append topicid condition if provided + if ($topicid > 0) { + $sql .= ' AND topicid = ?'; + $params[] = $topicid; + $types .= 'i'; // Add another integer type } else { - $sql .= ' AND ihome=0'; - if ($checkRight) { - $topics = Utility::getMyItemIds('news_view'); - if (\count($topics) > 0) { - $topics = \implode(',', $topics); - $sql .= ' AND topicid IN (' . $topics . ')'; - } else { - return null; - } + $sql .= ' AND ihome = 0'; + } + + // Check user's rights if necessary + if ($checkRight) { + $topics = Utility::getMyItemIds('news_view'); + if (\count($topics) > 0) { + $topicsList = \implode(',', \array_map('intval', $topics)); + $sql .= ' AND topicid IN (' . $topicsList . ')'; + } else { + return $count; } } - $result = $db->query($sql); - [$count] = $db->fetchRow($result); + + // Prepare the statement using the underlying mysqli connection + $stmt = $db->conn->prepare($sql); + if ($stmt === false) { + \XoopsLogger::getInstance()->handleError(E_USER_ERROR, "Error preparing query in countPublishedByTopic: " . $db->error(), __FILE__, __LINE__); + return $count; + } + + // Bind parameters + if (!$stmt->bind_param($types, ...$params)) { + \XoopsLogger::getInstance()->handleError(E_USER_ERROR, "Error binding parameters in countPublishedByTopic: " . $stmt->error, __FILE__, __LINE__); + $stmt->close(); + return $count; + } + + // Execute the prepared statement + if (!$stmt->execute()) { + \XoopsLogger::getInstance()->handleError(E_USER_ERROR, "Error executing query in countPublishedByTopic: " . $stmt->error, __FILE__, __LINE__); + $stmt->close(); + return $count; + } + + // Bind the result + $stmt->bind_result($count); + + // Fetch the result + if (!$stmt->fetch()) { + \XoopsLogger::getInstance()->handleError(E_USER_ERROR, "Error fetching result in countPublishedByTopic: " . $stmt->error, __FILE__, __LINE__); + $count = 0; + } + + // Close the statement + $stmt->close(); return $count; } + /** * Internal function */ - public function adminlink() + public function adminlink(): string { global $xoopsModule; $dirname = \basename(\dirname(__DIR__)); @@ -722,7 +781,7 @@ public function adminlink() * @param string $format * @return string */ - public function topic_imgurl($format = 'S') + public function topic_imgurl(string $format = 'S'): string { if ('' === \trim($this->topic_imgurl)) { $this->topic_imgurl = 'blank.png'; @@ -749,9 +808,9 @@ public function topic_imgurl($format = 'S') /** * @param string $format * - * @return mixed + * @return string */ - public function topic_title($format = 'S') + public function topic_title(string $format = 'S'): string { $myts = \MyTextSanitizer::getInstance(); switch ($format) { @@ -777,7 +836,7 @@ public function topic_title($format = 'S') /** * @return string */ - public function imglink() + public function imglink(): string { $ret = ''; if ('' !== $this->topic_imgurl() @@ -791,7 +850,7 @@ public function imglink() /** * @return string */ - public function textlink() + public function textlink(): string { $ret = '' . $this->topic_title() . ''; return $ret; @@ -802,10 +861,10 @@ public function textlink() * @param $filescount * @return array */ - public function prepare2show($filescount) + public function prepare2show($filescount): array { global $xoopsUser, $xoopsConfig, $xoopsModule; - /** @var News\Helper $helper */ + /** @var Helper $helper */ $helper = Helper::getInstance(); $dirname = \basename(\dirname(__DIR__)); @@ -827,7 +886,7 @@ public function prepare2show($filescount) $story['poster'] = $xoopsConfig['anonymous']; } if ($helper->getConfig('ratenews')) { - $story['rating'] = \number_format($this->rating(), 2); + $story['rating'] = \number_format((float)$this->rating(), 2); if (1 == $this->votes) { $story['votes'] = \_NW_ONEVOTE; } else { @@ -853,8 +912,8 @@ public function prepare2show($filescount) } $story['pictureinfo'] = $this->pictureinfo(); - $introcount = mb_strlen($story['text']); - $fullcount = mb_strlen($this->bodytext()); + $introcount = \mb_strlen($story['text']); + $fullcount = \mb_strlen($this->bodytext()); $totalcount = $introcount + $fullcount; $morelink = ''; @@ -934,9 +993,9 @@ public function prepare2show($filescount) /** * Returns the user's name of the current story according to the module's option "displayname" * @param int $uid - * @return null|string + * @return string */ - public function uname($uid = 0) + public function uname(int $uid = 0): string { global $xoopsConfig; static $tblusers = []; @@ -962,8 +1021,10 @@ public function uname($uid = 0) $tblusers[$uid] = \XoopsUser::getUnameFromId($uid); return $tblusers[$uid]; - case 2: // Display full name (if it is not empty) /** @var \XoopsMemberHandler $memberHandler */ $memberHandler = xoops_getHandler('member'); - $thisuser = $memberHandler->getUser($uid); + case 2: // Display full name (if it is not empty) + /** @var \XoopsMemberHandler $memberHandler */ + $memberHandler = xoops_getHandler('member'); + $thisuser = $memberHandler->getUser($uid); if (\is_object($thisuser)) { $return = $thisuser->getVar('name'); if ('' === $return) { @@ -973,17 +1034,20 @@ public function uname($uid = 0) $return = $xoopsConfig['anonymous']; } $tblusers[$uid] = $return; - - return $return; + break; case 3: // Nothing $tblusers[$uid] = ''; - - return ''; + break; + default: + $tblusers[$uid] = \XoopsUser::getUnameFromId($uid); // Default to username + break; } - return null; + return $tblusers[$uid] ?? ''; // Ensure we always return a string } + + /** * Function used to export news (in xml) and eventually the topics definitions * Warning, permissions are not exported ! @@ -1001,42 +1065,44 @@ public function uname($uid = 0) * @internal param string $topiclist If not empty, a list of topics to limit to */ public function exportNews( - $fromdate, - $todate, - $topicslist, - $usetopicsdef, - &$tbltopics, - $asobject = true, - $order = 'published' - ) { + int $fromdate, + int $todate, + string $topicslist, + $usetopicsdef, + &$tbltopics, + bool $asobject = true, + string $order = 'published' + ): array { $ret = []; - /** @var \XoopsMySQLDatabase $db */ - $db = \XoopsDatabaseFactory::getDatabaseConnection(); $myts = \MyTextSanitizer::getInstance(); if ($usetopicsdef) { // We firt begin by exporting topics definitions // Before all we must know wich topics to export - $sql = 'SELECT DISTINCT topicid FROM ' . $db->prefix('news_stories') . ' WHERE (published >=' . $fromdate . ' AND published <= ' . $todate . ')'; + $sql = 'SELECT DISTINCT topicid FROM ' . $this->db->prefix('news_stories') . ' WHERE (published >=' . $fromdate . ' AND published <= ' . $todate . ')'; if ('' !== \trim($topicslist)) { $sql .= ' AND topicid IN (' . $topicslist . ')'; } - $result = $db->query($sql); - while (false !== ($myrow = $db->fetchArray($result))) { - $tbltopics[] = $myrow['topicid']; + $result = $this->db->query($sql); + if ($this->db->isResultSet($result)) { + while (false !== ($myrow = $this->db->fetchArray($result))) { + $tbltopics[] = $myrow['topicid']; + } } } // Now we can search for the stories - $sql = 'SELECT s.*, t.* FROM ' . $this->table . ' s, ' . $db->prefix('news_topics') . ' t WHERE (s.topicid=t.topic_id) AND (s.published >=' . $fromdate . ' AND s.published <= ' . $todate . ')'; + $sql = 'SELECT s.*, t.* FROM ' . $this->table . ' s, ' . $this->db->prefix('news_topics') . ' t WHERE (s.topicid=t.topic_id) AND (s.published >=' . $fromdate . ' AND s.published <= ' . $todate . ')'; if ('' !== \trim($topicslist)) { $sql .= ' AND topicid IN (' . $topicslist . ')'; } $sql .= " ORDER BY $order DESC"; - $result = $db->query($sql); - while (false !== ($myrow = $db->fetchArray($result))) { - if ($asobject) { - $ret[] = new self($myrow); - } else { - $ret[$myrow['storyid']] = \htmlspecialchars($myrow['title'], \ENT_QUOTES | \ENT_HTML5); + $result = $this->db->query($sql); + if ($this->db->isResultSet($result)) { + while (false !== ($myrow = $this->db->fetchArray($result))) { + if ($asobject) { + $ret[] = new self($myrow); + } else { + $ret[$myrow['storyid']] = \htmlspecialchars($myrow['title'], \ENT_QUOTES | \ENT_HTML5); + } } } @@ -1048,20 +1114,20 @@ public function exportNews( * @param bool $approved * @return bool|int */ - public function store($approved = false) + public function store(bool $approved = false) { $myts = \MyTextSanitizer::getInstance(); $counter = $this->counter ?? 0; - $title = $GLOBALS['xoopsDB']->escape($myts->censorString($this->title)); - $subtitle = $GLOBALS['xoopsDB']->escape($myts->censorString($this->subtitle)); + $title = $GLOBALS['xoopsDB']->escape($myts->executeExtension('censor', $this->title)); + $subtitle = $GLOBALS['xoopsDB']->escape($myts->executeExtension('censor', $this->subtitle)); $hostname = $GLOBALS['xoopsDB']->escape($this->hostname); $type = $GLOBALS['xoopsDB']->escape($this->type); - $hometext = $GLOBALS['xoopsDB']->escape($myts->censorString($this->hometext)); - $bodytext = $GLOBALS['xoopsDB']->escape($myts->censorString($this->bodytext)); - $description = $GLOBALS['xoopsDB']->escape($myts->censorString($this->description)); - $keywords = $GLOBALS['xoopsDB']->escape($myts->censorString($this->keywords)); + $hometext = $GLOBALS['xoopsDB']->escape($myts->executeExtension('censor', $this->hometext)); + $bodytext = $GLOBALS['xoopsDB']->escape($myts->executeExtension('censor', $this->bodytext)); + $description = $GLOBALS['xoopsDB']->escape($myts->executeExtension('censor', $this->description)); + $keywords = $GLOBALS['xoopsDB']->escape($myts->executeExtension('censor', $this->keywords)); $picture = $GLOBALS['xoopsDB']->escape($this->picture); - $pictureinfo = $GLOBALS['xoopsDB']->escape($myts->censorString($this->pictureinfo)); + $pictureinfo = $GLOBALS['xoopsDB']->escape($myts->executeExtension('censor', $this->pictureinfo)); $votes = (int)$this->votes; $rating = (float)$this->rating; if (!isset($this->nohtml) || 1 != $this->nohtml) { @@ -1077,68 +1143,68 @@ public function store($approved = false) $this->topicdisplay = 1; } $expired = !empty($this->expired) ? $this->expired : 0; - if (!isset($this->storyid)) { - //$newpost = 1; - $newstoryid = $this->db->genId($this->table . '_storyid_seq'); - $created = \time(); - $published = $this->approved ? (int)$this->published : 0; + if (isset($this->storyid)) { $sql = \sprintf( - "INSERT INTO `%s` (storyid, uid, title, created, published, expired, hostname, nohtml, nosmiley, hometext, bodytext, counter, topicid, ihome, notifypub, story_type, topicdisplay, topicalign, comments, rating, votes, description, keywords, picture, pictureinfo, subtitle) VALUES (%u, %u, '%s', %u, %u, %u, '%s', %u, %u, '%s', '%s', %u, %u, %u, %u, '%s', %u, '%s', %u, %u, %u, '%s', '%s', '%s', '%s', '%s')", + "UPDATE `%s` SET title='%s', published=%u, expired=%u, nohtml=%u, nosmiley=%u, hometext='%s', bodytext='%s', topicid=%u, ihome=%u, topicdisplay=%u, topicalign='%s', comments=%u, rating=%u, votes=%u, uid=%u, description='%s', keywords='%s', picture='%s' , pictureinfo='%s' , subtitle='%s' WHERE storyid = %u", $this->table, - $newstoryid, - (int)$this->uid(), $title, - $created, - $published, + (int)$this->published(), $expired, - $hostname, $this->nohtml(), $this->nosmiley(), $hometext, $bodytext, - $counter, (int)$this->topicid(), $this->ihome(), - $this->notifypub(), - $type, (int)$this->topicdisplay(), $this->topicalign, (int)$this->comments(), $rating, $votes, + (int)$this->uid(), $description, $keywords, $picture, $pictureinfo, - $subtitle + $subtitle, + (int)$this->storyid() ); + $newstoryid = (int)$this->storyid(); } else { + //$newpost = 1; + $newstoryid = $this->db->genId($this->table . '_storyid_seq'); + $created = \time(); + $published = $this->approved ? (int)$this->published : 0; $sql = \sprintf( - "UPDATE `%s` SET title='%s', published=%u, expired=%u, nohtml=%u, nosmiley=%u, hometext='%s', bodytext='%s', topicid=%u, ihome=%u, topicdisplay=%u, topicalign='%s', comments=%u, rating=%u, votes=%u, uid=%u, description='%s', keywords='%s', picture='%s' , pictureinfo='%s' , subtitle='%s' WHERE storyid = %u", + "INSERT INTO `%s` (storyid, uid, title, created, published, expired, hostname, nohtml, nosmiley, hometext, bodytext, counter, topicid, ihome, notifypub, story_type, topicdisplay, topicalign, comments, rating, votes, description, keywords, picture, pictureinfo, subtitle) VALUES (%u, %u, '%s', %u, %u, %u, '%s', %u, %u, '%s', '%s', %u, %u, %u, %u, '%s', %u, '%s', %u, %u, %u, '%s', '%s', '%s', '%s', '%s')", $this->table, + $newstoryid, + (int)$this->uid(), $title, - (int)$this->published(), + $created, + $published, $expired, + $hostname, $this->nohtml(), $this->nosmiley(), $hometext, $bodytext, + $counter, (int)$this->topicid(), $this->ihome(), + $this->notifypub(), + $type, (int)$this->topicdisplay(), $this->topicalign, (int)$this->comments(), $rating, $votes, - (int)$this->uid(), $description, $keywords, $picture, $pictureinfo, - $subtitle, - (int)$this->storyid() + $subtitle ); - $newstoryid = (int)$this->storyid(); } if (!$this->db->queryF($sql)) { return false; @@ -1234,9 +1300,9 @@ public function setKeywords($data): void /** * @param string $format * - * @return mixed + * @return string */ - public function description($format = 'S') + public function description(string $format = 'S'): string { $myts = \MyTextSanitizer::getInstance(); switch (mb_strtoupper($format)) { @@ -1258,9 +1324,9 @@ public function description($format = 'S') /** * @param string $format * - * @return mixed + * @return string */ - public function keywords($format = 'S') + public function keywords(string $format = 'S'): string { $myts = \MyTextSanitizer::getInstance(); switch (mb_strtoupper($format)) { @@ -1281,28 +1347,32 @@ public function keywords($format = 'S') /** * Returns a random number of news - * @param int $limit - * @param int $start - * @param bool $checkRight - * @param int $topic - * @param int $ihome - * @param string $order - * @param bool $topic_frontpage + * @param int $limit + * @param int|null $start + * @param int|null $checkRight + * @param array|int $topic + * @param int|null $ihome + * @param string|null $order + * @param bool $topic_frontpage * @return array */ public function getRandomNews( - $limit = 0, - $start = 0, - $checkRight = false, - $topic = 0, - $ihome = 0, - $order = 'published', - $topic_frontpage = false - ) { - /** @var \XoopsMySQLDatabase $db */ - $db = \XoopsDatabaseFactory::getDatabaseConnection(); - $ret = $rand_keys = $ret3 = []; - $sql = 'SELECT storyid FROM ' . $db->prefix('news_stories') . ' WHERE (published > 0 AND published <= ' . \time() . ') AND (expired = 0 OR expired > ' . \time() . ')'; + int $limit = 0, + ?int $start = null, + ?int $checkRight = 0, + $topic = 0, + ?int $ihome = null, + ?string $order = null, + bool $topic_frontpage = false + ): ?array { + $order ??= 'published'; + $checkRight ??= 0; + $ihome ??= 0; + $start ??= 0; + $ret = []; + $rand_keys = []; + $ret3 = []; + $sql = 'SELECT storyid FROM ' . $this->db->prefix('news_stories') . ' WHERE (published > 0 AND published <= ' . \time() . ') AND (expired = 0 OR expired > ' . \time() . ')'; if (0 != $topic) { if (!\is_array($topic)) { if ($checkRight) { @@ -1337,10 +1407,11 @@ public function getRandomNews( $sql .= ' AND t.topic_frontpage=1'; } $sql .= " ORDER BY $order DESC"; - $result = $db->query($sql); - - while (false !== ($myrow = $db->fetchArray($result))) { - $ret[] = $myrow['storyid']; + $result = $this->db->query($sql); + if ($this->db->isResultSet($result)) { + while (false !== ($myrow = $this->db->fetchArray($result))) { + $ret[] = $myrow['storyid']; + } } $cnt = \count($ret); if ($cnt) { @@ -1366,20 +1437,20 @@ public function getRandomNews( * @param $limit * @return array */ - public function getStats($limit) + public function getStats($limit): array { $ret = []; - /** @var \XoopsMySQLDatabase $db */ - $db = \XoopsDatabaseFactory::getDatabaseConnection(); - $tbls = $db->prefix('news_stories'); - $tblt = $db->prefix('news_topics'); - $tblf = $db->prefix('news_stories_files'); + $tbls = $this->db->prefix('news_stories'); + $tblt = $this->db->prefix('news_topics'); + $tblf = $this->db->prefix('news_stories_files'); // Number of stories per topic, including expired and non published stories $ret2 = []; $sql = "SELECT count(s.storyid) as cpt, s.topicid, t.topic_title FROM $tbls s, $tblt t WHERE s.topicid=t.topic_id GROUP BY s.topicid ORDER BY t.topic_title"; - $result = $db->query($sql); - while (false !== ($myrow = $db->fetchArray($result))) { - $ret2[$myrow['topicid']] = $myrow; + $result = $this->db->query($sql); + if ($this->db->isResultSet($result)) { + while (false !== ($myrow = $this->db->fetchArray($result))) { + $ret2[$myrow['topicid']] = $myrow; + } } $ret['storiespertopic'] = $ret2; unset($ret2); @@ -1387,9 +1458,11 @@ public function getStats($limit) // Total of reads per topic $ret2 = []; $sql = "SELECT Sum(counter) as cpt, topicid FROM $tbls GROUP BY topicid ORDER BY topicid"; - $result = $db->query($sql); - while (false !== ($myrow = $db->fetchArray($result))) { - $ret2[$myrow['topicid']] = $myrow['cpt']; + $result = $this->db->query($sql); + if ($this->db->isResultSet($result)) { + while (false !== ($myrow = $this->db->fetchArray($result))) { + $ret2[$myrow['topicid']] = $myrow['cpt']; + } } $ret['readspertopic'] = $ret2; unset($ret2); @@ -1397,9 +1470,11 @@ public function getStats($limit) // Attached files per topic $ret2 = []; $sql = "SELECT Count(*) as cpt, s.topicid FROM $tblf f, $tbls s WHERE f.storyid=s.storyid GROUP BY s.topicid ORDER BY s.topicid"; - $result = $db->query($sql); - while (false !== ($myrow = $db->fetchArray($result))) { - $ret2[$myrow['topicid']] = $myrow['cpt']; + $result = $this->db->query($sql); + if ($this->db->isResultSet($result)) { + while (false !== ($myrow = $this->db->fetchArray($result))) { + $ret2[$myrow['topicid']] = $myrow['cpt']; + } } $ret['filespertopic'] = $ret2; unset($ret2); @@ -1407,9 +1482,11 @@ public function getStats($limit) // Expired articles per topic $ret2 = []; $sql = "SELECT Count(storyid) as cpt, topicid FROM $tbls WHERE expired>0 AND expired<=" . \time() . ' GROUP BY topicid ORDER BY topicid'; - $result = $db->query($sql); - while (false !== ($myrow = $db->fetchArray($result))) { - $ret2[$myrow['topicid']] = $myrow['cpt']; + $result = $this->db->query($sql); + if ($this->db->isResultSet($result)) { + while (false !== ($myrow = $this->db->fetchArray($result))) { + $ret2[$myrow['topicid']] = $myrow['cpt']; + } } $ret['expiredpertopic'] = $ret2; unset($ret2); @@ -1417,9 +1494,11 @@ public function getStats($limit) // Number of unique authors per topic $ret2 = []; $sql = "SELECT Count(Distinct(uid)) as cpt, topicid FROM $tbls GROUP BY topicid ORDER BY topicid"; - $result = $db->query($sql); - while (false !== ($myrow = $db->fetchArray($result))) { - $ret2[$myrow['topicid']] = $myrow['cpt']; + $result = $this->db->query($sql); + if ($this->db->isResultSet($result)) { + while (false !== ($myrow = $this->db->fetchArray($result))) { + $ret2[$myrow['topicid']] = $myrow['cpt']; + } } $ret['authorspertopic'] = $ret2; unset($ret2); @@ -1427,9 +1506,11 @@ public function getStats($limit) // Most readed articles $ret2 = []; $sql = "SELECT s.storyid, s.uid, s.title, s.counter, s.topicid, t.topic_title FROM $tbls s, $tblt t WHERE s.topicid=t.topic_id ORDER BY s.counter DESC"; - $result = $db->query($sql, (int)$limit); - while (false !== ($myrow = $db->fetchArray($result))) { - $ret2[$myrow['storyid']] = $myrow; + $result = $this->db->query($sql, (int)$limit); + if ($this->db->isResultSet($result)) { + while (false !== ($myrow = $this->db->fetchArray($result))) { + $ret2[$myrow['storyid']] = $myrow; + } } $ret['mostreadednews'] = $ret2; unset($ret2); @@ -1437,9 +1518,11 @@ public function getStats($limit) // Less readed articles $ret2 = []; $sql = "SELECT s.storyid, s.uid, s.title, s.counter, s.topicid, t.topic_title FROM $tbls s, $tblt t WHERE s.topicid=t.topic_id ORDER BY s.counter"; - $result = $db->query($sql, (int)$limit); - while (false !== ($myrow = $db->fetchArray($result))) { - $ret2[$myrow['storyid']] = $myrow; + $result = $this->db->query($sql, (int)$limit); + if ($this->db->isResultSet($result)) { + while (false !== ($myrow = $this->db->fetchArray($result))) { + $ret2[$myrow['storyid']] = $myrow; + } } $ret['lessreadednews'] = $ret2; unset($ret2); @@ -1447,9 +1530,11 @@ public function getStats($limit) // Best rated articles $ret2 = []; $sql = "SELECT s.storyid, s.uid, s.title, s.rating, s.topicid, t.topic_title FROM $tbls s, $tblt t WHERE s.topicid=t.topic_id ORDER BY s.rating DESC"; - $result = $db->query($sql, (int)$limit); - while (false !== ($myrow = $db->fetchArray($result))) { - $ret2[$myrow['storyid']] = $myrow; + $result = $this->db->query($sql, (int)$limit); + if ($this->db->isResultSet($result)) { + while (false !== ($myrow = $this->db->fetchArray($result))) { + $ret2[$myrow['storyid']] = $myrow; + } } $ret['besratednews'] = $ret2; unset($ret2); @@ -1457,9 +1542,11 @@ public function getStats($limit) // Most readed authors $ret2 = []; $sql = "SELECT Sum(counter) as cpt, uid FROM $tbls GROUP BY uid ORDER BY cpt DESC"; - $result = $db->query($sql, (int)$limit); - while (false !== ($myrow = $db->fetchArray($result))) { - $ret2[$myrow['uid']] = $myrow['cpt']; + $result = $this->db->query($sql, (int)$limit); + if ($this->db->isResultSet($result)) { + while (false !== ($myrow = $this->db->fetchArray($result))) { + $ret2[$myrow['uid']] = $myrow['cpt']; + } } $ret['mostreadedauthors'] = $ret2; unset($ret2); @@ -1467,9 +1554,11 @@ public function getStats($limit) // Best rated authors $ret2 = []; $sql = "SELECT Avg(rating) as cpt, uid FROM $tbls WHERE votes > 0 GROUP BY uid ORDER BY cpt DESC"; - $result = $db->query($sql, (int)$limit); - while (false !== ($myrow = $db->fetchArray($result))) { - $ret2[$myrow['uid']] = $myrow['cpt']; + $result = $this->db->query($sql, (int)$limit); + if ($this->db->isResultSet($result)) { + while (false !== ($myrow = $this->db->fetchArray($result))) { + $ret2[$myrow['uid']] = $myrow['cpt']; + } } $ret['bestratedauthors'] = $ret2; unset($ret2); @@ -1477,9 +1566,11 @@ public function getStats($limit) // Biggest contributors $ret2 = []; $sql = "SELECT Count(*) as cpt, uid FROM $tbls GROUP BY uid ORDER BY cpt DESC"; - $result = $db->query($sql, (int)$limit); - while (false !== ($myrow = $db->fetchArray($result))) { - $ret2[$myrow['uid']] = $myrow['cpt']; + $result = $this->db->query($sql, (int)$limit); + if ($this->db->isResultSet($result)) { + while (false !== ($myrow = $this->db->fetchArray($result))) { + $ret2[$myrow['uid']] = $myrow['cpt']; + } } $ret['biggestcontributors'] = $ret2; unset($ret2); @@ -1494,14 +1585,12 @@ public function getStats($limit) */ public function getOlderRecentNews(&$older, &$recent): void { - /** @var \XoopsMySQLDatabase $db */ - $db = \XoopsDatabaseFactory::getDatabaseConnection(); - $sql = 'SELECT min(published) AS minpublish, max(published) AS maxpublish FROM ' . $db->prefix('news_stories'); - $result = $db->query($sql); - if (!$result) { - $older = $recent = 0; + $sql = 'SELECT min(published) AS minpublish, max(published) AS maxpublish FROM ' . $this->db->prefix('news_stories'); + $result = Utility::queryAndCheck($this->db, $sql); + if ($this->db->isResultSet($result)) { + [$older, $recent] = $this->db->fetchRow($result); } else { - [$older, $recent] = $db->fetchRow($result); + $older = $recent = 0; } } @@ -1510,18 +1599,16 @@ public function getOlderRecentNews(&$older, &$recent): void */ /** - * @param bool $checkRight + * @param int $checkRight * @param int $limit * @param int $start * * @return array|null */ - public function getWhosWho($checkRight = false, $limit = 0, $start = 0) + public function getWhosWho(int $checkRight = 0, int $limit = 0, int $start = 0): ?array { - /** @var \XoopsMySQLDatabase $db */ - $db = \XoopsDatabaseFactory::getDatabaseConnection(); $ret = []; - $sql = 'SELECT DISTINCT(uid) AS uid FROM ' . $db->prefix('news_stories') . ' WHERE (published > 0 AND published <= ' . \time() . ') AND (expired = 0 OR expired > ' . \time() . ')'; + $sql = 'SELECT DISTINCT(uid) AS uid FROM ' . $this->db->prefix('news_stories') . ' WHERE (published > 0 AND published <= ' . \time() . ') AND (expired = 0 OR expired > ' . \time() . ')'; if ($checkRight) { $topics = Utility::getMyItemIds('news_view'); if (\count($topics) > 0) { @@ -1532,9 +1619,11 @@ public function getWhosWho($checkRight = false, $limit = 0, $start = 0) } } $sql .= ' ORDER BY uid'; - $result = $db->query($sql); - while (false !== ($myrow = $db->fetchArray($result))) { - $ret[] = $myrow['uid']; + $result = $this->db->query($sql); + if ($this->db->isResultSet($result)) { + while (false !== ($myrow = $this->db->fetchArray($result))) { + $ret[] = $myrow['uid']; + } } return $ret; @@ -1546,7 +1635,7 @@ public function getWhosWho($checkRight = false, $limit = 0, $start = 0) * @param $titles * @return string */ - public function auto_summary($text, &$titles) + public function auto_summary($text, &$titles): string { $auto_summary = ''; if (Utility::getModuleOption('enhanced_pagenav')) { @@ -1582,9 +1671,9 @@ public function auto_summary($text, &$titles) /** * @param string $format * - * @return mixed + * @return array|string|string[] */ - public function hometext($format = 'Show') + public function hometext(string $format = 'Show'): string { $hometext = ''; $myts = \MyTextSanitizer::getInstance(); @@ -1619,9 +1708,9 @@ public function hometext($format = 'Show') /** * @param string $format * - * @return mixed + * @return string */ - public function bodytext($format = 'Show') + public function bodytext(string $format = 'Show'): string { $myts = \MyTextSanitizer::getInstance(); $html = 1; @@ -1656,26 +1745,27 @@ public function bodytext($format = 'Show') /** * Returns stories by Ids - * @param $ids - * @param bool $checkRight - * @param bool $asobject - * @param string $order - * @param bool $onlyOnline + * @param array|string $ids + * @param int|null $checkRight + * @param bool|null $asobject + * @param string|null $order + * @param bool $onlyOnline * @return array|null */ public function getStoriesByIds( $ids, - $checkRight = true, - $asobject = true, - $order = 'published', - $onlyOnline = true - ) { - $limit = $start = 0; - /** @var \XoopsMySQLDatabase $db */ - $db = \XoopsDatabaseFactory::getDatabaseConnection(); - $myts = \MyTextSanitizer::getInstance(); - $ret = []; - $sql = 'SELECT s.*, t.* FROM ' . $db->prefix('news_stories') . ' s, ' . $db->prefix('news_topics') . ' t WHERE '; + ?int $checkRight = null, + ?bool $asobject = null, + ?string $order = null, + bool $onlyOnline = true + ): ?array { + $order ??= 'published'; + $asobject ??= true; + $checkRight ??= true; + $limit = $start = 0; + $myts = \MyTextSanitizer::getInstance(); + $ret = []; + $sql = 'SELECT s.*, t.* FROM ' . $this->db->prefix('news_stories') . ' s, ' . $this->db->prefix('news_topics') . ' t WHERE '; if ($ids && \is_array($ids)) { \array_walk($ids, '\intval'); } @@ -1695,16 +1785,16 @@ public function getStoriesByIds( } } $sql .= " ORDER BY s.$order DESC"; - $result = $db->query($sql, $limit, $start); - - while (false !== ($myrow = $db->fetchArray($result))) { - if ($asobject) { - $ret[$myrow['storyid']] = new self($myrow); - } else { - $ret[$myrow['storyid']] = \htmlspecialchars($myrow['title'], \ENT_QUOTES | \ENT_HTML5); + $result = $this->db->query($sql, $limit, $start); + if ($this->db->isResultSet($result)) { + while (false !== ($myrow = $this->db->fetchArray($result))) { + if ($asobject) { + $ret[$myrow['storyid']] = new self($myrow); + } else { + $ret[$myrow['storyid']] = \htmlspecialchars($myrow['title'], \ENT_QUOTES | \ENT_HTML5); + } } } - return $ret; } } diff --git a/class/NewsStoryHandler.php b/class/NewsStoryHandler.php index 8a1cae9..e5e520a 100644 --- a/class/NewsStoryHandler.php +++ b/class/NewsStoryHandler.php @@ -19,7 +19,7 @@ */ //require_once XOOPS_ROOT_PATH . '/modules/news/class/xoopsstory.php'; -require XOOPS_ROOT_PATH . '/include/comment_constants.php'; +//require XOOPS_ROOT_PATH . '/include/comment_constants.php'; require_once \dirname(__DIR__) . '/preloads/autoloader.php'; @@ -32,7 +32,12 @@ */ class NewsStoryHandler extends \XoopsPersistableObjectHandler { - public function __construct(\XoopsDatabase $db = null) + /** + * Constructor + * + * @param \XoopsDatabase|null $db database connection + */ + public function __construct(?\XoopsDatabase $db = null) { parent::__construct($db, 'news_stories', NewsStory::class, 'storieid', 'title'); } diff --git a/class/NewsTopic.php b/class/NewsTopic.php index 07ae580..5ceb80a 100644 --- a/class/NewsTopic.php +++ b/class/NewsTopic.php @@ -27,14 +27,14 @@ */ class NewsTopic extends XoopsTopic { - public $menu; - public $topic_description; - public $topic_frontpage; - public $topic_rssurl; - public $topic_color; +// public $menu; +// public $topic_description; +// public $topic_frontpage; +// public $topic_rssurl; +// public $topic_color; /** - * @param int $topicid + * @param array|int $topicid */ public function __construct($topicid = 0) { @@ -67,7 +67,7 @@ public function makeMyTopicSelBox( $onchange = '', $checkRight = false, $perm_type = 'news_view' - ) { + ): ?string { $perms = ''; if ($checkRight) { global $xoopsUser; @@ -118,7 +118,7 @@ public function makeMySelBox( $sel_name, $onchange, $perms - ) { + ): string { $myts = \MyTextSanitizer::getInstance(); $outbuffer = ''; $outbuffer = "'; - if ((bool)$addEmptyOption) { + if ($addEmptyOption) { $ret .= ''; } $this->makeSelBoxOptions($fieldName, $selected, $key, $ret, $prefix); @@ -224,33 +224,33 @@ public function makeSelBox( /** * Make a select box with options from the tree * - * @param string $name Name of the select box - * @param string $fieldName Name of the member variable from the - * node objects that should be used as the title for the options. - * @param string $prefix String to indent deeper levels - * @param string $selected Value to display as selected - * @param bool $addEmptyOption Set TRUE to add an empty option with value "0" at the top of the hierarchy - * @param int $key ID of the object to display as the root of select options - * @param string $extra extra content to add to the element - * @param string $caption optional caption for form element + * @param string $name Name of the select box + * @param string $fieldName Name of the member variable from the + * node objects that should be used as the title for the options. + * @param string $prefix String to indent deeper levels + * @param string|int $selected Value to display as selected + * @param bool $addEmptyOption Set TRUE to add an empty option with value "0" at the top of the hierarchy + * @param int $key ID of the object to display as the root of select options + * @param string $extra extra content to add to the element + * @param string $caption optional caption for form element * * @return \XoopsFormSelect form element */ public function makeSelectElement( - $name, - $fieldName, - $prefix = '-', + string $name, + string $fieldName, + string $prefix = '-', $selected = '', - $addEmptyOption = false, - $key = 0, - $extra = '', - $caption = '' - ) { + bool $addEmptyOption = false, + int $key = 0, + string $extra = '', + string $caption = '' + ): \XoopsFormSelect { \xoops_load('xoopsformselect'); $element = new \XoopsFormSelect($caption, $name, $selected); $element->setExtra($extra); - if ((bool)$addEmptyOption) { + if ($addEmptyOption) { $element->addOption('0', ' '); } $this->addSelectOptions($element, $fieldName, $key, $prefix); @@ -264,13 +264,13 @@ public function makeSelectElement( * @param \XoopsFormSelect $element form element to receive tree values as options * @param string $fieldName Name of the member variable from the node objects that * should be used as the title for the options. - * @param int $key ID of the object to display as the root of select options + * @param string|int $key ID of the object to display as the root of select options * @param string $prefix_orig String to indent items at deeper levels * @param string $prefix_curr String to indent the current item * * @access private */ - protected function addSelectOptions($element, $fieldName, $key, $prefix_orig, $prefix_curr = ''): void + protected function addSelectOptions(\XoopsFormSelect $element, string $fieldName, $key, string $prefix_orig, string $prefix_curr = ''): void { if ($key > 0) { $value = $this->tree[$key]['obj']->getVar($this->myId); @@ -296,11 +296,11 @@ protected function addSelectOptions($element, $fieldName, $key, $prefix_orig, $p * * @return mixed value */ - public function __get($name) + public function __get(?string $name) { $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1); if ('_tree' === $name) { - \trigger_error("XoopsObjectTree::\$_tree is deprecated, accessed from {$trace[0]['file']} line {$trace[0]['line']},"); + \trigger_error("XoopsObjectTree::\$_tree is deprecated, accessed from {$trace[0]['file']} line {$trace[0]['line']},", E_USER_DEPRECATED); return $this->tree; } diff --git a/class/PageNav.php b/class/PageNav.php index 5d33829..ef91fea 100644 --- a/class/PageNav.php +++ b/class/PageNav.php @@ -34,30 +34,31 @@ class PageNav /**#@+ * @access private */ - public $total; - public $perpage; - public $current; - public $url; + public int $total; + public int $perpage; + public int $current; + public string $url; /**#@-*/ /** * Constructor * - * @param int $total_items Total number of items - * @param int $items_perpage Number of items per page - * @param int $current_start First item on the current page - * @param string $start_name Name for "start" or "offset" - * @param string $extra_arg Additional arguments to pass in the URL + * @param int|string $total_items Total number of items + * @param int $items_perpage Number of items per page + * @param int $current_start First item on the current page + * @param string|null $start_name Name for "start" or "offset" + * @param string $extra_arg Additional arguments to pass in the URL **/ - public function __construct($total_items, $items_perpage, $current_start, $start_name = 'start', $extra_arg = '') + public function __construct($total_items, int $items_perpage, int $current_start, ?string $start_name = null, string $extra_arg = '') { + $start_name ??= 'start'; $this->total = (int)$total_items; $this->perpage = (int)$items_perpage; $this->current = (int)$current_start; if ('' !== $extra_arg && ('&' !== mb_substr($extra_arg, -5) || '&' !== mb_substr($extra_arg, -1))) { $extra_arg .= '&'; } - $this->url = $_SERVER['SCRIPT_NAME'] . '?' . $extra_arg . trim($start_name) . '='; + $this->url = $_SERVER['SCRIPT_NAME'] . '?' . $extra_arg . \trim($start_name) . '='; } /** @@ -67,20 +68,20 @@ public function __construct($total_items, $items_perpage, $current_start, $start * * @return string **/ - public function renderNav($offset = 4) + public function renderNav(int $offset = 4): string { $ret = ''; if ($this->total <= $this->perpage) { return $ret; } - $total_pages = ceil($this->total / $this->perpage); + $total_pages = \ceil($this->total / $this->perpage); if ($total_pages > 1) { $prev = $this->current - $this->perpage; if ($prev >= 0) { $ret .= '« '; } $counter = 1; - $current_page = (int)floor(($this->current + $this->perpage) / $this->perpage); + $current_page = (int)\floor(($this->current + $this->perpage) / $this->perpage); while ($counter <= $total_pages) { if ($counter == $current_page) { $ret .= '(' . $counter . ') '; @@ -112,18 +113,18 @@ public function renderNav($offset = 4) * * @return string **/ - public function renderSelect($showbutton = false) + public function renderSelect(bool $showbutton = false): ?string { if ($this->total < $this->perpage) { return null; } - $total_pages = ceil($this->total / $this->perpage); + $total_pages = \ceil($this->total / $this->perpage); $ret = ''; if ($total_pages > 1) { $ret = '
'; $ret .= ''; if ($showbutton) { - $ret .= ' '; + $ret .= ' '; } $ret .= '
'; } @@ -145,23 +146,24 @@ public function renderSelect($showbutton = false) /** * Create an enhanced navigational dropdown list * - * @param bool $showbutton Show the "Go" button? + * @param bool|null $showbutton Show the "Go" button? * @param null $titles * * @return string */ - public function renderEnhancedSelect($showbutton = false, $titles = null) + public function renderEnhancedSelect(?bool $showbutton = null, $titles = null): ?string { + $showbutton ??= false; if ($this->total < $this->perpage) { return null; } - $total_pages = ceil($this->total / $this->perpage); + $total_pages = \ceil($this->total / $this->perpage); $ret = ''; if ($total_pages > 1) { $ret = '
'; $ret .= ''; if ($showbutton) { - $ret .= ' '; + $ret .= ' '; } $ret .= '
'; } @@ -188,12 +190,12 @@ public function renderEnhancedSelect($showbutton = false, $titles = null) * * @return string **/ - public function renderImageNav($offset = 4) + public function renderImageNav(int $offset = 4): ?string { if ($this->total < $this->perpage) { return null; } - $total_pages = ceil($this->total / $this->perpage); + $total_pages = \ceil($this->total / $this->perpage); $ret = ''; if ($total_pages > 1) { $ret = ''; @@ -202,7 +204,7 @@ public function renderImageNav($offset = 4) $ret .= ''; } $counter = 1; - $current_page = (int)floor(($this->current + $this->perpage) / $this->perpage); + $current_page = (int)\floor(($this->current + $this->perpage) / $this->perpage); while ($counter <= $total_pages) { if ($counter == $current_page) { $ret .= ''; diff --git a/class/Registryfile.php b/class/Registryfile.php index 272d548..3ca7018 100644 --- a/class/Registryfile.php +++ b/class/Registryfile.php @@ -51,10 +51,10 @@ public function setfile($fichier = null): void public function getfile($fichier = null) { $fw = ''; - if (!$fichier) { - $fw = $this->filename; - } else { + if ($fichier) { $fw = XOOPS_UPLOAD_PATH . '/' . $fichier; + } else { + $fw = $this->filename; } if (\file_exists($fw)) { return file_get_contents($fw); @@ -69,19 +69,19 @@ public function getfile($fichier = null) * * @return bool */ - public function savefile($content, $fichier = null) + public function savefile($content, $fichier = null): bool { $fw = ''; - if (!$fichier) { - $fw = $this->filename; - } else { + if ($fichier) { $fw = XOOPS_UPLOAD_PATH . '/' . $fichier; + } else { + $fw = $this->filename; } if (\is_file($fw)) { @\unlink($fw); } /** @var resource $fp */ - $fp = \fopen($fw, 'wb') || exit(_ERRORS); + $fp = \fopen($fw, 'wb') || exit(\_ERRORS); \fwrite($fp, $content); \fclose($fp); diff --git a/class/Utility.php b/class/Utility.php index dad5f71..9762df9 100644 --- a/class/Utility.php +++ b/class/Utility.php @@ -2,18 +2,8 @@ namespace XoopsModules\News; -use MyTextSanitizer; use WideImage\WideImage; use Xmf\Request; -use XoopsFormDhtmlTextArea; -use XoopsFormEditor; -use XoopsFormFckeditor; -use XoopsFormHtmlarea; -use XoopsFormTextArea; -use XoopsFormTinyeditorTextArea; -use XoopsFormWysiwygTextArea; -use XoopsObjectTree; -use XoopsTpl; /** * Class Utility @@ -22,11 +12,11 @@ class Utility extends Common\SysUtility { //--------------- Custom module methods ----------------------------- /** - * @param $option - * @param string $repmodule - * @return bool|mixed + * @param string $option + * @param string $repmodule + * @return mixed */ - public static function getModuleOption($option, $repmodule = 'news') + public static function getModuleOption(string $option, string $repmodule = 'news') { global $xoopsModuleConfig, $xoopsModule; static $tbloptions = []; @@ -62,22 +52,22 @@ public static function getModuleOption($option, $repmodule = 'news') /** * Updates rating data in item table for a given item * - * @param $storyid + * @param int $storyid * @author Hervé Thouzard (https://www.herve-thouzard.com) * @copyright (c) Hervé Thouzard */ - public static function updateRating($storyid): void + public static function updateRating(int $storyid): void { global $xoopsDB; - $query = 'SELECT rating FROM ' . $xoopsDB->prefix('news_stories_votedata') . ' WHERE storyid = ' . $storyid; - $voteresult = $xoopsDB->query($query); - $votesDB = $xoopsDB->getRowsNum($voteresult); + $sql = 'SELECT rating FROM ' . $xoopsDB->prefix('news_stories_votedata') . ' WHERE storyid = ' . $storyid; + $result = self::queryAndCheck($xoopsDB, $sql); + $votesDB = $xoopsDB->getRowsNum($result); $totalrating = 0; - while ([$rating] = $xoopsDB->fetchRow($voteresult)) { + while ([$rating] = $xoopsDB->fetchRow($result)) { $totalrating += $rating; } $finalrating = $totalrating / $votesDB; - $finalrating = \number_format($finalrating, 4); + $finalrating = \number_format((float)$finalrating, 4); $sql = \sprintf('UPDATE `%s` SET rating = %u, votes = %u WHERE storyid = %u', $xoopsDB->prefix('news_stories'), $finalrating, $votesDB, $storyid); $xoopsDB->queryF($sql); } @@ -94,7 +84,7 @@ public static function updateRating($storyid): void * @author Hervé Thouzard (https://www.herve-thouzard.com) * @copyright (c) Hervé Thouzard */ - public static function getMyItemIds($permtype = 'news_view') + public static function getMyItemIds(string $permtype = 'news_view'): array { global $xoopsUser; static $tblperms = []; @@ -116,7 +106,7 @@ public static function getMyItemIds($permtype = 'news_view') /** * @param $document * - * @return mixed + * @return array|string|string[]|null */ public static function html2text($document) { @@ -129,7 +119,7 @@ public static function html2text($document) $search = [ "']*?>.*?'si", // Strip out javascript "''si", // Strip out img tags - "'<[\/\!]*?[^<>]*?>'si", // Strip out HTML tags + "'<[\/\!]*?[^<>]*?>'i", // Strip out HTML tags "'([\r\n])[\s]+'", // Strip out white space "'&(quot|#34);'i", // Replace HTML entities "'&(amp|#38);'i", @@ -176,7 +166,7 @@ static function ($matches) { * * @return bool need to say it ? */ - public static function isX23() + public static function isX23(): bool { $x23 = false; $xv = \str_replace('XOOPS ', '', \XOOPS_VERSION); @@ -190,17 +180,17 @@ public static function isX23() /** * Retrieve an editor according to the module's option "form_options" * - * @param $caption - * @param $name - * @param string $value - * @param string $width - * @param string $height - * @param string $supplemental - * @return bool|\XoopsFormDhtmlTextArea|\XoopsFormEditor|\XoopsFormFckeditor|\XoopsFormHtmlarea|\XoopsFormTextArea|\XoopsFormTinyeditorTextArea + * @param string $caption + * @param string $name + * @param string $value + * @param int $width + * @param int $height + * @param string $supplemental + * @return bool|\XoopsFormEditor|\XoopsFormTextArea * @author Hervé Thouzard (https://www.herve-thouzard.com) * @copyright (c) Hervé Thouzard */ - public static function getWysiwygForm($caption, $name, $value = '', $width = '100%', $height = '400px', $supplemental = '') + public static function getWysiwygForm(string $caption, string $name, string $value = '', int $width = 15, int $height = 60, string $supplemental = '') { $editor_option = \mb_strtolower(static::getModuleOption('form_options')); $editor = false; @@ -209,42 +199,30 @@ public static function getWysiwygForm($caption, $name, $value = '', $width = '10 $editor_configs['value'] = $value; $editor_configs['rows'] = 35; $editor_configs['cols'] = 60; - $editor_configs['width'] = '100%'; - $editor_configs['height'] = '350px'; + $editor_configs['width'] = (string)$width; + $editor_configs['height'] = (string)$height; $editor_configs['editor'] = $editor_option; if (static::isX23()) { - $editor = new XoopsFormEditor($caption, $name, $editor_configs); + $editor = new \XoopsFormEditor($caption, $name, $editor_configs); return $editor; } // Only for Xoops 2.0.x switch ($editor_option) { - case 'fckeditor': - if (\is_readable(XOOPS_ROOT_PATH . '/class/fckeditor/formfckeditor.php')) { - require_once XOOPS_ROOT_PATH . '/class/fckeditor/formfckeditor.php'; - $editor = new XoopsFormFckeditor($caption, $name, $value); - } - break; - case 'htmlarea': - if (\is_readable(XOOPS_ROOT_PATH . '/class/htmlarea/formhtmlarea.php')) { - require_once XOOPS_ROOT_PATH . '/class/htmlarea/formhtmlarea.php'; - $editor = new XoopsFormHtmlarea($caption, $name, $value); - } - break; case 'dhtmltextarea': case 'dhtml': - $editor = new XoopsFormDhtmlTextArea($caption, $name, $value, 10, 50, $supplemental); + $editor = new \XoopsFormDhtmlTextArea($caption, $name, $value, 10, 50, $supplemental); break; case 'textarea': - $editor = new XoopsFormTextArea($caption, $name, $value); + $editor = new \XoopsFormTextArea($caption, $name, $value); break; case 'tinyeditor': case 'tinymce': if (\is_readable(XOOPS_ROOT_PATH . '/class/xoopseditor/tinyeditor/formtinyeditortextarea.php')) { require_once XOOPS_ROOT_PATH . '/class/xoopseditor/tinyeditor/formtinyeditortextarea.php'; - $editor = new XoopsFormTinyeditorTextArea( + $editor = new \XoopsFormTinyeditorTextArea( [ 'caption' => $caption, 'name' => $name, @@ -255,78 +233,72 @@ public static function getWysiwygForm($caption, $name, $value = '', $width = '10 ); } break; - case 'koivi': - if (\is_readable(XOOPS_ROOT_PATH . '/class/wysiwyg/formwysiwygtextarea.php')) { - require_once XOOPS_ROOT_PATH . '/class/wysiwyg/formwysiwygtextarea.php'; - $editor = new XoopsFormWysiwygTextArea($caption, $name, $value, $width, $height, ''); - } - break; } return $editor; } - /** - * @param \Xmf\Module\Helper $helper - * @param array|null $options - * @return \XoopsFormDhtmlTextArea|\XoopsFormEditor - */ - public static function getEditor($helper = null, $options = null) - { - /** @var Helper $helper */ - if (null === $options) { - $options = []; - $options['name'] = 'Editor'; - $options['value'] = 'Editor'; - $options['rows'] = 10; - $options['cols'] = '100%'; - $options['width'] = '100%'; - $options['height'] = '400px'; - } - - if (null === $helper) { - $helper = Helper::getInstance(); - } - - $isAdmin = $helper->isUserAdmin(); - - if (\class_exists('XoopsFormEditor')) { - if ($isAdmin) { - $descEditor = new XoopsFormEditor(\ucfirst($options['name']), $helper->getConfig('editorAdmin'), $options, $nohtml = false, $onfailure = 'textarea'); - } else { - $descEditor = new XoopsFormEditor(\ucfirst($options['name']), $helper->getConfig('editorUser'), $options, $nohtml = false, $onfailure = 'textarea'); - } - } else { - $descEditor = new XoopsFormDhtmlTextArea(\ucfirst($options['name']), $options['name'], $options['value'], '100%', '100%'); - } - - // $form->addElement($descEditor); - - return $descEditor; - } +// /** +// * @param \Xmf\Module\Helper|null $helper +// * @param array|null $options +// * @return \XoopsFormDhtmlTextArea|\XoopsFormEditor +// */ +// public static function getEditor(?\Xmf\Module\Helper $helper = null, ?array $options = null) +// { +// /** @var Helper $helper */ +// if (null === $options) { +// $options = []; +// $options['name'] = 'Editor'; +// $options['value'] = 'Editor'; +// $options['rows'] = 10; +// $options['cols'] = '100%'; +// $options['width'] = '100%'; +// $options['height'] = '400px'; +// } +// +// if (null === $helper) { +// $helper = Helper::getInstance(); +// } +// +// $isAdmin = $helper->isUserAdmin(); +// +// if (\class_exists('XoopsFormEditor')) { +// if ($isAdmin) { +// $descEditor = new \XoopsFormEditor(\ucfirst((string) $options['name']), $helper->getConfig('editorAdmin'), $options, $nohtml = false, $onfailure = 'textarea'); +// } else { +// $descEditor = new \XoopsFormEditor(\ucfirst((string) $options['name']), $helper->getConfig('editorUser'), $options, $nohtml = false, $onfailure = 'textarea'); +// } +// } else { +// $descEditor = new \XoopsFormDhtmlTextArea(\ucfirst((string) $options['name']), $options['name'], $options['value']); +// } +// +// // $form->addElement($descEditor); +// +// return $descEditor; +// } /** * Internal function * - * @param $text - * @return mixed + * @param string $text + * @return array|string|string[] * @copyright (c) Hervé Thouzard * @author Hervé Thouzard (https://www.herve-thouzard.com) */ - public static function getDublinQuotes($text) + public static function getDublinQuotes(string $text) { return \str_replace('"', ' ', $text); } /** - * Creates all the meta datas : + * Creates all the metadatas : * - For Mozilla/Netscape and Opera the site navigation's bar * - The Dublin's Core Metadata * - The link for Firefox 2 micro summaries * - The meta keywords * - The meta description * - * @param null $story + * @param object|null $story * @author Hervé Thouzard (https://www.herve-thouzard.com) * @copyright (c) Hervé Thouzard */ @@ -334,7 +306,7 @@ public static function createMetaDatas($story = null): void { global $xoopsConfig, $xoTheme, $xoopsTpl; $content = ''; - $myts = MyTextSanitizer::getInstance(); + $myts = \MyTextSanitizer::getInstance(); // require_once XOOPS_ROOT_PATH . '/modules/news/class/class.newstopic.php'; /** @@ -353,7 +325,7 @@ public static function createMetaDatas($story = null): void // require_once XOOPS_ROOT_PATH . '/modules/news/class/class.newstopic.php'; $xt = new NewsTopic(); $allTopics = $xt->getAllTopics(static::getModuleOption('restrictindex')); - $topic_tree = new XoopsObjectTree($allTopics, 'topic_id', 'topic_pid'); + $topic_tree = new \XoopsObjectTree($allTopics, 'topic_id', 'topic_pid'); $topics_arr = $topic_tree->getAllChild(0); foreach ($topics_arr as $onetopic) { $content .= \sprintf("\n", $onetopic->topic_title(), XOOPS_URL . '/modules/news/index.php?storytopic=' . $onetopic->topic_id()); @@ -386,7 +358,7 @@ public static function createMetaDatas($story = null): void } /** - * Dublin Core's meta datas + * Dublin Core's metadatas */ if (static::getModuleOption('dublincore') && isset($story) && \is_object($story)) { /** @var XoopsConfigHandler $configHandler */ @@ -401,7 +373,7 @@ public static function createMetaDatas($story = null): void $content .= '\n"; $content .= '\n"; $content .= '\n"; - $content .= '\n"; + $content .= '\n"; $content .= '\n"; if (isset($xoopsConfigMetaFooter['meta_copyright'])) { $content .= '\n"; @@ -423,12 +395,12 @@ public static function createMetaDatas($story = null): void /** * Create the meta keywords based on the content * - * @param $content + * @param string $content * @return string * @copyright (c) Hervé Thouzard * @author Hervé Thouzard (https://www.herve-thouzard.com) */ - public static function createMetaKeywords($content) + public static function createMetaKeywords(string $content): string { global $cfg; require_once XOOPS_ROOT_PATH . '/modules/news/config.php'; @@ -459,7 +431,7 @@ public static function createMetaKeywords($content) $limit = $xoopsConfigSearch['keyword_min']; $_SESSION['news_keywords_limit'] = $limit; } - $myts = MyTextSanitizer::getInstance(); + $myts = \MyTextSanitizer::getInstance(); $content = \str_replace('
', ' ', $content); $content = $myts->undoHtmlSpecialChars($content); $content = \strip_tags($content); @@ -576,7 +548,7 @@ public static function updateCache(): void require_once XOOPS_ROOT_PATH . '/class/template.php'; $tplfileHandler = \xoops_getHandler('tplfile'); $tpllist = $tplfileHandler->find(null, null, null, $folder); - $xoopsTpl = new XoopsTpl(); + $xoopsTpl = new \XoopsTpl(); \xoops_template_clear_module_cache($xoopsModule->getVar('mid')); // Clear module's blocks cache // Remove cache for each page. @@ -597,15 +569,16 @@ public static function updateCache(): void /** * Verify that a mysql table exists * - * @param $tablename + * @param string $tablename * @return bool * @copyright (c) Hervé Thouzard * @author Hervé Thouzard (https://www.herve-thouzard.com) */ - public static function existTable($tablename) + public static function existTable(string $tablename): bool { global $xoopsDB; - $result = $xoopsDB->queryF("SHOW TABLES LIKE '$tablename'"); + $sql = "SHOW TABLES LIKE '$tablename'"; + $result = Utility::queryFAndCheck($xoopsDB, $sql); return ($xoopsDB->getRowsNum($result) > 0); } @@ -613,16 +586,17 @@ public static function existTable($tablename) /** * Verify that a field exists inside a mysql table * - * @param $fieldname - * @param $table + * @param string $fieldname + * @param string $table * @return bool * @author Hervé Thouzard (https://www.herve-thouzard.com) * @copyright (c) Hervé Thouzard */ - public static function existField($fieldname, $table) + public static function existField(string $fieldname, string $table): bool { global $xoopsDB; - $result = $xoopsDB->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'"); + $sql = "SHOW COLUMNS FROM $table LIKE '$fieldname'"; + $result = Utility::queryFAndCheck($xoopsDB, $sql); return ($xoopsDB->getRowsNum($result) > 0); } @@ -630,13 +604,13 @@ public static function existField($fieldname, $table) /** * Add a field to a mysql table * - * @param $field - * @param $table + * @param string $field + * @param string $table * @return bool|\mysqli_result * @author Hervé Thouzard (https://www.herve-thouzard.com) * @copyright (c) Hervé Thouzard */ - public static function addField($field, $table) + public static function addField(string $field, string $table) { global $xoopsDB; $result = $xoopsDB->queryF('ALTER TABLE ' . $table . " ADD $field;"); @@ -647,7 +621,7 @@ public static function addField($field, $table) /** * Verify that the current user is a member of the Admin group */ - public static function isAdminGroup() + public static function isAdminGroup(): bool { global $xoopsUser, $xoopsModule; if (\is_object($xoopsUser)) { @@ -700,16 +674,16 @@ public static function isBot() /** * Create an infotip * - * @param $text + * @param string $text * @return string|null * @copyright (c) Hervé Thouzard * @author Hervé Thouzard (https://www.herve-thouzard.com) */ - public static function makeInfotips($text) + public static function makeInfotips(string $text): ?string { $infotips = static::getModuleOption('infotips'); if ($infotips > 0) { - $myts = MyTextSanitizer::getInstance(); + $myts = \MyTextSanitizer::getInstance(); return \htmlspecialchars(\xoops_substr(\strip_tags($text), 0, $infotips), \ENT_QUOTES | \ENT_HTML5); } @@ -723,7 +697,7 @@ public static function makeInfotips($text) * @author Monte Ohrt , modified by Amos Robinson * */ - public static function closeTags($string) + public static function closeTags(string $string): string { // match opened tags if (\preg_match_all('/<([a-z\:\-]+)[^\/]>/', $string, $start_tags)) { @@ -765,22 +739,22 @@ public static function closeTags($string) * Makes sure no tags are left half-open or half-closed * (e.g. "Banana in a , modified by Amos Robinson * */ - public static function truncateTagSafe($string, $length = 80, $etc = '...', $break_words = false) + public static function truncateTagSafe(string $string, int $length = 80, string $etc = '...', bool $break_words = false): string { if (0 == $length) { return ''; } if (mb_strlen($string) > $length) { - $length -= mb_strlen($etc); + $length -= \mb_strlen($etc); if (!$break_words) { $string = \preg_replace('/\s+?(\S+)?$/', '', mb_substr($string, 0, $length + 1)); $string = \preg_replace('/<[^>]*$/', '', $string); @@ -806,13 +780,13 @@ public static function truncateTagSafe($string, $length = 80, $etc = '...', $bre * @return bool */ public static function resizePicture( - $src_path, - $dst_path, - $param_width, - $param_height, - $keep_original = false, - $fit = 'inside' - ) { + string $src_path, + string $dst_path, + int $param_width, + int $param_height, + bool $keep_original = false, + string $fit = 'inside' + ): bool { // require_once XOOPS_PATH . '/vendor/wideimage/WideImage.php'; $resize = true; $pictureDimensions = \getimagesize($src_path); diff --git a/class/XoopsStory.php b/class/XoopsStory.php index 9964bad..c1a9eaf 100644 --- a/class/XoopsStory.php +++ b/class/XoopsStory.php @@ -1,10 +1,8 @@ -db */ - $this->db = XoopsDatabaseFactory::getDatabaseConnection(); + $this->db = \XoopsDatabaseFactory::getDatabaseConnection(); $this->table = ''; $this->topicstable = ''; if (\is_array($storyid)) { @@ -157,7 +156,7 @@ public function setHostname($value): void /** * @param int $value */ - public function setNohtml($value = 0): void + public function setNohtml(int $value = 0): void { $this->nohtml = $value; } @@ -165,7 +164,7 @@ public function setNohtml($value = 0): void /** * @param int $value */ - public function setNosmiley($value = 0): void + public function setNosmiley(int $value = 0): void { $this->nosmiley = $value; } @@ -229,15 +228,15 @@ public function setComments($value): void /** * @param bool $approved * - * @return bool + * @return bool|int */ - public function store($approved = false) + public function store(bool $approved = false) { //$newpost = 0; - $myts = MyTextSanitizer::getInstance(); - $title = $myts->censorString($this->title); - $hometext = $myts->censorString($this->hometext); - $bodytext = $myts->censorString($this->bodytext); + $myts = \MyTextSanitizer::getInstance(); + $title = $myts->executeExtension('censor', $this->title); + $hometext = $myts->executeExtension('censor', $this->hometext); + $bodytext = $myts->executeExtension('censor', $this->bodytext); $title = $GLOBALS['xoopsDB']->escape($title); $hometext = $GLOBALS['xoopsDB']->escape($hometext); $bodytext = $GLOBALS['xoopsDB']->escape($bodytext); @@ -254,36 +253,7 @@ public function store($approved = false) $this->topicdisplay = 1; } $expired = !empty($this->expired) ? $this->expired : 0; - if (!isset($this->storyid)) { - //$newpost = 1; - $newstoryid = $this->db->genId($this->table . '_storyid_seq'); - $created = \time(); - $published = $this->approved ? $this->published : 0; - - $sql = \sprintf( - "INSERT INTO `%s` (storyid, uid, title, created, published, expired, hostname, nohtml, nosmiley, hometext, bodytext, counter, topicid, ihome, notifypub, story_type, topicdisplay, topicalign, comments) VALUES (%u, %u, '%s', %u, %u, %u, '%s', %u, %u, '%s', '%s', %u, %u, %u, %u, '%s', %u, '%s', %u)", - $this->table, - $newstoryid, - $this->uid, - $title, - $created, - $published, - $expired, - $this->hostname, - $this->nohtml, - $this->nosmiley, - $hometext, - $bodytext, - 0, - $this->topicid, - $this->ihome, - $this->notifypub, - $this->type, - $this->topicdisplay, - $this->topicalign, - $this->comments - ); - } else { + if (isset($this->storyid)) { if ($this->approved) { $sql = \sprintf( "UPDATE `%s` SET title = '%s', published = %u, expired = %u, nohtml = %u, nosmiley = %u, hometext = '%s', bodytext = '%s', topicid = %u, ihome = %u, topicdisplay = %u, topicalign = '%s', comments = %u WHERE storyid = %u", @@ -321,6 +291,35 @@ public function store($approved = false) ); } $newstoryid = $this->storyid; + } else { + //$newpost = 1; + $newstoryid = $this->db->genId($this->table . '_storyid_seq'); + $created = \time(); + $published = $this->approved ? $this->published : 0; + + $sql = \sprintf( + "INSERT INTO `%s` (storyid, uid, title, created, published, expired, hostname, nohtml, nosmiley, hometext, bodytext, counter, topicid, ihome, notifypub, story_type, topicdisplay, topicalign, comments) VALUES (%u, %u, '%s', %u, %u, %u, '%s', %u, %u, '%s', '%s', %u, %u, %u, %u, '%s', %u, '%s', %u)", + $this->table, + $newstoryid, + $this->uid, + $title, + $created, + $published, + $expired, + $this->hostname, + $this->nohtml, + $this->nosmiley, + $hometext, + $bodytext, + 0, + $this->topicid, + $this->ihome, + $this->notifypub, + $this->type, + $this->topicdisplay, + $this->topicalign, + $this->comments + ); } if (!$result = $this->db->query($sql)) { return false; @@ -345,19 +344,23 @@ public function getStory($storyid): void } /** - * @param $array + * @param array $array */ - public function makeStory($array): void + public function makeStory(array $array): void { foreach ($array as $key => $value) { $this->$key = $value; } + + if (!array_key_exists('type', $array)) { + $this->type = ''; // or some default value + } } /** * @return bool */ - public function delete() + public function delete(): bool { $sql = \sprintf('DELETE FROM `%s` WHERE storyid = %u', $this->table, $this->storyid); if (!$result = $this->db->query($sql)) { @@ -370,7 +373,7 @@ public function delete() /** * @return bool */ - public function updateCounter() + public function updateCounter(): bool { $sql = \sprintf('UPDATE `%s` SET counter = counter+1 WHERE storyid = %u', $this->table, $this->storyid); if (!$result = $this->db->queryF($sql)) { @@ -385,7 +388,7 @@ public function updateCounter() * * @return bool */ - public function updateComments($total) + public function updateComments($total): bool { $sql = \sprintf('UPDATE `%s` SET comments = %u WHERE storyid = %u', $this->table, $total, $this->storyid); if (!$result = $this->db->queryF($sql)) { @@ -403,7 +406,7 @@ public function topicid() /** * @return \XoopsModules\News\XoopsTopic */ - public function topic() + public function topic(): XoopsTopic { return new XoopsTopic($this->topicstable, $this->topicid); } @@ -416,19 +419,19 @@ public function uid() /** * @return string */ - public function uname() + public function uname(): string { - return XoopsUser::getUnameFromId($this->uid); + return \XoopsUser::getUnameFromId($this->uid); } /** * @param string $format * - * @return mixed + * @return string */ - public function title($format = 'Show') + public function title(string $format = 'Show'): string { - $myts = MyTextSanitizer::getInstance(); + $myts = \MyTextSanitizer::getInstance(); $smiley = 1; if ($this->nosmiley()) { $smiley = 0; @@ -452,9 +455,9 @@ public function title($format = 'Show') * * @return string */ - public function hometext($format = 'Show') + public function hometext(string $format = 'Show'): string { - $myts = MyTextSanitizer::getInstance(); + $myts = \MyTextSanitizer::getInstance(); $html = 1; $smiley = 1; $xcodes = 1; @@ -469,13 +472,13 @@ public function hometext($format = 'Show') $hometext = $myts->displayTarea($this->hometext, $html, $smiley, $xcodes); break; case 'Edit': - $hometext = \htmlspecialchars($this->hometext, \ENT_QUOTES); + $hometext = \htmlspecialchars($this->hometext, \ENT_QUOTES | ENT_HTML5); break; case 'Preview': $hometext = $myts->previewTarea($this->hometext, $html, $smiley, $xcodes); break; case 'InForm': - $hometext = \htmlspecialchars($this->hometext, \ENT_QUOTES); + $hometext = \htmlspecialchars($this->hometext, \ENT_QUOTES | ENT_HTML5); break; } @@ -487,9 +490,9 @@ public function hometext($format = 'Show') * * @return string */ - public function bodytext($format = 'Show') + public function bodytext(string $format = 'Show'): string { - $myts = MyTextSanitizer::getInstance(); + $myts = \MyTextSanitizer::getInstance(); $html = 1; $smiley = 1; $xcodes = 1; @@ -504,13 +507,13 @@ public function bodytext($format = 'Show') $bodytext = $myts->displayTarea($this->bodytext, $html, $smiley, $xcodes); break; case 'Edit': - $bodytext = \htmlspecialchars($this->bodytext, \ENT_QUOTES); + $bodytext = \htmlspecialchars($this->bodytext, \ENT_QUOTES | ENT_HTML5); break; case 'Preview': $bodytext = $myts->previewTarea($this->bodytext, $html, $smiley, $xcodes); break; case 'InForm': - $bodytext = \htmlspecialchars($this->bodytext, \ENT_QUOTES); + $bodytext = \htmlspecialchars($this->bodytext, \ENT_QUOTES | ENT_HTML5); break; } @@ -548,7 +551,7 @@ public function storyid() } /** - * @return int + * @return string|int */ public function nohtml() { @@ -556,7 +559,7 @@ public function nohtml() } /** - * @return int + * @return string|int */ public function nosmiley() { @@ -566,9 +569,9 @@ public function nosmiley() /** * @return int */ - public function notifypub() + public function notifypub(): int { - return $this->notifypub; + return (int)$this->notifypub; } public function type() @@ -579,9 +582,9 @@ public function type() /** * @return int */ - public function ihome() + public function ihome(): int { - return $this->ihome; + return (int)$this->ihome; } public function topicdisplay() @@ -594,7 +597,7 @@ public function topicdisplay() * * @return string */ - public function topicalign($astext = true) + public function topicalign(bool $astext = true): string { if ($astext) { if ('R' === $this->topicalign) { diff --git a/class/XoopsTopic.php b/class/XoopsTopic.php index a89918a..61d14aa 100644 --- a/class/XoopsTopic.php +++ b/class/XoopsTopic.php @@ -23,8 +23,9 @@ // require_once XOOPS_ROOT_PATH . '/modules/news/class/xoopstree.php'; -use MyTextSanitizer; -use XoopsDatabaseFactory; +use XoopsModules\News\{ + XoopsTree +}; use XoopsPerms; /** @@ -32,30 +33,29 @@ */ class XoopsTopic { - public $db; - public $table; - public $topic_id; - public $topic_pid; - public $topic_title; - public $topic_imgurl; - public $prefix; // only used in topic tree - public $use_permission = false; + public \XoopsDatabase $db; + public $menu; public $mid; // module id used for setting permission - - public $menu; - public $topic_color; + public $prefix; // only used in topic tree + public string $table; + public $topic_color; public $topic_description; public $topic_frontpage; + public $topic_id; + public $topic_imgurl; + public $topic_pid; public $topic_rssurl; + public $topic_title; + public bool $use_permission = false; /** - * @param $table - * @param int $topicid + * @param string $table + * @param array|int $topicid */ - public function __construct($table, $topicid = 0) + public function __construct(string $table, $topicid = 0) { /** @var \XoopsMySQLDatabase $db */ - $this->db = XoopsDatabaseFactory::getDatabaseConnection(); + $this->db = \XoopsDatabaseFactory::getDatabaseConnection(); $this->table = $table; if (\is_array($topicid)) { $this->makeTopic($topicid); @@ -97,7 +97,8 @@ public function getTopic($topicid): void { $topicid = (int)$topicid; $sql = 'SELECT * FROM ' . $this->table . ' WHERE topic_id=' . $topicid; - $array = $this->db->fetchArray($this->db->query($sql)); + $result = Utility::queryAndCheck($this->db, $sql); + $array = $this->db->fetchArray($result); $this->makeTopic($array); } @@ -123,9 +124,9 @@ public function usePermission($mid): void /** * @return bool */ - public function store() + public function store(): bool { - $myts = MyTextSanitizer::getInstance(); + $myts = \MyTextSanitizer::getInstance(); $title = ''; $imgurl = ''; if (isset($this->topic_title) && '' !== $this->topic_title) { @@ -144,7 +145,7 @@ public function store() $sql = \sprintf("UPDATE `%s` SET topic_pid = %u, topic_imgurl = '%s', topic_title = '%s' WHERE topic_id = %u", $this->table, $this->topic_pid, $imgurl, $title, $this->topic_id); } if (!$result = $this->db->query($sql)) { - \trigger_error("Query Failed! SQL: $sql- Error: " . $this->db->error(), E_USER_ERROR); + \trigger_error("Query Failed! SQL: $sql- Error: " . $this->db->error(), \E_USER_ERROR); } if ($this->use_permission) { if (empty($this->topic_id)) { @@ -174,7 +175,7 @@ public function store() } } if (!empty($this->s_groups) && \is_array($this->s_groups)) { - foreach ($this->s_groups as $s_g) { + foreach ($s_groups as $s_g) { $submit_topics = XoopsPerms::getPermitted($this->mid, 'SubmitInTopic', $s_g); $add = true; foreach ($parent_topics as $p_topic) { @@ -194,7 +195,7 @@ public function store() } } if (!empty($this->r_groups) && \is_array($this->r_groups)) { - foreach ($this->r_groups as $r_g) { + foreach ($r_groups as $r_g) { $read_topics = XoopsPerms::getPermitted($this->mid, 'ReadInTopic', $r_g); $add = true; foreach ($parent_topics as $p_topic) { @@ -240,11 +241,11 @@ public function topic_pid() /** * @param string $format * - * @return mixed + * @return string */ - public function topic_title($format = 'S') + public function topic_title(string $format = 'S'): string { - $myts = MyTextSanitizer::getInstance(); + $myts = \MyTextSanitizer::getInstance(); switch ($format) { case 'S': case 'E': @@ -262,11 +263,11 @@ public function topic_title($format = 'S') /** * @param string $format * - * @return mixed + * @return string */ - public function topic_imgurl($format = 'S') + public function topic_imgurl(string $format = 'S'): string { - $myts = MyTextSanitizer::getInstance(); + $myts = \MyTextSanitizer::getInstance(); switch ($format) { case 'S': case 'E': @@ -292,7 +293,7 @@ public function prefix() /** * @return array */ - public function getFirstChildTopics() + public function getFirstChildTopics(): array { $ret = []; $xt = new \XoopsTree($this->table, 'topic_id', 'topic_pid'); @@ -309,7 +310,7 @@ public function getFirstChildTopics() /** * @return array */ - public function getAllChildTopics() + public function getAllChildTopics(): array { $ret = []; $xt = new \XoopsTree($this->table, 'topic_id', 'topic_pid'); @@ -326,7 +327,7 @@ public function getAllChildTopics() /** * @return array */ - public function getChildTopicsTreeArray() + public function getChildTopicsTreeArray(): array { $ret = []; $xt = new \XoopsTree($this->table, 'topic_id', 'topic_pid'); @@ -342,11 +343,11 @@ public function getChildTopicsTreeArray() /** * @param int $none - * @param $seltopic + * @param int $seltopic * @param string $selname * @param string $onchange */ - public function makeTopicSelBox($none = 0, $seltopic = -1, $selname = '', $onchange = ''): void + public function makeTopicSelBox(int $none = 0, int $seltopic = -1, string $selname = '', string $onchange = ''): void { $xt = new XoopsTree($this->table, 'topic_id', 'topic_pid'); if (-1 != $seltopic) { @@ -363,9 +364,9 @@ public function makeTopicSelBox($none = 0, $seltopic = -1, $selname = '', $oncha /** * @param $funcURL * - * @return mixed + * @return string */ - public function getNiceTopicPathFromId($funcURL) + public function getNiceTopicPathFromId($funcURL): string { $xt = new XoopsTree($this->table, 'topic_id', 'topic_pid'); $ret = $xt->getNicePathFromId($this->topic_id, 'topic_title', $funcURL); @@ -374,9 +375,9 @@ public function getNiceTopicPathFromId($funcURL) } /** - * @return mixed + * @return array */ - public function getAllChildTopicsId() + public function getAllChildTopicsId(): array { $xt = new XoopsTree($this->table, 'topic_id', 'topic_pid'); $ret = $xt->getAllChildId($this->topic_id, 'topic_title'); @@ -387,12 +388,12 @@ public function getAllChildTopicsId() /** * @return array */ - public function getTopicsList() + public function getTopicsList(): array { $ret = []; - $result = $this->db->query('SELECT topic_id, topic_pid, topic_title FROM ' . $this->table); + $result = Utility::queryAndCheck($this->db, 'SELECT topic_id, topic_pid, topic_title FROM ' . $this->table); if ($result) { - $myts = MyTextSanitizer::getInstance(); + $myts = \MyTextSanitizer::getInstance(); while (false !== ($myrow = $this->db->fetchArray($result))) { $ret[$myrow['topic_id']] = [ 'title' => \htmlspecialchars($myrow['topic_title'], \ENT_QUOTES | \ENT_HTML5), @@ -410,11 +411,11 @@ public function getTopicsList() * * @return bool */ - public function topicExists($pid, $title) + public function topicExists($pid, $title): bool { $sql = 'SELECT COUNT(*) FROM ' . $this->table . ' WHERE topic_pid = ' . (int)$pid . " AND topic_title = '" . \trim($title) . "'"; - $rs = $this->db->query($sql); - [$count] = $this->db->fetchRow($rs); + $result = Utility::queryAndCheck($this->db, $sql); + [$count] = $this->db->fetchRow($result); if ($count > 0) { return true; } diff --git a/class/XoopsTree.php b/class/XoopsTree.php index 2e10957..df3f055 100644 --- a/class/XoopsTree.php +++ b/class/XoopsTree.php @@ -27,12 +27,12 @@ */ class XoopsTree { - public $table; //table with parent-child structure - public $id; //name of unique id for records in table $table - public $pid; // name of parent id used in table $table - public $order; //specifies the order of query results - public $title; // name of a field in table $table which will be used when selection box and paths are generated - public $db; + public $table; //table with parent-child structure + public $id; //name of unique id for records in table $table + public $pid; // name of parent id used in table $table + public $order; //specifies the order of query results + public $title; // name of a field in table $table which will be used when selection box and paths are generated + public \XoopsDatabase $db; //constructor of class XoopsTree //sets the names of table, unique id, and parend id @@ -43,8 +43,8 @@ class XoopsTree */ public function __construct($table_name, $id_name, $pid_name) { - $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1); - $GLOBALS['xoopsLogger']->addDeprecated("Class '" . __CLASS__ . "' is deprecated, check 'XoopsObjectTree' in tree.php" . ". Called from {$trace[0]['file']}line {$trace[0]['line']}"); +// $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1); +// $GLOBALS['xoopsLogger']->addDeprecated("Class '" . __CLASS__ . "' is deprecated, check 'XoopsObjectTree' in tree.php" . ". Called from {$trace[0]['file']} line {$trace[0]['line']}"); /** @var \XoopsMySQLDatabase $db */ $this->db = \XoopsDatabaseFactory::getDatabaseConnection(); $this->table = $table_name; @@ -60,7 +60,7 @@ public function __construct($table_name, $id_name, $pid_name) * * @return array */ - public function getFirstChild($sel_id, $order = '') + public function getFirstChild($sel_id, string $order = ''): array { $sel_id = (int)$sel_id; $arr = []; @@ -68,7 +68,7 @@ public function getFirstChild($sel_id, $order = '') if ('' !== $order) { $sql .= " ORDER BY $order"; } - $result = $this->db->query($sql); + $result = Utility::queryAndCheck($this->db, $sql); if ($this->db->isResultSet($result)) { while (false !== ($myrow = $this->db->fetchArray($result))) { $arr[] = $myrow; @@ -85,11 +85,12 @@ public function getFirstChild($sel_id, $order = '') * * @return array */ - public function getFirstChildId($sel_id) + public function getFirstChildId($sel_id): array { $sel_id = (int)$sel_id; $idarray = []; - $result = $this->db->query('SELECT ' . $this->id . ' FROM ' . $this->table . ' WHERE ' . $this->pid . '=' . $sel_id); + $sql = 'SELECT ' . $this->id . ' FROM ' . $this->table . ' WHERE ' . $this->pid . '=' . $sel_id; + $result = Utility::queryAndCheck($this->db, $sql); $count = $this->db->getRowsNum($result); if (0 == $count) { return $idarray; @@ -110,14 +111,14 @@ public function getFirstChildId($sel_id) * * @return array */ - public function getAllChildId($sel_id, $order = '', $idarray = []) + public function getAllChildId($sel_id, string $order = '', array $idarray = []): array { $sel_id = (int)$sel_id; $sql = 'SELECT ' . $this->id . ' FROM ' . $this->table . ' WHERE ' . $this->pid . '=' . $sel_id; if ('' !== $order) { $sql .= " ORDER BY $order"; } - $result = $this->db->query($sql); + $result = Utility::queryAndCheck($this->db, $sql); $count = $this->db->getRowsNum($result); if (0 == $count) { return $idarray; @@ -139,14 +140,14 @@ public function getAllChildId($sel_id, $order = '', $idarray = []) * * @return array */ - public function getAllParentId($sel_id, $order = '', $idarray = []) + public function getAllParentId($sel_id, string $order = '', array $idarray = []): array { $sel_id = (int)$sel_id; $sql = 'SELECT ' . $this->pid . ' FROM ' . $this->table . ' WHERE ' . $this->id . '=' . $sel_id; if ('' !== $order) { $sql .= " ORDER BY $order"; } - $result = $this->db->query($sql); + $result = Utility::queryAndCheck($this->db, $sql); [$r_id] = $this->db->fetchRow($result); if (0 == $r_id) { return $idarray; @@ -161,16 +162,17 @@ public function getAllParentId($sel_id, $order = '', $idarray = []) // the path is delimetered with "/" /** - * @param $sel_id - * @param $title - * @param string $path + * @param string|int $sel_id + * @param string $title + * @param string $path * * @return string */ - public function getPathFromId($sel_id, $title, $path = '') + public function getPathFromId($sel_id, string $title, string $path = ''): string { $sel_id = (int)$sel_id; - $result = $this->db->query('SELECT ' . $this->pid . ', ' . $title . ' FROM ' . $this->table . ' WHERE ' . $this->id . "=$sel_id"); + $sql = 'SELECT ' . $this->pid . ', ' . $title . ' FROM ' . $this->table . ' WHERE ' . $this->id . "=$sel_id"; + $result = Utility::queryAndCheck($this->db, $sql); if (0 == $this->db->getRowsNum($result)) { return $path; } @@ -198,7 +200,7 @@ public function getPathFromId($sel_id, $title, $path = '') * @param string $sel_name * @param string $onchange */ - public function makeMySelBox($title, $order = '', $preset_id = 0, $none = 0, $sel_name = '', $onchange = ''): void + public function makeMySelBox($title, string $order = '', int $preset_id = 0, int $none = 0, string $sel_name = '', string $onchange = ''): void { if ('' == $sel_name) { $sel_name = $this->id; @@ -213,7 +215,7 @@ public function makeMySelBox($title, $order = '', $preset_id = 0, $none = 0, $se if ('' !== $order) { $sql .= " ORDER BY $order"; } - $result = $this->db->query($sql); + $result = Utility::queryAndCheck($this->db, $sql); if ($none) { echo "\n"; } @@ -241,19 +243,19 @@ public function makeMySelBox($title, $order = '', $preset_id = 0, $none = 0, $se //generates nicely formatted linked path from the root id to a given id /** - * @param $sel_id - * @param $title - * @param $funcURL - * @param string $path + * @param string|int $sel_id + * @param string $title + * @param string $funcURL + * @param string $path * * @return string */ - public function getNicePathFromId($sel_id, $title, $funcURL, $path = '') + public function getNicePathFromId($sel_id, string $title, string $funcURL, string $path = ''): string { $path = !empty($path) ? ' : ' . $path : $path; $sel_id = (int)$sel_id; $sql = 'SELECT ' . $this->pid . ', ' . $title . ' FROM ' . $this->table . ' WHERE ' . $this->id . "=$sel_id"; - $result = $this->db->query($sql); + $result = Utility::queryAndCheck($this->db, $sql); if (0 == $this->db->getRowsNum($result)) { return $path; } @@ -278,10 +280,11 @@ public function getNicePathFromId($sel_id, $title, $funcURL, $path = '') * * @return string */ - public function getIdPathFromId($sel_id, $path = '') + public function getIdPathFromId($sel_id, string $path = ''): string { $sel_id = (int)$sel_id; - $result = $this->db->query('SELECT ' . $this->pid . ' FROM ' . $this->table . ' WHERE ' . $this->id . "=$sel_id"); + $sql = 'SELECT ' . $this->pid . ' FROM ' . $this->table . ' WHERE ' . $this->id . "=$sel_id"; + $result = Utility::queryAndCheck($this->db, $sql); if (0 == $this->db->getRowsNum($result)) { return $path; } @@ -311,8 +314,8 @@ public function getAllChild($sel_id = 0, $order = '', $parray = []) if ('' !== $order) { $sql .= " ORDER BY $order"; } - $result = $this->db->query($sql); - $count = $this->db->getRowsNum($result); + $result = Utility::queryAndCheck($this->db, $sql); + $count = $this->db->getRowsNum($result); if (0 == $count) { return $parray; } @@ -341,8 +344,8 @@ public function getChildTreeArray($sel_id = 0, $order = '', $parray = [], $r_pre if ('' !== $order) { $sql .= " ORDER BY $order"; } - $result = $this->db->query($sql); - $count = $this->db->getRowsNum($result); + $result = Utility::queryAndCheck($this->db, $sql); + $count = $this->db->getRowsNum($result); if (0 == $count) { return $parray; } diff --git a/class/plugins/plugin.tag.php b/class/plugins/plugin.tag.php index ac8411d..ab4c019 100644 --- a/class/plugins/plugin.tag.php +++ b/class/plugins/plugin.tag.php @@ -31,7 +31,7 @@ * @param $items * @return bool|null */ -function news_tag_iteminfo(&$items) +function news_tag_iteminfo(&$items): ?bool { if (empty($items) || !\is_array($items)) { return false; @@ -79,7 +79,7 @@ function news_tag_synchronization($mid): void $where = "($itemHandler_table.published > 0 AND $itemHandler_table.published <= " . \time() . ") AND ($itemHandler_table.expired = 0 OR $itemHandler_table.expired > " . \time() . ')'; /* clear tag-item links */ - if (version_compare($xoopsDB->getServerVersion(), '4.1.0', 'ge')) : + if ($module->versionCompare($xoopsDB->getServerVersion(), '4.1.0', 'ge')) : $sql = " DELETE FROM {$linkHandler->table}" . ' WHERE ' . " tag_modid = {$mid}" diff --git a/comment_new.php b/comment_new.php index 5830504..bf1a2a8 100644 --- a/comment_new.php +++ b/comment_new.php @@ -16,18 +16,21 @@ */ use Xmf\Request; -use XoopsModules\News; -use XoopsModules\News\NewsStory; +use XoopsModules\News\{ + Helper, + NewsStory, + Utility +}; require_once \dirname(__DIR__, 2) . '/mainfile.php'; -/** @var News\Helper $helper */ -$helper = News\Helper::getInstance(); +/** @var Helper $helper */ +$helper = Helper::getInstance(); // require_once XOOPS_ROOT_PATH . '/modules/news/class/class.newsstory.php'; // We verify that the user can post comments ********************************** -if (null === $helper->getModule()) { +if (!is_object($helper->getModule())) { exit(); } @@ -44,7 +47,7 @@ if ($com_itemid > 0) { $article = new NewsStory($com_itemid); if ($article->storyid > 0) { - $com_replytext = _POSTEDBY . ' ' . $article->uname() . ' ' . _DATE . ' ' . formatTimestamp($article->published(), News\Utility::getModuleOption('dateformat')) . '

' . $article->hometext(); + $com_replytext = _POSTEDBY . ' ' . $article->uname() . ' ' . _DATE . ' ' . formatTimestamp($article->published(), Utility::getModuleOption('dateformat')) . '

' . $article->hometext(); $bodytext = $article->bodytext(); if ('' !== $bodytext) { $com_replytext .= '

' . $bodytext; diff --git a/comment_post.php b/comment_post.php index ef346b2..5f3f239 100644 --- a/comment_post.php +++ b/comment_post.php @@ -15,15 +15,17 @@ * @author XOOPS Development Team */ -use XoopsModules\News; +use XoopsModules\News\{ + Helper +}; require_once \dirname(__DIR__, 2) . '/mainfile.php'; -/** @var News\Helper $helper */ -$helper = News\Helper::getInstance(); +/** @var Helper $helper */ +$helper = Helper::getInstance(); // We verify that the user can post comments ********************************** -if (null === $helper->getModule()) { +if (!is_object($helper->getModule())) { exit(); } diff --git a/config.php b/config.php index 2253f82..e9c7977 100644 --- a/config.php +++ b/config.php @@ -23,8 +23,9 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // ------------------------------------------------------------------------ // -use XoopsModules\News; -use XoopsModules\News\Helper; +use XoopsModules\News\{ + Helper +}; /** @var \XoopsModules\News\Helper $helper */ $helper = Helper::getInstance(); diff --git a/config/config.php b/config/config.php index 330a69e..2f09702 100644 --- a/config/config.php +++ b/config/config.php @@ -32,14 +32,14 @@ ], 'uploadFolders' => [ XOOPS_UPLOAD_PATH . '/' . $moduleDirName, - XOOPS_UPLOAD_PATH . '/' . $moduleDirName . '/category', - XOOPS_UPLOAD_PATH . '/' . $moduleDirName . '/screenshots', + XOOPS_UPLOAD_PATH . '/' . $moduleDirName . '/file', + XOOPS_UPLOAD_PATH . '/' . $moduleDirName . '/image', //XOOPS_UPLOAD_PATH . '/flags' ], 'copyBlankFiles' => [ XOOPS_UPLOAD_PATH . '/' . $moduleDirName, - XOOPS_UPLOAD_PATH . '/' . $moduleDirName . '/category', - XOOPS_UPLOAD_PATH . '/' . $moduleDirName . '/screenshots', + XOOPS_UPLOAD_PATH . '/' . $moduleDirName . '/file', + XOOPS_UPLOAD_PATH . '/' . $moduleDirName . '/image', //XOOPS_UPLOAD_PATH . '/flags' ], diff --git a/docs/changelog.txt b/docs/changelog.txt index 74c975e..f5ef8fd 100644 --- a/docs/changelog.txt +++ b/docs/changelog.txt @@ -1,4 +1,19 @@ -
1.72.0 Beta 6 [2022-10-24]
Dev: XOOPS 2.5.11-Beta2, PHP 7.4.28, PHP 8.1.11, PHP 8.2 RC4 +
1.73.0 Beta 3 [2025-01-16]
Dev: XOOPS 2.5.12, PHP 7.4.33, PHP 8.2.5, PHP 8.4 +
+- PHP 8.4 and Smarty 4 updates (mamba) +- Smarty 4 updates (koreus) + +
1.73.0 Beta 2 [2024-09-02]
Dev: XOOPS 2.5.11, PHP 7.4.33, PHP 8.2.5 +
+- PHP 8 and Smarty 4 updates (mamba) +- various code cosmetics (mamba) + +
1.73.0 Beta 1 [2023-04-20]
Dev: XOOPS 2.5.11, PHP 7.4.33, PHP 8.2.5 +
+- PHP 8 and Smarty 3 updates (mamba) +- various code cosmetics (mamba) + +
1.72.0 Beta 6 [2022-04-27]
Dev: XOOPS 2.5.11, PHP 7.4.28, PHP 8.1.5
- add namespace XoopsTree (Andrew-Staves) - remove Count() in news_top.php block (Andrew-Staves) @@ -294,10 +309,10 @@ tables. This will optimize, check and analyze the tables in the database. - I have added a new option to activate Dublin Core Metadata in the article's page. For more explanations, see http://dublincore.org/ - Dublin Core Metadata are, as the name state, a set of meta datas used to + Dublin Core Metadata are, as the name state, a set of metadatas used to describe your documents. If you are a Firefox user, you can use this extension to visualize the Dublin - Meta Datas : + Metadata : https://addons.mozilla.org/firefox/528/ - You can display a "Bookmark this article at these sites" on the article's page To see an example, look at the bottom of this article : @@ -305,7 +320,7 @@ - You can use Firefox 2 Micro summaries : http://wiki.mozilla.org/Microsummaries If someone bookmarks your page with Firefox 2 they can choose to see the last title of your last news instead of the current page's title. - The News module modifies the meta datas of all its page to include a line + The News module modifies the metadatas of all its page to include a line like this one : but you can also add it in your theme so that when someone bookmark your site diff --git a/header.php b/header.php index 2bde8fe..3fb0bcd 100644 --- a/header.php +++ b/header.php @@ -14,4 +14,30 @@ * @license {@link https://www.gnu.org/licenses/gpl-2.0.html GNU GPL 2 or later} * @author XOOPS Development Team */ + +use XoopsModules\News\{ + Helper +}; + require_once \dirname(__DIR__, 2) . '/mainfile.php'; +require XOOPS_ROOT_PATH . '/header.php'; + +require __DIR__ . '/preloads/autoloader.php'; + +$moduleDirName = basename(__DIR__); + +$helper = Helper::getInstance(); +// Load language files +$helper->loadLanguage('main'); + +$myts = \MyTextSanitizer::getInstance(); + +if (!isset($GLOBALS['xoTheme']) || !is_object($GLOBALS['xoTheme'])) { + require $GLOBALS['xoops']->path('class/theme.php'); + $GLOBALS['xoTheme'] = new \xos_opal_Theme(); +} + +if (!isset($GLOBALS['xoopsTpl']) || !($GLOBALS['xoopsTpl'] instanceof XoopsTpl)) { + require $GLOBALS['xoops']->path('class/template.php'); + $xoopsTpl = new XoopsTpl(); +} diff --git a/include/comment_functions.php b/include/comment_functions.php index 0e83e26..ea7c16f 100644 --- a/include/comment_functions.php +++ b/include/comment_functions.php @@ -20,7 +20,9 @@ // comment callback functions // require_once XOOPS_ROOT_PATH . '/modules/news/class/class.newsstory.php'; -use XoopsModules\News\NewsStory; +use XoopsModules\News\{ + NewsStory +}; /** * @param $story_id @@ -28,7 +30,7 @@ * * @return bool */ -function news_com_update($story_id, $total_num) +function news_com_update($story_id, $total_num): bool { $story_id = (int)$story_id; $total_num = (int)$total_num; diff --git a/include/common.php b/include/common.php index 38afdfe..64f5a58 100644 --- a/include/common.php +++ b/include/common.php @@ -15,8 +15,10 @@ * @author XOOPS Development Team */ -use XoopsModules\News; -use XoopsModules\News\Utility; +use XoopsModules\News\{ + Helper, + Utility +}; require_once \dirname(__DIR__) . '/preloads/autoloader.php'; @@ -24,10 +26,10 @@ $moduleDirNameUpper = \mb_strtoupper($moduleDirName); /** @var \XoopsDatabase $db */ -/** @var News\Helper $helper */ -/** @var News\Utility $utility */ +/** @var Helper $helper */ +/** @var Utility $utility */ $db = \XoopsDatabaseFactory::getDatabaseConnection(); -$helper = News\Helper::getInstance(); +$helper = Helper::getInstance(); $utility = new Utility(); //$configurator = new \XoopsModules\News\Common\Configurator(); @@ -38,14 +40,14 @@ //$downloadHandler = new \XoopsModules\News\DownloadHandler($db); if (!defined($moduleDirNameUpper . '_CONSTANTS_DEFINED')) { - define($moduleDirNameUpper . '_DIRNAME', basename(dirname(__DIR__))); + define($moduleDirNameUpper . '_' . 'DIRNAME', basename(dirname(__DIR__))); define($moduleDirNameUpper . '_ROOT_PATH', XOOPS_ROOT_PATH . '/modules/' . $moduleDirName . '/'); define($moduleDirNameUpper . '_URL', XOOPS_URL . '/modules/' . $moduleDirName . '/'); define($moduleDirNameUpper . '_IMAGE_URL', constant($moduleDirNameUpper . '_URL') . '/assets/images/'); define($moduleDirNameUpper . '_IMAGE_PATH', constant($moduleDirNameUpper . '_ROOT_PATH') . '/assets/images'); define($moduleDirNameUpper . '_ADMIN_URL', constant($moduleDirNameUpper . '_URL') . '/admin/'); define($moduleDirNameUpper . '_ADMIN_PATH', constant($moduleDirNameUpper . '_ROOT_PATH') . '/admin/'); - define($moduleDirNameUpper . '_PATH', XOOPS_ROOT_PATH . '/modules/' . constant($moduleDirNameUpper . '_DIRNAME')); + define($moduleDirNameUpper . '_PATH', XOOPS_ROOT_PATH . '/modules/' . constant($moduleDirNameUpper . '_' . 'DIRNAME')); define($moduleDirNameUpper . '_ADMIN', constant($moduleDirNameUpper . '_URL') . '/admin/index.php'); define($moduleDirNameUpper . '_AUTHOR_LOGOIMG', constant($moduleDirNameUpper . '_URL') . '/assets/images/logoModule.png'); define($moduleDirNameUpper . '_UPLOAD_URL', XOOPS_UPLOAD_URL . '/' . $moduleDirName); // WITHOUT Trailing slash @@ -93,7 +95,7 @@ xoops_loadLanguage('admin', $moduleDirName); xoops_loadLanguage('main', $moduleDirName); if (class_exists('D3LanguageManager')) { - require_once XOOPS_TRUST_PATH . "/libs/altsys/class/D3LanguageManager.class.php"; + require_once XOOPS_TRUST_PATH . '/libs/altsys/class/D3LanguageManager.class.php'; $langman = D3LanguageManager::getInstance(); $langman->read('admin.php', $moduleDirName); $langman->read('main.php', $moduleDirName); diff --git a/include/functions.php b/include/functions.php index 760d950..8feaf19 100644 --- a/include/functions.php +++ b/include/functions.php @@ -30,17 +30,19 @@ use WideImage\WideImage; use Xmf\Request; -use XoopsModules\News; -use XoopsModules\News\Blacklist; -use XoopsModules\News\NewsTopic; -use XoopsModules\News\Registryfile; +use XoopsModules\News\{ + Blacklist, + NewsTopic, + Registryfile, + Utility +}; /** - * @param $option - * @param string $repmodule + * @param string $option + * @param string $repmodule * @return bool|mixed */ -function news_getmoduleoption($option, $repmodule = 'news') +function news_getmoduleoption(string $option, string $repmodule = 'news') { global $xoopsModuleConfig, $xoopsModule; static $tbloptions = []; @@ -83,15 +85,15 @@ function news_getmoduleoption($option, $repmodule = 'news') function news_updaterating($storyid): void { global $xoopsDB; - $query = 'SELECT rating FROM ' . $xoopsDB->prefix('news_stories_votedata') . ' WHERE storyid = ' . $storyid; - $voteresult = $xoopsDB->query($query); - $votesDB = $xoopsDB->getRowsNum($voteresult); + $sql = 'SELECT rating FROM ' . $xoopsDB->prefix('news_stories_votedata') . ' WHERE storyid = ' . $storyid; + $result = Utility::queryAndCheck($xoopsDB, $sql); + $votesDB = $xoopsDB->getRowsNum($result); $totalrating = 0; - while ([$rating] = $xoopsDB->fetchRow($voteresult)) { + while ([$rating] = $xoopsDB->fetchRow($result)) { $totalrating += $rating; } $finalrating = $totalrating / $votesDB; - $finalrating = number_format($finalrating, 4); + $finalrating =number_format((float)$finalrating, 4); $sql = sprintf('UPDATE `%s` SET rating = %u, votes = %u WHERE storyid = %u', $xoopsDB->prefix('news_stories'), $finalrating, $votesDB, $storyid); $xoopsDB->queryF($sql); } @@ -108,7 +110,7 @@ function news_updaterating($storyid): void * @author Hervé Thouzard (https://www.herve-thouzard.com) * @copyright (c) Hervé Thouzard */ -function news_MygetItemIds($permtype = 'news_view') +function news_MygetItemIds(string $permtype = 'news_view'): array { global $xoopsUser; static $tblperms = []; @@ -131,7 +133,7 @@ function news_MygetItemIds($permtype = 'news_view') /** * @param $document * - * @return mixed + * @return array|string|string[]|null */ function news_html2text($document) { @@ -144,7 +146,7 @@ function news_html2text($document) $search = [ "']*?>.*?'si", // Strip out javascript "''si", // Strip out img tags - "'<[\/\!]*?[^<>]*?>'si", // Strip out HTML tags + "'<[\/\!]*?[^<>]*?>'i", // Strip out HTML tags "'([\r\n])[\s]+'", // Strip out white space "'&(quot|#34);'i", // Replace HTML entities "'&(amp|#38);'i", @@ -191,7 +193,7 @@ static function ($matches) { * * @return bool need to say it ? */ -function news_isX23() +function news_isX23(): bool { $x23 = false; $xv = str_replace('XOOPS ', '', XOOPS_VERSION); @@ -205,17 +207,17 @@ function news_isX23() /** * Retrieve an editor according to the module's option "form_options" * - * @param $caption - * @param $name - * @param string $value - * @param string $width - * @param string $height - * @param string $supplemental - * @return bool|XoopsFormDhtmlTextArea|XoopsFormEditor|\XoopsFormFckeditor|\XoopsFormHtmlarea|\XoopsFormTextArea|\XoopsFormTinyeditorTextArea + * @param string $caption + * @param string $name + * @param string $value + * @param string $width + * @param string $height + * @param string $supplemental + * @return bool|XoopsFormEditor|\XoopsFormTextArea * @author Hervé Thouzard (https://www.herve-thouzard.com) * @copyright (c) Hervé Thouzard */ -function news_getWysiwygForm($caption, $name, $value = '', $width = '100%', $height = '400px', $supplemental = '') +function news_getWysiwygForm(string $caption, string $name, string $value = '', string $width = '100%', string $height = '400px', string $supplemental = '') { $editor_option = \mb_strtolower(news_getmoduleoption('form_options')); $editor = false; @@ -236,18 +238,6 @@ function news_getWysiwygForm($caption, $name, $value = '', $width = '100%', $hei // Only for Xoops 2.0.x switch ($editor_option) { - case 'fckeditor': - if (is_readable(XOOPS_ROOT_PATH . '/class/fckeditor/formfckeditor.php')) { - require_once XOOPS_ROOT_PATH . '/class/fckeditor/formfckeditor.php'; - $editor = new \XoopsFormFckeditor($caption, $name, $value); - } - break; - case 'htmlarea': - if (is_readable(XOOPS_ROOT_PATH . '/class/htmlarea/formhtmlarea.php')) { - require_once XOOPS_ROOT_PATH . '/class/htmlarea/formhtmlarea.php'; - $editor = new \XoopsFormHtmlarea($caption, $name, $value); - } - break; case 'dhtmltextarea': case 'dhtml': $editor = new \XoopsFormDhtmlTextArea($caption, $name, $value, 10, 50, $supplemental); @@ -270,12 +260,6 @@ function news_getWysiwygForm($caption, $name, $value = '', $width = '100%', $hei ); } break; - case 'koivi': - if (is_readable(XOOPS_ROOT_PATH . '/class/wysiwyg/formwysiwygtextarea.php')) { - require_once XOOPS_ROOT_PATH . '/class/wysiwyg/formwysiwygtextarea.php'; - $editor = new \XoopsFormWysiwygTextArea($caption, $name, $value, $width, $height, ''); - } - break; } return $editor; @@ -285,7 +269,7 @@ function news_getWysiwygForm($caption, $name, $value = '', $width = '100%', $hei * Internal function * * @param $text - * @return mixed + * @return array|string|string[] * @copyright (c) Hervé Thouzard * @author Hervé Thouzard (https://www.herve-thouzard.com) */ @@ -295,7 +279,7 @@ function DublinQuotes($text) } /** - * Creates all the meta datas : + * Creates all the metadatas : * - For Mozilla/Netscape and Opera the site navigation's bar * - The Dublin's Core Metadata * - The link for Firefox 2 micro summaries @@ -362,17 +346,17 @@ function news_CreateMetaDatas($story = null): void } /** - * Dublin Core's meta datas + * Dublin Core's metadatas */ if (news_getmoduleoption('dublincore') && isset($story) && is_object($story)) { /** @var \XoopsConfigHandler $configHandler */ $configHandler = xoops_getHandler('config'); $xoopsConfigMetaFooter = $configHandler->getConfigsByCat(XOOPS_CONF_METAFOOTER); - $content .= '\n"; - $content .= '\n"; - $content .= '\n"; - $content .= '\n"; - $content .= '\n"; + $content .= '\n"; + $content .= '\n"; + $content .= '\n"; + $content .= '\n"; + $content .= '\n"; $content .= '\n"; $content .= '\n"; $content .= '\n"; @@ -380,7 +364,7 @@ function news_CreateMetaDatas($story = null): void $content .= '\n"; $content .= '\n"; if (isset($xoopsConfigMetaFooter['meta_copyright'])) { - $content .= '\n"; + $content .= '\n"; } } @@ -404,7 +388,7 @@ function news_CreateMetaDatas($story = null): void * @copyright (c) Hervé Thouzard * @author Hervé Thouzard (https://www.herve-thouzard.com) */ -function news_createmeta_keywords($content) +function news_createmeta_keywords($content): string { require_once XOOPS_ROOT_PATH . '/modules/news/config.php'; // require_once XOOPS_ROOT_PATH . '/modules/news/class/blacklist.php'; @@ -578,10 +562,12 @@ function news_updateCache(): void * @copyright (c) Hervé Thouzard * @author Hervé Thouzard (https://www.herve-thouzard.com) */ -function news_TableExists($tablename) +function news_TableExists($tablename): bool { global $xoopsDB; - $result = $xoopsDB->queryF("SHOW TABLES LIKE '$tablename'"); + + $sql = "SHOW TABLES LIKE '$tablename'"; + $result = Utility::queryFAndCheck($xoopsDB, $sql); return ($xoopsDB->getRowsNum($result) > 0); } @@ -595,10 +581,11 @@ function news_TableExists($tablename) * @author Hervé Thouzard (https://www.herve-thouzard.com) * @copyright (c) Hervé Thouzard */ -function news_FieldExists($fieldname, $table) +function news_FieldExists($fieldname, $table): bool { global $xoopsDB; - $result = $xoopsDB->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'"); + $sql = "SHOW COLUMNS FROM $table LIKE '$fieldname'"; + $result = Utility::queryFAndCheck($xoopsDB, $sql); return ($xoopsDB->getRowsNum($result) > 0); } @@ -623,7 +610,7 @@ function news_AddField($field, $table) /** * Verify that the current user is a member of the Admin group */ -function news_is_admin_group() +function news_is_admin_group(): bool { global $xoopsUser, $xoopsModule; if (is_object($xoopsUser)) { @@ -681,7 +668,7 @@ function news_isbot() * @copyright (c) Hervé Thouzard * @author Hervé Thouzard (https://www.herve-thouzard.com) */ -function news_make_infotips($text) +function news_make_infotips($text): ?string { $infotips = news_getmoduleoption('infotips'); if ($infotips > 0) { @@ -699,7 +686,7 @@ function news_make_infotips($text) * @author Monte Ohrt , modified by Amos Robinson * */ -function news_close_tags($string) +function news_close_tags(string $string): string { // match opened tags if (preg_match_all('/<([a-z\:\-]+)[^\/]>/', $string, $start_tags)) { @@ -750,13 +737,13 @@ function news_close_tags($string) * @author Monte Ohrt , modified by Amos Robinson * */ -function news_truncate_tagsafe($string, $length = 80, $etc = '...', $break_words = false) +function news_truncate_tagsafe($string, $length = 80, $etc = '...', $break_words = false): string { if (0 == $length) { return ''; } if (mb_strlen($string) > $length) { - $length -= mb_strlen($etc); + $length -= \mb_strlen($etc); if (!$break_words) { $string = preg_replace('/\s+?(\S+)?$/', '', mb_substr($string, 0, $length + 1)); $string = preg_replace('/<[^>]*$/', '', $string); @@ -782,13 +769,13 @@ function news_truncate_tagsafe($string, $length = 80, $etc = '...', $break_words * @return bool */ function news_resizePicture( - $src_path, - $dst_path, - $param_width, - $param_height, - $keep_original = false, - $fit = 'inside' -) { + string $src_path, + string $dst_path, + int $param_width, + int $param_height, + bool $keep_original = false, + string $fit = 'inside' +): bool { // require_once XOOPS_PATH . '/vendor/wideimage/WideImage.php'; $resize = true; $pictureDimensions = getimagesize($src_path); diff --git a/include/install_function.php b/include/install_function.php index 248c7a2..2bb7ec0 100644 --- a/include/install_function.php +++ b/include/install_function.php @@ -15,7 +15,7 @@ * @author Voltan * @return bool */ -function xoops_module_pre_install_news(\XoopsModule $module) +function xoops_module_pre_install_news(\XoopsModule $module): bool { // Check if this XOOPS version is supported $minSupportedVersion = explode('.', '2.5.0'); @@ -48,7 +48,7 @@ function xoops_module_pre_install_news(\XoopsModule $module) * @param \XoopsModule $module * @return bool */ -function xoops_module_install_news(\XoopsModule $module) +function xoops_module_install_news(\XoopsModule $module): bool { $module_id = $module->getVar('mid'); /** @var \XoopsGroupPermHandler $grouppermHandler */ @@ -73,20 +73,20 @@ function xoops_module_install_news(\XoopsModule $module) // mkdir($dir, 0777); // } - if (!@mkdir($dir) && !is_dir($dir)) { + if (!is_dir($dir) && !mkdir($dir, 0777, true) && !is_dir($dir)) { throw new \RuntimeException('The directory ' . $dir . ' could not be created.'); } chmod($dir, 0777); $dir = XOOPS_ROOT_PATH . '/uploads/news/file'; - if (!@mkdir($dir) && !is_dir($dir)) { + if (!is_dir($dir) && !mkdir($dir, 0777, true) && !is_dir($dir)) { throw new \RuntimeException('The directory ' . $dir . ' could not be created.'); } chmod($dir, 0777); $dir = XOOPS_ROOT_PATH . '/uploads/news/image'; - if (!@mkdir($dir) && !is_dir($dir)) { + if (!is_dir($dir) && !mkdir($dir, 0777, true) && !is_dir($dir)) { throw new \RuntimeException('The directory ' . $dir . ' could not be created.'); } chmod($dir, 0777); diff --git a/include/notification.inc.php b/include/notification.inc.php index fd7b3ed..70b1b04 100644 --- a/include/notification.inc.php +++ b/include/notification.inc.php @@ -13,15 +13,14 @@ * @copyright {@link https://xoops.org/ XOOPS Project} * @license {@link https://www.gnu.org/licenses/gpl-2.0.html GNU GPL 2 or later} * @author XOOPS Development Team - * @param mixed $category - * @param mixed $item_id */ /** - * @param $category - * @param $item_id + * @param mixed $category + * @param mixed $item_id + * @return array|null */ -function news_notify_iteminfo($category, $item_id) +function news_notify_iteminfo($category, $item_id): ?array { if ('global' === $category) { $item['name'] = ''; @@ -36,7 +35,7 @@ function news_notify_iteminfo($category, $item_id) // Assume we have a valid story id $sql = 'SELECT title FROM ' . $xoopsDB->prefix('news_stories') . ' WHERE storyid = ' . (int)$item_id; $result = $xoopsDB->query($sql); - if ($result) { + if ($xoopsDB->isResultSet($result)) { $result_array = $xoopsDB->fetchArray($result); $item['name'] = $result_array['title']; $item['url'] = XOOPS_URL . '/modules/news/article.php?storyid=' . (int)$item_id; @@ -51,7 +50,7 @@ function news_notify_iteminfo($category, $item_id) if ('category' === $category) { $sql = 'SELECT title FROM ' . $xoopsDB->prefix('news_topics') . ' WHERE topic_id = ' . (int)$item_id; $result = $xoopsDB->query($sql); - if ($result) { + if ($xoopsDB->isResultSet($result)) { $result_array = $xoopsDB->fetchArray($result); $item['name'] = $result_array['topic_id']; $item['url'] = XOOPS_URL . '/modules/news/index.php?storytopic=' . (int)$item_id; diff --git a/include/oninstall.php b/include/oninstall.php index 25ef2c1..cd9acce 100644 --- a/include/oninstall.php +++ b/include/oninstall.php @@ -15,9 +15,11 @@ * @author XOOPS Development Team */ -use XoopsModules\News; -use XoopsModules\News\Common\Configurator; -use XoopsModules\News\Utility; +use XoopsModules\News\{ + Common\Configurator, + Helper, + Utility +}; /** * Prepares system prior to attempting to install module @@ -25,10 +27,10 @@ * * @return bool true if ready to install, false if not */ -function xoops_module_pre_install_news(\XoopsModule $module) +function xoops_module_pre_install_news(\XoopsModule $module): bool { require_once \dirname(__DIR__) . '/preloads/autoloader.php'; - /** @var News\Utility $utility */ + /** @var Utility $utility */ $utility = new Utility(); $xoopsSuccess = $utility::checkVerXoops($module); $phpSuccess = $utility::checkVerPhp($module); @@ -49,14 +51,14 @@ function xoops_module_pre_install_news(\XoopsModule $module) * * @return bool true if installation successful, false if not */ -function xoops_module_install_news(\XoopsModule $module) +function xoops_module_install_news(\XoopsModule $module): bool { - require_once \dirname(__DIR__, 3) . '/mainfile.php'; + require \dirname(__DIR__, 3) . '/mainfile.php'; $moduleDirName = \basename(\dirname(__DIR__)); - /** @var News\Helper $helper */ - $helper = News\Helper::getInstance(); + /** @var Helper $helper */ + $helper = Helper::getInstance(); $utility = new Utility(); $configurator = new Configurator(); // Load language files @@ -64,8 +66,7 @@ function xoops_module_install_news(\XoopsModule $module) $helper->loadLanguage('modinfo'); // default Permission Settings ---------------------- - global $xoopsModule; - $moduleId = $xoopsModule->getVar('mid'); + $moduleId = $module->getVar('mid'); // $moduleId2 = $helper->getModule()->mid(); /** @var \XoopsGroupPermHandler $grouppermHandler */ $grouppermHandler = xoops_getHandler('groupperm'); @@ -93,7 +94,7 @@ function xoops_module_install_news(\XoopsModule $module) } } //delete .html entries from the tpl table - $sql = 'DELETE FROM ' . $GLOBALS['xoopsDB']->prefix('tplfile') . " WHERE `tpl_module` = '" . $xoopsModule->getVar('dirname', 'n') . "' AND `tpl_file` LIKE '%.html%'"; + $sql = 'DELETE FROM ' . $GLOBALS['xoopsDB']->prefix('tplfile') . " WHERE `tpl_module` = '" . $module->getVar('dirname', 'n') . "' AND `tpl_file` LIKE '%.html%'"; $GLOBALS['xoopsDB']->queryF($sql); return true; diff --git a/include/onuninstall.php b/include/onuninstall.php index 55177ff..91bc396 100644 --- a/include/onuninstall.php +++ b/include/onuninstall.php @@ -9,8 +9,10 @@ * @link https://xoops.org XOOPS */ -use XoopsModules\News; -use XoopsModules\News\Utility; +use XoopsModules\News\{ + Helper, + Utility +}; /** * Prepares system prior to attempting to uninstall module @@ -18,7 +20,7 @@ * * @return bool true if ready to uninstall, false if not */ -function xoops_module_pre_uninstall_news(\XoopsModule $module) +function xoops_module_pre_uninstall_news(\XoopsModule $module): bool { // Do some synchronization return true; @@ -30,16 +32,16 @@ function xoops_module_pre_uninstall_news(\XoopsModule $module) * * @return bool true if uninstallation successful, false if not */ -function xoops_module_uninstall_news(\XoopsModule $module) +function xoops_module_uninstall_news(\XoopsModule $module): bool { // return true; $moduleDirName = \basename(\dirname(__DIR__)); $moduleDirNameUpper = \mb_strtoupper($moduleDirName); - /** @var News\Helper $helper */ - $helper = News\Helper::getInstance(); + /** @var Helper $helper */ + $helper = Helper::getInstance(); - /** @var News\Utility $utility */ + /** @var Utility $utility */ $utility = new Utility(); $success = true; @@ -52,7 +54,7 @@ function xoops_module_uninstall_news(\XoopsModule $module) // The directory exists so rename it $date = date('Y-m-d'); if (!rename($uploadDirectory, $uploadDirectory . "_bak_$date")) { - $module->setErrors(sprintf(constant('CO_' . $moduleDirNameUpper . '_ERROR_BAD_DEL_PATH'), $uploadDirectory)); + $module->setErrors(sprintf(constant('CO_' . $moduleDirNameUpper . '_' . 'ERROR_BAD_DEL_PATH'), $uploadDirectory)); $success = false; } } @@ -63,7 +65,7 @@ function xoops_module_uninstall_news(\XoopsModule $module) // Remove xsitemap.xml from XOOPS root folder if it exists //------------------------------------------------------------------ $xmlfile = $GLOBALS['xoops']->path('xsitemap.xml'); - if (is_file($xmlfile)) { + if (\is_file($xmlfile)) { if (false === ($delOk = unlink($xmlfile))) { $module->setErrors(sprintf(_AM_XXXXX_ERROR_BAD_REMOVE, $xmlfile)); } diff --git a/include/onupdate.php b/include/onupdate.php index 064cfaf..c295c92 100644 --- a/include/onupdate.php +++ b/include/onupdate.php @@ -15,9 +15,12 @@ * @author XOOPS Development Team */ -use XoopsModules\News; -use XoopsModules\News\Common\Configurator; -use XoopsModules\News\Utility; +use XoopsModules\News\{ + Common\Configurator, + Helper, + Utility +}; + if ((!defined('XOOPS_ROOT_PATH')) || !($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) { @@ -26,16 +29,16 @@ /** * Prepares system prior to attempting to install module - * @param \XoopsModule $module {@link XoopsModule} + * @param \XoopsModule $module {@link \XoopsModule} * * @return bool true if ready to install, false if not */ -function xoops_module_pre_update_news(\XoopsModule $module) +function xoops_module_pre_update_news(\XoopsModule $module): bool { $moduleDirName = \basename(\dirname(__DIR__)); - /** @var News\Helper $helper */ - /** @var News\Utility $utility */ - $helper = News\Helper::getInstance(); + /** @var Helper $helper */ + /** @var Utility $utility */ + $helper = Helper::getInstance(); $utility = new Utility(); $xoopsSuccess = $utility::checkVerXoops($module); @@ -46,23 +49,206 @@ function xoops_module_pre_update_news(\XoopsModule $module) /** * Performs tasks required during update of the module - * @param \XoopsModule $module {@link XoopsModule} + * @param \XoopsModule $module {@link \XoopsModule} * @param null $previousVersion * * @return bool true if update successful, false if not */ -function xoops_module_update_news(\XoopsModule $module, $previousVersion = null) +function xoops_module_update_news(\XoopsModule $module, $previousVersion = null): bool { $moduleDirName = \basename(\dirname(__DIR__)); $moduleDirNameUpper = \mb_strtoupper($moduleDirName); - /** @var News\Helper $helper */ /** @var News\Utility $utility */ - /** @var News\Common\Configurator $configurator */ - $helper = News\Helper::getInstance(); + /** @var Helper $helper */ + /** @var Utility $utility */ + /** @var Configurator $configurator */ + $helper = Helper::getInstance(); $utility = new Utility(); $configurator = new Configurator(); - if ($previousVersion < 240) { + if ($previousVersion < 174) { + + global $xoopsDB; + $errors = 0; + + //0) Rename all tables + + if (Utility::existTable($xoopsDB->prefix('stories_files'))) { + $sql = 'ALTER TABLE ' . $xoopsDB->prefix('stories_files') . ' RENAME ' . $xoopsDB->prefix('news_stories_files'); + $result = $xoopsDB->queryF($sql); + if (!$result) { + echo '
' . _AM_NEWS_UPGRADEFAILED . ' ' . _AM_NEWS_UPGRADEFAILED2; + ++$errors; + } + } elseif (!Utility::existTable($xoopsDB->prefix('news_stories_files'))) { + // 1) Create, if it does not exists, the stories_files table + $sql = 'CREATE TABLE ' . $xoopsDB->prefix('news_stories_files') . " ( + fileid INT(8) UNSIGNED NOT NULL AUTO_INCREMENT, + filerealname VARCHAR(255) NOT NULL DEFAULT '', + storyid INT(8) UNSIGNED NOT NULL DEFAULT '0', + date INT(10) NOT NULL DEFAULT '0', + mimetype VARCHAR(64) NOT NULL DEFAULT '', + downloadname VARCHAR(255) NOT NULL DEFAULT '', + counter INT(8) UNSIGNED NOT NULL DEFAULT '0', + PRIMARY KEY (fileid), + KEY storyid (storyid) + ) ENGINE=MyISAM;"; + if (!$xoopsDB->queryF($sql)) { + echo '
' . _AM_NEWS_UPGRADEFAILED . ' ' . _AM_NEWS_UPGRADEFAILED1; + ++$errors; + } + } + + if (Utility::existTable($xoopsDB->prefix('stories'))) { + $sql = 'ALTER TABLE ' . $xoopsDB->prefix('stories') . ' RENAME ' . $xoopsDB->prefix('news_stories'); + $result = $xoopsDB->queryF($sql); + if (!$result) { + echo '
' . _AM_NEWS_UPGRADEFAILED . ' ' . _AM_NEWS_UPGRADEFAILED2; + ++$errors; + } + } + + if (Utility::existTable($xoopsDB->prefix('topics'))) { + $sql = 'ALTER TABLE ' . $xoopsDB->prefix('topics') . ' RENAME ' . $xoopsDB->prefix('news_topics'); + $result = $xoopsDB->queryF($sql); + if (!$result) { + echo '
' . _AM_NEWS_UPGRADEFAILED . ' ' . _AM_NEWS_UPGRADEFAILED2; + ++$errors; + } + } + + if (Utility::existTable($xoopsDB->prefix('stories_files'))) { + $sql = 'ALTER TABLE ' . $xoopsDB->prefix('stories_files') . ' RENAME ' . $xoopsDB->prefix('news_stories_files'); + $result = $xoopsDB->queryF($sql); + if (!$result) { + echo '
' . _AM_NEWS_UPGRADEFAILED . ' ' . _AM_NEWS_UPGRADEFAILED2; + ++$errors; + } + } + + // 2) Change the topic title's length, in the topics table + $sql = 'ALTER TABLE ' . $xoopsDB->prefix('news_topics') . ' CHANGE topic_title topic_title VARCHAR( 255 ) NOT NULL;'; + $result = $xoopsDB->queryF($sql); + if (!$result) { + echo '
' . _AM_NEWS_UPGRADEFAILED . ' ' . _AM_NEWS_UPGRADEFAILED2; + ++$errors; + } + + // 2.0a) change column size for IP address from varchar(16) to varchar(45) for IPv6 + $sql = 'ALTER TABLE ' . $xoopsDB->prefix('news_stories') . ' MODIFY hostname VARCHAR( 45 ) NOT NULL DEFAULT \'\';'; + $result = $xoopsDB->queryF($sql); + if (!$result) { + echo '
' . _AM_NEWS_UPGRADEFAILED . ' ' . _AM_NEWS_UPGRADEFAILED2; + ++$errors; + } + + // 2.0b) change column size for Picture from varchar(50) to varchar(255) for SEO + $sql = 'ALTER TABLE ' . $xoopsDB->prefix('news_stories') . ' MODIFY picture VARCHAR( 255 ) NOT NULL DEFAULT \'\';'; + $result = $xoopsDB->queryF($sql); + if (!$result) { + echo '
' . _AM_NEWS_UPGRADEFAILED . ' ' . _AM_NEWS_UPGRADEFAILED2; + ++$errors; + } + + + // 2.1) Add the new fields to the topic table + if (!Utility::existField('menu', $xoopsDB->prefix('news_topics'))) { + Utility::addField("menu TINYINT( 1 ) DEFAULT '0' NOT NULL", $xoopsDB->prefix('news_topics')); + } + if (!Utility::existField('topic_frontpage', $xoopsDB->prefix('news_topics'))) { + Utility::addField("topic_frontpage TINYINT( 1 ) DEFAULT '1' NOT NULL", $xoopsDB->prefix('news_topics')); + } + if (!Utility::existField('topic_rssurl', $xoopsDB->prefix('news_topics'))) { + Utility::addField('topic_rssurl VARCHAR( 255 ) NOT NULL', $xoopsDB->prefix('news_topics')); + } + if (!Utility::existField('topic_description', $xoopsDB->prefix('news_topics'))) { + Utility::addField('topic_description TEXT NOT NULL', $xoopsDB->prefix('news_topics')); + } + if (!Utility::existField('topic_color', $xoopsDB->prefix('news_topics'))) { + Utility::addField("topic_color varchar(6) NOT NULL default '000000'", $xoopsDB->prefix('news_topics')); + } + + // 3) If it does not exists, create the table stories_votedata + if (!Utility::existTable($xoopsDB->prefix('news_stories_votedata'))) { + $sql = 'CREATE TABLE ' . $xoopsDB->prefix('news_stories_votedata') . " ( + ratingid INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, + storyid INT(8) UNSIGNED NOT NULL DEFAULT '0', + ratinguser INT(11) NOT NULL DEFAULT '0', + rating TINYINT(3) UNSIGNED NOT NULL DEFAULT '0', + ratinghostname VARCHAR(60) NOT NULL DEFAULT '', + ratingtimestamp INT(10) NOT NULL DEFAULT '0', + PRIMARY KEY (ratingid), + KEY ratinguser (ratinguser), + KEY ratinghostname (ratinghostname), + KEY storyid (storyid) + ) ENGINE=MyISAM;"; + if (!$xoopsDB->queryF($sql)) { + echo '
' . _AM_NEWS_UPGRADEFAILED . ' ' . _AM_NEWS_UPGRADEFAILED3; + ++$errors; + } + } + + // 4) Create the four new fields for the votes in the story table + if (!Utility::existField('rating', $xoopsDB->prefix('news_stories'))) { + Utility::addField("rating DOUBLE( 6, 4 ) DEFAULT '0.0000' NOT NULL", $xoopsDB->prefix('news_stories')); + } + if (!Utility::existField('votes', $xoopsDB->prefix('news_stories'))) { + Utility::addField("votes INT( 11 ) UNSIGNED DEFAULT '0' NOT NULL", $xoopsDB->prefix('news_stories')); + } + if (!Utility::existField('keywords', $xoopsDB->prefix('news_stories'))) { + Utility::addField('keywords VARCHAR(255) NOT NULL', $xoopsDB->prefix('news_stories')); + } + if (!Utility::existField('description', $xoopsDB->prefix('news_stories'))) { + Utility::addField('description VARCHAR(255) NOT NULL', $xoopsDB->prefix('news_stories')); + } + if (!Utility::existField('pictureinfo', $xoopsDB->prefix('news_stories'))) { + Utility::addField('pictureinfo VARCHAR(255) NOT NULL', $xoopsDB->prefix('news_stories')); + } + if (!Utility::existField('subtitle', $xoopsDB->prefix('news_stories'))) { + Utility::addField('subtitle VARCHAR(255) NOT NULL', $xoopsDB->prefix('news_stories')); + } + + // 5) Add some indexes to the topics table + $sql = 'ALTER TABLE ' . $xoopsDB->prefix('news_topics') . ' ADD INDEX ( `topic_title` );'; + $result = $xoopsDB->queryF($sql); + $sql = 'ALTER TABLE ' . $xoopsDB->prefix('news_topics') . ' ADD INDEX ( `menu` );'; + $result = $xoopsDB->queryF($sql); + + // 6) Make files and folders + $dir = XOOPS_ROOT_PATH . '/uploads/news'; + if (!is_dir($dir) && !mkdir($dir, 0777, true) && !is_dir($dir)) { + throw new \RuntimeException('The directory ' . $dir . ' could not be created.'); + } + if (!is_writable($dir)) { + chmod($dir, 0777); + } + + $dir = XOOPS_ROOT_PATH . '/uploads/news/file'; + if (!is_dir($dir) && !mkdir($dir, 0777, true) && !is_dir($dir)) { + throw new \RuntimeException('The directory ' . $dir . ' could not be created.'); + } + if (!is_writable($dir)) { + chmod($dir, 0777); + } + + $dir = XOOPS_ROOT_PATH . '/uploads/news/image'; + if (!is_dir($dir) && !mkdir($dir, 0777, true) && !is_dir($dir)) { + throw new \RuntimeException('The directory ' . $dir . ' could not be created.'); + } + if (!is_writable($dir)) { + chmod($dir, 0777); + } + + // Copy index.html files on uploads folders + $indexFile = XOOPS_ROOT_PATH . '/modules/news/include/index.php'; + copy($indexFile, XOOPS_ROOT_PATH . '/uploads/news/index.php'); + copy($indexFile, XOOPS_ROOT_PATH . '/uploads/news/file/index.php'); + copy($indexFile, XOOPS_ROOT_PATH . '/uploads/news/image/index.php'); + } + +// $module = $helper->getModule(); + +// if (true === $module->versionCompare($previousVersion, $module->getInfo('version'))) { //delete old HTML templates if (count($configurator->templateFolders) > 0) { foreach ($configurator->templateFolders as $folder) { @@ -72,7 +258,7 @@ function xoops_module_update_news(\XoopsModule $module, $previousVersion = null) foreach ($templateList as $k => $v) { $fileInfo = new \SplFileInfo($templateFolder . $v); if ('html' === $fileInfo->getExtension() && 'index.html' !== $fileInfo->getFilename()) { - if (is_file($templateFolder . $v)) { + if (\is_file($templateFolder . $v)) { unlink($templateFolder . $v); } } @@ -86,7 +272,7 @@ function xoops_module_update_news(\XoopsModule $module, $previousVersion = null) // foreach (array_keys($GLOBALS['uploadFolders']) as $i) { foreach (array_keys($configurator->oldFiles) as $i) { $tempFile = $GLOBALS['xoops']->path('modules/' . $moduleDirName . $configurator->oldFiles[$i]); - if (is_file($tempFile)) { + if (\is_file($tempFile)) { unlink($tempFile); } } @@ -98,7 +284,7 @@ function xoops_module_update_news(\XoopsModule $module, $previousVersion = null) // foreach (array_keys($GLOBALS['uploadFolders']) as $i) { foreach (array_keys($configurator->oldFolders) as $i) { $tempFolder = $GLOBALS['xoops']->path('modules/' . $moduleDirName . $configurator->oldFolders[$i]); - /** @var XoopsObjectHandler $folderHandler */ + /** @var \XoopsObjectHandler $folderHandler */ $folderHandler = \XoopsFile::getHandler('folder', $tempFolder); $folderHandler->delete($tempFolder); } @@ -122,14 +308,29 @@ function xoops_module_update_news(\XoopsModule $module, $previousVersion = null) } //delete .html entries from the tpl table - $sql = 'DELETE FROM ' . $GLOBALS['xoopsDB']->prefix('tplfile') . " WHERE `tpl_module` = '" . $module->getVar('dirname', 'n') . '\' AND `tpl_file` LIKE \'%.html%\''; - $GLOBALS['xoopsDB']->queryF($sql); +// $sql = 'DELETE FROM ' . $GLOBALS['xoopsDB']->prefix('tplfile') . " WHERE `tpl_module` = '" . $module->getVar('dirname', 'n') . '\' AND `tpl_file` LIKE \'%.html%\''; +// $GLOBALS['xoopsDB']->queryF($sql); + //delete old .html entries from the tpl table + $sql = 'DELETE FROM ' . $GLOBALS['xoopsDB']->prefix('tplfile') . " WHERE `tpl_module` = '" . $module->getVar('dirname', 'n') . "' AND `tpl_file` LIKE '%.html%'"; + $GLOBALS['xoopsDB']->queryF($sql); + + //delete old .html entries from the newblocks table + $sql = 'DELETE FROM ' . $GLOBALS['xoopsDB']->prefix('newblocks') . " WHERE `mid` = '" . $module->getVar('mid') . "' AND `template` LIKE '%.html%'"; + $GLOBALS['xoopsDB']->queryF($sql); + + //delete old .tpl entries from the tpl table +// $sql = 'DELETE FROM ' . $GLOBALS['xoopsDB']->prefix('tplfile') . " WHERE `tpl_module` = '" . $module->getVar('dirname', 'n') . "' AND `tpl_file` LIKE '%.tpl%'"; +// $GLOBALS['xoopsDB']->queryF($sql); + + //delete .tpl entries from the tpl_source table +// $sql = 'DELETE FROM ' . $GLOBALS['xoopsDB']->prefix('tplsource') . " WHERE `tpl_source` LIKE '%' . $module->getVar('dirname', 'n') . '%'"; +// $GLOBALS['xoopsDB']->queryF($sql); /** @var \XoopsGroupPermHandler $grouppermHandler */ $grouppermHandler = xoops_getHandler('groupperm'); return $grouppermHandler->deleteByModule($module->getVar('mid'), 'item_read'); - } +// } return true; } diff --git a/include/search.inc.php b/include/search.inc.php index 6ecaae4..b172ff1 100644 --- a/include/search.inc.php +++ b/include/search.inc.php @@ -15,7 +15,9 @@ * @author XOOPS Development Team */ -use XoopsModules\News; +use XoopsModules\News\{ + Utility +}; /** * @param $queryarray @@ -26,12 +28,12 @@ * * @return array */ -function news_search($queryarray, $andor, $limit, $offset, $userid) +function news_search($queryarray, $andor, $limit, $offset, $userid): array { global $xoopsDB, $xoopsUser; - $restricted = News\Utility::getModuleOption('restrictindex'); + $restricted = Utility::getModuleOption('restrictindex'); $highlight = false; - $highlight = News\Utility::getModuleOption('keywordshighlight'); // keywords highlighting + $highlight = Utility::getModuleOption('keywordshighlight'); // keywords highlighting /** @var \XoopsModuleHandler $moduleHandler */ $moduleHandler = xoops_getHandler('module'); @@ -69,6 +71,9 @@ function news_search($queryarray, $andor, $limit, $offset, $userid) $sql .= 'ORDER BY created DESC'; $result = $xoopsDB->query($sql, $limit, $offset); + if (!$xoopsDB->isResultSet($result)) { + \trigger_error("Query Failed! SQL: $sql- Error: " . $xoopsDB->error(), E_USER_ERROR); + } $ret = []; $i = 0; while (false !== ($myrow = $xoopsDB->fetchArray($result))) { @@ -93,7 +98,7 @@ function news_search($queryarray, $andor, $limit, $offset, $userid) $searchincomments = $cfg['config_search_comments']; if ($searchincomments && (isset($limit) && $i <= $limit)) { - require XOOPS_ROOT_PATH . '/include/comment_constants.php'; + require_once XOOPS_ROOT_PATH . '/include/comment_constants.php'; $ind = $i; $sql = 'SELECT com_id, com_modid, com_itemid, com_created, com_uid, com_title, com_text, com_status FROM ' . $xoopsDB->prefix('xoopscomments') . " WHERE (com_id>0) AND (com_modid=$modid) AND (com_status=" . XOOPS_COMMENT_ACTIVE . ') '; if (0 != $userid) { @@ -111,6 +116,9 @@ function news_search($queryarray, $andor, $limit, $offset, $userid) $i = $ind; $sql .= 'ORDER BY com_created DESC'; $result = $xoopsDB->query($sql, $limit, $offset); + if (!$xoopsDB->isResultSet($result)) { + \trigger_error("Query Failed! SQL: $sql- Error: " . $xoopsDB->error(), E_USER_ERROR); + } while (false !== ($myrow = $xoopsDB->fetchArray($result))) { $display = true; if ($modid && $grouppermHandler) { diff --git a/include/storyform.inc.php b/include/storyform.inc.php index 4049254..2a67878 100644 --- a/include/storyform.inc.php +++ b/include/storyform.inc.php @@ -16,10 +16,13 @@ */ use Xmf\Request; -use XoopsModules\News; -use XoopsModules\News\Files; -use XoopsModules\News\NewsTopic; use XoopsModules\Tag\FormTag; +use XoopsModules\News\{ + Files, + NewsTopic, + Utility +}; + $moduleDirName = \basename(\dirname(__DIR__)); xoops_load('utility', $moduleDirName); @@ -49,7 +52,7 @@ $allTopics = $xt->getAllTopics($helper->getConfig('restrictindex'), 'news_submit'); $topic_tree = new \XoopsObjectTree($allTopics, 'topic_id', 'topic_pid'); -if (News\Utility::checkVerXoops($GLOBALS['xoopsModule'], '2.5.9')) { +if (Utility::checkVerXoops($GLOBALS['xoopsModule'], '2.5.9')) { $topic_select = $topic_tree->makeSelectElement('topic_id', 'topic_title', '--', $topicid, false, 0, '', _NW_TOPIC); $sform->addElement($topic_select); } else { @@ -89,26 +92,26 @@ } } -$editor = News\Utility::getWysiwygForm(_NW_THESCOOP, 'hometext', $hometext, 15, 60, 'hometext_hidden'); +$editor = Utility::getWysiwygForm(_NW_THESCOOP, 'hometext', $hometext, 15, 60, 'hometext_hidden'); $sform->addElement($editor, true); //Extra info //If admin -> if submit privilege if ($approveprivilege) { - $editor2 = News\Utility::getWysiwygForm(_AM_EXTEXT, 'bodytext', $bodytext, 15, 60, 'bodytext_hidden'); + $editor2 = Utility::getWysiwygForm(_AM_EXTEXT, 'bodytext', $bodytext, 15, 60, 'bodytext_hidden'); $sform->addElement($editor2, false); - if (News\Utility::getModuleOption('tags') && \class_exists(\XoopsModules\Tag\FormTag::class) && xoops_isActiveModule('tag')) { + if (Utility::getModuleOption('tags') && \class_exists(\XoopsModules\Tag\FormTag::class) && xoops_isActiveModule('tag')) { $itemIdForTag = $storyid ?? 0; $sform->addElement(new \XoopsModules\Tag\FormTag('item_tag', 60, 255, $itemIdForTag, 0)); } - if (News\Utility::getModuleOption('metadata')) { + if (Utility::getModuleOption('metadata')) { $sform->addElement(new xoopsFormText(_NW_META_DESCRIPTION, 'description', 50, 255, $description), false); $sform->addElement(new xoopsFormText(_NW_META_KEYWORDS, 'keywords', 50, 255, $keywords), false); } -} elseif (News\Utility::getModuleOption('tags') && \class_exists(\XoopsModules\Tag\FormTag::class) && xoops_isActiveModule('tag')) { +} elseif (Utility::getModuleOption('tags') && \class_exists(\XoopsModules\Tag\FormTag::class) && xoops_isActiveModule('tag')) { $itemIdForTag = $storyid ?? 0; $sform->addElement(new \XoopsModules\Tag\FormTag('item_tag', 60, 255, $itemIdForTag, 0)); } @@ -240,8 +243,8 @@ $sform->addElement($type_hidden); echo '

' . _NW_SUBMITNEWS . '

'; -if ('' !== xoops_trim(News\Utility::getModuleOption('submitintromsg'))) { - echo "


" . nl2br(News\Utility::getModuleOption('submitintromsg')) . '

'; +if ('' !== xoops_trim(Utility::getModuleOption('submitintromsg'))) { + echo "


" . nl2br(Utility::getModuleOption('submitintromsg')) . '

'; } $sform->display(); diff --git a/include/storyform.original.php b/include/storyform.original.php index 9b579aa..9e1fac3 100644 --- a/include/storyform.original.php +++ b/include/storyform.original.php @@ -16,16 +16,19 @@ */ use Xmf\Request; -use XoopsModules\News; -use XoopsModules\News\Files; -use XoopsModules\News\NewsTopic; +use XoopsModules\News\{ + Files, + Helper, + NewsTopic, + Utility +}; use XoopsModules\Tag\FormTag; require_once XOOPS_ROOT_PATH . '/class/xoopsformloader.php'; require_once XOOPS_ROOT_PATH . '/modules/news/config.php'; -/** @var News\Helper $helper */ -$helper = News\Helper::getInstance(); +/** @var Helper $helper */ +$helper = Helper::getInstance(); xoops_loadLanguage('calendar'); if (!isset($subtitle)) { @@ -55,14 +58,9 @@ $moduleDirName = \basename(\dirname(__DIR__)); xoops_load('utility', $moduleDirName); -if (News\Utility::checkVerXoops($GLOBALS['xoopsModule'], '2.5.9')) { - // $topic_select = $topic_tree->makeSelBox('topic_id', 'topic_title', '-- ', $topicid, false); - $topic_select = $topic_tree->makeSelectElement('topic_id', 'topic_title', '--', $topicid, false, 0, '', _NW_TOPIC); - $sform->addElement($topic_select); -} else { - $topic_select = $topic_tree->makeSelBox('topic_id', 'topic_title', '-- ', $topicid, false); - $sform->addElement(new \XoopsFormLabel(_NW_TOPIC, $topic_select)); -} +$topic_select = $topic_tree->makeSelectElement('topic_id', 'topic_title', '--', $topicid, false, 0, '', _NW_TOPIC); +$sform->addElement($topic_select); + //If admin - show admin form //TODO: Change to "If submit privilege" @@ -94,21 +92,21 @@ } } -$editor = News\Utility::getWysiwygForm(_NW_THESCOOP, 'hometext', $hometext, 15, 60, 'hometext_hidden'); +$editor = Utility::getWysiwygForm(_NW_THESCOOP, 'hometext', $hometext, 15, 60, 'hometext_hidden'); $sform->addElement($editor, true); //Extra info //If admin -> if submit privilege if ($approveprivilege) { - $editor2 = News\Utility::getWysiwygForm(_AM_EXTEXT, 'bodytext', $bodytext, 15, 60, 'bodytext_hidden'); + $editor2 = Utility::getWysiwygForm(_AM_EXTEXT, 'bodytext', $bodytext, 15, 60, 'bodytext_hidden'); $sform->addElement($editor2, false); - if (News\Utility::getModuleOption('tags') && \class_exists(\XoopsModules\Tag\FormTag::class) && xoops_isActiveModule('tag')) { + if (Utility::getModuleOption('tags') && \class_exists(\XoopsModules\Tag\FormTag::class) && xoops_isActiveModule('tag')) { $itemIdForTag = $storyid ?? 0; $sform->addElement(new \XoopsModules\Tag\FormTag('item_tag', 60, 255, $itemIdForTag, 0)); } - if (News\Utility::getModuleOption('metadata')) { + if (Utility::getModuleOption('metadata')) { $sform->addElement(new xoopsFormText(_NW_META_DESCRIPTION, 'description', 50, 255, $description), false); $sform->addElement(new xoopsFormText(_NW_META_KEYWORDS, 'keywords', 50, 255, $keywords), false); } diff --git a/include/update_function.php b/include/update_function.php index 6e3e99f..0bed051 100644 --- a/include/update_function.php +++ b/include/update_function.php @@ -15,26 +15,28 @@ * @author Voltan */ -use XoopsModules\News; +use XoopsModules\News\{ + Utility +}; /** * @return bool */ -function xoops_module_update_news() +function xoops_module_update_news(): bool { global $xoopsDB; $errors = 0; //0) Rename all tables - if (News\Utility::existTable($xoopsDB->prefix('stories_files'))) { + if (Utility::existTable($xoopsDB->prefix('stories_files'))) { $sql = 'ALTER TABLE ' . $xoopsDB->prefix('stories_files') . ' RENAME ' . $xoopsDB->prefix('news_stories_files'); $result = $xoopsDB->queryF($sql); if (!$result) { echo '
' . _AM_NEWS_UPGRADEFAILED . ' ' . _AM_NEWS_UPGRADEFAILED2; ++$errors; } - } elseif (!News\Utility::existTable($xoopsDB->prefix('news_stories_files'))) { + } elseif (!Utility::existTable($xoopsDB->prefix('news_stories_files'))) { // 1) Create, if it does not exists, the stories_files table $sql = 'CREATE TABLE ' . $xoopsDB->prefix('news_stories_files') . " ( fileid INT(8) UNSIGNED NOT NULL AUTO_INCREMENT, @@ -53,7 +55,7 @@ function xoops_module_update_news() } } - if (News\Utility::existTable($xoopsDB->prefix('stories'))) { + if (Utility::existTable($xoopsDB->prefix('stories'))) { $sql = 'ALTER TABLE ' . $xoopsDB->prefix('stories') . ' RENAME ' . $xoopsDB->prefix('news_stories'); $result = $xoopsDB->queryF($sql); if (!$result) { @@ -62,7 +64,7 @@ function xoops_module_update_news() } } - if (News\Utility::existTable($xoopsDB->prefix('topics'))) { + if (Utility::existTable($xoopsDB->prefix('topics'))) { $sql = 'ALTER TABLE ' . $xoopsDB->prefix('topics') . ' RENAME ' . $xoopsDB->prefix('news_topics'); $result = $xoopsDB->queryF($sql); if (!$result) { @@ -71,7 +73,7 @@ function xoops_module_update_news() } } - if (News\Utility::existTable($xoopsDB->prefix('stories_files'))) { + if (Utility::existTable($xoopsDB->prefix('stories_files'))) { $sql = 'ALTER TABLE ' . $xoopsDB->prefix('stories_files') . ' RENAME ' . $xoopsDB->prefix('news_stories_files'); $result = $xoopsDB->queryF($sql); if (!$result) { @@ -106,24 +108,24 @@ function xoops_module_update_news() // 2.1) Add the new fields to the topic table - if (!News\Utility::existField('menu', $xoopsDB->prefix('news_topics'))) { - News\Utility::addField("menu TINYINT( 1 ) DEFAULT '0' NOT NULL", $xoopsDB->prefix('news_topics')); + if (!Utility::existField('menu', $xoopsDB->prefix('news_topics'))) { + Utility::addField("menu TINYINT( 1 ) DEFAULT '0' NOT NULL", $xoopsDB->prefix('news_topics')); } - if (!News\Utility::existField('topic_frontpage', $xoopsDB->prefix('news_topics'))) { - News\Utility::addField("topic_frontpage TINYINT( 1 ) DEFAULT '1' NOT NULL", $xoopsDB->prefix('news_topics')); + if (!Utility::existField('topic_frontpage', $xoopsDB->prefix('news_topics'))) { + Utility::addField("topic_frontpage TINYINT( 1 ) DEFAULT '1' NOT NULL", $xoopsDB->prefix('news_topics')); } - if (!News\Utility::existField('topic_rssurl', $xoopsDB->prefix('news_topics'))) { - News\Utility::addField('topic_rssurl VARCHAR( 255 ) NOT NULL', $xoopsDB->prefix('news_topics')); + if (!Utility::existField('topic_rssurl', $xoopsDB->prefix('news_topics'))) { + Utility::addField('topic_rssurl VARCHAR( 255 ) NOT NULL', $xoopsDB->prefix('news_topics')); } - if (!News\Utility::existField('topic_description', $xoopsDB->prefix('news_topics'))) { - News\Utility::addField('topic_description TEXT NOT NULL', $xoopsDB->prefix('news_topics')); + if (!Utility::existField('topic_description', $xoopsDB->prefix('news_topics'))) { + Utility::addField('topic_description TEXT NOT NULL', $xoopsDB->prefix('news_topics')); } - if (!News\Utility::existField('topic_color', $xoopsDB->prefix('news_topics'))) { - News\Utility::addField("topic_color varchar(6) NOT NULL default '000000'", $xoopsDB->prefix('news_topics')); + if (!Utility::existField('topic_color', $xoopsDB->prefix('news_topics'))) { + Utility::addField("topic_color varchar(6) NOT NULL default '000000'", $xoopsDB->prefix('news_topics')); } // 3) If it does not exists, create the table stories_votedata - if (!News\Utility::existTable($xoopsDB->prefix('news_stories_votedata'))) { + if (!Utility::existTable($xoopsDB->prefix('news_stories_votedata'))) { $sql = 'CREATE TABLE ' . $xoopsDB->prefix('news_stories_votedata') . " ( ratingid INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, storyid INT(8) UNSIGNED NOT NULL DEFAULT '0', @@ -143,23 +145,23 @@ function xoops_module_update_news() } // 4) Create the four new fields for the votes in the story table - if (!News\Utility::existField('rating', $xoopsDB->prefix('news_stories'))) { - News\Utility::addField("rating DOUBLE( 6, 4 ) DEFAULT '0.0000' NOT NULL", $xoopsDB->prefix('news_stories')); + if (!Utility::existField('rating', $xoopsDB->prefix('news_stories'))) { + Utility::addField("rating DOUBLE( 6, 4 ) DEFAULT '0.0000' NOT NULL", $xoopsDB->prefix('news_stories')); } - if (!News\Utility::existField('votes', $xoopsDB->prefix('news_stories'))) { - News\Utility::addField("votes INT( 11 ) UNSIGNED DEFAULT '0' NOT NULL", $xoopsDB->prefix('news_stories')); + if (!Utility::existField('votes', $xoopsDB->prefix('news_stories'))) { + Utility::addField("votes INT( 11 ) UNSIGNED DEFAULT '0' NOT NULL", $xoopsDB->prefix('news_stories')); } - if (!News\Utility::existField('keywords', $xoopsDB->prefix('news_stories'))) { - News\Utility::addField('keywords VARCHAR(255) NOT NULL', $xoopsDB->prefix('news_stories')); + if (!Utility::existField('keywords', $xoopsDB->prefix('news_stories'))) { + Utility::addField('keywords VARCHAR(255) NOT NULL', $xoopsDB->prefix('news_stories')); } - if (!News\Utility::existField('description', $xoopsDB->prefix('news_stories'))) { - News\Utility::addField('description VARCHAR(255) NOT NULL', $xoopsDB->prefix('news_stories')); + if (!Utility::existField('description', $xoopsDB->prefix('news_stories'))) { + Utility::addField('description VARCHAR(255) NOT NULL', $xoopsDB->prefix('news_stories')); } - if (!News\Utility::existField('pictureinfo', $xoopsDB->prefix('news_stories'))) { - News\Utility::addField('pictureinfo VARCHAR(255) NOT NULL', $xoopsDB->prefix('news_stories')); + if (!Utility::existField('pictureinfo', $xoopsDB->prefix('news_stories'))) { + Utility::addField('pictureinfo VARCHAR(255) NOT NULL', $xoopsDB->prefix('news_stories')); } - if (!News\Utility::existField('subtitle', $xoopsDB->prefix('news_stories'))) { - News\Utility::addField('subtitle VARCHAR(255) NOT NULL', $xoopsDB->prefix('news_stories')); + if (!Utility::existField('subtitle', $xoopsDB->prefix('news_stories'))) { + Utility::addField('subtitle VARCHAR(255) NOT NULL', $xoopsDB->prefix('news_stories')); } // 5) Add some indexes to the topics table @@ -170,7 +172,7 @@ function xoops_module_update_news() // 6) Make files and folders $dir = XOOPS_ROOT_PATH . '/uploads/news'; - if (!@mkdir($dir) && !is_dir($dir)) { + if (!is_dir($dir) && !mkdir($dir, 0777, true) && !is_dir($dir)) { throw new \RuntimeException('The directory ' . $dir . ' could not be created.'); } if (!is_writable($dir)) { @@ -178,7 +180,7 @@ function xoops_module_update_news() } $dir = XOOPS_ROOT_PATH . '/uploads/news/file'; - if (!@mkdir($dir) && !is_dir($dir)) { + if (!is_dir($dir) && !mkdir($dir, 0777, true) && !is_dir($dir)) { throw new \RuntimeException('The directory ' . $dir . ' could not be created.'); } if (!is_writable($dir)) { @@ -186,7 +188,7 @@ function xoops_module_update_news() } $dir = XOOPS_ROOT_PATH . '/uploads/news/image'; - if (!@mkdir($dir) && !is_dir($dir)) { + if (!is_dir($dir) && !mkdir($dir, 0777, true) && !is_dir($dir)) { throw new \RuntimeException('The directory ' . $dir . ' could not be created.'); } if (!is_writable($dir)) { diff --git a/index.php b/index.php index 464454d..31e258a 100644 --- a/index.php +++ b/index.php @@ -174,13 +174,8 @@ $allTopics = $xt->getAllTopics($helper->getConfig('restrictindex')); $topic_tree = new ObjectTree($allTopics, 'topic_id', 'topic_pid'); - if (Utility::checkVerXoops($GLOBALS['xoopsModule'], '2.5.9')) { - $topic_select = $topic_tree->makeSelectElement('storytopic', 'topic_title', '--', $xoopsOption['storytopic'], true, 0, '', ''); - $xoopsTpl->assign('topic_select', $topic_select->render()); - } else { - $topic_select = $topic_tree->makeSelBox('storytopic', 'topic_title', '-- ', $xoopsOption['storytopic'], true); - $xoopsTpl->assign('topic_select', $topic_select); - } + $topic_select = $topic_tree->makeSelectElement('storytopic', 'topic_title', '--', $xoopsOption['storytopic'], true, 0, '', ''); + $xoopsTpl->assign('topic_select', $topic_select->render()); $storynum_options = ''; for ($i = 5; $i <= 30; $i += 5) { @@ -314,7 +309,7 @@ $xoopsTpl->assign('advertisement', Utility::getModuleOption('advertisement')); /** - * Create the Meta Datas + * Create the Metadata */ Utility::createMetaDatas(); diff --git a/language/english/blocksadmin.php b/language/english/blocksadmin.php new file mode 100644 index 0000000..c6c47d1 --- /dev/null +++ b/language/english/blocksadmin.php @@ -0,0 +1,44 @@ +Disabled (No thumbnails available)"); -\define('CO_' . $moduleDirNameUpper . '_GDON', "Enabled (Thumbsnails available)"); -\define('CO_' . $moduleDirNameUpper . '_IMAGEINFO', 'Server status'); -\define('CO_' . $moduleDirNameUpper . '_MAXPOSTSIZE', 'Max post size permitted (post_max_size directive in php.ini): '); -\define('CO_' . $moduleDirNameUpper . '_MAXUPLOADSIZE', 'Max upload size permitted (upload_max_filesize directive in php.ini): '); -\define('CO_' . $moduleDirNameUpper . '_MEMORYLIMIT', 'Memory limit (memory_limit directive in php.ini): '); -\define('CO_' . $moduleDirNameUpper . '_METAVERSION', "Downloads meta version: "); -\define('CO_' . $moduleDirNameUpper . '_OFF', "OFF"); -\define('CO_' . $moduleDirNameUpper . '_ON', "ON"); -\define('CO_' . $moduleDirNameUpper . '_SERVERPATH', 'Server path to XOOPS root: '); -\define('CO_' . $moduleDirNameUpper . '_SERVERUPLOADSTATUS', 'Server uploads status: '); -\define('CO_' . $moduleDirNameUpper . '_SPHPINI', "Information taken from PHP ini file:"); -\define('CO_' . $moduleDirNameUpper . '_UPLOADPATHDSC', 'Note. Upload path *MUST* contain the full server path of your upload folder.'); +\define('CO_' . $moduleDirNameUpper . '_' . 'GDLIBSTATUS', 'GD library support: '); +\define('CO_' . $moduleDirNameUpper . '_' . 'GDLIBVERSION', 'GD Library version: '); +\define('CO_' . $moduleDirNameUpper . '_' . 'GDOFF', "Disabled (No thumbnails available)"); +\define('CO_' . $moduleDirNameUpper . '_' . 'GDON', "Enabled (Thumbsnails available)"); +\define('CO_' . $moduleDirNameUpper . '_' . 'IMAGEINFO', 'Server status'); +\define('CO_' . $moduleDirNameUpper . '_' . 'MAXPOSTSIZE', 'Max post size permitted (post_max_size directive in php.ini): '); +\define('CO_' . $moduleDirNameUpper . '_' . 'MAXUPLOADSIZE', 'Max upload size permitted (upload_max_filesize directive in php.ini): '); +\define('CO_' . $moduleDirNameUpper . '_' . 'MEMORYLIMIT', 'Memory limit (memory_limit directive in php.ini): '); +\define('CO_' . $moduleDirNameUpper . '_' . 'METAVERSION', "Downloads meta version: "); +\define('CO_' . $moduleDirNameUpper . '_' . 'OFF', "OFF"); +\define('CO_' . $moduleDirNameUpper . '_' . 'ON', "ON"); +\define('CO_' . $moduleDirNameUpper . '_' . 'SERVERPATH', 'Server path to XOOPS root: '); +\define('CO_' . $moduleDirNameUpper . '_' . 'SERVERUPLOADSTATUS', 'Server uploads status: '); +\define('CO_' . $moduleDirNameUpper . '_' . 'SPHPINI', "Information taken from PHP ini file:"); +\define('CO_' . $moduleDirNameUpper . '_' . 'UPLOADPATHDSC', 'Note. Upload path *MUST* contain the full server path of your upload folder.'); \define('CO_' . $moduleDirNameUpper . '_PRINT', "Print"); \define('CO_' . $moduleDirNameUpper . '_PDF', "Create PDF"); -\define('CO_' . $moduleDirNameUpper . '_UPGRADEFAILED0', "Update failed - couldn't rename field '%s'"); -\define('CO_' . $moduleDirNameUpper . '_UPGRADEFAILED1', "Update failed - couldn't add new fields"); -\define('CO_' . $moduleDirNameUpper . '_UPGRADEFAILED2', "Update failed - couldn't rename table '%s'"); -\define('CO_' . $moduleDirNameUpper . '_ERROR_COLUMN', 'Could not create column in database : %s'); -\define('CO_' . $moduleDirNameUpper . '_ERROR_BAD_XOOPS', 'This module requires XOOPS %s+ (%s installed)'); -\define('CO_' . $moduleDirNameUpper . '_ERROR_BAD_PHP', 'This module requires PHP version %s+ (%s installed)'); -\define('CO_' . $moduleDirNameUpper . '_ERROR_TAG_REMOVAL', 'Could not remove tags from Tag Module'); +\define('CO_' . $moduleDirNameUpper . '_' . 'UPGRADEFAILED0', "Update failed - couldn't rename field '%s'"); +\define('CO_' . $moduleDirNameUpper . '_' . 'UPGRADEFAILED1', "Update failed - couldn't add new fields"); +\define('CO_' . $moduleDirNameUpper . '_' . 'UPGRADEFAILED2', "Update failed - couldn't rename table '%s'"); +\define('CO_' . $moduleDirNameUpper . '_' . 'ERROR_COLUMN', 'Could not create column in database : %s'); +\define('CO_' . $moduleDirNameUpper . '_' . 'ERROR_BAD_XOOPS', 'This module requires XOOPS %s+ (%s installed)'); +\define('CO_' . $moduleDirNameUpper . '_' . 'ERROR_BAD_PHP', 'This module requires PHP version %s+ (%s installed)'); +\define('CO_' . $moduleDirNameUpper . '_' . 'ERROR_TAG_REMOVAL', 'Could not remove tags from Tag Module'); -\define('CO_' . $moduleDirNameUpper . '_FOLDERS_DELETED_OK', 'Upload Folders have been deleted'); +\define('CO_' . $moduleDirNameUpper . '_' . 'FOLDERS_DELETED_OK', 'Upload Folders have been deleted'); // Error Msgs -\define('CO_' . $moduleDirNameUpper . '_ERROR_BAD_DEL_PATH', 'Could not delete %s directory'); -\define('CO_' . $moduleDirNameUpper . '_ERROR_BAD_REMOVE', 'Could not delete %s'); -\define('CO_' . $moduleDirNameUpper . '_ERROR_NO_PLUGIN', 'Could not load plugin'); +\define('CO_' . $moduleDirNameUpper . '_' . 'ERROR_BAD_DEL_PATH', 'Could not delete %s directory'); +\define('CO_' . $moduleDirNameUpper . '_' . 'ERROR_BAD_REMOVE', 'Could not delete %s'); +\define('CO_' . $moduleDirNameUpper . '_' . 'ERROR_NO_PLUGIN', 'Could not load plugin'); //Help -\define('CO_' . $moduleDirNameUpper . '_DIRNAME', basename(dirname(__DIR__, 2))); -\define('CO_' . $moduleDirNameUpper . '_HELP_HEADER', __DIR__ . '/help/helpheader.tpl'); -\define('CO_' . $moduleDirNameUpper . '_BACK_2_ADMIN', 'Back to Administration of '); -\define('CO_' . $moduleDirNameUpper . '_OVERVIEW', 'Overview'); +\define('CO_' . $moduleDirNameUpper . '_' . 'DIRNAME', basename(dirname(__DIR__, 2))); +\define('CO_' . $moduleDirNameUpper . '_' . 'HELP_HEADER', __DIR__ . '/help/helpheader.tpl'); +\define('CO_' . $moduleDirNameUpper . '_' . 'BACK_2_ADMIN', 'Back to Administration of '); +\define('CO_' . $moduleDirNameUpper . '_' . 'OVERVIEW', 'Overview'); //\define('CO_' . $moduleDirNameUpper . '_HELP_DIR', __DIR__); //help multipage -\define('CO_' . $moduleDirNameUpper . '_DISCLAIMER', 'Disclaimer'); -\define('CO_' . $moduleDirNameUpper . '_LICENSE', 'License'); -\define('CO_' . $moduleDirNameUpper . '_SUPPORT', 'Support'); +\define('CO_' . $moduleDirNameUpper . '_' . 'DISCLAIMER', 'Disclaimer'); +\define('CO_' . $moduleDirNameUpper . '_' . 'LICENSE', 'License'); +\define('CO_' . $moduleDirNameUpper . '_' . 'SUPPORT', 'Support'); //Sample Data \define('CO_' . $moduleDirNameUpper . '_' . 'LOAD_SAMPLEDATA', 'Import Sample Data (will delete ALL current data)'); @@ -227,4 +227,4 @@ //TCPDF \define('CO_' . $moduleDirNameUpper . '_' . 'ERROR_NO_PDF', 'TCPDF for XOOPS is not installed in /class/libraries/vendor/tecnickcom/tcpdf/
Please read the /docs/readme.txt or click on the Help tab to learn how to get it!'); -\define('CO_' . $moduleDirNameUpper . '_UPGRADEFAILED4', "Update failed - couldn't update column '%s'"); +\define('CO_' . $moduleDirNameUpper . '_' . 'UPGRADEFAILED4', "Update failed - couldn't update column '%s'"); diff --git a/language/english/directorychecker.php b/language/english/directorychecker.php new file mode 100644 index 0000000..9cc14eb --- /dev/null +++ b/language/english/directorychecker.php @@ -0,0 +1,23 @@ +Available"); +define('CO_' . $moduleDirNameUpper . '_' . 'DC_NOTAVAILABLE', "Not available"); +define('CO_' . $moduleDirNameUpper . '_' . 'DC_NOTWRITABLE', "Should have permission ( %d ), but it has ( %d )"); +define('CO_' . $moduleDirNameUpper . '_' . 'DC_CREATETHEDIR', 'Create it'); +define('CO_' . $moduleDirNameUpper . '_' . 'DC_SETMPERM', 'Set the permission'); +define('CO_' . $moduleDirNameUpper . '_' . 'DC_DIRCREATED', 'The directory has been created'); +define('CO_' . $moduleDirNameUpper . '_' . 'DC_DIRNOTCREATED', 'The directory cannot be created'); +define('CO_' . $moduleDirNameUpper . '_' . 'DC_PERMSET', 'The permission has been set'); +define('CO_' . $moduleDirNameUpper . '_' . 'DC_PERMNOTSET', 'The permission cannot be set'); diff --git a/language/english/filechecker.php b/language/english/filechecker.php new file mode 100644 index 0000000..3ad999a --- /dev/null +++ b/language/english/filechecker.php @@ -0,0 +1,24 @@ +Available"); +define('CO_' . $moduleDirNameUpper . '_' . 'FC_NOTAVAILABLE', "Not available"); +define('CO_' . $moduleDirNameUpper . '_' . 'FC_NOTWRITABLE', "Should have permission ( %d ), but it has ( %d )"); +define('CO_' . $moduleDirNameUpper . '_' . 'FC_COPYTHEFILE', 'Copy it'); +define('CO_' . $moduleDirNameUpper . '_' . 'FC_CREATETHEFILE', 'Create it'); +define('CO_' . $moduleDirNameUpper . '_' . 'FC_SETMPERM', 'Set the permission'); +define('CO_' . $moduleDirNameUpper . '_' . 'FC_FILECOPIED', 'The file has been copied'); +define('CO_' . $moduleDirNameUpper . '_' . 'FC_FILENOTCOPIED', 'The file cannot be copied'); +define('CO_' . $moduleDirNameUpper . '_' . 'FC_PERMSET', 'The permission has been set'); +define('CO_' . $moduleDirNameUpper . '_' . 'FC_PERMNOTSET', 'The permission cannot be set'); diff --git a/language/english/help/helpheader.tpl b/language/english/help/helpheader.tpl index 5776d5b..52355b0 100644 --- a/language/english/help/helpheader.tpl +++ b/language/english/help/helpheader.tpl @@ -1,6 +1,6 @@

Help: <{$smarty.const._MI_NEWS_NAME}> - <{$smarty.const._MI_NEWS_BACK_2_ADMIN}> <{$smarty.const._MI_NEWS_NAME}>

diff --git a/list.tag.php b/list.tag.php index 0ee6464..de3e276 100644 --- a/list.tag.php +++ b/list.tag.php @@ -25,11 +25,13 @@ * @copyright (c) Hervé Thouzard (https://www.herve-thouzard.com) */ -use XoopsModules\News; +use XoopsModules\News\{ + Utility +}; require_once __DIR__ . '/header.php'; -if (!News\Utility::getModuleOption('tags') || !xoops_isActiveModule('tag')) { +if (!Utility::getModuleOption('tags') || !xoops_isActiveModule('tag')) { redirect_header('index.php', 2, _ERRORS); } require_once XOOPS_ROOT_PATH . '/modules/tag/list.tag.php'; diff --git a/makepdf.php b/makepdf.php index 0fbd4d6..b84d873 100644 --- a/makepdf.php +++ b/makepdf.php @@ -31,7 +31,7 @@ //2.5.8 $helper = Helper::getInstance(); -if (is_file(XOOPS_ROOT_PATH . '/class/libraries/vendor/tecnickcom/tcpdf/tcpdf.php')) { +if (\is_file(XOOPS_ROOT_PATH . '/class/libraries/vendor/tecnickcom/tcpdf/tcpdf.php')) { require_once XOOPS_ROOT_PATH . '/class/libraries/vendor/tecnickcom/tcpdf/tcpdf.php'; } else { redirect_header($helper->url('index.php'), 3, \constant('CO_' . $moduleDirNameUpper . '_' . 'ERROR_NO_PDF')); @@ -98,15 +98,15 @@ //$pdf->setLanguageArray($localLanguageOptions); -$pdf->SetCreator(PDF_CREATOR); +$pdf->setCreator(PDF_CREATOR); -$pdf->SetTitle($pdf_data['title']); -$pdf->SetAuthor(PDF_AUTHOR); -$pdf->SetSubject($pdf_data['author']); +$pdf->setTitle($pdf_data['title']); +$pdf->setAuthor(PDF_AUTHOR); +$pdf->setSubject($pdf_data['author']); $out = PDF_AUTHOR . ', ' . $pdf_data['author'] . ', ' . $pdf_data['title'] . ', ' . $pdf_data['subtitle'] . ', ' . $pdf_data['subsubtitle']; -$pdf->SetKeywords($out); -$pdf->SetAutoPageBreak(true, 25); -$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); +$pdf->setKeywords($out); +$pdf->setAutoPageBreak(true, 25); +$pdf->setMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); $pdf->setFooterMargin(PDF_MARGIN_FOOTER); //$pdf->setHeaderFont(array(PDF_FONT_NAME_SUB, '', PDF_FONT_SIZE_SUB)); $pdf->setFooterFont([PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA]); @@ -114,15 +114,15 @@ //$pdf->SetHeaderData('','5',$pdf_config['slogan']); $pdf->setHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, $pdf_config['slogan'], [0, 64, 255], [0, 64, 128]); //set margins -$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); +$pdf->setMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); $pdf->setHeaderMargin(PDF_MARGIN_HEADER); $pdf->setFooterMargin(PDF_MARGIN_FOOTER); $pdf->Open(); //First page $pdf->AddPage(); -$pdf->SetXY(24, 25); -$pdf->SetTextColor(10, 60, 160); +$pdf->setXY(24, 25); +$pdf->setTextColor(10, 60, 160); //$pdf->SetFont(PDF_FONT_NAME_TITLE, PDF_FONT_STYLE_TITLE, PDF_FONT_SIZE_TITLE); $pdf->writeHTML($pdf_data['title'] . ' - ' . $pdf_data['subtitle'], K_TITLE_MAGNIFICATION); //$pdf->Line(25,20,190,20); @@ -137,7 +137,7 @@ $pdf->writeHTML($out, '0.2'); $out = NEWS_PDF_DATE . ': ' . $pdf_data['date'] . '
'; $pdf->writeHTML($out, '0.2'); -$pdf->SetTextColor(0, 0, 0); +$pdf->setTextColor(0, 0, 0); $pdf->writeHTML($puffer, '1'); //$pdf->SetFont(PDF_FONT_NAME_MAIN, PDF_FONT_STYLE_MAIN, PDF_FONT_SIZE_MAIN); diff --git a/micro_summary.php b/micro_summary.php index 2408082..dcc846b 100644 --- a/micro_summary.php +++ b/micro_summary.php @@ -29,16 +29,18 @@ * */ -use XoopsModules\News; -use XoopsModules\News\NewsStory; +use XoopsModules\News\{ + NewsStory, + Utility +}; require_once \dirname(__DIR__, 2) . '/mainfile.php'; // require_once XOOPS_ROOT_PATH . '/modules/news/class/class.newsstory.php'; -if (!News\Utility::getModuleOption('firefox_microsummaries')) { +if (!Utility::getModuleOption('firefox_microsummaries')) { exit(); } $story = new NewsStory(); -$restricted = News\Utility::getModuleOption('restrictindex'); +$restricted = Utility::getModuleOption('restrictindex'); $sarray = []; // Get the last news from all topics according to the module's restrictions $sarray = NewsStory::getAllPublished(1, 0, $restricted, 0); diff --git a/newsbythisauthor.php b/newsbythisauthor.php index bf0ffe2..f1b37fe 100644 --- a/newsbythisauthor.php +++ b/newsbythisauthor.php @@ -66,20 +66,23 @@ */ use Xmf\Request; -use XoopsModules\News; -use XoopsModules\News\NewsStory; +use XoopsModules\News\{ + Helper, + NewsStory, + Utility +}; require_once \dirname(__DIR__, 2) . '/mainfile.php'; //require_once XOOPS_ROOT_PATH . '/modules/news/class/class.newsstory.php'; //require_once XOOPS_ROOT_PATH . '/modules/news/class/class.newstopic.php'; //require_once XOOPS_ROOT_PATH . '/modules/news/class/class.sfiles.php'; -/** @var News\Helper $helper */ -$helper = News\Helper::getInstance(); +/** @var Helper $helper */ +$helper = Helper::getInstance(); global $xoopsUser; -$helper = News\Helper::getInstance(); +$helper = Helper::getInstance(); $helper->loadLanguage('modinfo'); $uid = Request::getInt('uid', 0, 'GET'); @@ -87,7 +90,7 @@ redirect_header('index.php', 2, _ERRORS); } -if (!News\Utility::getModuleOption('newsbythisauthor')) { +if (!Utility::getModuleOption('newsbythisauthor')) { redirect_header('index.php', 2, _ERRORS); } @@ -96,8 +99,8 @@ $GLOBALS['xoopsOption']['template_main'] = 'news_by_this_author.tpl'; require_once XOOPS_ROOT_PATH . '/header.php'; -$dateformat = News\Utility::getModuleOption('dateformat'); -$infotips = News\Utility::getModuleOption('infotips'); +$dateformat = Utility::getModuleOption('dateformat'); +$infotips = Utility::getModuleOption('infotips'); $thisuser = new \XoopsUser($uid); switch ($helper->getConfig('displayname')) { @@ -123,7 +126,7 @@ $xoopsTpl->assign('lang_date', _NW_DATE); $xoopsTpl->assign('lang_hits', _NW_VIEWS); $xoopsTpl->assign('lang_title', _NW_TITLE); -$xoopsTpl->assign('news_rating', News\Utility::getModuleOption('ratenews')); +$xoopsTpl->assign('news_rating', Utility::getModuleOption('ratenews')); $xoopsTpl->assign('lang_rating', _NW_RATING); $xoopsTpl->assign('author_name_with_link', sprintf("%s", XOOPS_URL . '/userinfo.php?uid=' . $uid, $authname)); @@ -163,7 +166,7 @@ } $htmltitle = ''; if ($infotips > 0) { - $htmltitle = ' title="' . News\Utility::makeInfotips($article['hometext']) . '"'; + $htmltitle = ' title="' . Utility::makeInfotips($article['hometext']) . '"'; } ++$count_articles; $count_reads += $article['counter']; @@ -190,12 +193,12 @@ ] ); $xoopsTpl->assign('xoops_pagetitle', _MI_NEWSBYTHISAUTHOR . ' - ' . $authname . ' - ' . htmlspecialchars($xoopsModule->name(), ENT_QUOTES | ENT_HTML5)); -$xoopsTpl->assign('advertisement', News\Utility::getModuleOption('advertisement')); +$xoopsTpl->assign('advertisement', Utility::getModuleOption('advertisement')); /** * Create the meta datas */ -News\Utility::createMetaDatas(); +Utility::createMetaDatas(); $meta_description = _MI_NEWSBYTHISAUTHOR . ' - ' . $authname . ' - ' . $xoopsModule->name('s'); if (isset($xoTheme) && is_object($xoTheme)) { diff --git a/preloads/autoloader.php b/preloads/autoloader.php index f8de47d..2b465e9 100644 --- a/preloads/autoloader.php +++ b/preloads/autoloader.php @@ -6,13 +6,13 @@ spl_autoload_register( static function ($class): void { // project-specific namespace prefix - $prefix = 'XoopsModules\\' . ucfirst(basename(dirname(__DIR__))); + $prefix = 'XoopsModules\\' . \ucfirst(\basename(\dirname(__DIR__))); // base directory for the namespace prefix $baseDir = \dirname(__DIR__) . '/class/'; // does the class use the namespace prefix? - $len = mb_strlen($prefix); + $len = \mb_strlen($prefix); if (0 !== strncmp($prefix, $class, $len)) { return; @@ -24,10 +24,10 @@ static function ($class): void { // replace the namespace prefix with the base directory, replace namespace // separators with directory separators in the relative class name, append // with .php - $file = $baseDir . str_replace('\\', '/', $relativeClass) . '.php'; + $file = $baseDir . \str_replace('\\', '/', $relativeClass) . '.php'; // if the file exists, require it - if (is_file($file)) { + if (\is_file($file)) { require_once $file; } } diff --git a/preloads/core.php b/preloads/core.php index 29c14b6..e07054a 100644 --- a/preloads/core.php +++ b/preloads/core.php @@ -22,9 +22,9 @@ class NewsCorePreload extends \XoopsPreloadItem { // to add PSR-4 autoloader /** - * @param $args + * @param array $args */ - public static function eventCoreIncludeCommonEnd($args): void + public static function eventCoreIncludeCommonEnd(array $args): void { require_once __DIR__ . '/autoloader.php'; } diff --git a/print.php b/print.php index 71279d7..8f9e7ff 100644 --- a/print.php +++ b/print.php @@ -33,8 +33,10 @@ */ use Xmf\Request; -use XoopsModules\News; -use XoopsModules\News\NewsStory; +use XoopsModules\News\{ + NewsStory, + Utility +}; require_once \dirname(__DIR__, 2) . '/mainfile.php'; // require_once XOOPS_ROOT_PATH . '/modules/news/class/class.newsstory.php'; @@ -73,7 +75,7 @@ if ('' !== trim($story->keywords())) { $xoops_meta_keywords = $story->keywords(); } else { - $xoops_meta_keywords = News\Utility::createMetaKeywords($story->hometext() . ' ' . $story->bodytext()); + $xoops_meta_keywords = Utility::createMetaKeywords($story->hometext() . ' ' . $story->bodytext()); } if ('' !== trim($story->description())) { @@ -86,7 +88,7 @@ function PrintPage(): void { global $xoopsConfig, $xoopsModule, $story, $xoops_meta_keywords, $xoops_meta_description; $myts = \MyTextSanitizer::getInstance(); - $datetime = formatTimestamp($story->published(), News\Utility::getModuleOption('dateformat')); ?> + $datetime = formatTimestamp($story->published(), Utility::getModuleOption('dateformat')); ?> '; $supplemental = ''; - if (News\Utility::getModuleOption('footNoteLinks')) { + if (Utility::getModuleOption('footNoteLinks')) { $supplemental = "footnoteLinks('content','content'); "; ?> -
  • @@ -193,7 +193,7 @@ <{if $fbcomments === true}>
    - <{/if}> diff --git a/templates/news_by_this_author.tpl b/templates/news_by_this_author.tpl index 9f63676..ba7ae6b 100644 --- a/templates/news_by_this_author.tpl +++ b/templates/news_by_this_author.tpl @@ -3,32 +3,32 @@

  • <' . $counter . '
    - <{foreach item=topic from=$topics}> + <{foreach item=topic from=$topics|default:null}> - <{if $news_rating}> + <{if isset($news_rating)}> - <{if $news_rating}> + <{if isset($news_rating)}> <{/if}> - <{foreach item=article from=$topic.news}> + <{foreach item=article from=$topic.news|default:null}> - <{if $news_rating}> + <{if isset($news_rating)}> <{/if}> <{/foreach}> - <{if $news_rating}> + <{if isset($news_rating)}> <{/if}> - <{if $news_rating}> + <{if isset($news_rating)}> diff --git a/templates/news_by_topic.tpl b/templates/news_by_topic.tpl index e0cc4e2..78ef77c 100644 --- a/templates/news_by_topic.tpl +++ b/templates/news_by_topic.tpl @@ -3,13 +3,13 @@ <{section name=i loop=$columns}>
    <{else}> <{/if}><{$topic.topic_link}>
    <{$lang_date}> <{$lang_title}><{$lang_hits}><{$lang_hits}><{$lang_rating}>
    <{$article.published}> <{$article.article_link}><{$article.hits}><{$article.hits}><{$article.rating}>
    <{$topic.topic_count_articles}><{$topic.topic_count_reads}><{$topic.topic_count_reads}> 
    <{else}> <{/if}> 
    - <{foreach item=topic from=$columns[i]}> + <{foreach item=topic from=$columns[i]|default:null}>
    <{$topic.title}> + href="<{$xoops_url}>/modules/<{$xoops_dirname}>/index.php?storytopic=<{$topic.id}>"><{$topic.title}>
    <{counter start=0 print=false assign=storynum}> - <{foreach item=story from=$topic.stories}> + <{foreach item=story from=$topic.stories|default:null}> <{if $storynum == 0}> <{include file="db:news_item.tpl" story=$story}>
    <{else}> @@ -17,7 +17,7 @@
      <{/if}>
    • <{$story.title}> + href="<{$xoops_url}>/modules/<{$xoops_dirname}>/article.php?storyid=<{$story.id}>"><{$story.title}> (<{$story.posttime}>)
    • <{/if}> @@ -26,7 +26,7 @@
    <{if $storynum > 1}> <{$lang_morereleases}><{$topic.title}> + href="<{$xoops_url}>/modules/<{$xoops_dirname}>/index.php?storytopic=<{$topic.id}>"><{$lang_morereleases}><{$topic.title}> <{/if}>
    <{/foreach}> diff --git a/templates/news_index.tpl b/templates/news_index.tpl index 9567480..bf55d5e 100644 --- a/templates/news_index.tpl +++ b/templates/news_index.tpl @@ -5,7 +5,7 @@ <{if $displaynav === true}>
    -
    + <{$topic_select}>

    @@ -20,7 +20,7 @@ <{section name=i loop=$columns}> - + <{/section}>
    <{foreach item=story from=$columns[i]}><{include file="db:news_item.tpl" story=$story}><{/foreach}><{foreach item=story from=$columns[i]|default:null}><{include file="db:news_item.tpl" story=$story}><{/foreach}>
    diff --git a/templates/news_item.tpl b/templates/news_item.tpl index 3f94a68..692d13e 100644 --- a/templates/news_item.tpl +++ b/templates/news_item.tpl @@ -1,7 +1,8 @@
    - <{if $displaytopictitle === true}> <{$story.topic_title}> -   <{/if}>

    <{$story.news_title}>

    + <{if $displaytopictitle === true}> <{$story.topic_title}> <{/if}> +

    <{$story.news_title}>

    <{$story.subtitle|default:''}>
    @@ -25,10 +26,10 @@
    <{$story.adminlink}> - <{if $rates}><{$lang_ratingc}> <{$story.rating}> (<{$story.votes}>) - - <{$lang_ratethisnews}> - - <{/if}> + <{if isset($rates)}><{$lang_ratingc|default:''}> <{$story.rating|default:''}> <{$story.votes|default:''}> + <{$lang_ratethisnews|default:''}> + <{/if}> <{$story.morelink}>
    diff --git a/templates/news_ratenews.tpl b/templates/news_ratenews.tpl index 98f5318..53e2bb2 100644 --- a/templates/news_ratenews.tpl +++ b/templates/news_ratenews.tpl @@ -10,8 +10,8 @@
    -
    - <{securityToken}><{*//mb*}> + + <{securityToken}>    + onclick="location='<{$xoops_url}>/modules/<{$xoops_dirname}>/article.php?storyid=<{$news.storyid}>'">
    diff --git a/templates/news_rss.tpl b/templates/news_rss.tpl index 20feb0a..f89627e 100644 --- a/templates/news_rss.tpl +++ b/templates/news_rss.tpl @@ -20,7 +20,7 @@ <{$image_height}> <{/if}> - <{foreach item=item from=$items}> + <{foreach item=item from=$items|default:null}> <{$item.title}> <{$item.link}> diff --git a/templates/news_topics_directory.tpl b/templates/news_topics_directory.tpl index 2020756..1f11186 100644 --- a/templates/news_topics_directory.tpl +++ b/templates/news_topics_directory.tpl @@ -5,7 +5,7 @@
      <{foreach item=topic from=$topics}>
    • <{$topic.prefix}><{$topic.title}> + href="<{$xoops_url}>/modules/<{$xoops_dirname}>/index.php?storytopic=<{$topic.id}>"><{$topic.title}> (<{$topic.news_count}>)
    • <{/foreach}> diff --git a/templates/news_whos_who.tpl b/templates/news_whos_who.tpl index f47d524..65772a4 100644 --- a/templates/news_whos_who.tpl +++ b/templates/news_whos_who.tpl @@ -5,7 +5,7 @@
        <{foreach item=who from=$whoswho}>
      • <{$who.name}>
      • + href="<{$xoops_url}>/modules/<{$xoops_dirname}>/newsbythisauthor.php?uid=<{$who.uid}>"><{$who.name}> <{/foreach}>
      diff --git a/testdata/index.php b/testdata/index.php index 03f6922..ecae985 100644 --- a/testdata/index.php +++ b/testdata/index.php @@ -99,7 +99,7 @@ function loadSampleData(): void loadTableFromArrayWithReplace($table, $tabledata, 'gperm_modid', $mid); // --- COPY test folder files --------------- - if (is_array($configurator->copyTestFolders) && count($configurator->copyTestFolders) > 0) { + if ($configurator->copyTestFolders && \is_array($configurator->copyTestFolders)) { // $file = \dirname(__DIR__) . '/testdata/images/'; foreach (array_keys($configurator->copyTestFolders) as $i) { $src = $configurator->copyTestFolders[$i][0]; @@ -159,16 +159,16 @@ function exportSchema(): void /** * loadTableFromArrayWithReplace * - * @param string $table value with should be used insead of original value of $search + * @param string $table value which should be used instead of original value of $search * * @param array $data array of rows to insert * Each element of the outer array represents a single table row. * Each row is an associative array in 'column' => 'value' format. * @param string $search name of column for which the value should be replaced - * @param $replace + * @param int $replace * @return int number of rows inserted */ -function loadTableFromArrayWithReplace($table, $data, $search, $replace) +function loadTableFromArrayWithReplace(string $table, array $data, string $search, int $replace): int { /** @var \XoopsMySQLDatabase $db */ $db = \XoopsDatabaseFactory::getDatabaseConnection(); diff --git a/topics_directory.php b/topics_directory.php index 98d64f1..337932a 100644 --- a/topics_directory.php +++ b/topics_directory.php @@ -25,8 +25,11 @@ * @copyright (c) Hervé Thouzard - https://www.herve-thouzard.com */ -use XoopsModules\News; -use XoopsModules\News\NewsTopic; +use XoopsModules\News\{ + Helper, + NewsTopic, + Utility +}; require_once \dirname(__DIR__, 2) . '/mainfile.php'; //require_once XOOPS_ROOT_PATH . '/modules/news/class/class.newsstory.php'; @@ -40,7 +43,7 @@ $newscountbytopic = $tbl_topics = []; $perms = ''; $xt = new NewsTopic(); -$restricted = News\Utility::getModuleOption('restrictindex'); +$restricted = Utility::getModuleOption('restrictindex'); if ($restricted) { global $xoopsUser; /** @var \XoopsModuleHandler $moduleHandler */ @@ -59,7 +62,7 @@ } $topics_arr = $xt->getChildTreeArray(0, 'topic_title', $perms); $newscountbytopic = $xt->getNewsCountByTopic(); -if (is_array($topics_arr) && count($topics_arr)) { +if ($topics_arr && \is_array($topics_arr)) { foreach ($topics_arr as $onetopic) { $count = 0; if (array_key_exists($onetopic['topic_id'], $newscountbytopic)) { @@ -82,12 +85,12 @@ } $xoopsTpl->assign('topics', $tbl_topics); -$xoopsTpl->assign('advertisement', News\Utility::getModuleOption('advertisement')); +$xoopsTpl->assign('advertisement', Utility::getModuleOption('advertisement')); /** - * Manage all the meta datas + * Manage all the metadatas */ -News\Utility::createMetaDatas(); +Utility::createMetaDatas(); $xoopsTpl->assign('xoops_pagetitle', _AM_NEWS_TOPICS_DIRECTORY); $meta_description = _AM_NEWS_TOPICS_DIRECTORY . ' - ' . $xoopsModule->name('s'); diff --git a/view.tag.php b/view.tag.php index 6f074c1..fce5540 100644 --- a/view.tag.php +++ b/view.tag.php @@ -29,7 +29,7 @@ require_once __DIR__ . '/header.php'; -if (!News\Utility::getModuleOption('tags') || !xoops_isActiveModule('tag')) { +if (!Utility::getModuleOption('tags') || !xoops_isActiveModule('tag')) { redirect_header('index.php', 2, _ERRORS); } require_once XOOPS_ROOT_PATH . '/modules/tag/view.tag.php'; diff --git a/visit.php b/visit.php index 2ba5ccc..d449b19 100644 --- a/visit.php +++ b/visit.php @@ -16,8 +16,10 @@ */ use Xmf\Request; -use XoopsModules\News\Files; -use XoopsModules\News\NewsStory; +use XoopsModules\News\{ + Files, + NewsStory +}; require_once \dirname(__DIR__, 2) . '/mainfile.php'; // require_once XOOPS_ROOT_PATH . '/modules/news/class/class.sfiles.php'; diff --git a/whoswho.php b/whoswho.php index 0053181..02e52c3 100644 --- a/whoswho.php +++ b/whoswho.php @@ -25,25 +25,27 @@ * @copyright (c) Hervé Thouzard (https://www.herve-thouzard.com) */ -use XoopsModules\News; -use XoopsModules\News\NewsStory; +use XoopsModules\News\{ + NewsStory, + Utility +}; require_once \dirname(__DIR__, 2) . '/mainfile.php'; //require_once XOOPS_ROOT_PATH . '/modules/news/class/class.newsstory.php'; //require_once XOOPS_ROOT_PATH . '/modules/news/class/class.newstopic.php'; //require_once XOOPS_ROOT_PATH . '/modules/news/class/class.sfiles.php'; -if (!News\Utility::getModuleOption('newsbythisauthor')) { +if (!Utility::getModuleOption('newsbythisauthor')) { redirect_header('index.php', 2, _ERRORS); } $GLOBALS['xoopsOption']['template_main'] = 'news_whos_who.tpl'; require_once XOOPS_ROOT_PATH . '/header.php'; -$option = News\Utility::getModuleOption('displayname'); +$option = Utility::getModuleOption('displayname'); $article = new NewsStory(); $uid_ids = []; -$uid_ids = $article->getWhosWho(News\Utility::getModuleOption('restrictindex')); +$uid_ids = $article->getWhosWho(Utility::getModuleOption('restrictindex')); if (count($uid_ids) > 0) { $lst_uid = implode(',', $uid_ids); /** @var \XoopsMemberHandler $memberHandler */ @@ -75,12 +77,12 @@ } } -$xoopsTpl->assign('advertisement', News\Utility::getModuleOption('advertisement')); +$xoopsTpl->assign('advertisement', Utility::getModuleOption('advertisement')); /** * Manage all the meta datas */ -News\Utility::createMetaDatas($article); +Utility::createMetaDatas($article); $xoopsTpl->assign('xoops_pagetitle', _AM_NEWS_WHOS_WHO); $myts = \MyTextSanitizer::getInstance(); diff --git a/xoops_version.php b/xoops_version.php index 197cba2..821572b 100644 --- a/xoops_version.php +++ b/xoops_version.php @@ -15,20 +15,23 @@ * @author XOOPS Development Team */ -use XoopsModules\News; -use XoopsModules\News\NewsTopic; +use XoopsModules\News\{ + Helper, + NewsTopic, + Utility +}; require_once __DIR__ . '/preloads/autoloader.php'; -/** @var News\Helper $helper */ -$helper = News\Helper::getInstance(); +/** @var Helper $helper */ +$helper = Helper::getInstance(); $helper->loadLanguage('common'); $moduleDirName = basename(__DIR__); $moduleDirNameUpper = \mb_strtoupper($moduleDirName); -$modversion['version'] = '1.72.0'; -$modversion['module_status'] = 'Beta 6'; -$modversion['release_date'] = '2022/10/24'; +$modversion['version'] = '1.73.0'; +$modversion['module_status'] = 'Beta 3'; +$modversion['release_date'] = '2025/01/16'; $modversion['name'] = _MI_NEWS_NAME; $modversion['description'] = _MI_NEWS_DESC; $modversion['credits'] = 'XOOPS Project, Christian, Pilou, Marco,
      ALL the members of the Newbb Team, GIJOE, Zoullou, Mithrandir,
      Setec Astronomy, Marcan, 5vision, Anne, Trabis, dhsoft, Mamba, Mage, Timgno'; @@ -44,15 +47,16 @@ //$modversion['icons16'] = '../../Frameworks/moduleclasses/icons/16'; //$modversion['icons32'] = '../../Frameworks/moduleclasses/icons/32'; $modversion['onInstall'] = 'include/install_function.php'; -$modversion['onUpdate'] = 'include/update_function.php'; +//$modversion['onUpdate'] = 'include/update_function.php'; +$modversion['onUpdate'] = 'include/onupdate.php'; $modversion['module_website_url'] = 'www.xoops.org/'; $modversion['module_website_name'] = 'XOOPS'; $modversion['author_website_url'] = 'https://xoops.org/'; $modversion['author_website_name'] = 'XOOPS'; $modversion['min_php'] = '7.4'; -$modversion['min_xoops'] = '2.5.10'; +$modversion['min_xoops'] = '2.5.11'; $modversion['min_admin'] = '1.2'; -$modversion['min_db'] = ['mysql' => '5.5']; +$modversion['min_db'] = ['mysql' => '5.7']; $modversion['sqlfile']['mysql'] = 'sql/mysql.sql'; @@ -230,7 +234,7 @@ // 2) If there's no topics to display as sub menus we can go on if (!isset($_SESSION['items_count']) || -1 == $_SESSION['items_count']) { $sql = 'SELECT COUNT(*) AS cpt FROM ' . $xoopsDB->prefix('news_topics') . ' WHERE menu=1'; - $result = $xoopsDB->query($sql); + $result = Utility::queryAndCheck($xoopsDB, $sql); [$count] = $xoopsDB->fetchRow($result); $_SESSION['items_count'] = $count; } else { @@ -240,7 +244,7 @@ require_once XOOPS_ROOT_PATH . '/class/tree.php'; // require_once XOOPS_ROOT_PATH . '/modules/news/class/class.newstopic.php'; $xt = new NewsTopic(); - $allTopics = $xt->getAllTopics(News\Utility::getModuleOption('restrictindex')); + $allTopics = $xt->getAllTopics(Utility::getModuleOption('restrictindex')); $topic_tree = new \XoopsObjectTree($allTopics, 'topic_id', 'topic_pid'); $topics_arr = $topic_tree->getAllChild(0); if ($module) { @@ -267,7 +271,7 @@ unset($cansubmit); //; -if (News\Utility::getModuleOption('newsbythisauthor')) { +if (Utility::getModuleOption('newsbythisauthor')) { ++$i; $modversion['sub'][$i]['name'] = _MI_NEWS_WHOS_WHO; $modversion['sub'][$i]['url'] = 'whoswho.php'; @@ -303,7 +307,7 @@ 'formtype' => 'select', 'valuetype' => 'int', 'default' => 5, - 'options' => ['5' => 5, '10' => 10, '15' => 15, '20' => 20, '25' => 25, '30' => 30], + 'options' => [5 => 5, 10 => 10, 15 => 15, 20 => 20, 25 => 25, 30 => 30], ]; /** * Format of the date to use in the module, if you don't specify anything then the default date's format will be used @@ -417,14 +421,14 @@ 'valuetype' => 'int', 'default' => 10, 'options' => [ - '5' => 5, - '10' => 10, - '15' => 15, - '20' => 20, - '25' => 25, - '30' => 30, - '35' => 35, - '40' => 40, + 5 => 5, + 10 => 10, + 15 => 15, + 20 => 20, + 25 => 25, + 30 => 30, + 35 => 35, + 40 => 40, ], ]; @@ -565,7 +569,7 @@ /** * If you set this option to yes then the approvers can type the keyword - * and description's meta datas + * and description's metadatas */ $modversion['config'][] = [ 'name' => 'metadata',