How to add most read topics in ojs 3.1?

Hi, I have added @ajnyga codes in my front page plugins .inc.php file with the indexsite code in the front page tpl. However it is not yet seen. Any idea on what to do next?

Codes in my .inc.php file

	> // Start Most read
  $metricsDao = DAORegistry::getDAO('MetricsDAO');
  $cacheManager =& CacheManager::getManager();
  $cache  =& $cacheManager->getCache('mostread', 0, array($this, '_cacheMiss'));
  $daysToStale = 1;
  $cachedMetrics = false;
  
  if (time() - $cache->getCacheTime() > 60 * 60 * 24 * $daysToStale) {
  	$cachedMetrics = $cache->getContents();
  	$cache->flush();
  }
  $resultMetrics = $cache->getContents();
  
  if (!$resultMetrics && $cachedMetrics) {
  	$resultMetrics = $cachedMetrics;
  	$cache->setEntireCache($cachedMetrics);
  } elseif (!$resultMetrics) {
  	$cache->flush();
  }
  
  $templateMgr->assign('resultMetrics', $resultMetrics);
  
  // End Most read		

}

function _cacheMiss($cache) {
$metricsDao = DAORegistry::getDAO(‘MetricsDAO’);
$publishedArticleDao = DAORegistry::getDAO(‘PublishedArticleDAO’);
$journalDao = DAORegistry::getDAO(‘JournalDAO’);

  	$result = $metricsDao->retrieve("SELECT submission_id, SUM(metric) AS metric FROM metrics WHERE (day BETWEEN CURDATE()-INTERVAL 1 WEEK AND CURDATE()) AND (assoc_type='515' AND submission_id IS NOT NULL) GROUP BY submission_id ORDER BY metric DESC LIMIT 5");
  	
  	while (!$result->EOF) {
  		$resultRow = $result->GetRowAssoc(false);
  		$article = $publishedArticleDao->getPublishedArticleByArticleId($resultRow['submission_id']);	
  		$journal = $journalDao->getById($article->getJournalId());
  		$articles[$resultRow['submission_id']]['journalPath'] = $journal->getPath();
  		$articles[$resultRow['submission_id']]['journalName'] = $journal->getLocalizedName();
  		$articles[$resultRow['submission_id']]['articleId'] = $article->getBestArticleId();
  		$articles[$resultRow['submission_id']]['articleTitle'] = $article->getLocalizedTitle();
  		$articles[$resultRow['submission_id']]['metric'] = $resultRow['metric'];
  		
  		$result->MoveNext();
  	}
  	$result->Close();			
  	$cache->setEntireCache($articles);
  	return $result;

}

Codes in my frontpage.tpl

<ul class="tsv_most_read">
			{foreach from=$resultMetrics item=article}
				<li class="tsv_most_read_article">
					<div class="tsv_most_read_article_title"><a href="{url journal=$article.journalPath page="article" op="view" path=$article.articleId}">{$article.articleTitle}</a></div>
					<div class="tsv_most_read_article_journal"><span class="fa fa-eye"></span> {$article.metric} | {$article.journalName}</div>
				</li>
			{/foreach}	
			</ul>
2 Likes

It would be easier to say if I would see the whole file, meaning also the context. Is the code inside the init function?

1 Like
<?php

import('lib.pkp.classes.plugins.GenericPlugin');
import("plugins.generic.browse.classes.BrowseArticle");

class BrowsePlugin extends GenericPlugin {
    /**
     * Get the display name of this plugin
     * @return string
     */
    function getDisplayName() {
        return __('plugins.generic.browse.displayName');
    }

    /**
     * Get the description of this plugin
     * @return string
     */



    function getDescription() {
        return __('plugins.generic.browse.description');
    }

    public function loadTemplateData($hookName, $args) {		
		$templateMgr = $args[0];
        $template = $args[1];
		$request = Application::getRequest();
        $site = $request->getSite();
		$issueDao = DAORegistry::getDAO('IssueDAO');
		$journalDao = DAORegistry::getDAO('JournalDAO');



// Start Most read
		$metricsDao = DAORegistry::getDAO('MetricsDAO');
		$cacheManager =& CacheManager::getManager();
		$cache  =& $cacheManager->getCache('mostread', 0, array($this, '_cacheMiss'));
		$daysToStale = 1;
		$cachedMetrics = false;
		
		if (time() - $cache->getCacheTime() > 60 * 60 * 24 * $daysToStale) {
			$cachedMetrics = $cache->getContents();
			$cache->flush();
		}
		$resultMetrics = $cache->getContents();
		
		if (!$resultMetrics && $cachedMetrics) {
			$resultMetrics = $cachedMetrics;
			$cache->setEntireCache($cachedMetrics);
		} elseif (!$resultMetrics) {
			$cache->flush();
		}
		
		$templateMgr->assign('resultMetrics', $resultMetrics);
		
		// End Most read		
		
	}
	
