Browse Source

Added license GPLv3 + Reworked code

Better compatibility with https://www.mediawiki.org/wiki/Manual:Pywikibot/Development_guidelines
Jonathan Golder 3 years ago
parent
commit
cafe08dd7f
7 changed files with 927 additions and 647 deletions
  1. 188
    0
      license.txt
  2. 0
    193
      mysql_red.py
  3. 231
    0
      mysqlred.py
  4. 0
    309
      red_fam.py
  5. 0
    145
      red_page.py
  6. 338
    0
      redfam.py
  7. 170
    0
      redpage.py

+ 188
- 0
license.txt View File

@@ -0,0 +1,188 @@
1
+GNU GENERAL PUBLIC LICENSE
2
+
3
+Version 3, 29 June 2007
4
+
5
+Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
6
+
7
+Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
8
+
9
+Preamble
10
+
11
+The GNU General Public License is a free, copyleft license for software and other kinds of works.
12
+
13
+The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
14
+
15
+When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
16
+
17
+To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
18
+
19
+For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
20
+
21
+Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
22
+
23
+For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
24
+
25
+Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
26
+
27
+Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
28
+
29
+The precise terms and conditions for copying, distribution and modification follow.
30
+TERMS AND CONDITIONS
31
+0. Definitions.
32
+
33
+“This License” refers to version 3 of the GNU General Public License.
34
+
35
+“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
36
+
37
+“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
38
+
39
+To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
40
+
41
+A “covered work” means either the unmodified Program or a work based on the Program.
42
+
43
+To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
44
+
45
+To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
46
+
47
+An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
48
+1. Source Code.
49
+
50
+The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
51
+
52
+A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
53
+
54
+The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
55
+
56
+The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
57
+
58
+The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
59
+
60
+The Corresponding Source for a work in source code form is that same work.
61
+2. Basic Permissions.
62
+
63
+All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
64
+
65
+You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
66
+
67
+Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
68
+3. Protecting Users' Legal Rights From Anti-Circumvention Law.
69
+
70
+No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
71
+
72
+When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
73
+4. Conveying Verbatim Copies.
74
+
75
+You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
76
+
77
+You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
78
+5. Conveying Modified Source Versions.
79
+
80
+You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
81
+
82
+    a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
83
+    b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
84
+    c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
85
+    d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
86
+
87
+A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
88
+6. Conveying Non-Source Forms.
89
+
90
+You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
91
+
92
+    a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
93
+    b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
94
+    c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
95
+    d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
96
+    e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
97
+
98
+A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
99
+
100
+A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
101
+
102
+“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
103
+
104
+If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
105
+
106
+The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
107
+
108
+Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
109
+7. Additional Terms.
110
+
111
+“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
112
+
113
+When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
114
+
115
+Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
116
+
117
+    a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
118
+    b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
119
+    c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
120
+    d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
121
+    e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
122
+    f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
123
+
124
+All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
125
+
126
+If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
127
+
128
+Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
129
+8. Termination.
130
+
131
+You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
132
+
133
+However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
134
+
135
+Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
136
+
137
+Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
138
+9. Acceptance Not Required for Having Copies.
139
+
140
+You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
141
+10. Automatic Licensing of Downstream Recipients.
142
+
143
+Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
144
+
145
+An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
146
+
147
+You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
148
+11. Patents.
149
+
150
+A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
151
+
152
+A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
153
+
154
+Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
155
+
156
+In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
157
+
158
+If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
159
+
160
+If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
161
+
162
+A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
163
+
164
+Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
165
+12. No Surrender of Others' Freedom.
166
+
167
+If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
168
+13. Use with the GNU Affero General Public License.
169
+
170
+Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
171
+14. Revised Versions of this License.
172
+
173
+The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
174
+
175
+Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
176
+
177
+If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
178
+
179
+Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
180
+15. Disclaimer of Warranty.
181
+
182
+THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
183
+16. Limitation of Liability.
184
+
185
+IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
186
+17. Interpretation of Sections 15 and 16.
187
+
188
+If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.

+ 0
- 193
mysql_red.py View File

