ADDED COPYING Index: COPYING ================================================================== --- /dev/null +++ COPYING @@ -0,0 +1,724 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + 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 +this service 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. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. 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. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +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 +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the 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. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE 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. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. + + +GNU Free Documentation License +****************************** + + Version 1.1, March 2000 + Copyright (C) 2000 Free Software Foundation, Inc. + 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + 0. PREAMBLE + + The purpose of this License is to make a manual, textbook, or other + written document "free" in the sense of freedom: to assure everyone + the effective freedom to copy and redistribute it, with or without + modifying it, either commercially or noncommercially. Secondarily, + this License preserves for the author and publisher a way to get + credit for their work, while not being considered responsible for + modifications made by others. + + This License is a kind of "copyleft", which means that derivative + works of the document must themselves be free in the same sense. + It complements the GNU General Public License, which is a copyleft + license designed for free software. + + We have designed this License in order to use it for manuals for + free software, because free software needs free documentation: a + free program should come with manuals providing the same freedoms + that the software does. But this License is not limited to + software manuals; it can be used for any textual work, regardless + of subject matter or whether it is published as a printed book. + We recommend this License principally for works whose purpose is + instruction or reference. + + 1. APPLICABILITY AND DEFINITIONS + + This License applies to any manual or other work that contains a + notice placed by the copyright holder saying it can be distributed + under the terms of this License. The "Document", below, refers to + any such manual or work. Any member of the public is a licensee, + and is addressed as "you". + + A "Modified Version" of the Document means any work containing the + Document or a portion of it, either copied verbatim, or with + modifications and/or translated into another language. + + A "Secondary Section" is a named appendix or a front-matter + section of the Document that deals exclusively with the + relationship of the publishers or authors of the Document to the + Document's overall subject (or to related matters) and contains + nothing that could fall directly within that overall subject. + (For example, if the Document is in part a textbook of + mathematics, a Secondary Section may not explain any mathematics.) + The relationship could be a matter of historical connection with + the subject or with related matters, or of legal, commercial, + philosophical, ethical or political position regarding them. + + The "Invariant Sections" are certain Secondary Sections whose + titles are designated, as being those of Invariant Sections, in + the notice that says that the Document is released under this + License. + + The "Cover Texts" are certain short passages of text that are + listed, as Front-Cover Texts or Back-Cover Texts, in the notice + that says that the Document is released under this License. + + A "Transparent" copy of the Document means a machine-readable copy, + represented in a format whose specification is available to the + general public, whose contents can be viewed and edited directly + and straightforwardly with generic text editors or (for images + composed of pixels) generic paint programs or (for drawings) some + widely available drawing editor, and that is suitable for input to + text formatters or for automatic translation to a variety of + formats suitable for input to text formatters. A copy made in an + otherwise Transparent file format whose markup has been designed + to thwart or discourage subsequent modification by readers is not + Transparent. A copy that is not "Transparent" is called "Opaque". + + Examples of suitable formats for Transparent copies include plain + ASCII without markup, Texinfo input format, LaTeX input format, + SGML or XML using a publicly available DTD, and + standard-conforming simple HTML designed for human modification. + Opaque formats include PostScript, PDF, proprietary formats that + can be read and edited only by proprietary word processors, SGML + or XML for which the DTD and/or processing tools are not generally + available, and the machine-generated HTML produced by some word + processors for output purposes only. + + The "Title Page" means, for a printed book, the title page itself, + plus such following pages as are needed to hold, legibly, the + material this License requires to appear in the title page. For + works in formats which do not have any title page as such, "Title + Page" means the text near the most prominent appearance of the + work's title, preceding the beginning of the body of the text. + + 2. VERBATIM COPYING + + You may copy and distribute the Document in any medium, either + commercially or noncommercially, provided that this License, the + copyright notices, and the license notice saying this License + applies to the Document are reproduced in all copies, and that you + add no other conditions whatsoever to those of this License. You + may not use technical measures to obstruct or control the reading + or further copying of the copies you make or distribute. However, + you may accept compensation in exchange for copies. If you + distribute a large enough number of copies you must also follow + the conditions in section 3. + + You may also lend copies, under the same conditions stated above, + and you may publicly display copies. + + 3. COPYING IN QUANTITY + + If you publish printed copies of the Document numbering more than + 100, and the Document's license notice requires Cover Texts, you + must enclose the copies in covers that carry, clearly and legibly, + all these Cover Texts: Front-Cover Texts on the front cover, and + Back-Cover Texts on the back cover. Both covers must also clearly + and legibly identify you as the publisher of these copies. The + front cover must present the full title with all words of the + title equally prominent and visible. You may add other material + on the covers in addition. Copying with changes limited to the + covers, as long as they preserve the title of the Document and + satisfy these conditions, can be treated as verbatim copying in + other respects. + + If the required texts for either cover are too voluminous to fit + legibly, you should put the first ones listed (as many as fit + reasonably) on the actual cover, and continue the rest onto + adjacent pages. + + If you publish or distribute Opaque copies of the Document + numbering more than 100, you must either include a + machine-readable Transparent copy along with each Opaque copy, or + state in or with each Opaque copy a publicly-accessible + computer-network location containing a complete Transparent copy + of the Document, free of added material, which the general + network-using public has access to download anonymously at no + charge using public-standard network protocols. If you use the + latter option, you must take reasonably prudent steps, when you + begin distribution of Opaque copies in quantity, to ensure that + this Transparent copy will remain thus accessible at the stated + location until at least one year after the last time you + distribute an Opaque copy (directly or through your agents or + retailers) of that edition to the public. + + It is requested, but not required, that you contact the authors of + the Document well before redistributing any large number of + copies, to give them a chance to provide you with an updated + version of the Document. + + 4. MODIFICATIONS + + You may copy and distribute a Modified Version of the Document + under the conditions of sections 2 and 3 above, provided that you + release the Modified Version under precisely this License, with + the Modified Version filling the role of the Document, thus + licensing distribution and modification of the Modified Version to + whoever possesses a copy of it. In addition, you must do these + things in the Modified Version: + + A. Use in the Title Page (and on the covers, if any) a title + distinct from that of the Document, and from those of + previous versions (which should, if there were any, be listed + in the History section of the Document). You may use the + same title as a previous version if the original publisher of + that version gives permission. + + B. List on the Title Page, as authors, one or more persons or + entities responsible for authorship of the modifications in + the Modified Version, together with at least five of the + principal authors of the Document (all of its principal + authors, if it has less than five). + + C. State on the Title page the name of the publisher of the + Modified Version, as the publisher. + + D. Preserve all the copyright notices of the Document. + + E. Add an appropriate copyright notice for your modifications + adjacent to the other copyright notices. + + F. Include, immediately after the copyright notices, a license + notice giving the public permission to use the Modified + Version under the terms of this License, in the form shown in + the Addendum below. + + G. Preserve in that license notice the full lists of Invariant + Sections and required Cover Texts given in the Document's + license notice. + + H. Include an unaltered copy of this License. + + I. Preserve the section entitled "History", and its title, and + add to it an item stating at least the title, year, new + authors, and publisher of the Modified Version as given on + the Title Page. If there is no section entitled "History" in + the Document, create one stating the title, year, authors, + and publisher of the Document as given on its Title Page, + then add an item describing the Modified Version as stated in + the previous sentence. + + J. Preserve the network location, if any, given in the Document + for public access to a Transparent copy of the Document, and + likewise the network locations given in the Document for + previous versions it was based on. These may be placed in + the "History" section. You may omit a network location for a + work that was published at least four years before the + Document itself, or if the original publisher of the version + it refers to gives permission. + + K. In any section entitled "Acknowledgments" or "Dedications", + preserve the section's title, and preserve in the section all + the substance and tone of each of the contributor + acknowledgments and/or dedications given therein. + + L. Preserve all the Invariant Sections of the Document, + unaltered in their text and in their titles. Section numbers + or the equivalent are not considered part of the section + titles. + + M. Delete any section entitled "Endorsements". Such a section + may not be included in the Modified Version. + + N. Do not retitle any existing section as "Endorsements" or to + conflict in title with any Invariant Section. + + If the Modified Version includes new front-matter sections or + appendices that qualify as Secondary Sections and contain no + material copied from the Document, you may at your option + designate some or all of these sections as invariant. To do this, + add their titles to the list of Invariant Sections in the Modified + Version's license notice. These titles must be distinct from any + other section titles. + + You may add a section entitled "Endorsements", provided it contains + nothing but endorsements of your Modified Version by various + parties--for example, statements of peer review or that the text + has been approved by an organization as the authoritative + definition of a standard. + + You may add a passage of up to five words as a Front-Cover Text, + and a passage of up to 25 words as a Back-Cover Text, to the end + of the list of Cover Texts in the Modified Version. Only one + passage of Front-Cover Text and one of Back-Cover Text may be + added by (or through arrangements made by) any one entity. If the + Document already includes a cover text for the same cover, + previously added by you or by arrangement made by the same entity + you are acting on behalf of, you may not add another; but you may + replace the old one, on explicit permission from the previous + publisher that added the old one. + + The author(s) and publisher(s) of the Document do not by this + License give permission to use their names for publicity for or to + assert or imply endorsement of any Modified Version. + + 5. COMBINING DOCUMENTS + + You may combine the Document with other documents released under + this License, under the terms defined in section 4 above for + modified versions, provided that you include in the combination + all of the Invariant Sections of all of the original documents, + unmodified, and list them all as Invariant Sections of your + combined work in its license notice. + + The combined work need only contain one copy of this License, and + multiple identical Invariant Sections may be replaced with a single + copy. If there are multiple Invariant Sections with the same name + but different contents, make the title of each such section unique + by adding at the end of it, in parentheses, the name of the + original author or publisher of that section if known, or else a + unique number. Make the same adjustment to the section titles in + the list of Invariant Sections in the license notice of the + combined work. + + In the combination, you must combine any sections entitled + "History" in the various original documents, forming one section + entitled "History"; likewise combine any sections entitled + "Acknowledgments", and any sections entitled "Dedications". You + must delete all sections entitled "Endorsements." + + 6. COLLECTIONS OF DOCUMENTS + + You may make a collection consisting of the Document and other + documents released under this License, and replace the individual + copies of this License in the various documents with a single copy + that is included in the collection, provided that you follow the + rules of this License for verbatim copying of each of the + documents in all other respects. + + You may extract a single document from such a collection, and + distribute it individually under this License, provided you insert + a copy of this License into the extracted document, and follow + this License in all other respects regarding verbatim copying of + that document. + + 7. AGGREGATION WITH INDEPENDENT WORKS + + A compilation of the Document or its derivatives with other + separate and independent documents or works, in or on a volume of + a storage or distribution medium, does not as a whole count as a + Modified Version of the Document, provided no compilation + copyright is claimed for the compilation. Such a compilation is + called an "aggregate", and this License does not apply to the + other self-contained works thus compiled with the Document, on + account of their being thus compiled, if they are not themselves + derivative works of the Document. + + If the Cover Text requirement of section 3 is applicable to these + copies of the Document, then if the Document is less than one + quarter of the entire aggregate, the Document's Cover Texts may be + placed on covers that surround only the Document within the + aggregate. Otherwise they must appear on covers around the whole + aggregate. + + 8. TRANSLATION + + Translation is considered a kind of modification, so you may + distribute translations of the Document under the terms of section + 4. Replacing Invariant Sections with translations requires special + permission from their copyright holders, but you may include + translations of some or all Invariant Sections in addition to the + original versions of these Invariant Sections. You may include a + translation of this License provided that you also include the + original English version of this License. In case of a + disagreement between the translation and the original English + version of this License, the original English version will prevail. + + 9. TERMINATION + + You may not copy, modify, sublicense, or distribute the Document + except as expressly provided for under this License. Any other + attempt to copy, modify, sublicense or distribute the Document is + void, and will automatically terminate your rights under this + License. However, parties who have received copies, or rights, + from you under this License will not have their licenses + terminated so long as such parties remain in full compliance. + + 10. FUTURE REVISIONS OF THIS LICENSE + + The Free Software Foundation may publish new, revised versions of + the GNU Free Documentation 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. See + `http://www.gnu.org/copyleft/'. + + Each version of the License is given a distinguishing version + number. If the Document specifies that a particular numbered + version of this License "or any later version" applies to it, you + have the option of following the terms and conditions either of + that specified version or of any later version that has been + published (not as a draft) by the Free Software Foundation. If + the Document does not specify a version number of this License, + you may choose any version ever published (not as a draft) by the + Free Software Foundation. + +ADDENDUM: How to use this License for your documents +---------------------------------------------------- + + To use this License in a document you have written, include a copy of +the License in the document and put the following copyright and license +notices just after the title page: + + Copyright (C) YEAR YOUR NAME. + Permission is granted to copy, distribute and/or modify this document + under the terms of the GNU Free Documentation License, Version 1.1 + or any later version published by the Free Software Foundation; + with the Invariant Sections being LIST THEIR TITLES, with the + Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST. + A copy of the license is included in the section entitled ``GNU + Free Documentation License''. + + If you have no Invariant Sections, write "with no Invariant Sections" +instead of saying which ones are invariant. If you have no Front-Cover +Texts, write "no Front-Cover Texts" instead of "Front-Cover Texts being +LIST"; likewise for Back-Cover Texts. + + If your document contains nontrivial examples of program code, we +recommend releasing these examples in parallel under your choice of +free software license, such as the GNU General Public License, to +permit their use in free software. + ADDED INSTALL Index: INSTALL ================================================================== --- /dev/null +++ INSTALL @@ -0,0 +1,12 @@ +These are rough installation instructions. Please contact me at matt@kiatoa.com +if you have trouble installing. + +1. Copy install.cfg.template to install.cfg and modify appropriately + +2. Copy stml.config.template to your cgi dir as .stml.config and modify appropriately + - choose your db + +3. Copy requirements.scm.template to requirements.scm and modify as needed + - choose your db (must match what you choose in 2. above) + + ADDED Makefile Index: Makefile ================================================================== --- /dev/null +++ Makefile @@ -0,0 +1,68 @@ +# Copyright 2007-2008, Matthew Welland. +# +# This program is made available under the GNU GPL version 2.0 or +# greater. See the accompanying file COPYING for details. +# +# This program is distributed WITHOUT ANY WARRANTY; without even the +# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +# PURPOSE. + +include install.cfg + +MODULEFILES = $(wildcard modules/*/*-mod.scm) +SOFILES = $(MODULEFILES:%.scm=%.so) +CFILES = $(MODULEFILES:%.scm=%.c) +OFILES = $(MODULEFILES:%.scm=%.o) +TARGFILES = $(notdir $(SOFILES)) +MODULES = $(addprefix $(TARGDIR)/modules/,$(TARGFILES)) + +install : $(TARGDIR)/stmlrun $(LOGDIR) $(MODULES) + +stmlrun : stmlrun.scm formdat.scm misc-stml.scm session.scm stml.scm \ + setup.scm html-filter.scm requirements.scm keystore.scm \ + sugar.scm + csc stmlrun.scm + + +$(TARGDIR)/stmlrun : stmlrun + cp stmlrun $(TARGDIR) + chmod a+rx $(TARGDIR)/stmlrun + +$(TARGDIR)/modules : + mkdir -p $(TARGDIR)/modules + +$(MODULES) : $(SOFILES) $(TARGDIR)/modules + cp $< $@ + +# logging currently relies on this +# +$(LOGDIR) : + mkdir -p $(LOGDIR) + chmod a+rwx $(LOGDIR) + +test: kiatoa.db + echo '(exit)'| csi -q ./tests/test.scm + +# modules +# +%.so : %.scm + csc -I modules/* -s $< + +all : $(SOFILES) + +dbi.so : dbi.scm + csc -i dbi.scm + +installdbi : dbi.so + cp dbi.so /usr/local/lib/chicken/3/ +# +# $(CFILES): build/%.c: ../scm/%.scm ../scm/macros.scm +# chicken $< -output-file $@ +# +# +# $(OFILES): src/%.o: src/%.c +# gcc -c $< `chicken-config -cflags` -o $@ +# +# $(src_code): %: src/%.o src/laedlib.o src/layobj.o +# gcc src/$*.o src/laedlib.o src/layobj.o -o $* `chicken-config -libs` +# ADDED README Index: README ================================================================== --- /dev/null +++ README @@ -0,0 +1,1 @@ +This is the stml, scheme based cgi application framework. ADDED TODO Index: TODO ================================================================== --- /dev/null +++ TODO @@ -0,0 +1,22 @@ +1. Documentation. + multiple apps in same cgi dir + compilation of models for speed and code protection + tricks +2. Hierarchial pages. Currently pages can be hierarchial but the control.scm + doesn't get called at the right time. +3. For sqlite3 usage put session into own db? +4. A mechanism for sharing variables better between control and view + would be good. + Perhaps: + (let () + (load control) + (load view)) +5. Change all the "included" files to be seperately compiled units + and adj. makefile accordingly. This would speed up compilation + when changes are isolated to one or two files. +6. The dbi interface needs a simple config mecanism alternative to + the current list of pairs which is hard to use on the fly. + Something like the perl: + "dbi:host:port:user:password" + +I'm sure there is more ... ADDED doc/howto.txt Index: doc/howto.txt ================================================================== --- /dev/null +++ doc/howto.txt @@ -0,0 +1,100 @@ +====================================================================== +1. Create a link. + +(s:null "[" (s:a name 'href + (s:link-to (string-append "location/" (string-intersperse p "/") ""))) "] "))) + +====================================================================== +2. Call current page with new param + +In view.scm: + + (s:center "[" (s:a 'href (s:link-to "polls" + 'id + (begin + (poll:poll 'fill-polls) + (poll:poll 'get-next-poll))) + "Go to the next poll") "]") + +In control.scm: + +(let ((poll-id (s:get-param 'id))) + ;; do stuff based on poll-id + +====================================================================== +3. Call an action on a specific page + + (s:a 'href (s:link-to "polls" 'id (poll:poll 'get 'id) + 'action "poll.edit") + "Suggest changes to this poll") + + NOT TRUE! This calls fuction poll.edit (should be in control.scm). Parameter set is 'id to a poll num. + +====================================================================== +4. A complex link example + +(s:a "Reply" 'href (s:link-to (s:current-page) + 'action "discussion.reply" ;; . + 'reply_to (number->string (hash-table-ref row 'posts.id)) + 'id (s:get "discussion.parent_object_id")) "reply") + +;; use (s:get-param to get the 'id, or 'reply_to values + +====================================================================== +5. Get and set a session var + +(s:session-var-get "keyname") +(s:session-var-set! "keyname" "value") + +5.1 Page local vars + +(s:set! key val) +(s:get key) + +====================================================================== +6. make a selection drop down + +In view.scm: + +(s:select '(("World" 0)("Country" 1)("State" 2)("Town/City" 3)) 'name 'scope) + +In control.scm: + +(let ((scope (s:get-input 'scope))) + .... + +====================================================================== +7. Simple error reporting + +In control.scm: +(s:set-err "You must provide an email address") + +In view.scm: +(s:get-err s:err-font) + +Or: +(s:get-err (lambda (x)(s:err-font x (s:br)))) + +====================================================================== +8. Misc useful stuff + + i. Lazy/safe string->number + +(s:any->number val) + + ii. Random string + +(session:make-rand-string len) + +====================================================================== +9. Forms and input + +(s:form 'action "login.login" 'method "post" + (s:input-preserve 'type "text" 'name "email-address" 'size "16" 'maxlength "30") + (s:input 'type "submit" 'name "form-name" 'value "login")) + +(s:get-input 'email-address) + +====================================================================== +10. + ADDED doc/stml-manual.odt Index: doc/stml-manual.odt ================================================================== --- /dev/null +++ doc/stml-manual.odt cannot compute difference between binary files ADDED example/Makefile Index: example/Makefile ================================================================== --- /dev/null +++ example/Makefile @@ -0,0 +1,26 @@ +# Copyright 2007-2008, Matthew Welland. +# +# This program is made available under the GNU GPL version 2.0 or +# greater. See the accompanying file COPYING for details. +# +# This program is distributed WITHOUT ANY WARRANTY; without even the +# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +# PURPOSE. + +# Uncomment and fix path if you want your models to be compiled +# +MODELS := $(wildcard models/*scm) +SOFILES := $(patsubst %.scm,%.so,$(MODELS)) + + +# all : $(SOFILES) + +# If you want compiled models uncomment the following +# +# $(SOFILES) : %.so: %.scm +# csc -s $< + +test: # $(SOFILES) + echo '(exit)'| csi -q ./tests/test.scm + +# cgi-util proplist cgi-util cookie ADDED example/POLICY Index: example/POLICY ================================================================== --- /dev/null +++ example/POLICY ADDED example/README Index: example/README ================================================================== --- /dev/null +++ example/README @@ -0,0 +1,3 @@ +This is an (unfinished) example application. + +To see it live go to: www.approvalvote.org ADDED example/TODO Index: example/TODO ================================================================== --- /dev/null +++ example/TODO @@ -0,0 +1,2 @@ + + ADDED example/db/db-tweaks.sql Index: example/db/db-tweaks.sql ================================================================== --- /dev/null +++ example/db/db-tweaks.sql @@ -0,0 +1,172 @@ +>-- create table polls(id serial not null,poll_type text,title text,description text,poll_state text); +-- create table poll_categories(id serial not null,poll_id integer,description text); +-- create table poll_votes(id serial not null,period integer,poll_type text,poll_category text,voter_group integer, votes integer); + +-- create table vote_items (id serial primary key,type integer,item_id integer,item_level text,town_votes integer,state_votes integer,country_votes integer,world_votes integer); +-- +-- alter table vote_items alter column town_votes set default 0; +-- alter table vote_items alter column state_votes set default 0; +-- alter table vote_items alter column country_votes set default 0; +-- alter table vote_items alter column world_votes set default 0; +-- +-- alter table poll_items add column class_0 int4; +-- alter table poll_items add column class_1 int4; +-- alter table poll_items add column class_2 int4; +-- +-- alter table poll_items add column classp_0 int4; +-- alter table poll_items add column classp_1 int4; +-- alter table poll_items add column classp_2 int4; +-- +-- alter table poll_items alter column classp_0 set default 0; +-- alter table poll_items alter column classp_1 set default 0; +-- alter table poll_items alter column classp_2 set default 0; +-- +-- alter table poll_items add column suggestor int4; +-- +-- alter table poll_items alter column class_0 set default 0; +-- alter table poll_items alter column class_1 set default 0; +-- alter table poll_items alter column class_2 set default 0; +-- +-- alter table poll_items add column status int4; +-- alter table poll_items alter column status set default 0; + +-- alter table poll_items add column url text; +-- alter table vote_items add column submit_date date; +-- alter table poll_items add column submit_date date; + +-- alter table people add column pt_balance int4; +-- alter table people alter column pt_balance set default 0; + +-- alter table people add column cert_date date; +-- alter table people alter column pt_balance set default 0; + +-- create table pt_transactions (id serial not null,from_id integer,to_id integer,amount integer,transaction_time timestamp); +-- alter table pt_transactions alter column amount set default 0; + +-- alter table classifieds add column points int4; +-- alter table classifieds alter column points set default 0; + +-- alter table pt_transactions add column comment text; +-- alter table pt_transactions add column comment text; + +-- create table temp_key(id serial not null,key text,sent_date date); +-- alter table people add column lastlogin timestamp; + +-- create table pictures(id serial not null,owner integer,size integer,name text,type text,md5sum text,uploaded date); +-- alter table pictures add column status text; + +-- create table pic_allocation(id serial not null,picnum integer,used_by integer); + +-- alter table posts add column url text; +-- alter table posts add column blurb text; + +insert into subjects (subjectid,subject,item_type,description) values('VoSp','Spanish','lang','Basic Spanish Vocabulary'); +insert into subjects (subjectid,subject,item_type,description) values('HoMe','Homeopathy','Info','Basic Homeopathy'); + +alter table items add column group_name text; +alter table items add column state int4; + +create table sessions (id serial not null,session_key text); +create table session_vars (id serial not null,session_id integer,page text,key text,value text); + +alter table poll_items add column num_voted integer default 0; +alter table poll_items add column vote_tot integer default 0; +alter table poll_items add column item_votes integer default 0; + +-- remember ballots are used for many things other than polls!!!!!!!! +create table ballots (id serial not null, item_id integer, class_id integer, votes integer, type_id integer); +create table ballot_classes (id serial not null, name text, pts_per_vote integer); -- join with ballots to sum up votes (pts are really votes) +insert into ballot_classes values (0,'',1); +insert into ballot_classes values (1,'',2); +insert into ballot_classes values (2,'',10); +insert into ballot_classes values (3,'',20); +insert into ballot_classes values (4,'',45); +insert into ballot_classes values (5,'',90); +insert into ballot_classes values (6,'',105); +insert into ballot_classes values (7,'',145); +insert into ballot_classes values (8,'',205); +insert into ballot_classes values (9,'',245); + +create table ballot_types (id serial not null, name text); -- poll plurality = 0, poll approval = 1 +insert into ballot_types (id,name) values (0,'poll plurality'); +insert into ballot_types (id,name) values (1,'poll approval'); + +alter table voted add column type_id integer; +alter table voted add column id serial not null; +create table voted_types (id serial not null, name text); +insert into voted_types (id, name) values (0, 'poll vote'); -- YES!!! WE DO NEED voted_types SEPERATE FROM ballot_types +insert into voted_types (id, name) values (1, 'council vote for poll'); -- yes, they are similar but I think combining them would be +insert into voted_types (id, name) values (2, 'council vote for item'); -- painful. +insert into voted_types (id, name) values (3, 'council vote for story'); + +alter table people add column email_validated integer default 0; -- has email been validated? Hmmm... should this be a seperate table +alter table people add column grade integer default 0; -- + +alter table voted add column grade integer default 0; + +-- grade +-- +-- 0 - no status (refusing cookies) +-- 1 - has session +-- 2 - logged in, has user id +-- 3 - email validated +-- 4 ++ add 1 for every 20 points of cert_level + +alter table poll_items drop column class_0 ; +alter table poll_items drop column class_1 ; +alter table poll_items drop column class_2 ; +alter table poll_items drop column classp_0 ; +alter table poll_items drop column classp_1 ; +alter table poll_items drop column classp_2 ; +alter table poll_items drop column votes ; +alter table poll_items drop column vote_tot ; +alter table poll_items drop column num_voted; + +alter table poll_items add column a_vote_tot integer default 0; -- approval votes total +alter table poll_items add column p_vote_tot integer default 0; -- plurality votes total + +alter table people alter column num set default 0; +alter table polls add column discussion_id integer default 0; + +create table poll_status (id serial not null, name text); +insert into poll_status (id,name) values (0, 'In queue'); -- just posted and in queue +insert into poll_status (id,name) values (1, 'Posted'); -- published to discussion + +-- fix default cert_level +alter table people alter column cert_level set default 0; +update people set cert_level=0 where cert_level is NULL; + +create table discussions (id serial not null,type_id integer,activity_state integer); +update posts set thread=id where parent=0; -- was this necessary? + +insert into discussions select id,0,1 from posts where parent=0; + +-- ====================================================================== +-- New council stuff +--====================================================================== + +create table councils (id serial not null, name text, discussion_id integer default 0); +alter table council_members add column join_date date; + +-- DONE ON TANG UP TO HERE + +--====================================================================== +-- New locations table +--====================================================================== + +create table locations + (id serial not null, parent_id integer default 0, + council_id integer,nick text, fullname text, + level_id integer, blurb text, pict_id integer); +insert into locations(council_id,nick,fullname,level_id,blurb) + values(0,'','World',0,'Our beloved Planet Earth'); +insert into locations(council_id,nick,fullname,level_id,blurb) + values(1,'us','United States',1,'The Land of the Free'); +insert into locations(parent_id,council_id,nick,fullname,level_id,blurb) + values(1,2,'az','Arizona',2,'It''s a dry heat'); + +drop table location; +drop table towns; +drop table states; +drop table neighborhoods ; +drop table countries; ADDED example/db/dump_db Index: example/db/dump_db ================================================================== --- /dev/null +++ example/db/dump_db @@ -0,0 +1,1 @@ +pg_dump -d kiatoa | grep -v 'INSERT INTO session_vars' | grep -v 'INSERT INTO sessions' > Kiatoa.sql ADDED example/docs/Setup-notes.txt Index: example/docs/Setup-notes.txt ================================================================== --- /dev/null +++ example/docs/Setup-notes.txt @@ -0,0 +1,15 @@ +1) add: + +host all all 192.168.1.1/32 password + +to the bottom of /etc/postgresql/8.2/main/pg_hba.conf + +2) + +ln -s /home/matt/kiatoa/kiatoa-scm/kiatoa /var/www + +3) copy/update the stml.conf file + +sudo cp stml.conf.template /usr/lib/cgi-bin/.stml.conf +sudo vi /usr/lib/cgi-bin/.stml.conf + ADDED example/docs/comments.txt Index: example/docs/comments.txt ================================================================== --- /dev/null +++ example/docs/comments.txt @@ -0,0 +1,20 @@ + +If we had any at all of the alternative voting ideas like instant runoff, Condorcet, any of them, I think it might make the whole process better + +My thought was to get people familiar with approval voting, then get people to pledge only to vote for a candidate if that candidate supported approval voting. I put the beginings of a site together here: http://approvalvote.org but stopped working on it because I decided not to push the idea for this election. Morally, in my opinion, letting the neocons in for another term is unacceptable, I suspect (but don't know) that McCain is a participant of the neocon movement. Since these elections can hinge on a few hundreds of votes I thought it wasn't worth even the infintesimal risk of any activity that would get people thinking about the alternatives to the top two pulling votes away from Obama. I did think of pushing the idea in venues dominated by interest in Ron Paul but there was some beer in the fridge and, well, you can guess the rest of that story. + +Although the current implementation needs major rework I do think the idea has potential. + + 1. Get people to experience plurality vs approval voting. IMHO once you've tried it going back to plurality is actually quite uncomfortable. + 2. Get people to pledge to vote only for candidates that support approval voting. + 3. Get candidates to address approval voting. + +Now why approval and not Condorcet, range, IRV or any one of the dozens of other voting techniques? + + 1. Approval is 100% doable using existing election machines + 2. Approval is highly resistant to any meaningful strategic voting. + 3. Approval is easy for the end users. Go try doing some condorcet or IRV ranked voting. It is really tedious. + 4. IRV is *worse* than Plurality in its vunerablity to strategic voting. + 5. Condorcet is too hard to grok for most folks. I knew once how it worked but couldn't explain it to someone right now for the life of me. + +In short the marginal improvement of the more complex voting solutions over approval doesn't buy much. ADDED example/example/layout.css Index: example/example/layout.css ================================================================== --- /dev/null +++ example/example/layout.css @@ -0,0 +1,244 @@ + +/*-General-----------------------------------------------*/ + +html, body { + margin:0px; + padding:0px; +} + +form { + display:inline; + margin:0px; + padding:0px; +} + +a img { + border:none; + margin:0px; + padding:0px; +} + +h1, h2, h3, h4, h5, h6, p, div { + margin:0px; + padding:0px; +} + +.right { + float:right; +} + +.left{ + float:left; +} + +/*-Main Layout-------------------------------------------*/ + +#overall { + margin:5px 12px 0px 12px; + padding:0px; +} + +/*-Header-------------*/ + +.header { + position:relative; + height:90px; +} + +/*-Footer-------------*/ + +.footer { + padding:40px 0px 0px 0px; + position:relative; + clear:both; +} + +/*-Content Area-------*/ + +.content { + width:100%; +} + +/*-Left Column--------*/ + +.leftcolumn { + float:left; + width:145px; + margin:5px; +} + +.leftcolumn .node { + margin:0px 0px 15px 0px; +} + +.leftcolumn .node h1 { + padding:0px 0px 0px 3px; +} + +.leftcolumn .node ul { + margin:0px; + padding:0px; +} + +.leftcolumn .node li { + display:block; + padding:0px 0px 0px 3px; + margin:0px; +} + +.leftcolumn .node li.more{ + padding:0px 0px 0px 6px; +} + +/*-Center Column------*/ + +.centercolumn { + margin: 5px; + margin-left:152px; + margin-right:200px; + font-family:"\"}\""; + font-family:inherit; +} + +.centercolumn .node h1 { + padding: 0px 0px 0px 13px; +} + +.centercolumn .node h4 { + margin: 15px 0px 10px 0px; +} + +.centercolumn .node p { + margin: 0px 0px 10px 0px; */ + padding: 0px 0px 0px 0px; +} /* this seemed not to work */ + +.posts_0 { + margin: 0px 0px 0px 0px; +} + +.posts_1 { + margin: 0px 0px 0px 20px; +} + +.posts_2 { + margin: 0px 0px 0px 40px; +} + +.posts_3 { + margin: 0px 0px 0px 60px; +} + +.posts_4 { + margin: 0px 0px 0px 80px; +} + +.posts_5 { + margin: 0px 0px 0px 100px; +} + +.posts_6 { + margin: 0px 0px 0px 120px; +} + +.posts_7 { + margin: 0px 0px 0px 140px; +} + +.posts_8 { + margin: 0px 0px 0px 160px; +} + +.posts_9 { + margin: 0px 0px 0px 160px; +} + +.posts_10 { + margin: 0px 0px 0px 180px; +} + +/*-Right Column-------*/ + +.rightcolumn { + float:right; + width:190px; + margin:5px 5px 0px 0px; +} + +* html .rightcolumn { + margin:3px 3px 3px 3px; +} + +body>div .rightcolumn { + margin:0px 0px 0px 0px; +} + +.rightcolumn .node { + margin:0px 0px 5px 0px; + padding:0px; +} + +.rightcolumn .node h2 { + margin:3px 3px 3px 2px; +} + +.rightcolumn .node ul { + list-style-position:inside; + margin:0px; + padding:1px; +} + +.rightcolumn .node ul.none { + list-style-position:inside; +} + +.rightcolumn .node ul.dot { + list-style-position:inside; +} + +.rightcolumn .node ul.books { + list-style-position:outside; + margin:0px 0px 0px 35px; +} + +.rightcolumn .node li { + padding:0px 0px 0px 3px; + margin:0px; +} + +/*-Remaining layout--------------------------------------*/ + +#title { + top: 0px; + left: 0px; + position: absolute; +} + +#search { + float:left; + margin:0px 0px 0px 30px; +} + +#randomquote { + float:right; + margin:0px 30px 0px 0px; +} + +#copyright { + text-align:center; + padding:15px 0px 0px 0px; + margin:0px 0px 0px 0px; + clear:both; +} + +#bottomNav { + text-align:center; + margin:0px 0px 20px 0px; + padding:0px; +} + +#oldStuffNav { + font-weight:bold; + text-align:right; +} + ADDED example/example/markup.css Index: example/example/markup.css ================================================================== --- /dev/null +++ example/example/markup.css @@ -0,0 +1,299 @@ +/*-General-----------------------------------------------*/ + +body { + background-color:#ffffff; + color:#0f0f0f; + font-family:serif; + font-weight:normal; + text-decoration:none; +/* font-size:x-small; */ + voice-family:"\"}\""; + voice-family:inherit; + font-size:small; +} + +html>body { + font-size:small; +} + +.strong { + font-weight:bold; +} + +#red { + color: #ff0000 +} + +/*-Main Markup-------------------------------------------*/ + +#overall { + background-color: #ffffff; + color:#000000; +} + +/*-Left Column--------*/ + +.leftcolumn .node a { + color:#006666; + background-color:transparent; +} + +.leftcolumn .node p { + font-size:1.2em; + font-weight:normal; +} + +.leftcolumn .node h1 { + font-weight:normal; + font-size:1.2em; + color:#ffffff; + background-color:#000000; /* #005991; #7f9bff #006666; */ +} + +.leftcolumn .node h1 a { + color:#ffffff; + background-color:transparent; +} + +.leftcolumn .node h2 { + font-weight:bold; + font-size:.95em; +} + +.leftcolumn .node ul { + list-style-type:none; +} + +.leftcolumn .node li.more { + font-weight:bold; + font-size:.75em; +} + +.leftcolumn .node li.selected { + font-weight:bold; + font-size:1.18em; + color:#000000; + background-color:#cccccc; +} + +.leftcolumn .node li.selected a { + color:#000000; + background-color:transparent; +} + +/*-Center Column for classifieds-*/ + +.centercolumn .classifieds h1 { + font-family:Arial, Helvetica, serif; + font-weight:bold; + font-size:1.38em; + color:#000000; /* ffffff; */ + background: #5390b7; /* a6bcac; #0c1e0f; 043b0d; 1a6126; */ +} + +/*-Center Column------*/ +.centercolumn .node { + font-family:serif; +} + +.centercolumn .node a { + color:#006666; + background-color:transparent; +} + +.centercolumn .node h1 { + font-family:Arial, Helvetica, serif; + font-weight:bold; + font-size:1.38em; + color:#ffffff; + background:#000000; /* #005991; */ +} /* #006666 /* url('../images/slc.gif') no-repeat; */ + +.centercolumn .node h1 a { + color:#ffffff; + background-color:transparent; +} + +.centercolumn .node h2 { + font-weight:bold; + font-size:1.18em; +} + +.centercolumn .node h3 { + font-weight:bold; + font-size:.95em; +} + +.centercolumn .node h4 { + font-weight:normal; + font-size:1.2em; +} + +.centercolumn .node h4 a { + font-weight:bold; +} + +.centercolumn .node p { + font-weight:normal; +} + +.centercolumn .posts_0 h1 { + color:#ffffff; + background-color:#606060; + font-size:1.18em; +} + +.centercolumn .posts_1 h1 { + color:#ffffff; + background-color:#606060; + font-size:1.18em; +} + +.centercolumn .posts_2 h1 { + color:#ffffff; + background-color:#606060; + font-size:1.18em; +} + +.centercolumn .posts_3 h1 { + color:#ffffff; + background-color:#606060; + font-size:1.18em; +} + +.centercolumn .posts_4 h1 { + color:#ffffff; + background-color:#606060; + font-size:1.18em; +} + +.centercolumn .posts_5 h1 { + color:#ffffff; + background-color:#606060; + font-size:1.18em; +} + +.centercolumn .posts_6 h1 { + color:#ffffff; + background-color:#606060; + font-size:1.18em; +} + +.centercolumn .posts_7 h1 { + color:#ffffff; + background-color:#606060; + font-size:1.18em; +} + +.centercolumn .posts_8 h1 { + color:#ffffff; + background-color:#606060; + font-size:1.18em; +} + +.centercolumn .posts_9 h1 { + color:#ffffff; + background-color:#606060; + font-size:1.18em; +} + +.centercolumn .posts_10 h1 { + color:#ffffff; + background-color:#606060; + font-size:1.18em; +} + +/*-Right Column-------*/ + +.rightcolumn .node { + color:#000000; + background-color:#cccccc; + font-family:serif; +} + +.rightcolumn .node a { + color:#000000; /* #005991; #006666; */ + background-color:transparent; +} + +.rightcolumn .node h1 { + font-family:Arial, Helvetica, serif; + font-weight:bold; + font-size:0.95em; /* 1.38em; */ + color:#ffffff; + background-color: #000000; /* #005991; #006666; */ +} + +.rightcolumn .node h1 a { + color:#ffffff; + background-color:transparent; +} + +.rightcolumn .node h2 { + font-weight:bold; + font-size:.95em; +} + +.rightcolumn .node ul.none { + list-style-type:none; +} + +.rightcolumn .node ul.dot { + list-style-type:none; + /* list-style-image:url('../images/listdot.gif'); */ +} + +.rightcolumn .node ul.books { + list-style-type:disc; +} + +/*-OSDN Navagation bar-----------------------------------*/ + +#OSDNNavbar { + background-color:#999999; + color:#000000; /* #005991; /* #006666; */ +} + +#OSDNNavbar div#links { + background-color:#999999; + color:#000000; /* #005991; /* #006666; */ +} + +#OSDNNavbar a { + background-color: transparent; + color: #000000; /* #005991; /* #006666; */ +} + +/*-Remaining layout--------------------------------------*/ + +#randomquote { + font-size:1.2em; + font-style:italic; +} + +#copyright { + font-size:.75em; + font-family:Arial, Helvetica, serif; + background-color:transparent; + color:#000000; /* #005991; /* #006666; */ +} + +#copyright a { + background-color:transparent; + color:#000000; /* #005991; /* #006666; */ +} + +#bottomNav { + background-color:transparent; + color:#000000; /* #005991; /* #006666; */ +} + +#bottomNav a { + background-color:transparent; + color:#ffffff; +} + +#oldStuffNav { + font-weight:bold; +} + ADDED example/models/candidate.scm Index: example/models/candidate.scm ================================================================== --- /dev/null +++ example/models/candidate.scm @@ -0,0 +1,67 @@ +;; Copyright 2007-2008, Matthew Welland. matt@kiatoa.com All rights reserved. +;; +;; models/candidates.scm +;; + +(define (candidate:get-top n) + (dbi:get-rows + (s:db) + "SELECT DISTINCT id,name,url,party,desc,supports_av,date_added,score,pscore FROM candidates AS c ORDER BY score DESC LIMIT ?;" n)) + +;; HERE !!!! getting vote counts... DONT'USE- SEE VOTED INSTEAD +(define (candidate:get-votes candidates vote_type) + (let ((ids (map (lambda (c)(candidate:get-id c)) candidates))) + (dbi:get-rows (s:db) + (conc + "SELECT id,sum(votes*(1+score)) WHERE vote_date>" + (- (current-time) (* 24 60 60 7)) ;; seven days + " AND id IN " + (apply conc (intersperse ids ",")))))) + +(define (candidate:get-by-name name) + (dbi:get-one-row (s:db) "SELECT id,name,url,party,desc,supports_av,date_added,score,pscore FROM candidates WHERE name=?;" name)) + +;; update an existing candidate or create if new +(define (candidate:update dat) + (let* ((name (candidate:get-name dat)) + (olddat (candidate:get-by-name name))) + (if olddat + (begin + (dbi:exec (s:db) + "UPDATE candidates SET url=?,party=?,desc=?,supports_av=? WHERE name=?;" + (candidate:get-url dat) + (candidate:get-party dat) + (candidate:get-desc dat) + (candidate:get-supports-av dat) + name) + (candidate:get-by-name name)) + (begin + (dbi:exec (s:db) + "INSERT INTO candidates (name,url,party,desc,supports_av) VALUES(?,?,?,?,?);" + name + (candidate:get-url dat) + (candidate:get-party dat) + (candidate:get-desc dat) + (candidate:get-supports-av dat)) + (candidate:get-by-name name))))) + + +(define (candidate:get-id dat)(vector-ref dat 0)) +(define (candidate:get-name dat)(vector-ref dat 1)) +(define (candidate:get-url dat)(vector-ref dat 2)) +(define (candidate:get-party dat)(vector-ref dat 3)) +(define (candidate:get-desc dat)(vector-ref dat 4)) +(define (candidate:get-supports-av dat)(vector-ref dat 5)) +(define (candidate:get-date-added dat)(vector-ref dat 6)) +(define (candidate:get-score dat)(vector-ref dat 7)) +(define (candidate:get-pscore dat)(vector-ref dat 8)) + +(define (candidate:set-id! dat val)(vector-set! dat 0 val)) +(define (candidate:set-name! dat val)(vector-set! dat 1 val)) +(define (candidate:set-url! dat val)(vector-set! dat 2 val)) +(define (candidate:set-party! dat val)(vector-set! dat 3 val)) +(define (candidate:set-desc! dat val)(vector-set! dat 4 val)) +(define (candidate:set-supports-av! dat val)(vector-set! dat 5 val)) +(define (candidate:set-date-added! dat val)(vector-set! dat 6 val)) +(define (candidate:set-score! dat val)(vector-set! dat 7 val)) + ADDED example/models/maint.scm Index: example/models/maint.scm ================================================================== --- /dev/null +++ example/models/maint.scm @@ -0,0 +1,57 @@ +;; Copyright 2007-2008, Matthew Welland. matt@kiatoa.com All rights reserved. +;; +;; maint/control.scm +;; + +;; evolve your schema here! +;; Add entries and then go to http:/your-url/maint +;; +;; first make maint:db available as a global +;; +(define maint:db (slot-ref s:session 'conn)) + +;; you can store lambda's or SQL queries to be exectuted +;; be extremely careful - especially with the lambda's!!! +(define maint:schema-updates + (list (list 1 (lambda ()(keystore:set! maint:db "MAINTPW" "Abc123"))) + (list 2 "CREATE TABLE people (id INTEGER PRIMARY KEY,name TEXT DEFAULT '',nick TEXT DEFAULT '',email TEXT,password TEXT,status INTEGER DEFAULT 0,score INTEGER DEFAULT 0,location_id INTEGER DEFAULT 0);") + (list 3 "CREATE TABLE candidates (id INTEGER PRIMARY KEY,name TEXT DEFAULT '',url TEXT DEFAULT '',party TEXT DEFAULT '',desc TEXT DEFAULT '',supports_av INTEGER,date_added DATETIME,score INTEGER DEFAULT 0);") + (list 4 "CREATE TABLE votes (id INTEGER PRIMARY KEY,candidate_id INTEGER,vote_date INTEGER,votes INTEGER,score INTEGER,vote_type INTEGER);") + (list 5 "CREATE TABLE voted (id INTEGER PRIMARY KEY,user_id INTEGER,vote_date INTEGER,score INTEGER);") + ;; location_type can be: city, town, state, region, county etc + (list 6 "CREATE TABLE locations (id INTEGER PRIMARY KEY,parent_id INTEGER,codename TEXT,name TEXT,location_type TEXT,desc TEXT,url TEXT);") + (list 7 "INSERT INTO locations VALUES(0,0,'ea','earth','planet','Home Planet of Humans','');") + (list 8 "ALTER TABLE candidates ADD column pscore INTEGER DEFAULT 0;") + )) + +(define (maint:am-i-maint?) + ;; Enter a maint password - return #t if good + #t) + +(define (maint:update-tables) + (let* ((db (slot-ref s:session 'conn)) + (curr-ver (s:any->number (keystore:get db "SCHEMA-VERSION")))) + (if (not curr-ver) + (begin + (keystore:set! (slot-ref s:session 'conn) "SCHEMA-VERSION" 0) + (set! curr-ver 0))) + (if (null? maint:schema-updates) + (keystore:set! (slot-ref s:session 'conn) "SCHEMA-VERSION" 0) + (let loop ((hed (car maint:schema-updates)) + (tal (cdr maint:schema-updates)) + (highest-ver 0)) + (if (< (length hed) 2) + (s:log "Malformed maint:schema-updates table in maint/control.scm") + (let ((ver (car hed)) + (act (cadr hed))) + (if (> ver curr-ver) ;; need to apply this one + (begin + (if (string? act) + (dbi:exec db act) + (act)) + ;; yes, do this for each one, just in case of a crash + (keystore:set! db "SCHEMA-VERSION" ver))) + (if (null? tal) + highest-ver + (loop (car tal)(cdr tal) ver)))))))) + ADDED example/models/person.scm Index: example/models/person.scm ================================================================== --- /dev/null +++ example/models/person.scm @@ -0,0 +1,68 @@ +;; Copyright 2007-2008, Matthew Welland. matt@kiatoa.com All rights reserved. +;; +;; models/person.scm +;; +(require "md5") + +(define (person:get-dat email) + (dbi:get-one-row (s:db) "SELECT id,name,email,status,password,score FROM people WHERE email=?;" email)) + +;; this effectively auto logs in using "" as the password +(define (person:create-or-get email) + (let ((dat (person:get-dat email))) + (if dat + (person:authenticate email "") + (person:set-password email "")))) + +(define (person:password-match? password cryptedpw) + (string=? (md5:digest password) cryptedpw)) + +(define (person:authenticate email password) + (let ((pdat (person:get-dat email))) + (if pdat + ;; (if (s:password-match? password (vector-ref pdat 4)) + (if (person:password-match? password (vector-ref pdat 4)) + pdat ;; password matched, return basic record id,name,email,status + #f) + #f))) + +;; sets password, creates user if doesn't exist +(define (person:set-password email password) + (let ((pdat (person:get-dat email)) + ;; (cpwd (s:crypt-passwd password #f))) + (cpwd (md5:digest password))) + (if pdat + (dbi:exec (s:db) + "UPDATE people SET password=? WHERE email=?;" + cpwd + email) + (dbi:exec (s:db) + "INSERT INTO people (name,email,password) VALUES(?,?,?);" + "" + email + cpwd)) + (if pdat + pdat + (person:get-dat email)))) + +(define (person:learn_enabled? email) + (eq? (dbi:get-one (s:db) "SELECT status FROM people WHERE email=?;" email) + 1)) + +(define(person:files_enabled? email) + #f) + +;; id,name,email,status,password,score +(define (person:get-id dat)(vector-ref dat 0)) +(define (person:get-name dat)(vector-ref dat 1)) +(define (person:get-email dat)(vector-ref dat 2)) +(define (person:get-status dat)(vector-ref dat 3)) +(define (person:get-password dat)(vector-ref dat 4)) +(define (person:get-score dat)(vector-ref dat 5)) + +(define (person:set-id! dat val)(vector-set! dat 0 val)) +(define (person:set-name! dat val)(vector-set! dat 1 val)) +(define (person:set-email! dat val)(vector-set! dat 2 val)) +(define (person:set-status! dat val)(vector-set! dat 3 val)) +(define (person:set-password! dat val)(vector-set! dat 4 val)) +(define (person:set-score! dat val)(vector-set! dat 5 val)) ADDED example/models/voting.scm Index: example/models/voting.scm ================================================================== --- /dev/null +++ example/models/voting.scm @@ -0,0 +1,61 @@ +;; Copyright 2007-2008, Matthew Welland. matt@kiatoa.com All rights reserved. +;; +;; models/voting.scm +;; +;; store the votes! + +;; look up the entry to which to add +(define (voting:get-entry-id candidate-id score type) + (dbi:get-one (s:db) "SELECT id FROM votes WHERE candidate_id=? AND score=? AND vote_type=? AND vote_date>?;" + candidate-id + score + type + (- (current-seconds) 86400))) ;; i.e. since 24 hrs ago + +(define (voting:apply-vote dat candidate-id vote-type) + (let* ((score (person:get-score dat)) + (vote-entry-id (voting:get-entry-id candidate-id score vote-type))) + (if vote-entry-id + (dbi:exec (s:db) "UPDATE votes SET votes=votes+1 WHERE id=?;" vote-entry-id) + (dbi:exec (s:db) "INSERT INTO votes (candidate_id,vote_date,votes,score,vote_type) VALUES(?,?,?,?,?);" + candidate-id + (current-seconds) + 1 + score + vote-type)))) + +(define (voting:rollup-votes) + (let ((adat (dbi:get-rows (s:db) + "SELECT candidate_id AS id,SUM(votes*(score+1)) AS score FROM votes WHERE vote_date>? AND vote_type=1 GROUP BY candidate_id;" + (- (current-seconds) (* 24 60 60 7)))) + (pdat (dbi:get-rows (s:db) + "SELECT candidate_id AS id,SUM(votes*(score+1)) AS score FROM votes WHERE vote_date>? AND vote_type=0 GROUP BY candidate_id;" + (- (current-seconds) (* 24 60 60 7))))) + (for-each + (lambda (row) + (dbi:exec (s:db) "UPDATE candidates SET score=? WHERE id=?;" (vector-ref row 1)(vector-ref row 0))) + adat) + (for-each + (lambda (row) + (dbi:exec (s:db) "UPDATE candidates SET pscore=? WHERE id=?;" (vector-ref row 1)(vector-ref row 0))) + pdat))) + +;; vote_type: 0=plurality, 1=approval +(define (voting:handle-votes email approval plurality) + (let* ((pdat (let ((e (s:session-var-get "email"))) + (if e + (person:get-dat e) + (person:create-or-get (if (or (not (string? email)) + (string-match (regexp "^\\s*$") email)) + "noname" + email)))))) ;; is this really the logic I wanted? + ;; (s:log "Got here eh!" " pdat: " pdat) + (if (not pdat) + (s:set! "errmsg" "Failed to auto log in/register, email or nick already in use. Consider reseting your password") + (begin + (s:session-var-set! "email" (person:get-email pdat)) + (voting:apply-vote pdat plurality 0) + (map (lambda (candidate-id) + (voting:apply-vote pdat candidate-id 1)) + approval) + (voting:rollup-votes))))) ADDED example/pages/action/view.scm Index: example/pages/action/view.scm ================================================================== --- /dev/null +++ example/pages/action/view.scm @@ -0,0 +1,51 @@ +;; Copyright 2007-2008, Matthew Welland. Kiatoa.com All rights reserved. +;; +(s:div 'class "node" + (s:h1 "Approval voting works") + "