	function _cacheMiss($cache) {
			$metricsDao = DAORegistry::getDAO('MetricsDAO');
			$publishedArticleDao = DAORegistry::getDAO('PublishedArticleDAO');
			$journalDao = DAORegistry::getDAO('JournalDAO');
			
			$result = $metricsDao->retrieve("SELECT submission_id, SUM(metric) AS metric FROM metrics WHERE (day BETWEEN CURDATE()-INTERVAL 1 WEEK AND CURDATE()) AND (assoc_type='515' AND submission_id IS NOT NULL) GROUP BY submission_id ORDER BY metric DESC LIMIT 5");
			
			while (!$result->EOF) {
				$resultRow = $result->GetRowAssoc(false);
				$article = $publishedArticleDao->getPublishedArticleByArticleId($resultRow['submission_id']);	
				$journal = $journalDao->getById($article->getJournalId());
				$articles[$resultRow['submission_id']]['journalPath'] = $journal->getPath();
				$articles[$resultRow['submission_id']]['journalName'] = $journal->getLocalizedName();
				$articles[$resultRow['submission_id']]['articleId'] = $article->getBestArticleId();
				$articles[$resultRow['submission_id']]['articleTitle'] = $article->getLocalizedTitle();
				$articles[$resultRow['submission_id']]['metric'] = $resultRow['metric'];
				
				$result->MoveNext();
			}
			$result->Close();			
			$cache->setEntireCache($articles);
			return $result;
	}
	



    /**
     * @copydoc PKPPlugin::getTemplatePath
     */
    function getTemplatePath($inCore = false) {
        return parent::getTemplatePath($inCore) . 'templates/';
    }

    /**
     * Called as a plugin is registered to the registry
     * @param $category String Name of category plugin was registered to
     * @return boolean True iff plugin initialized successfully; if false,
     * 	the plugin will not be registered.
     */
    function register($category, $path) {
        $success = parent::register($category, $path);
        if (!Config::getVar('general', 'installed') || defined('RUNNING_UPGRADE')) return true;
        if ($success && $this->getEnabled()) {

            HookRegistry::register('Templates::Index::journal', array($this, 'browseLatest'), HOOK_SEQUENCE_NORMAL);

            // Add stylesheet and javascript
            HookRegistry::register('TemplateManager::display',array($this, 'displayCallback'));

        }
        return $success;
    }

    function displayCallback($hookName, $params) {
        $template = $params[1];
        $output =& $params[2];

        if ($template != 'frontend/pages/indexJournal.tpl') return false;

        $templateMgr = $params[0];
        $templateMgr->addStylesheet('browse1', Request::getBaseUrl() . DIRECTORY_SEPARATOR . $this->getPluginPath() . DIRECTORY_SEPARATOR . 'css' . DIRECTORY_SEPARATOR . 'browse.css');
        $templateMgr->addJavaScript('jatsParser', Request::getBaseUrl() . DIRECTORY_SEPARATOR . $this->getPluginPath() . DIRECTORY_SEPARATOR .  'js' . DIRECTORY_SEPARATOR .'browse.js');

        return false;
    }

















    function browseLatest($hookName, $params) {
        $smarty =& $params[1];
        $output =& $params[2];

        //articles id for displaying from database
        $params = $this->getRequest();
        $journal = $params->getJournal();
        $sliderFirst = $this->getSetting($journal->getId(), 'sliderFirst');
        $sliderSecond = $this->getSetting($journal->getId(), 'sliderSecond');
        $sliderThird = $this->getSetting($journal->getId(), 'sliderThird');

        // Limit artcles number to retrieve
        import('lib.pkp.classes.db.DBResultRange');
        $rangeInfo = new DBResultRange(50, 1);


    /**
     * @see Plugin::getActions()
     */
    function getActions($request, $verb) {
        $router = $request->getRouter();
        import('lib.pkp.classes.linkAction.request.AjaxModal');
        return array_merge(
            $this->getEnabled()?array(
                new LinkAction(
                    'settings',
                    new AjaxModal(
                        $router->url($request, null, null, 'manage', null, array('verb' => 'settings', 'plugin' => $this->getName(), 'category' => 'generic')),
                        $this->getDisplayName()
                    ),
                    __('manager.plugins.settings'),
                    null
                ),
            ):array(),
            parent::getActions($request, $verb)
        );
    }

    /**
     * @see Plugin::manage()
     */
    function manage($args, $request) {
        switch ($request->getUserVar('verb')) {
            case 'settings':
                $context = $request->getContext();

                AppLocale::requireComponents(LOCALE_COMPONENT_APP_COMMON,  LOCALE_COMPONENT_PKP_MANAGER);
                $templateMgr = TemplateManager::getManager($request);
                $templateMgr->register_function('plugin_url', array($this, 'smartyPluginUrl'));

                $this->import('SettingsForm');
                $form = new SettingsForm($this, $context->getId());

                if ($request->getUserVar('save')) {
                    $form->readInputData();
                    if ($form->validate()) {
                        $form->execute();
                        return new JSONMessage(true);
                    }
                } else {
                    $form->initData();
                }
                return new JSONMessage(true, $form->fetch($request));
        }
        return parent::manage($args, $request);
    }








     
   // Get articles except Editorial and News
        $publishedArticleDao = DAORegistry::getDAO('PublishedArticleDAO');
        $publishedArticleObjects = $publishedArticleDao->getPublishedArticlesByJournalId($journalId = null, $rangeInfo, $reverse = true);
        $publishedArticles = array();
        $publishedNews = array();

        $showArticlesCount = 0;
        $showNewsCount = 0;
        $xmlGalley = null;
        $browseArticles = array();
        while ((($showArticlesCount + $showNewsCount) < 18) && $publishedArticle = $publishedArticleObjects->next()) {
           // echo $publishedArticle->getSectionTitle() . ": " . $publishedArticle->getSectionId() . " \n";
            if ($showArticlesCount < 20) {
                $publishedArticles[]['articles'][] = $publishedArticle;
                $showArticlesCount = $showArticlesCount + 1;
            } elseif ($showNewsCount < 18) {
                $publishedNews[]['articles'][] = $publishedArticle;
                $showNewsCount = $showNewsCount + 1;
            }

            if ($publishedArticle->getId() == $sliderFirst) {
                $browseArticles = $this->slidersSearch($params, $publishedArticle, $browseArticles);
            } elseif ($publishedArticle->getId() == $sliderSecond) {
                $browseArticles = $this->slidersSearch($params, $publishedArticle, $browseArticles);
            } elseif ($publishedArticle->getId() == $sliderThird) {
                $browseArticles = $this->slidersSearch($params, $publishedArticle, $browseArticles);
            }
        }



        $smarty->assign('browseArticles', $browseArticles);
        $smarty->assign('publishedArticles', $publishedArticles);
        $smarty->assign('publishedNews', $publishedNews);

        $output .= $smarty->fetch($this->getTemplatePath() . 'browseLatest.tpl');
        return false;
    }