@@ -1,193 +0,0 @@
1
-#!/usr/bin/env python3
2
-# -*- coding: utf-8  -*-
3
-
4
-try:
5
-	import oursql as mysqldb
6
-except ImportError:
7
-	import MySQLdb as mysqldb
8
-
9
-from pywikibot import config
10
-
11
-class MYSQL_RED:
12
-	
13
-	#Save mysqldb-connection as class attribute to use only one in descendant classes
14
-	connection = False
15
-	db_hostname=config.db_hostname
16
-	db_username=config.db_username
17
-	db_password=config.db_password
18
-	db_name=config.db_username + '__bot'
19
-	
20
-	def __init__( self ):
21
-		"""
22
-		Opens a connection to MySQL-DB
23
-		
24
-		@returns 	mysql-stream	MySQL Connection
25
-		"""
26
-		
27
-		# Connect to mysqldb only once
28
-		if( type( self ).connection == False ):
29
-			
30
-			type( self ).connection = mysqldb.connect( host=type( self ).db_hostname, user=type( self ).db_username, passwd=type( self ).db_password, db=type( self ).db_name )
31
-		
32
-	def __del__( self ):
33
-		"""
34
-		Before deleting class, close connection to MySQL-DB
35
-		"""
36
-		
37
-		type( self ).connection.close()
38
-
39
-class MYSQL_RED_PAGE( MYSQL_RED ):
40
-	
41
-	def __init__( self, page_id ):
42
-		"""
43
-		Creates a new instance, runs __init__ of parent class
44
-		"""
45
-		super().__init__( )
46
-		
47
-		self.__page_id = int( page_id );
48
-		
49
-		self.data = self.get_page()
50
-	
51
-	def __del__( self ):
52
-		pass
53
-	
54
-	def get_page( self ):
55
-		"""
56
-		Retrieves a red page row from MySQL-Database for given page_id
57
-		
58
-		@param		int		page_id		MediaWiki page_id for page to retrieve
59
-		
60
-		@returns	tuple				Tuple with data for given page_id otherwise if none found
61
-					bool	FALSE
62
-		"""
63
-		cursor = type( self ).connection.cursor(mysqldb.DictCursor)
64
-		
65
-		cursor.execute( 'SELECT * FROM `red_pages` WHERE `page_id` = ?;', ( self.__page_id, ) )
66
-		res = cursor.fetchone()
67
-		
68
-		if res:
69
-			return res
70
-		else:
71
-			return False
72
-	
73
-	def add_page( self, page_title, rev_id, status=0 ):
74
-		"""
75
-		Inserts a red page row in MySQL-Database for given page_id
76
-		
77
-		@param		int		rev_id		MediaWiki current rev_id for page to update
78
-		@param		str		page_title	MediaWiki new page_title for page to update
79
-		@param		int		status		Page parsing status (0 - not (successfully) parsed; 1 - successfully parsed; 2 - successfully parsed archive)
80
-		"""
81
-		
82
-		cursor = type( self ).connection.cursor()
83
-		
84
-		if not page_title:
85
-			page_title = self.data[ 'page_title' ]
86
-		if not rev_id:
87
-			rev_id = self.data[ 'rev_id' ]
88
-		
89
-		query = 'INSERT INTO `red_pages` ( page_id, page_title, rev_id, status ) VALUES ( ?, ?, ?, ? );'
90
-		data = ( self.__page_id, str( page_title ), int( rev_id ), int( status ) )
91
-		
92
-		cursor.execute( query, data)
93
-		
94
-		type( self ).connection.commit()
95
-		
96
-		self.data = self.get_page()
97
-	
98
-	
99
-	def update_page( self, rev_id=None, page_title=None, status=0 ):
100
-		"""
101
-		Updates the red page row in MySQL-Database for given page_id
102
-		
103
-		@param		int		rev_id		MediaWiki current rev_id for page to update
104
-		@param		str		page_title	MediaWiki new page_title for page to update
105
-		@param		int		status		Page parsing status (0 - not (successfully) parsed; 1 - successfully parsed)
106
-		"""
107
-		
108
-		cursor = type( self ).connection.cursor()
109
-		
110
-		if not page_title:
111
-			page_title = self.data[ 'page_title' ]
112
-		if not rev_id:
113
-			rev_id = self.data[ 'rev_id' ]
114
-		
115
-		query = 'UPDATE `red_pages` SET `page_title` = ?, `rev_id` = ?, `status`= ? WHERE `page_id` = ?;'
116
-		data = ( str( page_title ), int( rev_id ), int( status ), self.__page_id )
117
-		
118
-		cursor.execute( query, data)
119
-		
120
-		type( self ).connection.commit()
121
-	
122
-
123
-class MYSQL_RED_FAM( MYSQL_RED ):
124
-	
125
-	def __init__( self, fam_hash ):
126
-		"""
127
-		Creates a new instance, runs __init__ of parent class
128
-		"""
129
-		super().__init__( )
130
-		
131
-		self.__fam_hash = fam_hash
132
-		
133
-		self.data = self.get_fam()
134
-	
135
-	def __del__( self ):
136
-		pass
137
-	
138
-	def get_fam( self ):
139
-		"""
140
-		Retrieves a red family row from MySQL-Database for given fam_hash
141
-		
142
-		@returns	dict				Dictionairy with data for given fam hash otherwise if none found
143
-					bool	FALSE
144
-		"""
145
-		cursor = type( self ).connection.cursor(mysqldb.DictCursor)
146
-		
147
-		cursor.execute( 'SELECT * FROM `red_families` WHERE `fam_hash` = ?;', ( self.__fam_hash, ) )
148
-		res = cursor.fetchone()
149
-		
150
-		if res:
151
-			return res
152
-		else:
153
-			return False
154
-			
155
-	def add_fam( self, articlesList, heading, red_page_id, beginning, ending=None, status=0 ):
156
-		
157
-		cursor = type( self ).connection.cursor()
158
-		
159
-		query = 'INSERT INTO `red_families` ( fam_hash, red_page_id, beginning, ending, status, heading, article0, article1, article2, article3, article4, article5, article6, article7 ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? );'
160
-		data = [ str( self.__fam_hash ), red_page_id, beginning, ending, status, heading ]
161
-		
162
-		for article in articlesList:
163
-			data.append( str( article ) )
164
-		
165
-		while len( data ) < 14:
166
-			data.append( None )
167
-		
168
-		data = tuple( data )
169
-		
170
-		cursor.execute( query, data)
171
-		
172
-		type( self ).connection.commit()
173
-		
174
-		self.data = self.get_fam()
175
-	
176
-	def update_fam( self, red_page_id, heading, beginning, ending, status ):
177
-		"""
178
-		Updates the red fam row in MySQL-Database for given fam_hash
179
-		
180
-		@param		int			red_page_id		MediaWiki page_id which contains red_fam
181
-		@param		datetime	beginning		Timestamp of beginning of redundance discussion
182
-		qparam		datetime	ending			Timestamp of ending of redundance discussion
183
-		@param		int			status			red_fam status (0 - discussion is running; 1 - discussion over; 2 - discussion archived)
184
-		"""
185
-		
186
-		cursor = type( self ).connection.cursor()
187
-		
188
-		query = 'UPDATE `red_families` SET `red_page_id` = ?, `heading` = ?, `beginning` = ?, `ending` = ?, `status`= ? WHERE `fam_hash` = ?;'
189
-		data = ( int(red_page_id ), str( heading ),  beginning, ending, int( status ), self.__fam_hash )
190
-		
191
-		cursor.execute( query, data)
192
-		
193
-		type( self ).connection.commit()

+ 231
- 0
mysqlred.py View File

