From 869d4a91f1ad913c2e474b4d5976575acb5b3167 Mon Sep 17 00:00:00 2001 From: spotweb Date: Wed, 4 Jul 2012 00:50:04 +0200 Subject: [PATCH] Further steps in the removal of dependency on SpotsOveriew and SpotDb --- index.php | 886 +++++++++--------- install.php | 4 +- lib/Bootstrap.php | 168 ++++ lib/SpotAudit.php | 38 +- lib/SpotClassAutoload.php | 5 + lib/SpotDb.php | 41 +- lib/SpotNotifications.php | 462 ++++----- lib/SpotSecurity.php | 333 ++++--- lib/SpotSettings.php | 504 +++++----- lib/SpotSettingsUpgrader.php | 2 +- lib/SpotTemplateHelper.php | 2 +- lib/SpotTiming.php | 2 +- lib/SpotUserSystem.php | 6 +- lib/SpotUserUpgrader.php | 2 +- lib/dao/Base/Dao_Base_BlackWhiteList.php | 43 +- lib/dbeng/dbeng_abs.php | 2 +- lib/exceptions/CorruptBWListException.php | 2 + lib/nzbhandler/NzbHandler_Factory.php | 6 +- lib/page/SpotPage_Abs.php | 252 ++--- lib/page/SpotPage_blacklistspotter.php | 132 +-- lib/page/SpotPage_catsjson.php | 460 ++++----- lib/page/SpotPage_createuser.php | 6 +- lib/page/SpotPage_editfilter.php | 362 +++---- lib/page/SpotPage_editsecgroup.php | 250 ++--- lib/page/SpotPage_editsettings.php | 4 +- lib/page/SpotPage_edituser.php | 402 ++++---- lib/page/SpotPage_edituserprefs.php | 326 +++---- lib/page/SpotPage_getimage.php | 4 +- lib/page/SpotPage_getnzb.php | 86 +- lib/page/SpotPage_getnzbmobile.php | 100 +- lib/page/SpotPage_getspot.php | 46 +- lib/page/SpotPage_index.php | 6 +- lib/page/SpotPage_login.php | 140 +-- lib/page/SpotPage_newznabapi.php | 4 +- lib/page/SpotPage_nzbhandlerapi.php | 243 +++-- lib/page/SpotPage_postcomment.php | 7 +- lib/page/SpotPage_postspot.php | 6 +- lib/page/SpotPage_render.php | 76 +- lib/page/SpotPage_reportpost.php | 6 +- lib/page/SpotPage_rss.php | 4 +- lib/page/SpotPage_statics.php | 4 +- lib/page/SpotPage_statistics.php | 4 +- lib/page/SpotPage_twitteroauth.php | 174 ++-- .../BWList/Services_BWList_Retriever.php | 74 ++ .../Format/Services_Format_Parsing.php | 2 +- lib/services/Nntp/Services_Nntp_Engine.php | 25 +- .../Nntp/Services_Nntp_EnginePool.php | 59 ++ .../Nntp/Services_Nntp_SpotPosting.php | 6 +- .../Nntp/Services_Nntp_SpotReading.php | 4 +- .../Retriever/Services_Retriever_Base.php | 50 +- .../Retriever/Services_Retriever_Comments.php | 27 +- .../Retriever/Services_Retriever_Reports.php | 21 +- .../Retriever/Services_Retriever_Spots.php | 94 +- .../Signing/Services_Signing_Base.php | 4 +- retrieve.php | 197 ++-- 55 files changed, 3184 insertions(+), 2991 deletions(-) create mode 100644 lib/Bootstrap.php create mode 100644 lib/exceptions/CorruptBWListException.php create mode 100644 lib/services/BWList/Services_BWList_Retriever.php create mode 100644 lib/services/Nntp/Services_Nntp_EnginePool.php diff --git a/index.php b/index.php index 09ee34218..6d1bcb80b 100755 --- a/index.php +++ b/index.php @@ -1,467 +1,419 @@ -connect(); - - /* - * Create the setting object as soon as possible because - * we need it for a lot of stuff - */ - $settings = SpotSettings::singleton($db, $settings); - - /* - * Disable the timing part as soon as possible because it - * gobbles memory - */ - if (!$settings->get('enable_timing')) { - SpotTiming::disable(); - } # if - - /* - * The basics has been setup, lets check if the schema needs - * updating - */ - if (!$settings->schemaValid()) { - throw new SchemaNotUpgradedException(); - } # if - - /* - * Does our global setting table need updating? - */ - if (!$settings->settingsValid()) { - throw new SettingsNotUpgradedException(); - } # if - - /* - * Because users are asked to modify ownsettings.php themselves, it is - * possible they create a mistake and accidentally create output from it. - * - * This output breaks a lot of stuff like download integration, image generation - * and more. - * - * We try to check if any output has been submitted, and if so, we refuse - * to continue to prevent all sorts of confusing bug reports - */ - if ((headers_sent()) || ((int) ob_get_length() > 0)) { - throw new OwnsettingsCreatedOutputException(); - } # if - - # helper functions for passed variables - $req = new SpotReq(); - $req->initialize($settings); - - $page = $req->getDef('page', 'index'); - - # Retrieve the users object of the user which is logged on - SpotTiming::start('auth'); - $spotUserSystem = new SpotUserSystem($db, $settings); - if ($req->doesExist('apikey')) { - $currentSession = $spotUserSystem->verifyApi($req->getDef('apikey', '')); - } else { - $currentSession = $spotUserSystem->useOrStartSession(false); - } # if - - /* - * If three is no user object, we don't have a security system - * either. Without a security system we cannot boot, so fatal - */ - if ($currentSession === false) { - if ($req->doesExist('apikey')) { - $currentSession = $spotUserSystem->useOrStartSession(true); - - throw new PermissionDeniedException(SpotSecurity::spotsec_consume_api, 'invalid API key'); - } else { - throw new SqlErrorException("Unable to create session"); - } # else - } # if - SpotTiming::stop('auth'); - - /* - * And check if the security groups need updating - */ - if (!$currentSession['security']->securityValid()) { - throw new SecurityNotUpgradedException(); - } # if - - # User session has been loaded, let's translate the categories - if ($currentSession['user']['prefs']['user_language'] != 'en_US') { - SpotTranslation::initialize($currentSession['user']['prefs']['user_language']); - } # if - SpotCategories::startTranslation(); - - - /* - * Let the form handler know what userid we are using so - * we can make the CSRF cookie be user-bounded - */ - $req->setUserId($currentSession['user']['userid']); - - /* - * Only now it is safe to check wether the user is actually alowed - * to authenticate with an API key - */ - if ($req->doesExist('apikey')) { - /* - * To use the Spotweb API we need the actual permission - */ - $currentSession['security']->fatalPermCheck(SpotSecurity::spotsec_consume_api, ''); - - /* - * but we also need a specific permission, because else things could - * be automated which we simply do not want to be automated - */ - $currentSession['security']->fatalPermCheck(SpotSecurity::spotsec_consume_api, $page); - } # if - - SpotTiming::start('renderpage'); - switch($page) { - case 'render' : { - $page = new SpotPage_render($db, $settings, $currentSession, $req->getDef('tplname', ''), - Array('search' => $req->getDef('search', $spotUserSystem->getIndexFilter($currentSession['user']['userid'])), - 'data' => $req->getDef('data', array()), - 'messageid' => $req->getDef('messageid', ''), - 'pagenr' => $req->getDef('pagenr', 0), - 'perpage' => $req->getDef('perpage', 10), - 'sortby' => $req->getDef('sortby', ''), - 'sortdir' => $req->getDef('sortdir', ''))); - - $page->render(); - break; - } # render - - case 'getspot' : { - if (strpos($_SERVER['HTTP_USER_AGENT'], "SABnzbd+") === 0) { - $page = new SpotPage_getnzb($db, $settings, $currentSession, - Array('messageid' => $req->getDef('messageid', ''), - 'action' => $req->getDef('action', 'display'), - 'username' => $req->getDef('username', ''), - 'apikey' => $req->getDef('apikey', ''))); - } else { - $page = new SpotPage_getspot($db, $settings, $currentSession, $req->getDef('messageid', '')); - } # else - $page->render(); - break; - } # getspot - - case 'getnzb' : { - $page = new SpotPage_getnzb($db, $settings, $currentSession, - Array('messageid' => $req->getDef('messageid', ''), - 'action' => $req->getDef('action', 'display'), - 'username' => $req->getDef('username', ''), - 'apikey' => $req->getDef('apikey', ''))); - $page->render(); - break; - } - - case 'getnzbmobile' : { - $page = new SpotPage_getnzbmobile($db, $settings, $currentSession, - Array('messageid' => $req->getDef('messageid', ''), - 'action' => $req->getDef('action', 'display'))); - $page->render(); - break; - } # getnzbmobile - - case 'erasedls' : { - $page = new SpotPage_erasedls($db, $settings, $currentSession); - $page->render(); - break; - } # erasedls - - case 'catsjson' : { - $page = new SpotPage_catsjson( - $db, - $settings, - $currentSession, - Array('search' => $req->getDef('search', $spotUserSystem->getIndexFilter($currentSession['user']['userid'])), - 'subcatz' => $req->getDef('subcatz', '*'), - 'category' => $req->getDef('category', '*'), - 'rendertype' => $req->getDef('rendertype', 'tree'), - 'disallowstrongnot' => $req->getDef('disallowstrongnot', ''))); - $page->render(); - break; - } # getspot - - case 'markallasread' : { - $page = new SpotPage_markallasread($db, $settings, $currentSession); - $page->render(); - break; - } # markallasread - - case 'getimage' : { - $page = new SpotPage_getimage($db, $settings, $currentSession, - Array('messageid' => $req->getDef('messageid', ''), - 'image' => $req->getDef('image', Array()))); - $page->render(); - break; - } - case 'newznabapi' : { - $page = new SpotPage_newznabapi($db, $settings, $currentSession, - Array('t' => $req->getDef('t', ''), - 'messageid' => $req->getDef('id', ''), - 'apikey' => $req->getDef('apikey', ''), - 'q' => $req->getDef('q', ''), - 'limit' => $req->getDef('limit', ''), - 'cat' => $req->getDef('cat', ''), - 'imdbid' => $req->getDef('imdbid', ''), - 'artist' => $req->getDef('artist', ''), - 'rid' => $req->getDef('rid', ''), - 'season' => $req->getDef('season', ''), - 'ep' => $req->getDef('ep', ''), - 'o' => $req->getDef('o', ''), - 'extended' => $req->getDef('extended', ''), - 'maxage' => $req->getDef('maxage', ''), - 'offset' => $req->getDef('offset', ''), - 'del' => $req->getDef('del', '') - ) - ); - $page->render(); - break; - } # api - - case 'rss' : { - $page = new SpotPage_rss($db, $settings, $currentSession, - Array('search' => $req->getDef('search', $spotUserSystem->getIndexFilter($currentSession['user']['userid'])), - 'page' => $req->getDef('page', 0), - 'sortby' => $req->getDef('sortby', ''), - 'sortdir' => $req->getDef('sortdir', ''), - 'username' => $req->getDef('username', ''), - 'apikey' => $req->getDef('apikey', '')) - ); - $page->render(); - break; - } # rss - - case 'statics' : { - $page = new SpotPage_statics($db, $settings, $currentSession, - Array('type' => $req->getDef('type', ''))); - $page->render(); - break; - } # statics - - case 'createuser' : { - $page = new SpotPage_createuser($db, $settings, $currentSession, - Array('createuserform' => $req->getForm('createuserform'))); - $page->render(); - break; - } # createuser - - case 'editsettings' : { - $page = new SpotPage_editsettings($db, $settings, $currentSession, - Array('editsettingsform' => $req->getForm('editsettingsform'))); - $page->render(); - break; - } # editsettings - - case 'edituserprefs' : { - $page = new SpotPage_edituserprefs($db, $settings, $currentSession, - Array('edituserprefsform' => $req->getForm('edituserprefsform'), - 'userid' => $req->getDef('userid', ''), - 'data' => $req->getDef('data', array()), - 'dialogembedded' => $req->getDef('dialogembedded', 0))); - $page->render(); - break; - } # edituserprefs - - case 'editsecgroup' : { - $page = new SpotPage_editsecgroup($db, $settings, $currentSession, - Array('editsecgroupform' => $req->getForm('editsecgroupform'), - 'groupid' => $req->getDef('groupid', 0))); - $page->render(); - break; - } # editsecgroup - - case 'editfilter' : { - $page = new SpotPage_editfilter($db, $settings, $currentSession, - Array('editfilterform' => $req->getForm('editfilterform'), - 'orderfilterslist' => $req->getDef('orderfilterslist', array()), - 'search' => $req->getDef('search', array()), - 'sorton' => $req->getDef('sortby', ''), - 'sortorder' => $req->getDef('sortdir', ''), - 'filterid' => $req->getDef('filterid', 0), - 'data' => $req->getDef('data', array()))); - $page->render(); - break; - } # editfilter - - case 'edituser' : { - $page = new SpotPage_edituser($db, $settings, $currentSession, - Array('edituserform' => $req->getForm('edituserform'), - 'userid' => $req->getDef('userid', ''))); - $page->render(); - break; - } # edituser - - case 'login' : { - $page = new SpotPage_login($db, $settings, $currentSession, - Array('loginform' => $req->getForm('loginform'), - 'data' => $req->getDef('data', array()))); - $page->render(); - break; - } # login - - case 'postcomment' : { - $page = new SpotPage_postcomment($db, $settings, $currentSession, - Array('commentform' => $req->getForm('postcommentform'), - 'inreplyto' => $req->getDef('inreplyto', ''))); - $page->render(); - break; - } # postcomment - - case 'postspot' : { - $page = new SpotPage_postspot($db, $settings, $currentSession, - Array('spotform' => $req->getForm('newspotform'))); - $page->render(); - break; - } # postspot - - case 'reportpost' : { - $page = new SpotPage_reportpost($db, $settings, $currentSession, - Array ('reportform' => $req->getForm('postreportform'), - 'inreplyto' => $req->getDef('inreplyto', ''))); - $page->render(); - break; - } # reportpost - - case 'versioncheck' : { - $page = new SpotPage_versioncheck($db, $settings, $currentSession, array()); - $page->render(); - break; - } # versioncheck - - case 'blacklistspotter' : { - $page = new SpotPage_blacklistspotter($db, $settings, $currentSession, - Array ('blform' => $req->getForm('blacklistspotterform'))); - $page->render(); - break; - } # blacklistspotter - - case 'logout' : { - $page = new SpotPage_logout($db, $settings, $currentSession); - $page->render(); - break; - } # logout - - case 'sabapi' : { - $page = new SpotPage_sabapi($db, $settings, $currentSession); - $page->render(); - break; - } # sabapi - - case 'nzbhandlerapi' : { - $page = new SpotPage_nzbhandlerapi($db, $settings, $currentSession); - $page->render(); - break; - } # nzbhandlerapi - - case 'twitteroauth' : { - $page = new SpotPage_twitteroauth($db, $settings, $currentSession, - Array('action' => $req->getDef('action', ''), - 'pin' => $req->getDef('pin', ''))); - $page->render(); - break; - } # twitteroauth - - case 'statistics' : { - $page = new SpotPage_statistics($db, $settings, $currentSession, - Array('limit' => $req->getDef('limit', ''))); - $page->render(); - break; - } # statistics - - default : { - SpotTiming::start('renderpage->case-default'); - if (@$_SERVER['HTTP_X_PURPOSE'] == 'preview') { - $page = new SpotPage_getimage($db, $settings, $currentSession, - Array('messageid' => $req->getDef('messageid', ''), - 'image' => array('type' => 'speeddial'))); - } else { - $page = new SpotPage_index($db, $settings, $currentSession, - Array('search' => $req->getDef('search', $spotUserSystem->getIndexFilter($currentSession['user']['userid'])), - 'pagenr' => $req->getDef('pagenr', 0), - 'sortby' => $req->getDef('sortby', ''), - 'sortdir' => $req->getDef('sortdir', ''), - 'messageid' => $req->getDef('messageid', ''), - 'action' => $req->getDef('action', ''), - 'data' => $req->getDef('data', array())) - ); - } # if - SpotTiming::stop('renderpage->case-default'); - $page->render(); - break; - } # default - } # switch - SpotTiming::stop('renderpage'); - - # timing - SpotTiming::stop('total'); - - # enable of disable de timer - if (($settings->get('enable_timing')) && (!in_array($req->getDef('page', ''), array('catsjson', 'statics', 'getnzb', 'getnzbmobile', 'markallasread', 'rss', 'newznabapi')))) { - SpotTiming::display(); - } # if -} -catch(PermissionDeniedException $x) { - /* - * We try to render a permission denied error using the already created - * renderer first. We do this, so pages which are supposed to output - * XML, can also output their errors using XML. - * - * If no page is initiated just yet, we create an basic renderer object - * to render an error page - */ - if (! ($page instanceof SpotPage_Abs)) { - $page = new SpotPage_render($db, $settings, $currentSession, '', array()); - } # if - - $page->permissionDenied($x, $page, $req->getHttpReferer()); -} # PermissionDeniedException - -catch(InvalidOwnSettingsSettingException $x) { - echo "There is an error in your ownsettings.php