    /**
     * @param $params
     * @param $publishedArticle
     * @param $browseArticles BrowseArticle
     * @return array
     */
    public function slidersSearch($params, $publishedArticle, $browseArticles)
    {
        foreach ($publishedArticle->getGalleys() as $galley) {
            if ($galley && in_array($galley->getFileType(), array('application/xml', 'text/xml'))) {
                $xmlGalley = $galley;
                $submissionFile = $xmlGalley->getFile();

                $submissionFileDao = DAORegistry::getDAO('SubmissionFileDAO');
                import('lib.pkp.classes.submission.SubmissionFile'); // Constants
                $embeddableFiles = array_merge(
                    $submissionFileDao->getLatestRevisions($submissionFile->getSubmissionId(), SUBMISSION_FILE_PROOF),
                    $submissionFileDao->getLatestRevisionsByAssocId(ASSOC_TYPE_SUBMISSION_FILE, $submissionFile->getFileId(), $submissionFile->getSubmissionId(), SUBMISSION_FILE_DEPENDENT)
                );
                $referredArticle = null;
                $articleDao = DAORegistry::getDAO('ArticleDAO');
                foreach ($embeddableFiles as $embeddableFile) {
                    $params = array();

                    if ($embeddableFile->getFileType() == 'image/png' || $embeddableFile->getFileType() == 'image/jpeg') {

                        // Ensure that the $referredArticle object refers to the article we want
                        if (!$referredArticle || $referredArticle->getId() != $galley->getSubmissionId()) {
                            $referredArticle = $articleDao->getById($galley->getSubmissionId());
                        }
                        $fileUrl = Application::getRequest()->url(null, 'article', 'download', array($referredArticle->getBestArticleId(), $galley->getBestGalleyId(), $embeddableFile->getFileId()), $params);

                        //$imageUrlArray[$embeddableFile->getOriginalFileName()] = $fileUrl;
                        if ($embeddableFile->getOriginalFileName() == "slider.png") {
                            $browseArticle = new BrowseArticle($publishedArticle->getLocalizedTitle(), $fileUrl, $publishedArticle->getBestArticleId(), $publishedArticle->getLocalizedAbstract(), $publishedArticle->getSectionTitle());
                            array_push($browseArticles, $browseArticle);
                        }
                    }
                }
            }
        }
        return $browseArticles;
    }

}





?>
1 Like

@ajnyga any ideas what is wrong here?

I do not think that you are calling the loadTemplateData function in the init function? See tsvSite/TsvSiteThemePlugin.inc.php at master · ajnyga/tsvSite · GitHub

1 Like

I tried adding them in the init function n my themes inc.php file. But then the site stops working. This is the theme’s inc.php without your addition

<?php
/**
 * @file plugins/themes/default/DefaultManuscriptChildThemePlugin.inc.php
 *
 * Copyright (c) 2014-2017 Simon Fraser University Library
 * Copyright (c) 2003-2017 John Willinsky
 * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING.
 * Modyfied by Vitaliy Bezsheiko, MD
 * @class DefaultManuscriptChildThemePlugin
 * @ingroup plugins_themes_default_manuscript
 *
 * @brief Default theme
 */