@@ -0,0 +1,231 @@
1
+#!/usr/bin/env python3
2
+# -*- coding: utf-8  -*-
3
+#
4
+#  mysqlred.py
5
+#  
6
+#  Copyright 2015 GOLDERWEB – Jonathan Golder <jonathan@golderweb.de>
7
+#  
8
+#  This program is free software; you can redistribute it and/or modify
9
+#  it under the terms of the GNU General Public License as published by
10
+#  the Free Software Foundation; either version 3 of the License, or
11
+#  (at your option) any later version.
12
+#  
13
+#  This program is distributed in the hope that it will be useful,
14
+#  but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
+#  GNU General Public License for more details.
17
+#  
18
+#  You should have received a copy of the GNU General Public License
19
+#  along with this program; if not, write to the Free Software
20
+#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21
+#  MA 02110-1301, USA.
22
+#  
23
+#  
24
+"""
25
+Provides interface classes for communication of redundances bot with mysql-db
26
+"""
27
+
28
+# Prefere using oursql then MySQLdb
29
+try:
30
+    import oursql as mysqldb
31
+except ImportError:
32
+    import MySQLdb as mysqldb
33
+
34
+from pywikibot import config
35
+
36
+class MysqlRed:
37
+    """
38
+    Basic interface class, containing opening of connection
39
+    
40
+    Specific querys should be defined in descendant classes per data type
41
+    """
42
+    
43
+    #Save mysqldb-connection as class attribute to use only one in descendant classes
44
+    connection = False
45
+    db_hostname=config.db_hostname
46
+    db_username=config.db_username
47
+    db_password=config.db_password
48
+    db_name=config.db_username + '__bot'
49
+    
50
+    def __init__( self ):
51
+        """
52
+        Opens a connection to MySQL-DB
53
+        
54
+        @returns     mysql-stream    MySQL Connection
55
+        """
56
+        
57
+        # Connect to mysqldb only once
58
+        if( type( self ).connection == False ):
59
+            
60
+            type( self ).connection = mysqldb.connect( host=type( self ).db_hostname, user=type( self ).db_username, passwd=type( self ).db_password, db=type( self ).db_name )
61
+        
62
+    def __del__( self ):
63
+        """
64
+        Before deleting class, close connection to MySQL-DB
65
+        """
66
+        
67
+        type( self ).connection.close()
68
+
69
+class MysqlRedPage( MysqlRed ):
70
+	"""
71
+	MySQL-db Interface for handling querys for RedPages
72
+	"""
73
+    
74
+    def __init__( self, page_id ):
75
+        """
76
+        Creates a new instance, runs __init__ of parent class
77
+        """
78
+        
79
+        super().__init__( )
80
+        
81
+        self.__page_id = int( page_id );
82
+        
83
+        self.data = self.get_page()
84
+    
85
+    def __del__( self ):
86
+        pass
87
+    
88
+    def get_page( self ):
89
+        """
90
+        Retrieves a red page row from MySQL-Database for given page_id
91
+        
92
+        @param      int      page_id    MediaWiki page_id for page to retrieve
93
+        
94
+        @returns    tuple               Tuple with data for given page_id otherwise if none found
95
+                    bool     FALSE
96
+        """
97
+        
98
+        cursor = type( self ).connection.cursor(mysqldb.DictCursor)
99
+        
100
+        cursor.execute( 'SELECT * FROM `red_pages` WHERE `page_id` = ?;', ( self.__page_id, ) )
101
+        res = cursor.fetchone()
102
+        
103
+        if res:
104
+            return res
105
+        else:
106
+            return False
107
+    
108
+    def add_page( self, page_title, rev_id, status=0 ):
109
+        """
110
+        Inserts a red page row in MySQL-Database for given page_id
111
+        
112
+        @param        int    rev_id        MediaWiki current rev_id for page to update
113
+        @param        str    page_title    MediaWiki new page_title for page to update
114
+        @param        int    status        Page parsing status (0 - not (successfully) parsed; 1 - successfully parsed; 2 - successfully parsed archive)
115
+        """
116
+        
117
+        cursor = type( self ).connection.cursor()
118
+        
119
+        if not page_title:
120
+            page_title = self.data[ 'page_title' ]
121
+        if not rev_id:
122
+            rev_id = self.data[ 'rev_id' ]
123
+        
124
+        query = 'INSERT INTO `red_pages` ( page_id, page_title, rev_id, status ) VALUES ( ?, ?, ?, ? );'
125
+        data = ( self.__page_id, str( page_title ), int( rev_id ), int( status ) )
126
+        
127
+        cursor.execute( query, data)
128
+        
129
+        type( self ).connection.commit()
130
+        
131
+        self.data = self.get_page()
132
+    
133
+    def update_page( self, rev_id=None, page_title=None, status=0 ):
134
+        """
135
+        Updates the red page row in MySQL-Database for given page_id
136
+        
137
+        @param        int    rev_id        MediaWiki current rev_id for page to update
138
+        @param        str    page_title    MediaWiki new page_title for page to update
139
+        @param        int    status        Page parsing status (0 - not (successfully) parsed; 1 - successfully parsed)
140
+        """
141
+        
142
+        cursor = type( self ).connection.cursor()
143
+        
144
+        if not page_title:
145
+            page_title = self.data[ 'page_title' ]
146
+        if not rev_id:
147
+            rev_id = self.data[ 'rev_id' ]
148
+        
149
+        query = 'UPDATE `red_pages` SET `page_title` = ?, `rev_id` = ?, `status`= ? WHERE `page_id` = ?;'
150
+        data = ( str( page_title ), int( rev_id ), int( status ), self.__page_id )
151
+        
152
+        cursor.execute( query, data)
153
+        
154
+        type( self ).connection.commit()
155
+    
156
+class MysqlRedFam( MysqlRed ):
157
+    """
158
+	MySQL-db Interface for handling querys for RedFams
159
+	"""
160
+    
161
+    def __init__( self, fam_hash ):
162
+        """
163
+        Creates a new instance, runs __init__ of parent class
164
+        """
165
+        
166
+        super().__init__( )
167
+        
168
+        self.__fam_hash = fam_hash
169
+        
170
+        self.data = self.get_fam()
171
+    
172
+    def __del__( self ):
173
+        pass
174
+    
175
+    def get_fam( self ):
176
+        """
177
+        Retrieves a red family row from MySQL-Database for given fam_hash
178
+        
179
+        @returns    dict    Dictionairy with data for given fam hash otherwise if none found
180
+                    bool    FALSE
181
+        """
182
+        
183
+        cursor = type( self ).connection.cursor(mysqldb.DictCursor)
184
+        
185
+        cursor.execute( 'SELECT * FROM `red_families` WHERE `fam_hash` = ?;', ( self.__fam_hash, ) )
186
+        res = cursor.fetchone()
187
+        
188
+        if res:
189
+            return res
190
+        else:
191
+            return False
192
+            
193
+    def add_fam( self, articlesList, heading, red_page_id, beginning, ending=None, status=0 ):
194
+        
195
+        cursor = type( self ).connection.cursor()
196
+        
197
+        query = 'INSERT INTO `red_families` ( fam_hash, red_page_id, beginning, ending, status, heading, article0, article1, article2, article3, article4, article5, article6, article7 ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? );'
198
+        data = [ str( self.__fam_hash ), red_page_id, beginning, ending, status, heading ]
199
+        
200
+        for article in articlesList:
201
+            data.append( str( article ) )
202
+        
203
+        while len( data ) < 14:
204
+            data.append( None )
205
+        
206
+        data = tuple( data )
207
+        
208
+        cursor.execute( query, data)
209
+        
210
+        type( self ).connection.commit()
211
+        
212
+        self.data = self.get_fam()
213
+    
214
+    def update_fam( self, red_page_id, heading, beginning, ending, status ):
215
+        """
216
+        Updates the red fam row in MySQL-Database for given fam_hash
217
+        
218
+        @param        int         red_page_id    MediaWiki page_id which contains red_fam
219
+        @param        datetime    beginning      Timestamp of beginning of redundance discussion
220
+        qparam        datetime    ending         Timestamp of ending of redundance discussion
221
+        @param        int         status         red_fam status (0 - discussion is running; 1 - discussion over; 2 - discussion archived)
222
+        """
223
+        
224
+        cursor = type( self ).connection.cursor()
225
+        
226
+        query = 'UPDATE `red_families` SET `red_page_id` = ?, `heading` = ?, `beginning` = ?, `ending` = ?, `status`= ? WHERE `fam_hash` = ?;'
227
+        data = ( int(red_page_id ), str( heading ),  beginning, ending, int( status ), self.__fam_hash )
228
+        
229
+        cursor.execute( query, data)
230
+        
231
+        type( self ).connection.commit()

+ 0
- 309
red_fam.py View File

