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
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 181 additions and 145 deletions

View File

@ -30,7 +30,6 @@ This module exports the Html class
#------------------------------------------------------------------------
# Python modules
#------------------------------------------------------------------------
import re
#------------------------------------------------------------------------
#
@ -140,8 +139,8 @@ class Html(list):
:param external_id: external identifier of this DOCTYPE.
Defaults to XHTML 1.0 STRICT
:type args: object
:param args: 0 or more positional parameters to be added to this
DOCTYPE.
:param args: 0 or more positional parameters to be added to
this DOCTYPE.
"""
return (
'<!DOCTYPE %s %s %s' % (
@ -152,23 +151,24 @@ class Html(list):
).rstrip() + '>'
#
@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
: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
:param lang: language to be used. Defaul = 'en'
: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',
indent=False,
xmlns=xmlns,
return Html('html', indent=False, xmlns=xmlns,
attr='xml:lang="%s" lang="%s"' % ((lang,)*2),
*args, **keywargs
)
php=php_session,
*args, **keywargs)
#
@staticmethod
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
if pre-html5 syntax required
: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)
@ -199,7 +200,8 @@ class Html(list):
return head
#
@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
@ -212,26 +214,24 @@ class Html(list):
:param html5: generate html5 syntax. Default = True. Set to False
if pre-html5 syntax required
:rtype: three object references
:php_session: the note to include before all html code
:returns: references to the newly-created Html instances for
page, head and body
"""
page = Html.html(lang=lang, *args, **keywargs)
page = Html.html(lang=lang, php_session=php_session,
*args, **keywargs)
if html5:
page.addDOCTYPE(external_id=_HTML5)
else:
page.addXML(encoding=encoding)
page.addDOCTYPE(external_id=_XHTML10_STRICT)
#
head = Html.head(title=title,
encoding=encoding,
lang=lang,
html5=html5,
indent=False,
*args, **keywargs
)
head = Html.head(title=title, encoding=encoding, lang=lang,
html5=html5, indent=False, *args, **keywargs)
#
if cms:
body = Html('div', class_ = "body", indent=False, *args, **keywargs)
body = Html('div', class_="body", indent=False,
*args, **keywargs)
else:
body = Html('body', indent=False, *args, **keywargs)
page += (head, body)
@ -247,15 +247,18 @@ class Html(list):
:param args: 0 more positional arguments to be inserted between
opening and closing HTML tags.
: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
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
:type inline: boolean
:param inline: True ==> instructs the write() method to output this
object and any child objects as a single string
False ==> output this object and its contents one string
at a time
:param inline: True ==> instructs the write() method to output
this object and any child objects as a
single string
False ==> output this object and its contents one
string at a time
Defaults to False
:type close: boolean or None
: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
# addition to the opening tag as attributes.
#
phpnote = None
for keyw, arg in sorted(keywargs.items()):
if (keyw in ['indent', 'close', 'inline'] and
arg in [True, False, None]):
setattr(self, keyw, arg)
elif keyw == 'attr': # pass attributes along
attr += ' ' + arg
elif keyw == 'php': # php init session
phpnote = arg
elif keyw[-1] == '_': # avoid Python conflicts
attr += ' %s="%s"' % (keyw[:-1], arg) # pass keyword arg along
else:
@ -301,7 +307,13 @@ class Html(list):
else:
if tag in _START_CLOSE: # if tag in special list
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,
attr,
('' if self.close is not False else ' /')
@ -393,8 +405,8 @@ class Html(list):
#
def write(self, method=print, indent='\t', tabs=''):
"""
Output function: performs an insertion-order tree traversal
and calls supplied method for each item found.
Output function: performs an insertion-order tree traversal and
calls supplied method for each item found.
:type method: function reference
:param method: function to call with each item found
@ -446,20 +458,20 @@ class Html(list):
:param external_id: external identifier of this DOCTYPE.
Defaults to XHTML 1.0 STRICT
:type args: object
:param args: 0 or more positional parameters to be added to this
DOCTYPE.
:param args: 0 or more positional parameters to be added
to this DOCTYPE.
"""
doctype = (
'<!DOCTYPE %s %s %s%s' % (
name,
('' if external_id ==_HTML5 else public),
'<!DOCTYPE %s %s %s%s' % (name,
('' if external_id == _HTML5
else public),
external_id,
' %s'*len(args) % args
)
' %s'*len(args) % args)
).rstrip() + '>'
# 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]
else:
self[0:0] = [doctype]
@ -520,12 +532,8 @@ class Html(list):
"""
Removes HTML attributes for this object
"""
self[0] = '<' + self.tag + (
# Set correct closing delimiter(s)
' />' if self.close is False else '>'
)
self[0] = '<' + self.tag + (# Set correct closing delimiter(s)
' />' if self.close is False else '>')
#
attr = property(__getattr, __setattr, __delattr)
#