import('lib.pkp.classes.plugins.ThemePlugin');
class ManuscriptJats extends ThemePlugin {
	/**
	 * Initialize the theme's styles, scripts and hooks. This is only run for
	 * the currently active theme.
	 *
	 * @return null
	 */
	public function init() {

// Load additional template data
		HookRegistry::register ('TemplateManager::display', array($this, 'loadTemplateData'));

		// Initialize the parent theme
		$this->setParent('defaultthemeplugin');
        $this->removeScript('jQueryTagIt');
        $this->removeScript('popper');
        $this->removeScript('bsUtil');
        $this->removeScript('bsDropdown');
		// Add bootstrap and jquery ui css
        $this->addStyle('my-custom-style1', 'styles/bootstrap/bootstrap.min.css');
        $this->addStyle('my-custom-style2', 'styles/bootstrap/bootstrap-theme.min.css');
        $this->addStyle('my-custom-style3', 'jquery-ui/jquery-ui.min.css');
        $this->addStyle('my-custom-style4', 'jquery-ui/jquery-ui.structure.min.css');
        $this->addStyle('my-custom-style5', 'jquery-ui/jquery-ui.theme.min.css');
        $this->addStyle('my-custom-style6', 'styles/article_detail.css');
        // Add bootstrap and jquery ui javascript
        //$this->addScript('my-javascript1', 'js/jquery.min.js');
        //$this->addScript('my-javascript2', 'jquery-ui/jquery-ui.min.js');
        $this->addScript('my-javascript3', 'js/bootstrap.min.js');
		// Add custom styles
		$this->modifyStyle('stylesheet', array('addLess' => array('styles/index.less')));
		// Add custom menus
        $this->addMenuArea(array('primary', 'user'));
		// Remove the typography options of the parent theme.
		// `removeOption` was introduced in OJS 3.0.2
		if (method_exists($this, 'removeOption')) {
			$this->removeOption('typography');
		}
		// Add the option for an accent color
		$this->addOption('accentColour', 'colour', array(
			'label' => 'plugins.themes.manuscript-jats.option.accentColour.label',
			'description' => 'plugins.themes.default.option.colour.description',
			'default' => '#F7BC4A',
		));
		// Load the Montserrat and Open Sans fonts
		$this->addStyle(
			'font',
			'//fonts.googleapis.com/css?family=Montserrat:400,700|Noto+Serif:400,400i,700,700i',
			array('baseUrl' => '')
		);
		// Dequeue any fonts loaded by parent theme
		// `removeStyle` was introduced in OJS 3.0.2
		if (method_exists($this, 'removeStyle')) {
			$this->removeStyle('fontNotoSans');
			$this->removeStyle('fontNotoSerif');
			$this->removeStyle('fontNotoSansNotoSerif');
			$this->removeStyle('fontLato');
			$this->removeStyle('fontLora');
			$this->removeStyle('fontLoraOpenSans');
			$this->removeStyle('fontNotoSerif');
			$this->removeStyle('fontNotoSerif');
			$this->removeStyle('fontNotoSerif');
			$this->removeStyle('fontNotoSerif');
			$this->removeStyle('fontNotoSerif');
		}
		// Start with a fresh array of additionalLessVariables so that we can
		// ignore those added by the parent theme. This gets rid of @font
		// variable overrides from the typography option
		$additionalLessVariables = array();
		// Update colour based on theme option from parent theme
		if ($this->getOption('baseColour') !== '#1E6292') {
			$additionalLessVariables[] = '@bg-base:' . $this->getOption('baseColour') . ';';
			if (!$this->isColourDark($this->getOption('baseColour'))) {
				$additionalLessVariables[] = '@text-bg-base:rgba(0,0,0,0.84);';
			}
		}
		// Update accent colour based on theme option
		if ($this->getOption('accentColour') !== '#F7BC4A') {
			$additionalLessVariables[] = '@accent:' . $this->getOption('accentColour') . ';';
		}
		if ($this->getOption('baseColour') && $this->getOption('accentColour')) {
			$this->modifyStyle('stylesheet', array('addLessVariables' => join('', $additionalLessVariables)));
		}
	}





	/**
	 * Get the display name of this plugin
	 * @return string
	 */
	function getDisplayName() {
		return __('plugins.themes.manuscript-jats.name');
	}
	/**
	 * Get the description of this plugin
	 * @return string
	 */
	function getDescription() {
		return __('plugins.themes.manuscript-jats.description');
	}





}

?>

Now, I am not seeing the rest of the code in DefaultManuscriptChildThemePlugin.inc.php?

I mean the actual loadTemplateData function?

edit: I see now that you had the code originally in “class BrowsePlugin” and not in the themeplugin file? The code should be in the theme plugin file. See here: https://pkp.gitbooks.io/pkp-theming-guide/content/en/advanced-custom-data.html

Yes it is DefaulManuscriptThemeplugin.inc.php

<?php
/**
 * @file plugins/themes/default/DefaultManuscriptChildThemePlugin.inc.php
 *
 * Copyright (c) 2014-2017 Simon Fraser University Library
 * Copyright (c) 2003-2017 John Willinsky
 * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING.
 * Modyfied by Vitaliy Bezsheiko, MD
 * @class DefaultManuscriptChildThemePlugin
 * @ingroup plugins_themes_default_manuscript
 *
 * @brief Default theme
 */