@@ -1,309 +0,0 @@
1
-#!/usr/bin/env python3
2
-# -*- coding: utf-8  -*-
3
-
4
-import hashlib
5
-import re
6
-import locale
7
-from datetime import datetime
8
-
9
-import pywikibot
10
-
11
-from mysql_red import MYSQL_RED_FAM
12
-
13
-class RED_FAM:
14
-	
15
-
16
-	
17
-	def __init__( self, fam_hash=None, articlesList=None, red_page_id=None, beginning=None, ending=None, status=0 ):
18
-		"""
19
-		Generates a new RED_FAM object
20
-		
21
-		@param		articlesList	list		List of articles of redundance family
22
-		@param		beginning		datetime	Beginning date of redundance diskussion
23
-		@param		ending			datetime	Ending date of redundance diskussion
24
-		"""
25
-		
26
-		#if( beginning ):
27
-		#	self.add_beginning( beginning )
28
-		#	self._beginning = None
29
-		
30
-		#if( ending ):
31
-		#	self.add_ending( ending )
32
-		#else:
33
-		#	self._ending = None
34
-			
35
-		#self._status = status # __TODO__ STATUS CODE
36
-		
37
-		#self._handle_db()
38
-
39
-
40
-
41
-	def __repr__( self ):
42
-		
43
-		if( self._beginning ):
44
-			beginning = ", beginning=" + repr( self._beginning )
45
-		else:
46
-			beginning = ""
47
-			
48
-		if( self._ending ):
49
-			ending = ", ending=" + repr( self._ending )
50
-		else:
51
-			ending = ""
52
-		
53
-		__repr = "RED_FAM( " + repr( self._articlesList ) + beginning + ending + ", status=" + repr( self._status ) + " )"
54
-		
55
-		return __repr
56
-		
57
-class RED_FAM_PARSER( RED_FAM ):
58
-	"""
59
-	Provides an interface to RED_FAM for adding/updating redundance families while parsig redundance pages
60
-	"""
61
-	
62
-	# Define the timestamp format
63
-	__timestamp_format = "%H:%M, %d. %b. %Y"
64
-	
65
-	# Define section heading re.pattern
66
-	__sectionhead_pat = re.compile( r"^(=+)(.*\[\[.+\]\].*\[\[.+\]\].*)\1" )
67
-	
68
-	# Define timestamp re.pattern
69
-	__timestamp_pat = re.compile( r"(\d{2}:\d{2}), (\d{1,2}). (Jan|Feb|Mär|Apr|Mai|Jun|Jul|Aug|Sep|Okt|Nov|Dez).? (\d{4})" )
70
-	
71
-	# Textpattern for recognisation of done-notices
72
-	__done_notice = ":<small>Archivierung dieses Abschnittes wurde gewünscht von:"
73
-	__done_notice2 = "{{Erledigt|"
74
-	
75
-	def __init__( self, heading, red_page_id, red_page_archive, beginning, ending=None ):
76
-		"""
77
-		Creates a RED_FAM object based on data collected while parsing red_pages combined with possibly former known data from db
78
-		
79
-		@param		red_fam_heading		string		String with wikitext heading of redundance section
80
-		@param		red_page_id			int			MediaWiki page_id of red_page containing red_fam
81
-		@param		red_page_archive	bool		Is red_page an archive
82
-		@param		beginning			datetime	Timestamp of beginning of redundance discussion
83
-										string		Timestamp of beginning of redundance discussion as srftime parseable string
84
-		@param		ending				datetime	Timestamp of ending of redundance discussion
85
-										string		Timestamp of ending of redundance discussion as srftime parseable string
86
-		"""
87
-		## Set object attributes:
88
-		self._red_page_id = red_page_id
89
-		self._red_page_archive = red_page_archive
90
-		
91
-		# Method self.add_beginning sets self._beginning directly
92
-		self.add_beginning( beginning )
93
-		
94
-		# Method self.add_ending sets self._ending directly
95
-		if( ending ):
96
-			self.add_ending( ending )
97
-		else:
98
-			#If no ending was provided set to None
99
-			self._ending = None
100
-		
101
-		self._status = None
102
-		
103
-		# Parse the provided heading of redundance section to set self._articlesList
104
-		self.heading_parser( heading )
105
-		
106
-		# Calculates the sha1 hash over self._articlesList to rediscover known redundance families
107
-		self.fam_hash()
108
-		
109
-		# Open database connection, ask for data if existing, otherwise create entry
110
-		self.__handle_db()
111
-		
112
-		# Check status changes
113
-		self.status()
114
-		
115
-		# Triggers db update if anything changed
116
-		self.changed()
117
-		
118
-	def __handle_db( self ):
119
-		"""
120
-		Handles opening of db connection
121
-		"""
122
-		# We need a connection to our mysqldb
123
-		self.__mysql = MYSQL_RED_FAM( self._fam_hash )
124
-		
125
-		if not self.__mysql.data:
126
-			self.__mysql.add_fam( self._articlesList, self._heading, self._red_page_id, self._beginning, self._ending )
127
-	
128
-	def heading_parser( self, heading ):
129
-		"""
130
-		Parses given red_fam_heading string and saves articles list
131
-		"""
132
-		
133
-		# Predefine a pattern for wikilinks' destination
134
-		wikilink_pat = re.compile( r"\[\[([^\[\]\|]*)(\]\]|\|)" )
135
-	
136
-		# Parse content of heading for generating section links later
137
-		match = self.__sectionhead_pat.search( heading )
138
-		if match:
139
-			self._heading = match.group(2).lstrip()
140
-		else:
141
-			raise ValueError( "Heading is not valid" )
142
-		
143
-		# We get the pages in first [0] element iterating over wikilink_pat.findall( line )
144
-		self._articlesList = [ link[0] for link in wikilink_pat.findall( self._heading ) ]
145
-		
146
-		# Catch sections with more then 8 articles, print error
147
-		if len( self._articlesList ) > 8:
148
-			pywikibot.output( "{datetime} – \03{{lightred}}[WARNING] – Maximum number of articles in red_fam exceeded, maximum number is 8, {number:d} were given\n{repress}".format( datetime=datetime.now().strftime("%Y-%m-%d %H:%M:%S (%Z)"), number=len( self._articlesList ), repress=repr( self ) ) )
149
-			self._articlesList = self._articlesList[:8]
150
-
151
-	def fam_hash( self ):
152
-		"""
153
-		Calculates the SHA-1 hash for the articlesList of redundance family.
154
-		Since we don't need security SHA-1 is just fine.
155
-		
156
-		@returns	str					String with the hexadecimal hash digest
157
-		"""
158
-		
159
-		h = hashlib.sha1()
160
-		h.update( str( self._articlesList ).encode('utf-8') )
161
-		
162
-		self._fam_hash= h.hexdigest()
163
-
164
-	def add_beginning( self, beginning ):
165
-		"""
166
-		Adds the beginning date of a redundance diskussion to the object and sets changed to True
167
-		
168
-		@param		datetime	datetime	Beginning date of redundance diskussion
169
-		"""
170
-		
171
-		self._beginning = self.__datetime( beginning )
172
-		
173
-	def add_ending( self, ending ):
174
-		"""
175
-		Adds the ending date of a redundance diskussion to the object. Also sets the status to __TODO__ STATUS NUMBER and changed to True
176
-		
177
-		@param		datetime	datetime	Ending date of redundance diskussion
178
-		"""
179
-		
180
-		self._ending = self.__datetime( ending )
181
-	
182
-	def __datetime( self, timestamp ):
183
-		"""
184
-		Decides wether given timestamp is a parseable string or a datetime object and returns a datetime object in both cases
185
-		
186
-		@param		timestamp	datetime	Datetime object
187
-								str			Parseable string with timestamp in format __timestamp_format
188
-								
189
-		@returns				datetime	Datetime object
190
-		"""
191
-		locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')
192
-		
193
-		if( isinstance( timestamp, datetime ) ):
194
-			return timestamp
195
-		else:
196
-			result = datetime.strptime( timestamp, type( self ).__timestamp_format )
197
-		return result
198
-			
199
-	def status( self ):
200
-		"""
201
-		Handles detection of correct status
202
-		There are three possible stati:
203
-		- 0 Discussion is running --> no ending, page is not an archive
204
-		- 1 Discussion is over --> ending present, page is not an archive
205
-		- 2 Discussion is archived --> ending (normaly) present, page is an archive
206
-		- 3 and greater status was set by worker script, do not change it
207
-		"""
208
-		
209
-		# Do not change stati set by worker script etc.
210
-		if not self.__mysql.data['status'] > 2:
211
-			
212
-			# No ending, discussion is running:
213
-			# Sometimes archived discussions also have no detectable ending
214
-			if not self._ending and not self._red_page_archive:
215
-				self._status = 0
216
-			else:
217
-				if not self._red_page_archive:
218
-					self._status = 1
219
-				else:
220
-					self._status = 2
221
-		else:
222
-			self._status = self.__mysql.data[ 'status' ]
223
-		
224
-		
225
-				
226
-	def changed( self ):
227
-		"""
228
-		Checks wether anything has changed and maybe triggers db update
229
-		"""
230
-		
231
-		# On archived red_fams do not delete possibly existing ending
232
-		if not self._ending and self._status > 1 and self.__mysql.data[ 'ending' ]:
233
-			self._ending = self.__mysql.data[ 'ending' ]
234
-			 
235
-		
236
-		# Since status change means something has changed, update database
237
-		if( self._status != self.__mysql.data[ 'status' ] or self._beginning !=  self.__mysql.data[ 'beginning' ] or self._ending !=  self.__mysql.data[ 'ending' ] or self._red_page_id != self.__mysql.data[ 'red_page_id' ] or self._heading != self.__mysql.data[ 'heading' ]):
238
-			self.__mysql.update_fam( self._red_page_id, self._heading, self._beginning, self._ending, self._status )
239
-			
240
-	@classmethod
241
-	def is_sectionheading( cls, line ):
242
-		"""
243
-		Checks wether given line is a red_fam section heading
244
-		
245
-		@param		line	string		String to check
246
-		
247
-		@returns	bool				Returns True if it is a section heading, otherwise false
248
-		"""
249
-		
250
-		if cls.__sectionhead_pat.search( line ):
251
-			return True
252
-		else:
253
-			return False
254
-	
255
-	@classmethod
256
-	def is_beginning( cls, line ):
257
-		"""
258
-		Returns the first timestamp found in line, otherwise None
259
-	
260
-		@param		str		line	String to search in
261
-	
262
-		@returns	str				Timestamp, otherwise None
263
-		"""
264
-		
265
-		match = cls.__timestamp_pat.search( line )
266
-		if match:
267
-			# Since some timestamps are broken we need to reconstruct them by regex match groups
268
-			result = match.group(1) + ", " + match.group(2) + ". " + match.group(3) + ". " + match.group(4)
269
-			return result
270
-		else:
271
-			return None
272
-		
273
-	@classmethod
274
-	def is_ending( cls, line ):
275
-		"""
276
-		Returns the timestamp of done notice ( if one ), otherwise None
277
-		@param		str		line	String to search in
278
-	
279
-		@returns	str				Timestamp, otherwise None
280
-		"""
281
-		if ( cls.__done_notice in line ) or ( cls.__done_notice2 in line ):
282
-			match = cls.__timestamp_pat.search( line )
283
-			if match:
284
-				# Since some timestamps are broken we need to reconstruct them by regex match groups
285
-				result = match.group(1) + ", " + match.group(2) + ". " + match.group(3) + ". " + match.group(4)
286
-				return result
287
-		return None
288
-	
289
-	@classmethod
290
-	def is_ending2( cls, line ):
291
-		"""
292
-		Returns the last timestamp found in line, otherwise None
293
-		@param		str		line	String to search in
294
-	
295
-		@returns	str				Timestamp, otherwise None
296
-		"""
297
-		matches = cls.__timestamp_pat.findall( line )
298
-		if matches:
299
-			# Since some timestamps are broken we need to reconstruct them by regex match groups
300
-			result = matches[-1][0] + ", " + matches[-1][1] + ". " + matches[-1][2] + ". " + matches[-1][3]
301
-			return result
302
-		else:
303
-			return None 
304
-
305
-class RED_FAM_WORKER( RED_FAM ):
306
-	"""
307
-	Handles working with redundance families stored in database where discussion is finished
308
-	"""
309
-	pass