View File

@ -1503,6 +1503,16 @@ class BasePage:
@param: title -- Is the title of the web page
@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...
if self.the_lang:
xmllang = self.the_lang.replace('_', '-')
@ -1512,11 +1522,11 @@ class BasePage:
(html_escape(self.title_str.strip()),
html_escape(the_title)),
self.report.encoding,
xmllang, cms=self.usecms)
xmllang, cms=self.usecms, php_session=note)
# temporary fix for .php parsing error
if self.ext in [".php", ".php3", ".cgi"]:
del page[0]
if self.ext in [".php", ".cgi"]:
del page[0] # remove the "DOCTYPE" directive
# Header constants
_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
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.gui.pluginmanager import GuiPluginManager
@ -74,9 +74,6 @@ _LOG = logging.getLogger(".WebPage")
FULLCLEAR = Html("div", class_="fullclear", inline=True)
# Web page filename extensions
_WEB_EXT = ['.html', '.htm', '.shtml', '.php', '.php3', '.cgi']
# Calendar stylesheet names
_CALENDARSCREEN = 'calendar-screen.css'
_CALENDARPRINT = 'calendar-print.css'

View File

@ -50,7 +50,7 @@ LOG = logging.getLogger(".NarrativeWeb")
# define clear blank line for proper styling
FULLCLEAR = Html("div", class_="fullclear", inline=True)
# 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
HTTP = "http://"
HTTPS = "https://"

View File

@ -1906,6 +1906,8 @@ class NavWebOptions(MenuReportOptions):
self.__toggle = None
self.__death_anniv = None
self.__after_year = None
self.__ext = None
self.__phpnote = None
db_options = name + ' ' + dbase.get_dbname()
MenuReportOptions.__init__(self, db_options, dbase)
@ -1929,7 +1931,6 @@ class NavWebOptions(MenuReportOptions):
self.__add_translations(menu)
self.__add_calendar_options(menu)
def __add_report_options(self, menu):
"""
Options on the "Report Options" tab.
@ -1999,11 +2000,12 @@ class NavWebOptions(MenuReportOptions):
category_name = _("Html options")
addopt = partial(menu.add_option, category_name)
ext = EnumeratedListOption(_("File extension"), ".html")
self.__ext = EnumeratedListOption(_("File extension"), ".html")
for etype in _WEB_EXT:
ext.add_item(etype, etype)
ext.set_help(_("The extension to be used for the web files"))
addopt("ext", ext)
self.__ext.add_item(etype, etype)
self.__ext.set_help(_("The extension to be used for the web files"))
addopt("ext", self.__ext)
self.__ext.connect("value-changed", self.__ext_changed)
cright = EnumeratedListOption(_('Copyright'), 0)
for index, copt in enumerate(_COPY_OPTIONS):
@ -2197,13 +2199,22 @@ class NavWebOptions(MenuReportOptions):
addopt("contactimg", contactimg)
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)
footernote = NoteOption(_('HTML user footer'))
footernote.set_help(_("A note to be used as the page footer"))
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):
"""
Options on the "Page Generation" tab.
@ -2602,6 +2613,16 @@ class NavWebOptions(MenuReportOptions):
self.__maxupdates.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):
"""
We need to use cms or not