" . PHP_EOL; - echo nl2br($x->getMessage()); -} # InvalidOwnSettingsSettingException - -catch(OwnsettingsCreatedOutputException $x) { - echo "ownsettings.php or dbsettings.inc.php created output. Please make sure theese files do not contain a PHP closing tag ( ?> ) and no information before the PHP opening tag (
" . PHP_EOL; - echo nl2br($x->getMessage()); -} # OwnsettingsCreatedOutputException - -catch(SchemaNotUpgradedException $x) { - echo "Database schema has been changed. Please run 'upgrade-db.php' from an console window"; -} # SchemaNotUpgradedException - -catch(SecurityNotUpgradedException $x) { - echo "Spotweb contains updated security settings. Please run 'upgrade-db.php' from a console window"; -} # SecurityNotUpgradedException - -catch(SettingsNotUpgradedException $x) { - echo "Spotweb contains updated global settings settings. Please run 'upgrade-db.php' from a console window"; -} # SecurityNotUpgradedException - -catch(DatabaseConnectionException $x) { - echo "Unable to connect to database:
"; - echo nl2br($x->getMessage()) . PHP_EOL . '
'; - echo "

Please make sure your database server is up and running and your connection parameters are set
" . PHP_EOL; -} # DatabaseConnectionException - -catch(Exception $x) { - echo 'SpotWeb v' . SPOTWEB_VERSION . ' on PHP v' . PHP_VERSION . ' crashed' . PHP_EOL; - if ((isset($settings) && is_object($settings) && $settings->get('enable_stacktrace')) || (!isset($settings))) { - var_dump($x); - } # if - echo $x->getMessage(); -} # catch +boot(); + + # helper functions for passed variables + $page = $req->getDef('page', 'index'); + + # Retrieve the users object of the user which is logged on + SpotTiming::start('auth'); + $spotUserSystem = new SpotUserSystem($daoFactory, $settings); + if ($req->doesExist('apikey')) { + $currentSession = $spotUserSystem->verifyApi($req->getDef('apikey', '')); + } else { + $currentSession = $spotUserSystem->useOrStartSession(false); + } # if + + /* + * If three is no user object, we don't have a security system + * either. Without a security system we cannot boot, so fatal + */ + if ($currentSession === false) { + if ($req->doesExist('apikey')) { + $currentSession = $spotUserSystem->useOrStartSession(true); + + throw new PermissionDeniedException(SpotSecurity::spotsec_consume_api, 'invalid API key'); + } else { + throw new SqlErrorException("Unable to create session"); + } # else + } # if + SpotTiming::stop('auth'); + + /* + * And check if the security groups need updating + */ + if (!$currentSession['security']->securityValid()) { + throw new SecurityNotUpgradedException(); + } # if + + # User session has been loaded, let's translate the categories + if ($currentSession['user']['prefs']['user_language'] != 'en_US') { + SpotTranslation::initialize($currentSession['user']['prefs']['user_language']); + } # if + SpotCategories::startTranslation(); + + + /* + * Let the form handler know what userid we are using so + * we can make the CSRF cookie be user-bounded + */ + $req->setUserId($currentSession['user']['userid']); + + /* + * Only now it is safe to check wether the user is actually alowed + * to authenticate with an API key + */ + if ($req->doesExist('apikey')) { + /* + * To use the Spotweb API we need the actual permission + */ + $currentSession['security']->fatalPermCheck(SpotSecurity::spotsec_consume_api, ''); + + /* + * but we also need a specific permission, because else things could + * be automated which we simply do not want to be automated + */ + $currentSession['security']->fatalPermCheck(SpotSecurity::spotsec_consume_api, $page); + } # if + + SpotTiming::start('renderpage'); + switch($page) { + case 'render' : { + $page = new SpotPage_render($daoFactory, $settings, $currentSession, $req->getDef('tplname', ''), + Array('search' => $req->getDef('search', $spotUserSystem->getIndexFilter($currentSession['user']['userid'])), + 'data' => $req->getDef('data', array()), + 'messageid' => $req->getDef('messageid', ''), + 'pagenr' => $req->getDef('pagenr', 0), + 'perpage' => $req->getDef('perpage', 10), + 'sortby' => $req->getDef('sortby', ''), + 'sortdir' => $req->getDef('sortdir', ''))); + + $page->render(); + break; + } # render + + case 'getspot' : { + if (strpos($_SERVER['HTTP_USER_AGENT'], "SABnzbd+") === 0) { + $page = new SpotPage_getnzb($daoFactory, $settings, $currentSession, + Array('messageid' => $req->getDef('messageid', ''), + 'action' => $req->getDef('action', 'display'), + 'username' => $req->getDef('username', ''), + 'apikey' => $req->getDef('apikey', ''))); + } else { + $page = new SpotPage_getspot($daoFactory, $settings, $currentSession, $req->getDef('messageid', '')); + } # else + $page->render(); + break; + } # getspot + + case 'getnzb' : { + $page = new SpotPage_getnzb($daoFactory, $settings, $currentSession, + Array('messageid' => $req->getDef('messageid', ''), + 'action' => $req->getDef('action', 'display'), + 'username' => $req->getDef('username', ''), + 'apikey' => $req->getDef('apikey', ''))); + $page->render(); + break; + } + + case 'getnzbmobile' : { + $page = new SpotPage_getnzbmobile($daoFactory, $settings, $currentSession, + Array('messageid' => $req->getDef('messageid', ''), + 'action' => $req->getDef('action', 'display'))); + $page->render(); + break; + } # getnzbmobile + + case 'erasedls' : { + $page = new SpotPage_erasedls($daoFactory, $settings, $currentSession); + $page->render(); + break; + } # erasedls + + case 'catsjson' : { + $page = new SpotPage_catsjson( + $daoFactory, + $settings, + $currentSession, + Array('search' => $req->getDef('search', $spotUserSystem->getIndexFilter($currentSession['user']['userid'])), + 'subcatz' => $req->getDef('subcatz', '*'), + 'category' => $req->getDef('category', '*'), + 'rendertype' => $req->getDef('rendertype', 'tree'), + 'disallowstrongnot' => $req->getDef('disallowstrongnot', ''))); + $page->render(); + break; + } # getspot + + case 'markallasread' : { + $page = new SpotPage_markallasread($daoFactory, $settings, $currentSession); + $page->render(); + break; + } # markallasread + + case 'getimage' : { + $page = new SpotPage_getimage($daoFactory, $settings, $currentSession, + Array('messageid' => $req->getDef('messageid', ''), + 'image' => $req->getDef('image', Array()))); + $page->render(); + break; + } + case 'newznabapi' : { + $page = new SpotPage_newznabapi($daoFactory, $settings, $currentSession, + Array('t' => $req->getDef('t', ''), + 'messageid' => $req->getDef('id', ''), + 'apikey' => $req->getDef('apikey', ''), + 'q' => $req->getDef('q', ''), + 'limit' => $req->getDef('limit', ''), + 'cat' => $req->getDef('cat', ''), + 'imdbid' => $req->getDef('imdbid', ''), + 'artist' => $req->getDef('artist', ''), + 'rid' => $req->getDef('rid', ''), + 'season' => $req->getDef('season', ''), + 'ep' => $req->getDef('ep', ''), + 'o' => $req->getDef('o', ''), + 'extended' => $req->getDef('extended', ''), + 'maxage' => $req->getDef('maxage', ''), + 'offset' => $req->getDef('offset', ''), + 'del' => $req->getDef('del', '') + ) + ); + $page->render(); + break; + } # api + + case 'rss' : { + $page = new SpotPage_rss($daoFactory, $settings, $currentSession, + Array('search' => $req->getDef('search', $spotUserSystem->getIndexFilter($currentSession['user']['userid'])), + 'page' => $req->getDef('page', 0), + 'sortby' => $req->getDef('sortby', ''), + 'sortdir' => $req->getDef('sortdir', ''), + 'username' => $req->getDef('username', ''), + 'apikey' => $req->getDef('apikey', '')) + ); + $page->render(); + break; + } # rss + + case 'statics' : { + $page = new SpotPage_statics($daoFactory, $settings, $currentSession, + Array('type' => $req->getDef('type', ''))); + $page->render(); + break; + } # statics + + case 'createuser' : { + $page = new SpotPage_createuser($daoFactory, $settings, $currentSession, + Array('createuserform' => $req->getForm('createuserform'))); + $page->render(); + break; + } # createuser + + case 'editsettings' : { + $page = new SpotPage_editsettings($daoFactory, $settings, $currentSession, + Array('editsettingsform' => $req->getForm('editsettingsform'))); + $page->render(); + break; + } # editsettings + + case 'edituserprefs' : { + $page = new SpotPage_edituserprefs($daoFactory, $settings, $currentSession, + Array('edituserprefsform' => $req->getForm('edituserprefsform'), + 'userid' => $req->getDef('userid', ''), + 'data' => $req->getDef('data', array()), + 'dialogembedded' => $req->getDef('dialogembedded', 0))); + $page->render(); + break; + } # edituserprefs + + case 'editsecgroup' : { + $page = new SpotPage_editsecgroup($daoFactory, $settings, $currentSession, + Array('editsecgroupform' => $req->getForm('editsecgroupform'), + 'groupid' => $req->getDef('groupid', 0))); + $page->render(); + break; + } # editsecgroup + + case 'editfilter' : { + $page = new SpotPage_editfilter($daoFactory, $settings, $currentSession, + Array('editfilterform' => $req->getForm('editfilterform'), + 'orderfilterslist' => $req->getDef('orderfilterslist', array()), + 'search' => $req->getDef('search', array()), + 'sorton' => $req->getDef('sortby', ''), + 'sortorder' => $req->getDef('sortdir', ''), + 'filterid' => $req->getDef('filterid', 0), + 'data' => $req->getDef('data', array()))); + $page->render(); + break; + } # editfilter + + case 'edituser' : { + $page = new SpotPage_edituser($daoFactory, $settings, $currentSession, + Array('edituserform' => $req->getForm('edituserform'), + 'userid' => $req->getDef('userid', ''))); + $page->render(); + break; + } # edituser + + case 'login' : { + $page = new SpotPage_login($daoFactory, $settings, $currentSession, + Array('loginform' => $req->getForm('loginform'), + 'data' => $req->getDef('data', array()))); + $page->render(); + break; + } # login + + case 'postcomment' : { + $page = new SpotPage_postcomment($daoFactory, $settings, $currentSession, + Array('commentform' => $req->getForm('postcommentform'), + 'inreplyto' => $req->getDef('inreplyto', ''))); + $page->render(); + break; + } # postcomment + + case 'postspot' : { + $page = new SpotPage_postspot($daoFactory, $settings, $currentSession, + Array('spotform' => $req->getForm('newspotform'))); + $page->render(); + break; + } # postspot + + case 'reportpost' : { + $page = new SpotPage_reportpost($daoFactory, $settings, $currentSession, + Array ('reportform' => $req->getForm('postreportform'), + 'inreplyto' => $req->getDef('inreplyto', ''))); + $page->render(); + break; + } # reportpost + + case 'versioncheck' : { + $page = new SpotPage_versioncheck($daoFactory, $settings, $currentSession, array()); + $page->render(); + break; + } # versioncheck + + case 'blacklistspotter' : { + $page = new SpotPage_blacklistspotter($daoFactory, $settings, $currentSession, + Array ('blform' => $req->getForm('blacklistspotterform'))); + $page->render(); + break; + } # blacklistspotter + + case 'logout' : { + $page = new SpotPage_logout($daoFactory, $settings, $currentSession); + $page->render(); + break; + } # logout + + case 'sabapi' : { + $page = new SpotPage_sabapi($daoFactory, $settings, $currentSession); + $page->render(); + break; + } # sabapi + + case 'nzbhandlerapi' : { + $page = new SpotPage_nzbhandlerapi($daoFactory, $settings, $currentSession); + $page->render(); + break; + } # nzbhandlerapi + + case 'twitteroauth' : { + $page = new SpotPage_twitteroauth($daoFactory, $settings, $currentSession, + Array('action' => $req->getDef('action', ''), + 'pin' => $req->getDef('pin', ''))); + $page->render(); + break; + } # twitteroauth + + case 'statistics' : { + $page = new SpotPage_statistics($daoFactory, $settings, $currentSession, + Array('limit' => $req->getDef('limit', ''))); + $page->render(); + break; + } # statistics + + default : { + SpotTiming::start('renderpage->case-default'); + if (@$_SERVER['HTTP_X_PURPOSE'] == 'preview') { + $page = new SpotPage_getimage($daoFactory, $settings, $currentSession, + Array('messageid' => $req->getDef('messageid', ''), + 'image' => array('type' => 'speeddial'))); + } else { + $page = new SpotPage_index($daoFactory, $settings, $currentSession, + Array('search' => $req->getDef('search', $spotUserSystem->getIndexFilter($currentSession['user']['userid'])), + 'pagenr' => $req->getDef('pagenr', 0), + 'sortby' => $req->getDef('sortby', ''), + 'sortdir' => $req->getDef('sortdir', ''), + 'messageid' => $req->getDef('messageid', ''), + 'action' => $req->getDef('action', ''), + 'data' => $req->getDef('data', array())) + ); + } # if + SpotTiming::stop('renderpage->case-default'); + $page->render(); + break; + } # default + } # switch + SpotTiming::stop('renderpage'); + + # timing + SpotTiming::stop('total'); + + # enable of disable de timer + if (($settings->get('enable_timing')) && (!in_array($req->getDef('page', ''), array('catsjson', 'statics', 'getnzb', 'getnzbmobile', 'markallasread', 'rss', 'newznabapi')))) { + SpotTiming::display(); + } # if +} +catch(PermissionDeniedException $x) { + /* + * We try to render a permission denied error using the already created + * renderer first. We do this, so pages which are supposed to output + * XML, can also output their errors using XML. + * + * If no page is initiated just yet, we create an basic renderer object + * to render an error page + */ + if (! ($page instanceof SpotPage_Abs)) { + $page = new SpotPage_render($daoFactory, $settings, $currentSession, '', array()); + } # if + + $page->permissionDenied($x, $page, $req->getHttpReferer()); +} # PermissionDeniedException + +catch(InvalidOwnSettingsSettingException $x) { + echo "There is an error in your ownsettings.php

" . PHP_EOL; + echo nl2br($x->getMessage()); +} # InvalidOwnSettingsSettingException + +catch(OwnsettingsCreatedOutputException $x) { + echo "ownsettings.php or dbsettings.inc.php created output. Please make sure theese files do not contain a PHP closing tag ( ?> ) and no information before the PHP opening tag (
" . PHP_EOL; + echo nl2br($x->getMessage()); +} # OwnsettingsCreatedOutputException + +catch(SchemaNotUpgradedException $x) { + echo "Database schema has been changed. Please run 'upgrade-db.php' from an console window"; +} # SchemaNotUpgradedException + +catch(SecurityNotUpgradedException $x) { + echo "Spotweb contains updated security settings. Please run 'upgrade-db.php' from a console window"; +} # SecurityNotUpgradedException + +catch(SettingsNotUpgradedException $x) { + echo "Spotweb contains updated global settings settings. Please run 'upgrade-db.php' from a console window"; +} # SecurityNotUpgradedException + +catch(DatabaseConnectionException $x) { + echo "Unable to connect to database:
"; + echo nl2br($x->getMessage()) . PHP_EOL . '
'; + echo "

Please make sure your database server is up and running and your connection parameters are set
" . PHP_EOL; +} # DatabaseConnectionException + +catch(Exception $x) { + echo 'SpotWeb v' . SPOTWEB_VERSION . ' on PHP v' . PHP_VERSION . ' crashed' . PHP_EOL; + if ((isset($settings) && is_object($settings) && $settings->get('enable_stacktrace')) || (!isset($settings))) { + var_dump($x); + } # if + echo $x->getMessage(); +} # catch diff --git a/install.php b/install.php index f34f8bfa5..16f9b9ddc 100755 --- a/install.php +++ b/install.php @@ -95,7 +95,7 @@ function performAndPrintTests() { createPrivateKey($settings['openssl_cnf_path']); /* We need either one of those 3 extensions, so set the error flag manually */ @@ -517,7 +517,7 @@ function createSystem() { /* * Create a private/public key pair for this user */ - $spotSigning = Services_Signing_Base::newServiceSigning(); + $spotSigning = Services_Signing_Base::factory(); $userKey = $spotSigning->createPrivateKey($spotSettings->get('openssl_cnf_path')); $spotUser['publickey'] = $userKey['public']; $spotUser['privatekey'] = $userKey['private']; diff --git a/lib/Bootstrap.php b/lib/Bootstrap.php new file mode 100644 index 000000000..0083c0d91 --- /dev/null +++ b/lib/Bootstrap.php @@ -0,0 +1,168 @@ +getDaoFactory(); + $settings = $this->getSettings($daoFactory); + $spotReq = $this->getSpotReq($settings); + + /* + * Run the validation of the most basic systems + * in Spotweb + */ + $this->validate($settings); + + /* + * Disable the timing part as soon as possible because it + * gobbles memory + */ + if (!$settings->get('enable_timing')) { + SpotTiming::disable(); + } # if + + + return array($settings, $daoFactory, $spotReq); + } # boot + + + /* + * Returns the DAO factory used by all of + * Spotweb + */ + private function getDaoFactory() { + require "dbsettings.inc.php"; + + $dbCon = dbeng_abs::getDbFactory($dbsettings['engine']); + $dbCon->connect($dbsettings['host'], + $dbsettings['user'], + $dbsettings['pass'], + $dbsettings['dbname']); + + $daoFactory = Dao_Factory::getDAOFactory($dbsettings['engine']); + $daoFactory->setConnection($dbCon); + + return $daoFactory; + } # getDaoFactory + + /* + * Returns a sort of pre-flight check to see if + * everything is setup the way we like. + */ + private function validate(SpotSettings $settings) { + /* + * The basics has been setup, lets check if the schema needs + * updating + */ + if (!$settings->schemaValid()) { + throw new SchemaNotUpgradedException(); + } # if + + /* + * Does our global setting table need updating? + */ + if (!$settings->settingsValid()) { + throw new SettingsNotUpgradedException(); + } # if + + /* + * Because users are asked to modify ownsettings.php themselves, it is + * possible they create a mistake and accidentally create output from it. + * + * This output breaks a lot of stuff like download integration, image generation + * and more. + * + * We try to check if any output has been submitted, and if so, we refuse + * to continue to prevent all sorts of confusing bug reports + */ + if ((headers_sent()) || ((int) ob_get_length() > 0)) { + throw new OwnsettingsCreatedOutputException(); + } # if + } # validate + + /* + * Bootup the settings system + */ + private function getSettings(Dao_Factory $daoFactory) { + require_once "settings.php"; + return SpotSettings::singleton($daoFactory->getSettingDao(), $settings); + } # getSettings + + /* + * Initializes the NNTP access + */ + static public function createNntpEngine($type) { + /* + * Retrieve the NNTP header settings we can validate those + */ + $settings = Registry::get('settings'); + $settings_nntp_hdr = $settings->get('nntp_hdr'); + + /* + * Make sure we have a valid NNTP configuration + */ + if (empty($settings_nntp_hdr['host'])) { + throw new MissingNntpConfigurationException(); + } # if + + + switch ($type) { + case 'hdr' : return new Service_Nntp_Engine($settings_nntp_hdr); break; + case 'nzb' : { + $settings_nntp_bin = $settings->get('nntp_nzb'); + if (empty($settings_nntp_nzb['host'])) { + return Registry::get('nntp_hdr'); + } else { + return new Service_Nntp_Engine($settings_nntp_nzb); + } # else + } # nzb + + case 'post' : { + $settings_nntp_post = $settings->get('nntp_post'); + if (empty($settings_nntp_post['host'])) { + return Registry::get('nntp_hdr'); + } else { + return new Service_Nntp_Engine($settings_nntp_post); + } # else + } # post + + default : throw new Exception("Unknown NNTP type engine (" . $type . ") for registry creation"); + } # switch + } # initNntpAccess + + /* + * Instantiate an Request object + */ + private function getSpotReq(SpotSettings $settings) { + $req = new SpotReq(); + $req->initialize($settings); + + return $req; + } # getSpotReq + +} # Bootstrap + diff --git a/lib/SpotAudit.php b/lib/SpotAudit.php index 8dcc15f7a..5df16ba14 100755 --- a/lib/SpotAudit.php +++ b/lib/SpotAudit.php @@ -1,19 +1,19 @@ -_db = $db; - $this->_user = $user; - $this->_settings = $settings; - $this->_ipaddr = $ipaddr; - } # ctor - - function audit($perm, $objectid, $allowed) { - $this->_db->addAuditEntry($this->_user['userid'], $perm, $objectid, $allowed, $this->_ipaddr); - } # audit - -} # class SpotAudit +_auditDao = $auditDao; + $this->_user = $user; + $this->_settings = $settings; + $this->_ipaddr = $ipaddr; + } # ctor + + function audit($perm, $objectid, $allowed) { + $this->_auditDao->addAuditEntry($this->_user['userid'], $perm, $objectid, $allowed, $this->_ipaddr); + } # audit + +} # class SpotAudit diff --git a/lib/SpotClassAutoload.php b/lib/SpotClassAutoload.php index 724e39b74..6c86de2b6 100755 --- a/lib/SpotClassAutoload.php +++ b/lib/SpotClassAutoload.php @@ -66,6 +66,11 @@ function __autoload($class_name) { return ; } # if + if ($class_name == 'Registry') { + require_once "vendor/Lim_Registry/Registry.php"; + return ; + } # if + require_once 'lib/' . $class_name . '.php'; } # default } # switch diff --git a/lib/SpotDb.php b/lib/SpotDb.php index 12f1d8511..c1655d635 100755 --- a/lib/SpotDb.php +++ b/lib/SpotDb.php @@ -1,5 +1,4 @@ _dbsettings = $db; - } # __ctor - - - /* - * Open connectie naar de database (basically factory), de 'engine' wordt uit de - * settings gehaald die mee worden gegeven in de ctor. - */ - function connect() { - SpotTiming::start(__FUNCTION__); - - $dbCon = dbeng_abs::getDbFactory($this->_dbsettings['engine']);; - $daoFactory = Dao_Factory::getDAOFactory($this->_dbsettings['engine']); + function __construct(Dao_Factory $daoFactory) { + $this->_daoFactory = $daoFactory; - $daoFactory->setConnection($dbCon); $this->_auditDao = $daoFactory->getAuditDao(); $this->_blackWhiteListDao = $daoFactory->getBlackWhiteListDao(); $this->_cacheDao = $daoFactory->getCacheDao(); @@ -50,31 +36,32 @@ function connect() { $this->_sessionDao = $daoFactory->getSessionDao(); $this->_settingDao = $daoFactory->getSettingDao(); $this->_spotReportDao = $daoFactory->getSpotReportDao(); - $this->_userFilterCountDao = $daoFactory->getUserFilterCountDao(); $this->_userFilterDao = $daoFactory->getUserFilterDao(); + $this->_userFilterCountDao = $daoFactory->getUserFilterCountDao(); $this->_userDao = $daoFactory->getUserDao(); - $this->_spotDao = $daoFactory->getSpotdao(); + $this->_spotDao = $daoFactory->getSpotDao(); $this->_spotStateListDao = $daoFactory->getSpotStateListDao(); $this->_nntpConfigDao = $daoFactory->getNntpConfigDao(); + } # __ctor + - $dbCon->connect($this->_dbsettings['host'], - $this->_dbsettings['user'], - $this->_dbsettings['pass'], - $this->_dbsettings['dbname']); - $this->_conn = $dbCon; - SpotTiming::stop(__FUNCTION__); + /* + * Open connectie naar de database (basically factory), de 'engine' wordt uit de + * settings gehaald die mee worden gegeven in de ctor. + */ + function connect() { } # connect /* * Geeft het database connectie object terug */ function getDbHandle() { - return $this->_conn; + return $this->_daoFactory->getConnection(); } # getDbHandle function safe($x) { - return $this->_conn->safe($x); + return $this->_daoFactory->getConnection()->safe($x); } /* --------------------------- */ diff --git a/lib/SpotNotifications.php b/lib/SpotNotifications.php index bd0cfe1f6..82f7c98fb 100755 --- a/lib/SpotNotifications.php +++ b/lib/SpotNotifications.php @@ -1,231 +1,231 @@ -_db = $db; - $this->_settings = $settings; - $this->_currentSession = $currentSession; - $this->_spotSec = $currentSession['security']; - $this->_notificationTemplate = new SpotNotificationTemplate($this->_db, $this->_settings, $this->_currentSession); - } # ctor - - function register() { - if ($this->_spotSec->allowed(SpotSecurity::spotsec_send_notifications_services, '')) { - # Boxcar heeft extra settings nodig - $this->_currentSession['user']['prefs']['notifications']['boxcar']['api_key'] = $this->_settings->get('boxcar_api_key'); - $this->_currentSession['user']['prefs']['notifications']['boxcar']['api_secret'] = $this->_settings->get('boxcar_api_secret'); - - $notifProviders = Notifications_Factory::getActiveServices(); - foreach ($notifProviders as $notifProvider) { - if ($this->_currentSession['user']['prefs']['notifications'][$notifProvider]['enabled']) { - if ($this->_spotSec->allowed(SpotSecurity::spotsec_send_notifications_services, $notifProvider)) { - $this->_notificationServices[$notifProvider] = Notifications_Factory::build('Spotweb', $notifProvider, $this->_currentSession['user']['prefs']['notifications'][$notifProvider]); - } # if - } # if - } # foreach - } # if - - foreach($this->_notificationServices as $notificationService) { - $notificationService->register(); - } # foreach - } # register - - function sendWatchlistHandled($action, $messageid) { - $spot = $this->_db->getSpotHeader($messageid); - switch ($action) { - case 'remove' : $notification = $this->_notificationTemplate->template('watchlist_removed', array('spot' => $spot)); break; - case 'add' : $notification = $this->_notificationTemplate->template('watchlist_added', array('spot' => $spot)); break; - } # switch - $this->newSingleMessage($this->_currentSession, SpotNotifications::notifytype_watchlist_handled, 'Single', $notification); - } # sendWatchlistHandled - - function sendNzbHandled($action, $spot) { - switch ($action) { - case 'save' : $notification = $this->_notificationTemplate->template('nzb_save', array('spot' => $spot, 'nzbhandling' => $this->_currentSession['user']['prefs']['nzbhandling'])); break; - case 'runcommand' : $notification = $this->_notificationTemplate->template('nzb_runcommand', array('spot' => $spot, 'nzbhandling' => $this->_currentSession['user']['prefs']['nzbhandling'])); break; - case 'push-sabnzbd' : - case 'client-sabnzbd' : $notification = $this->_notificationTemplate->template('nzb_sabnzbd', array('spot' => $spot)); break; - case 'nzbget' : $notification = $this->_notificationTemplate->template('nzb_nzbget', array('spot' => $spot)); break; - default : return; - } # switch - - $this->newSingleMessage($this->_currentSession, SpotNotifications::notifytype_nzb_handled, 'Single', $notification); - } # sendNzbHandled - - function sendNewSpotsForFilter($userId, $filterTitle, $newSpotCount) { - $notification = $this->_notificationTemplate->template('newspots_for_filter', array('filtertitle' => $filterTitle, 'newCount' => $newSpotCount)); - -echo 'Sending notification to user: ' . $userId . ' for filter: ' . $filterTitle . ', it has ' . $newSpotCount . ' new spots' . PHP_EOL; - - /* and send the message */ - $user = array('user' => array('userid' => $userId), - 'session' => array('ipaddr' => '127.0.0.1')); - $this->newSingleMessage($user, SpotNotifications::notifytype_newspots_for_filter, 'Single', $notification); - } # sendNewSpotsForFilter - - function sendRetrieverFinished($newSpotCount, $newCommentCount, $newReportCount) { - if ($newSpotCount > 0) { - $notification = $this->_notificationTemplate->template('retriever_finished', array('newSpotCount' => $newSpotCount, 'newCommentCount' => $newCommentCount, 'newReportCount' => $newReportCount)); - $this->newMultiMessage(SpotNotifications::notifytype_retriever_finished, $notification); - } # if - } # sendRetrieverFinished - - function sendReportPosted($messageid) { - # haal de spot op - $spot = $this->_db->getSpotHeader($messageid); - - $notification = $this->_notificationTemplate->template('report_posted', array('spot' => $spot)); - $this->newSingleMessage($this->_currentSession, SpotNotifications::notifytype_report_posted, 'Single', $notification); - } # sendReportPosted - - function sendSpotPosted($spot) { - $notification = $this->_notificationTemplate->template('spot_posted', array('spot' => $spot)); - $this->newSingleMessage($this->_currentSession, SpotNotifications::notifytype_spot_posted, 'Single', $notification); - } # sendSpotPosted - - function sendUserAdded($username, $password) { - $notification = $this->_notificationTemplate->template('user_added', array('username' => $username, 'password' => $password)); - $this->newMultiMessage(SpotNotifications::notifytype_user_added, $notification); - } # sendUserAdded - - function sendNewUserMail($user) { - # Omdat het versturen van dit bericht expliciet is opgegeven, worden er - # geen security-checks gedaan voor de ontvanger. - if ($this->_spotSec->allowed(SpotSecurity::spotsec_send_notifications_services, 'welcomemail')) { - $notification = $this->_notificationTemplate->template('user_added_email', array('user' => $user, 'adminUser' => $this->_currentSession['user'])); - - $user['prefs']['notifications']['email']['sender'] = $this->_settings->get('systemfrommail'); - $user['prefs']['notifications']['email']['receiver'] = $user['mail']; - $this->_notificationServices['email'] = Notifications_Factory::build('Spotweb', 'email', $user['prefs']['notifications']['email']); - $this->_notificationServices['email']->sendMessage('Single', $notification['title'], implode(PHP_EOL, $notification['body']), $this->_settings->get('spotweburl')); - $this->_notificationServices = array(); - } # if - } # sendNewUserMail - - function newSingleMessage($user, $objectId, $type, $notification) { - # Aangezien het niet zeker kunnen zijn als welke user we dit stuk - # code uitvoeren, halen we voor de zekerheid opnieuw het user record op - $tmpUser['user'] = $this->_db->getUser($user['user']['userid']); - $tmpUser['security'] = new SpotSecurity($this->_db, $this->_settings, $tmpUser['user'], $user['session']['ipaddr']); - $this->_spotSecTmp = $tmpUser['security']; - - if ($this->_spotSecTmp->allowed(SpotSecurity::spotsec_send_notifications_services, '')) { - $notifProviders = Notifications_Factory::getActiveServices(); - foreach ($notifProviders as $notifProvider) { - if ($tmpUser['user']['prefs']['notifications'][$notifProvider]['enabled'] && $tmpUser['user']['prefs']['notifications'][$notifProvider]['events'][$objectId]) { - if ($this->_spotSecTmp->allowed(SpotSecurity::spotsec_send_notifications_types, '') && - $this->_spotSecTmp->allowed(SpotSecurity::spotsec_send_notifications_types, $objectId) && - $this->_spotSecTmp->allowed(SpotSecurity::spotsec_send_notifications_services, $notifProvider) - ) { - $this->_db->addNewNotification($tmpUser['user']['userid'], $objectId, $type, $notification['title'], implode(PHP_EOL, $notification['body'])); - break; - } # if - } # if - } # foreach - } # if - - if ($type == 'Single') { - $this->sendNowOrLater($tmpUser['user']['userid']); - } # if - } # newSingleMessage - - function newMultiMessage($objectId, $notification) { - $userArray = $this->_db->getUserList(); - foreach ($userArray as $user['user']) { - # Create a fake session array - $user['session'] = array('ipaddr' => ''); - - $this->newSingleMessage($user, $objectId, 'Multi', $notification); - } # foreach - - $this->sendNowOrLater(0); - } # newMultiMessage - - function sendNowOrLater($userId) { - # TODO: optioneel maken of berichten direct worden verstuurd of via cron - # Tot die tijd versturen we ze direct - $this->sendMessages($userId); - } # sendNowOrLater - - function sendMessages($userId) { - if ($userId == 0) { - $userList = $this->_db->getUserList(); - } else { - $thisUser = $this->_db->getUser($userId); - $userList = array($thisUser); - } # else - - foreach ($userList as $user) { - # Omdat we vanuit getUserList() niet alle velden meekrijgen - # vragen we opnieuw het user record op - $user = $this->_db->getUser($user['userid']); - $security = new SpotSecurity($this->_db, $this->_settings, $user, ''); - - # Om e-mail te kunnen versturen hebben we iets meer data nodig - $user['prefs']['notifications']['email']['sender'] = $this->_settings->get('systemfrommail'); - $user['prefs']['notifications']['email']['receiver'] = $user['mail']; - - # Twitter heeft ook extra settings nodig - $user['prefs']['notifications']['twitter']['consumer_key'] = $this->_settings->get('twitter_consumer_key'); - $user['prefs']['notifications']['twitter']['consumer_secret'] = $this->_settings->get('twitter_consumer_secret'); - - # Evenals Boxcar - $user['prefs']['notifications']['boxcar']['api_key'] = $this->_settings->get('boxcar_api_key'); - $user['prefs']['notifications']['boxcar']['api_secret'] = $this->_settings->get('boxcar_api_secret'); - - $newMessages = $this->_db->getUnsentNotifications($user['userid']); - foreach ($newMessages as $newMessage) { - $objectId = $newMessage['objectid']; - $spotweburl = ($this->_settings->get('spotweburl') == 'http://mijnuniekeservernaam/spotweb/') ? '' : $this->_settings->get('spotweburl'); - - $notifProviders = Notifications_Factory::getActiveServices(); - foreach ($notifProviders as $notifProvider) { - if ($user['prefs']['notifications'][$notifProvider]['enabled'] && $user['prefs']['notifications'][$notifProvider]['events'][$objectId]) { - if ($security->allowed(SpotSecurity::spotsec_send_notifications_services, $notifProvider)) { - $this->_notificationServices[$notifProvider] = Notifications_Factory::build('Spotweb', $notifProvider, $user['prefs']['notifications'][$notifProvider]); - } # if - } # if - } # foreach - - # nu wordt het bericht pas echt verzonden - foreach($this->_notificationServices as $notificationService) { - $notificationService->sendMessage($newMessage['type'], utf8_decode($newMessage['title']), utf8_decode($newMessage['body']), $spotweburl); - } # foreach - - # Alle services resetten, deze mogen niet hergebruikt worden - $this->_notificationServices = array(); - - # Als dit bericht ging over het aanmaken van een nieuwe user, verwijderen we - # het plaintext wachtwoord uit de database uit veiligheidsoverwegingen. - if ($objectId == SpotNotifications::notifytype_user_added) { - $body = explode(" ", $newMessage['body']); - $body[4] = '[deleted]'; - $newMessage['body'] = implode(" ", $body); - } # if - - $newMessage['sent'] = true; - $this->_db->updateNotification($newMessage); - } # foreach message - } # foreach user - } # sendMessages - -} # SpotsNotifications - +_db = new SpotDb($daoFactory); + $this->_settings = $settings; + $this->_currentSession = $currentSession; + $this->_spotSec = $currentSession['security']; + $this->_notificationTemplate = new SpotNotificationTemplate($this->_db, $this->_settings, $this->_currentSession); + } # ctor + + function register() { + if ($this->_spotSec->allowed(SpotSecurity::spotsec_send_notifications_services, '')) { + # Boxcar heeft extra settings nodig + $this->_currentSession['user']['prefs']['notifications']['boxcar']['api_key'] = $this->_settings->get('boxcar_api_key'); + $this->_currentSession['user']['prefs']['notifications']['boxcar']['api_secret'] = $this->_settings->get('boxcar_api_secret'); + + $notifProviders = Notifications_Factory::getActiveServices(); + foreach ($notifProviders as $notifProvider) { + if ($this->_currentSession['user']['prefs']['notifications'][$notifProvider]['enabled']) { + if ($this->_spotSec->allowed(SpotSecurity::spotsec_send_notifications_services, $notifProvider)) { + $this->_notificationServices[$notifProvider] = Notifications_Factory::build('Spotweb', $notifProvider, $this->_currentSession['user']['prefs']['notifications'][$notifProvider]); + } # if + } # if + } # foreach + } # if + + foreach($this->_notificationServices as $notificationService) { + $notificationService->register(); + } # foreach + } # register + + function sendWatchlistHandled($action, $messageid) { + $spot = $this->_db->getSpotHeader($messageid); + switch ($action) { + case 'remove' : $notification = $this->_notificationTemplate->template('watchlist_removed', array('spot' => $spot)); break; + case 'add' : $notification = $this->_notificationTemplate->template('watchlist_added', array('spot' => $spot)); break; + } # switch + $this->newSingleMessage($this->_currentSession, SpotNotifications::notifytype_watchlist_handled, 'Single', $notification); + } # sendWatchlistHandled + + function sendNzbHandled($action, $spot) { + switch ($action) { + case 'save' : $notification = $this->_notificationTemplate->template('nzb_save', array('spot' => $spot, 'nzbhandling' => $this->_currentSession['user']['prefs']['nzbhandling'])); break; + case 'runcommand' : $notification = $this->_notificationTemplate->template('nzb_runcommand', array('spot' => $spot, 'nzbhandling' => $this->_currentSession['user']['prefs']['nzbhandling'])); break; + case 'push-sabnzbd' : + case 'client-sabnzbd' : $notification = $this->_notificationTemplate->template('nzb_sabnzbd', array('spot' => $spot)); break; + case 'nzbget' : $notification = $this->_notificationTemplate->template('nzb_nzbget', array('spot' => $spot)); break; + default : return; + } # switch + + $this->newSingleMessage($this->_currentSession, SpotNotifications::notifytype_nzb_handled, 'Single', $notification); + } # sendNzbHandled + + function sendNewSpotsForFilter($userId, $filterTitle, $newSpotCount) { + $notification = $this->_notificationTemplate->template('newspots_for_filter', array('filtertitle' => $filterTitle, 'newCount' => $newSpotCount)); + +echo 'Sending notification to user: ' . $userId . ' for filter: ' . $filterTitle . ', it has ' . $newSpotCount . ' new spots' . PHP_EOL; + + /* and send the message */ + $user = array('user' => array('userid' => $userId), + 'session' => array('ipaddr' => '127.0.0.1')); + $this->newSingleMessage($user, SpotNotifications::notifytype_newspots_for_filter, 'Single', $notification); + } # sendNewSpotsForFilter + + function sendRetrieverFinished($newSpotCount, $newCommentCount, $newReportCount) { + if ($newSpotCount > 0) { + $notification = $this->_notificationTemplate->template('retriever_finished', array('newSpotCount' => $newSpotCount, 'newCommentCount' => $newCommentCount, 'newReportCount' => $newReportCount)); + $this->newMultiMessage(SpotNotifications::notifytype_retriever_finished, $notification); + } # if + } # sendRetrieverFinished + + function sendReportPosted($messageid) { + # haal de spot op + $spot = $this->_db->getSpotHeader($messageid); + + $notification = $this->_notificationTemplate->template('report_posted', array('spot' => $spot)); + $this->newSingleMessage($this->_currentSession, SpotNotifications::notifytype_report_posted, 'Single', $notification); + } # sendReportPosted + + function sendSpotPosted($spot) { + $notification = $this->_notificationTemplate->template('spot_posted', array('spot' => $spot)); + $this->newSingleMessage($this->_currentSession, SpotNotifications::notifytype_spot_posted, 'Single', $notification); + } # sendSpotPosted + + function sendUserAdded($username, $password) { + $notification = $this->_notificationTemplate->template('user_added', array('username' => $username, 'password' => $password)); + $this->newMultiMessage(SpotNotifications::notifytype_user_added, $notification); + } # sendUserAdded + + function sendNewUserMail($user) { + # Omdat het versturen van dit bericht expliciet is opgegeven, worden er + # geen security-checks gedaan voor de ontvanger. + if ($this->_spotSec->allowed(SpotSecurity::spotsec_send_notifications_services, 'welcomemail')) { + $notification = $this->_notificationTemplate->template('user_added_email', array('user' => $user, 'adminUser' => $this->_currentSession['user'])); + + $user['prefs']['notifications']['email']['sender'] = $this->_settings->get('systemfrommail'); + $user['prefs']['notifications']['email']['receiver'] = $user['mail']; + $this->_notificationServices['email'] = Notifications_Factory::build('Spotweb', 'email', $user['prefs']['notifications']['email']); + $this->_notificationServices['email']->sendMessage('Single', $notification['title'], implode(PHP_EOL, $notification['body']), $this->_settings->get('spotweburl')); + $this->_notificationServices = array(); + } # if + } # sendNewUserMail + + function newSingleMessage($user, $objectId, $type, $notification) { + # Aangezien het niet zeker kunnen zijn als welke user we dit stuk + # code uitvoeren, halen we voor de zekerheid opnieuw het user record op + $tmpUser['user'] = $this->_db->getUser($user['user']['userid']); + $tmpUser['security'] = new SpotSecurity($this->_db, $this->_settings, $tmpUser['user'], $user['session']['ipaddr']); + $this->_spotSecTmp = $tmpUser['security']; + + if ($this->_spotSecTmp->allowed(SpotSecurity::spotsec_send_notifications_services, '')) { + $notifProviders = Notifications_Factory::getActiveServices(); + foreach ($notifProviders as $notifProvider) { + if ($tmpUser['user']['prefs']['notifications'][$notifProvider]['enabled'] && $tmpUser['user']['prefs']['notifications'][$notifProvider]['events'][$objectId]) { + if ($this->_spotSecTmp->allowed(SpotSecurity::spotsec_send_notifications_types, '') && + $this->_spotSecTmp->allowed(SpotSecurity::spotsec_send_notifications_types, $objectId) && + $this->_spotSecTmp->allowed(SpotSecurity::spotsec_send_notifications_services, $notifProvider) + ) { + $this->_db->addNewNotification($tmpUser['user']['userid'], $objectId, $type, $notification['title'], implode(PHP_EOL, $notification['body'])); + break; + } # if + } # if + } # foreach + } # if + + if ($type == 'Single') { + $this->sendNowOrLater($tmpUser['user']['userid']); + } # if + } # newSingleMessage + + function newMultiMessage($objectId, $notification) { + $userArray = $this->_db->getUserList(); + foreach ($userArray as $user['user']) { + # Create a fake session array + $user['session'] = array('ipaddr' => ''); + + $this->newSingleMessage($user, $objectId, 'Multi', $notification); + } # foreach + + $this->sendNowOrLater(0); + } # newMultiMessage + + function sendNowOrLater($userId) { + # TODO: optioneel maken of berichten direct worden verstuurd of via cron + # Tot die tijd versturen we ze direct + $this->sendMessages($userId); + } # sendNowOrLater + + function sendMessages($userId) { + if ($userId == 0) { + $userList = $this->_db->getUserList(); + } else { + $thisUser = $this->_db->getUser($userId); + $userList = array($thisUser); + } # else + + foreach ($userList as $user) { + # Omdat we vanuit getUserList() niet alle velden meekrijgen + # vragen we opnieuw het user record op + $user = $this->_db->getUser($user['userid']); + $security = new SpotSecurity($this->_db, $this->_settings, $user, ''); + + # Om e-mail te kunnen versturen hebben we iets meer data nodig + $user['prefs']['notifications']['email']['sender'] = $this->_settings->get('systemfrommail'); + $user['prefs']['notifications']['email']['receiver'] = $user['mail']; + + # Twitter heeft ook extra settings nodig + $user['prefs']['notifications']['twitter']['consumer_key'] = $this->_settings->get('twitter_consumer_key'); + $user['prefs']['notifications']['twitter']['consumer_secret'] = $this->_settings->get('twitter_consumer_secret'); + + # Evenals Boxcar + $user['prefs']['notifications']['boxcar']['api_key'] = $this->_settings->get('boxcar_api_key'); + $user['prefs']['notifications']['boxcar']['api_secret'] = $this->_settings->get('boxcar_api_secret'); + + $newMessages = $this->_db->getUnsentNotifications($user['userid']); + foreach ($newMessages as $newMessage) { + $objectId = $newMessage['objectid']; + $spotweburl = ($this->_settings->get('spotweburl') == 'http://mijnuniekeservernaam/spotweb/') ? '' : $this->_settings->get('spotweburl'); + + $notifProviders = Notifications_Factory::getActiveServices(); + foreach ($notifProviders as $notifProvider) { + if ($user['prefs']['notifications'][$notifProvider]['enabled'] && $user['prefs']['notifications'][$notifProvider]['events'][$objectId]) { + if ($security->allowed(SpotSecurity::spotsec_send_notifications_services, $notifProvider)) { + $this->_notificationServices[$notifProvider] = Notifications_Factory::build('Spotweb', $notifProvider, $user['prefs']['notifications'][$notifProvider]); + } # if + } # if + } # foreach + + # nu wordt het bericht pas echt verzonden + foreach($this->_notificationServices as $notificationService) { + $notificationService->sendMessage($newMessage['type'], utf8_decode($newMessage['title']), utf8_decode($newMessage['body']), $spotweburl); + } # foreach + + # Alle services resetten, deze mogen niet hergebruikt worden + $this->_notificationServices = array(); + + # Als dit bericht ging over het aanmaken van een nieuwe user, verwijderen we + # het plaintext wachtwoord uit de database uit veiligheidsoverwegingen. + if ($objectId == SpotNotifications::notifytype_user_added) { + $body = explode(" ", $newMessage['body']); + $body[4] = '[deleted]'; + $newMessage['body'] = implode(" ", $body); + } # if + + $newMessage['sent'] = true; + $this->_db->updateNotification($newMessage); + } # foreach message + } # foreach user + } # sendMessages + +} # SpotsNotifications + diff --git a/lib/SpotSecurity.php b/lib/SpotSecurity.php index d30aa3444..1a6fd6512 100755 --- a/lib/SpotSecurity.php +++ b/lib/SpotSecurity.php @@ -1,167 +1,166 @@ - "Display overview of spots", - 1 => "Log in", - 2 => "Perform a search", - 3 => "View spot in detail", - 4 => "Retrieve NZB file", - 5 => "Download manager integration", - 6 => "Mark spots as read", - 7 => "View image of spot", - 8 => "RSS feed", - 9 => "Static resources", - 10 => "Create new user", - 11 => "Change own preferences", - 12 => "Change own user settings", - 13 => "List all users", - 14 => "Post comments to a spot", - 15 => "Log out", - 16 => "Use downloads manager API ", - 17 => "Keep watchlist", - 18 => "Keep downloadlist", - 19 => "Keep seenlist", - 20 => "Show new spotcount in list of filters", - 21 => "Display Retrieve new spots button", - 22 => "Display comments of a spot", - 23 => "Let user choose their template", - 24 => "Use Spotweb using an API key", - 25 => "Change other users", - 26 => "Display total amount of spots", - 27 => "Delete users", - 28 => "Change users' group membeship", - 29 => "Display users' group membership", - 30 => "Change security groups", - 31 => "Send notifications (per service)", - 32 => "Send notifications (per type)", - 33 => "Let users create their own CSS", - 34 => "Create own Spot filters", - 35 => "Set a set of filters as default for new users", - 36 => "Report a spot as spam", - 37 => "Post a new spot", - 38 => "Blacklist a spotter", - 39 => "Display statistics", - 40 => "Display Spotweb's changelog", - 41 => "Change settings" - ); - - /* - * Audit levels - */ - const spot_secaudit_none = 0; - const spot_secaudit_failure = 1; - const spot_secaudit_all = 2; - - function __construct(SpotDb $db, SpotSettings $settings, array $user, $ipaddr) { - $this->_db = $db; - $this->_user = $user; - $this->_settings = $settings; - $this->_failAudit = ($settings->get('auditlevel') == SpotSecurity::spot_secaudit_failure); - $this->_allAudit = ($settings->get('auditlevel') == SpotSecurity::spot_secaudit_all); - - if (($this->_failAudit) || ($this->_allAudit)) { - $this->_spotAudit = new SpotAudit($db, $settings, $user, $ipaddr); - } # if - - $this->_permissions = $db->getPermissions($user['userid']); - } # ctor - - function allowed($perm, $object) { - $allowed = isset($this->_permissions[$perm][$object]) && $this->_permissions[$perm][$object]; - - # We check for auditing in SpotSecurity to prevent the overhead - # of a function call for each security check - if (($this->_allAudit) || ((!$allowed) && ($this->_failAudit))) { - $this->_spotAudit->audit($perm, $object, $allowed); - } # if - - return $allowed; - } # allowed - - function fatalPermCheck($perm, $object) { - if (!$this->allowed($perm, $object)) { - throw new PermissionDeniedException($perm, $object); - } # if - } # fatalPermCheck - - function toHuman($perm) { - return $this->_secHumanReadable[$perm]; - } # toHuman - - function getAllPermissions() { - return $this->_secHumanReadable; - } # getAllPermissions - - function securityValid() { - # SPOTWEB_SECURITY_VERSION is gedefinieerd bovenin dit bestand - return ($this->_settings->get('securityversion') == SPOTWEB_SECURITY_VERSION); - } # securityValid - -} # class SpotSecurity + "Display overview of spots", + 1 => "Log in", + 2 => "Perform a search", + 3 => "View spot in detail", + 4 => "Retrieve NZB file", + 5 => "Download manager integration", + 6 => "Mark spots as read", + 7 => "View image of spot", + 8 => "RSS feed", + 9 => "Static resources", + 10 => "Create new user", + 11 => "Change own preferences", + 12 => "Change own user settings", + 13 => "List all users", + 14 => "Post comments to a spot", + 15 => "Log out", + 16 => "Use downloads manager API ", + 17 => "Keep watchlist", + 18 => "Keep downloadlist", + 19 => "Keep seenlist", + 20 => "Show new spotcount in list of filters", + 21 => "Display Retrieve new spots button", + 22 => "Display comments of a spot", + 23 => "Let user choose their template", + 24 => "Use Spotweb using an API key", + 25 => "Change other users", + 26 => "Display total amount of spots", + 27 => "Delete users", + 28 => "Change users' group membeship", + 29 => "Display users' group membership", + 30 => "Change security groups", + 31 => "Send notifications (per service)", + 32 => "Send notifications (per type)", + 33 => "Let users create their own CSS", + 34 => "Create own Spot filters", + 35 => "Set a set of filters as default for new users", + 36 => "Report a spot as spam", + 37 => "Post a new spot", + 38 => "Blacklist a spotter", + 39 => "Display statistics", + 40 => "Display Spotweb's changelog", + 41 => "Change settings" + ); + + /* + * Audit levels + */ + const spot_secaudit_none = 0; + const spot_secaudit_failure = 1; + const spot_secaudit_all = 2; + + function __construct(Dao_User $userDao, Dao_Audit $auditDao, SpotSettings $settings, array $user, $ipaddr) { + $this->_userDao = $userDao; + $this->_user = $user; + $this->_settings = $settings; + $this->_failAudit = ($settings->get('auditlevel') == SpotSecurity::spot_secaudit_failure); + $this->_allAudit = ($settings->get('auditlevel') == SpotSecurity::spot_secaudit_all); + + if (($this->_failAudit) || ($this->_allAudit)) { + $this->_spotAudit = new SpotAudit($auditDao, $settings, $user, $ipaddr); + } # if + + $this->_permissions = $userDao->getPermissions($user['userid']); + } # ctor + + function allowed($perm, $object) { + $allowed = isset($this->_permissions[$perm][$object]) && $this->_permissions[$perm][$object]; + + # We check for auditing in SpotSecurity to prevent the overhead + # of a function call for each security check + if (($this->_allAudit) || ((!$allowed) && ($this->_failAudit))) { + $this->_spotAudit->audit($perm, $object, $allowed); + } # if + + return $allowed; + } # allowed + + function fatalPermCheck($perm, $object) { + if (!$this->allowed($perm, $object)) { + throw new PermissionDeniedException($perm, $object); + } # if + } # fatalPermCheck + + function toHuman($perm) { + return $this->_secHumanReadable[$perm]; + } # toHuman + + function getAllPermissions() { + return $this->_secHumanReadable; + } # getAllPermissions + + function securityValid() { + # SPOTWEB_SECURITY_VERSION is gedefinieerd bovenin dit bestand + return ($this->_settings->get('securityversion') == SPOTWEB_SECURITY_VERSION); + } # securityValid + +} # class SpotSecurity diff --git a/lib/SpotSettings.php b/lib/SpotSettings.php index ce7a76402..1b2f1cd47 100755 --- a/lib/SpotSettings.php +++ b/lib/SpotSettings.php @@ -1,253 +1,251 @@ -getAllSettings(); - - # en merge de settings met degene die we door krijgen - self::$_settings = array_merge(self::$_dbSettings, self::$_phpSettings); - - # Override NNTP header/comments settings, als er geen aparte NNTP header/comments server is opgegeven, gebruik die van - # de NZB server - if ((empty(self::$_settings['nntp_hdr']['host'])) && (!empty(self::$_settings['nntp_nzb']))) { - self::$_settings['nntp_hdr'] = self::$_settings['nntp_nzb']; - } # if - - # Hetzelfde voor de NNTP upload server - if ((empty(self::$_settings['nntp_post']['host'])) && (!empty(self::$_settings['nntp_nzb']))) { - self::$_settings['nntp_post'] = self::$_settings['nntp_nzb']; - } # if - } # if - - return self::$_instance; - } # singleton - - /* - * Geeft de waarde van de setting terug - */ - function get($name) { - return self::$_settings[$name]; - } # get - - /* - * Unset een bepaalde waarde - */ - function remove($name) { - unset(self::$_settings[$name]); - - $this->_db->removeSetting($name); - } # remove - - /* - * Geeft terug of een bepaalde setting uit de database - * komt of uit de settings.php file. De settings-file - * heeft altijd prioriteit - */ - function getOrigin($name) { - if (isset(self::$_phpSettings[$name])) { - return "php"; - } else { - return "db"; - } # if - } # getOrigin - - /* - * Set de waarde van de setting, maakt hem ook - * meteen persistent dus mee oppassen - */ - function set($name, $value) { - # Als de setting uit PHP komt, dan mag die niet geupdate worden - # hier omdat we dan niet meer weten wat er gebeurt. - if (isset(self::$_phpSettings[$name])) { - throw new InvalidSettingsUpdateException("InvalidSettingUpdat Exception for '" . $name . '"'); - } # if - - # Update onze eigen settings array zodat we meteen up-to-date zijn - self::$_settings[$name] = $value; - - $this->_db->updateSetting($name, $value); - } # set - - /* - * Validate settings - */ - function validateSettings($settings) { - $errorList = array(); - - # Define arrays with valid settings - $validNntpEnc = array(false, 'ssl', 'tls'); - $validModerationAction = array('disable', 'act', 'markspot'); - $validRetentionTypes = array('fullonly', 'everything'); - - # Get the given value for NNTP encryption - $settings['nntp_nzb']['enc'] = (isset($settings['nntp_nzb']['enc']['switch'])) ? $settings['nntp_nzb']['enc']['select'] : false; - $settings['nntp_hdr']['enc'] = (isset($settings['nntp_hdr']['enc']['switch'])) ? $settings['nntp_hdr']['enc']['select'] : false; - $settings['nntp_post']['enc'] = (isset($settings['nntp_post']['enc']['switch'])) ? $settings['nntp_post']['enc']['select'] : false; - - # Trim human-entered text fields - $settings['nntp_nzb']['host'] = trim($settings['nntp_nzb']['host']); - $settings['nntp_hdr']['host'] = trim($settings['nntp_hdr']['host']); - $settings['nntp_post']['host'] = trim($settings['nntp_post']['host']); - - # Verify settings with the previous declared arrays - if (in_array($settings['nntp_nzb']['enc'], $validNntpEnc) === false || in_array($settings['nntp_hdr']['enc'], $validNntpEnc) === false || in_array($settings['nntp_post']['enc'], $validNntpEnc) === false) { - $errorList[] = _('Invalid encryption setting'); - } # if - if (in_array($settings['spot_moderation'], $validModerationAction) === false) { - $errorList[] = _('Invalid spot moderation setting'); - } # if - if (in_array($settings['retentiontype'], $validRetentionTypes) === false) { - $errorList[] = _('Invalid spot retentiontype setting'); - } # if - - # Verify settings - $settings['cookie_expires'] = (int) $settings['cookie_expires']; - if ($settings['cookie_expires'] < 0) { - $errorList[] = _('Invalid cookie_expires setting'); - } # if - - $settings['retention'] = (int) $settings['retention']; - if ($settings['retention'] < 0) { - $errorList[] = _('Invalid retention setting'); - } # if - - if (($settings['retrieve_newer_than'] = strtotime($settings['retrieve_newer_than'])) === false || $settings['retrieve_newer_than'] > time()) { - $errorList[] = _('Invalid retrieve_newer_than setting'); - } elseif ($settings['retrieve_newer_than'] < 1230789600) { - $settings['retrieve_newer_than'] = 1230789600; - } # elseif - - $settings['retrieve_increment'] = (int) $settings['retrieve_increment']; - if ($settings['retrieve_increment'] < 1) { - $errorList[] = _('Invalid retrieve_increment setting'); - } # if - - # check the mailaddress - if (!filter_var($settings['systemfrommail'], FILTER_VALIDATE_EMAIL)) { - $errorList[] = _('Not a valid email address'); - } # if - - # We don't want to save megabyts of CSS, so put a limit to the size - if (strlen($settings['customcss'] > 1024 * 10)) { - $errorList[] = _('Custom CSS is too large'); - } # if - - # converteer overige settings naar boolean zodat we gewoon al weten wat er uitkomt - $settings['deny_robots'] = (isset($settings['deny_robots'])) ? true : false; - $settings['sendwelcomemail'] = (isset($settings['sendwelcomemail'])) ? true : false; - $settings['nntp_nzb']['buggy'] = (isset($settings['nntp_nzb']['buggy'])) ? true : false; - $settings['nntp_hdr']['buggy'] = (isset($settings['nntp_hdr']['buggy'])) ? true : false; - $settings['nntp_post']['buggy'] = (isset($settings['nntp_post']['buggy'])) ? true : false; - $settings['retrieve_full'] = (isset($settings['retrieve_full'])) ? true : false; - $settings['prefetch_image'] = (isset($settings['prefetch_image'])) ? true : false; - $settings['prefetch_nzb'] = (isset($settings['prefetch_nzb'])) ? true : false; - $settings['retrieve_comments'] = (isset($settings['retrieve_comments'])) ? true : false; - $settings['retrieve_full_comments'] = (isset($settings['retrieve_full_comments'])) ? true : false; - $settings['retrieve_reports'] = (isset($settings['retrieve_reports'])) ? true : false; - $settings['enable_timing'] = (isset($settings['enable_timing'])) ? true : false; - $settings['enable_stacktrace'] = (isset($settings['enable_stacktrace'])) ? true : false; - $settings['prepare_statistics'] = (isset($settings['prepare_statistics'])) ? true : false; - $settings['external_blacklist'] = (isset($settings['external_blacklist'])) ? true : false; - $settings['external_whitelist'] = (isset($settings['external_whitelist'])) ? true : false; - - # Default server settings if they won't be used - if (!isset($settings['nntp_hdr']['use'])) { - $settings['nntp_hdr'] = array('host' => '', - 'user' => '', - 'pass' => '', - 'enc' => false, - 'port' => 119, - 'buggy' => false); - } # if - - if (!isset($settings['nntp_post']['use'])) { - $settings['nntp_post'] = array('host' => '', - 'user' => '', - 'pass' => '', - 'enc' => false, - 'port' => 119, - 'buggy' => false); - } # if - - unset($settings['nntp_hdr']['use'], $settings['nntp_post']['use']); - - return array($errorList, $settings); - } # validateSettings - - function setSettings($settings) { - # If we disable the external blacklist, clear all entries - if ($settings['external_blacklist'] == false && $this->get('external_blacklist') == true) { - $this->_db->removeOldList($this->get('blacklist_url'), SpotDb::spotterlist_Black); - } # if - - # If we disable the external whitelist, clear all entries - if ($settings['external_whitelist'] == false && $this->get('external_whitelist') == true) { - $this->_db->removeOldList($this->get('whitelist_url'), SpotDb::spotterlist_White); - } # if - - # clear some stuff we don't need to store - unset($settings['xsrfid'], $settings['http_referer'], $settings['buttonpressed'], $settings['action'], $settings['submitedit']); - - # Store settings - foreach ($settings as $key => $value) { - # and write these updated settings to the database - $this->set($key, $value); - } # foreach - } # setSettings - - /* - * Is onze database versie nog wel geldig? - */ - function schemaValid() { - # SPOTDB_SCHEMA_VERSION is gedefinieerd bovenin SpotDb - return ($this->get('schemaversion') == SPOTDB_SCHEMA_VERSION); - } # schemaValid - - - /* - * Zijn onze settings versie nog wel geldig? - */ - function settingsValid() { - # SPOTWEB_SETTINGS_VERSION is gedefinieerd bovenin dit bestand - return ($this->get('settingsversion') == SPOTWEB_SETTINGS_VERSION); - } # settingsValid - - /* - * Bestaat de opgegeven setting ? - */ - function exists($name) { - return isset(self::$_settings[$name]); - } # isSet - - /* - * Private constructor, moet altijd via singleton gaan - */ - private function __construct($db) { - $this->_db = $db; - } # ctor - -} # class SpotSettings +getAllSettings(); + + # en merge de settings met degene die we door krijgen + self::$_settings = array_merge(self::$_dbSettings, self::$_phpSettings); + + # Override NNTP header/comments settings, als er geen aparte NNTP header/comments server is opgegeven, gebruik die van + # de NZB server + if ((empty(self::$_settings['nntp_hdr']['host'])) && (!empty(self::$_settings['nntp_nzb']))) { + self::$_settings['nntp_hdr'] = self::$_settings['nntp_nzb']; + } # if + + # Hetzelfde voor de NNTP upload server + if ((empty(self::$_settings['nntp_post']['host'])) && (!empty(self::$_settings['nntp_nzb']))) { + self::$_settings['nntp_post'] = self::$_settings['nntp_nzb']; + } # if + } # if + + return self::$_instance; + } # singleton + + /* + * Geeft de waarde van de setting terug + */ + function get($name) { + return self::$_settings[$name]; + } # get + + /* + * Unset een bepaalde waarde + */ + function remove($name) { + unset(self::$_settings[$name]); + + $this->_db->removeSetting($name); + } # remove + + /* + * Geeft terug of een bepaalde setting uit de database + * komt of uit de settings.php file. De settings-file + * heeft altijd prioriteit + */ + function getOrigin($name) { + if (isset(self::$_phpSettings[$name])) { + return "php"; + } else { + return "db"; + } # if + } # getOrigin + + /* + * Set de waarde van de setting, maakt hem ook + * meteen persistent dus mee oppassen + */ + function set($name, $value) { + # Als de setting uit PHP komt, dan mag die niet geupdate worden + # hier omdat we dan niet meer weten wat er gebeurt. + if (isset(self::$_phpSettings[$name])) { + throw new InvalidSettingsUpdateException("InvalidSettingUpdat Exception for '" . $name . '"'); + } # if + + # Update onze eigen settings array zodat we meteen up-to-date zijn + self::$_settings[$name] = $value; + + $this->_db->updateSetting($name, $value); + } # set + + /* + * Validate settings + */ + function validateSettings($settings) { + $errorList = array(); + + # Define arrays with valid settings + $validNntpEnc = array(false, 'ssl', 'tls'); + $validModerationAction = array('disable', 'act', 'markspot'); + $validRetentionTypes = array('fullonly', 'everything'); + + # Get the given value for NNTP encryption + $settings['nntp_nzb']['enc'] = (isset($settings['nntp_nzb']['enc']['switch'])) ? $settings['nntp_nzb']['enc']['select'] : false; + $settings['nntp_hdr']['enc'] = (isset($settings['nntp_hdr']['enc']['switch'])) ? $settings['nntp_hdr']['enc']['select'] : false; + $settings['nntp_post']['enc'] = (isset($settings['nntp_post']['enc']['switch'])) ? $settings['nntp_post']['enc']['select'] : false; + + # Trim human-entered text fields + $settings['nntp_nzb']['host'] = trim($settings['nntp_nzb']['host']); + $settings['nntp_hdr']['host'] = trim($settings['nntp_hdr']['host']); + $settings['nntp_post']['host'] = trim($settings['nntp_post']['host']); + + # Verify settings with the previous declared arrays + if (in_array($settings['nntp_nzb']['enc'], $validNntpEnc) === false || in_array($settings['nntp_hdr']['enc'], $validNntpEnc) === false || in_array($settings['nntp_post']['enc'], $validNntpEnc) === false) { + $errorList[] = _('Invalid encryption setting'); + } # if + if (in_array($settings['spot_moderation'], $validModerationAction) === false) { + $errorList[] = _('Invalid spot moderation setting'); + } # if + if (in_array($settings['retentiontype'], $validRetentionTypes) === false) { + $errorList[] = _('Invalid spot retentiontype setting'); + } # if + + # Verify settings + $settings['cookie_expires'] = (int) $settings['cookie_expires']; + if ($settings['cookie_expires'] < 0) { + $errorList[] = _('Invalid cookie_expires setting'); + } # if + + $settings['retention'] = (int) $settings['retention']; + if ($settings['retention'] < 0) { + $errorList[] = _('Invalid retention setting'); + } # if + + if (($settings['retrieve_newer_than'] = strtotime($settings['retrieve_newer_than'])) === false || $settings['retrieve_newer_than'] > time()) { + $errorList[] = _('Invalid retrieve_newer_than setting'); + } elseif ($settings['retrieve_newer_than'] < 1230789600) { + $settings['retrieve_newer_than'] = 1230789600; + } # elseif + + $settings['retrieve_increment'] = (int) $settings['retrieve_increment']; + if ($settings['retrieve_increment'] < 1) { + $errorList[] = _('Invalid retrieve_increment setting'); + } # if + + # check the mailaddress + if (!filter_var($settings['systemfrommail'], FILTER_VALIDATE_EMAIL)) { + $errorList[] = _('Not a valid email address'); + } # if + + # We don't want to save megabyts of CSS, so put a limit to the size + if (strlen($settings['customcss'] > 1024 * 10)) { + $errorList[] = _('Custom CSS is too large'); + } # if + + # converteer overige settings naar boolean zodat we gewoon al weten wat er uitkomt + $settings['deny_robots'] = (isset($settings['deny_robots'])) ? true : false; + $settings['sendwelcomemail'] = (isset($settings['sendwelcomemail'])) ? true : false; + $settings['nntp_nzb']['buggy'] = (isset($settings['nntp_nzb']['buggy'])) ? true : false; + $settings['nntp_hdr']['buggy'] = (isset($settings['nntp_hdr']['buggy'])) ? true : false; + $settings['nntp_post']['buggy'] = (isset($settings['nntp_post']['buggy'])) ? true : false; + $settings['retrieve_full'] = (isset($settings['retrieve_full'])) ? true : false; + $settings['prefetch_image'] = (isset($settings['prefetch_image'])) ? true : false; + $settings['prefetch_nzb'] = (isset($settings['prefetch_nzb'])) ? true : false; + $settings['retrieve_comments'] = (isset($settings['retrieve_comments'])) ? true : false; + $settings['retrieve_full_comments'] = (isset($settings['retrieve_full_comments'])) ? true : false; + $settings['retrieve_reports'] = (isset($settings['retrieve_reports'])) ? true : false; + $settings['enable_timing'] = (isset($settings['enable_timing'])) ? true : false; + $settings['enable_stacktrace'] = (isset($settings['enable_stacktrace'])) ? true : false; + $settings['prepare_statistics'] = (isset($settings['prepare_statistics'])) ? true : false; + $settings['external_blacklist'] = (isset($settings['external_blacklist'])) ? true : false; + $settings['external_whitelist'] = (isset($settings['external_whitelist'])) ? true : false; + + # Default server settings if they won't be used + if (!isset($settings['nntp_hdr']['use'])) { + $settings['nntp_hdr'] = array('host' => '', + 'user' => '', + 'pass' => '', + 'enc' => false, + 'port' => 119, + 'buggy' => false); + } # if + + if (!isset($settings['nntp_post']['use'])) { + $settings['nntp_post'] = array('host' => '', + 'user' => '', + 'pass' => '', + 'enc' => false, + 'port' => 119, + 'buggy' => false); + } # if + + unset($settings['nntp_hdr']['use'], $settings['nntp_post']['use']); + + return array($errorList, $settings); + } # validateSettings + + function setSettings($settings) { + # If we disable the external blacklist, clear all entries + if ($settings['external_blacklist'] == false && $this->get('external_blacklist') == true) { + $this->_db->removeOldList($this->get('blacklist_url'), SpotDb::spotterlist_Black); + } # if + + # If we disable the external whitelist, clear all entries + if ($settings['external_whitelist'] == false && $this->get('external_whitelist') == true) { + $this->_db->removeOldList($this->get('whitelist_url'), SpotDb::spotterlist_White); + } # if + + # clear some stuff we don't need to store + unset($settings['xsrfid'], $settings['http_referer'], $settings['buttonpressed'], $settings['action'], $settings['submitedit']); + + # Store settings + foreach ($settings as $key => $value) { + # and write these updated settings to the database + $this->set($key, $value); + } # foreach + } # setSettings + + /* + * Is onze database versie nog wel geldig? + */ + function schemaValid() { + # SPOTDB_SCHEMA_VERSION is gedefinieerd bovenin SpotDb + return ($this->get('schemaversion') == SPOTDB_SCHEMA_VERSION); + } # schemaValid + + + /* + * Zijn onze settings versie nog wel geldig? + */ + function settingsValid() { + # SPOTWEB_SETTINGS_VERSION is gedefinieerd bovenin dit bestand + return ($this->get('settingsversion') == SPOTWEB_SETTINGS_VERSION); + } # settingsValid + + /* + * Bestaat de opgegeven setting ? + */ + function exists($name) { + return isset(self::$_settings[$name]); + } # isSet + + /* + * Private constructor, moet altijd via singleton gaan + */ + private function __construct($db) { + $this->_db = $db; + } # ctor + +} # class SpotSettings diff --git a/lib/SpotSettingsUpgrader.php b/lib/SpotSettingsUpgrader.php index de57040b6..3968b1f62 100755 --- a/lib/SpotSettingsUpgrader.php +++ b/lib/SpotSettingsUpgrader.php @@ -110,7 +110,7 @@ function updateSettingsVersion() { * Create the server private and public keys */ function createServerKeys($openSslCnfPath) { - $spotSigning = Services_Signing_Base::newServiceSigning(); + $spotSigning = Services_Signing_Base::factory(); $x = $spotSigning->createPrivateKey($openSslCnfPath); $this->setIfNot('publickey', $x['public']); diff --git a/lib/SpotTemplateHelper.php b/lib/SpotTemplateHelper.php index 321fb4d6a..08a30185c 100755 --- a/lib/SpotTemplateHelper.php +++ b/lib/SpotTemplateHelper.php @@ -1151,7 +1151,7 @@ function isReportPlaced($messageId) { */ function getCleanRandomString($len) { $spotParseUtil = new Services_Format_Util(); - $spotSigning = Services_Signing_Base::newServiceSigning(); + $spotSigning = Services_Signing_Base::factory(); return substr($spotParseUtil->spotPrepareBase64(base64_encode($spotSigning->makeRandomStr($len))), 0, $len); } # getRandomStr diff --git a/lib/SpotTiming.php b/lib/SpotTiming.php index a22673487..b8ac4a5bf 100755 --- a/lib/SpotTiming.php +++ b/lib/SpotTiming.php @@ -48,4 +48,4 @@ static function display() { echo '



'; } # display() -} # class SpotTiming \ No newline at end of file +} # class SpotTiming diff --git a/lib/SpotUserSystem.php b/lib/SpotUserSystem.php index 0796342c9..82654970d 100755 --- a/lib/SpotUserSystem.php +++ b/lib/SpotUserSystem.php @@ -6,8 +6,8 @@ class SpotUserSystem { private $_db; private $_settings; - function __construct(SpotDb $db, SpotSettings $settings) { - $this->_db = $db; + function __construct(Dao_Factory $daoFactory, SpotSettings $settings) { + $this->_db = new SpotDb($daoFactory); $this->_settings = $settings; } # ctor @@ -123,7 +123,7 @@ function useOrStartSession($forceAnonymous) { } # if # Initialize the security system - $spotSec = new SpotSecurity($this->_db, $this->_settings, $userSession['user'], $userSession['session']['ipaddr']); + $spotSec = new SpotSecurity($this->_db->_userDao, $this->_db->_auditDao, $this->_settings, $userSession['user'], $userSession['session']['ipaddr']); $userSession['security'] = $spotSec; /* diff --git a/lib/SpotUserUpgrader.php b/lib/SpotUserUpgrader.php index 311f5fe8f..6fabb2a68 100755 --- a/lib/SpotUserUpgrader.php +++ b/lib/SpotUserUpgrader.php @@ -270,7 +270,7 @@ function updateUserPreferences() { $rsaKey = $this->_db->getUserPrivateRsaKey($user['userid']); if (empty($rsaKey)) { # Creer een private en public key paar voor deze user - $spotSigning = Services_Signing_Base::newServiceSigning(); + $spotSigning = Services_Signing_Base::factory(); $userKey = $spotSigning->createPrivateKey($this->_settings->get('openssl_cnf_path')); $this->_db->setUserRsaKeys($user['userid'], $userKey['public'], $userKey['private']); diff --git a/lib/dao/Base/Dao_Base_BlackWhiteList.php b/lib/dao/Base/Dao_Base_BlackWhiteList.php index 89a96caa4..e2fa9a0df 100644 --- a/lib/dao/Base/Dao_Base_BlackWhiteList.php +++ b/lib/dao/Base/Dao_Base_BlackWhiteList.php @@ -22,51 +22,59 @@ function removeOldList($listUrl, $idtype) { * Updates the current black- and whitelist with new information for * external sources. */ - function updateExternalList($newlist,$idtype) { + function updateExternalList($newlist, $idtype) { $updatelist = array(); $updskipped = 0; $countnewlistspotterid = 0; $countdellistspotterid = 0; - /* Haal de oude lijst op*/ + if ($idtype == 'black') { + $idtype = 1; + } elseif ($idtype == 'white') { + $idtype = 2; + } else { + throw new Exception("Invalid list type specified for updateExternalList: " . $idtype); + } # else + + /* Retrieve the current list */ $oldlist = $this->_conn->arrayQuery("SELECT spotterid,idtype FROM spotteridblacklist WHERE ouruserid = -1 AND origin = 'external'"); foreach ($oldlist as $obl) { $islisted = (($obl['idtype'] == $idtype) > 0); - $updatelist[$obl['spotterid']] = 3 - $islisted; # 'oude' spotterid eerst op verwijderen zetten. + $updatelist[$obl['spotterid']] = 3 - $islisted; # Put "old" spotterids (current ones) on the to-delete list } /* verwerk de nieuwe lijst */ foreach ($newlist as $nwl) { - $nwl = trim($nwl); # Enters en eventuele spaties wegfilteren - if ((strlen($nwl) >= 3) && (strlen($nwl) <= 6)) { # de lengte van een spotterid is tussen 3 en 6 karakters groot (tot op heden) + $nwl = trim($nwl); + if ((strlen($nwl) >= 3) && (strlen($nwl) <= 6)) { # Spotterids are between 2 and 7 characters long if (empty($updatelist[$nwl])) { - $updatelist[$nwl] = 1; # nieuwe spoterids toevoegen + $updatelist[$nwl] = 1; # We want to add this spotterid } elseif ($updatelist[$nwl] == 2) { - $updatelist[$nwl] = 5; # spotterid staat al op dezelfde lijst, niet verwijderen. + $updatelist[$nwl] = 5; # SpotterID is on the list already, dont remove it } elseif ($updatelist[$nwl] == 3) { if ($idtype == 1) { - $updatelist[$nwl] = 4; # spotterid staat op een andere lijst, idtype veranderen. + $updatelist[$nwl] = 4; # Spotterid is on another kind of list, change the idtype } else { - $updskipped++; # spotterid staat al op de blacklist, niet veranderen. + $updskipped++; # Spotter is already on the list, dont remove it $updatelist[$nwl] = 5; } } else { - $updskipped++; # dubbel spotterid in xxxxxlist.txt. + $updskipped++; # double spotterid in xxxxxlist.txt. } } else { - $updskipped++; # er is iets mis met het spotterid (bijvoorbeeld een lege regel in xxxxxlist.txt) + $updskipped++; # Spotterid did not pass the sanity check } } $updlist = array_keys($updatelist); foreach ($updlist as $updl) { if ($updatelist[$updl] == 1) { - # voeg nieuwe spotterid's toe aan de lijst + # Add new spotterid's to the list $countnewlistspotterid++; $this->_conn->modify("INSERT INTO spotteridblacklist (spotterid,ouruserid,idtype,origin) VALUES ('%s','-1',%d,'external')", Array($updl, (int) $idtype)); $this->_conn->modify("UPDATE spotteridblacklist SET doubled = '%s' WHERE spotterid = '%s'AND ouruserid != -1 AND idtype = %d ", Array($this->_conn->bool2dt(true), $updl, (int) $idtype)); } elseif ($updatelist[$updl] == 2) { - # verwijder spotterid's die niet meer op de lijst staan + # Remove spotters which aren't on the list $countdellistspotterid++; $this->_conn->modify("DELETE FROM spotteridblacklist WHERE (spotterid = '%s') AND (ouruserid = -1) AND (origin = 'external')", Array($updl)); $this->_conn->modify("UPDATE spotteridblacklist SET doubled = '%s' WHERE spotterid = '%s' AND ouruserid != -1 AND idtype = %d ", Array($this->_conn->bool2dt(true), $updl, (int) $idtype)); @@ -74,10 +82,13 @@ function updateExternalList($newlist,$idtype) { $countnewlistspotterid++; $this->_conn->modify("UPDATE spotteridblacklist SET idtype = 1 WHERE (spotterid = '%s') AND (ouruserid = -1) AND (origin = 'external')", Array($updl)); $this->_conn->modify("UPDATE spotteridblacklist SET doubled = (idtype = 1) WHERE spotterid = '%s' AND ouruserid != -1", Array($updl)); - } + } # elseif + } # foreach - } - return array('added' => $countnewlistspotterid,'removed' => $countdellistspotterid,'skipped' => $updskipped); + return array('added' => $countnewlistspotterid, + 'removed' => $countdellistspotterid, + 'skipped' => $updskipped, + 'total' => count($newlist)); } # updateExternallist /* diff --git a/lib/dbeng/dbeng_abs.php b/lib/dbeng/dbeng_abs.php index ab0429434..fcad868d5 100755 --- a/lib/dbeng/dbeng_abs.php +++ b/lib/dbeng/dbeng_abs.php @@ -20,7 +20,7 @@ public static function getDbFactory($engine) { case 'pdo_pgsql' : return new dbeng_pdo_pgsql(); break; case 'pdo_sqlite' : return new dbeng_pdo_sqlite(); break; - default : throw new Exception("Unknown database engine (" . $dbSettings['engine'] . ") factory specified"); + default : throw new Exception("Unknown database engine (" . $engine . ") factory specified"); } // switch } # getDbFactory() diff --git a/lib/exceptions/CorruptBWListException.php b/lib/exceptions/CorruptBWListException.php new file mode 100644 index 000000000..972627a69 --- /dev/null +++ b/lib/exceptions/CorruptBWListException.php @@ -0,0 +1,2 @@ +isAvailable()!==true) { - $handler = new NzbHandler_Disable($settings, $nzbHandling); - } + if (!$handler instanceof NzbHandler_Disable && $handler->isAvailable()!==true) { + $handler = new NzbHandler_Disable($settings, $nzbHandling); + } return $handler; } # build() diff --git a/lib/page/SpotPage_Abs.php b/lib/page/SpotPage_Abs.php index 9940259e5..08a023447 100755 --- a/lib/page/SpotPage_Abs.php +++ b/lib/page/SpotPage_Abs.php @@ -1,125 +1,127 @@ -_db = $db; - $this->_settings = $settings; - $this->_currentSession = $currentSession; - $this->_spotSec = $currentSession['security']; - $this->_tplHelper = $this->getTplHelper(array()); - - /* - * Create a list of paths where to look for template files in - * the correct (last template first) order - */ - $this->_templatePaths = array('templates/' . $currentSession['active_tpl'] . '/'); - foreach($this->_tplHelper->getParentTemplates() as $parentTemplate) { - $this->_templatePaths[] = 'templates/' . $parentTemplate . '/'; - } # foreach - } # ctor - - /* - * Standaard mogen paginas niet gecached worden - * om invalid cached informatie te voorkomen. Kan overriden worden - * per pagina - */ - function sendExpireHeaders($preventCaching) { - if ($preventCaching) { - Header("Cache-Control: private, post-check=1, pre-check=2, max-age=1, must-revalidate"); - Header("Expires: Mon, 12 Jul 2000 01:00:00 GMT"); - } else { - # stuur een expires header zodat dit een jaar of 10 geldig is - Header("Cache-Control: public"); - Header("Expires: " . gmdate("D, d M Y H:i:s", (time() + (86400 * 3650))) . " GMT"); - Header("Pragma: "); - } # if - } # sendExpireHeaders - - /* - * Stuur een content header, dit zorgt er voor dat de browser - * eventuele content sneller kan parsen - */ - function sendContentTypeHeader($type) { - switch($type) { - case 'xml' : Header("Content-Type: text/xml; charset=utf-8"); break; - case 'rss' : Header("Content-Type: application/rss+xml; charset=utf-8"); break; - case 'json' : Header("Content-Type: application/json; charset=utf-8"); break; - case 'css' : Header("Content-Type: text/css; charset=utf-8"); break; - case 'js' : Header("Content-Type: application/javascript; charset=utf-8"); break; - case 'ico' : Header("Content-Type: image/x-icon"); break; - - default : Header("Content-Type: text/html; charset=utf-8"); break; - } # switch - - } # sendContentTypeHeader - - - # Geef the tpl helper terug - private function getTplHelper($params) { - $tplName = $this->_currentSession['active_tpl']; - - $className = 'SpotTemplateHelper_' . ucfirst($tplName); - $tplHelper = new $className($this->_settings, $this->_currentSession, $this->_db, $params); - - return $tplHelper; - } # getTplHelper - - - /* - * Display de template - */ - function template($tpl, $params = array()) { - SpotTiming::start(__FUNCTION__ . ':' . $tpl); - - extract($params, EXTR_REFS); - $settings = $this->_settings; - $pagetitle = $this->_pageTitle; - - # update the template helper variables - $this->_tplHelper->setParams($params); - - # Expose some variables to the template script in its local scope - $tplHelper = $this->_tplHelper; - $currentSession = $this->_currentSession; - $spotSec = $this->_currentSession['security']; - - # send any expire headers - $this->sendExpireHeaders(true); - $this->sendContentTypeHeader('html'); - - # and include the template - foreach($this->_templatePaths as $tplPath) { - if (file_exists($tplPath . $tpl . '.inc.php')) { - require_once($tplPath . $tpl . '.inc.php'); - - break; - } # if - } # foreach - SpotTiming::stop(__FUNCTION__ . ':' . $tpl, array($params)); - } # template - - /* - * Daadwerkelijk renderen van de pagina -- implementatie specifiek - */ - abstract function render(); - - /* - * Renderen van een permission denied pagina, kan overridden worden door een implementatie - * specifieke renderer - */ - function permissionDenied($exception, $page, $http_referer) { - $this->template('permdenied', - array('exception' => $exception, - 'page' => $page, - 'http_referer' => $http_referer)); - } # permissionDenied - -} # SpotPage_Abs +_db = new SpotDb($daoFactory); + $this->_settings = $settings; + $this->_currentSession = $currentSession; + $this->_spotSec = $currentSession['security']; + $this->_tplHelper = $this->getTplHelper(array()); + $this->_daoFactory = $daoFactory; + + /* + * Create a list of paths where to look for template files in + * the correct (last template first) order + */ + $this->_templatePaths = array('templates/' . $currentSession['active_tpl'] . '/'); + foreach($this->_tplHelper->getParentTemplates() as $parentTemplate) { + $this->_templatePaths[] = 'templates/' . $parentTemplate . '/'; + } # foreach + } # ctor + + /* + * Standaard mogen paginas niet gecached worden + * om invalid cached informatie te voorkomen. Kan overriden worden + * per pagina + */ + function sendExpireHeaders($preventCaching) { + if ($preventCaching) { + Header("Cache-Control: private, post-check=1, pre-check=2, max-age=1, must-revalidate"); + Header("Expires: Mon, 12 Jul 2000 01:00:00 GMT"); + } else { + # stuur een expires header zodat dit een jaar of 10 geldig is + Header("Cache-Control: public"); + Header("Expires: " . gmdate("D, d M Y H:i:s", (time() + (86400 * 3650))) . " GMT"); + Header("Pragma: "); + } # if + } # sendExpireHeaders + + /* + * Stuur een content header, dit zorgt er voor dat de browser + * eventuele content sneller kan parsen + */ + function sendContentTypeHeader($type) { + switch($type) { + case 'xml' : Header("Content-Type: text/xml; charset=utf-8"); break; + case 'rss' : Header("Content-Type: application/rss+xml; charset=utf-8"); break; + case 'json' : Header("Content-Type: application/json; charset=utf-8"); break; + case 'css' : Header("Content-Type: text/css; charset=utf-8"); break; + case 'js' : Header("Content-Type: application/javascript; charset=utf-8"); break; + case 'ico' : Header("Content-Type: image/x-icon"); break; + + default : Header("Content-Type: text/html; charset=utf-8"); break; + } # switch + + } # sendContentTypeHeader + + + # Geef the tpl helper terug + private function getTplHelper($params) { + $tplName = $this->_currentSession['active_tpl']; + + $className = 'SpotTemplateHelper_' . ucfirst($tplName); + $tplHelper = new $className($this->_settings, $this->_currentSession, $this->_db, $params); + + return $tplHelper; + } # getTplHelper + + + /* + * Display de template + */ + function template($tpl, $params = array()) { + SpotTiming::start(__FUNCTION__ . ':' . $tpl); + + extract($params, EXTR_REFS); + $settings = $this->_settings; + $pagetitle = $this->_pageTitle; + + # update the template helper variables + $this->_tplHelper->setParams($params); + + # Expose some variables to the template script in its local scope + $tplHelper = $this->_tplHelper; + $currentSession = $this->_currentSession; + $spotSec = $this->_currentSession['security']; + + # send any expire headers + $this->sendExpireHeaders(true); + $this->sendContentTypeHeader('html'); + + # and include the template + foreach($this->_templatePaths as $tplPath) { + if (file_exists($tplPath . $tpl . '.inc.php')) { + require_once($tplPath . $tpl . '.inc.php'); + + break; + } # if + } # foreach + SpotTiming::stop(__FUNCTION__ . ':' . $tpl, array($params)); + } # template + + /* + * Daadwerkelijk renderen van de pagina -- implementatie specifiek + */ + abstract function render(); + + /* + * Renderen van een permission denied pagina, kan overridden worden door een implementatie + * specifieke renderer + */ + function permissionDenied($exception, $page, $http_referer) { + $this->template('permdenied', + array('exception' => $exception, + 'page' => $page, + 'http_referer' => $http_referer)); + } # permissionDenied + +} # SpotPage_Abs diff --git a/lib/page/SpotPage_blacklistspotter.php b/lib/page/SpotPage_blacklistspotter.php index 5d1df7f16..3e8072a18 100755 --- a/lib/page/SpotPage_blacklistspotter.php +++ b/lib/page/SpotPage_blacklistspotter.php @@ -1,66 +1,66 @@ -_blForm = $params['blform']; - } # ctor - - function render() { - $formMessages = array('errors' => array(), - 'info' => array()); - - # Controleer de users' rechten - $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_blacklist_spotter, ''); - - # creeer een default blacklist - $blackList = array('spotterid' => '', - 'origin' => ''); - - # blacklist is standaard niet geprobeerd - $postResult = array(); - - # zet de page title - $this->_pageTitle = "report: blacklist spotter"; - - /* - * bring the forms' action into the local scope for - * easier access - */ - $formAction = $this->_blForm['action']; - - # Make sure the anonymous user and reserved usernames cannot post content - $spotUserSystem = new SpotUserSystem($this->_db, $this->_settings); - if (!$spotUserSystem->allowedToPost($this->_currentSession['user'])) { - $postResult = array('result' => 'notloggedin'); - - $formAction = ''; - } # if - - if (!empty($formAction)) { - # zorg er voor dat alle variables ingevuld zijn - $blackList = array_merge($blackList, $this->_blForm); - - switch($formAction) { - case 'addspotterid' : { - $spotUserSystem->addSpotterToList($this->_currentSession['user']['userid'], $blackList['spotterid'], $blackList['origin'], $blackList['idtype']); - break; - } # case addspotterid - - case 'removespotterid' : { - $idtyPe = $blackList['idtype']; - $spotUserSystem->removeSpotterFromList($this->_currentSession['user']['userid'], $blackList['spotterid']); - break; - } # case removespotterid - } # switch - - $postResult = array('result' => 'success'); - } # if - - #- display stuff -# - $this->template('blacklistspotter', array('blacklistspotter' => $blackList, - 'formmessages' => $formMessages, - 'postresult' => $postResult)); - } # render -} # class SpotPage_blacklistspotter +_blForm = $params['blform']; + } # ctor + + function render() { + $formMessages = array('errors' => array(), + 'info' => array()); + + # Controleer de users' rechten + $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_blacklist_spotter, ''); + + # creeer een default blacklist + $blackList = array('spotterid' => '', + 'origin' => ''); + + # blacklist is standaard niet geprobeerd + $postResult = array(); + + # zet de page title + $this->_pageTitle = "report: blacklist spotter"; + + /* + * bring the forms' action into the local scope for + * easier access + */ + $formAction = $this->_blForm['action']; + + # Make sure the anonymous user and reserved usernames cannot post content + $spotUserSystem = new SpotUserSystem($this->_db, $this->_settings); + if (!$spotUserSystem->allowedToPost($this->_currentSession['user'])) { + $postResult = array('result' => 'notloggedin'); + + $formAction = ''; + } # if + + if (!empty($formAction)) { + # zorg er voor dat alle variables ingevuld zijn + $blackList = array_merge($blackList, $this->_blForm); + + switch($formAction) { + case 'addspotterid' : { + $spotUserSystem->addSpotterToList($this->_currentSession['user']['userid'], $blackList['spotterid'], $blackList['origin'], $blackList['idtype']); + break; + } # case addspotterid + + case 'removespotterid' : { + $idtyPe = $blackList['idtype']; + $spotUserSystem->removeSpotterFromList($this->_currentSession['user']['userid'], $blackList['spotterid']); + break; + } # case removespotterid + } # switch + + $postResult = array('result' => 'success'); + } # if + + #- display stuff -# + $this->template('blacklistspotter', array('blacklistspotter' => $blackList, + 'formmessages' => $formMessages, + 'postresult' => $postResult)); + } # render +} # class SpotPage_blacklistspotter diff --git a/lib/page/SpotPage_catsjson.php b/lib/page/SpotPage_catsjson.php index 6ae8c8392..796c72dec 100755 --- a/lib/page/SpotPage_catsjson.php +++ b/lib/page/SpotPage_catsjson.php @@ -1,230 +1,230 @@ -sendContentTypeHeader('html'); - - $this->_params = $params; - } # ctor - - /* - * render a page - */ - function render() { - if ($this->_params['rendertype'] == 'tree') { - $this->categoriesToJson(); - } else { - $this->renderSelectBox(); - } # else - } # render - - /* - * Render the JSON specifically for one selectbox, no - * logic whatsoever - */ - function renderSelectBox() { - # stuur een 'always cache' header zodat dit gecached kan worden - $this->sendExpireHeaders(false); - - $category = $this->_params['category']; - $genre = $this->_params['subcatz']; - if (strlen($genre) == 0) { - $genre = 'z'; - } # if - - /* Validate the selected category */ - if (!isset(SpotCategories::$_head_categories[$category])) { - return ''; - } # if - - $returnArray = array(); - $scType = 'z'; - - switch($this->_params['rendertype']) { - case 'subcatz' : { - $scType = $this->_params['rendertype'][6]; - - foreach(SpotCategories::$_categories[$category]['z'] as $key => $value) { - $returnArray[$key] = $value; - } # foreach - - break; - } # case subcatz - - case 'subcata' : - case 'subcatb' : - case 'subcatc' : - case 'subcatd' : { - $scType = $this->_params['rendertype'][6]; - - if (isset(SpotCategories::$_categories[$category][$scType])) { - foreach(SpotCategories::$_categories[$category][$scType] as $key => $value) { - if (in_array('z'. $genre, $value[1])) { - $returnArray['cat' . $category . '_z' . $genre . '_' . $scType . $key] = $value[0]; - } # if - } # foreach - } # if - - break; - } # case subcatz - } # switch - - if (isset(SpotCategories::$_subcat_descriptions[$category][$scType])) { - echo json_encode( - array('title' => SpotCategories::$_subcat_descriptions[$category][$scType], - 'items' => $returnArray)); - } else { - echo json_encode( - array('title' => '', - 'items' => array())); - } # if - } # renderSelectBox - - /* - * Geeft JSON terug interpreteerbaar voor DynaTree om de categorylist als boom - * te kunnen weergeven - */ - function categoriesToJson() { - # stuur een expires header zodat dit niet gecached is, hierin staat - # state van de boom - $this->sendExpireHeaders(true); - - /* First parse the search string so we know which items to select and which not */ - $spotUserSystem = new SpotUserSystem($this->_db, $this->_settings); - $spotsOverview = new SpotsOverview($this->_db, $this->_settings); - $parsedSearch = $spotsOverview->filterToQuery($this->_params['search'], - array(), - $this->_currentSession, - $spotUserSystem->getIndexFilter($this->_currentSession['user']['userid'])); - if ($this->_params['disallowstrongnot']) { - $parsedSearch['strongNotList'] = ''; - } # if - $compressedCatList = ',' . $spotsOverview->compressCategorySelection($parsedSearch['categoryList'], $parsedSearch['strongNotList']); -//error_log($this->_params['search']['tree']); -//var_dump($parsedSearch); -//var_dump($compressedCatList); -//die(); - - echo "["; - - $hcatList = array(); - foreach(SpotCategories::$_head_categories as $hcat_key => $hcat_val) { - # The uer can opt to only show a specific category, if so, skip all others - if (($hcat_key != $this->_params['category']) && ($this->_params['category'] != '*')) { - continue; - } # if - - # If the user choose to show only one category, we dont want the category item itself - if ($this->_params['category'] == '*') { - $hcatTmp = '{"title": "' . $hcat_val . '", "isFolder": true, "key": "cat' . $hcat_key . '", "children": [' ; - } # if - $typeCatDesc = array(); - - if (isset(SpotCategories::$_categories[$hcat_key]['z'])) { - foreach(SpotCategories::$_categories[$hcat_key]['z'] as $type_key => $type_value) { - - if (($type_key !== 'z') && (($this->_params['subcatz'] == $type_key) || ($this->_params['subcatz'] == '*'))) { - # Now determine whether we need to enable the checkbox - $isSelected = strpos($compressedCatList, ',cat' . $hcat_key . '_z' . $type_key . ',') !== false ? "true" : "false"; - - # Is this strongnot? - $isStrongNot = strpos($compressedCatList, ',~cat' . $hcat_key . '_z' . $type_key . ',') !== false ? true : false; - if ($isStrongNot) { - $isStrongNot = '"strongnot": true, "addClass": "strongnotnode", '; - $isSelected = 'true'; - } else { - $isStrongNot = ''; - } # if - - # If the user choose to show only one categortype, we dont want the categorytype item itself - if ($this->_params['subcatz'] == '*') { - $typeCatTmp = '{"title": "' . $type_value . '", "isFolder": true, ' . $isStrongNot . ' "select": ' . $isSelected . ', "hideCheckbox": false, "key": "cat' . $hcat_key . '_z' . $type_key . '", "unselectable": false, "children": ['; - } # if - } # if - - $subcatDesc = array(); - foreach(SpotCategories::$_subcat_descriptions[$hcat_key] as $sclist_key => $sclist_desc) { - if (($sclist_key !== 'z') && (($this->_params['subcatz'] == $type_key) || ($this->_params['subcatz'] == '*'))) { - - # We inherit the strongnode from our parent - $isStrongNot = strpos($compressedCatList, ',~cat' . $hcat_key . '_z' . $type_key . ',') !== false ? true : false; - if ($isStrongNot) { - $isStrongNot = '"strongnot": true, "addClass": "strongnotnode", '; - $isSelected = 'true'; - } else { - $isStrongNot = ''; - } # if - - $subcatTmp = '{"title": "' . $sclist_desc . '", "isFolder": true, ' . $isStrongNot . ' "hideCheckbox": true, "key": "cat' . $hcat_key . '_z' . $type_key . '_' . $sclist_key . '", "unselectable": false, "children": ['; - # echo ".." . $sclist_desc . "
"; - - $catList = array(); - foreach(SpotCategories::$_categories[$hcat_key][$sclist_key] as $key => $valTmp) { - //error_log($hcat_key . ' => ' . $sclist_key . ' ==:: ' . $key); - - if (in_array('z' . $type_key, $valTmp[2])) { - $val = $valTmp[0]; - - if ((strlen($val) != 0) && (strlen($key) != 0)) { - # Now determine whether we need to enable the checkbox - $isSelected = strpos($compressedCatList, ',cat' . $hcat_key . '_z' . $type_key . '_' . $sclist_key.$key . ',') !== false ? true : false; - $parentSelected = strpos($compressedCatList, ',cat' . $hcat_key . '_z' . $type_key .',') !== false ? true : false; - $isSelected = ($isSelected || $parentSelected) ? 'true' : 'false'; - - /* - * Is this strongnot? - */ - $isStrongNot = strpos($compressedCatList, ',~cat' . $hcat_key . '_z' . $type_key . ',') !== false ? true : false; - if (!$isStrongNot) { - $isStrongNot = strpos($compressedCatList, ',~cat' . $hcat_key . '_z' . $type_key . '_' . $sclist_key.$key . ',') !== false ? true : false; - } # if - if ($isStrongNot) { - $isStrongNot = '"strongnot": true, "addClass": "strongnotnode", '; - $isSelected = 'true'; - } else { - $isStrongNot = ''; - } # if - - $catList[] = '{"title": "' . $val . '", "icon": false, "select": ' . $isSelected . ', ' . $isStrongNot . '"key":"'. 'cat' . $hcat_key . '_z' . $type_key . '_' . $sclist_key.$key .'"}'; - } # if - } # if - } # foreach - $subcatTmp .= join(",", $catList); - - $subcatDesc[] = $subcatTmp . "]}"; - } # if - } # foreach - - if ($type_key !== 'z') { - # If the user choose to show only one categortype, we dont want the categorytype item itself - if ($this->_params['subcatz'] == '*') { - $typeCatDesc[] = $typeCatTmp . join(",", $subcatDesc) . "]}"; - } else { - if (!empty($subcatDesc)) { - $typeCatDesc[] = join(",", array_filter($subcatDesc)); - } # if - } # else - } else { - $typeCatDesc[] = join(",", $subcatDesc); - } # else - } # foreach - - } # foreach - - # If the user choose to show only one category, we dont want the category item itself - if ($this->_params['category'] == '*') { - $hcatList[] = $hcatTmp . join(",", $typeCatDesc) . "]}"; - } else { - $hcatList[] = join(",", $typeCatDesc); - } # if - } # foreach - - echo join(",", $hcatList); - echo "]"; - } # categoriesToJson - - -} # class SpotPage_catjson +sendContentTypeHeader('html'); + + $this->_params = $params; + } # ctor + + /* + * render a page + */ + function render() { + if ($this->_params['rendertype'] == 'tree') { + $this->categoriesToJson(); + } else { + $this->renderSelectBox(); + } # else + } # render + + /* + * Render the JSON specifically for one selectbox, no + * logic whatsoever + */ + function renderSelectBox() { + # stuur een 'always cache' header zodat dit gecached kan worden + $this->sendExpireHeaders(false); + + $category = $this->_params['category']; + $genre = $this->_params['subcatz']; + if (strlen($genre) == 0) { + $genre = 'z'; + } # if + + /* Validate the selected category */ + if (!isset(SpotCategories::$_head_categories[$category])) { + return ''; + } # if + + $returnArray = array(); + $scType = 'z'; + + switch($this->_params['rendertype']) { + case 'subcatz' : { + $scType = $this->_params['rendertype'][6]; + + foreach(SpotCategories::$_categories[$category]['z'] as $key => $value) { + $returnArray[$key] = $value; + } # foreach + + break; + } # case subcatz + + case 'subcata' : + case 'subcatb' : + case 'subcatc' : + case 'subcatd' : { + $scType = $this->_params['rendertype'][6]; + + if (isset(SpotCategories::$_categories[$category][$scType])) { + foreach(SpotCategories::$_categories[$category][$scType] as $key => $value) { + if (in_array('z'. $genre, $value[1])) { + $returnArray['cat' . $category . '_z' . $genre . '_' . $scType . $key] = $value[0]; + } # if + } # foreach + } # if + + break; + } # case subcatz + } # switch + + if (isset(SpotCategories::$_subcat_descriptions[$category][$scType])) { + echo json_encode( + array('title' => SpotCategories::$_subcat_descriptions[$category][$scType], + 'items' => $returnArray)); + } else { + echo json_encode( + array('title' => '', + 'items' => array())); + } # if + } # renderSelectBox + + /* + * Geeft JSON terug interpreteerbaar voor DynaTree om de categorylist als boom + * te kunnen weergeven + */ + function categoriesToJson() { + # stuur een expires header zodat dit niet gecached is, hierin staat + # state van de boom + $this->sendExpireHeaders(true); + + /* First parse the search string so we know which items to select and which not */ + $spotUserSystem = new SpotUserSystem($this->_db, $this->_settings); + $spotsOverview = new SpotsOverview($this->_db, $this->_settings); + $parsedSearch = $spotsOverview->filterToQuery($this->_params['search'], + array(), + $this->_currentSession, + $spotUserSystem->getIndexFilter($this->_currentSession['user']['userid'])); + if ($this->_params['disallowstrongnot']) { + $parsedSearch['strongNotList'] = ''; + } # if + $compressedCatList = ',' . $spotsOverview->compressCategorySelection($parsedSearch['categoryList'], $parsedSearch['strongNotList']); +//error_log($this->_params['search']['tree']); +//var_dump($parsedSearch); +//var_dump($compressedCatList); +//die(); + + echo "["; + + $hcatList = array(); + foreach(SpotCategories::$_head_categories as $hcat_key => $hcat_val) { + # The uer can opt to only show a specific category, if so, skip all others + if (($hcat_key != $this->_params['category']) && ($this->_params['category'] != '*')) { + continue; + } # if + + # If the user choose to show only one category, we dont want the category item itself + if ($this->_params['category'] == '*') { + $hcatTmp = '{"title": "' . $hcat_val . '", "isFolder": true, "key": "cat' . $hcat_key . '", "children": [' ; + } # if + $typeCatDesc = array(); + + if (isset(SpotCategories::$_categories[$hcat_key]['z'])) { + foreach(SpotCategories::$_categories[$hcat_key]['z'] as $type_key => $type_value) { + + if (($type_key !== 'z') && (($this->_params['subcatz'] == $type_key) || ($this->_params['subcatz'] == '*'))) { + # Now determine whether we need to enable the checkbox + $isSelected = strpos($compressedCatList, ',cat' . $hcat_key . '_z' . $type_key . ',') !== false ? "true" : "false"; + + # Is this strongnot? + $isStrongNot = strpos($compressedCatList, ',~cat' . $hcat_key . '_z' . $type_key . ',') !== false ? true : false; + if ($isStrongNot) { + $isStrongNot = '"strongnot": true, "addClass": "strongnotnode", '; + $isSelected = 'true'; + } else { + $isStrongNot = ''; + } # if + + # If the user choose to show only one categortype, we dont want the categorytype item itself + if ($this->_params['subcatz'] == '*') { + $typeCatTmp = '{"title": "' . $type_value . '", "isFolder": true, ' . $isStrongNot . ' "select": ' . $isSelected . ', "hideCheckbox": false, "key": "cat' . $hcat_key . '_z' . $type_key . '", "unselectable": false, "children": ['; + } # if + } # if + + $subcatDesc = array(); + foreach(SpotCategories::$_subcat_descriptions[$hcat_key] as $sclist_key => $sclist_desc) { + if (($sclist_key !== 'z') && (($this->_params['subcatz'] == $type_key) || ($this->_params['subcatz'] == '*'))) { + + # We inherit the strongnode from our parent + $isStrongNot = strpos($compressedCatList, ',~cat' . $hcat_key . '_z' . $type_key . ',') !== false ? true : false; + if ($isStrongNot) { + $isStrongNot = '"strongnot": true, "addClass": "strongnotnode", '; + $isSelected = 'true'; + } else { + $isStrongNot = ''; + } # if + + $subcatTmp = '{"title": "' . $sclist_desc . '", "isFolder": true, ' . $isStrongNot . ' "hideCheckbox": true, "key": "cat' . $hcat_key . '_z' . $type_key . '_' . $sclist_key . '", "unselectable": false, "children": ['; + # echo ".." . $sclist_desc . "
"; + + $catList = array(); + foreach(SpotCategories::$_categories[$hcat_key][$sclist_key] as $key => $valTmp) { + //error_log($hcat_key . ' => ' . $sclist_key . ' ==:: ' . $key); + + if (in_array('z' . $type_key, $valTmp[2])) { + $val = $valTmp[0]; + + if ((strlen($val) != 0) && (strlen($key) != 0)) { + # Now determine whether we need to enable the checkbox + $isSelected = strpos($compressedCatList, ',cat' . $hcat_key . '_z' . $type_key . '_' . $sclist_key.$key . ',') !== false ? true : false; + $parentSelected = strpos($compressedCatList, ',cat' . $hcat_key . '_z' . $type_key .',') !== false ? true : false; + $isSelected = ($isSelected || $parentSelected) ? 'true' : 'false'; + + /* + * Is this strongnot? + */ + $isStrongNot = strpos($compressedCatList, ',~cat' . $hcat_key . '_z' . $type_key . ',') !== false ? true : false; + if (!$isStrongNot) { + $isStrongNot = strpos($compressedCatList, ',~cat' . $hcat_key . '_z' . $type_key . '_' . $sclist_key.$key . ',') !== false ? true : false; + } # if + if ($isStrongNot) { + $isStrongNot = '"strongnot": true, "addClass": "strongnotnode", '; + $isSelected = 'true'; + } else { + $isStrongNot = ''; + } # if + + $catList[] = '{"title": "' . $val . '", "icon": false, "select": ' . $isSelected . ', ' . $isStrongNot . '"key":"'. 'cat' . $hcat_key . '_z' . $type_key . '_' . $sclist_key.$key .'"}'; + } # if + } # if + } # foreach + $subcatTmp .= join(",", $catList); + + $subcatDesc[] = $subcatTmp . "]}"; + } # if + } # foreach + + if ($type_key !== 'z') { + # If the user choose to show only one categortype, we dont want the categorytype item itself + if ($this->_params['subcatz'] == '*') { + $typeCatDesc[] = $typeCatTmp . join(",", $subcatDesc) . "]}"; + } else { + if (!empty($subcatDesc)) { + $typeCatDesc[] = join(",", array_filter($subcatDesc)); + } # if + } # else + } else { + $typeCatDesc[] = join(",", $subcatDesc); + } # else + } # foreach + + } # foreach + + # If the user choose to show only one category, we dont want the category item itself + if ($this->_params['category'] == '*') { + $hcatList[] = $hcatTmp . join(",", $typeCatDesc) . "]}"; + } else { + $hcatList[] = join(",", $typeCatDesc); + } # if + } # foreach + + echo join(",", $hcatList); + echo "]"; + } # categoriesToJson + + +} # class SpotPage_catjson diff --git a/lib/page/SpotPage_createuser.php b/lib/page/SpotPage_createuser.php index af00acdf9..4d88e50bf 100755 --- a/lib/page/SpotPage_createuser.php +++ b/lib/page/SpotPage_createuser.php @@ -2,8 +2,8 @@ class SpotPage_createuser extends SpotPage_Abs { private $_createUserForm; - function __construct(SpotDb $db, SpotSettings $settings, $currentSession, $params) { - parent::__construct($db, $settings, $currentSession); + function __construct(Dao_Factory $daoFactory, SpotSettings $settings, $currentSession, $params) { + parent::__construct($daoFactory, $settings, $currentSession); $this->_createUserForm = $params['createuserform']; } # ctor @@ -60,7 +60,7 @@ function render() { if (empty($formMessages['errors'])) { # Creer een private en public key paar voor deze user - $spotSigning = Services_Signing_Base::newServiceSigning(); + $spotSigning = Services_Signing_Base::factory(); $userKey = $spotSigning->createPrivateKey($this->_settings->get('openssl_cnf_path')); $spotUser['publickey'] = $userKey['public']; $spotUser['privatekey'] = $userKey['private']; diff --git a/lib/page/SpotPage_editfilter.php b/lib/page/SpotPage_editfilter.php index fa2f81298..aeacfa27d 100755 --- a/lib/page/SpotPage_editfilter.php +++ b/lib/page/SpotPage_editfilter.php @@ -1,181 +1,181 @@ -_editFilterForm = $params['editfilterform']; - $this->_filterId = $params['filterid']; - $this->_orderList = $params['orderfilterslist']; - $this->_search = $params['search']; - $this->_sorton = $params['sorton']; - $this->_sortorder = $params['sortorder']; - $this->_data = $params['data']; - } # ctor - - function render() { - $formMessages = array('errors' => array(), - 'info' => array()); - - # Controleer de users' rechten - $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_keep_own_filters, ''); - - # editfilter resultaat is standaard niet geprobeerd - $editResult = array(); - - # Instantieer het Spot user system - $spotUserSystem = new SpotUserSystem($this->_db, $this->_settings); - - # zet de page title - $this->_pageTitle = "spot: filters"; - - # haal de te editten filter op - $spotFilter = $spotUserSystem->getFilter($this->_currentSession['user']['userid'], $this->_filterId); - - /* - * bring the forms' action into the local scope for - * easier access - */ - $formAction = $this->_editFilterForm['action']; - - # als de te wijzigen security group niet gevonden kan worden, - # geef dan een error - if ((empty($spotFilter)) && ($formAction == 'changefilter')) { - $editResult = array('result' => 'failure'); - $formMessages['errors'][] = _("Filter doesn't exist"); - } # if - - - # Is dit een submit van een form, of nog maar de aanroep? - if ((!empty($formAction)) && (empty($formMessages['errors']))) { - switch($formAction) { - case 'removefilter' : { - $spotUserSystem->removeFilter($this->_currentSession['user']['userid'], $this->_filterId); - $editResult = array('result' => 'success'); - - break; - } # case 'removefilter' - - case 'discardfilters' : { - $spotUserSystem->resetFilterList($this->_currentSession['user']['userid']); - $editResult = array('result' => 'success'); - - break; - } # case 'discardfilters' - - case 'setfiltersasdefault' : { - $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_set_filters_as_default, ''); - - $spotUserSystem->setFiltersAsDefault($this->_currentSession['user']['userid']); - $editResult = array('result' => 'success'); - - break; - } # case 'setfiltersasdefault' - - case 'exportfilters': { - $editResult = $spotUserSystem->filtersToXml($spotUserSystem->getPlainFilterList($this->_currentSession['user']['userid'], 'filter')); - - break; - } # case 'exportfilters' - - case 'importfilters': { - if (isset($_FILES['filterimport'])) { - - if ($_FILES['filterimport']['error'] === UPLOAD_ERR_OK) { - $xml = file_get_contents($_FILES['filterimport']['tmp_name']); - try { - $filterList = $spotUserSystem->xmlToFilters($xml); - $spotUserSystem->setFilterList($this->_currentSession['user']['userid'], $filterList); - } catch(Exception $x) { - $editResult = array('result' => 'failure'); - $formMessages['errors'][] = _('Uploaded Spotwebfilter in invalid'); - } # catch - } else { - $editResult = array('result' => 'failure'); - $formMessages['errors'][] = sprintf(_('Error while uploading filter (%s)'), $_FILES['filterimport']['error']); - } # if - - } else { - $editResult = array('result' => 'failure'); - $formMessages['errors'][] = _("Filter hasn't been uploaded"); - } # else - - break; - } # case 'importfilters' - - case 'addfilter' : { - # Creeer een nieuw filter record - we voegen een filter altijd aan de root toe - $filter = $this->_editFilterForm; - $filter['valuelist'] = explode('&', $filter['valuelist']) ; - $filter['torder'] = 999; - $filter['tparent'] = 0; - $filter['children'] = array(); - $filter['filtertype'] = 'filter'; - $filter['sorton'] = $filter['sorton']; - $filter['sortorder'] = $filter['sortorder']; - $filter['enablenotify'] = isset($filter['enablenotify']) ? true : false; - - # en probeer de filter toe te voegen - $formMessages['errors'] = $spotUserSystem->addFilter($this->_currentSession['user']['userid'], $filter); - - if (!empty($formMessages['errors'])) { - $editResult = array('result' => 'failure'); - } else { - $editResult = array('result' => 'success'); - } # else - - break; - } # case 'addfilter' - - case 'reorder' : { - $orderCounter = 0; - - # Omdat de nestedSortable jquery widget niet een expliciete sortering meegeeft, voegen - # we die zelf toe aan de hand van hoe de elementen binnen komen - foreach($this->_orderList as $id => $parent) { - $spotFilter = $spotUserSystem->getFilter($this->_currentSession['user']['userid'], $id); - - # Als de volgorde of hierarchie dan moet de filter geupdate worden - if (($spotFilter['torder'] <> $orderCounter) || ($spotFilter['tparent'] <> $parent)) { - $spotFilter['torder'] = (int) $orderCounter; - $spotFilter['tparent'] = (int) $parent; - $spotUserSystem->changeFilter($this->_currentSession['user']['userid'], $spotFilter); - } # if - - $orderCounter++; - } # foreach - } # case 'reorder' - - case 'changefilter' : { - $spotFilter = array_merge($spotFilter, $this->_editFilterForm); - - $spotUserSystem->changeFilter($this->_currentSession['user']['userid'], - $spotFilter); - $editResult = array('result' => 'success'); - - break; - } # case 'changefilter' - - } # switch - } # if - - #- display stuff -# - $this->template('editfilter', array('filter' => $spotFilter, - 'sorton' => $this->_sorton, - 'sortorder' => $this->_sortorder, - 'sortby' => $this->_sorton, - 'sortdir' => $this->_sortorder, - 'lastformaction' => $formAction, - 'formmessages' => $formMessages, - 'data' => $this->_data, - 'http_referer' => $this->_editFilterForm['http_referer'], - 'editresult' => $editResult)); - } # render - -} # class SpotPage_editfilter +_editFilterForm = $params['editfilterform']; + $this->_filterId = $params['filterid']; + $this->_orderList = $params['orderfilterslist']; + $this->_search = $params['search']; + $this->_sorton = $params['sorton']; + $this->_sortorder = $params['sortorder']; + $this->_data = $params['data']; + } # ctor + + function render() { + $formMessages = array('errors' => array(), + 'info' => array()); + + # Controleer de users' rechten + $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_keep_own_filters, ''); + + # editfilter resultaat is standaard niet geprobeerd + $editResult = array(); + + # Instantieer het Spot user system + $spotUserSystem = new SpotUserSystem($this->_db, $this->_settings); + + # zet de page title + $this->_pageTitle = "spot: filters"; + + # haal de te editten filter op + $spotFilter = $spotUserSystem->getFilter($this->_currentSession['user']['userid'], $this->_filterId); + + /* + * bring the forms' action into the local scope for + * easier access + */ + $formAction = $this->_editFilterForm['action']; + + # als de te wijzigen security group niet gevonden kan worden, + # geef dan een error + if ((empty($spotFilter)) && ($formAction == 'changefilter')) { + $editResult = array('result' => 'failure'); + $formMessages['errors'][] = _("Filter doesn't exist"); + } # if + + + # Is dit een submit van een form, of nog maar de aanroep? + if ((!empty($formAction)) && (empty($formMessages['errors']))) { + switch($formAction) { + case 'removefilter' : { + $spotUserSystem->removeFilter($this->_currentSession['user']['userid'], $this->_filterId); + $editResult = array('result' => 'success'); + + break; + } # case 'removefilter' + + case 'discardfilters' : { + $spotUserSystem->resetFilterList($this->_currentSession['user']['userid']); + $editResult = array('result' => 'success'); + + break; + } # case 'discardfilters' + + case 'setfiltersasdefault' : { + $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_set_filters_as_default, ''); + + $spotUserSystem->setFiltersAsDefault($this->_currentSession['user']['userid']); + $editResult = array('result' => 'success'); + + break; + } # case 'setfiltersasdefault' + + case 'exportfilters': { + $editResult = $spotUserSystem->filtersToXml($spotUserSystem->getPlainFilterList($this->_currentSession['user']['userid'], 'filter')); + + break; + } # case 'exportfilters' + + case 'importfilters': { + if (isset($_FILES['filterimport'])) { + + if ($_FILES['filterimport']['error'] === UPLOAD_ERR_OK) { + $xml = file_get_contents($_FILES['filterimport']['tmp_name']); + try { + $filterList = $spotUserSystem->xmlToFilters($xml); + $spotUserSystem->setFilterList($this->_currentSession['user']['userid'], $filterList); + } catch(Exception $x) { + $editResult = array('result' => 'failure'); + $formMessages['errors'][] = _('Uploaded Spotwebfilter in invalid'); + } # catch + } else { + $editResult = array('result' => 'failure'); + $formMessages['errors'][] = sprintf(_('Error while uploading filter (%s)'), $_FILES['filterimport']['error']); + } # if + + } else { + $editResult = array('result' => 'failure'); + $formMessages['errors'][] = _("Filter hasn't been uploaded"); + } # else + + break; + } # case 'importfilters' + + case 'addfilter' : { + # Creeer een nieuw filter record - we voegen een filter altijd aan de root toe + $filter = $this->_editFilterForm; + $filter['valuelist'] = explode('&', $filter['valuelist']) ; + $filter['torder'] = 999; + $filter['tparent'] = 0; + $filter['children'] = array(); + $filter['filtertype'] = 'filter'; + $filter['sorton'] = $filter['sorton']; + $filter['sortorder'] = $filter['sortorder']; + $filter['enablenotify'] = isset($filter['enablenotify']) ? true : false; + + # en probeer de filter toe te voegen + $formMessages['errors'] = $spotUserSystem->addFilter($this->_currentSession['user']['userid'], $filter); + + if (!empty($formMessages['errors'])) { + $editResult = array('result' => 'failure'); + } else { + $editResult = array('result' => 'success'); + } # else + + break; + } # case 'addfilter' + + case 'reorder' : { + $orderCounter = 0; + + # Omdat de nestedSortable jquery widget niet een expliciete sortering meegeeft, voegen + # we die zelf toe aan de hand van hoe de elementen binnen komen + foreach($this->_orderList as $id => $parent) { + $spotFilter = $spotUserSystem->getFilter($this->_currentSession['user']['userid'], $id); + + # Als de volgorde of hierarchie dan moet de filter geupdate worden + if (($spotFilter['torder'] <> $orderCounter) || ($spotFilter['tparent'] <> $parent)) { + $spotFilter['torder'] = (int) $orderCounter; + $spotFilter['tparent'] = (int) $parent; + $spotUserSystem->changeFilter($this->_currentSession['user']['userid'], $spotFilter); + } # if + + $orderCounter++; + } # foreach + } # case 'reorder' + + case 'changefilter' : { + $spotFilter = array_merge($spotFilter, $this->_editFilterForm); + + $spotUserSystem->changeFilter($this->_currentSession['user']['userid'], + $spotFilter); + $editResult = array('result' => 'success'); + + break; + } # case 'changefilter' + + } # switch + } # if + + #- display stuff -# + $this->template('editfilter', array('filter' => $spotFilter, + 'sorton' => $this->_sorton, + 'sortorder' => $this->_sortorder, + 'sortby' => $this->_sorton, + 'sortdir' => $this->_sortorder, + 'lastformaction' => $formAction, + 'formmessages' => $formMessages, + 'data' => $this->_data, + 'http_referer' => $this->_editFilterForm['http_referer'], + 'editresult' => $editResult)); + } # render + +} # class SpotPage_editfilter diff --git a/lib/page/SpotPage_editsecgroup.php b/lib/page/SpotPage_editsecgroup.php index e34392312..ba1b72f06 100755 --- a/lib/page/SpotPage_editsecgroup.php +++ b/lib/page/SpotPage_editsecgroup.php @@ -1,125 +1,125 @@ -_editSecGroupForm = $params['editsecgroupform']; - $this->_groupId = $params['groupid']; - } # ctor - - function render() { - $formMessages = array('errors' => array(), - 'info' => array()); - - # Controleer de users' rechten - $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_edit_securitygroups, ''); - - # editsecgroup resultaat is standaard niet geprobeerd - $editResult = array(); - - # Instantieer het Spot user system - $spotUserSystem = new SpotUserSystem($this->_db, $this->_settings); - - # zet de page title - $this->_pageTitle = "spot: edit security groups"; - - # haal de te editten securitygroup op - $secGroup = $spotUserSystem->getSecGroup($this->_groupId); - - /* - * bring the forms' action into the local scope for - * easier access - */ - $formAction = $this->_editSecGroupForm['action']; - - # als de te wijzigen security group niet gevonden kan worden, - # geef dan een error - if ((empty($secGroup)) && ($formAction != 'addgroup')) { - $editResult = array('result' => 'failure'); - $formMessages['errors'][] = _('Group does\'nt exist'); - } # if - - # Als er een van de ingebouwde groepen geprobeerd bewerkt te worden, - # geef dan ook een error. - if ((!empty($formAction)) && ($formAction != 'addgroup') && ($secGroup['id'] < 6)) { - $editResult = array('result' => 'failure'); - $formMessages['errors'][] = _('Built-in groups can not be edited'); - } # if - - # Is dit een submit van een form, of nog maar de aanroep? - if ((!empty($formAction)) && (empty($formMessages['errors']))) { - switch($formAction) { - case 'removegroup' : { - $spotUserSystem->removeSecGroup($secGroup); - $editResult = array('result' => 'success'); - - break; - } # case 'removegroup' - - case 'addperm' : { - $formMessages['errors'] = $spotUserSystem->addPermToSecGroup($this->_groupId, $this->_editSecGroupForm); - - if (!empty($formMessages['errors'])) { - $editResult = array('result' => 'failure'); - } else { - $editResult = array('result' => 'success'); - } # else - - break; - } # case 'addperm' - - case 'removeperm' : { - $spotUserSystem->removePermFromSecGroup($this->_groupId, - $this->_editSecGroupForm); - $editResult = array('result' => 'success'); - - break; - } # case 'removeparm' - - case 'setallow' : - case 'setdeny' : { - $this->_editSecGroupForm['deny'] = (bool) ($formAction == 'setdeny'); - - $spotUserSystem->setDenyForPermFromSecGroup($this->_groupId, - $this->_editSecGroupForm); - $editResult = array('result' => 'success'); - - break; - } # case 'setallow' / 'setdeny' - - case 'addgroup' : - case 'changename' : { - # update het security group record - $secGroup['name'] = $this->_editSecGroupForm['name']; - - # controleer en repareer alle preferences - list ($formMessages['errors'], $secGroup) = $spotUserSystem->validateSecGroup($secGroup); - - if (empty($formMessages['errors'])) { - # en update de database - switch($formAction) { - case 'changename' : $spotUserSystem->setSecGroup($secGroup); break; - case 'addgroup' : $spotUserSystem->addSecGroup($secGroup); break; - } # switch - - $editResult = array('result' => 'success'); - } else { - $editResult = array('result' => 'failure'); - } # if - - break; - } # case 'changename' - - } # switch - } # if - - #- display stuff -# - $this->template('editsecgroup', array('securitygroup' => $secGroup, - 'formmessages' => $formMessages, - 'http_referer' => $this->_editSecGroupForm['http_referer'], - 'editresult' => $editResult)); - } # render - -} # class SpotPage_editsecgroup +_editSecGroupForm = $params['editsecgroupform']; + $this->_groupId = $params['groupid']; + } # ctor + + function render() { + $formMessages = array('errors' => array(), + 'info' => array()); + + # Controleer de users' rechten + $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_edit_securitygroups, ''); + + # editsecgroup resultaat is standaard niet geprobeerd + $editResult = array(); + + # Instantieer het Spot user system + $spotUserSystem = new SpotUserSystem($this->_db, $this->_settings); + + # zet de page title + $this->_pageTitle = "spot: edit security groups"; + + # haal de te editten securitygroup op + $secGroup = $spotUserSystem->getSecGroup($this->_groupId); + + /* + * bring the forms' action into the local scope for + * easier access + */ + $formAction = $this->_editSecGroupForm['action']; + + # als de te wijzigen security group niet gevonden kan worden, + # geef dan een error + if ((empty($secGroup)) && ($formAction != 'addgroup')) { + $editResult = array('result' => 'failure'); + $formMessages['errors'][] = _('Group does\'nt exist'); + } # if + + # Als er een van de ingebouwde groepen geprobeerd bewerkt te worden, + # geef dan ook een error. + if ((!empty($formAction)) && ($formAction != 'addgroup') && ($secGroup['id'] < 6)) { + $editResult = array('result' => 'failure'); + $formMessages['errors'][] = _('Built-in groups can not be edited'); + } # if + + # Is dit een submit van een form, of nog maar de aanroep? + if ((!empty($formAction)) && (empty($formMessages['errors']))) { + switch($formAction) { + case 'removegroup' : { + $spotUserSystem->removeSecGroup($secGroup); + $editResult = array('result' => 'success'); + + break; + } # case 'removegroup' + + case 'addperm' : { + $formMessages['errors'] = $spotUserSystem->addPermToSecGroup($this->_groupId, $this->_editSecGroupForm); + + if (!empty($formMessages['errors'])) { + $editResult = array('result' => 'failure'); + } else { + $editResult = array('result' => 'success'); + } # else + + break; + } # case 'addperm' + + case 'removeperm' : { + $spotUserSystem->removePermFromSecGroup($this->_groupId, + $this->_editSecGroupForm); + $editResult = array('result' => 'success'); + + break; + } # case 'removeparm' + + case 'setallow' : + case 'setdeny' : { + $this->_editSecGroupForm['deny'] = (bool) ($formAction == 'setdeny'); + + $spotUserSystem->setDenyForPermFromSecGroup($this->_groupId, + $this->_editSecGroupForm); + $editResult = array('result' => 'success'); + + break; + } # case 'setallow' / 'setdeny' + + case 'addgroup' : + case 'changename' : { + # update het security group record + $secGroup['name'] = $this->_editSecGroupForm['name']; + + # controleer en repareer alle preferences + list ($formMessages['errors'], $secGroup) = $spotUserSystem->validateSecGroup($secGroup); + + if (empty($formMessages['errors'])) { + # en update de database + switch($formAction) { + case 'changename' : $spotUserSystem->setSecGroup($secGroup); break; + case 'addgroup' : $spotUserSystem->addSecGroup($secGroup); break; + } # switch + + $editResult = array('result' => 'success'); + } else { + $editResult = array('result' => 'failure'); + } # if + + break; + } # case 'changename' + + } # switch + } # if + + #- display stuff -# + $this->template('editsecgroup', array('securitygroup' => $secGroup, + 'formmessages' => $formMessages, + 'http_referer' => $this->_editSecGroupForm['http_referer'], + 'editresult' => $editResult)); + } # render + +} # class SpotPage_editsecgroup diff --git a/lib/page/SpotPage_editsettings.php b/lib/page/SpotPage_editsettings.php index 3414b786e..895e5bdf4 100755 --- a/lib/page/SpotPage_editsettings.php +++ b/lib/page/SpotPage_editsettings.php @@ -2,8 +2,8 @@ class SpotPage_editsettings extends SpotPage_Abs { private $_editSettingsFrom; - function __construct(SpotDb $db, SpotSettings $settings, $currentSession, $params) { - parent::__construct($db, $settings, $currentSession); + function __construct(Dao_Factory $daoFactory, SpotSettings $settings, $currentSession, $params) { + parent::__construct($daoFactory, $settings, $currentSession); $this->_editSettingsForm = $params['editsettingsform']; } # ctor diff --git a/lib/page/SpotPage_edituser.php b/lib/page/SpotPage_edituser.php index 29e25dd89..258525716 100755 --- a/lib/page/SpotPage_edituser.php +++ b/lib/page/SpotPage_edituser.php @@ -1,201 +1,201 @@ -_editUserForm = $params['edituserform']; - $this->_userIdToEdit = $params['userid']; - } # ctor - - /* - * Erase all fields from the user record which shouldn't - * be in the form anyways - */ - function cleanseEditForm($editForm) { - /* Make sure the preferences aren't set using this page as it might override security */ - $validFields = array('firstname', 'lastname', 'mail', 'newpassword1', 'newpassword2', 'grouplist', 'prefs'); - foreach($editForm as $key => $value) { - if (in_array($key, $validFields) === false) { - unset($editForm[$key]); - } # if - } # foreach - - return $editForm; - } # cleanseEditForm - - function render() { - $groupMembership = array(); - $formMessages = array('errors' => array(), - 'info' => array()); - - # check the users' permissions - if ($this->_userIdToEdit == $this->_currentSession['user']['userid']) { - $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_edit_own_user, ''); - } else { - $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_edit_other_users, ''); - } # if - - # per default the result is 'not tried' - $editResult = array(); - - # Instantiate the spotuser object - $spotUserSystem = new SpotUserSystem($this->_db, $this->_settings); - - # and create a nic and shiny page title - $this->_pageTitle = "spot: edit user"; - - # retrieve the to-edit user - $spotUser = $this->_db->getUser($this->_userIdToEdit); - if ($spotUser === false) { - $formMessages['errors'][] = sprintf(_('User %d can not be found'), $this->_userIdToEdit); - $editResult = array('result' => 'failure'); - } # if - - # request the users' groupmembership - if ($spotUser != false) { - $groupMembership = $this->_db->getGroupList($spotUser['userid']); - } # if - - /* - * bring the forms' action into the local scope for - * easier access - */ - $formAction = $this->_editUserForm['action']; - - # Only perform certain validations when the form is actually submitted - if ((!empty($formAction)) && (empty($formMessages['errors']))) { - # sta niet toe, dat de admin user gewist wordt - if (($spotUser['userid'] <= SPOTWEB_ADMIN_USERID) && ($formAction == 'delete')) { - $formMessages['errors'][] = _('Admin and Anonymous can not be deleted'); - $editResult = array('result' => 'failure'); - } # if - } # if - - - # Only perform certain validations when the form is actually submitted - if ((!empty($formAction)) && (empty($formMessages['errors']))) { - switch($formAction) { - case 'delete' : { - $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_delete_user, ''); - - $spotUser = array_merge($spotUser, $this->_editUserForm); - $spotUserSystem->removeUser($spotUser['userid']); - $editResult = array('result' => 'success'); - - break; - } # case delete - - case 'edit' : { - # Remove any non-valid fields from the array - $this->_editUserForm = $this->cleanseEditForm($this->_editUserForm); - - # validate the user fields - $spotUser = array_merge($spotUser, $this->_editUserForm); - $formMessages['errors'] = $spotUserSystem->validateUserRecord($spotUser, true); - - if (empty($formMessages['errors'])) { - # actually update the user record - $spotUserSystem->setUser($spotUser); - - /* - * Update the users' password, but only when - * a new password is given - */ - if (!empty($spotUser['newpassword1'])) { - $spotUserSystem->setUserPassword($spotUser); - } # if - - /* - * Did we get an groupmembership list? If so, - * try to update it as well - */ - if (isset($this->_editUserForm['grouplist'])) { - # retrieve the list of user groups - $groupList = array(); - foreach($this->_editUserForm['grouplist'] as $val) { - if ($val != 'dummy') { - $groupList[] = array('groupid' => $val, - 'prio' => count($groupList)); - } # if - } # for - - # make sure there is at least one group - if (count($groupList) < 1) { - $formMessages['errors'][] = _('A user must be member of at least one group'); - $editResult = array('result' => 'failure'); - } else { - # Mangle the current group membership to a common format - $currentGroupList = array(); - foreach($groupList as $value) { - $currentGroupList[] = $value['groupid']; - } # foreach - - # and mangle the new requested group membership - $tobeGroupList = array(); - foreach($groupMembership as $value) { - $tobeGroupList[] = $value['id']; - } # foreach - - /* - * Try to compare the grouplist with the current - * grouplist. If the grouplist changes, the user - * needs change group membership permissions - */ - sort($currentGroupList, SORT_NUMERIC); - sort($tobeGroupList, SORT_NUMERIC); - - /* - * If the groupmembership list changes, lets make sure - * the user has the specific permission - */ - $groupDiff = (count($currentGroupList) != count($tobeGroupList)); - for ($i = 0; $i < count($currentGroupList) && !$groupDiff; $i++) { - $groupDiff = ($currentGroupList[$i] != $tobeGroupList[$i]); - } # for - - if ($groupDiff) { - if ($this->_spotSec->allowed(SpotSecurity::spotsec_edit_groupmembership, '')) { - $spotUserSystem->setUserGroupList($spotUser, $groupList); - } else { - $formMessages['errors'][] = _('Changing group membership is not allowed'); - $editResult = array('result' => 'failure'); - } # else - } # if - } # if - } # if - - # report success - $editResult = array('result' => 'success'); - } else { - $editResult = array('result' => 'failure'); - } # else - break; - } # case 'edit' - - case 'removeallsessions' : { - $spotUserSystem->removeAllUserSessions($spotUser['userid']); - $editResult = array('result' => 'success'); - - break; - } # case 'removeallsessions' - - case 'resetuserapi' : { - $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_consume_api, ''); - - $user = $spotUserSystem->resetUserApi($spotUser); - $editResult = array('result' => 'success', 'newapikey' => $user['apikey']); - break; - } # case resetuserapi - } # switch - } # if - - #- display stuff -# - $this->template('edituser', array('edituserform' => $spotUser, - 'formmessages' => $formMessages, - 'editresult' => $editResult, - 'groupMembership' => $groupMembership)); - } # render - -} # class SpotPage_edituser +_editUserForm = $params['edituserform']; + $this->_userIdToEdit = $params['userid']; + } # ctor + + /* + * Erase all fields from the user record which shouldn't + * be in the form anyways + */ + function cleanseEditForm($editForm) { + /* Make sure the preferences aren't set using this page as it might override security */ + $validFields = array('firstname', 'lastname', 'mail', 'newpassword1', 'newpassword2', 'grouplist', 'prefs'); + foreach($editForm as $key => $value) { + if (in_array($key, $validFields) === false) { + unset($editForm[$key]); + } # if + } # foreach + + return $editForm; + } # cleanseEditForm + + function render() { + $groupMembership = array(); + $formMessages = array('errors' => array(), + 'info' => array()); + + # check the users' permissions + if ($this->_userIdToEdit == $this->_currentSession['user']['userid']) { + $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_edit_own_user, ''); + } else { + $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_edit_other_users, ''); + } # if + + # per default the result is 'not tried' + $editResult = array(); + + # Instantiate the spotuser object + $spotUserSystem = new SpotUserSystem($this->_db, $this->_settings); + + # and create a nic and shiny page title + $this->_pageTitle = "spot: edit user"; + + # retrieve the to-edit user + $spotUser = $this->_db->getUser($this->_userIdToEdit); + if ($spotUser === false) { + $formMessages['errors'][] = sprintf(_('User %d can not be found'), $this->_userIdToEdit); + $editResult = array('result' => 'failure'); + } # if + + # request the users' groupmembership + if ($spotUser != false) { + $groupMembership = $this->_db->getGroupList($spotUser['userid']); + } # if + + /* + * bring the forms' action into the local scope for + * easier access + */ + $formAction = $this->_editUserForm['action']; + + # Only perform certain validations when the form is actually submitted + if ((!empty($formAction)) && (empty($formMessages['errors']))) { + # sta niet toe, dat de admin user gewist wordt + if (($spotUser['userid'] <= SPOTWEB_ADMIN_USERID) && ($formAction == 'delete')) { + $formMessages['errors'][] = _('Admin and Anonymous can not be deleted'); + $editResult = array('result' => 'failure'); + } # if + } # if + + + # Only perform certain validations when the form is actually submitted + if ((!empty($formAction)) && (empty($formMessages['errors']))) { + switch($formAction) { + case 'delete' : { + $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_delete_user, ''); + + $spotUser = array_merge($spotUser, $this->_editUserForm); + $spotUserSystem->removeUser($spotUser['userid']); + $editResult = array('result' => 'success'); + + break; + } # case delete + + case 'edit' : { + # Remove any non-valid fields from the array + $this->_editUserForm = $this->cleanseEditForm($this->_editUserForm); + + # validate the user fields + $spotUser = array_merge($spotUser, $this->_editUserForm); + $formMessages['errors'] = $spotUserSystem->validateUserRecord($spotUser, true); + + if (empty($formMessages['errors'])) { + # actually update the user record + $spotUserSystem->setUser($spotUser); + + /* + * Update the users' password, but only when + * a new password is given + */ + if (!empty($spotUser['newpassword1'])) { + $spotUserSystem->setUserPassword($spotUser); + } # if + + /* + * Did we get an groupmembership list? If so, + * try to update it as well + */ + if (isset($this->_editUserForm['grouplist'])) { + # retrieve the list of user groups + $groupList = array(); + foreach($this->_editUserForm['grouplist'] as $val) { + if ($val != 'dummy') { + $groupList[] = array('groupid' => $val, + 'prio' => count($groupList)); + } # if + } # for + + # make sure there is at least one group + if (count($groupList) < 1) { + $formMessages['errors'][] = _('A user must be member of at least one group'); + $editResult = array('result' => 'failure'); + } else { + # Mangle the current group membership to a common format + $currentGroupList = array(); + foreach($groupList as $value) { + $currentGroupList[] = $value['groupid']; + } # foreach + + # and mangle the new requested group membership + $tobeGroupList = array(); + foreach($groupMembership as $value) { + $tobeGroupList[] = $value['id']; + } # foreach + + /* + * Try to compare the grouplist with the current + * grouplist. If the grouplist changes, the user + * needs change group membership permissions + */ + sort($currentGroupList, SORT_NUMERIC); + sort($tobeGroupList, SORT_NUMERIC); + + /* + * If the groupmembership list changes, lets make sure + * the user has the specific permission + */ + $groupDiff = (count($currentGroupList) != count($tobeGroupList)); + for ($i = 0; $i < count($currentGroupList) && !$groupDiff; $i++) { + $groupDiff = ($currentGroupList[$i] != $tobeGroupList[$i]); + } # for + + if ($groupDiff) { + if ($this->_spotSec->allowed(SpotSecurity::spotsec_edit_groupmembership, '')) { + $spotUserSystem->setUserGroupList($spotUser, $groupList); + } else { + $formMessages['errors'][] = _('Changing group membership is not allowed'); + $editResult = array('result' => 'failure'); + } # else + } # if + } # if + } # if + + # report success + $editResult = array('result' => 'success'); + } else { + $editResult = array('result' => 'failure'); + } # else + break; + } # case 'edit' + + case 'removeallsessions' : { + $spotUserSystem->removeAllUserSessions($spotUser['userid']); + $editResult = array('result' => 'success'); + + break; + } # case 'removeallsessions' + + case 'resetuserapi' : { + $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_consume_api, ''); + + $user = $spotUserSystem->resetUserApi($spotUser); + $editResult = array('result' => 'success', 'newapikey' => $user['apikey']); + break; + } # case resetuserapi + } # switch + } # if + + #- display stuff -# + $this->template('edituser', array('edituserform' => $spotUser, + 'formmessages' => $formMessages, + 'editresult' => $editResult, + 'groupMembership' => $groupMembership)); + } # render + +} # class SpotPage_edituser diff --git a/lib/page/SpotPage_edituserprefs.php b/lib/page/SpotPage_edituserprefs.php index b359c62fc..a6f89c609 100755 --- a/lib/page/SpotPage_edituserprefs.php +++ b/lib/page/SpotPage_edituserprefs.php @@ -1,163 +1,163 @@ -_editUserPrefsForm = $params['edituserprefsform']; - $this->_userIdToEdit = $params['userid']; - $this->_dialogembedded = $params['dialogembedded']; - } # ctor - - function render() { - $formMessages = array('errors' => array(), - 'info' => array()); - - # Validate proper permissions - if ($this->_userIdToEdit == $this->_currentSession['user']['userid']) { - $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_edit_own_userprefs, ''); - } else { - $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_edit_other_users, ''); - } # if - - # Make sure the editresult is set to 'not comitted' per default - $editResult = array(); - - # Instantiat the user system as necessary for the management of user preferences - $spotUserSystem = new SpotUserSystem($this->_db, $this->_settings); - - # zet de page title - $this->_pageTitle = "spot: edit user preferences"; - - # retrieve the to-edit user - $spotUser = $this->_db->getUser($this->_userIdToEdit); - if ($spotUser === false) { - $formMessages['errors'][] = sprintf(_('User %d can not be found'), $this->_userIdToEdit); - $editResult = array('result' => 'failure'); - } # if - - /* - * bring the forms' action into the local scope for - * easier access - */ - $formAction = $this->_editUserPrefsForm['action']; - - /* - * We want the annymous' users account so we can use this users' preferences as a - * template. This makes sure all properties are atleast set. - */ - $anonUser = $this->_db->getUser(SPOTWEB_ANONYMOUS_USERID); - - # Are we trying to submit this form, or only rendering it? - if ((!empty($formAction)) && (empty($formMessages['errors']))) { - switch($formAction) { - case 'edit' : { - /* - * We have a few dummy preferenes -- these are submitted like a checkbox for example - * but in reality do something completely different. - * - * Because we use cleanseUserPreferences() those dummies will not end up in the database - */ - if (isset($this->_editUserPrefsForm['_dummy_prevent_porn'])) { - $spotUserSystem->setIndexFilter( - $spotUser['userid'], - array('valuelist' => array(), - 'title' => 'Index filter', - 'torder' => 999, - 'tparent' => 0, - 'children' => array(), - 'filtertype' => 'index_filter', - 'sorton' => '', - 'sortorder' => '', - 'enablenotify' => false, - 'icon' => 'spotweb.png', - 'tree' => '~cat0_z3')); - } else { - $spotUserSystem->removeIndexFilter($spotUser['userid']); - } # if - - # Save the current' user preferences because we need them before cleansing - $savePrefs = $spotUser['prefs']; - $spotUser['prefs'] = $spotUserSystem->cleanseUserPreferences($this->_editUserPrefsForm, - $anonUser['prefs'], - $this->_tplHelper->getTemplatePreferences()); - - # Validate all preferences - list($formMessages['errors'], $spotUser['prefs']) = $spotUserSystem->validateUserPreferences($spotUser['prefs'], $savePrefs); - - # Make sure user has permission to select this template - if ($spotUser['prefs']['normal_template'] != $savePrefs['normal_template']) { - $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_select_template, $spotUser['prefs']['normal_template']); - } # if - - if ($spotUser['prefs']['mobile_template'] != $savePrefs['mobile_template']) { - $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_select_template, $spotUser['prefs']['mobile_template']); - } # if - - if ($spotUser['prefs']['tablet_template'] != $savePrefs['tablet_template']) { - $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_select_template, $spotUser['prefs']['tablet_template']); - } # if - - if (empty($formMessages['errors'])) { - # Make sure an NZB file was provided - if (isset($_FILES['edituserprefsform'])) { - $uploadError = $_FILES['edituserprefsform']['error']['avatar']; - - /** - * Give a proper error if the file is too large, because changeAvatar() wont see - * these errors so they cannot provide the error - */ - if (($uploadError == UPLOAD_ERR_FORM_SIZE) || ($uploadError == UPLOAD_ERR_INI_SIZE)) { - $formMessages['errors'][] = _("Uploaded file is too large"); - } # if - - if ($uploadError == UPLOAD_ERR_OK) { - $formMessages['errors'] = $spotUserSystem->changeAvatar( - $spotUser['userid'], - file_get_contents($_FILES['edituserprefsform']['tmp_name']['avatar'])); - } # if - } # if - } # if - - if (empty($formMessages['errors'])) { - # and actually update the user in the database - $spotUserSystem->setUser($spotUser); - - # if we didnt get an exception, it automatically succeeded - $editResult = array('result' => 'success'); - } else { - $editResult = array('result' => 'failure'); - } # else - - /* - * We have the register Spotweb with the notification providers (growl, prowl, etc) atleast once. - * The safes option is to just do this wih each preferences submit. But first we create a fake - * session for this user. - */ - $fakeSession = $spotUserSystem->createNewSession($spotUser['userid']); - $fakeSession['security'] = new SpotSecurity($this->_db, $this->_settings, $fakeSession['user'], ''); - - $spotsNotifications = new SpotNotifications($this->_db, $this->_settings, $fakeSession); - $spotsNotifications->register(); - - break; - } # case 'edit' - - case 'cancel' : { - $editResult = array('result' => 'success'); - } # case 'cancel' - } # switch - } # if - - #- display stuff -# - $this->template('edituserprefs', array('edituserprefsform' => $spotUser['prefs'], - 'formmessages' => $formMessages, - 'spotuser' => $spotUser, - 'dialogembedded' => $this->_dialogembedded, - 'http_referer' => $this->_editUserPrefsForm['http_referer'], - 'edituserprefsresult' => $editResult)); - } # render - -} # class SpotPage_edituserprefs +_editUserPrefsForm = $params['edituserprefsform']; + $this->_userIdToEdit = $params['userid']; + $this->_dialogembedded = $params['dialogembedded']; + } # ctor + + function render() { + $formMessages = array('errors' => array(), + 'info' => array()); + + # Validate proper permissions + if ($this->_userIdToEdit == $this->_currentSession['user']['userid']) { + $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_edit_own_userprefs, ''); + } else { + $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_edit_other_users, ''); + } # if + + # Make sure the editresult is set to 'not comitted' per default + $editResult = array(); + + # Instantiat the user system as necessary for the management of user preferences + $spotUserSystem = new SpotUserSystem($this->_db, $this->_settings); + + # zet de page title + $this->_pageTitle = "spot: edit user preferences"; + + # retrieve the to-edit user + $spotUser = $this->_db->getUser($this->_userIdToEdit); + if ($spotUser === false) { + $formMessages['errors'][] = sprintf(_('User %d can not be found'), $this->_userIdToEdit); + $editResult = array('result' => 'failure'); + } # if + + /* + * bring the forms' action into the local scope for + * easier access + */ + $formAction = $this->_editUserPrefsForm['action']; + + /* + * We want the annymous' users account so we can use this users' preferences as a + * template. This makes sure all properties are atleast set. + */ + $anonUser = $this->_db->getUser(SPOTWEB_ANONYMOUS_USERID); + + # Are we trying to submit this form, or only rendering it? + if ((!empty($formAction)) && (empty($formMessages['errors']))) { + switch($formAction) { + case 'edit' : { + /* + * We have a few dummy preferenes -- these are submitted like a checkbox for example + * but in reality do something completely different. + * + * Because we use cleanseUserPreferences() those dummies will not end up in the database + */ + if (isset($this->_editUserPrefsForm['_dummy_prevent_porn'])) { + $spotUserSystem->setIndexFilter( + $spotUser['userid'], + array('valuelist' => array(), + 'title' => 'Index filter', + 'torder' => 999, + 'tparent' => 0, + 'children' => array(), + 'filtertype' => 'index_filter', + 'sorton' => '', + 'sortorder' => '', + 'enablenotify' => false, + 'icon' => 'spotweb.png', + 'tree' => '~cat0_z3')); + } else { + $spotUserSystem->removeIndexFilter($spotUser['userid']); + } # if + + # Save the current' user preferences because we need them before cleansing + $savePrefs = $spotUser['prefs']; + $spotUser['prefs'] = $spotUserSystem->cleanseUserPreferences($this->_editUserPrefsForm, + $anonUser['prefs'], + $this->_tplHelper->getTemplatePreferences()); + + # Validate all preferences + list($formMessages['errors'], $spotUser['prefs']) = $spotUserSystem->validateUserPreferences($spotUser['prefs'], $savePrefs); + + # Make sure user has permission to select this template + if ($spotUser['prefs']['normal_template'] != $savePrefs['normal_template']) { + $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_select_template, $spotUser['prefs']['normal_template']); + } # if + + if ($spotUser['prefs']['mobile_template'] != $savePrefs['mobile_template']) { + $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_select_template, $spotUser['prefs']['mobile_template']); + } # if + + if ($spotUser['prefs']['tablet_template'] != $savePrefs['tablet_template']) { + $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_select_template, $spotUser['prefs']['tablet_template']); + } # if + + if (empty($formMessages['errors'])) { + # Make sure an NZB file was provided + if (isset($_FILES['edituserprefsform'])) { + $uploadError = $_FILES['edituserprefsform']['error']['avatar']; + + /** + * Give a proper error if the file is too large, because changeAvatar() wont see + * these errors so they cannot provide the error + */ + if (($uploadError == UPLOAD_ERR_FORM_SIZE) || ($uploadError == UPLOAD_ERR_INI_SIZE)) { + $formMessages['errors'][] = _("Uploaded file is too large"); + } # if + + if ($uploadError == UPLOAD_ERR_OK) { + $formMessages['errors'] = $spotUserSystem->changeAvatar( + $spotUser['userid'], + file_get_contents($_FILES['edituserprefsform']['tmp_name']['avatar'])); + } # if + } # if + } # if + + if (empty($formMessages['errors'])) { + # and actually update the user in the database + $spotUserSystem->setUser($spotUser); + + # if we didnt get an exception, it automatically succeeded + $editResult = array('result' => 'success'); + } else { + $editResult = array('result' => 'failure'); + } # else + + /* + * We have the register Spotweb with the notification providers (growl, prowl, etc) atleast once. + * The safes option is to just do this wih each preferences submit. But first we create a fake + * session for this user. + */ + $fakeSession = $spotUserSystem->createNewSession($spotUser['userid']); + $fakeSession['security'] = new SpotSecurity($this->_db, $this->_settings, $fakeSession['user'], ''); + + $spotsNotifications = new SpotNotifications($this->_db, $this->_settings, $fakeSession); + $spotsNotifications->register(); + + break; + } # case 'edit' + + case 'cancel' : { + $editResult = array('result' => 'success'); + } # case 'cancel' + } # switch + } # if + + #- display stuff -# + $this->template('edituserprefs', array('edituserprefsform' => $spotUser['prefs'], + 'formmessages' => $formMessages, + 'spotuser' => $spotUser, + 'dialogembedded' => $this->_dialogembedded, + 'http_referer' => $this->_editUserPrefsForm['http_referer'], + 'edituserprefsresult' => $editResult)); + } # render + +} # class SpotPage_edituserprefs diff --git a/lib/page/SpotPage_getimage.php b/lib/page/SpotPage_getimage.php index 479bc87f8..bf9de3059 100755 --- a/lib/page/SpotPage_getimage.php +++ b/lib/page/SpotPage_getimage.php @@ -3,8 +3,8 @@ class SpotPage_getimage extends SpotPage_Abs { private $_messageid; private $_image; - function __construct(SpotDb $db, SpotSettings $settings, $currentSession, $params) { - parent::__construct($db, $settings, $currentSession); + function __construct(Dao_Factory $daoFactory, SpotSettings $settings, $currentSession, $params) { + parent::__construct($daoFactory, $settings, $currentSession); $this->_messageid = $params['messageid']; $this->_image = $params['image']; } # ctor diff --git a/lib/page/SpotPage_getnzb.php b/lib/page/SpotPage_getnzb.php index bec6b95b4..61cd6c9ea 100755 --- a/lib/page/SpotPage_getnzb.php +++ b/lib/page/SpotPage_getnzb.php @@ -1,50 +1,50 @@ -_messageid = $params['messageid']; - $this->_action = $params['action']; - } # ctor - - + private $_messageid; + private $_action; + + function __construct(Dao_Factory $daoFactory, SpotSettings $settings, $currentSession, $params) { + parent::__construct($daoFactory, $settings, $currentSession); + $this->_messageid = $params['messageid']; + $this->_action = $params['action']; + } # ctor + + function render() { $hdr_spotnntp = new SpotNntp($this->_settings->get('nntp_hdr')); - - # Controleer de users' rechten - $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_retrieve_nzb, ''); - - # als het niet display is, check of we ook download integratie rechten hebben - if ($this->_action != 'display') { - $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_download_integration, $this->_action); - } # if - - /* Als de HDR en de NZB host hetzelfde zijn, zet geen tweede verbinding op */ - $settings_nntp_hdr = $this->_settings->get('nntp_hdr'); - $settings_nntp_nzb = $this->_settings->get('nntp_nzb'); - if ($settings_nntp_hdr['host'] == $settings_nntp_nzb['host']) { + + # Controleer de users' rechten + $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_retrieve_nzb, ''); + + # als het niet display is, check of we ook download integratie rechten hebben + if ($this->_action != 'display') { + $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_download_integration, $this->_action); + } # if + + /* Als de HDR en de NZB host hetzelfde zijn, zet geen tweede verbinding op */ + $settings_nntp_hdr = $this->_settings->get('nntp_hdr'); + $settings_nntp_nzb = $this->_settings->get('nntp_nzb'); + if ($settings_nntp_hdr['host'] == $settings_nntp_nzb['host']) { $nzb_spotnntp = $hdr_spotnntp; } else { $nzb_spotnntp = new SpotNntp($this->_settings->get('nntp_nzb')); } # else - - # NZB files mogen liever niet gecached worden op de client - $this->sendExpireHeaders(true); - - try { - $spotNzb = new SpotNzb($this->_db, $this->_settings); - $spotNzb->handleNzbAction($this->_messageid, $this->_currentSession, - $this->_action, $hdr_spotnntp, $nzb_spotnntp); - - if ($this->_action != 'display') { - echo "OK"; - } # if - } - catch(Exception $x) { - echo "ERROR" . $x->getMessage() . ""; - } # catch - } # render - -} # SpotPage_getnzb + + # NZB files mogen liever niet gecached worden op de client + $this->sendExpireHeaders(true); + + try { + $spotNzb = new SpotNzb($this->_db, $this->_settings); + $spotNzb->handleNzbAction($this->_messageid, $this->_currentSession, + $this->_action, $hdr_spotnntp, $nzb_spotnntp); + + if ($this->_action != 'display') { + echo "OK"; + } # if + } + catch(Exception $x) { + echo "ERROR" . $x->getMessage() . ""; + } # catch + } # render + +} # SpotPage_getnzb diff --git a/lib/page/SpotPage_getnzbmobile.php b/lib/page/SpotPage_getnzbmobile.php index 37cfda87d..e3a3c0be9 100755 --- a/lib/page/SpotPage_getnzbmobile.php +++ b/lib/page/SpotPage_getnzbmobile.php @@ -1,50 +1,50 @@ -_messageid = $params['messageid']; - $this->_action = $params['action']; - } # ctor - - - function render() { - $hdr_spotnntp = new SpotNntp($this->_settings->get('nntp_hdr')); - - # Controleer de users' rechten - $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_retrieve_nzb, ''); - - # als het niet display is, check of we ook download integratie rechten hebben - if ($this->_action != 'display') { - $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_download_integration, $this->_action); - } # if - - /* Als de HDR en de NZB host hetzelfde zijn, zet geen tweede verbinding op */ - $settings_nntp_hdr = $this->_settings->get('nntp_hdr'); - $settings_nntp_nzb = $this->_settings->get('nntp_nzb'); - if ($settings_nntp_hdr['host'] == $settings_nntp_nzb['host']) { - $nzb_spotnntp = $hdr_spotnntp; - } else { - $nzb_spotnntp = new SpotNntp($this->_settings->get('nntp_nzb')); - } # else - - # NZB files mogen liever niet gecached worden op de client - $this->sendExpireHeaders(true); - - try { - $spotNzb = new SpotNzb($this->_db, $this->_settings); - $spotNzb->handleNzbAction($this->_messageid, $this->_currentSession, - $this->_action, $hdr_spotnntp, $nzb_spotnntp); - - if ($this->_action != 'display') { - echo "