import('lib.pkp.classes.plugins.ThemePlugin');
class ManuscriptJats extends ThemePlugin {
	/**
	 * Initialize the theme's styles, scripts and hooks. This is only run for
	 * the currently active theme.
	 *
	 * @return null
	 */
	public function init() {

// Load additional template data
		HookRegistry::register ('TemplateManager::display', array($this, 'loadTemplateData'));

		// Initialize the parent theme
		$this->setParent('defaultthemeplugin');
        $this->removeScript('jQueryTagIt');
        $this->removeScript('popper');
        $this->removeScript('bsUtil');
        $this->removeScript('bsDropdown');
		// Add bootstrap and jquery ui css
        $this->addStyle('my-custom-style1', 'styles/bootstrap/bootstrap.min.css');
        $this->addStyle('my-custom-style2', 'styles/bootstrap/bootstrap-theme.min.css');
        $this->addStyle('my-custom-style3', 'jquery-ui/jquery-ui.min.css');
        $this->addStyle('my-custom-style4', 'jquery-ui/jquery-ui.structure.min.css');
        $this->addStyle('my-custom-style5', 'jquery-ui/jquery-ui.theme.min.css');
        $this->addStyle('my-custom-style6', 'styles/article_detail.css');
        // Add bootstrap and jquery ui javascript
        //$this->addScript('my-javascript1', 'js/jquery.min.js');
        //$this->addScript('my-javascript2', 'jquery-ui/jquery-ui.min.js');
        $this->addScript('my-javascript3', 'js/bootstrap.min.js');
		// Add custom styles
		$this->modifyStyle('stylesheet', array('addLess' => array('styles/index.less')));
		// Add custom menus
        $this->addMenuArea(array('primary', 'user'));
		// Remove the typography options of the parent theme.
		// `removeOption` was introduced in OJS 3.0.2
		if (method_exists($this, 'removeOption')) {
			$this->removeOption('typography');
		}
		// Add the option for an accent color
		$this->addOption('accentColour', 'colour', array(
			'label' => 'plugins.themes.manuscript-jats.option.accentColour.label',
			'description' => 'plugins.themes.default.option.colour.description',
			'default' => '#F7BC4A',
		));
		// Load the Montserrat and Open Sans fonts
		$this->addStyle(
			'font',
			'//fonts.googleapis.com/css?family=Montserrat:400,700|Noto+Serif:400,400i,700,700i',
			array('baseUrl' => '')
		);
		// Dequeue any fonts loaded by parent theme
		// `removeStyle` was introduced in OJS 3.0.2
		if (method_exists($this, 'removeStyle')) {
			$this->removeStyle('fontNotoSans');
			$this->removeStyle('fontNotoSerif');
			$this->removeStyle('fontNotoSansNotoSerif');
			$this->removeStyle('fontLato');
			$this->removeStyle('fontLora');
			$this->removeStyle('fontLoraOpenSans');
			$this->removeStyle('fontNotoSerif');
			$this->removeStyle('fontNotoSerif');
			$this->removeStyle('fontNotoSerif');
			$this->removeStyle('fontNotoSerif');
			$this->removeStyle('fontNotoSerif');
		}
		// Start with a fresh array of additionalLessVariables so that we can
		// ignore those added by the parent theme. This gets rid of @font
		// variable overrides from the typography option
		$additionalLessVariables = array();
		// Update colour based on theme option from parent theme
		if ($this->getOption('baseColour') !== '#1E6292') {
			$additionalLessVariables[] = '@bg-base:' . $this->getOption('baseColour') . ';';
			if (!$this->isColourDark($this->getOption('baseColour'))) {
				$additionalLessVariables[] = '@text-bg-base:rgba(0,0,0,0.84);';
			}
		}
		// Update accent colour based on theme option
		if ($this->getOption('accentColour') !== '#F7BC4A') {
			$additionalLessVariables[] = '@accent:' . $this->getOption('accentColour') . ';';
		}
		if ($this->getOption('baseColour') && $this->getOption('accentColour')) {
			$this->modifyStyle('stylesheet', array('addLessVariables' => join('', $additionalLessVariables)));
		}
	}





	/**
	 * Get the display name of this plugin
	 * @return string
	 */
	function getDisplayName() {
		return __('plugins.themes.manuscript-jats.name');
	}
	/**
	 * Get the description of this plugin
	 * @return string
	 */
	function getDescription() {
		return __('plugins.themes.manuscript-jats.description');
	}





}

?>

Yes, you are calling the function in the theme plugin, but the function is not there in the file.

Yes, but there is no init function in browse code, so I thought to add in my theme since it did have.

Yes definitely you should not add the code to the browse plugin. All changes and additions go to the theme plugin

Yes, how to add the function? I am still a noob in coding, so sorry for that

you just add the two functions to the theme plugin: loadTemplateData and _cacheMiss, just like you did when you added them to the browseplugin file. Then you add the hook call I mentioned above to the init function.

For a basic overview see here: https://pkp.gitbooks.io/pkp-theming-guide/content/en/advanced-custom-data.html

I added, but the site is now not working. This is the code. jmri.org.in is site

<?php
/**
 * @file plugins/themes/default/DefaultManuscriptChildThemePlugin.inc.php
 *
 * Copyright (c) 2014-2017 Simon Fraser University Library
 * Copyright (c) 2003-2017 John Willinsky
 * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING.
 * Modyfied by Vitaliy Bezsheiko, MD
 * @class DefaultManuscriptChildThemePlugin
 * @ingroup plugins_themes_default_manuscript
 *
 * @brief Default theme
 */