+ 0
- 145
red_page.py View File

@@ -1,145 +0,0 @@
1
-#!/usr/bin/env python3
2
-# -*- coding: utf-8  -*-
3
-
4
-import pywikibot
5
-
6
-from mysql_red import MYSQL_RED_PAGE
7
-from red_fam import RED_FAM_PARSER
8
-
9
-
10
-class RED_PAGE:
11
-	"""Class for handling redundance discussion pages and archives"""
12
-	
13
-	def __init__( self, page, archive=False ):
14
-		"""
15
-		Generate a new RED_PAGE object based on the given pywikibot page object
16
-	
17
-		@param		page	page
18
-		"""
19
-		
20
-		# Safe the pywikibot page object
21
-		self.page = page
22
-		self._archive = archive
23
-		
24
-		self.__handle_db( )
25
-
26
-		self.is_page_changed()
27
-		
28
-		self._parsed = None
29
-		if( self._changed or self.__mysql.data[ 'status' ] == 0 ):
30
-			self.parse()
31
-		
32
-		self.__update_db()
33
-			
34
-	#	else:
35
-	#		self.__mysql.add_page()
36
-	
37
-	def __handle_db( self ):
38
-		"""
39
-		Handles opening of db connection
40
-		"""
41
-		# We need a connection to our mysqldb
42
-		self.__mysql = MYSQL_RED_PAGE( self.page._pageid )
43
-		
44
-		if not self.__mysql.data:
45
-			self.__mysql.add_page( self.page.title(), self.page._revid )
46
-			
47
-	def is_page_changed( self ):
48
-		"""
49
-		Check wether the page was changed since last run
50
-		"""
51
-		
52
-		if( self.__mysql.data != { 'page_id': self.page._pageid, 'rev_id': self.page._revid, 'page_title': self.page.title(), 'status': self.__mysql.data[ 'status' ] } ):
53
-			self._changed = True
54
-		else:
55
-			self._changed = False
56
-
57
-	def is_archive( self ):
58
-		"""
59
-		Detects wether current page is an archive of discussions
60
-		"""
61
-		if self._archive or ( u"/Archiv" in self.page.title() ) or ( "{{Archiv}}" in self.page.text ) or ( "{{Archiv|" in self.page.text ):
62
-			return True
63
-		else:
64
-			return False
65
-		
66
-	def parse( self ):
67
-		"""
68
-		Handles the parsing process
69
-		"""
70
-
71
-		# Since @param text is a string we need to split it in lines
72
-		text_lines = self.page.text.split( "\n" )
73
-		length = len( text_lines )
74
-		
75
-		# Initialise line counter
76
-		i = 0
77
-		fam_heading = None
78
-		beginning = None
79
-		ending = None
80
-	
81
-		# Set line for last detected Redundance-Family to 0
82
-		last_fam = 0
83
-	
84
-		# Iterate over the lines of the page
85
-		for line in text_lines:
86
-			
87
-			# Check wether we have an "Redundance-Family"-Section heading (Level 3)
88
-			if RED_FAM_PARSER.is_sectionheading( line ):
89
-				
90
-				# Save line number for last detected Redundance-Family
91
-				last_fam = i
92
-				# Save heading
93
-				fam_heading = line
94
-				
95
-				# Defined (re)initialisation of dates
96
-				beginning = None
97
-				ending = None
98
-			
99
-			# Check wether we are currently in an "Redundance-Family"-Section Body
100
-			if i > last_fam and last_fam > 0:
101
-			
102
-				# Check if we have alredy recognized the beginning date of the discussion (in former iteration) or if we have a done-notice
103
-				if not beginning:
104
-					beginning = RED_FAM_PARSER.is_beginning( line )
105
-				elif not ending:
106
-					ending = RED_FAM_PARSER.is_ending( line )
107
-			
108
-			# Detect end of red_fam section (next line is new sectionheading) or end of file
109
-			# Prevent from running out of index
110
-			if i < (length - 1):
111
-				test = RED_FAM_PARSER.is_sectionheading( text_lines[ i + 1 ] )
112
-			else:
113
-				test = False
114
-			if ( test or ( length == ( i + 1 ) ) ):
115
-				
116
-				# Create the red_fam object
117
-				if( fam_heading and beginning ):
118
-					
119
-					#Maybe we can find a ending by feed if we have None yet (No done notice on archive pages)
120
-					if not ending and self.is_archive():
121
-						j = i
122
-						while (j > last_fam) and not ending:
123
-							j -= 1
124
-							ending = RED_FAM_PARSER.is_ending2( text_lines[ j ] )
125
-					
126
-					
127
-					red_fam = RED_FAM_PARSER( fam_heading, self.page._pageid, self.is_archive(), beginning, ending )
128
-			
129
-			# Increment line counter
130
-			i += 1
131
-		else:
132
-			self._parsed = True
133
-	def __update_db( self ):
134
-		"""
135
-		Updates the page meta data in mysql db
136
-		"""
137
-		if( self._parsed or not self._changed ):
138
-			status = 1
139
-		
140
-			if( self.is_archive() ):
141
-				status = 2
142
-		else:
143
-			status = 0
144
-			
145
-		self.__mysql.update_page( self.page._revid, self.page.title(), status )