NZB saved.

OK
"; - } # if - } - catch(Exception $x) { - echo "

" . $x->getMessage() . "

OK
"; - } # catch - } # render - -} # SpotPage_getnzb +_messageid = $params['messageid']; + $this->_action = $params['action']; + } # ctor + + + function render() { + $hdr_spotnntp = new SpotNntp($this->_settings->get('nntp_hdr')); + + # Controleer de users' rechten + $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_retrieve_nzb, ''); + + # als het niet display is, check of we ook download integratie rechten hebben + if ($this->_action != 'display') { + $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_download_integration, $this->_action); + } # if + + /* Als de HDR en de NZB host hetzelfde zijn, zet geen tweede verbinding op */ + $settings_nntp_hdr = $this->_settings->get('nntp_hdr'); + $settings_nntp_nzb = $this->_settings->get('nntp_nzb'); + if ($settings_nntp_hdr['host'] == $settings_nntp_nzb['host']) { + $nzb_spotnntp = $hdr_spotnntp; + } else { + $nzb_spotnntp = new SpotNntp($this->_settings->get('nntp_nzb')); + } # else + + # NZB files mogen liever niet gecached worden op de client + $this->sendExpireHeaders(true); + + try { + $spotNzb = new SpotNzb($this->_db, $this->_settings); + $spotNzb->handleNzbAction($this->_messageid, $this->_currentSession, + $this->_action, $hdr_spotnntp, $nzb_spotnntp); + + if ($this->_action != 'display') { + echo "

