From 42c5114f9a7b007e345c8d288c0f7e50b996e78e Mon Sep 17 00:00:00 2001 From: mambax7 Date: Thu, 15 Mar 2018 19:22:24 -0400 Subject: [PATCH] updates --- .scrutinizer.yml | 7 + CONTRIBUTING.md | 2 +- README.md | 2 +- admin/admin_header.php | 2 +- admin/category.php | 16 +- admin/file.php | 12 +- admin/import/ams.php | 27 +- admin/import/cjaycontent.php | 13 +- admin/import/fmcontent.php | 27 +- admin/import/news.php | 21 +- admin/import/smartsection.php | 20 +- admin/import/wfsection.php | 23 +- admin/import/xfsection.php | 25 +- admin/import/xnews.php | 23 +- admin/item.php | 81 +- admin/main.php | 45 +- admin/menu.php | 2 +- admin/mimetypes.php | 66 +- admin/permissions.php | 55 +- archive.php | 8 +- author_items.php | 8 +- backend.php | 4 +- blocks/category_items_sel.php | 13 +- blocks/date_to_date.php | 10 +- blocks/items_columns.php | 12 +- blocks/items_menu.php | 10 +- blocks/items_new.php | 11 +- blocks/items_random_item.php | 7 +- blocks/items_recent.php | 11 +- blocks/items_spot.php | 16 +- blocks/latest_files.php | 11 +- blocks/latest_news.php | 9 +- blocks/search.php | 6 +- category.php | 14 +- class/BaseObjectHandler.php | 364 ++++ class/{blockform.php => BlockForm.php} | 8 +- class/Category.php | 356 +++ class/CategoryHandler.php | 409 ++++ class/{common => Common}/Breadcrumb.php | 6 +- class/{common => Common}/Configurator.php | 4 +- class/{common => Common}/FilesManagement.php | 24 +- class/{common => Common}/ServerStats.php | 2 +- class/{common => Common}/VersionChecks.php | 0 class/{common => Common}/index.html | 0 class/{constants.php => Constants.php} | 9 +- class/{file.php => File.php} | 180 +- class/FileHandler.php | 166 ++ .../category.php => Form/CategoryForm.php} | 30 +- class/{form/file.php => Form/FileForm.php} | 13 +- class/{form/item.php => Form/ItemForm.php} | 130 +- class/{form => Form}/index.html | 0 class/{formdatetime.php => FormDateTime.php} | 10 +- class/{groupperm.php => GroupPermHandler.php} | 10 +- class/Helper.php | 22 +- class/{highlighter.php => Highlighter.php} | 4 +- class/Item.php | 1087 ++++++++++ class/ItemHandler.php | 847 ++++++++ class/{metagen.php => Metagen.php} | 18 +- class/Mimetype.php | 57 + class/MimetypeHandler.php | 284 +++ .../{permission.php => PermissionHandler.php} | 20 +- class/{rating.php => Rating.php} | 24 +- class/RatingHandler.php | 36 + include/seo_functions.php => class/Seo.php | 11 +- class/{session.php => Session.php} | 12 +- class/{themetabform.php => ThemeTabForm.php} | 12 +- class/Utility.php | 164 +- class/category.php | 736 ------- class/item.php | 1905 ----------------- class/mimetype.php | 650 ------ class/plugins/plugin.tag.php | 11 +- comment_new.php | 2 +- docs/changelog.txt | 6 +- file.php | 12 +- footer.php | 2 +- header.php | 2 +- include/ajax_rating.php | 10 +- include/common.php | 38 +- include/config.php | 110 +- include/notification.inc.php | 10 +- include/oninstall.php | 4 +- include/onupdate.php | 8 +- include/plugin.tag.php | 2 +- include/search.inc.php | 6 +- include/seo.inc.php | 2 +- index.php | 17 +- item.php | 12 +- makepdf.php | 4 +- preloads/core.php | 4 +- print.php | 2 +- rate.php | 16 +- search.php | 5 +- sql/mysql.sql | 1 - submit.php | 34 +- templates/publisher_item.tpl | 7 +- testdata/index.php | 2 +- visit.php | 7 +- xoops_version.php | 17 +- 98 files changed, 4461 insertions(+), 4121 deletions(-) create mode 100644 class/BaseObjectHandler.php rename class/{blockform.php => BlockForm.php} (93%) create mode 100644 class/Category.php create mode 100644 class/CategoryHandler.php rename class/{common => Common}/Breadcrumb.php (91%) rename class/{common => Common}/Configurator.php (95%) rename class/{common => Common}/FilesManagement.php (91%) rename class/{common => Common}/ServerStats.php (98%) rename class/{common => Common}/VersionChecks.php (100%) rename class/{common => Common}/index.html (100%) rename class/{constants.php => Constants.php} (94%) rename class/{file.php => File.php} (55%) create mode 100644 class/FileHandler.php rename class/{form/category.php => Form/CategoryForm.php} (90%) rename class/{form/file.php => Form/FileForm.php} (92%) rename class/{form/item.php => Form/ItemForm.php} (85%) rename class/{form => Form}/index.html (100%) rename class/{formdatetime.php => FormDateTime.php} (89%) rename class/{groupperm.php => GroupPermHandler.php} (90%) rename class/{highlighter.php => Highlighter.php} (98%) create mode 100644 class/Item.php create mode 100644 class/ItemHandler.php rename class/{metagen.php => Metagen.php} (95%) create mode 100644 class/Mimetype.php create mode 100644 class/MimetypeHandler.php rename class/{permission.php => PermissionHandler.php} (89%) rename class/{rating.php => Rating.php} (69%) create mode 100644 class/RatingHandler.php rename include/seo_functions.php => class/Seo.php (96%) rename class/{session.php => Session.php} (92%) rename class/{themetabform.php => ThemeTabForm.php} (97%) delete mode 100644 class/category.php delete mode 100644 class/item.php delete mode 100644 class/mimetype.php diff --git a/.scrutinizer.yml b/.scrutinizer.yml index 2ece9394..c933b14f 100644 --- a/.scrutinizer.yml +++ b/.scrutinizer.yml @@ -1,3 +1,10 @@ +build: + nodes: + analysis: + project_setup: + override: true + tests: + override: [php-scrutinizer-run] checks: php: code_rating: true diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0d8e30b9..0e5885b5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,7 +1,7 @@ ![alt XOOPS CMS](https://xoops.org/images/logoXoops4GithubRepository.png) # Contributing to [XOOPS CMS](https://xoops.org) [![XOOPS CMS Module](https://img.shields.io/badge/XOOPS%20CMS-Module-blue.svg)](https://xoops.org) -[![Software License](https://img.shields.io/badge/license-GPL-brightgreen.svg?style=flat)](LICENSE) +[![Software License](https://img.shields.io/badge/license-GPL-brightgreen.svg?style=flat)](http://www.gnu.org/licenses/gpl-2.0.html) Contributions are **welcome** and will be fully **credited**. diff --git a/README.md b/README.md index 77aac7f4..867c9dc2 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ ![alt XOOPS CMS](https://xoops.org/images/logoXoops4GithubRepository.png) ## Publisher module for [XOOPS CMS 2.5.8+](https://xoops.org) [![XOOPS CMS Module](https://img.shields.io/badge/XOOPS%20CMS-Module-blue.svg)](https://xoops.org) -[![Software License](https://img.shields.io/badge/license-GPL-brightgreen.svg?style=flat)](LICENSE) +[![Software License](https://img.shields.io/badge/license-GPL-brightgreen.svg?style=flat)](http://www.gnu.org/licenses/gpl-2.0.html) [![Scrutinizer Code Quality](https://img.shields.io/scrutinizer/g/mambax7/publisher.svg?style=flat)](https://scrutinizer-ci.com/g/mambax7/publisher/?branch=master) [![Codacy Badge](https://api.codacy.com/project/badge/grade/2d27c0023ee54f0b9ba2b5d17a68b2a5)](https://www.codacy.com/app/mambax7/publisher) diff --git a/admin/admin_header.php b/admin/admin_header.php index 4f643222..062d66f7 100644 --- a/admin/admin_header.php +++ b/admin/admin_header.php @@ -25,7 +25,7 @@ //require_once $GLOBALS['xoops']->path('www/class/xoopsformloader.php'); include __DIR__ . '/../preloads/autoloader.php'; - +require_once __DIR__ . '/../include/common.php'; $moduleDirName = basename(dirname(__DIR__)); diff --git a/admin/category.php b/admin/category.php index f329682b..4b30b707 100644 --- a/admin/category.php +++ b/admin/category.php @@ -34,11 +34,11 @@ switch ($op) { case 'del': - $categoryObj = $helper->getHandler('category')->get($categoryid); + $categoryObj = $helper->getHandler('Category')->get($categoryid); $confirm = Request::getInt('confirm', '', 'POST'); $name = Request::getString('name', '', 'POST'); if ($confirm) { - if (!$helper->getHandler('category')->delete($categoryObj)) { + if (!$helper->getHandler('Category')->delete($categoryObj)) { redirect_header('category.php', 1, _AM_PUBLISHER_DELETE_CAT_ERROR); // exit(); } @@ -66,9 +66,9 @@ $parentid = Request::getInt('parentid'); if (0 != $categoryid) { - $categoryObj = $helper->getHandler('category')->get($categoryid); + $categoryObj = $helper->getHandler('Category')->get($categoryid); } else { - $categoryObj = $helper->getHandler('category')->create(); + $categoryObj = $helper->getHandler('Category')->create(); } // Uploading the image, if any @@ -144,7 +144,7 @@ for ($i = 0; $i < $sizeof; ++$i) { $temp = Request::getArray('scname', [], 'POST'); if ('' != $temp[$i]) { - $categoryObj = $helper->getHandler('category')->create(); + $categoryObj = $helper->getHandler('Category')->create(); $temp2 = Request::getArray('scname', [], 'POST'); $categoryObj->setVar('name', $temp2[$i]); $categoryObj->setVar('parentid', $parentCat); @@ -170,7 +170,7 @@ $categoryid = 0; $nb_subcats = Request::getInt('nb_subcats', 0, 'POST') + Request::getInt('nb_sub_yet', 0, 'POST'); - $categoryObj = $helper->getHandler('category')->create(); + $categoryObj = $helper->getHandler('Category')->create(); $categoryObj->setVar('name', Request::getString('name', '', 'POST')); $categoryObj->setVar('description', Request::getString('description', '', 'POST')); $categoryObj->setVar('weight', Request::getInt('weight', 0, 'POST')); @@ -200,7 +200,7 @@ echo ''; // Creating the objects for top categories - $categoriesObj = $helper->getHandler('category')->getCategories($helper->getConfig('idxcat_perpage'), $startcategory, 0); + $categoriesObj = $helper->getHandler('Category')->getCategories($helper->getConfig('idxcat_perpage'), $startcategory, 0); Publisher\Utility::openCollapsableBar('createdcategories', 'createdcategoriesicon', _AM_PUBLISHER_CATEGORIES_TITLE, _AM_PUBLISHER_CATEGORIES_DSC); @@ -211,7 +211,7 @@ echo "" . _CO_PUBLISHER_WEIGHT . ''; echo "" . _AM_PUBLISHER_ACTION . ''; echo ''; - $totalCategories = $helper->getHandler('category')->getCategoriesCount(0); + $totalCategories = $helper->getHandler('Category')->getCategoriesCount(0); if (count($categoriesObj) > 0) { foreach ($categoriesObj as $key => $thiscat) { Publisher\Utility::displayCategory($thiscat); diff --git a/admin/file.php b/admin/file.php index ea1cfb7e..76d6b498 100644 --- a/admin/file.php +++ b/admin/file.php @@ -38,7 +38,7 @@ function publisher_editFile($showmenu = false, $fileid = 0, $itemid = 0) // if there is a parameter, and the id exists, retrieve data: we're editing a file if (0 != $fileid) { // Creating the File object - $fileObj = $helper->getHandler('file')->get($fileid); + $fileObj = $helper->getHandler('File')->get($fileid); if ($fileObj->notLoaded()) { redirect_header('javascript:history.go(-1)', 1, _AM_PUBLISHER_NOFILESELECTED); @@ -51,7 +51,7 @@ function publisher_editFile($showmenu = false, $fileid = 0, $itemid = 0) Publisher\Utility::openCollapsableBar('editfile', 'editfileicon', _AM_PUBLISHER_FILE_INFORMATIONS); } else { // there's no parameter, so we're adding an item - $fileObj = $helper->getHandler('file')->create(); + $fileObj = $helper->getHandler('File')->create(); $fileObj->setVar('itemid', $itemid); echo "" . _AM_PUBLISHER_FILE_ADDING . ''; echo '' . _AM_PUBLISHER_FILE_ADDING_DSC . ''; @@ -101,9 +101,9 @@ function publisher_editFile($showmenu = false, $fileid = 0, $itemid = 0) // Creating the file object if (0 != $fileid) { - $fileObj = $helper->getHandler('file')->get($fileid); + $fileObj = $helper->getHandler('File')->get($fileid); } else { - $fileObj = $helper->getHandler('file')->create(); + $fileObj = $helper->getHandler('File')->create(); } // Putting the values in the file object @@ -125,13 +125,13 @@ function publisher_editFile($showmenu = false, $fileid = 0, $itemid = 0) $fileid = Request::getInt('fileid', 0, 'POST'); $fileid = Request::getInt('fileid', $fileid, 'GET'); - $fileObj = $helper->getHandler('file')->get($fileid); + $fileObj = $helper->getHandler('File')->get($fileid); $confirm = Request::getInt('confirm', 0, 'POST'); $title = Request::getString('title', '', 'POST'); if ($confirm) { - if (!$helper->getHandler('file')->delete($fileObj)) { + if (!$helper->getHandler('File')->delete($fileObj)) { redirect_header('item.php?op=mod&itemid=' . $fileObj->itemid() . '#tab_2', 2, _AM_PUBLISHER_FILE_DELETE_ERROR); // exit; } diff --git a/admin/import/ams.php b/admin/import/ams.php index e48b94fc..d49fd084 100644 --- a/admin/import/ams.php +++ b/admin/import/ams.php @@ -21,6 +21,7 @@ use Xmf\Request; use XoopsModules\Publisher; +use XoopsModules\Publisher\Constants; require_once dirname(__DIR__) . '/admin_header.php'; $myts = \MyTextSanitizer::getInstance(); @@ -160,7 +161,7 @@ if ('go' === $op) { Publisher\Utility::cpHeader(); //publisher_adminMenu(-1, _AM_PUBLISHER_IMPORT); - require_once dirname(dirname(__DIR__)) . '/include/common.php'; + require_once __DIR__ . '/../../include/common.php'; Publisher\Utility::openCollapsableBar('amsimportgo', 'amsimportgoicon', sprintf(_AM_PUBLISHER_IMPORT_FROM, $importFromModuleName), _AM_PUBLISHER_IMPORT_RESULT); /* @var $moduleHandler XoopsModuleHandler */ $moduleHandler = xoops_getHandler('module'); @@ -215,8 +216,8 @@ $newCat = []; $newCat['oldid'] = $arrCat['topic_id']; $newCat['oldpid'] = $arrCat['topic_pid']; - /* @var $categoryObj PublisherCategory */ - $categoryObj = $helper->getHandler('category')->create(); + /* @var $categoryObj Publisher\Category */ + $categoryObj = $helper->getHandler('Category')->create(); $categoryObj->setVar('parentid', $arrCat['topic_pid']); $categoryObj->setVar('image', $arrCat['topic_imgurl']); @@ -254,7 +255,7 @@ } } - if (!$helper->getHandler('category')->insert($categoryObj)) { + if (!$helper->getHandler('Category')->insert($categoryObj)) { echo sprintf(_AM_PUBLISHER_IMPORT_CATEGORY_ERROR, $arrCat['topic_title']) . '
'; continue; } @@ -292,8 +293,8 @@ while (false !== ($arrArticle = $GLOBALS['xoopsDB']->fetchArray($resultArticles))) { // insert article - /** @var XoopsPersistableObjectHandler $itemObj */ - $itemObj = $helper->getHandler('item')->create(); + /** @var \XoopsPersistableObjectHandler $itemObj */ + $itemObj = $helper->getHandler('Item')->create(); $itemObj->setVar('categoryid', $categoryObj->categoryid()); $itemObj->setVar('title', $arrArticle['title']); @@ -305,7 +306,7 @@ $itemObj->setVar('dohtml', !$arrArticle['nohtml']); $itemObj->setVar('dosmiley', !$arrArticle['nosmiley']); $itemObj->setVar('weight', 0); - $itemObj->setVar('status', PublisherConstants::PUBLISHER_STATUS_PUBLISHED); + $itemObj->setVar('status', Constants::PUBLISHER_STATUS_PUBLISHED); // $itemObj->setVar('dobr', !$arrArticle['dobr']); // $itemObj->setVar('item_tag', $arrArticle['tags']); @@ -354,11 +355,11 @@ $filename = $GLOBALS['xoops']->path('uploads/AMS/attached/' . $arrFile['downloadname']); if (file_exists($filename)) { if (copy($filename, $GLOBALS['xoops']->path('uploads/publisher/' . $arrFile['filerealname']))) { - /** @var PublisherFile $fileObj */ - $fileObj = $helper->getHandler('file')->create(); + /** @var Publisher\File $fileObj */ + $fileObj = $helper->getHandler('File')->create(); $fileObj->setVar('name', $arrFile['filerealname']); $fileObj->setVar('description', $arrFile['filerealname']); - $fileObj->setVar('status', PublisherConstants::PUBLISHER_STATUS_FILE_ACTIVE); + $fileObj->setVar('status', Constants::PUBLISHER_STATUS_FILE_ACTIVE); $fileObj->setVar('uid', $arrArticle['uid']); $fileObj->setVar('itemid', $itemObj->itemid()); $fileObj->setVar('mimetype', $arrFile['mimetype']); @@ -406,7 +407,7 @@ } else { $newpid = $newCatArray[$oldpid]['newid']; } - $helper->getHandler('category')->updateAll('parentid', $newpid, $criteria); + $helper->getHandler('Category')->updateAll('parentid', $newpid, $criteria); unset($criteria); } unset($oldid, $newCat); @@ -416,12 +417,12 @@ $publisher_module_id = $helper->getModule()->mid(); - /** @var XoopsCommentHandler $commentHandler */ + /** @var \XoopsCommentHandler $commentHandler */ $commentHandler = xoops_getHandler('comment'); $criteria = new \CriteriaCompo(); $criteria->add(new \Criteria('com_modid', $ams_module_id)); $comments = $commentHandler->getObjects($criteria); - /** @var XoopsComment $comment */ + /** @var \XoopsComment $comment */ foreach ($comments as $comment) { $comment->setVar('com_itemid', $newArticleArray[$comment->getVar('com_itemid')]); $comment->setVar('com_modid', $publisher_module_id); diff --git a/admin/import/cjaycontent.php b/admin/import/cjaycontent.php index 02dcc773..7cc70eff 100644 --- a/admin/import/cjaycontent.php +++ b/admin/import/cjaycontent.php @@ -21,6 +21,7 @@ use Xmf\Request; use XoopsModules\Publisher; +use XoopsModules\Publisher\Constants; require_once dirname(__DIR__) . '/admin_header.php'; $myts = \MyTextSanitizer::getInstance(); @@ -86,7 +87,7 @@ if ('go' === $op) { Publisher\Utility::cpHeader(); //publisher_adminMenu(-1, _AM_PUBLISHER_IMPORT); - require_once dirname(dirname(__DIR__)) . '/include/common.php'; + require_once __DIR__ . '/../../include/common.php'; Publisher\Utility::openCollapsableBar('cjaycontentimportgo', 'cjaycontentimportgoicon', sprintf(_AM_PUBLISHER_IMPORT_FROM, $importFromModuleName), _AM_PUBLISHER_IMPORT_RESULT); /* @var $moduleHandler XoopsModuleHandler */ $moduleHandler = xoops_getHandler('module'); @@ -105,8 +106,8 @@ $resultArticles = $GLOBALS['xoopsDB']->query($sql); while (false !== ($arrArticle = $GLOBALS['xoopsDB']->fetchArray($resultArticles))) { // insert article - /** @var PublisherItem $itemObj */ - $itemObj = $helper->getHandler('item')->create(); + /** @var Publisher\Item $itemObj */ + $itemObj = $helper->getHandler('Item')->create(); $itemObj->setVar('itemid', $arrArticle['id']); // $itemObj->setVar('categoryid', $categoryObj->categoryid()); $itemObj->setVar('title', $arrArticle['title']); @@ -118,7 +119,7 @@ // $itemObj->setVar('dohtml', !$arrArticle['nohtml']); // $itemObj->setVar('dosmiley', !$arrArticle['nosmiley']); $itemObj->setVar('weight', $arrArticle['weight']); - $itemObj->setVar('status', PublisherConstants::PUBLISHER_STATUS_PUBLISHED); + $itemObj->setVar('status', Constants::PUBLISHER_STATUS_PUBLISHED); // $itemObj->setVar('dobr', !$arrArticle['dobr']); // $itemObj->setVar('item_tag', $arrArticle['tags']); @@ -160,11 +161,11 @@ echo _AM_PUBLISHER_IMPORT_COMMENTS . '
'; $publisher_module_id = $helper->getModule()->mid(); - /** @var XoopsCommentHandler $commentHandler */ + /** @var \XoopsCommentHandler $commentHandler */ $commentHandler = xoops_getHandler('comment'); $criteria = new \CriteriaCompo(); $criteria->add(new \Criteria('com_modid', $cjaycontent_module_id)); - /** @var XoopsComment $comment */ + /** @var \XoopsComment $comment */ $comments = $commentHandler->getObjects($criteria); foreach ($comments as $comment) { $comment->setVar('com_itemid', $newArticleArray[$comment->getVar('com_itemid')]); diff --git a/admin/import/fmcontent.php b/admin/import/fmcontent.php index da23d3bc..c0569c76 100644 --- a/admin/import/fmcontent.php +++ b/admin/import/fmcontent.php @@ -22,6 +22,7 @@ use Xmf\Request; use XoopsModules\Publisher; +use XoopsModules\Publisher\Constants; require_once dirname(__DIR__) . '/admin_header.php'; $myts = \MyTextSanitizer::getInstance(); @@ -93,7 +94,7 @@ // Publisher parent category xoops_load('tree'); - $categoryHdlr = $helper->getHandler('category'); + $categoryHdlr = $helper->getHandler('Category'); $catObjs = $categoryHdlr->getAll(); $myObjTree = new \XoopsObjectTree($catObjs, 'categoryid', 'parentid'); $moduleDirName = basename(dirname(__DIR__)); @@ -158,8 +159,8 @@ ++$cnt_imported_cat; //count category if there was content to import // create Publsher category to hold FmContent Content items with no Topic (content_topic=0) - /* @var $categoryObj PublisherCategory */ - $categoryObj = $helper->getHandler('category')->create(); + /* @var $categoryObj Publisher\Category */ + $categoryObj = $helper->getHandler('Category')->create(); $categoryObj->setVars([ 'parentid' => $parentId, 'name' => _AM_PUBLISHER_IMPORT_FMCONTENT_NAME, @@ -177,7 +178,7 @@ // insert articles for this category foreach ($fmContentObjs as $thisFmContentObj) { - $itemObj = $helper->getHandler('item')->create(); + $itemObj = $helper->getHandler('Item')->create(); $itemObj->setVars([ 'categoryid' => $categoryObj->categoryid(), 'title' => $thisFmContentObj->getVar('content_title'), @@ -191,7 +192,7 @@ 'doimage' => $thisFmContentObj->getVar('doimage'), 'dobr' => $thisFmContentObj->getVar('dobr'), 'weight' => $thisFmContentObj->getVar('content_order'), - 'status' => $thisFmContentObj->getVar('content_status') ? PublisherConstants::PUBLISHER_STATUS_PUBLISHED : PublisherConstants::PUBLISHER_STATUS_OFFLINE, + 'status' => $thisFmContentObj->getVar('content_status') ? Constants::PUBLISHER_STATUS_PUBLISHED : Constants::PUBLISHER_STATUS_OFFLINE, 'counter' => $thisFmContentObj->getVar('content_hits'), 'rating' => 0, 'votes' => 0, @@ -241,7 +242,7 @@ 'oldpid' => $thisFmTopicObj->getVar('topic_pid') ]; - $categoryObj = $helper->getHandler('category')->create(); + $categoryObj = $helper->getHandler('Category')->create(); $categoryObj->setVars([ 'parentid' => $thisFmTopicObj->getVar('topic_pid'), @@ -256,7 +257,7 @@ $categoryObj->setVar('image', $thisFmTopicObj->getVar('topic_img')); } } - if (!$helper->getHandler('category')->insert($categoryObj)) { + if (!$helper->getHandler('Category')->insert($categoryObj)) { echo sprintf(_AM_PUBLISHER_IMPORT_CATEGORY_ERROR, $thisFmTopicObj->getVar('topic_title')) . "
\n"; continue; } @@ -273,9 +274,9 @@ $fmContentObjs = $fmContentHdlr->getAll($criteria); // insert articles for this category - /** @var PublisherItem $itemObj */ + /** @var Publisher\Item $itemObj */ foreach ($fmContentObjs as $thisFmContentObj) { - $itemObj = $helper->getHandler('item')->create(); + $itemObj = $helper->getHandler('Item')->create(); $itemObj->setVars([ 'categoryid' => $CatIds['newid'], 'title' => $thisFmContentObj->getVar('content_title'), @@ -290,7 +291,7 @@ 'doimage' => $thisFmContentObj->getVar('doimage'), 'dobr' => $thisFmContentObj->getVar('dobr'), 'weight' => $thisFmContentObj->getVar('content_order'), - 'status' => $thisFmContentObj->getVar('content_status') ? PublisherConstants::PUBLISHER_STATUS_PUBLISHED : PublisherConstants::PUBLISHER_STATUS_OFFLINE, + 'status' => $thisFmContentObj->getVar('content_status') ? Constants::PUBLISHER_STATUS_PUBLISHED : Constants::PUBLISHER_STATUS_OFFLINE, 'rating' => 0, 'votes' => 0, 'comments' => $thisFmContentObj->getVar('content_comments'), @@ -331,7 +332,7 @@ $criteria->add(new \Criteria('categoryid', $CatIds['newid'])); $oldpid = $CatIds['oldpid']; $newpid = (0 == $oldpid) ? $parentId : $newCatArray[$oldpid]['newid']; - $helper->getHandler('category')->updateAll('parentid', $newpid, $criteria); + $helper->getHandler('Category')->updateAll('parentid', $newpid, $criteria); unset($criteria); } unset($oldid, $CatIds); @@ -340,11 +341,11 @@ echo _AM_PUBLISHER_IMPORT_COMMENTS . "
\n"; $publisher_module_id = $helper->getModule()->mid(); - /** @var XoopsCommentHandler $commentHandler */ + /** @var \XoopsCommentHandler $commentHandler */ $commentHandler = xoops_getHandler('comment'); $criteria = new \CriteriaCompo(); $criteria->add(new \Criteria('com_modid', $fm_module_id)); - /** @var XoopsComment $comment */ + /** @var \XoopsComment $comment */ $comments = $commentHandler->getObjects($criteria); foreach ($comments as $comment) { $comment->setVar('com_itemid', $newArticleArray[$comment->getVar('com_itemid')]); diff --git a/admin/import/news.php b/admin/import/news.php index 3d049200..7ab978e0 100644 --- a/admin/import/news.php +++ b/admin/import/news.php @@ -21,6 +21,7 @@ use Xmf\Request; use XoopsModules\Publisher; +use XoopsModules\Publisher\Constants; require_once dirname(__DIR__) . '/admin_header.php'; $myts = \MyTextSanitizer::getInstance(); @@ -122,8 +123,8 @@ $newCat = []; $newCat['oldid'] = $arrCat['topic_id']; $newCat['oldpid'] = $arrCat['topic_pid']; - /* @var $categoryObj PublisherCategory */ - $categoryObj = $helper->getHandler('category')->create(); + /* @var $categoryObj Publisher\Category */ + $categoryObj = $helper->getHandler('Category')->create(); $categoryObj->setVar('parentid', $arrCat['topic_pid']); $categoryObj->setVar('weight', 0); @@ -137,7 +138,7 @@ } } - if (!$helper->getHandler('category')->insert($categoryObj)) { + if (!$helper->getHandler('Category')->insert($categoryObj)) { echo sprintf(_AM_PUBLISHER_IMPORT_CATEGORY_ERROR, $arrCat['topic_title']) . '
'; continue; } @@ -151,8 +152,8 @@ $resultArticles = $GLOBALS['xoopsDB']->query($sql); while (false !== ($arrArticle = $GLOBALS['xoopsDB']->fetchArray($resultArticles))) { // insert article - /** @var PublisherItem $itemObj */ - $itemObj = $helper->getHandler('item')->create(); + /** @var Publisher\Item $itemObj */ + $itemObj = $helper->getHandler('Item')->create(); $itemObj->setVar('categoryid', $categoryObj->categoryid()); $itemObj->setVar('title', $arrArticle['title']); @@ -164,7 +165,7 @@ $itemObj->setVar('dohtml', !$arrArticle['nohtml']); $itemObj->setVar('dosmiley', !$arrArticle['nosmiley']); $itemObj->setVar('weight', 0); - $itemObj->setVar('status', PublisherConstants::PUBLISHER_STATUS_PUBLISHED); + $itemObj->setVar('status', Constants::PUBLISHER_STATUS_PUBLISHED); $itemObj->setVar('rating', $arrArticle['rating']); $itemObj->setVar('votes', $arrArticle['votes']); @@ -205,7 +206,7 @@ $fileObj = $publisher_fileHandler->create(); $fileObj->setVar('name', $arrFile['fileshowname']); $fileObj->setVar('description', $arrFile['filedescript']); - $fileObj->setVar('status', PublisherConstants::PUBLISHER_STATUS_FILE_ACTIVE); + $fileObj->setVar('status', Constants::PUBLISHER_STATUS_FILE_ACTIVE); $fileObj->setVar('uid', $arrArticle['uid']); $fileObj->setVar('itemid', $itemObj->itemid()); $fileObj->setVar('mimetype', $arrFile['minetype']); @@ -247,7 +248,7 @@ } else { $newpid = $newCatArray[$oldpid]['newid']; } - $helper->getHandler('category')->updateAll('parentid', $newpid, $criteria); + $helper->getHandler('Category')->updateAll('parentid', $newpid, $criteria); unset($criteria); } unset($oldid, $newCat); @@ -256,11 +257,11 @@ echo _AM_PUBLISHER_IMPORT_COMMENTS . '
'; $publisher_module_id = $helper->getModule()->mid(); - /** @var XoopsCommentHandler $commentHandler */ + /** @var \XoopsCommentHandler $commentHandler */ $commentHandler = xoops_getHandler('comment'); $criteria = new \CriteriaCompo(); $criteria->add(new \Criteria('com_modid', $news_module_id)); - /** @var XoopsComment $comment */ + /** @var \XoopsComment $comment */ $comments = $commentHandler->getObjects($criteria); foreach ($comments as $comment) { $comment->setVar('com_itemid', $newArticleArray[$comment->getVar('com_itemid')]); diff --git a/admin/import/smartsection.php b/admin/import/smartsection.php index d6e9c3c1..ff6806a7 100644 --- a/admin/import/smartsection.php +++ b/admin/import/smartsection.php @@ -122,8 +122,8 @@ $newCat = []; $newCat['oldid'] = $arrCat['categoryid']; $newCat['oldpid'] = $arrCat['parentid']; - /* @var $categoryObj PublisherCategory */ - $categoryObj = $helper->getHandler('category')->create(); + /* @var $categoryObj Publisher\Category */ + $categoryObj = $helper->getHandler('Category')->create(); $categoryObj->setVars($arrCat); $categoryObj->setVar('categoryid', 0); @@ -133,7 +133,7 @@ copy($GLOBALS['xoops']->path('uploads/smartsection/images/category/' . $arrCat['image']), $GLOBALS['xoops']->path('uploads/publisher/images/category/' . $arrCat['image'])); } - if (!$helper->getHandler('category')->insert($categoryObj)) { + if (!$helper->getHandler('Category')->insert($categoryObj)) { echo sprintf(_AM_PUBLISHER_IMPORT_CATEGORY_ERROR, $arrCat['name']) . '
'; continue; } @@ -148,8 +148,8 @@ while (false !== ($arrArticle = $GLOBALS['xoopsDB']->fetchArray($resultArticles))) { // insert article - /** @var PublisherItem $itemObj */ - $itemObj = $helper->getHandler('item')->create(); + /** @var Publisher\Item $itemObj */ + $itemObj = $helper->getHandler('Item')->create(); $itemObj->setVars($arrArticle); $itemObj->setVar('itemid', 0); @@ -183,8 +183,8 @@ $filename = $GLOBALS['xoops']->path('uploads/smartsection/' . $arrFile['filename']); if (file_exists($filename)) { if (copy($filename, $GLOBALS['xoops']->path('uploads/publisher/' . $arrFile['filename']))) { - /** @var PublisherFile $fileObj */ - $fileObj = $helper->getHandler('file')->create(); + /** @var Publisher\File $fileObj */ + $fileObj = $helper->getHandler('File')->create(); $fileObj->setVars($arrFile); $fileObj->setVar('fileid', 0); @@ -222,7 +222,7 @@ } else { $newpid = $newCatArray[$oldpid]['newid']; } - $helper->getHandler('category')->updateAll('parentid', $newpid, $criteria); + $helper->getHandler('Category')->updateAll('parentid', $newpid, $criteria); unset($criteria); } unset($oldid, $newCat); @@ -231,11 +231,11 @@ echo _AM_PUBLISHER_IMPORT_COMMENTS . '
'; $publisher_module_id = $helper->getModule()->mid(); - /** @var XoopsCommentHandler $commentHandler */ + /** @var \XoopsCommentHandler $commentHandler */ $commentHandler = xoops_getHandler('comment'); $criteria = new \CriteriaCompo(); $criteria->add(new \Criteria('com_modid', $smartsection_module_id)); - /** @var XoopsComment $comment */ + /** @var \XoopsComment $comment */ $comments = $commentHandler->getObjects($criteria); foreach ($comments as $comment) { $comment->setVar('com_itemid', $newArticleArray[$comment->getVar('com_itemid')]); diff --git a/admin/import/wfsection.php b/admin/import/wfsection.php index 6d3ee840..15cf261d 100644 --- a/admin/import/wfsection.php +++ b/admin/import/wfsection.php @@ -21,6 +21,7 @@ use Xmf\Request; use XoopsModules\Publisher; +use XoopsModules\Publisher\Constants; require_once dirname(__DIR__) . '/admin_header.php'; $myts = \MyTextSanitizer::getInstance(); @@ -113,8 +114,8 @@ $newCatArray = []; while (false !== ($arrCat = $GLOBALS['xoopsDB']->fetchArray($resultCat))) { - /* @var $categoryObj PublisherCategory */ - $categoryObj = $helper->getHandler('category')->create(); + /* @var $categoryObj Publisher\Category */ + $categoryObj = $helper->getHandler('Category')->create(); $newCat = []; @@ -156,8 +157,8 @@ $resultArticles = $GLOBALS['xoopsDB']->query($sql); while (false !== ($arrArticle = $GLOBALS['xoopsDB']->fetchArray($resultArticles))) { // insert article - /** @var PublisherItem $itemObj */ - $itemObj = $helper->getHandler('item')->create(); + /** @var Publisher\Item $itemObj */ + $itemObj = $helper->getHandler('Item')->create(); $itemObj->setVar('categoryid', $categoryObj->categoryid()); $itemObj->setVar('title', $arrArticle['title']); @@ -170,7 +171,7 @@ $itemObj->setVar('dosmiley', !$arrArticle['nosmiley']); $itemObj->setVar('dobr', $arrArticle['nobreaks']); $itemObj->setVar('weight', $arrArticle['weight']); - $itemObj->setVar('status', PublisherConstants::PUBLISHER_STATUS_PUBLISHED); + $itemObj->setVar('status', Constants::PUBLISHER_STATUS_PUBLISHED); $itemObj->setGroupsRead(explode(' ', trim($arrArticle['groupid']))); // HTML Wrap @@ -197,11 +198,11 @@ $filename = $GLOBALS['xoops']->path('modules/wfsection/cache/uploaded/' . $arrFile['filerealname']); if (file_exists($filename)) { if (copy($filename, PUBLISHER_UPLOAD_PATH . '/' . $arrFile['filerealname'])) { - /** @var PublisherFile $fileObj */ - $fileObj = $helper->getHandler('file')->create(); + /** @var Publisher\File $fileObj */ + $fileObj = $helper->getHandler('File')->create(); $fileObj->setVar('name', $arrFile['fileshowname']); $fileObj->setVar('description', $arrFile['filedescript']); - $fileObj->setVar('status', PublisherConstants::PUBLISHER_STATUS_FILE_ACTIVE); + $fileObj->setVar('status', Constants::PUBLISHER_STATUS_FILE_ACTIVE); $fileObj->setVar('uid', $arrArticle['uid']); $fileObj->setVar('itemid', $itemObj->itemid()); $fileObj->setVar('mimetype', $arrFile['minetype']); @@ -235,7 +236,7 @@ } else { $newpid = $newCatArray[$oldpid]['newid']; } - $helper->getHandler('category')->updateAll('parentid', $newpid, $criteria); + $helper->getHandler('Category')->updateAll('parentid', $newpid, $criteria); unset($criteria); } unset($oldid, $newCat); @@ -248,11 +249,11 @@ $news_module_id = $moduleObj->getVar('mid'); $publisher_module_id = $helper->getModule()->mid(); - /** @var XoopsCommentHandler $commentHandler */ + /** @var \XoopsCommentHandler $commentHandler */ $commentHandler = xoops_getHandler('comment'); $criteria = new \CriteriaCompo(); $criteria->add(new \Criteria('com_modid', $news_module_id)); - /** @var XoopsComment $comment */ + /** @var \XoopsComment $comment */ $comments = $commentHandler->getObjects($criteria); foreach ($comments as $comment) { $comment->setVar('com_itemid', $newArticleArray[$comment->getVar('com_itemid')]); diff --git a/admin/import/xfsection.php b/admin/import/xfsection.php index ddc8ba2b..97022a06 100644 --- a/admin/import/xfsection.php +++ b/admin/import/xfsection.php @@ -21,6 +21,7 @@ use Xmf\Request; use XoopsModules\Publisher; +use XoopsModules\Publisher\Constants; require_once dirname(__DIR__) . '/admin_header.php'; $myts = \MyTextSanitizer::getInstance(); @@ -108,8 +109,8 @@ $newCatArray = []; while (false !== ($arrCat = $GLOBALS['xoopsDB']->fetchArray($resultCat))) { - /* @var $categoryObj PublisherCategory */ - $categoryObj = $helper->getHandler('category')->create(); + /* @var $categoryObj Publisher\Category */ + $categoryObj = $helper->getHandler('Category')->create(); $newCat = []; @@ -149,8 +150,8 @@ $resultArticles = $GLOBALS['xoopsDB']->query($sql); while (false !== ($arrArticle = $GLOBALS['xoopsDB']->fetchArray($resultArticles))) { // insert article - /** @var PublisherItem $itemObj */ - $itemObj = $helper->getHandler('item')->create(); + /** @var Publisher\Item $itemObj */ + $itemObj = $helper->getHandler('Item')->create(); $itemObj->setVar('categoryid', $categoryObj->categoryid()); $itemObj->setVar('title', $arrArticle['title']); @@ -166,9 +167,9 @@ $itemObj->setGroupsRead(explode(' ', trim($arrArticle['groupid']))); // status - $status = PublisherConstants::PUBLISHER_STATUS_PUBLISHED; + $status = Constants::PUBLISHER_STATUS_PUBLISHED; if ($arrArticle['offline']) { - $status = PublisherConstants::PUBLISHER_STATUS_OFFLINE; + $status = Constants::PUBLISHER_STATUS_OFFLINE; } $itemObj->setVar('status', $status); @@ -196,11 +197,11 @@ $filename = $GLOBALS['xoops']->path('modules/xfsection/cache/uploaded/' . $arrFile['filerealname']); if (file_exists($filename)) { if (copy($filename, PUBLISHER_UPLOAD_PATH . '/' . $arrFile['filerealname'])) { - /** @var PublisherFile $fileObj */ - $fileObj = $helper->getHandler('file')->create(); + /** @var Publisher\File $fileObj */ + $fileObj = $helper->getHandler('File')->create(); $fileObj->setVar('name', $arrFile['fileshowname']); $fileObj->setVar('description', $arrFile['filedescript']); - $fileObj->setVar('status', PublisherConstants::PUBLISHER_STATUS_FILE_ACTIVE); + $fileObj->setVar('status', Constants::PUBLISHER_STATUS_FILE_ACTIVE); $fileObj->setVar('uid', $arrArticle['uid']); $fileObj->setVar('itemid', $itemObj->itemid()); $fileObj->setVar('mimetype', $arrFile['minetype']); @@ -234,7 +235,7 @@ } else { $newpid = $newCatArray[$oldpid]['newid']; } - $helper->getHandler('category')->updateAll('parentid', $newpid, $criteria); + $helper->getHandler('Category')->updateAll('parentid', $newpid, $criteria); unset($criteria); } unset($oldid, $newCat); @@ -247,11 +248,11 @@ $news_module_id = $moduleObj->getVar('mid'); $publisher_module_id = $helper->getModule()->mid(); - /** @var XoopsCommentHandler $commentHandler */ + /** @var \XoopsCommentHandler $commentHandler */ $commentHandler = xoops_getHandler('comment'); $criteria = new \CriteriaCompo(); $criteria->add(new \Criteria('com_modid', $news_module_id)); - /** @var XoopsComment $comment */ + /** @var \XoopsComment $comment */ $comments = $commentHandler->getObjects($criteria); foreach ($comments as $comment) { $comment->setVar('com_itemid', $newArticleArray[$comment->getVar('com_itemid')]); diff --git a/admin/import/xnews.php b/admin/import/xnews.php index 1d12b365..919c18c6 100644 --- a/admin/import/xnews.php +++ b/admin/import/xnews.php @@ -21,6 +21,7 @@ use Xmf\Request; use XoopsModules\Publisher; +use XoopsModules\Publisher\Constants; require_once dirname(__DIR__) . '/admin_header.php'; $myts = \MyTextSanitizer::getInstance(); @@ -161,7 +162,7 @@ if ('go' === $op) { Publisher\Utility::cpHeader(); //publisher_adminMenu(-1, _AM_PUBLISHER_IMPORT); - require_once dirname(dirname(__DIR__)) . '/include/common.php'; + require_once __DIR__ . '/../../include/common.php'; Publisher\Utility::openCollapsableBar('xnewsimportgo', 'xnewsimportgoicon', sprintf(_AM_PUBLISHER_IMPORT_FROM, $importFromModuleName), _AM_PUBLISHER_IMPORT_RESULT); /* @var $moduleHandler XoopsModuleHandler */ $moduleHandler = xoops_getHandler('module'); @@ -216,8 +217,8 @@ $newCat['oldid'] = $arrCat['topic_id']; $newCat['oldpid'] = $arrCat['topic_pid']; - /* @var $categoryObj PublisherCategory */ - $categoryObj = $helper->getHandler('category')->create(); + /* @var $categoryObj Publisher\Category */ + $categoryObj = $helper->getHandler('Category')->create(); $categoryObj->setVar('parentid', $arrCat['topic_pid']); $categoryObj->setVar('image', $arrCat['topic_imgurl']); @@ -255,7 +256,7 @@ } } - if (!$helper->getHandler('category')->insert($categoryObj)) { + if (!$helper->getHandler('Category')->insert($categoryObj)) { echo sprintf(_AM_PUBLISHER_IMPORT_CATEGORY_ERROR, $arrCat['topic_title']) . '
'; continue; } @@ -291,8 +292,8 @@ while (false !== ($arrArticle = $GLOBALS['xoopsDB']->fetchArray($resultArticles))) { // insert article - /** @var PublisherItem $itemObj */ - $itemObj = $helper->getHandler('item')->create(); + /** @var Publisher\Item $itemObj */ + $itemObj = $helper->getHandler('Item')->create(); $itemObj->setVar('categoryid', $categoryObj->categoryid()); $itemObj->setVar('title', $arrArticle['title']); @@ -304,7 +305,7 @@ $itemObj->setVar('dohtml', !$arrArticle['nohtml']); $itemObj->setVar('dosmiley', !$arrArticle['nosmiley']); $itemObj->setVar('weight', 0); - $itemObj->setVar('status', PublisherConstants::PUBLISHER_STATUS_PUBLISHED); + $itemObj->setVar('status', Constants::PUBLISHER_STATUS_PUBLISHED); $itemObj->setVar('dobr', !$arrArticle['dobr']); $itemObj->setVar('item_tag', $arrArticle['tags']); @@ -353,11 +354,11 @@ $filename = $GLOBALS['xoops']->path('uploads/xnews/attached/' . $arrFile['downloadname']); if (file_exists($filename)) { if (copy($filename, $GLOBALS['xoops']->path('uploads/publisher/' . $arrFile['filerealname']))) { - /* @var $fileObj PublisherFile */ - $fileObj = $helper->getHandler('file')->create(); + /* @var $fileObj File */ + $fileObj = $helper->getHandler('File')->create(); $fileObj->setVar('name', $arrFile['filerealname']); $fileObj->setVar('description', $arrFile['filerealname']); - $fileObj->setVar('status', PublisherConstants::PUBLISHER_STATUS_FILE_ACTIVE); + $fileObj->setVar('status', Constants::PUBLISHER_STATUS_FILE_ACTIVE); $fileObj->setVar('uid', $arrArticle['uid']); $fileObj->setVar('itemid', $itemObj->itemid()); $fileObj->setVar('mimetype', $arrFile['mimetype']); @@ -405,7 +406,7 @@ } else { $newpid = $newCatArray[$oldpid]['newid']; } - $helper->getHandler('category')->updateAll('parentid', $newpid, $criteria); + $helper->getHandler('Category')->updateAll('parentid', $newpid, $criteria); unset($criteria); } unset($oldid, $newCat); diff --git a/admin/item.php b/admin/item.php index 89db19ee..75595a4e 100644 --- a/admin/item.php +++ b/admin/item.php @@ -21,6 +21,7 @@ use Xmf\Request; use XoopsModules\Publisher; +use XoopsModules\Publisher\Constants; require_once __DIR__ . '/admin_header.php'; @@ -46,7 +47,7 @@ switch ($op) { case 'clone': if (0 == $itemid) { - $totalcategories = $helper->getHandler('category')->getCategoriesCount(-1); + $totalcategories = $helper->getHandler('Category')->getCategoriesCount(-1); if (0 == $totalcategories) { redirect_header('category.php?op=mod', 3, _AM_PUBLISHER_NEED_CATEGORY_ITEM); // exit(); @@ -58,7 +59,7 @@ case 'mod': if (0 == $itemid) { - $totalcategories = $helper->getHandler('category')->getCategoriesCount(-1); + $totalcategories = $helper->getHandler('Category')->getCategoriesCount(-1); if (0 == $totalcategories) { redirect_header('category.php?op=mod', 3, _AM_PUBLISHER_NEED_CATEGORY_ITEM); // exit(); @@ -73,46 +74,46 @@ $redirect_msg = $error_msg = ''; // Creating the item object if (0 != $itemid) { - $itemObj = $helper->getHandler('item')->get($itemid); + $itemObj = $helper->getHandler('Item')->get($itemid); } else { - $itemObj = $helper->getHandler('item')->create(); + $itemObj = $helper->getHandler('Item')->create(); } $itemObj->setVarsFromRequest(); $old_status = $itemObj->status(); - $newStatus = Request::getInt('status', PublisherConstants::PUBLISHER_STATUS_PUBLISHED); //_PUBLISHER_STATUS_NOTSET; + $newStatus = Request::getInt('status', Constants::PUBLISHER_STATUS_PUBLISHED); //_PUBLISHER_STATUS_NOTSET; switch ($newStatus) { - case PublisherConstants::PUBLISHER_STATUS_SUBMITTED: + case Constants::PUBLISHER_STATUS_SUBMITTED: $error_msg = _AM_PUBLISHER_ITEMNOTCREATED; - if ($old_status == PublisherConstants::PUBLISHER_STATUS_NOTSET) { + if ($old_status == Constants::PUBLISHER_STATUS_NOTSET) { $error_msg = _AM_PUBLISHER_ITEMNOTUPDATED; } $redirect_msg = _AM_PUBLISHER_ITEM_RECEIVED_NEED_APPROVAL; break; - case PublisherConstants::PUBLISHER_STATUS_PUBLISHED: - if (($old_status == PublisherConstants::PUBLISHER_STATUS_NOTSET) || ($old_status == PublisherConstants::PUBLISHER_STATUS_SUBMITTED)) { + case Constants::PUBLISHER_STATUS_PUBLISHED: + if (($old_status == Constants::PUBLISHER_STATUS_NOTSET) || ($old_status == Constants::PUBLISHER_STATUS_SUBMITTED)) { $redirect_msg = _AM_PUBLISHER_SUBMITTED_APPROVE_SUCCESS; - $notifToDo = [PublisherConstants::PUBLISHER_NOTIFY_ITEM_PUBLISHED]; + $notifToDo = [Constants::PUBLISHER_NOTIFY_ITEM_PUBLISHED]; } else { $redirect_msg = _AM_PUBLISHER_PUBLISHED_MOD_SUCCESS; } $error_msg = _AM_PUBLISHER_ITEMNOTUPDATED; break; - case PublisherConstants::PUBLISHER_STATUS_OFFLINE: + case Constants::PUBLISHER_STATUS_OFFLINE: $redirect_msg = _AM_PUBLISHER_OFFLINE_MOD_SUCCESS; - if ($old_status == PublisherConstants::PUBLISHER_STATUS_NOTSET) { + if ($old_status == Constants::PUBLISHER_STATUS_NOTSET) { $redirect_msg = _AM_PUBLISHER_OFFLINE_CREATED_SUCCESS; } $error_msg = _AM_PUBLISHER_ITEMNOTUPDATED; break; - case PublisherConstants::PUBLISHER_STATUS_REJECTED: + case Constants::PUBLISHER_STATUS_REJECTED: $error_msg = _AM_PUBLISHER_ITEMNOTCREATED; - if ($old_status == PublisherConstants::PUBLISHER_STATUS_NOTSET) { + if ($old_status == Constants::PUBLISHER_STATUS_NOTSET) { $error_msg = _AM_PUBLISHER_ITEMNOTUPDATED; } $redirect_msg = _AM_PUBLISHER_ITEM_REJECTED; @@ -145,11 +146,11 @@ break; case 'del': - $itemObj = $helper->getHandler('item')->get($itemid); + $itemObj = $helper->getHandler('Item')->get($itemid); $confirm = Request::getInt('confirm', 0, 'POST'); if ($confirm) { - if (!$helper->getHandler('item')->delete($itemObj)) { + if (!$helper->getHandler('Item')->delete($itemObj)) { redirect_header('item.php', 2, _AM_PUBLISHER_ITEM_DELETE_ERROR . Publisher\Utility::formatErrors($itemObj->getErrors())); // exit(); } @@ -181,9 +182,9 @@ Publisher\Utility::openCollapsableBar('submiteditemstable', 'submiteditemsicon', _AM_PUBLISHER_SUBMISSIONSMNGMT, _AM_PUBLISHER_SUBMITTED_EXP); // Get the total number of submitted ITEM - $totalitems = $helper->getHandler('item')->getItemsCount(-1, [PublisherConstants::PUBLISHER_STATUS_SUBMITTED]); + $totalitems = $helper->getHandler('Item')->getItemsCount(-1, [Constants::PUBLISHER_STATUS_SUBMITTED]); - $itemsObj = $helper->getHandler('item')->getAllSubmitted($helper->getConfig('idxcat_perpage'), $submittedstartitem, -1, $orderBy, $ascOrDesc); + $itemsObj = $helper->getHandler('Item')->getAllSubmitted($helper->getConfig('idxcat_perpage'), $submittedstartitem, -1, $orderBy, $ascOrDesc); $totalItemsOnPage = count($itemsObj); @@ -232,9 +233,9 @@ Publisher\Utility::openCollapsableBar('item_publisheditemstable', 'item_publisheditemsicon', _AM_PUBLISHER_PUBLISHEDITEMS, _AM_PUBLISHER_PUBLISHED_DSC); // Get the total number of published ITEM - $totalitems = $helper->getHandler('item')->getItemsCount(-1, [PublisherConstants::PUBLISHER_STATUS_PUBLISHED]); + $totalitems = $helper->getHandler('Item')->getItemsCount(-1, [Constants::PUBLISHER_STATUS_PUBLISHED]); - $itemsObj = $helper->getHandler('item')->getAllPublished($helper->getConfig('idxcat_perpage'), $publishedstartitem, -1, $orderBy, $ascOrDesc); + $itemsObj = $helper->getHandler('Item')->getAllPublished($helper->getConfig('idxcat_perpage'), $publishedstartitem, -1, $orderBy, $ascOrDesc); $totalItemsOnPage = count($itemsObj); @@ -283,9 +284,9 @@ // Display Offline articles Publisher\Utility::openCollapsableBar('offlineitemstable', 'offlineitemsicon', _AM_PUBLISHER_ITEMS . ' ' . _CO_PUBLISHER_OFFLINE, _AM_PUBLISHER_OFFLINE_EXP); - $totalitems = $helper->getHandler('item')->getItemsCount(-1, [PublisherConstants::PUBLISHER_STATUS_OFFLINE]); + $totalitems = $helper->getHandler('Item')->getItemsCount(-1, [Constants::PUBLISHER_STATUS_OFFLINE]); - $itemsObj = $helper->getHandler('item')->getAllOffline($helper->getConfig('idxcat_perpage'), $offlinestartitem, -1, $orderBy, $ascOrDesc); + $itemsObj = $helper->getHandler('Item')->getAllOffline($helper->getConfig('idxcat_perpage'), $offlinestartitem, -1, $orderBy, $ascOrDesc); $totalItemsOnPage = count($itemsObj); @@ -336,8 +337,8 @@ Publisher\Utility::openCollapsableBar('Rejecteditemstable', 'rejecteditemsicon', _AM_PUBLISHER_REJECTED_ITEM, _AM_PUBLISHER_REJECTED_ITEM_EXP, _AM_PUBLISHER_SUBMITTED_EXP); // Get the total number of Rejected ITEM - $totalitems = $helper->getHandler('item')->getItemsCount(-1, [PublisherConstants::PUBLISHER_STATUS_REJECTED]); - $itemsObj = $helper->getHandler('item')->getAllRejected($helper->getConfig('idxcat_perpage'), $rejectedstartitem, -1, $orderBy, $ascOrDesc); + $totalitems = $helper->getHandler('Item')->getItemsCount(-1, [Constants::PUBLISHER_STATUS_REJECTED]); + $itemsObj = $helper->getHandler('Item')->getAllRejected($helper->getConfig('idxcat_perpage'), $rejectedstartitem, -1, $orderBy, $ascOrDesc); $totalItemsOnPage = count($itemsObj); @@ -404,7 +405,7 @@ function publisher_editItem($showmenu = false, $itemid = 0, $clone = false) if (0 != $itemid) { // Creating the ITEM object - $itemObj = $helper->getHandler('item')->get($itemid); + $itemObj = $helper->getHandler('Item')->get($itemid); if (!$itemObj) { redirect_header('item.php', 1, _AM_PUBLISHER_NOITEMSELECTED); @@ -414,52 +415,52 @@ function publisher_editItem($showmenu = false, $itemid = 0, $clone = false) if ($clone) { $itemObj->setNew(); $itemObj->setVar('itemid', 0); - $itemObj->setVar('status', PublisherConstants::PUBLISHER_STATUS_NOTSET); + $itemObj->setVar('status', Constants::PUBLISHER_STATUS_NOTSET); $itemObj->setVar('datesub', time()); } switch ($itemObj->status()) { - case PublisherConstants::PUBLISHER_STATUS_SUBMITTED: + case Constants::PUBLISHER_STATUS_SUBMITTED: $breadcrumbAction1 = _CO_PUBLISHER_SUBMITTED; $breadcrumbAction2 = _AM_PUBLISHER_APPROVING; $pageTitle = _AM_PUBLISHER_SUBMITTED_TITLE; $pageInfo = _AM_PUBLISHER_SUBMITTED_INFO; $buttonCaption = _AM_PUBLISHER_APPROVE; - $newStatus = PublisherConstants::PUBLISHER_STATUS_PUBLISHED; + $newStatus = Constants::PUBLISHER_STATUS_PUBLISHED; break; - case PublisherConstants::PUBLISHER_STATUS_PUBLISHED: + case Constants::PUBLISHER_STATUS_PUBLISHED: $breadcrumbAction1 = _CO_PUBLISHER_PUBLISHED; $breadcrumbAction2 = _AM_PUBLISHER_EDITING; $pageTitle = _AM_PUBLISHER_PUBLISHEDEDITING; $pageInfo = _AM_PUBLISHER_PUBLISHEDEDITING_INFO; $buttonCaption = _AM_PUBLISHER_MODIFY; - $newStatus = PublisherConstants::PUBLISHER_STATUS_PUBLISHED; + $newStatus = Constants::PUBLISHER_STATUS_PUBLISHED; break; - case PublisherConstants::PUBLISHER_STATUS_OFFLINE: + case Constants::PUBLISHER_STATUS_OFFLINE: $breadcrumbAction1 = _CO_PUBLISHER_OFFLINE; $breadcrumbAction2 = _AM_PUBLISHER_EDITING; $pageTitle = _AM_PUBLISHER_OFFLINEEDITING; $pageInfo = _AM_PUBLISHER_OFFLINEEDITING_INFO; $buttonCaption = _AM_PUBLISHER_MODIFY; - $newStatus = PublisherConstants::PUBLISHER_STATUS_OFFLINE; + $newStatus = Constants::PUBLISHER_STATUS_OFFLINE; break; - case PublisherConstants::PUBLISHER_STATUS_REJECTED: + case Constants::PUBLISHER_STATUS_REJECTED: $breadcrumbAction1 = _CO_PUBLISHER_REJECTED; $breadcrumbAction2 = _AM_PUBLISHER_REJECTED; $pageTitle = _AM_PUBLISHER_REJECTED_EDIT; $pageInfo = _AM_PUBLISHER_REJECTED_EDIT_INFO; $buttonCaption = _AM_PUBLISHER_MODIFY; - $newStatus = PublisherConstants::PUBLISHER_STATUS_REJECTED; + $newStatus = Constants::PUBLISHER_STATUS_REJECTED; break; - case PublisherConstants::PUBLISHER_STATUS_NOTSET: // Then it's a clone... + case Constants::PUBLISHER_STATUS_NOTSET: // Then it's a clone... $breadcrumbAction1 = _AM_PUBLISHER_ITEMS; $breadcrumbAction2 = _AM_PUBLISHER_CLONE_NEW; $buttonCaption = _AM_PUBLISHER_CREATE; - $newStatus = PublisherConstants::PUBLISHER_STATUS_PUBLISHED; + $newStatus = Constants::PUBLISHER_STATUS_PUBLISHED; $pageTitle = _AM_PUBLISHER_ITEM_DUPLICATING; $pageInfo = _AM_PUBLISHER_ITEM_DUPLICATING_DSC; break; @@ -471,7 +472,7 @@ function publisher_editItem($showmenu = false, $itemid = 0, $clone = false) $pageTitle = _AM_PUBLISHER_PUBLISHEDEDITING; $pageInfo = _AM_PUBLISHER_PUBLISHEDEDITING_INFO; $buttonCaption = _AM_PUBLISHER_MODIFY; - $newStatus = PublisherConstants::PUBLISHER_STATUS_PUBLISHED; + $newStatus = Constants::PUBLISHER_STATUS_PUBLISHED; break; } @@ -488,14 +489,14 @@ function publisher_editItem($showmenu = false, $itemid = 0, $clone = false) } else { // there's no parameter, so we're adding an item - $itemObj = $helper->getHandler('item')->create(); + $itemObj = $helper->getHandler('Item')->create(); $itemObj->setVarsFromRequest(); - $categoryObj = $helper->getHandler('category')->create(); + $categoryObj = $helper->getHandler('Category')->create(); $breadcrumbAction1 = _AM_PUBLISHER_ITEMS; $breadcrumbAction2 = _AM_PUBLISHER_CREATINGNEW; $buttonCaption = _AM_PUBLISHER_CREATE; - $newStatus = PublisherConstants::PUBLISHER_STATUS_PUBLISHED; + $newStatus = Constants::PUBLISHER_STATUS_PUBLISHED; $categoryObj->setVar('categoryid', Request::getInt('categoryid', 0, 'GET')); diff --git a/admin/main.php b/admin/main.php index 5a12f472..6fbac87f 100644 --- a/admin/main.php +++ b/admin/main.php @@ -20,11 +20,12 @@ use Xmf\Request; use XoopsModules\Publisher; +use XoopsModules\Publisher\Constants; require_once __DIR__ . '/admin_header.php'; require_once $GLOBALS['xoops']->path('class/xoopslists.php'); require_once $GLOBALS['xoops']->path('class/pagenav.php'); -//require_once __DIR__ . '/../class/Utility.php'; +// require_once __DIR__ . '/../class/Utility.php'; require_once __DIR__ . '/../include/common.php'; $itemid = Request::getInt('itemid', 0, 'POST'); @@ -47,22 +48,22 @@ //publisher_adminMenu(0, _AM_PUBLISHER_INDEX); // Total ITEMs -- includes everything on the table -$totalitems = $helper->getHandler('item')->getItemsCount(); +$totalitems = $helper->getHandler('Item')->getItemsCount(); // Total categories -$totalcategories = $helper->getHandler('category')->getCategoriesCount(-1); +$totalcategories = $helper->getHandler('Category')->getCategoriesCount(-1); // Total submitted ITEMs -$totalsubmitted = $helper->getHandler('item')->getItemsCount(-1, [PublisherConstants::PUBLISHER_STATUS_SUBMITTED]); +$totalsubmitted = $helper->getHandler('Item')->getItemsCount(-1, [Constants::PUBLISHER_STATUS_SUBMITTED]); // Total published ITEMs -$totalpublished = $helper->getHandler('item')->getItemsCount(-1, [PublisherConstants::PUBLISHER_STATUS_PUBLISHED]); +$totalpublished = $helper->getHandler('Item')->getItemsCount(-1, [Constants::PUBLISHER_STATUS_PUBLISHED]); // Total offline ITEMs -$totaloffline = $helper->getHandler('item')->getItemsCount(-1, [PublisherConstants::PUBLISHER_STATUS_OFFLINE]); +$totaloffline = $helper->getHandler('Item')->getItemsCount(-1, [Constants::PUBLISHER_STATUS_OFFLINE]); // Total rejected -$totalrejected = $helper->getHandler('item')->getItemsCount(-1, [PublisherConstants::PUBLISHER_STATUS_REJECTED]); +$totalrejected = $helper->getHandler('Item')->getItemsCount(-1, [Constants::PUBLISHER_STATUS_REJECTED]); // Check Path Configuration if ((Publisher\Utility::getPathStatus('root', true) < 0) @@ -160,38 +161,38 @@ } switch ($statussel) { - case PublisherConstants::PUBLISHER_STATUS_ALL: + case Constants::PUBLISHER_STATUS_ALL: $selectedtxt0 = 'selected'; $caption = _AM_PUBLISHER_ALL; $cond = ''; $status_explaination = _AM_PUBLISHER_ALL_EXP; break; - case PublisherConstants::PUBLISHER_STATUS_SUBMITTED: + case Constants::PUBLISHER_STATUS_SUBMITTED: $selectedtxt1 = 'selected'; $caption = _CO_PUBLISHER_SUBMITTED; - $cond = ' WHERE status = ' . PublisherConstants::PUBLISHER_STATUS_SUBMITTED . ' '; + $cond = ' WHERE status = ' . Constants::PUBLISHER_STATUS_SUBMITTED . ' '; $status_explaination = _AM_PUBLISHER_SUBMITTED_EXP; break; - case PublisherConstants::PUBLISHER_STATUS_PUBLISHED: + case Constants::PUBLISHER_STATUS_PUBLISHED: $selectedtxt2 = 'selected'; $caption = _CO_PUBLISHER_PUBLISHED; - $cond = ' WHERE status = ' . PublisherConstants::PUBLISHER_STATUS_PUBLISHED . ' '; + $cond = ' WHERE status = ' . Constants::PUBLISHER_STATUS_PUBLISHED . ' '; $status_explaination = _AM_PUBLISHER_PUBLISHED_EXP; break; - case PublisherConstants::PUBLISHER_STATUS_OFFLINE: + case Constants::PUBLISHER_STATUS_OFFLINE: $selectedtxt3 = 'selected'; $caption = _CO_PUBLISHER_OFFLINE; - $cond = ' WHERE status = ' . PublisherConstants::PUBLISHER_STATUS_OFFLINE . ' '; + $cond = ' WHERE status = ' . Constants::PUBLISHER_STATUS_OFFLINE . ' '; $status_explaination = _AM_PUBLISHER_OFFLINE_EXP; break; - case PublisherConstants::PUBLISHER_STATUS_REJECTED: + case Constants::PUBLISHER_STATUS_REJECTED: $selectedtxt4 = 'selected'; $caption = _CO_PUBLISHER_REJECTED; - $cond = ' WHERE status = ' . PublisherConstants::PUBLISHER_STATUS_REJECTED . ' '; + $cond = ' WHERE status = ' . Constants::PUBLISHER_STATUS_REJECTED . ' '; $status_explaination = _AM_PUBLISHER_REJECTED_ITEM_EXP; break; } @@ -236,10 +237,10 @@ // Get number of entries in the selected state $statusSelected = (0 == $statussel) ? -1 : $statussel; -$numrows = $helper->getHandler('item')->getItemsCount(-1, $statusSelected); +$numrows = $helper->getHandler('Item')->getItemsCount(-1, $statusSelected); // creating the Q&As objects -$itemsObj = $helper->getHandler('item')->getItems($helper->getConfig('idxcat_perpage'), $startentry, $statusSelected, -1, $sortsel, $ordersel); +$itemsObj = $helper->getHandler('Item')->getItems($helper->getConfig('idxcat_perpage'), $startentry, $statusSelected, -1, $sortsel, $ordersel); $totalItemsOnPage = count($itemsObj); @@ -252,7 +253,7 @@ $approve = ''; switch ($itemsObj[$i]->status()) { - case PublisherConstants::PUBLISHER_STATUS_SUBMITTED: + case Constants::PUBLISHER_STATUS_SUBMITTED: $statustxt = _CO_PUBLISHER_SUBMITTED; $approve = "itemid() . "'>getModule()->dirname() . "/assets/images/links/clone.gif' title='" . _AM_PUBLISHER_CLONE_ITEM . "' alt='" . _AM_PUBLISHER_CLONE_ITEM . "'> "; break; - case PublisherConstants::PUBLISHER_STATUS_OFFLINE: + case Constants::PUBLISHER_STATUS_OFFLINE: $statustxt = _CO_PUBLISHER_OFFLINE; $approve = ''; $modify = "getModule()->dirname() . "/assets/images/links/edit.gif' title='" . _AM_PUBLISHER_ITEM_EDIT . "' alt='" . _AM_PUBLISHER_ITEM_EDIT . "'> "; @@ -288,7 +289,7 @@ "getModule()->dirname() . "/assets/images/links/clone.gif' title='" . _AM_PUBLISHER_CLONE_ITEM . "' alt='" . _AM_PUBLISHER_CLONE_ITEM . "'> "; break; - case PublisherConstants::PUBLISHER_STATUS_REJECTED: + case Constants::PUBLISHER_STATUS_REJECTED: $statustxt = _CO_PUBLISHER_REJECTED; $approve = ''; $modify = "get('publisher_addMime'); $mimeErrors = $session->get('publisher_addMimeErr'); @@ -207,7 +207,7 @@ public static function add() } if ($hasErrors) { - $session = PublisherSession::getInstance(); + $session = Session::getInstance(); $mime = []; $mime['mime_ext'] = $mimeExt; $mime['mime_name'] = $mimeName; @@ -219,14 +219,14 @@ public static function add() header('Location: ' . Publisher\Utility::makeUri(PUBLISHER_ADMIN_URL . '/mimetypes.php', ['op' => 'add'], false)); } - $mimeType = $helper->getHandler('mimetype')->create(); + $mimeType = $helper->getHandler('Mimetype')->create(); $mimeType->setVar('mime_ext', $mimeExt); $mimeType->setVar('mime_name', $mimeName); $mimeType->setVar('mime_types', $mimeTypes); $mimeType->setVar('mime_admin', $mimeAdmin); $mimeType->setVar('mime_user', $mimeUser); - if (!$helper->getHandler('mimetype')->insert($mimeType)) { + if (!$helper->getHandler('Mimetype')->insert($mimeType)) { redirect_header(PUBLISHER_ADMIN_URL . "/mimetypes.php?op=manage&limit=$limit&start=$start", 3, _AM_PUBLISHER_MESSAGE_ADD_MIME_ERROR); } else { self::clearAddSessionVars(); @@ -245,8 +245,8 @@ public static function delete() } else { $mimeId = Request::getInt('id', 0, 'GET'); } - $mimeType = $helper->getHandler('mimetype')->get($mimeId); // Retrieve mimetype object - if (!$helper->getHandler('mimetype')->delete($mimeType, true)) { + $mimeType = $helper->getHandler('Mimetype')->get($mimeId); // Retrieve mimetype object + if (!$helper->getHandler('Mimetype')->delete($mimeType, true)) { redirect_header(PUBLISHER_ADMIN_URL . "/mimetypes.php?op=manage&id=$mimeId&limit=$limit&start=$start", 3, _AM_PUBLISHER_MESSAGE_DELETE_MIME_ERROR); } else { header('Location: ' . PUBLISHER_ADMIN_URL . "/mimetypes.php?op=manage&limit=$limit&start=$start"); @@ -265,10 +265,10 @@ public static function edit() } else { $mimeId = Request::getInt('id', 0, 'GET'); } - $mimeTypeObj = $helper->getHandler('mimetype')->get($mimeId); // Retrieve mimetype object + $mimeTypeObj = $helper->getHandler('Mimetype')->get($mimeId); // Retrieve mimetype object if (!Request::getString('edit_mime', '', 'POST')) { - $session = PublisherSession::getInstance(); + $session = Session::getInstance(); $mimeType = $session->get('publisher_editMime_' . $mimeId); $mimeErrors = $session->get('publisher_editMimeErr_' . $mimeId); @@ -369,7 +369,7 @@ public static function edit() } if ($hasErrors) { - $session = PublisherSession::getInstance(); + $session = Session::getInstance(); $mime = []; $mime['mime_ext'] = Request::getString('mime_ext', '', 'POST'); $mime['mime_name'] = Request::getString('mime_name', '', 'POST'); @@ -387,7 +387,7 @@ public static function edit() $mimeTypeObj->setVar('mime_admin', $mimeAdmin); $mimeTypeObj->setVar('mime_user', $mimeUser); - if (!$helper->getHandler('mimetype')->insert($mimeTypeObj, true)) { + if (!$helper->getHandler('Mimetype')->insert($mimeTypeObj, true)) { redirect_header(PUBLISHER_ADMIN_URL . "/mimetypes.php?op=edit&id=$mimeId", 3, _AM_PUBLISHER_MESSAGE_EDIT_MIME_ERROR); } else { self::clearEditSessionVars($mimeId); @@ -399,7 +399,7 @@ public static function edit() public static function manage() { $helper = Publisher\Helper::getInstance(); - /** @var \XoopsModules\Publisher\Utility $utility */ + /** @var Publisher\Utility $utility */ $utility = new Publisher\Utility(); global $imagearray, $start, $limit, $aSortBy, $aOrderBy, $aLimitBy, $aSearchBy; @@ -408,7 +408,7 @@ public static function manage() $crit = new \Criteria('mime_id', '(' . implode($aMimes, ',') . ')', 'IN'); - if ($helper->getHandler('mimetype')->deleteAll($crit)) { + if ($helper->getHandler('Mimetype')->deleteAll($crit)) { header('Location: ' . PUBLISHER_ADMIN_URL . "/mimetypes.php?limit=$limit&start=$start"); } else { redirect_header(PUBLISHER_ADMIN_URL . "/mimetypes.php?limit=$limit&start=$start", 3, _AM_PUBLISHER_MESSAGE_DELETE_MIME_ERROR); @@ -436,8 +436,8 @@ public static function manage() $crit->setStart($start); $crit->setLimit($limit); $crit->setSort($sort); - $mimetypes = $helper->getHandler('mimetype')->getObjects($crit); // Retrieve a list of all mimetypes - $mimeCount = $helper->getHandler('mimetype')->getCount(); + $mimetypes = $helper->getHandler('Mimetype')->getObjects($crit); // Retrieve a list of all mimetypes + $mimeCount = $helper->getHandler('Mimetype')->getCount(); $nav = new \XoopsPageNav($mimeCount, $limit, $start, 'start', "op=manage&limit=$limit"); echo ""; @@ -550,7 +550,7 @@ public static function search() $crit = new \Criteria('mime_id', '(' . implode($aMimes, ',') . ')', 'IN'); - if ($helper->getHandler('mimetype')->deleteAll($crit)) { + if ($helper->getHandler('Mimetype')->deleteAll($crit)) { header('Location: ' . PUBLISHER_ADMIN_URL . "/mimetypes.php?limit=$limit&start=$start"); } else { redirect_header(PUBLISHER_ADMIN_URL . "/mimetypes.php?limit=$limit&start=$start", 3, _AM_PUBLISHER_MESSAGE_DELETE_MIME_ERROR); @@ -606,8 +606,8 @@ public static function search() $crit->setOrder($order); $crit->setLimit($limit); $crit->setStart($start); - $mimeCount = $helper->getHandler('mimetype')->getCount($crit); - $mimetypes = $helper->getHandler('mimetype')->getObjects($crit); + $mimeCount = $helper->getHandler('Mimetype')->getCount($crit); + $mimetypes = $helper->getHandler('Mimetype')->getObjects($crit); $nav = new \XoopsPageNav($mimeCount, $limit, $start, 'start', "op=search&limit=$limit&order=$order&sort=$sort&mime_search=1&search_by=$searchField&search_text=" . htmlentities($searchText, ENT_QUOTES)); // Display results echo ''; @@ -735,7 +735,7 @@ public static function updateMimeValue() ]; $helper = Publisher\Helper::getInstance(); - $mimeTypeObj = $helper->getHandler('mimetype')->get($hiddens['id']); + $mimeTypeObj = $helper->getHandler('Mimetype')->get($hiddens['id']); if (Request::hasVar('mime_admin')) { $hiddens['mime_admin'] = Request::getInt('mime_admin', 0, 'GET'); $msg = sprintf(_AM_PUBLISHER_MIME_ACCESS_CONFIRM_ADMIN, $mimeTypeObj->getVar('mime_name')); @@ -762,7 +762,7 @@ public static function confirmUpdateMimeValue() redirect_header(PUBLISHER_ADMIN_URL . '/mimetypes.php', 3, _AM_PUBLISHER_MESSAGE_NO_ID); } - $mimeTypeObj = $helper->getHandler('mimetype')->get($mimeId); + $mimeTypeObj = $helper->getHandler('Mimetype')->get($mimeId); if (-1 !== ($mimeAdmin = Request::getInt('mime_admin', -1, 'POST'))) { $mimeAdmin = self::changeMimeValue($mimeAdmin); @@ -771,7 +771,7 @@ public static function confirmUpdateMimeValue() $mimeUser = self::changeMimeValue($mimeUser); $mimeTypeObj->setVar('mime_user', $mimeUser); } - if ($helper->getHandler('mimetype')->insert($mimeTypeObj, true)) { + if ($helper->getHandler('Mimetype')->insert($mimeTypeObj, true)) { header('Location: ' . PUBLISHER_ADMIN_URL . "/mimetypes.php?limit=$limit&start=$start"); } else { redirect_header(PUBLISHER_ADMIN_URL . "/mimetypes.php?limit=$limit&start=$start", 3); @@ -796,7 +796,7 @@ protected static function changeMimeValue($mimeValue) protected static function clearAddSessionVars() { - $session = PublisherSession::getInstance(); + $session = Session::getInstance(); $session->del('publisher_addMime'); $session->del('publisher_addMimeErr'); } @@ -813,7 +813,7 @@ public static function clearAddSession() public static function clearEditSessionVars($id) { $id = (int)$id; - $session = PublisherSession::getInstance(); + $session = Session::getInstance(); $session->del("publisher_editMime_$id"); $session->del("publisher_editMimeErr_$id"); } diff --git a/admin/permissions.php b/admin/permissions.php index 38c0a772..48772098 100644 --- a/admin/permissions.php +++ b/admin/permissions.php @@ -19,6 +19,7 @@ */ use XoopsModules\Publisher; +use XoopsModules\Publisher\Constants; require_once __DIR__ . '/admin_header.php'; require_once __DIR__ . '/../include/common.php'; @@ -80,32 +81,32 @@ echo "
\n"; Publisher\Utility::openCollapsableBar('permissionstable_form', 'permissionsicon_form', _AM_PUBLISHER_PERMISSIONS_FORM, _AM_PUBLISHER_PERMISSIONS_FORM_DSC); $form_options = [ - PublisherConstants::PUBLISHER_SUMMARY => _AM_PUBLISHER_SUMMARY, - //PublisherConstants::PUBLISHER_DISPLAY_SUMMARY => _CO_PUBLISHER_DISPLAY_SUMMARY, - PublisherConstants::PUBLISHER_AVAILABLE_PAGE_WRAP => _CO_PUBLISHER_AVAILABLE_PAGE_WRAP, - PublisherConstants::PUBLISHER_ITEM_TAG => _AM_PUBLISHER_ITEM_TAG, - PublisherConstants::PUBLISHER_IMAGE_ITEM => _AM_PUBLISHER_IMAGE_ITEM, + Constants::PUBLISHER_SUMMARY => _AM_PUBLISHER_SUMMARY, + //Constants::PUBLISHER_DISPLAY_SUMMARY => _CO_PUBLISHER_DISPLAY_SUMMARY, + Constants::PUBLISHER_AVAILABLE_PAGE_WRAP => _CO_PUBLISHER_AVAILABLE_PAGE_WRAP, + Constants::PUBLISHER_ITEM_TAG => _AM_PUBLISHER_ITEM_TAG, + Constants::PUBLISHER_IMAGE_ITEM => _AM_PUBLISHER_IMAGE_ITEM, //_PUBLISHER_IMAGE_UPLOAD => _AM_PUBLISHER_IMAGE_UPLOAD, - PublisherConstants::PUBLISHER_ITEM_UPLOAD_FILE => _CO_PUBLISHER_ITEM_UPLOAD_FILE, - PublisherConstants::PUBLISHER_UID => _CO_PUBLISHER_UID, - PublisherConstants::PUBLISHER_DATESUB => _CO_PUBLISHER_DATESUB, - PublisherConstants::PUBLISHER_STATUS => _CO_PUBLISHER_STATUS, - PublisherConstants::PUBLISHER_ITEM_SHORT_URL => _CO_PUBLISHER_ITEM_SHORT_URL, - PublisherConstants::PUBLISHER_ITEM_META_KEYWORDS => _CO_PUBLISHER_ITEM_META_KEYWORDS, - PublisherConstants::PUBLISHER_ITEM_META_DESCRIPTION => _CO_PUBLISHER_ITEM_META_DESCRIPTION, - PublisherConstants::PUBLISHER_WEIGHT => _CO_PUBLISHER_WEIGHT, - PublisherConstants::PUBLISHER_ALLOWCOMMENTS => _CO_PUBLISHER_ALLOWCOMMENTS, - //PublisherConstants::PUBLISHER_PERMISSIONS_ITEM => _CO_PUBLISHER_PERMISSIONS_ITEM, - //PublisherConstants::PUBLISHER_PERMISSIONS_ITEM_DSC => _CO_PUBLISHER_PERMISSIONS_ITEM_DSC, - // PublisherConstants::PUBLISHER_PARTIAL_VIEW => _CO_PUBLISHER_PARTIAL_VIEW, - PublisherConstants::PUBLISHER_DOHTML => _CO_PUBLISHER_DOHTML, - PublisherConstants::PUBLISHER_DOSMILEY => _CO_PUBLISHER_DOSMILEY, - PublisherConstants::PUBLISHER_DOXCODE => _CO_PUBLISHER_DOXCODE, - PublisherConstants::PUBLISHER_DOIMAGE => _CO_PUBLISHER_DOIMAGE, - PublisherConstants::PUBLISHER_DOLINEBREAK => _CO_PUBLISHER_DOLINEBREAK, - PublisherConstants::PUBLISHER_NOTIFY => _AM_PUBLISHER_NOTIFY, - PublisherConstants::PUBLISHER_SUBTITLE => _CO_PUBLISHER_SUBTITLE, - PublisherConstants::PUBLISHER_AUTHOR_ALIAS => _CO_PUBLISHER_AUTHOR_ALIAS + Constants::PUBLISHER_ITEM_UPLOAD_FILE => _CO_PUBLISHER_ITEM_UPLOAD_FILE, + Constants::PUBLISHER_UID => _CO_PUBLISHER_UID, + Constants::PUBLISHER_DATESUB => _CO_PUBLISHER_DATESUB, + Constants::PUBLISHER_STATUS => _CO_PUBLISHER_STATUS, + Constants::PUBLISHER_ITEM_SHORT_URL => _CO_PUBLISHER_ITEM_SHORT_URL, + Constants::PUBLISHER_ITEM_META_KEYWORDS => _CO_PUBLISHER_ITEM_META_KEYWORDS, + Constants::PUBLISHER_ITEM_META_DESCRIPTION => _CO_PUBLISHER_ITEM_META_DESCRIPTION, + Constants::PUBLISHER_WEIGHT => _CO_PUBLISHER_WEIGHT, + Constants::PUBLISHER_ALLOWCOMMENTS => _CO_PUBLISHER_ALLOWCOMMENTS, + //Constants::PUBLISHER_PERMISSIONS_ITEM => _CO_PUBLISHER_PERMISSIONS_ITEM, + //Constants::PUBLISHER_PERMISSIONS_ITEM_DSC => _CO_PUBLISHER_PERMISSIONS_ITEM_DSC, + // Constants::PUBLISHER_PARTIAL_VIEW => _CO_PUBLISHER_PARTIAL_VIEW, + Constants::PUBLISHER_DOHTML => _CO_PUBLISHER_DOHTML, + Constants::PUBLISHER_DOSMILEY => _CO_PUBLISHER_DOSMILEY, + Constants::PUBLISHER_DOXCODE => _CO_PUBLISHER_DOXCODE, + Constants::PUBLISHER_DOIMAGE => _CO_PUBLISHER_DOIMAGE, + Constants::PUBLISHER_DOLINEBREAK => _CO_PUBLISHER_DOLINEBREAK, + Constants::PUBLISHER_NOTIFY => _AM_PUBLISHER_NOTIFY, + Constants::PUBLISHER_SUBTITLE => _CO_PUBLISHER_SUBTITLE, + Constants::PUBLISHER_AUTHOR_ALIAS => _CO_PUBLISHER_AUTHOR_ALIAS ]; $form_submit = new \XoopsGroupPermForm('', $helper->getModule()->mid(), 'form_view', '', 'admin/permissions.php'); foreach ($form_options as $key => $value) { @@ -131,8 +132,8 @@ echo "
\n"; Publisher\Utility::openCollapsableBar('permissionstable_global', 'permissionsicon_global', _AM_PUBLISHER_PERMISSIONS_GLOBAL, _AM_PUBLISHER_PERMISSIONS_GLOBAL_DSC); $form_options = [ - PublisherConstants::PUBLISHER_SEARCH => _AM_PUBLISHER_SEARCH, - PublisherConstants::PUBLISHER_RATE => _AM_PUBLISHER_RATE + Constants::PUBLISHER_SEARCH => _AM_PUBLISHER_SEARCH, + Constants::PUBLISHER_RATE => _AM_PUBLISHER_RATE ]; $form_submit = new \XoopsGroupPermForm('', $helper->getModule()->mid(), 'global', '', 'admin/permissions.php'); foreach ($form_options as $key => $value) { diff --git a/archive.php b/archive.php index 4bd271bd..991e3422 100644 --- a/archive.php +++ b/archive.php @@ -79,12 +79,12 @@ $criteria = new \CriteriaCompo(); $criteria->add(new \Criteria('status', 2), 'AND'); $criteria->add(new \Criteria('datesub', time(), '<='), 'AND'); -$categoriesGranted = $helper->getHandler('permission')->getGrantedItems('category_read'); +$categoriesGranted = $helper->getHandler('Permission')->getGrantedItems('category_read'); $criteria->add(new \Criteria('categoryid', '(' . implode(',', $categoriesGranted) . ')', 'IN')); $criteria->setSort('datesub'); $criteria->setOrder('DESC'); //Get all articles dates as an array to save memory -$items = $helper->getHandler('item')->getAll($criteria, ['datesub'], false); +$items = $helper->getHandler('Item')->getAll($criteria, ['datesub'], false); $itemsCount = count($items); if (!($itemsCount > 0)) { @@ -171,12 +171,12 @@ $count = 0; - $itemHandler = $helper->getHandler('item'); + $itemHandler = $helper->getHandler('Item'); $itemHandler->table_link = $GLOBALS['xoopsDB']->prefix($helper->getDirname() . '_categories'); $itemHandler->field_link = 'categoryid'; $itemHandler->field_object = 'categoryid'; // Categories for which user has access - $categoriesGranted = $helper->getHandler('permission')->getGrantedItems('category_read'); + $categoriesGranted = $helper->getHandler('Permission')->getGrantedItems('category_read'); $grantedCategories = new \Criteria('l.categoryid', '(' . implode(',', $categoriesGranted) . ')', 'IN'); $criteria = new \CriteriaCompo(); $criteria->add($grantedCategories, 'AND'); diff --git a/author_items.php b/author_items.php index 9cdb4c6a..1be2cf2c 100644 --- a/author_items.php +++ b/author_items.php @@ -19,6 +19,8 @@ */ use Xmf\Request; +use XoopsModules\Publisher; +use XoopsModules\Publisher\Constants; require_once __DIR__ . '/header.php'; @@ -49,7 +51,7 @@ $criteria = new \CriteriaCompo(new \Criteria('datesub', time(), '<=')); $criteria->add(new \Criteria('uid', $uid)); -$items = $helper->getHandler('item')->getItems($limit = 0, $start = 0, [PublisherConstants::PUBLISHER_STATUS_PUBLISHED], -1, 'datesub', 'DESC', '', true, $criteria); +$items = $helper->getHandler('Item')->getItems($limit = 0, $start = 0, [Constants::PUBLISHER_STATUS_PUBLISHED], -1, 'datesub', 'DESC', '', true, $criteria); unset($criteria); $count = count($items); @@ -63,7 +65,7 @@ //$xoopsLocal = new \XoopsLocal(); $categories = []; if ($count > 0) { - /** @var PublisherItem $item */ + /** @var Publisher\Item $item */ foreach ($items as $item) { $catid = $item->categoryid(); if (!isset($categories[$catid])) { @@ -95,7 +97,7 @@ /** * Generating meta information for this page */ -$publisherMetagen = new PublisherMetagen($title, '', $title); +$publisherMetagen = new Publisher\Metagen($title, '', $title); $publisherMetagen->createMetaTags(); require_once $GLOBALS['xoops']->path('footer.php'); diff --git a/backend.php b/backend.php index 8044bc74..71186d8e 100644 --- a/backend.php +++ b/backend.php @@ -35,7 +35,7 @@ $categoryid = Request::getInt('categoryid', -1, 'GET'); if ($categoryid != -1) { - $categoryObj = $helper->getHandler('category')->get($categoryid); + $categoryObj = $helper->getHandler('Category')->get($categoryid); } header('Content-Type:text/xml; charset=' . _CHARSET); @@ -80,7 +80,7 @@ } $tpl->assign('image_width', $width); $tpl->assign('image_height', $height); - $sarray = $helper->getHandler('item')->getAllPublished(10, 0, $categoryid); + $sarray = $helper->getHandler('Item')->getAllPublished(10, 0, $categoryid); if (!empty($sarray) && is_array($sarray)) { $count = $sarray; foreach ($sarray as $item) { diff --git a/blocks/category_items_sel.php b/blocks/category_items_sel.php index 94a2c007..061a779d 100644 --- a/blocks/category_items_sel.php +++ b/blocks/category_items_sel.php @@ -19,10 +19,11 @@ */ use XoopsModules\Publisher; +use XoopsModules\Publisher\Constants; -// defined('XOOPS_ROOT_PATH') || exit('Restricted access.'); +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); -require_once dirname(__DIR__) . '/include/common.php'; +require_once __DIR__ . '/../include/common.php'; /** * @param $options @@ -35,7 +36,7 @@ function publisher_category_items_sel_show($options) $block = $item = []; - $categories = $helper->getHandler('category')->getCategories(0, 0, -1); + $categories = $helper->getHandler('Category')->getCategories(0, 0, -1); if (0 === count($categories)) { return $block; @@ -55,7 +56,7 @@ function publisher_category_items_sel_show($options) } $criteria = new \Criteria('categoryid', $catID); - $items = $helper->getHandler('item')->getItems($limit, $start, [PublisherConstants::PUBLISHER_STATUS_PUBLISHED], -1, $sort, $order, '', true, $criteria, true); + $items = $helper->getHandler('Item')->getItems($limit, $start, [Constants::PUBLISHER_STATUS_PUBLISHED], -1, $sort, $order, '', true, $criteria, true); unset($criteria); if (0 === count($items)) { @@ -90,10 +91,10 @@ function publisher_category_items_sel_show($options) */ function publisher_category_items_sel_edit($options) { - require_once PUBLISHER_ROOT_PATH . '/class/blockform.php'; + // require_once PUBLISHER_ROOT_PATH . '/class/blockform.php'; xoops_load('XoopsFormLoader'); - $form = new PublisherBlockForm(); + $form = new Publisher\BlockForm(); $catEle = new \XoopsFormLabel(_MB_PUBLISHER_SELECTCAT, Publisher\Utility::createCategorySelect($options[0]), 'options[0]'); $orderEle = new \XoopsFormSelect(_MB_PUBLISHER_ORDER, 'options[1]', $options[1]); diff --git a/blocks/date_to_date.php b/blocks/date_to_date.php index 45c3639b..e02e54ed 100644 --- a/blocks/date_to_date.php +++ b/blocks/date_to_date.php @@ -21,9 +21,9 @@ use XoopsModules\Publisher; -// defined('XOOPS_ROOT_PATH') || exit('Restricted access.'); +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); -require_once dirname(__DIR__) . '/include/common.php'; +require_once __DIR__ . '/../include/common.php'; /** * @param $options @@ -44,7 +44,7 @@ function publisher_date_to_date_show($options) $criteria->setOrder('DESC'); // creating the ITEM objects that belong to the selected category - $itemsObj = $helper->getHandler('item')->getObjects($criteria); + $itemsObj = $helper->getHandler('Item')->getObjects($criteria); $totalItems = count($itemsObj); if ($itemsObj) { @@ -79,11 +79,11 @@ function publisher_date_to_date_show($options) */ function publisher_date_to_date_edit($options) { - require_once PUBLISHER_ROOT_PATH . '/class/blockform.php'; + // require_once PUBLISHER_ROOT_PATH . '/class/blockform.php'; xoops_load('XoopsFormLoader'); xoops_load('XoopsFormTextDateSelect'); - $form = new PublisherBlockForm(); + $form = new Publisher\BlockForm(); $fromEle = new \XoopsFormTextDateSelect(_MB_PUBLISHER_FROM, 'options[0]', 15, strtotime($options[0])); // $fromEle->setNocolspan(); $untilEle = new \XoopsFormTextDateSelect(_MB_PUBLISHER_UNTIL, 'options[1]', 15, isset($options[1]) ? strtotime($options[1]) : ''); diff --git a/blocks/items_columns.php b/blocks/items_columns.php index 7b09c8fa..a12f0cb1 100644 --- a/blocks/items_columns.php +++ b/blocks/items_columns.php @@ -21,9 +21,9 @@ use XoopsModules\Publisher; -// defined('XOOPS_ROOT_PATH') || exit('Restricted access.'); +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); -require_once dirname(__DIR__) . '/include/common.php'; +require_once __DIR__ . '/../include/common.php'; /*** * Function To Show Publisher Items From Categories In Their Own Columns @@ -51,7 +51,7 @@ function publisher_items_columns_show($options) $selCategoriesObj = []; //get permited categories only once - $categoriesObj = $helper->getHandler('category')->getCategories(0, 0, -1); + $categoriesObj = $helper->getHandler('Category')->getCategories(0, 0, -1); //if not selected 'all', let's get the selected ones if (!in_array(0, $selCategories)) { @@ -79,7 +79,7 @@ function publisher_items_columns_show($options) $columns = $mainItem = $subItem = []; foreach ($selCategoriesObj as $categoryId => $mainItemCatObj) { - $categoryItemsObj = $helper->getHandler('item')->getAllPublished($optCatItems, 0, $categoryId); + $categoryItemsObj = $helper->getHandler('Item')->getAllPublished($optCatItems, 0, $categoryId); $scount = count($categoryItemsObj); if ($scount > 0 && is_array($categoryItemsObj)) { reset($categoryItemsObj); @@ -147,10 +147,10 @@ function publisher_items_columns_show($options) */ function publisher_items_columns_edit($options) { - require_once PUBLISHER_ROOT_PATH . '/class/blockform.php'; + // require_once PUBLISHER_ROOT_PATH . '/class/blockform.php'; xoops_load('XoopsFormLoader'); - $form = new PublisherBlockForm(); + $form = new Publisher\BlockForm(); $colEle = new \XoopsFormSelect(_MB_PUBLISHER_NUMBER_COLUMN_VIEW, 'options[0]', $options[0]); $colEle->addOptionArray([ '1' => 1, diff --git a/blocks/items_menu.php b/blocks/items_menu.php index 8376b835..2d625224 100644 --- a/blocks/items_menu.php +++ b/blocks/items_menu.php @@ -22,9 +22,9 @@ use Xmf\Request; use XoopsModules\Publisher; -// defined('XOOPS_ROOT_PATH') || exit('Restricted access.'); +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); -require_once dirname(__DIR__) . '/include/common.php'; +require_once __DIR__ . '/../include/common.php'; /** * @param $options @@ -38,7 +38,7 @@ function publisher_items_menu_show($options) $helper = Publisher\Helper::getInstance(); // Getting all top cats - $blockCategoriesObj = $helper->getHandler('category')->getCategories(0, 0, 0); + $blockCategoriesObj = $helper->getHandler('Category')->getCategories(0, 0, 0); if (0 == count($blockCategoriesObj)) { return $block; @@ -79,10 +79,10 @@ function publisher_items_menu_show($options) */ function publisher_items_menu_edit($options) { - require_once PUBLISHER_ROOT_PATH . '/class/blockform.php'; + // require_once PUBLISHER_ROOT_PATH . '/class/blockform.php'; xoops_load('XoopsFormLoader'); - $form = new PublisherBlockForm(); + $form = new Publisher\BlockForm(); $catEle = new \XoopsFormLabel(_MB_PUBLISHER_SELECTCAT, Publisher\Utility::createCategorySelect($options[0], 0, true, 'options[0]')); $orderEle = new \XoopsFormSelect(_MB_PUBLISHER_ORDER, 'options[1]', $options[1]); diff --git a/blocks/items_new.php b/blocks/items_new.php index 9fc10488..98d7f555 100644 --- a/blocks/items_new.php +++ b/blocks/items_new.php @@ -20,10 +20,11 @@ */ use XoopsModules\Publisher; +use XoopsModules\Publisher\Constants; -// defined('XOOPS_ROOT_PATH') || exit('Restricted access.'); +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); -require_once dirname(__DIR__) . '/include/common.php'; +require_once __DIR__ . '/../include/common.php'; /** * @param $options @@ -55,7 +56,7 @@ function publisher_items_new_show($options) $criteria = new \CriteriaCompo(); $criteria->add(new \Criteria('categoryid', '(' . $options[0] . ')', 'IN')); } - $itemsObj = $helper->getHandler('item')->getItems($limit, $start, [PublisherConstants::PUBLISHER_STATUS_PUBLISHED], -1, $sort, $order, '', true, $criteria, 'none'); + $itemsObj = $helper->getHandler('Item')->getItems($limit, $start, [Constants::PUBLISHER_STATUS_PUBLISHED], -1, $sort, $order, '', true, $criteria, 'none'); $totalitems = count($itemsObj); if ($itemsObj && $totalitems > 0) { @@ -136,10 +137,10 @@ function publisher_items_new_show($options) */ function publisher_items_new_edit($options) { - require_once PUBLISHER_ROOT_PATH . '/class/blockform.php'; + // require_once PUBLISHER_ROOT_PATH . '/class/blockform.php'; xoops_load('XoopsFormLoader'); - $form = new PublisherBlockForm(); + $form = new Publisher\BlockForm(); $catEle = new \XoopsFormLabel(_MB_PUBLISHER_SELECTCAT, Publisher\Utility::createCategorySelect($options[0], 0, true, 'options[0]')); $orderEle = new \XoopsFormSelect(_MB_PUBLISHER_ORDER, 'options[1]', $options[1]); diff --git a/blocks/items_random_item.php b/blocks/items_random_item.php index 0cf4cba8..2168ed8c 100644 --- a/blocks/items_random_item.php +++ b/blocks/items_random_item.php @@ -20,10 +20,11 @@ */ use XoopsModules\Publisher; +use XoopsModules\Publisher\Constants; -// defined('XOOPS_ROOT_PATH') || exit('Restricted access.'); +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); -require_once dirname(__DIR__) . '/include/common.php'; +require_once __DIR__ . '/../include/common.php'; /** * @param $options @@ -35,7 +36,7 @@ function publisher_items_random_item_show($options) $block = []; $helper = Publisher\Helper::getInstance(); // creating the ITEM object - $itemsObj = $helper->getHandler('item')->getRandomItem('', [PublisherConstants::PUBLISHER_STATUS_PUBLISHED]); + $itemsObj = $helper->getHandler('Item')->getRandomItem('', [Constants::PUBLISHER_STATUS_PUBLISHED]); if (!is_object($itemsObj)) { return $block; diff --git a/blocks/items_recent.php b/blocks/items_recent.php index 55c4fa93..e43d1c06 100644 --- a/blocks/items_recent.php +++ b/blocks/items_recent.php @@ -20,10 +20,11 @@ */ use XoopsModules\Publisher; +use XoopsModules\Publisher\Constants; -// defined('XOOPS_ROOT_PATH') || exit('Restricted access.'); +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); -require_once dirname(__DIR__) . '/include/common.php'; +require_once __DIR__ . '/../include/common.php'; /** * @param $options @@ -56,7 +57,7 @@ function publisher_items_recent_show($options) $criteria = new \CriteriaCompo(); $criteria->add(new \Criteria('categoryid', '(' . $options[0] . ')', 'IN')); } - $itemsObj = $helper->getHandler('item')->getItems($limit, $start, [PublisherConstants::PUBLISHER_STATUS_PUBLISHED], -1, $sort, $order, '', true, $criteria, 'none'); + $itemsObj = $helper->getHandler('Item')->getItems($limit, $start, [Constants::PUBLISHER_STATUS_PUBLISHED], -1, $sort, $order, '', true, $criteria, 'none'); $totalItems = count($itemsObj); @@ -92,10 +93,10 @@ function publisher_items_recent_show($options) */ function publisher_items_recent_edit($options) { - require_once PUBLISHER_ROOT_PATH . '/class/blockform.php'; + // require_once PUBLISHER_ROOT_PATH . '/class/blockform.php'; xoops_load('XoopsFormLoader'); - $form = new PublisherBlockForm(); + $form = new Publisher\BlockForm(); $catEle = new \XoopsFormLabel(_MB_PUBLISHER_SELECTCAT, Publisher\Utility::createCategorySelect($options[0], 0, true, 'options[0]')); $orderEle = new \XoopsFormSelect(_MB_PUBLISHER_ORDER, 'options[1]', $options[1]); diff --git a/blocks/items_spot.php b/blocks/items_spot.php index 786999d3..986736d6 100644 --- a/blocks/items_spot.php +++ b/blocks/items_spot.php @@ -20,9 +20,9 @@ use XoopsModules\Publisher; -// defined('XOOPS_ROOT_PATH') || exit('Restricted access.'); +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); -require_once dirname(__DIR__) . '/include/common.php'; +require_once __DIR__ . '/../include/common.php'; /** * @param $options @@ -47,12 +47,12 @@ function publisher_items_spot_show($options) } $block = []; if (1 == $optDisplayLast) { - $itemsObj = $helper->getHandler('item')->getAllPublished($optItemsCount, 0, $optCategoryId, $sort = 'datesub', $order = 'DESC', 'summary'); + $itemsObj = $helper->getHandler('Item')->getAllPublished($optItemsCount, 0, $optCategoryId, $sort = 'datesub', $order = 'DESC', 'summary'); $i = 1; $itemsCount = count($itemsObj); if ($itemsObj) { if ($optCategoryId != -1 && $optCatImage) { - $cat = $helper->getHandler('category')->get($optCategoryId); + $cat = $helper->getHandler('Category')->get($optCategoryId); $category['name'] = $cat->name(); $category['categoryurl'] = $cat->getCategoryUrl(); if ('blank.png' !== $cat->getImage()) { @@ -80,7 +80,7 @@ function publisher_items_spot_show($options) $i = 1; $itemsCount = count($selItems); foreach ($selItems as $itemId) { - $itemObj = $helper->getHandler('item')->get($itemId); + $itemObj = $helper->getHandler('Item')->get($itemId); if (!$itemObj->notLoaded()) { $item = $itemObj->toArraySimple(); $item['who_when'] = sprintf(_MB_PUBLISHER_WHO_WHEN, $itemObj->posterName(), $itemObj->getDatesub()); @@ -121,9 +121,9 @@ function publisher_items_spot_show($options) */ function publisher_items_spot_edit($options) { - require_once PUBLISHER_ROOT_PATH . '/class/blockform.php'; + // require_once PUBLISHER_ROOT_PATH . '/class/blockform.php'; xoops_load('XoopsFormLoader'); - $form = new PublisherBlockForm(); + $form = new Publisher\BlockForm(); $autoEle = new \XoopsFormRadioYN(_MB_PUBLISHER_AUTO_LAST_ITEMS, 'options[0]', $options[0]); $countEle = new \XoopsFormText(_MB_PUBLISHER_LAST_ITEMS_COUNT, 'options[1]', 2, 255, $options[1]); $catEle = new \XoopsFormLabel(_MB_PUBLISHER_SELECTCAT, Publisher\Utility::createCategorySelect($options[2], 0, true, 'options[2]')); @@ -131,7 +131,7 @@ function publisher_items_spot_edit($options) $criteria = new \CriteriaCompo(); $criteria->setSort('datesub'); $criteria->setOrder('DESC'); - $itemsObj = $helper->getHandler('item')->getList($criteria); + $itemsObj = $helper->getHandler('Item')->getList($criteria); $keys = array_keys($itemsObj); unset($criteria); if (empty($options[3]) || (0 == $options[3])) { diff --git a/blocks/latest_files.php b/blocks/latest_files.php index e81658cc..eb6c70c7 100644 --- a/blocks/latest_files.php +++ b/blocks/latest_files.php @@ -20,10 +20,11 @@ */ use XoopsModules\Publisher; +use XoopsModules\Publisher\Constants; -// defined('XOOPS_ROOT_PATH') || exit('Restricted access.'); +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); -require_once dirname(__DIR__) . '/include/common.php'; +require_once __DIR__ . '/../include/common.php'; /** * @param $options @@ -49,7 +50,7 @@ function publisher_latest_files_show($options) $directDownload = $options[3]; // creating the files objects - $filesObj = $helper->getHandler('file')->getAllFiles(0, PublisherConstants::PUBLISHER_STATUS_FILE_ACTIVE, $limit, 0, $sort, $order, explode(',', $options[0])); + $filesObj = $helper->getHandler('File')->getAllFiles(0, Constants::PUBLISHER_STATUS_FILE_ACTIVE, $limit, 0, $sort, $order, explode(',', $options[0])); foreach ($filesObj as $fileObj) { $aFile = []; $aFile['link'] = $directDownload ? $fileObj->getFileLink() : $fileObj->getItemLink(); @@ -73,10 +74,10 @@ function publisher_latest_files_show($options) */ function publisher_latest_files_edit($options) { - require_once PUBLISHER_ROOT_PATH . '/class/blockform.php'; + // require_once PUBLISHER_ROOT_PATH . '/class/blockform.php'; xoops_load('XoopsFormLoader'); - $form = new PublisherBlockForm(); + $form = new Publisher\BlockForm(); $catEle = new \XoopsFormLabel(_MB_PUBLISHER_SELECTCAT, Publisher\Utility::createCategorySelect($options[0], 0, true, 'options[0]')); $orderEle = new \XoopsFormSelect(_MB_PUBLISHER_ORDER, 'options[1]', $options[1]); diff --git a/blocks/latest_news.php b/blocks/latest_news.php index 40a44385..272e4bd4 100644 --- a/blocks/latest_news.php +++ b/blocks/latest_news.php @@ -21,10 +21,11 @@ */ use XoopsModules\Publisher; +use XoopsModules\Publisher\Constants; -// defined('XOOPS_ROOT_PATH') || exit('Restricted access.'); +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); -require_once dirname(__DIR__) . '/include/common.php'; +require_once __DIR__ . '/../include/common.php'; /** * @param $options @@ -76,7 +77,7 @@ function publisher_latest_news_show($options) $criteria->add(new \Criteria('itemid', '(' . $selectedStories . ')', 'IN')); } - $itemsObj = $helper->getHandler('item')->getItems($limit, $start, [PublisherConstants::PUBLISHER_STATUS_PUBLISHED], -1, $sort, $order, '', true, $criteria, 'itemid'); + $itemsObj = $helper->getHandler('Item')->getItems($limit, $start, [Constants::PUBLISHER_STATUS_PUBLISHED], -1, $sort, $order, '', true, $criteria, 'itemid'); $scount = count($itemsObj); @@ -198,7 +199,7 @@ function publisher_latest_news_show($options) $item['print'] = ''; if (1 == $options[24]) { - $item['print'] = '' . _CO_PUBLISHER_PRINT . ' '; + $item['print'] = '' . _CO_PUBLISHER_PRINT . ' '; } $item['pdf'] = ''; diff --git a/blocks/search.php b/blocks/search.php index 84723757..f8406697 100644 --- a/blocks/search.php +++ b/blocks/search.php @@ -22,9 +22,9 @@ use Xmf\Request; use XoopsModules\Publisher; -// defined('XOOPS_ROOT_PATH') || exit('Restricted access.'); +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); -require_once dirname(__DIR__) . '/include/common.php'; +require_once __DIR__ . '/../include/common.php'; /** * @param $options @@ -35,7 +35,7 @@ function publisher_search_show($options) { $block = []; $helper = Publisher\Helper::getInstance(); - $categories = $helper->getHandler('category')->getCategoriesForSearch(); + $categories = $helper->getHandler('Category')->getCategoriesForSearch(); if (0 == count($categories)) { return $block; } diff --git a/category.php b/category.php index bf2a5871..c1412d33 100644 --- a/category.php +++ b/category.php @@ -27,7 +27,7 @@ $categoryid = Request::getInt('categoryid', 0, 'GET'); // Creating the category object for the selected category -$categoryObj = $helper->getHandler('category')->get($categoryid); +$categoryObj = $helper->getHandler('Category')->get($categoryid); // if the selected category was not found, exit if (!is_object($categoryObj) || $categoryObj->notLoaded()) { @@ -46,7 +46,7 @@ $item_page_id = Request::getInt('page', -1, 'GET'); -$totalItems = $helper->getHandler('category')->publishedItemsCount(); +$totalItems = $helper->getHandler('Category')->publishedItemsCount(); // if there is no Item under this categories or the sub-categories, exit // why? @@ -104,7 +104,7 @@ break; } -$itemsObj = $helper->getHandler('item')->getAllPublished($helper->getConfig('idxcat_index_perpage'), $start, $categoryid, $sort, $order); +$itemsObj = $helper->getHandler('Item')->getAllPublished($helper->getConfig('idxcat_index_perpage'), $start, $categoryid, $sort, $order); $totalItemOnPage = 0; if ($itemsObj) { @@ -123,12 +123,12 @@ if (1 == $helper->getConfig('idxcat_display_last_item')) { // Get the last smartitem - $lastItemObj = $helper->getHandler('item')->getLastPublishedByCat([[$categoryObj]]); + $lastItemObj = $helper->getHandler('Item')->getLastPublishedByCat([[$categoryObj]]); } $lastitemsize = (int)$helper->getConfig('idxcat_last_item_size'); // Creating the sub-categories objects that belong to the selected category -$subcatsObj = $helper->getHandler('category')->getCategories(0, 0, $categoryid); +$subcatsObj = $helper->getHandler('Category')->getCategories(0, 0, $categoryid); $total_subcats = count($subcatsObj); $total_items = 0; @@ -199,7 +199,7 @@ for ($i = 0; $i < $totalItemOnPage; ++$i) { $item = $itemsObj[$i]->toArraySimple('default', $helper->getConfig('item_title_size')); $item['categoryname'] = $categoryObj->name(); - $item['categorylink'] = "categoryid(), $categoryObj->short_url()) . "'>" . $categoryObj->name() . ''; + $item['categorylink'] = "categoryid(), $categoryObj->short_url()) . "'>" . $categoryObj->name() . ''; $item['who_when'] = $itemsObj[$i]->getWhoAndWhen(); $xoopsTpl->append('items', $item); } @@ -241,7 +241,7 @@ /** * Generating meta information for this page */ -$publisherMetagen = new PublisherMetagen($categoryObj->getVar('name'), $categoryObj->getVar('meta_keywords', 'n'), $categoryObj->getVar('meta_description', 'n'), $categoryObj->getCategoryPathForMetaTitle()); +$publisherMetagen = new Publisher\Metagen($categoryObj->getVar('name'), $categoryObj->getVar('meta_keywords', 'n'), $categoryObj->getVar('meta_description', 'n'), $categoryObj->getCategoryPathForMetaTitle()); $publisherMetagen->createMetaTags(); // RSS Link diff --git a/class/BaseObjectHandler.php b/class/BaseObjectHandler.php new file mode 100644 index 00000000..00a34b1b --- /dev/null +++ b/class/BaseObjectHandler.php @@ -0,0 +1,364 @@ + + * @author The SmartFactory + */ + +use XoopsModules\Publisher; + +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); + +require_once __DIR__ . '/../include/common.php'; + +/** + * BaseObjectHandler class + * + * @copyright The XUUPS Project http://sourceforge.net/projects/xuups/ + * @license http://www.fsf.org/copyleft/gpl.html GNU public license + * @package Publisher + * @since 1.0 + * @author trabis + * @author Nazar Aziz + */ +class BaseObjectHandler extends \XoopsPersistableObjectHandler +{ + /** + * Database connection + * + * @var XoopsDatabase + */ + //mb public $_db; //mb it is already declared in XoopsObjectHandler + + /** + * Autoincrementing DB fieldname + * + * @var string + */ + protected $idfield = 'id'; + + /** + * @param XoopsDatabase $db + */ + public function init(\XoopsDatabase $db) + { + $this->db = $db; + } + + /** + * DB Table Name + * + * @var string + */ + protected $dbtable = 'publisher_mimetypes'; + + /** + * create a new object + * + * @param bool $isNew + * @return XoopsObject + * @access public + */ + public function create($isNew = true) + { + return new $this->className(); + } + + /** + * retrieve an object from the database, based on. use in child classes + * + * @param int $id ID + * + * @param null $fields + * @return mixed object if id exists, false if not + * @access public + */ + public function get($id = null, $fields = null) + { + $id = (int)$id; + if ($id > 0) { + $sql = $this->selectQuery(new \Criteria($this->idfield, $id)); + if (!$result = $this->db->query($sql)) { + return false; + } + $numrows = $this->db->getRowsNum($result); + if (1 == $numrows) { + $obj = new $this->className($this->db->fetchArray($result)); + + return $obj; + } + } + + return false; + } + + /** + * retrieve objects from the database + * + * @param CriteriaElement $criteria {@link CriteriaElement} + * conditions to be met + * @param bool $idAsKey Should the department ID be used as array key + * + * @param bool $asObject + * @return array array of objects + * @access public + */ + public function &getObjects (\CriteriaElement $criteria = null, $idAsKey = false, $asObject = true) //&getObjects($criteria = null, $idAsKey = false) + { + $ret = []; + $limit = $start = 0; + $sql = $this->selectQuery($criteria); + $id = $this->idfield; + if (isset($criteria)) { + $limit = $criteria->getLimit(); + $start = $criteria->getStart(); + } + $result = $this->db->query($sql, $limit, $start); + // if no records from db, return empty array + if (!$result) { + return $ret; + } + // Add each returned record to the result array + while (false !== ($myrow = $this->db->fetchArray($result))) { + $obj = new $this->className($myrow); + if (!$idAsKey) { + $ret[] = $obj; + } else { + $ret[$obj->getVar($id)] = $obj; + } + unset($obj); + } + + return $ret; + } + + /** + * @param XoopsObject $obj + * @param bool $force + * + * @return bool|void + */ + public function insert(\XoopsObject $obj, $force = false)// insert($obj, $force = false) + { + // Make sure object is of correct type + if (0 != strcasecmp($this->className, get_class($obj))) { + return false; + } + // Make sure object needs to be stored in DB + if (!$obj->isDirty()) { + return true; + } + // Make sure object fields are filled with valid values + if (!$obj->cleanVars()) { + return false; + } + // Create query for DB update + if ($obj->isNew()) { + // Determine next auto-gen ID for table + $this->db->genId($this->db->prefix($this->dbtable) . '_uid_seq'); + $sql = $this->insertQuery($obj); + } else { + $sql = $this->updateQuery($obj); + } + // Update DB + if (false !== $force) { + $result = $this->db->queryF($sql); + } else { + $result = $this->db->query($sql); + } + if (!$result) { + $obj->setErrors('The query returned an error. ' . $this->db->error()); + + return false; + } + //Make sure auto-gen ID is stored correctly in object + if ($obj->isNew()) { + $obj->assignVar($this->idfield, $this->db->getInsertId()); + } + + return true; + } + + /** + * Create a "select" SQL query + * + * @param CriteriaElement $criteria {@link CriteriaElement} to match + * + * @return string SQL query + * @access private + */ + private function selectQuery($criteria = null) + { + $sql = sprintf('SELECT * FROM %s', $this->db->prefix($this->dbtable)); + if (isset($criteria) && is_subclass_of($criteria, 'CriteriaElement')) { + $sql .= ' ' . $criteria->renderWhere(); + if ('' != $criteria->getSort()) { + $sql .= ' ORDER BY ' . $criteria->getSort() . ' + ' . $criteria->getOrder(); + } + } + + return $sql; + } + + /** + * count objects matching a criteria + * + * @param CriteriaElement $criteria {@link CriteriaElement} to match + * + * @return int count of objects + * @access public + */ + public function getCount (\CriteriaElement $criteria = null) //getCount($criteria = null) + { + $sql = 'SELECT COUNT(*) FROM ' . $this->db->prefix($this->dbtable); + if (isset($criteria) && is_subclass_of($criteria, 'CriteriaElement')) { + $sql .= ' ' . $criteria->renderWhere(); + } + if (!$result = $this->db->query($sql)) { + return 0; + } + list($count) = $this->db->fetchRow($result); + + return $count; + } + + /** + * delete object based on id + * + * @param XoopsObject $obj {@link XoopsObject} to delete + * @param bool $force override XOOPS delete protection + * + * @return bool deletion successful? + * @access public + */ + public function delete(\XoopsObject $obj, $force = false) //delete($obj, $force = false) + { + if (0 != strcasecmp($this->className, get_class($obj))) { + return false; + } + $sql = $this->deleteQuery($obj); + if (false !== $force) { + $result = $this->db->queryF($sql); + } else { + $result = $this->db->query($sql); + } + if (!$result) { + return false; + } + + return true; + } + + /** + * delete department matching a set of conditions + * + * @param CriteriaElement $criteria {@link CriteriaElement} + * + * @param bool $force + * @param bool $asObject + * @return bool FALSE if deletion failed + * @access public + */ + public function deleteAll (\CriteriaElement $criteria = null, $force = true, $asObject = false) //deleteAll($criteria = null) + { + $sql = 'DELETE FROM ' . $this->db->prefix($this->dbtable); + if (isset($criteria) && is_subclass_of($criteria, 'CriteriaElement')) { + $sql .= ' ' . $criteria->renderWhere(); + } + if (!$result = $this->db->query($sql)) { + return false; + } + + return true; + } + + /** + * Assign a value to 1 field for tickets matching a set of conditions + * + * @param string $fieldname + * @param string $fieldvalue + * @param \CriteriaElement $criteria {@link \CriteriaElement} + * + * @param bool $force + * @return bool FALSE if update failed + * @access public + */ + public function updateAll($fieldname, $fieldvalue, \CriteriaElement $criteria = null, $force = false) //updateAll($fieldname, $fieldvalue, $criteria = null) + { + $setClause = is_numeric($fieldvalue) ? $fieldname . ' = ' . $fieldvalue : $fieldname . ' = ' . $this->db->quoteString($fieldvalue); + $sql = 'UPDATE ' . $this->db->prefix($this->dbtable) . ' SET ' . $setClause; + if (isset($criteria) && is_subclass_of($criteria, 'CriteriaElement')) { + $sql .= ' ' . $criteria->renderWhere(); + } + if (!$result = $this->db->query($sql)) { + return false; + } + + return true; + } + + /** + * @param $obj + * + * @return bool + */ + protected function insertQuery($obj) + { + return false; + } + + /** + * @param $obj + * + * @return bool|string + */ + protected function updateQuery($obj) + { + return false; + } + + /** + * @param $obj + * + * @return bool + */ + protected function deleteQuery($obj) + { + return false; + } + + /** + * Singleton - prevent multiple instances of this class + * + * @param XoopsDatabase $db + * + * @return XoopsObject {@link pagesCategoryHandler} + * @access public + */ + public function getInstance(\XoopsDatabase $db) + { + static $instance; + if (null === $instance) { + $className = $this->className . 'Handler'; + $instance = new $className($db); + } + + return $instance; + } +} diff --git a/class/blockform.php b/class/BlockForm.php similarity index 93% rename from class/blockform.php rename to class/BlockForm.php index eb36a80e..326b618d 100644 --- a/class/blockform.php +++ b/class/BlockForm.php @@ -1,4 +1,4 @@ - */ -// defined('XOOPS_ROOT_PATH') || exit('Restricted access.'); +use XoopsModules\Publisher; + +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); xoops_load('XoopsForm'); @@ -28,7 +30,7 @@ * * No styles and no JavaScript to check for required fields. */ -class PublisherBlockForm extends XoopsForm +class BlockForm extends \XoopsForm { /** * diff --git a/class/Category.php b/class/Category.php new file mode 100644 index 00000000..adc16659 --- /dev/null +++ b/class/Category.php @@ -0,0 +1,356 @@ + + * @author The SmartFactory + */ + +use XoopsModules\Publisher; + +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); + +require_once __DIR__ . '/../include/common.php'; + +/** + * Class Publisher\Category + */ +class Category extends \XoopsObject +{ + /** + * @var Publisher + * @access public + */ + public $helper; + + /** + * @var array + */ + public $categoryPath = false; + + /** + * constructor + */ + public function __construct() + { + $this->helper = Publisher\Helper::getInstance(); + $this->initVar('categoryid', XOBJ_DTYPE_INT, null, false); + $this->initVar('parentid', XOBJ_DTYPE_INT, null, false); + $this->initVar('name', XOBJ_DTYPE_TXTBOX, null, true, 100); + $this->initVar('description', XOBJ_DTYPE_TXTAREA, null, false, 255); + $this->initVar('image', XOBJ_DTYPE_TXTBOX, null, false, 255); + $this->initVar('total', XOBJ_DTYPE_INT, 1, false); + $this->initVar('weight', XOBJ_DTYPE_INT, 1, false); + $this->initVar('created', XOBJ_DTYPE_INT, null, false); + $this->initVar('template', XOBJ_DTYPE_TXTBOX, null, false, 255); + $this->initVar('header', XOBJ_DTYPE_TXTAREA, null, false); + $this->initVar('meta_keywords', XOBJ_DTYPE_TXTAREA, null, false); + $this->initVar('meta_description', XOBJ_DTYPE_TXTAREA, null, false); + $this->initVar('short_url', XOBJ_DTYPE_TXTBOX, null, false, 255); + $this->initVar('moderator', XOBJ_DTYPE_INT, null, false, 0); + //not persistent values + $this->initVar('itemcount', XOBJ_DTYPE_INT, 0, false); + $this->initVar('last_itemid', XOBJ_DTYPE_INT); + $this->initVar('last_title_link', XOBJ_DTYPE_TXTBOX); + $this->initVar('dohtml', XOBJ_DTYPE_INT, 1, false); + } + + /** + * @param string $method + * @param array $args + * + * @return mixed + */ + public function __call($method, $args) + { + $arg = isset($args[0]) ? $args[0] : null; + + return $this->getVar($method, $arg); + } + + /** + * @return bool + */ + public function notLoaded() + { + return ($this->getVar('categoryid') == -1); + } + + /** + * @return bool + */ + public function checkPermission() + { + // global $publisherIsAdmin; + $ret = false; + if ($GLOBALS['publisherIsAdmin']) { + return true; + } + if (is_object($GLOBALS['xoopsUser']) && $GLOBALS['xoopsUser']->getVar('uid') == $this->moderator()) { + return true; + } + $categoriesGranted = $this->helper->getHandler('permission')->getGrantedItems('category_read'); + if (in_array($this->categoryid(), $categoriesGranted)) { + $ret = true; + } + + return $ret; + } + + /** + * @param string $format + * + * @return mixed|string + */ + public function getImage($format = 's') + { + if ('' != $this->getVar('image')) { + return $this->getVar('image', $format); + } else { + return 'blank.png'; + } + } + + /** + * @param string $format + * + * @return mixed + */ + public function template($format = 'n') + { + return $this->getVar('template', $format); + } + + /** + * @param bool $withAllLink + * + * @return array|bool|string + */ + public function getCategoryPath($withAllLink = true) + { + if (empty($this->categoryPath)) { + if ($withAllLink) { + $ret = $this->getCategoryLink(); + } else { + $ret = $this->name(); + } + $parentid = $this->parentid(); + if (0 != $parentid) { + $parentObj = $this->helper->getHandler('Category')->get($parentid); + // if ($parentObj->notLoaded()) { + // exit; + // } + + try { + if ($parentObj->notLoaded()) { + throw new RuntimeException(_NOPERM); + } + } catch (Exception $e) { + $this->helper->addLog($e); + // redirect_header('javascript:history.go(-1)', 1, _NOPERM); + } + + $ret = $parentObj->getCategoryPath($withAllLink) . '
  • ' . $ret . '
  • '; + } + $this->categoryPath = $ret; + } + + return $this->categoryPath; + } + + /** + * @return mixed|string + */ + public function getCategoryPathForMetaTitle() + { + $ret = ''; + $parentid = $this->parentid(); + if (0 != $parentid) { + $parentObj = $this->helper->getHandler('Category')->get($parentid); + // if ($parentObj->notLoaded()) { + // exit('NOT LOADED'); + // } + + try { + if ($parentObj->notLoaded()) { + throw new RuntimeException('NOT LOADED'); + } + } catch (Exception $e) { + $this->helper->addLog($e); + // redirect_header('javascript:history.go(-1)', 1, _NOPERM); + } + + $ret = $parentObj->getCategoryPath(false); + $ret = str_replace(' >', ' -', $ret); + } + + return $ret; + } + + /** + * @return array|null + */ + public function getGroupsRead() + { + return $this->helper->getHandler('permission')->getGrantedGroupsById('category_read', $this->categoryid()); + } + + /** + * @return array|null + */ + public function getGroupsSubmit() + { + return $this->helper->getHandler('permission')->getGrantedGroupsById('item_submit', $this->categoryid()); + } + + /** + * @return array|null + */ + public function getGroupsModeration() + { + return $this->helper->getHandler('permission')->getGrantedGroupsById('category_moderation', $this->categoryid()); + } + + /** + * @return string + */ + public function getCategoryUrl() + { + return Publisher\Seo::generateUrl('category', $this->categoryid(), $this->short_url()); + } + + /** + * @param bool $class + * + * @return string + */ + public function getCategoryLink($class = false) + { + if ($class) { + return "" . $this->name() . ''; + } else { + return "" . $this->name() . ''; + } + } + + /** + * @param bool $sendNotifications + * @param bool $force + * + * @return mixed + */ + public function store($sendNotifications = true, $force = true) + { + $ret = $this->helper->getHandler('Category')->insert($this, $force); + if ($sendNotifications && $ret && $this->isNew()) { + $this->sendNotifications(); + } + $this->unsetNew(); + + return $ret; + } + + /** + * Send notifications + */ + public function sendNotifications() + { + $tags = []; + $tags['MODULE_NAME'] = $this->helper->getModule()->getVar('name'); + $tags['CATEGORY_NAME'] = $this->name(); + $tags['CATEGORY_URL'] = $this->getCategoryUrl(); + /* @var $notificationHandler XoopsNotificationHandler */ + $notificationHandler = xoops_getHandler('notification'); + $notificationHandler->triggerEvent('global_item', 0, 'category_created', $tags); + } + + /** + * @param array $category + * + * @return array + */ + public function toArraySimple($category = []) + { + $category['categoryid'] = $this->categoryid(); + $category['name'] = $this->name(); + $category['categorylink'] = $this->getCategoryLink(); + $category['categoryurl'] = $this->getCategoryUrl(); + $category['total'] = ($this->getVar('itemcount') > 0) ? $this->getVar('itemcount') : ''; + $category['description'] = $this->description(); + $category['header'] = $this->header(); + $category['meta_keywords'] = $this->meta_keywords(); + $category['meta_description'] = $this->meta_description(); + $category['short_url'] = $this->short_url(); + if ($this->getVar('last_itemid') > 0) { + $category['last_itemid'] = $this->getVar('last_itemid', 'n'); + $category['last_title_link'] = $this->getVar('last_title_link', 'n'); + } + if ('blank.png' !== $this->getImage()) { + $category['image_path'] = Publisher\Utility::getImageDir('category', false) . $this->getImage(); + } else { + $category['image_path'] = ''; + } + $category['lang_subcategories'] = sprintf(_CO_PUBLISHER_SUBCATEGORIES_INFO, $this->name()); + + return $category; + } + + /** + * @param array $category + * + * @return array + */ + public function toArrayTable($category = []) + { + $category['categoryid'] = $this->categoryid(); + $category['categorylink'] = $this->getCategoryLink(); + $category['total'] = ($this->getVar('itemcount') > 0) ? $this->getVar('itemcount') : ''; + $category['description'] = $this->description(); + if ($this->getVar('last_itemid') > 0) { + $category['last_itemid'] = $this->getVar('last_itemid', 'n'); + $category['last_title_link'] = $this->getVar('last_title_link', 'n'); + } + if ('blank.png' !== $this->getImage()) { + $category['image_path'] = Publisher\Utility::getImageDir('category', false) . $this->getImage(); + } else { + $category['image_path'] = ''; + } + $category['lang_subcategories'] = sprintf(_CO_PUBLISHER_SUBCATEGORIES_INFO, $this->name()); + + return $category; + } + + /** + * + */ + public function createMetaTags() + { + $publisherMetagen = new Publisher\Metagen($this->name(), $this->meta_keywords(), $this->meta_description()); + $publisherMetagen->createMetaTags(); + } + + /** + * @param int $subCatsCount + * + * @return Publisher\CategoryForm + */ + public function getForm($subCatsCount = 4) + { +// require_once $GLOBALS['xoops']->path('modules/' . PUBLISHER_DIRNAME . '/class/form/category.php'); + $form = new Publisher\Form\CategoryForm($this, $subCatsCount); + + return $form; + } +} diff --git a/class/CategoryHandler.php b/class/CategoryHandler.php new file mode 100644 index 00000000..7e60179b --- /dev/null +++ b/class/CategoryHandler.php @@ -0,0 +1,409 @@ + + * @author The SmartFactory + */ + +use XoopsModules\Publisher; +use XoopsModules\Publisher\Constants; + +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); + +require_once __DIR__ . '/../include/common.php'; + + +/** + * Categories handler class. + * This class is responsible for providing data access mechanisms to the data source + * of Category class objects. + * + * @author marcan + * @package Publisher + */ +class CategoryHandler extends \XoopsPersistableObjectHandler +{ + /** + * @var Helper + * @access public + */ + public $helper; + + /** + * @param null|\XoopsDatabase $db + */ + public function __construct(\XoopsDatabase $db) + { + $this->helper = Publisher\Helper::getInstance(); + parent::__construct($db, 'publisher_categories', Category::class, 'categoryid', 'name'); + } + + /** + * retrieve an item + * + * @param int|null $id itemid of the user + * + * @param null $fields + * @return mixed reference to the Publisher\Category object, FALSE if failed + * object, FALSE if failed + */ + public function get($id = null, $fields = null) + { + static $cats; + if (isset($cats[$id])) { + return $cats[$id]; + } + $obj = parent::get($id); + $cats[$id] = $obj; + + return $obj; + } + + /** + * insert a new category in the database + * + * @param XoopsObject $category reference to the {@link Publisher\Category} + * @param bool $force + * @return bool FALSE if failed, TRUE if already present and unchanged or successful + */ + public function insert(\XoopsObject $category, $force = false) //insert(&$category, $force = false) + { + // Auto create meta tags if empty + if (!$category->meta_keywords() || !$category->meta_description()) { + $publisherMetagen = new Publisher\Metagen($category->name(), $category->getVar('meta_keywords'), $category->getVar('description')); + if (!$category->meta_keywords()) { + $category->setVar('meta_keywords', $publisherMetagen->keywords); + } + if (!$category->meta_description()) { + $category->setVar('meta_description', $publisherMetagen->description); + } + } + // Auto create short_url if empty + if (!$category->short_url()) { + $category->setVar('short_url', Metagen::generateSeoTitle($category->name('n'), false)); + } + $ret = parent::insert($category, $force); + + return $ret; + } + + /** + * delete a category from the database + * + * @param XoopsObject $category reference to the category to delete + * @param bool $force + * + * @return bool FALSE if failed. + */ + public function delete(\XoopsObject $category, $force = false) //delete(&$category, $force = false) + { + // Deleting this category ITEMs + $criteria = new \Criteria('categoryid', $category->categoryid()); + $this->helper->getHandler('Item')->deleteAll($criteria); + unset($criteria); + // Deleting the sub categories + $subcats =& $this->getCategories(0, 0, $category->categoryid()); + foreach ($subcats as $subcat) { + $this->delete($subcat); + } + if (!parent::delete($category, $force)) { + $category->setErrors('An error while deleting.'); + + return false; + } + $moduleId = $this->helper->getModule()->getVar('mid'); + xoops_groupperm_deletebymoditem($moduleId, 'category_read', $category->categoryid()); + xoops_groupperm_deletebymoditem($moduleId, 'item_submit', $category->categoryid()); + xoops_groupperm_deletebymoditem($moduleId, 'category_moderation', $category->categoryid()); + + return true; + } + + /** + * retrieve categories from the database + * + * @param \CriteriaElement $criteria {@link CriteriaElement} conditions to be met + * @param bool $idAsKey use the categoryid as key for the array? + * + * @param bool $as_object + * @return array array of XoopsItem objects + */ + + public function &getObjects(\CriteriaElement $criteria = null, $idAsKey = false, $as_object = true) //&getObjects($criteria = null, $idAsKey = false) + { + $ret = []; + $theObjects = parent::getObjects($criteria, true); + foreach ($theObjects as $theObject) { + if (!$idAsKey) { + $ret[] = $theObject; + } else { + $ret[$theObject->categoryid()] = $theObject; + } + unset($theObject); + } + + return $ret; + } + + /** + * @param int $limit + * @param int $start + * @param int $parentid + * @param string $sort + * @param string $order + * @param bool $idAsKey + * + * @return array + */ + public function &getCategories($limit = 0, $start = 0, $parentid = 0, $sort = 'weight', $order = 'ASC', $idAsKey = true) + { + // global $publisherIsAdmin; + $criteria = new \CriteriaCompo(); + $criteria->setSort($sort); + $criteria->setOrder($order); + if ($parentid != -1) { + $criteria->add(new \Criteria('parentid', $parentid)); + } + if (!$GLOBALS['publisherIsAdmin']) { + $categoriesGranted = $this->helper->getHandler('permission')->getGrantedItems('category_read'); + if (count($categoriesGranted) > 0) { + $criteria->add(new \Criteria('categoryid', '(' . implode(',', $categoriesGranted) . ')', 'IN')); + } else { + return []; + } + if (is_object($GLOBALS['xoopsUser'])) { + $criteria->add(new \Criteria('moderator', $GLOBALS['xoopsUser']->getVar('uid')), 'OR'); + } + } + $criteria->setStart($start); + $criteria->setLimit($limit); + $ret =& $this->getObjects($criteria, $idAsKey); + + return $ret; + } + + /** + * @param $category + * @param $level + * @param $catArray + * @param $catResult + */ + public function getSubCatArray($category, $level, $catArray, $catResult) + { + global $theresult; + $spaces = ''; + for ($j = 0; $j < $level; ++$j) { + $spaces .= '--'; + } + $theresult[$category['categoryid']] = $spaces . $category['name']; + if (isset($catArray[$category['categoryid']])) { + ++$level; + foreach ($catArray[$category['categoryid']] as $parentid => $cat) { + $this->getSubCatArray($cat, $level, $catArray, $catResult); + } + } + } + + /** + * @return array + */ + public function &getCategoriesForSubmit() + { + global $publisherIsAdmin, $theresult; + $ret = []; + $criteria = new \CriteriaCompo(); + $criteria->setSort('name'); + $criteria->setOrder('ASC'); + if (!$publisherIsAdmin) { + $categoriesGranted = $this->helper->getHandler('permission')->getGrantedItems('item_submit'); + if (count($categoriesGranted) > 0) { + $criteria->add(new \Criteria('categoryid', '(' . implode(',', $categoriesGranted) . ')', 'IN')); + } else { + return $ret; + } + if (is_object($GLOBALS['xoopsUser'])) { + $criteria->add(new \Criteria('moderator', $GLOBALS['xoopsUser']->getVar('uid')), 'OR'); + } + } + $categories = $this->getAll($criteria, ['categoryid', 'parentid', 'name'], false, false); + if (0 == count($categories)) { + return $ret; + } + $catArray = []; + foreach ($categories as $cat) { + $catArray[$cat['parentid']][$cat['categoryid']] = $cat; + } + // Needs to have permission on at least 1 top level category + if (!isset($catArray[0])) { + return $ret; + } + $catResult = []; + foreach ($catArray[0] as $thecat) { + $level = 0; + $this->getSubCatArray($thecat, $level, $catArray, $catResult); + } + + return $theresult; //this is a global + } + + /** + * @return array + */ + public function getCategoriesForSearch() + { + global $publisherIsAdmin, $theresult; + $ret = []; + $criteria = new \CriteriaCompo(); + $criteria->setSort('name'); + $criteria->setOrder('ASC'); + if (!$publisherIsAdmin) { + $categoriesGranted = $this->helper->getHandler('permission')->getGrantedItems('category_read'); + if (count($categoriesGranted) > 0) { + $criteria->add(new \Criteria('categoryid', '(' . implode(',', $categoriesGranted) . ')', 'IN')); + } else { + return $ret; + } + if (is_object($GLOBALS['xoopsUser'])) { + $criteria->add(new \Criteria('moderator', $GLOBALS['xoopsUser']->getVar('uid')), 'OR'); + } + } + $categories = $this->getAll($criteria, ['categoryid', 'parentid', 'name'], false, false); + if (0 == count($categories)) { + return $ret; + } + $catArray = []; + foreach ($categories as $cat) { + $catArray[$cat['parentid']][$cat['categoryid']] = $cat; + } + // Needs to have permission on at least 1 top level category + if (!isset($catArray[0])) { + return $ret; + } + $catResult = []; + foreach ($catArray[0] as $thecat) { + $level = 0; + $this->getSubCatArray($thecat, $level, $catArray, $catResult); + } + + return $theresult; //this is a global + } + + /** + * @param int $parentid + * + * @return int + */ + public function getCategoriesCount($parentid = 0) + { + // global $publisherIsAdmin; + if ($parentid == -1) { + return $this->getCount(); + } + $criteria = new \CriteriaCompo(); + if (isset($parentid) && ($parentid != -1)) { + $criteria->add(new \Criteria('parentid', $parentid)); + if (!$GLOBALS['publisherIsAdmin']) { + $categoriesGranted = $this->helper->getHandler('permission')->getGrantedItems('category_read'); + if (count($categoriesGranted) > 0) { + $criteria->add(new \Criteria('categoryid', '(' . implode(',', $categoriesGranted) . ')', 'IN')); + } else { + return 0; + } + if (is_object($GLOBALS['xoopsUser'])) { + $criteria->add(new \Criteria('moderator', $GLOBALS['xoopsUser']->getVar('uid')), 'OR'); + } + } + } + + return $this->getCount($criteria); + } + + /** + * Get all subcats and put them in an array indexed by parent id + * + * @param array $categories + * + * @return array + */ + public function getSubCats($categories) + { + // global $publisherIsAdmin; + $criteria = new \CriteriaCompo(new \Criteria('parentid', '(' . implode(',', array_keys($categories)) . ')', 'IN')); + $ret = []; + if (!$GLOBALS['publisherIsAdmin']) { + $categoriesGranted = $this->helper->getHandler('permission')->getGrantedItems('category_read'); + if (count($categoriesGranted) > 0) { + $criteria->add(new \Criteria('categoryid', '(' . implode(',', $categoriesGranted) . ')', 'IN')); + } else { + return $ret; + } + + if (is_object($GLOBALS['xoopsUser'])) { + $criteria->add(new \Criteria('moderator', $GLOBALS['xoopsUser']->getVar('uid')), 'OR'); + } + } + $criteria->setSort('weight'); + $criteria->setOrder('ASC'); + $subcats =& $this->getObjects($criteria, true); + foreach ($subcats as $subcat) { + $ret[$subcat->getVar('parentid')][$subcat->getVar('categoryid')] = $subcat; + } + + return $ret; + } + + /** + * delete categories matching a set of conditions + * + * @param CriteriaElement $criteria {@link CriteriaElement} + * + * @param bool $force + * @param bool $asObject + * @return bool FALSE if deletion failed + */ + public function deleteAll (\CriteriaElement $criteria = null, $force = true, $asObject = false) //deleteAll($criteria = null) + { + $categories =& $this->getObjects($criteria); + foreach ($categories as $category) { + if (!$this->delete($category)) { + return false; + } + } + + return true; + } + + /** + * @param int $catId + * + * @return mixed + */ + public function publishedItemsCount($catId = 0) + { + return $this->itemsCount($catId, $status = [Constants::PUBLISHER_STATUS_PUBLISHED]); + } + + /** + * @param int $catId + * @param string $status + * + * @return mixed + */ + public function itemsCount($catId = 0, $status = '') + { + return $this->helper->getHandler('Item')->getCountsByCat($catId, $status); + } +} diff --git a/class/common/Breadcrumb.php b/class/Common/Breadcrumb.php similarity index 91% rename from class/common/Breadcrumb.php rename to class/Common/Breadcrumb.php index 3221ebd1..cabbe3ed 100644 --- a/class/common/Breadcrumb.php +++ b/class/Common/Breadcrumb.php @@ -17,14 +17,14 @@ * @package xxxxx * * Example: - * $breadcrumb = new PedigreeBreadcrumb(); + * $breadcrumb = new Publisher\Common\Breadcrumb(); * $breadcrumb->addLink( 'bread 1', 'index1.php' ); * $breadcrumb->addLink( 'bread 2', '' ); * $breadcrumb->addLink( 'bread 3', 'index3.php' ); * echo $breadcrumb->render(); */ -defined('XOOPS_ROOT_PATH') || exit('XOOPS Root Path not defined'); +defined('XOOPS_ROOT_PATH') || die('XOOPS Root Path not defined'); /** * Class Breadcrumb @@ -64,7 +64,7 @@ public function render() { if (!isset($GLOBALS['xoTheme']) || !is_object($GLOBALS['xoTheme'])) { require_once $GLOBALS['xoops']->path('class/theme.php'); - $GLOBALS['xoTheme'] = new xos_opal_Theme(); + $GLOBALS['xoTheme'] = new \xos_opal_Theme(); } require_once $GLOBALS['xoops']->path('class/template.php'); diff --git a/class/common/Configurator.php b/class/Common/Configurator.php similarity index 95% rename from class/common/Configurator.php rename to class/Common/Configurator.php index 56ab0c2e..0fe1f986 100644 --- a/class/common/Configurator.php +++ b/class/Common/Configurator.php @@ -20,8 +20,8 @@ * */ -require_once __DIR__ . '/../include/common.php'; -require_once __DIR__ . '/../include/config.php'; +require_once __DIR__ . '/../../include/common.php'; +require_once __DIR__ . '/../../include/config.php'; //namespace Publisher; diff --git a/class/common/FilesManagement.php b/class/Common/FilesManagement.php similarity index 91% rename from class/common/FilesManagement.php rename to class/Common/FilesManagement.php index 29ec7444..ee463456 100644 --- a/class/common/FilesManagement.php +++ b/class/Common/FilesManagement.php @@ -29,7 +29,7 @@ public static function createFolder($folder) { try { if (!file_exists($folder)) { - if (!mkdir($folder) && !is_dir($folder)) { + if (!is_dir($folder) && !mkdir($folder) && !is_dir($folder)) { throw new \RuntimeException(sprintf('Unable to create the %s directory', $folder)); } @@ -130,18 +130,18 @@ public static function xcopy($source, $dest) public static function deleteDirectory($src) { // 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())) { @@ -178,7 +178,7 @@ public static function deleteDirectory($src) public static function rrmdir($src) { // 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; } @@ -190,7 +190,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(); @@ -218,7 +218,7 @@ public static function rrmdir($src) public static function rmove($src, $dest) { // 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; } @@ -228,12 +228,12 @@ public static function rmove($src, $dest) } // If the destination directory does not exist and could not be created stop processing - if (!is_dir($dest) && !mkdir($dest, 0755)) { + if (!is_dir($dest) && !mkdir($dest) && !is_dir($dest)) { return false; } // 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()); @@ -261,7 +261,7 @@ public static function rmove($src, $dest) public static function rcopy($src, $dest) { // 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; } @@ -271,12 +271,12 @@ public static function rcopy($src, $dest) } // If the destination directory does not exist and could not be created stop processing - if (!is_dir($dest) && !mkdir($dest, 0755)) { + if (!is_dir($dest) && !mkdir($dest) && !is_dir($dest)) { return false; } // 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()); diff --git a/class/common/ServerStats.php b/class/Common/ServerStats.php similarity index 98% rename from class/common/ServerStats.php rename to class/Common/ServerStats.php index 1fd39fd6..7cf63370 100644 --- a/class/common/ServerStats.php +++ b/class/Common/ServerStats.php @@ -51,7 +51,7 @@ public static function getServerStats() $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 ($gdlib = true === gd_info()) { + if(true === ($gdlib = gd_info())){ $html .= '
  • ' . constant('CO_' . $moduleDirNameUpper . '_GDLIBVERSION') . '' . $gdlib['GD Version'] . ''; } } diff --git a/class/common/VersionChecks.php b/class/Common/VersionChecks.php similarity index 100% rename from class/common/VersionChecks.php rename to class/Common/VersionChecks.php diff --git a/class/common/index.html b/class/Common/index.html similarity index 100% rename from class/common/index.html rename to class/Common/index.html diff --git a/class/constants.php b/class/Constants.php similarity index 94% rename from class/constants.php rename to class/Constants.php index 2935c01f..3e29bedc 100644 --- a/class/constants.php +++ b/class/Constants.php @@ -1,4 +1,5 @@ - */ -defined('XOOPS_ROOT_PATH') || exit('Restricted access.'); +defined('XOOPS_ROOT_PATH') || die('Restricted access'); /** - * Interface PublisherConstants + * class Constants */ -interface PublisherConstants +class Constants { // ITEM status const PUBLISHER_STATUS_NOTSET = -1; diff --git a/class/file.php b/class/File.php similarity index 55% rename from class/file.php rename to class/File.php index 20c261ed..87a84e4b 100644 --- a/class/file.php +++ b/class/File.php @@ -1,4 +1,4 @@ -publisher = Publisher\Helper::getInstance(); + $this->helper = Publisher\Helper::getInstance(); $this->db = \XoopsDatabaseFactory::getDatabaseConnection(); $this->initVar('fileid', XOBJ_DTYPE_INT, 0, false); $this->initVar('itemid', XOBJ_DTYPE_INT, null, true); @@ -58,7 +58,7 @@ public function __construct($id = null) $this->initVar('notifypub', XOBJ_DTYPE_INT, 0, false); $this->initVar('counter', XOBJ_DTYPE_INT, null, false); if (isset($id)) { - $file = $this->publisher->getHandler('file')->get($id); + $file = $this->helper->getHandler('file')->get($id); foreach ($file->vars as $k => $v) { $this->assignVar($k, $v['value']); } @@ -88,17 +88,17 @@ public function __call($method, $args) public function checkUpload($postField, $allowedMimetypes = [], &$errors) { $errors = []; - if (!$this->publisher->getHandler('mimetype')->checkMimeTypes($postField)) { + if (!$this->helper->getHandler('mimetype')->checkMimeTypes($postField)) { $errors[] = _CO_PUBLISHER_MESSAGE_WRONG_MIMETYPE; return false; } if (0 === count($allowedMimetypes)) { - $allowedMimetypes = $this->publisher->getHandler('mimetype')->getArrayByType(); + $allowedMimetypes = $this->helper->getHandler('mimetype')->getArrayByType(); } - $maxfilesize = $this->publisher->getConfig('maximum_filesize'); - $maxfilewidth = $this->publisher->getConfig('maximum_image_width'); - $maxfileheight = $this->publisher->getConfig('maximum_image_height'); + $maxfilesize = $this->helper->getConfig('maximum_filesize'); + $maxfilewidth = $this->helper->getConfig('maximum_image_width'); + $maxfileheight = $this->helper->getConfig('maximum_image_height'); xoops_load('XoopsMediaUploader'); $uploader = new \XoopsMediaUploader(Publisher\Utility::getUploadDir(), $allowedMimetypes, $maxfilesize, $maxfilewidth, $maxfileheight); if ($uploader->fetchMedia($postField)) { @@ -121,13 +121,13 @@ public function storeUpload($postField, $allowedMimetypes = [], &$errors) { $itemid = $this->getVar('itemid'); if (0 === count($allowedMimetypes)) { - $allowedMimetypes = $this->publisher->getHandler('mimetype')->getArrayByType(); + $allowedMimetypes = $this->helper->getHandler('mimetype')->getArrayByType(); } - $maxfilesize = $this->publisher->getConfig('maximum_filesize'); - $maxfilewidth = $this->publisher->getConfig('maximum_image_width'); - $maxfileheight = $this->publisher->getConfig('maximum_image_height'); + $maxfilesize = $this->helper->getConfig('maximum_filesize'); + $maxfilewidth = $this->helper->getConfig('maximum_image_width'); + $maxfileheight = $this->helper->getConfig('maximum_image_height'); if (!is_dir(Publisher\Utility::getUploadDir())) { - mkdir(Publisher\Utility::getUploadDir(), 0757); + @mkdir(Publisher\Utility::getUploadDir(), 0757); } xoops_load('XoopsMediaUploader'); $uploader = new \XoopsMediaUploader(Publisher\Utility::getUploadDir() . '/', $allowedMimetypes, $maxfilesize, $maxfilewidth, $maxfileheight); @@ -177,7 +177,7 @@ public function store($allowedMimetypes = null, $force = true, $doupload = true) } } - return $this->publisher->getHandler('file')->insert($this, $force); + return $this->helper->getHandler('file')->insert($this, $force); } /** @@ -268,149 +268,13 @@ public function getNameFromFilename() } /** - * @return PublisherFileForm + * @return FileForm */ public function getForm() { - require_once $GLOBALS['xoops']->path('modules/' . PUBLISHER_DIRNAME . '/class/form/file.php'); - $form = new PublisherFileForm($this); +// require_once $GLOBALS['xoops']->path('modules/' . PUBLISHER_DIRNAME . '/class/form/file.php'); + $form = new Publisher\Form\FileForm($this); return $form; } } - -/** - * Files handler class. - * This class is responsible for providing data access mechanisms to the data source - * of File class objects. - * - * @author marcan - * @package Publisher - */ -class PublisherFileHandler extends XoopsPersistableObjectHandler -{ - public $table_link = ''; - /** - * @var Publisher - * @access public - */ - public $helper; - - /** - * @param null|XoopsDatabase $db - */ - public function __construct(\XoopsDatabase $db) - { - $this->publisher = Publisher\Helper::getInstance(); - parent::__construct($db, 'publisher_files', 'PublisherFile', 'fileid', 'name'); - } - - /** - * delete a file from the database - * - * @param XoopsObject $file reference to the file to delete - * @param bool $force - * - * @return bool FALSE if failed. - */ - public function delete(\XoopsObject $file, $force = false) //delete(&$file, $force = false) - { - $ret = false; - // Delete the actual file - if (is_file($file->getFilePath()) && unlink($file->getFilePath())) { - $ret = parent::delete($file, $force); - } - - return $ret; - } - - /** - * delete files related to an item from the database - * - * @param XoopsObject $itemObj reference to the item which files to delete - * - * @return bool - */ - public function deleteItemFiles(\XoopsObject $itemObj) - { - if ('publisheritem' !== strtolower(get_class($itemObj))) { - return false; - } - $files = $this->getAllFiles($itemObj->itemid()); - $result = true; - foreach ($files as $file) { - if (!$this->delete($file)) { - $result = false; - } - } - - return $result; - } - - /** - * retrieve all files - * - * @param int $itemid - * @param int|array $status - * @param int $limit - * @param int $start - * @param string $sort - * @param string $order - * @param array $category - * - * @return array array of {@link PublisherFile} objects - */ - public function getAllFiles($itemid = 0, $status = -1, $limit = 0, $start = 0, $sort = 'datesub', $order = 'DESC', $category = []) - { - $files = []; - - $this->table_link = $this->db->prefix($this->publisher->getDirname() . '_items'); - - $result = $GLOBALS['xoopsDB']->query('SELECT COUNT(*) FROM ' . $this->db->prefix($this->publisher->getDirname() . '_files')); - list($count) = $GLOBALS['xoopsDB']->fetchRow($result); - if ($count > 0) { - $this->field_object = 'itemid'; - $this->field_link = 'itemid'; - $hasStatusCriteria = false; - $criteriaStatus = new \CriteriaCompo(); - if (is_array($status)) { - $hasStatusCriteria = true; - foreach ($status as $v) { - $criteriaStatus->add(new \Criteria('o.status', $v), 'OR'); - } - } elseif ($status != -1) { - $hasStatusCriteria = true; - $criteriaStatus->add(new \Criteria('o.status', $status), 'OR'); - } - $hasCategoryCriteria = false; - $criteriaCategory = new \CriteriaCompo(); - $category = (array)$category; - if (isset($category[0]) && 0 != $category[0] && count($category) > 0) { - $hasCategoryCriteria = true; - foreach ($category as $cat) { - $criteriaCategory->add(new \Criteria('l.categoryid', $cat), 'OR'); - } - } - $criteriaItemid = new \Criteria('o.itemid', $itemid); - $criteria = new \CriteriaCompo(); - if (0 != $itemid) { - $criteria->add($criteriaItemid); - } - if ($hasStatusCriteria) { - $criteria->add($criteriaStatus); - } - if ($hasCategoryCriteria) { - $criteria->add($criteriaCategory); - } - $criteria->setSort($sort); - $criteria->setOrder($order); - $criteria->setLimit($limit); - $criteria->setStart($start); - $files =& $this->getByLink($criteria, ['o.*'], true); - - // return $files; - } - - return $files; - } -} diff --git a/class/FileHandler.php b/class/FileHandler.php new file mode 100644 index 00000000..6f9c1a6f --- /dev/null +++ b/class/FileHandler.php @@ -0,0 +1,166 @@ + + * @author The SmartFactory + */ + +use XoopsModules\Publisher; + +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); + +require_once __DIR__ . '/../include/common.php'; + +// File status +//define("_PUBLISHER_STATUS_FILE_NOTSET", -1); +//define("_PUBLISHER_STATUS_FILE_ACTIVE", 1); +//define("_PUBLISHER_STATUS_FILE_INACTIVE", 2); + + +/** + * Files handler class. + * This class is responsible for providing data access mechanisms to the data source + * of File class objects. + * + * @author marcan + * @package Publisher + */ +class FileHandler extends \XoopsPersistableObjectHandler +{ + public $table_link = ''; + /** + * @var Publisher\Helper + * @access public + */ + public $helper; + + /** + * @param null|\XoopsDatabase $db + */ + public function __construct(\XoopsDatabase $db) + { + $this->helper = Publisher\Helper::getInstance(); + parent::__construct($db, 'publisher_files', File::class, 'fileid', 'name'); + } + + /** + * delete a file from the database + * + * @param XoopsObject $file reference to the file to delete + * @param bool $force + * + * @return bool FALSE if failed. + */ + public function delete(\XoopsObject $file, $force = false) //delete(&$file, $force = false) + { + $ret = false; + // Delete the actual file + if (is_file($file->getFilePath()) && unlink($file->getFilePath())) { + $ret = parent::delete($file, $force); + } + + return $ret; + } + + /** + * delete files related to an item from the database + * + * @param XoopsObject $itemObj reference to the item which files to delete + * + * @return bool + */ + public function deleteItemFiles(\XoopsObject $itemObj) + { + if ('publisheritem' !== strtolower(get_class($itemObj))) { + return false; + } + $files = $this->getAllFiles($itemObj->itemid()); + $result = true; + foreach ($files as $file) { + if (!$this->delete($file)) { + $result = false; + } + } + + return $result; + } + + /** + * retrieve all files + * + * @param int $itemid + * @param int|array $status + * @param int $limit + * @param int $start + * @param string $sort + * @param string $order + * @param array $category + * + * @return array array of {@link File} objects + */ + public function getAllFiles($itemid = 0, $status = -1, $limit = 0, $start = 0, $sort = 'datesub', $order = 'DESC', $category = []) + { + $files = []; + + $this->table_link = $this->db->prefix($this->helper->getDirname() . '_items'); + + $result = $GLOBALS['xoopsDB']->query('SELECT COUNT(*) FROM ' . $this->db->prefix($this->helper->getDirname() . '_files')); + list($count) = $GLOBALS['xoopsDB']->fetchRow($result); + if ($count > 0) { + $this->field_object = 'itemid'; + $this->field_link = 'itemid'; + $hasStatusCriteria = false; + $criteriaStatus = new \CriteriaCompo(); + if (is_array($status)) { + $hasStatusCriteria = true; + foreach ($status as $v) { + $criteriaStatus->add(new \Criteria('o.status', $v), 'OR'); + } + } elseif ($status != -1) { + $hasStatusCriteria = true; + $criteriaStatus->add(new \Criteria('o.status', $status), 'OR'); + } + $hasCategoryCriteria = false; + $criteriaCategory = new \CriteriaCompo(); + $category = (array)$category; + if (isset($category[0]) && 0 != $category[0] && count($category) > 0) { + $hasCategoryCriteria = true; + foreach ($category as $cat) { + $criteriaCategory->add(new \Criteria('l.categoryid', $cat), 'OR'); + } + } + $criteriaItemid = new \Criteria('o.itemid', $itemid); + $criteria = new \CriteriaCompo(); + if (0 != $itemid) { + $criteria->add($criteriaItemid); + } + if ($hasStatusCriteria) { + $criteria->add($criteriaStatus); + } + if ($hasCategoryCriteria) { + $criteria->add($criteriaCategory); + } + $criteria->setSort($sort); + $criteria->setOrder($order); + $criteria->setLimit($limit); + $criteria->setStart($start); + $files =& $this->getByLink($criteria, ['o.*'], true); + + // return $files; + } + + return $files; + } +} diff --git a/class/form/category.php b/class/Form/CategoryForm.php similarity index 90% rename from class/form/category.php rename to class/Form/CategoryForm.php index 504a118e..f65f9fa9 100644 --- a/class/form/category.php +++ b/class/Form/CategoryForm.php @@ -1,4 +1,4 @@ -path('class/tree.php'); /** - * Class PublisherCategoryForm + * Class Publisher\CategoryForm */ -class PublisherCategoryForm extends XoopsThemeForm +class CategoryForm extends \XoopsThemeForm { /** * @var Publisher @@ -52,7 +52,7 @@ class PublisherCategoryForm extends XoopsThemeForm */ public function __construct(&$target, $subCatsCount = 4) { - $this->publisher = Publisher\Helper::getInstance(); + $this->helper = Publisher\Helper::getInstance(); $this->targetObject =& $target; $this->subCatsCount = $subCatsCount; @@ -69,12 +69,12 @@ public function __construct(&$target, $subCatsCount = 4) public function createElements() { - require_once dirname(dirname(__DIR__)) . '/include/common.php'; + require_once __DIR__ . '/../../include/common.php'; // Category $criteria = new \Criteria(null); $criteria->setSort('weight'); $criteria->setOrder('ASC'); - $myTree = new \XoopsObjectTree($this->publisher->getHandler('category')->getObjects($criteria), 'categoryid', 'parentid'); + $myTree = new \XoopsObjectTree($this->helper->getHandler('Category')->getObjects($criteria), 'categoryid', 'parentid'); $moduleDirName = basename(dirname(__DIR__)); $module = \XoopsModule::getByDirname($moduleDirName); if (Publisher\Utility::checkVerXoops($GLOBALS['xoopsModule'], '2.5.9')) { @@ -93,8 +93,8 @@ public function createElements() // EDITOR $groups = $GLOBALS['xoopsUser'] ? $GLOBALS['xoopsUser']->getGroups() : XOOPS_GROUP_ANONYMOUS; - $gpermHandler = $this->publisher->getHandler('groupperm'); - $moduleId = $this->publisher->getModule()->mid(); + $gpermHandler = $this->helper->getHandler('groupperm'); + $moduleId = $this->helper->getModule()->mid(); $allowedEditors = Publisher\Utility::getEditors($gpermHandler->getItemIds('editors', $groups, $moduleId)); $nohtml = false; if (count($allowedEditors) > 0) { @@ -107,18 +107,18 @@ public function createElements() $editor = (null !== $GLOBALS['xoopsUser']->getVar('publisher_editor')) ? $GLOBALS['xoopsUser']->getVar('publisher_editor') : ''; // Need set through user profile } } - $editor = (empty($editor) || !in_array($editor, $allowedEditors)) ? $this->publisher->getConfig('submit_editor') : $editor; + $editor = (empty($editor) || !in_array($editor, $allowedEditors)) ? $this->helper->getConfig('submit_editor') : $editor; $formEditor = new \XoopsFormSelectEditor($this, 'editor', $editor, $nohtml, $allowedEditors); $this->addElement($formEditor); } else { - $editor = $this->publisher->getConfig('submit_editor'); + $editor = $this->helper->getConfig('submit_editor'); } $editorConfigs = []; - $editorConfigs['rows'] = '' == $this->publisher->getConfig('submit_editor_rows') ? 35 : $this->publisher->getConfig('submit_editor_rows'); - $editorConfigs['cols'] = '' == $this->publisher->getConfig('submit_editor_cols') ? 60 : $this->publisher->getConfig('submit_editor_cols'); - $editorConfigs['width'] = '' == $this->publisher->getConfig('submit_editor_width') ? '100%' : $this->publisher->getConfig('submit_editor_width'); - $editorConfigs['height'] = '' == $this->publisher->getConfig('submit_editor_height') ? '400px' : $this->publisher->getConfig('submit_editor_height'); + $editorConfigs['rows'] = '' == $this->helper->getConfig('submit_editor_rows') ? 35 : $this->helper->getConfig('submit_editor_rows'); + $editorConfigs['cols'] = '' == $this->helper->getConfig('submit_editor_cols') ? 60 : $this->helper->getConfig('submit_editor_cols'); + $editorConfigs['width'] = '' == $this->helper->getConfig('submit_editor_width') ? '100%' : $this->helper->getConfig('submit_editor_width'); + $editorConfigs['height'] = '' == $this->helper->getConfig('submit_editor_height') ? '400px' : $this->helper->getConfig('submit_editor_height'); $editorConfigs['name'] = 'header'; $editorConfigs['value'] = $this->targetObject->header('e'); diff --git a/class/form/file.php b/class/Form/FileForm.php similarity index 92% rename from class/form/file.php rename to class/Form/FileForm.php index 5d4707e6..2bb9633f 100644 --- a/class/form/file.php +++ b/class/Form/FileForm.php @@ -1,4 +1,4 @@ -loadLanguage('main'); /** - * Class PublisherFileForm + * Class FileForm */ -class PublisherFileForm extends XoopsThemeForm +class FileForm extends \XoopsThemeForm { /** * @var Publisher @@ -49,7 +50,7 @@ class PublisherFileForm extends XoopsThemeForm */ public function __construct(&$target) { - $this->publisher = Publisher\Helper::getInstance(); + $this->helper = Publisher\Helper::getInstance(); $this->targetObject =& $target; parent::__construct(_AM_PUBLISHER_UPLOAD_FILE, 'form', xoops_getenv('PHP_SELF'), 'post', true); @@ -78,7 +79,7 @@ public function createElements() $this->addElement($fileBox); //} - $statusSelect = new \XoopsFormRadioYN(_CO_PUBLISHER_FILE_STATUS, 'file_status', PublisherConstants::PUBLISHER_STATUS_FILE_ACTIVE); + $statusSelect = new \XoopsFormRadioYN(_CO_PUBLISHER_FILE_STATUS, 'file_status', Constants::PUBLISHER_STATUS_FILE_ACTIVE); $statusSelect->setDescription(_CO_PUBLISHER_FILE_STATUS_DSC); $this->addElement($statusSelect); diff --git a/class/form/item.php b/class/Form/ItemForm.php similarity index 85% rename from class/form/item.php rename to class/Form/ItemForm.php index e6e22b21..7fc2ab94 100644 --- a/class/form/item.php +++ b/class/Form/ItemForm.php @@ -1,4 +1,4 @@ -path('class/tree.php'); -require_once PUBLISHER_ROOT_PATH . '/class/formdatetime.php'; -require_once PUBLISHER_ROOT_PATH . '/class/themetabform.php'; +//require_once PUBLISHER_ROOT_PATH . '/class/formdatetime.php'; +//require_once PUBLISHER_ROOT_PATH . '/class/themetabform.php'; /** - * Class PublisherItemForm + * Class ItemForm */ -class PublisherItemForm extends PublisherThemeTabForm +class ItemForm extends Publisher\ThemeTabForm { public $checkperm = true; public $tabs = [ @@ -47,36 +49,36 @@ class PublisherItemForm extends PublisherThemeTabForm ]; public $mainTab = [ - PublisherConstants::PUBLISHER_SUBTITLE, - PublisherConstants::PUBLISHER_ITEM_SHORT_URL, - PublisherConstants::PUBLISHER_ITEM_TAG, - PublisherConstants::PUBLISHER_SUMMARY, - PublisherConstants::PUBLISHER_DOHTML, - PublisherConstants::PUBLISHER_DOSMILEY, - PublisherConstants::PUBLISHER_DOXCODE, - PublisherConstants::PUBLISHER_DOIMAGE, - PublisherConstants::PUBLISHER_DOLINEBREAK, - PublisherConstants::PUBLISHER_DATESUB, - PublisherConstants::PUBLISHER_STATUS, - PublisherConstants::PUBLISHER_AUTHOR_ALIAS, - PublisherConstants::PUBLISHER_NOTIFY, - PublisherConstants::PUBLISHER_AVAILABLE_PAGE_WRAP, - PublisherConstants::PUBLISHER_UID + Constants::PUBLISHER_SUBTITLE, + Constants::PUBLISHER_ITEM_SHORT_URL, + Constants::PUBLISHER_ITEM_TAG, + Constants::PUBLISHER_SUMMARY, + Constants::PUBLISHER_DOHTML, + Constants::PUBLISHER_DOSMILEY, + Constants::PUBLISHER_DOXCODE, + Constants::PUBLISHER_DOIMAGE, + Constants::PUBLISHER_DOLINEBREAK, + Constants::PUBLISHER_DATESUB, + Constants::PUBLISHER_STATUS, + Constants::PUBLISHER_AUTHOR_ALIAS, + Constants::PUBLISHER_NOTIFY, + Constants::PUBLISHER_AVAILABLE_PAGE_WRAP, + Constants::PUBLISHER_UID ]; public $imagesTab = [ - PublisherConstants::PUBLISHER_IMAGE_ITEM + Constants::PUBLISHER_IMAGE_ITEM ]; public $filesTab = [ - PublisherConstants::PUBLISHER_ITEM_UPLOAD_FILE + Constants::PUBLISHER_ITEM_UPLOAD_FILE ]; public $othersTab = [ - PublisherConstants::PUBLISHER_ITEM_META_KEYWORDS, - PublisherConstants::PUBLISHER_ITEM_META_DESCRIPTION, - PublisherConstants::PUBLISHER_WEIGHT, - PublisherConstants::PUBLISHER_ALLOWCOMMENTS + Constants::PUBLISHER_ITEM_META_KEYWORDS, + Constants::PUBLISHER_ITEM_META_DESCRIPTION, + Constants::PUBLISHER_WEIGHT, + Constants::PUBLISHER_ALLOWCOMMENTS ]; /** @@ -96,7 +98,7 @@ public function isGranted($item) { $helper = Publisher\Helper::getInstance(); $ret = false; - if (!$this->checkperm || $helper->getHandler('permission')->isGranted('form_view', $item)) { + if (!$this->checkperm || $helper->getHandler('Permission')->isGranted('form_view', $item)) { $ret = true; } @@ -134,7 +136,7 @@ public function createElements($obj) { $helper = Publisher\Helper::getInstance(); - $allowedEditors = Publisher\Utility::getEditors($helper->getHandler('permission')->getGrantedItems('editors')); + $allowedEditors = Publisher\Utility::getEditors($helper->getHandler('Permission')->getGrantedItems('editors')); if (!is_object($GLOBALS['xoopsUser'])) { $group = [XOOPS_GROUP_ANONYMOUS]; @@ -149,28 +151,28 @@ public function createElements($obj) // Category $categoryFormSelect = new \XoopsFormSelect(_CO_PUBLISHER_CATEGORY, 'categoryid', $obj->getVar('categoryid', 'e')); $categoryFormSelect->setDescription(_CO_PUBLISHER_CATEGORY_DSC); - $categoryFormSelect->addOptionArray($helper->getHandler('category')->getCategoriesForSubmit()); + $categoryFormSelect->addOptionArray($helper->getHandler('Category')->getCategoriesForSubmit()); $this->addElement($categoryFormSelect); // ITEM TITLE $this->addElement(new \XoopsFormText(_CO_PUBLISHER_TITLE, 'title', 50, 255, $obj->getVar('title', 'e')), true); // SUBTITLE - if ($this->isGranted(PublisherConstants::PUBLISHER_SUBTITLE)) { + if ($this->isGranted(Constants::PUBLISHER_SUBTITLE)) { $this->addElement(new \XoopsFormText(_CO_PUBLISHER_SUBTITLE, 'subtitle', 50, 255, $obj->getVar('subtitle', 'e'))); } // SHORT URL - if ($this->isGranted(PublisherConstants::PUBLISHER_ITEM_SHORT_URL)) { + if ($this->isGranted(Constants::PUBLISHER_ITEM_SHORT_URL)) { $textShortUrl = new \XoopsFormText(_CO_PUBLISHER_ITEM_SHORT_URL, 'item_short_url', 50, 255, $obj->short_url('e')); $textShortUrl->setDescription(_CO_PUBLISHER_ITEM_SHORT_URL_DSC); $this->addElement($textShortUrl); } // TAGS - if (xoops_isActiveModule('tag') && $this->isGranted(PublisherConstants::PUBLISHER_ITEM_TAG)) { + if (xoops_isActiveModule('tag') && $this->isGranted(Constants::PUBLISHER_ITEM_TAG)) { require_once $GLOBALS['xoops']->path('modules/tag/include/formtag.php'); - $textTags = new TagFormTag('item_tag', 60, 255, $obj->getVar('item_tag', 'e'), 0); + $textTags = new \XoopsModules\Tag\FormTag('item_tag', 60, 255, $obj->getVar('item_tag', 'e'), 0); $this->addElement($textTags); } @@ -204,7 +206,7 @@ public function createElements($obj) $editorConfigs['height'] = !$helper->getConfig('submit_editor_height') ? '400px' : $helper->getConfig('submit_editor_height'); // SUMMARY - if ($this->isGranted(PublisherConstants::PUBLISHER_SUMMARY)) { + if ($this->isGranted(Constants::PUBLISHER_SUMMARY)) { // Description //$summaryText = new \XoopsFormTextArea(_CO_PUBLISHER_SUMMARY, 'summary', $obj->getVar('summary', 'e'), 7, 60); $editorConfigs['name'] = 'summary'; @@ -222,35 +224,35 @@ public function createElements($obj) $this->addElement($bodyText); // VARIOUS OPTIONS - if ($this->isGranted(PublisherConstants::PUBLISHER_DOHTML) - || $this->isGranted(PublisherConstants::PUBLISHER_DOSMILEY) - || $this->isGranted(PublisherConstants::PUBLISHER_DOXCODE) - || $this->isGranted(PublisherConstants::PUBLISHER_DOIMAGE) - || $this->isGranted(PublisherConstants::PUBLISHER_DOLINEBREAK)) { - if ($this->isGranted(PublisherConstants::PUBLISHER_DOHTML)) { + if ($this->isGranted(Constants::PUBLISHER_DOHTML) + || $this->isGranted(Constants::PUBLISHER_DOSMILEY) + || $this->isGranted(Constants::PUBLISHER_DOXCODE) + || $this->isGranted(Constants::PUBLISHER_DOIMAGE) + || $this->isGranted(Constants::PUBLISHER_DOLINEBREAK)) { + if ($this->isGranted(Constants::PUBLISHER_DOHTML)) { $html_radio = new \XoopsFormRadioYN(_CO_PUBLISHER_DOHTML, 'dohtml', $obj->dohtml(), _YES, _NO); $this->addElement($html_radio); } - if ($this->isGranted(PublisherConstants::PUBLISHER_DOSMILEY)) { + if ($this->isGranted(Constants::PUBLISHER_DOSMILEY)) { $smiley_radio = new \XoopsFormRadioYN(_CO_PUBLISHER_DOSMILEY, 'dosmiley', $obj->dosmiley(), _YES, _NO); $this->addElement($smiley_radio); } - if ($this->isGranted(PublisherConstants::PUBLISHER_DOXCODE)) { + if ($this->isGranted(Constants::PUBLISHER_DOXCODE)) { $xcode_radio = new \XoopsFormRadioYN(_CO_PUBLISHER_DOXCODE, 'doxcode', $obj->doxcode(), _YES, _NO); $this->addElement($xcode_radio); } - if ($this->isGranted(PublisherConstants::PUBLISHER_DOIMAGE)) { + if ($this->isGranted(Constants::PUBLISHER_DOIMAGE)) { $image_radio = new \XoopsFormRadioYN(_CO_PUBLISHER_DOIMAGE, 'doimage', $obj->doimage(), _YES, _NO); $this->addElement($image_radio); } - if ($this->isGranted(PublisherConstants::PUBLISHER_DOLINEBREAK)) { + if ($this->isGranted(Constants::PUBLISHER_DOLINEBREAK)) { $linebreak_radio = new \XoopsFormRadioYN(_CO_PUBLISHER_DOLINEBREAK, 'dolinebreak', $obj->dobr(), _YES, _NO); $this->addElement($linebreak_radio); } } // Available pages to wrap - if ($this->isGranted(PublisherConstants::PUBLISHER_AVAILABLE_PAGE_WRAP)) { + if ($this->isGranted(Constants::PUBLISHER_AVAILABLE_PAGE_WRAP)) { $wrapPages = \XoopsLists::getHtmlListAsArray(Publisher\Utility::getUploadDir(true, 'content')); $availableWrapPagesText = []; foreach ($wrapPages as $page) { @@ -261,7 +263,7 @@ public function createElements($obj) $this->addElement($availableWrapPages); } - if ($this->isGranted(PublisherConstants::PUBLISHER_UID)) { + if ($this->isGranted(Constants::PUBLISHER_UID)) { $this->addElement(new \XoopsFormSelectUser(_CO_PUBLISHER_UID, 'uid', false, $obj->uid(), 1, false), false); } @@ -271,7 +273,7 @@ public function createElements($obj) */ // Trabis : well, maybe is because you are getting 6000 objects into memory , no??? LOL /* - if ($this->isGranted(PublisherConstants::PUBLISHER_UID)) { + if ($this->isGranted(Constants::PUBLISHER_UID)) { $uidSelect = new \XoopsFormSelect(_CO_PUBLISHER_UID, 'uid', $obj->uid(), 1, false); $uidSelect->setDescription(_CO_PUBLISHER_UID_DSC); $sql = 'SELECT uid, uname FROM ' . $obj->db->prefix('users') . ' ORDER BY uname ASC'; @@ -293,7 +295,7 @@ public function createElements($obj) }*/ // Author ALias - if ($this->isGranted(PublisherConstants::PUBLISHER_AUTHOR_ALIAS)) { + if ($this->isGranted(Constants::PUBLISHER_AUTHOR_ALIAS)) { $element = new \XoopsFormText(_CO_PUBLISHER_AUTHOR_ALIAS, 'author_alias', 50, 255, $obj->getVar('author_alias', 'e')); $element->setDescription(_CO_PUBLISHER_AUTHOR_ALIAS_DSC); $this->addElement($element); @@ -301,12 +303,12 @@ public function createElements($obj) } // STATUS - if ($this->isGranted(PublisherConstants::PUBLISHER_STATUS)) { + if ($this->isGranted(Constants::PUBLISHER_STATUS)) { $options = [ - PublisherConstants::PUBLISHER_STATUS_SUBMITTED => _CO_PUBLISHER_SUBMITTED, - PublisherConstants::PUBLISHER_STATUS_PUBLISHED => _CO_PUBLISHER_PUBLISHED, - PublisherConstants::PUBLISHER_STATUS_OFFLINE => _CO_PUBLISHER_OFFLINE, - PublisherConstants::PUBLISHER_STATUS_REJECTED => _CO_PUBLISHER_REJECTED + Constants::PUBLISHER_STATUS_SUBMITTED => _CO_PUBLISHER_SUBMITTED, + Constants::PUBLISHER_STATUS_PUBLISHED => _CO_PUBLISHER_PUBLISHED, + Constants::PUBLISHER_STATUS_OFFLINE => _CO_PUBLISHER_OFFLINE, + Constants::PUBLISHER_STATUS_REJECTED => _CO_PUBLISHER_REJECTED ]; $statusSelect = new \XoopsFormSelect(_CO_PUBLISHER_STATUS, 'status', $obj->getVar('status')); $statusSelect->addOptionArray($options); @@ -316,13 +318,13 @@ public function createElements($obj) } // Datesub - if ($this->isGranted(PublisherConstants::PUBLISHER_DATESUB)) { + if ($this->isGranted(Constants::PUBLISHER_DATESUB)) { if ($obj->isNew()) { $datesub = time(); } else { $datesub = (0 == $obj->getVar('datesub')) ? time() : $obj->getVar('datesub'); } - $datesub_datetime = new PublisherFormDateTime(_CO_PUBLISHER_DATESUB, 'datesub', $size = 15, $datesub, true, true); + $datesub_datetime = new Publisher\FormDateTime(_CO_PUBLISHER_DATESUB, 'datesub', $size = 15, $datesub, true, true); // $datesub_datetime = new \XoopsFormDateTime(_CO_PUBLISHER_DATESUB, 'datesub', $size = 15, $datesub, true, true); $datesub_datetime->setDescription(_CO_PUBLISHER_DATESUB_DSC); @@ -330,7 +332,7 @@ public function createElements($obj) } // NOTIFY ON PUBLISH - if ($this->isGranted(PublisherConstants::PUBLISHER_NOTIFY)) { + if ($this->isGranted(Constants::PUBLISHER_NOTIFY)) { $notify_radio = new \XoopsFormRadioYN(_CO_PUBLISHER_NOTIFY, 'notify', $obj->notifypub(), _YES, _NO); $this->addElement($notify_radio); } @@ -340,7 +342,7 @@ public function createElements($obj) } // IMAGE - if ($this->isGranted(PublisherConstants::PUBLISHER_IMAGE_ITEM)) { + if ($this->isGranted(Constants::PUBLISHER_IMAGE_ITEM)) { $objimages = $obj->getImages(); $mainarray = is_object($objimages['main']) ? [$objimages['main']] : []; $mergedimages = array_merge($mainarray, $objimages['others']); @@ -497,7 +499,7 @@ public function createElements($obj) $this->startTab(_CO_PUBLISHER_TAB_FILES); } // File upload UPLOAD - if ($this->isGranted(PublisherConstants::PUBLISHER_ITEM_UPLOAD_FILE)) { + if ($this->isGranted(Constants::PUBLISHER_ITEM_UPLOAD_FILE)) { // NAME $nameText = new \XoopsFormText(_CO_PUBLISHER_FILENAME, 'item_file_name', 50, 255, ''); $nameText->setDescription(_CO_PUBLISHER_FILE_NAME_DSC); @@ -522,7 +524,7 @@ public function createElements($obj) unset($fileBox); if (!$obj->isNew()) { - $filesObj = $helper->getHandler('file')->getAllFiles($obj->itemid()); + $filesObj = $helper->getHandler('File')->getAllFiles($obj->itemid()); if (count($filesObj) > 0) { $table = ''; $table .= "
  • "; @@ -565,14 +567,14 @@ public function createElements($obj) } //$this->startTab(_CO_PUBLISHER_TAB_META); // Meta Keywords - if ($this->isGranted(PublisherConstants::PUBLISHER_ITEM_META_KEYWORDS)) { + if ($this->isGranted(Constants::PUBLISHER_ITEM_META_KEYWORDS)) { $text_meta_keywords = new \XoopsFormTextArea(_CO_PUBLISHER_ITEM_META_KEYWORDS, 'item_meta_keywords', $obj->meta_keywords('e'), 7, 60); $text_meta_keywords->setDescription(_CO_PUBLISHER_ITEM_META_KEYWORDS_DSC); $this->addElement($text_meta_keywords); } // Meta Description - if ($this->isGranted(PublisherConstants::PUBLISHER_ITEM_META_DESCRIPTION)) { + if ($this->isGranted(Constants::PUBLISHER_ITEM_META_DESCRIPTION)) { $text_meta_description = new \XoopsFormTextArea(_CO_PUBLISHER_ITEM_META_DESCRIPTION, 'item_meta_description', $obj->meta_description('e'), 7, 60); $text_meta_description->setDescription(_CO_PUBLISHER_ITEM_META_DESCRIPTION_DSC); $this->addElement($text_meta_description); @@ -581,13 +583,13 @@ public function createElements($obj) //$this->startTab(_CO_PUBLISHER_TAB_PERMISSIONS); // COMMENTS - if ($this->isGranted(PublisherConstants::PUBLISHER_ALLOWCOMMENTS)) { + if ($this->isGranted(Constants::PUBLISHER_ALLOWCOMMENTS)) { $addcomments_radio = new \XoopsFormRadioYN(_CO_PUBLISHER_ALLOWCOMMENTS, 'allowcomments', $obj->cancomment(), _YES, _NO); $this->addElement($addcomments_radio); } // WEIGHT - if ($this->isGranted(PublisherConstants::PUBLISHER_WEIGHT)) { + if ($this->isGranted(Constants::PUBLISHER_WEIGHT)) { $this->addElement(new \XoopsFormText(_CO_PUBLISHER_WEIGHT, 'weight', 5, 5, $obj->weight())); } diff --git a/class/form/index.html b/class/Form/index.html similarity index 100% rename from class/form/index.html rename to class/Form/index.html diff --git a/class/formdatetime.php b/class/FormDateTime.php similarity index 89% rename from class/formdatetime.php rename to class/FormDateTime.php index 5fe27927..c60754e1 100644 --- a/class/formdatetime.php +++ b/class/FormDateTime.php @@ -1,4 +1,4 @@ - */ -// defined('XOOPS_ROOT_PATH') || exit('Restricted access.'); +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); -require_once dirname(__DIR__) . '/include/common.php'; +require_once __DIR__ . '/../include/common.php'; /** - * Class PublisherFormDateTime + * Class FormDateTime */ -class PublisherFormDateTime extends XoopsFormElementTray +class FormDateTime extends \XoopsFormElementTray { /** * @param $caption diff --git a/class/groupperm.php b/class/GroupPermHandler.php similarity index 90% rename from class/groupperm.php rename to class/GroupPermHandler.php index 89adee9a..4bc07524 100644 --- a/class/groupperm.php +++ b/class/GroupPermHandler.php @@ -1,4 +1,4 @@ - */ -// defined('XOOPS_ROOT_PATH') || exit('Restricted access.'); +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); require_once $GLOBALS['xoops']->path('kernel/groupperm.php'); -require_once dirname(__DIR__) . '/include/common.php'; +require_once __DIR__ . '/../include/common.php'; /** - * Class PublisherGroupPermHandler + * Class GroupPermHandler */ -class PublisherGroupPermHandler extends XoopsGroupPermHandler +class GrouppermHandler extends \XoopsGroupPermHandler { /** * Check permission diff --git a/class/Helper.php b/class/Helper.php index 9ed72299..f9244fee 100644 --- a/class/Helper.php +++ b/class/Helper.php @@ -20,7 +20,7 @@ * @author trabis */ -defined('XOOPS_ROOT_PATH') || exit('Restricted access'); +defined('XOOPS_ROOT_PATH') || die('Restricted access'); /** * Class Helper @@ -43,7 +43,7 @@ protected function __construct($debug = false) /** * @param bool $debug * - * @return \Helper + * @return \Xmf\Module\Helper */ public static function getInstance($debug = false) { @@ -80,4 +80,22 @@ public function getDirname() { return $this->dirname; } + + /** + * Get an Object Handler + * + * @param string $name name of handler to load + * + * @return bool|\XoopsObjectHandler|\XoopsPersistableObjectHandler + */ + public function getHandler($name) + { + $ret = false; + $db = \XoopsDatabaseFactory::getDatabaseConnection(); + $class = '\\XoopsModules\\' . ucfirst(strtolower(basename(dirname(__DIR__)))) . '\\' . $name . 'Handler'; + $ret = new $class($db); + return $ret; + } } + + diff --git a/class/highlighter.php b/class/Highlighter.php similarity index 98% rename from class/highlighter.php rename to class/Highlighter.php index c70d26fb..2f44163f 100644 --- a/class/highlighter.php +++ b/class/Highlighter.php @@ -1,4 +1,4 @@ - * @link http://aidanlister.com/2004/04/highlighting-a-search-string-in-html-text/ */ -class PublisherHighlighter +class Highlighter { /** * Perform a simple text replace diff --git a/class/Item.php b/class/Item.php new file mode 100644 index 00000000..5fc1746a --- /dev/null +++ b/class/Item.php @@ -0,0 +1,1087 @@ + + * @author The SmartFactory + */ + +use Xmf\Request; +use XoopsModules\Publisher; + +//namespace Publisher; + +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); +require_once __DIR__ . '/../include/common.php'; + +/** + * Class Item + */ +class Item extends \XoopsObject +{ + /** + * @var Publisher + * @access public + */ + public $helper; + public $groupsRead = []; + + /** + * @var Publisher\Category + * @access public + */ + public $category; + + /** + * @param int|null $id + */ + public function __construct($id = null) + { + $this->helper = Publisher\Helper::getInstance(); + $this->db = \XoopsDatabaseFactory::getDatabaseConnection(); + $this->initVar('itemid', XOBJ_DTYPE_INT, 0); + $this->initVar('categoryid', XOBJ_DTYPE_INT, 0, false); + $this->initVar('title', XOBJ_DTYPE_TXTBOX, '', true, 255); + $this->initVar('subtitle', XOBJ_DTYPE_TXTBOX, '', false, 255); + $this->initVar('summary', XOBJ_DTYPE_TXTAREA, '', false); + $this->initVar('body', XOBJ_DTYPE_TXTAREA, '', false); + $this->initVar('uid', XOBJ_DTYPE_INT, 0, false); + $this->initVar('author_alias', XOBJ_DTYPE_TXTBOX, '', false, 255); + $this->initVar('datesub', XOBJ_DTYPE_INT, '', false); + $this->initVar('status', XOBJ_DTYPE_INT, -1, false); + $this->initVar('image', XOBJ_DTYPE_INT, 0, false); + $this->initVar('images', XOBJ_DTYPE_TXTBOX, '', false, 255); + $this->initVar('counter', XOBJ_DTYPE_INT, 0, false); + $this->initVar('rating', XOBJ_DTYPE_OTHER, 0, false); + $this->initVar('votes', XOBJ_DTYPE_INT, 0, false); + $this->initVar('weight', XOBJ_DTYPE_INT, 0, false); + $this->initVar('dohtml', XOBJ_DTYPE_INT, 1, true); + $this->initVar('dosmiley', XOBJ_DTYPE_INT, 1, true); + $this->initVar('doimage', XOBJ_DTYPE_INT, 1, true); + $this->initVar('dobr', XOBJ_DTYPE_INT, 1, false); + $this->initVar('doxcode', XOBJ_DTYPE_INT, 1, true); + $this->initVar('cancomment', XOBJ_DTYPE_INT, 1, true); + $this->initVar('comments', XOBJ_DTYPE_INT, 0, false); + $this->initVar('notifypub', XOBJ_DTYPE_INT, 1, false); + $this->initVar('meta_keywords', XOBJ_DTYPE_TXTAREA, '', false); + $this->initVar('meta_description', XOBJ_DTYPE_TXTAREA, '', false); + $this->initVar('short_url', XOBJ_DTYPE_TXTBOX, '', false, 255); + $this->initVar('item_tag', XOBJ_DTYPE_TXTAREA, '', false); + // Non consistent values + $this->initVar('pagescount', XOBJ_DTYPE_INT, 0, false); + if (isset($id)) { + $item = $this->helper->getHandler('Item')->get($id); + foreach ($item->vars as $k => $v) { + $this->assignVar($k, $v['value']); + } + } + } + + /** + * @param string $method + * @param array $args + * + * @return mixed + */ + public function __call($method, $args) + { + $arg = isset($args[0]) ? $args[0] : null; + + return $this->getVar($method, $arg); + } + + /** + * @return null|Publisher\Category + */ + public function getCategory() + { + if (!isset($this->category)) { + $this->category = $this->helper->getHandler('Category')->get($this->getVar('categoryid')); + } + + return $this->category; + } + + /** + * @param int $maxLength + * @param string $format + * + * @return mixed|string + */ + public function getTitle($maxLength = 0, $format = 'S') + { + $ret = $this->getVar('title', $format); + if (0 != $maxLength) { + if (!XOOPS_USE_MULTIBYTES) { + if (strlen($ret) >= $maxLength) { + $ret = Publisher\Utility::substr($ret, 0, $maxLength); + } + } + } + + return $ret; + } + + /** + * @param int $maxLength + * @param string $format + * + * @return mixed|string + */ + public function getSubtitle($maxLength = 0, $format = 'S') + { + $ret = $this->getVar('subtitle', $format); + if (0 != $maxLength) { + if (!XOOPS_USE_MULTIBYTES) { + if (strlen($ret) >= $maxLength) { + $ret = Publisher\Utility::substr($ret, 0, $maxLength); + } + } + } + + return $ret; + } + + /** + * @param int $maxLength + * @param string $format + * @param string $stripTags + * + * @return mixed|string + */ + public function getSummary($maxLength = 0, $format = 'S', $stripTags = '') + { + $ret = $this->getVar('summary', $format); + if (!empty($stripTags)) { + $ret = strip_tags($ret, $stripTags); + } + if (0 != $maxLength) { + if (!XOOPS_USE_MULTIBYTES) { + if (strlen($ret) >= $maxLength) { + //$ret = Publisher\Utility::substr($ret , 0, $maxLength); + // $ret = Publisher\Utility::truncateTagSafe($ret, $maxLength, $etc = '...', $breakWords = false); + $ret = Publisher\Utility::truncateTagSafe($ret, $maxLength, $etc = '...', $breakWords = false); + } + } + } + + return $ret; + } + + /** + * @param int $maxLength + * @param bool $fullSummary + * + * @return mixed|string + */ + public function getBlockSummary($maxLength = 0, $fullSummary = false) + { + if ($fullSummary) { + $ret = $this->getSummary(0, 's', '

    '); + } else { + $ret = $this->getSummary($maxLength, 's', '

    '); + } + //no summary? get body! + if ('' === $ret) { + $ret = $this->getBody($maxLength, 's', '

    '); + } + + return $ret; + } + + /** + * @param string $fileName + * + * @return string + */ + public function wrapPage($fileName) + { + $content = ''; + $page = Publisher\Utility::getUploadDir(true, 'content') . $fileName; + if (file_exists($page)) { + // this page uses smarty template + ob_start(); + include $page; + $content = ob_get_contents(); + ob_end_clean(); + // Cleaning the content + $bodyStartPos = strpos($content, ''); + if ($bodyStartPos) { + $bodyEndPos = strpos($content, '', $bodyStartPos); + $content = substr($content, $bodyStartPos + strlen(''), $bodyEndPos - strlen('') - $bodyStartPos); + } + // Check if ML Hack is installed, and if yes, parse the $content in formatForML + $myts = \MyTextSanitizer::getInstance(); + if (method_exists($myts, 'formatForML')) { + $content = $myts->formatForML($content); + } + } + + return $content; + } + + /** + * This method returns the body to be displayed. Not to be used for editing + * + * @param int $maxLength + * @param string $format + * @param string $stripTags + * + * @return mixed|string + */ + public function getBody($maxLength = 0, $format = 'S', $stripTags = '') + { + $ret = $this->getVar('body', $format); + $wrapPos = strpos($ret, '[pagewrap='); + if (!(false === $wrapPos)) { + $wrapPages = []; + $wrapCodeLength = strlen('[pagewrap='); + while (!(false === $wrapPos)) { + $endWrapPos = strpos($ret, ']', $wrapPos); + if ($endWrapPos) { + $wrap_page_name = substr($ret, $wrapPos + $wrapCodeLength, $endWrapPos - $wrapCodeLength - $wrapPos); + $wrapPages[] = $wrap_page_name; + } + $wrapPos = strpos($ret, '[pagewrap=', $endWrapPos - 1); + } + foreach ($wrapPages as $page) { + $wrapPageContent = $this->wrapPage($page); + $ret = str_replace("[pagewrap={$page}]", $wrapPageContent, $ret); + } + } + if ($this->helper->getConfig('item_disp_blocks_summary')) { + $summary = $this->getSummary($maxLength, $format, $stripTags); + if ($summary) { + $ret = $this->getSummary() . '

    ' . $ret; + } + } + if (!empty($stripTags)) { + $ret = strip_tags($ret, $stripTags); + } + if (0 != $maxLength) { + if (!XOOPS_USE_MULTIBYTES) { + if (strlen($ret) >= $maxLength) { + //$ret = Publisher\Utility::substr($ret , 0, $maxLength); + $ret = Publisher\Utility::truncateTagSafe($ret, $maxLength, $etc = '...', $breakWords = false); + } + } + } + + return $ret; + } + + /** + * @param string $dateFormat + * @param string $format + * + * @return string + */ + public function getDatesub($dateFormat = '', $format = 'S') + { + if (empty($dateFormat)) { + $dateFormat = $this->helper->getConfig('format_date'); + } + + return formatTimestamp($this->getVar('datesub', $format), $dateFormat); + } + + /** + * @param int $realName + * + * @return string + */ + public function posterName($realName = -1) + { + xoops_load('XoopsUserUtility'); + if ($realName == -1) { + $realName = $this->helper->getConfig('format_realname'); + } + $ret = $this->author_alias(); + if ('' == $ret) { + $ret = \XoopsUserUtility::getUnameFromId($this->uid(), $realName); + } + + return $ret; + } + + /** + * @return string + */ + public function posterAvatar() + { + $ret = 'blank.gif'; + $memberHandler = xoops_getHandler('member'); + $thisUser = $memberHandler->getUser($this->uid()); + if (is_object($thisUser)) { + $ret = $thisUser->getVar('user_avatar'); + } + + return $ret; + } + + /** + * @return string + */ + public function getLinkedPosterName() + { + xoops_load('XoopsUserUtility'); + $ret = $this->author_alias(); + if ('' === $ret) { + $ret = \XoopsUserUtility::getUnameFromId($this->uid(), $this->helper->getConfig('format_realname'), true); + } + + return $ret; + } + + /** + * @return mixed + */ + public function updateCounter() + { + return $this->helper->getHandler('Item')->updateCounter($this->itemid()); + } + + /** + * @param bool $force + * + * @return bool + */ + public function store($force = true) + { + $isNew = $this->isNew(); + if (!$this->helper->getHandler('Item')->insert($this, $force)) { + return false; + } + if ($isNew && $this->status() == Constants::PUBLISHER_STATUS_PUBLISHED) { + // Increment user posts + $userHandler = xoops_getHandler('user'); + $memberHandler = xoops_getHandler('member'); + $poster = $userHandler->get($this->uid()); + if (is_object($poster) && !$poster->isNew()) { + $poster->setVar('posts', $poster->getVar('posts') + 1); + if (!$memberHandler->insertUser($poster, true)) { + $this->setErrors('Article created but could not increment user posts.'); + + return false; + } + } + } + + return true; + } + + /** + * @return string + */ + public function getCategoryName() + { + return $this->getCategory()->name(); + } + + /** + * @return string + */ + public function getCategoryUrl() + { + return $this->getCategory()->getCategoryUrl(); + } + + /** + * @return string + */ + public function getCategoryLink() + { + return $this->getCategory()->getCategoryLink(); + } + + /** + * @param bool $withAllLink + * + * @return string + */ + public function getCategoryPath($withAllLink = true) + { + return $this->getCategory()->getCategoryPath($withAllLink); + } + + /** + * @return string + */ + public function getCategoryImagePath() + { + return Publisher\Utility::getImageDir('category', false) . $this->getCategory()->getImage(); + } + + /** + * @return mixed + */ + public function getFiles() + { + return $this->helper->getHandler('file')->getAllFiles($this->itemid(), Constants::PUBLISHER_STATUS_FILE_ACTIVE); + } + + /** + * @return string + */ + public function getAdminLinks() + { + $adminLinks = ''; + if (is_object($GLOBALS['xoopsUser']) + && (Publisher\Utility::userIsAdmin() || Publisher\Utility::userIsAuthor($this) + || $this->helper->getHandler('permission')->isGranted('item_submit', $this->categoryid()))) { + if (Publisher\Utility::userIsAdmin() || Publisher\Utility::userIsAuthor($this) || Publisher\Utility::userIsModerator($this)) { + if ($this->helper->getConfig('perm_edit') || Publisher\Utility::userIsModerator($this) || Publisher\Utility::userIsAdmin()) { + // Edit button + $adminLinks .= "" . _CO_PUBLISHER_EDIT . ""; + $adminLinks .= ' '; + } + if ($this->helper->getConfig('perm_delete') || Publisher\Utility::userIsModerator($this) || Publisher\Utility::userIsAdmin()) { + // Delete button + $adminLinks .= "itemid() . "'>" . _CO_PUBLISHER_DELETE . ""; + $adminLinks .= ' '; + } + } + if ($this->helper->getConfig('perm_clone') || Publisher\Utility::userIsModerator($this) || Publisher\Utility::userIsAdmin()) { + // Duplicate button + $adminLinks .= "itemid() . "'>" . _CO_PUBLISHER_CLONE . ""; + $adminLinks .= ' '; + } + } + + // PDF button + if ($this->helper->getConfig('display_pdf')) { + if (!is_file(XOOPS_ROOT_PATH . '/class/libraries/vendor/tecnickcom/tcpdf/tcpdf.php')) { + // if (is_object($GLOBALS['xoopsUser']) && Publisher\Utility::userIsAdmin()) { + // $GLOBALS['xoTheme']->addStylesheet('/modules/system/css/jquery.jgrowl.min.css'); + // $GLOBALS['xoTheme']->addScript('browse.php?Frameworks/jquery/plugins/jquery.jgrowl.js'); + // $adminLinks .= ''; + // } + } else { + $adminLinks .= "" . _CO_PUBLISHER_PDF . ""; + $adminLinks .= ' '; + } + } + + // Print button + $adminLinks .= "itemid(), $this->short_url()) . "' rel='nofollow' target='_blank'>" . _CO_PUBLISHER_PRINT . ""; + $adminLinks .= ' '; + // Email button + if (xoops_isActiveModule('tellafriend')) { + $subject = sprintf(_CO_PUBLISHER_INTITEMFOUND, $GLOBALS['xoopsConfig']['sitename']); + $subject = $this->convertForJapanese($subject); + $maillink = Publisher\Utility::tellAFriend($subject); + $adminLinks .= '' . _CO_PUBLISHER_MAIL . ''; + $adminLinks .= ' '; + } + + return $adminLinks; + } + + /** + * @param array $notifications + */ + public function sendNotifications($notifications = []) + { + $notificationHandler = xoops_getHandler('notification'); + $tags = []; + + $tags['MODULE_NAME'] = $this->helper->getModule()->getVar('name'); + $tags['ITEM_NAME'] = $this->getTitle(); + $tags['ITEM_NAME'] = $this->subtitle(); + $tags['CATEGORY_NAME'] = $this->getCategoryName(); + $tags['CATEGORY_URL'] = PUBLISHER_URL . '/category.php?categoryid=' . $this->categoryid(); + $tags['ITEM_BODY'] = $this->body(); + $tags['DATESUB'] = $this->getDatesub(); + foreach ($notifications as $notification) { + switch ($notification) { + case Constants::PUBLISHER_NOTIFY_ITEM_PUBLISHED: + $tags['ITEM_URL'] = PUBLISHER_URL . '/item.php?itemid=' . $this->itemid(); + $notificationHandler->triggerEvent('global_item', 0, 'published', $tags, [], $this->helper->getModule()->getVar('mid')); + $notificationHandler->triggerEvent('category_item', $this->categoryid(), 'published', $tags, [], $this->helper->getModule()->getVar('mid')); + $notificationHandler->triggerEvent('item', $this->itemid(), 'approved', $tags, [], $this->helper->getModule()->getVar('mid')); + break; + case Constants::PUBLISHER_NOTIFY_ITEM_SUBMITTED: + $tags['WAITINGFILES_URL'] = PUBLISHER_URL . '/admin/item.php?itemid=' . $this->itemid(); + $notificationHandler->triggerEvent('global_item', 0, 'submitted', $tags, [], $this->helper->getModule()->getVar('mid')); + $notificationHandler->triggerEvent('category_item', $this->categoryid(), 'submitted', $tags, [], $this->helper->getModule()->getVar('mid')); + break; + case Constants::PUBLISHER_NOTIFY_ITEM_REJECTED: + $notificationHandler->triggerEvent('item', $this->itemid(), 'rejected', $tags, [], $this->helper->getModule()->getVar('mid')); + break; + case -1: + default: + break; + } + } + } + + /** + * Sets default permissions for this item + */ + public function setDefaultPermissions() + { + $memberHandler = xoops_getHandler('member'); + $groups = $memberHandler->getGroupList(); + $j = 0; + $groupIds = []; + foreach (array_keys($groups) as $i) { + $groupIds[$j] = $i; + ++$j; + } + $this->groupsRead = $groupIds; + } + + /** + * @todo look at this + * + * @param $groupIds + */ + public function setPermissions($groupIds) + { + if (!isset($groupIds)) { + $memberHandler = xoops_getHandler('member'); + $groups = $memberHandler->getGroupList(); + $j = 0; + $groupIds = []; + foreach (array_keys($groups) as $i) { + $groupIds[$j] = $i; + ++$j; + } + } + } + + /** + * @return bool + */ + public function notLoaded() + { + return $this->getVar('itemid') == -1; + } + + /** + * @return string + */ + public function getItemUrl() + { + return Publisher\Seo::generateUrl('item', $this->itemid(), $this->short_url()); + } + + /** + * @param bool $class + * @param int $maxsize + * + * @return string + */ + public function getItemLink($class = false, $maxsize = 0) + { + if ($class) { + return '' . $this->getTitle($maxsize) . ''; + } else { + return '' . $this->getTitle($maxsize) . ''; + } + } + + /** + * @return string + */ + public function getWhoAndWhen() + { + $posterName = $this->getLinkedPosterName(); + $postdate = $this->getDatesub(); + + return sprintf(_CO_PUBLISHER_POSTEDBY, $posterName, $postdate); + } + + /** + * @return string + */ + public function getWho() + { + $posterName = $this->getLinkedPosterName(); + + return $posterName; + } + + /** + * @return string + */ + public function getWhen() + { + $postdate = $this->getDatesub(); + + return $postdate; + } + + /** + * @param null|string $body + * + * @return string + */ + public function plainMaintext($body = null) + { + $ret = ''; + if (!$body) { + $body = $this->body(); + } + $ret .= str_replace('[pagebreak]', '

    ', $body); + + return $ret; + } + + /** + * @param int $itemPageId + * @param null|string $body + * + * @return string + */ + public function buildMainText($itemPageId = -1, $body = null) + { + if (null === $body) { + $body = $this->body(); + } + $bodyParts = explode('[pagebreak]', $body); + $this->setVar('pagescount', count($bodyParts)); + if (count($bodyParts) <= 1) { + return $this->plainMaintext($body); + } + $ret = ''; + if ($itemPageId == -1) { + $ret .= trim($bodyParts[0]); + + return $ret; + } + if ($itemPageId >= count($bodyParts)) { + $itemPageId = count($bodyParts) - 1; + } + $ret .= trim($bodyParts[$itemPageId]); + + return $ret; + } + + /** + * @return mixed + */ + public function getImages() + { + static $ret; + $itemid = $this->getVar('itemid'); + if (!isset($ret[$itemid])) { + $ret[$itemid]['main'] = ''; + $ret[$itemid]['others'] = []; + $imagesIds = []; + $image = $this->getVar('image'); + $images = $this->getVar('images'); + if ('' != $images) { + $imagesIds = explode('|', $images); + } + if ($image > 0) { + $imagesIds = array_merge($imagesIds, [$image]); + } + $imageObjs = []; + if (count($imagesIds) > 0) { + $imageHandler = xoops_getHandler('image'); + $criteria = new \CriteriaCompo(new \Criteria('image_id', '(' . implode(',', $imagesIds) . ')', 'IN')); + $imageObjs = $imageHandler->getObjects($criteria, true); + unset($criteria); + } + foreach ($imageObjs as $id => $imageObj) { + if ($id == $image) { + $ret[$itemid]['main'] = $imageObj; + } else { + $ret[$itemid]['others'][] = $imageObj; + } + unset($imageObj); + } + unset($imageObjs); + } + + return $ret[$itemid]; + } + + /** + * @param string $display + * @param int $maxCharTitle + * @param int $maxCharSummary + * @param bool $fullSummary + * + * @return array + */ + public function toArraySimple($display = 'default', $maxCharTitle = 0, $maxCharSummary = 0, $fullSummary = false) + { + $itemPageId = -1; + if (is_numeric($display)) { + $itemPageId = $display; + $display = 'all'; + } + $item['itemid'] = $this->itemid(); + $item['uid'] = $this->uid(); + $item['itemurl'] = $this->getItemUrl(); + $item['titlelink'] = $this->getItemLink('titlelink', $maxCharTitle); + $item['subtitle'] = $this->subtitle(); + $item['datesub'] = $this->getDatesub(); + $item['counter'] = $this->counter(); + $item['who'] = $this->getWho(); + $item['when'] = $this->getWhen(); + $item['category'] = $this->getCategoryName(); + $item = $this->getMainImage($item); + switch ($display) { + case 'summary': + case 'list': + break; + case 'full': + case 'wfsection': + case 'default': + $summary = $this->getSummary($maxCharSummary); + if (!$summary) { + $summary = $this->getBody($maxCharSummary); + } + $item['summary'] = $summary; + $item = $this->toArrayFull($item); + break; + case 'all': + $item = $this->toArrayFull($item); + $item = $this->toArrayAll($item, $itemPageId); + break; + } + // Highlighting searched words + $highlight = true; + if ($highlight && Request::getString('keywords', '', 'GET')) { + $myts = \MyTextSanitizer::getInstance(); + $keywords = $myts->htmlSpecialChars(trim(urldecode(Request::getString('keywords', '', 'GET')))); + $fields = ['title', 'maintext', 'summary']; + foreach ($fields as $field) { + if (isset($item[$field])) { + $item[$field] = $this->highlight($item[$field], $keywords); + } + } + } + + return $item; + } + + /** + * @param array $item + * + * @return array + */ + public function toArrayFull($item) + { + $item['title'] = $this->getTitle(); + $item['clean_title'] = $this->getTitle(); + $item['itemurl'] = $this->getItemUrl(); + $item['cancomment'] = $this->cancomment(); + $item['comments'] = $this->comments(); + $item['adminlink'] = $this->getAdminLinks(); + $item['categoryPath'] = $this->getCategoryPath($this->helper->getConfig('format_linked_path')); + $item['who_when'] = $this->getWhoAndWhen(); + $item['who'] = $this->getWho(); + $item['when'] = $this->getWhen(); + $item['category'] = $this->getCategoryName(); + $item = $this->getMainImage($item); + + return $item; + } + + /** + * @param array $item + * @param int $itemPageId + * + * @return array + */ + public function toArrayAll($item, $itemPageId) + { + $item['maintext'] = $this->buildMainText($itemPageId, $this->getBody()); + $item = $this->getOtherImages($item); + + return $item; + } + + /** + * @param array $item + * + * @return array + */ + public function getMainImage($item = []) + { + $images = $this->getImages(); + $item['image_path'] = ''; + $item['image_name'] = ''; + if (is_object($images['main'])) { + $dimensions = getimagesize($GLOBALS['xoops']->path('uploads/' . $images['main']->getVar('image_name'))); + $item['image_width'] = $dimensions[0]; + $item['image_height'] = $dimensions[1]; + $item['image_path'] = XOOPS_URL . '/uploads/' . $images['main']->getVar('image_name'); + // check to see if GD function exist + if (!function_exists('imagecreatetruecolor')) { + $item['image_thumb'] = XOOPS_URL . '/uploads/' . $images['main']->getVar('image_name'); + } else { + $item['image_thumb'] = PUBLISHER_URL . '/thumb.php?src=' . XOOPS_URL . '/uploads/' . $images['main']->getVar('image_name') . '&h=180'; + } + $item['image_name'] = $images['main']->getVar('image_nicename'); + } + + return $item; + } + + /** + * @param array $item + * + * @return array + */ + public function getOtherImages($item = []) + { + $images = $this->getImages(); + $item['images'] = []; + $i = 0; + foreach ($images['others'] as $image) { + $dimensions = getimagesize($GLOBALS['xoops']->path('uploads/' . $image->getVar('image_name'))); + $item['images'][$i]['width'] = $dimensions[0]; + $item['images'][$i]['height'] = $dimensions[1]; + $item['images'][$i]['path'] = XOOPS_URL . '/uploads/' . $image->getVar('image_name'); + // check to see if GD function exist + if (!function_exists('imagecreatetruecolor')) { + $item['images'][$i]['thumb'] = XOOPS_URL . '/uploads/' . $image->getVar('image_name'); + } else { + $item['images'][$i]['thumb'] = PUBLISHER_URL . '/thumb.php?src=' . XOOPS_URL . '/uploads/' . $image->getVar('image_name') . '&w=240'; + } + $item['images'][$i]['name'] = $image->getVar('image_nicename'); + ++$i; + } + + return $item; + } + + /** + * @param string $content + * @param string|array $keywords + * + * @return string Text + */ + public function highlight($content, $keywords) + { + $color = $this->helper->getConfig('format_highlight_color'); + if (0 !== strpos($color, '#')) { + $color = '#' . $color; + } + require_once __DIR__ . '/highlighter.php'; + $highlighter = new Highlighter(); + $highlighter->setReplacementString('\1'); + + return $highlighter->highlight($content, $keywords); + } + + /** + * Create metada and assign it to template + */ + public function createMetaTags() + { + $publisherMetagen = new Publisher\Metagen($this->getTitle(), $this->meta_keywords(), $this->meta_description(), $this->category->categoryPath); + $publisherMetagen->createMetaTags(); + } + + /** + * @param string $str + * + * @return string + */ + protected function convertForJapanese($str) + { + // no action, if not flag + if (!defined('_PUBLISHER_FLAG_JP_CONVERT')) { + return $str; + } + // no action, if not Japanese + if ('japanese' !== $GLOBALS['xoopsConfig']['language']) { + return $str; + } + // presume OS Browser + $agent = Request::getString('HTTP_USER_AGENT', '', 'SERVER'); + $os = ''; + $browser = ''; + // if (preg_match("/Win/i", $agent)) { + if (false !== stripos($agent, 'Win')) { + $os = 'win'; + } + // if (preg_match("/MSIE/i", $agent)) { + if (false !== stripos($agent, 'MSIE')) { + $browser = 'msie'; + } + // if msie + if (('win' === $os) && ('msie' === $browser)) { + // if multibyte + if (function_exists('mb_convert_encoding')) { + $str = mb_convert_encoding($str, 'SJIS', 'EUC-JP'); + $str = rawurlencode($str); + } + } + + return $str; + } + + /** + * @param string $title + * @param bool $checkperm + * + * @return ItemForm + */ + public function getForm($title = 'default', $checkperm = true) + { +// require_once $GLOBALS['xoops']->path('modules/' . PUBLISHER_DIRNAME . '/class/form/item.php'); + $form = new Publisher\Form\ItemForm($title, 'form', xoops_getenv('PHP_SELF'), 'post', true); + $form->setCheckPermissions($checkperm); + $form->createElements($this); + + return $form; + } + + /** + * Checks if a user has access to a selected item. if no item permissions are + * set, access permission is denied. The user needs to have necessary category + * permission as well. + * Also, the item needs to be Published + * + * @return boolean : TRUE if the no errors occured + */ + public function accessGranted() + { + if (Publisher\Utility::userIsAdmin()) { + return true; + } + if ($this->status() != Constants::PUBLISHER_STATUS_PUBLISHED) { + return false; + } + // Do we have access to the parent category + if ($this->helper->getHandler('permission')->isGranted('category_read', $this->categoryid())) { + return true; + } + + return false; + } + + /** + * The name says it all + */ + public function setVarsFromRequest() + { + //Required fields + // if (!empty($categoryid = Request::getInt('categoryid', 0, 'POST'))) { + // $this->setVar('categoryid', $categoryid);} + + $this->setVar('categoryid', Request::getInt('categoryid', 0, 'POST')); + $this->setVar('title', Request::getString('title', '', 'POST')); + $this->setVar('body', Request::getText('body', '', 'POST')); + + //Not required fields + $this->setVar('summary', Request::getText('summary', '', 'POST')); + $this->setVar('subtitle', Request::getString('subtitle', '', 'POST')); + $this->setVar('item_tag', Request::getString('item_tag', '', 'POST')); + + if (false !== ($imageFeatured = Request::getString('image_featured', '', 'POST'))) { + $imageItem = Request::getArray('image_item', [], 'POST'); + // $imageFeatured = Request::getString('image_featured', '', 'POST'); + //Todo: get a better image class for xoops! + //Image hack + $imageItemIds = []; + + $sql = 'SELECT image_id, image_name FROM ' . $GLOBALS['xoopsDB']->prefix('image'); + $result = $GLOBALS['xoopsDB']->query($sql, 0, 0); + while (false !== ($myrow = $GLOBALS['xoopsDB']->fetchArray($result))) { + $imageName = $myrow['image_name']; + $id = $myrow['image_id']; + if ($imageName == $imageFeatured) { + $this->setVar('image', $id); + } + if (in_array($imageName, $imageItem)) { + $imageItemIds[] = $id; + } + } + $this->setVar('images', implode('|', $imageItemIds)); + } else { + $this->setVar('image', 0); + $this->setVar('images', ''); + } + + if (false !== ($authorAlias = Request::getString('author_alias', '', 'POST'))) { + $this->setVar('author_alias', $authorAlias); + if ('' !== $this->getVar('author_alias')) { + $this->setVar('uid', 0); + } + } + + //mb TODO check on version + //check if date is set and convert it to GMT date + // if (($datesub = Request::getString('datesub', '', 'POST'))) { + if ('' !== Request::getString('datesub', '', 'POST')) { + // if (version_compare(PHP_VERSION, '5.4.0') >= 0) { + // $this->setVar('datesub', strtotime(Request::getArray('datesub', array(), 'POST')['date']) + Request::getArray('datesub', array(), 'POST')['time']); + // } else { + $resDate = Request::getArray('datesub', [], 'POST'); + $resTime = Request::getArray('datesub', [], 'POST'); + // $this->setVar('datesub', strtotime($resDate['date']) + $resTime['time']); + $localTimestamp = strtotime($resDate['date']) + $resTime['time']; + + // get user Timezone offset and use it to find out the Timezone, needed for PHP DataTime + $userTimeoffset = $GLOBALS['xoopsUser']->getVar('timezone_offset'); + $tz = timezone_name_from_abbr(null, $userTimeoffset * 3600); + if (false === $tz) { + $tz = timezone_name_from_abbr(null, $userTimeoffset * 3600, false); + } + + $userTimezone = new \DateTimeZone($tz); + $gmtTimezone = new \DateTimeZone('GMT'); + $myDateTime = new \DateTime('now', $gmtTimezone); + $offset = $userTimezone->getOffset($myDateTime); + + $gmtTimestamp = $localTimestamp - $offset; + $this->setVar('datesub', $gmtTimestamp); + + // } + } elseif ($this->isNew()) { + $this->setVar('datesub', time()); + } + + $this->setVar('short_url', Request::getString('item_short_url', '', 'POST')); + $this->setVar('meta_keywords', Request::getString('item_meta_keywords', '', 'POST')); + $this->setVar('meta_description', Request::getString('item_meta_description', '', 'POST')); + $this->setVar('weight', Request::getInt('weight', 0, 'POST')); + + if ($this->isNew()) { + $this->setVar('uid', is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->uid() : 0); + $this->setVar('cancoment', $this->helper->getConfig('submit_allowcomments')); + $this->setVar('status', $this->helper->getConfig('submit_status')); + $this->setVar('dohtml', $this->helper->getConfig('submit_dohtml')); + $this->setVar('dosmiley', $this->helper->getConfig('submit_dosmiley')); + $this->setVar('doxcode', $this->helper->getConfig('submit_doxcode')); + $this->setVar('doimage', $this->helper->getConfig('submit_doimage')); + $this->setVar('dobr', $this->helper->getConfig('submit_dobr')); + } else { + $this->setVar('uid', Request::getInt('uid', 0, 'POST')); + $this->setVar('cancomment', Request::getInt('allowcomments', 1, 'POST')); + $this->setVar('status', Request::getInt('status', 1, 'POST')); + $this->setVar('dohtml', Request::getInt('dohtml', 1, 'POST')); + $this->setVar('dosmiley', Request::getInt('dosmiley', 1, 'POST')); + $this->setVar('doxcode', Request::getInt('doxcode', 1, 'POST')); + $this->setVar('doimage', Request::getInt('doimage', 1, 'POST')); + $this->setVar('dobr', Request::getInt('dolinebreak', 1, 'POST')); + } + + $this->setVar('notifypub', Request::getString('notify', '', 'POST')); + } +} diff --git a/class/ItemHandler.php b/class/ItemHandler.php new file mode 100644 index 00000000..4a76fa79 --- /dev/null +++ b/class/ItemHandler.php @@ -0,0 +1,847 @@ + + * @author The SmartFactory + */ + +use Xmf\Request; +use XoopsModules\Publisher; +use XoopsModules\Publisher\Constants; + +//namespace Publisher; + +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); +require_once __DIR__ . '/../include/common.php'; + + +/** + * Items handler class. + * This class is responsible for providing data access mechanisms to the data source + * of Q&A class objects. + * + * @author marcan + * @package Publisher + */ +class ItemHandler extends \XoopsPersistableObjectHandler +{ + /** + * @var Publisher + * @access public + */ + public $helper; + + protected $resultCatCounts = []; + + /** + * @param null|\XoopsDatabase $db + */ + public function __construct(\XoopsDatabase $db) + { + parent::__construct($db, 'publisher_items', Item::class, 'itemid', 'title'); + $this->helper = Publisher\Helper::getInstance(); + } + + /** + * @param bool $isNew + * + * @return XoopsObject + */ + public function create($isNew = true) + { + $obj = parent::create($isNew); + if ($isNew) { + $obj->setDefaultPermissions(); + } + + return $obj; + } + + /** + * retrieve an item + * + * @param int $id itemid of the user + * + * @param null $fields + * @return mixed reference to the Item object, FALSE if failed + * object, FALSE if failed + */ + public function get($id = null, $fields = null) + { + $obj = parent::get($id); + if (is_object($obj)) { + $obj->assignOtherProperties(); + } + + return $obj; + } + + /** + * insert a new item in the database + * + * @param XoopsObject $item reference to the {@link Item} object + * @param bool $force + * + * @return bool FALSE if failed, TRUE if already present and unchanged or successful + */ + public function insert(\XoopsObject $item, $force = false) //insert(&$item, $force = false) + { + if (!$item->meta_keywords() || !$item->meta_description() || !$item->short_url()) { + $publisherMetagen = new Publisher\Metagen($item->getTitle(), $item->getVar('meta_keywords'), $item->getVar('summary')); + // Auto create meta tags if empty + if (!$item->meta_keywords()) { + $item->setVar('meta_keywords', $publisherMetagen->keywords); + } + if (!$item->meta_description()) { + $item->setVar('meta_description', $publisherMetagen->description); + } + // Auto create short_url if empty + if (!$item->short_url()) { + $item->setVar('short_url', substr(Metagen::generateSeoTitle($item->getVar('title', 'n'), false), 0, 254)); + } + } + if (!parent::insert($item, $force)) { + return false; + } + if (xoops_isActiveModule('tag')) { + // Storing tags information + $tagHandler = \XoopsModules\Tag\Helper::getInstance()->getHandler('Tag'); // xoops_getModuleHandler('tag', 'tag'); + $tagHandler->updateByItem($item->getVar('item_tag'), $item->getVar('itemid'), PUBLISHER_DIRNAME, 0); + } + + return true; + } + + /** + * delete an item from the database + * + * @param XoopsObject $item reference to the ITEM to delete + * @param bool $force + * + * @return bool FALSE if failed. + */ + public function delete(\XoopsObject $item, $force = false) + { + // Deleting the files + if (!$this->helper->getHandler('file')->deleteItemFiles($item)) { + $item->setErrors(_AM_PUBLISHER_FILE_DELETE_ERROR); + } + if (!parent::delete($item, $force)) { + $item->setErrors(_AM_PUBLISHER_ITEM_DELETE_ERROR); + + return false; + } + // Removing tags information + if (xoops_isActiveModule('tag')) { + $tagHandler = \XoopsModules\Tag\Helper::getInstance()->getHandler('Tag'); // xoops_getModuleHandler('tag', 'tag'); + $tagHandler->updateByItem('', $item->getVar('itemid'), PUBLISHER_DIRNAME, 0); + } + + return true; + } + + /** + * retrieve items from the database + * + * @param CriteriaElement $criteria {@link CriteriaElement} conditions to be met + * @param bool|string $idKey what shall we use as array key ? none, itemid, categoryid + * @param bool $as_object + * @param string $notNullFields + * @return array array of Item objects + * objects + */ + + public function &getObjects (\CriteriaElement $criteria = null, $idKey = 'none', $as_object = true, $notNullFields = null) + { + $limit = $start = 0; + $ret = []; + $notNullFields = (null !== $notNullFields) ?: ''; + + $sql = 'SELECT * FROM ' . $this->db->prefix($this->helper->getDirname() . '_items'); + if (isset($criteria) && is_subclass_of($criteria, 'CriteriaElement')) { + $whereClause = $criteria->renderWhere(); + if ('WHERE ()' !== $whereClause) { + $sql .= ' ' . $criteria->renderWhere(); + if (!empty($notNullFields)) { + $sql .= $this->notNullFieldClause($notNullFields, true); + } + } elseif (!empty($notNullFields)) { + $sql .= ' WHERE ' . $this->notNullFieldClause($notNullFields); + } + if ('' != $criteria->getSort()) { + $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder(); + } + $limit = $criteria->getLimit(); + $start = $criteria->getStart(); + } elseif (!empty($notNullFields)) { + $sql .= $sql .= ' WHERE ' . $this->notNullFieldClause($notNullFields); + } + $result = $this->db->query($sql, $limit, $start); + if (!$result || 0 === $GLOBALS['xoopsDB']->getRowsNum($result)) { + return $ret; + } + $theObjects = []; + while (false !== ($myrow = $this->db->fetchArray($result))) { + $item = new Item(); + $item->assignVars($myrow); + $theObjects[$myrow['itemid']] = $item; + unset($item); + } + foreach ($theObjects as $theObject) { + if ('none' === $idKey) { + $ret[] = $theObject; + } elseif ('itemid' === $idKey) { + $ret[$theObject->itemid()] = $theObject; + } else { + $ret[$theObject->getVar($idKey)][$theObject->itemid()] = $theObject; + } + unset($theObject); + } + + return $ret; + } + + /** + * count items matching a condition + * + * @param CriteriaElement $criteria {@link CriteriaElement} to match + * @param string $notNullFields + * + * @return int count of items + */ + public function getCount (\CriteriaElement $criteria = null, $notNullFields = '') + { + $sql = 'SELECT COUNT(*) FROM ' . $this->db->prefix($this->helper->getDirname() . '_items'); + if (isset($criteria) && is_subclass_of($criteria, 'CriteriaElement')) { + $whereClause = $criteria->renderWhere(); + if ('WHERE ()' !== $whereClause) { + $sql .= ' ' . $criteria->renderWhere(); + if (!empty($notNullFields)) { + $sql .= $this->notNullFieldClause($notNullFields, true); + } + } elseif (!empty($notNullFields)) { + $sql .= ' WHERE ' . $this->notNullFieldClause($notNullFields); + } + } elseif (!empty($notNullFields)) { + $sql .= ' WHERE ' . $this->notNullFieldClause($notNullFields); + } + $result = $this->db->query($sql); + if (!$result) { + return 0; + } + list($count) = $this->db->fetchRow($result); + + return $count; + } + + /** + * @param int $categoryid + * @param string|array $status + * @param string $notNullFields + * @param $criteriaPermissions + * @return CriteriaCompo + */ + private function getItemsCriteria($categoryid = -1, $status = '', $notNullFields = '', $criteriaPermissions) + { + // global $publisherIsAdmin; + // $ret = 0; + // if (!$publisherIsAdmin) { + // $criteriaPermissions = new \CriteriaCompo(); + // // Categories for which user has access + // $categoriesGranted = $this->helper->getHandler('permission')->getGrantedItems('category_read'); + // if (!empty($categoriesGranted)) { + // $grantedCategories = new \Criteria('categoryid', "(" . implode(',', $categoriesGranted) . ")", 'IN'); + // $criteriaPermissions->add($grantedCategories, 'AND'); + // } else { + // return $ret; + // } + // } + if (isset($categoryid) && $categoryid != -1) { + $criteriaCategory = new \Criteria('categoryid', $categoryid); + } + $criteriaStatus = new \CriteriaCompo(); + if (!empty($status) && is_array($status)) { + foreach ($status as $v) { + $criteriaStatus->add(new \Criteria('status', $v), 'OR'); + } + } elseif (!empty($status) && $status != -1) { + $criteriaStatus->add(new \Criteria('status', $status), 'OR'); + } + $criteria = new \CriteriaCompo(); + if (!empty($criteriaCategory)) { + $criteria->add($criteriaCategory); + } + if (!empty($criteriaPermissions)) { + $criteria->add($criteriaPermissions); + } + if (!empty($criteriaStatus)) { + $criteria->add($criteriaStatus); + } + + return $criteria; + } + + /** + * @param $categoryid + * @param string $status + * @param string $notNullFields + * + * @return int + */ + public function getItemsCount($categoryid = -1, $status = '', $notNullFields = '') + { + + // global $publisherIsAdmin; + $criteriaPermissions = ''; + if (!$GLOBALS['publisherIsAdmin']) { + $criteriaPermissions = new \CriteriaCompo(); + // Categories for which user has access + $categoriesGranted = $this->helper->getHandler('permission')->getGrantedItems('category_read'); + if (!empty($categoriesGranted)) { + $grantedCategories = new \Criteria('categoryid', '(' . implode(',', $categoriesGranted) . ')', 'IN'); + $criteriaPermissions->add($grantedCategories, 'AND'); + } else { + return 0; + } + } + // $ret = array(); + $criteria = $this->getItemsCriteria($categoryid, $status, $notNullFields, $criteriaPermissions); + /* + if (isset($categoryid) && $categoryid != -1) { + $criteriaCategory = new \Criteria('categoryid', $categoryid); + } + $criteriaStatus = new \CriteriaCompo(); + if (!empty($status) && is_array($status)) { + foreach ($status as $v) { + $criteriaStatus->add(new \Criteria('status', $v), 'OR'); + } + } elseif (!empty($status) && $status != -1) { + $criteriaStatus->add(new \Criteria('status', $status), 'OR'); + } + $criteria = new \CriteriaCompo(); + if (!empty($criteriaCategory)) { + $criteria->add($criteriaCategory); + } + if (!empty($criteriaPermissions)) { + $criteria->add($criteriaPermissions); + } + if (!empty($criteriaStatus)) { + $criteria->add($criteriaStatus); + } + */ + $ret = $this->getCount($criteria, $notNullFields); + + return $ret; + } + + /** + * @param int $limit + * @param int $start + * @param int $categoryid + * @param string $sort + * @param string $order + * @param string $notNullFields + * @param bool $asObject + * @param string $idKey + * + * @return array + */ + public function getAllPublished($limit = 0, $start = 0, $categoryid = -1, $sort = 'datesub', $order = 'DESC', $notNullFields = '', $asObject = true, $idKey = 'none') + { + $otherCriteria = new \Criteria('datesub', time(), '<='); + + return $this->getItems($limit, $start, [Constants::PUBLISHER_STATUS_PUBLISHED], $categoryid, $sort, $order, $notNullFields, $asObject, $otherCriteria, $idKey); + } + + /** + * @param Item $obj + * + * @return bool + */ + public function getPreviousPublished($obj) + { + $ret = false; + $otherCriteria = new \CriteriaCompo(); + $otherCriteria->add(new \Criteria('datesub', $obj->getVar('datesub'), '<')); + $objs = $this->getItems(1, 0, [Constants::PUBLISHER_STATUS_PUBLISHED], $obj->getVar('categoryid'), 'datesub', 'DESC', '', true, $otherCriteria, 'none'); + if (count($objs) > 0) { + $ret = $objs[0]; + } + + return $ret; + } + + /** + * @param Item $obj + * + * @return bool + */ + public function getNextPublished($obj) + { + $ret = false; + $otherCriteria = new \CriteriaCompo(); + $otherCriteria->add(new \Criteria('datesub', $obj->getVar('datesub'), '>')); + $otherCriteria->add(new \Criteria('datesub', time(), '<=')); + $objs = $this->getItems(1, 0, [Constants::PUBLISHER_STATUS_PUBLISHED], $obj->getVar('categoryid'), 'datesub', 'ASC', '', true, $otherCriteria, 'none'); + if (count($objs) > 0) { + $ret = $objs[0]; + } + + return $ret; + } + + /** + * @param int $limit + * @param int $start + * @param int $categoryid + * @param string $sort + * @param string $order + * @param string $notNullFields + * @param bool $asObject + * @param string $idKey + * + * @return array + */ + public function getAllSubmitted($limit = 0, $start = 0, $categoryid = -1, $sort = 'datesub', $order = 'DESC', $notNullFields = '', $asObject = true, $idKey = 'none') + { + return $this->getItems($limit, $start, [Constants::PUBLISHER_STATUS_SUBMITTED], $categoryid, $sort, $order, $notNullFields, $asObject, null, $idKey); + } + + /** + * @param int $limit + * @param int $start + * @param int $categoryid + * @param string $sort + * @param string $order + * @param string $notNullFields + * @param bool $asObject + * @param string $idKey + * + * @return array + */ + public function getAllOffline($limit = 0, $start = 0, $categoryid = -1, $sort = 'datesub', $order = 'DESC', $notNullFields = '', $asObject = true, $idKey = 'none') + { + return $this->getItems($limit, $start, [Constants::PUBLISHER_STATUS_OFFLINE], $categoryid, $sort, $order, $notNullFields, $asObject, null, $idKey); + } + + /** + * @param int $limit + * @param int $start + * @param int $categoryid + * @param string $sort + * @param string $order + * @param string $notNullFields + * @param bool $asObject + * @param string $idKey + * + * @return array + */ + public function getAllRejected($limit = 0, $start = 0, $categoryid = -1, $sort = 'datesub', $order = 'DESC', $notNullFields = '', $asObject = true, $idKey = 'none') + { + return $this->getItems($limit, $start, [Constants::PUBLISHER_STATUS_REJECTED], $categoryid, $sort, $order, $notNullFields, $asObject, null, $idKey); + } + + /** + * @param int $limit + * @param int $start + * @param string $status + * @param int $categoryid + * @param string $sort + * @param string $order + * @param string $notNullFields + * @param bool $asObject + * @param null $otherCriteria + * @param string $idKey + * @return array + * @internal param bool $asObject + */ + public function getItems($limit = 0, $start = 0, $status = '', $categoryid = -1, $sort = 'datesub', $order = 'DESC', $notNullFields = '', $asObject = true, $otherCriteria = null, $idKey = 'none') + { + // global $publisherIsAdmin; + $criteriaPermissions = ''; + if (!$GLOBALS['publisherIsAdmin']) { + $criteriaPermissions = new \CriteriaCompo(); + // Categories for which user has access + $categoriesGranted = $this->helper->getHandler('permission')->getGrantedItems('category_read'); + if (!empty($categoriesGranted)) { + $grantedCategories = new \Criteria('categoryid', '(' . implode(',', $categoriesGranted) . ')', 'IN'); + $criteriaPermissions->add($grantedCategories, 'AND'); + } else { + return []; + } + } + + $criteria = $this->getItemsCriteria($categoryid, $status, $notNullFields, $criteriaPermissions); + /* + if (isset($categoryid) && $categoryid != -1) { + $criteriaCategory = new \Criteria('categoryid', $categoryid); + } + $criteriaStatus = new \CriteriaCompo(); + if (!empty($status) && is_array($status)) { + foreach ($status as $v) { + $criteriaStatus->add(new \Criteria('status', $v), 'OR'); + } + } elseif (!empty($status) && $status != -1) { + $criteriaStatus->add(new \Criteria('status', $status), 'OR'); + } + $criteria = new \CriteriaCompo(); + if (!empty($criteriaCategory)) { + $criteria->add($criteriaCategory); + } + if (!empty($criteriaPermissions)) { + $criteria->add($criteriaPermissions); + } + if (!empty($criteriaStatus)) { + $criteria->add($criteriaStatus); + } + */ + // $ret = array(); + + if (!empty($otherCriteria)) { + $criteria->add($otherCriteria); + } + $criteria->setLimit($limit); + $criteria->setStart($start); + $criteria->setSort($sort); + $criteria->setOrder($order); + $ret =& $this->getObjects($criteria, $idKey, $notNullFields); + + return $ret; + } + + /** + * @param string $field + * @param string $status + * @param int $categoryId + * + * @return bool + */ + public function getRandomItem($field = '', $status = '', $categoryId = -1) + { + $ret = false; + $notNullFields = $field; + // Getting the number of published Items + $totalItems = $this->getItemsCount($categoryId, $status, $notNullFields); + if ($totalItems > 0) { + --$totalItems; + mt_srand((double)microtime() * 1000000); + $entryNumber = mt_rand(0, $totalItems); + $item = $this->getItems(1, $entryNumber, $status, $categoryId, $sort = 'datesub', $order = 'DESC', $notNullFields); + if ($item) { + $ret = $item[0]; + } + } + + return $ret; + } + + /** + * delete Items matching a set of conditions + * + * @param CriteriaElement $criteria {@link CriteriaElement} + * + * @param bool $force + * @param bool $asObject + * @return bool FALSE if deletion failed + */ + public function deleteAll (\CriteriaElement $criteria = null, $force = true, $asObject = false) //deleteAll($criteria = null) + { + //todo resource consuming, use get list instead? + $items =& $this->getObjects($criteria); + foreach ($items as $item) { + $this->delete($item); + } + + return true; + } + + /** + * @param $itemid + * + * @return bool + */ + public function updateCounter($itemid) + { + $sql = 'UPDATE ' . $this->db->prefix($this->helper->getDirname() . '_items') . ' SET counter=counter+1 WHERE itemid = ' . $itemid; + if ($this->db->queryF($sql)) { + return true; + } else { + return false; + } + } + + /** + * @param string|array $notNullFields + * @param bool $withAnd + * + * @return string + */ + public function notNullFieldClause($notNullFields = '', $withAnd = false) + { + $ret = ''; + if ($withAnd) { + $ret .= ' AND '; + } + if (!empty($notNullFields) && is_array($notNullFields)) { + foreach ($notNullFields as $v) { + $ret .= " ($v IS NOT NULL AND $v <> ' ' )"; + } + } elseif (!empty($notNullFields)) { + $ret .= " ($notNullFields IS NOT NULL AND $notNullFields <> ' ' )"; + } + + return $ret; + } + + /** + * @param array $queryArray + * @param string $andor + * @param int $limit + * @param int $offset + * @param int $userid + * @param array $categories + * @param int $sortby + * @param string|array $searchin + * @param string $extra + * + * @return array + */ + public function getItemsFromSearch($queryArray = [], $andor = 'AND', $limit = 0, $offset = 0, $userid = 0, $categories = [], $sortby = 0, $searchin = '', $extra = '') + { + // global $publisherIsAdmin; + $ret = []; + /* @var $gpermHandler XoopsGroupPermHandler */ + $gpermHandler = xoops_getHandler('groupperm'); + $groups = is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getGroups() : XOOPS_GROUP_ANONYMOUS; + $searchin = empty($searchin) ? ['title', 'body', 'summary'] : (is_array($searchin) ? $searchin : [$searchin]); + if (in_array('all', $searchin) || 0 == count($searchin)) { + $searchin = ['title', 'subtitle', 'body', 'summary', 'meta_keywords']; + } + if (is_array($userid) && count($userid) > 0) { + $userid = array_map('intval', $userid); + $criteriaUser = new \CriteriaCompo(); + $criteriaUser->add(new \Criteria('uid', '(' . implode(',', $userid) . ')', 'IN'), 'OR'); + } elseif (is_numeric($userid) && $userid > 0) { + $criteriaUser = new \CriteriaCompo(); + $criteriaUser->add(new \Criteria('uid', $userid), 'OR'); + } + $count = 0; + if (is_array($queryArray)) { + $count = count($queryArray); + } + if (is_array($queryArray) && $count > 0) { + $criteriaKeywords = new \CriteriaCompo(); + $elementCount = count($queryArray); + for ($i = 0; $i < $elementCount; ++$i) { + $criteriaKeyword = new \CriteriaCompo(); + if (in_array('title', $searchin)) { + $criteriaKeyword->add(new \Criteria('title', '%' . $queryArray[$i] . '%', 'LIKE'), 'OR'); + } + if (in_array('subtitle', $searchin)) { + $criteriaKeyword->add(new \Criteria('subtitle', '%' . $queryArray[$i] . '%', 'LIKE'), 'OR'); + } + if (in_array('body', $searchin)) { + $criteriaKeyword->add(new \Criteria('body', '%' . $queryArray[$i] . '%', 'LIKE'), 'OR'); + } + if (in_array('summary', $searchin)) { + $criteriaKeyword->add(new \Criteria('summary', '%' . $queryArray[$i] . '%', 'LIKE'), 'OR'); + } + if (in_array('meta_keywords', $searchin)) { + $criteriaKeyword->add(new \Criteria('meta_keywords', '%' . $queryArray[$i] . '%', 'LIKE'), 'OR'); + } + $criteriaKeywords->add($criteriaKeyword, $andor); + unset($criteriaKeyword); + } + } + if (!$GLOBALS['publisherIsAdmin'] && (count($categories) > 0)) { + $criteriaPermissions = new \CriteriaCompo(); + // Categories for which user has access + $categoriesGranted = $gpermHandler->getItemIds('category_read', $groups, $this->helper->getModule()->getVar('mid')); + if (count($categories) > 0) { + $categoriesGranted = array_intersect($categoriesGranted, $categories); + } + if (0 == count($categoriesGranted)) { + return $ret; + } + $grantedCategories = new \Criteria('categoryid', '(' . implode(',', $categoriesGranted) . ')', 'IN'); + $criteriaPermissions->add($grantedCategories, 'AND'); + } elseif (count($categories) > 0) { + $criteriaPermissions = new \CriteriaCompo(); + $grantedCategories = new \Criteria('categoryid', '(' . implode(',', $categories) . ')', 'IN'); + $criteriaPermissions->add($grantedCategories, 'AND'); + } + $criteriaItemsStatus = new \CriteriaCompo(); + $criteriaItemsStatus->add(new \Criteria('status', Constants::PUBLISHER_STATUS_PUBLISHED)); + $criteria = new \CriteriaCompo(); + if (!empty($criteriaUser)) { + $criteria->add($criteriaUser, 'AND'); + } + if (!empty($criteriaKeywords)) { + $criteria->add($criteriaKeywords, 'AND'); + } + if (!empty($criteriaPermissions)) { + $criteria->add($criteriaPermissions); + } + if (!empty($criteriaItemsStatus)) { + $criteria->add($criteriaItemsStatus, 'AND'); + } + $criteria->setLimit($limit); + $criteria->setStart($offset); + if (empty($sortby)) { + $sortby = 'datesub'; + } + $criteria->setSort($sortby); + $order = 'ASC'; + if ('datesub' === $sortby) { + $order = 'DESC'; + } + $criteria->setOrder($order); + $ret =& $this->getObjects($criteria); + + return $ret; + } + + /** + * @param array $categoriesObj + * @param array $status + * + * @return array + */ + public function getLastPublishedByCat($categoriesObj, $status = [Constants::PUBLISHER_STATUS_PUBLISHED]) + { + $ret = []; + $catIds = []; + foreach ($categoriesObj as $parentid) { + foreach ($parentid as $category) { + $catId = $category->getVar('categoryid'); + $catIds[$catId] = $catId; + } + } + if (empty($catIds)) { + return $ret; + } + /*$cat = array(); + + $sql = "SELECT categoryid, MAX(datesub) as date FROM " . $this->db->prefix($this->helper->getDirname() . '_items') . " WHERE status IN (" . implode(',', $status) . ") GROUP BY categoryid"; + $result = $this->db->query($sql); + while ($row = $this->db->fetchArray($result)) { + $cat[$row['categoryid']] = $row['date']; + } + if (count($cat) == 0) return $ret; + $sql = "SELECT categoryid, itemid, title, short_url, uid, datesub FROM " . $this->db->prefix($this->helper->getDirname() . '_items'); + $criteriaBig = new \CriteriaCompo(); + foreach ($cat as $id => $date) { + $criteria = new \CriteriaCompo(new \Criteria('categoryid', $id)); + $criteria->add(new \Criteria('datesub', $date)); + $criteriaBig->add($criteria, 'OR'); + unset($criteria); + } + $sql .= " " . $criteriaBig->renderWhere(); + $result = $this->db->query($sql); + while ($row = $this->db->fetchArray($result)) { + $item = new Item(); + $item->assignVars($row); + $ret[$row['categoryid']] = $item; + unset($item); + } + */ + $sql = 'SELECT mi.categoryid, mi.itemid, mi.title, mi.short_url, mi.uid, mi.datesub'; + $sql .= ' FROM (SELECT categoryid, MAX(datesub) AS date FROM ' . $this->db->prefix($this->helper->getDirname() . '_items'); + $sql .= ' WHERE status IN (' . implode(',', $status) . ')'; + $sql .= ' AND categoryid IN (' . implode(',', $catIds) . ')'; + $sql .= ' GROUP BY categoryid)mo'; + $sql .= ' JOIN ' . $this->db->prefix($this->helper->getDirname() . '_items') . ' mi ON mi.datesub = mo.date'; + $result = $this->db->query($sql); + while (false !== ($row = $this->db->fetchArray($result))) { + $item = new Item(); + $item->assignVars($row); + $ret[$row['categoryid']] = $item; + unset($item); + } + + return $ret; + } + + /** + * @param $parentid + * @param $catsCount + * @param string $spaces + * @return int + */ + public function countArticlesByCat($parentid, $catsCount, $spaces = '') + { + // global $resultCatCounts; + $newspaces = $spaces . '--'; + $thecount = 0; + foreach ($catsCount[$parentid] as $subCatId => $count) { + $thecount += $count; + $this->resultCatCounts[$subCatId] = $count; + if (isset($catsCount[$subCatId])) { + $thecount += $this->countArticlesByCat($subCatId, $catsCount, $newspaces); + $this->resultCatCounts[$subCatId] = $thecount; + } + } + + return $thecount; + } + + /** + * @param int $catId + * @param array $status + * @param bool $inSubCat + * + * @return array + */ + public function getCountsByCat($catId = 0, $status, $inSubCat = false) + { + // global $resultCatCounts; + + $ret = []; + $catsCount = []; + $sql = 'SELECT c.parentid, i.categoryid, COUNT(*) AS count FROM ' . $this->db->prefix($this->helper->getDirname() . '_items') . ' AS i INNER JOIN ' . $this->db->prefix($this->helper->getDirname() . '_categories') . ' AS c ON i.categoryid=c.categoryid'; + if ((int)$catId > 0) { + $sql .= ' WHERE i.categoryid = ' . (int)$catId; + $sql .= ' AND i.status IN (' . implode(',', $status) . ')'; + } else { + $sql .= ' WHERE i.status IN (' . implode(',', $status) . ')'; + } + $sql .= ' GROUP BY i.categoryid ORDER BY c.parentid ASC, i.categoryid ASC'; + $result = $this->db->query($sql); + if (!$result) { + return $ret; + } + if (!$inSubCat) { + while (false !== ($row = $this->db->fetchArray($result))) { + $catsCount[$row['categoryid']] = $row['count']; + } + + return $catsCount; + } + // while ($row = $this->db->fetchArray($result)) { + while (false !== ($row = $this->db->fetchArray($result))) { + $catsCount[$row['parentid']][$row['categoryid']] = $row['count']; + } + // $resultCatCounts = array(); + foreach ($catsCount[0] as $subCatId => $count) { + $this->resultCatCounts[$subCatId] = $count; + if (isset($catsCount[$subCatId])) { + $this->resultCatCounts[$subCatId] += $this->countArticlesByCat($subCatId, $catsCount, ''); + } + } + + return $this->resultCatCounts; + } +} diff --git a/class/metagen.php b/class/Metagen.php similarity index 95% rename from class/metagen.php rename to class/Metagen.php index 38436459..a1510052 100644 --- a/class/metagen.php +++ b/class/Metagen.php @@ -1,4 +1,4 @@ -publisher = Publisher\Helper::getInstance(); + $this->helper = Publisher\Helper::getInstance(); $this->myts = \MyTextSanitizer::getInstance(); $this->setCategoryPath($categoryPath); $this->setTitle($title); @@ -97,7 +97,7 @@ public function setTitle($title) $this->title = $this->html2text($title); $this->originalTitle = $this->title; $titleTag = []; - $titleTag['module'] = $this->publisher->getModule()->getVar('name'); + $titleTag['module'] = $this->helper->getModule()->getVar('name'); if (isset($this->title) && ('' != $this->title) && (strtoupper($this->title) != strtoupper($titleTag['module']))) { $titleTag['title'] = $this->title; } @@ -210,7 +210,7 @@ public function findMetaKeywords($text, $minChar) public function createMetaKeywords() { $keywords = $this->findMetaKeywords($this->originalTitle . ' ' . $this->description, $this->minChar); - $moduleKeywords = $this->publisher->getConfig('seo_meta_keywords'); + $moduleKeywords = $this->helper->getConfig('seo_meta_keywords'); if ('' != $moduleKeywords) { $moduleKeywords = explode(',', $moduleKeywords); $keywords = array_merge($keywords, array_map('trim', $moduleKeywords)); @@ -337,7 +337,7 @@ public static function generateSeoTitle($title = '', $withExt = true) $repPat = ['-', 'e', 'e', 'e', 'e', 'c', 'a', 'a', 'a', 'i', 'i', 'u', 'u', 'u', 'o', 'o']; $title = str_replace($pattern, $repPat, $title); $tableau = explode('-', $title); // Transforms the string in table //Transforme la chaine de caractères en tableau - $tableau = array_filter($tableau, ['PublisherMetagen', 'emptyString']); // Remove empty strings of the table //Supprime les chaines vides du tableau + $tableau = array_filter($tableau, ['Metagen', 'emptyString']); // Remove empty strings of the table //Supprime les chaines vides du tableau $title = implode('-', $tableau); // Transforms a character string in table separated by a hyphen //Transforme un tableau en chaine de caractères séparé par un tiret if (count($title) > 0) { if ($withExt) { diff --git a/class/Mimetype.php b/class/Mimetype.php new file mode 100644 index 00000000..d72cd3dd --- /dev/null +++ b/class/Mimetype.php @@ -0,0 +1,57 @@ + + * @author The SmartFactory + */ + +use XoopsModules\Publisher; + +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); + +require_once __DIR__ . '/../include/common.php'; + + +/** + * Mimetype class + * + * @author Eric Juden + * @access public + * @package publisher + */ +class Mimetype extends \XoopsObject +{ + /** + * @param null|int|array $id + */ + public function __construct($id = null) + { + $this->initVar('mime_id', XOBJ_DTYPE_INT, null, false); + $this->initVar('mime_ext', XOBJ_DTYPE_TXTBOX, null, true, 60); + $this->initVar('mime_types', XOBJ_DTYPE_TXTAREA, null, false, 1024); + $this->initVar('mime_name', XOBJ_DTYPE_TXTBOX, null, true, 255); + $this->initVar('mime_admin', XOBJ_DTYPE_INT, null, false); + $this->initVar('mime_user', XOBJ_DTYPE_INT, null, false); + if (isset($id)) { + if (is_array($id)) { + $this->assignVars($id); + } + } else { + $this->setNew(); + } + } +} diff --git a/class/MimetypeHandler.php b/class/MimetypeHandler.php new file mode 100644 index 00000000..7109a420 --- /dev/null +++ b/class/MimetypeHandler.php @@ -0,0 +1,284 @@ + + * @author The SmartFactory + */ + +use XoopsModules\Publisher; + +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); + +require_once __DIR__ . '/../include/common.php'; + + +/** + * Class MimetypeHandler + */ +class MimetypeHandler extends BaseObjectHandler +{ + + /** + * Constructor + * + * @param null|\XoopsDatabase $db reference to a xoopsDB object + */ + public function __construct(\XoopsDatabase $db) + { + parent::init($db); + $this->className = Mimetype::class; + } + + /** + * retrieve a mimetype object from the database + * + * @param int $id ID of mimetype + * + * @param null $fields + * @return bool|Mimetype + * @access public + */ + public function get($id = null, $fields = null) + { + $id = (int)$id; + if ($id > 0) { + $sql = $this->selectQuery(new \Criteria('mime_id', $id)); + if (!$result = $this->db->query($sql)) { + return false; + } + $numrows = $this->db->getRowsNum($result); + if (1 == $numrows) { + $obj = new $this->className($this->db->fetchArray($result)); + + return $obj; + } + } + + return false; + } + + /** + * retrieve objects from the database + * + * @param CriteriaElement $criteria {@link CriteriaElement} + * conditions to be met + * + * @param bool $idAsKey + * @param bool $asObject + * @return array array of Mimetype objects + * objects + * @access public + */ + public function &getObjects (\CriteriaElement $criteria = null, $idAsKey = false, $asObject = true) //&getObjects($criteria = null) + { + $ret = []; + $limit = $start = 0; + $sql = $this->selectQuery($criteria); + if (isset($criteria)) { + $limit = $criteria->getLimit(); + $start = $criteria->getStart(); + } + //echo "
    $sql
    "; + $result = $this->db->query($sql, $limit, $start); + // if no records from db, return empty array + if (!$result) { + return $ret; + } + // Add each returned record to the result array + while (false !== ($myrow = $this->db->fetchArray($result))) { + $obj = new $this->className($myrow); + $ret[] = $obj; + unset($obj); + } + + return $ret; + } + + /** + * Format mime_types into array + * + * @param null $mimeExt + * + * @return array array of mime_types + */ + public function getArray($mimeExt = null) + { + // global $publisherIsAdmin; + $ret = []; + if ($GLOBALS['xoopsUser'] && !$GLOBALS['publisherIsAdmin']) { + // For user uploading + $crit = new \CriteriaCompo(new \Criteria('mime_user', 1)); //$sql = sprintf("SELECT * FROM %s WHERE mime_user=1", $GLOBALS['xoopsDB']->prefix($module->getVar('dirname', 'n') . '_mimetypes')); + } elseif ($GLOBALS['xoopsUser'] && $GLOBALS['publisherIsAdmin']) { + // For admin uploading + $crit = new \CriteriaCompo(new \Criteria('mime_admin', 1)); //$sql = sprintf("SELECT * FROM %s WHERE mime_admin=1", $GLOBALS['xoopsDB']->prefix($module->getVar('dirname', 'n') . '_mimetypes')); + } else { + return $ret; + } + if ($mimeExt) { + $crit->add(new \Criteria('mime_ext', $mimeExt)); + } + $result =& $this->getObjects($crit); + // if no records from db, return empty array + if (!$result) { + return $ret; + } + foreach ($result as $mime) { + $line = explode(' ', $mime->getVar('mime_types')); + foreach ($line as $row) { + $ret[] = ['type' => $row, 'ext' => $mime->getVar('mime_ext')]; + } + } + + return $ret; + } + + /** + * Checks to see if the user uploading the file has permissions to upload this mimetype + * + * @param string $postField file being uploaded + * + * @return bool false if no permission, return mimetype if has permission + * @access public + */ + public function checkMimeTypes($postField) + { + $ret = false; + $allowed_mimetypes = $this->getArrayByType(); + if (empty($allowed_mimetypes)) { + return $ret; + } + foreach ($allowed_mimetypes as $mime) { + if ($mime == $_FILES[$postField]['type']) { + $ret = $mime; + break; + } + } + + return $ret; + } + + /** + * @return array + */ + public function getArrayByType() + { + static $array = []; + if (empty($array)) { + $items = $this->getArray(); + foreach ($items as $item) { + $array[] = $item['type']; + } + } + + return $array; + } + + /** + * Create a "select" SQL query + * + * @param null|CriteriaElement $criteria {@link CriteriaElement} to match + * @param bool $join + * + * @return string string SQL query + * @access private + */ + private function selectQuery (\CriteriaElement $criteria = null, $join = false) + { + // if (!$join) { + // $sql = sprintf('SELECT * FROM %s', $this->db->prefix($this->dbtable)); + // } else { + // echo "no need for join..."; + // exit; + // } + + try { + if ($join) { + throw new RuntimeException('no need for join...'); + } + } catch (Exception $e) { + $helper = Publisher\Helper::getInstance(); + $helper->addLog($e); + echo 'no need for join...'; + } + + $sql = sprintf('SELECT * FROM %s', $this->db->prefix($this->dbtable)); + + if (isset($criteria) && is_subclass_of($criteria, 'CriteriaElement')) { + $sql .= ' ' . $criteria->renderWhere(); + if ('' != $criteria->getSort()) { + $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder(); + } + } + + return $sql; + } + + /** + * @param $obj + * + * @return bool|string + */ + protected function insertQuery($obj) + { + // Copy all object vars into local variables + foreach ($obj->cleanVars as $k => $v) { + ${$k} = $v; + } + $sql = sprintf( + 'INSERT INTO %s (mime_id, mime_ext, mime_types, mime_name, mime_admin, mime_user) VALUES + (%u, %s, %s, %s, %u, %u)', + $this->db->prefix($this->dbtable), + $obj->getVar('mime_id'), + $this->db->quoteString($obj->getVar('mime_ext')), + $this->db->quoteString($obj->getVar('mime_types')), + $this->db->quoteString($obj->getVar('mime_name')), + $obj->getVar('mime_admin'), + $obj->getVar('mime_user') + ); + + return $sql; + } + + /** + * @param $obj + * + * @return bool|string + */ + protected function updateQuery($obj) + { + // Copy all object vars into local variables + foreach ($obj->cleanVars as $k => $v) { + ${$k} = $v; + } + $sql = sprintf('UPDATE %s SET mime_ext = %s, mime_types = %s, mime_name = %s, mime_admin = %u, mime_user = %u WHERE + mime_id = %u', $this->db->prefix($this->dbtable), $this->db->quoteString($obj->getVar('mime_ext')), $this->db->quoteString($obj->getVar('mime_types')), $this->db->quoteString($obj->getVar('mime_name')), $obj->getVar('mime_admin'), $obj->getVar('mime_user'), $obj->getVar('mime_id')); + + return $sql; + } + + /** + * @param $obj + * + * @return bool|string + */ + protected function deleteQuery($obj) + { + $sql = sprintf('DELETE FROM %s WHERE mime_id = %u', $this->db->prefix($this->dbtable), $obj->getVar('mime_id')); + + return $sql; + } +} diff --git a/class/permission.php b/class/PermissionHandler.php similarity index 89% rename from class/permission.php rename to class/PermissionHandler.php index 8a50fece..f64999bc 100644 --- a/class/permission.php +++ b/class/PermissionHandler.php @@ -1,4 +1,4 @@ -publisher = Publisher\Helper::getInstance(); + $this->helper = Publisher\Helper::getInstance(); } /** @@ -60,7 +60,7 @@ public function getGrantedGroupsById($gpermName, $id) } $groups = []; $criteria = new \CriteriaCompo(); - $criteria->add(new \Criteria('gperm_modid', $this->publisher->getModule()->getVar('mid'))); + $criteria->add(new \Criteria('gperm_modid', $this->helper->getModule()->getVar('mid'))); $criteria->add(new \Criteria('gperm_name', $gpermName)); $criteria->add(new \Criteria('gperm_itemid', $id)); //Instead of calling groupperm handler and get objects, we will save some memory and do it our way @@ -98,7 +98,7 @@ public function getGrantedItems($gpermName) $ret = []; //Instead of calling groupperm handler and get objects, we will save some memory and do it our way $criteria = new \CriteriaCompo(new \Criteria('gperm_name', $gpermName)); - $criteria->add(new \Criteria('gperm_modid', $this->publisher->getModule()->getVar('mid'))); + $criteria->add(new \Criteria('gperm_modid', $this->helper->getModule()->getVar('mid'))); //Get user's groups $groups = is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getGroups() : [XOOPS_GROUP_ANONYMOUS]; @@ -151,7 +151,7 @@ public function isGranted($gpermName, $id) public function saveItemPermissions($groups, $itemId, $permName) { $result = true; - $moduleId = $this->publisher->getModule()->getVar('mid'); + $moduleId = $this->helper->getModule()->getVar('mid'); /* @var $gpermHandler XoopsGroupPermHandler */ $gpermHandler = xoops_getHandler('groupperm'); // First, if the permissions are already there, delete them @@ -180,7 +180,7 @@ public function deletePermissions($itemId, $gpermName) { $result = true; $gpermHandler = xoops_getHandler('groupperm'); - $gpermHandler->deleteByModule($this->publisher->getModule()->getVar('mid'), $gpermName, $itemId); + $gpermHandler->deleteByModule($this->helper->getModule()->getVar('mid'), $gpermName, $itemId); return $result; } diff --git a/class/rating.php b/class/Rating.php similarity index 69% rename from class/rating.php rename to class/Rating.php index 5b05844b..e4c91720 100644 --- a/class/rating.php +++ b/class/Rating.php @@ -1,4 +1,4 @@ - */ -// defined('XOOPS_ROOT_PATH') || exit('Restricted access.'); +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); -require_once dirname(__DIR__) . '/include/common.php'; +require_once __DIR__ . '/../include/common.php'; /** - * Class PublisherRating + * Class Rating */ -class PublisherRating extends XoopsObject +class Rating extends \XoopsObject { /** * constructor @@ -39,17 +39,3 @@ public function __construct() $this->initVar('date', XOBJ_DTYPE_INT, null, false); } } - -/** - * Class PublisherRatingHandler - */ -class PublisherRatingHandler extends XoopsPersistableObjectHandler -{ - /** - * @param null|XoopsDatabase $db - */ - public function __construct(\XoopsDatabase $db) - { - parent::__construct($db, 'publisher_rating', 'PublisherRating', 'ratingid', 'itemid'); - } -} diff --git a/class/RatingHandler.php b/class/RatingHandler.php new file mode 100644 index 00000000..8254b915 --- /dev/null +++ b/class/RatingHandler.php @@ -0,0 +1,36 @@ + + */ +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); + +require_once __DIR__ . '/../include/common.php'; + +/** + * Class RatingHandler + */ +class RatingHandler extends \XoopsPersistableObjectHandler +{ + /** + * @param null|\XoopsDatabase $db + */ + public function __construct(\XoopsDatabase $db) + { + parent::__construct($db, 'publisher_rating', Rating::class, 'ratingid', 'itemid'); + } +} diff --git a/include/seo_functions.php b/class/Seo.php similarity index 96% rename from include/seo_functions.php rename to class/Seo.php index be9ae2dd..00602063 100644 --- a/include/seo_functions.php +++ b/class/Seo.php @@ -1,4 +1,5 @@ - @@ -97,7 +97,7 @@ public function destroy() } /** - * @return PublisherSession + * @return Session */ public static function getInstance() { diff --git a/class/themetabform.php b/class/ThemeTabForm.php similarity index 97% rename from class/themetabform.php rename to class/ThemeTabForm.php index 17b0e4c0..ede5f987 100644 --- a/class/themetabform.php +++ b/class/ThemeTabForm.php @@ -1,4 +1,4 @@ - * @author John Neill */ -// defined('XOOPS_ROOT_PATH') || exit('Restricted access.'); +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); -require_once dirname(__DIR__) . '/include/common.php'; +require_once __DIR__ . '/../include/common.php'; /** * XoopsThemeTabForm @@ -30,7 +30,7 @@ * @copyright Copyright (c) 2009 * @access public */ -class PublisherThemeTabForm extends XoopsForm +class ThemeTabForm extends \XoopsForm { public $formTabs = []; @@ -281,7 +281,7 @@ public function getMethod() /** * Add an element to the form * - * @param string|XoopsFormElement $formElement reference to a {@link XoopsFormElement} + * @param string|\XoopsFormElement $formElement reference to a {@link XoopsFormElement} * @param bool $required is this a "required" element? */ public function addElement($formElement, $required = false) @@ -347,7 +347,7 @@ public function getElementNames() * * @param string $name "name" attribute assigned to a {@link XoopsFormElement} * - * @return bool|XoopsFormElement reference to a {@link XoopsFormElement}, false if not found + * @return bool|\XoopsFormElement reference to a {@link XoopsFormElement}, false if not found */ public function &getElementByName($name) { diff --git a/class/Utility.php b/class/Utility.php index 843a1acc..88993d88 100644 --- a/class/Utility.php +++ b/class/Utility.php @@ -22,18 +22,19 @@ use Xmf\Request; use XoopsModules\Publisher; -use XoopsModules\Publisher\commmon; +use XoopsModules\Publisher\Common; +use XoopsModules\Publisher\Constants; /** * Class Utility */ class Utility { - use common\VersionChecks; //checkVerXoops, checkVerPhp Traits + use Common\VersionChecks; //checkVerXoops, checkVerPhp Traits - use common\ServerStats; // getServerStats Trait + use Common\ServerStats; // getServerStats Trait - use common\FilesManagement; // Files Management Trait + use Common\FilesManagement; // Files Management Trait //--------------- Custom module methods ----------------------------- @@ -48,7 +49,7 @@ public static function createFolder($folder) { try { if (!file_exists($folder)) { - if (!mkdir($folder) && !is_dir($folder)) { + if (!is_dir($folder) && !mkdir($folder) && !is_dir($folder)) { throw new \RuntimeException(sprintf('Unable to create the %s directory', $folder)); } else { file_put_contents($folder . '/index.html', ''); @@ -176,10 +177,10 @@ public static function buildTableItemTitleRow() } /** - * @param \PublisherCategory $categoryObj + * @param Publisher\Category $categoryObj * @param int $level */ - public static function displayCategory(\PublisherCategory $categoryObj, $level = 0) + public static function displayCategory(Publisher\Category $categoryObj, $level = 0) { $helper = Publisher\Helper::getInstance(); @@ -203,7 +204,7 @@ public static function displayCategory(\PublisherCategory $categoryObj, $level = echo "
    '; echo ""; echo ''; - $subCategoriesObj = $helper->getHandler('category')->getCategories(0, 0, $categoryObj->categoryid()); + $subCategoriesObj = $helper->getHandler('Category')->getCategories(0, 0, $categoryObj->categoryid()); if (count($subCategoriesObj) > 0) { ++$level; foreach ($subCategoriesObj as $key => $thiscat) { @@ -225,17 +226,17 @@ public static function editCategory($showmenu = false, $categoryId = 0, $nbSubCa $helper = Publisher\Helper::getInstance(); // if there is a parameter, and the id exists, retrieve data: we're editing a category - /* @var $categoryObj PublisherCategory */ + /* @var $categoryObj Publisher\Category */ if (0 != $categoryId) { // Creating the category object for the selected category - $categoryObj = $helper->getHandler('category')->get($categoryId); + $categoryObj = $helper->getHandler('Category')->get($categoryId); if ($categoryObj->notLoaded()) { redirect_header('category.php', 1, _AM_PUBLISHER_NOCOLTOEDIT); // exit(); } } else { if (!$categoryObj) { - $categoryObj = $helper->getHandler('category')->create(); + $categoryObj = $helper->getHandler('Category')->create(); } } @@ -261,10 +262,10 @@ public static function editCategory($showmenu = false, $categoryId = 0, $nbSubCa static::openCollapsableBar('subcatstable', 'subcatsicon', _AM_PUBLISHER_SUBCAT_CAT, _AM_PUBLISHER_SUBCAT_CAT_DSC); // Get the total number of sub-categories - $categoriesObj = $helper->getHandler('category')->get($selCat); - $totalsubs = $helper->getHandler('category')->getCategoriesCount($selCat); + $categoriesObj = $helper->getHandler('Category')->get($selCat); + $totalsubs = $helper->getHandler('Category')->getCategoriesCount($selCat); // creating the categories objects that are published - $subcatsObj = $helper->getHandler('category')->getCategories(0, 0, $categoriesObj->categoryid()); + $subcatsObj = $helper->getHandler('Category')->getCategories(0, 0, $categoriesObj->categoryid()); $totalSCOnPage = count($subcatsObj); echo "
    " . $categoryObj->weight() . ' $modify $delete
    "; echo ''; @@ -297,11 +298,11 @@ public static function editCategory($showmenu = false, $categoryId = 0, $nbSubCa static::openCollapsableBar('bottomtable', 'bottomtableicon', _AM_PUBLISHER_CAT_ITEMS, _AM_PUBLISHER_CAT_ITEMS_DSC); $startitem = Request::getInt('startitem'); // Get the total number of published ITEMS - $totalitems = $helper->getHandler('item')->getItemsCount($selCat, [\PublisherConstants::PUBLISHER_STATUS_PUBLISHED]); + $totalitems = $helper->getHandler('Item')->getItemsCount($selCat, [Constants::PUBLISHER_STATUS_PUBLISHED]); // creating the items objects that are published - $itemsObj = $helper->getHandler('item')->getAllPublished($helper->getConfig('idxcat_perpage'), $startitem, $selCat); + $itemsObj = $helper->getHandler('Item')->getAllPublished($helper->getConfig('idxcat_perpage'), $startitem, $selCat); $totalitemsOnPage = count($itemsObj); - $allcats = $helper->getHandler('category')->getObjects(null, true); + $allcats = $helper->getHandler('Category')->getObjects(null, true); echo "
    "; echo ''; echo "'; @@ -729,7 +730,7 @@ public static function userIsAuthor($itemObj) public static function userIsModerator($itemObj) { $helper = Publisher\Helper::getInstance(); - $categoriesGranted = $helper->getHandler('permission')->getGrantedItems('category_moderation'); + $categoriesGranted = $helper->getHandler('Permission')->getGrantedItems('category_moderation'); return (is_object($itemObj) && in_array($itemObj->categoryid(), $categoriesGranted)); } @@ -884,13 +885,13 @@ public static function getCurrentPage() } /** - * @param null|\PublisherCategory $categoryObj + * @param null|Publisher\Category $categoryObj * @param int|array $selectedid * @param int $level * @param string $ret * @return string */ - public static function addCategoryOption(\PublisherCategory $categoryObj, $selectedid = 0, $level = 0, $ret = '') + public static function addCategoryOption(Publisher\Category $categoryObj, $selectedid = 0, $level = 0, $ret = '') { $helper = Publisher\Helper::getInstance(); @@ -907,7 +908,7 @@ public static function addCategoryOption(\PublisherCategory $categoryObj, $selec } $ret .= '>' . $spaces . $categoryObj->name() . "\n"; - $subCategoriesObj = $helper->getHandler('category')->getCategories(0, 0, $categoryObj->categoryid()); + $subCategoriesObj = $helper->getHandler('Category')->getCategories(0, 0, $categoryObj->categoryid()); if (count($subCategoriesObj) > 0) { ++$level; foreach ($subCategoriesObj as $catID => $subCategoryObj) { @@ -941,7 +942,7 @@ public static function createCategorySelect($selectedid = 0, $parentcategory = 0 } // Creating category objects - $categoriesObj = $helper->getHandler('category')->getCategories(0, 0, $parentcategory); + $categoriesObj = $helper->getHandler('Category')->getCategories(0, 0, $parentcategory); if (count($categoriesObj) > 0) { foreach ($categoriesObj as $catID => $categoryObj) { @@ -970,7 +971,7 @@ public static function createCategoryOptions($selectedid = 0, $parentcategory = } // Creating category objects - $categoriesObj = $helper->getHandler('category')->getCategories(0, 0, $parentcategory); + $categoriesObj = $helper->getHandler('Category')->getCategories(0, 0, $parentcategory); if (count($categoriesObj) > 0) { foreach ($categoriesObj as $catID => $categoryObj) { $ret .= static::addCategoryOption($categoryObj, $selectedid); @@ -1071,7 +1072,7 @@ public static function uploadFile($another = false, $withRedirect = true, &$item $itemId = Request::getInt('itemid', 0, 'POST'); $uid = is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->uid() : 0; - $session = PublisherSession::getInstance(); + $session = Session::getInstance(); $session->set('publisher_file_filename', Request::getString('item_file_name', '', 'POST')); $session->set('publisher_file_description', Request::getString('item_file_description', '', 'POST')); $session->set('publisher_file_status', Request::getInt('item_file_status', 1, 'POST')); @@ -1079,10 +1080,10 @@ public static function uploadFile($another = false, $withRedirect = true, &$item $session->set('publisher_file_itemid', $itemId); if (!is_object($itemObj)) { - $itemObj = $helper->getHandler('item')->get($itemId); + $itemObj = $helper->getHandler('Item')->get($itemId); } - $fileObj = $helper->getHandler('file')->create(); + $fileObj = $helper->getHandler('File')->create(); $fileObj->setVar('name', Request::getString('item_file_name', '', 'POST')); $fileObj->setVar('description', Request::getString('item_file_description', '', 'POST')); $fileObj->setVar('status', Request::getInt('item_file_status', 1, 'POST')); @@ -1091,7 +1092,7 @@ public static function uploadFile($another = false, $withRedirect = true, &$item $fileObj->setVar('datesub', time()); // Get available mimetypes for file uploading - $allowedMimetypes = $helper->getHandler('mimetype')->getArrayByType(); + $allowedMimetypes = $helper->getHandler('Mimetype')->getArrayByType(); // TODO : display the available mimetypes to the user $errors = []; if ($helper->getConfig('perm_upload') && is_uploaded_file($_FILES['item_upload_file']['tmp_name'])) { @@ -1233,7 +1234,7 @@ public static function ratingBar($itemId) $units = 5; $criteria = new \Criteria('itemid', $itemId); - $ratingObjs = $helper->getHandler('rating')->getObjects($criteria); + $ratingObjs = $helper->getHandler('Rating')->getObjects($criteria); unset($criteria); $uid = is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getVar('uid') : 0; @@ -1262,7 +1263,7 @@ public static function ratingBar($itemId) /* @var $gpermHandler XoopsGroupPermHandler */ $gpermHandler = $helper->getHandler('groupperm'); - if (!$gpermHandler->checkRight('global', \PublisherConstants::PUBLISHER_RATE, $groups, $helper->getModule()->getVar('mid'))) { + if (!$gpermHandler->checkRight('global', Constants::PUBLISHER_RATE, $groups, $helper->getModule()->getVar('mid'))) { $staticRater = []; $staticRater[] .= "\n" . '
    '; $staticRater[] .= '
    '; @@ -1426,4 +1427,109 @@ public static function checkVerPhp(\XoopsModule $module) return $success; } + + /** + * 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 + * + * @param string $text String to truncate. + * @param integer $length Length of returned string, including ellipsis. + * @param string $ending Ending to be appended to the trimmed string. + * @param boolean $exact If false, $text will not be cut mid-word + * @param boolean $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) + { + if ($considerHtml) { + // if the plain text is shorter than the maximum length, return the whole text + if (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 = strlen($ending); + $open_tags = []; + $truncate = ''; + foreach ($lines as $line_matchings) { + // if there is any html-tag in this line, handle it and add it (uncounted) to the output + if (!empty($line_matchings[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])) { + // 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); + if (false !== $pos) { + unset($open_tags[$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, strtolower($tag_matchings[1])); + } + // add html-tag to $truncate'd text + $truncate .= $line_matchings[1]; + } + // calculate the length of the plain text part of the line; handle entities as one character + $content_length = 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) { + // the number of characters which are left + $left = $length - $total_length; + $entities_length = 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)) { + // calculate the real length of all entities in the legal range + foreach ($entities[0] as $entity) { + if ($entity[1] + 1 - $entities_length <= $left) { + $left--; + $entities_length += strlen($entity[0]); + } else { + // no more characters left + break; + } + } + } + $truncate .= substr($line_matchings[2], 0, $left + $entities_length); + // maximum lenght is reached, so get off the loop + break; + } else { + $truncate .= $line_matchings[2]; + $total_length += $content_length; + } + // if the maximum length is reached, get off the loop + if ($total_length >= $length) { + break; + } + } + } else { + if (strlen($text) <= $length) { + return $text; + } else { + $truncate = substr($text, 0, $length - strlen($ending)); + } + } + // if the words shouldn't be cut in the middle... + if (!$exact) { + // ...search the last occurance of a space... + $spacepos = strrpos($truncate, ' '); + if (isset($spacepos)) { + // ...and cut the text in this position + $truncate = 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) { + $truncate .= ''; + } + } + + return $truncate; + } } diff --git a/class/category.php b/class/category.php deleted file mode 100644 index d179ebfa..00000000 --- a/class/category.php +++ /dev/null @@ -1,736 +0,0 @@ - - * @author The SmartFactory - */ - -use XoopsModules\Publisher; - -// defined('XOOPS_ROOT_PATH') || exit('Restricted access.'); - -require_once dirname(__DIR__) . '/include/common.php'; - -/** - * Class PublisherCategory - */ -class PublisherCategory extends XoopsObject -{ - /** - * @var Publisher - * @access public - */ - public $helper; - - /** - * @var array - */ - public $categoryPath = false; - - /** - * constructor - */ - public function __construct() - { - $this->publisher = Publisher\Helper::getInstance(); - $this->initVar('categoryid', XOBJ_DTYPE_INT, null, false); - $this->initVar('parentid', XOBJ_DTYPE_INT, null, false); - $this->initVar('name', XOBJ_DTYPE_TXTBOX, null, true, 100); - $this->initVar('description', XOBJ_DTYPE_TXTAREA, null, false, 255); - $this->initVar('image', XOBJ_DTYPE_TXTBOX, null, false, 255); - $this->initVar('total', XOBJ_DTYPE_INT, 1, false); - $this->initVar('weight', XOBJ_DTYPE_INT, 1, false); - $this->initVar('created', XOBJ_DTYPE_INT, null, false); - $this->initVar('template', XOBJ_DTYPE_TXTBOX, null, false, 255); - $this->initVar('header', XOBJ_DTYPE_TXTAREA, null, false); - $this->initVar('meta_keywords', XOBJ_DTYPE_TXTAREA, null, false); - $this->initVar('meta_description', XOBJ_DTYPE_TXTAREA, null, false); - $this->initVar('short_url', XOBJ_DTYPE_TXTBOX, null, false, 255); - $this->initVar('moderator', XOBJ_DTYPE_INT, null, false, 0); - //not persistent values - $this->initVar('itemcount', XOBJ_DTYPE_INT, 0, false); - $this->initVar('last_itemid', XOBJ_DTYPE_INT); - $this->initVar('last_title_link', XOBJ_DTYPE_TXTBOX); - $this->initVar('dohtml', XOBJ_DTYPE_INT, 1, false); - } - - /** - * @param string $method - * @param array $args - * - * @return mixed - */ - public function __call($method, $args) - { - $arg = isset($args[0]) ? $args[0] : null; - - return $this->getVar($method, $arg); - } - - /** - * @return bool - */ - public function notLoaded() - { - return ($this->getVar('categoryid') == -1); - } - - /** - * @return bool - */ - public function checkPermission() - { - // global $publisherIsAdmin; - $ret = false; - if ($GLOBALS['publisherIsAdmin']) { - return true; - } - if (is_object($GLOBALS['xoopsUser']) && $GLOBALS['xoopsUser']->getVar('uid') == $this->moderator()) { - return true; - } - $categoriesGranted = $this->publisher->getHandler('permission')->getGrantedItems('category_read'); - if (in_array($this->categoryid(), $categoriesGranted)) { - $ret = true; - } - - return $ret; - } - - /** - * @param string $format - * - * @return mixed|string - */ - public function getImage($format = 's') - { - if ('' != $this->getVar('image')) { - return $this->getVar('image', $format); - } else { - return 'blank.png'; - } - } - - /** - * @param string $format - * - * @return mixed - */ - public function template($format = 'n') - { - return $this->getVar('template', $format); - } - - /** - * @param bool $withAllLink - * - * @return array|bool|string - */ - public function getCategoryPath($withAllLink = true) - { - if (empty($this->categoryPath)) { - if ($withAllLink) { - $ret = $this->getCategoryLink(); - } else { - $ret = $this->name(); - } - $parentid = $this->parentid(); - if (0 != $parentid) { - $parentObj = $this->publisher->getHandler('category')->get($parentid); - // if ($parentObj->notLoaded()) { - // exit; - // } - - try { - if ($parentObj->notLoaded()) { - throw new RuntimeException(_NOPERM); - } - } catch (Exception $e) { - $this->publisher->addLog($e); - // redirect_header('javascript:history.go(-1)', 1, _NOPERM); - } - - $ret = $parentObj->getCategoryPath($withAllLink) . '
  • ' . $ret . '
  • '; - } - $this->categoryPath = $ret; - } - - return $this->categoryPath; - } - - /** - * @return mixed|string - */ - public function getCategoryPathForMetaTitle() - { - $ret = ''; - $parentid = $this->parentid(); - if (0 != $parentid) { - $parentObj = $this->publisher->getHandler('category')->get($parentid); - // if ($parentObj->notLoaded()) { - // exit('NOT LOADED'); - // } - - try { - if ($parentObj->notLoaded()) { - throw new RuntimeException('NOT LOADED'); - } - } catch (Exception $e) { - $this->publisher->addLog($e); - // redirect_header('javascript:history.go(-1)', 1, _NOPERM); - } - - $ret = $parentObj->getCategoryPath(false); - $ret = str_replace(' >', ' -', $ret); - } - - return $ret; - } - - /** - * @return array|null - */ - public function getGroupsRead() - { - return $this->publisher->getHandler('permission')->getGrantedGroupsById('category_read', $this->categoryid()); - } - - /** - * @return array|null - */ - public function getGroupsSubmit() - { - return $this->publisher->getHandler('permission')->getGrantedGroupsById('item_submit', $this->categoryid()); - } - - /** - * @return array|null - */ - public function getGroupsModeration() - { - return $this->publisher->getHandler('permission')->getGrantedGroupsById('category_moderation', $this->categoryid()); - } - - /** - * @return string - */ - public function getCategoryUrl() - { - return PublisherSeo::generateUrl('category', $this->categoryid(), $this->short_url()); - } - - /** - * @param bool $class - * - * @return string - */ - public function getCategoryLink($class = false) - { - if ($class) { - return "" . $this->name() . ''; - } else { - return "" . $this->name() . ''; - } - } - - /** - * @param bool $sendNotifications - * @param bool $force - * - * @return mixed - */ - public function store($sendNotifications = true, $force = true) - { - $ret = $this->publisher->getHandler('category')->insert($this, $force); - if ($sendNotifications && $ret && $this->isNew()) { - $this->sendNotifications(); - } - $this->unsetNew(); - - return $ret; - } - - /** - * Send notifications - */ - public function sendNotifications() - { - $tags = []; - $tags['MODULE_NAME'] = $this->publisher->getModule()->getVar('name'); - $tags['CATEGORY_NAME'] = $this->name(); - $tags['CATEGORY_URL'] = $this->getCategoryUrl(); - /* @var $notificationHandler XoopsNotificationHandler */ - $notificationHandler = xoops_getHandler('notification'); - $notificationHandler->triggerEvent('global_item', 0, 'category_created', $tags); - } - - /** - * @param array $category - * - * @return array - */ - public function toArraySimple($category = []) - { - $category['categoryid'] = $this->categoryid(); - $category['name'] = $this->name(); - $category['categorylink'] = $this->getCategoryLink(); - $category['categoryurl'] = $this->getCategoryUrl(); - $category['total'] = ($this->getVar('itemcount') > 0) ? $this->getVar('itemcount') : ''; - $category['description'] = $this->description(); - $category['header'] = $this->header(); - $category['meta_keywords'] = $this->meta_keywords(); - $category['meta_description'] = $this->meta_description(); - $category['short_url'] = $this->short_url(); - if ($this->getVar('last_itemid') > 0) { - $category['last_itemid'] = $this->getVar('last_itemid', 'n'); - $category['last_title_link'] = $this->getVar('last_title_link', 'n'); - } - if ('blank.png' !== $this->getImage()) { - $category['image_path'] = Publisher\Utility::getImageDir('category', false) . $this->getImage(); - } else { - $category['image_path'] = ''; - } - $category['lang_subcategories'] = sprintf(_CO_PUBLISHER_SUBCATEGORIES_INFO, $this->name()); - - return $category; - } - - /** - * @param array $category - * - * @return array - */ - public function toArrayTable($category = []) - { - $category['categoryid'] = $this->categoryid(); - $category['categorylink'] = $this->getCategoryLink(); - $category['total'] = ($this->getVar('itemcount') > 0) ? $this->getVar('itemcount') : ''; - $category['description'] = $this->description(); - if ($this->getVar('last_itemid') > 0) { - $category['last_itemid'] = $this->getVar('last_itemid', 'n'); - $category['last_title_link'] = $this->getVar('last_title_link', 'n'); - } - if ('blank.png' !== $this->getImage()) { - $category['image_path'] = Publisher\Utility::getImageDir('category', false) . $this->getImage(); - } else { - $category['image_path'] = ''; - } - $category['lang_subcategories'] = sprintf(_CO_PUBLISHER_SUBCATEGORIES_INFO, $this->name()); - - return $category; - } - - /** - * - */ - public function createMetaTags() - { - $publisherMetagen = new PublisherMetagen($this->name(), $this->meta_keywords(), $this->meta_description()); - $publisherMetagen->createMetaTags(); - } - - /** - * @param int $subCatsCount - * - * @return PublisherCategoryForm - */ - public function getForm($subCatsCount = 4) - { - require_once $GLOBALS['xoops']->path('modules/' . PUBLISHER_DIRNAME . '/class/form/category.php'); - $form = new PublisherCategoryForm($this, $subCatsCount); - - return $form; - } -} - -/** - * Categories handler class. - * This class is responsible for providing data access mechanisms to the data source - * of Category class objects. - * - * @author marcan - * @package Publisher - */ -class PublisherCategoryHandler extends XoopsPersistableObjectHandler -{ - /** - * @var Publisher - * @access public - */ - public $helper; - - /** - * @param null|XoopsDatabase $db - */ - public function __construct(\XoopsDatabase $db) - { - $this->publisher = Publisher\Helper::getInstance(); - parent::__construct($db, 'publisher_categories', 'PublisherCategory', 'categoryid', 'name'); - } - - /** - * retrieve an item - * - * @param int|null $id itemid of the user - * - * @param null $fields - * @return mixed reference to the PublisherCategory object, FALSE if failed - * object, FALSE if failed - */ - public function get($id = null, $fields = null) - { - static $cats; - if (isset($cats[$id])) { - return $cats[$id]; - } - $obj = parent::get($id); - $cats[$id] = $obj; - - return $obj; - } - - /** - * insert a new category in the database - * - * @param XoopsObject $category reference to the {@link PublisherCategory} - * @param bool $force - * @return bool FALSE if failed, TRUE if already present and unchanged or successful - */ - public function insert(\XoopsObject $category, $force = false) //insert(&$category, $force = false) - { - // Auto create meta tags if empty - if (!$category->meta_keywords() || !$category->meta_description()) { - $publisherMetagen = new PublisherMetagen($category->name(), $category->getVar('meta_keywords'), $category->getVar('description')); - if (!$category->meta_keywords()) { - $category->setVar('meta_keywords', $publisherMetagen->keywords); - } - if (!$category->meta_description()) { - $category->setVar('meta_description', $publisherMetagen->description); - } - } - // Auto create short_url if empty - if (!$category->short_url()) { - $category->setVar('short_url', PublisherMetagen::generateSeoTitle($category->name('n'), false)); - } - $ret = parent::insert($category, $force); - - return $ret; - } - - /** - * delete a category from the database - * - * @param XoopsObject $category reference to the category to delete - * @param bool $force - * - * @return bool FALSE if failed. - */ - public function delete(\XoopsObject $category, $force = false) //delete(&$category, $force = false) - { - // Deleting this category ITEMs - $criteria = new \Criteria('categoryid', $category->categoryid()); - $this->publisher->getHandler('item')->deleteAll($criteria); - unset($criteria); - // Deleting the sub categories - $subcats =& $this->getCategories(0, 0, $category->categoryid()); - foreach ($subcats as $subcat) { - $this->delete($subcat); - } - if (!parent::delete($category, $force)) { - $category->setErrors('An error while deleting.'); - - return false; - } - $moduleId = $this->publisher->getModule()->getVar('mid'); - xoops_groupperm_deletebymoditem($moduleId, 'category_read', $category->categoryid()); - xoops_groupperm_deletebymoditem($moduleId, 'item_submit', $category->categoryid()); - xoops_groupperm_deletebymoditem($moduleId, 'category_moderation', $category->categoryid()); - - return true; - } - - /** - * retrieve categories from the database - * - * @param CriteriaElement $criteria {@link CriteriaElement} conditions to be met - * @param bool $idAsKey use the categoryid as key for the array? - * - * @param bool $as_object - * @return array array of XoopsItem objects - */ - public function &getObjects(CriteriaElement $criteria = null, $idAsKey = false, $as_object = true) //&getObjects($criteria = null, $idAsKey = false) - { - $ret = []; - $theObjects = parent::getObjects($criteria, true); - foreach ($theObjects as $theObject) { - if (!$idAsKey) { - $ret[] = $theObject; - } else { - $ret[$theObject->categoryid()] = $theObject; - } - unset($theObject); - } - - return $ret; - } - - /** - * @param int $limit - * @param int $start - * @param int $parentid - * @param string $sort - * @param string $order - * @param bool $idAsKey - * - * @return array - */ - public function &getCategories($limit = 0, $start = 0, $parentid = 0, $sort = 'weight', $order = 'ASC', $idAsKey = true) - { - // global $publisherIsAdmin; - $criteria = new \CriteriaCompo(); - $criteria->setSort($sort); - $criteria->setOrder($order); - if ($parentid != -1) { - $criteria->add(new \Criteria('parentid', $parentid)); - } - if (!$GLOBALS['publisherIsAdmin']) { - $categoriesGranted = $this->publisher->getHandler('permission')->getGrantedItems('category_read'); - if (count($categoriesGranted) > 0) { - $criteria->add(new \Criteria('categoryid', '(' . implode(',', $categoriesGranted) . ')', 'IN')); - } else { - return []; - } - if (is_object($GLOBALS['xoopsUser'])) { - $criteria->add(new \Criteria('moderator', $GLOBALS['xoopsUser']->getVar('uid')), 'OR'); - } - } - $criteria->setStart($start); - $criteria->setLimit($limit); - $ret = $this->getObjects($criteria, $idAsKey); - - return $ret; - } - - /** - * @param $category - * @param $level - * @param $catArray - * @param $catResult - */ - public function getSubCatArray($category, $level, $catArray, $catResult) - { - global $theresult; - $spaces = ''; - for ($j = 0; $j < $level; ++$j) { - $spaces .= '--'; - } - $theresult[$category['categoryid']] = $spaces . $category['name']; - if (isset($catArray[$category['categoryid']])) { - ++$level; - foreach ($catArray[$category['categoryid']] as $parentid => $cat) { - $this->getSubCatArray($cat, $level, $catArray, $catResult); - } - } - } - - /** - * @return array - */ - public function &getCategoriesForSubmit() - { - global $publisherIsAdmin, $theresult; - $ret = []; - $criteria = new \CriteriaCompo(); - $criteria->setSort('name'); - $criteria->setOrder('ASC'); - if (!$publisherIsAdmin) { - $categoriesGranted = $this->publisher->getHandler('permission')->getGrantedItems('item_submit'); - if (count($categoriesGranted) > 0) { - $criteria->add(new \Criteria('categoryid', '(' . implode(',', $categoriesGranted) . ')', 'IN')); - } else { - return $ret; - } - if (is_object($GLOBALS['xoopsUser'])) { - $criteria->add(new \Criteria('moderator', $GLOBALS['xoopsUser']->getVar('uid')), 'OR'); - } - } - $categories = $this->getAll($criteria, ['categoryid', 'parentid', 'name'], false, false); - if (0 == count($categories)) { - return $ret; - } - $catArray = []; - foreach ($categories as $cat) { - $catArray[$cat['parentid']][$cat['categoryid']] = $cat; - } - // Needs to have permission on at least 1 top level category - if (!isset($catArray[0])) { - return $ret; - } - $catResult = []; - foreach ($catArray[0] as $thecat) { - $level = 0; - $this->getSubCatArray($thecat, $level, $catArray, $catResult); - } - - return $theresult; //this is a global - } - - /** - * @return array - */ - public function getCategoriesForSearch() - { - global $publisherIsAdmin, $theresult; - $ret = []; - $criteria = new \CriteriaCompo(); - $criteria->setSort('name'); - $criteria->setOrder('ASC'); - if (!$publisherIsAdmin) { - $categoriesGranted = $this->publisher->getHandler('permission')->getGrantedItems('category_read'); - if (count($categoriesGranted) > 0) { - $criteria->add(new \Criteria('categoryid', '(' . implode(',', $categoriesGranted) . ')', 'IN')); - } else { - return $ret; - } - if (is_object($GLOBALS['xoopsUser'])) { - $criteria->add(new \Criteria('moderator', $GLOBALS['xoopsUser']->getVar('uid')), 'OR'); - } - } - $categories = $this->getAll($criteria, ['categoryid', 'parentid', 'name'], false, false); - if (0 == count($categories)) { - return $ret; - } - $catArray = []; - foreach ($categories as $cat) { - $catArray[$cat['parentid']][$cat['categoryid']] = $cat; - } - // Needs to have permission on at least 1 top level category - if (!isset($catArray[0])) { - return $ret; - } - $catResult = []; - foreach ($catArray[0] as $thecat) { - $level = 0; - $this->getSubCatArray($thecat, $level, $catArray, $catResult); - } - - return $theresult; //this is a global - } - - /** - * @param int $parentid - * - * @return int - */ - public function getCategoriesCount($parentid = 0) - { - // global $publisherIsAdmin; - if ($parentid == -1) { - return $this->getCount(); - } - $criteria = new \CriteriaCompo(); - if (isset($parentid) && ($parentid != -1)) { - $criteria->add(new \Criteria('parentid', $parentid)); - if (!$GLOBALS['publisherIsAdmin']) { - $categoriesGranted = $this->publisher->getHandler('permission')->getGrantedItems('category_read'); - if (count($categoriesGranted) > 0) { - $criteria->add(new \Criteria('categoryid', '(' . implode(',', $categoriesGranted) . ')', 'IN')); - } else { - return 0; - } - if (is_object($GLOBALS['xoopsUser'])) { - $criteria->add(new \Criteria('moderator', $GLOBALS['xoopsUser']->getVar('uid')), 'OR'); - } - } - } - - return $this->getCount($criteria); - } - - /** - * Get all subcats and put them in an array indexed by parent id - * - * @param array $categories - * - * @return array - */ - public function getSubCats($categories) - { - // global $publisherIsAdmin; - $criteria = new \CriteriaCompo(new \Criteria('parentid', '(' . implode(',', array_keys($categories)) . ')', 'IN')); - $ret = []; - if (!$GLOBALS['publisherIsAdmin']) { - $categoriesGranted = $this->publisher->getHandler('permission')->getGrantedItems('category_read'); - if (count($categoriesGranted) > 0) { - $criteria->add(new \Criteria('categoryid', '(' . implode(',', $categoriesGranted) . ')', 'IN')); - } else { - return $ret; - } - - if (is_object($GLOBALS['xoopsUser'])) { - $criteria->add(new \Criteria('moderator', $GLOBALS['xoopsUser']->getVar('uid')), 'OR'); - } - } - $criteria->setSort('weight'); - $criteria->setOrder('ASC'); - $subcats = $this->getObjects($criteria, true); - foreach ($subcats as $subcat) { - $ret[$subcat->getVar('parentid')][$subcat->getVar('categoryid')] = $subcat; - } - - return $ret; - } - - /** - * delete categories matching a set of conditions - * - * @param CriteriaElement $criteria {@link CriteriaElement} - * - * @param bool $force - * @param bool $asObject - * @return bool FALSE if deletion failed - */ - public function deleteAll(CriteriaElement $criteria = null, $force = true, $asObject = false) //deleteAll($criteria = null) - { - $categories = $this->getObjects($criteria); - foreach ($categories as $category) { - if (!$this->delete($category)) { - return false; - } - } - - return true; - } - - /** - * @param int $catId - * - * @return mixed - */ - public function publishedItemsCount($catId = 0) - { - return $this->itemsCount($catId, $status = [PublisherConstants::PUBLISHER_STATUS_PUBLISHED]); - } - - /** - * @param int $catId - * @param string $status - * - * @return mixed - */ - public function itemsCount($catId = 0, $status = '') - { - return $this->publisher->getHandler('item')->getCountsByCat($catId, $status); - } -} diff --git a/class/item.php b/class/item.php deleted file mode 100644 index 52dd084a..00000000 --- a/class/item.php +++ /dev/null @@ -1,1905 +0,0 @@ - - * @author The SmartFactory - */ - -use Xmf\Request; -use XoopsModules\Publisher; - -//namespace Publisher; - -// defined('XOOPS_ROOT_PATH') || exit('Restricted access.'); -require_once dirname(__DIR__) . '/include/common.php'; - -/** - * Class PublisherItem - */ -class PublisherItem extends XoopsObject -{ - /** - * @var Publisher - * @access public - */ - public $helper; - public $groupsRead = []; - - /** - * @var PublisherCategory - * @access public - */ - public $category; - - /** - * @param int|null $id - */ - public function __construct($id = null) - { - $this->publisher = Publisher\Helper::getInstance(); - $this->db = \XoopsDatabaseFactory::getDatabaseConnection(); - $this->initVar('itemid', XOBJ_DTYPE_INT, 0); - $this->initVar('categoryid', XOBJ_DTYPE_INT, 0, false); - $this->initVar('title', XOBJ_DTYPE_TXTBOX, '', true, 255); - $this->initVar('subtitle', XOBJ_DTYPE_TXTBOX, '', false, 255); - $this->initVar('summary', XOBJ_DTYPE_TXTAREA, '', false); - $this->initVar('body', XOBJ_DTYPE_TXTAREA, '', false); - $this->initVar('uid', XOBJ_DTYPE_INT, 0, false); - $this->initVar('author_alias', XOBJ_DTYPE_TXTBOX, '', false, 255); - $this->initVar('datesub', XOBJ_DTYPE_INT, '', false); - $this->initVar('status', XOBJ_DTYPE_INT, -1, false); - $this->initVar('image', XOBJ_DTYPE_INT, 0, false); - $this->initVar('images', XOBJ_DTYPE_TXTBOX, '', false, 255); - $this->initVar('counter', XOBJ_DTYPE_INT, 0, false); - $this->initVar('rating', XOBJ_DTYPE_OTHER, 0, false); - $this->initVar('votes', XOBJ_DTYPE_INT, 0, false); - $this->initVar('weight', XOBJ_DTYPE_INT, 0, false); - $this->initVar('dohtml', XOBJ_DTYPE_INT, 1, true); - $this->initVar('dosmiley', XOBJ_DTYPE_INT, 1, true); - $this->initVar('doimage', XOBJ_DTYPE_INT, 1, true); - $this->initVar('dobr', XOBJ_DTYPE_INT, 1, false); - $this->initVar('doxcode', XOBJ_DTYPE_INT, 1, true); - $this->initVar('cancomment', XOBJ_DTYPE_INT, 1, true); - $this->initVar('comments', XOBJ_DTYPE_INT, 0, false); - $this->initVar('notifypub', XOBJ_DTYPE_INT, 1, false); - $this->initVar('meta_keywords', XOBJ_DTYPE_TXTAREA, '', false); - $this->initVar('meta_description', XOBJ_DTYPE_TXTAREA, '', false); - $this->initVar('short_url', XOBJ_DTYPE_TXTBOX, '', false, 255); - $this->initVar('item_tag', XOBJ_DTYPE_TXTAREA, '', false); - // Non consistent values - $this->initVar('pagescount', XOBJ_DTYPE_INT, 0, false); - if (isset($id)) { - $item = $this->publisher->getHandler('item')->get($id); - foreach ($item->vars as $k => $v) { - $this->assignVar($k, $v['value']); - } - } - } - - /** - * @param string $method - * @param array $args - * - * @return mixed - */ - public function __call($method, $args) - { - $arg = isset($args[0]) ? $args[0] : null; - - return $this->getVar($method, $arg); - } - - /** - * @return null|PublisherCategory - */ - public function getCategory() - { - if (!isset($this->category)) { - $this->category = $this->publisher->getHandler('category')->get($this->getVar('categoryid')); - } - - return $this->category; - } - - /** - * @param int $maxLength - * @param string $format - * - * @return mixed|string - */ - public function getTitle($maxLength = 0, $format = 'S') - { - $ret = $this->getVar('title', $format); - if (0 != $maxLength) { - if (!XOOPS_USE_MULTIBYTES) { - if (strlen($ret) >= $maxLength) { - $ret = Publisher\Utility::substr($ret, 0, $maxLength); - } - } - } - - return $ret; - } - - /** - * @param int $maxLength - * @param string $format - * - * @return mixed|string - */ - public function getSubtitle($maxLength = 0, $format = 'S') - { - $ret = $this->getVar('subtitle', $format); - if (0 != $maxLength) { - if (!XOOPS_USE_MULTIBYTES) { - if (strlen($ret) >= $maxLength) { - $ret = Publisher\Utility::substr($ret, 0, $maxLength); - } - } - } - - return $ret; - } - - /** - * @param int $maxLength - * @param string $format - * @param string $stripTags - * - * @return mixed|string - */ - public function getSummary($maxLength = 0, $format = 'S', $stripTags = '') - { - $ret = $this->getVar('summary', $format); - if (!empty($stripTags)) { - $ret = strip_tags($ret, $stripTags); - } - if (0 != $maxLength) { - if (!XOOPS_USE_MULTIBYTES) { - if (strlen($ret) >= $maxLength) { - //$ret = Publisher\Utility::substr($ret , 0, $maxLength); -// $ret = Publisher\Utility::truncateTagSafe($ret, $maxLength, $etc = '...', $breakWords = false); - $ret = Publisher\Utility::truncateTagSafe($ret, $maxLength, $etc = '...', $breakWords = false); - } - } - } - - return $ret; - } - - /** - * @param int $maxLength - * @param bool $fullSummary - * - * @return mixed|string - */ - public function getBlockSummary($maxLength = 0, $fullSummary = false) - { - if ($fullSummary) { - $ret = $this->getSummary(0, 's', '

    '); - } else { - $ret = $this->getSummary($maxLength, 's', '

    '); - } - //no summary? get body! - if ('' === $ret) { - $ret = $this->getBody($maxLength, 's', '

    '); - } - - return $ret; - } - - /** - * @param string $fileName - * - * @return string - */ - public function wrapPage($fileName) - { - $content = ''; - $page = Publisher\Utility::getUploadDir(true, 'content') . $fileName; - if (file_exists($page)) { - // this page uses smarty template - ob_start(); - include $page; - $content = ob_get_contents(); - ob_end_clean(); - // Cleaning the content - $bodyStartPos = strpos($content, ''); - if ($bodyStartPos) { - $bodyEndPos = strpos($content, '', $bodyStartPos); - $content = substr($content, $bodyStartPos + strlen(''), $bodyEndPos - strlen('') - $bodyStartPos); - } - // Check if ML Hack is installed, and if yes, parse the $content in formatForML - $myts = \MyTextSanitizer::getInstance(); - if (method_exists($myts, 'formatForML')) { - $content = $myts->formatForML($content); - } - } - - return $content; - } - - /** - * This method returns the body to be displayed. Not to be used for editing - * - * @param int $maxLength - * @param string $format - * @param string $stripTags - * - * @return mixed|string - */ - public function getBody($maxLength = 0, $format = 'S', $stripTags = '') - { - $ret = $this->getVar('body', $format); - $wrapPos = strpos($ret, '[pagewrap='); - if (!(false === $wrapPos)) { - $wrapPages = []; - $wrapCodeLength = strlen('[pagewrap='); - while (!(false === $wrapPos)) { - $endWrapPos = strpos($ret, ']', $wrapPos); - if ($endWrapPos) { - $wrap_page_name = substr($ret, $wrapPos + $wrapCodeLength, $endWrapPos - $wrapCodeLength - $wrapPos); - $wrapPages[] = $wrap_page_name; - } - $wrapPos = strpos($ret, '[pagewrap=', $endWrapPos - 1); - } - foreach ($wrapPages as $page) { - $wrapPageContent = $this->wrapPage($page); - $ret = str_replace("[pagewrap={$page}]", $wrapPageContent, $ret); - } - } - if ($this->publisher->getConfig('item_disp_blocks_summary')) { - $summary = $this->getSummary($maxLength, $format, $stripTags); - if ($summary) { - $ret = $this->getSummary() . '

    ' . $ret; - } - } - if (!empty($stripTags)) { - $ret = strip_tags($ret, $stripTags); - } - if (0 != $maxLength) { - if (!XOOPS_USE_MULTIBYTES) { - if (strlen($ret) >= $maxLength) { - //$ret = Publisher\Utility::substr($ret , 0, $maxLength); - $ret = Publisher\Utility::truncateTagSafe($ret, $maxLength, $etc = '...', $breakWords = false); - } - } - } - - return $ret; - } - - /** - * @param string $dateFormat - * @param string $format - * - * @return string - */ - public function getDatesub($dateFormat = '', $format = 'S') - { - if (empty($dateFormat)) { - $dateFormat = $this->publisher->getConfig('format_date'); - } - - return formatTimestamp($this->getVar('datesub', $format), $dateFormat); - } - - /** - * @param int $realName - * - * @return string - */ - public function posterName($realName = -1) - { - xoops_load('XoopsUserUtility'); - if ($realName == -1) { - $realName = $this->publisher->getConfig('format_realname'); - } - $ret = $this->author_alias(); - if ('' == $ret) { - $ret = \XoopsUserUtility::getUnameFromId($this->uid(), $realName); - } - - return $ret; - } - - /** - * @return string - */ - public function posterAvatar() - { - $ret = 'blank.gif'; - $memberHandler = xoops_getHandler('member'); - $thisUser = $memberHandler->getUser($this->uid()); - if (is_object($thisUser)) { - $ret = $thisUser->getVar('user_avatar'); - } - - return $ret; - } - - /** - * @return string - */ - public function getLinkedPosterName() - { - xoops_load('XoopsUserUtility'); - $ret = $this->author_alias(); - if ('' === $ret) { - $ret = \XoopsUserUtility::getUnameFromId($this->uid(), $this->publisher->getConfig('format_realname'), true); - } - - return $ret; - } - - /** - * @return mixed - */ - public function updateCounter() - { - return $this->publisher->getHandler('item')->updateCounter($this->itemid()); - } - - /** - * @param bool $force - * - * @return bool - */ - public function store($force = true) - { - $isNew = $this->isNew(); - if (!$this->publisher->getHandler('item')->insert($this, $force)) { - return false; - } - if ($isNew && $this->status() == PublisherConstants::PUBLISHER_STATUS_PUBLISHED) { - // Increment user posts - $userHandler = xoops_getHandler('user'); - $memberHandler = xoops_getHandler('member'); - $poster = $userHandler->get($this->uid()); - if (is_object($poster) && !$poster->isNew()) { - $poster->setVar('posts', $poster->getVar('posts') + 1); - if (!$memberHandler->insertUser($poster, true)) { - $this->setErrors('Article created but could not increment user posts.'); - - return false; - } - } - } - - return true; - } - - /** - * @return string - */ - public function getCategoryName() - { - return $this->getCategory()->name(); - } - - /** - * @return string - */ - public function getCategoryUrl() - { - return $this->getCategory()->getCategoryUrl(); - } - - /** - * @return string - */ - public function getCategoryLink() - { - return $this->getCategory()->getCategoryLink(); - } - - /** - * @param bool $withAllLink - * - * @return string - */ - public function getCategoryPath($withAllLink = true) - { - return $this->getCategory()->getCategoryPath($withAllLink); - } - - /** - * @return string - */ - public function getCategoryImagePath() - { - return Publisher\Utility::getImageDir('category', false) . $this->getCategory()->getImage(); - } - - /** - * @return mixed - */ - public function getFiles() - { - return $this->publisher->getHandler('file')->getAllFiles($this->itemid(), PublisherConstants::PUBLISHER_STATUS_FILE_ACTIVE); - } - - /** - * @return string - */ - public function getAdminLinks() - { - $adminLinks = ''; - if (is_object($GLOBALS['xoopsUser']) - && (Publisher\Utility::userIsAdmin() || Publisher\Utility::userIsAuthor($this) - || $this->publisher->getHandler('permission')->isGranted('item_submit', $this->categoryid()))) { - if (Publisher\Utility::userIsAdmin() || Publisher\Utility::userIsAuthor($this) || Publisher\Utility::userIsModerator($this)) { - if ($this->publisher->getConfig('perm_edit') || Publisher\Utility::userIsModerator($this) || Publisher\Utility::userIsAdmin()) { - // Edit button - $adminLinks .= "" . _CO_PUBLISHER_EDIT . ""; - $adminLinks .= ' '; - } - if ($this->publisher->getConfig('perm_delete') || Publisher\Utility::userIsModerator($this) || Publisher\Utility::userIsAdmin()) { - // Delete button - $adminLinks .= "itemid() . "'>" . _CO_PUBLISHER_DELETE . ""; - $adminLinks .= ' '; - } - } - if ($this->publisher->getConfig('perm_clone') || Publisher\Utility::userIsModerator($this) || Publisher\Utility::userIsAdmin()) { - // Duplicate button - $adminLinks .= "itemid() . "'>" . _CO_PUBLISHER_CLONE . ""; - $adminLinks .= ' '; - } - } - - // PDF button - if ($this->publisher->getConfig('display_pdf')) { - if (!is_file(XOOPS_ROOT_PATH . '/class/libraries/vendor/tecnickcom/tcpdf/tcpdf.php')) { - // if (is_object($GLOBALS['xoopsUser']) && Publisher\Utility::userIsAdmin()) { - // $GLOBALS['xoTheme']->addStylesheet('/modules/system/css/jquery.jgrowl.min.css'); - // $GLOBALS['xoTheme']->addScript('browse.php?Frameworks/jquery/plugins/jquery.jgrowl.js'); - // $adminLinks .= ''; - // } - } else { - $adminLinks .= "" . _CO_PUBLISHER_PDF . ""; - $adminLinks .= ' '; - } - } - - // Print button - $adminLinks .= "itemid(), $this->short_url()) . "' rel='nofollow' target='_blank'>" . _CO_PUBLISHER_PRINT . ""; - $adminLinks .= ' '; - // Email button - if (xoops_isActiveModule('tellafriend')) { - $subject = sprintf(_CO_PUBLISHER_INTITEMFOUND, $GLOBALS['xoopsConfig']['sitename']); - $subject = $this->convertForJapanese($subject); - $maillink = Publisher\Utility::tellAFriend($subject); - $adminLinks .= '' . _CO_PUBLISHER_MAIL . ''; - $adminLinks .= ' '; - } - - return $adminLinks; - } - - /** - * @param array $notifications - */ - public function sendNotifications($notifications = []) - { - $notificationHandler = xoops_getHandler('notification'); - $tags = []; - - $tags['MODULE_NAME'] = $this->publisher->getModule()->getVar('name'); - $tags['ITEM_NAME'] = $this->getTitle(); - $tags['ITEM_NAME'] = $this->subtitle(); - $tags['CATEGORY_NAME'] = $this->getCategoryName(); - $tags['CATEGORY_URL'] = PUBLISHER_URL . '/category.php?categoryid=' . $this->categoryid(); - $tags['ITEM_BODY'] = $this->body(); - $tags['DATESUB'] = $this->getDatesub(); - foreach ($notifications as $notification) { - switch ($notification) { - case PublisherConstants::PUBLISHER_NOTIFY_ITEM_PUBLISHED: - $tags['ITEM_URL'] = PUBLISHER_URL . '/item.php?itemid=' . $this->itemid(); - $notificationHandler->triggerEvent('global_item', 0, 'published', $tags, [], $this->publisher->getModule()->getVar('mid')); - $notificationHandler->triggerEvent('category_item', $this->categoryid(), 'published', $tags, [], $this->publisher->getModule()->getVar('mid')); - $notificationHandler->triggerEvent('item', $this->itemid(), 'approved', $tags, [], $this->publisher->getModule()->getVar('mid')); - break; - case PublisherConstants::PUBLISHER_NOTIFY_ITEM_SUBMITTED: - $tags['WAITINGFILES_URL'] = PUBLISHER_URL . '/admin/item.php?itemid=' . $this->itemid(); - $notificationHandler->triggerEvent('global_item', 0, 'submitted', $tags, [], $this->publisher->getModule()->getVar('mid')); - $notificationHandler->triggerEvent('category_item', $this->categoryid(), 'submitted', $tags, [], $this->publisher->getModule()->getVar('mid')); - break; - case PublisherConstants::PUBLISHER_NOTIFY_ITEM_REJECTED: - $notificationHandler->triggerEvent('item', $this->itemid(), 'rejected', $tags, [], $this->publisher->getModule()->getVar('mid')); - break; - case -1: - default: - break; - } - } - } - - /** - * Sets default permissions for this item - */ - public function setDefaultPermissions() - { - $memberHandler = xoops_getHandler('member'); - $groups = $memberHandler->getGroupList(); - $j = 0; - $groupIds = []; - foreach (array_keys($groups) as $i) { - $groupIds[$j] = $i; - ++$j; - } - $this->groupsRead = $groupIds; - } - - /** - * @todo look at this - * - * @param $groupIds - */ - public function setPermissions($groupIds) - { - if (!isset($groupIds)) { - $memberHandler = xoops_getHandler('member'); - $groups = $memberHandler->getGroupList(); - $j = 0; - $groupIds = []; - foreach (array_keys($groups) as $i) { - $groupIds[$j] = $i; - ++$j; - } - } - } - - /** - * @return bool - */ - public function notLoaded() - { - return $this->getVar('itemid') == -1; - } - - /** - * @return string - */ - public function getItemUrl() - { - return PublisherSeo::generateUrl('item', $this->itemid(), $this->short_url()); - } - - /** - * @param bool $class - * @param int $maxsize - * - * @return string - */ - public function getItemLink($class = false, $maxsize = 0) - { - if ($class) { - return '' . $this->getTitle($maxsize) . ''; - } else { - return '' . $this->getTitle($maxsize) . ''; - } - } - - /** - * @return string - */ - public function getWhoAndWhen() - { - $posterName = $this->getLinkedPosterName(); - $postdate = $this->getDatesub(); - - return sprintf(_CO_PUBLISHER_POSTEDBY, $posterName, $postdate); - } - - /** - * @return string - */ - public function getWho() - { - $posterName = $this->getLinkedPosterName(); - - return $posterName; - } - - /** - * @return string - */ - public function getWhen() - { - $postdate = $this->getDatesub(); - - return $postdate; - } - - /** - * @param null|string $body - * - * @return string - */ - public function plainMaintext($body = null) - { - $ret = ''; - if (!$body) { - $body = $this->body(); - } - $ret .= str_replace('[pagebreak]', '

    ', $body); - - return $ret; - } - - /** - * @param int $itemPageId - * @param null|string $body - * - * @return string - */ - public function buildMainText($itemPageId = -1, $body = null) - { - if (null === $body) { - $body = $this->body(); - } - $bodyParts = explode('[pagebreak]', $body); - $this->setVar('pagescount', count($bodyParts)); - if (count($bodyParts) <= 1) { - return $this->plainMaintext($body); - } - $ret = ''; - if ($itemPageId == -1) { - $ret .= trim($bodyParts[0]); - - return $ret; - } - if ($itemPageId >= count($bodyParts)) { - $itemPageId = count($bodyParts) - 1; - } - $ret .= trim($bodyParts[$itemPageId]); - - return $ret; - } - - /** - * @return mixed - */ - public function getImages() - { - static $ret; - $itemid = $this->getVar('itemid'); - if (!isset($ret[$itemid])) { - $ret[$itemid]['main'] = ''; - $ret[$itemid]['others'] = []; - $imagesIds = []; - $image = $this->getVar('image'); - $images = $this->getVar('images'); - if ('' != $images) { - $imagesIds = explode('|', $images); - } - if ($image > 0) { - $imagesIds = array_merge($imagesIds, [$image]); - } - $imageObjs = []; - if (count($imagesIds) > 0) { - $imageHandler = xoops_getHandler('image'); - $criteria = new \CriteriaCompo(new \Criteria('image_id', '(' . implode(',', $imagesIds) . ')', 'IN')); - $imageObjs = $imageHandler->getObjects($criteria, true); - unset($criteria); - } - foreach ($imageObjs as $id => $imageObj) { - if ($id == $image) { - $ret[$itemid]['main'] = $imageObj; - } else { - $ret[$itemid]['others'][] = $imageObj; - } - unset($imageObj); - } - unset($imageObjs); - } - - return $ret[$itemid]; - } - - /** - * @param string $display - * @param int $maxCharTitle - * @param int $maxCharSummary - * @param bool $fullSummary - * - * @return array - */ - public function toArraySimple($display = 'default', $maxCharTitle = 0, $maxCharSummary = 0, $fullSummary = false) - { - $itemPageId = -1; - if (is_numeric($display)) { - $itemPageId = $display; - $display = 'all'; - } - $item['itemid'] = $this->itemid(); - $item['uid'] = $this->uid(); - $item['itemurl'] = $this->getItemUrl(); - $item['titlelink'] = $this->getItemLink('titlelink', $maxCharTitle); - $item['subtitle'] = $this->subtitle(); - $item['datesub'] = $this->getDatesub(); - $item['counter'] = $this->counter(); - $item['who'] = $this->getWho(); - $item['when'] = $this->getWhen(); - $item['category'] = $this->getCategoryName(); - $item = $this->getMainImage($item); - switch ($display) { - case 'summary': - case 'list': - break; - case 'full': - case 'wfsection': - case 'default': - $summary = $this->getSummary($maxCharSummary); - if (!$summary) { - $summary = $this->getBody($maxCharSummary); - } - $item['summary'] = $summary; - $item = $this->toArrayFull($item); - break; - case 'all': - $item = $this->toArrayFull($item); - $item = $this->toArrayAll($item, $itemPageId); - break; - } - // Highlighting searched words - $highlight = true; - if ($highlight && Request::getString('keywords', '', 'GET')) { - $myts = \MyTextSanitizer::getInstance(); - $keywords = $myts->htmlSpecialChars(trim(urldecode(Request::getString('keywords', '', 'GET')))); - $fields = ['title', 'maintext', 'summary']; - foreach ($fields as $field) { - if (isset($item[$field])) { - $item[$field] = $this->highlight($item[$field], $keywords); - } - } - } - - return $item; - } - - /** - * @param array $item - * - * @return array - */ - public function toArrayFull($item) - { - $item['title'] = $this->getTitle(); - $item['clean_title'] = $this->getTitle(); - $item['itemurl'] = $this->getItemUrl(); - $item['cancomment'] = $this->cancomment(); - $item['comments'] = $this->comments(); - $item['adminlink'] = $this->getAdminLinks(); - $item['categoryPath'] = $this->getCategoryPath($this->publisher->getConfig('format_linked_path')); - $item['who_when'] = $this->getWhoAndWhen(); - $item['who'] = $this->getWho(); - $item['when'] = $this->getWhen(); - $item['category'] = $this->getCategoryName(); - $item = $this->getMainImage($item); - - return $item; - } - - /** - * @param array $item - * @param int $itemPageId - * - * @return array - */ - public function toArrayAll($item, $itemPageId) - { - $item['maintext'] = $this->buildMainText($itemPageId, $this->getBody()); - $item = $this->getOtherImages($item); - - return $item; - } - - /** - * @param array $item - * - * @return array - */ - public function getMainImage($item = []) - { - $images = $this->getImages(); - $item['image_path'] = ''; - $item['image_name'] = ''; - if (is_object($images['main'])) { - $dimensions = getimagesize($GLOBALS['xoops']->path('uploads/' . $images['main']->getVar('image_name'))); - $item['image_width'] = $dimensions[0]; - $item['image_height'] = $dimensions[1]; - $item['image_path'] = XOOPS_URL . '/uploads/' . $images['main']->getVar('image_name'); - // check to see if GD function exist - if (!function_exists('imagecreatetruecolor')) { - $item['image_thumb'] = XOOPS_URL . '/uploads/' . $images['main']->getVar('image_name'); - } else { - $item['image_thumb'] = PUBLISHER_URL . '/thumb.php?src=' . XOOPS_URL . '/uploads/' . $images['main']->getVar('image_name') . '&h=180'; - } - $item['image_name'] = $images['main']->getVar('image_nicename'); - } - - return $item; - } - - /** - * @param array $item - * - * @return array - */ - public function getOtherImages($item = []) - { - $images = $this->getImages(); - $item['images'] = []; - $i = 0; - foreach ($images['others'] as $image) { - $dimensions = getimagesize($GLOBALS['xoops']->path('uploads/' . $image->getVar('image_name'))); - $item['images'][$i]['width'] = $dimensions[0]; - $item['images'][$i]['height'] = $dimensions[1]; - $item['images'][$i]['path'] = XOOPS_URL . '/uploads/' . $image->getVar('image_name'); - // check to see if GD function exist - if (!function_exists('imagecreatetruecolor')) { - $item['images'][$i]['thumb'] = XOOPS_URL . '/uploads/' . $image->getVar('image_name'); - } else { - $item['images'][$i]['thumb'] = PUBLISHER_URL . '/thumb.php?src=' . XOOPS_URL . '/uploads/' . $image->getVar('image_name') . '&w=240'; - } - $item['images'][$i]['name'] = $image->getVar('image_nicename'); - ++$i; - } - - return $item; - } - - /** - * @param string $content - * @param string|array $keywords - * - * @return string Text - */ - public function highlight($content, $keywords) - { - $color = $this->publisher->getConfig('format_highlight_color'); - if (0 !== strpos($color, '#')) { - $color = '#' . $color; - } - require_once __DIR__ . '/highlighter.php'; - $highlighter = new PublisherHighlighter(); - $highlighter->setReplacementString('\1'); - - return $highlighter->highlight($content, $keywords); - } - - /** - * Create metada and assign it to template - */ - public function createMetaTags() - { - $publisherMetagen = new PublisherMetagen($this->getTitle(), $this->meta_keywords(), $this->meta_description(), $this->category->categoryPath); - $publisherMetagen->createMetaTags(); - } - - /** - * @param string $str - * - * @return string - */ - protected function convertForJapanese($str) - { - // no action, if not flag - if (!defined('_PUBLISHER_FLAG_JP_CONVERT')) { - return $str; - } - // no action, if not Japanese - if ('japanese' !== $GLOBALS['xoopsConfig']['language']) { - return $str; - } - // presume OS Browser - $agent = Request::getString('HTTP_USER_AGENT', '', 'SERVER'); - $os = ''; - $browser = ''; - // if (preg_match("/Win/i", $agent)) { - if (false !== stripos($agent, 'Win')) { - $os = 'win'; - } - // if (preg_match("/MSIE/i", $agent)) { - if (false !== stripos($agent, 'MSIE')) { - $browser = 'msie'; - } - // if msie - if (('win' === $os) && ('msie' === $browser)) { - // if multibyte - if (function_exists('mb_convert_encoding')) { - $str = mb_convert_encoding($str, 'SJIS', 'EUC-JP'); - $str = rawurlencode($str); - } - } - - return $str; - } - - /** - * @param string $title - * @param bool $checkperm - * - * @return PublisherItemForm - */ - public function getForm($title = 'default', $checkperm = true) - { - require_once $GLOBALS['xoops']->path('modules/' . PUBLISHER_DIRNAME . '/class/form/item.php'); - $form = new PublisherItemForm($title, 'form', xoops_getenv('PHP_SELF'), 'post', true); - $form->setCheckPermissions($checkperm); - $form->createElements($this); - - return $form; - } - - /** - * Checks if a user has access to a selected item. if no item permissions are - * set, access permission is denied. The user needs to have necessary category - * permission as well. - * Also, the item needs to be Published - * - * @return boolean : TRUE if the no errors occured - */ - public function accessGranted() - { - if (Publisher\Utility::userIsAdmin()) { - return true; - } - if ($this->status() != PublisherConstants::PUBLISHER_STATUS_PUBLISHED) { - return false; - } - // Do we have access to the parent category - if ($this->publisher->getHandler('permission')->isGranted('category_read', $this->categoryid())) { - return true; - } - - return false; - } - - /** - * The name says it all - */ - public function setVarsFromRequest() - { - //Required fields - // if (!empty($categoryid = Request::getInt('categoryid', 0, 'POST'))) { - // $this->setVar('categoryid', $categoryid);} - - $this->setVar('categoryid', Request::getInt('categoryid', 0, 'POST')); - $this->setVar('title', Request::getString('title', '', 'POST')); - $this->setVar('body', Request::getText('body', '', 'POST')); - - //Not required fields - $this->setVar('summary', Request::getText('summary', '', 'POST')); - $this->setVar('subtitle', Request::getString('subtitle', '', 'POST')); - $this->setVar('item_tag', Request::getString('item_tag', '', 'POST')); - - if (false !== ($imageFeatured = Request::getString('image_featured', '', 'POST'))) { - $imageItem = Request::getArray('image_item', [], 'POST'); - // $imageFeatured = Request::getString('image_featured', '', 'POST'); - //Todo: get a better image class for xoops! - //Image hack - $imageItemIds = []; - - $sql = 'SELECT image_id, image_name FROM ' . $GLOBALS['xoopsDB']->prefix('image'); - $result = $GLOBALS['xoopsDB']->query($sql, 0, 0); - while (false !== ($myrow = $GLOBALS['xoopsDB']->fetchArray($result))) { - $imageName = $myrow['image_name']; - $id = $myrow['image_id']; - if ($imageName == $imageFeatured) { - $this->setVar('image', $id); - } - if (in_array($imageName, $imageItem)) { - $imageItemIds[] = $id; - } - } - $this->setVar('images', implode('|', $imageItemIds)); - } else { - $this->setVar('image', 0); - $this->setVar('images', ''); - } - - if (false !== ($authorAlias = Request::getString('author_alias', '', 'POST'))) { - $this->setVar('author_alias', $authorAlias); - if ('' !== $this->getVar('author_alias')) { - $this->setVar('uid', 0); - } - } - - //mb TODO check on version - //check if date is set and convert it to GMT date - // if (($datesub = Request::getString('datesub', '', 'POST'))) { - if ('' !== Request::getString('datesub', '', 'POST')) { - // if (version_compare(PHP_VERSION, '5.4.0') >= 0) { - // $this->setVar('datesub', strtotime(Request::getArray('datesub', array(), 'POST')['date']) + Request::getArray('datesub', array(), 'POST')['time']); - // } else { - $resDate = Request::getArray('datesub', [], 'POST'); - $resTime = Request::getArray('datesub', [], 'POST'); - // $this->setVar('datesub', strtotime($resDate['date']) + $resTime['time']); - $localTimestamp = strtotime($resDate['date']) + $resTime['time']; - - // get user Timezone offset and use it to find out the Timezone, needed for PHP DataTime - $userTimeoffset = $GLOBALS['xoopsUser']->getVar('timezone_offset'); - $tz = timezone_name_from_abbr(null, $userTimeoffset * 3600); - if (false === $tz) { - $tz = timezone_name_from_abbr(null, $userTimeoffset * 3600, false); - } - - $userTimezone = new DateTimeZone($tz); - $gmtTimezone = new DateTimeZone('GMT'); - $myDateTime = new DateTime('now', $gmtTimezone); - $offset = $userTimezone->getOffset($myDateTime); - - $gmtTimestamp = $localTimestamp - $offset; - $this->setVar('datesub', $gmtTimestamp); - - // } - } elseif ($this->isNew()) { - $this->setVar('datesub', time()); - } - - $this->setVar('short_url', Request::getString('item_short_url', '', 'POST')); - $this->setVar('meta_keywords', Request::getString('item_meta_keywords', '', 'POST')); - $this->setVar('meta_description', Request::getString('item_meta_description', '', 'POST')); - $this->setVar('weight', Request::getInt('weight', 0, 'POST')); - - if ($this->isNew()) { - $this->setVar('uid', is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->uid() : 0); - $this->setVar('cancoment', $this->publisher->getConfig('submit_allowcomments')); - $this->setVar('status', $this->publisher->getConfig('submit_status')); - $this->setVar('dohtml', $this->publisher->getConfig('submit_dohtml')); - $this->setVar('dosmiley', $this->publisher->getConfig('submit_dosmiley')); - $this->setVar('doxcode', $this->publisher->getConfig('submit_doxcode')); - $this->setVar('doimage', $this->publisher->getConfig('submit_doimage')); - $this->setVar('dobr', $this->publisher->getConfig('submit_dobr')); - } else { - $this->setVar('uid', Request::getInt('uid', 0, 'POST')); - $this->setVar('cancomment', Request::getInt('allowcomments', 1, 'POST')); - $this->setVar('status', Request::getInt('status', 1, 'POST')); - $this->setVar('dohtml', Request::getInt('dohtml', 1, 'POST')); - $this->setVar('dosmiley', Request::getInt('dosmiley', 1, 'POST')); - $this->setVar('doxcode', Request::getInt('doxcode', 1, 'POST')); - $this->setVar('doimage', Request::getInt('doimage', 1, 'POST')); - $this->setVar('dobr', Request::getInt('dolinebreak', 1, 'POST')); - } - - $this->setVar('notifypub', Request::getString('notify', '', 'POST')); - } -} - -/** - * Items handler class. - * This class is responsible for providing data access mechanisms to the data source - * of Q&A class objects. - * - * @author marcan - * @package Publisher - */ -class PublisherItemHandler extends XoopsPersistableObjectHandler -{ - /** - * @var Publisher - * @access public - */ - public $helper; - - protected $resultCatCounts = []; - - /** - * @param null|XoopsDatabase $db - */ - public function __construct(\XoopsDatabase $db) - { - parent::__construct($db, 'publisher_items', 'PublisherItem', 'itemid', 'title'); - $this->publisher = Publisher\Helper::getInstance(); - } - - /** - * @param bool $isNew - * - * @return XoopsObject - */ - public function create($isNew = true) - { - $obj = parent::create($isNew); - if ($isNew) { - $obj->setDefaultPermissions(); - } - - return $obj; - } - - /** - * retrieve an item - * - * @param int $id itemid of the user - * - * @param null $fields - * @return mixed reference to the PublisherItem object, FALSE if failed - * object, FALSE if failed - */ - public function get($id = null, $fields = null) - { - $obj = parent::get($id); - if (is_object($obj)) { - $obj->assignOtherProperties(); - } - - return $obj; - } - - /** - * insert a new item in the database - * - * @param XoopsObject $item reference to the {@link PublisherItem} object - * @param bool $force - * - * @return bool FALSE if failed, TRUE if already present and unchanged or successful - */ - public function insert(\XoopsObject $item, $force = false) //insert(&$item, $force = false) - { - if (!$item->meta_keywords() || !$item->meta_description() || !$item->short_url()) { - $publisherMetagen = new PublisherMetagen($item->getTitle(), $item->getVar('meta_keywords'), $item->getVar('summary')); - // Auto create meta tags if empty - if (!$item->meta_keywords()) { - $item->setVar('meta_keywords', $publisherMetagen->keywords); - } - if (!$item->meta_description()) { - $item->setVar('meta_description', $publisherMetagen->description); - } - // Auto create short_url if empty - if (!$item->short_url()) { - $item->setVar('short_url', substr(PublisherMetagen::generateSeoTitle($item->getVar('title', 'n'), false), 0, 254)); - } - } - if (!parent::insert($item, $force)) { - return false; - } - if (xoops_isActiveModule('tag')) { - // Storing tags information - $tagHandler = xoops_getModuleHandler('tag', 'tag'); - $tagHandler->updateByItem($item->getVar('item_tag'), $item->getVar('itemid'), PUBLISHER_DIRNAME, 0); - } - - return true; - } - - /** - * delete an item from the database - * - * @param XoopsObject $item reference to the ITEM to delete - * @param bool $force - * - * @return bool FALSE if failed. - */ - public function delete(\XoopsObject $item, $force = false) - { - // Deleting the files - if (!$this->publisher->getHandler('file')->deleteItemFiles($item)) { - $item->setErrors(_AM_PUBLISHER_FILE_DELETE_ERROR); - } - if (!parent::delete($item, $force)) { - $item->setErrors(_AM_PUBLISHER_ITEM_DELETE_ERROR); - - return false; - } - // Removing tags information - if (xoops_isActiveModule('tag')) { - $tagHandler = xoops_getModuleHandler('tag', 'tag'); - $tagHandler->updateByItem('', $item->getVar('itemid'), PUBLISHER_DIRNAME, 0); - } - - return true; - } - - /** - * retrieve items from the database - * - * @param CriteriaElement $criteria {@link CriteriaElement} conditions to be met - * @param bool|string $idKey what shall we use as array key ? none, itemid, categoryid - * @param bool $as_object - * @param string $notNullFields - * @return array array of PublisherItem objects - * objects - */ - - public function &getObjects(CriteriaElement $criteria = null, $idKey = 'none', $as_object = true, $notNullFields = null) - { - $limit = $start = 0; - $ret = []; - $notNullFields = (null !== $notNullFields) ?: ''; - - $sql = 'SELECT * FROM ' . $this->db->prefix($this->publisher->getDirname() . '_items'); - if (isset($criteria) && is_subclass_of($criteria, 'CriteriaElement')) { - $whereClause = $criteria->renderWhere(); - if ('WHERE ()' !== $whereClause) { - $sql .= ' ' . $criteria->renderWhere(); - if (!empty($notNullFields)) { - $sql .= $this->notNullFieldClause($notNullFields, true); - } - } elseif (!empty($notNullFields)) { - $sql .= ' WHERE ' . $this->notNullFieldClause($notNullFields); - } - if ('' != $criteria->getSort()) { - $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder(); - } - $limit = $criteria->getLimit(); - $start = $criteria->getStart(); - } elseif (!empty($notNullFields)) { - $sql .= $sql .= ' WHERE ' . $this->notNullFieldClause($notNullFields); - } - $result = $this->db->query($sql, $limit, $start); - if (!$result || 0 === $GLOBALS['xoopsDB']->getRowsNum($result)) { - return $ret; - } - $theObjects = []; - while (false !== ($myrow = $this->db->fetchArray($result))) { - $item = new PublisherItem(); - $item->assignVars($myrow); - $theObjects[$myrow['itemid']] = $item; - unset($item); - } - foreach ($theObjects as $theObject) { - if ('none' === $idKey) { - $ret[] = $theObject; - } elseif ('itemid' === $idKey) { - $ret[$theObject->itemid()] = $theObject; - } else { - $ret[$theObject->getVar($idKey)][$theObject->itemid()] = $theObject; - } - unset($theObject); - } - - return $ret; - } - - /** - * count items matching a condition - * - * @param CriteriaElement $criteria {@link CriteriaElement} to match - * @param string $notNullFields - * - * @return int count of items - */ - public function getCount(CriteriaElement $criteria = null, $notNullFields = '') - { - $sql = 'SELECT COUNT(*) FROM ' . $this->db->prefix($this->publisher->getDirname() . '_items'); - if (isset($criteria) && is_subclass_of($criteria, 'CriteriaElement')) { - $whereClause = $criteria->renderWhere(); - if ('WHERE ()' !== $whereClause) { - $sql .= ' ' . $criteria->renderWhere(); - if (!empty($notNullFields)) { - $sql .= $this->notNullFieldClause($notNullFields, true); - } - } elseif (!empty($notNullFields)) { - $sql .= ' WHERE ' . $this->notNullFieldClause($notNullFields); - } - } elseif (!empty($notNullFields)) { - $sql .= ' WHERE ' . $this->notNullFieldClause($notNullFields); - } - $result = $this->db->query($sql); - if (!$result) { - return 0; - } - list($count) = $this->db->fetchRow($result); - - return $count; - } - - /** - * @param int $categoryid - * @param string|array $status - * @param string $notNullFields - * @param $criteriaPermissions - * @return CriteriaCompo - */ - private function getItemsCriteria($categoryid = -1, $status = '', $notNullFields = '', $criteriaPermissions) - { - // global $publisherIsAdmin; - // $ret = 0; - // if (!$publisherIsAdmin) { - // $criteriaPermissions = new \CriteriaCompo(); - // // Categories for which user has access - // $categoriesGranted = $this->publisher->getHandler('permission')->getGrantedItems('category_read'); - // if (!empty($categoriesGranted)) { - // $grantedCategories = new \Criteria('categoryid', "(" . implode(',', $categoriesGranted) . ")", 'IN'); - // $criteriaPermissions->add($grantedCategories, 'AND'); - // } else { - // return $ret; - // } - // } - if (isset($categoryid) && $categoryid != -1) { - $criteriaCategory = new \Criteria('categoryid', $categoryid); - } - $criteriaStatus = new \CriteriaCompo(); - if (!empty($status) && is_array($status)) { - foreach ($status as $v) { - $criteriaStatus->add(new \Criteria('status', $v), 'OR'); - } - } elseif (!empty($status) && $status != -1) { - $criteriaStatus->add(new \Criteria('status', $status), 'OR'); - } - $criteria = new \CriteriaCompo(); - if (!empty($criteriaCategory)) { - $criteria->add($criteriaCategory); - } - if (!empty($criteriaPermissions)) { - $criteria->add($criteriaPermissions); - } - if (!empty($criteriaStatus)) { - $criteria->add($criteriaStatus); - } - - return $criteria; - } - - /** - * @param $categoryid - * @param string $status - * @param string $notNullFields - * - * @return int - */ - public function getItemsCount($categoryid = -1, $status = '', $notNullFields = '') - { - - // global $publisherIsAdmin; - $criteriaPermissions = ''; - if (!$GLOBALS['publisherIsAdmin']) { - $criteriaPermissions = new \CriteriaCompo(); - // Categories for which user has access - $categoriesGranted = $this->publisher->getHandler('permission')->getGrantedItems('category_read'); - if (!empty($categoriesGranted)) { - $grantedCategories = new \Criteria('categoryid', '(' . implode(',', $categoriesGranted) . ')', 'IN'); - $criteriaPermissions->add($grantedCategories, 'AND'); - } else { - return 0; - } - } - // $ret = array(); - $criteria = $this->getItemsCriteria($categoryid, $status, $notNullFields, $criteriaPermissions); - /* - if (isset($categoryid) && $categoryid != -1) { - $criteriaCategory = new \Criteria('categoryid', $categoryid); - } - $criteriaStatus = new \CriteriaCompo(); - if (!empty($status) && is_array($status)) { - foreach ($status as $v) { - $criteriaStatus->add(new \Criteria('status', $v), 'OR'); - } - } elseif (!empty($status) && $status != -1) { - $criteriaStatus->add(new \Criteria('status', $status), 'OR'); - } - $criteria = new \CriteriaCompo(); - if (!empty($criteriaCategory)) { - $criteria->add($criteriaCategory); - } - if (!empty($criteriaPermissions)) { - $criteria->add($criteriaPermissions); - } - if (!empty($criteriaStatus)) { - $criteria->add($criteriaStatus); - } - */ - $ret = $this->getCount($criteria, $notNullFields); - - return $ret; - } - - /** - * @param int $limit - * @param int $start - * @param int $categoryid - * @param string $sort - * @param string $order - * @param string $notNullFields - * @param bool $asObject - * @param string $idKey - * - * @return array - */ - public function getAllPublished($limit = 0, $start = 0, $categoryid = -1, $sort = 'datesub', $order = 'DESC', $notNullFields = '', $asObject = true, $idKey = 'none') - { - $otherCriteria = new \Criteria('datesub', time(), '<='); - - return $this->getItems($limit, $start, [PublisherConstants::PUBLISHER_STATUS_PUBLISHED], $categoryid, $sort, $order, $notNullFields, $asObject, $otherCriteria, $idKey); - } - - /** - * @param PublisherItem $obj - * - * @return bool - */ - public function getPreviousPublished($obj) - { - $ret = false; - $otherCriteria = new \CriteriaCompo(); - $otherCriteria->add(new \Criteria('datesub', $obj->getVar('datesub'), '<')); - $objs = $this->getItems(1, 0, [PublisherConstants::PUBLISHER_STATUS_PUBLISHED], $obj->getVar('categoryid'), 'datesub', 'DESC', '', true, $otherCriteria, 'none'); - if (count($objs) > 0) { - $ret = $objs[0]; - } - - return $ret; - } - - /** - * @param PublisherItem $obj - * - * @return bool - */ - public function getNextPublished($obj) - { - $ret = false; - $otherCriteria = new \CriteriaCompo(); - $otherCriteria->add(new \Criteria('datesub', $obj->getVar('datesub'), '>')); - $otherCriteria->add(new \Criteria('datesub', time(), '<=')); - $objs = $this->getItems(1, 0, [PublisherConstants::PUBLISHER_STATUS_PUBLISHED], $obj->getVar('categoryid'), 'datesub', 'ASC', '', true, $otherCriteria, 'none'); - if (count($objs) > 0) { - $ret = $objs[0]; - } - - return $ret; - } - - /** - * @param int $limit - * @param int $start - * @param int $categoryid - * @param string $sort - * @param string $order - * @param string $notNullFields - * @param bool $asObject - * @param string $idKey - * - * @return array - */ - public function getAllSubmitted($limit = 0, $start = 0, $categoryid = -1, $sort = 'datesub', $order = 'DESC', $notNullFields = '', $asObject = true, $idKey = 'none') - { - return $this->getItems($limit, $start, [PublisherConstants::PUBLISHER_STATUS_SUBMITTED], $categoryid, $sort, $order, $notNullFields, $asObject, null, $idKey); - } - - /** - * @param int $limit - * @param int $start - * @param int $categoryid - * @param string $sort - * @param string $order - * @param string $notNullFields - * @param bool $asObject - * @param string $idKey - * - * @return array - */ - public function getAllOffline($limit = 0, $start = 0, $categoryid = -1, $sort = 'datesub', $order = 'DESC', $notNullFields = '', $asObject = true, $idKey = 'none') - { - return $this->getItems($limit, $start, [PublisherConstants::PUBLISHER_STATUS_OFFLINE], $categoryid, $sort, $order, $notNullFields, $asObject, null, $idKey); - } - - /** - * @param int $limit - * @param int $start - * @param int $categoryid - * @param string $sort - * @param string $order - * @param string $notNullFields - * @param bool $asObject - * @param string $idKey - * - * @return array - */ - public function getAllRejected($limit = 0, $start = 0, $categoryid = -1, $sort = 'datesub', $order = 'DESC', $notNullFields = '', $asObject = true, $idKey = 'none') - { - return $this->getItems($limit, $start, [PublisherConstants::PUBLISHER_STATUS_REJECTED], $categoryid, $sort, $order, $notNullFields, $asObject, null, $idKey); - } - - /** - * @param int $limit - * @param int $start - * @param string $status - * @param int $categoryid - * @param string $sort - * @param string $order - * @param string $notNullFields - * @param bool $asObject - * @param null $otherCriteria - * @param string $idKey - * @return array - * @internal param bool $asObject - */ - public function getItems($limit = 0, $start = 0, $status = '', $categoryid = -1, $sort = 'datesub', $order = 'DESC', $notNullFields = '', $asObject = true, $otherCriteria = null, $idKey = 'none') - { - // global $publisherIsAdmin; - $criteriaPermissions = ''; - if (!$GLOBALS['publisherIsAdmin']) { - $criteriaPermissions = new \CriteriaCompo(); - // Categories for which user has access - $categoriesGranted = $this->publisher->getHandler('permission')->getGrantedItems('category_read'); - if (!empty($categoriesGranted)) { - $grantedCategories = new \Criteria('categoryid', '(' . implode(',', $categoriesGranted) . ')', 'IN'); - $criteriaPermissions->add($grantedCategories, 'AND'); - } else { - return []; - } - } - - $criteria = $this->getItemsCriteria($categoryid, $status, $notNullFields, $criteriaPermissions); - /* - if (isset($categoryid) && $categoryid != -1) { - $criteriaCategory = new \Criteria('categoryid', $categoryid); - } - $criteriaStatus = new \CriteriaCompo(); - if (!empty($status) && is_array($status)) { - foreach ($status as $v) { - $criteriaStatus->add(new \Criteria('status', $v), 'OR'); - } - } elseif (!empty($status) && $status != -1) { - $criteriaStatus->add(new \Criteria('status', $status), 'OR'); - } - $criteria = new \CriteriaCompo(); - if (!empty($criteriaCategory)) { - $criteria->add($criteriaCategory); - } - if (!empty($criteriaPermissions)) { - $criteria->add($criteriaPermissions); - } - if (!empty($criteriaStatus)) { - $criteria->add($criteriaStatus); - } - */ - // $ret = array(); - - if (!empty($otherCriteria)) { - $criteria->add($otherCriteria); - } - $criteria->setLimit($limit); - $criteria->setStart($start); - $criteria->setSort($sort); - $criteria->setOrder($order); - $ret = $this->getObjects($criteria, $idKey, $notNullFields); - - return $ret; - } - - /** - * @param string $field - * @param string $status - * @param int $categoryId - * - * @return bool - */ - public function getRandomItem($field = '', $status = '', $categoryId = -1) - { - $ret = false; - $notNullFields = $field; - // Getting the number of published Items - $totalItems = $this->getItemsCount($categoryId, $status, $notNullFields); - if ($totalItems > 0) { - --$totalItems; - mt_srand((double)microtime() * 1000000); - $entryNumber = mt_rand(0, $totalItems); - $item = $this->getItems(1, $entryNumber, $status, $categoryId, $sort = 'datesub', $order = 'DESC', $notNullFields); - if ($item) { - $ret = $item[0]; - } - } - - return $ret; - } - - /** - * delete Items matching a set of conditions - * - * @param CriteriaElement $criteria {@link CriteriaElement} - * - * @param bool $force - * @param bool $asObject - * @return bool FALSE if deletion failed - */ - public function deleteAll(CriteriaElement $criteria = null, $force = true, $asObject = false) //deleteAll($criteria = null) - { - //todo resource consuming, use get list instead? - $items = $this->getObjects($criteria); - foreach ($items as $item) { - $this->delete($item); - } - - return true; - } - - /** - * @param $itemid - * - * @return bool - */ - public function updateCounter($itemid) - { - $sql = 'UPDATE ' . $this->db->prefix($this->publisher->getDirname() . '_items') . ' SET counter=counter+1 WHERE itemid = ' . $itemid; - if ($this->db->queryF($sql)) { - return true; - } else { - return false; - } - } - - /** - * @param string|array $notNullFields - * @param bool $withAnd - * - * @return string - */ - public function notNullFieldClause($notNullFields = '', $withAnd = false) - { - $ret = ''; - if ($withAnd) { - $ret .= ' AND '; - } - if (!empty($notNullFields) && is_array($notNullFields)) { - foreach ($notNullFields as $v) { - $ret .= " ($v IS NOT NULL AND $v <> ' ' )"; - } - } elseif (!empty($notNullFields)) { - $ret .= " ($notNullFields IS NOT NULL AND $notNullFields <> ' ' )"; - } - - return $ret; - } - - /** - * @param array $queryArray - * @param string $andor - * @param int $limit - * @param int $offset - * @param int $userid - * @param array $categories - * @param int $sortby - * @param string|array $searchin - * @param string $extra - * - * @return array - */ - public function getItemsFromSearch($queryArray = [], $andor = 'AND', $limit = 0, $offset = 0, $userid = 0, $categories = [], $sortby = 0, $searchin = '', $extra = '') - { - // global $publisherIsAdmin; - $ret = []; - /* @var $gpermHandler XoopsGroupPermHandler */ - $gpermHandler = xoops_getHandler('groupperm'); - $groups = is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getGroups() : XOOPS_GROUP_ANONYMOUS; - $searchin = empty($searchin) ? ['title', 'body', 'summary'] : (is_array($searchin) ? $searchin : [$searchin]); - if (in_array('all', $searchin) || 0 == count($searchin)) { - $searchin = ['title', 'subtitle', 'body', 'summary', 'meta_keywords']; - } - if (is_array($userid) && count($userid) > 0) { - $userid = array_map('intval', $userid); - $criteriaUser = new \CriteriaCompo(); - $criteriaUser->add(new \Criteria('uid', '(' . implode(',', $userid) . ')', 'IN'), 'OR'); - } elseif (is_numeric($userid) && $userid > 0) { - $criteriaUser = new \CriteriaCompo(); - $criteriaUser->add(new \Criteria('uid', $userid), 'OR'); - } - $count = 0; - if (is_array($queryArray)) { - $count = count($queryArray); - } - if (is_array($queryArray) && $count > 0) { - $criteriaKeywords = new \CriteriaCompo(); - $elementCount = count($queryArray); - for ($i = 0; $i < $elementCount; ++$i) { - $criteriaKeyword = new \CriteriaCompo(); - if (in_array('title', $searchin)) { - $criteriaKeyword->add(new \Criteria('title', '%' . $queryArray[$i] . '%', 'LIKE'), 'OR'); - } - if (in_array('subtitle', $searchin)) { - $criteriaKeyword->add(new \Criteria('subtitle', '%' . $queryArray[$i] . '%', 'LIKE'), 'OR'); - } - if (in_array('body', $searchin)) { - $criteriaKeyword->add(new \Criteria('body', '%' . $queryArray[$i] . '%', 'LIKE'), 'OR'); - } - if (in_array('summary', $searchin)) { - $criteriaKeyword->add(new \Criteria('summary', '%' . $queryArray[$i] . '%', 'LIKE'), 'OR'); - } - if (in_array('meta_keywords', $searchin)) { - $criteriaKeyword->add(new \Criteria('meta_keywords', '%' . $queryArray[$i] . '%', 'LIKE'), 'OR'); - } - $criteriaKeywords->add($criteriaKeyword, $andor); - unset($criteriaKeyword); - } - } - if (!$GLOBALS['publisherIsAdmin'] && (count($categories) > 0)) { - $criteriaPermissions = new \CriteriaCompo(); - // Categories for which user has access - $categoriesGranted = $gpermHandler->getItemIds('category_read', $groups, $this->publisher->getModule()->getVar('mid')); - if (count($categories) > 0) { - $categoriesGranted = array_intersect($categoriesGranted, $categories); - } - if (0 == count($categoriesGranted)) { - return $ret; - } - $grantedCategories = new \Criteria('categoryid', '(' . implode(',', $categoriesGranted) . ')', 'IN'); - $criteriaPermissions->add($grantedCategories, 'AND'); - } elseif (count($categories) > 0) { - $criteriaPermissions = new \CriteriaCompo(); - $grantedCategories = new \Criteria('categoryid', '(' . implode(',', $categories) . ')', 'IN'); - $criteriaPermissions->add($grantedCategories, 'AND'); - } - $criteriaItemsStatus = new \CriteriaCompo(); - $criteriaItemsStatus->add(new \Criteria('status', PublisherConstants::PUBLISHER_STATUS_PUBLISHED)); - $criteria = new \CriteriaCompo(); - if (!empty($criteriaUser)) { - $criteria->add($criteriaUser, 'AND'); - } - if (!empty($criteriaKeywords)) { - $criteria->add($criteriaKeywords, 'AND'); - } - if (!empty($criteriaPermissions)) { - $criteria->add($criteriaPermissions); - } - if (!empty($criteriaItemsStatus)) { - $criteria->add($criteriaItemsStatus, 'AND'); - } - $criteria->setLimit($limit); - $criteria->setStart($offset); - if (empty($sortby)) { - $sortby = 'datesub'; - } - $criteria->setSort($sortby); - $order = 'ASC'; - if ('datesub' === $sortby) { - $order = 'DESC'; - } - $criteria->setOrder($order); - $ret = $this->getObjects($criteria); - - return $ret; - } - - /** - * @param array $categoriesObj - * @param array $status - * - * @return array - */ - public function getLastPublishedByCat($categoriesObj, $status = [PublisherConstants::PUBLISHER_STATUS_PUBLISHED]) - { - $ret = []; - $catIds = []; - foreach ($categoriesObj as $parentid) { - foreach ($parentid as $category) { - $catId = $category->getVar('categoryid'); - $catIds[$catId] = $catId; - } - } - if (empty($catIds)) { - return $ret; - } - /*$cat = array(); - - $sql = "SELECT categoryid, MAX(datesub) as date FROM " . $this->db->prefix($this->publisher->getDirname() . '_items') . " WHERE status IN (" . implode(',', $status) . ") GROUP BY categoryid"; - $result = $this->db->query($sql); - while ($row = $this->db->fetchArray($result)) { - $cat[$row['categoryid']] = $row['date']; - } - if (count($cat) == 0) return $ret; - $sql = "SELECT categoryid, itemid, title, short_url, uid, datesub FROM " . $this->db->prefix($this->publisher->getDirname() . '_items'); - $criteriaBig = new \CriteriaCompo(); - foreach ($cat as $id => $date) { - $criteria = new \CriteriaCompo(new \Criteria('categoryid', $id)); - $criteria->add(new \Criteria('datesub', $date)); - $criteriaBig->add($criteria, 'OR'); - unset($criteria); - } - $sql .= " " . $criteriaBig->renderWhere(); - $result = $this->db->query($sql); - while ($row = $this->db->fetchArray($result)) { - $item = new PublisherItem(); - $item->assignVars($row); - $ret[$row['categoryid']] = $item; - unset($item); - } - */ - $sql = 'SELECT mi.categoryid, mi.itemid, mi.title, mi.short_url, mi.uid, mi.datesub'; - $sql .= ' FROM (SELECT categoryid, MAX(datesub) AS date FROM ' . $this->db->prefix($this->publisher->getDirname() . '_items'); - $sql .= ' WHERE status IN (' . implode(',', $status) . ')'; - $sql .= ' AND categoryid IN (' . implode(',', $catIds) . ')'; - $sql .= ' GROUP BY categoryid)mo'; - $sql .= ' JOIN ' . $this->db->prefix($this->publisher->getDirname() . '_items') . ' mi ON mi.datesub = mo.date'; - $result = $this->db->query($sql); - while (false !== ($row = $this->db->fetchArray($result))) { - $item = new PublisherItem(); - $item->assignVars($row); - $ret[$row['categoryid']] = $item; - unset($item); - } - - return $ret; - } - - /** - * @param $parentid - * @param $catsCount - * @param string $spaces - * @return int - */ - public function countArticlesByCat($parentid, $catsCount, $spaces = '') - { - // global $resultCatCounts; - $newspaces = $spaces . '--'; - $thecount = 0; - foreach ($catsCount[$parentid] as $subCatId => $count) { - $thecount += $count; - $this->resultCatCounts[$subCatId] = $count; - if (isset($catsCount[$subCatId])) { - $thecount += $this->countArticlesByCat($subCatId, $catsCount, $newspaces); - $this->resultCatCounts[$subCatId] = $thecount; - } - } - - return $thecount; - } - - /** - * @param int $catId - * @param array $status - * @param bool $inSubCat - * - * @return array - */ - public function getCountsByCat($catId = 0, $status, $inSubCat = false) - { - // global $resultCatCounts; - - $ret = []; - $catsCount = []; - $sql = 'SELECT c.parentid, i.categoryid, COUNT(*) AS count FROM ' . $this->db->prefix($this->publisher->getDirname() . '_items') . ' AS i INNER JOIN ' . $this->db->prefix($this->publisher->getDirname() . '_categories') . ' AS c ON i.categoryid=c.categoryid'; - if ((int)$catId > 0) { - $sql .= ' WHERE i.categoryid = ' . (int)$catId; - $sql .= ' AND i.status IN (' . implode(',', $status) . ')'; - } else { - $sql .= ' WHERE i.status IN (' . implode(',', $status) . ')'; - } - $sql .= ' GROUP BY i.categoryid ORDER BY c.parentid ASC, i.categoryid ASC'; - $result = $this->db->query($sql); - if (!$result) { - return $ret; - } - if (!$inSubCat) { - while (false !== ($row = $this->db->fetchArray($result))) { - $catsCount[$row['categoryid']] = $row['count']; - } - - return $catsCount; - } - // while ($row = $this->db->fetchArray($result)) { - while (false !== ($row = $this->db->fetchArray($result))) { - $catsCount[$row['parentid']][$row['categoryid']] = $row['count']; - } - // $resultCatCounts = array(); - foreach ($catsCount[0] as $subCatId => $count) { - $this->resultCatCounts[$subCatId] = $count; - if (isset($catsCount[$subCatId])) { - $this->resultCatCounts[$subCatId] += $this->countArticlesByCat($subCatId, $catsCount, ''); - } - } - - return $this->resultCatCounts; - } -} diff --git a/class/mimetype.php b/class/mimetype.php deleted file mode 100644 index 627a947e..00000000 --- a/class/mimetype.php +++ /dev/null @@ -1,650 +0,0 @@ - - * @author The SmartFactory - */ - -use XoopsModules\Publisher; - -// defined('XOOPS_ROOT_PATH') || exit('Restricted access.'); - -require_once dirname(__DIR__) . '/include/common.php'; - -/** - * PublisherBaseObjectHandler class - * - * @copyright The XUUPS Project http://sourceforge.net/projects/xuups/ - * @license http://www.fsf.org/copyleft/gpl.html GNU public license - * @package Publisher - * @since 1.0 - * @author trabis - * @author Nazar Aziz - */ -class PublisherBaseObjectHandler extends XoopsPersistableObjectHandler -{ - /** - * Database connection - * - * @var XoopsDatabase - */ - //mb public $_db; //mb it is already declared in XoopsObjectHandler - - /** - * Autoincrementing DB fieldname - * - * @var string - */ - protected $idfield = 'id'; - - /** - * @param XoopsDatabase $db - */ - public function init(\XoopsDatabase $db) - { - $this->db = $db; - } - - /** - * DB Table Name - * - * @var string - */ - protected $dbtable = 'publisher_mimetypes'; - - /** - * create a new object - * - * @param bool $isNew - * @return XoopsObject - * @access public - */ - public function create($isNew = true) - { - return new $this->className(); - } - - /** - * retrieve an object from the database, based on. use in child classes - * - * @param int $id ID - * - * @param null $fields - * @return mixed object if id exists, false if not - * @access public - */ - public function get($id = null, $fields = null) - { - $id = (int)$id; - if ($id > 0) { - $sql = $this->selectQuery(new \Criteria($this->idfield, $id)); - if (!$result = $this->db->query($sql)) { - return false; - } - $numrows = $this->db->getRowsNum($result); - if (1 == $numrows) { - $obj = new $this->className($this->db->fetchArray($result)); - - return $obj; - } - } - - return false; - } - - /** - * retrieve objects from the database - * - * @param CriteriaElement $criteria {@link CriteriaElement} - * conditions to be met - * @param bool $idAsKey Should the department ID be used as array key - * - * @param bool $asObject - * @return array array of objects - * @access public - */ - public function &getObjects(CriteriaElement $criteria = null, $idAsKey = false, $asObject = true) //&getObjects($criteria = null, $idAsKey = false) - { - $ret = []; - $limit = $start = 0; - $sql = $this->selectQuery($criteria); - $id = $this->idfield; - if (isset($criteria)) { - $limit = $criteria->getLimit(); - $start = $criteria->getStart(); - } - $result = $this->db->query($sql, $limit, $start); - // if no records from db, return empty array - if (!$result) { - return $ret; - } - // Add each returned record to the result array - while (false !== ($myrow = $this->db->fetchArray($result))) { - $obj = new $this->className($myrow); - if (!$idAsKey) { - $ret[] = $obj; - } else { - $ret[$obj->getVar($id)] = $obj; - } - unset($obj); - } - - return $ret; - } - - /** - * @param XoopsObject $obj - * @param bool $force - * - * @return bool|void - */ - public function insert(\XoopsObject $obj, $force = false)// insert($obj, $force = false) - { - // Make sure object is of correct type - if (0 != strcasecmp($this->className, get_class($obj))) { - return false; - } - // Make sure object needs to be stored in DB - if (!$obj->isDirty()) { - return true; - } - // Make sure object fields are filled with valid values - if (!$obj->cleanVars()) { - return false; - } - // Create query for DB update - if ($obj->isNew()) { - // Determine next auto-gen ID for table - $this->db->genId($this->db->prefix($this->dbtable) . '_uid_seq'); - $sql = $this->insertQuery($obj); - } else { - $sql = $this->updateQuery($obj); - } - // Update DB - if (false !== $force) { - $result = $this->db->queryF($sql); - } else { - $result = $this->db->query($sql); - } - if (!$result) { - $obj->setErrors('The query returned an error. ' . $this->db->error()); - - return false; - } - //Make sure auto-gen ID is stored correctly in object - if ($obj->isNew()) { - $obj->assignVar($this->idfield, $this->db->getInsertId()); - } - - return true; - } - - /** - * Create a "select" SQL query - * - * @param CriteriaElement $criteria {@link CriteriaElement} to match - * - * @return string SQL query - * @access private - */ - private function selectQuery($criteria = null) - { - $sql = sprintf('SELECT * FROM %s', $this->db->prefix($this->dbtable)); - if (isset($criteria) && is_subclass_of($criteria, 'CriteriaElement')) { - $sql .= ' ' . $criteria->renderWhere(); - if ('' != $criteria->getSort()) { - $sql .= ' ORDER BY ' . $criteria->getSort() . ' - ' . $criteria->getOrder(); - } - } - - return $sql; - } - - /** - * count objects matching a criteria - * - * @param CriteriaElement $criteria {@link CriteriaElement} to match - * - * @return int count of objects - * @access public - */ - public function getCount(CriteriaElement $criteria = null) //getCount($criteria = null) - { - $sql = 'SELECT COUNT(*) FROM ' . $this->db->prefix($this->dbtable); - if (isset($criteria) && is_subclass_of($criteria, 'CriteriaElement')) { - $sql .= ' ' . $criteria->renderWhere(); - } - if (!$result = $this->db->query($sql)) { - return 0; - } - list($count) = $this->db->fetchRow($result); - - return $count; - } - - /** - * delete object based on id - * - * @param XoopsObject $obj {@link XoopsObject} to delete - * @param bool $force override XOOPS delete protection - * - * @return bool deletion successful? - * @access public - */ - public function delete(\XoopsObject $obj, $force = false) //delete($obj, $force = false) - { - if (0 != strcasecmp($this->className, get_class($obj))) { - return false; - } - $sql = $this->deleteQuery($obj); - if (false !== $force) { - $result = $this->db->queryF($sql); - } else { - $result = $this->db->query($sql); - } - if (!$result) { - return false; - } - - return true; - } - - /** - * delete department matching a set of conditions - * - * @param CriteriaElement $criteria {@link CriteriaElement} - * - * @param bool $force - * @param bool $asObject - * @return bool FALSE if deletion failed - * @access public - */ - public function deleteAll(CriteriaElement $criteria = null, $force = true, $asObject = false) //deleteAll($criteria = null) - { - $sql = 'DELETE FROM ' . $this->db->prefix($this->dbtable); - if (isset($criteria) && is_subclass_of($criteria, 'CriteriaElement')) { - $sql .= ' ' . $criteria->renderWhere(); - } - if (!$result = $this->db->query($sql)) { - return false; - } - - return true; - } - - /** - * Assign a value to 1 field for tickets matching a set of conditions - * - * @param string $fieldname - * @param string $fieldvalue - * @param CriteriaElement $criteria {@link CriteriaElement} - * - * @param bool $force - * @return bool FALSE if update failed - * @access public - */ - public function updateAll($fieldname, $fieldvalue, CriteriaElement $criteria = null, $force = false) //updateAll($fieldname, $fieldvalue, $criteria = null) - { - $setClause = is_numeric($fieldvalue) ? $fieldname . ' = ' . $fieldvalue : $fieldname . ' = ' . $this->db->quoteString($fieldvalue); - $sql = 'UPDATE ' . $this->db->prefix($this->dbtable) . ' SET ' . $setClause; - if (isset($criteria) && is_subclass_of($criteria, 'CriteriaElement')) { - $sql .= ' ' . $criteria->renderWhere(); - } - if (!$result = $this->db->query($sql)) { - return false; - } - - return true; - } - - /** - * @param $obj - * - * @return bool - */ - protected function insertQuery($obj) - { - return false; - } - - /** - * @param $obj - * - * @return bool|string - */ - protected function updateQuery($obj) - { - return false; - } - - /** - * @param $obj - * - * @return bool - */ - protected function deleteQuery($obj) - { - return false; - } - - /** - * Singleton - prevent multiple instances of this class - * - * @param XoopsDatabase $db - * - * @return XoopsObject {@link pagesCategoryHandler} - * @access public - */ - public function getInstance(\XoopsDatabase $db) - { - static $instance; - if (null === $instance) { - $className = $this->className . 'Handler'; - $instance = new $className($db); - } - - return $instance; - } -} - -/** - * PublisherMimetype class - * - * @author Eric Juden - * @access public - * @package publisher - */ -class PublisherMimetype extends XoopsObject -{ - /** - * @param null|int|array $id - */ - public function __construct($id = null) - { - $this->initVar('mime_id', XOBJ_DTYPE_INT, null, false); - $this->initVar('mime_ext', XOBJ_DTYPE_TXTBOX, null, true, 60); - $this->initVar('mime_types', XOBJ_DTYPE_TXTAREA, null, false, 1024); - $this->initVar('mime_name', XOBJ_DTYPE_TXTBOX, null, true, 255); - $this->initVar('mime_admin', XOBJ_DTYPE_INT, null, false); - $this->initVar('mime_user', XOBJ_DTYPE_INT, null, false); - if (isset($id)) { - if (is_array($id)) { - $this->assignVars($id); - } - } else { - $this->setNew(); - } - } -} - -/** - * Class PublisherMimetypeHandler - */ -class PublisherMimetypeHandler extends PublisherBaseObjectHandler -{ - - /** - * Constructor - * - * @param null|XoopsDatabase $db reference to a xoopsDB object - */ - public function __construct(\XoopsDatabase $db) - { - parent::init($db); - $this->className = 'publishermimetype'; - } - - /** - * retrieve a mimetype object from the database - * - * @param int $id ID of mimetype - * - * @param null $fields - * @return bool|PublisherMimetype - * @access public - */ - public function get($id = null, $fields = null) - { - $id = (int)$id; - if ($id > 0) { - $sql = $this->selectQuery(new \Criteria('mime_id', $id)); - if (!$result = $this->db->query($sql)) { - return false; - } - $numrows = $this->db->getRowsNum($result); - if (1 == $numrows) { - $obj = new $this->className($this->db->fetchArray($result)); - - return $obj; - } - } - - return false; - } - - /** - * retrieve objects from the database - * - * @param CriteriaElement $criteria {@link CriteriaElement} - * conditions to be met - * - * @param bool $idAsKey - * @param bool $asObject - * @return array array of PublisherMimetype objects - * objects - * @access public - */ - public function &getObjects(CriteriaElement $criteria = null, $idAsKey = false, $asObject = true) //&getObjects($criteria = null) - { - $ret = []; - $limit = $start = 0; - $sql = $this->selectQuery($criteria); - if (isset($criteria)) { - $limit = $criteria->getLimit(); - $start = $criteria->getStart(); - } - //echo "
    $sql
    "; - $result = $this->db->query($sql, $limit, $start); - // if no records from db, return empty array - if (!$result) { - return $ret; - } - // Add each returned record to the result array - while (false !== ($myrow = $this->db->fetchArray($result))) { - $obj = new $this->className($myrow); - $ret[] = $obj; - unset($obj); - } - - return $ret; - } - - /** - * Format mime_types into array - * - * @param null $mimeExt - * - * @return array array of mime_types - */ - public function getArray($mimeExt = null) - { - // global $publisherIsAdmin; - $ret = []; - if ($GLOBALS['xoopsUser'] && !$GLOBALS['publisherIsAdmin']) { - // For user uploading - $crit = new \CriteriaCompo(new \Criteria('mime_user', 1)); //$sql = sprintf("SELECT * FROM %s WHERE mime_user=1", $GLOBALS['xoopsDB']->prefix($module->getVar('dirname', 'n') . '_mimetypes')); - } elseif ($GLOBALS['xoopsUser'] && $GLOBALS['publisherIsAdmin']) { - // For admin uploading - $crit = new \CriteriaCompo(new \Criteria('mime_admin', 1)); //$sql = sprintf("SELECT * FROM %s WHERE mime_admin=1", $GLOBALS['xoopsDB']->prefix($module->getVar('dirname', 'n') . '_mimetypes')); - } else { - return $ret; - } - if ($mimeExt) { - $crit->add(new \Criteria('mime_ext', $mimeExt)); - } - $result = $this->getObjects($crit); - // if no records from db, return empty array - if (!$result) { - return $ret; - } - foreach ($result as $mime) { - $line = explode(' ', $mime->getVar('mime_types')); - foreach ($line as $row) { - $ret[] = ['type' => $row, 'ext' => $mime->getVar('mime_ext')]; - } - } - - return $ret; - } - - /** - * Checks to see if the user uploading the file has permissions to upload this mimetype - * - * @param string $postField file being uploaded - * - * @return bool false if no permission, return mimetype if has permission - * @access public - */ - public function checkMimeTypes($postField) - { - $ret = false; - $allowed_mimetypes = $this->getArrayByType(); - if (empty($allowed_mimetypes)) { - return $ret; - } - foreach ($allowed_mimetypes as $mime) { - if ($mime == $_FILES[$postField]['type']) { - $ret = $mime; - break; - } - } - - return $ret; - } - - /** - * @return array - */ - public function getArrayByType() - { - static $array = []; - if (empty($array)) { - $items = $this->getArray(); - foreach ($items as $item) { - $array[] = $item['type']; - } - } - - return $array; - } - - /** - * Create a "select" SQL query - * - * @param null|CriteriaElement $criteria {@link CriteriaElement} to match - * @param bool $join - * - * @return string string SQL query - * @access private - */ - private function selectQuery(CriteriaElement $criteria = null, $join = false) - { - // if (!$join) { - // $sql = sprintf('SELECT * FROM %s', $this->db->prefix($this->dbtable)); - // } else { - // echo "no need for join..."; - // exit; - // } - - try { - if ($join) { - throw new RuntimeException('no need for join...'); - } - } catch (Exception $e) { - $helper = Publisher\Helper::getInstance(); - $helper->addLog($e); - echo 'no need for join...'; - } - - $sql = sprintf('SELECT * FROM %s', $this->db->prefix($this->dbtable)); - - if (isset($criteria) && is_subclass_of($criteria, 'CriteriaElement')) { - $sql .= ' ' . $criteria->renderWhere(); - if ('' != $criteria->getSort()) { - $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder(); - } - } - - return $sql; - } - - /** - * @param $obj - * - * @return bool|string - */ - protected function insertQuery($obj) - { - // Copy all object vars into local variables - foreach ($obj->cleanVars as $k => $v) { - ${$k} = $v; - } - $sql = sprintf( - 'INSERT INTO %s (mime_id, mime_ext, mime_types, mime_name, mime_admin, mime_user) VALUES - (%u, %s, %s, %s, %u, %u)', - $this->db->prefix($this->dbtable), - $obj->getVar('mime_id'), - $this->db->quoteString($obj->getVar('mime_ext')), - $this->db->quoteString($obj->getVar('mime_types')), - $this->db->quoteString($obj->getVar('mime_name')), - $obj->getVar('mime_admin'), - $obj->getVar('mime_user') - ); - - return $sql; - } - - /** - * @param $obj - * - * @return bool|string - */ - protected function updateQuery($obj) - { - // Copy all object vars into local variables - foreach ($obj->cleanVars as $k => $v) { - ${$k} = $v; - } - $sql = sprintf('UPDATE %s SET mime_ext = %s, mime_types = %s, mime_name = %s, mime_admin = %u, mime_user = %u WHERE - mime_id = %u', $this->db->prefix($this->dbtable), $this->db->quoteString($obj->getVar('mime_ext')), $this->db->quoteString($obj->getVar('mime_types')), $this->db->quoteString($obj->getVar('mime_name')), $obj->getVar('mime_admin'), $obj->getVar('mime_user'), $obj->getVar('mime_id')); - - return $sql; - } - - /** - * @param $obj - * - * @return bool|string - */ - protected function deleteQuery($obj) - { - $sql = sprintf('DELETE FROM %s WHERE mime_id = %u', $this->db->prefix($this->dbtable), $obj->getVar('mime_id')); - - return $sql; - } -} diff --git a/class/plugins/plugin.tag.php b/class/plugins/plugin.tag.php index 77d10ec3..fb3d308b 100644 --- a/class/plugins/plugin.tag.php +++ b/class/plugins/plugin.tag.php @@ -19,7 +19,7 @@ * @author The SmartFactory */ -// defined('XOOPS_ROOT_PATH') || exit('Restricted access.'); +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); /** Get item fields: title, content, time, link, uid, uname, tags * * @@ -36,9 +36,12 @@ function publisher_tag_iteminfo(&$items) $itemsId[] = (int)$itemId; } } - $itemHandler = xoops_getModuleHandler('item', 'publisher'); - $criteria = new \Criteria('itemid', '(' . implode(', ', $itemsId) . ')', 'IN'); - $itemsObj = $itemHandler->getObjects($criteria, 'itemid'); + + /** @var \XoopsModules\Publisher\ItemHandler $itemHandler */ + $itemHandler = \XoopsModules\Publisher\Helper::getInstance()->getHandler('Item'); + + $criteria = new \Criteria('itemid', '(' . implode(', ', $itemsId) . ')', 'IN'); + $itemsObj = $itemHandler->getObjects($criteria, 'itemid'); foreach (array_keys($items) as $catId) { foreach (array_keys($items[$catId]) as $itemId) { diff --git a/comment_new.php b/comment_new.php index d039d9e8..052d1c1e 100644 --- a/comment_new.php +++ b/comment_new.php @@ -25,7 +25,7 @@ $com_itemid = Request::getInt('com_itemid', 0, 'GET'); if ($com_itemid > 0) { - $itemObj = $helper->getHandler('item')->get($com_itemid); + $itemObj = $helper->getHandler('Item')->get($com_itemid); $com_replytext = _POSTEDBY . ' ' . $itemObj->getLinkedPosterName() . ' ' . _DATE . ' ' . $itemObj->dateSub() . '

    ' . $itemObj->summary(); $bodytext = $itemObj->body(); if ('' != $bodytext) { diff --git a/docs/changelog.txt b/docs/changelog.txt index 6f729e5e..2dde78ef 100644 --- a/docs/changelog.txt +++ b/docs/changelog.txt @@ -1,7 +1,9 @@ -
    1.06 Beta 2 [NOT RELEASED]
    Dev: Xoops 2.5.9, PHP 7.2.0 +
    1.06 Beta 2 [NOT RELEASED]
    Dev: Xoops 2.5.9, PHP 7.2.3
    - addded missing common traits (goffy/mamba) - fix for page styling in categories (liomj/mamba) +- added Constants (mamba) +- added truncateHTML (mamba)
    1.06 Beta 1 [NOT RELEASED]
    @@ -168,7 +170,7 @@ - added extra columns in Admin's Summary view (mamba) - remove non-existent XoopsFormCalendar in blocks (mamba) - replace XoopsLocal::formatTimestamp() with formatTimestamp() so we have User local time (mamba/geekwright) -- replaced hard-coded GMT date in PublisherFormDateTime with formatTimestamp (mamba) (TODO: do the same for XoopsFormDateTime) +- replaced hard-coded GMT date in FormDateTime with formatTimestamp (mamba) (TODO: do the same for XoopsFormDateTime) - adjusted apostrophes to prevent the define translation errors (slider84) - bug #6: Array to string conversion (cesagonchu/mamba) - fixed bug: not able to delete category (Dante7237/mamba) diff --git a/file.php b/file.php index 05586c31..67e0c20f 100644 --- a/file.php +++ b/file.php @@ -34,7 +34,7 @@ // exit(); } -$fileObj = $helper->getHandler('file')->get($fileid); +$fileObj = $helper->getHandler('File')->get($fileid); // if the selected item was not found, exit if (!$fileObj) { @@ -42,7 +42,7 @@ // exit(); } -$itemObj = $helper->getHandler('item')->get($fileObj->getVar('itemid')); +$itemObj = $helper->getHandler('Item')->get($fileObj->getVar('itemid')); // if the user does not have permission to modify this file, exit if (!(Publisher\Utility::userIsAdmin() || Publisher\Utility::userIsModerator($itemObj) || (is_object($GLOBALS['xoopsUser']) && $fileObj->getVar('uid') == $GLOBALS['xoopsUser']->getVar('uid')))) { @@ -67,7 +67,7 @@ // Creating the file object if (0 != $fileid) { - $fileObj = $helper->getHandler('file')->get($fileid); + $fileObj = $helper->getHandler('File')->get($fileid); } else { redirect_header('index.php', 1, _NOPERM); // exit(); @@ -84,7 +84,7 @@ $oldfile = $fileObj->getFilePath(); // Get available mimetypes for file uploading - $allowed_mimetypes = $helper->getHandler('mimetype')->getArrayByType(); + $allowed_mimetypes = $helper->getHandler('Mimetype')->getArrayByType(); // TODO : display the available mimetypes to the user $errors = []; @@ -99,7 +99,7 @@ } } - if (!$helper->getHandler('file')->insert($fileObj)) { + if (!$helper->getHandler('File')->insert($fileObj)) { redirect_header('item.php?itemid=' . $fileObj->itemid(), 3, _AM_PUBLISHER_FILE_EDITING_ERROR . Publisher\Utility::formatErrors($fileObj->getErrors())); // exit; } @@ -116,7 +116,7 @@ $confirm = Request::getInt('confirm', '', 'POST'); if ($confirm) { - if (!$helper->getHandler('file')->delete($fileObj)) { + if (!$helper->getHandler('File')->delete($fileObj)) { redirect_header('item.php?itemid=' . $fileObj->itemid(), 2, _AM_PUBLISHER_FILE_DELETE_ERROR); // exit; } diff --git a/footer.php b/footer.php index f47f61f6..ac0417fb 100644 --- a/footer.php +++ b/footer.php @@ -19,7 +19,7 @@ * @author The SmartFactory */ -// defined('XOOPS_ROOT_PATH') || exit('Restricted access.'); +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); require_once __DIR__ . '/include/common.php'; diff --git a/header.php b/header.php index 4f45dcf7..6be5f528 100644 --- a/header.php +++ b/header.php @@ -24,5 +24,5 @@ $myts = \MyTextSanitizer::getInstance(); if ('none' !== $helper->getConfig('seo_url_rewrite')) { - require_once PUBLISHER_ROOT_PATH . '/include/seo.inc.php'; + require_once PUBLISHER_ROOT_PATH . '/include/seo.inc.php'; } diff --git a/include/ajax_rating.php b/include/ajax_rating.php index c9d9e5b6..31893313 100644 --- a/include/ajax_rating.php +++ b/include/ajax_rating.php @@ -80,7 +80,7 @@ } $criteria = new \Criteria('itemid', $itemid); -$ratingObjs = $helper->getHandler('rating')->getObjects($criteria); +$ratingObjs = $helper->getHandler('Rating')->getObjects($criteria); $uid = is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getVar('uid') : 0; $count = count($ratingObjs); @@ -112,19 +112,19 @@ echo $output; } -$newRatingObj = $helper->getHandler('rating')->create(); +$newRatingObj = $helper->getHandler('Rating')->create(); $newRatingObj->setVar('itemid', $itemid); $newRatingObj->setVar('ip', $ip); $newRatingObj->setVar('uid', $uid); $newRatingObj->setVar('rate', $rating); $newRatingObj->setVar('date', time()); -$helper->getHandler('rating')->insert($newRatingObj); +$helper->getHandler('Rating')->insert($newRatingObj); $current_rating += $rating; ++$count; -$helper->getHandler('item')->updateAll('rating', number_format($current_rating / $count, 4), $criteria, true); -$helper->getHandler('item')->updateAll('votes', $count, $criteria, true); +$helper->getHandler('Item')->updateAll('rating', number_format($current_rating / $count, 4), $criteria, true); +$helper->getHandler('Item')->updateAll('votes', $count, $criteria, true); $tense = 1 == $count ? _MD_PUBLISHER_VOTE_VOTE : _MD_PUBLISHER_VOTE_VOTES; //plural form votes/vote diff --git a/include/common.php b/include/common.php index 9b8a2b9e..818c7163 100644 --- a/include/common.php +++ b/include/common.php @@ -52,9 +52,9 @@ if (!defined($moduleDirNameUpper . '_CONSTANTS_DEFINED')) { define($moduleDirNameUpper . '_DIRNAME', basename(dirname(__DIR__))); - define($moduleDirNameUpper . '_ROOT_PATH', XOOPS_ROOT_PATH . '/modules/' . $moduleDirName . '/'); - define($moduleDirNameUpper . '_PATH', XOOPS_ROOT_PATH . '/modules/' . $moduleDirName . '/'); - define($moduleDirNameUpper . '_URL', XOOPS_URL . '/modules/' . $moduleDirName . '/'); + define($moduleDirNameUpper . '_ROOT_PATH', XOOPS_ROOT_PATH . '/modules/' . $moduleDirName); + define($moduleDirNameUpper . '_PATH', XOOPS_ROOT_PATH . '/modules/' . $moduleDirName); + define($moduleDirNameUpper . '_URL', XOOPS_URL . '/modules/' . $moduleDirName ); define($moduleDirNameUpper . '_IMAGES_URL', constant($moduleDirNameUpper . '_URL') . '/assets/images/'); define($moduleDirNameUpper . '_IMAGES_PATH', constant($moduleDirNameUpper . '_ROOT_PATH') . '/assets/images/'); define($moduleDirNameUpper . '_ADMIN_URL', constant($moduleDirNameUpper . '_URL') . '/admin/'); @@ -70,30 +70,30 @@ } -if (!defined('PUBLISHER_DIRNAME')) { - define('PUBLISHER_DIRNAME', basename(dirname(__DIR__))); - define('PUBLISHER_URL', XOOPS_URL . '/modules/' . PUBLISHER_DIRNAME); - define('PUBLISHER_PATH', XOOPS_ROOT_PATH . '/modules/' . PUBLISHER_DIRNAME); - define('PUBLISHER_IMAGES_URL', PUBLISHER_URL . '/assets/images'); - define('PUBLISHER_ADMIN_URL', PUBLISHER_URL . '/admin'); - define('PUBLISHER_ADMIN_PATH', PUBLISHER_PATH . '/admin/index.php'); - define('PUBLISHER_ROOT_PATH', $GLOBALS['xoops']->path('modules/' . PUBLISHER_DIRNAME)); - define('PUBLISHER_AUTHOR_LOGOIMG', PUBLISHER_URL . '/assets/images/logo.png'); - define('PUBLISHER_UPLOAD_URL', XOOPS_UPLOAD_URL . '/' . PUBLISHER_DIRNAME); // WITHOUT Trailing slash - define('PUBLISHER_UPLOAD_PATH', XOOPS_UPLOAD_PATH . '/' . PUBLISHER_DIRNAME); // WITHOUT Trailing slash -} +//if (!defined('PUBLISHER_DIRNAME')) { +// define('PUBLISHER_DIRNAME', basename(dirname(__DIR__))); +// define('PUBLISHER_URL', XOOPS_URL . '/modules/' . PUBLISHER_DIRNAME); +// define('PUBLISHER_PATH', XOOPS_ROOT_PATH . '/modules/' . PUBLISHER_DIRNAME); +// define('PUBLISHER_IMAGES_URL', PUBLISHER_URL . '/assets/images'); +// define('PUBLISHER_ADMIN_URL', PUBLISHER_URL . '/admin'); +// define('PUBLISHER_ADMIN_PATH', PUBLISHER_PATH . '/admin/index.php'); +// define('PUBLISHER_ROOT_PATH', $GLOBALS['xoops']->path('modules/' . PUBLISHER_DIRNAME)); +// define('PUBLISHER_AUTHOR_LOGOIMG', PUBLISHER_URL . '/assets/images/logo.png'); +// define('PUBLISHER_UPLOAD_URL', XOOPS_UPLOAD_URL . '/' . PUBLISHER_DIRNAME); // WITHOUT Trailing slash +// define('PUBLISHER_UPLOAD_PATH', XOOPS_UPLOAD_PATH . '/' . PUBLISHER_DIRNAME); // WITHOUT Trailing slash +//} //require_once PUBLISHER_ROOT_PATH . '/include/functions.php'; //require_once PUBLISHER_ROOT_PATH . '/include/constants.php'; -require_once PUBLISHER_ROOT_PATH . '/include/seo_functions.php'; -require_once PUBLISHER_ROOT_PATH . '/class/metagen.php'; -require_once PUBLISHER_ROOT_PATH . '/class/session.php'; +//require_once PUBLISHER_ROOT_PATH . '/include/seo_functions.php'; +//require_once PUBLISHER_ROOT_PATH . '/class/metagen.php'; +//require_once PUBLISHER_ROOT_PATH . '/class/session.php'; //require_once PUBLISHER_ROOT_PATH . '/class/request.php'; -xoops_load('constants', PUBLISHER_DIRNAME); +//xoops_load('Constants', PUBLISHER_DIRNAME); //This is needed or it will not work in blocks. global $publisherIsAdmin; diff --git a/include/config.php b/include/config.php index 4672005b..b9de1afe 100644 --- a/include/config.php +++ b/include/config.php @@ -22,64 +22,66 @@ $moduleDirName = basename(dirname(__DIR__)); $moduleDirNameUpper = strtoupper($moduleDirName); -//Configurator -return (object)[ - 'name' => strtoupper($moduleDirName) . ' Module Configurator', - 'paths' => [ - 'dirname' => $moduleDirName, - 'admin' => XOOPS_ROOT_PATH . '/modules/' . $moduleDirName . '/admin', - 'modPath' => XOOPS_ROOT_PATH . '/modules/' . $moduleDirName, - 'modUrl' => XOOPS_URL . '/modules/' . $moduleDirName, - 'uploadPath' => XOOPS_UPLOAD_PATH . '/' . $moduleDirName, - 'uploadUrl' => XOOPS_UPLOAD_URL . '/' . $moduleDirName, - ], - 'uploadFolders' => [ - XOOPS_UPLOAD_PATH . '/' . $moduleDirName, - XOOPS_UPLOAD_PATH . '/' . $moduleDirName . '/content', - XOOPS_UPLOAD_PATH . '/' . $moduleDirName . '/images', - XOOPS_UPLOAD_PATH . '/' . $moduleDirName . '/images/category', - XOOPS_UPLOAD_PATH . '/' . $moduleDirName . '/images/thumbnails', - ], - 'copyBlankFiles' => [ - XOOPS_UPLOAD_PATH . '/' . $moduleDirName, - XOOPS_UPLOAD_PATH . '/' . $moduleDirName . '/images/category', - XOOPS_UPLOAD_PATH . '/' . $moduleDirName . '/images/thumbnails', - ], +function getConfig() +{ + return (object)[ + 'name' => strtoupper($moduleDirName) . ' Module Configurator', + 'paths' => [ + 'dirname' => $moduleDirName, + 'admin' => XOOPS_ROOT_PATH . '/modules/' . $moduleDirName . '/admin', + 'modPath' => XOOPS_ROOT_PATH . '/modules/' . $moduleDirName, + 'modUrl' => XOOPS_URL . '/modules/' . $moduleDirName, + 'uploadPath' => XOOPS_UPLOAD_PATH . '/' . $moduleDirName, + 'uploadUrl' => XOOPS_UPLOAD_URL . '/' . $moduleDirName, + ], + 'uploadFolders' => [ + XOOPS_UPLOAD_PATH . '/' . $moduleDirName, + XOOPS_UPLOAD_PATH . '/' . $moduleDirName . '/content', + XOOPS_UPLOAD_PATH . '/' . $moduleDirName . '/images', + XOOPS_UPLOAD_PATH . '/' . $moduleDirName . '/images/category', + XOOPS_UPLOAD_PATH . '/' . $moduleDirName . '/images/thumbnails', + ], + 'copyBlankFiles' => [ + XOOPS_UPLOAD_PATH . '/' . $moduleDirName, + XOOPS_UPLOAD_PATH . '/' . $moduleDirName . '/images/category', + XOOPS_UPLOAD_PATH . '/' . $moduleDirName . '/images/thumbnails', + ], - 'copyTestFolders' => [ + 'copyTestFolders' => [ - [ - XOOPS_ROOT_PATH . '/modules/' . $moduleDirName . '/testdata/images', - XOOPS_UPLOAD_PATH . '/' . $moduleDirName . '/images', + [ + XOOPS_ROOT_PATH . '/modules/' . $moduleDirName . '/testdata/images', + XOOPS_UPLOAD_PATH . '/' . $moduleDirName . '/images', + ], + [ + XOOPS_ROOT_PATH . '/modules/' . $moduleDirName . '/testdata/thumbs', + XOOPS_UPLOAD_PATH . '/' . $moduleDirName . '/thumbs', + ] ], - [ - XOOPS_ROOT_PATH . '/modules/' . $moduleDirName . '/testdata/thumbs', - XOOPS_UPLOAD_PATH . '/' . $moduleDirName . '/thumbs', - ] - ], - 'templateFolders' => [ - '/templates/', - '/templates/blocks/', - '/templates/admin/' + 'templateFolders' => [ + '/templates/', + '/templates/blocks/', + '/templates/admin/' - ], - 'oldFiles' => [ - '/class/request.php', - '/class/registry.php', - '/class/utilities.php', - '/class/util.php', - '/include/constants.php', - '/include/functions.php', - '/ajaxrating.txt' - ], - 'oldFolders' => [ - '/images', - '/css', - '/js', - '/tcpdf', - ], + ], + 'oldFiles' => [ + '/class/request.php', + '/class/registry.php', + '/class/utilities.php', + '/class/util.php', + '/include/constants.php', + '/include/functions.php', + '/ajaxrating.txt' + ], + 'oldFolders' => [ + '/images', + '/css', + '/js', + '/tcpdf', + ], 'modCopyright' => " - \'XOOPS', + \'XOOPS', -]; + ]; +} diff --git a/include/notification.inc.php b/include/notification.inc.php index 5f8ffb33..b3019f0c 100644 --- a/include/notification.inc.php +++ b/include/notification.inc.php @@ -19,9 +19,11 @@ * @author The SmartFactory */ -// defined('XOOPS_ROOT_PATH') || exit('Restricted access.'); +use XoopsModules\Publisher; -require_once __DIR__ . '/seo_functions.php'; +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); + +//require_once __DIR__ . '/seo_functions.php'; /** * @param $category @@ -45,7 +47,7 @@ function publisher_notify_iteminfo($category, $itemId) $result = $GLOBALS['xoopsDB']->query($sql); // TODO: error check $resultArray = $GLOBALS['xoopsDB']->fetchArray($result); $item['name'] = $resultArray['name']; - $item['url'] = PublisherSeo::generateUrl('category', $itemId, $resultArray['short_url']); + $item['url'] = Publisher\Seo::generateUrl('category', $itemId, $resultArray['short_url']); return $item; } @@ -56,7 +58,7 @@ function publisher_notify_iteminfo($category, $itemId) $result = $GLOBALS['xoopsDB']->query($sql); // TODO: error check $resultArray = $GLOBALS['xoopsDB']->fetchArray($result); $item['name'] = $resultArray['title']; - $item['url'] = PublisherSeo::generateUrl('item', $itemId, $resultArray['short_url']); + $item['url'] = Publisher\Seo::generateUrl('item', $itemId, $resultArray['short_url']); return $item; } diff --git a/include/oninstall.php b/include/oninstall.php index 32721b49..70ef9eca 100644 --- a/include/oninstall.php +++ b/include/oninstall.php @@ -58,10 +58,10 @@ function xoops_module_install_publisher(\XoopsModule $module) /** @var Publisher\Helper $helper */ /** @var Publisher\Utility $utility */ - /** @var common\Configurator $configurator */ + /** @var Common\Configurator $configurator */ $helper = Publisher\Helper::getInstance(); $utility = new Publisher\Utility(); - $configurator = new common\Configurator(); + $configurator = new Common\Configurator(); // Load language files $helper->loadLanguage('admin'); diff --git a/include/onupdate.php b/include/onupdate.php index 2d5552b4..48bb4d93 100644 --- a/include/onupdate.php +++ b/include/onupdate.php @@ -18,7 +18,7 @@ use XoopsModules\Publisher; -if ((!defined('XOOPS_ROOT_PATH')) || !($GLOBALS['xoopsUser'] instanceof XoopsUser) +if ((!defined('XOOPS_ROOT_PATH')) || !($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->IsAdmin() ) { exit('Restricted access' . PHP_EOL); @@ -84,7 +84,7 @@ function xoops_module_update_publisher(\XoopsModule $module, $previousVersion = $xoopsDB->queryF($sql); $sql = ' ALTER TABLE ' . $GLOBALS['xoopsDB']->prefix($module->getVar('dirname', 'n') . '_categories') . ' MODIFY `meta_description` TEXT NULL'; $xoopsDB->queryF($sql); - /** @var \Utility $utility */ + /** @var Publisher\Utility $utility */ $utility = new Publisher\Utility(); //delete old HTML templates @@ -94,7 +94,7 @@ function xoops_module_update_publisher(\XoopsModule $module, $previousVersion = if (is_dir($templateFolder)) { $templateList = array_diff(scandir($templateFolder, SCANDIR_SORT_NONE), ['..', '.']); foreach ($templateList as $k => $v) { - $fileInfo = new SplFileInfo($templateFolder . $v); + $fileInfo = new \SplFileInfo($templateFolder . $v); if ('html' === $fileInfo->getExtension() && 'index.html' !== $fileInfo->getFilename()) { if (file_exists($templateFolder . $v)) { unlink($templateFolder . $v); @@ -122,7 +122,7 @@ function xoops_module_update_publisher(\XoopsModule $module, $previousVersion = // 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); } diff --git a/include/plugin.tag.php b/include/plugin.tag.php index b06f404a..f00d2ee0 100644 --- a/include/plugin.tag.php +++ b/include/plugin.tag.php @@ -19,7 +19,7 @@ * @author The SmartFactory */ -// defined('XOOPS_ROOT_PATH') || exit('Restricted access.'); +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); /** Get item fields: title, content, time, link, uid, uname, tags * * diff --git a/include/search.inc.php b/include/search.inc.php index cd5e7b00..4045d02e 100644 --- a/include/search.inc.php +++ b/include/search.inc.php @@ -19,9 +19,9 @@ use XoopsModules\Publisher; -// defined('XOOPS_ROOT_PATH') || exit('Restricted access.'); +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); -require_once dirname(__DIR__) . '/include/common.php'; +require_once __DIR__ . '/common.php'; /** * @param string|array $queryArray @@ -46,7 +46,7 @@ function publisher_search($queryArray, $andor, $limit, $offset, $userid, $catego $keywords = implode('+', $queryArray); $hightlightKey = '&keywords=' . $keywords; } - $itemsObjs = $helper->getHandler('item')->getItemsFromSearch($queryArray, $andor, $limit, $offset, $userid, $categories, $sortby, $searchin, $extra); + $itemsObjs = $helper->getHandler('Item')->getItemsFromSearch($queryArray, $andor, $limit, $offset, $userid, $categories, $sortby, $searchin, $extra); $withCategoryPath = $helper->getConfig('search_cat_path'); //xoops_load("xoopslocal"); $usersIds = []; diff --git a/include/seo.inc.php b/include/seo.inc.php index cc8c0d38..b52ed2ef 100644 --- a/include/seo.inc.php +++ b/include/seo.inc.php @@ -21,7 +21,7 @@ use Xmf\Request; -// defined('XOOPS_ROOT_PATH') || exit('Restricted access.'); +// defined('XOOPS_ROOT_PATH') || die('Restricted access'); //$seoOp = @$_GET['seoOp']; $seoOp = Request::getString('seoOp', '', 'GET'); diff --git a/index.php b/index.php index b5f0162f..896be186 100644 --- a/index.php +++ b/index.php @@ -21,6 +21,7 @@ use Xmf\Request; use XoopsModules\Publisher; +use XoopsModules\Publisher\Constants; require_once __DIR__ . '/header.php'; @@ -31,7 +32,7 @@ $start = Request::getInt('start', 0, 'GET'); // Number of categories at the top level -$totalCategories = $helper->getHandler('category')->getCategoriesCount(0); +$totalCategories = $helper->getHandler('Category')->getCategoriesCount(0); // if there ain't no category to display, let's get out of here if (0 == $totalCategories) { @@ -46,7 +47,7 @@ $gpermHandler = xoops_getHandler('groupperm'); // Creating the top categories objects -$categoriesObj = $helper->getHandler('category')->getCategories($helper->getConfig('idxcat_cat_perpage'), $catstart); +$categoriesObj = $helper->getHandler('Category')->getCategories($helper->getConfig('idxcat_cat_perpage'), $catstart); // if no categories are found, exit $totalCategoriesOnPage = count($categoriesObj); @@ -56,17 +57,17 @@ } // Get subcats of the top categories -$subcats = $helper->getHandler('category')->getSubCats($categoriesObj); +$subcats = $helper->getHandler('Category')->getSubCats($categoriesObj); // Count of items within each top categories -$totalItems = $helper->getHandler('category')->publishedItemsCount(); +$totalItems = $helper->getHandler('Category')->publishedItemsCount(); // real total count of items -$real_total_items = $helper->getHandler('item')->getItemsCount(-1, [PublisherConstants::PUBLISHER_STATUS_PUBLISHED]); +$real_total_items = $helper->getHandler('Item')->getItemsCount(-1, [Constants::PUBLISHER_STATUS_PUBLISHED]); if (1 == $helper->getConfig('idxcat_display_last_item')) { // Get the last item in each category - $lastItemObj = $helper->getHandler('item')->getLastPublishedByCat(array_merge([$categoriesObj], $subcats)); + $lastItemObj = $helper->getHandler('Item')->getLastPublishedByCat(array_merge([$categoriesObj], $subcats)); } // Max size of the title in the last item column @@ -177,7 +178,7 @@ } // Creating the last ITEMs - $itemsObj = $helper->getHandler('item')->getAllPublished($helper->getConfig('idxcat_index_perpage'), $start, -1, $sort, $order); + $itemsObj = $helper->getHandler('Item')->getAllPublished($helper->getConfig('idxcat_index_perpage'), $start, -1, $sort, $order); $itemsCount = count($itemsObj); //todo: make config for summary size @@ -226,7 +227,7 @@ /** * Generating meta information for this page */ -$publisherMetagen = new PublisherMetagen($helper->getModule()->getVar('name')); +$publisherMetagen = new Publisher\Metagen($helper->getModule()->getVar('name')); $publisherMetagen->createMetaTags(); // RSS Link diff --git a/item.php b/item.php index 0a961bfa..5c852b96 100644 --- a/item.php +++ b/item.php @@ -33,7 +33,7 @@ } // Creating the item object for the selected item -$itemObj = $helper->getHandler('item')->get($itemId); +$itemObj = $helper->getHandler('Item')->get($itemId); // if the selected item was not found, exit if (!$itemObj) { @@ -55,7 +55,7 @@ require_once PUBLISHER_ROOT_PATH . '/footer.php'; // Creating the category object that holds the selected item -$categoryObj = $helper->getHandler('category')->get($itemObj->categoryid()); +$categoryObj = $helper->getHandler('Category')->get($itemObj->categoryid()); // Check user permissions to access that category of the selected item if (!$itemObj->accessGranted()) { @@ -116,8 +116,8 @@ $nextItemLink = ''; $nextItemUrl = ''; - $previousObj = $helper->getHandler('item')->getPreviousPublished($itemObj); - $nextObj = $helper->getHandler('item')->getNextPublished($itemObj); + $previousObj = $helper->getHandler('Item')->getPreviousPublished($itemObj); + $nextObj = $helper->getHandler('Item')->getNextPublished($itemObj); if (is_object($previousObj)) { $previousItemLink = $previousObj->getItemLink(); $previousItemUrl = $previousObj->getItemUrl(); @@ -136,7 +136,7 @@ //CAREFUL!! with many items this will exhaust memory if ('all' === $helper->getConfig('item_other_items_type')) { - $itemsObj = $helper->getHandler('item')->getAllPublished(0, 0, $categoryObj->categoryid(), $sort, $order, '', true, true); + $itemsObj = $helper->getHandler('Item')->getAllPublished(0, 0, $categoryObj->categoryid(), $sort, $order, '', true, true); $items = []; foreach ($itemsObj[''] as $theItemObj) { $theItem = []; @@ -235,7 +235,7 @@ /** * Generating meta information for this page */ -$publisherMetagen = new PublisherMetagen($itemObj->getVar('title'), $itemObj->getVar('meta_keywords', 'n'), $itemObj->getVar('meta_description', 'n'), $itemObj->getCategoryPath()); +$publisherMetagen = new Publisher\Metagen($itemObj->getVar('title'), $itemObj->getVar('meta_keywords', 'n'), $itemObj->getVar('meta_description', 'n'), $itemObj->getCategoryPath()); $publisherMetagen->createMetaTags(); // Include the comments if the selected ITEM supports comments diff --git a/makepdf.php b/makepdf.php index cbdcc17d..987f3702 100644 --- a/makepdf.php +++ b/makepdf.php @@ -23,7 +23,7 @@ require_once XOOPS_ROOT_PATH . '/class/libraries/vendor/tecnickcom/tcpdf/tcpdf.php'; // Creating the item object for the selected item -$itemObj = $helper->getHandler('item')->get($itemid); +$itemObj = $helper->getHandler('Item')->get($itemid); // if the selected item was not found, exit if (!$itemObj) { @@ -31,7 +31,7 @@ } // Creating the category object that holds the selected item -$categoryObj = $helper->getHandler('category')->get($itemObj->categoryid()); +$categoryObj = $helper->getHandler('Category')->get($itemObj->categoryid()); // Check user permissions to access that category of the selected item if (!$itemObj->accessGranted()) { diff --git a/preloads/core.php b/preloads/core.php index 9704f2b8..0d7e06d9 100644 --- a/preloads/core.php +++ b/preloads/core.php @@ -15,12 +15,12 @@ * @author XOOPS Project */ -defined('XOOPS_ROOT_PATH') || exit('Restricted access.'); +defined('XOOPS_ROOT_PATH') || die('Restricted access'); /** * Class PublisherCorePreload */ -class PublisherCorePreload extends XoopsPreloadItem +class PublisherCorePreload extends \XoopsPreloadItem { // to add PSR-4 autoloader /** diff --git a/print.php b/print.php index 5e75fa9c..67b7c7d3 100644 --- a/print.php +++ b/print.php @@ -33,7 +33,7 @@ } // Creating the ITEM object for the selected ITEM -$itemObj = $helper->getHandler('item')->get($itemid); +$itemObj = $helper->getHandler('Item')->get($itemid); // if the selected ITEM was not found, exit if ($itemObj->notLoaded()) { diff --git a/rate.php b/rate.php index fe2817a5..0119e0f2 100644 --- a/rate.php +++ b/rate.php @@ -19,6 +19,8 @@ */ use Xmf\Request; +use XoopsModules\Publisher; +use XoopsModules\Publisher\Constants; require_once __DIR__ . '/header.php'; @@ -28,13 +30,13 @@ $groups = $GLOBALS['xoopsUser'] ? $GLOBALS['xoopsUser']->getGroups() : XOOPS_GROUP_ANONYMOUS; /* @var $gpermHandler XoopsGroupPermHandler */ -$gpermHandler = xoops_getModuleHandler('groupperm'); +$gpermHandler = \XoopsModules\Publisher\Helper::getInstance()->getHandler('Groupperm');//xoops_getModuleHandler('groupperm'); /* @var $configHandler XoopsConfigHandler */ $configHandler = xoops_getHandler('config'); $module_id = $helper->getModule()->getVar('mid'); //Checking permissions -if (!$helper->getConfig('perm_rating') || !$gpermHandler->checkRight('global', PublisherConstants::PUBLISHER_RATE, $groups, $module_id)) { +if (!$helper->getConfig('perm_rating') || !$gpermHandler->checkRight('global', Constants::PUBLISHER_RATE, $groups, $module_id)) { redirect_header(PUBLISHER_URL . '/item.php?itemid=' . $itemid, 2, _NOPERM); // exit(); } @@ -45,7 +47,7 @@ } $criteria = new \Criteria('itemid', $itemid); -$ratingObjs = $helper->getHandler('rating')->getObjects($criteria); +$ratingObjs = $helper->getHandler('Rating')->getObjects($criteria); $uid = is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getVar('uid') : 0; $count = count($ratingObjs); @@ -66,19 +68,19 @@ // exit(); } -$newRatingObj = $helper->getHandler('rating')->create(); +$newRatingObj = $helper->getHandler('Rating')->create(); $newRatingObj->setVar('itemid', $itemid); $newRatingObj->setVar('ip', $ip); $newRatingObj->setVar('uid', $uid); $newRatingObj->setVar('rate', $rating); $newRatingObj->setVar('date', time()); -$helper->getHandler('rating')->insert($newRatingObj); +$helper->getHandler('Rating')->insert($newRatingObj); $current_rating += $rating; ++$count; -$helper->getHandler('item')->updateAll('rating', number_format($current_rating / $count, 4), $criteria, true); -$helper->getHandler('item')->updateAll('votes', $count, $criteria, true); +$helper->getHandler('Item')->updateAll('rating', number_format($current_rating / $count, 4), $criteria, true); +$helper->getHandler('Item')->updateAll('votes', $count, $criteria, true); redirect_header(PUBLISHER_URL . '/item.php?itemid=' . $itemid, 2, _MD_PUBLISHER_VOTE_THANKS); //exit(); diff --git a/search.php b/search.php index 16a2c3f2..755ff503 100644 --- a/search.php +++ b/search.php @@ -21,6 +21,7 @@ use Xmf\Request; use XoopsModules\Publisher; +use XoopsModules\Publisher\Constants; require_once __DIR__ . '/header.php'; xoops_loadLanguage('search'); @@ -37,7 +38,7 @@ $module_id = $helper->getModule()->mid(); //Checking permissions -if (!$helper->getConfig('perm_search') || !$gpermHandler->checkRight('global', PublisherConstants::PUBLISHER_SEARCH, $groups, $module_id)) { +if (!$helper->getConfig('perm_search') || !$gpermHandler->checkRight('global', Constants::PUBLISHER_SEARCH, $groups, $module_id)) { redirect_header(PUBLISHER_URL, 2, _NOPERM); // exit(); } @@ -197,7 +198,7 @@ $typeSelect .= ''; /* category */ -$categories = $helper->getHandler('category')->getCategoriesForSearch(); +$categories = $helper->getHandler('Category')->getCategoriesForSearch(); $categorySelect = '
    <{/foreach}> -
    " . _AM_PUBLISHER_ITEMID . '
    <{/if}><{if $rating_enabled}> - <{$item.ratingbar}><{/if}><{include file='db:publisher_footer.tpl'}> - + <{/if}> + <{if $rating_enabled}> + <{$item.ratingbar}><{/if}> + <{include file='db:publisher_footer.tpl'}>