Approval voting is very resistant to strategic voting and it is + extremely easy to implement using existing ballot technology. +

Every four years voters must + make a painful strategic choice, either vote for the candidate + they really want and risk getting saddled + with a candidate they don't want, OR + vote for the most palatable frontrunner, and send a false + message of disinterest in their true choice." + (s:h1 "Thinking is required for a democracy to work") + "

Consider trying the "fool test" on an unsuspecting friend or aquaintence. + . Pick a popular smear or other known distortion aimed at a candidate you suspect your + "person under test", or PUT, + doesn't like. Research the item and find out the truth about it as + best you can. Start with + factcheck.org but don't stop there. Use google or other search + engines to build up a picture of what is true. + +

Once you are armed with information you can apply the test. Ask your + friend or collegue for the truth behind the smear. Be neutral. Accept + their answer without judgement if it is incorrect. Say "oh", or + "thanks" and let it be at that. Again, DO NOT CORRECT THEM! + +

If your PUT fails the test don't harp on them or correct them. + Although everyone is responsible for researching the facts many people will + lock onto their existing ideas if challenged. Instead say something like, + "you may want to research that" and accept that you are dealing with + someone who just might be a fool, unwilling or unable to look at their + favorite candidate with a critical eye. +

Finally, be prepared to be tested yourself, + aggressively research the smears your favored candidates put out. If they are true + be prepared to prove it, if they are false, be prepared to put them in + context or simply admit they are false. No candidate will be perfect." + (s:h1 "A strategy for change") + "

Get a yes/no answer from your favored candidate about approval voting. + If your candidate refuses to support approval voting first hear them out. If their + reasons are good then publish them so we can all learn from it. If their + reasons are weak then look for an alternative candidate to support. + +

Improve your score here on approvalvote.org and then vote again in our front + page poll. Your score will adjust the power of your vote such that the poll + will reflect the choices of those who are willing to think. + + We will advocate that everyone votes for an approval vote supporting independant + candidate if that candidate is at least 10% ahead of the next candidate of + the same leaning (i.e. liberal or conservative). Otherwise you should vote + for the frontrunner candidate of your choosen leaning due to the dangers of + plurality voting.") ADDED example/pages/footer/view.scm Index: example/pages/footer/view.scm ================================================================== --- /dev/null +++ example/pages/footer/view.scm @@ -0,0 +1,5 @@ +;; Copyright 2007-2008, Matthew Welland. Kiatoa.com All rights reserved. +;; +;; footer +(list + (s:div 'class "node" "This is the footer")) ADDED example/pages/header/control.scm Index: example/pages/header/control.scm ================================================================== --- /dev/null +++ example/pages/header/control.scm @@ -0,0 +1,9 @@ +;; Copyright 2007-2008, Matthew Welland. Kiatoa.com All rights reserved. +;; +;; header/control.scm + +;; (load (s:model-path "blah")) +(define header:menu-items '(("home" "Home")("learn" "Learn")("action" "Take Action")("discussion" "Discussion") + ("preferences" "Preferences"))) +(define header:title (let ((t (s:get-param 'section))) + (if t t "Home"))) ADDED example/pages/header/view.scm Index: example/pages/header/view.scm ================================================================== --- /dev/null +++ example/pages/header/view.scm @@ -0,0 +1,30 @@ +;; Copyright 2007-2008, Matthew Welland. Kiatoa.com All rights reserved. +;; +;; header/view.scm +;; +(list + ;; (s:div 'id "titlebar" + (s:table + (s:tr + (s:td (s:img 'src "/www/images/approvalvote.png" + 'alt "ApprovalVote.com" + 'title "Welcome to ApprovalVote.com")) + (s:td 'valign "top" 'align "right" + (s:table 'border "0" 'cellspacing "0" + (s:tr + (s:td 'valign "center" ;; 'width "250" ;; 'rowspan "2" + (s:a (s:small " * NOW IS A GREAT TIME TO PUSH FOR APPROVAL VOTING! * ")) + (s:br))) + (s:tr + (s:td 'columnspan="3" + (s:center "*********")))))) ;; header:title)))))) + ;; this is the horizontal menus + (s:tr 'columnspan "4" + (s:table + (s:tr + (map (lambda (m-item) + (s:td (s:small "[" + (s:a 'href (s:link-to (car m-item))(cadr m-item)) + "]"))) + header:menu-items) + )))));; ) ADDED example/pages/home/view.scm Index: example/pages/home/view.scm ================================================================== --- /dev/null +++ example/pages/home/view.scm @@ -0,0 +1,12 @@ +;; Copyright 2007-2008, Matthew Welland. Kiatoa.com All rights reserved. +;; +(s:div 'class "node" + (s:h1 "Please Help Save Our Democracy.") + "

We need approval voting to re-energize our democracy. + Our system is in danger of failing us since it leaves us powerless + to force change. Arguably the biggest problem lies in our use of + plurality voting to choose leaders. + ") +(s:div 'class "node" + (s:h1 "Practice some approval voting now!") + (s:call "uspresident")) ADDED example/pages/index/control.scm Index: example/pages/index/control.scm ================================================================== --- /dev/null +++ example/pages/index/control.scm @@ -0,0 +1,6 @@ +;; Copyright 2007-2008, Matthew Welland. Kiatoa.com All rights reserved. +;; +;; this gets read for ALL pages. Don't weigh it down excessively! +;; +;; index/control.scm + ADDED example/pages/index/view.scm Index: example/pages/index/view.scm ================================================================== --- /dev/null +++ example/pages/index/view.scm @@ -0,0 +1,21 @@ +;; Copyright 2007-2008, Matthew Welland. Kiatoa.com All rights reserved. +;; +;; index + +(list + (s:html + (s:head + (s:title "Approval Voting Now!") + (s:link 'rel "stylesheet" 'type "text/css" 'href "/approvalvote/markup.css") + (s:link 'rel "stylesheet" 'type "text/css" 'href "/approvalvote/layout.css")) + (s:body + (s:div 'class "header" (s:call "header")) + (s:div 'class "rightcolumn" (s:call "rightcol")) + (s:div 'class "leftcolumn" (s:call "leftnav")) + (s:div 'class "centercolumn" + (let ((page (slot-ref s:session 'page))) + (if page + (s:call page) + (list (s:h2 "Home") + (s:call "sys-state"))))) + (s:div 'class "footer" (s:call "footer"))))) ADDED example/pages/learn/view.scm Index: example/pages/learn/view.scm ================================================================== --- /dev/null +++ example/pages/learn/view.scm @@ -0,0 +1,7 @@ +;; Copyright 2007-2008, Matthew Welland. Kiatoa.com All rights reserved. +;; +(s:div 'class "node" + (s:h1 "Resources") + "

Two excellent sites with more information on approval voting: +

approvalvoting.org +