NZB saved.

OK
"; + } # if + } + catch(Exception $x) { + echo "

" . $x->getMessage() . "

OK
"; + } # catch + } # render + +} # SpotPage_getnzb diff --git a/lib/page/SpotPage_getspot.php b/lib/page/SpotPage_getspot.php index cfabeed2a..22177e12b 100755 --- a/lib/page/SpotPage_getspot.php +++ b/lib/page/SpotPage_getspot.php @@ -1,24 +1,24 @@ -_messageid = $messageid; - } # ctor - - function render() { - # Controleer de users' rechten - $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_view_spotdetail, ''); - - # Haal de volledige spotinhoud op - $fullSpot = $this->_tplHelper->getFullSpot($this->_messageid, true); - - # zet de page title - $this->_pageTitle = "spot: " . $fullSpot['title']; - - #- display stuff -# - $this->template('spotinfo', array('spot' => $fullSpot)); - } # render - +_messageid = $messageid; + } # ctor + + function render() { + # Controleer de users' rechten + $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_view_spotdetail, ''); + + # Haal de volledige spotinhoud op + $fullSpot = $this->_tplHelper->getFullSpot($this->_messageid, true); + + # zet de page title + $this->_pageTitle = "spot: " . $fullSpot['title']; + + #- display stuff -# + $this->template('spotinfo', array('spot' => $fullSpot)); + } # render + } # class SpotPage_getspot \ No newline at end of file diff --git a/lib/page/SpotPage_index.php b/lib/page/SpotPage_index.php index 6f5583799..3853c0ebe 100755 --- a/lib/page/SpotPage_index.php +++ b/lib/page/SpotPage_index.php @@ -2,9 +2,9 @@ class SpotPage_index extends SpotPage_Abs { private $_params; - function __construct(SpotDb $db, SpotSettings $settings, $currentSession, $params) { + function __construct(Dao_Factory $daoFactory, SpotSettings $settings, $currentSession, $params) { SpotTiming::start('SpotPage_Index::ctor'); - parent::__construct($db, $settings, $currentSession); + parent::__construct($daoFactory, $settings, $currentSession); $this->_params = $params; @@ -31,7 +31,7 @@ function render() { # Zet the query parameters om naar een lijst met filters, velden, # en sorteringen etc - $spotUserSystem = new SpotUserSystem($this->_db, $this->_settings); + $spotUserSystem = new SpotUserSystem($this->_daoFactory, $this->_settings); $parsedSearch = $spotsOverview->filterToQuery($this->_params['search'], array('field' => $this->_params['sortby'], 'direction' => $this->_params['sortdir']), $this->_currentSession, diff --git a/lib/page/SpotPage_login.php b/lib/page/SpotPage_login.php index c3f96b554..6db5a5e35 100755 --- a/lib/page/SpotPage_login.php +++ b/lib/page/SpotPage_login.php @@ -1,70 +1,70 @@ -_loginForm = $params['loginform']; - $this->_params = $params; - } # ctor - - function render() { - $formMessages = array('errors' => array(), - 'info' => array()); - - # Controleer de users' rechten - $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_perform_login, ''); - - # creeer een default credentials zodat het form altijd - # de waardes van het form kan renderen - $credentials = array('username' => '', - 'password' => ''); - - # login verzoek was standaard niet geprobeerd - $loginResult = array(); - - # Instantieer het Spot user system - $spotUserSystem = new SpotUserSystem($this->_db, $this->_settings); - - # zet de page title - $this->_pageTitle = "spot: login"; - - # bring the form action into the local scope - $formAction = $this->_loginForm['action']; - - # Is dit een submit van een form, of nog maar de aanroep? - if (!empty($formAction)) { - # valideer de user - $credentials = array_merge($credentials, $this->_loginForm); - - $tryLogin = $spotUserSystem->login($credentials['username'], $credentials['password']); - if (!$tryLogin) { - /* Create an audit event */ - if ($this->_settings->get('auditlevel') != SpotSecurity::spot_secaudit_none) { - $spotAudit = new SpotAudit($this->_db, $this->_settings, $this->_currentSession['user'], $this->_currentSession['session']['ipaddr']); - $spotAudit->audit(SpotSecurity::spotsec_perform_login, 'incorrect user or pass', false); - } # if - - $loginResult = array('result' => 'failure'); - $formMessages['errors'][] = _('Invalid username or password'); - } else { - $loginResult = array('result' => 'success'); - $this->_currentSession = $tryLogin; - } # else - } else { - # Als de user al een sessie heeft, voeg een waarschuwing toe - if ($this->_currentSession['user']['userid'] != $this->_settings->get('nonauthenticated_userid')) { - $loginResult = array('result' => 'alreadyloggedin'); - } # if - } # else - - #- display stuff -# - $this->template('login', array('loginform' => $credentials, - 'formmessages' => $formMessages, - 'loginresult' => $loginResult, - 'http_referer' => $this->_loginForm['http_referer'], - 'data' => $this->_params['data'])); - } # render - -} # class SpotPage_login +_loginForm = $params['loginform']; + $this->_params = $params; + } # ctor + + function render() { + $formMessages = array('errors' => array(), + 'info' => array()); + + # Controleer de users' rechten + $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_perform_login, ''); + + # creeer een default credentials zodat het form altijd + # de waardes van het form kan renderen + $credentials = array('username' => '', + 'password' => ''); + + # login verzoek was standaard niet geprobeerd + $loginResult = array(); + + # Instantieer het Spot user system + $spotUserSystem = new SpotUserSystem($this->_db, $this->_settings); + + # zet de page title + $this->_pageTitle = "spot: login"; + + # bring the form action into the local scope + $formAction = $this->_loginForm['action']; + + # Is dit een submit van een form, of nog maar de aanroep? + if (!empty($formAction)) { + # valideer de user + $credentials = array_merge($credentials, $this->_loginForm); + + $tryLogin = $spotUserSystem->login($credentials['username'], $credentials['password']); + if (!$tryLogin) { + /* Create an audit event */ + if ($this->_settings->get('auditlevel') != SpotSecurity::spot_secaudit_none) { + $spotAudit = new SpotAudit($this->_db, $this->_settings, $this->_currentSession['user'], $this->_currentSession['session']['ipaddr']); + $spotAudit->audit(SpotSecurity::spotsec_perform_login, 'incorrect user or pass', false); + } # if + + $loginResult = array('result' => 'failure'); + $formMessages['errors'][] = _('Invalid username or password'); + } else { + $loginResult = array('result' => 'success'); + $this->_currentSession = $tryLogin; + } # else + } else { + # Als de user al een sessie heeft, voeg een waarschuwing toe + if ($this->_currentSession['user']['userid'] != $this->_settings->get('nonauthenticated_userid')) { + $loginResult = array('result' => 'alreadyloggedin'); + } # if + } # else + + #- display stuff -# + $this->template('login', array('loginform' => $credentials, + 'formmessages' => $formMessages, + 'loginresult' => $loginResult, + 'http_referer' => $this->_loginForm['http_referer'], + 'data' => $this->_params['data'])); + } # render + +} # class SpotPage_login diff --git a/lib/page/SpotPage_newznabapi.php b/lib/page/SpotPage_newznabapi.php index 463ef019f..bb38db765 100755 --- a/lib/page/SpotPage_newznabapi.php +++ b/lib/page/SpotPage_newznabapi.php @@ -2,8 +2,8 @@ class SpotPage_newznabapi extends SpotPage_Abs { private $_params; - function __construct(SpotDb $db, SpotSettings $settings, $currentSession, $params) { - parent::__construct($db, $settings, $currentSession); + function __construct(Dao_Factory $daoFactory, SpotSettings $settings, $currentSession, $params) { + parent::__construct($daoFactory, $settings, $currentSession); $this->_params = $params; } # __construct diff --git a/lib/page/SpotPage_nzbhandlerapi.php b/lib/page/SpotPage_nzbhandlerapi.php index 9399b6d2d..ea381e5ff 100755 --- a/lib/page/SpotPage_nzbhandlerapi.php +++ b/lib/page/SpotPage_nzbhandlerapi.php @@ -1,125 +1,120 @@ -_spotSec->fatalPermCheck(SpotSecurity::spotsec_use_sabapi, ''); - - parse_str($_SERVER['QUERY_STRING'], $request); - - $apikey = $this->_currentSession['user']['apikey']; - if ($this->_tplHelper->apiToHash($apikey) != $request['nzbhandlerapikey']) { - error_log('API Key Incorrect'); - echo 'API Key Incorrect'; - - return ; - } # if - - $nzbHandlerFactory = new NzbHandler_Factory(); - $this->_nzbHandler = $nzbHandlerFactory->build($this->_settings, - $this->_currentSession['user']['prefs']['nzbhandling']['action'], - $this->_currentSession['user']['prefs']['nzbhandling']); - - if ($this->_nzbHandler->hasApiSupport() !== false) - { - $action = strtolower($request['action']); - - switch($action) - { - # actions on the entire queue - case 'getstatus': - $result = $this->_nzbHandler->getStatus(); - break; - case 'pausequeue': - $result = $this->_nzbHandler->pauseQueue(); - break; - case 'resumequeue': - $result = $this->_nzbHandler->resumeQueue(); - break; - case 'setspeedlimit': - $result = $this->_nzbHandler->setSpeedLimit($request['limit']); - break; - # actions on a specific download - case 'movedown': - $result = $this->_nzbHandler->moveDown($request['id']); - break; - case 'moveup': - $result = $this->_nzbHandler->moveUp($request['id']); - break; - case 'movetop': - $result = $this->_nzbHandler->moveTop($request['id']); - break; - case 'movebottom': - $result = $this->_nzbHandler->moveBottom($request['id']); - break; - case 'setcategory': - $result = $this->_nzbHandler->setCategory($request['id'], $request['category']); - break; - case 'setpriority': - $result = $this->_nzbHandler->setPriority($request['id'], $request['priority']); - break; - case 'setpassword': - $result = $this->_nzbHandler->setPassword($request['id'], $request['password']); - break; - case 'delete': - $result = $this->_nzbHandler->delete($request['id']); - break; - case 'rename': - $result = $this->_nzbHandler->rename($request['id'], $request['name']); - break; - case 'pause': - $result = $this->_nzbHandler->pause($request['id']); - break; - case 'resume': - $result = $this->_nzbHandler->resume($request['id']); - break; - # non download related actions - case 'getcategories': - $result = $this->_nzbHandler->getCategories(); - break; - case 'getversion': - $tmp = $this->_nzbHandler->getVersion(); - if ($tmp === false) - { - $result = false; - } - else - { - $result['version'] = $tmp; - } - break; - default: - # default action - $result = false; - } - } - else - { - error_log('The configured NZB handler has no api support'); - echo 'The configured NZB handler has no api support'; - - return ; - } - - # de nzbhandlerapi output moet niet gecached worden - $this->sendExpireHeaders(true); - $this->sendContentTypeHeader('json'); - - if (($result === true) || ($result === false)) - { - $tmp['result'] = $result; - $result = $tmp; - } - $result = json_encode($result); - - echo $result; - } # render - +_spotSec->fatalPermCheck(SpotSecurity::spotsec_use_sabapi, ''); + + parse_str($_SERVER['QUERY_STRING'], $request); + + $apikey = $this->_currentSession['user']['apikey']; + if ($this->_tplHelper->apiToHash($apikey) != $request['nzbhandlerapikey']) { + error_log('API Key Incorrect'); + echo 'API Key Incorrect'; + + return ; + } # if + + $nzbHandlerFactory = new NzbHandler_Factory(); + $this->_nzbHandler = $nzbHandlerFactory->build($this->_settings, + $this->_currentSession['user']['prefs']['nzbhandling']['action'], + $this->_currentSession['user']['prefs']['nzbhandling']); + + if ($this->_nzbHandler->hasApiSupport() !== false) + { + $action = strtolower($request['action']); + + switch($action) + { + # actions on the entire queue + case 'getstatus': + $result = $this->_nzbHandler->getStatus(); + break; + case 'pausequeue': + $result = $this->_nzbHandler->pauseQueue(); + break; + case 'resumequeue': + $result = $this->_nzbHandler->resumeQueue(); + break; + case 'setspeedlimit': + $result = $this->_nzbHandler->setSpeedLimit($request['limit']); + break; + # actions on a specific download + case 'movedown': + $result = $this->_nzbHandler->moveDown($request['id']); + break; + case 'moveup': + $result = $this->_nzbHandler->moveUp($request['id']); + break; + case 'movetop': + $result = $this->_nzbHandler->moveTop($request['id']); + break; + case 'movebottom': + $result = $this->_nzbHandler->moveBottom($request['id']); + break; + case 'setcategory': + $result = $this->_nzbHandler->setCategory($request['id'], $request['category']); + break; + case 'setpriority': + $result = $this->_nzbHandler->setPriority($request['id'], $request['priority']); + break; + case 'setpassword': + $result = $this->_nzbHandler->setPassword($request['id'], $request['password']); + break; + case 'delete': + $result = $this->_nzbHandler->delete($request['id']); + break; + case 'rename': + $result = $this->_nzbHandler->rename($request['id'], $request['name']); + break; + case 'pause': + $result = $this->_nzbHandler->pause($request['id']); + break; + case 'resume': + $result = $this->_nzbHandler->resume($request['id']); + break; + # non download related actions + case 'getcategories': + $result = $this->_nzbHandler->getCategories(); + break; + case 'getversion': + $tmp = $this->_nzbHandler->getVersion(); + if ($tmp === false) + { + $result = false; + } + else + { + $result['version'] = $tmp; + } + break; + default: + # default action + $result = false; + } + } + else + { + error_log('The configured NZB handler has no api support'); + echo 'The configured NZB handler has no api support'; + + return ; + } + + # de nzbhandlerapi output moet niet gecached worden + $this->sendExpireHeaders(true); + $this->sendContentTypeHeader('json'); + + if (($result === true) || ($result === false)) + { + $tmp['result'] = $result; + $result = $tmp; + } + $result = json_encode($result); + + echo $result; + } # render + } # class SpotPage_nzbhandlerapi \ No newline at end of file diff --git a/lib/page/SpotPage_postcomment.php b/lib/page/SpotPage_postcomment.php index a705c3099..cf42e06e8 100755 --- a/lib/page/SpotPage_postcomment.php +++ b/lib/page/SpotPage_postcomment.php @@ -3,8 +3,8 @@ class SpotPage_postcomment extends SpotPage_Abs { private $_inReplyTo; private $_commentForm; - function __construct(SpotDb $db, SpotSettings $settings, $currentSession, $params) { - parent::__construct($db, $settings, $currentSession); + function __construct(Dao_Factory $daoFactory, SpotSettings $settings, $currentSession, $params) { + parent::__construct($daoFactory, $settings, $currentSession); $this->_commentForm = $params['commentform']; $this->_inReplyTo = $params['inreplyto']; } # ctor @@ -20,7 +20,7 @@ function render() { $spotParseUtil = new Services_Format_Util(); # spot signing is nodig voor het RSA signen van de spot en dergelijke - $spotSigning = Services_Signing_Base::newServiceSigning(); + $spotSigning = Services_Signing_Base::factory(); # creeer een default comment zodat het form altijd # de waardes van het form kan renderen @@ -75,7 +75,6 @@ function render() { if (!empty($this->_currentSession['user']['avatar'])) { $comment['user-avatar'] = $this->_currentSession['user']['avatar']; } else { - $spotSigning = Services_Signing_Base::newServiceSigning(); $tmpKey = $spotSigning->getPublicKey($this->_currentSession['user']['privatekey']); $comment['user-key'] = $tmpKey['publickey']; } # else diff --git a/lib/page/SpotPage_postspot.php b/lib/page/SpotPage_postspot.php index e4d23384a..5c51e6f66 100755 --- a/lib/page/SpotPage_postspot.php +++ b/lib/page/SpotPage_postspot.php @@ -2,8 +2,8 @@ class SpotPage_postspot extends SpotPage_Abs { private $_spotForm; - function __construct(SpotDb $db, SpotSettings $settings, $currentSession, $params) { - parent::__construct($db, $settings, $currentSession); + function __construct(Dao_Factory $daoFactory, SpotSettings $settings, $currentSession, $params) { + parent::__construct($daoFactory, $settings, $currentSession); $this->_spotForm = $params['spotform']; } # ctor @@ -18,7 +18,7 @@ function render() { $spotParseUtil = new Services_Format_Util(); # spot signing is nodig voor het RSA signen van de spot en dergelijke - $spotSigning = Services_Signing_Base::newServiceSigning(); + $spotSigning = Services_Signing_Base::factory(); # creeer een default spot zodat het form altijd # de waardes van het form kan renderen diff --git a/lib/page/SpotPage_render.php b/lib/page/SpotPage_render.php index 3a78e9eaf..eee8943ab 100755 --- a/lib/page/SpotPage_render.php +++ b/lib/page/SpotPage_render.php @@ -1,38 +1,38 @@ -_tplname = $tplName; - $this->_params = $params; - } # ctor - - function sanitizeTplName($tpl) { - $validChars = 'abcdefghijklmnopqrstuvwxyz0123456789'; - - $newName = ''; - for($i = 0; $i < strlen($tpl); $i++) { - if (strpos($validChars, $tpl[$i]) !== false) { - $newName .= $tpl[$i]; - } # if - } # for - - return $newName; - } # sanitizeTplName - - function render() { - # Haal de volledige spotinhoud op - $spotsOverview = new SpotsOverview($this->_db, $this->_settings); - - # sanitize the template name - $tplFile = $this->sanitizeTplName($this->_tplname); - - #- display stuff -# - if (strlen($tplFile) > 0) { - $this->template($tplFile, $this->_params); - } # if - } # render - -} # class SpotPage_render +_tplname = $tplName; + $this->_params = $params; + } # ctor + + function sanitizeTplName($tpl) { + $validChars = 'abcdefghijklmnopqrstuvwxyz0123456789'; + + $newName = ''; + for($i = 0; $i < strlen($tpl); $i++) { + if (strpos($validChars, $tpl[$i]) !== false) { + $newName .= $tpl[$i]; + } # if + } # for + + return $newName; + } # sanitizeTplName + + function render() { + # Haal de volledige spotinhoud op + $spotsOverview = new SpotsOverview($this->_db, $this->_settings); + + # sanitize the template name + $tplFile = $this->sanitizeTplName($this->_tplname); + + #- display stuff -# + if (strlen($tplFile) > 0) { + $this->template($tplFile, $this->_params); + } # if + } # render + +} # class SpotPage_render diff --git a/lib/page/SpotPage_reportpost.php b/lib/page/SpotPage_reportpost.php index 3ff53ff77..8114d2b77 100755 --- a/lib/page/SpotPage_reportpost.php +++ b/lib/page/SpotPage_reportpost.php @@ -3,8 +3,8 @@ class SpotPage_reportpost extends SpotPage_Abs { private $_inReplyTo; private $_reportForm; - function __construct(SpotDb $db, SpotSettings $settings, $currentSession, $params) { - parent::__construct($db, $settings, $currentSession); + function __construct(Dao_Factory $daoFactory, SpotSettings $settings, $currentSession, $params) { + parent::__construct($daoFactory, $settings, $currentSession); $this->_reportForm = $params['reportform']; $this->_inReplyTo = $params['inreplyto']; } # ctor @@ -20,7 +20,7 @@ function render() { $spotParser = new Services_Format_Parsing(); # spot signing is nodig voor het RSA signen van de spot en dergelijke - $spotSigning = Services_Signing_Base::newServiceSigning(); + $spotSigning = Services_Signing_Base::factory(); # creeer een default report $report = array('body' => 'This is SPAM!', diff --git a/lib/page/SpotPage_rss.php b/lib/page/SpotPage_rss.php index 226e36d77..fcdd7d850 100755 --- a/lib/page/SpotPage_rss.php +++ b/lib/page/SpotPage_rss.php @@ -2,8 +2,8 @@ class SpotPage_rss extends SpotPage_Abs { private $_params; - function __construct(SpotDb $db, SpotSettings $settings, $currentSession, $params) { - parent::__construct($db, $settings, $currentSession); + function __construct(Dao_Factory $daoFactory, SpotSettings $settings, $currentSession, $params) { + parent::__construct($daoFactory, $settings, $currentSession); $this->_params = $params; } diff --git a/lib/page/SpotPage_statics.php b/lib/page/SpotPage_statics.php index d4b0667f6..6046f09a9 100755 --- a/lib/page/SpotPage_statics.php +++ b/lib/page/SpotPage_statics.php @@ -9,8 +9,8 @@ class SpotPage_statics extends SpotPage_Abs { private $_params; private $_currentCssFile; - function __construct(SpotDb $db, SpotSettings $settings, $currentSession, $params) { - parent::__construct($db, $settings, $currentSession); + function __construct(Dao_Factory $daoFactory, SpotSettings $settings, $currentSession, $params) { + parent::__construct($daoFactory, $settings, $currentSession); $this->_params = $params; } # ctor diff --git a/lib/page/SpotPage_statistics.php b/lib/page/SpotPage_statistics.php index 6b9123427..08772fa70 100755 --- a/lib/page/SpotPage_statistics.php +++ b/lib/page/SpotPage_statistics.php @@ -2,8 +2,8 @@ class SpotPage_statistics extends SpotPage_Abs { private $_params; - function __construct(SpotDb $db, SpotSettings $settings, $currentSession, $params) { - parent::__construct($db, $settings, $currentSession); + function __construct(Dao_Factory $daoFactory, SpotSettings $settings, $currentSession, $params) { + parent::__construct($daoFactory, $settings, $currentSession); $this->_params = $params; } # ctor diff --git a/lib/page/SpotPage_twitteroauth.php b/lib/page/SpotPage_twitteroauth.php index 22d153f92..57e1ec294 100755 --- a/lib/page/SpotPage_twitteroauth.php +++ b/lib/page/SpotPage_twitteroauth.php @@ -1,88 +1,88 @@ -_params = $params; - } - - function render() { - # Controleer de users' rechten - $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_send_notifications_services, 'twitter'); - - # Instantieer het Spot user system & notificatiesysteem - $spotUserSystem = new SpotUserSystem($this->_db, $this->_settings); - $spotsNotifications = new SpotNotifications($this->_db, $this->_settings, $this->_currentSession); - - $requestArray = array_merge_recursive($this->_currentSession['user']['prefs']['notifications']['twitter'], - array('consumer_key' => $this->_settings->get('twitter_consumer_key'), - 'consumer_secret' => $this->_settings->get('twitter_consumer_secret')) - ); - - if ($this->_params['action'] == 'verify') { - $this->_notificationService = Notifications_Factory::build('Spotweb', 'twitter', $requestArray); - # een foute PIN invoeren geeft een notice, terwijl we zonder notice al een prima foutafhandeling hebben - list ($http_code, $access_token) = @$this->_notificationService->verifyPIN($this->_params['pin']); - - if ($http_code == 200) { - # request_token hebben we niet meer nodig - $this->_currentSession['user']['prefs']['notifications']['twitter']['request_token'] = ''; - $this->_currentSession['user']['prefs']['notifications']['twitter']['request_token_secret'] = ''; - # access_token is wat we wel willen opslaan - $this->_currentSession['user']['prefs']['notifications']['twitter']['screen_name'] = $access_token['screen_name']; - $this->_currentSession['user']['prefs']['notifications']['twitter']['access_token'] = $access_token['oauth_token']; - $this->_currentSession['user']['prefs']['notifications']['twitter']['access_token_secret'] = $access_token['oauth_token_secret']; - $spotUserSystem->setUser($this->_currentSession['user']); - echo "Account " . $access_token['screen_name'] . " geverifiëerd."; - } else { - echo "Code " . $http_code . ": " . $this->getError($http_code); - } # if - } elseif ($this->_params['action'] == 'remove') { - $screen_name = $this->_currentSession['user']['prefs']['notifications']['twitter']['screen_name']; - $this->_currentSession['user']['prefs']['notifications']['twitter']['screen_name'] = ''; - $this->_currentSession['user']['prefs']['notifications']['twitter']['access_token'] = ''; - $this->_currentSession['user']['prefs']['notifications']['twitter']['access_token_secret'] = ''; - $spotUserSystem->setUser($this->_currentSession['user']); - echo "Account " . $screen_name . " verwijderd."; - } else { - $this->_notificationService = Notifications_Factory::build('Spotweb', 'twitter', $requestArray); - list ($http_code, $request_token, $registerURL) = @$this->_notificationService->requestAuthorizeURL(); - - if ($http_code == 200) { - # request_token slaan we op in de preferences, deze hebben we - # weer nodig wanneer de PIN wordt ingevoerd - $this->_currentSession['user']['prefs']['notifications']['twitter']['request_token'] = $request_token['oauth_token']; - $this->_currentSession['user']['prefs']['notifications']['twitter']['request_token_secret'] = $request_token['oauth_token_secret']; - $spotUserSystem->setUser($this->_currentSession['user']); - echo $registerURL; - } else { - echo "Code " . $http_code . ": " . $this->getError($http_code); - } # if - - } # if - } # render - - function getError($errcode) { - # http://dev.twitter.com/pages/responses_errors - switch ($errcode) { - case 200: $errtext = "OK"; break; - case 304: $errtext = "Not Modified"; break; - case 400: $errtext = "Bad Request"; break; - case 401: $errtext = "Unauthorized"; break; - case 403: $errtext = "Forbidden"; break; - case 404: $errtext = "Not Found"; break; - case 406: $errtext = "Not Acceptable"; break; - case 420: $errtext = "Enhance Your Calm"; break; - case 500: $errtext = "Internal Server Error"; break; - case 502: $errtext = "Bad Gateway"; break; - case 503: $errtext = "Service Unavailable"; break; - default: $errtext = "Unknown error"; break; - } # switch - - return ($errtext); - } # getError - +_params = $params; + } + + function render() { + # Controleer de users' rechten + $this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_send_notifications_services, 'twitter'); + + # Instantieer het Spot user system & notificatiesysteem + $spotUserSystem = new SpotUserSystem($this->_db, $this->_settings); + $spotsNotifications = new SpotNotifications($this->_db, $this->_settings, $this->_currentSession); + + $requestArray = array_merge_recursive($this->_currentSession['user']['prefs']['notifications']['twitter'], + array('consumer_key' => $this->_settings->get('twitter_consumer_key'), + 'consumer_secret' => $this->_settings->get('twitter_consumer_secret')) + ); + + if ($this->_params['action'] == 'verify') { + $this->_notificationService = Notifications_Factory::build('Spotweb', 'twitter', $requestArray); + # een foute PIN invoeren geeft een notice, terwijl we zonder notice al een prima foutafhandeling hebben + list ($http_code, $access_token) = @$this->_notificationService->verifyPIN($this->_params['pin']); + + if ($http_code == 200) { + # request_token hebben we niet meer nodig + $this->_currentSession['user']['prefs']['notifications']['twitter']['request_token'] = ''; + $this->_currentSession['user']['prefs']['notifications']['twitter']['request_token_secret'] = ''; + # access_token is wat we wel willen opslaan + $this->_currentSession['user']['prefs']['notifications']['twitter']['screen_name'] = $access_token['screen_name']; + $this->_currentSession['user']['prefs']['notifications']['twitter']['access_token'] = $access_token['oauth_token']; + $this->_currentSession['user']['prefs']['notifications']['twitter']['access_token_secret'] = $access_token['oauth_token_secret']; + $spotUserSystem->setUser($this->_currentSession['user']); + echo "Account " . $access_token['screen_name'] . " geverifiëerd."; + } else { + echo "Code " . $http_code . ": " . $this->getError($http_code); + } # if + } elseif ($this->_params['action'] == 'remove') { + $screen_name = $this->_currentSession['user']['prefs']['notifications']['twitter']['screen_name']; + $this->_currentSession['user']['prefs']['notifications']['twitter']['screen_name'] = ''; + $this->_currentSession['user']['prefs']['notifications']['twitter']['access_token'] = ''; + $this->_currentSession['user']['prefs']['notifications']['twitter']['access_token_secret'] = ''; + $spotUserSystem->setUser($this->_currentSession['user']); + echo "Account " . $screen_name . " verwijderd."; + } else { + $this->_notificationService = Notifications_Factory::build('Spotweb', 'twitter', $requestArray); + list ($http_code, $request_token, $registerURL) = @$this->_notificationService->requestAuthorizeURL(); + + if ($http_code == 200) { + # request_token slaan we op in de preferences, deze hebben we + # weer nodig wanneer de PIN wordt ingevoerd + $this->_currentSession['user']['prefs']['notifications']['twitter']['request_token'] = $request_token['oauth_token']; + $this->_currentSession['user']['prefs']['notifications']['twitter']['request_token_secret'] = $request_token['oauth_token_secret']; + $spotUserSystem->setUser($this->_currentSession['user']); + echo $registerURL; + } else { + echo "Code " . $http_code . ": " . $this->getError($http_code); + } # if + + } # if + } # render + + function getError($errcode) { + # http://dev.twitter.com/pages/responses_errors + switch ($errcode) { + case 200: $errtext = "OK"; break; + case 304: $errtext = "Not Modified"; break; + case 400: $errtext = "Bad Request"; break; + case 401: $errtext = "Unauthorized"; break; + case 403: $errtext = "Forbidden"; break; + case 404: $errtext = "Not Found"; break; + case 406: $errtext = "Not Acceptable"; break; + case 420: $errtext = "Enhance Your Calm"; break; + case 500: $errtext = "Internal Server Error"; break; + case 502: $errtext = "Bad Gateway"; break; + case 503: $errtext = "Service Unavailable"; break; + default: $errtext = "Unknown error"; break; + } # switch + + return ($errtext); + } # getError + } # class SpotPage_twitteroauth \ No newline at end of file diff --git a/lib/services/BWList/Services_BWList_Retriever.php b/lib/services/BWList/Services_BWList_Retriever.php new file mode 100644 index 000000000..9c425bc37 --- /dev/null +++ b/lib/services/BWList/Services_BWList_Retriever.php @@ -0,0 +1,74 @@ +_blackWhiteListDao = $blackWhiteListDao; + $this->_cacheDao = $cacheDao; + $this->_svcPrvHttp = new Services_Providers_Http($cacheDao); + } # ctor + + /* + * Retrieve a black or whitelist from the ewb + */ + private function retrieveExternalList($listUrl) { + /* + * Actually retrieve the list + */ + list($http_code, $items) = $this->_svcPrvHttp->getFromWeb($listUrl, false, 30*60); + + /* + * If the list didn't modify, that's enough to know + */ + if ($http_code == 304) { + return false; + } elseif (strpos($items,">")) { + throw new CorruptBWListException(); + } # else + + /* + * We've come so far, the list might be valid + */ + $expItems = explode(chr(10), $items); + + # Perform a very small sanity check on the black/whitelist + if ((count($expItems) > 5) && (strlen($expItems[0]) < 10)) { + return $expItems; + } else { + throw new CorruptBWListException(); + } # else + } # retrieveExternalList + + /* + * Retrieve the blacklist + */ + public function retrieveBlackList($listUrl) { + $result = $this->retrieveExternalList($listUrl); + + if ($result !== false) { + $result = $this->_blackWhiteListDao->updateExternalList($result, 'black'); + } # if + + return $result; + } # retrieveBlackList + + /* + * Retrieve the whitelist + */ + public function retrieveWhiteList($listUrl) { + $result = $this->retrieveExternalList($listUrl); + + if ($result !== false) { + $result = $this->_blackWhiteListDao->updateExternalList($result, 'white'); + } # if + + return $result; + } # retrieveWhiteList + +} # Services_BWList_Retriever diff --git a/lib/services/Format/Services_Format_Parsing.php b/lib/services/Format/Services_Format_Parsing.php index 0066360b7..a30631d3f 100755 --- a/lib/services/Format/Services_Format_Parsing.php +++ b/lib/services/Format/Services_Format_Parsing.php @@ -4,7 +4,7 @@ class Services_Format_Parsing { private $_util; function __construct() { - $this->_spotSigning = Services_Signing_Base::newServiceSigning(); + $this->_spotSigning = Services_Signing_Base::factory(); $this->_util = new Services_Format_Util(); } # ctor diff --git a/lib/services/Nntp/Services_Nntp_Engine.php b/lib/services/Nntp/Services_Nntp_Engine.php index 8bf3eb7bb..4e28c5bbc 100644 --- a/lib/services/Nntp/Services_Nntp_Engine.php +++ b/lib/services/Nntp/Services_Nntp_Engine.php @@ -131,6 +131,15 @@ public function getBody($msgid) { * if necessary */ public function connect() { + /* + * Store the username and password in it, + * we will not put it in member variables + * because they might show up in a stack + * trace + */ + static $tmpUser; + static $tmpPass; + # dummy operation if ($this->_connected) { return ; @@ -155,13 +164,19 @@ public function connect() { /* * Erase username/password so it won't show up in any stacktrace + * + * Because this class can be reused (e - reconnected) without + * reconstructing it, we cannot simple */ - $tmpUser = $this->_user; - $tmpPass = $this->_pass; - $this->_user = '*FILTERED*'; - $this->_pass = '*FILTERED*'; + if (($this->_user !== '*FILTERED*') && ($this->_pass !== '*FILTERED*')) { + $tmpUser = $this->_user; + $tmpPass = $this->_pass; - try{ + $this->_user = '*FILTERED*'; + $this->_pass = '*FILTERED*'; + } # if + + try { $ret = $this->_nntp->connect($this->_server, $this->_serverenc, $this->_serverport, 10); if ($ret === false) { throw new NntpException('Error while connecting to server (server did not respond)', -1); diff --git a/lib/services/Nntp/Services_Nntp_EnginePool.php b/lib/services/Nntp/Services_Nntp_EnginePool.php new file mode 100644 index 000000000..0a97bc35e --- /dev/null +++ b/lib/services/Nntp/Services_Nntp_EnginePool.php @@ -0,0 +1,59 @@ +get('nntp_hdr'); + if (empty($settings_nntp_hdr)) { + throw new MissingNntpConfigurationException(); + } # if + + /* + * Retrieve the NNTP header settings we can validate those + */ + switch ($type) { + case 'hdr' : self::$_instances[$type] = new Services_Nntp_Engine($settings_nntp_hdr); break; + case 'bin' : { + + $settings_nntp_bin = $settings->get('nntp_nzb'); + if (empty($settings_nntp_nzb['host'])) { + self::$_instances[$type] = self::pool($settings, 'hdr'); + } else { + self::$_instances[$type] = new Services_Nntp_Engine($settings_nntp_nzb); + } # else + + break; + } # nzb + + case 'post' : { + $settings_nntp_post = $settings->get('nntp_post'); + if (empty($settings_nntp_post['host'])) { + self::$_instances[$type] = self::pool($settings, 'hdr'); + } else { + self::$_instances[$type] = new Services_Nntp_Engine($settings_nntp_post); + } # else + + break; + } # post + + default : throw new Exception("Unknown NNTP type engine (" . $type . ") for pool creation"); + } # switch + + return self::$_instances[$type]; + } # pool + +} # Services_Nntp_Engine_Pool diff --git a/lib/services/Nntp/Services_Nntp_SpotPosting.php b/lib/services/Nntp/Services_Nntp_SpotPosting.php index 31c114c43..2b9721676 100644 --- a/lib/services/Nntp/Services_Nntp_SpotPosting.php +++ b/lib/services/Nntp/Services_Nntp_SpotPosting.php @@ -32,7 +32,7 @@ private function postPlainMessage($newsgroup, $message, $additionalHeaders) { */ private function postSignedMessage($user, $serverPrivKey, $newsgroup, $message, $additionalHeaders) { # instantiate necessary objects - $spotSigning = Services_Signing_Base::newServiceSigning(); + $spotSigning = Services_Signing_Base::factory(); # also by the SpotWeb server $server_signature = $spotSigning->signMessage($serverPrivKey, '<' . $message['newmessageid'] . '>'); @@ -61,7 +61,7 @@ private function postSignedMessage($user, $serverPrivKey, $newsgroup, $message, public function postBinaryMessage($user, $newsgroup, $body, $additionalHeaders) { $chunkLen = (1024 * 1024); $segmentList = array(); - $spotSigning = Services_Signing_Base::newServiceSigning(); + $spotSigning = Services_Signing_Base::factory(); /* * Now start posting chunks of the binary files @@ -137,7 +137,7 @@ public function postComment($user, $serverPrivKey, $newsgroup, $comment) { */ public function postFullSpot($user, $serverPrivKey, $newsgroup, $spot) { # instantiate the necessary objects - $spotSigning = Services_Signing_Base::newServiceSigning(); + $spotSigning = Services_Signing_Base::factory(); /* * Create the spotnet from header part accrdoing to the following structure: diff --git a/lib/services/Nntp/Services_Nntp_SpotReading.php b/lib/services/Nntp/Services_Nntp_SpotReading.php index f9a5f07dc..9abaa4b15 100644 --- a/lib/services/Nntp/Services_Nntp_SpotReading.php +++ b/lib/services/Nntp/Services_Nntp_SpotReading.php @@ -60,7 +60,7 @@ private function cbCommentDateSort($a, $b) { */ public function readComments($commentList) { $comments = array(); - $spotSigning = Services_Signing_Base::newServiceSigning(); + $spotSigning = Services_Signing_Base::factory(); /* * We retrieve all comments from the server @@ -125,7 +125,7 @@ public function readBinary($segmentList, $compressed) { */ public function readFullSpot($msgId) { # initialize some variables - $spotSigning = Services_Signing_Base::newServiceSigning(); + $spotSigning = Services_Signing_Base::factory(); $spot = array('fullxml' => '', 'user-signature' => '', diff --git a/lib/services/Retriever/Services_Retriever_Base.php b/lib/services/Retriever/Services_Retriever_Base.php index a62aaf53e..de3062be9 100755 --- a/lib/services/Retriever/Services_Retriever_Base.php +++ b/lib/services/Retriever/Services_Retriever_Base.php @@ -1,15 +1,18 @@ _textServer = $textServer; - $this->_binServer = $binServer; - - $this->_db = $db; + function __construct(Dao_Factory $daoFactory, SpotSettings $settings, $debug, $force, $retro) { + $this->_daoFactory = $daoFactory; $this->_settings = $settings; $this->_debug = $debug; $this->_retro = $retro; + $this->_force = $force; + $this->_textServer = $settings->get('nntp_hdr'); + $this->_binServer = $settings->get('nntp_nzb'); + + /* + * Create the specific DAO objects + */ + $this->_nntpCfgDao = $daoFactory->getNntpConfigDao(); /* * Create the service objects for both the NNTP binary group and the * textnews group. We only create a basic NNTP_Engine object, but we * don't create any higher level objects */ - $this->_svcNntpText = new Services_Nntp_Engine($this->_textServer); - - if (!empty($groupList['bin'])) { - if ($this->_textServer['host'] == $this->_binServer['host']) { - $this->_svcNntpBin = $this->_svcNntpBin; - } else { - $this->_svcNntpBin = new Services_Nntp_Engine($this->_binServer); - $this->_svcNntpBin->selectGroup($groupList['bin']); - } # else - } # if + $this->_svcNntpText = Services_Nntp_EnginePool::pool($this->_settings, 'hdr'); + $this->_svcNntpBin = Services_Nntp_EnginePool::pool($this->_settings, 'bin'); } # ctor function debug($s) { @@ -81,17 +81,17 @@ function debug($s) { function connect(array $groupList) { # if an retriever instance is already running, stop this one - if ($this->_db->isRetrieverRunning($this->_textServer['host'])) { + if ((!$this->_force) && ($this->_nntpCfgDao->isRetrieverRunning($this->_textServer['host']))) { throw new RetrieverRunningException(); } # if /* * and notify the system we are running */ - $this->_db->setRetrieverRunning($this->_textServer['host'], true); + $this->_nntpCfgDao->setRetrieverRunning($this->_textServer['host'], true); # and fireup the nntp connection - $this->displayStatus("lastretrieve", $this->_db->getLastUpdate($this->_textServer['host'])); + $this->displayStatus("lastretrieve", $this->_nntpCfgDao->getLastUpdate($this->_textServer['host'])); $this->displayStatus("start", $this->_textServer['host']); /* @@ -199,7 +199,7 @@ function loopTillEnd($curMsg, $increment = 1000) { # reset the start time to prevent a another retriever from starting # during the intial retrieve which can take many hours - $this->_db->setRetrieverRunning($this->_textServer['host'], true); + $this->_nntpCfgDao->setRetrieverRunning($this->_textServer['host'], true); } # while # we are done updating, make sure that if the newsserver deleted @@ -215,7 +215,7 @@ function loopTillEnd($curMsg, $increment = 1000) { function quit() { # notify the system we are not running anymore - $this->_db->setRetrieverRunning($this->_textServer['host'], false); + $this->_nntpCfgDao->setRetrieverRunning($this->_textServer['host'], false); # and disconnect if (!is_null($this->_svcNntpText)) { @@ -266,7 +266,7 @@ function perform() { * and cleanup */ $this->quit(); - $this->_db->setLastUpdate($this->_textServer['host']); + $this->_nntpCfgDao->setLastUpdate($this->_textServer['host']); return $newProcessedCount; } # perform diff --git a/lib/services/Retriever/Services_Retriever_Comments.php b/lib/services/Retriever/Services_Retriever_Comments.php index d8881063b..1f2ef5b5c 100755 --- a/lib/services/Retriever/Services_Retriever_Comments.php +++ b/lib/services/Retriever/Services_Retriever_Comments.php @@ -7,9 +7,12 @@ class Services_Retriever_Comments extends Services_Retriever_Base { * Server is the server array we are expecting to connect to * db - database object */ - function __construct($textServer, $binServer, SpotDb $db, SpotSettings $settings, $debug, $retro) { - parent::__construct($textServer, $binServer, $db, $settings, $debug, $retro); + function __construct(Dao_Factory $daoFactory, SpotSettings $settings, $debug, $force, $retro) { + parent::__construct($daoFactory, $settings, $debug, $force, $retro); + $this->_spotDao = $daoFactory->getSpotDao(); + $this->_commentDao = $daoFactory->getCommentDao(); + $this->_svcNntpTextReading = new Services_Nntp_SpotReading($this->_svcNntpText); $this->_retrieveFull = $this->_settings->get('retrieve_full_comments'); } # ctor @@ -51,7 +54,7 @@ function updateLastRetrieved($highestMessageId) { * always checked so we do not have to do this */ if (!$this->_textServer['buggy']) { - $this->_db->removeExtraComments($highestMessageId); + $this->_commentDao->removeExtraComments($highestMessageId); } # if } # updateLastRetrieved @@ -79,7 +82,7 @@ function process($hdrList, $curMsg, $endMsg, $timer) { * We ask the database to match our messageid's we just retrieved with * the list of id's we have just retrieved from the server */ - $dbIdList = $this->_db->matchCommentMessageIds($hdrList); + $dbIdList = $this->_commentDao->matchCommentMessageIds($hdrList); /* * We keep a seperate list of messageid's for updating the amount of @@ -271,18 +274,18 @@ function process($hdrList, $curMsg, $endMsg, $timer) { } # while if ($this->_retro) { - $this->_db->setMaxArticleid('comments_retro', $endMsg); + $this->_nntpCfgDao->setMaxArticleid('comments_retro', $endMsg); } else { - $this->_db->setMaxArticleid('comments', $endMsg); + $this->_nntpCfgDao->setMaxArticleid('comments', $endMsg); } # if - $this->_db->addComments($commentDbList, $fullComments); + $this->_commentDao->addComments($commentDbList, $fullComments); /* * Recalculate the average spotrating and update the amount * of unverified comments */ - $this->_db->updateSpotRating($spotMsgIdRatingList); - $this->_db->updateSpotCommentCount($spotMsgIdList); + $this->_spotDao->updateSpotRating($spotMsgIdRatingList); + $this->_spotDao->updateSpotCommentCount($spotMsgIdList); return array('count' => count($hdrList), 'headercount' => count($hdrList), 'lastmsgid' => $lastProcessedId); } # process() @@ -300,9 +303,9 @@ function getGroupName() { */ function getMaxArticleId() { if ($this->_retro) { - return $this->_db->getMaxArticleid('comments_retro'); + return $this->_nntpCfgDao->getMaxArticleid('comments_retro'); } else { - return $this->_db->getMaxArticleid('comments'); + return $this->_nntpCfgDao->getMaxArticleid('comments'); } # if } # getMaxArticleId @@ -310,7 +313,7 @@ function getMaxArticleId() { * Returns the highest messageid in the database */ function getMaxMessageId() { - return $this->_db->getMaxMessageId('comments'); + return $this->_spotDao->getMaxMessageId('comments'); } # getMaxMessageId } # Services_Retriever_Comments diff --git a/lib/services/Retriever/Services_Retriever_Reports.php b/lib/services/Retriever/Services_Retriever_Reports.php index 6bc03f86e..9a79e2221 100755 --- a/lib/services/Retriever/Services_Retriever_Reports.php +++ b/lib/services/Retriever/Services_Retriever_Reports.php @@ -4,8 +4,11 @@ class Services_Retriever_Reports extends Services_Retriever_Base { * Server is the server array we are expecting to connect to * db - database object */ - function __construct($textServer, $binServer, SpotDb $db, SpotSettings $settings, $debug) { - parent::__construct($textServer, $binServer, $db, $settings, $debug, false); + function __construct(Dao_Factory $daoFactory, SpotSettings $settings, $debug, $force) { + parent::__construct($daoFactory, $settings, $debug, $force, false); + + $this->_reportDao = $daoFactory->getSpotReportDao(); + $this->_spotDao = $daoFactory->getSpotDao(); } # ctor /* @@ -45,7 +48,7 @@ function updateLastRetrieved($highestMessageId) { * always checked so we do not have to do this */ if (!$this->_textServer['buggy']) { - $this->_db->removeExtraReports($highestMessageId); + $this->_reportDao->removeExtraReports($highestMessageId); } # if } # updateLastRetrieved @@ -63,7 +66,7 @@ function process($hdrList, $curMsg, $endMsg, $timer) { * We ask the database to match our messageid's we just retrieved with * the list of id's we have just retrieved from the server */ - $dbIdList = $this->_db->matchReportMessageIds($hdrList); + $dbIdList = $this->_reportDao->matchReportMessageIds($hdrList); /* * We keep a seperate list of messageid's for updating the amount of @@ -115,11 +118,11 @@ function process($hdrList, $curMsg, $endMsg, $timer) { $this->displayStatus("timer", round(microtime(true) - $timer, 2)); # update the last retrieved article - $this->_db->addReportRefs($reportDbList); - $this->_db->setMaxArticleid('reports', $endMsg); + $this->_reportDao->addReportRefs($reportDbList); + $this->_nntpCfgDao->setMaxArticleid('reports', $endMsg); # Calculate the amount of reports for a spot - $this->_db->updateSpotReportCount($spotMsgIdList); + $this->_spotDao->updateSpotReportCount($spotMsgIdList); return array('count' => count($hdrList), 'headercount' => count($hdrList), 'lastmsgid' => $lastProcessedId); } # process() @@ -136,14 +139,14 @@ function getGroupName() { * Highest articleid for the implementation in the database */ function getMaxArticleId() { - return $this->_db->getMaxArticleid('reports'); + return $this->_nntpCfgDao->getMaxArticleid('reports'); } # getMaxArticleId /* * Returns the highest messageid in the database */ function getMaxMessageId() { - return $this->_db->getMaxMessageId('reports'); + return $this->_spotDao->getMaxMessageId('reports'); } # getMaxMessageId } # Services_Retriever_Reports diff --git a/lib/services/Retriever/Services_Retriever_Spots.php b/lib/services/Retriever/Services_Retriever_Spots.php index 3a78d2525..ebf3fc7f6 100755 --- a/lib/services/Retriever/Services_Retriever_Spots.php +++ b/lib/services/Retriever/Services_Retriever_Spots.php @@ -5,17 +5,47 @@ class Services_Retriever_Spots extends Services_Retriever_Base { private $_prefetch_image; private $_prefetch_nzb; + private $_svcNntpTextReading; + private $_svcNntpBinReading; + private $_svcProvNzb; + private $_svcProvImage; + private $_svcSpotParser; + + private $_spotDao; + private $_commentDao; + private $_cacheDao; + /** * Server is the server array we are expecting to connect to * db - database object */ - function __construct($textServer, $binServer, SpotDb $db, SpotSettings $settings, $debug, $retro) { - parent::__construct($textServer, $binServer, $db, $settings, $debug, $retro); + function __construct(Dao_Factory $daoFactory, SpotSettings $settings, $debug, $force, $retro) { + parent::__construct($daoFactory, $settings, $debug, $force, $retro); $this->_rsakeys = $this->_settings->get('rsa_keys'); $this->_retrieveFull = $this->_settings->get('retrieve_full'); $this->_prefetch_image = $this->_settings->get('prefetch_image'); $this->_prefetch_nzb = $this->_settings->get('prefetch_nzb'); + + $this->_spotDao = $daoFactory->getSpotDao(); + $this->_commentDao = $daoFactory->getCommentDao(); + $this->_cacheDao = $daoFactory->getCacheDao(); + $this->_svcSpotParser = new Services_Format_Parsing(); + + # if we need to fetch images or nzb files, we need several service objects + if ($this->_retrieveFull && ($this->_prefetch_image) || ($this->_prefetch_nzb)) { + /* + * NNTP Spot Reading engine + */ + $this->_svcNntpTextReading = new Services_Nntp_SpotReading($this->_svcNntpText); + $this->_svcNntpBinReading = new Services_Nntp_SpotReading($this->_svcNntpBin); + + $this->_svcProvNzb = new Services_Providers_Nzb($this->_cacheDao, + $this->_svcNntpBinReading); + $this->_svcProvImage = new Services_Providers_SpotImage(new Services_Providers_Http($this->_cacheDao), + $this->_svcNntpBinReading, + $this->_cacheDao); + } # if } # ctor /* @@ -62,7 +92,7 @@ function updateLastRetrieved($highestMessageId) { * always checked so we do not have to do this */ if (!$this->_textServer['buggy']) { - $this->_db->removeExtraSpots($highestMessageId); + $this->_spotDao->removeExtraSpots($highestMessageId); } # if } # updateLastRetrieved @@ -72,7 +102,6 @@ function updateLastRetrieved($highestMessageId) { function process($hdrList, $curMsg, $endMsg, $timer) { $this->displayStatus("progress", ($curMsg) . " till " . ($endMsg)); - $spotParser = new Services_Format_Parsing(); $signedCount = 0; $hdrsRetrieved = 0; $fullsRetrieved = 0; @@ -101,27 +130,10 @@ function process($hdrList, $curMsg, $endMsg, $timer) { * We ask the database to match our messageid's we just retrieved with * the list of id's we have just retrieved from the server */ - $dbIdList = $this->_db->matchSpotMessageIds($hdrList); + $dbIdList = $this->_spotDao->matchSpotMessageIds($hdrList); $this->debug('dbIdList=' . serialize($dbIdList)); - # if we need to fetch images or nzb files, we need several service objects - if ($this->_retrieveFull && ($this->_prefetch_image) || ($this->_prefetch_nzb)) { - /* - * NNTP Spot Reading engine - */ - $this->_svcNntpTextReading = new Services_Nntp_SpotReading($this->_svcNntpText); - $this->_svcNntpBinReading = new Services_Nntp_SpotReading($this->_svcNntpBin); - - $svcProvNzb = new Services_Providers_Nzb($this->_db->_cacheDao, - $this->_svcNntpBinReading); - $svcProvImage = new Services_Providers_SpotImage(new Services_Providers_Http($this->_db->_cacheDao), - $this->_svcNntpBinReading, - $this->_db->_cacheDao); - } # if - - - foreach($hdrList as $msgheader) { $msgCounter++; $this->debug('foreach-loop, start. msgId= ' . $msgCounter); @@ -171,11 +183,11 @@ function process($hdrList, $curMsg, $endMsg, $timer) { if (!$header_isInDb || ((!$fullspot_isInDb || $this->_retro) && $this->_retrieveFull)) { $hdrsRetrieved++; $this->debug('foreach-loop, parsingXover, start. msgId= ' . $msgCounter); - $spot = $spotParser->parseHeader($msgheader['Subject'], - $msgheader['From'], - $msgheader['Date'], - $msgheader['Message-ID'], - $this->_rsakeys); + $spot = $this->_svcSpotParser->parseHeader($msgheader['Subject'], + $msgheader['From'], + $msgheader['Date'], + $msgheader['Message-ID'], + $this->_rsakeys); $this->debug('foreach-loop, parsingXover, done. msgId= ' . $msgCounter); /* @@ -318,8 +330,8 @@ function process($hdrList, $curMsg, $endMsg, $timer) { * again */ if (!$didFetchFullSpot) { - $fullSpot = $this->_db->getFullSpot($msgId, SPOTWEB_ANONYMOUS_USERID); - $fullSpot = array_merge($spotParser->parseFull($fullSpot['fullxml']), $fullSpot); + $fullSpot = $this->_spotDao->getFullSpot($msgId, SPOTWEB_ANONYMOUS_USERID); + $fullSpot = array_merge($this->_svcSpotParser->parseFull($fullSpot['fullxml']), $fullSpot); } # if /* @@ -332,7 +344,7 @@ function process($hdrList, $curMsg, $endMsg, $timer) { */ if (is_array($fullSpot['image']) || ($fullSpot['stamp'] > (int) time()-30*24*60*60)) { $this->debug('foreach-loop, getImage(), start. msgId= ' . $msgId); - $svcProvImage->fetchSpotImage($fullSpot); + $this->_svcProvImage->fetchSpotImage($fullSpot); $this->debug('foreach-loop, getImage(), done. msgId= ' . $msgId); } # if } # if @@ -346,7 +358,7 @@ function process($hdrList, $curMsg, $endMsg, $timer) { */ if (!empty($fullSpot['nzb']) && $fullSpot['stamp'] > 1290578400) { $this->debug('foreach-loop, getNzb(), start. msgId= ' . $msgId); - $svcProvNzb>fetchNzb($fullSpot); + $this->_svcProvNzb>fetchNzb($fullSpot); $this->debug('foreach-loop, getNzb(), done. msgId= ' . $msgId); } # if } # if @@ -395,7 +407,7 @@ function process($hdrList, $curMsg, $endMsg, $timer) { * Add the spots to the database and update the last article * number found */ - $this->_db->addSpots($spotDbList, $fullSpotDbList); + $this->_spotDao->addSpots($spotDbList, $fullSpotDbList); $this->debug('added Spots, spotDbList=' . serialize($spotDbList)); $this->debug('added Spots, fullSpotDbList=' . serialize($fullSpotDbList)); @@ -406,14 +418,14 @@ function process($hdrList, $curMsg, $endMsg, $timer) { switch($this->_settings->get('spot_moderation')) { case 'disable' : break; case 'markspot' : { - $this->_db->markCommentsModerated($moderationList); - $this->_db->markSpotsModerated($moderationList); + $this->_commentDao->markCommentsModerated($moderationList); + $this->_spotDao->markSpotsModerated($moderationList); break; } # case 'markspot' default : { - $this->_db->removeSpots($moderationList); - $this->_db->removeComments($moderationList); + $this->_spotDao->removeSpots($moderationList); + $this->_commentDao->removeComments($moderationList); break; } # default @@ -421,9 +433,9 @@ function process($hdrList, $curMsg, $endMsg, $timer) { # update the maximum article id if ($this->_retro) { - $this->_db->setMaxArticleid('spots_retro', $endMsg); + $this->_nntpCfgDao->setMaxArticleid('spots_retro', $endMsg); } else { - $this->_db->setMaxArticleid($this->_textServer['host'], $endMsg); + $this->_nntpCfgDao->setMaxArticleid($this->_textServer['host'], $endMsg); } # if $this->debug('loop finished, setMaxArticleId=' . serialize($endMsg)); @@ -445,9 +457,9 @@ function getGroupName() { */ function getMaxArticleId() { if ($this->_retro) { - return $this->_db->getMaxArticleid('spots_retro'); + return $this->_nntpCfgDao->getMaxArticleid('spots_retro'); } else { - return $this->_db->getMaxArticleid($this->_textServer['host']); + return $this->_nntpCfgDao->getMaxArticleid($this->_textServer['host']); } # if } # getMaxArticleId @@ -455,7 +467,7 @@ function getMaxArticleId() { * Returns the highest messageid in the database */ function getMaxMessageId() { - return $this->_db->getMaxMessageId('headers'); + return $this->_spotDao->getMaxMessageId('headers'); } # getMaxMessageId diff --git a/lib/services/Signing/Services_Signing_Base.php b/lib/services/Signing/Services_Signing_Base.php index be67830cc..68894bc6c 100644 --- a/lib/services/Signing/Services_Signing_Base.php +++ b/lib/services/Signing/Services_Signing_Base.php @@ -12,7 +12,7 @@ private function __construct() { /* * Create a factory method */ - static public function newServiceSigning() { + static public function factory() { /* * Automatically select OpenSSL if * possible @@ -31,7 +31,7 @@ static public function newServiceSigning() { } else { return new Services_Signing_Php(); } # else - } # newServiceSigning + } # factory /* * Actually validates the RSA signature diff --git a/retrieve.php b/retrieve.php index f8e344025..0404670b8 100755 --- a/retrieve.php +++ b/retrieve.php @@ -2,20 +2,13 @@ error_reporting(2147483647); try { + require_once "lib/SpotClassAutoload.php"; + /* - * If we are run from another directory, try to change the current - * working directory to a directory the script is in + * Initialize the Spotweb base classes */ - if (@!file_exists(getcwd() . '/' . basename($argv[0]))) { - chdir(dirname(__FILE__)); - } # if - - require_once "lib/SpotTranslation.php"; - require_once "lib/SpotClassAutoload.php"; - require_once "settings.php"; - require_once "lib/SpotTiming.php"; - require_once "lib/exceptions/ParseSpotXmlException.php"; - require_once "lib/exceptions/NntpException.php"; + $bootstrap = new Bootstrap(); + list($settings, $daoFactory, $req) = $bootstrap->boot(); /* * disable timing, all queries which are ran by retrieve this would make it use @@ -33,39 +26,15 @@ * When PHP is running in safe mode, max execution time cannot be set, * which is necessary on slow systems for retrieval and statistics generation */ - if (ini_get('safe_mode') ) { + if (ini_get('safe_mode')) { echo "WARNING: PHP safemode is enabled, maximum execution cannot be reset! Turn off safemode if this causes problems" . PHP_EOL . PHP_EOL; } # if - $db = new SpotDb($settings['db']); - $db->connect(); - - # Create the settings object, needed for all other code - $settings = SpotSettings::singleton($db, $settings); - - /* - * The basics has been setup, lets check if the schema needs - * updating - */ - if (!$settings->schemaValid()) { - throw new SchemaNotUpgradedException(); - } # if - - /* - * Does our global setting table need updating? - */ - if (!$settings->settingsValid()) { - throw new SettingsNotUpgradedException(); - } # if - - $req = new SpotReq(); - $req->initialize($settings); - /* * When retrieval is run from the webinterface, we want to make * sure this user is actually allowed to run retrieval. */ - $spotUserSystem = new SpotUserSystem($db, $settings); + $spotUserSystem = new SpotUserSystem($daoFactory, $settings); if (!SpotCommandline::isCommandline()) { /* * An API key is required, so request it and try to @@ -86,28 +55,21 @@ # Add the user's ip addres, we need it for sending notifications $userSession['session'] = array('ipaddr' => ''); } else { - $userSession['user'] = $db->getUser(SPOTWEB_ADMIN_USERID); - $userSession['security'] = new SpotSecurity($db, $settings, $userSession['user'], ''); + $userSession['user'] = $spotUserSystem->getUser(SPOTWEB_ADMIN_USERID); + $userSession['security'] = new SpotSecurity($daoFactory->getUserDao(), + $daoFactory->getAuditDao(), + $settings, + $userSession['user'], + ''); $userSession['session'] = array('ipaddr' => ''); } # if - /* - * Retrieve the NNTP header settings weo can validate those - */ - $settings_nntp_hdr = $settings->get('nntp_hdr'); - $settings_nntp_bin = $settings->get('nntp_nzb'); - if (empty($settings_nntp_hdr['host'])) { - throw new MissingNntpConfigurationException(); - } # if - /* * We normally check whether we are not running already, because * this would mean it will mess up all sorts of things like * comment calculation, but a user can force our hand */ - if (SpotCommandline::get('force')) { - $db->setRetrieverRunning($settings_nntp_hdr['host'], false); - } # if + $forceMode = SpotCommandline::get('force'); /* * Do we need to debuglog this session? Generates loads of @@ -131,15 +93,17 @@ * display the spots, so we delete nzb's, images, comments, etc. */ if (($settings->get('retention') > 0) && (!$retroMode)) { + $spotDao = $daoFactory->getSpotDao(); + switch ($settings->get('retentiontype')) { case 'everything' : { - $db->deleteSpotsRetention($settings->get('retention')); + $spotDao->deleteSpotsRetention($settings->get('retention')); } # case everything case 'fullonly' : { - $db->expireCache($settings->get('retention')); - $db->expireCommentsFull($settings->get('retention')); - $db->expireSpotsFull($settings->get('retention')); + $spotDao->expireCache($settings->get('retention')); + $spotDao->expireCommentsFull($settings->get('retention')); + $spotDao->expireSpotsFull($settings->get('retention')); } # case fullonly } # switch } # if @@ -153,21 +117,19 @@ /* * Actually retrieve spots from the server */ - $retriever = new Services_Retriever_Spots($settings_nntp_hdr, - $settings_nntp_bin, - $db, - $settings, + $retriever = new Services_Retriever_Spots($daoFactory, + $settings, $debugLog, + $forceMode, $retroMode); $newSpotCount = $retriever->perform(); ## Creating filter counts if ($newSpotCount > 0) { - $svcPrv_cacheSpotCount = new Services_Providers_CacheNewSpotCount($db->_userFilterCountDao, - $db->_userFilterDao, - $db->_spotDao, - new Services_Search_QueryParser($db->getDbHandle())); - $svcPrv_cacheSpotCount = new SpotsOverview($db, $settings); + $svcPrv_cacheSpotCount = new Services_Providers_CacheNewSpotCount($daoFactory->getUserFilterCountDao(), + $daoFactory->getUserFilterDao(), + $daoFactory->getSpotDao(), + new Services_Search_QueryParser($daoFactory->getConnection())); echo 'Calculating how many spots are new'; $notifyNewArray = $svcPrv_cacheSpotCount->cacheNewSpotCount(); echo ', done.' . PHP_EOL; @@ -177,11 +139,10 @@ * Should we retrieve comments? */ if ($settings->get('retrieve_comments')) { - $retriever = new Services_Retriever_Comments($settings_nntp_hdr, - $settings_nntp_bin, - $db, + $retriever = new Services_Retriever_Comments($daoFactory, $settings, $debugLog, + $forceMode, $retroMode); $newCommentCount = $retriever->perform(); } # if @@ -190,95 +151,47 @@ * Retrieval of reports */ if ($settings->get('retrieve_reports') && !$retroMode) { - $retriever = new Services_Retriever_Reports($settings_nntp_hdr, - $settings_nntp_bin, - $db, + $retriever = new Services_Retriever_Reports($daoFactory, $settings, - $debugLog); + $debugLog, + $forceMode); $newReportCount = $retriever->perform(); } # if /* * SpotStateList cleanup */ - $db->cleanSpotStateList(); + $daoFactory->getSpotStateListDao()->cleanSpotStateList(); if (!$retroMode) { - $db->expireCache(30); + $daoFactory->getCacheDao()->expireCache(30); } # if ## External blacklist - $settings_external_blacklist = $settings->get('external_blacklist'); - if ($settings_external_blacklist) { - try { - $spotsOverview = new SpotsOverview($db, $settings); - # haal de blacklist op - list($http_code, $blacklist) = $spotsOverview->getFromWeb($settings->get('blacklist_url'), false, 30*60); - - if ($http_code == 304) { - echo "Blacklist not modified, no need to update" . PHP_EOL; - } elseif (strpos($blacklist,">")) { - echo "Error, blacklist does not have expected layout!" . PHP_EOL; - } else { - # update de blacklist - $blacklistarray = explode(chr(10),$blacklist); - - # Perform a very small snaity check on the blacklist - if ((count($blacklistarray) > 5) && (strlen($blacklistarray[0]) < 10)) { - $updateblacklist = $db->updateExternallist($blacklistarray, SpotDb::spotterlist_Black); - echo "Finished updating blacklist. Added " . $updateblacklist['added'] . ", removed " . $updateblacklist['removed'] . ", skipped " . $updateblacklist['skipped'] . " of " . count($blacklistarray) . " lines." . PHP_EOL; - } else { - echo "Blacklist is probably corrupt, skipping" . PHP_EOL; - } # else - } - } catch(Exception $x) { - echo "Fatal error occured while updating blacklist:" . PHP_EOL; - echo " " . $x->getMessage() . PHP_EOL; - echo PHP_EOL . PHP_EOL; - echo $x->getTraceAsString(); - echo PHP_EOL . PHP_EOL; - } - } # if + $svcBwListRetriever = new Services_BWList_Retriever($daoFactory->getBlackWhiteListDao(), $daoFactory->getCacheDao()); + $bwResult = $svcBwListRetriever->retrieveBlackList($settings->get('blacklist_url')); + if ($bwResult === false) { + echo "Blacklist not modified, no need to update" . PHP_EOL; + } else { + echo "Finished updating blacklist. Added " . $bwResult['added'] . ", removed " . $bwResult['removed'] . ", skipped " . $bwResult['skipped'] . " of " . $bwResult['total'] . " lines." . PHP_EOL; + } # else ## External whitelist - $settings_external_whitelist = $settings->get('external_whitelist'); - if ($settings_external_whitelist) { - try { - $spotsOverview = new SpotsOverview($db, $settings); - # haal de whitelist op - list($http_code, $whitelist) = $spotsOverview->getFromWeb($settings->get('whitelist_url'), false, 30*60); - - if ($http_code == 304) { - echo "Whitelist not modified, no need to update" . PHP_EOL; - } elseif (strpos($whitelist,">")) { - echo "Error, whitelist does not have expected layout!" . PHP_EOL; - } else { - # update de whitelist - $whitelistarray = explode(chr(10),$whitelist); - - # Perform a very small snaity check on the whitelist - if ((count($whitelistarray) > 5) && (strlen($whitelistarray[0]) < 10)) { - $updatewhitelist = $db->updateExternallist($whitelistarray, SpotDb::spotterlist_White); - echo "Finished updating whitelist. Added " . $updatewhitelist['added'] . ", removed " . $updatewhitelist['removed'] . ", skipped " . $updatewhitelist['skipped'] . " of " . count($whitelistarray) . " lines." . PHP_EOL; - } else { - echo "Whitelist is probably corrupt, skipping" . PHP_EOL; - } # else - } - } catch(Exception $x) { - echo "Fatal error occured while updating whitelist:" . PHP_EOL; - echo " " . $x->getMessage() . PHP_EOL; - echo PHP_EOL . PHP_EOL; - echo $x->getTraceAsString(); - echo PHP_EOL . PHP_EOL; - } - } # if + $bwResult = $svcBwListRetriever->retrieveWhiteList($settings->get('whitelist_url')); + if ($bwResult === false) { + echo "Whitelist not modified, no need to update" . PHP_EOL; + } else { + echo "Finished updating whitelist. Added " . $bwResult['added'] . ", removed " . $bwResult['removed'] . ", skipped " . $bwResult['skipped'] . " of " . $bwResult['total'] . " lines." . PHP_EOL; + } # else + ## Statistics if ($settings->get('prepare_statistics') && $newSpotCount > 0) { - $svcPrv_Stats = new Services_Providers_Statistics($db->_spotDao, - $db->_cacheDao, - $db->_nntpConfigDao->getLastUpdate($settings_nntp_hdr['host'])); + $settings_nntp_hdr = $settings->get('nntp_hdr'); + $svcPrv_Stats = new Services_Providers_Statistics($daoFactory->getSpotDao(), + $daoFactory->getCachedao(), + $daoFactory->getNntpConfigDao()->getLastUpdate($settings_nntp_hdr['host'])); echo "Starting to create statistics " . PHP_EOL; foreach ($svcPrv_Stats->getValidStatisticsLimits() as $limitValue => $limitName) { @@ -296,7 +209,7 @@ } # if # Verstuur notificaties - $spotsNotifications = new SpotNotifications($db, $settings, $userSession); + $spotsNotifications = new SpotNotifications($daoFactory, $settings, $userSession); if (!empty($notifyNewArray)) { foreach($notifyNewArray as $userId => $newSpotInfo) { foreach($newSpotInfo as $filterInfo) { @@ -307,10 +220,6 @@ } # foreach } # if $spotsNotifications->sendRetrieverFinished($newSpotCount, $newCommentCount, $newReportCount); - - if ($req->getDef('output', '') == 'xml') { - echo ""; - } # if } catch(RetrieverRunningException $x) {