import('lib.pkp.classes.plugins.ThemePlugin');
class ManuscriptJats extends ThemePlugin {
	/**
	 * Initialize the theme's styles, scripts and hooks. This is only run for
	 * the currently active theme.
	 *
	 * @return null
	 */
	public function init() {

// Load additional template data
		HookRegistry::register ('TemplateManager::display', array($this, 'loadTemplateData'));







		// Initialize the parent theme
		$this->setParent('defaultthemeplugin');
        $this->removeScript('jQueryTagIt');
        $this->removeScript('popper');
        $this->removeScript('bsUtil');
        $this->removeScript('bsDropdown');
		// Add bootstrap and jquery ui css
        $this->addStyle('my-custom-style1', 'styles/bootstrap/bootstrap.min.css');
        $this->addStyle('my-custom-style2', 'styles/bootstrap/bootstrap-theme.min.css');
        $this->addStyle('my-custom-style3', 'jquery-ui/jquery-ui.min.css');
        $this->addStyle('my-custom-style4', 'jquery-ui/jquery-ui.structure.min.css');
        $this->addStyle('my-custom-style5', 'jquery-ui/jquery-ui.theme.min.css');
        $this->addStyle('my-custom-style6', 'styles/article_detail.css');
        // Add bootstrap and jquery ui javascript
        //$this->addScript('my-javascript1', 'js/jquery.min.js');
        //$this->addScript('my-javascript2', 'jquery-ui/jquery-ui.min.js');
        $this->addScript('my-javascript3', 'js/bootstrap.min.js');
		// Add custom styles
		$this->modifyStyle('stylesheet', array('addLess' => array('styles/index.less')));
		// Add custom menus
        $this->addMenuArea(array('primary', 'user'));
		// Remove the typography options of the parent theme.
		// `removeOption` was introduced in OJS 3.0.2
		if (method_exists($this, 'removeOption')) {
			$this->removeOption('typography');
		}
		// Add the option for an accent color
		$this->addOption('accentColour', 'colour', array(
			'label' => 'plugins.themes.manuscript-jats.option.accentColour.label',
			'description' => 'plugins.themes.default.option.colour.description',
			'default' => '#F7BC4A',
		));
		// Load the Montserrat and Open Sans fonts
		$this->addStyle(
			'font',
			'//fonts.googleapis.com/css?family=Montserrat:400,700|Noto+Serif:400,400i,700,700i',
			array('baseUrl' => '')
		);
		// Dequeue any fonts loaded by parent theme
		// `removeStyle` was introduced in OJS 3.0.2
		if (method_exists($this, 'removeStyle')) {
			$this->removeStyle('fontNotoSans');
			$this->removeStyle('fontNotoSerif');
			$this->removeStyle('fontNotoSansNotoSerif');
			$this->removeStyle('fontLato');
			$this->removeStyle('fontLora');
			$this->removeStyle('fontLoraOpenSans');
			$this->removeStyle('fontNotoSerif');
			$this->removeStyle('fontNotoSerif');
			$this->removeStyle('fontNotoSerif');
			$this->removeStyle('fontNotoSerif');
			$this->removeStyle('fontNotoSerif');
		}
		// Start with a fresh array of additionalLessVariables so that we can
		// ignore those added by the parent theme. This gets rid of @font
		// variable overrides from the typography option
		$additionalLessVariables = array();
		// Update colour based on theme option from parent theme
		if ($this->getOption('baseColour') !== '#1E6292') {
			$additionalLessVariables[] = '@bg-base:' . $this->getOption('baseColour') . ';';
			if (!$this->isColourDark($this->getOption('baseColour'))) {
				$additionalLessVariables[] = '@text-bg-base:rgba(0,0,0,0.84);';
			}
		}
		// Update accent colour based on theme option
		if ($this->getOption('accentColour') !== '#F7BC4A') {
			$additionalLessVariables[] = '@accent:' . $this->getOption('accentColour') . ';';
		}
		if ($this->getOption('baseColour') && $this->getOption('accentColour')) {
			$this->modifyStyle('stylesheet', array('addLessVariables' => join('', $additionalLessVariables)));
		}
	}





	/**
	 * Get the display name of this plugin
	 * @return string
	 */
	function getDisplayName() {
		return __('plugins.themes.manuscript-jats.name');
	}
	/**
	 * Get the description of this plugin
	 * @return string
	 */
	function getDescription() {
		return __('plugins.themes.manuscript-jats.description');
	}

/**
	 * Get the HTML contents for this block.
	 * @param $templateMgr object
	 * @param $request PKPRequest
	 */
	public function loadTemplateData($hookName, $args) {		
		$templateMgr = $args[0];
        $template = $args[1];
		$request = Application::getRequest();
        $site = $request->getSite();
		$issueDao = DAORegistry::getDAO('IssueDAO');
		$journalDao = DAORegistry::getDAO('JournalDAO');
		
		// Start Language selector
		$templateMgr->assign('isPostRequest', $request->isPost());	
		
		if (!defined('SESSION_DISABLE_INIT')) {
			$locales = $site->getSupportedLocales();
		} else {
			$locales = AppLocale::getAllLocales();
			$templateMgr->assign('languageToggleNoUser', true);
		}
		if (isset($locales) && count($locales) > 1) {
			$templateMgr->assign('enableLanguageToggle', false);
			$templateMgr->assign('languageToggleLocales', $locales);
			
			
		}
		// End Language selector
		
		

		
		
		// Start Most read
		$metricsDao = DAORegistry::getDAO('MetricsDAO');
		$cacheManager =& CacheManager::getManager();
		$cache  =& $cacheManager->getCache('mostread', 0, array($this, '_cacheMiss'));
		$daysToStale = 1;
		$cachedMetrics = false;
		
		if (time() - $cache->getCacheTime() > 60 * 60 * 24 * $daysToStale) {
			$cachedMetrics = $cache->getContents();
			$cache->flush();
		}
		$resultMetrics = $cache->getContents();
		
		if (!$resultMetrics && $cachedMetrics) {
			$resultMetrics = $cachedMetrics;
			$cache->setEntireCache($cachedMetrics);
		} elseif (!$resultMetrics) {
			$cache->flush();
		}
		
		$templateMgr->assign('resultMetrics', $resultMetrics);
		
		// End Most read		
		
	}
	