approvalvoting.com") ADDED example/pages/leftnav/control.scm Index: example/pages/leftnav/control.scm ================================================================== --- /dev/null +++ example/pages/leftnav/control.scm @@ -0,0 +1,11 @@ +;; Copyright 2007-2008, Matthew Welland. Kiatoa.com All rights reserved. +;; +;; leftnav/control.scm + +;; nothing needed here yet! + +(define (leftnav-action action) + (case action + ('logout + (s:logout)))) + ADDED example/pages/leftnav/view.scm Index: example/pages/leftnav/view.scm ================================================================== --- /dev/null +++ example/pages/leftnav/view.scm @@ -0,0 +1,38 @@ +;; Copyright 2007-2008, Matthew Welland. Kiatoa.com All rights reserved. +;; +;; leftnav/view.scm + +(list + (s:div + 'class "node" + (s:h1 "Navigation") + (let ((section (slot-ref s:session 'page))) + (cond + ((or (not section) ;; this is home + (string=? section "home")) + "Home menu") + ((string=? section "discussions") + (list + (s:a "Filter" 'href (s:link-to "discussions" 'filter "on")))) + ((string=? section "learn") + (list + (s:a "Learn" 'href (s:link-to "learn" 'action "learn.teach"))(s:br) + (s:a "Test" 'href (s:link-to "learn" 'action "learn.test"))(s:br) + )) + ((string=? section "preferences") + (list + (s:a "Password" 'href (s:link-to "preferences" 'action "password"))(s:br) + (s:a "Messages" 'href (s:link-to "preferences" 'action "messages"))(s:br) + (s:a "Preferences" 'href (s:link-to "preferences" 'action "preferences"))(s:br))) + (else '( "nada" )))) + (s:br)) + (s:div + 'class "node" + (s:h1 "About you") + (let ((email (s:session-var-get "email"))) + (if email + (list email (s:br)) + "Not logged in"))) + (s:div + 'class "node" + (s:call "pledge"))) ADDED example/pages/login/control.scm Index: example/pages/login/control.scm ================================================================== --- /dev/null +++ example/pages/login/control.scm @@ -0,0 +1,25 @@ +;; Copyright 2007-2008, Matthew Welland. Kiatoa.com All rights reserved. +;; +(load (s:model-path "person")) + +(define (login-action action) + (case (string->symbol action) + ('login + ;; the actual login code + (s:log "Got here, doing login") + (let ((email (s:get-input 'email-address)) + (passwd (s:get-input 'password))) + ;; (person (make-person))) ;; DO WE NEED A PERSON "OBJECT"? + (s:set! "email-address" email) ;; preserve user as email-address + (if (and email passwd) + (let ((good-login (person:authenticate email passwd))) + (if good-login + (begin + (s:set! "msg" "Login successful!") + (s:session-var-set! "email" email)) + (s:set! "msg" "Bad password or email. Please try again"))) + (s:set! "msg" "Missing password or email")))) + ('logout + (s:delete-session)) + ('nada + (s:log "Got here, action=" action)))) ADDED example/pages/login/view.scm Index: example/pages/login/view.scm ================================================================== --- /dev/null +++ example/pages/login/view.scm @@ -0,0 +1,24 @@ +;; Copyright 2007-2008, Matthew Welland. Kiatoa.com All rights reserved. +;; +;; Login view + +(s:div 'class "node" + ;; (s:p (s:get-err s:strong)) ;; error message + (if (s:session-var-get "email") + (s:a "Log out" 'href (s:link-to (s:current-page) 'action "login.logout")) + (list + (s:center (s:p (s:strong "Log in here!"))) + (let ((msg (s:get "msg"))) + (if msg + (begin + (s:del! "msg") + (s:err-font msg)) + (s:null ""))) + (s:form 'action "login.login" 'method "post" + (s:strong "Id: (*)")(s:br) + (s:input-preserve 'type "text" 'name "email-address" 'size "14" 'maxlength "30")(s:br) + (s:strong "Password:")(s:br) + (s:input 'type "password" 'name "password" 'size "14" 'maxlength "30")(s:br) + (s:input 'type "submit" 'name "form-name" 'value "login")(s:br) + (s:a "Create account" 'href (s:link-to "new_account")) + )))) ADDED example/pages/maint/control.scm Index: example/pages/maint/control.scm ================================================================== --- /dev/null +++ example/pages/maint/control.scm @@ -0,0 +1,13 @@ +;; Copyright 2007-2008, Matthew Welland. matt@kiatoa.com All rights reserved. +;; +;; maint/control.scm +;; +(s:load-model "maint") + +;; remember that the system will call the function -action with the action as a parameter +(define (maint-action action) + (let ((asym (string->symbol action))) + (s:log "Doing action! " action) + (case asym + ('update_tables + (maint:update-tables))))) ADDED example/pages/maint/view.scm Index: example/pages/maint/view.scm ================================================================== --- /dev/null +++ example/pages/maint/view.scm @@ -0,0 +1,12 @@ +;; Copyright 2007-2008, Matthew Welland. Kiatoa.com All rights reserved. +;; +;; maint/view.scm +;; +(if (maint:am-i-maint?) + (list + (s:h1 "Hello Maint!") + (s:p (s:a "Update Tables" 'href (s:link-to (s:current-page) + 'action "maint.update_tables")))) + '()) + + ADDED example/pages/new_account/control.scm Index: example/pages/new_account/control.scm ================================================================== --- /dev/null +++ example/pages/new_account/control.scm @@ -0,0 +1,53 @@ +;; Copyright 2007-2008, Matthew Welland. matt@iatoa.com All rights reserved. +;; +;; new_account/control.scm + +(load (s:model-path "person")) + +(define (new_account:validate-inputs password password-again email-address email-address-again) + (cond + ((or (not password)(not password-again) + (not email-address)(not email-address-again)) + (s:set-err "Form is incomplete. Please fill in all fields and try again") + #f) + ((< (string-length password) 2) + (s:set-err "Password is too short. Please try again") + #f) + ((not (string=? password password-again)) + (s:set-err "Passwords do not match. Please try again") + #f) + ((> (string-length password) 9) + (s:set-err "Password is too long. Please try again") + #f) + ((not (string=? email-address email-address-again)) + (s:set-err "Email addresses provided do not match. Please try again") + #f) + ((and (not (string-match (regexp "^\\s*$") email-address)) + (not (string-match (regexp "^[^@]+@[^@]+\\.[^@]+$") email-address))) + (s:set-err "Not a valid email address, please try again") + #f) + (else #t))) + +(define (new_account-action action) + (case (string->symbol action) + ('create + (s:log "Got here, doing create new account") + (let ((password (s:get-input 'password)) + (password-again (s:get-input 'password-again)) + (email-address (s:string-downcase (s:get-input 'email-address))) + (email-address-again (s:string-downcase (s:get-input 'email-address-again)))) + ;; save preserved inputs + (s:set! "email-address" email-address) + (s:log "Saved inputs. Now check inputs") + (if (new_account:validate-inputs password password-again email-address + email-address-again) + ;; Great!! Now have good inputs + (if (person:get-dat email-address) + (s:set-err "There is already an account for that email address!") + (let ((pdat (person:set-password email-address password))) + (if pdat + (s:set-err "SUCCESS!! You can now log in with " email-address " and your password") + (s:set-err "ERROR!! Unable to automatically log you on with the same credentials used to create your account. This shouldn't happen. Please send email to matt@kiatoa.com about this")))) + ;; bad inputs + #f))) + ('else (s:log "Placeholder for future actions. Shouldn't get here")))) ADDED example/pages/new_account/view.scm Index: example/pages/new_account/view.scm ================================================================== --- /dev/null +++ example/pages/new_account/view.scm @@ -0,0 +1,27 @@ +;; Copyright 2007-2008, Matthew Welland. Kiatoa.com All rights reserved. +;; +;; new_account/view.scm +;; +(list + (s:div 'class "node" + ;; (s:p (s:get-err s:strong)) ;; error message + (s:p "")(s:p (s:get-err s:err-font)) + (if (not (s:session-var-get "email")) ;; setting email defines "logged in" + (s:form 'action "new_account.create" 'method "post" + (s:table 'border "0" 'spacing "0" + + (s:tr (s:td (s:strong "Email address:")) ;; (s:br) + (s:td (s:input-preserve 'type "text" 'name "email-address" 'size "16" 'maxlength "30"))) ;; (s:br) + + (s:tr (s:td (s:strong "Email address again:")) ;; (s:br) + (s:td (s:input-preserve 'type "text" 'name "email-address-again" 'size "16" 'maxlength "30"))) ;; (s:br) + + (s:tr (s:td (s:strong "Password:")) ;; (s:br) + (s:td (s:input 'type "password" 'name "password" 'size "16" 'maxlength "16"))) ;; (s:br) + + (s:tr (s:td (s:strong "Password again:")) ;; (s:br) + (s:td (s:input 'type "password" 'name "password-again" 'size "16" 'maxlength "16")))); (s:br) + + (s:input 'type "submit" 'name "form-name" 'value "submit")) + (s:h1 "Welcome " (s:session-var-get "email") ":" (s:session-var-get "location") "!")))) + ADDED example/pages/pledge/view.scm Index: example/pages/pledge/view.scm ================================================================== --- /dev/null +++ example/pages/pledge/view.scm @@ -0,0 +1,16 @@ +;; Copyright 2007-2008, Matthew Welland. matt@iatoa.com All rights reserved. +;; +(s:if-sessionvar + "email" + (list + (s:h1 "Pledge now!") + (s:fieldset + "Pledge" + (s:form 'action "pledge.pledge" + 'method "post" + (s:i " - I will vote" (s:b "ONLY") " for a candidate who supports approval voting!") + (s:table + (s:tr (s:td "Yes") (s:td (s:input 'type "radio" 'name "pledge_answer" 'value "yes"))) + (s:tr (s:td "No") (s:td (s:input 'type "radio" 'name "pledge_answer" 'value "no"))) + (s:tr (s:td "Maybe")(s:td (s:input 'type "radio" 'name "pledge_answer" 'value "maybe")))) + (s:input 'type "button" 'name "pledge_answer" 'value "Submit"))))) ADDED example/pages/preferences/view.scm Index: example/pages/preferences/view.scm ================================================================== --- /dev/null +++ example/pages/preferences/view.scm @@ -0,0 +1,12 @@ +;; Copyright 2007-2008, Matthew Welland. matt@iatoa.com All rights reserved. +;; +;; preferences/view.scm +;; +(s:div + 'class "node" + (s:h1 "Register your email address") + (s:p "Adds 9 pts to your score the first time you do it and enables very occasional email updates. If you change your email address + you need to re-register to keep your 9 pts.") + (s:form 'action "preferences.register_email" + 'method "post" + (s:input 'type "submit" 'name "register_email" 'value "Register Email"))) ADDED example/pages/rightcol/view.scm Index: example/pages/rightcol/view.scm ================================================================== --- /dev/null +++ example/pages/rightcol/view.scm @@ -0,0 +1,9 @@ +;; Copyright 2007-2008, Matthew Welland. Kiatoa.com All rights reserved. +;; + +;; rightcol +(list + (s:div 'class "node" + (s:call "login"))) + +;; "This is the right-most column")) ADDED example/pages/sys-state/view.scm Index: example/pages/sys-state/view.scm ================================================================== --- /dev/null +++ example/pages/sys-state/view.scm @@ -0,0 +1,16 @@ +;; Copyright 2007-2008, Matthew Welland. Kiatoa.com All rights reserved. +;; + +;; sys-state + +(list (let ((p (open-input-pipe "env"))) + (let loop ((l (read-line p)) + (res '())) + (if (not (eof-object? l)) + (loop (read-line p)(cons (list l "
") res)) + res))) + ;; "USER=" (user-information (current-user-id)) + + (s:h2 "Form data") + (session:pp-formdat s:session) + "argv=" (argv)) ADDED example/pages/uspresident/control.scm Index: example/pages/uspresident/control.scm ================================================================== --- /dev/null +++ example/pages/uspresident/control.scm @@ -0,0 +1,72 @@ +;; Copyright 2007-2008, Matthew Welland. Kiatoa.com All rights reserved. +;; +;; this gets read for ALL pages. Don't weigh it down excessively! +;; +;; uspresident/control.scm + +(s:load-model "candidate") +(s:load-model "voting") +(s:load-model "person") + +(define candidates (candidate:get-top 10)) +(define candidates:vote-sum-approval (apply + (map candidate:get-score candidates))) +(define candidates:vote-sum-plurality (apply + (map candidate:get-pscore candidates))) +(define candidates:top-plurality-id (let ((id #f) + (topscore 0)) + (for-each (lambda (cand) + (if (> (candidate:get-pscore cand) topscore) + (begin + (set! topscore (candidate:get-pscore cand)) + (set! id (candidate:get-id cand))))) + candidates) + id)) +(define candidates:top-approval-id (let ((id #f) + (topscore 0)) + (for-each (lambda (cand) + (if (> (candidate:get-score cand) topscore) + (begin + (set! topscore (candidate:get-score cand)) + (set! id (candidate:get-id cand))))) + candidates) + id)) + + +(define (uspresident-action action) + (let ((acsym (string->symbol action))) + (cond + ('vote + (let ((button (s:get-input 'vote))) + (cond + ((equal? button "Vote") + (let* ((approval (s:get-input 'approval)) + (plurality (s:get-input 'plurality)) + (newdat (make-vector 9 "")) + (email (s:session-var-get "email")) + (newcandname (s:get-input 'poll_name)) + (nick-email (if email email (s:get-input 'users_email)))) + (if (not (list? approval)) + (set! approval (list approval))) + (if (string-match (regexp "^[a-zA-Z]+") newcandname) + (let* ((dat (candidate:get-by-name newcandname))) + (if dat ;; i.e. this is a new candidate + (set! newdat dat) + (begin + (candidate:set-name! newdat newcandname) + (candidate:set-supports-av! newdat (s:get-input 'poll_supports_av)) + (candidate:set-party! newdat (s:get-input 'poll_party)) + (candidate:set-url! newdat (s:get-input 'poll_url)) + (set! newdat (candidate:update newdat)))) + (s:log "cid: " (candidate:get-id newdat)) + (set! approval (cons (candidate:get-id newdat) approval)) + (set! plurality (candidate:get-id newdat)))) + (set! approval (filter (lambda (x)(or (number? x)(string? x))) approval)) ;; clean the approval list + (s:log "using email: " nick-email) + (s:log "approval: " approval) + (s:log "plurality: " plurality) + (if (and approval plurality (not (null? approval))) + (begin + (voting:handle-votes nick-email + approval + plurality) + (s:session-var-set! "voted" "yes")) + (s:set! "errmsg" "Please select one plurality vote and one or more approval votes")))))))))) ADDED example/pages/uspresident/view.scm Index: example/pages/uspresident/view.scm ================================================================== --- /dev/null +++ example/pages/uspresident/view.scm @@ -0,0 +1,85 @@ +;; Copyright 2007-2008, Matthew Welland. Kiatoa.com All rights reserved. +;; + +;; Note: the (list is actually no longer needed. + +(list + (s:if-sessionvar + "email" + (s:if-sessionvar + "voted" + "We are glad you tried approval voting. Try again to see how the system works. Don't worry about the poll numbers. This poll is for you to play with.")) + (s:fieldset + "Poll" + (s:center + (s:if-param "errmsg" + (let ((err (s:get "errmsg"))) + (s:del! "errmsg") + (s:err-font err))) + (s:form 'action "uspresident.vote" + 'method "post" + (s:table 'border "1" 'cellspacing "0" + (s:tr + (s:td "Candidate")(s:td "Party")(s:td "Supports approval?") + (s:if-sessionvar + "voted" + (list (s:td "Plurality") + (s:td "Approval") + (s:td "Plurality" (conc "(" candidates:vote-sum-plurality "votes" ")")) + (s:td "Approval" (conc "(" candidates:vote-sum-plurality "votes" ")"))) + (list (s:td "Plurality (vote for one only)")(s:td "Approval (vote for all which you approve of)")))) + ;; map the poll items for each row + (map (lambda (candidate) + (let ((poll-item-id (number->string (candidate:get-id candidate))) + (poll-item-url (s:tidy-url (candidate:get-url candidate))) + (poll-item-name (candidate:get-name candidate)) + (poll-item-description (candidate:get-desc candidate)) + (poll-item-percent-a (quotient (* 100 (candidate:get-score candidate)) candidates:vote-sum-plurality)) + (poll-item-percent-p (quotient (* 100 (candidate:get-pscore candidate)) candidates:vote-sum-plurality))) + (list + (s:tr + (s:td + (if poll-item-url + (s:a 'href poll-item-url 'target "_blank" poll-item-name) + poll-item-name)) + ;; (if (poll:poll 'have-description?) + ;; (s:td 'bgcolor "#f0f0f0" poll-item-description) ;; description + ;; '()) + (s:td (candidate:get-party candidate)) + (s:td (candidate:get-supports-av candidate)) + ;; (if (not (s:session-var-get "voted")) ;; here are the check buttons for plurality and approval voting + ;; (list + (s:td (s:center + (s:input 'type "radio" 'name "plurality" 'value poll-item-id))) + (s:td (s:center + (s:input 'type "checkbox" 'name "approval" 'value poll-item-id))) + (s:if-sessionvar "voted" + (list + (s:td (conc poll-item-percent-p "%") 'bgcolor (if (eq? (candidate:get-id candidate) candidates:top-plurality-id) + "cyan" + "lightgrey") + (conc "(" (candidate:get-pscore candidate) ")") 'align "center") + (s:td (conc poll-item-percent-a "%") 'bgcolor (if (eq? (candidate:get-id candidate) candidates:top-approval-id) + "cyan" + "lightgrey") + (conc "(" (candidate:get-score candidate) ")") 'align "center"))))))) ;; % votes + candidates) + (s:tr + (s:td "Write in (name):
" + (s:input-preserve 'type "text" 'name "poll_name" 'size "15" 'maxlength "40")) + (s:td "Party:
" (s:input-preserve 'type "text" 'name "poll_party" 'size "10" 'maxlength "40")) + (s:td "Supports approval:
" (s:input-preserve 'type "text" 'name "poll_supports_av" 'size "10" 'maxlength "40")) + (s:td "Url:
" (s:input-preserve 'type "text" 'name "poll_url" 'size "40" 'maxlength "120") 'colspan 4)) + (s:tr + (s:td 'colspan 7 + (s:center (s:input 'type "submit" 'name "vote" 'value "Vote") + (s:if-sessionvar "email" + '() + (list + "Email or nickname:" + (s:input-preserve 'type "text" 'name "users_email" 'size 20 'maxlength 40) + "(required), Country code:" + (s:input-preserve 'type "text" 'name "users_country_code" 'size 2 'maxlength 2) + "(optional)" + )) + )))))))) ADDED example/tests/test.scm Index: example/tests/test.scm ================================================================== --- /dev/null +++ example/tests/test.scm @@ -0,0 +1,85 @@ +#!/usr/local/bin/csi -q + +;; This currently requires that the stml code is available in a parallel directory. + +(use test) +(if (file-exists? "test.db") + (begin + (print "Removing old test.db") + (system "rm -f test.db"))) + +(load "../stml/misc-stml.scm") +(load "../stml/formdat.scm") +(load "../stml/stml.scm") +(load "../stml/session.scm") +(load "../stml/sqltbl.scm") +(load "../stml/html-filter.scm") ;; required for s:split-string +(load "../stml/dbi.scm") +(load "../stml/keystore.scm") +(load "../stml/sugar.scm") + +;; create a session to work with") +(setenv "REQUEST_URI" "/stmlrun?action=maint.nada") +(setenv "SCRIPT_NAME" "/cgi-bin/stmlrun") +(setenv "PATH_INFO" "/maint") +(setenv "QUERY_STRING" "action=maint.nada") +(setenv "SERVER_NAME" "localhost") +(setenv "REQUEST_METHOD" "GET") +;; (define session-name "pfNOeqUHkJ26BpU6y49IN") ;; ensure this session already exists +;; (setenv "HTTP_COOKIE" (string-append "session_key=" session-name)) ;; to09ipFJ9_2KXT96b2f9Q") + +(load "../stml/setup.scm") +;; (test (string-append "Session set to existing session " session-name) +;; session-name (slot-ref s:session 'session-key)) + +(s:validate-inputs) + +;; test session variables + +;; lazy stuff +(define *conn* (slot-ref s:session 'conn)) + +;; setup tables +(load "models/maint.scm") +(test "Create tables" #t (> (maint:update-tables) + 0)) + +;; test person +(let ((fh (open-input-pipe "ls models/*.scm"))) + (let loop ((l (read-line fh))) + (if (not (eof-object? l)) + (begin + (print "loading " l) + (load l) + (loop (read-line fh))))) + (close-input-port fh)) + +(let ((fh (open-input-pipe "find pages -name control.scm"))) ;; ls pages/*/control.scm"))) + (let loop ((l (read-line fh))) + (if (not (eof-object? l)) + (begin + (print "loading " l) + (load l) + (loop (read-line fh))))) + (close-input-port fh)) + +(let ((fh (open-input-pipe "ls pages/*/view.scm"))) + (let loop ((l (read-line fh))) + (if (not (eof-object? l)) + (begin + (print "loading " l) + (load l) + (loop (read-line fh))))) + (close-input-port fh)) + +;;====================================================================== +;; Maint +;;====================================================================== +;; +(load "models/maint.scm") + +(test "Update tables" #t (> (maint:update-tables))) ;; *conn* 2 "us") 0)) +(test "Add user" "matt@kiatoa.com" (vector-ref (person:set-password "matt@kiatoa.com" "Password") 2)) +(test "Authenticate" "matt@kiatoa.com" (vector-ref (person:authenticate "matt@kiatoa.com" "Password") 2)) +(test "Validate inputs" #t (new_account:validate-inputs "Password" "Password" "matt@kiatoa.com" "matt@kiatoa.com")) + ADDED example/www/layout.css Index: example/www/layout.css ================================================================== --- /dev/null +++ example/www/layout.css @@ -0,0 +1,245 @@ + +/*-General-----------------------------------------------*/ + +html, body { + margin:0px; + padding:0px; +} + +form { + display:inline; + margin:0px; + padding:0px; +} + +a img { + border:none; + margin:0px; + padding:0px; +} + +h1, h2, h3, h4, h5, h6, p, div { + margin:0px; + padding:0px; +} + +.right { + float:right; +} + +.left{ + float:left; +} + +/*-Main Layout-------------------------------------------*/ + +#overall { + /* margin:5px 12px 0px 12px; */ + padding:0px; +} + +/*-Header-------------*/ + +.header { + /* float:top; */ + position:relative; + height:55px; +} + +/*-Footer-------------*/ + +.footer { + padding:40px 0px 0px 0px; + position:relative; + clear:both; +} + +/*-Content Area-------*/ + +.content { + width:100%; +} + +/*-Left Column--------*/ + +.leftcolumn { + float:left; + width:145px; + margin:5px; +} + +.leftcolumn .node { + margin:0px 0px 15px 0px; +} + +.leftcolumn .node h1 { + padding:0px 0px 0px 3px; +} + +.leftcolumn .node ul { + margin:0px; + padding:0px; +} + +.leftcolumn .node li { + display:block; + padding:0px 0px 0px 3px; + margin:0px; +} + +.leftcolumn .node li.more{ + padding:0px 0px 0px 6px; +} + +/*-Center Column------*/ + +.centercolumn { + margin: 5px; + margin-left:152px; + margin-right:140px; + font-family:"\"}\""; + font-family:inherit; +} + +.centercolumn .node h1 { + padding: 0px 0px 0px 13px; +} + +.centercolumn .node h4 { + margin: 15px 0px 10px 0px; +} + +.centercolumn .node p { + margin: 0px 0px 10px 0px; */ + padding: 0px 0px 0px 0px; +} /* this seemed not to work */ + +.posts_0 { + margin: 0px 0px 0px 0px; +} + +.posts_1 { + margin: 0px 0px 0px 20px; +} + +.posts_2 { + margin: 0px 0px 0px 40px; +} + +.posts_3 { + margin: 0px 0px 0px 60px; +} + +.posts_4 { + margin: 0px 0px 0px 80px; +} + +.posts_5 { + margin: 0px 0px 0px 100px; +} + +.posts_6 { + margin: 0px 0px 0px 120px; +} + +.posts_7 { + margin: 0px 0px 0px 140px; +} + +.posts_8 { + margin: 0px 0px 0px 160px; +} + +.posts_9 { + margin: 0px 0px 0px 160px; +} + +.posts_10 { + margin: 0px 0px 0px 180px; +} + +/*-Right Column-------*/ + +.rightcolumn { + float:right; + width:130px; + margin:5px 5px 0px 0px; +} + +* html .rightcolumn { + margin:3px 3px 3px 3px; +} + +body>div .rightcolumn { + margin:0px 0px 0px 0px; +} + +.rightcolumn .node { + margin:0px 0px 5px 0px; + padding:0px; +} + +.rightcolumn .node h2 { + margin:3px 3px 3px 2px; +} + +.rightcolumn .node ul { + list-style-position:inside; + margin:0px; + padding:1px; +} + +.rightcolumn .node ul.none { + list-style-position:inside; +} + +.rightcolumn .node ul.dot { + list-style-position:inside; +} + +.rightcolumn .node ul.books { + list-style-position:outside; + margin:0px 0px 0px 35px; +} + +.rightcolumn .node li { + padding:0px 0px 0px 3px; + margin:0px; +} + +/*-Remaining layout--------------------------------------*/ + +#title { + top: 0px; + left: 0px; + position: absolute; +} + +#search { + float:left; + margin:0px 0px 0px 30px; +} + +#randomquote { + float:right; + margin:0px 30px 0px 0px; +} + +#copyright { + text-align:center; + padding:15px 0px 0px 0px; + margin:0px 0px 0px 0px; + clear:both; +} + +#bottomNav { + text-align:center; + margin:0px 0px 20px 0px; + padding:0px; +} + +#oldStuffNav { + font-weight:bold; + text-align:right; +} + ADDED example/www/markup.css Index: example/www/markup.css ================================================================== --- /dev/null +++ example/www/markup.css @@ -0,0 +1,299 @@ +/*-General-----------------------------------------------*/ + +body { + background-color:#ffffff; + color:#0f0f0f; +/* font-family:serif; */ + font-weight:normal; + text-decoration:none; + font-size:x-small; + voice-family:"\"}\""; + voice-family:inherit; + font-size:small; +} + +html>body { + font-size:small; +} + +.strong { + font-weight:bold; +} + +#red { + color: #ff0000 +} + +/*-Main Markup-------------------------------------------*/ + +#overall { + background-color: #ffffff; + color:#000000; +} + +/*-Left Column--------*/ + +.leftcolumn .node a { + color:#006666; + background-color:transparent; +} + +.leftcolumn .node p { + font-size:1.2em; + font-weight:normal; +} + +.leftcolumn .node h1 { + font-weight:normal; + font-size:1.2em; + color:#ffffff; + background-color:#000000; /* #005991; #7f9bff #006666; */ +} + +.leftcolumn .node h1 a { + color:#ffffff; + background-color:transparent; +} + +.leftcolumn .node h2 { + font-weight:bold; + font-size:.95em; +} + +.leftcolumn .node ul { + list-style-type:none; +} + +.leftcolumn .node li.more { + font-weight:bold; + font-size:.75em; +} + +.leftcolumn .node li.selected { + font-weight:bold; + font-size:1.18em; + color:#000000; + background-color:#cccccc; +} + +.leftcolumn .node li.selected a { + color:#000000; + background-color:transparent; +} + +/*-Center Column for classifieds-*/ + +.centercolumn .classifieds h1 { + font-family:Arial, Helvetica, serif; + font-weight:bold; + font-size:1.38em; + color:#000000; /* ffffff; */ + background: #5390b7; /* a6bcac; #0c1e0f; 043b0d; 1a6126; */ +} + +/*-Center Column------*/ +.centercolumn .node { +/* font-family:serif; */ +} + +.centercolumn .node a { + color:#006666; + background-color:transparent; +} + +.centercolumn .node h1 { + font-family:Arial, Helvetica, serif; + font-weight:bold; + font-size:1.38em; + color:#ffffff; + background:#000000; /* #005991; */ +} /* #006666 /* url('../images/slc.gif') no-repeat; */ + +.centercolumn .node h1 a { + color:#ffffff; + background-color:transparent; +} + +.centercolumn .node h2 { + font-weight:bold; + font-size:1.18em; +} + +.centercolumn .node h3 { + font-weight:bold; + font-size:.95em; +} + +.centercolumn .node h4 { + font-weight:normal; + font-size:1.2em; +} + +.centercolumn .node h4 a { + font-weight:bold; +} + +.centercolumn .node p { + font-weight:normal; +} + +.centercolumn .posts_0 h1 { + color:#ffffff; + background-color:#606060; + font-size:1.18em; +} + +.centercolumn .posts_1 h1 { + color:#ffffff; + background-color:#606060; + font-size:1.18em; +} + +.centercolumn .posts_2 h1 { + color:#ffffff; + background-color:#606060; + font-size:1.18em; +} + +.centercolumn .posts_3 h1 { + color:#ffffff; + background-color:#606060; + font-size:1.18em; +} + +.centercolumn .posts_4 h1 { + color:#ffffff; + background-color:#606060; + font-size:1.18em; +} + +.centercolumn .posts_5 h1 { + color:#ffffff; + background-color:#606060; + font-size:1.18em; +} + +.centercolumn .posts_6 h1 { + color:#ffffff; + background-color:#606060; + font-size:1.18em; +} + +.centercolumn .posts_7 h1 { + color:#ffffff; + background-color:#606060; + font-size:1.18em; +} + +.centercolumn .posts_8 h1 { + color:#ffffff; + background-color:#606060; + font-size:1.18em; +} + +.centercolumn .posts_9 h1 { + color:#ffffff; + background-color:#606060; + font-size:1.18em; +} + +.centercolumn .posts_10 h1 { + color:#ffffff; + background-color:#606060; + font-size:1.18em; +} + +/*-Right Column-------*/ + +.rightcolumn .node { + color:#000000; + background-color:#cccccc; + font-family:serif; +} + +.rightcolumn .node a { + color:#000000; /* #005991; #006666; */ + background-color:transparent; +} + +.rightcolumn .node h1 { + font-family:Arial, Helvetica, serif; + font-weight:bold; + font-size:0.95em; /* 1.38em; */ + color:#ffffff; + background-color: #000000; /* #005991; #006666; */ +} + +.rightcolumn .node h1 a { + color:#ffffff; + background-color:transparent; +} + +.rightcolumn .node h2 { + font-weight:bold; + font-size:.95em; +} + +.rightcolumn .node ul.none { + list-style-type:none; +} + +.rightcolumn .node ul.dot { + list-style-type:none; + /* list-style-image:url('../images/listdot.gif'); */ +} + +.rightcolumn .node ul.books { + list-style-type:disc; +} + +/*-OSDN Navagation bar-----------------------------------*/ + +#OSDNNavbar { + background-color:#999999; + color:#000000; /* #005991; /* #006666; */ +} + +#OSDNNavbar div#links { + background-color:#999999; + color:#000000; /* #005991; /* #006666; */ +} + +#OSDNNavbar a { + background-color: transparent; + color: #000000; /* #005991; /* #006666; */ +} + +/*-Remaining layout--------------------------------------*/ + +#randomquote { + font-size:1.2em; + font-style:italic; +} + +#copyright { + font-size:.75em; + font-family:Arial, Helvetica, serif; + background-color:transparent; + color:#000000; /* #005991; /* #006666; */ +} + +#copyright a { + background-color:transparent; + color:#000000; /* #005991; /* #006666; */ +} + +#bottomNav { + background-color:transparent; + color:#000000; /* #005991; /* #006666; */ +} + +#bottomNav a { + background-color:transparent; + color:#ffffff; +} + +#oldStuffNav { + font-weight:bold; +} + ADDED formdat.scm Index: formdat.scm ================================================================== --- /dev/null +++ formdat.scm @@ -0,0 +1,330 @@ +;; Copyright 2007-2008, Matthew Welland. +;; +;; This program is made available under the GNU GPL version 2.0 or +;; greater. See the accompanying file COPYING for details. +;; +;; This program is distributed WITHOUT ANY WARRANTY; without even the +;; implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +;; PURPOSE. + +(include "requirements.scm") + +(define formdat:*debug* #f) + +;; Old data format was something like this. BUT! +;; Forms do not have names so the hierarcy is +;; unnecessary (I think) +;; +;; hashtable +;; |-formname --> 'form-name=formname +;; | 'form-data=hashtable +;; | | name => value +;; +;; New data format is only the portion from above + +(define-class () + (form-data + )) + +(define-method (initialize (self ) initargs) + (call-next-method) + (slot-set! self 'form-data (make-hash-table)) + (initialize-slots self initargs)) + +(define-method (formdat:get (self ) key) + (hash-table-ref/default (slot-ref self 'form-data) key #f)) + +;; change to convert data to list and append val if already exists +;; or is a list +(define-method (formdat:set! (self ) key val) + (let ((prev-val (formdat:get self key)) + (ht (slot-ref self 'form-data))) + (if prev-val + (if (list? prev-val) + (hash-table-set! ht key (cons val prev-val)) + (hash-table-set! ht key (list val prev-val))) + (hash-table-set! ht key val)) + self)) + +(define-method (formdat:keys (self )) + (hash-table-keys (slot-ref self 'form-data))) + +(define-method (formdat:printall (self ) printproc) + (printproc "formdat:printall " (formdat:keys self)) + (for-each (lambda (k) + (printproc k " => " (formdat:get self k))) + (formdat:keys self))) + +(define-method (formdat:all->strings (self )) + (let ((res '())) + (for-each (lambda (k) + (set! res (cons (conc k "=>" (formdat:get self k)) res))) + (formdat:keys self)) + res)) + +;; call with *one* of the lists in the list of lists created by CGI:url-unquote +(define-method (formdat:load (self ) formlist) + (let ((ht (slot-ref self 'form-data))) + (if (null? formlist) self ;; no values provided, return self for no good reason + (let loop ((head (car formlist)) + (tail (cdr formlist))) + (let ((key (car head)) + (val (cdr head))) + ;; (err:log "key=" key " val=" val) + (if (> (length val) 1) + (formdat:set! self key val) + (formdat:set! self key (car val))) + (if (null? tail) self ;; we are done + (loop (car tail)(cdr tail)))))))) + +;; get the header from datstr +(define (formdat:read-header datstr) ;; datstr is an input string port + (let loop ((hs (read-line datstr)) + (header '())) + (if (or (eof-object? hs) + (string=? hs "")) + header + (loop (read-line datstr)(append header (list hs)))))) + +;; get the data up to the next key. if there is no key then return #f +;; return (dat remdat) +(define (formdat:read-dat dat key) + (let ((index (string-search-positions key dat))) + (if (or (not index) + (null? index)) ;; the key was not found + #f + (let* ((datstr (open-input-string dat)) + (result (read-string (caar index) datstr)) + (remdat (read-string #f datstr))) + (close-input-port datstr) + (list result remdat))))) + + ;; inp is port to read data from, maxsize is max data allowed to read (total) +(define (formdat:dat->list inp maxsize) + ;; read 1Meg chunks from the input port. If a block is not complete + ;; tack on the next 1Meg chunk as needed. Set up so the header is always + ;; at the beginning of the chunk + ;;-----------------------------29932024411502323332136214973 + ;;Content-Disposition: form-data; name="input-picture"; filename="breadfruit.jpg" + ;;Content-Type: image/jpeg + (let loop ((dat (read-string 1000000 inp)) + (res '()) + (siz 0)) + (if (> siz maxsize) + (begin + (print "DATA TOO BIG") + res) + (let* ((datstr (open-input-string dat)) + (header (formdat:read-header datstr)) + (key (if (not (null? header))(car header) #f)) + (remdat (read-string #f datstr)) ;; used in next line, discard if got data, else revert to + (alldat (if key (formdat:read-dat remdat key) #f)) ;; try to extract the data + (thsdat (if alldat (car alldat) #f)) ;; the data + (newdat (if alldat (cadr alldat) #f)) ;; left over data, must process ... + (thsres (list header thsdat)) ;; speculatively construct results + (newres (append res (list thsres)))) ;; speculatively construct results + (close-input-port datstr) + (cond + ;; either no header or single input + ((and (not alldat) + (or (null? header) + (not (string-match formdat:delim-patt-rex (car header))))) + ;; (print "Got here") + (cons (list header "") res)) ;; note use header as dat and use "" as header???? + ;; didn't find end key in this block + ((not alldat) + (let ((mordat (read-string 1000000 inp))) + (if (string=? mordat "") ;; there is no more data, discard results and use remdat as data, this input is broken + (cons (list header remdat) res) + (loop (string-append dat mordat) res (+ siz 2000000))))) ;; add the extra 1000000 + (alldat ;; got data, don't attempt to check if there is more, just loop and rely on (not alldat) to get more data + (loop newdat newres (+ siz 1000000)))))))) + +(define formdat:bin-data-disp-rex (regexp "^Content-Disposition:\\s+form-data;")) +(define formdat:bin-data-name-rex (regexp "\\Wname=\"([^\"]+)\"")) +(define formdat:bin-file-name-rex (regexp "\\Wfilename=\"([^\"]+)\"")) +(define formdat:bin-file-type-rex (regexp "Content-Type:\\s+([^\\s]+)")) +(define formdat:delim-patt-rex (regexp "^\\-+[0-9]+\\-*$")) + +;; returns a hash with entries for all forms - could well use a proplist? +(define (formdat:load-all) + (let ((request-method (getenv "REQUEST_METHOD"))) + (if (and request-method + (string=? request-method "POST")) + (formdat:load-all-port (current-input-port))))) + +;; (s:process-cgi-input (caaar dat)) +(define (formdat:load-all-port inp) + (let* ((formdat (make ))) +;; (debugp (open-output-file (conc (slot-ref s:session 'sroot) "/delme-" (current-user-id) ".log")))) + ;; (write-string (read-string #f inp) #f debugp) + (let ((alldats (formdat:dat->list inp 10e6))) + + ;; (format debugp "formdat : alldats: ~A\n" alldats) + (let ((firstitem (car alldats)) + (multipass #f)) + (if (not (null? firstitem)) + (if (string-match formdat:delim-patt-rex (caar firstitem)) + (set! multipass #t))) + (if multipass + ;; handle multi-part form + (for-each (lambda (datlst) + (let* ((header (formdat:extract-header-info (car datlst))) + (name (if (assoc 'name header) + (string->symbol (cadr (assoc 'name header))) + "")) ;; grumble + (fnamel (assoc 'filename header)) + (content (assoc 'content header)) + (dat (cadr datlst))) + ;; (print "header: " header " name: " name " fnamel: " fnamel " content: " content) ;; " dat: " (dat) + (formdat:set! formdat + name + (if fnamel + (list (cadr fnamel) + (if content + (cadr content) + "unknown") + (string->blob dat)) + dat)))) + alldats) + ;; handle single part form + ;; (if (and (string? name) + ;; (string=? name "")) ;; this is the short form input I guess + ;; (let* ((datstr (caar datlst)) + ;; (munged (s:process-cgi-input datstr))) + ;; (print "datstr: " datstr " munged: " munged) + (formdat:load formdat (s:process-cgi-input (caaar alldats)))) ;; munged)) + ;; (format debugp "formdat : name: ~A content: ~A\n" name content) + ;; (close-output-port debugp) + formdat)))) + +#| +(define inp (open-input-file "tests/example.post.in")) +(define dat (read-string #f inp)) +(define datstr (open-input-string dat)) + +;; or + +(define inp (open-input-file "tests/example.post.binary.in")) +(define dat (read-string #f inp)) +(define datstr (open-input-string dat)) + +(formdat:read-header datstr) + +(define dat (formdat:dat->list inp 10e6)) +(close-input-port inp) +|# + +(define (formdat:extract-header-info header) + (if (null? header) + '() + (let loop ((hed (car header)) + (tal (cdr header)) + (res '())) + (if (string-match formdat:bin-data-disp-rex hed) ;; + (let* ((data-namem (string-match formdat:bin-data-name-rex hed)) + (file-namem (string-match formdat:bin-file-name-rex hed)) + (data-name (if data-namem (cadr data-namem) #f)) + (this (if file-namem + (list (list 'name data-name)(list 'filename (cadr file-namem))) + (list (list 'name data-name))))) + (if (null? tal) + (append res this) + (loop (car tal)(cdr tal)(append res this)))) + (let ((content (string-match formdat:bin-file-type-rex hed))) ;; this is the stanza for the content type + (if content + (let ((newres (cons (list 'content (cadr content)) res))) + (if (null? tal) + newres + (loop (car tal)(cdr tal) newres))) + (if (null? tal) + res + (loop (car tal)(cdr tal) res) + ))))))) + +;; (let loop ((l (read-line)) ;; (if (eq? mode 'norm)(read-line)(read-char))) +;; (endline #f) +;; (num 0)) +;; ;; (format debugp "~A\n" l) +;; (if (or (not (eof-object? l)) +;; (not (and (eq? mode 'bin) +;; (string=? l "")))) ;; if in bin mode empty string is end of file +;; (case mode +;; ((start) +;; (set! mode 'norm) +;; (if (string-match delim-patt-rex l) +;; (begin +;; (set! delim-string l) +;; (set! delim-len (string-length l)) +;; (loop (read-line) #f 0)) +;; (loop l #f 0))) +;; ((norm) +;; ;; I don't like how this gets checked on every single input. Must be a better way. FIXME +;; (if (and (string-match bin-data-disp-rex l) +;; (string-match bin-data-name-rex l) +;; (string-match bin-file-name-rex l)) +;; (begin +;; (set! data-name (cadr (string-match bin-data-name-rex l))) +;; (set! file-name (cadr (string-match bin-file-name-rex l))) +;; (set! mode 'content) +;; (loop (read-line) #f num))) +;; (let* ((dat (s:process-cgi-input l))) ;; (CGI:url-unquote l)) +;; (format debugp "PROCESS-CGI-INPUT: ~A\n" (intersperse dat ",")) +;; (formdat:load formdat dat) +;; (loop (read-line) #f num))) +;; ((content) +;; (if (string-match bin-file-type-rex l) +;; (begin +;; (set! mode 'bin) +;; (set! data-type (cadr (string-match bin-file-type-rex l))) +;; (loop (read-string 1) #f num)))) +;; ((bin) +;; ;; delim-string: \n"---------------12345" +;; ;; 012345678901234567890 +;; ;; endline: "---------------12" +;; ;; l = "3" +;; ;; delim-len = 20 +;; ;; (substring "---------------12345" 17 18) => "3" +;; ;; +;; (cond +;; ;; haven't found the start of an endline, is the next char a newline? +;; ((and (not endline) +;; (string=? l "\n")) ;; required first character +;; (let ((newendline (open-output-string))) +;; ;; (write-line l newendline) ;; discard the newline. add it back if don't have a lock on delim-string +;; (loop (read-string 1) newendline (+ num 1)))) +;; ((not endline) +;; (write-string l #f bin-dat) +;; (loop (read-string 1) #f (+ num 1))) +;; ;; string so far matches delim-string +;; (endline +;; (let* ((endstr (get-output-string endline)) +;; (endlen (string-length endstr))) +;; (if (> endlen 0) +;; (format debugp " delim: ~A\nendstr: ~A\n" delim-string endstr)) +;; (if (and (> delim-len endlen) +;; (string=? l (substring delim-string endlen (+ endlen 1)))) +;; ;; yes, this character matches the next in the delim-string +;; (if (eq? delim-len endlen) ;; have a match! Ignore that a newline is required. Lazy bugger. +;; (let* ((fn (string->symbol data-name))) +;; (formdat:set! formdat fn (list file-name data-type (string->blob (get-output-string bin-dat)))) +;; (set! mode 'norm) +;; (loop (read-line) #f 0)) +;; (begin +;; (write-string l #f endline) +;; (loop (read-string 1) endline (+ num 1)))) +;; ;; no, this character does NOT match the next in line in delim-string +;; (begin +;; (write-string "\n" #f bin-dat) ;; don't forget that newline we dropped +;; (write-string endstr #f bin-dat) +;; (write-string l #f bin-dat) +;; (loop (read-string 1) #f (+ num 1)))))))) +;; ))))) + +;; (formdat:printall formdat (lambda (x)(write-line x debugp))) + +#| +(define inp (open-input-file "/tmp/stmlrun/delme-33.log.keep-for-ref")) +(define dat (read-string #f inp)) +(close-input-port inp) +|# ADDED html-filter.scm Index: html-filter.scm ================================================================== --- /dev/null +++ html-filter.scm @@ -0,0 +1,190 @@ +;; Copyright 2007-2008, Matthew Welland. +;; +;; This program is made available under the GNU GPL version 2.0 or +;; greater. See the accompanying file COPYING for details. +;; +;; This program is distributed WITHOUT ANY WARRANTY; without even the +;; implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +;; PURPOSE. + +;; +(define (s:split-string strng delim) + (if (eq? (string-length strng) 0) (list strng) + (let loop ((head (make-string 1 (car (string->list strng)))) + (tail (cdr (string->list strng))) + (dest '()) + (temp "")) + (cond ((equal? head delim) + (set! dest (append dest (list temp))) + (set! temp "")) + ((null? head) + (set! dest (append dest (list temp)))) + (else (set! temp (string-append temp head)))) ;; end if + (cond ((null? tail) + (set! dest (append dest (list temp))) dest) + (else (loop (make-string 1 (car tail)) (cdr tail) dest temp)))))) + +;; allowed-tags is a list of tags as symbols: +;; '(a b center p a) +;; parsing is simplistic and the response conservative +;; if a < is found without the tag and closing > then +;; the < or > is replaced with < or > without +;; even trying hard to figure out if there is a legit tag +;; buried in the text somewhere. +;; a list of strings is returned. +;; +;; NOTES +;; 1. case is important in the allowed-tags list! +;; 2. only "solid" tags are supported i.e. will not work? +;; + +;; (s:cgi-out (eval (s:output (s:html-filter "hellogoodbye eh" '(a b i)))) + +;; strategy +;; 1. convert \n to +;; 2. Split on "<" +;; 3. Split on ">" +;; 4. Fix +(define (s:html-filter input-text allowed-tags) + (let* ((toks (s:str->toks input-text)) + (tmp (s:toks->stml '(s:null) #f toks allowed-tags)) + (res (car tmp)) + (nxttag (cadr tmp)) + (rem (caddr tmp))) + res)) + +(define (s:html-filter->string input-text allowed-tags) + (let ((ostr (open-output-string))) + ;;; (s:output-new ostr (s:html-filter input-text allowed-tags)) + (s:output-new ostr (car (eval (s:html-filter input-text allowed-tags)))) + (get-output-string ostr))) + +;; (if (null? rem) +;; res '()) +;; (s:toks->stml (if (list? res) res '()) #f rem allowed-tags)))) + +(define (s:str->toks str) + (apply append (map (lambda (tok) + (intersperse (s:split-string tok ">") ">")) + (intersperse (s:split-string str "<") "<")))) + +(define (s:tag->stml tag) + (string->symbol (string-append "s:" (symbol->string tag)))) + + +(define (s:toks->stml res tag rem allowed) + ;; (print "tag: " tag " rem: " rem) + (if (null? rem) + (list (append res (if tag + (list (s:tag->stml tag)) + '())) #f '() allowed) ;; the case of a lone tag + ;; handle a starting tag + (let* ((tmp (s:upto-tag rem allowed)) + (txt (car tmp)) ;; this txt goes with tag!!! + (nexttag (cadr tmp)) ;; this is the NEXT DAMN tag! + (begin-tag (caddr tmp)) + (newrem (cadddr tmp))) + ;; (print "txt: " txt "\nnexttag: " nexttag "\nbegin-tag: " begin-tag "\nnewrem: " newrem "\nres: " res "\n") + (if begin-tag ;; nest the following stuff + (let* ((childdat (s:toks->stml '() nexttag newrem allowed)) + (child (car childdat)) + (newtag (cadr childdat)) + (newrem2 (caddr childdat)) + (allowed (cadddr childdat))) ;; ya, it shouldn't have changed + (if tag + (s:toks->stml (append res (list (append (list (s:tag->stml tag)) child (list txt)))) + newtag newrem2 allowed) + (s:toks->stml (append res (list txt) child) + newtag newrem2 allowed))) + ;; it must have been an end tag + (list (append res (list + (if tag + (list (s:tag->stml tag) txt) + txt))) + #f + newrem + allowed))))) + + +;; "<" "b" ">" => "" +;; "<" +;; (define (s:rebuild-tags input-list) + +;; ("blah blah" "<" "b" ">" "more stuff" "<" "i" ">" ) +;; => ("blah blah" b #t ( "more stuff" "<" "i" ">" )) +;; ("blah blah" "<" "/b" ">" "more stuff" "<" "i" ">" ) +;; => ("blah blah" b #f ( "more stuff" "<" "i" ">" )) +(define (s:upto-tag inlst allowed-tags) + (if (null? inlst) inlst + (let loop ((tok (car inlst)) + (tail (cdr inlst)) + (prel "")) ;; create a string or a list of string parts? + (if (string=? tok "<") ;; might have a tag + (if (> (length tail) 1) ;; to be a tag, need tag and closing ">" + (let ((tag (car tail)) + (end (cadr tail)) + (rem (cddr tail))) + (if (string=? end ">") ;; yep, it is probably a tag + (let* ((trim-tag (if (string=? "/" (substring tag 0 1)) + (substring tag 1 (string-length tag)) #f)) + (tag-sym (string->symbol (if trim-tag trim-tag tag)))) + (if (member tag-sym allowed-tags) + ;; have a valid tag, rebuild it and return the result + (list prel tag-sym (if trim-tag #f #t) rem) + ;; not a valid tag, convert "<" and ">" and add all to prel + (let ((newprel (string-append prel "<" tag ">"))) + (if (null? rem)(list newprel #f #f '()) ;; return newprel - add #f #f ??? + (loop (car rem)(cdr rem) newprel))))) + ;; so, it wasn't a tag + (let ((newprel (string-append prel "<" tag))) + (if (null? tail) + (list newprel #f #f '()) + (loop (car rem)(cdr rem) newprel))))) + ;; too short to be a tag + (list (apply string-append prel "<" tail) #f #f '())) + (if (null? tail) + ;; we're done + (list (string-append prel tok) #f #f '()) + (loop (car tail)(cdr tail)(string-append prel tok))))))) + + +(define (s:divy-up-cgi-str instr) + (map (lambda (x) (string-split x "=")) (string-split instr "&"))) + +(define (s:decode-str instr) + (let* ((abc (string-substitute "\\+" " " instr #t)) + (toks (s:split-string abc "%"))) + (if (< (length toks) 2) abc + (let loop ((head (cadr toks)) + (tail (cddr toks)) + (result (car toks))) + (if (string=? head "") + (if (null? tail) + result + (loop (car tail)(cdr tail) result)) + (let* ((key (substring head 0 2)) + (rem (substring head 2 (string-length head))) + (num (string->number key 16)) + (ch (if (exact? num) + (integer->char num) + #f)) ;; this is an error. I will probably regret this some day + (chstr (if ch (make-string 1 ch) "")) + (newres (if ch + (string-append result chstr rem) + (string-append result head)))) + ;; (print "head: " head " num: " num " ch: |" ch "| chstr: " chstr) + (if (null? tail) + newres + (loop (car tail)(cdr tail) newres)))))))) + +(define (s:process-cgi-input instr) + (map (lambda (xy) + (list (string->symbol (s:decode-str (car xy))) + (if (eq? (length xy) 1) + "" + (s:decode-str (cadr xy))))) + (s:divy-up-cgi-str instr))) + +;; for testing -- deletme +;; (define blah "post_title=%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2Bhello-------------+++++++++++%26%26%26%26%26%26%26%26%26%40%40%40%40%40%40%40%40%40&post_body=%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2Bhello-------------+++++++++++%26%26%26%26%26%26%26%26%26%40%40%40%40%40%40%40%40%40%0D%0A%0D%0A%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2Bhello-------------+++++++++++%26%26%26%26%26%26%26%26%26%40%40%40%40%40%40%40%40%40%0D%0A%0D%0A%0D%0A%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2Bhello-------------+++++++++++%26%26%26%26%26%26%26%26%26%40%40%40%40%40%40%40%40%40&new_post=Submit") +;; (define blah2 "post_title=5%25&post_body=and+10%25&new_post=Submit") ADDED install.cfg.template Index: install.cfg.template ================================================================== --- /dev/null +++ install.cfg.template @@ -0,0 +1,6 @@ + +TARGDIR=/usr/lib/cgi-bin +LOGDIR=/tmp/stmlrun +SQLITE3=/usr/bin/sqlite3 +# this was needed on the nokia n800 :-) +# SQLITE3=/tmp/sqlite3 ADDED keystore.scm Index: keystore.scm ================================================================== --- /dev/null +++ keystore.scm @@ -0,0 +1,25 @@ +;; Copyright 2007-2008, Matthew Welland. +;; +;; This program is made available under the GNU GPL version 2.0 or +;; greater. See the accompanying file COPYING for details. +;; +;; This program is distributed WITHOUT ANY WARRANTY; without even the +;; implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +;; PURPOSE. + +;;====================================================================== +;; The meta data key store, just a general dumping ground for values +;; only used occasionally +;;====================================================================== + +(define (keystore:get db key) + (dbi:get-one db "SELECT value FROM metadata WHERE key=?;" key)) + +(define (keystore:set! db key value) + (let ((curr-val (keystore:get db key))) + (if curr-val + (dbi:exec db "UPDATE metadata SET value=? WHERE key=?;" value key) + (dbi:exec db "INSERT INTO metadata (key,value) VALUES (?,?);" key value)))) + +(define (keystore:del! db key) + (dbi:exec db "DELETE FROM metadata WHERE key=?;" key)) ADDED misc-stml.scm Index: misc-stml.scm ================================================================== --- /dev/null +++ misc-stml.scm @@ -0,0 +1,279 @@ +;; Copyright 2007-2008, Matthew Welland. +;; +;; This program is made available under the GNU GPL version 2.0 or +;; greater. See the accompanying file COPYING for details. +;; +;; This program is distributed WITHOUT ANY WARRANTY; without even the +;; implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +;; PURPOSE. + +;;====================================================================== +;; dumbobj helpers +;;====================================================================== + +;; given a list of symbols give the count of the matching symbol +;; l => '(a b c) (dumobj:indx a 'b) => 1 +(define (s:get-fieldnum lst field-name) + (let loop ((head (car lst)) + (tail (cdr lst)) + (fnum 0)) + (if (eq? head field-name) fnum + (if (null? tail) #f + (loop (car tail)(cdr tail)(+ fnum 1)))))) + +(define (s:fields->string lst) + (string-join (map symbol->string lst) ",")) + +(define (s:vector-get-field vec field field-list) + (vector-ref vec (s:get-fieldnum field-list field))) + +;;====================================================================== +;; +;;====================================================================== + +(define (err:log . msg) + (with-output-to-port (current-error-port) ;; (slot-ref self 'logpt) + (lambda () + (apply print msg)))) + +(define (s:tidy-url url) + (if url + (let ((r1 (regexp "^http:\\/\\/")) + (r2 (regexp "^[ \\t]*$"))) ;; blank + (if (string-match r1 url) url + (if (string-match r2 url) #f ;; convert a blank to #f + (conc "http://" url)))) + url)) + +(define (s:lazy->num num) + (if (number? num) num + (if (string->number num) (string->number num) + (if num 1 0)))) ;; wierd eh! yep, #f=>0 #t=>1 + +;;====================================================================== +;; D B +;;====================================================================== + +;; convert values to appropriate strings +;; +(define (s:sqlparam-val->string val) + (cond + ((list? val)(string-join (map symbol->string val) ",")) ;; (a b c) => a,b,c + ((string? val)(conc "'" (dbi:escape-string val) "'")) + ((number? val)(number->string val)) + ((symbol? val)(dbi:escape-string (symbol->string val))) + ((boolean? val) + (if val "TRUE" "FALSE")) ;; should this be "TRUE" or 1? + ;; should this be "FALSE" or 0 or NULL? + (else + (err:log "sqlparam: unknown type for value: " val) + ""))) + +;; (sqlparam "INSERT INTO foo(name,age) VALUES(?,?);" "bob" 20) +;; NB// 1. values only!! +;; 2. terminating semicolon required (used as part of logic) +;; +;; a=? 1 (number) => a=1 +;; a=? 1 (string) => a='1' +;; a=? #f => a=FALSE +;; a=? a (symbol) => a=a +;; +(define (s:sqlparam query . args) + (let* ((query-parts (string-split query "?")) + (num-parts (length query-parts)) + (num-args (length args))) + (if (not (= (+ num-args 1) num-parts)) + (err:log "ERROR, sqlparam: wrong number of arguments or missing semicolon, " num-args " for query " query) + (if (= num-args 0) query + (let loop ((section (car query-parts)) + (tail (cdr query-parts)) + (result "") + (arg (car args)) + (argtail (cdr args))) + (let* ((valstr (s:sqlparam-val->string arg)) + (newresult (conc result section valstr))) + (if (null? argtail) ;; we are done + (conc newresult (car tail)) + (loop + (car tail) + (cdr tail) + newresult + (car argtail) + (cdr argtail))))))))) + +;; random string stuff +(define (s:string-downcase str) + (if (string? str) + (string-translate str "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz") + str)) + +;; (define session:valid-chars "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") +(define session:valid-chars "abcdefghijklmnopqrstuvwxyz0123456789") ;; cookies are case insensitive. +(define session:num-valid-chars (string-length session:valid-chars)) + +(define (session:get-nth-char nth) + (substring session:valid-chars nth (+ nth 1))) + +(define (session:get-rand-char) + (session:get-nth-char (random session:num-valid-chars))) + +(define (session:make-rand-string len) + (let loop ((res "") + (n 1)) + (if (> n len) res + (loop (string-append res (session:get-rand-char)) + (+ n 1))))) + +;; openssl passwd -crypt -salt xx password +;; +(define (s:crypt-passwd pw s) + (let* ((salt (if s s (session:make-rand-string 2))) + (inp (open-input-pipe + ;;(string-append "echo " pw " | mkpasswd -S " salt " -s"))) + (conc "mkpasswd " pw " " salt))) + (res (read-line inp))) + (close-input-port inp) + res)) + +(define (s:password-match? password crypted) + (let* ((salt (substring crypted 0 2)) + (pcrypted (s:crypt-passwd password salt))) + (string=? pcrypted crypted))) + +;; (read-line (open-input-pipe "echo foo | mkpasswd -S ab -s")) + +(define (s:error-page . err) + (s:cgi-out (cons "Content-type: text/html; charset=iso-8859-1\n\n" + (s:html (s:head + (s:title err) + (s:body + (s:h1 "ERROR") + (s:p err))))))) + +(define (s:validate-uri) + (let ((uri (getenv "REQUEST_URI")) + (qrs (getenv "QUERY_STRING"))) + (if (not uri) + (set! uri qrs)) + (if uri + (string-match + (regexp "^(/[a-z\\-\\._:0-9]*)*(|\\?([A-Za-z0-9_\\-\\+]+=[A-Za-z0-9_\\-\\.\\+]*&{0,1})*)$") uri) + (begin + (s:log "REQUEST URI NOT AVAILABLE!") + (let ((p (open-input-pipe "env"))) + (let loop ((l (read-line p)) + (res '())) + (if (eof-object? l) + (s:log res) + (loop (read-line p)(cons (list l "
") res))))) + #t)))) + +(define (s:validate-inputs) + (if (not (s:validate-uri))(begin (s:error-page "Bad URI" (let ((ref (getenv "HTTP_REFERER"))) + (if ref + (list "referred from" ref) + ""))) + (exit)))) + +;; anything except a list is converted to a string!!! +(define (s:any->string val) + (cond + ((string? val) val) + ((number? val) (number->string val)) + ((symbol? val) (symbol->string val)) + ((eq? val #f) "") + ((eq? val #t) "TRUE") + ((list? val) val) + (else + (let ((ostr (open-output-string))) + (with-output-to-port ostr + (lambda () + (display val))) + (get-output-string ostr))))) + +(define (s:any->number val) + (cond + ((number? val) val) + ((string? val) (string->number val)) + ((symbol? val) (string->number (symbol->string val))) + (else #f))) + +;; string is a string and non-zero length +(define (misc:non-zero-string str) + (if (and (string? str) + (> (string-length str) 0)) + str + #f)) + +;;====================================================================== +;; P A R A M S +;;====================================================================== + +;; input: 'a ('a "val a" 'b "val b") => "val a" +(define (s:find-param key param-lst) + (let loop ((head (car param-lst)) + (tail (cdr param-lst))) + (if (eq? head key) + (car tail) + (if (< (length tail) 2) #f + (loop (cadr tail)(cddr tail)))))) + +(define (s:param->string param) + (conc (symbol->string (car param)) "=" "\"" (cadr param) "\"")) + +;; remove 'foo "bar" from ('foo "bar" 'bar "foo") +(define (s:remove-param-matching params key) + (if (= (length params) 0)'() ;; proper params list >= 2 items + (let loop ((head (car params)) + (tail (cdr params)) + (result '())) + (if (symbol? head) ;; symbols have params + (let ((val (car tail)) + (newtail (cdr tail))) + (if (eq? head key) ;; get rid of this one + (if (null? newtail) result + (loop (car newtail)(cdr newtail) result)) + (let ((newresult (append result (list head val)))) + (if (null? newtail) newresult + (loop (car newtail)(cdr newtail) newresult))))) + (let ((newresult (append result (list head)))) + (if (null? tail) newresult + (loop (car tail)(cdr tail) newresult))))))) + +(define (session:get-param-from params key) + (let ((r1 (regexp (conc "^" (s:any->string key) "=(.*)$")))) + (if (null? params) #f + (let loop ((head (car params)) + (tail (cdr params))) + (let ((match (string-match r1 head))) + (if match + (list-ref match 1) + (if (null? tail) #f + (loop (car tail)(cdr tail))))))))) + +(define (s:process-params params) + (if (null? params) "" + (let loop ((res "") + (head (car params)) + (tail (cdr params))) + (if (null? tail) + (conc res " " (s:param->string head)) + (loop + (conc res " " (s:param->string head)) + (car tail) + (cdr tail)))))) + +;; remove key=var from (key=var key1=var1 key2=var2 ...) +(define (k=v-params:remove-matching params key) + (if (= (length params) 0) params + (let ((r1 (regexp (conc "^" key "=")))) + (let loop ((head (car params)) + (tail (cdr params)) + (result '())) + (if (string-match r1 head) + (if (null? tail) result + (loop (car tail)(cdr tail) result)) + (let ((newlst (cons head result))) + (if (null? tail) newlst + (loop (car tail)(cdr tail) newlst)))))))) + ADDED modules/twiki/Makefile Index: modules/twiki/Makefile ================================================================== --- /dev/null +++ modules/twiki/Makefile @@ -0,0 +1,10 @@ + +twiki.l.scm : twiki.l + csi -batch -eval '(use silex)(if (lex "twiki.l" "twiki.l.scm")(exit 0)(exit 1))' + +test-silex : twiki.l.scm test-silex.scm + csc test-silex.scm + +twikicount : twiki.l.scm twikicount.scm + csc twikicount.scm + ADDED modules/twiki/misc-notes.txt Index: modules/twiki/misc-notes.txt ================================================================== --- /dev/null +++ modules/twiki/misc-notes.txt @@ -0,0 +1,46 @@ +#| +telnet localhost 80 +GET cgi-bin/kiatoa/twiki?image=4&wiki_key=bG9jYXRpb25zIHdvcmxk HTTP/1.1 +Accept: */* +Accept-Language: en-us +Connection: Keep-Alive +Host: localhost +Referer: http://localhost/links.asp +User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0) +Accept-Encoding: gzip, deflate + +GET /kiatoa/images/kiatoa.png HTTP/1.1 +Accept: */* +Accept-Language: en-us +Connection: Keep-Alive +Host: localhost +Referer: http://localhost/links.asp + +GET index.html HTTP/1.1 +Accept: */* +Accept-Language: en-us +Connection: Keep-Alive +Host: localhost +Referer: http://localhost/links.asp + +GET /cgi-bin/kiatoa/twiki?image=2&wiki_key=bG9jYXRpb25zIHdvcmxk HTTP/1.1 +Accept: */* +Accept-Language: en-us +Connection: Keep-Alive +Host: localhost +Referer: http://192.168.2.1/cgi-bin/kiatoa/location/?twiki_maint=2 +User-Agent: Mozilla/4.0 +Accept-Encoding: gzip, deflate + +HTTP/1.1 200 OK +Date: Tue, 01 Sep 2009 02:18:16 GMT +Server: Apache/2.2.11 (Ubuntu) PHP/5.2.6-3ubuntu4.2 with Suhosin-Patch +Last-Modified: Sun, 19 Jul 2009 02:47:52 GMT +ETag: "a38005-12c2-46f060c330600" +Accept-Ranges: bytes +Content-Length: 4802 +Keep-Alive: timeout=15, max=100 +Connection: Keep-Alive +Content-Type: image/png + +|# ADDED modules/twiki/tlayout.css Index: modules/twiki/tlayout.css ================================================================== --- /dev/null +++ modules/twiki/tlayout.css @@ -0,0 +1,172 @@ +/*{{{*/ +* html .tiddler {height:1%;} + +body {font-size:.75em; font-family:arial,helvetica; margin:0; padding:0;} + +h1,h2,h3,h4,h5,h6 {font-weight:bold; text-decoration:none;} +h1,h2,h3 {padding-bottom:1px; margin-top:1.2em;margin-bottom:0.3em;} +h4,h5,h6 {margin-top:1em;} +h1 {font-size:1.35em;} +h2 {font-size:1.25em;} +h3 {font-size:1.1em;} +h4 {font-size:1em;} +h5 {font-size:.9em;} + +hr {height:1px;} + +a {text-decoration:none;} + +dt {font-weight:bold;} + +ol {list-style-type:decimal;} +ol ol {list-style-type:lower-alpha;} +ol ol ol {list-style-type:lower-roman;} +ol ol ol ol {list-style-type:decimal;} +ol ol ol ol ol {list-style-type:lower-alpha;} +ol ol ol ol ol ol {list-style-type:lower-roman;} +ol ol ol ol ol ol ol {list-style-type:decimal;} + +.txtOptionInput {width:11em;} + +#contentWrapper .chkOptionInput {border:0;} + +.externalLink {text-decoration:underline;} + +.indent {margin-left:3em;} +.outdent {margin-left:3em; text-indent:-3em;} +code.escaped {white-space:nowrap;} + +.tiddlyLinkExisting {font-weight:bold;} +.tiddlyLinkNonExisting {font-style:italic;} + +/* the 'a' is required for IE, otherwise it renders the whole tiddler in bold */ +a.tiddlyLinkNonExisting.shadow {font-weight:bold;} + +#mainMenu .tiddlyLinkExisting, + #mainMenu .tiddlyLinkNonExisting, + #sidebarTabs .tiddlyLinkNonExisting {font-weight:normal; font-style:normal;} +#sidebarTabs .tiddlyLinkExisting {font-weight:bold; font-style:normal;} + +.header {position:relative;} +.header a:hover {background:transparent;} +.headerShadow {position:relative; padding:4.5em 0em 1em 1em; left:-1px; top:-1px;} +.headerForeground {position:absolute; padding:4.5em 0em 1em 1em; left:0px; top:0px;} + +.siteTitle {font-size:3em;} +.siteSubtitle {font-size:1.2em;} + +#mainMenu {position:absolute; left:0; width:10em; text-align:right; line-height:1.6em; padding:1.5em 0.5em 0.5em 0.5em; font-size:1.1em;} + +#sidebar {position:absolute; right:3px; width:16em; font-size:.9em;} +#sidebarOptions {padding-top:0.3em;} +#sidebarOptions a {margin:0em 0.2em; padding:0.2em 0.3em; display:block;} +#sidebarOptions input {margin:0.4em 0.5em;} +#sidebarOptions .sliderPanel {margin-left:1em; padding:0.5em; font-size:.85em;} +#sidebarOptions .sliderPanel a {font-weight:bold; display:inline; padding:0;} +#sidebarOptions .sliderPanel input {margin:0 0 .3em 0;} +#sidebarTabs .tabContents {width:15em; overflow:hidden;} + +.wizard {padding:0.1em 1em 0em 2em;} +.wizard h1 {font-size:2em; font-weight:bold; background:none; padding:0em 0em 0em 0em; margin:0.4em 0em 0.2em 0em;} +.wizard h2 {font-size:1.2em; font-weight:bold; background:none; padding:0em 0em 0em 0em; margin:0.4em 0em 0.2em 0em;} +.wizardStep {padding:1em 1em 1em 1em;} +.wizard .button {margin:0.5em 0em 0em 0em; font-size:1.2em;} +.wizardFooter {padding:0.8em 0.4em 0.8em 0em;} +.wizardFooter .status {padding:0em 0.4em 0em 0.4em; margin-left:1em;} +.wizard .button {padding:0.1em 0.2em 0.1em 0.2em;} + +#messageArea {position:fixed; top:2em; right:0em; margin:0.5em; padding:0.5em; z-index:2000; _position:absolute;} +.messageToolbar {display:block; text-align:right; padding:0.2em 0.2em 0.2em 0.2em;} +#messageArea a {text-decoration:underline;} + +.tiddlerPopupButton {padding:0.2em 0.2em 0.2em 0.2em;} +.popupTiddler {position: absolute; z-index:300; padding:1em 1em 1em 1em; margin:0;} + +.popup {position:absolute; z-index:300; font-size:.9em; padding:0; list-style:none; margin:0;} +.popup .popupMessage {padding:0.4em;} +.popup hr {display:block; height:1px; width:auto; padding:0; margin:0.2em 0em;} +.popup li.disabled {padding:0.4em;} +.popup li a {display:block; padding:0.4em; font-weight:normal; cursor:pointer;} +.listBreak {font-size:1px; line-height:1px;} +.listBreak div {margin:2px 0;} + +.tabset {padding:1em 0em 0em 0.5em;} +.tab {margin:0em 0em 0em 0.25em; padding:2px;} +.tabContents {padding:0.5em;} +.tabContents ul, .tabContents ol {margin:0; padding:0;} +.txtMainTab .tabContents li {list-style:none;} +.tabContents li.listLink { margin-left:.75em;} + +#contentWrapper {display:block;} +#splashScreen {display:none;} + +#displayArea {margin:1em 17em 0em 14em;} + +.toolbar {text-align:right; font-size:.9em;} + +.tiddler {padding:1em 1em 0em 1em;} + +.missing .viewer,.missing .title {font-style:italic;} + +.title {font-size:1.6em; font-weight:bold;} + +.missing .subtitle {display:none;} +.subtitle {font-size:1.1em;} + +.tiddler .button {padding:0.2em 0.4em;} + +.tagging {margin:0.5em 0.5em 0.5em 0; float:left; display:none;} +.isTag .tagging {display:block;} +.tagged {margin:0.5em; float:right;} +.tagging, .tagged {font-size:0.9em; padding:0.25em;} +.tagging ul, .tagged ul {list-style:none; margin:0.25em; padding:0;} +.tagClear {clear:both;} + +.footer {font-size:.9em;} +.footer li {display:inline;} + +.annotation {padding:0.5em; margin:0.5em;} + +* html .viewer pre {width:99%; padding:0 0 1em 0;} +.viewer {line-height:1.4em; padding-top:0.5em;} +.viewer .button {margin:0em 0.25em; padding:0em 0.25em;} +.viewer blockquote {line-height:1.5em; padding-left:0.8em;margin-left:2.5em;} +.viewer ul, .viewer ol {margin-left:0.5em; padding-left:1.5em;} + +.viewer table, table.twtable {border-collapse:collapse; margin:0.8em 1.0em;} +.viewer th, .viewer td, .viewer tr,.viewer caption,.twtable th, .twtable td, .twtable tr,.twtable caption {padding:3px;} +table.listView {font-size:0.85em; margin:0.8em 1.0em;} +table.listView th, table.listView td, table.listView tr {padding:0px 3px 0px 3px;} + +.viewer pre {padding:0.5em; margin-left:0.5em; font-size:1.2em; line-height:1.4em; overflow:auto;} +.viewer code {font-size:1.2em; line-height:1.4em;} + +.editor {font-size:1.1em;} +.editor input, .editor textarea {display:block; width:100%; font:inherit;} +.editorFooter {padding:0.25em 0em; font-size:.9em;} +.editorFooter .button {padding-top:0px; padding-bottom:0px;} + +.fieldsetFix {border:0; padding:0; margin:1px 0px 1px 0px;} + +.sparkline {line-height:1em;} +.sparktick {outline:0;} + +.zoomer {font-size:1.1em; position:absolute; overflow:hidden;} +.zoomer div {padding:1em;} + +* html #backstage {width:99%;} +* html #backstageArea {width:99%;} +#backstageArea {display:none; position:relative; overflow: hidden; z-index:150; padding:0.3em 0.5em 0.3em 0.5em;} +#backstageToolbar {position:relative;} +#backstageArea a {font-weight:bold; margin-left:0.5em; padding:0.3em 0.5em 0.3em 0.5em;} +#backstageButton {display:none; position:absolute; z-index:175; top:0em; right:0em;} +#backstageButton a {padding:0.1em 0.4em 0.1em 0.4em; margin:0.1em 0.1em 0.1em 0.1em;} +#backstage {position:relative; width:100%; z-index:50;} +#backstagePanel {display:none; z-index:100; position:absolute; width:90%; margin:0em 3em 0em 3em; padding:1em 1em 1em 1em;} +.backstagePanelFooter {padding-top:0.2em; float:right;} +.backstagePanelFooter a {padding:0.2em 0.4em 0.2em 0.4em;} +#backstageCloak {display:none; z-index:20; position:absolute; width:100%; height:100px;} + +.whenBackstage {display:none;} +.backstageVisible .whenBackstage {display:block;} +/*}}}*/ ADDED modules/twiki/twiki-mod.scm Index: modules/twiki/twiki-mod.scm ================================================================== --- /dev/null +++ modules/twiki/twiki-mod.scm @@ -0,0 +1,999 @@ +;; Copyright 2007-2010, Matthew Welland. +;; +;; This program is made available under the GNU GPL version 2.0 or +;; greater. See the accompanying file COPYING for details. +;; +;; This program is distributed WITHOUT ANY WARRANTY; without even the +;; implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +;; PURPOSE. + +;; twiki module +(require-extension sqlite3 regex posix md5 base64) + +;; TODO +;; +;; * Inline tiddlers [inline[TiddlerName]] +;; * Pics [pic X Y[picname.jpg]] +;; * Move twiki parsing/expanding to mattsutils as loadable module + +;; Routines intended to be overridden by end users +;; (twiki:access keys wiki-name user-id) +;; search the code for "override" for more. + +;; This is the currently supported mechanism. Postgres will be added later -mrw- 7/26/2009 +;; +(define (twiki:open-db key . create-not-ok) + ;; (s:log "Got to twiki:open-db with key: " key) + (let* ((create-ok (if (null? create-not-ok) #t (car create-not-ok))) + (fdat (twiki:key->fname key)) + (basepath (slot-ref s:session 'twikidir)) + (fpath (car fdat)) + (fname (cadr fdat)) + (fullname (conc basepath "/" fpath "/" fname)) + (fexists (file-exists? fullname)) + (db (if fexists (dbi:open 'sqlite3 (list (cons 'dbname fullname))) #f))) + (if (and (not db) + (not create-ok)) + (exit 100) + (begin + (if (not fexists) + (begin + ;; (print "fullname: " fullname) + (twiki:register-wiki key fullname) + (system (conc "mkdir -p " fpath)) ;; create the path + (set! db (dbi:open 'sqlite3 (list (cons 'dbname fullname)))) + (for-each + (lambda (sqry) + ;; (print sqry) + (dbi:exec db sqry)) + ;; types: 0 text, 1 jpg, 2 png, 3 svg, 4 spreadsheet, 5 audio, 6 video :: better specs to come... + (list + "CREATE TABLE pics (id INTEGER PRIMARY KEY,name TEXT,wiki_id INTEGER,dat_id INTEGER,thumb_dat_id INTEGER,created_on INTEGER,owner_id INTEGER);" + "CREATE TABLE dats (id INTEGER PRIMARY KEY,md5sum TEXT,dat BLOB,type INTEGER);" + ;; on every modification a new tiddlers entry is created. When displaying the tiddlers do: + ;; select where created_on < somedate order by created_on desc limit 1 + "CREATE TABLE tiddlers (id INTEGER PRIMARY KEY,wiki_id INTEGER,name TEXT,rev INTEGER,dat_id INTEGER,created_on INTEGER,owner_id INTEGER);" + ;; rev and tag only utilized when user sets a tag. All results from a select as above for tiddlers are set to the tag + "CREATE TABLE revs (id INTEGER PRIMARY KEY,tag TEXT);" + ;; wikis is here for when postgresql support is added or if a sub wiki is created. + "CREATE TABLE wikis (id INTEGER PRIMARY KEY,name TEXT,created_on INTEGER);" + ;; access control, negative numbered groups are private groups, postive numbered groups are system groups + ;; permissions are on a per-wiki granularity + ;; access; 0=none,1=read,2=read/write + "CREATE TABLE perms (id INTEGER PRIMARY KEY,wiki_id INTEGER,group_id INTEGER,access INTEGER);" + "CREATE TABLE groups (id INTEGER PRIMARY KEY,name TEXT);" + "CREATE TABLE members (id INTEGER PRIMARY KEY,person_id INTEGER,group_id INTEGER);" + ;; setup and configuration data + "CREATE TABLE meta (id INTEGER PRIMARY KEY,key TEXT,val TEXT);" + ;; need to create an entry for *this* twiki + (conc "INSERT INTO wikis (id,name,created_on) VALUES (1,'main'," (current-seconds) ");"))) + ;; (conc "INSERT INTO tiddlers (wiki_id,name,created_on) VALUES(1,'MainMenu'," (current-seconds) ");"))))) + (twiki:save-tiddler db "MainMenu" "[[FirstTiddler]]" "" 1 1))) + (sqlite3:set-busy-timeout!(dbi:db-conn db) 1000000) + db)))) + +;;====================================================================== +;; twikis (db naming, sqlite vs postgresql, keys etc. +;;====================================================================== + +;; A wiki is specified by a list of keys, here we convert that list to a single string +(define (twiki:keys->key keys) + (if (not (null? keys)) + (string-intersperse (map conc keys) " ") + " ")) + +(define (twiki:key->fname key) + (let* (;; (md5keypath (md5:digest key)) ;; (twiki:keys->key keys))) + (keypath (twiki:web64enc key)) + (delta (quotient (string-length keypath) 3)) ;; + (p1 (substring keypath 0 delta)) ;; 0 8)) + (p2 (substring keypath delta (* delta 2)));; 8 16)) + (p3 (substring keypath (* delta 2) (* delta 3)))) ;; 16 24)) + (list (string-intersperse (list "twikis" p1 p2 p3) "/") keypath))) + +;; look up the wid based on the keys, this is used for sub wikis only. I.e. a wiki instantiated inside another wiki +;; giving a separate namespace to all the tiddlers +(define (twiki:name->wid db name) ;; (slot-ref s:session 'conn) + (let ((wid (dbi:get-one db "SELECT id FROM wikis WHERE name=?;" name))) + (if wid wid + (begin + (dbi:exec db "INSERT INTO wikis (name,created_on) VALUES(?,?);" name (current-seconds)) + (twiki:name->wid db name))))) + +;;====================================================================== +;; twiki record +;;====================================================================== + +;; make-vector-record twiki wiki wid name key dbh +(define (make-twiki:wiki)(make-vector 5)) +(define-inline (twiki:wiki-get-wid vec) (vector-ref vec 0)) +(define-inline (twiki:wiki-get-name vec) (vector-ref vec 1)) +(define-inline (twiki:wiki-get-key vec) (vector-ref vec 2)) +(define-inline (twiki:wiki-get-dbh vec) (vector-ref vec 3)) +(define-inline (twiki:wiki-get-perms vec) (vector-ref vec 4)) + +(define-inline (twiki:wiki-set-wid! vec val)(vector-set! vec 0 val)) +(define-inline (twiki:wiki-set-name! vec val)(vector-set! vec 1 val)) +(define-inline (twiki:wiki-set-key! vec val)(vector-set! vec 2 val)) +(define-inline (twiki:wiki-set-dbh! vec val)(vector-set! vec 3 val)) +(define-inline (twiki:wiki-set-perms! vec val)(vector-set! vec 4 val)) + +;;====================================================================== +;; twiki misc +;;====================================================================== + +;; returns help html +(define (twiki:help section) + (let ((main (twiki:div + 'node "twiki-help" + (list + (twiki:h3 "Help stuff") + (twiki:pre " +Link to page: [[Page Title]] +Heading3: !!! The heading +Underline: __underlined__ +Table: | cell1 | cell2 | +List: # item1 + ## item2 +Bullet: * item1 + ** item2 +Preformatted: {{{stuff here}}} +Insert a picture: [pic[PicName]] +Or with size: [pic100x100[PicName]] +Upload the picture using the \"Pic\" link first"))))) + ;;(case section + main)) + +;;====================================================================== +;; twiki access control +;;====================================================================== + +;; idea here is for the end user to redefine this routine, +;; and call twiki:interal-access if desired +;; +;; if override is #t then give access no matter what +(define (twiki:access keys wiki-name user-id) + '(r w)) + +;; Add support for storing groups, users and access internally +;; +(define (twiki:internal-access keys wiki-name user-id) + #f) + +;;====================================================================== +;; twiki registry +;;====================================================================== + +;; these can be overridden by end user (just create a new routine by the same name) + +(define (twiki:open-registry) + (let* ((basepath (slot-ref s:session 'sroot)) + (regfile (conc basepath "/twikis/registry.db")) + (regexists (file-exists? regfile)) + (db (dbi:open 'sqlite3 (list (cons 'dbname regfile))))) + (if regexists + db + (begin + (for-each (lambda (stmt)(dbi:exec db stmt)) + (list "CREATE TABLE wikis (key TEXT PRIMARY KEY,path TEXT,creation_date INTEGER,creator_id INTEGER);")) + db)))) + +(define (twiki:register-wiki key path) + (let ((db (twiki:open-registry))) + (dbi:exec db + "INSERT OR REPLACE INTO wikis (key,path,creation_date,creator_id) VALUES(?,?,?,?);" + key path (current-seconds) (twiki:get-id)) + (dbi:close db))) + +;;====================================================================== +;; tiddlers +;;====================================================================== + +(define twiki:tiddler-selector "SELECT t.id,t.name,t.rev,t.dat_id,t.created_on,t.owner_id FROM tiddlers AS t INNER JOIN dats AS d ON t.dat_id=d.id") +(define (twiki:tiddler-make)(make-vector 8 #f)) +(define-inline (twiki:tiddler-get-id vec) (vector-ref vec 0)) +(define-inline (twiki:tiddler-get-name vec) (vector-ref vec 1)) +(define-inline (twiki:tiddler-get-rev vec) (vector-ref vec 2)) +(define-inline (twiki:tiddler-get-dat-id vec) (vector-ref vec 3)) +(define-inline (twiki:tiddler-get-created_on vec) (vector-ref vec 4)) +(define-inline (twiki:tiddler-get-owner_id vec) (vector-ref vec 5)) +;; (define-inline (twiki:tiddler-get-dat-type vec) (vector-ref vec 6)) + +(define-inline (twiki:tiddler-set-id! vec val)(vector-set! vec 0 val) vec) +(define-inline (twiki:tiddler-set-name! vec val)(vector-set! vec 1 val) vec) +(define-inline (twiki:tiddler-set-rev! vec val)(vector-set! vec 2 val) vec) +(define-inline (twiki:tiddler-set-dat-id! vec val)(vector-set! vec 3 val) vec) +(define-inline (twiki:tiddler-set-created_on! vec val)(vector-set! vec 4 val) vec) +;; (define-inline (twiki:tiddler-set-owner_id! vec val)(vector-set! vec 5 val)) + +;;====================================================================== +;; Routines for displaying, editing, browsing etc. tiddlers +;;====================================================================== + +;; should change this to take a tiddler structure? +(define (twiki:view dat tkey wid tiddler wiki) ;; close, close others, edit, more + (let ((is-not-main (not (equal? "MainMenu" (twiki:tiddler-get-name tiddler)))) + (edit-allowed (member 'w (twiki:wiki-get-perms wiki)))) + (s:div 'class "node" ;; "node" + ;; (s:hr " ") + ;; (s:p 'class (if is-not-main "float-left" "float-left-menu") + ;; (s:p 'class (if is-not-main "float-left" "float-right") + ;; (if is-not-main + ;; (s:big (s:b (twiki:tiddler-get-name tiddler))) + ;; (s:small ;; (s:b "Menu") + ;; (if edit-allowed + ;; (list "(" + ;; (s:a "edit" 'href + ;; (s:link-to (twiki:get-link-back-to-current) + ;; 'edit_tiddler (twiki:tiddler-get-id tiddler))) ")") + ;; '())))) + (s:div 'class "tiddler" + (s:p 'class "tiddlercommands" + (if (equal? "MainMenu" (twiki:tiddler-get-name tiddler)) + (if edit-allowed + (list (s:a "edit" 'href + (s:link-to (twiki:get-link-back-to-current) + 'edit_tiddler (twiki:tiddler-get-id tiddler)))) + '()) + (list + (s:a "close" 'href (s:link-to (twiki:get-link-back-to-current) 'close_tiddler (twiki:tiddler-get-id tiddler))) "." + (s:a "close others" 'href (s:link-to (twiki:get-link-back-to-current) 'close_other_tiddlers (twiki:tiddler-get-id tiddler))) "." + (if edit-allowed + (s:a "edit" 'href (s:link-to (twiki:get-link-back-to-current) 'edit_tiddler (twiki:tiddler-get-id tiddler))) + '())))) + ;; (s:p 'class "tiddler-skip-par" "-") + ;; (s:p ".") + ;; (s:p (twiki:dat->html dat wiki) (s:br)))))) + (s:p (twiki:dat->html dat wiki)))))) +;; (let ((twhtml (twiki:dat->html dat wiki))) ;; let's try to force a minimum of one paragraph +;; (if (< (length twhtml) 2) +;; (s:p twhtml (s:br)) +;; twhtml)))))) + +(define (twiki:view-tiddler db tkey wid tiddler wiki) + (let* ((dat-id (twiki:tiddler-get-dat-id tiddler)) + (dat (twiki:get-dat db dat-id)) + (tnum (twiki:tiddler-get-id tiddler))) + ;; (s:log "twid: " dat-id " dat: " dat) + (twiki:view dat tkey wid tiddler wiki))) + +;; call with param => action-name-key e.g. save-bWFpbg__-aGVsbG8gbnVyc2U_ (save main "hello nurse") +;; this one is called when an edit form is submitted (i.e. POST) +(define (twiki:action params) + (if (and (list? params) + (> (length params) 0)) + (let* ((cmdln (string-split (car params) "-")) + (cmd (string->symbol (car cmdln))) + (tkey (twiki:web64dec (caddr cmdln))) + (wid (string->number (cadr cmdln))) + (tdb (twiki:open-db tkey))) + (s:log "cmdln: " cmdln " cmd: " cmd " tkey: " tkey " wid: " wid) + (case cmd + ((save) + (twiki:save-curr-tiddler tdb wid)) + ((savepic) + (s:log "twiki:action got to savepic") + (twiki:save-pic-from-form tdb wid)) + ((cancel) ;; deprecated. Use a link for this (i.e in the twiki:twiki proc + (s:del! (conc "CURRENT_TWIDLER_UNDER_EDIT:" wid)) + ))))) + +;; generate a form for editing a twiddler tnum +(define (twiki:edit-tiddler db tkey wid tnum) + (s:log "twiki:edit-tiddler: tkey=" tkey " wid: " wid) + (let* ((enc-key (twiki:web64enc tkey)) + (tiddats (twiki:get-tiddlers-by-num db wid (list tnum)))) + (if (null? tiddats) + (let* ((tid 0) + (dat-id 0)) + (s:set! "twiki_title" "") + (s:set! "twiki_body" "")) + (let* ((tid (car tiddats)) + (dat-id (twiki:tiddler-get-dat-id tid))) + ;; (s:log "tid: " tid " dat-id: " dat-id) + (s:set! "twiki_title" (twiki:tiddler-get-name tid)) + (s:set! "twiki_body" (twiki:get-dat db dat-id)))) + (s:form 'action (s:link-to (twiki:get-link-back-to-current) + 'action (conc "twiki.save-" (number->string wid) "-" enc-key)) + 'method "post" ;; 'twikiname tkey ;; done, cancel, delete + (s:input 'type "submit" 'name "form-name" 'value "save" 'twikiname tkey) + ;; (s:a "done" 'href (s:link-to (twiki:get-link-back-to-current) 'save_tmenu tnum)) + (s:a "cancel" 'href (s:link-to (twiki:get-link-back-to-current) 'cancel_tedit tnum)) "." + (s:a "delete" 'href (s:link-to (twiki:get-link-back-to-current) 'delete_tiddler tnum))(s:br) + (s:input-preserve 'type "text" 'name "twiki_title" 'size "58" 'maxlength "150") + (s:textarea-preserve 'type "textarea" 'name "twiki_body" 'rows "10" 'cols "65") + (s:p "Tags" (s:input-preserve 'type "text" 'name "twiki_tags" 'size "55" 'maxlength "150"))))) + +;; save a tiddler to the db for the twiki twik, getting data from the INPUT +(define (twiki:save-curr-tiddler tdb wid) + (formdat:printall (slot-ref s:session 'formdat) s:log) + (let* ((heading (s:get-input 'twiki_title)) + (body (s:get-input 'twiki_body)) + (tags (s:get-input 'twiki_tags)) + (uid (twiki:get-id))) + ;; (s:log "twiki:save-curr-tiddler heading: " heading " body: " body " tags: " tags) + (s:set! 'twiki_title heading) + (if body + (begin + (set! body (string-chomp body)) + (s:set! 'twiki_body body))) + (s:set! 'twiki_tags tags) + (s:del! (conc "CURRENT_TWIDLER_UNDER_EDIT:" wid)) + (let ((res (twiki:save-tiddler tdb heading body tags wid uid))) + ;; Now, replace this twiddler number in the view list with + ;; the new number from the db + (twiki:normalize-current-twiddlers tdb wid) + (s:del! 'twiki_title) + (s:del! 'twiki_body) + (s:del! 'twiki_tags) + res) + )) + +(define (twiki:normalize-current-twiddlers tdb wid) + (let* ((cvar (conc "CURRENT_TWIDLERS:" wid)) + (curr-slst (s:get cvar)) + (curr-lst (map string->number (string-split curr-slst ","))) + (tdlrs (twiki:get-tiddlers-by-num tdb wid curr-lst)) + (names (remove (lambda (t)(string=? "MainMenu" t)) + (map twiki:tiddler-get-name tdlrs))) + (newnums (map twiki:tiddler-get-id + (map (lambda (tn) + (twiki:get-tiddler-by-name tdb wid tn)) + names)))) + (s:set! cvar (string-intersperse (map number->string newnums) + ",")))) + +;; generic save tiddler +(define (twiki:save-tiddler tdb heading body tags wid uid) + (if (misc:non-zero-string heading) + (let* ((prev-tid (twiki:get-tiddler-by-name tdb wid heading)) + (prev-dat-id (if prev-tid + (twiki:tiddler-get-dat-id prev-tid) + -1)) + (dat-id (twiki:save-dat tdb body 0))) ;; 0=text + ;; (s:log "twiki:save-tiddler dat-id: " dat-id " body: " body) + (if (equal? prev-dat-id dat-id) ;; no need to insert a new record if the dat didn't change + #t + (dbi:exec tdb + "INSERT INTO tiddlers (wiki_id,name,dat_id,created_on,owner_id) VALUES(?,?,?,?,?);" + wid heading dat-id (current-seconds) uid)) + #t) ;; success + #f)) ;; non-success + +;; text=0, jpg=1, png=2 +(define (twiki:save-dat db dat type) + (let* ((md5sum (md5:digest dat)) + (datid (twiki:dat-exists? db md5sum type)) + (datblob (if (string? dat) + (string->blob dat) + dat))) + (if datid + datid + (begin + (case type + ((0) (dbi:exec db "INSERT INTO dats (md5sum,dat,type) VALUES(?,?,?);" md5sum datblob 0)) + ((1) (dbi:exec db "INSERT INTO dats (md5sum,dat,type) VALUES(?,?,?);" md5sum datblob 1)) + (else (dbi:exec db "INSERT INTO dats (md5sum,dat,type) VALUES(?,?,?);" md5sum datblob type))) + (twiki:dat-exists? db md5sum type))))) + +(define (twiki:dat-exists? db md5sum type) + (dbi:get-one db "SELECT id FROM dats WHERE md5sum=? AND type=?;" md5sum type)) + +(define (twiki:get-dat db id) + (if (and id (number? id)) + (if (< id 0) + "" + (let ((res (dbi:get-one-row db "SELECT dat,type FROM dats WHERE id=?;" id))) + (if res + (case (vector-ref res 1) + ((0)(blob->string (vector-ref res 0))) + (else (vector-ref res 0))) + #f))) + #f)) + +(define (twiki:maint_area tdb wid tkey wiki) + (let ((maint (s:get-param 'twiki_maint)) + (write-perm (member 'w (twiki:wiki-get-perms wiki)))) + (s:div ;; 'class "node" + (if write-perm + (list (s:a "Orphans" 'href (s:link-to (twiki:get-link-back-to-current) 'twiki_maint 1))(s:br) + (s:a "Pics" 'href (s:link-to (twiki:get-link-back-to-current) 'twiki_maint 2))(s:br) + (s:a "Help" 'href (s:link-to (twiki:get-link-back-to-current) 'twiki_maint 4))(s:br)) + '()) + (s:a "Search" 'href (s:link-to (twiki:get-link-back-to-current) 'twiki_maint 3))(s:br) + (case maint + ((1) + (twiki:list-orphans tdb)) + (else + '()))))) + +;;====================================================================== +;; Orphans +;;====================================================================== +(define (twiki:make-tiddler-list tdlrs . tnums) + (conc (string-intersperse + (map conc (delete-duplicates + (append (map twiki:tiddler-get-id tdlrs) tnums))) + ","))) + +(define (twiki:get-orphans tdb) + '()) + +(define (twiki:list-orphans tdb) + '()) + +;;====================================================================== +;; Pictures +;;====================================================================== +(define (twiki:pic_mgmt tdb wid tkey) + (s:div + (s:a "Add pic" 'href (s:link-to (twiki:get-link-back-to-current) 'twiki_maint 2 'twiki_maint_add_pics 1))(s:br) + (if (s:get-param "twiki_maint_add_pics") + (s:form 'enctype "multipart/form-data" ;; 'name "does-a-form-have-a-name" + (s:input 'type "file" 'name "input-picture" 'value "Upload pic") + (s:input 'type "submit" 'name "submit-picture" 'value "Submit") + 'method "post" + 'action (s:link-to (twiki:get-link-back-to-current) 'action (conc "twiki.savepic-" (number->string wid) "-" (twiki:web64enc tkey))) + (s:input 'type "text" 'name "picture-name" 'value "")) + '()) + (let ((pics (dbi:get-rows tdb "SELECT id,name,dat_id,thumb_dat_id FROM pics WHERE wiki_id=?;" wid))) + (map (lambda (pic) + (s:div 'class "tiddlerthumb" + (s:img 'title (vector-ref pic 1) 'alt (vector-ref pic 1) + ;; 'src (s:link-to "twiki" 'wiki_key (twiki:web64enc tkey) 'image (vector-ref pic 0))) + 'src (s:link-to "twiki" 'wiki_key (conc (number->string wid) "-" (twiki:web64enc tkey)) + 'thumb (vector-ref pic 0))) + ;; (conc "twiki/" wid "/thumbs/" (vector-ref pic 0)))) + (vector-ref pic 0) (vector-ref pic 1))) + pics)))) + +(define (twiki:save-pic-from-form tdb wid) + (let* ((pic-dat (s:get-input 'input-picture)) + (alt-name (s:get-input 'picture-name))) + (if pic-dat + (begin + (s:log "twiki:save-pic-from-form with pic-dat=" pic-dat " and alt-name=" alt-name) + (twiki:save-pic tdb pic-dat wid alt-name)) + #f))) + +;; get pic id for a pic name, returns the latest +(define (twiki:get-pic-id tdb pic-name wid) + (dbi:get-one tdb "SELECT pics.id FROM pics WHERE pics.name=? AND pics.wiki_id=? ORDER BY pics.id DESC LIMIT 1;" pic-name wid)) + +(define (twiki:save-pic tdb pic-dat wid alt) + (let ((pic-name (car pic-dat)) + (pic-type (cadr pic-dat)) + (pic-data (caddr pic-dat)) + ;; I'm not too happy with this solution but I can't seem to chomp the \n\d from the end of the string + (alt-name (if alt (string-substitute (regexp "[^\\w ]") "" alt #t) #f))) + (if (and alt-name + (string-match (regexp "\\w+") alt-name)) + (set! pic-name alt-name)) + (s:log "alt: " alt " alt-name: " alt-name) + (if pic-data + (let ((dat-id (twiki:save-dat tdb pic-data (twiki:mime->twiki-type pic-type))) + (creation-time (current-seconds))) + ;; (twiki:delete-pic-by-name tdb pic-name) + (dbi:exec tdb + "INSERT INTO pics (name,wiki_id,dat_id,created_on,owner_id) VALUES(?,?,?,?,?);" + pic-name wid dat-id creation-time (twiki:get-id)) + (let ((pic-id (twiki:get-pic-id tdb pic-name wid))) + (twiki:make-thumbnail tdb pic-id wid)) + #t) + #f))) + +(define (twiki:get-pic-dat tdb wid pic-id) + (dbi:get-one tdb "SELECT dat FROM pics INNER JOIN dats ON pics.dat_id=dats.id WHERE pics.id=? AND wiki_id=?;" pic-id wid)) + +(define (twiki:get-thumb-dat tdb wid pic-id) + (dbi:get-one tdb "SELECT dat FROM pics INNER JOIN dats ON pics.thumb_dat_id=dats.id WHERE pics.id=? AND wiki_id=?;" pic-id wid)) + +;; this one sets up the Content type, puts the data into page-dat and is done +(define (twiki:return-image-dat tdb wid pic-id) + (let ((dat (twiki:get-pic-dat tdb wid pic-id))) + (s:log "twiki:return-image-dat dat is: " dat " of size: " (if (blob? dat)(blob-size dat) "[not a blob]")) + (slot-set! s:session 'page-type 'image) + (slot-set! s:session 'content-type "image/jpeg") + (slot-set! s:session 'alt-page-dat dat))) + ;; (session:alt-out s:session))) + +;; this one sets up the Content type, puts the data into page-dat and is done +(define (twiki:return-thumb-dat tdb wid pic-id) + (let ((dat (twiki:get-thumb-dat tdb wid pic-id))) + (s:log "twiki:return-image-dat dat is: " dat " of size: " (if (blob? dat)(blob-size dat) "[not a blob]")) + (slot-set! s:session 'page-type 'image) + (slot-set! s:session 'content-type "image/jpeg") + (slot-set! s:session 'alt-page-dat dat))) + ;; (session:alt-out s:session))) + +(define (twiki:make-thumbnail tdb pic-id wid) + (let ((indat (twiki:get-pic-dat tdb wid pic-id))) + ;; (outdat (open-output-string))) + (let-values (((inp oup pid)(process "convert" (list "-size" "500x180" "-" "-thumbnail" "250x90" "-unsharp" "0x.5" "-")))) + (write-string (blob->string indat) #f oup) + (close-input-port oup) + ;; (write-string #f inp (blob->string indat)) + (let ((l (read-string #f inp))) + (close-output-port inp) + ;; (write-string l #f outdat) + (let* ((newdat (string->blob l)) ;; (get-output-string outdat))) + (dat-id (twiki:save-dat tdb newdat 2))) ;; bug? + (dbi:exec tdb "UPDATE pics SET thumb_dat_id=? WHERE id=?;" dat-id pic-id) + dat-id))))) + +;; not tested +(define (twiki:picdat->thumbdat picdat) + (let-values (((inp oup pid)(process "convert" ;; (list "-size" "500x180" "-" "-thumbnail" "250x90" "-unsharp" "0x.5" "-")))) + (list "-size" "500x180" "-" "-thumbnail" "200x70" "-unsharp" "0x.5" "-")))) + (write-string (blob->string picdat) #f oup) + (close-input-port oup) + ;; (write-string #f inp (blob->string indat)) + (let ((l (read-string #f inp))) + (close-output-port inp) + (write-string l #f oup) + (string->blob l)))) + +(define (twiki:mime->twiki-type mime-type) + (case (string->symbol mime-type) + ((image/jpeg) 1) + ((image/png) 2) + (else 0))) + +;;====================================================================== +;; Wiki stuff +;;====================================================================== + +;; curr-tiddlers is a list of the names of the current tiddlers displayed +;; tiddler-under-edit is the tiddler being edited (or #f for none). +(define (twiki:wiki name keys) + (let ((perms (twiki:access name keys (twiki:get-id)))) + ;; (s:log "twiki:wiki name: \"" name "\" keys: " keys) + (if (or (not name) + (string=? name "")) ;; name must be "" or #f to get here and return an image + ;; handle returning pictures, note keys and name are ignored for these. They are called out in + ;; the twiki/view.scm (twiki:twiki "blah" '(nada foo)) call. + (let ((image (s:get-param "image")) + (thumb (s:get-param "thumb"))) + (s:log "image: " image " thumb: " thumb " wiki_key: " (s:get-param 'wiki_key)) + (if (and (member 'r perms) image) + (let* ((varlst (string-split (s:get-param 'wiki_key) "-")) + (tkey (twiki:web64dec (cadr varlst))) + (wid (string->number (car varlst))) + (tdbn (twiki:open-db tkey #f))) + (s:log "tkey: " tkey " image number: " image) + (twiki:return-image-dat tdbn wid (string->number image)))) ;; do not return from twiki:return-image + (if (and (member 'r perms) thumb) + (let* ((varlst (string-split (s:get-param 'wiki_key) "-")) + (tkey (twiki:web64dec (cadr varlst))) + (wid (string->number (car varlst))) + (tdbn (twiki:open-db tkey #f))) + (s:log "tkey: " tkey " thumb number: " image) + (twiki:return-thumb-dat tdbn wid (string->number thumb))))) ;; do not return from twiki:return-image + (if (not (member 'r perms)) ;; read access + '() ;; return a blank slate + (twiki:display-wiki name keys perms))))) + +(define (twiki:display-wiki name keys perms) + (let* ((wikidat (make-twiki:wiki)) + (tkey (twiki:keys->key keys)) + (tdb (twiki:open-db tkey)) + (wid (twiki:name->wid tdb name)) + (cvar (conc "CURRENT_TWIDLERS:" wid)) ;; page var to store current twiddlers being viewed + (cvar-ed (conc "CURRENT_TWIDLER_UNDER_EDIT:" wid)) + (tnumedit (if (s:get cvar-ed) + (string->number (s:get cvar-ed)) + #f)) ;; #f => nothing to edit, -1 create a new tiddler + (tnumview #f) + (lmenu (twiki:get-tiddlers tdb wid (list "MainMenu"))) + ;; store tiddlers for this page/twiki in cvar (i.e. CURRENT_TWIDLERS: + (tdlnums (if (s:get cvar) + (map string->number (string-split (s:get cvar) ",")) + '())) ;; list of tiddler numbers + (tdlrs '()) + (tedited (if (member 'w perms) #f #t)) ;; force no edits if not a writer + (edit-tmenu-id (if (and (member 'w perms) + (s:get-param "edit_tmenu")) + (string->number (s:get-param "edit_tmenu")) + #f)) + (edit-tiddler (if (and (member 'w perms) + (s:get-param "edit_tiddler")) ;; this handles the "edit" link in the tiddler control bar + (let ((t (twiki:get-tiddlers-by-num tdb wid (list (string->number (s:get-param "edit_tiddler")))))) + (s:log "t: " t) + (if t + (car t ) ;; should be a list of one + (twiki:tiddler-set-name! + (twiki:tiddler-set-id! (twiki:tiddler-make) -1) "NewTiddler"))) + #f)) + (view-tiddler (if (s:get-param "view_tiddler") + (let* ((tname (twiki:web64dec (s:get-param "view_tiddler"))) + (t (twiki:get-tiddler-by-name tdb wid tname))) + (s:log "t: " t) + (if t + t + (begin + (twiki:save-tiddler tdb tname (conc "!" tname) "" wid (twiki:get-id)) + (twiki:get-tiddler-by-name tdb wid tname)))) + #f)) + ) ;; image is the dat_id, keep it simple silly. + + (twiki:wiki-set-wid! wikidat wid) + (twiki:wiki-set-key! wikidat tkey) + (twiki:wiki-set-name! wikidat name) + (twiki:wiki-set-dbh! wikidat tdb) + (twiki:wiki-set-perms! wikidat perms) + + ;; (s:log "edit-tmenu-id: " edit-tmenu-id " edit-tiddler: " edit-tiddler) + + ;; Handle other URI commands here + (if (s:get-param "cancel_tedit") ;; doesn't matter which tiddler - just use this to cancel any edit + (begin + (s:del! (conc "CURRENT_TWIDLER_UNDER_EDIT:" wid)) + (set! edit-tiddler #f) + (set! tnumedit #f) + (set! view-tiddler #f) + (twiki:normalize-current-twiddlers tdb wid) + (if (s:get cvar) + (set! tdlnums (map string->number (string-split (s:get cvar) ",")))))) + (if (s:get-param "delete_tiddler") '()) + ;; (twiki:delete_tiddler tdb wid (string->number (s:get-param "delete_tiddler")))) + + (s:set! "TWIKI_KEY" tkey) ;; this mechanism will fail for hierarchial twikis + ;; override the twiddler to edit when editing MainMenu + (if edit-tiddler + (begin + (set! tnumedit (twiki:tiddler-get-id edit-tiddler)) + (s:set! 'twiki_title (twiki:tiddler-get-name edit-tiddler)) + (s:set! 'twiki_body (twiki:get-dat tdb (twiki:tiddler-get-dat-id edit-tiddler))))) + (if view-tiddler + (begin + (set! tnumview (twiki:tiddler-get-id view-tiddler)))) + + ;; NOW WHAT FOR VIEW - fix the links, add to tdlst + + + (if edit-tmenu-id (set! tnumedit edit-tmenu-id)) + (if tnumedit (set! tdlnums (cons tnumedit tdlnums))) + (if tnumview (set! tdlnums (cons tnumview tdlnums))) + (set! tdlrs (twiki:get-tiddlers-by-num tdb wid tdlnums)) + + ;; remove tdlrs from the list if close_tiddler called + (if (s:get-param "close_tiddler") + (set! tdlrs (let ((tnum (string->number (s:get-param "close_tiddler")))) + (remove (lambda (t) + (equal? (twiki:tiddler-get-id t) tnum)) + tdlrs)))) + + ;; remove all others if close_other_tiddlers called + (if (s:get-param "close_other_tiddlers") + (set! tdlrs (let ((tnum (string->number (s:get-param "close_other_tiddlers")))) + (remove (lambda (t) + (not (equal? (twiki:tiddler-get-id t) tnum))) + tdlrs)))) + + (s:set! cvar (twiki:make-tiddler-list tdlrs)) + (if tnumedit + (s:set! cvar-ed tnumedit) + (s:del! cvar-ed)) + + ;; must have a MainMenu tiddler by now + (if (null? lmenu) + (begin + (twiki:save-tiddler tdb "MainMenu" "" "" wid (twiki:get-id)) + (set! lmenu (twiki:get-tiddlers tdb wid (list "MainMenu"))))) + + ;; get the tiddlers from the db now + (set! result + (s:table + ;; ;; A header row MainMenu WikiName Other + ;; (s:tr + ;; (s:td + ;; (let ((main-menu-tnum (twiki:tiddler-name->id tdb "MainMenu"))) + ;; (if edit-tmenu-id + ;; "MainMenu" + ;; (s:a "MainMenu" 'href (s:link-to (twiki:get-link-back-to-current) 'edit_tmenu main-menu-tnum))))) + ;; (s:td (twiki:key->fname tkey)) + ;; (s:td "")) + (s:tr + ;; The menu column (must do all this with css some time) + ;; July 5, 2010, attempting to switch to a top menu + ;; (s:td 'class "col1-tiddler" (twiki:view-tiddler tdb tkey wid (car lmenu) wikidat)) + (s:td 'class "col2-tiddler" (twiki:view-tiddler tdb tkey wid (car lmenu) wikidat) 'colspan "2")) + (s:tr + (s:td 'class "col2-tiddler" + ;; this is probably not needed as there is no reason to create tiddlers this way + ;; (if (eq? tnumedit -1)(twiki:edit-tiddler tdb tkey wid tnumedit) '()) + ;; insert the picture editor window if enabled + (if (equal? (s:get-param "twiki_maint") "2")(twiki:pic_mgmt tdb wid tkey) '()) + (if (equal? (s:get-param "twiki_maint") "4")(twiki:help 1) '()) + (if (not (null? tdlrs)) + (map (lambda (tdlr) + (let ((tnum (twiki:tiddler-get-id tdlr))) + (s:log "tnum: " tnum " tnumedit: " tnumedit) + (if (and tnumedit (not tedited) (equal? tnumedit tnum)) + (begin + (set! tedited #t) ;; only allow editing one tiddler at a time + (twiki:edit-tiddler tdb tkey wid tnum)) + (twiki:view-tiddler tdb tkey wid tdlr wikidat)))) + tdlrs) + '())) + (s:td 'valign "top" 'class "tiddler-top" (twiki:maint_area tdb wid tkey wikidat))))) + (dbi:close tdb) + result)) + +;; should do a single more efficient query but this is good enough +(define (twiki:get-tiddlers db wid tnames) + (apply twiki:get-tiddlers-by-name db wid tnames)) +;; (let* ((tdlrs '()) +;; ;; (conn (slot-ref s:session 'conn)) +;; (namelst (conc "('" (string-intersperse (map conc tnames) "','") "')")) +;; (qry (conc twiki:tiddler-selector " WHERE t.wiki_id=? AND t.id IN " namelst ";"))) +;; ;; (print qry) +;; (dbi:for-each-row +;; (lambda (row) +;; (set! tdlrs (cons row tdlrs))) +;; db qry wid) +;; (reverse tdlrs))) ;; !Twiki\ + +;; tlst is a list of tiddler nums +(define (twiki:get-tiddlers-by-num db wid tlst) + ;; (s:log "Got to twiki:get-tiddlers with keys: " tlst " and wid: " wid) + ;; select where created_on < somedate order by created_on desc limit 1 + (let* ((tdlrs '()) + (tlststr (string-intersperse (map number->string tlst) ",")) + (already-got (make-hash-table)) + (qry (conc twiki:tiddler-selector " WHERE t.wiki_id=? AND t.id IN (" tlststr ") ORDER BY created_on DESC;"))) + ;; (conn (slot-ref s:session 'conn)) + ;; (print "qry: " qry) + (dbi:for-each-row + (lambda (row) + (let ((tname (twiki:tiddler-get-name row))) + (if (not (hash-table-ref/default already-got tname #f)) + (begin + (set! tdlrs (cons row tdlrs)) + (hash-table-set! already-got tname #t))))) + db qry wid) + (if (null? tdlrs) tdlrs (reverse tdlrs)))) ;; !Twiki\nTitle, pictures, etc.\n{{{\nCode\n}}}\n[[links]]\n|table|of|stuff|\n|more|stuff|here|\n")) + +;; wid = wiki id +;; returns a list of twiki:tiddlers +(define (twiki:get-tiddlers-by-name tdb wid . names) + (let ((tdlrs '())) + (for-each (lambda (name) + (let ((tdlr (twiki:get-tiddler-by-name tdb wid name))) + (if tdlr (set! tdlrs (cons tdlr tdlrs))))) + names) + (reverse tdlrs))) +;; with the right query it should be possible to do this much faster approach for twiki:get-tiddlers-by-name +;; (let ((tdlrs '()) +;; (namelst (conc "('" (string-intersperse names "','") "')"))) +;; (dbi:for-each-row +;; (lambda (row) +;; (set! tdlrs (cons row tdlrs))) +;; tdb +;; (conc twiki:tiddler-selector " WHERE t.wiki_id=? AND t.name IN " namelst) wid) +;; (reverse tdlrs))) + +;; get the tiddler with the given name and the max date +(define (twiki:get-tiddler-by-name tdb wid name) + (dbi:get-one-row tdb (conc twiki:tiddler-selector " WHERE t.wiki_id=? AND t.name=? ORDER BY created_on DESC LIMIT 1;") wid name)) + +(define (twiki:tiddler-name->id db tname) + (dbi:get-one db "SELECT id FROM tiddlers WHERE name=?;" tname)) + +;;====================================================================== +;; twiki text formating, parsing and display +;;====================================================================== + +;; twiki formating routines (override these to change your look and feel +(define twiki:twiki-tag s:b) +(define twiki:h3 s:h3) +(define twiki:h2 s:h2) +(define twiki:h1 s:h1) +;; (define twiki:make-tlink s:i) +(define twiki:ul s:ul) +(define twiki:ol s:ol) +(define twiki:li s:li) +(define twiki:pre s:pre) +(define twiki:p s:p) +(define twiki:u s:u) +(define twiki:td s:td) +(define twiki:tr s:tr) +(define twiki:table s:table) +(define twiki:div s:div) + +(define (twiki:web64enc str) + (string-substitute "=" "_" (base64:encode str) #t)) + +(define (twiki:web64dec str) + (base64:decode (string-substitute "_" "=" str #t))) + +(define (twiki:make-tlink text tiddlername) + (s:a text 'href (s:link-to (twiki:get-link-back-to-current) 'view_tiddler (twiki:web64enc tiddlername)))) + +(define (twiki:pic pic-name size wiki) + (let* ((tdb (twiki:wiki-get-dbh wiki)) + (tkey (twiki:wiki-get-key wiki)) + (xy (string-split size "x")) + (pic-id (twiki:get-pic-id tdb pic-name (twiki:wiki-get-wid wiki))) + (img-lnk (s:link-to "twiki" 'wiki_key (conc (number->string (twiki:wiki-get-wid wiki)) "-" (twiki:web64enc tkey)) + 'image pic-id))) + (if (and (> (length xy) 1) + (car xy) + (cadr xy)) ;; yep, have two numbers + (s:img 'title pic-name 'alt pic-name 'width (car xy) 'height (cadr xy) 'src img-lnk) + (s:img 'title pic-name 'alt pic-name 'src img-lnk)))) + +;; override these also +(define (twiki:get-id) + (s:session-var-get "id")) + +;; override this to set links inside wiki's +(define (twiki:get-link-back-to-current) + (s:current-page)) + + +;; regexes are listed in the order in which they should be checked + +(define twiki:h3-patt (regexp "^!!!(.*)$")) +(define twiki:h2-patt (regexp "^!!(.*)$")) +(define twiki:h1-patt (regexp "^!(.*)$")) + +(define twiki:tlink-patt (regexp "^(.*)\\[\\[([^\\[\\]]*)\\]\\](.*)$")) +(define twiki:pic-patt (regexp "^(.*)\\[pic([0-9%]*x*[0-9%]*)\\[([^\\[\\]]+)\\]\\](.*)$")) +(define twiki:underline-patt (regexp "^(.*)__(.*)__(.*)$")) +(define twiki:table-patt (regexp "^\\|(.*)\\|$")) + +;; these are for multi-line formating +(define twiki:list-patt (regexp "^(\\*+|\\#+)(.*)$")) +(define twiki:bullet-patt (regexp "^(\\*+)(.*)$")) +(define twiki:number-patt (regexp "^(\\#+)(.*)$")) +(define twiki:prefor-patt (regexp "^\\{\\{\\{$")) +(define twiki:prefor-end-patt (regexp "^\\}\\}\\}$")) + +;; regex +(define t:match #f) +(define (t-match r s) + (let ((res (string-match r s))) + (set! t:match res) + res)) + +;; should switch to recursively processing by block? +;; (process-block dat) +;; ... +;; (process-block remdat) +(define (twiki:dat->html dat wiki) + (let* ((inp (open-input-string dat)) + (nest-depth 0) ;; depth of nested lists + ;; token (i.e. line) handling stuff + (next-line #f) + (peek-line (lambda () + next-line)) + (get-line (lambda () + (let ((res next-line)) + (set! next-line (read-line inp)) + ;; (print "get-line: prev=" res " next=" next-line "\n") + res))) + (l (get-line))) ;; discard the #f in next-line + (twiki:read-block peek-line get-line nest-depth #f wiki))) + +;; blk-type is #f for not in a block (i.e. at top level), 'pre for preformated, 'ul or 'ol +;; call with first line as legit data +;; i.e. for preform - skip the {{{ line then call read-block +;; for # or * call with first line +(define (twiki:read-block peek-line get-line nest-depth blk-type wiki) + (let loop ((res '()) + (l (peek-line))) ;; should this be a peek-line? yes!! + ;; (print "twiki:read-block loop nest-depth="nest-depth " blk-type=" blk-type " l=" l "\n res=" res) + (if (eof-object? l) + ;; we are done! return the list + res + ;; process it! + (cond + ;; handle preformated text + ((eq? blk-type 'pre) + (if (t-match twiki:prefor-end-patt l) + (begin + (get-line) ;; discard the }}} + res) ;; end of preformatted + (begin + ;; (get-line) ;; discard the {{{ + (loop (append res (list (get-line))) + (peek-line))))) + ;; handle tables + ((eq? blk-type 'table) + (if (t-match twiki:table-patt l) + (let ((cels (string-split (cadr t:match) "|"))) + (get-line) + (loop (append res (twiki:tr (map twiki:td + (map (lambda (x)(twiki:line->html x #f wiki)) cels)))) + (get-line))) + res)) + ;; handle lists + ((or (t-match twiki:bullet-patt l) ;; have * + (t-match twiki:number-patt l)) + (let* ((directive (cadr t:match)) + (levelnum (string-length directive)) + (text (twiki:line->html (caddr t:match) #t wiki)) + (btype (if (string=? "#" (substring directive 0 1)) + 'ol + 'ul)) + (func (if (eq? btype 'ul) + twiki:ul + twiki:ol))) + ;; (print "handling " btype ": levelnum=" levelnum " text=" text " nest-depth=" nest-depth " blk-type=" blk-type) + (cond + ((not blk-type) ;; i.e first member of the list! + (loop (append res (func (twiki:read-block peek-line get-line levelnum btype wiki))) + (get-line))) + ((> levelnum nest-depth) + (loop (append res (func (twiki:read-block peek-line get-line (+ nest-depth 1) btype wiki))) + (peek-line))) + ((< levelnum nest-depth) + (append res (twiki:li text))) ;; return the bulleted item, don't get the next line?? + (else + (get-line) + (loop (append res (twiki:li text)) + (peek-line)))))) + ((t-match twiki:prefor-patt l) + (get-line) ;; discard the {{{ + (loop (append res (twiki:pre (twiki:read-block peek-line get-line nest-depth 'pre wiki))) + (peek-line))) + ((t-match twiki:table-patt l) + (get-line) + (loop (append res (twiki:table 'border 1 'cellspacing 0 (twiki:read-block peek-line get-line 0 'table wiki))) + (peek-line))) + (else + (get-line) + (loop (append res (twiki:line->html l #t wiki)) + (peek-line))))))) + +(define (twiki:line->html dat firstcall wiki) + (if firstcall + ;; process the patterns that test for beginning of line only on the first call + (cond + ((t-match twiki:h3-patt dat) + (twiki:h3 (twiki:line->html (cadr t:match) #f wiki))) + ((t-match twiki:h2-patt dat) + (twiki:h2 (twiki:line->html (cadr t:match) #f wiki))) + ((t-match twiki:h1-patt dat) + (twiki:h1 (twiki:line->html (cadr t:match) #f wiki))) + ;; why was the (s:br) here? trying without + (else (twiki:line->html dat #f wiki))) + ;; (else (append (twiki:line->html dat #f wiki)(list (s:br)))));; (s:p 'class "tiddlerpar" + ;; not firstcall so process other patterns + (cond + ((t-match twiki:tlink-patt dat) + (let ((pre (cadr t:match)) + (lnk (caddr t:match)) + (post (cadddr t:match))) + (list (twiki:line->html pre #f wiki) + (twiki:make-tlink (twiki:line->html lnk #f wiki) lnk) ;; special handling + (twiki:line->html post #f wiki)))) + ((t-match twiki:pic-patt dat) + (let ((pre (cadr t:match)) + (size (caddr t:match)) + (pic (cadddr t:match)) + (post (list-ref t:match 4))) + (list (twiki:line->html pre #f wiki) + (twiki:pic pic size wiki) + (twiki:line->html post #t wiki)))) + ((t-match twiki:underline-patt dat) + (let ((pre (cadr t:match)) + (lnk (caddr t:match)) + (post (cadddr t:match))) + (list (twiki:line->html pre #f wiki) + (twiki:u (twiki:line->html lnk #f wiki)) + (twiki:line->html post #f wiki)))) + ((t-match twiki:table-patt dat) + (let ((cels (string-split (cadr t:match) "|"))) + (twiki:tr (map twiki:td (twiki:line->html cels #f wiki))))) + (else (list dat))))) + + +#| +(twiki:dat->html "a\n{{{\nb\nc\nd\n}}}\n!e\n[[f]]\n[[g]]\n*h" wiki) +(s:output (current-output-port) (twiki:dat->html "!Testing [[my first link]]\n* Test\n* Foo\nblah" wiki)) +(s:output (current-output-port) (twiki:dat->html "[[a]]\n{{{\nb\n c\n d\n}}}\n*x\n[[f]]\n[[g]]\n*h" wiki)) +(s:output (current-output-port) +|# + ADDED modules/twiki/twiki-test.scm Index: modules/twiki/twiki-test.scm ================================================================== --- /dev/null +++ modules/twiki/twiki-test.scm @@ -0,0 +1,5 @@ +(include "../../stml.scm") +;; (include "../../session.scm") +(include "../../misc-stml.scm") +(include "twiki-mod.scm") + ADDED modules/twiki/twiki.l Index: modules/twiki/twiki.l ================================================================== --- /dev/null +++ modules/twiki/twiki.l @@ -0,0 +1,33 @@ +;; twiki + +period \. +comma , +semicolon \; +opensq \[ +closesq \] +opensquig \{ +closesquig \} + +digit [0-9] +letter [a-zA-Z] +okchars [_%\/\.:\*\+\-\(\)\\#'] +escape \\ +whitespace [ \9] +linefeed \n +bang ! +plaintext ({letter}|{digit}|{okchars}|{whitespace}|{linefeed})+ + +%% + +{opensq} (list 'opensq yytext) +{closesq} (list 'closesq yytext) + +{opensquig} (list 'opensquig yytext) +{closesquig} (list 'closesquig yytext) + +{bang} (list 'bang yytext) +{plaintext} (list 'plaintext yytext) + +<> (list 'end-of-input #f ) ;; yyline) + +<> (lex-error (conc yyline " : illegal character ") (yygetc)) ADDED modules/twiki/twiki.l.scm Index: modules/twiki/twiki.l.scm ================================================================== --- /dev/null +++ modules/twiki/twiki.l.scm @@ -0,0 +1,1194 @@ +; *** This file starts with a copy of the file multilex.scm *** +; Copyright (C) 1997 Danny Dube', Universite' de Montre'al. +; All rights reserved. +; SILex 1.0. + +; +; Gestion des Input Systems +; Fonctions a utiliser par l'usager: +; lexer-make-IS, lexer-get-func-getc, lexer-get-func-ungetc, +; lexer-get-func-line, lexer-get-func-column et lexer-get-func-offset +; + +; Taille initiale par defaut du buffer d'entree +(define lexer-init-buffer-len 1024) + +; Numero du caractere newline +(define lexer-integer-newline (char->integer #\newline)) + +; Constructeur d'IS brut +(define lexer-raw-IS-maker + (lambda (buffer read-ptr input-f counters) + (let ((input-f input-f) ; Entree reelle + (buffer buffer) ; Buffer + (buflen (string-length buffer)) + (read-ptr read-ptr) + (start-ptr 1) ; Marque de debut de lexeme + (start-line 1) + (start-column 1) + (start-offset 0) + (end-ptr 1) ; Marque de fin de lexeme + (point-ptr 1) ; Le point + (user-ptr 1) ; Marque de l'usager + (user-line 1) + (user-column 1) + (user-offset 0) + (user-up-to-date? #t)) ; Concerne la colonne seul. + (letrec + ((start-go-to-end-none ; Fonctions de depl. des marques + (lambda () + (set! start-ptr end-ptr))) + (start-go-to-end-line + (lambda () + (let loop ((ptr start-ptr) (line start-line)) + (if (= ptr end-ptr) + (begin + (set! start-ptr ptr) + (set! start-line line)) + (if (char=? (string-ref buffer ptr) #\newline) + (loop (+ ptr 1) (+ line 1)) + (loop (+ ptr 1) line)))))) + (start-go-to-end-all + (lambda () + (set! start-offset (+ start-offset (- end-ptr start-ptr))) + (let loop ((ptr start-ptr) + (line start-line) + (column start-column)) + (if (= ptr end-ptr) + (begin + (set! start-ptr ptr) + (set! start-line line) + (set! start-column column)) + (if (char=? (string-ref buffer ptr) #\newline) + (loop (+ ptr 1) (+ line 1) 1) + (loop (+ ptr 1) line (+ column 1))))))) + (start-go-to-user-none + (lambda () + (set! start-ptr user-ptr))) + (start-go-to-user-line + (lambda () + (set! start-ptr user-ptr) + (set! start-line user-line))) + (start-go-to-user-all + (lambda () + (set! start-line user-line) + (set! start-offset user-offset) + (if user-up-to-date? + (begin + (set! start-ptr user-ptr) + (set! start-column user-column)) + (let loop ((ptr start-ptr) (column start-column)) + (if (= ptr user-ptr) + (begin + (set! start-ptr ptr) + (set! start-column column)) + (if (char=? (string-ref buffer ptr) #\newline) + (loop (+ ptr 1) 1) + (loop (+ ptr 1) (+ column 1)))))))) + (end-go-to-point + (lambda () + (set! end-ptr point-ptr))) + (point-go-to-start + (lambda () + (set! point-ptr start-ptr))) + (user-go-to-start-none + (lambda () + (set! user-ptr start-ptr))) + (user-go-to-start-line + (lambda () + (set! user-ptr start-ptr) + (set! user-line start-line))) + (user-go-to-start-all + (lambda () + (set! user-ptr start-ptr) + (set! user-line start-line) + (set! user-column start-column) + (set! user-offset start-offset) + (set! user-up-to-date? #t))) + (init-lexeme-none ; Debute un nouveau lexeme + (lambda () + (if (< start-ptr user-ptr) + (start-go-to-user-none)) + (point-go-to-start))) + (init-lexeme-line + (lambda () + (if (< start-ptr user-ptr) + (start-go-to-user-line)) + (point-go-to-start))) + (init-lexeme-all + (lambda () + (if (< start-ptr user-ptr) + (start-go-to-user-all)) + (point-go-to-start))) + (get-start-line ; Obtention des stats du debut du lxm + (lambda () + start-line)) + (get-start-column + (lambda () + start-column)) + (get-start-offset + (lambda () + start-offset)) + (peek-left-context ; Obtention de caracteres (#f si EOF) + (lambda () + (char->integer (string-ref buffer (- start-ptr 1))))) + (peek-char + (lambda () + (if (< point-ptr read-ptr) + (char->integer (string-ref buffer point-ptr)) + (let ((c (input-f))) + (if (char? c) + (begin + (if (= read-ptr buflen) + (reorganize-buffer)) + (string-set! buffer point-ptr c) + (set! read-ptr (+ point-ptr 1)) + (char->integer c)) + (begin + (set! input-f (lambda () 'eof)) + #f)))))) + (read-char + (lambda () + (if (< point-ptr read-ptr) + (let ((c (string-ref buffer point-ptr))) + (set! point-ptr (+ point-ptr 1)) + (char->integer c)) + (let ((c (input-f))) + (if (char? c) + (begin + (if (= read-ptr buflen) + (reorganize-buffer)) + (string-set! buffer point-ptr c) + (set! read-ptr (+ point-ptr 1)) + (set! point-ptr read-ptr) + (char->integer c)) + (begin + (set! input-f (lambda () 'eof)) + #f)))))) + (get-start-end-text ; Obtention du lexeme + (lambda () + (substring buffer start-ptr end-ptr))) + (get-user-line-line ; Fonctions pour l'usager + (lambda () + (if (< user-ptr start-ptr) + (user-go-to-start-line)) + user-line)) + (get-user-line-all + (lambda () + (if (< user-ptr start-ptr) + (user-go-to-start-all)) + user-line)) + (get-user-column-all + (lambda () + (cond ((< user-ptr start-ptr) + (user-go-to-start-all) + user-column) + (user-up-to-date? + user-column) + (else + (let loop ((ptr start-ptr) (column start-column)) + (if (= ptr user-ptr) + (begin + (set! user-column column) + (set! user-up-to-date? #t) + column) + (if (char=? (string-ref buffer ptr) #\newline) + (loop (+ ptr 1) 1) + (loop (+ ptr 1) (+ column 1))))))))) + (get-user-offset-all + (lambda () + (if (< user-ptr start-ptr) + (user-go-to-start-all)) + user-offset)) + (user-getc-none + (lambda () + (if (< user-ptr start-ptr) + (user-go-to-start-none)) + (if (< user-ptr read-ptr) + (let ((c (string-ref buffer user-ptr))) + (set! user-ptr (+ user-ptr 1)) + c) + (let ((c (input-f))) + (if (char? c) + (begin + (if (= read-ptr buflen) + (reorganize-buffer)) + (string-set! buffer user-ptr c) + (set! read-ptr (+ read-ptr 1)) + (set! user-ptr read-ptr) + c) + (begin + (set! input-f (lambda () 'eof)) + 'eof)))))) + (user-getc-line + (lambda () + (if (< user-ptr start-ptr) + (user-go-to-start-line)) + (if (< user-ptr read-ptr) + (let ((c (string-ref buffer user-ptr))) + (set! user-ptr (+ user-ptr 1)) + (if (char=? c #\newline) + (set! user-line (+ user-line 1))) + c) + (let ((c (input-f))) + (if (char? c) + (begin + (if (= read-ptr buflen) + (reorganize-buffer)) + (string-set! buffer user-ptr c) + (set! read-ptr (+ read-ptr 1)) + (set! user-ptr read-ptr) + (if (char=? c #\newline) + (set! user-line (+ user-line 1))) + c) + (begin + (set! input-f (lambda () 'eof)) + 'eof)))))) + (user-getc-all + (lambda () + (if (< user-ptr start-ptr) + (user-go-to-start-all)) + (if (< user-ptr read-ptr) + (let ((c (string-ref buffer user-ptr))) + (set! user-ptr (+ user-ptr 1)) + (if (char=? c #\newline) + (begin + (set! user-line (+ user-line 1)) + (set! user-column 1)) + (set! user-column (+ user-column 1))) + (set! user-offset (+ user-offset 1)) + c) + (let ((c (input-f))) + (if (char? c) + (begin + (if (= read-ptr buflen) + (reorganize-buffer)) + (string-set! buffer user-ptr c) + (set! read-ptr (+ read-ptr 1)) + (set! user-ptr read-ptr) + (if (char=? c #\newline) + (begin + (set! user-line (+ user-line 1)) + (set! user-column 1)) + (set! user-column (+ user-column 1))) + (set! user-offset (+ user-offset 1)) + c) + (begin + (set! input-f (lambda () 'eof)) + 'eof)))))) + (user-ungetc-none + (lambda () + (if (> user-ptr start-ptr) + (set! user-ptr (- user-ptr 1))))) + (user-ungetc-line + (lambda () + (if (> user-ptr start-ptr) + (begin + (set! user-ptr (- user-ptr 1)) + (let ((c (string-ref buffer user-ptr))) + (if (char=? c #\newline) + (set! user-line (- user-line 1)))))))) + (user-ungetc-all + (lambda () + (if (> user-ptr start-ptr) + (begin + (set! user-ptr (- user-ptr 1)) + (let ((c (string-ref buffer user-ptr))) + (if (char=? c #\newline) + (begin + (set! user-line (- user-line 1)) + (set! user-up-to-date? #f)) + (set! user-column (- user-column 1))) + (set! user-offset (- user-offset 1))))))) + (reorganize-buffer ; Decaler ou agrandir le buffer + (lambda () + (if (< (* 2 start-ptr) buflen) + (let* ((newlen (* 2 buflen)) + (newbuf (make-string newlen)) + (delta (- start-ptr 1))) + (let loop ((from (- start-ptr 1))) + (if (< from buflen) + (begin + (string-set! newbuf + (- from delta) + (string-ref buffer from)) + (loop (+ from 1))))) + (set! buffer newbuf) + (set! buflen newlen) + (set! read-ptr (- read-ptr delta)) + (set! start-ptr (- start-ptr delta)) + (set! end-ptr (- end-ptr delta)) + (set! point-ptr (- point-ptr delta)) + (set! user-ptr (- user-ptr delta))) + (let ((delta (- start-ptr 1))) + (let loop ((from (- start-ptr 1))) + (if (< from buflen) + (begin + (string-set! buffer + (- from delta) + (string-ref buffer from)) + (loop (+ from 1))))) + (set! read-ptr (- read-ptr delta)) + (set! start-ptr (- start-ptr delta)) + (set! end-ptr (- end-ptr delta)) + (set! point-ptr (- point-ptr delta)) + (set! user-ptr (- user-ptr delta))))))) + (list (cons 'start-go-to-end + (cond ((eq? counters 'none) start-go-to-end-none) + ((eq? counters 'line) start-go-to-end-line) + ((eq? counters 'all ) start-go-to-end-all))) + (cons 'end-go-to-point + end-go-to-point) + (cons 'init-lexeme + (cond ((eq? counters 'none) init-lexeme-none) + ((eq? counters 'line) init-lexeme-line) + ((eq? counters 'all ) init-lexeme-all))) + (cons 'get-start-line + get-start-line) + (cons 'get-start-column + get-start-column) + (cons 'get-start-offset + get-start-offset) + (cons 'peek-left-context + peek-left-context) + (cons 'peek-char + peek-char) + (cons 'read-char + read-char) + (cons 'get-start-end-text + get-start-end-text) + (cons 'get-user-line + (cond ((eq? counters 'none) #f) + ((eq? counters 'line) get-user-line-line) + ((eq? counters 'all ) get-user-line-all))) + (cons 'get-user-column + (cond ((eq? counters 'none) #f) + ((eq? counters 'line) #f) + ((eq? counters 'all ) get-user-column-all))) + (cons 'get-user-offset + (cond ((eq? counters 'none) #f) + ((eq? counters 'line) #f) + ((eq? counters 'all ) get-user-offset-all))) + (cons 'user-getc + (cond ((eq? counters 'none) user-getc-none) + ((eq? counters 'line) user-getc-line) + ((eq? counters 'all ) user-getc-all))) + (cons 'user-ungetc + (cond ((eq? counters 'none) user-ungetc-none) + ((eq? counters 'line) user-ungetc-line) + ((eq? counters 'all ) user-ungetc-all)))))))) + +; Construit un Input System +; Le premier parametre doit etre parmi "port", "procedure" ou "string" +; Prend un parametre facultatif qui doit etre parmi +; "none", "line" ou "all" +(define lexer-make-IS + (lambda (input-type input . largs) + (let ((counters-type (cond ((null? largs) + 'line) + ((memq (car largs) '(none line all)) + (car largs)) + (else + 'line)))) + (cond ((and (eq? input-type 'port) (input-port? input)) + (let* ((buffer (make-string lexer-init-buffer-len #\newline)) + (read-ptr 1) + (input-f (lambda () (read-char input)))) + (lexer-raw-IS-maker buffer read-ptr input-f counters-type))) + ((and (eq? input-type 'procedure) (procedure? input)) + (let* ((buffer (make-string lexer-init-buffer-len #\newline)) + (read-ptr 1) + (input-f input)) + (lexer-raw-IS-maker buffer read-ptr input-f counters-type))) + ((and (eq? input-type 'string) (string? input)) + (let* ((buffer (string-append (string #\newline) input)) + (read-ptr (string-length buffer)) + (input-f (lambda () 'eof))) + (lexer-raw-IS-maker buffer read-ptr input-f counters-type))) + (else + (let* ((buffer (string #\newline)) + (read-ptr 1) + (input-f (lambda () 'eof))) + (lexer-raw-IS-maker buffer read-ptr input-f counters-type))))))) + +; Les fonctions: +; lexer-get-func-getc, lexer-get-func-ungetc, +; lexer-get-func-line, lexer-get-func-column et lexer-get-func-offset +(define lexer-get-func-getc + (lambda (IS) (cdr (assq 'user-getc IS)))) +(define lexer-get-func-ungetc + (lambda (IS) (cdr (assq 'user-ungetc IS)))) +(define lexer-get-func-line + (lambda (IS) (cdr (assq 'get-user-line IS)))) +(define lexer-get-func-column + (lambda (IS) (cdr (assq 'get-user-column IS)))) +(define lexer-get-func-offset + (lambda (IS) (cdr (assq 'get-user-offset IS)))) + +; +; Gestion des lexers +; + +; Fabrication de lexer a partir d'arbres de decision +(define lexer-make-tree-lexer + (lambda (tables IS) + (letrec + (; Contenu de la table + (counters-type (vector-ref tables 0)) + (<>-pre-action (vector-ref tables 1)) + (<>-pre-action (vector-ref tables 2)) + (rules-pre-actions (vector-ref tables 3)) + (table-nl-start (vector-ref tables 5)) + (table-no-nl-start (vector-ref tables 6)) + (trees-v (vector-ref tables 7)) + (acc-v (vector-ref tables 8)) + + ; Contenu du IS + (IS-start-go-to-end (cdr (assq 'start-go-to-end IS))) + (IS-end-go-to-point (cdr (assq 'end-go-to-point IS))) + (IS-init-lexeme (cdr (assq 'init-lexeme IS))) + (IS-get-start-line (cdr (assq 'get-start-line IS))) + (IS-get-start-column (cdr (assq 'get-start-column IS))) + (IS-get-start-offset (cdr (assq 'get-start-offset IS))) + (IS-peek-left-context (cdr (assq 'peek-left-context IS))) + (IS-peek-char (cdr (assq 'peek-char IS))) + (IS-read-char (cdr (assq 'read-char IS))) + (IS-get-start-end-text (cdr (assq 'get-start-end-text IS))) + (IS-get-user-line (cdr (assq 'get-user-line IS))) + (IS-get-user-column (cdr (assq 'get-user-column IS))) + (IS-get-user-offset (cdr (assq 'get-user-offset IS))) + (IS-user-getc (cdr (assq 'user-getc IS))) + (IS-user-ungetc (cdr (assq 'user-ungetc IS))) + + ; Resultats + (<>-action #f) + (<>-action #f) + (rules-actions #f) + (states #f) + (final-lexer #f) + + ; Gestion des hooks + (hook-list '()) + (add-hook + (lambda (thunk) + (set! hook-list (cons thunk hook-list)))) + (apply-hooks + (lambda () + (let loop ((l hook-list)) + (if (pair? l) + (begin + ((car l)) + (loop (cdr l))))))) + + ; Preparation des actions + (set-action-statics + (lambda (pre-action) + (pre-action final-lexer IS-user-getc IS-user-ungetc))) + (prepare-special-action-none + (lambda (pre-action) + (let ((action #f)) + (let ((result + (lambda () + (action ""))) + (hook + (lambda () + (set! action (set-action-statics pre-action))))) + (add-hook hook) + result)))) + (prepare-special-action-line + (lambda (pre-action) + (let ((action #f)) + (let ((result + (lambda (yyline) + (action "" yyline))) + (hook + (lambda () + (set! action (set-action-statics pre-action))))) + (add-hook hook) + result)))) + (prepare-special-action-all + (lambda (pre-action) + (let ((action #f)) + (let ((result + (lambda (yyline yycolumn yyoffset) + (action "" yyline yycolumn yyoffset))) + (hook + (lambda () + (set! action (set-action-statics pre-action))))) + (add-hook hook) + result)))) + (prepare-special-action + (lambda (pre-action) + (cond ((eq? counters-type 'none) + (prepare-special-action-none pre-action)) + ((eq? counters-type 'line) + (prepare-special-action-line pre-action)) + ((eq? counters-type 'all) + (prepare-special-action-all pre-action))))) + (prepare-action-yytext-none + (lambda (pre-action) + (let ((get-start-end-text IS-get-start-end-text) + (start-go-to-end IS-start-go-to-end) + (action #f)) + (let ((result + (lambda () + (let ((yytext (get-start-end-text))) + (start-go-to-end) + (action yytext)))) + (hook + (lambda () + (set! action (set-action-statics pre-action))))) + (add-hook hook) + result)))) + (prepare-action-yytext-line + (lambda (pre-action) + (let ((get-start-end-text IS-get-start-end-text) + (start-go-to-end IS-start-go-to-end) + (action #f)) + (let ((result + (lambda (yyline) + (let ((yytext (get-start-end-text))) + (start-go-to-end) + (action yytext yyline)))) + (hook + (lambda () + (set! action (set-action-statics pre-action))))) + (add-hook hook) + result)))) + (prepare-action-yytext-all + (lambda (pre-action) + (let ((get-start-end-text IS-get-start-end-text) + (start-go-to-end IS-start-go-to-end) + (action #f)) + (let ((result + (lambda (yyline yycolumn yyoffset) + (let ((yytext (get-start-end-text))) + (start-go-to-end) + (action yytext yyline yycolumn yyoffset)))) + (hook + (lambda () + (set! action (set-action-statics pre-action))))) + (add-hook hook) + result)))) + (prepare-action-yytext + (lambda (pre-action) + (cond ((eq? counters-type 'none) + (prepare-action-yytext-none pre-action)) + ((eq? counters-type 'line) + (prepare-action-yytext-line pre-action)) + ((eq? counters-type 'all) + (prepare-action-yytext-all pre-action))))) + (prepare-action-no-yytext-none + (lambda (pre-action) + (let ((start-go-to-end IS-start-go-to-end) + (action #f)) + (let ((result + (lambda () + (start-go-to-end) + (action))) + (hook + (lambda () + (set! action (set-action-statics pre-action))))) + (add-hook hook) + result)))) + (prepare-action-no-yytext-line + (lambda (pre-action) + (let ((start-go-to-end IS-start-go-to-end) + (action #f)) + (let ((result + (lambda (yyline) + (start-go-to-end) + (action yyline))) + (hook + (lambda () + (set! action (set-action-statics pre-action))))) + (add-hook hook) + result)))) + (prepare-action-no-yytext-all + (lambda (pre-action) + (let ((start-go-to-end IS-start-go-to-end) + (action #f)) + (let ((result + (lambda (yyline yycolumn yyoffset) + (start-go-to-end) + (action yyline yycolumn yyoffset))) + (hook + (lambda () + (set! action (set-action-statics pre-action))))) + (add-hook hook) + result)))) + (prepare-action-no-yytext + (lambda (pre-action) + (cond ((eq? counters-type 'none) + (prepare-action-no-yytext-none pre-action)) + ((eq? counters-type 'line) + (prepare-action-no-yytext-line pre-action)) + ((eq? counters-type 'all) + (prepare-action-no-yytext-all pre-action))))) + + ; Fabrique les fonctions de dispatch + (prepare-dispatch-err + (lambda (leaf) + (lambda (c) + #f))) + (prepare-dispatch-number + (lambda (leaf) + (let ((state-function #f)) + (let ((result + (lambda (c) + state-function)) + (hook + (lambda () + (set! state-function (vector-ref states leaf))))) + (add-hook hook) + result)))) + (prepare-dispatch-leaf + (lambda (leaf) + (if (eq? leaf 'err) + (prepare-dispatch-err leaf) + (prepare-dispatch-number leaf)))) + (prepare-dispatch-< + (lambda (tree) + (let ((left-tree (list-ref tree 1)) + (right-tree (list-ref tree 2))) + (let ((bound (list-ref tree 0)) + (left-func (prepare-dispatch-tree left-tree)) + (right-func (prepare-dispatch-tree right-tree))) + (lambda (c) + (if (< c bound) + (left-func c) + (right-func c))))))) + (prepare-dispatch-= + (lambda (tree) + (let ((left-tree (list-ref tree 2)) + (right-tree (list-ref tree 3))) + (let ((bound (list-ref tree 1)) + (left-func (prepare-dispatch-tree left-tree)) + (right-func (prepare-dispatch-tree right-tree))) + (lambda (c) + (if (= c bound) + (left-func c) + (right-func c))))))) + (prepare-dispatch-tree + (lambda (tree) + (cond ((not (pair? tree)) + (prepare-dispatch-leaf tree)) + ((eq? (car tree) '=) + (prepare-dispatch-= tree)) + (else + (prepare-dispatch-< tree))))) + (prepare-dispatch + (lambda (tree) + (let ((dicho-func (prepare-dispatch-tree tree))) + (lambda (c) + (and c (dicho-func c)))))) + + ; Fabrique les fonctions de transition (read & go) et (abort) + (prepare-read-n-go + (lambda (tree) + (let ((dispatch-func (prepare-dispatch tree)) + (read-char IS-read-char)) + (lambda () + (dispatch-func (read-char)))))) + (prepare-abort + (lambda (tree) + (lambda () + #f))) + (prepare-transition + (lambda (tree) + (if (eq? tree 'err) + (prepare-abort tree) + (prepare-read-n-go tree)))) + + ; Fabrique les fonctions d'etats ([set-end] & trans) + (prepare-state-no-acc + (lambda (s r1 r2) + (let ((trans-func (prepare-transition (vector-ref trees-v s)))) + (lambda (action) + (let ((next-state (trans-func))) + (if next-state + (next-state action) + action)))))) + (prepare-state-yes-no + (lambda (s r1 r2) + (let ((peek-char IS-peek-char) + (end-go-to-point IS-end-go-to-point) + (new-action1 #f) + (trans-func (prepare-transition (vector-ref trees-v s)))) + (let ((result + (lambda (action) + (let* ((c (peek-char)) + (new-action + (if (or (not c) (= c lexer-integer-newline)) + (begin + (end-go-to-point) + new-action1) + action)) + (next-state (trans-func))) + (if next-state + (next-state new-action) + new-action)))) + (hook + (lambda () + (set! new-action1 (vector-ref rules-actions r1))))) + (add-hook hook) + result)))) + (prepare-state-diff-acc + (lambda (s r1 r2) + (let ((end-go-to-point IS-end-go-to-point) + (peek-char IS-peek-char) + (new-action1 #f) + (new-action2 #f) + (trans-func (prepare-transition (vector-ref trees-v s)))) + (let ((result + (lambda (action) + (end-go-to-point) + (let* ((c (peek-char)) + (new-action + (if (or (not c) (= c lexer-integer-newline)) + new-action1 + new-action2)) + (next-state (trans-func))) + (if next-state + (next-state new-action) + new-action)))) + (hook + (lambda () + (set! new-action1 (vector-ref rules-actions r1)) + (set! new-action2 (vector-ref rules-actions r2))))) + (add-hook hook) + result)))) + (prepare-state-same-acc + (lambda (s r1 r2) + (let ((end-go-to-point IS-end-go-to-point) + (trans-func (prepare-transition (vector-ref trees-v s))) + (new-action #f)) + (let ((result + (lambda (action) + (end-go-to-point) + (let ((next-state (trans-func))) + (if next-state + (next-state new-action) + new-action)))) + (hook + (lambda () + (set! new-action (vector-ref rules-actions r1))))) + (add-hook hook) + result)))) + (prepare-state + (lambda (s) + (let* ((acc (vector-ref acc-v s)) + (r1 (car acc)) + (r2 (cdr acc))) + (cond ((not r1) (prepare-state-no-acc s r1 r2)) + ((not r2) (prepare-state-yes-no s r1 r2)) + ((< r1 r2) (prepare-state-diff-acc s r1 r2)) + (else (prepare-state-same-acc s r1 r2)))))) + + ; Fabrique la fonction de lancement du lexage a l'etat de depart + (prepare-start-same + (lambda (s1 s2) + (let ((peek-char IS-peek-char) + (eof-action #f) + (start-state #f) + (error-action #f)) + (let ((result + (lambda () + (if (not (peek-char)) + eof-action + (start-state error-action)))) + (hook + (lambda () + (set! eof-action <>-action) + (set! start-state (vector-ref states s1)) + (set! error-action <>-action)))) + (add-hook hook) + result)))) + (prepare-start-diff + (lambda (s1 s2) + (let ((peek-char IS-peek-char) + (eof-action #f) + (peek-left-context IS-peek-left-context) + (start-state1 #f) + (start-state2 #f) + (error-action #f)) + (let ((result + (lambda () + (cond ((not (peek-char)) + eof-action) + ((= (peek-left-context) lexer-integer-newline) + (start-state1 error-action)) + (else + (start-state2 error-action))))) + (hook + (lambda () + (set! eof-action <>-action) + (set! start-state1 (vector-ref states s1)) + (set! start-state2 (vector-ref states s2)) + (set! error-action <>-action)))) + (add-hook hook) + result)))) + (prepare-start + (lambda () + (let ((s1 table-nl-start) + (s2 table-no-nl-start)) + (if (= s1 s2) + (prepare-start-same s1 s2) + (prepare-start-diff s1 s2))))) + + ; Fabrique la fonction principale + (prepare-lexer-none + (lambda () + (let ((init-lexeme IS-init-lexeme) + (start-func (prepare-start))) + (lambda () + (init-lexeme) + ((start-func)))))) + (prepare-lexer-line + (lambda () + (let ((init-lexeme IS-init-lexeme) + (get-start-line IS-get-start-line) + (start-func (prepare-start))) + (lambda () + (init-lexeme) + (let ((yyline (get-start-line))) + ((start-func) yyline)))))) + (prepare-lexer-all + (lambda () + (let ((init-lexeme IS-init-lexeme) + (get-start-line IS-get-start-line) + (get-start-column IS-get-start-column) + (get-start-offset IS-get-start-offset) + (start-func (prepare-start))) + (lambda () + (init-lexeme) + (let ((yyline (get-start-line)) + (yycolumn (get-start-column)) + (yyoffset (get-start-offset))) + ((start-func) yyline yycolumn yyoffset)))))) + (prepare-lexer + (lambda () + (cond ((eq? counters-type 'none) (prepare-lexer-none)) + ((eq? counters-type 'line) (prepare-lexer-line)) + ((eq? counters-type 'all) (prepare-lexer-all)))))) + + ; Calculer la valeur de <>-action et de <>-action + (set! <>-action (prepare-special-action <>-pre-action)) + (set! <>-action (prepare-special-action <>-pre-action)) + + ; Calculer la valeur de rules-actions + (let* ((len (quotient (vector-length rules-pre-actions) 2)) + (v (make-vector len))) + (let loop ((r (- len 1))) + (if (< r 0) + (set! rules-actions v) + (let* ((yytext? (vector-ref rules-pre-actions (* 2 r))) + (pre-action (vector-ref rules-pre-actions (+ (* 2 r) 1))) + (action (if yytext? + (prepare-action-yytext pre-action) + (prepare-action-no-yytext pre-action)))) + (vector-set! v r action) + (loop (- r 1)))))) + + ; Calculer la valeur de states + (let* ((len (vector-length trees-v)) + (v (make-vector len))) + (let loop ((s (- len 1))) + (if (< s 0) + (set! states v) + (begin + (vector-set! v s (prepare-state s)) + (loop (- s 1)))))) + + ; Calculer la valeur de final-lexer + (set! final-lexer (prepare-lexer)) + + ; Executer les hooks + (apply-hooks) + + ; Resultat + final-lexer))) + +; Fabrication de lexer a partir de listes de caracteres taggees +(define lexer-make-char-lexer + (let* ((char->class + (lambda (c) + (let ((n (char->integer c))) + (list (cons n n))))) + (merge-sort + (lambda (l combine zero-elt) + (if (null? l) + zero-elt + (let loop1 ((l l)) + (if (null? (cdr l)) + (car l) + (loop1 + (let loop2 ((l l)) + (cond ((null? l) + l) + ((null? (cdr l)) + l) + (else + (cons (combine (car l) (cadr l)) + (loop2 (cddr l)))))))))))) + (finite-class-union + (lambda (c1 c2) + (let loop ((c1 c1) (c2 c2) (u '())) + (if (null? c1) + (if (null? c2) + (reverse u) + (loop c1 (cdr c2) (cons (car c2) u))) + (if (null? c2) + (loop (cdr c1) c2 (cons (car c1) u)) + (let* ((r1 (car c1)) + (r2 (car c2)) + (r1start (car r1)) + (r1end (cdr r1)) + (r2start (car r2)) + (r2end (cdr r2))) + (if (<= r1start r2start) + (cond ((< (+ r1end 1) r2start) + (loop (cdr c1) c2 (cons r1 u))) + ((<= r1end r2end) + (loop (cdr c1) + (cons (cons r1start r2end) (cdr c2)) + u)) + (else + (loop c1 (cdr c2) u))) + (cond ((> r1start (+ r2end 1)) + (loop c1 (cdr c2) (cons r2 u))) + ((>= r1end r2end) + (loop (cons (cons r2start r1end) (cdr c1)) + (cdr c2) + u)) + (else + (loop (cdr c1) c2 u)))))))))) + (char-list->class + (lambda (cl) + (let ((classes (map char->class cl))) + (merge-sort classes finite-class-union '())))) + (class-< + (lambda (b1 b2) + (cond ((eq? b1 'inf+) #f) + ((eq? b2 'inf-) #f) + ((eq? b1 'inf-) #t) + ((eq? b2 'inf+) #t) + (else (< b1 b2))))) + (finite-class-compl + (lambda (c) + (let loop ((c c) (start 'inf-)) + (if (null? c) + (list (cons start 'inf+)) + (let* ((r (car c)) + (rstart (car r)) + (rend (cdr r))) + (if (class-< start rstart) + (cons (cons start (- rstart 1)) + (loop c rstart)) + (loop (cdr c) (+ rend 1)))))))) + (tagged-chars->class + (lambda (tcl) + (let* ((inverse? (car tcl)) + (cl (cdr tcl)) + (class-tmp (char-list->class cl))) + (if inverse? (finite-class-compl class-tmp) class-tmp)))) + (charc->arc + (lambda (charc) + (let* ((tcl (car charc)) + (dest (cdr charc)) + (class (tagged-chars->class tcl))) + (cons class dest)))) + (arc->sharcs + (lambda (arc) + (let* ((range-l (car arc)) + (dest (cdr arc)) + (op (lambda (range) (cons range dest)))) + (map op range-l)))) + (class-<= + (lambda (b1 b2) + (cond ((eq? b1 'inf-) #t) + ((eq? b2 'inf+) #t) + ((eq? b1 'inf+) #f) + ((eq? b2 'inf-) #f) + (else (<= b1 b2))))) + (sharc-<= + (lambda (sharc1 sharc2) + (class-<= (caar sharc1) (caar sharc2)))) + (merge-sharcs + (lambda (l1 l2) + (let loop ((l1 l1) (l2 l2)) + (cond ((null? l1) + l2) + ((null? l2) + l1) + (else + (let ((sharc1 (car l1)) + (sharc2 (car l2))) + (if (sharc-<= sharc1 sharc2) + (cons sharc1 (loop (cdr l1) l2)) + (cons sharc2 (loop l1 (cdr l2)))))))))) + (class-= eqv?) + (fill-error + (lambda (sharcs) + (let loop ((sharcs sharcs) (start 'inf-)) + (cond ((class-= start 'inf+) + '()) + ((null? sharcs) + (cons (cons (cons start 'inf+) 'err) + (loop sharcs 'inf+))) + (else + (let* ((sharc (car sharcs)) + (h (caar sharc)) + (t (cdar sharc))) + (if (class-< start h) + (cons (cons (cons start (- h 1)) 'err) + (loop sharcs h)) + (cons sharc (loop (cdr sharcs) + (if (class-= t 'inf+) + 'inf+ + (+ t 1))))))))))) + (charcs->tree + (lambda (charcs) + (let* ((op (lambda (charc) (arc->sharcs (charc->arc charc)))) + (sharcs-l (map op charcs)) + (sorted-sharcs (merge-sort sharcs-l merge-sharcs '())) + (full-sharcs (fill-error sorted-sharcs)) + (op (lambda (sharc) (cons (caar sharc) (cdr sharc)))) + (table (list->vector (map op full-sharcs)))) + (let loop ((left 0) (right (- (vector-length table) 1))) + (if (= left right) + (cdr (vector-ref table left)) + (let ((mid (quotient (+ left right 1) 2))) + (if (and (= (+ left 2) right) + (= (+ (car (vector-ref table mid)) 1) + (car (vector-ref table right))) + (eqv? (cdr (vector-ref table left)) + (cdr (vector-ref table right)))) + (list '= + (car (vector-ref table mid)) + (cdr (vector-ref table mid)) + (cdr (vector-ref table left))) + (list (car (vector-ref table mid)) + (loop left (- mid 1)) + (loop mid right)))))))))) + (lambda (tables IS) + (let ((counters (vector-ref tables 0)) + (<>-action (vector-ref tables 1)) + (<>-action (vector-ref tables 2)) + (rules-actions (vector-ref tables 3)) + (nl-start (vector-ref tables 5)) + (no-nl-start (vector-ref tables 6)) + (charcs-v (vector-ref tables 7)) + (acc-v (vector-ref tables 8))) + (let* ((len (vector-length charcs-v)) + (v (make-vector len))) + (let loop ((i (- len 1))) + (if (>= i 0) + (begin + (vector-set! v i (charcs->tree (vector-ref charcs-v i))) + (loop (- i 1))) + (lexer-make-tree-lexer + (vector counters + <>-action + <>-action + rules-actions + 'decision-trees + nl-start + no-nl-start + v + acc-v) + IS)))))))) + +; Fabrication d'un lexer a partir de code pre-genere +(define lexer-make-code-lexer + (lambda (tables IS) + (let ((<>-pre-action (vector-ref tables 1)) + (<>-pre-action (vector-ref tables 2)) + (rules-pre-action (vector-ref tables 3)) + (code (vector-ref tables 5))) + (code <>-pre-action <>-pre-action rules-pre-action IS)))) + +(define lexer-make-lexer + (lambda (tables IS) + (let ((automaton-type (vector-ref tables 4))) + (cond ((eq? automaton-type 'decision-trees) + (lexer-make-tree-lexer tables IS)) + ((eq? automaton-type 'tagged-chars-lists) + (lexer-make-char-lexer tables IS)) + ((eq? automaton-type 'code) + (lexer-make-code-lexer tables IS)))))) + +; +; Table generated from the file twiki.l by SILex 1.0 +; + +(define lexer-default-table + (vector + 'line + (lambda (yycontinue yygetc yyungetc) + (lambda (yytext yyline) + (list 'end-of-input #f ) ;; yyline) + )) + (lambda (yycontinue yygetc yyungetc) + (lambda (yytext yyline) + (lex-error (conc yyline " : illegal character ") (yygetc)) + )) + (vector + #t + (lambda (yycontinue yygetc yyungetc) + (lambda (yytext yyline) + (list 'opensq yytext) + )) + #t + (lambda (yycontinue yygetc yyungetc) + (lambda (yytext yyline) + (list 'closesq yytext) + )) + #t + (lambda (yycontinue yygetc yyungetc) + (lambda (yytext yyline) + (list 'opensquig yytext) + )) + #t + (lambda (yycontinue yygetc yyungetc) + (lambda (yytext yyline) + (list 'closesquig yytext) + )) + #t + (lambda (yycontinue yygetc yyungetc) + (lambda (yytext yyline) + (list 'bang yytext) + )) + #t + (lambda (yycontinue yygetc yyungetc) + (lambda (yytext yyline) + (list 'plaintext yytext) + ))) + 'decision-trees + 0 + 0 + '#((59 (35 (32 (9 err (11 1 err)) (33 1 (34 2 err))) (38 (= 36 err 1) + (44 (39 err 1) (45 err 1)))) (95 (92 (65 err (91 1 6)) (93 1 (94 5 + err))) (123 (= 96 err 1) (125 (124 4 err) (126 3 err))))) (44 (35 (11 + (9 err 1) (= 32 1 err)) (37 (36 1 err) (= 38 err 1))) (92 (59 (45 err + 1) (65 err (91 1 err))) (96 (93 1 (95 err 1)) (97 err (123 1 err))))) + err err err err err) + '#((#f . #f) (5 . 5) (4 . 4) (3 . 3) (2 . 2) (1 . 1) (0 . 0)))) + +; +; User functions +; + +(define lexer #f) + +(define lexer-get-line #f) +(define lexer-getc #f) +(define lexer-ungetc #f) + +(define lexer-init + (lambda (input-type input) + (let ((IS (lexer-make-IS input-type input 'line))) + (set! lexer (lexer-make-lexer lexer-default-table IS)) + (set! lexer-get-line (lexer-get-func-line IS)) + (set! lexer-getc (lexer-get-func-getc IS)) + (set! lexer-ungetc (lexer-get-func-ungetc IS))))) ADDED modules/twiki/twiki.scm Index: modules/twiki/twiki.scm ================================================================== --- /dev/null +++ modules/twiki/twiki.scm @@ -0,0 +1,68 @@ +;; twiki module +(require-extension silex sqlite3 regex posix) + +(include "twiki.l.scm") + +(define (twiki:open-db keys) + (let* ((fname (twiki:keys->fname keys)) + (fexists (file-exists? fname)) + (db (dbi:open 'sqlite3 '((dbname . fname))))) + (if (not fexists) + (for-each + (lambda (sqry) + (dbi:exec db sqry)) + '("CREATE TABLE dats (id INTEGER PRIMARY KEY,md5sum TEXT,dat BLOB,type INTEGER);" + "CREATE TABLE tiddlers (id INTEGER PRIMARY KEY,wiki_id INTEGER,name TEXT,rev INTEGER,dat_id INTEGER,created_on INTEGER,changed_on INTEGER,owner_id INTEGER);" + "CREATE TABLE revs (id INTEGER PRIMARY KEY,tag TEXT);" + "CREATE TABLE wikis (id INTEGER PRIMARY KEY,key_name TEXT,title TEXT,created_on INTEGER);"))) + (sqlite3:set-busy-timeout!(dbi:db-conn db) 1000000) + db)) + +(define (twiki:view) + (s:div 'class "node" + (s:h1 "Twiki") + "Title, pictures, etc." + (let () + "blah"))) + + +(define (twiki:wiki . keys) + (let ((key (conc keys))) + (twiki:view))) + +(define (twiki:extract-tiddlers dat) + (let* ((inp (open-input-string dat)) + (prev-state #f) + (stack (list 'start)) + (links '()) + (currlnk #f)) + (lexer-init 'port inp) + (let loop ((token (lexer))) + (let ((token-type (car token)) + (token-val (cadr token)) + (state (car stack))) + (if (not (eq? prev-state state)) + (begin + (print "state: " state) + (set! prev-state state))) + (case token-type + ('end-of-input (print "Done")(close-input-port inp)) + ('twikilink-start + (set! stack (cons 'twikilink-start stack)) + (loop (lexer))) + ('twikilink-end + (set! links (cons currlnk links)) + (set! stack (cdr stack)) + (loop (lexer))) + ('twikitext + (if (eq? state 'twikilink-start) + (set! currlnk (cadr token)) + (print "Got " token)) + (loop (lexer))) + ('anydat + (loop (lexer))) + (else + (print "ERROR: unknown token " token " on line " (lexer-get-line)) + (loop (lexer)))))) + links)) + ADDED modules/twiki/twikiparser.scm Index: modules/twiki/twikiparser.scm ================================================================== --- /dev/null +++ modules/twiki/twikiparser.scm @@ -0,0 +1,457 @@ + +(require-extension sqlite3 regex posix eformat silex stack regex) + +(define help " +Usage: nldb [options] + + +General + -h : this help + +Netlist data queries + + -findpath start,end : find path from start to end. % is a wildcard + +Managing netlist data + + -load /path/to/netlist : load a model into the db + -d dbname : name of the .db file + -dump fname : dump the netlist in to verilog file + +") + +(include "/nfs/an/home/mrwellan/stuff/tools/lnkmkr/args.scm") +(include "verilog.l.scm") + +;; process args +(define remargs (get-args (argv) + (list "-load" + "-d" "-dump" + "-findpath") + + (list "-h" + ) + arg-hash + 0)) ;; + +(define dbpaths (list "testing.db")) + +(define dbpath #f) + +(if (get-arg "-d") + (set! dbpath (get-arg "-d")) + (for-each + (lambda (path) + (if (file-exists? path) + (set! dbpath path))) + dbpaths)) + +(if (and (not dbpath) (get-arg "-d")) + (begin + (print "Can't find db. " (get-arg "-d") " Try again or contact Matt!") + (exit 1))) + +(define dbexists (file-exists? dbpath)) + +(define realuser (getenv "USER")) +(define user realuser) + +(define db (sqlite3:open dbpath)) +(sqlite3:set-busy-timeout! db 1000000) + +(define (mk-tables) + (for-each + (lambda (sqlstmt) + (sqlite3:exec db sqlstmt)) + (list "CREATE TABLE modules(id INTEGER PRIMARY KEY,name_id INTEGER);" + "CREATE TABLE nets (id INTEGER PRIMARY KEY,name_id INTEGER,module_id INTEGER);" + "CREATE TABLE insts (id INTEGER PRIMARY KEY,name_id INTEGER,module_id INTEGER,parent_id INTEGER);" + "CREATE TABLE pins (id INTEGER PRIMARY KEY,name_id INTEGER,module_id INTEGER,net_id INTEGER,type_id INTEGER);" + "CREATE TABLE conns (id INTEGER PRIMARY KEY,net_id INTEGER,inst_id INTEGER,pin_id INTEGER);" + "CREATE TABLE names (id INTEGER PRIMARY KEY,name TEXT);" + "CREATE TABLE types(id INTEGER PRIMARY KEY,type TEXT);" + "INSERT INTO types VALUES(1, 'undef');" + "INSERT INTO types VALUES(2, 'input');" + "INSERT INTO types VALUES(3, 'output');" + "INSERT INTO types VALUES(4, 'inout');" + "INSERT INTO types VALUES(5, 'pwr');" + "PRAGMA synchronous=OFF;"))) + +(if (not dbexists)(mk-tables)) + +;;====================================================================== +;; NETLIST READING +;;====================================================================== + +;; Use a stack to tracking state +;; +(define nldb:*stack* (make-stack)) + +(define (nldb:read-files fnames) ;; read in a list of files + (for-each + (lambda (fname) + (if (file-exists? fname) + (nldb:read-file fname))) + fnames)) + +;;====================================================================== +;; PRECOMPILED REGEXS +;;====================================================================== + +(define nldb:escaped-name (regexp "^\\s*\\\\([^\\s]+)\\s*")) +(define nldb:trailing-garbage (regexp "^\\s*([^\\s,;]+)[,;\\s]*$")) +(define nldb:module-pin (regexp "^\\s*([^\\s]+)\\s*([,\\s\\)]*)")) +(define nldb:pins-end (regexp "\\)\\s*;")) +(define nldb:input-output (regexp "\\s*(input|output)\\s+([^\\s]+)[\\s;,]")) + +;; modname instname( .\pinname[35] (\netname ), +(define nldb:instance (regexp "^\\s*([^\\s]+)\\s+([^\\s]+)\\s*\\(\\s*\\.([^\\s]+)\\s*\\(\\s*([^\\s]+)\\s*\\)\\s*,")) +(define nldb:inst-conn (regexp "^\\s*\\.([^\\s]+)\\s*\\(\\s*([^\\s])+\\s+\\)\\s*([\\),;]+)")) + +;; module_name netname (opt) +(define nldb:module-regex (regexp "^\\s*module\\s+([^\\s]+)\\s*\\(\\s*([^\\s,]+\\s*,|)$")) + +;;====================================================================== +;; MISC +;;====================================================================== + +;; apply regex and set nldb:match-val +(define nldb:match-val #f) +(define (nldb:regex-match r l) + (let ((m (string-match r l))) + (set! nldb:match-val m) m)) + +;; stmt can only return *one* value!! +(define (nldb:sqlite3:get-one stmt . params) + (let ((sqlstmt (sqlite3:prepare db stmt)) + (result #f)) + (apply sqlite3:for-each-row + (lambda (x) + (set! result x)) sqlstmt params) + (sqlite3:finalize! sqlstmt) + result)) + +;;====================================================================== +;; CACHE +;;====================================================================== + +(define *cache* (make-hash-table)) +(define *module-name-cache* (make-hash-table)) + +(define (cache-get-module-hash module) + (sub-hash-create-get *cache* module)) + +(define (sub-hash-create-get subhash key) + (let ((shash (hash-table-get/default subhash key))) + (if shash shash + (let ((newh (make-hash-table))) + (hash-table-set! subhash key newh) + newh)))) + +;; (cache-set! "abc_adder" 'pin "addrin" 0) +(define (cache-set! module objtype objname value) + (let* ((mhash (cache-get-module-hash module)) + (thash (sub-hash-create-get mhash objtype))) + (hash-table-set! thash objname value))) + +(define (cache-ref module objtype objname) + (let ((mhash (hash-table-ref/default *cache* module))) + (if mhash + (let ((ohash (hash-table-ref/default mhash objtype))) + (if ohash + (hash-table-ref/default ohash objname) + #f)) + #f))) + +;;====================================================================== +;; NAMES +;;====================================================================== + +(define nldb:names-hash (make-hash-table)) + +;; always sucessful. inserts name if not found +(define (nldb:get-name-id name) + (let ((cached-id (hash-table-ref/default nldb:names-hash name #f))) + (if cached-id cached-id + (let ((id (nldb:sqlite3:get-one "SELECT id FROM names WHERE name=?;" name))) + (if id + (begin + (hash-table-set! nldb:names-hash name id ) + id) + (begin + (sqlite3:exec db "INSERT INTO names (name) VALUES (?);" name) + (nldb:get-name-id name))))))) + +(define (nldb:clean-name name) + (if (nldb:regex-match nldb:escaped-name name) ;; process escaped identifiers + (list-ref nldb:match-val 1) + (if (nldb:regex-match nldb:trailing-garbage name) + (list-ref nldb:match-val 1) + name))) + +;;====================================================================== +;; MODULES +;;====================================================================== + +;; add a module and return its id. +(define (nldb:get-module-id name-id) + (let ((id (nldb:sqlite3:get-one + "SELECT id FROM modules WHERE name_id=?;" name-id))) + (if id id + (begin + (nldb:insert-module name-id) + (nldb:get-module-id name-id))))) ;; now retrieve and return the id + +;; not safe to use outside of get-module-id - could add duplicates +(define (nldb:insert-module name-id) + (sqlite3:exec db "INSERT INTO modules (name_id) VALUES (?);" name-id)) + +;; module namespace is unique so this is ok, should check for redefining though. +(define (nldb:get-module-by-name name) + (let ((module-id (hash-table-ref *module-name-cache* name))) + (if module-id module-id + (let ((mid (nldb:get-module-id (nldb:get-name-id name)))) + (hash-table-set! *module-name-cache* name mid))))) + +;;====================================================================== +;; PINS +;;====================================================================== + +(define (nldb:get-pin-id module-id name-id) + (nldb:sqlite3:get-one + (string-append "SELECT id FROM pins WHERE module_id=? AND name_id=?;") + module-id name-id)) + +(define (nldb:add-pin module-id name-id type-id) + (let ((pin-id (nldb:get-pin-id module-id name-id))) + (if pin-id pin-id + (begin + (nldb:insert-pin module-id name-id type-id) + (nldb:get-pin-id module-id name-id))))) + +(define (nldb:insert-pin module-id name-id type-id) + (sqlite3:exec db "INSERT INTO pins (module_id,name_id,type_id) VALUES (?,?,?);" + module-id name-id (if type-id type-id 0))) + +(define (nldb:set-pin-direction pin-id direction) + (sqlite3:exec db "UPDATE pins SET type_id=(SELECT id FROM types WHERE type=?) WHERE id=?;" direction pin-id)) + +(define (nldb:set-pin-net pin-id net-id) + (sqlite3:exec db "UPDATE pins SET net_id=? WHERE id=?;" net-id pin-id)) + +;;==================================================================== +;; CONNS +;;====================================================================== + +(define (nldb:get-conn-id inst-id pin-id) + ;; (if (not (and inst-id pin-id))(print "ERROR: nldb:get-conn-id called with bad params: inst-id " inst-id " pin-id " pin-id) + (nldb:sqlite3:get-one "SELECT id FROM conns WHERE inst_id=? AND pin_id=?;" inst-id pin-id)) + +(define (nldb:add-conn inst-id pin-id net-id) + ;; (if (not (and inst-id pin-id net-id))(print "ERROR: nldb:add-conn called with bad params: inst-id " inst-id " pin-id " pin-id " net-id " net-id) + (let ((conn-id (nldb:get-conn-id inst-id pin-id))) + (if conn-id conn-id + (begin + (nldb:insert-conn inst-id pin-id net-id) + (nldb:get-conn-id inst-id pin-id))))) + +(define (nldb:insert-conn inst-id pin-id net-id) + ;; (if (not (and inst-id pin-id net-id))(print "ERROR: nldb:insert-conn called with bad params: inst-id " inst-id " pin-id " pin-id " net-id " net-id) + (sqlite3:exec db "INSERT INTO conns (inst_id,pin_id,net_id) VALUES (?,?,?);" + inst-id pin-id net-id )) + +;;====================================================================== +;; NET +;;====================================================================== + +(define (nldb:get-net-id module-id name-id) + (nldb:sqlite3:get-one "SELECT id FROM nets WHERE name_id=?;" name-id)) + +(define (nldb:add-net module-id name-id) + (let ((net-id (nldb:get-net-id module-id name-id))) + (if net-id net-id + (begin + (nldb:insert-net module-id name-id) + (nldb:get-net-id module-id name-id))))) + +(define (nldb:insert-net module-id name-id) + (sqlite3:exec db "INSERT INTO nets (module_id,name_id) VALUES(?,?);" module-id name-id)) + +;;====================================================================== +;; INSTANCES +;;====================================================================== + +(define (nldb:get-inst-id parent-id name-id) + (nldb:sqlite3:get-one "SELECT id FROM insts WHERE parent_id=? AND name_id=?;" parent-id name-id)) + +;; sub-mod-id = type of instance, parent-id = where instantiated +(define (nldb:add-inst module-id parent-id name-id) + (let ((inst-id (nldb:get-inst-id parent-id name-id))) ;; parent and name are enough to identify it + (if inst-id inst-id + (begin + (nldb:insert-inst module-id parent-id name-id) + (nldb:get-inst-id parent-id name-id))))) + +(define (nldb:insert-inst module-id parent-id name-id) + (sqlite3:exec db "INSERT INTO insts (module_id,parent_id,name_id) VALUES(?,?,?);" module-id parent-id name-id)) + +;;====================================================================== +;; RECORD FOR STATE +;;====================================================================== + +(define *statevec* (make-vector 5)) + +(define-inline (curr-pin-id) (vector-ref *statevec* 0)) +(define-inline (curr-inst-id) (vector-ref *statevec* 1)) +(define-inline (curr-module-id) (vector-ref *statevec* 2)) +(define-inline (curr-inst-module-id) (vector-ref *statevec* 3)) + +(define-inline (set-curr-pin-id! id)(vector-set! *statevec* 0 id)) +(define-inline (set-curr-inst-id! id)(vector-set! *statevec* 1 id)) +(define-inline (set-curr-module-id! id)(vector-set! *statevec* 2 id)) +(define-inline (set-curr-inst-module-id! id)(vector-set! *statevec* 3 id)) + +;;====================================================================== +;; FILE I/O +;;====================================================================== + +;; Initialization and support routines for nldb:read-file +(stack-push! nldb:*stack* 'start) +(define nldb:esc-regex (regexp "^\\\\([^\\s]*)\\s*$") ) +(define (nldb:clean-identifier token) + (let* ((t (car token)) + (v (cadr token)) + (ctm (string-match nldb:esc-regex v))) + (list 'identifier (list-ref ctm 1)))) + + +(define (nldb:read-file fname) + (let* ((inp (open-input-file fname)) + (prev-state #f)) + (lexer-init 'port inp) + (let loop ((token (lexer))) + (let ((token-type (car token)) + (token-val (cadr token)) + (state (stack-peek herc:*stack*))) + (if (not (eq? prev-state state)) + (begin + (print "state: " state) + (set! prev-state state))) + (case token-type + ('end-of-input (print "Done")(close-input-port inp)) + ('whitespace (loop (lexer))) ;; skip whitespace + ('comment-begin + (stack-push! herc:*stack* 'comment ) + (loop (lexer))) + ('comment-end (stack-pop! herc:*stack*)(loop (lexer))) + ('begin (stack-push! herc:*stack* 'begin)(loop (lexer))) + ('end (stack-pop! herc:*stack*)(loop (lexer))) + ('cell + (case state + ('begin + (stack-push! herc:*stack* 'cell-name) + (loop (lexer))) + (else + (loop (lexer))))) + ('plainidentifier + (case state + ('cell-name + + ('statementend (stack-pop! nldb:*stack*)(loop (lexer))) + ('endparen (stack-pop! nldb:*stack*)(loop (lexer))) + ('endmodule (stack-pop! nldb:*stack*)(loop (lexer))) + + ('startparen + (case state + ('module-pins (loop (lexer))) + ('inst-def (loop (lexer))) + ('inst-conn-def (loop (lexer))) + ('pin-net (loop (lexer))) + (else (print "ERROR: Didn't expect an open paren here! Line " (lexer-get-line))))) + + ('comma + (case state + ('module-pins (loop (lexer))) + ('input-pin (loop (lexer))) + ('output-pin (loop (lexer))) + ('wire (loop (lexer))) + ('inst-conn-def (loop (lexer))) ;; (stack-pop! nldb:*stack*) (loop (lexer))) + (else (print "ERROR: Didn't expect a comma here! Line " (lexer-get-line))))) + + ('module + (case state + ('start + (stack-push! nldb:*stack* 'module) ;; we will be in a module + (stack-push! nldb:*stack* 'module-def)) ;; starting in the def + (else + (print "ERROR: Didn't expect module declaration here! Line " (lexer-get-line)))) + (loop (lexer))) + + ('input + (case state + ('module (stack-push! nldb:*stack* 'input-pin)) + (else (print "ERROR: Didn't expect \"input\" statement here! Linenum " (lexer-get-line)))) + (loop (lexer))) + + ('output + (case state + ('module (stack-push! nldb:*stack* 'output-pin)) + (else (print "ERROR: Didn't expect \"output\" statement here! Linenum " (lexer-get-line)))) + (loop (lexer))) + + ('inout + (case state + ('module (stack-push! nldb:*stack* 'inout-pin)) + (else (print "ERROR: Didn't expect \"inout\" statement here! Linenum " (lexer-get-line)))) + (loop (lexer))) + + ('pin + (case state + ('inst-conn-def + (let* ((pin-name (substring token-val 1 (string-length token-val))) + (pin-name-id (nldb:get-name-id pin-name)) + (pin-id (nldb:add-pin (curr-module-id) pin-name-id #f))) + (stack-push! nldb:*stack* 'pin-net) + (set-curr-pin-id! pin-id) + (loop (lexer)))) + (else (print "ERROR: Didn't expect pin here " token-val " Linenum: " (lexer-get-line))))) + + ('identifier + (case state + ('module ;; this must be an instance, an identifier at the top level + (let* ((inst-mod-id (nldb:get-module-by-name token-val))) + (set-curr-inst-module-id! inst-mod-id) + (stack-push! nldb:*stack* 'inst-def)) + (loop (lexer))) + ('inst-def ;; inst-module type parent-id inst-name-id + (let* ((inst-id (nldb:add-inst (curr-inst-module-id)(curr-module-id)(nldb:get-name-id token-val)))) + (set-curr-inst-id! inst-id)) + (stack-push! nldb:*stack* 'inst-conn-def) + (loop (lexer))) + ('module-def + (let* ((m-id (nldb:get-module-by-name token-val))) + (set-curr-module-id! m-id)) + (stack-push! nldb:*stack* 'module-pins)) + ('module-pins + (nldb:add-pin (curr-module-id) (nldb:get-name-id token-val) #f)) + ('input-pin + (let ((pin-id (nldb:get-pin-id (curr-module-id) (nldb:get-name-id token-val)))) + (nldb:set-pin-direction pin-id "input"))) + ('output-pin + (let ((pin-id (nldb:get-pin-id (curr-module-id) (nldb:get-name-id token-val)))) + (nldb:set-pin-direction pin-id "output"))) + ('inout-pin + (let ((pin-id (nldb:get-pin-id (curr-module-id) (nldb:get-name-id token-val)))) + (nldb:set-pin-direction pin-id "inout"))) + ('pin-net + (let* ((net-name-id (nldb:get-name-id token-val)) + (net-id (nldb:add-net (curr-inst-module-id) net-name-id))) + (nldb:add-conn (curr-inst-id) (curr-pin-id) net-id))) + (else + (print "ERROR: Didn't expect an identifier here! Token " token-val " Line " (lexer-get-line)))) + (loop (lexer))) + + (else + (print "ERROR: unknown token " token " on line " (lexer-get-line)) + (loop (lexer)))))))) + ADDED requirements.scm.template Index: requirements.scm.template ================================================================== --- /dev/null +++ requirements.scm.template @@ -0,0 +1,11 @@ +;; choose your db interface as appropriate +(require-extension sqlite3) +;; (require-extension postgresql) + +(require-extension cgi-util) +(require-extension cookie) +(require-extension posix) +(require-extension proplist) +(require-extension regex) +(require-extension srfi-1) +(require-extension tinyclos) ADDED session.scm Index: session.scm ================================================================== --- /dev/null +++ session.scm @@ -0,0 +1,677 @@ +;; Copyright 2007-2008, Matthew Welland. +;; +;; This program is made available under the GNU GPL version 2.0 or +;; greater. See the accompanying file COPYING for details. +;; +;; This program is distributed WITHOUT ANY WARRANTY; without even the +;; implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +;; PURPOSE. + +(include "requirements.scm") + +;; sessions table +;; id session_id session_key +;; create table sessions (id serial not null,session-key text); + +;; session_vars table +;; id session_id page_id key value +;; create table session_vars (id serial not null,session_id integer,page text,key text,value text); + +;; TODO +;; Concept of order num incremented with each page access +;; if a branch is taken then a new session would need to be created +;; + +(define-class () + (dbtype ;; 'pg or 'sqlite3 + dbinit + conn + params ;; params from the key=val&key1=val2 string + path-params ;; remaining params from the path + session-key + session-id + domain + toppage ;; defaults to "index" - override in .stml.config if desired + page ;; the page name - defaults to home + curr-page ;; the current page being evaluated + content-type ;; the default content type is text/html, override to deliver other stuff + page-type ;; use in conjunction with content-type to deliver other payloads + sroot + twikidir ;; location for twikis - needs to be fully writable by web server + pagedat + alt-page-dat + pagevars ;; session vars specific to this page + pagevars-before + sessionvars ;; session vars visible to all pages + sessionvars-before + globalvars ;; global vars visible to all sessions + globalvars-before + logpt + formdat + request-method + session-cookie + curr-err + log-port + logfile + seen-pages + debugmode)) + +;; SPLIT INTO STRAIGHT FORWARD INIT AND COMPLEX INIT +(define-method (initialize (self ) initargs) + (call-next-method) + (slot-set! self 'dbtype 'pg) + (slot-set! self 'page "home") ;; these are defaults + (slot-set! self 'curr-page "home") + (slot-set! self 'content-type "Content-type: text/html; charset=iso-8859-1\n\n") + (slot-set! self 'page-type 'html) + (slot-set! self 'toppage "index") + (slot-set! self 'params '()) ;; + (slot-set! self 'path-params '()) + (slot-set! self 'session-key #f) + (slot-set! self 'pagedat '()) + (slot-set! self 'alt-page-dat #f) + (slot-set! self 'sroot "./") + (slot-set! self 'session-cookie #f) + (slot-set! self 'curr-err #f) + (slot-set! self 'log-port (current-error-port)) + (slot-set! self 'seen-pages '()) + (slot-set! self 'debugmode #f) + (for-each (lambda (slot-name) + (slot-set! self slot-name (make-hash-table))) + (list 'pagevars 'sessionvars 'globalvars 'pagevars-before + 'sessionvars-before 'globalvars-before)) + (slot-set! self 'domain "locahost") ;; end of defaults + (initialize-slots self (session:read-config self)) + ;; some values read in from the config file need to be evaled + (for-each (lambda (slot-name) + (slot-set! self slot-name (eval (slot-ref self slot-name)))) + (list 'dbtype)) + (initialize-slots self initargs)) + +(define-method (session:setup (self )) + (let ((dbtype (slot-ref self 'dbtype)) + (dbinit (eval (slot-ref self 'dbinit))) + (dbexists #f)) + (let ((dbfname (alist-ref 'dbname dbinit))) + (if (eq? dbtype 'sqlite3) + (if (file-exists? dbfname) + (begin + ;; (session:log self "setting dbexists to #t") + (set! dbexists #t)))) + ;; (session:log self "dbtype: " dbtype " dbfname: " dbfname " dbexists: " dbexists)) + ) + (slot-set! self 'conn (dbi:open dbtype dbinit)) + (if (and (not dbexists)(eq? dbtype 'sqlite3)) + (begin + (print "WARNING: Setting up session db with sqlite3") + (session:setup-db self))) + (session:process-url-path self) + (session:setup-session-key self) + ;; capture stdin if this is a POST + (slot-set! self 'request-method (getenv "REQUEST_METHOD")) + (slot-set! self 'formdat (formdat:load-all)))) + +;; setup the db with session tables, works for sqlite only right now +(define-method (session:setup-db (self )) + (let ((conn (slot-ref self 'conn))) + (for-each + (lambda (stmt) + (dbi:exec conn stmt)) + (list "CREATE TABLE session_vars (id INTEGER PRIMARY KEY,session_id INTEGER,page TEXT,key TEXT,value TEXT);" + "CREATE TABLE sessions (id INTEGER PRIMARY KEY,session_key TEXT,last_used TIMESTAMP);" + "CREATE TABLE metadata (id INTEGER PRIMARY KEY,key TEXT,value TEXT);")))) +;; ;; if we have a session_key look up the session-id and store it +;; (slot-set! self 'session-id (session:get-id self))) + +;; only set session-cookie when a new session is created +(define-method (session:setup-session-key (self )) + (let* ((sk (session:extract-session-key self)) + (sid (if sk (session:get-id self sk) #f))) + (if (not sid) ;; need a new key + (let* ((new-key (session:get-new-key self)) + (new-sid (session:get-id self new-key))) + (slot-set! self 'session-key new-key) + (slot-set! self 'session-id new-sid) + (slot-set! self 'session-cookie (session:make-cookie self))) + (slot-set! self 'session-id sid)))) + +(define-method (session:make-cookie (self )) + ;; (list (conc "session_key=" (slot-ref self 'session-key) "; Path=/; Domain=." (slot-ref self 'domain) "; Max-Age=" (* 86400 14) "; Version=1"))) + (list (string-substitute + ";" "; " + (car (construct-cookie-string + ;; warning! messing up this itty bitty bit of code will cost much time! + `(("session_key" ,(slot-ref self 'session-key) + expires: ,(+ (current-seconds) (* 14 86400)) + max-age: (* 14 86400) + path: "/" ;; + domain: ,(string-append "." (slot-ref self 'domain)) + version: 1)) 0))))) + +;; look up a given session key and return the id if found, #f if not found +(define-method (session:get-id (self ) session-key) + ;; (let ((session-key (slot-ref self 'session-key))) + (if session-key + (let ((query (string-append "SELECT id FROM sessions WHERE session_key='" session-key "'")) + (conn (slot-ref self 'conn)) + (result #f)) + (dbi:for-each-row + (lambda (tuple) + (set! result (vector-ref tuple 0))) + conn query) + (if result (dbi:exec conn (conc "UPDATE sessions SET last_used=" (dbi:now conn) " WHERE session_key=?;") session-key)) + result) + #f)) + +;; +(define-method (session:process-url-path (self )) + (let ((path-info (getenv "PATH_INFO")) + (query-string (getenv "QUERY_STRING"))) + ;; (session:log self "path-info=" path-info " query-string=" query-string) + (if path-info + (let* ((parts (string-split path-info "/")) + (numparts (length parts))) + (if (> numparts 0) + (slot-set! self 'page (car parts))) + ;; (session:log self "url-path=" url-path " parts=" parts) + (if (> numparts 1) + (slot-set! self 'path-params (cdr parts))) + (if query-string + (slot-set! self 'params (string-split query-string "&"))))))) + +;; BUGGY! +(define-method (session:get-new-key (self )) + (let ((conn (slot-ref self 'conn)) + (tmpkey (session:make-rand-string 20)) + (status #f)) + (dbi:for-each-row (lambda (tuple) + (set! status #t)) + conn (string-append "INSERT INTO sessions (session_key) VALUES ('" tmpkey "')")) + tmpkey)) + +;; returns session key IFF it is in the HTTP_COOKIE +(define-method (session:extract-session-key (self )) + (let ((http-session (getenv "HTTP_COOKIE"))) + (if http-session + (session:extract-key-from-param self (list http-session) "session_key") + #f))) + +(define-method (session:get-session-id (self ) session-key) + (let ((query "SELECT id FROM sessions WHERE session_key=?;") + (result #f)) + ;; (pg:query-for-each (lambda (tuple) + ;; (set! result (vector-ref tuple 0))) ;; (vector-ref tuple 0))) + ;; (s:sqlparam query session-key) + ;; (slot-ref self 'conn)) + ;; conn) + (dbi:for-each-row (lambda (tuple) + (set! result (vector-ref tuple 0))) ;; (vector-ref tuple 0))) + (slot-ref self 'conn) + (s:sqlparam query session-key)) + result)) + +;; delete all records for a session +;; +(define-method (session:delete-session (self ) session-key) + (let ((session-id (session:get-session-id self session-key)) + (qry (conc "BEGIN;" + "DELETE FROM session_vars WHERE session_id=?;" + "DELETE FROM sessions WHERE id=?;" + "COMMIT;")) + (conn (slot-ref self 'conn))) + (if session-id + (begin + (dbi:exec conn qry session-id session-id) + (initialize self '()) + (session:setup self))) + (not (session:get-session-id self session-key)))) + +;; (define-method (session:delete-session (self ) session-key) +;; (let ((session-id (session:get-session-id self session-key)) +;; (queries (list "BEGIN;" +;; "DELETE FROM session_vars WHERE session_id=?;" +;; "DELETE FROM sessions WHERE id=?;" +;; "COMMIT;")) +;; (conn (slot-ref self 'conn))) +;; (if session-id +;; (begin +;; (for-each +;; (lambda (query) +;; (dbi:exec conn query session-id)) +;; queries) +;; (initialize self '()) +;; (session:setup self))) +;; (not (session:get-session-id self session-key)))) + +(define-method (session:extract-key (self ) key) + (let ((params (slot-ref self 'params))) + (session:extract-key-from-param self params key))) + +(define-method (session:extract-key-from-param (self ) params key) + (let ((r1 (regexp (string-append "^" key "=([^=]+)$")))) + (if (< (length params) 1) #f + (let loop ((head (car params)) + (tail (cdr params))) + (let ((match (string-match r1 head))) + (cond + (match + (let ((session-key (list-ref match 1))) + (slot-set! self 'session-key (list-ref match 1)) + session-key)) + ((null? tail) + #f) + (else + (loop (car tail) + (cdr tail))))))))) + +(define-method (session:set-page! (self ) page_name) + (slot-set! self 'page page_name)) + +(define-method (session:close (self )) + (dbi:close (slot-ref self 'conn))) +;; (close-output-port (slot-ref self 'logpt)) + +(define-method (session:err-msg (self ) msg) + (hash-table-set! (slot-ref self 'sessionvars) "ERROR_MSG" + (string-intersperse (map s:any->string msg) " "))) + +(define-method (session:prev-err (self )) + (let ((prev-err (hash-table-ref/default (slot-ref self 'sessionvars-before) "ERROR_MSG" #f)) + (curr-err (hash-table-ref/default (slot-ref self 'sessionvars) "ERROR_MSG" #f))) + (if prev-err prev-err + (if curr-err curr-err #f)))) + +;; session vars +;; 1. keys are always a string NOT a symbol +;; 2. values are always a string conversion is the responsibility of the +;; consuming function (at least for now, I'd like to change this) + +;; set a session var for the current page +;; +(define-method (session:set! (self ) key value) + (hash-table-set! (slot-ref self 'pagevars) (s:any->string key) (s:any->string value))) + +;; del a var for the current page +;; +(define-method (session:del! (self ) key) + (hash-table-delete! (slot-ref self 'pagevars) (s:any->string key))) + +;; get the appropriate hash given a page "*sessionvars*, *globalvars* or page +;; +(define-method (session:get-page-hash (self ) page) + (if (string=? page "*sessionvars*") + (slot-ref self 'sessionvars) + (if (string=? page "*globalvars*") + (slot-ref self 'globalvars) + (slot-ref self 'pagevars)))) + +;; set a session var for a given page +;; +(define-method (session:set! (self ) page key value) + (let ((ht (session:get-page-hash self page))) + (hash-table-set! ht (s:any->string key) (s:any->string value)))) + +;; get session vars for the current page +;; +(define-method (session:get (self ) key) + (hash-table-ref/default (slot-ref self 'pagevars) key #f)) + +;; get session vars for a specified page +;; +(define-method (session:get (self ) page key) + (let ((ht (session:get-page-hash self page))) + (hash-table-ref/default ht key #f))) + +;; delete a session var for a specified page +;; +(define-method (session:del! (self ) page key) + (let ((ht (session:get-page-hash self page))) + (hash-table-delete! ht key))) + +;; get ALL keys for this page and store in the session pagevars hash +;; +(define-method (session:get-vars (self )) + (let ((session-id (slot-ref self 'session-id))) + (if (not session-id) + (err:log "ERROR: No session id in session object! session:get-vars") + (let* ((result #f) + (conn (slot-ref self 'conn)) + (pagevars-before (slot-ref self 'pagevars-before)) + (sessionvars-before (slot-ref self 'sessionvars-before)) + (globalvars-before (slot-ref self 'globalvars-before)) + (pagevars (slot-ref self 'pagevars)) + (sessionvars (slot-ref self 'sessionvars)) + (globalvars (slot-ref self 'globalvars)) + (page-name (slot-ref self 'page)) + (session-key (slot-ref self 'session-key)) + (query (string-append + "SELECT key,value FROM session_vars INNER JOIN sessions ON session_vars.session_id=sessions.id " + "WHERE session_key=? AND page=?;"))) + ;; first the page specific vars + (dbi:for-each-row (lambda (tuple) + (let ((k (vector-ref tuple 0)) + (v (vector-ref tuple 1))) + (hash-table-set! pagevars-before k v) + (hash-table-set! pagevars k v))) + conn + (s:sqlparam query session-key page-name)) + ;; then the session specific vars + (dbi:for-each-row (lambda (tuple) + (let ((k (vector-ref tuple 0)) + (v (vector-ref tuple 1))) + (hash-table-set! sessionvars-before k v) + (hash-table-set! sessionvars k v))) + conn + (s:sqlparam query session-key "*sessionvars*")) + ;; and finally the global vars + (dbi:for-each-row (lambda (tuple) + (let ((k (vector-ref tuple 0)) + (v (vector-ref tuple 1))) + (hash-table-set! globalvars-before k v) + (hash-table-set! globalvars k v))) + conn + (s:sqlparam query session-key "*globalvars")) + )))) + +(define-method (session:save-vars (self )) + (let ((session-id (slot-ref self 'session-id))) + (if (not session-id) + (err:log "ERROR: No session id in session object! session:get-vars") + (let* ((status #f) + (conn (slot-ref self 'conn)) + (page-name (slot-ref self 'page)) + (del-query "DELETE FROM session_vars WHERE session_id=? AND page=? AND key=?;") + (ins-query "INSERT INTO session_vars (session_id,page,key,value) VALUES(?,?,?,?);") + (upd-query "UPDATE session_vars set value=? WHERE key=? AND session_id=? AND page=?;") + (changed-count 0)) + ;; save the delta only + (for-each + (lambda (page) ;; page is: "*globalvars*" "*sessionvars*" or otherstring + (let* ((master-slot-name (cond + ((string=? page "*sessionvars*") 'sessionvars) + ((string=? page "*globalvars*") 'globalvars) + (else 'pagevars))) + (before-slot-name (string->symbol (string-append (symbol->string master-slot-name) + "-before"))) + (master-ht (slot-ref self master-slot-name)) + (before-ht (slot-ref self before-slot-name)) + (master-keys (hash-table-keys master-ht)) + (before-keys (hash-table-keys before-ht)) + (all-keys (delete-duplicates (append master-keys before-keys)))) + (for-each + (lambda (key) + (let ((master-value (hash-table-ref/default master-ht key #f)) + (before-value (hash-table-ref/default before-ht key #f))) + (cond + ;; before and after exist and value unchanged - do nothing + ((and master-value before-value (equal? master-value before-value))) + ;; before and after exist but are changed + ((and master-value before-value) + (dbi:for-each-row (lambda (tuple) + (set! changed-count (+ changed-count 1))) + conn + (s:sqlparam upd-query master-value key session-id page))) + ;; master-value no longer exists (i.e. #f) - remove item + ((not master-value) + (dbi:for-each-row (lambda (tuple) + (set! changed-count (+ changed-count 1))) + conn + (s:sqlparam del-query session-id page key))) + ;; before-value doesn't exist - insert a new value + ((not before-value) + (dbi:for-each-row (lambda (tuple) + (set! changed-count (+ changed-count 1))) + conn + (s:sqlparam ins-query session-id page key master-value))) + (else (err:log "Shouldn't get here"))))) + all-keys))) ;; process all keys + (list "*sessionvars*" "*globalvars*" page-name)))))) + +;; ;; (print del-query) +;; (for-each +;; (lambda (page) +;; (pg:query-for-each (lambda (tuple) +;; (set! status #t)) +;; (s:sqlparam del-query session-id page-name) +;; conn)) +;; (list page-name "*sessionvars")) +;; ;; NOTE: The following approach is inefficient and a little dangerous. Need to keep +;; ;; two hashes, before and after and use the delta to drive updating the db OR +;; ;; even better move to using rpc with a central process for maintaining state +;; ;; write the session page specific vars to the db +;; (for-each (lambda (key) +;; (pg:query-for-each (lambda (tuple) +;; (set! status #t)) +;; (s:sqlparam ins-query session-id page-name +;; (s:any->string key) ;; just in case it is a symbol +;; (hash-table-ref pagevars key)) +;; conn)) +;; (hash-table-keys pagevars)) +;; ;; write the session specific vars to the db +;; ;; BUG!!! THIS IS LAZY AND WILL BREAK FOR SOMEONE ACCESSING THE SAME SESSION FROM TWO WINDOWS!!! +;; (for-each (lambda (key) +;; (pg:query-for-each (lambda (tuple) +;; (set! status #t)) +;; (s:sqlparam ins-query session-id "*sessionvars*" +;; (s:any->string key) ;; just in case it is a symbol +;; (hash-table-ref sessionvars key)) +;; conn)) +;; (hash-table-keys sessionvars)) +;; ;; global vars will require a little more care - delaying for now. +;; )))) + +;; (pg:sql-null-object? element) +(define-method (session:read-config (self )) + (let ((name (string-append "." (pathname-file (car (argv))) ".config"))) + (if (not (file-exists? name)) + (print name " not found at " (current-directory)) + (let* ((fp (open-input-file name)) + (initargs (read fp))) + (close-input-port fp) + initargs)))) + +;; call the controller if it exists +;; +;; WARNING - this code needs a defence agains recursive calling!!!!! +;; +;; I suggest a limit of 100 calls. Plenty for allowing multiple instances +;; of a page inside another page. +;; +;; parts = 'both | 'control | 'view +;; + +(define (files-read->string . files) + (string-intersperse + (apply append (map file-read->string files)) "\n")) + +(define (file-read->string f) + (let ((p (open-input-file f))) + (let loop ((hed (read-line p)) + (res '())) + (if (eof-object? hed) + res + (loop (read-line p)(append res (list hed))))))) + +(define-method (session:call-parts (self ) page parts) + (slot-set! self 'curr-page page) + (let* ((dir (string-append (slot-ref self 'sroot) "/pages/" page)) + (control (string-append dir "/control.scm")) + (view (string-append dir "/view.scm")) + (load-view (and (file-exists? view) + (or (eq? parts 'both)(eq? parts 'view)))) + (load-control (and (file-exists? control) + (or (eq? parts 'both)(eq? parts 'control)))) + (view-dat '()) + (sugar "/home/matt/kiatoa/stml/sugar.scm" )) + ;; (print "dir=" dir " control=" control " view=" view " load-view=" load-view " load=control=" load-control) + (if load-control + (begin + (load control) + (session:set-called! self page))) + ;; move this to where it gets exectuted only once + ;; + (if load-view + ;; option one.: + ;; + ;; (let ((inp (open-input-string + ;; (files-read->string "/home/matt/kiatoa/stml/sugar.scm" + ;; view)))) + ;; (map + ;; (lambda (x) + ;; (cond + ;; ((list? x) x) + ;; ((string? x) x) + ;; (else '()))) + ;; (port-map eval (lambda () + ;; (read inp))))) + ;; + ;; option two: + ;; + (let* (;; (inps (map open-input-file (list view))) ;; sugar view))) + (p (open-input-file view)) ;; (apply make-concatenated-port inps)) + (dat (map + (lambda (x) + (cond + ((list? x) x) + ((string? x) x) + (else '()))) + (port-map eval (lambda ()(read p)))))) + ;; (map close-input-port inps) + (close-input-port p) + dat) + (list "