+ 338
- 0
redfam.py View File

@@ -0,0 +1,338 @@
1
+#!/usr/bin/env python3
2
+# -*- coding: utf-8  -*-
3
+#
4
+#  redfam.py
5
+#  
6
+#  Copyright 2015 GOLDERWEB – Jonathan Golder <jonathan@golderweb.de>
7
+#  
8
+#  This program is free software; you can redistribute it and/or modify
9
+#  it under the terms of the GNU General Public License as published by
10
+#  the Free Software Foundation; either version 3 of the License, or
11
+#  (at your option) any later version.
12
+#  
13
+#  This program is distributed in the hope that it will be useful,
14
+#  but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
+#  GNU General Public License for more details.
17
+#  
18
+#  You should have received a copy of the GNU General Public License
19
+#  along with this program; if not, write to the Free Software
20
+#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21
+#  MA 02110-1301, USA.
22
+#  
23
+#  
24
+"""
25
+Provides classes for working with RedFams
26
+"""
27
+
28
+import hashlib
29
+import re
30
+import locale
31
+from datetime import datetime
32
+
33
+import pywikibot
34
+
35
+from mysqlred import MysqlRedFam
36
+
37
+class RedFam:
38
+    """
39
+    Basic class for RedFams, containing the basic data structure
40
+    """
41
+    
42
+    def __init__( self, fam_hash=None, articlesList=None, red_page_id=None, beginning=None, ending=None, status=0 ):
43
+        """
44
+        Generates a new RedFam object
45
+        
46
+        @param    articlesList    list        List of articles of redundance family
47
+        @param    beginning       datetime    Beginning date of redundance diskussion
48
+        @param    ending          datetime    Ending date of redundance diskussion
49
+        """
50
+        
51
+        #if( beginning ):
52
+        #    self.add_beginning( beginning )
53
+        #    self._beginning = None
54
+        
55
+        #if( ending ):
56
+        #    self.add_ending( ending )
57
+        #else:
58
+        #    self._ending = None
59
+            
60
+        #self._status = status # __TODO__ STATUS CODE
61
+        
62
+        #self._handle_db()
63
+    
64
+    def __repr__( self ):
65
+        
66
+        if( self._beginning ):
67
+            beginning = ", beginning=" + repr( self._beginning )
68
+        else:
69
+            beginning = ""
70
+            
71
+        if( self._ending ):
72
+            ending = ", ending=" + repr( self._ending )
73
+        else:
74
+            ending = ""
75
+        
76
+        __repr = "RedFam( " + repr( self._articlesList ) + beginning + ending + ", status=" + repr( self._status ) + " )"
77
+        
78
+        return __repr
79
+    
80
+class RedFamParser( RedFam ):
81
+    """
82
+    Provides an interface to RedFam for adding/updating redundance families while parsig redundance pages
83
+    """
84
+    
85
+    # Define the timestamp format
86
+    __timestamp_format = "%H:%M, %d. %b. %Y"
87
+    
88
+    # Define section heading re.pattern
89
+    __sectionhead_pat = re.compile( r"^(=+)(.*\[\[.+\]\].*\[\[.+\]\].*)\1" )
90
+    
91
+    # Define timestamp re.pattern
92
+    __timestamp_pat = re.compile( r"(\d{2}:\d{2}), (\d{1,2}). (Jan|Feb|Mär|Apr|Mai|Jun|Jul|Aug|Sep|Okt|Nov|Dez).? (\d{4})" )
93
+    
94
+    # Textpattern for recognisation of done-notices
95
+    __done_notice = ":<small>Archivierung dieses Abschnittes wurde gewünscht von:"
96
+    __done_notice2 = "{{Erledigt|"
97
+    
98
+    def __init__( self, heading, red_page_id, red_page_archive, beginning, ending=None ):
99
+        """
100
+        Creates a RedFam object based on data collected while parsing red_pages combined with possibly former known data from db
101
+        
102
+        @param        red_fam_heading        string        String with wikitext heading of redundance section
103
+        @param        red_page_id            int            MediaWiki page_id of red_page containing red_fam
104
+        @param        red_page_archive    bool        Is red_page an archive
105
+        @param        beginning            datetime    Timestamp of beginning of redundance discussion
106
+                                        string        Timestamp of beginning of redundance discussion as srftime parseable string
107
+        @param        ending                datetime    Timestamp of ending of redundance discussion
108
+                                        string        Timestamp of ending of redundance discussion as srftime parseable string
109
+        """
110
+        
111
+        ## Set object attributes:
112
+        self._red_page_id = red_page_id
113
+        self._red_page_archive = red_page_archive
114
+        
115
+        # Method self.add_beginning sets self._beginning directly
116
+        self.add_beginning( beginning )
117
+        
118
+        # Method self.add_ending sets self._ending directly
119
+        if( ending ):
120
+            self.add_ending( ending )
121
+        else:
122
+            #If no ending was provided set to None
123
+            self._ending = None
124
+        
125
+        self._status = None
126
+        
127
+        # Parse the provided heading of redundance section to set self._articlesList
128
+        self.heading_parser( heading )
129
+        
130
+        # Calculates the sha1 hash over self._articlesList to rediscover known redundance families
131
+        self.fam_hash()
132
+        
133
+        # Open database connection, ask for data if existing, otherwise create entry
134
+        self.__handle_db()
135
+        
136
+        # Check status changes
137
+        self.status()
138
+        
139
+        # Triggers db update if anything changed
140
+        self.changed()
141
+        
142
+    def __handle_db( self ):
143
+        """
144
+        Handles opening of db connection
145
+        """
146
+        
147
+        # We need a connection to our mysqldb
148
+        self.__mysql = MysqlRedFam( self._fam_hash )
149
+        
150
+        if not self.__mysql.data:
151
+            self.__mysql.add_fam( self._articlesList, self._heading, self._red_page_id, self._beginning, self._ending )
152
+    
153
+    def heading_parser( self, heading ):
154
+        """
155
+        Parses given red_fam_heading string and saves articles list
156
+        """
157
+        
158
+        # Predefine a pattern for wikilinks' destination
159
+        wikilink_pat = re.compile( r"\[\[([^\[\]\|]*)(\]\]|\|)" )
160
+    
161
+        # Parse content of heading for generating section links later
162
+        match = self.__sectionhead_pat.search( heading )
163
+        if match:
164
+            self._heading = match.group(2).lstrip()
165
+        else:
166
+            raise ValueError( "Heading is not valid" )
167
+        
168
+        # We get the pages in first [0] element iterating over wikilink_pat.findall( line )
169
+        self._articlesList = [ link[0] for link in wikilink_pat.findall( self._heading ) ]
170
+        
171
+        # Catch sections with more then 8 articles, print error
172
+        if len( self._articlesList ) > 8:
173
+            pywikibot.output( "{datetime} – \03{{lightred}}[WARNING] – Maximum number of articles in red_fam exceeded, maximum number is 8, {number:d} were given\n{repress}".format( datetime=datetime.now().strftime("%Y-%m-%d %H:%M:%S (%Z)"), number=len( self._articlesList ), repress=repr( self ) ) )
174
+            self._articlesList = self._articlesList[:8]
175
+    
176
+    def fam_hash( self ):
177
+        """
178
+        Calculates the SHA-1 hash for the articlesList of redundance family.
179
+        Since we don't need security SHA-1 is just fine.
180
+        
181
+        @returns    str                    String with the hexadecimal hash digest
182
+        """
183
+        
184
+        h = hashlib.sha1()
185
+        h.update( str( self._articlesList ).encode('utf-8') )
186
+        
187
+        self._fam_hash= h.hexdigest()
188
+
189
+    def add_beginning( self, beginning ):
190
+        """
191
+        Adds the beginning date of a redundance diskussion to the object and sets changed to True
192
+        
193
+        @param      datetime    datetime    Beginning date of redundance diskussion
194
+        """
195
+        
196
+        self._beginning = self.__datetime( beginning )
197
+        
198
+    def add_ending( self, ending ):
199
+        """
200
+        Adds the ending date of a redundance diskussion to the object. Also sets the status to __TODO__ STATUS NUMBER and changed to True
201
+        
202
+        @param      datetime    datetime    Ending date of redundance diskussion
203
+        """
204
+        
205
+        self._ending = self.__datetime( ending )
206
+    
207
+    def __datetime( self, timestamp ):
208
+        """
209
+        Decides wether given timestamp is a parseable string or a datetime object and returns a datetime object in both cases
210
+        
211
+        @param      datetime    timestamp    Datetime object
212
+                    str         timestamp    Parseable string with timestamp in format __timestamp_format
213
+        
214
+        @returns    datetime                 Datetime object
215
+        """
216
+        
217
+        # Make sure locale is set to 'de_DE.UTF-8' to prevent problems with wrong month abreviations in strptime
218
+        locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')
219
+        
220
+        if( isinstance( timestamp, datetime ) ):
221
+            return timestamp
222
+        else:
223
+            result = datetime.strptime( timestamp, type( self ).__timestamp_format )
224
+        return result
225
+            
226
+    def status( self ):
227
+        """
228
+        Handles detection of correct status
229
+        There are three possible stati:
230
+        - 0 Discussion is running --> no ending, page is not an archive
231
+        - 1 Discussion is over --> ending present, page is not an archive
232
+        - 2 Discussion is archived --> ending (normaly) present, page is an archive
233
+        - 3 and greater status was set by worker script, do not change it
234
+        """
235
+        
236
+        # Do not change stati set by worker script etc.
237
+        if not self.__mysql.data['status'] > 2:
238
+            
239
+            # No ending, discussion is running:
240
+            # Sometimes archived discussions also have no detectable ending
241
+            if not self._ending and not self._red_page_archive:
242
+                self._status = 0
243
+            else:
244
+                if not self._red_page_archive:
245
+                    self._status = 1
246
+                else:
247
+                    self._status = 2
248
+        else:
249
+            self._status = self.__mysql.data[ 'status' ]
250
+        
251
+        
252
+                
253
+    def changed( self ):
254
+        """
255
+        Checks wether anything has changed and maybe triggers db update
256
+        """
257
+        
258
+        # On archived red_fams do not delete possibly existing ending
259
+        if not self._ending and self._status > 1 and self.__mysql.data[ 'ending' ]:
260
+            self._ending = self.__mysql.data[ 'ending' ]
261
+             
262
+        
263
+        # Since status change means something has changed, update database
264
+        if( self._status != self.__mysql.data[ 'status' ] or self._beginning !=  self.__mysql.data[ 'beginning' ] or self._ending !=  self.__mysql.data[ 'ending' ] or self._red_page_id != self.__mysql.data[ 'red_page_id' ] or self._heading != self.__mysql.data[ 'heading' ]):
265
+            self.__mysql.update_fam( self._red_page_id, self._heading, self._beginning, self._ending, self._status )
266
+            
267
+    @classmethod
268
+    def is_sectionheading( cls, line ):
269
+        """
270
+        Checks wether given line is a red_fam section heading
271
+        
272
+        @param      str     line    String to check
273
+        
274
+        @returns    bool            Returns True if it is a section heading, otherwise false
275
+        """
276
+        
277
+        if cls.__sectionhead_pat.search( line ):
278
+            return True
279
+        else:
280
+            return False
281
+    
282
+    @classmethod
283
+    def is_beginning( cls, line ):
284
+        """
285
+        Returns the first timestamp found in line, otherwise None
286
+    
287
+        @param      str    line    String to search in
288
+    
289
+        @returns    str            Timestamp, otherwise None
290
+        """
291
+        
292
+        match = cls.__timestamp_pat.search( line )
293
+        if match:
294
+            # Since some timestamps are broken we need to reconstruct them by regex match groups
295
+            result = match.group(1) + ", " + match.group(2) + ". " + match.group(3) + ". " + match.group(4)
296
+            return result
297
+        else:
298
+            return None
299
+        
300
+    @classmethod
301
+    def is_ending( cls, line ):
302
+        """
303
+        Returns the timestamp of done notice ( if one ), otherwise None
304
+        @param        str        line    String to search in
305
+    
306
+        @returns    str                Timestamp, otherwise None
307
+        """
308
+        
309
+        if ( cls.__done_notice in line ) or ( cls.__done_notice2 in line ):
310
+            match = cls.__timestamp_pat.search( line )
311
+            if match:
312
+                # Since some timestamps are broken we need to reconstruct them by regex match groups
313
+                result = match.group(1) + ", " + match.group(2) + ". " + match.group(3) + ". " + match.group(4)
314
+                return result
315
+        return None
316
+    
317
+    @classmethod
318
+    def is_ending2( cls, line ):
319
+        """
320
+        Returns the last timestamp found in line, otherwise None
321
+        @param      str    line    String to search in
322
+    
323
+        @returns    str            Timestamp, otherwise None
324
+        """
325
+        
326
+        matches = cls.__timestamp_pat.findall( line )
327
+        if matches:
328
+            # Since some timestamps are broken we need to reconstruct them by regex match groups
329
+            result = matches[-1][0] + ", " + matches[-1][1] + ". " + matches[-1][2] + ". " + matches[-1][3]
330
+            return result
331
+        else:
332
+            return None 
333
+
334
+class RedFamWorker( RedFam ):
335
+    """
336
+    Handles working with redundance families stored in database where discussion is finished
337
+    """
338
+    pass

