PICCORO Lenz McKAY pushed to branch master at venenux / simpleticket109
Commits:
450f8796 by PICCORO Lenz McKAY at 2017-12-31T19:16:15-04:00
added attachment preview plugin as default with osticket sources but not enabled at install
- - - - -
16 changed files:
- + include/plugins/attachment_preview/.gitignore
- + include/plugins/attachment_preview/.travis.yml
- + include/plugins/attachment_preview/CODE_OF_CONDUCT.md
- + include/plugins/attachment_preview/CONTRIBUTING.md
- + include/plugins/attachment_preview/LICENSE
- + include/plugins/attachment_preview/README.md
- + include/plugins/attachment_preview/class.AttachmentPreviewPlugin.php
- + include/plugins/attachment_preview/config.php
- + include/plugins/attachment_preview/eclipse_formatter.xml
- + include/plugins/attachment_preview/phpunit.xml
- + include/plugins/attachment_preview/plugin.php
- + include/plugins/attachment_preview/sanitizer.js
- + include/plugins/attachment_preview/script.js
- + include/plugins/attachment_preview/stylesheet.css
- + include/plugins/attachment_preview/tests/AttachmentPreviewPluginTest.php
- + include/plugins/attachment_preview/tests/setup.inc
Changes:
=====================================
include/plugins/attachment_preview/.gitignore
=====================================
--- /dev/null
+++ b/include/plugins/attachment_preview/.gitignore
@@ -0,0 +1,5 @@
+tests/coverage
+.buildpath
+.project
+.settings/
+
=====================================
include/plugins/attachment_preview/.travis.yml
=====================================
--- /dev/null
+++ b/include/plugins/attachment_preview/.travis.yml
@@ -0,0 +1,15 @@
+language: php
+php:
+ - '5.6'
+ - '7.1'
+
+matrix:
+ - fast_finish: true
+
+install:
+ - wget
https://github.com/osTicket/osTicket/archive/v1.10.1.tar.gz -O ot.tgz
+ - tar xvf ot.tgz && mv osTicket-1.10.1 ../osticket
+
+before_script:
+ - '! find . -type f -name "*.php" -exec php -d error_reporting=32767 -l {} \; 2>&1 >&- | grep "^"'
+ - echo 'date.timezone = "Europe/Paris"' >> ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/travis.ini
=====================================
include/plugins/attachment_preview/CODE_OF_CONDUCT.md
=====================================
--- /dev/null
+++ b/include/plugins/attachment_preview/CODE_OF_CONDUCT.md
@@ -0,0 +1,46 @@
+# Contributor Covenant Code of Conduct
+
+## Our Pledge
+
+In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
+
+## Our Standards
+
+Examples of behavior that contributes to creating a positive environment include:
+
+* Using welcoming and inclusive language
+* Being respectful of differing viewpoints and experiences
+* Gracefully accepting constructive criticism
+* Focusing on what is best for the community
+* Showing empathy towards other community members
+
+Examples of unacceptable behavior by participants include:
+
+* The use of sexualized language or imagery and unwelcome sexual attention or advances
+* Trolling, insulting/derogatory comments, and personal or political attacks
+* Public or private harassment
+* Publishing others' private information, such as a physical or electronic address, without explicit permission
+* Other conduct which could reasonably be considered inappropriate in a professional setting
+
+## Our Responsibilities
+
+Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
+
+Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
+
+## Scope
+
+This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at
clonem...@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
+
+Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [
http://contributor-covenant.org/version/1/4][version]
+
+[homepage]:
http://contributor-covenant.org
+[version]:
http://contributor-covenant.org/version/1/4/
=====================================
include/plugins/attachment_preview/CONTRIBUTING.md
=====================================
--- /dev/null
+++ b/include/plugins/attachment_preview/CONTRIBUTING.md
@@ -0,0 +1,9 @@
+# Contribution Guidelines
+
+Please help me to make this plugin better. Your pull requests and suggestions are welcome.
+
+* Start individual Issue for each discussion topic
+* Make individual pull requests for each atomic change
+* Be sure you have searched for duplicate of your addition in existing list and Issues/Pull requests
+* Format code according to [Drupal coding standards](
https://www.drupal.org/docs/develop/standards)
+* Remove unneeded trailing whitespaces
=====================================
include/plugins/attachment_preview/LICENSE
=====================================
--- /dev/null
+++ b/include/plugins/attachment_preview/LICENSE
@@ -0,0 +1,339 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc., <
http://fsf.org/>
+ 51 Franklin Street, 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 Lesser 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.
+
+ {description}
+ Copyright (C) {year} {fullname}
+
+ 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 Street, 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.
+
+ {signature of Ty Coon}, 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 Lesser General
+Public License instead of this License.
=====================================
include/plugins/attachment_preview/README.md
=====================================
--- /dev/null
+++ b/include/plugins/attachment_preview/README.md
@@ -0,0 +1,48 @@
+# Attachment Preview
+An [osTicket](
https://github.com/osTicket/osTicket) plugin allowing inlining of Attachments
+
+[](https://travis-ci.org/clonemeagain/attachment_preview)
+
+#How it looks:
+
+
+## Current features:
+- PDF Files attachments are embedded as full PDF `<object>` in the entry.
+- Images inserted as normal `<img>` tags. Supported by most browsers: `png,jpg,gif,svg,bmp`
+- Text files attachments are inserted into using `<pre>` (If enabled).
+- HTML files are filtered and inserted (If enabled).
+- Youtube links in comments can be used to create embedded `<iframe>` players. (if enabled)
+- HTML5 Compatible video formats attached are embedded as `<video>` players. (if enabled)
+- All modifications to the DOM are now performed on the server.
+- Admin can choose the types of attachments to inline, and who can inline them.
+- Default admin options are embed "PDF's & Images" only for "Agents".
+- Plugin API: allows other plugins to manipulate the DOM without adding race conditions or multiple re-parses.
+
+## To Install:
+1. Simply `git clone
https://github.com/clonemeagain/attachment_preview.git /includes/plugins/attachment_preview` Or extract [latest-zip](
https://github.com/clonemeagain/attachment_preview/archive/master.zip) into /includes/plugins/attachment_preview
+1. Navigate to:
https://your.domain/support/scp/plugins.php?a=add to add a new plugin.
+1. Click "Install" next to "Attachment Inline Plugin"
+1. Now the plugin needs to be enabled & configured, so you should be seeing the list of currently installed plugins, pick the checkbox next to "Attachment Inline Plugin" and select the "Enable" button.
+1. Now you can configure the plugin, click the link "Attachment Inline Plugin" and choose who the plugin should be activated for, or keep the default.
+
+## To Remove:
+Navigate to admin plugins view, click the checkbox and push the "Delete" button.
+
+The plugin will still be available, you have deleted the config only at this point, to remove after deleting, remove the /plugins/attachment_preview folder.
+
+
+# How it works:
+Latest in [Wiki](
https://github.com/clonemeagain/attachment_preview/wiki)
+
+* Essentially it's simple, when enabled, and a ticket page is viewed, an output buffer is created on osTicket BootStrap which waits for the page to be finished rendering by osTicket. (Using php's register_shutdown_function & ob_start)
+* When that's done, we fetch the output buffer and convert the HTML structure into a DOMDocument, pretty standard PHP so far.
+* The plugin then runs through the link elements of the Document, to find all Attachments.
+* It then adds a new DOMElement after the attachments section, inlining each attachment. PDF's become `<object>`'s, PNG's become `<img>` etc.
+Tested and works on 1.8-git. SHOULD work on future versions, depending on how the files are attached.. haven't tested on anything else though, let me know!
+
+The plugin is self-contained, so ZERO MODS to core are required. You simply clone the repo or download the zip from github and extract into /includes/plugins/ which should make a folder: "attachment_preview", but it could be called anything.
+
+
+# TODO:
+- ??
+- You tell me!
=====================================
include/plugins/attachment_preview/class.AttachmentPreviewPlugin.php
=====================================
--- /dev/null
+++ b/include/plugins/attachment_preview/class.AttachmentPreviewPlugin.php
@@ -0,0 +1,1030 @@
+<?php
+
+require_once (INCLUDE_DIR . 'class.plugin.php');
+require_once (INCLUDE_DIR . 'class.file.php');
+require_once (INCLUDE_DIR . 'class.format.php');
+require_once ('config.php');
+
+/**
+ * Provides in-line attachments, and an interface to the DOM wrapper. Read the
+ * wiki for more. Requires PHP 5.6+
+ *
+ * @return string
+ */
+class AttachmentPreviewPlugin extends Plugin {
+
+ var $config_class = 'AttachmentPreviewPluginConfig';
+
+ /**
+ * What signal are we going to allow others to connect to?
+ *
+ * @var unknown
+ */
+ const signal_id = 'attachments.wrapper';
+
+ /**
+ * An array of received structures containing DOMElement's.
+ *
+ * @var array
+ */
+ static $foreign_elements = [];
+
+ /**
+ * You will want this off! It will post an error log entry for every single
+ * request.. which get's heavy.
+ *
+ * @var string
+ */
+ const DEBUG = FALSE;
+
+ /**
+ * An array of messages to be logged. This plugin is called before $ost is
+ * fully loaded, so it's likely/possible that actually sending $ost->logDebug
+ * $ost->logError etc isn't possible.
+ *
+ * @var array
+ */
+ private $messages = [];
+
+ /**
+ * An array of scripts to be injected.
+ *
+ * @var array
+ */
+ static $scripts = [];
+
+ /**
+ * A string of HTML to be appended madly to the end of the normal output.
+ *
+ * @var string
+ */
+ private $appended = '';
+
+ /**
+ * Try and do as little as possible in the bootstrap function, as it is called
+ * on every page load, before the system is even ready to start deciding what
+ * to do. I'm serious. $ost is what starts this, but it does it during it's
+ * own bootstrap phase, so we don't actually have access to all functions that
+ * $ost has yet.
+ *
+ * {@inheritdoc}
+ *
+ * @see Plugin::bootstrap()
+ */
+ function bootstrap() {
+ // Ensure plugin does not run during cli cron calls. There is no DOM to manipulate in CLI mode.
+ if (php_sapi_name() == 'cli') {
+ return;
+ }
+
+ // Assuming that other plugins want to inject an element or two..
+ // Provide a connection point to the attachments.wrapper
+ Signal::connect(self::signal_id, function ($object, $data) {
+ $this->debug_log("Received connection from %s", get_class($object));
+ // Assumes you want to edit the DOM with your structures, and that you've read the docs.
+ // Just save them here until the page is done rendering, then we'll make all these changes at once:
+ self::$foreign_elements[get_class($object)] = $data;
+ });
+
+ // Load our Admin defined settings..
+ $config = $this->getConfig();
+
+ // Check what our URI is, if acceptable, add to the output.. :-)
+ // Looks like there is no central router in osTicket yet, so I'll just parse REQUEST_URI
+ // Can't go injecting this into every page.. we only want it for the actual ticket pages & Knowledgebase Pages
+ if (self::isTicketsView() && $config->get('attachment-enabled')) {
+ $this->debug_log(
+ "Agent requested a tickets-view: Starting the attachments plugin.");
+ // We could hack at core, or we can simply capture the whole page output and modify the HTML then..
+ // Not "easier", but less likely to break core.. right?
+ // There appears to be a few uses of ob_start in the codebase, but they stack, so it works!
+ ob_start();
+
+ // This will run after everything else, empties the buffer and runs our code over the HTML
+ // Then we send it to the browser as though nothing changed..
+ register_shutdown_function(
+ function () {
+ $this->debug_log("Shutdown handler for inline attachments running");
+ // Output the buffer
+ // Check for Attachable's and print
+ // Note: This also checks foreign_elements
+ print $this->inlineAttachments(ob_get_clean());
+ });
+
+ // See if there was any HTML to be appended.
+ register_shutdown_function(
+ function () {
+ $this->debug_log("Shutdown hander appender running");
+ if ($this->appended) {
+ $this->debug_log("Appender appending appendable HTML");
+ print $this->appended;
+ }
+ });
+ }
+ // Actually, do we want this?
+ /*
+ else {
+ // The API stands seperate to the ostensible purpose of the plugin.
+ $this->debug_log(
+ "Exposing API as main plugin is disabled or this isn't a tickets-view.");
+ // There might be work to do via Signals.. This would otherwise be ignored as the shutdown handler
+ // is nominally only initiated when enabled.. This allows other plugins to send it jobs. ;-)
+ ob_start();
+ register_shutdown_function(
+ function () {
+ $this->debug_log("Shutdown handler remote work running");
+ // This check is for the add_script and add_arbitrary_html function output as well:
+ if (count(self::$foreign_elements)) {
+ // We've got something to do, let's do it:
+ print $this->doRemoteWork(ob_get_clean());
+ }
+ else {
+ print ob_get_clean();
+ }
+ });
+ }
+ *
+ */
+ }
+
+ /**
+ * Converts an osTicket filesize2bytes($size) string
+ * back into the number of bytes: eg: "10 mb" == 10485760
+ * @param string $formatted_size
+ * @return int
+ */
+ private function unFormatSize($formatted_size) {
+ $from = array(
+ 'bytes' => function($value) {
+ return $value;
+ },
+ 'kb' => function($value) {
+ return $value * 1024;
+ },
+ 'mb' => function($value) {
+ return $value * 1024 * 1024;
+ }
+ );
+ foreach ($from as $match => $formula) {
+ if (stripos($formatted_size, $match) !== FALSE) {
+ return call_user_func($formula, trim(str_replace($match, '', $formatted_size)));
+ }
+ }
+ }
+
+ /**
+ * Builds a DOMDocument structure representing the HTML, checks the links
+ * within for Attachments, then builds inserts inline attachment objects, and
+ * returns the new HTML as a string for printing.
+ *
+ * @param string $html
+ * @return string $html
+ */
+ private function inlineAttachments($html) {
+ if (!$html) {
+ $this->debug_log("Received no HTML, returned none..");
+ // Something broke.. we can't even really recover from this, hopefully it wasn't our fault.
+ // If this was called incorrectly, actually sending HTML could break AJAX or a binary file or something..
+ // Error message therefore disabled:
+ return '<html><body><h3>:-(</h3><p>Not sure what happened.. something broke though.</p></body></html>';
+ }
+
+ // We'll need this..
+ $config = $this->getConfig();
+ $allowed_extensions = $this->get_allowed_extensions($config);
+
+ if (!count($allowed_extensions)) {
+ $this->debug_log("Not allowed to do anything, not doing anything.");
+ // We've not been granted permission to change anything, so don't... just return original HTML.
+ return $html;
+ }
+
+ // Let's not get regex happy.. we all have the tendency.. :-)
+ $dom = self::getDom($html);
+ $xpath = new DOMXPath($dom);
+
+
+
+ // Find all <a> elements:
http://stackoverflow.com/a/29272222 as DOMElement's
+ foreach ($dom->getElementsByTagName('a') as $link) {
+ // Check the link points to osTicket's "attachments" provider:
+ // osTicket uses /file.php for all attachments
+ if (strpos($link->getAttribute('href'), '/file.php') !== FALSE) {
+
+ // Luckily, the attachment link contains the filename.. which we can use!
+ // Grab the extension of the file from the filename:
+ $ext = $this->getExtension($link->textContent);
+ $size_element = $xpath->query("following-sibling::*[1]", $link)[0];
+ if ($size_element instanceof DomElement) {
+ $size_kb = $this->unFormatSize($size_element->nodeValue);
+ $this->debug_log("Attachment is roughly: " . $size_kb . ' bytes in size.');
+ if ($config->get('attachment-size') < (int) ($size_kb / 1024)) {
+ // Skip this one, got a bit of an ass on it!
+ $this->debug_log("Skipping attachment, size filter");
+ continue;
+ }
+ }
+ $this->debug_log("Attempting to add $ext file.");
+
+ // See if admin allowed us to inject files with this extension:
+ if (!$ext || !isset($allowed_extensions[$ext])) {
+ continue;
+ }
+
+ // Find the associated method to add the attachment: (defined above, eg: csv => addTEXT)
+ $func = $allowed_extensions[$ext];
+ if (method_exists($this, $func)) {
+ $this->debug_log("Calling %s for %s", $func, $link->getAttribute('href'));
+ // Call the method to insert the linked attachment into the DOM:
+ call_user_func([
+ $this,
+ $func
+ ], $dom, $link);
+ }
+ }
+ elseif ($config->get('attach-youtube')) {
+ // This link isn't to /file.php & admin have asked us to check if it is a youtube link.
+ // The overhead of checking strpos on every URL is less than the overhead of checking for a youtube ID!
+ if (strpos($link->getAttribute('href'), 'youtub') !== FALSE) {
+ $this->add_youtube($dom, $link);
+ }
+ }
+ }
+
+ // Before we return this, let's see if any foreign_elements have been provided by other plugins, we'll insert them.
+ // This allows those plugins to edit this plugin.. seat-of-the-pants stuff!
+ if (count(self::$foreign_elements)) {
+ $this->processRemoteElements($dom); // Handles the HTML generation at the end.
+ }
+
+ // just return the original if error
+ $modified_html = self::printDom($dom);
+ if (!$modified_html) {
+ $this->log("Error manipulating the DOM");
+ return $html;
+ }
+ // The edited HTML can be sent to the browser (end of shutdown_handler calls print)
+ return $modified_html;
+ }
+
+ /**
+ * Figures out which extensions we are allowed to insert based on config
+ * Handily compiles the associated method.
+ *
+ * @param PluginConfig $config
+ */
+ private function get_allowed_extensions(PluginConfig $config) {
+ // Determine what method to run for each extension type:
+ $allowed_extensions = [];
+
+ // If you know browsers can handle more, please, submit a pull request!
+ $types = [
+ 'pdf' => [
+ 'pdf'
+ ],
+ 'text' => [
+ 'csv',
+ 'txt'
+ ],
+ 'html' => [
+ 'html'
+ ],
+ 'image' => [
+ 'bmp',
+ 'svg',
+ 'gif',
+ 'png',
+ 'jpg',
+ 'jpeg'
+ ],
+ 'audio' => [
+ 'wav',
+ 'mp3'
+ ],
+ 'video' => [
+ 'mp4',
+ 'ogv',
+ 'ogg',
+ 'ogm',
+ 'webm',
+ '3gp',
+ 'flv'
+ ]
+ ];
+ foreach ($types as $type => $extensions) {
+ if (!$config->get("attach-{$type}")) {
+ continue;
+ }
+ foreach ($extensions as $ext) {
+ // Example: [pdf] = add_pdf
+ $allowed_extensions[$ext] = 'add_' . $type;
+ }
+ }
+ return $allowed_extensions;
+ }
+
+ /**
+ * Converts a linked audio file into an embedded HTML5 player.
+ *
+ * @see
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio
+ * @param DOMDocument $doc
+ * @param DOMElement $link
+ */
+ private function add_audio(DOMDocument $doc, DOMElement $link) {
+ $audio = $doc->createElement('audio');
+ // $audio->setAttribute('autoplay','false'); //TODO: See if anyone wants these as admin options
+ // $audio->setAttribute('loop','false');
+ $audio->setAttribute('preload', 'auto');
+ $audio->setAttribute('controls', 1);
+ $audio->setAttribute('src', $link->getAttribute('href'));
+ $this->debug_log('Wrapped %s as audio player.', $link->textContent);
+ $this->wrap($doc, $link, $audio);
+ }
+
+ /**
+ * Fetches an HTML attachment as the user via javascript in the browser, then
+ * injects it into the DOM. Attempts have been made to sanitize it.
+ *
+ * @param DOMDocument $doc
+ * @param DOMElement $link
+ */
+ private function add_html(DOMDocument $doc, DOMElement $link) {
+ static $trim_func;
+ if (!$trim_func) {
+ $trim_func = TRUE;
+ $t = $doc->createElement('script');
+ $t->setAttribute('name', 'HTML Sanitizer');
+ $t->nodeValue = file_get_contents(__DIR__ . '/sanitizer.js');
+ $doc->appendChild($t);
+ }
+
+ $d = $doc->createElement('div');
+ $d->setAttribute('data-url', $link->getAttribute('href'));
+ $d->setAttribute('data-type', 'html');
+ $this->debug_log('Wrapped %s as html.', $link->textContent);
+ $this->wrap($doc, $link, $d);
+ }
+
+ /**
+ * Embeds the image into the DOM as <img> Only supports what Mozilla says
+ * browsers can support.
+ *
+ * @see
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img
+ * @param DOMDocument $doc
+ * @param DOMElement $link
+ */
+ private function add_image(DOMDocument $doc, DOMElement $link) {
+
+ // Rebuild the download link as a normal clickable link, for full-size viewing:
+ $a = $doc->createElement('a');
+ $a->setAttribute('href', $link->getAttribute('href'));
+
+ // Build an image of the referenced file, so we can simply preview it
+ $img = $doc->createElement('img');
+ $img->setAttribute('data-url', $link->getAttribute('href'));
+ $img->setAttribute('data-type', 'image');
+ // Put the image inside the link, so the image is clickable (opens in new tab):
+ $a->appendChild($img);
+
+ // Add a title attribute to the download link:
+ $link->setAttribute('title', 'Download this image.');
+ $this->debug_log('Wrapped %s as image.', $link->textContent);
+ $this->wrap($doc, $link, $a);
+ }
+
+ /**
+ * Attach PDF into the DOM
+ *
+ * @param DOMDocument $doc
+ * @param DOMElement $link
+ */
+ private function add_pdf(DOMDocument $doc, DOMElement $link) {
+ // Build a Chrome/Firefox compatible <object> to hold the PDF
+ $pdf = $doc->createElement('object');
+ $pdf->setAttribute('width', '100%');
+ $pdf->setAttribute('height', '1000px'); // Arbitrary height
+ $pdf->setAttribute('data','');//$url . '&disposition=inline'); // Can't use inline disposition with XSS security rules.. :-(
+ $pdf->setAttribute('type', 'application/pdf');
+ $pdf->setAttribute('data-type', 'pdf');
+ $pdf->setAttribute('data-url', $link->getAttribute('href'));
+
+ // Add a <b>Nope</b> type message for obsolete or text-based browsers.
+ $message = $doc->createElement('b');
+ $message->nodeValue = 'Your "browser" is unable to display this PDF. ';
+ if ($this->getConfig()->get('show-ms-upgrade-help')) {
+ $call_to_action = $doc->createElement('a');
+ $call_to_action->setAttribute('href', '
http://abetterbrowser.org/');
+ $call_to_action->setAttribute('title', 'Get a better browser to use this content inline.');
+ $call_to_action->nodeValue = 'Help';
+ $message->appendChild($call_to_action);
+ }
+ $pdf->appendChild($message);
+ $this->debug_log('Wrapped %s as pdf.', $link->textContent);
+ $this->wrap($doc, $link, $pdf);
+ }
+
+ /**
+ * Fetches a TEXT attachment entirely, and injects it into the DOM via ajax
+ *
+ * @param DOMDocument $doc
+ * @param DOMElement $link
+ */
+ private function add_text(DOMDocument $doc, DOMElement $link) {
+ $pre = $doc->createElement('pre');
+ $pre->setAttribute('data-url', $link->getAttribute('href'));
+ $pre->setAttribute('data-type', 'text');
+ $this->debug_log('Wrapped %s as preformatted text.', $link->textContent);
+ $this->wrap($doc, $link, $pre);
+ }
+
+ /**
+ * Converts a link to Youtube player Fully loaded only, ie: <a
+ * src="
youtube.com/v/12345">Link to youtube</a> only, not just a bare youtube
+ * URL.
+ *
+ * @param DOMDocument $doc
+ * @param DOMElement $link
+ */
+ private function add_youtube(DOMDocument $doc, DOMElement $link) {
+ $youtube_id = $this->getYoutubeIdFromUrl($link->getAttribute('href'));
+ if ($youtube_id !== FALSE) {
+ // Now we can add an iframe so the video is instantly playable.
+ // eg: <iframe width="560" height="349" src="
http://www.youtube.com/embed/something?rel=0&hd=1" frameborder="0" allowfullscreen></iframe>
+ // TODO: Make responsive.. if required.
+ $player = $doc->createElement('iframe');
+ $player->setAttribute('width', '560');
+ $player->setAttribute('height', '349');
+ $player->setAttribute('src', '
https://www.youtube.com/embed/' . $youtube_id . '?rel=0&hd=1');
+ $player->setAttribute('frameborder', 0);
+ $player->setAttribute('allowfullscreen', 1);
+ $this->debug_log('Wrapped %s as youtube player.', $link->textContent);
+ $this->wrap($doc, $link, $player);
+ }
+ }
+
+ /**
+ * Converts a linked video file into an embedded HTML5 player.
+ *
+ * @see
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video
+ * @param DOMDocument $doc
+ * @param DOMElement $link
+ */
+ private function add_video(DOMDocument $doc, DOMElement $link) {
+ $video = $doc->createElement('video');
+ $video->setAttribute('controls', 1);
+ $video->setAttribute('preload', 'metadata');
+ $video->nodeValue = 'Sorry, your browser doesn\'t support embedded videos, but don\'t worry, you can still download it and watch it with your favorite video player!';
+ $source = $doc->createElement('source');
+ $source->setAttribute('src', $link->getAttribute('href'));
+ $source->setAttribute('type', 'video/' . $this->getExtension($link->textContent));
+ $video->appendChild($source);
+ $this->debug_log('Wrapped %s as video player.', $link->textContent);
+ $this->wrap($doc, $link, $video);
+ }
+
+ /**
+ * Constructs a <div> element to contain each inlined attachment.
+ *
+ * @param DOMDocument $doc
+ * @param DOMElement $source
+ * @param DOMElement $new_child
+ */
+ private function wrap(DOMDocument $doc, DOMElement $source, DOMElement $new_child) {
+ // Implement a limit for attachments. Only show the admin configured amount at first
+ // if there are any more, we will inject them, however they will be shown as buttons
+ static $number;
+ static $limit;
+
+ if (!isset($number)) {
+ $number = 1;
+ // Fetch the attachment limit from the config for later
+ $limit = $this->getConfig()->get('show-initially');
+ // First attachment, add our stylesheet
+ $css = $doc->createElement('style');
+ $css->setAttribute('name', 'Attachments Preview Stylesheet');
+ $css->nodeValue = file_get_contents(__DIR__ . '/stylesheet.css', FALSE);
+ $source->parentNode->appendChild($css);
+
+ // This script enables toggling the display of the too many attachments
+ $toggle_script = $doc->createElement('script');
+ $toggle_script->setAttribute('type', 'text/javascript');
+ $toggle_script->setAttribute('name', 'Attachments Preview Toggle Script');
+
+ // This makes it translateable.
+ $replace = [
+ '#SHOW#' => __('Show Attachment'),
+ '#HIDE#' => __('Hide Attachment'),
+ '#LIMIT#' => $limit
+ ];
+ $toggle_script->nodeValue = str_replace(array_keys($replace), array_values($replace), file_get_contents(__DIR__ . '/script.js'));
+
+ // Insert the script into the first wrapped element
+ $source->parentNode->appendChild($toggle_script);
+ }
+ else {
+ $number++;
+ }
+
+ // Build a wrapper element to contain the attachment
+ $wrapper = $doc->createElement('div');
+
+ // Build an ID for the wrapper
+ $id = 'ap-file-' . $number;
+ $wrapper->setAttribute('id', $id);
+
+ // Set the child's ID.. for ease of scripting
+ $new_child->setAttribute('id', "$id-c");
+
+ // Add the element to the wrapper
+ $wrapper->appendChild($new_child);
+
+ // See if we are over the admin-defined maximum number of inline-attachments:
+ if ($limit == "ALL" || $number <= $limit) {
+ // Not limited, just add a class to received our styles
+ $wrapper->setAttribute('class', 'ap_embedded');
+ }
+ else {
+ // Instead of injecting the element, let's show a button to click
+ $button = $doc->createElement('a');
+ $button->setAttribute('class', 'button');
+
+ // Link button to the toggle function
+ $button->setAttribute('onClick', "javascript:ap_toggle(this,'$id');");
+
+ // Initially set the text, toggle will change it to "Hide" if toggled
+ $button->nodeValue = __('Show Attachment');
+
+ // Hide the whole wrapper via the class "hidden"
+ $wrapper->setAttribute('class', 'ap_embedded hidden');
+
+ // Insert the button before the wrapper, so it stays where it is when the wrapper expands.
+ $source->parentNode->appendChild($button);
+ }
+ // Add the wrapper to the thread/source element
+ $source->parentNode->appendChild($wrapper);
+ }
+
+ /**
+ * Get Youtube video ID Based on
http://stackoverflow.com/a/9785191
+ *
+ * @param string $url
+ * @return mixed Youtube video ID or FALSE if not found
+ */
+ public function getYoutubeIdFromUrl($url) {
+ // Series of possible url patterns, please pull-request any others you find!
+ // Ideally they are in "most-common" first order.
+ // Note the match group's around the ID of the video
+ $regex = array(
+ '/youtube\.com\/watch\?v=([^\&\?\/]+)/',
+ '/youtube\.com\/embed\/([^\&\?\/]+)/',
+ '/youtube\.com\/v\/([^\&\?\/]+)/',
+ '/youtu\.be\/([^\&\?\/]+)/',
+ '/youtube\.com\/verify_age\?next_url=\/watch%3Fv%3D([^\&\?\/]+)/'
+ );
+ $match = array();
+ foreach ($regex as $pattern) {
+ if (preg_match($pattern, $url, $match)) {
+ $this->debug_log('Matched youtube id: %s for url: %s', $match[1], $url);
+ // Return the matched video ID
+ return $match[1];
+ }
+ }
+ // not a youtube video
+ return FALSE;
+ }
+
+ /**
+ * Converts and HTML string into a DOMDocument.
+ *
+ * @param string $html
+ * @return \DOMDocument
+ */
+ public static function getDom($html = '') {
+ $dom = new \DOMDocument('1.0', 'UTF-8');
+ // Turn off XML errors.. if only it was that easy right?
+ $dom->strictErrorChecking = FALSE;
+ libxml_use_internal_errors(true);
+
+ // Because PJax isn't a full document, it kinda breaks DOMDocument
+ // Which expects a full document! (You know with a DOCTYPE, <HTML> <BODY> etc.. )
+ if (self::isPjax() &&
+ (strpos($html, '<!DOCTYPE') !== 0 || strpos($html, '<html') !== 0)) {
+ // Prefix the non-doctyped html snippet with an xml prefix
+ // This tricks DOMDocument into loading the HTML snippet
+ $xml_prefix = '<?xml encoding="UTF-8" />';
+ $html = $xml_prefix . $html;
+ }
+
+ // Convert the HTML into a DOMDocument, however, don't imply it's HTML, and don't insert a default Document Type Template
+ @$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
+ libxml_use_internal_errors(FALSE); // restore xml parser error handlers
+ return $dom;
+ }
+
+ /**
+ * Wrapper around DOMDocument::saveHTHML() that strips any pjax prefix we
+ * added Ensure you check for null!
+ *
+ * @param DOMDocument $dom
+ * @return mixed|string
+ */
+ public static function printDom(DOMDocument $dom) {
+ // Check for failure to generate HTML
+ // DOMDocument::saveHTML() returns null on error
+ $new_html = $dom->saveHTML();
+
+ // Remove the DOMDocument make-happy encoding prefix:
+ if (self::isPjax()) {
+ $remove_prefix_pattern = '@<\?xml encoding="UTF-8" />@';
+ $new_html = preg_replace($remove_prefix_pattern, '', $new_html);
+ }
+ return $new_html;
+ }
+
+ /**
+ * Wrapper around log method
+ */
+ private function debug_log(...$args) {
+ if (self::DEBUG) {
+ $text = array_shift($args);
+ $this->log($text, $args);
+ }
+ }
+
+ /**
+ * Supports variable replacement of $text using sprintf macros
+ *
+ * @param string $text
+ * @param mixed $args
+ */
+ private function log($text, ...$args) {
+ // Log to system, if available
+ global $ost;
+
+ if (func_num_args() > 1) {
+ $text = vsprintf($text, ...$args);
+ }
+
+ if (!$ost instanceof osTicket) {
+ // doh, can't log to the admin log without this object
+ // setup a callback to do the logging afterwards:
+ if (!$this->messages) {
+ register_shutdown_function(
+ function () {
+ $this->log_after();
+ });
+ }
+ // save the log message in memory for now
+ // the callback registered above will retrieve it and log it
+ $this->messages[] = $text;
+ return;
+ }
+
+ error_log("AttachmentPreviewPlugin: $text");
+ $ost->logInfo(wordwrap($text, 30), $text, FALSE);
+ }
+
+ /**
+ * Calls Log function again before shutting down, allows logs to be logged in
+ * admin logs, when they otherwise aren't able to be logged. :-)
+ */
+ private function log_after() {
+ global $ost;
+ if (!$ost instanceof osTicket) {
+ $this->debug_log("Unable to log to normal admin log..");
+ foreach ($this->messages as $text) {
+ $this->debug_log("Emergency PluginLog: $text");
+ }
+ }
+ else {
+ foreach ($this->messages as $text) {
+ $this->log($text);
+ }
+ }
+ }
+
+ /**
+ * Processes other plugin's structures when we don't run ours.
+ *
+ * @param string $html
+ */
+ private function doRemoteWork($html) {
+ $dom = self::getDom($html);
+ $dom = $this->processRemoteElements($dom);
+ $new_html = self::printDom($dom);
+ return $new_html ?: $html;
+ }
+
+ /**
+ * Provides an interface to safely inject HTML into any page. Hopefully
+ * useful. Used like:
+ * AttachmentsPreviewPlugin::addRawHtml('<h2>Yo!</h2>','tag','body'); Now,
+ * your <h2> will appear at the end of the <body> tag. When you don't want to
+ * build a sendable structure and send a Signal, just addRaw!
+ *
+ *
+ * @param string $html
+ * @param string $locator
+ * one of: id,tag,xpath
+ * @param string $expression
+ * an expression used by the locator to place the HTML Nodes within
+ * the Dom.
+ */
+ public static function add_arbitrary_html($html = '', $locator = 'id', $expression = 'pjax-container') {
+
+ // Define a static index, we increment it for every node we add
+ static $foreigners = 1;
+
+ if (self::DEBUG) {
+ // note: static function can't call $this->debug_log()
+ error_log("Received arbitrary HTML injection");
+ }
+
+ // Wrap in a <div> then check for children of it immediately after:
+ // DOMElement needs something like a div to wrap it.. otherwise it loads scripts as a DOMCdataElement or something
+ $dom = self::getDom("<html><div>$html</div></html>");
+ // Now everything that they added can be injected as a "Foreign Element"
+ // Note the selector selects the first <div> which is what we injected two lines up:
+ $structures = [];
+ foreach ($dom->getElementsByTagName('div')->item(0)->childNodes as $node) {
+ $structures[] = (object) [
+ 'element' => $node,
+ 'locator' => $locator,
+ 'expression' => $expression
+ ];
+ }
+ if (count($structures)) {
+ self::$foreign_elements['raw-' . $foreigners++] = $structures;
+ }
+ }
+
+ /**
+ * Adds a script by rebuilding the script into an injectable format. Don't
+ * wrap in <script> tags. Assumes all scripts want to be just before the
+ * </body> tag.
+ *
+ * @param string $script
+ */
+ public static function add_arbitrary_script($script) {
+ static $script_count = 1;
+ if (self::DEBUG) {
+ error_log("Received arbitrary script injection");
+ }
+ $dom = new DOMDocument();
+ $script_element = $dom->createElement('script');
+ $script_element->setAttribute('type', 'text/javascript');
+ $script_element->nodeValue = $script;
+
+ // Connect to the attachment_previews API wrapper and save the structure:
+ self::$foreign_elements['raw-script-' . $script_count++] = [
+ (object) [
+ 'locator' => 'tag', // References an HTML tag, in this case <body>
+ 'expression' => 'body', // Append to the end of the body (persists through pjax loads of the container)
+ 'element' => $script_element
+ ]
+ ];
+ }
+
+ /**
+ * Prints whatever is given to it, after the page is done. Designed to occur
+ * AFTER bootstrapping. See end of checkPermissionsAndRun()
+ *
+ * @param string $html
+ */
+ public static function appendHtml($html) {
+ if (self::DEBUG) {
+ error_log("Received html append");
+ }
+ $this->appended .= $html;
+ }
+
+ /**
+ * Receives a DOMDocument, returns a DOMDocument that might contain foreign
+ * element changes. Works on self::$foreign_elements as an API of changes to
+ * the DOM.
+ *
+ * @param DOMDocument $dom
+ * @throws \Exception
+ * @return DOMDocument
+ */
+ private function processRemoteElements(DOMDocument &$dom) {
+ //@formatter:off
+ /*
+ * $this->foreign_elements should be an array of structures like:
+ * [
+ * 'sourceClassName' =>
+ * [ (object)[
+ * 'element' => $element, // The DOMElement to replace/inject etc.
+ * 'locator' => 'tag', // EG: tag/id/xpath
+ * 'replace_found' => FALSE, // default
+ * 'setAttribute' =>
+ * [
+ * 'attribute_name' => 'attribute_value'
+ * ],
+ * 'expression' => 'body' // which tag/id/xpath etc.
+ * ],
+ * (object)[ // next structure properties ]
+ * ]
+ * ]
+ */
+ //@formatter:on
+ if (!count(self::$foreign_elements)) {
+ // We've already done them.
+ return $dom;
+ }
+ foreach (self::$foreign_elements as $source => $structures) {
+ $this->debug_log("Loading %d remote structures from %s", count($structures), $source);
+ foreach ($structures as $structure) {
+ // Validate the Structure
+ if (!is_object($structure)) {
+ $this->debug_log("Structure wasn't an object. Skipped.");
+ continue; // just skip
+ }
+ try {
+ if (!property_exists($structure, 'setAttribute') && (!property_exists(
+ $structure, 'element') || !is_object($structure->element) ||
+ !$structure->element instanceof DOMElement)) {
+ // What?
+ throw new \Exception(
+ "Invalid or missing parameter 'element' from source {$source}.");
+ }
+
+ // Verify that the sender used a tag/id/xpath
+ if (!property_exists($structure, 'locator')) {
+ throw new \Exception("Invalid or missing locator");
+ }
+ if (!property_exists($structure, 'replace_found')) {
+ $structure->replace_found = FALSE;
+ }
+
+ if (!property_exists($structure, 'expression')) {
+ throw new \Exception("Invalid or missing expression");
+ }
+
+ // Load the element(s) into our DOM, we can't insert them until then.
+ if (!property_exists($structure, 'setAttribute')) {
+ // we aren't just changing an attribute, we are inserting new or replacing.
+ $imported_element = $dom->importNode($structure->element, true);
+ }
+
+ // Based on type of DOM Selector, lets insert this imported element.
+ switch ($structure->locator) {
+ case 'xpath':
+ // TODO: Fix this.. doesn't seem to work
+ $finder = new \DOMXPath($dom);
+ $test = 0;
+ foreach ($finder->query($structure->expression) as $node) {
+ $test++;
+ $this->updateStructure($node, $structure, $imported_element);
+ }
+ if (!$test) {
+ throw new Exception("Nothing matched: {$structure->expression}");
+ }
+ break;
+ case 'id':
+ // Note, ID doesn't mean jQuery $('#id'); usefulness.. its xml:id="something", which none of our docs will have.
+ $finder = new \DOMXPath($dom);
+ // Add a fake namespace for the XPath class.. which needs one:
+ // $finder->registerNamespace('pluginprefix',
+ // $_SERVER['SERVER_NAME'] . '/pluginnamespace');
+ // Find the first DOMElement with the id attribute matching the expression, there should only be one
+ $nodeList = $finder->query("//*[@id='{$structure->expression}']");
+ // Check length of the DOMNodeList
+ if ($nodeList->length) {
+ $node = $nodeList->item(0);
+ $this->debug_log("Found a match for $expression!");
+ }
+ else {
+ $this->log("Unable to find node with expression %s", $structure->expression);
+ continue;
+ }
+ $this->updateStructure($node, $structure, $imported_element);
+ break;
+ case 'tag':
+ foreach ($dom->getElementsByTagName($structure->expression) as $node) {
+ $this->updateStructure($node, $structure, $imported_element);
+ }
+ break;
+ default:
+ $this->log(
+ "Your locator from %s is invalid, %s has not been implemented. Available options are: xpath,id,tag", $source, $structure->locator);
+ continue;
+ }
+ } catch (\Exception $de) {
+ $this->log("FAIL: %s triggered DOM error: %s", $source, $de->getMessage());
+ }
+ $this->debug_log('Successfull.');
+ }
+ }
+ // Clear the array
+ self::$foreign_elements = array();
+ }
+
+ /**
+ * Connects a remote structure with a DOMElement. either setting attributes,
+ * or appending or replacing nodes..
+ *
+ * @param \DOMElement $node
+ * @param stdClass $structure
+ * @param \DOMElement $imported_element
+ */
+ private function updateStructure(\DOMElement $node, $structure, \DOMElement $imported_element = null) {
+ if ($structure->replace_found) {
+ $node->parentNode->replaceChild($node, $imported_element);
+ }
+ elseif ($structure->setAttribute) {
+ foreach ($structure->setAttribute as $key => $val) {
+ $node->setAttribute($key, $val);
+ }
+ }
+ else {
+ $node->appendChild($imported_element);
+ }
+ }
+
+ /**
+ * Retrieve the file extension from a string in lowercase
+ *
+ * @param DOMElement $link
+ * @return string
+ */
+ public static function getExtension($string) {
+ return trim(strtolower(pathinfo($string, PATHINFO_EXTENSION)));
+ }
+
+ /**
+ * We only want to inject when viewing tickets, not when EDITING tickets.. or
+ * any other view. Available statically via:
+ * AttachmentPreviewPlugin::isTicketsView()
+ *
+ * @return bool whether or not current page is viewing a ticket.
+ */
+ public static function isTicketsView() {
+ $tickets_view = FALSE;
+ $url = $_SERVER['REQUEST_URI'];
+
+ // Only checks it once per pageload
+ // Run through the most likely candidates first:
+ // Ignore POST data, unless we're seeing a new ticket, then don't ignore.
+ if (isset($_POST['a']) && $_POST['a'] == 'open') {
+ $tickets_view = TRUE;
+ }
+ elseif (strpos($url, '/scp/') === FALSE) {
+ // URL doesn't include /scp/ so isn't an agent page
+ $tickets_view = FALSE;
+ }
+ elseif (isset($_POST) && count($_POST)) {
+ // If something has been POST'd to osTicket, assume we're not Viewing a ticket
+ $tickets_view = FALSE;
+ }
+ elseif (strpos($url, 'a=edit') || strpos($url, 'a=print')) {
+ // URL contains a=edit or a=print, so assume we aren't needed here!
+ $tickets_view = FALSE;
+ }
+ elseif (strpos($url, 'index.php') !== FALSE ||
+ strpos($url, 'tickets.php') !== FALSE) {
+ // Might be a ticket page..
+ $tickets_view = TRUE;
+ }
+ else {
+ // Default
+ $tickets_view = FALSE;
+ }
+
+ if (self::DEBUG) {
+ error_log(
+ "Matched $url as " . ($tickets_view ? 'ticket' : 'not ticket'));
+ }
+
+ return $tickets_view;
+ }
+
+ /**
+ * Determines if the page was/is being build from a PJAX request. Uses the
+ * request header.
+ *
+ * @return bool
+ */
+ public static function isPjax() {
+ return (isset($_SERVER['HTTP_X_PJAX']) && $_SERVER['HTTP_X_PJAX'] == 'true');
+ }
+
+ /**
+ * Required stub.
+ *
+ * {@inheritdoc}
+ *
+ * @see Plugin::uninstall()
+ */
+ function uninstall(&$errors) {
+ parent::uninstall($errors);
+ }
+
+ /**
+ * Plugin seems to want this.
+ */
+ public function getForm() {
+ return [];
+ }
+
+}
=====================================
include/plugins/attachment_preview/config.php
=====================================
--- /dev/null
+++ b/include/plugins/attachment_preview/config.php
@@ -0,0 +1,114 @@
+<?php
+require_once INCLUDE_DIR . 'class.plugin.php';
+
+class AttachmentPreviewPluginConfig extends PluginConfig {
+
+ // Provide compatibility function for versions of osTicket prior to
+ // translation support (v1.9.4)
+ function translate() {
+ if (! method_exists('Plugin', 'translate')) {
+ return [
+ function ($x) {
+ return $x;
+ },
+ function ($x, $y, $n) {
+ return $n != 1 ? $y : $x;
+ }
+ ];
+ }
+ return Plugin::translate('attachment_preview');
+ }
+
+ /**
+ * Build an Admin settings page.
+ *
+ * {@inheritdoc}
+ *
+ * @see PluginConfig::getOptions()
+ */
+ function getOptions() {
+ list ($__, $_N) = self::translate();
+
+ return [
+ 'attachment-enabled' => new BooleanField(
+ [
+ 'label' => $__('Permission'),
+ 'default' => TRUE,
+ 'hint' => 'Check to enable attachments inline, uncheck only allows the API to function.'
+ ]),
+ 'attachment-size' => new TextboxField(
+ [
+ 'label' => $__('Max Size'),
+ 'default' => 1024,
+ 'hint' => 'Enter maximum Kilobytes of an attachment to inline. Larger attachments are ignored.'
+ ]),
+ 'attach-pdf' => new BooleanField(
+ [
+ 'label' => $__('Inline PDF files as <object>s'),
+ 'default' => TRUE
+ ]),
+ 'attach-image' => new BooleanField(
+ [
+ 'label' => $__('Inline image files as <img>s'),
+ 'default' => TRUE
+ ]),
+ 'attach-text' => new BooleanField(
+ [
+ 'label' => $__('Inline textfiles (txt,csv) as <pre>'),
+ 'default' => TRUE
+ ]),
+ 'attach-html' => new BooleanField(
+ [
+ 'label' => $__('Inline HTML files into a <div>'),
+ 'hint' => $__(
+ 'Dangerous: While we filter/sanitize the HTML, make sure it is something you really need before turning on.'),
+ 'default' => FALSE
+ ]),
+ 'attach-audio' => new BooleanField(
+ [
+ 'label' => $__('Inline audio attachments as Players'),
+ 'default' => FALSE
+ ]),
+ 'attach-video' => new BooleanField(
+ [
+ 'label' => $__('Inline video attachments as Players'),
+ 'hint' => $__("Embeds video attachments "),
+ 'default' => FALSE
+ ]),
+ 'attach-youtube' => new BooleanField(
+ [
+ 'label' => $__('Inline Youtube links to Players'),
+ 'default' => FALSE
+ ]),
+ 'show-ms-upgrade-help' => new BooleanField(
+ [
+ 'label' => $__('Show IE upgrade link'),
+ 'hint' => $__(
+ 'Enable help link to
abetterbrowser.org for PDFs when on Internet Explorer'),
+ 'default' => TRUE
+ ]),
+ 'show-initially' => new ChoiceField(
+ [
+ 'label' => $__('Number of attachments to show initially'),
+ 'default' => "ALL",
+ 'hint' => $__(
+ 'If you find too many attachments displaying at once is slowing you down, change this to only show some of them at first.'),
+ 'choices' =>
+ [
+ "NONE" => '0',
+ '1' => '1',
+ '2' => '2',
+ '3' => '3',
+ '4' => '4',
+ '5' => '5',
+ '6' => '6',
+ '7' => '7',
+ '8' => '8',
+ '9' => '9',
+ '10' => '10',
+ "ALL" => $__('All') // Woo.
+ ]
+ ])
+ ];
+ }
+}
\ No newline at end of file
=====================================
include/plugins/attachment_preview/eclipse_formatter.xml
=====================================
--- /dev/null
+++ b/include/plugins/attachment_preview/eclipse_formatter.xml
@@ -0,0 +1,210 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<profiles>
+<profile name="Drupal">
+<setting id="indentationChar" value=" "/>
+<setting id="insert_space_after_opening_paren_in_declare" value="false"/>
+<setting id="insert_space_before_closing_paren_in_declare" value="false"/>
+<setting id="insert_space_before_opening_paren_in_declare" value="false"/>
+<setting id="org.eclipse.php.core.formatter.insert_new_line_in_function_invoke" value="3"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_arguments_in_allocation_expression_force_split" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_arguments_in_allocation_expression_indent_policy" value="0"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_arguments_in_allocation_expression_line_wrap_policy" value="1"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_arguments_in_method_invocation_force_split" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_arguments_in_method_invocation_indent_policy" value="0"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_arguments_in_method_invocation_line_wrap_policy" value="1"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_assignment_force_split" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_assignment_indent_policy" value="0"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_assignment_line_wrap_policy" value="0"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_binary_expression_force_split" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_binary_expression_indent_policy" value="0"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_binary_expression_line_wrap_policy" value="1"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_compact_if_force_split" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_compact_if_indent_policy" value="0"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_compact_if_line_wrap_policy" value="0"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_conditional_expression_force_split" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_conditional_expression_indent_policy" value="0"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_conditional_expression_line_wrap_policy" value="0"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_expressions_in_array_initializer_force_split" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_expressions_in_array_initializer_indent_policy" value="0"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_expressions_in_array_initializer_line_wrap_policy" value="3"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_parameters_in_method_declaration_force_split" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_parameters_in_method_declaration_indent_policy" value="0"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_parameters_in_method_declaration_line_wrap_policy" value="1"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_superclass_in_type_declaration_force_split" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_superclass_in_type_declaration_indent_policy" value="0"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_superclass_in_type_declaration_line_wrap_policy" value="0"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_superinterfaces_in_type_declaration_force_split" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_superinterfaces_in_type_declaration_indent_policy" value="0"/>
+<setting id="org.eclipse.php.formatter.core.formatter.alignment_for_superinterfaces_in_type_declaration_line_wrap_policy" value="1"/>
+<setting id="org.eclipse.php.formatter.core.formatter.blank_lines_before_field" value="1"/>
+<setting id="org.eclipse.php.formatter.core.formatter.blank_lines_before_member_type" value="1"/>
+<setting id="org.eclipse.php.formatter.core.formatter.blank_lines_before_method" value="1"/>
+<setting id="org.eclipse.php.formatter.core.formatter.blank_lines_between_type_declarations" value="1"/>
+<setting id="org.eclipse.php.formatter.core.formatter.brace_position_for_block" value="0"/>
+<setting id="org.eclipse.php.formatter.core.formatter.brace_position_for_lambda_function_declaration" value="0"/>
+<setting id="org.eclipse.php.formatter.core.formatter.brace_position_for_method_declaration" value="0"/>
+<setting id="org.eclipse.php.formatter.core.formatter.brace_position_for_switch" value="0"/>
+<setting id="org.eclipse.php.formatter.core.formatter.brace_position_for_type_declaration" value="0"/>
+<setting id="org.eclipse.php.formatter.core.formatter.comment.clear_blank_lines_in_block_comment" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.comment.clear_blank_lines_in_javadoc_comment" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.comment.format_block_comments" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.comment.format_header" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.comment.format_html" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.comment.format_javadoc_comments" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.comment.format_line_comments" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.comment.format_source_code" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.comment.indent_parameter_description" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.comment.indent_root_tags" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.comment.insert_new_line_before_root_tags" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.comment.insert_new_line_for_parameter" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.comment.line_length" value="80"/>
+<setting id="org.eclipse.php.formatter.core.formatter.comment.new_lines_at_block_boundaries" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.comment.new_lines_at_javadoc_boundaries" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.comment.preserve_white_space_between_code_and_line_comments" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.continuation_indentation" value="1"/>
+<setting id="org.eclipse.php.formatter.core.formatter.continuation_indentation_for_array_initializer" value="1"/>
+<setting id="org.eclipse.php.formatter.core.formatter.disabling_tag" value="@formatter:off"/>
+<setting id="org.eclipse.php.formatter.core.formatter.enabling_tag" value="@formatter:on"/>
+<setting id="org.eclipse.php.formatter.core.formatter.format_guardian_clause_on_one_line" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.format_line_comment_starting_on_first_column" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.indent_body_declarations_compare_to_type_header" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.indent_breaks_compare_to_cases" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.indent_empty_lines" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.indent_statements_compare_to_block" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.indent_statements_compare_to_body" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.indent_switchstatements_compare_to_cases" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.indent_switchstatements_compare_to_switch" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.indentation.size" value="2"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_new_line_after_opening_brace_in_array_initializer" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_new_line_before_catch_in_try_statement" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_new_line_before_closing_brace_in_array_initializer" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_new_line_before_else_in_if_statement" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_new_line_before_finally_in_try_statement" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_new_line_before_while_in_do_statement" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_new_line_in_empty_block" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_new_line_in_empty_method_body" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_new_line_in_empty_type_declaration" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_arrow_in_array_creation" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_arrow_in_field_access" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_arrow_in_foreach" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_arrow_in_method_invocation" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_arrow_in_yield" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_assignment_operator" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_binary_operator" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_closing_brace_in_block" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_closing_paren_in_cast" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_colon_in_conditional" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_coloncolon_in_field_access" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_coloncolon_in_method_invocation" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_comma_in_array_creation" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_comma_in_echo" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_comma_in_for_inits" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_comma_in_global" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_comma_in_list" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_comma_in_method_declaration_parameters" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_comma_in_method_invocation_arguments" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_comma_in_multiple_constant_declarations" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_comma_in_multiple_field_declarations" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_comma_in_static" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_comma_in_superinterfaces" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_opening_bracket_in_array_reference" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_opening_paren_in_array_creation" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_opening_paren_in_cast" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_opening_paren_in_catch" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_opening_paren_in_for" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_opening_paren_in_foreach" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_opening_paren_in_if" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_opening_paren_in_list" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_opening_paren_in_method_declaration" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_opening_paren_in_method_invocation" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_opening_paren_in_switch" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_opening_paren_in_while" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_postfix_operator" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_prefix_operator" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_question_in_conditional" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_semicolon_in_for" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_after_unary_operator" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_arrow_in_array_creation" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_arrow_in_field_access" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_arrow_in_foreach" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_arrow_in_method_invocation" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_arrow_in_yield" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_assignment_operator" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_binary_operator" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_closing_bracket_in_array_reference" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_closing_paren_in_array_creation" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_closing_paren_in_cast" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_closing_paren_in_catch" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_closing_paren_in_for" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_closing_paren_in_foreach" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_closing_paren_in_if" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_closing_paren_in_list" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_closing_paren_in_method_declaration" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_closing_paren_in_method_invocation" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_closing_paren_in_switch" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_closing_paren_in_while" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_colon_in_case" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_colon_in_conditional" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_colon_in_default" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_coloncolon_in_field_access" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_coloncolon_in_method_invocation" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_comma_in_array_creation" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_comma_in_echo" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_comma_in_for_inits" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_comma_in_global" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_comma_in_list" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_comma_in_method_declaration_parameters" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_comma_in_method_invocation_arguments" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_comma_in_multiple_constant_declarations" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_comma_in_multiple_field_declarations" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_comma_in_static" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_comma_in_superinterfaces" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_opening_brace_in_block" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_opening_brace_in_method_declaration" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_opening_brace_in_switch" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_opening_brace_in_type_declaration" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_opening_bracket_in_array_reference" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_opening_paren_in_array_creation" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_opening_paren_in_catch" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_opening_paren_in_for" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_opening_paren_in_foreach" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_opening_paren_in_if" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_opening_paren_in_list" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_opening_paren_in_method_declaration" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_opening_paren_in_method_invocation" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_opening_paren_in_switch" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_opening_paren_in_while" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_postfix_operator" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_prefix_operator" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_question_in_conditional" value="true"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_semicolon" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_semicolon_in_for" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_before_unary_operator" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_between_brackets_in_array_type_reference" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_between_empty_parens_in_method_declaration" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.insert_space_between_empty_parens_in_method_invocation" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.join_lines_in_comments" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.keep_else_statement_on_same_line" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.keep_elseif_statement_on_same_line" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.keep_imple_if_on_one_line" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.keep_then_statement_on_same_line" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.lineSplit" value="80"/>
+<setting id="org.eclipse.php.formatter.core.formatter.never_indent_block_comments_on_first_column" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.never_indent_line_comments_on_first_column" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.number_of_blank_lines_after_namespace" value="1"/>
+<setting id="org.eclipse.php.formatter.core.formatter.number_of_blank_lines_after_use_statements" value="0"/>
+<setting id="org.eclipse.php.formatter.core.formatter.number_of_blank_lines_at_beginning_of_method_body" value="0"/>
+<setting id="org.eclipse.php.formatter.core.formatter.number_of_blank_lines_at_end_of_class_body" value="0"/>
+<setting id="org.eclipse.php.formatter.core.formatter.number_of_blank_lines_at_end_of_method_body" value="0"/>
+<setting id="org.eclipse.php.formatter.core.formatter.number_of_blank_lines_before_namespace" value="0"/>
+<setting id="org.eclipse.php.formatter.core.formatter.number_of_blank_lines_before_use_statements" value="0"/>
+<setting id="org.eclipse.php.formatter.core.formatter.number_of_blank_lines_between_namespaces" value="0"/>
+<setting id="org.eclipse.php.formatter.core.formatter.number_of_blank_lines_between_use_statements" value="0"/>
+<setting id="org.eclipse.php.formatter.core.formatter.number_of_empty_lines_to_preserve" value="1"/>
+<setting id="org.eclipse.php.formatter.core.formatter.put_empty_statement_on_new_line" value="false"/>
+<setting id="org.eclipse.php.formatter.core.formatter.tabulation.size" value="4"/>
+<setting id="org.eclipse.php.formatter.core.formatter.use_on_off_tags" value="true"/>
+</profile>
+</profiles>
=====================================
include/plugins/attachment_preview/phpunit.xml
=====================================
--- /dev/null
+++ b/include/plugins/attachment_preview/phpunit.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<phpunit>
+<testsuite name='AttachmentPreviewPluginTestSuite'>
+ <directory suffix='.php'>./tests</directory>
+</testsuite>
+<filter>
+ <whitelist processUncoveredFilesFromWhitelist="true">
+ <directory suffix=".php">./</directory>
+ <file></file>
+ </whitelist>
+</filter>F
+</phpunit>
=====================================
include/plugins/attachment_preview/plugin.php
=====================================
--- /dev/null
+++ b/include/plugins/attachment_preview/plugin.php
@@ -0,0 +1,11 @@
+<?php
+
+return array(
+ 'id' => 'clonemeagain:attachment_preview', # notrans
+ 'version' => '1.0',
+ 'name' => 'Attachment Inline Plugin',
+ 'author' => '
clonem...@gmail.com',
+ 'description' => 'Modifies the page to include as many attachments as would make sense, directly into the Thread.',
+ 'url' => '
https://github.com/clonemeagain/attachment_preview',
+ 'plugin' => 'class.AttachmentPreviewPlugin.php:AttachmentPreviewPlugin'
+);
=====================================
include/plugins/attachment_preview/sanitizer.js
=====================================
--- /dev/null
+++ b/include/plugins/attachment_preview/sanitizer.js
@@ -0,0 +1,41 @@
+// src:
https://gist.github.com/ufologist/5a0da51b2b9ef1b861c30254172ac3c9
+var sanitizer = {};
+(function($) {
+ var safe = '<a><b><blockquote><dd><div><dl><dt><em><h1><h2><h3><h4><i><img><li><ol><p><pre><s><sup><sub><strong><strike><ul><br><hr><table><th><tr><td><tbody><tfoot>';
+
+ function trimAttributes(node) {
+ $.each(node.attributes, function() {
+ var attrName =
this.name;
+ var attrValue = this.value;
+ // we could filter the "bad" attributes, or just purge them all..
+ $(node).removeAttr(attrName);
+ });
+ }
+ sanitizer.sanitize = function(html) {
+ html = strip_tags(html, safe);
+ var output = $($.parseHTML('<div>' + $.trim(html) + '</div>', null,
+ false));
+ output.find('*').each(function() {
+ trimAttributes(this);
+ });
+ return output.html();
+ }
+
+ //
http://locutus.io/php/strings/strip_tags/ filter the html to only those
+ // acceptable tags defined above as safe
+ function strip_tags(input, allowed) {
+ allowed = (((allowed || '') + '').toLowerCase().match(
+ /<[a-z][a-z0-9]*>/g) || []).join('')
+ var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi
+ var commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi
+ return input
+ .replace(commentsAndPhpTags, '')
+ .replace(
+ tags,
+ function($0, $1) {
+ return allowed
+ .indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0
+ : ''
+ })
+ }
+})(jQuery);
\ No newline at end of file
=====================================
include/plugins/attachment_preview/script.js
=====================================
--- /dev/null
+++ b/include/plugins/attachment_preview/script.js
@@ -0,0 +1,124 @@
+'use strict';
+// Attachments Preview Script.
+
+/**
+ * Configure handler for ready/pjax-ready events.
+ *
+ * Basically, starts fetching non hidden attachments when the page is ready.
+ *
+ * @returns void
+ */
+$(document).on('ready pjax:success', function() {
+ var attachments = $(".ap_embedded:not(.hidden)");
+ if(attachments.length){
+ console.log("Fetching " + attachments.length + " non-hidden attachment" + ((attachments.length > 1) ? 's.' : '.'));
+ attachments.trigger('ap:fetch');
+ }
+});
+
+/**
+ * Toggle function for buttons, shows the attachment's wrapper element and
+ * triggers the fetch if the attachment isn't already there.
+ *
+ * @param item
+ * (the button that was clicked)
+ * @param key
+ * (the id of the element we want to expand/load)
+ * @return false to prevent bubbling of event.
+ */
+function ap_toggle(item, key) {
+ var i = $(item), elem = $('#' + key);
+ elem.slideToggle();
+ if (i.text() === '#HIDE#') {
+ i.text('#SHOW#');
+ } else {
+ elem.trigger('ap:fetch');
+ i.text('#HIDE#');
+ }
+ return false;
+}
+
+/**
+ * Slightly more convoluted that the other types Load the PDF into an Object
+ * Blob and shove it into the <embed> :-)
+ *
+ * @param id id of the element to inject the pdf
+ * @param url of the file to convert into a Blob and inject
+ */
+function fetch_pdf(id, url) {
+ var pdf = document.getElementById(id);
+ if (/* @cc_on!@ */false || !!document.documentMode) {
+ // IE still cant display a PDF inside an <object>
+ console.log("Why Microsoft?");
+ var b = $(pdf).contents();
+ $(pdf).replaceWith(b);
+ return;
+ }
+ var req = new XMLHttpRequest();
+ req.open("GET", url, true)
+ req.responseType = "arraybuffer";
+ req.onload = function(e) {
+ var ab = req.response;
+ var blob = new Blob([ ab ], {
+ type : "application/pdf"
+ });
+ // Convert the binary blob of PDF data into an Object URL
+ var object_url = (window.URL || window.webkitURL).createObjectURL(blob);
+ if(!object_url){
+ return;
+ }
+
+ var newpdf = pdf.cloneNode();
+ newpdf.setAttribute('data', object_url);
+
+ // Replace the node with our new one which displays it:
+ pdf.parentNode.replaceChild(newpdf, pdf);
+ // prevent repeated fetch events from re-fetching
+ delete newpdf.dataset.type;
+ };
+ req.send();
+}
+
+/**
+ * Setup handler to receive Attachments Preview Fetch events, and act on them.
+ * This is starting to look like the original version.. all javascript.
+ */
+$(document).on(
+ 'ap:fetch',
+ function(e) {
+ var elem = $(e.target).find('[data-type]').first(),
+ type = elem.data('type'),
+ url = elem.data('url');
+ if (type &&& url) { // Is it a PHP7 thing? wtf
+ switch (type) {
+ case 'image': {
+ // We just have to set the src url, let the browser fetch
+ // the file as normal.
+ elem.attr('src',url);
+ break;
+ }
+ case 'pdf': {
+ // Call our Wunderbar Blobinator function
+ var id = elem.attr('id');
+ fetch_pdf(id, url);
+ break;
+ }
+ case 'text':
+ // Replace the <pre> element's text with the Attachment:
+ $.get(url, function(data) {
+ elem.text(data);
+ });
+ break;
+ case 'html':
+ // Replace the html with the attachment, after passing
+ // through the sanitizer:
+ $.get(url, function(data) {
+ elem.html($("<div>" + $.trim(sanitizer.sanitize(data))
+ + "</div>"));
+ });
+ }
+ // prevent repeated fetch events from re-fetching
+ elem.data('type', '');
+ }
+ });
+console.log("AttachmentPreview plugin loaded, initial fetch limit configured to #LIMIT#.");
\ No newline at end of file
=====================================
include/plugins/attachment_preview/stylesheet.css
=====================================
--- /dev/null
+++ b/include/plugins/attachment_preview/stylesheet.css
@@ -0,0 +1,22 @@
+@CHARSET "ISO-8859-1";
+/** Allow attachments to be as big as the thread */
+.thread-body .attachment-info {
+ width: 100%;
+ height: auto;
+}
+/** Add some borders and margins */
+div.ap_embedded {
+ max-width: 100%;
+ height: auto;
+ padding: 4px;
+ border: 1px solid #C3D9FF;
+ margin-top: 10px;
+}
+
+div.ap_embedded img {
+ max-width: 100%;
+}
+/* If we get reeeeeallly specific with it, CSS let's us override things in a stylesheet */
+.thread-body>div.attachments>span.attachment-info>div.ap_embedded {
+ margin-bottom: 10px !important;
+}
\ No newline at end of file
=====================================
include/plugins/attachment_preview/tests/AttachmentPreviewPluginTest.php
=====================================
--- /dev/null
+++ b/include/plugins/attachment_preview/tests/AttachmentPreviewPluginTest.php
@@ -0,0 +1,162 @@
+<?php
+
+/**
+ * I've started testing.. yay.
+ */
+use PHPUnit\Framework\TestCase;
+
+// Get some mocks
+include_once 'setup.inc';
+
+//TODO: Migrate this to phpunit!
+// Now, we can test things!
+//
+final class AttachmentPreviewPluginTest extends TestCase {
+
+ private $plugin;
+
+ protected function setUp() {
+ // reset the mock
+ $this->plugin = new AttachmentPreviewPlugin(1);
+ }
+
+// Let's start with the bottom, and work our way up.. phew!
+ //public function testBootstrap(){
+ //how to test?
+ //}
+ //
+ //skip 10 other private methods.. for now.
+ //public function wrap()// fuck.
+
+ /**
+ * Test Youtube fetcher
+ * @param type $url
+ * @dataProvider getYoutubeUrls
+ */
+ public function testGetYoutubeIdFromUrl($url, $expectation) {
+ $this->assertEquals($this->plugin->getYoutubeIdFromUrl($url), $expectation);
+ }
+
+ public function getYoutubeUrls() {
+ return [
+ ['
https://www.youtube.com/watch?v=53nCql7VEXA', '53nCql7VEXA'],
+ ['
m.youtube.com/watch?v=53nCql7VEXA&app=desktop', '53nCql7VEXA']
+ ];
+ }
+
+ //public function testGetDom()// who named this shit?
+ //public function testPrintDom() // needs a dom..
+
+ public function fakeApiUser() {
+ // Need a remote structure to test with.. christ.
+ $dom = new DOMDocument();
+ $script_element = $dom->createElement('b');
+ $script_element->nodeValue = 'FINDME';
+
+ // Connect to the attachment_previews API wrapper and save the structure:
+ Signal::send('attachments.wrapper', 'test', (object) [
+ 'locator' => 'tag', // References an HTML tag, in this case <body>
+ 'expression' => 'body', // Append to the end of the body (persists through pjax loads of the container)
+ 'element' => $script_element
+ ]
+ );
+
+ $html = '<!DOCTYPE html><html><head><title>Title!</title></head><body><p>Body!</p></body></html>';
+ }
+
+ // public function testAddArbitraryHtml(){} // really?
+ public function testAddArbitraryScript() {
+ $script = 'var variable = 1;';
+ AttachmentPreviewPlugin::add_arbitrary_script($script);
+
+ $this->assertArrayHasKey('raw-script-1', AttachmentPreviewPlugin::$foreign_elements);
+ $obj = reset(AttachmentPreviewPlugin::$foreign_elements['raw-script-1']);
+ $this->assertInstanceOf(DOMElement::class, $obj->element);
+ }
+
+ // public function testAppendHtml(){} // pointless
+ // public function testProcessRemoteElements(){} // christ
+ //public function testUpdateStructure(){
+ // hmm.. we'll need a DOMDocument structure, something to add to it
+ // and a way of testing that it's updated.. fuck.
+ //}
+
+ /** Test for getExtension($string)
+ * @dataProvider getExtensionData
+ */
+ public function testGetExtension($filename, $expectation) {
+ $this->assertEquals(AttachmentPreviewPlugin::getExtension($filename), $expectation);
+ }
+
+ public function getExtensionData() {
+ return [
+ ['test.php', 'php'],
+ ['something.jpg', 'jpg'],
+ ['ANtyHingsdf.asdfadf.234m,345,gdfd.F', 'f'],
+ ['swear.words', 'words']
+ ];
+ }
+
+ /**
+ * Test for isTicketsView()
+ * @dataProvider getUrls
+ */
+ public function testIsTicketsView($url, $expected) {
+ $_SERVER['REQUEST_URI'] = $url;
+ $this->assertSame(AttachmentPreviewPlugin::isTicketsView(), $expected);
+ }
+
+ /**
+ *
+ * @return type
+ * @dataProvider postUrls
+ */
+ public function testIsTicketsViewPost($url, $postdata, $expected) {
+ global $_SERVER, $_POST;
+ $_SERVER['REQUEST_URI'] = $url;
+ $_POST = $postdata;
+ $this->assertSame(AttachmentPreviewPlugin::isTicketsView(), $expected);
+ }
+
+ public function getUrls() {
+ $b = '
https://tickets.dev/support/';
+
+ return [
+ [$b . 'index.php', FALSE],
+ [$b . 'tickets.php', FALSE],
+ [$b . 'scp/index.php', TRUE],
+ [$b . 'scp/tickets.php', TRUE],
+ [$b . 'scp/tickets.php?a=edit', FALSE],
+ [$b . 'scp/tickets.php?a=print', FALSE],
+ ['
http://crazylongdomainnamethatreallyprobablyhopefullyisntinusebutactuallyyouknowwhatitjustmightbe.longasstld/someidiotpainfullylong/series/of/folders/threatening/to/make/the/url/longer/than/the/maximum/well/lets/be/honest/its/already/longer/than/anyone/would/want/to/type/support/scp/tickets.php?id=158279',
+ TRUE]
+ ];
+ }
+
+ public function postUrls() {
+ $b = '
https://tickets.dev/support/';
+
+ return [
+ [$b . 'scp/tickets.php', ['a' => 'open'], TRUE],
+ [$b . 'scp/anything.php', ['a' => 'anything'], FALSE],
+ ];
+ }
+
+ /**
+ * Test for isPjax
+ */
+ public function testIsNotPjax() {
+ $_SERVER['HTTP_X_PJAX'] = 'false';
+ $this->assertSame(AttachmentPreviewPlugin::isPjax(), FALSE);
+ }
+
+ /**
+ * Test for isPjax
+ */
+ public function testIsPjax() {
+
+ $_SERVER['HTTP_X_PJAX'] = 'true';
+ $this->assertSame(AttachmentPreviewPlugin::isPjax(), TRUE);
+ }
+
+}
=====================================
include/plugins/attachment_preview/tests/setup.inc
=====================================
--- /dev/null
+++ b/include/plugins/attachment_preview/tests/setup.inc
@@ -0,0 +1,34 @@
+<?php
+
+// Validate that the plugin.php file works, also load
+// Stuff that we need to build plugins from the subdirectory
+// of an osTicket install:
+
+$plugin = include_once(dirname(__DIR__) . '/plugin.php');
+
+define('INCLUDE_DIR', dirname(dirname(__DIR__)) . '/osticket/include/');
+define('PLUGIN_TABLE', 'ost_plugin');
+
+// We need database functions to fake with
+function db_input() {
+
+}
+
+function db_query() {
+ return array('ht' => []);
+}
+
+function db_fetch_array() { // obviously, tweak if you compile phars:
+ return ['ht' => [], 'install_path' => __DIR__, 'isphar' => FALSE];
+}
+
+assert(isset($plugin['plugin']) == TRUE);
+
+$file = explode(':', $plugin['plugin'])[0];
+$class = explode(':', $plugin['plugin'])[1];
+
+assert(file_exists($file));
+include_once($file);
+
+assert(class_exists($class));
+$attachment_plugin = new $class(1);
View it on GitLab:
https://gitlab.com/venenux/simpleticket109/commit/450f87966703f855c4efc850f75ba22b2cfbeb10
---
View it on GitLab:
https://gitlab.com/venenux/simpleticket109/commit/450f87966703f855c4efc850f75ba22b2cfbeb10
You're receiving this email because of your account on
gitlab.com.