Page not found " page "

")))) + +(define-method (session:call (self ) page) + (session:call-parts self page 'both)) + +(define-method (session:call (self ) page parts) + (session:call-parts self page 'both)) + +(define-method (session:load-model (self ) model) + (let ((model.scm (string-append (slot-ref self 'sroot) "/models/" model ".scm")) + (model.so (string-append (slot-ref self 'sroot) "/models/" model ".so"))) + (if (file-exists? model.so) + (load model.so) + (if (file-exists? model.scm) + (load model.scm) + (s:log "ERROR: model " model.scm " not found"))))) + +(define-method (session:model-path (self ) model) + (string-append (slot-ref self 'sroot) "/models/" model ".scm")) + +(define-method (session:pp-formdat (self )) + (let ((dat (formdat:all->strings (slot-ref self 'formdat)))) + (string-intersperse dat "
"))) + +(define (session:param->string params) + ;; (err:log "params=" params) + (if (< (length params) 1) + "" + (let loop ((key (car params)) + (val (cadr params)) + (tail (cddr params)) + (result '())) + (let ((newresult (cons (string-append (s:any->string key) "=" (s:any->string val)) + result))) + (if (< (length tail) 1) ;; true if done + (string-intersperse newresult "&") + (loop (car tail)(cadr tail)(cddr tail) newresult)))))) + +(define-method (session:link-to (self ) page params) + (let* ((server (if (getenv "HTTP_HOST") + (getenv "HTTP_HOST") + (getenv "SERVER_NAME"))) + (script (let ((script-name (string-split (getenv "SCRIPT_NAME") "/"))) + (if (> (length script-name) 1) + (string-append (car script-name) "/" (cadr script-name)) + (getenv "SCRIPT_NAME")))) ;; build script name from first two elements. This is a hangover from before I used ? in the URL. + (session-key (slot-ref self 'session-key)) + (paramstr (session:param->string params))) + ;; (session:log self "server=" server " script=" script " page=" page) + (string-append "http://" server "/" script "/" page "?" paramstr))) ;; "/sn=" session-key))) + +(define-method (session:cgi-out (self )) + (let* ((content (list (slot-ref self 'content-type))) ;; '("Content-type: text/html; charset=iso-8859-1\n\n")) + (header (let ((cookie (slot-ref self 'session-cookie))) + (if cookie + (cons (string-append "Set-Cookie: " (car cookie)) + content) + content))) + (pagedat (slot-ref self 'pagedat))) + (s:cgi-out + (cons header pagedat)))) + +(define-method (session:log (self ) . msg) + (with-output-to-port (slot-ref self 'log-port) ;; (slot-ref self 'logpt) + (lambda () + (apply print msg)))) + +(define-method (session:get-param (self ) key) + ;; (session:log s:session "params=" (slot-ref s:session 'params)) + (let ((params (slot-ref self 'params))) + (session:get-param-from params key))) + +;; This one will get the first value found regardless of form +(define-method (session:get-input (self ) key) + (let* ((formdat (slot-ref self 'formdat))) + (if (not formdat) #f + (if (or (string? key)(number? key)(symbol? key)) + (if (eq? (class-of formdat) ) + (formdat:get formdat key) + (begin + (session:log self "ERROR: formdat: " formdat " is not of class ") + #f)) + (session:log self "ERROR: bad key " key))))) + +(define-method (session:run-actions (self )) + (let* ((action (session:get-param self 'action)) + (page (slot-ref self 'page))) + ;; (print "action=" action " page=" page) + (if action + (let ((action-lst (string-split action "."))) + ;; (print "action-lst=" action-lst) + (if (not (= (length action-lst) 2)) + (err:log "Action should be of form: module.action") + (let* ((targ-page (car action-lst)) + (proc-name (string-append targ-page "-action")) + (targ-action (cadr action-lst))) + ;; (err:log "targ-page=" targ-page " proc-name=" proc-name " targ-action=" targ-action) + + ;; call here only if never called before + (if (session:never-called-page? self targ-page) + (session:call-parts self targ-page 'control)) + ;; proc action + + (if #t ;; set to #t to see better error messages during debuggin :-) + ((eval (string->symbol proc-name)) targ-action) ;; unsafe execution + (condition-case ((eval (string->symbol proc-name)) targ-action) + ((exn file) (s:log "file error")) + ((exn i/o) (s:log "i/o error")) + ((exn ) (s:log "Action not implemented: " proc-name " action: " targ-action)) + (var () (s:log "Unknown Error")))))))))) + +(define-method (session:never-called-page? (self ) page) + (session:log self "Checking for page: " page) + (not (member page (slot-ref self 'seen-pages)))) + +(define-method (session:set-called! (self ) page) + (slot-set! self 'seen-pages (cons page (slot-ref self 'seen-pages)))) + +;;====================================================================== +;; Alternative data type delivery +;;====================================================================== + +(define-method (session:alt-out (self )) + (let ((dat (slot-ref self 'alt-page-dat))) + ;; (s:log "dat is: " dat) + ;; (print "HTTP/1.1 200 OK") + (print "Date: " (time->string (seconds->utc-time (current-seconds)))) + (print "Content-Type: " (slot-ref self 'content-type)) + (print "Accept-Ranges: bytes") + (print "Content-Length: " (if (blob? dat) + (blob-size dat) + 0)) + (print "Keep-Alive: timeout=15, max=100") + (print "Connection: Keep-Alive") + (print "") + (write-string (blob->string dat) #f (current-output-port)))) ADDED sessions.sql Index: sessions.sql ================================================================== --- /dev/null +++ sessions.sql @@ -0,0 +1,5 @@ +CREATE TABLE session_vars (id integer primary key, session_id integer, page text, key text, value text); + +CREATE TABLE sessions ( id integer primary key, session_key text); + + ADDED setup.scm Index: setup.scm ================================================================== --- /dev/null +++ setup.scm @@ -0,0 +1,102 @@ +;; Copyright 2007-2008, Matthew Welland. +;; +;; This program is made available under the GNU GPL version 2.0 or +;; greater. See the accompanying file COPYING for details. +;; +;; This program is distributed WITHOUT ANY WARRANTY; without even the +;; implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +;; PURPOSE. + +;; +(define s:session (make )) + +;; use this for getting data from page to page when scope and evals +;; get in the way +(define s:local-vars (make-hash-table)) + +(define (s:local-set! k v) + (hash-table-set! s:local-vars k v)) + +(define (s:local-get k) + (hash-table-ref/default s:local-vars k #f)) + +(session:setup s:session) + +(define (s:log . msg) + (apply session:log s:session msg)) + +(session:get-vars s:session) + +(define (s:set-err . args) + (slot-set! s:session 'curr-err args)) + +;; Usage: (s:get-err s:big) +(define (s:get-err wrapperfunc) + (let ((errmsg (slot-ref s:session 'curr-err))) + (if errmsg ((if wrapperfunc + wrapperfunc + s:strong) errmsg) '()))) + +(define (s:current-page) + (slot-ref s:session 'page)) + +(define (s:delete-session) + (session:delete-session s:session (slot-ref s:session 'session-key))) + +(define (s:call page . partsl) + (if (null? partsl) + (session:call s:session page) + (session:call s:session page (car partsl)))) + +(define (s:link-to page . params) + (session:link-to s:session page params)) + +(define (s:get-param key) + (session:get-param s:session key)) + +;; these are page local +(define (s:get key) + (session:get s:session key)) + +(define (s:set! key val) + (session:set! s:session key val)) + +(define (s:del! key) + (session:del! s:session key)) + +(define (s:get-n-del! key) + (let ((val (session:get s:session key))) + (session:del! s:session key) + val)) + +;; these are session wide +(define (s:session-var-get key) + (session:get s:session "*sessionvars*" key)) + +(define (s:session-var-set! key val) + (session:set! s:session "*sessionvars*" key val)) + +(define (s:session-var-get-n-del! key) + (let ((val (session:get s:session key))) + (session:del! s:session "*sessionvars*" key) + val)) + +(define (s:session-var-del! key) + (session:del! s:session "*sessionvars*" key)) + +;; +(define (s:get-input key) + (session:get-input s:session key)) + +(define (s:load-model model) + (session:load-model s:session model)) + +(define (s:model-path model) + (session:model-path s:session model)) + +(define (s:db) + (slot-ref s:session 'conn)) + +(define (s:never-called-page? page) + (session:never-called-page? s:session page)) + ADDED spiffyserver.scm Index: spiffyserver.scm ================================================================== --- /dev/null +++ spiffyserver.scm @@ -0,0 +1,13 @@ +;; This doesn't work yet +;; +(use spiffy cgi-handler) + +(spiffy-debug-mode #t) + +(spiffy-file-ext-handlers + `(("drcdb" . ,(cgi-handler* "/path/to/drcdb")))) + +(spiffy-root-path "/path/to/web") + +(start-server location: (get-host-name) + init: noop) ADDED sqlite3.scm Index: sqlite3.scm ================================================================== --- /dev/null +++ sqlite3.scm @@ -0,0 +1,54 @@ +;; Copyright 2007-2008, Matthew Welland. +;; +;; This program is made available under the GNU GPL version 2.0 or +;; greater. See the accompanying file COPYING for details. +;; +;; This program is distributed WITHOUT ANY WARRANTY; without even the +;; implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +;; PURPOSE. +;; + +;; I used this to get a simple interactive sqlite editor on the nokia n800 +;; since I couldn't get sqlite3 to install (for reasons I can't remember). + +(use sqlite3) + +(define args (argv)) +(define num-args (length args)) + +(define dbname #f) +(define cmd #f) + +(if (> num-args 1) + (set! dbname (cadr args)) + (exit 0)) + +(if (> num-args 2) + (set! cmd (caddr args))) + +(define db (sqlite3:open dbname)) + +(define (interactive db) + (let ((prompt " > ")) + (display prompt) + (let loop ((cmd (read-line))) + (cond + ((> (string-length cmd) 0) + (process-cmd db cmd) + (display prompt) + (loop (read-line))) + (else + (loop (read-line))))))) + +(define (process-cmd db cmd) + (sqlite3:for-each-row + (lambda (a . b) + (print a " " (string-intersperse b " "))) + db cmd)) + +(if cmd + (process-cmd db cmd) + (interactive db)) + +(sqlite3:finalize! db) + ADDED sqltbl.scm Index: sqltbl.scm ================================================================== --- /dev/null +++ sqltbl.scm @@ -0,0 +1,94 @@ +;; Copyright 2007-2008, Matthew Welland. Kiatoa.com All rights reserved. +;; + +;; DON'T USE THIS!!!! It was a bad idea :-( + +;; If performance becomes an issue upgrade this to use a vector to + +(require-extension tinyclos) + +(define-class () + (rows + fields ;; list of field + fields-hash ;; hash of fields -> number + query ;; query string using ?'s + query-params ;; list of params for the query + conn ;; connection to db + num-rows ;; whatever + curr-row-ptr ;; number of the current row + curr-row ;; the current row vector (?? do we really want this ??) + )) + +(define-method (initialize (self ) initargs) + (call-next-method) + (slot-set! self 'num-rows 0) + (slot-set! self 'curr-row-ptr 0) + (slot-set! self 'fields '()) + (slot-set! self 'fields-hash (make-hash-table)) + (initialize-slots self initargs)) +;; (if (> (length (slot-ref self 'rows) 0)) +;; (slot-set! self 'curr-row (car rows)))) + +(define-method (sqltbl:next-row (self )) + (let ((curr-row-ptr (+ (slot-ref self 'curr-row-ptr) 1)) + (num-rows (slot-ref self 'num-rows)) + (rows (slot-ref self 'rows))) + (if (> curr-row-prt (slot-ref self 'num-rows)) #f ;; there is no next row + (let ((new-curr-row (list-ref rows curr-row-ptr))) + (slot-set! self 'curr-row new-curr-row) + (slot-set! self 'curr-row-prt curr-row-prt) + new-curr-row)))) + +;; run the query and fill the rows list +(define-method (sqltbl:run-query (self ) . params) + (let* ((query (slot-ref self 'query)) + (fields (slot-ref self 'fields)) + (rows (let ((result '()) + (actual-query (apply s:sqlparam query fields params))) + ;; (s:log "actual-query=" actual-query) + (dbi:for-each-row (lambda (tuple) + (set! result (cons tuple result))) + (slot-ref self 'conn) + actual-query) + (slot-set! self 'query-params params) + (slot-set! self 'num-rows (length result)) + (sqltbl:setup-fields self) ;; update the fields lookup hash + (reverse result)))) + (slot-set! self 'rows rows) + (if (not (null? rows)) + (slot-set! self 'curr-row (car rows))) + (slot-set! self 'curr-row-ptr 0) + rows)) + +(define-method (sqltbl:setup-fields (self )) + (let ((fields-hash (slot-ref self 'fields-hash)) + (fields-list (slot-ref self 'fields))) + (let loop ((head (car fields-list)) + (tail (cdr fields-list)) + (fnum 0)) + (hash-table-set! fields-hash head fnum) + (if (null? tail) fnum + (loop (car tail)(cdr tail)(+ fnum 1)))))) + +;; get a value from the current row +(define-method (sqltbl:get-field-value-curr (self ) field) + (let ((curr-row (slot-ref self 'curr-row)) + (field-num (hash-table-ref/default (slot-ref self 'fields-hash) field #f))) + (if field-num + (vector-ref curr-row field-num) + #f))) ;; not found -> #f + +(define-method (sqltbl:vector->hash (self ) vec) + (let ((h (make-hash-table)) + (fields (slot-ref self 'fields))) + (do ((i 0 (+ i 1))) + ((>= i (length fields))) + (hash-table-set! h (list-ref fields i)(vector-ref vec i))) + h)) + + +;; runs proc on each row and returns the resulting list +(define-method (sqltbl:map (self ) proc) + (map (lambda (row) + (proc (sqltbl:vector->hash self row))) (slot-ref self 'rows))) + ADDED stml.config.template Index: stml.config.template ================================================================== --- /dev/null +++ stml.config.template @@ -0,0 +1,8 @@ +(list sroot "/path/to/{pages,models}/dir" + logfile "/tmp/stmlrun/logs.log" ;; this is now required! + dbtype 'sqlite3 ;; or 'pg + dbinit '((dbname . "test-stml.db") + (user . "nobody") + (password . "Dapassword") + (host . "localhost")) + domain "192.168.1.150") ADDED stml.scm Index: stml.scm ================================================================== --- /dev/null +++ stml.scm @@ -0,0 +1,263 @@ +;; Copyright 2007-2008, Matthew Welland. +;; +;; This program is made available under the GNU GPL version 2.0 or +;; greater. See the accompanying file COPYING for details. +;; +;; This program is distributed WITHOUT ANY WARRANTY; without even the +;; implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +;; PURPOSE. + +;; stml is a list of html strings + +;; extract various tokens from the parameter list +;; 'key val => put in the params list +;; strings => maintain order and add to the datalist <<== IMPORTANT +(define (s:extract inlst) + (if (null? inlst) inlst + (let loop ((data '()) + (params '()) + (head (car inlst)) + (tail (cdr inlst))) + ;; (print "head=" head " tail=" tail) + (cond + ((null? tail) + (if (symbol? head) ;; the last item is a param - borked + (s:log "ERROR: param with no value")) + (list (append data (list (s:any->string head))) params)) + ((or (string? head)(list? head)(number? head)) + (loop (append data (list (s:any->string head))) params (car tail) (cdr tail))) + ((symbol? head) + (let ((new-params (cons (list head (car tail)) params)) + (new-tail (cdr tail))) + (if (null? new-tail) ;; we are done, no more params etc. + (list data new-params) + (loop data new-params (car new-tail)(cdr new-tail))))) + (else + (s:log "WARNING: Malformed input, you have broken stml, probably in a form: head=" head + "\ntail=" tail + "\ninlst=" inlst + "\nparams=" params) + (if (null? tail) + (list data params) + (loop data params (car tail)(cdr tail)))))))) + +;; most tags can be handled by this routine +(define (s:common-tag tagname args) + (let* ((inputs (s:extract args)) + (data (car inputs)) + (params (s:process-params (cadr inputs)))) + (list (conc "<" tagname params ">") + data + (conc "")))) + +;; Suggestion: order these alphabetically +(define (s:a . args) (s:common-tag "A" args)) +(define (s:b . args) (s:common-tag "B" args)) +(define (s:u . args) (s:common-tag "U" args)) +(define (s:big . args) (s:common-tag "BIG" args)) +(define (s:body . args) (s:common-tag "BODY" args)) +(define (s:center . args) (s:common-tag "CENTER" args)) +(define (s:code . args) (s:common-tag "CODE" args)) +(define (s:div . args) (s:common-tag "DIV" args)) +(define (s:h1 . args) (s:common-tag "H1" args)) +(define (s:h2 . args) (s:common-tag "H2" args)) +(define (s:h3 . args) (s:common-tag "H3" args)) +(define (s:head . args) (s:common-tag "HEAD" args)) +(define (s:html . args) (s:common-tag "HTML" args)) +(define (s:i . args) (s:common-tag "I" args)) +(define (s:img . args) (s:common-tag "IMG" args)) +(define (s:input . args) (s:common-tag "INPUT" args)) +(define (s:link . args) (s:common-tag "LINK" args)) +(define (s:p . args) (s:common-tag "P" args)) +(define (s:strong . args) (s:common-tag "STRONG" args)) +(define (s:table . args) (s:common-tag "TABLE" args)) +(define (s:td . args) (s:common-tag "TD" args)) +(define (s:title . args) (s:common-tag "TITLE" args)) +(define (s:tr . args) (s:common-tag "TR" args)) +(define (s:small . args) (s:common-tag "SMALL" args)) +(define (s:quote . args) (s:common-tag "QUOTE" args)) +(define (s:hr . args) (s:common-tag "HR" args)) +(define (s:li . args) (s:common-tag "LI" args)) +(define (s:ul . args) (s:common-tag "UL" args)) +(define (s:ol . args) (s:common-tag "OL" args)) +(define (s:dl . args) (s:common-tag "DL" args)) +(define (s:dt . args) (s:common-tag "DT" args)) +(define (s:dd . args) (s:common-tag "DD" args)) +(define (s:pre . args) (s:common-tag "PRE" args)) +(define (s:span . args) (s:common-tag "SPAN" args)) + +(define (s:dblquote . args) + (let* ((inputs (s:extract args)) + (data (caar inputs)) + (params (s:process-params (cadr inputs)))) + (conc """ data """))) + +(define (s:br . args) "
") ;; THIS MAY NOT WORK!!!! BR CAN (MISTAKENLY) GET PARAM TEXT +;; (define (s:br . args) (s:common-tag "BR" args)) +(define (s:font . args) (s:common-tag "FONT" args)) +(define (s:err-font . args) + (s:b (s:font 'color "red" args))) + +(define (s:comment . args) + (let* ((inputs (s:extract args)) + (data (car inputs)) + (params (s:process-params (cadr inputs)))) + (list ""))) + +(define (s:null . args) ;; nop + (let* ((inputs (s:extract args)) + (data (car inputs)) + (params (s:process-params (cadr inputs)))) + (list data))) + +;; puts a nice box around a chunk of stuff +(define (s:fieldset legend . args) + (list "
" legend "" args "
")) + +;; USE 'page_override to override a linkto page from a button +(define (s:form . args) + ;; create a link for calling back into the current page and calling a specified + ;; function + (let* ((action (let ((v (s:find-param 'action args))) + (if v v "default"))) + (id (let ((i (s:find-param 'id args))) + (if i i #f))) + (page (let ((p (slot-ref s:session 'page))) + (if p p "home"))) + ;; (link (session:link-to s:session page (if id + ;; (list 'action action 'id id) + ;; (list 'action action))))) + (link (if (string=? (substring action 0 5) "http:") ;; if first part of string is http: + action + (session:link-to s:session + page + (if id + (list 'action action 'id id) + (list 'action action)))))) + ;; (script (slot-ref s:session 'script)) + ;; (action-str (string-append script "/" page "?action=" action))) + (s:common-tag "FORM" (append (s:remove-param-matching (s:remove-param-matching args 'action) 'id) + (list 'action link))))) + +;; look up the variable name (via the 'name tag) then inject the value from the session var +;; replacing the 'value value if it is already there, adding it if it is not. +(define (s:preserve tag args) + (let* ((var-name (s:find-param 'name args)) ;; name='varname' + (value (let ((v (s:get var-name))) + (if v v #f))) + (newargs (append (s:remove-param-matching args 'value) (if value (list 'value value) '())))) + (s:common-tag tag newargs))) + +(define (s:input-preserve . args) + (s:preserve "INPUT" args)) + +;; text areas are done a little differently. The value is stored between the tags +(define (s:textarea-preserve . args) + (let* ((var-name (s:find-param 'name args)) + (value (let ((v (s:get var-name))) + (if v v #f)))) + (s:common-tag "TEXTAREA" (if value (cons value args) args)))) + +(define (s:option dat) + (let ((len (length dat))) + (cond + ((eq? len 1) + (let ((item (car dat))) + (s:option (list item item item)))) + ((eq? len 2) + (s:option (append dat (list (car dat))))) + (else + (let ((label (car dat)) + (value (cadr dat)) + (dispval (caddr dat)) + (selected (if (> len 3)(cadddr dat) #f))) + (list (conc ""))))))) + +;; call only with (label (label value dispval [#t]) ...) +;; NB// sadly this block is redundantly almost identical to the s:select +;; fix that later ... +(define (s:optgroup dat) + (let ((label (car dat)) + (rem (cdr dat))) + (if (null? rem) + (s:common-tag "OPTGROUP" 'label label) + (let loop ((hed (car rem)) + (tal (cdr rem)) + (res (list (conc "")) + (loop (car tal)(cdr tal) new))))))) + +;; items is a hierarchial alist +;; ( (label1 value1 dispval1 #t) ;; <== this one is selected +;; (label2 (label3 value2 dispval2) +;; (label4 value3 dispval3))) +;; +;; required arg is 'name +(define (s:select items . args) + (if (null? items) + (s:common-tag "SELECT" args) + (let loop ((hed (car items)) + (tal (cdr items)) + (res '())) + ;; (print "hed: " hed " tal: " tal " res: " res) + (let ((new (append res (list (if (and (> (length hed) 1) + (list? (cadr hed))) + (s:optgroup hed) + (s:option hed)))))) + (if (null? tal) + (s:common-tag "SELECT" (cons new args)) + (loop (car tal)(cdr tal) new)))))) + +(define (s:color . args) + "#00ff00") + +(define (s:print indent inlst) + (map (lambda (x) + (cond + ((or (string? x)(symbol? x)) + (print (conc (make-string (* indent 2) #\ ) (any->string x)))) + ((list? x) + (s:print (+ indent 1) x)) + (else + ;; (print "ERROR: Bad input 01") ;; why do anything with junk? + ))) + inlst)) + +(define (s:cgi-out inlst) + (s:output (current-output-port) inlst)) + +(define (s:output port inlst) + (map (lambda (x) + (cond + ((string? x) (print x)) ;; (print x)) + ((symbol? x) (print x)) ;; (print x)) + ((list? x) (s:output port x)) + (else + ;; (print "ERROR: Bad input 02") ;; why do anything? don't output junk. + ))) + inlst)) +; (if (> (length inlst) 2) +; (print))) + +(define (s:output-new port inlst) + (with-output-to-port port + (lambda () + (map (lambda (x) + (cond + ((string? x) (print x)) + ((symbol? x) (print x)) + ((list? x) (s:output port x)) + (else + ;; (print "ERROR: Bad input 03") + ))) + inlst)))) + ADDED stmlrun.scm Index: stmlrun.scm ================================================================== --- /dev/null +++ stmlrun.scm @@ -0,0 +1,51 @@ +#!/usr/local/bin/csi -q + +;; Copyright 2007-2008, Matthew Welland. +;; +;; This program is made available under the GNU GPL version 2.0 or +;; greater. See the accompanying file COPYING for details. +;; +;; This program is distributed WITHOUT ANY WARRANTY; without even the +;; implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +;; PURPOSE. + +;; (require-extension syntax-case) +(declare (run-time-macros)) + +(use dbi) + +(include "requirements.scm") +(include "html-filter.scm") +(include "misc-stml.scm") +(include "formdat.scm") +(include "stml.scm") +;; (include "dbi.scm") +(include "session.scm") +(include "setup.scm") ;; s:session gets created here +(include "sqltbl.scm") +(include "keystore.scm") +(include "sugar.scm") + +(slot-set! s:session 'log-port ;; (current-error-port)) + (open-output-file (slot-ref s:session 'logfile) #:append)) + +;; (s:log "HTTP_COOKIE" (getenv "HTTP_COOKIE")) +;; (s:log "stdin-dat=" (slot-ref s:session 'stdin-dat)) + +(s:validate-inputs) + +(session:run-actions s:session) + +(slot-set! s:session 'pagedat + (append (slot-ref s:session 'pagedat) + (s:call (slot-ref s:session 'toppage)))) + +(if (eq? (slot-ref s:session 'page-type) 'html) ;; default is html. + (session:cgi-out s:session) + (session:alt-out s:session)) + +(session:save-vars s:session) + +(session:close s:session) + +(exit) ADDED sugar.scm Index: sugar.scm ================================================================== --- /dev/null +++ sugar.scm @@ -0,0 +1,39 @@ +;; Copyright 2007-2008, Matthew Welland. +;; +;; This program is made available under the GNU GPL version 2.0 or +;; greater. See the accompanying file COPYING for details. +;; +;; This program is distributed WITHOUT ANY WARRANTY; without even the +;; implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +;; PURPOSE. +;; + +;;====================================================================== +;; Sugar +;;====================================================================== +;; +;; (require 'syntax-case) +;; +;; (define-syntax s:if-param +;; (syntax-rules () +;; [(_ s x) (if (s:get s) x (s:comment "s:if not"))] +;; [(_ s x y) (if (s:get s) x y)])) +;; ;; +;; (define-syntax s:if-test +;; (syntax-rules () +;; [(_ s x) (if (string=? "yep" s) x (list "s:if not"))] +;; [(_ s x y) (if (string=? "yep" s) x y)])) + + +(define-macro (s:if-param varname . dat) + (match dat + (() '()) + ((a) `(if (s:get ,varname) ,a '())) + ((a b) `(if (s:get ,varname) ,a ,b)))) + +(define-macro (s:if-sessionvar varname . dat) + (match dat + (() '()) + ((a) `(if (s:session-var-get ,varname) ,a '())) + ((a b) `(if (s:session-var-get ,varname) ,a ,b)))) + ADDED tests/example.post.binary.in Index: tests/example.post.binary.in ================================================================== --- /dev/null +++ tests/example.post.binary.in cannot compute difference between binary files ADDED tests/example.post.in Index: tests/example.post.in ================================================================== --- /dev/null +++ tests/example.post.in @@ -0,0 +1,1 @@ +email-address=matt%3A1&password=Blah&form-name=login ADDED tests/models/test.scm Index: tests/models/test.scm ================================================================== --- /dev/null +++ tests/models/test.scm @@ -0,0 +1,11 @@ +;; Copyright 2007-2008, Matthew Welland. +;; +;; This program is made available under the GNU GPL version 2.0 or +;; greater. See the accompanying file COPYING for details. +;; +;; This program is distributed WITHOUT ANY WARRANTY; without even the +;; implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +;; PURPOSE. +;; + +;; models/test.scm ADDED tests/pages/test/control.scm Index: tests/pages/test/control.scm ================================================================== --- /dev/null +++ tests/pages/test/control.scm @@ -0,0 +1,11 @@ +;; Copyright 2007-2008, Matthew Welland. +;; +;; This program is made available under the GNU GPL version 2.0 or +;; greater. See the accompanying file COPYING for details. +;; +;; This program is distributed WITHOUT ANY WARRANTY; without even the +;; implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +;; PURPOSE. +;; + +;; pages/test/control.scm ADDED tests/pages/test/view.scm Index: tests/pages/test/view.scm ================================================================== --- /dev/null +++ tests/pages/test/view.scm @@ -0,0 +1,11 @@ +;; Copyright 2007-2008, Matthew Welland. +;; +;; This program is made available under the GNU GPL version 2.0 or +;; greater. See the accompanying file COPYING for details. +;; +;; This program is distributed WITHOUT ANY WARRANTY; without even the +;; implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +;; PURPOSE. +;; + +;; pages/test/view.scm ADDED tests/test.scm Index: tests/test.scm ================================================================== --- /dev/null +++ tests/test.scm @@ -0,0 +1,212 @@ +#!/usr/local/bin/csi -q + +;; Copyright 2007-2008, Matthew Welland. +;; +;; This program is made available under the GNU GPL version 2.0 or +;; greater. See the accompanying file COPYING for details. +;; +;; This program is distributed WITHOUT ANY WARRANTY; without even the +;; implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +;; PURPOSE. + +(use test md5 dbi) + +(load "./requirements.scm") +(load "./misc-stml.scm") +(load "./formdat.scm") +(load "./stml.scm") +(load "./session.scm") +(load "./sqltbl.scm") +(load "./html-filter.scm") +(load "./keystore.scm") + +;; Test the primitive dbi interface + +(system "rm -f tests/test.db") +(define db (dbi:open 'sqlite3 '((dbname . "tests/test.db")))) +(dbi:exec db "CREATE TABLE foo(id INTEGER PRIMARY KEY,name TEXT);") +(dbi:exec db "INSERT INTO foo(name) VALUES(?);" "Matt") +(dbi:for-each-row + (lambda (tuple) + (print (vector-ref tuple 0) " " (vector-ref tuple 1))) + db "SELECT * FROM foo;") +(test "dbi:get-one" "Matt" (dbi:get-one db "SELECT name FROM foo WHERE name='Matt';")) + +;; keystore +(dbi:exec db "CREATE TABLE metadata (id INTEGER PRIMARY KEY,key TEXT,value TEXT);") + +(keystore:set! db "SCHEMA-VERSION" 1.2) +(test "Keystore get" "1.2" (keystore:get db "SCHEMA-VERSION")) +(keystore:del! db "SCHEMA-VERSION") +(test "Keystore get deleted" #f (keystore:get db "SCHEMA-VERSION")) + +(system "rm -f tests/test.db") + +;; create a session to work with") +(setenv "REQUEST_URI" "/stmlrun?action=test.test") +(setenv "SCRIPT_NAME" "/cgi-bin/stmlrun") +(setenv "PATH_INFO" "/test") +(setenv "QUERY_STRING" "action=test.test") +(setenv "SERVER_NAME" "localhost") +(setenv "REQUEST_METHOD" "GET") + +(load "./setup.scm") + +(s:validate-inputs) + +;; test session variables + +(session:get-vars s:session) +(define nada "andnndhhshaas") +(s:session-var-set! "nick" nada) +(test "Session var set/get" nada (s:session-var-get "nick")) +(print "got here") +(session:save-vars s:session) +(session:get-vars s:session) +(test "Session var set/get after save/get" nada (s:session-var-get "nick")) +(session:del! s:session "*sessionvars*" "nick") +(test "Session var del" #f (s:session-var-get "nick")) +(session:save-vars s:session) +(session:get-vars s:session) +(s:session-var-set! "nick" nada) +(session:save-vars s:session) + +;; (test "Session var del" #f (s:session-var-get "nick")) + +;; test person + +(load "./tests/models/test.scm") + +(print "Session key is " (slot-ref s:session 'session-key)) + +(test "Delete session" #t (s:delete-session)) + +(let ((fh (open-input-pipe "ls ./tests/pages/*/control.scm"))) + (let loop ((l (read-line fh))) + (if (not (eof-object? l)) + (begin + ;; (print "loading " l) + (load l) + (loop (read-line fh))))) + (close-input-port fh)) + +;; Should have poll:poll defined now. +(test "Make a random string" 2 (string-length (session:make-rand-string 2))) +(test "Create a encrypted password" "abQ9KY.KfrYrc" (s:crypt-passwd "foo" "ab")) + +(test "s:any->string on a hash-table" "#" (s:any->string (make-hash-table))) + +(define select-list + '((a b c)(d (e f g)(h i j #t)))) +(define result '("")) + +(test "Select list" result (s:select select-list 'name "efg")) + +;; Test modules + +(test "misc:non-zero-string \"\"" #f (misc:non-zero-string "")) +(test "misc:non-zero-string #f" #f (misc:non-zero-string #f)) +(test "misc:non-zero-string 'blah" #f (misc:non-zero-string 'blah)) + +;; forms +(define form #f) +(test "make " #t (let ((f (make ))) + (set! form f) + #t)) +(test "formdat: set!/get" "Yep!" (begin + (formdat:set! form "blah" "Yep!") + (formdat:get form "blah"))) + +;; The twiki module + +;; clean up +(system "rm -rf twikis/*") +(load "modules/twiki/twiki-mod.scm") +(define keys (list "blah" 1 'nada)) +(test "twiki:keys->key" "blah 1 nada" (twiki:keys->key keys)) +(define key (twiki:keys->key keys)) + +(define *tdb* #f) +(test "twiki:open-db" #t (let ((db (twiki:open-db key))) + (set! *tdb* db) + (if *tdb* #t #f))) +(define wiki (make-twiki:wiki)) +(twiki:wiki-set-wid! wiki 1) +(twiki:wiki-set-name! wiki "main") +(twiki:wiki-set-perms! wiki '(r w)) + +(test "twiki:dat->html" '("Hello" "
") (twiki:dat->html "Hello" wiki)) +(test "twiki:keys->fname" '("twikis/Ymxha/CAxIG/5hZGE" "YmxhaCAxIG5hZGE_") ;; ("twikis/d99a2de9/6808493b/23770f70" "d99a2de96808493b23770f70c76dffe4") + (twiki:key->fname key)) + +(test "twiki:name->wid" 1 (twiki:name->wid *tdb* "main")) +(test "twiki:get-tiddlers-by-num" '() (twiki:get-tiddlers-by-num *tdb* 0 (list 1 2 3))) +(test "twiki:get-tiddlers-by-name" '() (twiki:get-tiddlers-by-name *tdb* 0 "MainMenu")) +(test "twiki:get-tiddlers" '() (twiki:get-tiddlers *tdb* 0 (list "MainMenu"))) +(test "twiki:get-tiddlers" '() (twiki:get-tiddlers *tdb* 0 (list "MainMenu" "AnotherOne"))) +(test "twiki:wiki" "" (car (twiki:wiki "main" (list "blah" 1 'nada)))) +(test "twiki:view" "
" (car (twiki:view "" "" 0 (twiki:tiddler-make) wiki))) + +(test "s:td" '("
") (s:td '())) +;; (test "twiki:get-tiddlers-by-name" '() (twiki:get-tiddlers-by-name 1 "fred")) +(test "twiki:tiddler-name->id" 1 (twiki:tiddler-name->id *tdb* "MainMenu")) +(test "s:set! a var to #f" "" + (begin (s:set! "BLAH" #f) + (s:get "BLAH"))) ;; don't know if this one makes sense. Setting to #f should really delete the value +(test "twiki:save-dat" 2 (twiki:save-dat *tdb* "dat" 0)) +(test "twiki:get-dat" "dat" (twiki:get-dat *tdb* 2)) +(test "twiki:get-dat" #f (twiki:get-dat *tdb* 5)) +;; (test "twiki:get-dat" #f (twiki:get-dat *tdb* #f)) +(test "twiki:save-tiddler" #t (twiki:save-tiddler *tdb* "heading" "body" "tags" key 0)) +;; (test "twiki:save-curr-tiddler" #f (twiki:save-curr-tiddler *tdb* 1)) +(test "twiki:edit-twiddler" #t (list? (twiki:edit-tiddler *tdb* key 0 0))) +(test "twiki:maint_area" "
" (car (twiki:maint_area *tdb* 1 key wiki))) +(test "twiki:pic_mgmt" "
" (car (twiki:pic_mgmt *tdb* 1 key))) + +;; get a blob jpg to process +(define inp2 (open-input-file "tests/kiatoa.png")) +(define dat (string->blob (read-string #f inp2))) +(close-input-port inp2) + + +(test "twiki:save-pic" #t (twiki:save-pic *tdb* (list "mypic.jpg" "image/jpeg" dat) 0)) ;; (string->blob "testing eh!")))) +;; (test "twiki:save-pic-from-form" #f (twiki:save-pic-from-form *tdb* 1)) + +;; more tests on dats + +(define dat #f) +(let ((inp (open-input-file "tests/kiatoa.png"))) + (set! dat (read-string #f inp)) + (close-input-port inp)) +(use md5) +(define dat-md5 (md5:digest dat)) +(test "twiki:save-dat (binary)" 4 (twiki:save-dat *tdb* dat 1)) +(test "twiki:get-dat (binary)" dat-md5 (let ((d (twiki:get-dat *tdb* 4))) + (md5:digest d))) +;; forms +;; (define inp (open-input-file "tests/example.post.in")) +;; (define dat (read-string #f inp)) +;; (define datstr (open-input-string dat)) + +;; binary inputs +(define inp (open-input-file "tests/example.post.binary.in")) +(define dat #f) + +(test "formdat:load-all-port multipart" #t (let ((idat (formdat:load-all-port inp))) + (set! dat idat) + #t)) +(test "formdat:keys" '(picture-name input-picture "" submit-picture) (formdat:keys dat)) + +(define inp (open-input-file "tests/example.post.in")) +(test "formdat:load-all-port single part" #t (let ((idat (formdat:load-all-port inp))) + (set! dat idat) + #t)) +(test "formdat:keys" '(email-address form-name password) (formdat:keys dat)) + +(close-input-port inp) ADDED testscript.sh Index: testscript.sh ================================================================== --- /dev/null +++ testscript.sh @@ -0,0 +1,7 @@ +export REQUEST_URI='/stmlrun?action=login.login' +export SCRIPT_NAME=/cgi-bin/stmlrun +export PATH_INFO=/classifieds +export QUERY_STRING='action=login.login' +export SERVER_NAME=localhost +export REQUEST_METHOD=GET +export HTTP_COOKIE='session_key=to09ipFJ9_2KXT96b2f9Q'
" (()) "