	function _cacheMiss($cache) {
			$metricsDao = DAORegistry::getDAO('MetricsDAO');
			$publishedArticleDao = DAORegistry::getDAO('PublishedArticleDAO');
			$journalDao = DAORegistry::getDAO('JournalDAO');
			
			$result = $metricsDao->retrieve("SELECT submission_id, SUM(metric) AS metric FROM metrics WHERE (day BETWEEN CURDATE()-INTERVAL 1 WEEK AND CURDATE()) AND (assoc_type='515' AND submission_id IS NOT NULL) GROUP BY submission_id ORDER BY metric DESC LIMIT 5");
			
			while (!$result->EOF) {
				$resultRow = $result->GetRowAssoc(false);
				$article = $publishedArticleDao->getPublishedArticleByArticleId($resultRow['submission_id']);	
				$journal = $journalDao->getById($article->getJournalId());
				$articles[$resultRow['submission_id']]['journalPath'] = $journal->getPath();
				$articles[$resultRow['submission_id']]['journalName'] = $journal->getLocalizedName();
				$articles[$resultRow['submission_id']]['articleId'] = $article->getBestArticleId();
				$articles[$resultRow['submission_id']]['articleTitle'] = $article->getLocalizedTitle();
				$articles[$resultRow['submission_id']]['metric'] = $resultRow['metric'];
				
				$result->MoveNext();
			}
			$result->Close();			
			$cache->setEntireCache($articles);
			return $result;
	}



}

?>

This is hard to debug while I do not have a similar theme installed anywhere. But at least I think that you do not need the language selector part there. You could try this and if you still get a blank page then there is an error on the page I am not seeing only by looking at the code. You should see it in the error logs.

<?php
/**
 * @file plugins/themes/default/DefaultManuscriptChildThemePlugin.inc.php
 *
 * Copyright (c) 2014-2017 Simon Fraser University Library
 * Copyright (c) 2003-2017 John Willinsky
 * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING.
 * Modyfied by Vitaliy Bezsheiko, MD
 * @class DefaultManuscriptChildThemePlugin
 * @ingroup plugins_themes_default_manuscript
 *
 * @brief Default theme
 */
import('lib.pkp.classes.plugins.ThemePlugin');
class ManuscriptJats extends ThemePlugin {
	/**
	 * Initialize the theme's styles, scripts and hooks. This is only run for
	 * the currently active theme.
	 *
	 * @return null
	 */
	public function init() {

		// Load additional template data
		HookRegistry::register ('TemplateManager::display', array($this, 'loadTemplateData'));

		// Initialize the parent theme
		$this->setParent('defaultthemeplugin');
        $this->removeScript('jQueryTagIt');
        $this->removeScript('popper');
        $this->removeScript('bsUtil');
        $this->removeScript('bsDropdown');
		// Add bootstrap and jquery ui css
        $this->addStyle('my-custom-style1', 'styles/bootstrap/bootstrap.min.css');
        $this->addStyle('my-custom-style2', 'styles/bootstrap/bootstrap-theme.min.css');
        $this->addStyle('my-custom-style3', 'jquery-ui/jquery-ui.min.css');
        $this->addStyle('my-custom-style4', 'jquery-ui/jquery-ui.structure.min.css');
        $this->addStyle('my-custom-style5', 'jquery-ui/jquery-ui.theme.min.css');
        $this->addStyle('my-custom-style6', 'styles/article_detail.css');
        // Add bootstrap and jquery ui javascript
        //$this->addScript('my-javascript1', 'js/jquery.min.js');
        //$this->addScript('my-javascript2', 'jquery-ui/jquery-ui.min.js');
        $this->addScript('my-javascript3', 'js/bootstrap.min.js');
		// Add custom styles
		$this->modifyStyle('stylesheet', array('addLess' => array('styles/index.less')));
		// Add custom menus
        $this->addMenuArea(array('primary', 'user'));
		// Remove the typography options of the parent theme.
		// `removeOption` was introduced in OJS 3.0.2
		if (method_exists($this, 'removeOption')) {
			$this->removeOption('typography');
		}
		// Add the option for an accent color
		$this->addOption('accentColour', 'colour', array(
			'label' => 'plugins.themes.manuscript-jats.option.accentColour.label',
			'description' => 'plugins.themes.default.option.colour.description',
			'default' => '#F7BC4A',
		));
		// Load the Montserrat and Open Sans fonts
		$this->addStyle(
			'font',
			'//fonts.googleapis.com/css?family=Montserrat:400,700|Noto+Serif:400,400i,700,700i',
			array('baseUrl' => '')
		);
		// Dequeue any fonts loaded by parent theme
		// `removeStyle` was introduced in OJS 3.0.2
		if (method_exists($this, 'removeStyle')) {
			$this->removeStyle('fontNotoSans');
			$this->removeStyle('fontNotoSerif');
			$this->removeStyle('fontNotoSansNotoSerif');
			$this->removeStyle('fontLato');
			$this->removeStyle('fontLora');
			$this->removeStyle('fontLoraOpenSans');
			$this->removeStyle('fontNotoSerif');
			$this->removeStyle('fontNotoSerif');
			$this->removeStyle('fontNotoSerif');
			$this->removeStyle('fontNotoSerif');
			$this->removeStyle('fontNotoSerif');
		}
		// Start with a fresh array of additionalLessVariables so that we can
		// ignore those added by the parent theme. This gets rid of @font
		// variable overrides from the typography option
		$additionalLessVariables = array();
		// Update colour based on theme option from parent theme
		if ($this->getOption('baseColour') !== '#1E6292') {
			$additionalLessVariables[] = '@bg-base:' . $this->getOption('baseColour') . ';';
			if (!$this->isColourDark($this->getOption('baseColour'))) {
				$additionalLessVariables[] = '@text-bg-base:rgba(0,0,0,0.84);';
			}
		}
		// Update accent colour based on theme option
		if ($this->getOption('accentColour') !== '#F7BC4A') {
			$additionalLessVariables[] = '@accent:' . $this->getOption('accentColour') . ';';
		}
		if ($this->getOption('baseColour') && $this->getOption('accentColour')) {
			$this->modifyStyle('stylesheet', array('addLessVariables' => join('', $additionalLessVariables)));
		}
	}

