Narweb: add php session_start (#1169)

* Narweb: add php session_start

Fixes #12135

- remove php3
- remove duplicate code

* libhtml: better pylint score
This commit is contained in:
Serge Noiraud
2021-02-13 17:39:03 +01:00
committed by GitHub
parent 94ddf6a815
commit 66680851f2
5 changed files with 181 additions and 145 deletions

View File

@@ -30,7 +30,6 @@ This module exports the Html class
#------------------------------------------------------------------------ #------------------------------------------------------------------------
# Python modules # Python modules
#------------------------------------------------------------------------ #------------------------------------------------------------------------
import re
#------------------------------------------------------------------------ #------------------------------------------------------------------------
# #
@@ -140,8 +139,8 @@ class Html(list):
:param external_id: external identifier of this DOCTYPE. :param external_id: external identifier of this DOCTYPE.
Defaults to XHTML 1.0 STRICT Defaults to XHTML 1.0 STRICT
:type args: object :type args: object
:param args: 0 or more positional parameters to be added to this :param args: 0 or more positional parameters to be added to
DOCTYPE. this DOCTYPE.
""" """
return ( return (
'<!DOCTYPE %s %s %s' % ( '<!DOCTYPE %s %s %s' % (
@@ -152,23 +151,24 @@ class Html(list):
).rstrip() + '>' ).rstrip() + '>'
# #
@staticmethod @staticmethod
def html(xmlns=_XMLNS, lang='en', *args, **keywargs): def html(xmlns=_XMLNS, lang='en', php_session=None, *args, **keywargs):
""" """
Build and return a properly-formated <html> object Build and return a properly-formated <html> object
:type xmlns: string :type xmlns: string
:param xmlns: XML namespace string. Default = 'http://www.w3.org/1999/xhtml' :param xmlns: XML namespace string.
Default = 'http://www.w3.org/1999/xhtml'
:type lang: string :type lang: string
:param lang: language to be used. Defaul = 'en' :param lang: language to be used. Defaul = 'en'
:rtype: reference to new Html instance :rtype: reference to new Html instance
:returns: reference to the newly-created Html instances for <html> object :php_session: If we need to have a php session start
:returns: reference to the newly-created Html instances
for <html> object
""" """
return Html('html', return Html('html', indent=False, xmlns=xmlns,
indent=False,
xmlns=xmlns,
attr='xml:lang="%s" lang="%s"' % ((lang,)*2), attr='xml:lang="%s" lang="%s"' % ((lang,)*2),
*args, **keywargs php=php_session,
) *args, **keywargs)
# #
@staticmethod @staticmethod
def head(title=None, encoding='utf-8', html5=True, *args, **keywargs): def head(title=None, encoding='utf-8', html5=True, *args, **keywargs):
@@ -183,7 +183,8 @@ class Html(list):
:param html5: generate html5 syntax. Default = True. Set to False :param html5: generate html5 syntax. Default = True. Set to False
if pre-html5 syntax required if pre-html5 syntax required
:rtype: reference to new Html instance :rtype: reference to new Html instance
:returns: reference to the newly-created Html instances for <head> object :returns: reference to the newly-created Html instances
for <head> object
""" """
head = Html('head', *args, **keywargs) head = Html('head', *args, **keywargs)
@@ -199,7 +200,8 @@ class Html(list):
return head return head
# #
@staticmethod @staticmethod
def page(title=None, encoding='utf-8', lang='en', html5=True, cms=False, *args, **keywargs): def page(title=None, encoding='utf-8', lang='en', html5=True, cms=False,
php_session=None, *args, **keywargs):
""" """
This function prepares a new Html class based page and returns This function prepares a new Html class based page and returns
@@ -212,26 +214,24 @@ class Html(list):
:param html5: generate html5 syntax. Default = True. Set to False :param html5: generate html5 syntax. Default = True. Set to False
if pre-html5 syntax required if pre-html5 syntax required
:rtype: three object references :rtype: three object references
:php_session: the note to include before all html code
:returns: references to the newly-created Html instances for :returns: references to the newly-created Html instances for
page, head and body page, head and body
""" """
page = Html.html(lang=lang, *args, **keywargs) page = Html.html(lang=lang, php_session=php_session,
*args, **keywargs)
if html5: if html5:
page.addDOCTYPE(external_id=_HTML5) page.addDOCTYPE(external_id=_HTML5)
else: else:
page.addXML(encoding=encoding) page.addXML(encoding=encoding)
page.addDOCTYPE(external_id=_XHTML10_STRICT) page.addDOCTYPE(external_id=_XHTML10_STRICT)
# #
head = Html.head(title=title, head = Html.head(title=title, encoding=encoding, lang=lang,
encoding=encoding, html5=html5, indent=False, *args, **keywargs)
lang=lang,
html5=html5,
indent=False,
*args, **keywargs
)
# #
if cms: if cms:
body = Html('div', class_ = "body", indent=False, *args, **keywargs) body = Html('div', class_="body", indent=False,
*args, **keywargs)
else: else:
body = Html('body', indent=False, *args, **keywargs) body = Html('body', indent=False, *args, **keywargs)
page += (head, body) page += (head, body)
@@ -247,15 +247,18 @@ class Html(list):
:param args: 0 more positional arguments to be inserted between :param args: 0 more positional arguments to be inserted between
opening and closing HTML tags. opening and closing HTML tags.
:type indent: boolean or None :type indent: boolean or None
:param indent: True ==> indent this object with respect to its parent :param indent: True ==> indent this object with respect to its
parent
False ==> do not indent this object False ==> do not indent this object
None ==> no indent for this object (use eg for pre tag) None ==> no indent for this object
(use eg for pre tag)
Defaults to True Defaults to True
:type inline: boolean :type inline: boolean
:param inline: True ==> instructs the write() method to output this :param inline: True ==> instructs the write() method to output
object and any child objects as a single string this object and any child objects as a
False ==> output this object and its contents one string single string
at a time False ==> output this object and its contents one
string at a time
Defaults to False Defaults to False
:type close: boolean or None :type close: boolean or None
:param close: True ==> this tag should be closed normally :param close: True ==> this tag should be closed normally
@@ -284,12 +287,15 @@ class Html(list):
# Keywords we don't recognize are saved for later # Keywords we don't recognize are saved for later
# addition to the opening tag as attributes. # addition to the opening tag as attributes.
# #
phpnote = None
for keyw, arg in sorted(keywargs.items()): for keyw, arg in sorted(keywargs.items()):
if (keyw in ['indent', 'close', 'inline'] and if (keyw in ['indent', 'close', 'inline'] and
arg in [True, False, None]): arg in [True, False, None]):
setattr(self, keyw, arg) setattr(self, keyw, arg)
elif keyw == 'attr': # pass attributes along elif keyw == 'attr': # pass attributes along
attr += ' ' + arg attr += ' ' + arg
elif keyw == 'php': # php init session
phpnote = arg
elif keyw[-1] == '_': # avoid Python conflicts elif keyw[-1] == '_': # avoid Python conflicts
attr += ' %s="%s"' % (keyw[:-1], arg) # pass keyword arg along attr += ' %s="%s"' % (keyw[:-1], arg) # pass keyword arg along
else: else:
@@ -301,7 +307,13 @@ class Html(list):
else: else:
if tag in _START_CLOSE: # if tag in special list if tag in _START_CLOSE: # if tag in special list
self.close = False # it needs no closing tag self.close = False # it needs no closing tag
begin = '<%s%s%s>' % ( # build opening tag with attributes if phpnote:
# We need to insert php code before the html tag
# This is used to initiate a php session.
htmlhead = phpnote + '<%s%s%s>'
else:
htmlhead = '<%s%s%s>'
begin = htmlhead % ( # build opening tag with attributes
tag, tag,
attr, attr,
('' if self.close is not False else ' /') ('' if self.close is not False else ' /')
@@ -393,8 +405,8 @@ class Html(list):
# #
def write(self, method=print, indent='\t', tabs=''): def write(self, method=print, indent='\t', tabs=''):
""" """
Output function: performs an insertion-order tree traversal Output function: performs an insertion-order tree traversal and
and calls supplied method for each item found. calls supplied method for each item found.
:type method: function reference :type method: function reference
:param method: function to call with each item found :param method: function to call with each item found
@@ -446,20 +458,20 @@ class Html(list):
:param external_id: external identifier of this DOCTYPE. :param external_id: external identifier of this DOCTYPE.
Defaults to XHTML 1.0 STRICT Defaults to XHTML 1.0 STRICT
:type args: object :type args: object
:param args: 0 or more positional parameters to be added to this :param args: 0 or more positional parameters to be added
DOCTYPE. to this DOCTYPE.
""" """
doctype = ( doctype = (
'<!DOCTYPE %s %s %s%s' % ( '<!DOCTYPE %s %s %s%s' % (name,
name, ('' if external_id == _HTML5
('' if external_id ==_HTML5 else public), else public),
external_id, external_id,
' %s'*len(args) % args ' %s'*len(args) % args)
)
).rstrip() + '>' ).rstrip() + '>'
# Note: DOCTYPE declaration must follow XML declaration # Note: DOCTYPE declaration must follow XML declaration
if len(self) and self[0][:6] == '<?xml ': #if len(self) and self[0][:6] == '<?xml ':
if self[0][:6] == '<?xml ':
self[1:1] = [doctype] self[1:1] = [doctype]
else: else:
self[0:0] = [doctype] self[0:0] = [doctype]
@@ -520,12 +532,8 @@ class Html(list):
""" """
Removes HTML attributes for this object Removes HTML attributes for this object
""" """
self[0] = '<' + self.tag + ( self[0] = '<' + self.tag + (# Set correct closing delimiter(s)
' />' if self.close is False else '>')
# Set correct closing delimiter(s)
' />' if self.close is False else '>'
)
# #
attr = property(__getattr, __setattr, __delattr) attr = property(__getattr, __setattr, __delattr)
# #

View File

@@ -1503,6 +1503,16 @@ class BasePage:
@param: title -- Is the title of the web page @param: title -- Is the title of the web page
@param: cal -- The number of directories to use @param: cal -- The number of directories to use
""" """
# If .php extension and a note selected, add it to the head section.
phpnote = self.report.options['phpnote']
note = None
if phpnote and self.ext == ".php":
# This is used to give the ability to have a php init session.
# This note must not contains formatting
# and should only contains php code. ie:
# <? php session_start (); ?>
note = self.r_db.get_note_from_gramps_id(phpnote).get()
# begin each html page... # begin each html page...
if self.the_lang: if self.the_lang:
xmllang = self.the_lang.replace('_', '-') xmllang = self.the_lang.replace('_', '-')
@@ -1512,11 +1522,11 @@ class BasePage:
(html_escape(self.title_str.strip()), (html_escape(self.title_str.strip()),
html_escape(the_title)), html_escape(the_title)),
self.report.encoding, self.report.encoding,
xmllang, cms=self.usecms) xmllang, cms=self.usecms, php_session=note)
# temporary fix for .php parsing error # temporary fix for .php parsing error
if self.ext in [".php", ".php3", ".cgi"]: if self.ext in [".php", ".cgi"]:
del page[0] del page[0] # remove the "DOCTYPE" directive
# Header constants # Header constants
_meta1 = 'name ="viewport" content="width=device-width, ' _meta1 = 'name ="viewport" content="width=device-width, '

View File

@@ -57,7 +57,7 @@ from gramps.gen.display.name import displayer as _nd
import gramps.plugins.lib.libholiday as libholiday import gramps.plugins.lib.libholiday as libholiday
from gramps.plugins.webreport.basepage import BasePage from gramps.plugins.webreport.basepage import BasePage
from gramps.plugins.webreport.common import do_we_have_holidays from gramps.plugins.webreport.common import (do_we_have_holidays, _WEB_EXT)
from gramps.plugins.lib.libhtml import Html #, xml_lang from gramps.plugins.lib.libhtml import Html #, xml_lang
from gramps.gui.pluginmanager import GuiPluginManager from gramps.gui.pluginmanager import GuiPluginManager
@@ -74,9 +74,6 @@ _LOG = logging.getLogger(".WebPage")
FULLCLEAR = Html("div", class_="fullclear", inline=True) FULLCLEAR = Html("div", class_="fullclear", inline=True)
# Web page filename extensions
_WEB_EXT = ['.html', '.htm', '.shtml', '.php', '.php3', '.cgi']
# Calendar stylesheet names # Calendar stylesheet names
_CALENDARSCREEN = 'calendar-screen.css' _CALENDARSCREEN = 'calendar-screen.css'
_CALENDARPRINT = 'calendar-print.css' _CALENDARPRINT = 'calendar-print.css'

View File

@@ -50,7 +50,7 @@ LOG = logging.getLogger(".NarrativeWeb")
# define clear blank line for proper styling # define clear blank line for proper styling
FULLCLEAR = Html("div", class_="fullclear", inline=True) FULLCLEAR = Html("div", class_="fullclear", inline=True)
# define all possible web page filename extensions # define all possible web page filename extensions
_WEB_EXT = ['.html', '.htm', '.shtml', '.php', '.php3', '.cgi'] _WEB_EXT = ['.html', '.htm', '.shtml', '.php', '.cgi']
# used to select secured web site or not # used to select secured web site or not
HTTP = "http://" HTTP = "http://"
HTTPS = "https://" HTTPS = "https://"

View File

@@ -1906,6 +1906,8 @@ class NavWebOptions(MenuReportOptions):
self.__toggle = None self.__toggle = None
self.__death_anniv = None self.__death_anniv = None
self.__after_year = None self.__after_year = None
self.__ext = None
self.__phpnote = None
db_options = name + ' ' + dbase.get_dbname() db_options = name + ' ' + dbase.get_dbname()
MenuReportOptions.__init__(self, db_options, dbase) MenuReportOptions.__init__(self, db_options, dbase)
@@ -1929,7 +1931,6 @@ class NavWebOptions(MenuReportOptions):
self.__add_translations(menu) self.__add_translations(menu)
self.__add_calendar_options(menu) self.__add_calendar_options(menu)
def __add_report_options(self, menu): def __add_report_options(self, menu):
""" """
Options on the "Report Options" tab. Options on the "Report Options" tab.
@@ -1999,11 +2000,12 @@ class NavWebOptions(MenuReportOptions):
category_name = _("Html options") category_name = _("Html options")
addopt = partial(menu.add_option, category_name) addopt = partial(menu.add_option, category_name)
ext = EnumeratedListOption(_("File extension"), ".html") self.__ext = EnumeratedListOption(_("File extension"), ".html")
for etype in _WEB_EXT: for etype in _WEB_EXT:
ext.add_item(etype, etype) self.__ext.add_item(etype, etype)
ext.set_help(_("The extension to be used for the web files")) self.__ext.set_help(_("The extension to be used for the web files"))
addopt("ext", ext) addopt("ext", self.__ext)
self.__ext.connect("value-changed", self.__ext_changed)
cright = EnumeratedListOption(_('Copyright'), 0) cright = EnumeratedListOption(_('Copyright'), 0)
for index, copt in enumerate(_COPY_OPTIONS): for index, copt in enumerate(_COPY_OPTIONS):
@@ -2197,13 +2199,22 @@ class NavWebOptions(MenuReportOptions):
addopt("contactimg", contactimg) addopt("contactimg", contactimg)
headernote = NoteOption(_('HTML user header')) headernote = NoteOption(_('HTML user header'))
headernote.set_help(_("A note to be used as the page header")) headernote.set_help(_("A note to be used as the page header"
" or a php code to insert."))
addopt("headernote", headernote) addopt("headernote", headernote)
footernote = NoteOption(_('HTML user footer')) footernote = NoteOption(_('HTML user footer'))
footernote.set_help(_("A note to be used as the page footer")) footernote.set_help(_("A note to be used as the page footer"))
addopt("footernote", footernote) addopt("footernote", footernote)
# This option will be available only if you select ".php" in the
# "File extension" from the "Html" tab
self.__phpnote = NoteOption(_('PHP user session'))
self.__phpnote.set_help(_("A note to use for starting the php session."
"\nThis option will be available only if "
"the .php file extension is selected."))
addopt("phpnote", self.__phpnote)
def __add_images_generation_options(self, menu): def __add_images_generation_options(self, menu):
""" """
Options on the "Page Generation" tab. Options on the "Page Generation" tab.
@@ -2602,6 +2613,16 @@ class NavWebOptions(MenuReportOptions):
self.__maxupdates.set_available(False) self.__maxupdates.set_available(False)
self.__maxdays.set_available(False) self.__maxdays.set_available(False)
def __ext_changed(self):
"""
The file extension changed.
If .php selected, we must set the PHP user session available
"""
if self.__ext.get_value()[:4] == ".php":
self.__phpnote.set_available(True)
else:
self.__phpnote.set_available(False)
def __usecms_changed(self): def __usecms_changed(self):
""" """
We need to use cms or not We need to use cms or not