+ 170
- 0
redpage.py View File

@@ -0,0 +1,170 @@
1
+#!/usr/bin/env python3
2
+# -*- coding: utf-8  -*-
3
+#
4
+#  redpage.py
5
+#  
6
+#  Copyright 2015 GOLDERWEB – Jonathan Golder <jonathan@golderweb.de>
7
+#  
8
+#  This program is free software; you can redistribute it and/or modify
9
+#  it under the terms of the GNU General Public License as published by
10
+#  the Free Software Foundation; either version 3 of the License, or
11
+#  (at your option) any later version.
12
+#  
13
+#  This program is distributed in the hope that it will be useful,
14
+#  but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
+#  GNU General Public License for more details.
17
+#  
18
+#  You should have received a copy of the GNU General Public License
19
+#  along with this program; if not, write to the Free Software
20
+#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21
+#  MA 02110-1301, USA.
22
+#  
23
+#
24
+"""
25
+Provides a class for handling redundance discussion pages and archives
26
+"""
27
+
28
+import pywikibot
29
+
30
+from mysqlred import MysqlRedPage
31
+from redfam import RedFamParser
32
+
33
+class RedPage:
34
+    """
35
+    Class for handling redundance discussion pages and archives
36
+    """
37
+    
38
+    def __init__( self, page, archive=False ):
39
+        """
40
+        Generate a new RedPage object based on the given pywikibot page object
41
+    
42
+        @param    page    page    Pywikibot/MediaWiki page object for page to work on
43
+        """
44
+        
45
+        # Safe the pywikibot page object
46
+        self.page = page
47
+        self._archive = archive
48
+        
49
+        self.__handle_db( )
50
+
51
+        self.is_page_changed()
52
+        
53
+        self._parsed = None
54
+        if( self._changed or self.__mysql.data[ 'status' ] == 0 ):
55
+            self.parse()
56
+        
57
+        self.__update_db()
58
+    
59
+    def __handle_db( self ):
60
+        """
61
+        Handles opening of db connection
62
+        """
63
+        
64
+        # We need a connection to our mysqldb
65
+        self.__mysql = MysqlRedPage( self.page._pageid )
66
+        
67
+        if not self.__mysql.data:
68
+            self.__mysql.add_page( self.page.title(), self.page._revid )
69
+            
70
+    def is_page_changed( self ):
71
+        """
72
+        Check wether the page was changed since last run
73
+        """
74
+        
75
+        if( self.__mysql.data != { 'page_id': self.page._pageid, 'rev_id': self.page._revid, 'page_title': self.page.title(), 'status': self.__mysql.data[ 'status' ] } ):
76
+            self._changed = True
77
+        else:
78
+            self._changed = False
79
+
80
+    def is_archive( self ):
81
+        """
82
+        Detects wether current page is an archive of discussions
83
+        """
84
+        
85
+        if self._archive or ( u"/Archiv" in self.page.title() ) or ( "{{Archiv}}" in self.page.text ) or ( "{{Archiv|" in self.page.text ):
86
+            return True
87
+        else:
88
+            return False
89
+        
90
+    def parse( self ):
91
+        """
92
+        Handles the parsing process
93
+        """
94
+
95
+        # Since @param text is a string we need to split it in lines
96
+        text_lines = self.page.text.split( "\n" )
97
+        length = len( text_lines )
98
+        
99
+        # Initialise line counter
100
+        i = 0
101
+        fam_heading = None
102
+        beginning = None
103
+        ending = None
104
+    
105
+        # Set line for last detected Redundance-Family to 0
106
+        last_fam = 0
107
+    
108
+        # Iterate over the lines of the page
109
+        for line in text_lines:
110
+            
111
+            # Check wether we have an "Redundance-Family"-Section heading (Level 3)
112
+            if RedFamParser.is_sectionheading( line ):
113
+                
114
+                # Save line number for last detected Redundance-Family
115
+                last_fam = i
116
+                # Save heading
117
+                fam_heading = line
118
+                
119
+                # Defined (re)initialisation of dates
120
+                beginning = None
121
+                ending = None
122
+            
123
+            # Check wether we are currently in an "Redundance-Family"-Section Body
124
+            if i > last_fam and last_fam > 0:
125
+            
126
+                # Check if we have alredy recognized the beginning date of the discussion (in former iteration) or if we have a done-notice
127
+                if not beginning:
128
+                    beginning = RedFamParser.is_beginning( line )
129
+                elif not ending:
130
+                    ending = RedFamParser.is_ending( line )
131
+            
132
+            # Detect end of red_fam section (next line is new sectionheading) or end of file
133
+            # Prevent from running out of index
134
+            if i < (length - 1):
135
+                test = RedFamParser.is_sectionheading( text_lines[ i + 1 ] )
136
+            else:
137
+                test = False
138
+            if ( test or ( length == ( i + 1 ) ) ):
139
+                
140
+                # Create the red_fam object
141
+                if( fam_heading and beginning ):
142
+                    
143
+                    #Maybe we can find a ending by feed if we have None yet (No done notice on archive pages)
144
+                    if not ending and self.is_archive():
145
+                        j = i
146
+                        while (j > last_fam) and not ending:
147
+                            j -= 1
148
+                            ending = RedFamParser.is_ending2( text_lines[ j ] )
149
+                    
150
+                    # Create the RedFam object
151
+                    red_fam = RedFamParser( fam_heading, self.page._pageid, self.is_archive(), beginning, ending )
152
+            
153
+            # Increment line counter
154
+            i += 1
155
+        else:
156
+            self._parsed = True
157
+    
158
+    def __update_db( self ):
159
+        """
160
+        Updates the page meta data in mysql db
161
+        """
162
+        if( self._parsed or not self._changed ):
163
+            status = 1
164
+        
165
+            if( self.is_archive() ):
166
+                status = 2
167
+        else:
168
+            status = 0
169
+            
170
+        self.__mysql.update_page( self.page._revid, self.page.title(), status )