	/**
	 * Get the display name of this plugin
	 * @return string
	 */
	function getDisplayName() {
		return __('plugins.themes.manuscript-jats.name');
	}
	/**
	 * Get the description of this plugin
	 * @return string
	 */
	function getDescription() {
		return __('plugins.themes.manuscript-jats.description');
	}

	/**
	 * Get the HTML contents for this block.
	 * @param $templateMgr object
	 * @param $request PKPRequest
	 */
	public function loadTemplateData($hookName, $args) {		
		$templateMgr = $args[0];
		$request = Application::getRequest();
        $context = $request->getContext();
		
		// Start Most read
		$metricsDao = DAORegistry::getDAO('MetricsDAO');
		$cacheManager =& CacheManager::getManager();
		$cache  =& $cacheManager->getCache('mostread', $context->getId(), array($this, '_cacheMiss'));
		$daysToStale = 1;
		$cachedMetrics = false;
		
		if (time() - $cache->getCacheTime() > 60 * 60 * 24 * $daysToStale) {
			$cachedMetrics = $cache->getContents();
			$cache->flush();
		}
		$resultMetrics = $cache->getContents();
		
		if (!$resultMetrics && $cachedMetrics) {
			$resultMetrics = $cachedMetrics;
			$cache->setEntireCache($cachedMetrics);
		} elseif (!$resultMetrics) {
			$cache->flush();
		}
		
		$templateMgr->assign('resultMetrics', $resultMetrics);
		
		// End Most read		
		
	}
	
	function _cacheMiss($cache) {
		$metricsDao = DAORegistry::getDAO('MetricsDAO');
		$publishedArticleDao = DAORegistry::getDAO('PublishedArticleDAO');
		$journalDao = DAORegistry::getDAO('JournalDAO');
		
		$result = $metricsDao->retrieve("SELECT submission_id, SUM(metric) AS metric FROM metrics WHERE (day BETWEEN CURDATE()-INTERVAL 1 WEEK AND CURDATE()) AND (assoc_type='515' AND submission_id IS NOT NULL) GROUP BY submission_id ORDER BY metric DESC LIMIT 5");
		
		while (!$result->EOF) {
			$resultRow = $result->GetRowAssoc(false);
			$article = $publishedArticleDao->getPublishedArticleByArticleId($resultRow['submission_id']);	
			$journal = $journalDao->getById($article->getJournalId());
			$articles[$resultRow['submission_id']]['journalPath'] = $journal->getPath();
			$articles[$resultRow['submission_id']]['journalName'] = $journal->getLocalizedName();
			$articles[$resultRow['submission_id']]['articleId'] = $article->getBestArticleId();
			$articles[$resultRow['submission_id']]['articleTitle'] = $article->getLocalizedTitle();
			$articles[$resultRow['submission_id']]['metric'] = $resultRow['metric'];
			
			$result->MoveNext();
		}
		$result->Close();			
		$cache->setEntireCache($articles);
		return $result;
	}

}

?>

It is still blank (error 500 is showing)

That is odd. There could be numerous reasons for the error, but if the code itself has an error, then you should see fatal php error in the logs.

Now that it is working again, did you 1) edit the file again and remove the additions you made or 2) replaced the edited file with an original file without the changes.

Because if you did number 2, then maybe the way you save the changes to the file changes the file permissions or something similar? Again, hard to say without seeing.

You could try the first example here: https://pkp.gitbooks.io/pkp-theming-guide/content/en/advanced-custom-data.html

I mean just try to pass the ‘This is my custom data. It could be any PHP variable.’ text to your front page template and show it there. If you are getting the same problems with a simple code like that, then the problem is not probably the code itself but something different.

Yes, i removed the codes. I will try as you said and will keep you updated. Thanks :slight_smile:

Yes! It is easier to debug when you start by sending something simple. I mean the code is made for a site level theme plugin so there could be something I am not seeing which would create problems with a journal level theme plugin.

1 Like

he estado mirando el codigo y depurando en consola y el problema esta
PHP Fatal error: Uncaught Error: Call to undefined method PublishedArticleDAO::getPublishedArticleByArticleId() cuando hacemos esa llamada, si quisieran ayudar por favor, me sucede lo mismo como podemos arreglar esta llamada